diff --git a/core/.eslintrc.json b/core/.eslintrc.json index 6a6916b1a2c0aef4d1f49b21c18bf21c423f067b..7b1ed46abeca6b8ae943e070edf3cd77e47a8b29 100644 --- a/core/.eslintrc.json +++ b/core/.eslintrc.json @@ -21,6 +21,7 @@ "_": true, "Cookies": true, "Backbone": true, + "htmx": true, "loadjs": true, "Shepherd": true, "Sortable": true, diff --git a/core/.phpstan-baseline.php b/core/.phpstan-baseline.php index 6f4a52139f114e96d79dffef704a5acfa579831b..f50467a4dda42a068ac3c2831c2cf738c3641149 100644 --- a/core/.phpstan-baseline.php +++ b/core/.phpstan-baseline.php @@ -10443,12 +10443,6 @@ 'count' => 1, 'path' => __DIR__ . '/lib/Drupal/Core/Template/Attribute.php', ]; -$ignoreErrors[] = [ - 'message' => '#^Method Drupal\\\\Core\\\\Template\\\\Attribute\\:\\:storage\\(\\) has no return type specified\\.$#', - 'identifier' => 'missingType.return', - 'count' => 1, - 'path' => __DIR__ . '/lib/Drupal/Core/Template/Attribute.php', -]; $ignoreErrors[] = [ 'message' => '#^Method Drupal\\\\Core\\\\Template\\\\AttributeArray\\:\\:getIterator\\(\\) return type with generic class ArrayIterator does not specify its types\\: TKey, TValue$#', 'identifier' => 'missingType.generics', @@ -10461,6 +10455,12 @@ 'count' => 1, 'path' => __DIR__ . '/lib/Drupal/Core/Template/AttributeValueBase.php', ]; +$ignoreErrors[] = [ + 'message' => '#^Method Drupal\\\\Core\\\\Template\\\\HtmxAttribute\\:\\:getIterator\\(\\) return type with generic class ArrayIterator does not specify its types\\: TKey, TValue$#', + 'identifier' => 'missingType.generics', + 'count' => 1, + 'path' => __DIR__ . '/lib/Drupal/Core/Template/HtmxAttribute.php', +]; $ignoreErrors[] = [ 'message' => '#^Constructor of class Drupal\\\\Core\\\\Template\\\\TwigEnvironment has an unused parameter \\$root\\.$#', 'identifier' => 'constructor.unusedParameter', @@ -13761,30 +13761,12 @@ 'count' => 1, 'path' => __DIR__ . '/modules/config/src/Form/ConfigSingleExportForm.php', ]; -$ignoreErrors[] = [ - 'message' => '#^Method Drupal\\\\config\\\\Form\\\\ConfigSingleExportForm\\:\\:findConfiguration\\(\\) has no return type specified\\.$#', - 'identifier' => 'missingType.return', - 'count' => 1, - 'path' => __DIR__ . '/modules/config/src/Form/ConfigSingleExportForm.php', -]; $ignoreErrors[] = [ 'message' => '#^Method Drupal\\\\config\\\\Form\\\\ConfigSingleExportForm\\:\\:submitForm\\(\\) has no return type specified\\.$#', 'identifier' => 'missingType.return', 'count' => 1, 'path' => __DIR__ . '/modules/config/src/Form/ConfigSingleExportForm.php', ]; -$ignoreErrors[] = [ - 'message' => '#^Method Drupal\\\\config\\\\Form\\\\ConfigSingleExportForm\\:\\:updateConfigurationType\\(\\) has no return type specified\\.$#', - 'identifier' => 'missingType.return', - 'count' => 1, - 'path' => __DIR__ . '/modules/config/src/Form/ConfigSingleExportForm.php', -]; -$ignoreErrors[] = [ - 'message' => '#^Method Drupal\\\\config\\\\Form\\\\ConfigSingleExportForm\\:\\:updateExport\\(\\) has no return type specified\\.$#', - 'identifier' => 'missingType.return', - 'count' => 1, - 'path' => __DIR__ . '/modules/config/src/Form/ConfigSingleExportForm.php', -]; $ignoreErrors[] = [ 'message' => '#^Method Drupal\\\\config\\\\Form\\\\ConfigSingleImportForm\\:\\:create\\(\\) has no return type specified\\.$#', 'identifier' => 'missingType.return', diff --git a/core/assets/vendor/htmx/debug.js b/core/assets/vendor/htmx/debug.js new file mode 100644 index 0000000000000000000000000000000000000000..15378ccc077720b1c91c05cf4bfd230fd3853f10 --- /dev/null +++ b/core/assets/vendor/htmx/debug.js @@ -0,0 +1,11 @@ +htmx.defineExtension('debug', { + onEvent: function(name, evt) { + if (console.debug) { + console.debug(name, evt) + } else if (console) { + console.log('DEBUG:', name, evt) + } else { + throw new Error('NO CONSOLE SUPPORTED') + } + } +}) diff --git a/core/assets/vendor/htmx/htmx.min.js b/core/assets/vendor/htmx/htmx.min.js new file mode 100644 index 0000000000000000000000000000000000000000..59937d712d905c314d0bbcd3c49cc8a15d0b6cdd --- /dev/null +++ b/core/assets/vendor/htmx/htmx.min.js @@ -0,0 +1 @@ +var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=cn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true},parseInterval:null,_:null,version:"2.0.4"};Q.onLoad=j;Q.process=kt;Q.on=ye;Q.off=be;Q.trigger=he;Q.ajax=Rn;Q.find=u;Q.findAll=x;Q.closest=g;Q.remove=z;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=$e;Q.defineExtension=Fn;Q.removeExtension=Bn;Q.logAll=V;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:le,canAccessLocalStorage:B,findThisElement:Se,filterValues:hn,swap:$e,hasAttribute:s,getAttributeValue:te,getClosestAttributeValue:re,getClosestMatch:o,getExpressionVars:En,getHeaders:fn,getInputValues:cn,getInternalData:ie,getSwapSpecification:gn,getTriggerSpecs:st,getTarget:Ee,makeFragment:P,mergeObjects:ce,makeSettleInfo:xn,oobSwap:He,querySelectorExt:ae,settleImmediately:Kt,shouldCancel:ht,triggerEvent:he,triggerErrorEvent:fe,withExtensions:Ft};const r=["get","post","put","delete","patch"];const H=r.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function c(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ne(){return document}function m(e,t){return e.getRootNode?e.getRootNode({composed:t}):ne()}function o(e,t){while(e&&!t(e)){e=c(e)}return e||null}function i(e,t,n){const r=te(t,n);const o=te(t,"hx-disinherit");var i=te(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function re(t,n){let r=null;o(t,function(e){return!!(r=i(t,ue(e),n))});if(r!=="unset"){return r}}function h(e,t){const n=e instanceof Element&&(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector);return!!n&&n.call(e,t)}function T(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function q(e){const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function A(e){const t=ne().createElement("script");se(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function N(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(N(e)){const t=A(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){O(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/<head(\s[^>]*)?>[\s\S]*?<\/head>/i,"");const n=T(t);let r;if(n==="html"){r=new DocumentFragment;const i=q(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=q(t);L(r,i.body);r.title=i.title}else{const i=q('<body><template class="internal-htmx-wrapper">'+t+"</template></body>");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function oe(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return typeof e==="function"}function D(e){return t(e,"Object")}function ie(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e<t.length;e++){n.push(t[e])}}return n}function se(t,n){if(t){for(let e=0;e<t.length;e++){n(t[e])}}}function X(e){const t=e.getBoundingClientRect();const n=t.top;const r=t.bottom;return n<window.innerHeight&&r>=0}function le(e){return e.getRootNode({composed:true})===document}function F(e){return e.trim().split(/\s+/)}function ce(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function S(e){try{return JSON.parse(e)}catch(e){O(e);return null}}function B(){const e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function U(t){try{const e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function e(e){return vn(ne().body,function(){return eval(e)})}function j(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function V(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function _(){Q.logger=null}function u(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return u(ne(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(ne(),e)}}function E(){return window}function z(e,t){e=y(e);if(t){E().setTimeout(function(){z(e);e=null},t)}else{c(e).removeChild(e)}}function ue(e){return e instanceof Element?e:null}function $(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function f(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ue(y(e));if(!e){return}if(n){E().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ue(y(e));if(!r){return}if(n){E().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=y(e);e.classList.toggle(t)}function Z(e,t){e=y(e);se(e.parentElement.children,function(e){G(e,t)});K(ue(e),t)}function g(e,t){e=ue(y(e));if(e&&e.closest){return e.closest(t)}else{do{if(e==null||h(e,t)){return e}}while(e=e&&ue(c(e)));return null}}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function ge(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function p(t,r,n){if(r.indexOf("global ")===0){return p(t,r.slice(7),true)}t=y(t);const o=[];{let t=0;let n=0;for(let e=0;e<r.length;e++){const l=r[e];if(l===","&&t===0){o.push(r.substring(n,e));n=e+1;continue}if(l==="<"){t++}else if(l==="/"&&e<r.length-1&&r[e+1]===">"){t--}}if(n<r.length){o.push(r.substring(n))}}const i=[];const s=[];while(o.length>0){const r=ge(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ue(t),ge(r.substr(8)))}else if(r.indexOf("find ")===0){e=u(f(t),ge(r.substr(5)))}else if(r==="next"||r==="nextElementSibling"){e=ue(t).nextElementSibling}else if(r.indexOf("next ")===0){e=pe(t,ge(r.substr(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ue(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,ge(r.substr(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=m(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=f(m(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var pe=function(t,e,n){const r=f(m(t,n)).querySelectorAll(e);for(let e=0;e<r.length;e++){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_PRECEDING){return o}}};var me=function(t,e,n){const r=f(m(t,n)).querySelectorAll(e);for(let e=r.length-1;e>=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ae(e,t){if(typeof e!=="string"){return p(e,t)[0]}else{return p(ne().body,e)[0]}}function y(e,t){if(typeof e==="string"){return u(f(t)||document,e)}else{return e}}function xe(e,t,n,r){if(k(t)){return{target:ne().body,event:J(e),listener:t,options:n}}else{return{target:y(e),event:J(t),listener:n,options:r}}}function ye(t,n,r,o){Vn(function(){const e=xe(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=k(n);return e?n:r}function be(t,n,r){Vn(function(){const e=xe(t,n,r);e.target.removeEventListener(e.event,e.listener)});return k(n)?n:r}const ve=ne().createElement("output");function we(e,t){const n=re(e,t);if(n){if(n==="this"){return[Se(e,t)]}else{const r=p(e,n);if(r.length===0){O('The selector "'+n+'" on '+t+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ue(o(e,function(e){return te(ue(e),t)!=null}))}function Ee(e){const t=re(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ae(e,t)}}else{const n=ie(e);if(n.boosted){return ne().body}else{return e}}}function Ce(t){const n=Q.config.attributesToSettle;for(let e=0;e<n.length;e++){if(t===n[e]){return true}}return false}function Oe(t,n){se(t.attributes,function(e){if(!n.hasAttribute(e.name)&&Ce(e.name)){t.removeAttribute(e.name)}});se(n.attributes,function(e){if(Ce(e.name)){t.setAttribute(e.name,e.value)}})}function Re(t,e){const n=Un(e);for(let e=0;e<n.length;e++){const r=n[e];try{if(r.isInlineSwap(t)){return true}}catch(e){O(e)}}return t==="outerHTML"}function He(e,o,i,t){t=t||ne();let n="#"+ee(o,"id");let s="outerHTML";if(e==="true"){}else if(e.indexOf(":")>0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=p(t,n,false);if(r){se(r,function(e){let t;const n=o.cloneNode(true);t=ne().createDocumentFragment();t.appendChild(n);if(!Re(s,e)){t=f(n)}const r={shouldSwap:true,target:e,fragment:t};if(!he(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);_e(s,e,e,t,i);Te()}se(i.elts,function(e){he(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(ne().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Te(){const e=u("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=u("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){se(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=te(e,"id");const n=ne().getElementById(t);if(n!=null){if(e.moveBefore){let e=u("#--htmx-preserve-pantry--");if(e==null){ne().body.insertAdjacentHTML("afterend","<div id='--htmx-preserve-pantry--'></div>");e=u("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Le(l,e,c){se(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=f(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Ae(e){return function(){G(e,Q.config.addedClass);kt(ue(e));Ne(f(e));he(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=$(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function a(e,t,n,r){Le(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(ue(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Ae(o))}}}function Ie(e,t){let n=0;while(n<e.length){t=(t<<5)-t+e.charCodeAt(n++)|0}return t}function Pe(t){let n=0;if(t.attributes){for(let e=0;e<t.attributes.length;e++){const r=t.attributes[e];if(r.value){n=Ie(r.name,n);n=Ie(r.value,n)}}}return n}function ke(t){const n=ie(t);if(n.onHandlers){for(let e=0;e<n.onHandlers.length;e++){const r=n.onHandlers[e];be(t,r.event,r.listener)}delete n.onHandlers}}function De(e){const t=ie(e);if(t.timeout){clearTimeout(t.timeout)}if(t.listenerInfos){se(t.listenerInfos,function(e){if(e.on){be(e.on,e.trigger,e.listener)}})}ke(e);se(Object.keys(t),function(e){if(e!=="firstInitCompleted")delete t[e]})}function b(e){he(e,"htmx:beforeCleanupElement");De(e);if(e.children){se(e.children,function(e){b(e)})}}function Me(t,e,n){if(t instanceof Element&&t.tagName==="BODY"){return Ve(t,e,n)}let r;const o=t.previousSibling;const i=c(t);if(!i){return}a(i,t,e,n);if(o==null){r=i.firstChild}else{r=o.nextSibling}n.elts=n.elts.filter(function(e){return e!==t});while(r&&r!==t){if(r instanceof Element){n.elts.push(r)}r=r.nextSibling}b(t);if(t instanceof Element){t.remove()}else{t.parentNode.removeChild(t)}}function Xe(e,t,n){return a(e,e.firstChild,t,n)}function Fe(e,t,n){return a(c(e),e,t,n)}function Be(e,t,n){return a(e,null,t,n)}function Ue(e,t,n){return a(c(e),e.nextSibling,t,n)}function je(e){b(e);const t=c(e);if(t){return t.removeChild(e)}}function Ve(e,t,n){const r=e.firstChild;a(e,r,t,n);if(r){while(r.nextSibling){b(r.nextSibling);e.removeChild(r.nextSibling)}b(r);e.removeChild(r)}}function _e(t,e,n,r,o){switch(t){case"none":return;case"outerHTML":Me(n,r,o);return;case"afterbegin":Xe(n,r,o);return;case"beforebegin":Fe(n,r,o);return;case"beforeend":Be(n,r,o);return;case"afterend":Ue(n,r,o);return;case"delete":je(n);return;default:var i=Un(e);for(let e=0;e<i.length;e++){const s=i[e];try{const l=s.handleSwap(t,n,r,o);if(l){if(Array.isArray(l)){for(let e=0;e<l.length;e++){const c=l[e];if(c.nodeType!==Node.TEXT_NODE&&c.nodeType!==Node.COMMENT_NODE){o.tasks.push(Ae(c))}}}return}}catch(e){O(e)}}if(t==="innerHTML"){Ve(n,r,o)}else{_e(Q.config.defaultSwapStyle,e,n,r,o)}}}function ze(e,n,r){var t=x(e,"[hx-swap-oob], [data-hx-swap-oob]");se(t,function(e){if(Q.config.allowNestedOobSwaps||e.parentElement===null){const t=te(e,"hx-swap-oob");if(t!=null){He(t,e,n,r)}}else{e.removeAttribute("hx-swap-oob");e.removeAttribute("data-hx-swap-oob")}});return t.length>0}function $e(e,t,r,o){if(!o){o={}}e=y(e);const i=o.contextElement?m(o.contextElement,false):ne();const n=document.activeElement;let s={};try{s={elt:n,start:n?n.selectionStart:null,end:n?n.selectionEnd:null}}catch(e){}const l=xn(e);if(r.swapStyle==="textContent"){e.textContent=t}else{let n=P(t);l.title=n.title;if(o.selectOOB){const u=o.selectOOB.split(",");for(let t=0;t<u.length;t++){const a=u[t].split(":",2);let e=a[0].trim();if(e.indexOf("#")===0){e=e.substring(1)}const f=a[1]||"true";const h=n.querySelector("#"+e);if(h){He(f,h,l,i)}}}ze(n,l,i);se(x(n,"template"),function(e){if(e.content&&ze(e.content,l,i)){e.remove()}});if(o.select){const d=ne().createDocumentFragment();se(n.querySelectorAll(o.select),function(e){d.appendChild(e)});n=d}qe(n);_e(r.swapStyle,o.contextElement,e,n,l);Te()}if(s.elt&&!le(s.elt)&&ee(s.elt,"id")){const g=document.getElementById(ee(s.elt,"id"));const p={preventScroll:r.focusScroll!==undefined?!r.focusScroll:!Q.config.defaultFocusScroll};if(g){if(s.start&&g.setSelectionRange){try{g.setSelectionRange(s.start,s.end)}catch(e){}}g.focus(p)}}e.classList.remove(Q.config.swappingClass);se(l.elts,function(e){if(e.classList){e.classList.add(Q.config.settlingClass)}he(e,"htmx:afterSwap",o.eventInfo)});if(o.afterSwapCallback){o.afterSwapCallback()}if(!r.ignoreTitle){kn(l.title)}const c=function(){se(l.tasks,function(e){e.call()});se(l.elts,function(e){if(e.classList){e.classList.remove(Q.config.settlingClass)}he(e,"htmx:afterSettle",o.eventInfo)});if(o.anchor){const e=ue(y("#"+o.anchor));if(e){e.scrollIntoView({block:"start",behavior:"auto"})}}yn(l.elts,r);if(o.afterSettleCallback){o.afterSettleCallback()}};if(r.settleDelay>0){E().setTimeout(c,r.settleDelay)}else{c()}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=S(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(D(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}he(n,i,e)}}}else{const s=r.split(",");for(let e=0;e<s.length;e++){he(n,s[e].trim(),[])}}}const Ke=/\s/;const v=/[\s,]/;const Ge=/[_$a-zA-Z]/;const We=/[_$a-zA-Z0-9]/;const Ze=['"',"'","/"];const w=/[^\s]/;const Ye=/[{(]/;const Qe=/[})]/;function et(e){const t=[];let n=0;while(n<e.length){if(Ge.exec(e.charAt(n))){var r=n;while(We.exec(e.charAt(n+1))){n++}t.push(e.substring(r,n+1))}else if(Ze.indexOf(e.charAt(n))!==-1){const o=e.charAt(n);var r=n;n++;while(n<e.length&&e.charAt(n)!==o){if(e.charAt(n)==="\\"){n++}n++}t.push(e.substring(r,n+1))}else{const i=e.charAt(n);t.push(i)}n++}return t}function tt(e,t,n){return Ge.exec(e.charAt(0))&&e!=="true"&&e!=="false"&&e!=="this"&&e!==n&&t!=="."}function nt(r,o,i){if(o[0]==="["){o.shift();let e=1;let t=" return (function("+i+"){ return (";let n=null;while(o.length>0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=vn(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(ne().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function C(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=C(e,Qe).trim();e.shift()}else{t=C(e,v)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{C(o,w);const l=o.length;const c=C(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};C(o,w);u.pollInterval=d(C(o,/[,\[\s]/));C(o,w);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const a={trigger:c};var i=nt(e,o,"event");if(i){a.eventFilter=i}C(o,w);while(o.length>0&&o[0]!==","){const f=o.shift();if(f==="changed"){a.changed=true}else if(f==="once"){a.once=true}else if(f==="consume"){a.consume=true}else if(f==="delay"&&o[0]===":"){o.shift();a.delay=d(C(o,v))}else if(f==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=C(o,v);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}a.from=s}else if(f==="target"&&o[0]===":"){o.shift();a.target=rt(o)}else if(f==="throttle"&&o[0]===":"){o.shift();a.throttle=d(C(o,v))}else if(f==="queue"&&o[0]===":"){o.shift();a.queue=C(o,v)}else if(f==="root"&&o[0]===":"){o.shift();a[f]=rt(o)}else if(f==="threshold"&&o[0]===":"){o.shift();a[f]=C(o,v)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}r.push(a)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=te(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){ie(e).cancelled=true}function ct(e,t,n){const r=ie(e);r.timeout=E().setTimeout(function(){if(le(e)&&r.cancelled!==true){if(!gt(n,e,Mt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function at(e){return g(e,Q.config.disableSelector)}function ft(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=ne().location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){pt(t,function(e,t){const n=ue(e);if(at(n)){b(n);return}de(r,o,n,t)},n,e,true)})}}function ht(e,t){const n=ue(t);if(!n){return false}if(e.type==="submit"||e.type==="click"){if(n.tagName==="FORM"){return true}if(h(n,'input[type="submit"], button')&&(h(n,"[form]")||g(n,"form")!==null)){return true}if(n instanceof HTMLAnchorElement&&n.href&&(n.getAttribute("href")==="#"||n.getAttribute("href").indexOf("#")!==0)){return true}}return false}function dt(e,t){return ie(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function gt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(ne().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function pt(l,c,e,u,a){const f=ie(l);let t;if(u.from){t=p(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in f)){f.lastValue=new WeakMap}t.forEach(function(e){if(!f.lastValue.has(u)){f.lastValue.set(u,new WeakMap)}f.lastValue.get(u).set(e,e.value)})}se(t,function(i){const s=function(e){if(!le(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(a||ht(e,l)){e.preventDefault()}if(gt(u,l,e)){return}const t=ie(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ue(e.target),u.target)){return}}if(u.once){if(f.triggeredOnce){return}else{f.triggeredOnce=true}}if(u.changed){const n=event.target;const r=n.value;const o=f.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(f.delayed){clearTimeout(f.delayed)}if(f.throttle){return}if(u.throttle>0){if(!f.throttle){he(l,"htmx:trigger");c(l,e);f.throttle=E().setTimeout(function(){f.throttle=null},u.throttle)}}else if(u.delay>0){f.delayed=E().setTimeout(function(){he(l,"htmx:trigger");c(l,e)},u.delay)}else{he(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let xt=null;function yt(){if(!xt){xt=function(){mt=true};window.addEventListener("scroll",xt);window.addEventListener("resize",xt);setInterval(function(){if(mt){mt=false;se(ne().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&X(e)){e.setAttribute("data-hx-revealed","true");const t=ie(e);if(t.initHash){he(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){he(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;he(e,"htmx:trigger");t(e)}};if(r>0){E().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;se(r,function(r){if(s(t,"hx-"+r)){const o=te(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ue(e);if(g(n,Q.config.disableSelector)){b(n);return}de(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){yt();pt(r,n,t,e);bt(ue(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ae(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e<t.length;e++){const n=t[e];if(n.isIntersecting){he(r,"intersect");break}}},o);i.observe(ue(r));pt(ue(r),n,t,e)}else if(!t.firstInitCompleted&&e.trigger==="load"){if(!gt(e,r,Mt("load",{elt:r}))){vt(ue(r),n,t,e.delay)}}else if(e.pollInterval>0){t.polling=true;ct(ue(r),n,e)}else{pt(r,n,t,e)}}function Et(e){const t=ue(e);if(!t){return false}const n=t.attributes;for(let e=0;e<n.length;e++){const r=n[e].name;if(l(r,"hx-on:")||l(r,"data-hx-on:")||l(r,"hx-on-")||l(r,"data-hx-on-")){return true}}return false}const Ct=(new XPathEvaluator).createExpression('.//*[@*[ starts-with(name(), "hx-on:") or starts-with(name(), "data-hx-on:") or'+' starts-with(name(), "hx-on-") or starts-with(name(), "data-hx-on-") ]]');function Ot(e,t){if(Et(e)){t.push(ue(e))}const n=Ct.evaluate(e);let r=null;while(r=n.iterateNext())t.push(ue(r))}function Rt(e){const t=[];if(e instanceof DocumentFragment){for(const n of e.childNodes){Ot(n,t)}}else{Ot(e,t)}return t}function Ht(e){if(e.querySelectorAll){const n=", [hx-boost] a, [data-hx-boost] a, a[hx-boost], a[data-hx-boost]";const r=[];for(const i in Mn){const s=Mn[i];if(s.getSelectors){var t=s.getSelectors();if(t){r.push(t)}}}const o=e.querySelectorAll(H+n+", form, [type='submit'],"+" [hx-ext], [data-hx-ext], [hx-trigger], [data-hx-trigger]"+r.flat().map(e=>", "+e).join(""));return o}else{return[]}}function Tt(e){const t=g(ue(e.target),"button, input[type='submit']");const n=Lt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Lt(e);if(t){t.lastButtonClicked=null}}function Lt(e){const t=g(ue(e.target),"button, input[type='submit']");if(!t){return}const n=y("#"+ee(t,"form"),t.getRootNode())||g(t,"form");if(!n){return}return ie(n)}function At(e){e.addEventListener("click",Tt);e.addEventListener("focusin",Tt);e.addEventListener("focusout",qt)}function Nt(t,e,n){const r=ie(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){vn(t,function(){if(at(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function It(t){ke(t);for(let e=0;e<t.attributes.length;e++){const n=t.attributes[e].name;const r=t.attributes[e].value;if(l(n,"hx-on")||l(n,"data-hx-on")){const o=n.indexOf("-on")+3;const i=n.slice(o,o+1);if(i==="-"||i===":"){let e=n.slice(o+1);if(l(e,":")){e="htmx"+e}else if(l(e,"-")){e="htmx:"+e.slice(1)}else if(l(e,"htmx-")){e="htmx:"+e.slice(5)}Nt(t,e,r)}}}}function Pt(t){if(g(t,Q.config.disableSelector)){b(t);return}const n=ie(t);const e=Pe(t);if(n.initHash!==e){De(t);n.initHash=e;he(t,"htmx:beforeProcessNode");const r=st(t);const o=wt(t,n,r);if(!o){if(re(t,"hx-boost")==="true"){ft(t,n,r)}else if(s(t,"hx-trigger")){r.forEach(function(e){St(t,e,n,function(){})})}}if(t.tagName==="FORM"||ee(t,"type")==="submit"&&s(t,"form")){At(t)}n.firstInitCompleted=true;he(t,"htmx:afterProcessNode")}}function kt(e){e=y(e);if(g(e,Q.config.disableSelector)){b(e);return}Pt(e);se(Ht(e),function(e){Pt(e)});se(Rt(e),It)}function Dt(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function Mt(e,t){let n;if(window.CustomEvent&&typeof window.CustomEvent==="function"){n=new CustomEvent(e,{bubbles:true,cancelable:true,composed:true,detail:t})}else{n=ne().createEvent("CustomEvent");n.initCustomEvent(e,true,true,t)}return n}function fe(e,t,n){he(e,t,ce({error:t},n))}function Xt(e){return e==="htmx:afterProcessNode"}function Ft(e,t){se(Un(e),function(e){try{t(e)}catch(e){O(e)}})}function O(e){if(console.error){console.error(e)}else if(console.log){console.log("ERROR: ",e)}}function he(e,t,n){e=y(e);if(n==null){n={}}n.elt=e;const r=Mt(t,n);if(Q.logger&&!Xt(t)){Q.logger(e,t,n)}if(n.error){O(n.error);he(e,"htmx:error",{errorInfo:n})}let o=e.dispatchEvent(r);const i=Dt(t);if(o&&i!==t){const s=Mt(i,r.detail);o=o&&e.dispatchEvent(s)}Ft(ue(e),function(e){o=o&&(e.onEvent(t,r)!==false&&!r.defaultPrevented)});return o}let Bt=location.pathname+location.search;function Ut(){const e=ne().querySelector("[hx-history-elt],[data-hx-history-elt]");return e||ne().body}function jt(t,e){if(!B()){return}const n=_t(e);const r=ne().title;const o=window.scrollY;if(Q.config.historyCacheSize<=0){localStorage.removeItem("htmx-history-cache");return}t=U(t);const i=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e<i.length;e++){if(i[e].url===t){i.splice(e,1);break}}const s={url:t,content:n,title:r,scroll:o};he(ne().body,"htmx:historyItemCreated",{item:s,cache:i});i.push(s);while(i.length>Q.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(ne().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Vt(t){if(!B()){return null}t=U(t);const n=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e<n.length;e++){if(n[e].url===t){return n[e]}}return null}function _t(e){const t=Q.config.requestClass;const n=e.cloneNode(true);se(x(n,"."+t),function(e){G(e,t)});se(x(n,"[data-disabled-by-htmx]"),function(e){e.removeAttribute("disabled")});return n.innerHTML}function zt(){const e=Ut();const t=Bt||location.pathname+location.search;let n;try{n=ne().querySelector('[hx-history="false" i],[data-hx-history="false" i]')}catch(e){n=ne().querySelector('[hx-history="false"],[data-hx-history="false"]')}if(!n){he(ne().body,"htmx:beforeHistorySave",{path:t,historyElt:e});jt(t,e)}if(Q.config.historyEnabled)history.replaceState({htmx:true},ne().title,window.location.href)}function $t(e){if(Q.config.getCacheBusterParam){e=e.replace(/org\.htmx\.cache-buster=[^&]*&?/,"");if(Y(e,"&")||Y(e,"?")){e=e.slice(0,-1)}}if(Q.config.historyEnabled){history.pushState({htmx:true},"",e)}Bt=e}function Jt(e){if(Q.config.historyEnabled)history.replaceState({htmx:true},"",e);Bt=e}function Kt(e){se(e,function(e){e.call(undefined)})}function Gt(o){const e=new XMLHttpRequest;const i={path:o,xhr:e};he(ne().body,"htmx:historyCacheMiss",i);e.open("GET",o,true);e.setRequestHeader("HX-Request","true");e.setRequestHeader("HX-History-Restore-Request","true");e.setRequestHeader("HX-Current-URL",ne().location.href);e.onload=function(){if(this.status>=200&&this.status<400){he(ne().body,"htmx:historyCacheMissLoad",i);const e=P(this.response);const t=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;const n=Ut();const r=xn(n);kn(e.title);qe(e);Ve(n,t,r);Te();Kt(r.tasks);Bt=o;he(ne().body,"htmx:historyRestore",{path:o,cacheMiss:true,serverResponse:this.response})}else{fe(ne().body,"htmx:historyCacheMissLoadError",i)}};e.send()}function Wt(e){zt();e=e||location.pathname+location.search;const t=Vt(e);if(t){const n=P(t.content);const r=Ut();const o=xn(r);kn(t.title);qe(n);Ve(r,n,o);Te();Kt(o.tasks);E().setTimeout(function(){window.scrollTo(0,t.scroll)},0);Bt=e;he(ne().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{Gt(e)}}}function Zt(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function Yt(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function Qt(e,t){se(e.concat(t),function(e){const t=ie(e);t.requestCount=(t.requestCount||1)-1});se(e,function(e){const t=ie(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});se(t,function(e){const t=ie(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function en(t,n){for(let e=0;e<t.length;e++){const r=t[e];if(r.isSameNode(n)){return true}}return false}function tn(e){const t=e;if(t.name===""||t.name==null||t.disabled||g(t,"fieldset[disabled]")){return false}if(t.type==="button"||t.type==="submit"||t.tagName==="image"||t.tagName==="reset"||t.tagName==="file"){return false}if(t.type==="checkbox"||t.type==="radio"){return t.checked}return true}function nn(t,e,n){if(t!=null&&e!=null){if(Array.isArray(e)){e.forEach(function(e){n.append(t,e)})}else{n.append(t,e)}}}function rn(t,n,r){if(t!=null&&n!=null){let e=r.getAll(t);if(Array.isArray(n)){e=e.filter(e=>n.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);se(e,e=>r.append(t,e))}}function on(t,n,r,o,i){if(o==null||en(t,o)){return}else{t.push(o)}if(tn(o)){const s=ee(o,"name");let e=o.value;if(o instanceof HTMLSelectElement&&o.multiple){e=M(o.querySelectorAll("option:checked")).map(function(e){return e.value})}if(o instanceof HTMLInputElement&&o.files){e=M(o.files)}nn(s,e,n);if(i){sn(o,r)}}if(o instanceof HTMLFormElement){se(o.elements,function(e){if(t.indexOf(e)>=0){rn(e.name,e.value,n)}else{t.push(e)}if(i){sn(e,r)}});new FormData(o).forEach(function(e,t){if(e instanceof File&&e.name===""){return}nn(t,e,n)})}}function sn(e,t){const n=e;if(n.willValidate){he(n,"htmx:validation:validate");if(!n.checkValidity()){t.push({elt:n,message:n.validationMessage,validity:n.validity});he(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})}}}function ln(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function cn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=ie(e);if(s.lastButtonClicked&&!le(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||te(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){on(n,o,i,g(e,"form"),l)}on(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const a=ee(u,"name");nn(a,u.value,o)}const c=we(e,"hx-include");se(c,function(e){on(n,r,i,ue(e),l);if(!h(e,"form")){se(f(e).querySelectorAll(ot),function(e){on(n,r,i,e,l)})}});ln(r,o);return{errors:i,formData:r,values:An(r)}}function un(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function an(e){e=qn(e);let n="";e.forEach(function(e,t){n=un(n,t,e)});return n}function fn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":te(t,"id"),"HX-Current-URL":ne().location.href};bn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(ie(e).boosted){r["HX-Boosted"]="true"}return r}function hn(n,e){const t=re(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){se(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;se(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function dn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function gn(e,t){const n=t||re(e,"hx-swap");const r={swapStyle:ie(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ie(e).boosted&&!dn(e)){r.show="top"}if(n){const s=F(n);if(s.length>0){for(let e=0;e<s.length;e++){const l=s[e];if(l.indexOf("swap:")===0){r.swapDelay=d(l.slice(5))}else if(l.indexOf("settle:")===0){r.settleDelay=d(l.slice(7))}else if(l.indexOf("transition:")===0){r.transition=l.slice(11)==="true"}else if(l.indexOf("ignoreTitle:")===0){r.ignoreTitle=l.slice(12)==="true"}else if(l.indexOf("scroll:")===0){const c=l.slice(7);var o=c.split(":");const u=o.pop();var i=o.length>0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const a=l.slice(5);var o=a.split(":");const f=o.pop();var i=o.length>0?o.join(":"):null;r.show=f;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{O("Unknown modifier in hx-swap: "+l)}}}}return r}function pn(e){return re(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function mn(t,n,r){let o=null;Ft(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(pn(n)){return ln(new FormData,qn(r))}else{return an(r)}}}function xn(e){return{tasks:[],elts:[e]}}function yn(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ue(ae(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ue(ae(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function bn(r,e,o,i){if(i==null){i={}}if(r==null){return i}const s=te(r,e);if(s){let e=s.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=vn(r,function(){return Function("return ("+e+")")()},{})}else{n=S(e)}for(const l in n){if(n.hasOwnProperty(l)){if(i[l]==null){i[l]=n[l]}}}}return bn(ue(c(r)),e,o,i)}function vn(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function wn(e,t){return bn(e,"hx-vars",true,t)}function Sn(e,t){return bn(e,"hx-vals",false,t)}function En(e){return ce(wn(e),Sn(e))}function Cn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function On(t){if(t.responseURL&&typeof URL!=="undefined"){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(ne().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function R(e,t){return t.test(e.getAllResponseHeaders())}function Rn(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return de(t,n,null,null,{targetOverride:y(r)||ve,returnPromise:true})}else{let e=y(r.target);if(r.target&&!e||r.source&&!e&&!y(r.source)){e=ve}return de(t,n,y(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true})}}else{return de(t,n,null,null,{returnPromise:true})}}function Hn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function Tn(e,t,n){let r;let o;if(typeof URL==="function"){o=new URL(t,document.location.href);const i=document.location.origin;r=i===o.origin}else{o=t;r=l(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!r){return false}}return he(e,"htmx:validateUrl",ce({url:o,sameHost:r},n))}function qn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Ln(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function An(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}else{return e[t]}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Ln(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function de(t,n,r,o,i,D){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=ne().body}const M=i.handler||Dn;const X=i.select||null;if(!le(r)){oe(s);return e}const c=i.targetOverride||ue(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:te(r,"hx-target")});oe(l);return e}let u=ie(r);const a=u.lastButtonClicked;if(a){const L=ee(a,"formaction");if(L!=null){n=L}const A=ee(a,"formmethod");if(A!=null){if(A.toLowerCase()!=="dialog"){t=A}}}const f=re(r,"hx-confirm");if(D===undefined){const K=function(e){return de(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:f};if(he(r,"htmx:confirm",G)===false){oe(s);return e}}let h=r;let d=re(r,"hx-sync");let g=null;let F=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ue(ae(r,I))}d=(N[1]||"drop").trim();u=ie(h);if(d==="drop"&&u.xhr&&u.abortable!==true){oe(s);return e}else if(d==="abort"){if(u.xhr){oe(s);return e}else{F=true}}else if(d==="replace"){he(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");g=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){he(h,"htmx:abort")}else{if(g==null){if(o){const P=ie(o);if(P&&P.triggerSpec&&P.triggerSpec.queue){g=P.triggerSpec.queue}}if(g==null){g="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(g==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="all"){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){de(t,n,r,o,i)})}oe(s);return e}}const p=new XMLHttpRequest;u.xhr=p;u.abortable=F;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const B=re(r,"hx-prompt");if(B){var x=prompt(B);if(x===null||!he(r,"htmx:prompt",{prompt:x,target:c})){oe(s);m();return e}}if(f&&!D){if(!confirm(f)){oe(s);m();return e}}let y=fn(r,c,x);if(t!=="get"&&!pn(r)){y["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){y=ce(y,i.headers)}const U=cn(r,t);let b=U.errors;const j=U.formData;if(i.values){ln(j,qn(i.values))}const V=qn(En(r));const v=ln(j,V);let w=hn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=ne().location.href}const S=bn(r,"hx-request");const _=ie(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:_,useUrlParams:E,formData:w,parameters:An(w),unfilteredFormData:v,unfilteredParameters:An(v),headers:y,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!he(r,"htmx:configRequest",C)){oe(s);m();return e}n=C.path;t=C.verb;y=C.headers;w=qn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){he(r,"htmx:validation:halted",C);oe(s);m();return e}const z=n.split("#");const $=z[0];const O=z[1];let R=n;if(E){R=$;const Z=!w.keys().next().done;if(Z){if(R.indexOf("?")<0){R+="?"}else{R+="&"}R+=an(w);if(O){R+="#"+O}}}if(!Tn(r,R,C)){fe(r,"htmx:invalidPath",C);oe(l);return e}p.open(t.toUpperCase(),R,true);p.overrideMimeType("text/html");p.withCredentials=C.withCredentials;p.timeout=C.timeout;if(S.noHeaders){}else{for(const k in y){if(y.hasOwnProperty(k)){const Y=y[k];Cn(p,k,Y)}}}const H={xhr:p,target:c,requestConfig:C,etc:i,boosted:_,select:X,pathInfo:{requestPath:n,finalRequestPath:R,responsePath:null,anchor:O}};p.onload=function(){try{const t=Hn(r);H.pathInfo.responsePath=On(p);M(r,H);if(H.keepIndicators!==true){Qt(T,q)}he(r,"htmx:afterRequest",H);he(r,"htmx:afterOnLoad",H);if(!le(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(le(n)){e=n}}if(e){he(e,"htmx:afterRequest",H);he(e,"htmx:afterOnLoad",H)}}oe(s);m()}catch(e){fe(r,"htmx:onLoadError",ce({error:e},H));throw e}};p.onerror=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendError",H);oe(l);m()};p.onabort=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendAbort",H);oe(l);m()};p.ontimeout=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:timeout",H);oe(l);m()};if(!he(r,"htmx:beforeRequest",H)){oe(s);m();return e}var T=Zt(r);var q=Yt(r);se(["loadstart","loadend","progress","abort"],function(t){se([p,p.upload],function(e){e.addEventListener(t,function(e){he(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});he(r,"htmx:beforeSend",H);const J=E?null:mn(p,r,w);p.send(J);return e}function Nn(e,t){const n=t.xhr;let r=null;let o=null;if(R(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(R(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(R(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=re(e,"hx-push-url");const c=re(e,"hx-replace-url");const u=ie(e).boosted;let a=null;let f=null;if(l){a="push";f=l}else if(c){a="replace";f=c}else if(u){a="push";f=s||i}if(f){if(f==="false"){return{}}if(f==="true"){f=s||i}if(t.pathInfo.anchor&&f.indexOf("#")===-1){f=f+"#"+t.pathInfo.anchor}return{type:a,path:f}}else{return{}}}function In(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Pn(e){for(var t=0;t<Q.config.responseHandling.length;t++){var n=Q.config.responseHandling[t];if(In(n,e.status)){return n}}return{swap:false}}function kn(e){if(e){const t=u("title");if(t){t.innerHTML=e}else{window.document.title=e}}}function Dn(o,i){const s=i.xhr;let l=i.target;const e=i.etc;const c=i.select;if(!he(o,"htmx:beforeOnLoad",i))return;if(R(s,/HX-Trigger:/i)){Je(s,"HX-Trigger",o)}if(R(s,/HX-Location:/i)){zt();let e=s.getResponseHeader("HX-Location");var t;if(e.indexOf("{")===0){t=S(e);e=t.path;delete t.path}Rn("get",e,t).then(function(){$t(e)});return}const n=R(s,/HX-Refresh:/i)&&s.getResponseHeader("HX-Refresh")==="true";if(R(s,/HX-Redirect:/i)){i.keepIndicators=true;location.href=s.getResponseHeader("HX-Redirect");n&&location.reload();return}if(n){i.keepIndicators=true;location.reload();return}if(R(s,/HX-Retarget:/i)){if(s.getResponseHeader("HX-Retarget")==="this"){i.target=o}else{i.target=ue(ae(o,s.getResponseHeader("HX-Retarget")))}}const u=Nn(o,i);const r=Pn(s);const a=r.swap;let f=!!r.error;let h=Q.config.ignoreTitle||r.ignoreTitle;let d=r.select;if(r.target){i.target=ue(ae(o,r.target))}var g=e.swapOverride;if(g==null&&r.swapOverride){g=r.swapOverride}if(R(s,/HX-Retarget:/i)){if(s.getResponseHeader("HX-Retarget")==="this"){i.target=o}else{i.target=ue(ae(o,s.getResponseHeader("HX-Retarget")))}}if(R(s,/HX-Reswap:/i)){g=s.getResponseHeader("HX-Reswap")}var p=s.response;var m=ce({shouldSwap:a,serverResponse:p,isError:f,ignoreTitle:h,selectOverride:d,swapOverride:g},i);if(r.event&&!he(l,r.event,m))return;if(!he(l,"htmx:beforeSwap",m))return;l=m.target;p=m.serverResponse;f=m.isError;h=m.ignoreTitle;d=m.selectOverride;g=m.swapOverride;i.target=l;i.failed=f;i.successful=!f;if(m.shouldSwap){if(s.status===286){lt(o)}Ft(o,function(e){p=e.transformResponse(p,s,o)});if(u.type){zt()}var x=gn(o,g);if(!x.hasOwnProperty("ignoreTitle")){x.ignoreTitle=h}l.classList.add(Q.config.swappingClass);let n=null;let r=null;if(c){d=c}if(R(s,/HX-Reselect:/i)){d=s.getResponseHeader("HX-Reselect")}const y=re(o,"hx-select-oob");const b=re(o,"hx-select");let e=function(){try{if(u.type){he(ne().body,"htmx:beforeHistoryUpdate",ce({history:u},i));if(u.type==="push"){$t(u.path);he(ne().body,"htmx:pushedIntoHistory",{path:u.path})}else{Jt(u.path);he(ne().body,"htmx:replacedInHistory",{path:u.path})}}$e(l,p,x,{select:d||b,selectOOB:y,eventInfo:i,anchor:i.pathInfo.anchor,contextElement:o,afterSwapCallback:function(){if(R(s,/HX-Trigger-After-Swap:/i)){let e=o;if(!le(o)){e=ne().body}Je(s,"HX-Trigger-After-Swap",e)}},afterSettleCallback:function(){if(R(s,/HX-Trigger-After-Settle:/i)){let e=o;if(!le(o)){e=ne().body}Je(s,"HX-Trigger-After-Settle",e)}oe(n)}})}catch(e){fe(o,"htmx:swapError",i);oe(r);throw e}};let t=Q.config.globalViewTransitions;if(x.hasOwnProperty("transition")){t=x.transition}if(t&&he(o,"htmx:beforeTransition",i)&&typeof Promise!=="undefined"&&document.startViewTransition){const v=new Promise(function(e,t){n=e;r=t});const w=e;e=function(){document.startViewTransition(function(){w();return v})}}if(x.swapDelay>0){E().setTimeout(e,x.swapDelay)}else{e()}}if(f){fe(o,"htmx:responseError",ce({error:"Response Status Error Code "+s.status+" from "+i.pathInfo.requestPath},i))}}const Mn={};function Xn(){return{init:function(e){return null},getSelectors:function(){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,n){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,n,r){return false},encodeParameters:function(e,t,n){return null}}}function Fn(e,t){if(t.init){t.init(n)}Mn[e]=ce(Xn(),t)}function Bn(e){delete Mn[e]}function Un(e,n,r){if(n==undefined){n=[]}if(e==undefined){return n}if(r==undefined){r=[]}const t=te(e,"hx-ext");if(t){se(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){r.push(e.slice(7));return}if(r.indexOf(e)<0){const t=Mn[e];if(t&&n.indexOf(t)<0){n.push(t)}}})}return Un(ue(c(e)),n,r)}var jn=false;ne().addEventListener("DOMContentLoaded",function(){jn=true});function Vn(e){if(jn||ne().readyState==="complete"){e()}else{ne().addEventListener("DOMContentLoaded",e)}}function _n(){if(Q.config.includeIndicatorStyles!==false){const e=Q.config.inlineStyleNonce?` nonce="${Q.config.inlineStyleNonce}"`:"";ne().head.insertAdjacentHTML("beforeend","<style"+e+"> ."+Q.config.indicatorClass+"{opacity:0} ."+Q.config.requestClass+" ."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ."+Q.config.requestClass+"."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} </style>")}}function zn(){const e=ne().querySelector('meta[name="htmx-config"]');if(e){return S(e.content)}else{return null}}function $n(){const e=zn();if(e){Q.config=ce(Q.config,e)}}Vn(function(){$n();_n();let e=ne().body;kt(e);const t=ne().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.target;const n=ie(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){Wt();se(t,function(e){he(e,"htmx:restored",{document:ne(),triggerEvent:he})})}else{if(n){n(e)}}};E().setTimeout(function(){he(e,"htmx:load",{});e=null},0)});return Q}(); \ No newline at end of file diff --git a/core/core.libraries.yml b/core/core.libraries.yml index cf74707b51e4aa496e4173ffe136f4978113995f..35bf4b0d7a46615e9942762fe9f042e10dc1c4d6 100644 --- a/core/core.libraries.yml +++ b/core/core.libraries.yml @@ -614,6 +614,16 @@ drupal.form: - core/drupal.debounce - core/once +drupal.htmx: + version: VERSION + js: + misc/htmx-behaviors.js: {} + dependencies: + - core/drupal + - core/drupalSettings + - core/htmx + - core/loadjs + drupal.machine-name: version: VERSION js: @@ -782,6 +792,28 @@ drupal.vertical-tabs: - core/drupalSettings - core/drupal.form +htmx: + remote: https://github.com/bigskysoftware/htmx + version: "2.0.4" + license: + name: Zero-Clause BSD + url: https://github.com/bigskysoftware/htmx/blob/master/LICENSE + gpl-compatible: true + js: + assets/vendor/htmx/htmx.min.js: { minified: true } + +htmx.debug: + remote: https://github.com/bigskysoftware/htmx-extensions + version: "2.0.1" + license: + name: Zero-Clause BSD + url: https://github.com/bigskysoftware/htmx-extensions/blob/dev/src/debug/LICENSE + gpl-compatible: true + js: + assets/vendor/htmx/debug.js: {} + dependencies: + - core/htmx + internal.floating-ui: remote: https://github.com/floating-ui/floating-ui version: "1.6.12" diff --git a/core/core.services.yml b/core/core.services.yml index 4372e6512c3e34c73f1db7c5174306690d134bd0..79d276046000d77ea51fcb101036e35352e4f5a7 100644 --- a/core/core.services.yml +++ b/core/core.services.yml @@ -1400,6 +1400,14 @@ services: html_response.subscriber: class: Drupal\Core\EventSubscriber\HtmlResponseSubscriber arguments: ['@html_response.attachments_processor'] + htmx_response.attachments_processor: + class: Drupal\Core\Render\Hypermedia\HtmxResponseAttachmentsProcessor + arguments: [ '@asset.resolver', '@config.factory', '@asset.css.collection_renderer', '@asset.js.collection_renderer', '@request_stack', '@renderer', '@module_handler', '@language_manager' ] + htmx.response_subscriber: + class: Drupal\Core\EventSubscriber\HtmxResponseSubscriber + arguments: [ '@request_stack', '@htmx_response.attachments_processor' ] + tags: + - { name: event_subscriber } finish_response_subscriber: class: Drupal\Core\EventSubscriber\FinishResponseSubscriber arguments: ['@language_manager', '@config.factory', '@page_cache_request_policy', '@page_cache_response_policy', '@cache_contexts_manager', '@datetime.time', '%http.response.debug_cacheability_headers%'] diff --git a/core/lib/Drupal/Core/Datetime/Element/Datetime.php b/core/lib/Drupal/Core/Datetime/Element/Datetime.php index f3b7aba93a450282350077cee59af244b294c92e..e154ab415750f7fab3ebfbb3f1f8e616c32e6eec 100644 --- a/core/lib/Drupal/Core/Datetime/Element/Datetime.php +++ b/core/lib/Drupal/Core/Datetime/Element/Datetime.php @@ -52,6 +52,7 @@ public function getInfo() { '#process' => [ [static::class, 'processDatetime'], [static::class, 'processAjaxForm'], + [static::class, 'processHtmxElement'], [static::class, 'processGroup'], ], '#pre_render' => [ diff --git a/core/lib/Drupal/Core/EventSubscriber/HtmxResponseSubscriber.php b/core/lib/Drupal/Core/EventSubscriber/HtmxResponseSubscriber.php new file mode 100644 index 0000000000000000000000000000000000000000..1a0fa2170317818283c6e83eb6510bec4e34e7dc --- /dev/null +++ b/core/lib/Drupal/Core/EventSubscriber/HtmxResponseSubscriber.php @@ -0,0 +1,61 @@ +<?php + +declare(strict_types=1); + +namespace Drupal\Core\EventSubscriber; + +use Drupal\Core\Render\AttachmentsResponseProcessorInterface; +use Drupal\Core\Render\HtmlResponse; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpKernel\Event\ResponseEvent; +use Symfony\Component\HttpKernel\KernelEvents; + +/** + * Adds assets to a header value on responses to HTMX requests. + * + * Process all attachments before the attachments are rendered in + * HtmlResponseSubscriber. + * + * @see \Drupal\Core\Ajax\HtmxResponseAttachmentsProcessor + */ +final class HtmxResponseSubscriber implements EventSubscriberInterface { + + /** + * Constructs a HtmxResponseSubscriber object. + */ + public function __construct( + private readonly RequestStack $requestStack, + private readonly AttachmentsResponseProcessorInterface $attachmentsProcessor, + ) {} + + /** + * Add assemble and attachments add HTMX attributes. + * + * @see \Drupal\Core\EventSubscriber\HtmlResponseSubscriber::onRespond + */ + public function onRespond(ResponseEvent $event): void { + $response = $event->getResponse(); + $requestHeaders = $this->requestStack->getCurrentRequest()->headers; + if (!($response instanceof HtmlResponse && $requestHeaders->has('HX-Request'))) { + // Only operate on HTML responses from an HTMX request. + return; + } + $processedResponse = $this->attachmentsProcessor->processAttachments($response); + if (!($processedResponse instanceof HtmlResponse)) { + throw new \TypeError("ResponseEvent::setResponse() requires an HtmlResponse object"); + } + $event->setResponse($processedResponse); + } + + /** + * {@inheritdoc} + */ + public static function getSubscribedEvents(): array { + return [ + // Our method needs to run before the HtmlResponseSubscriber(weight 0). + KernelEvents::RESPONSE => ['onRespond', 100], + ]; + } + +} diff --git a/core/lib/Drupal/Core/Form/FormBase.php b/core/lib/Drupal/Core/Form/FormBase.php index d88810943acd0dc6763195c2dd4357192b41b444..4892e20cdf5e5307aa5aa1efbba199216aa32159 100644 --- a/core/lib/Drupal/Core/Form/FormBase.php +++ b/core/lib/Drupal/Core/Form/FormBase.php @@ -194,6 +194,28 @@ protected function currentUser() { return \Drupal::currentUser(); } + /** + * True if the HX-Request header was present on the request. + * + * @return bool + * Is this an HTMX request? + */ + public function isHtmxRequest(): bool { + $request = $this->getRequest(); + return $request->headers->has('HX-Request'); + } + + /** + * Returns the HTMX trigger value stored from the request. + * + * @return string + * The trigger name or empty string if the header is not present. + */ + public function getHtmxTrigger(): string { + $request = $this->getRequest(); + return $request->headers->get('HX-Trigger', ''); + } + /** * Returns a redirect response object for the specified route. * diff --git a/core/lib/Drupal/Core/Form/FormBuilder.php b/core/lib/Drupal/Core/Form/FormBuilder.php index ee3e4893feca035c00a95603554569bb00c3d052..650ea21e83f888b3d3ef2d20a46a90eab370d718 100644 --- a/core/lib/Drupal/Core/Form/FormBuilder.php +++ b/core/lib/Drupal/Core/Form/FormBuilder.php @@ -17,6 +17,7 @@ use Drupal\Core\Render\ElementInfoManagerInterface; use Drupal\Core\Security\TrustedCallbackInterface; use Drupal\Core\Theme\ThemeManagerInterface; +use Symfony\Component\HttpFoundation\Request; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\FileBag; use Symfony\Component\HttpFoundation\InputBag; @@ -302,8 +303,10 @@ public function buildForm($form_arg, FormStateInterface &$form_state) { } } - // If this form is an AJAX request, disable all form redirects. - if ($ajax_form_request = $request->query->has(static::AJAX_FORM_REQUEST)) { + // If this form is a jQuery AJAX request, or an HTMX request disable all + // form redirects. + $ajax_form_request = $request->query->has(static::AJAX_FORM_REQUEST); + if ($ajax_form_request || $this->isHtmxRequest($request)) { $form_state->disableRedirect(); } @@ -602,6 +605,19 @@ public function processForm($form_id, &$form, FormStateInterface &$form_state) { return; } + // If a form from an HTMX request is still processing at this point it + // was not submitted. The form_build_id value needs to be restored if + // the form rebuilds. + // @see \Drupal\Core\Form\EventSubscriber\FormAjaxSubscriber::onException + // @see Drupal.AjaxCommands.update_build_id + if ($this->isHtmxRequest()) { + // Restore the build id that was sent with the request. It will be used + // after the rebuild to cache the rebuilt form. + $form_state->addRebuildInfo('copy', ['#build_id' => TRUE]); + $input = $form_state->getUserInput(); + $form['#build_id'] = $input['form_build_id']; + } + // If $form_state->isRebuilding() has been set and input has been // processed without validation errors, we are in a multi-step workflow // that is not yet complete. A new $form needs to be constructed based on @@ -1299,7 +1315,7 @@ protected function handleInputElement($form_id, &$element, FormStateInterface &$ // \Drupal\Core\Form\FormState::cleanValues(). Enforce the same input // processing restrictions as above. if ($process_input) { - // Detect if the element triggered the submission via Ajax. + // Detect if the element triggered the submission via Ajax or HTMX. if ($this->elementTriggeredScriptedSubmission($element, $form_state)) { $form_state->setTriggeringElement($element); } @@ -1342,6 +1358,12 @@ protected function handleInputElement($form_id, &$element, FormStateInterface &$ */ protected function elementTriggeredScriptedSubmission($element, FormStateInterface &$form_state) { $input = $form_state->getUserInput(); + if ($this->isHtmxRequest()) { + if (isset($element['#attributes']['data-drupal-selector']) && $element['#attributes']['data-drupal-selector'] === $this->getHtmxTrigger()) { + // @see htmxDrupalData() in core/misc/htmx-behaviors.js. + return TRUE; + } + } if (!empty($input['_triggering_element_name']) && $element['#name'] == $input['_triggering_element_name']) { if (empty($input['_triggering_element_value']) || $input['_triggering_element_value'] == $element['#value']) { return TRUE; @@ -1419,6 +1441,38 @@ protected function currentUser() { return $this->currentUser; } + /** + * True if the HX-Request header was present on the request. + * + * @param \Symfony\Component\HttpFoundation\Request|null $request + * A Request to use. If omitted, the current request on the stack is used. + * + * @return bool + * Is this an HTMX request? + */ + public function isHtmxRequest(?Request $request = NULL): bool { + if (!($request instanceof Request)) { + $request = $this->requestStack->getCurrentRequest(); + } + return $request->headers->has('HX-Request'); + } + + /** + * Returns the HTMX trigger value stored from the request. + * + * @param \Symfony\Component\HttpFoundation\Request|null $request + * A Request to use. If omitted, the current request on the stack is used. + * + * @return string + * The trigger name or empty string if the header is not present. + */ + public function getHtmxTrigger(?Request $request = NULL): string { + if (!($request instanceof Request)) { + $request = $this->requestStack->getCurrentRequest(); + } + return $request->headers->get('HX-Trigger', ''); + } + /** * {@inheritdoc} */ diff --git a/core/lib/Drupal/Core/Http/HtmxHeaderInterface.php b/core/lib/Drupal/Core/Http/HtmxHeaderInterface.php new file mode 100644 index 0000000000000000000000000000000000000000..f1cd52b352899efe97ce184e1fddced32c6f1965 --- /dev/null +++ b/core/lib/Drupal/Core/Http/HtmxHeaderInterface.php @@ -0,0 +1,42 @@ +<?php + +namespace Drupal\Core\Http; + +/** + * An interface for classes that manage HTMX Headers. + * + * @extends \IteratorAggregate<string, list<string|null>> + */ +interface HtmxHeaderInterface extends \IteratorAggregate, \Countable, \Stringable { + + /** + * Checks if the storage has a header with the given name. + * + * @param string $name + * The name of the header to check for. + * + * @return bool + * Returns TRUE if the header exists, or FALSE otherwise. + */ + public function hasHeader(string $name): bool; + + /** + * Returns all storage elements as a Drupal 'http_header' array. + * + * @return mixed[] + * An associative array of headers. + */ + public function toArray(): array; + + /** + * Merges an HtmxHeaderInterface object into the current storage. + * + * @param HtmlAttributeInterface $headers + * The Attribute object to merge. + * + * @return HtmxHeaderInterface + * A combined header collection. + */ + public function merge(HtmxHeaderInterface $headers): HtmxHeaderInterface; + +} diff --git a/core/lib/Drupal/Core/Http/HtmxLocationResponseData.php b/core/lib/Drupal/Core/Http/HtmxLocationResponseData.php new file mode 100644 index 0000000000000000000000000000000000000000..4fee738040ab1132cae1823a2e89d793b3c722fe --- /dev/null +++ b/core/lib/Drupal/Core/Http/HtmxLocationResponseData.php @@ -0,0 +1,70 @@ +<?php + +namespace Drupal\Core\Http; + +use Drupal\Core\Url; + +/** + * Optional data object for HX-Location. + */ +class HtmxLocationResponseData implements \Stringable { + + /** + * Data for HX-Location headers. + * + * @param \Drupal\Core\Url $path + * The path for the GET request. + * @param string $source + * The source element of the request. + * @param string $event + * An event that “triggered” the request. + * @param array<string, string> $headers + * Headers to submit with the request. + * @param string $handler + * A callback that will handle the response HTML. + * @param string $target + * The target for the swap. + * @param string $swap + * The swap strategy. + * @param string $select + * A selector for the content to swap into the target. + * @param array<string, string> $values + * A set of values to submit with the request. + * + * @see https://htmx.org/headers/hx-location/ + */ + public function __construct( + public readonly Url $path, + public readonly string $source = '', + public readonly string $event = '', + public readonly array $headers = [], + public readonly string $handler = '', + public readonly string $target = '', + public readonly string $swap = '', + public readonly string $select = '', + public readonly array $values = [], + ) {} + + /** + * Returns non-empty data, JSON encoded. + * + * @return string + * The encoded data. + */ + public function __toString(): string { + $data = [ + 'path' => $this->path->toString(), + 'source' => $this->source, + 'event' => $this->event, + 'headers' => $this->headers, + 'handler' => $this->handler, + 'target' => $this->target, + 'swap' => $this->swap, + 'select' => $this->select, + 'values' => $this->values, + ]; + $data = array_filter($data, static fn ($item) => $item !== '' && $item !== []); + return json_encode($data); + } + +} diff --git a/core/lib/Drupal/Core/Http/HtmxResponseHeaders.php b/core/lib/Drupal/Core/Http/HtmxResponseHeaders.php new file mode 100644 index 0000000000000000000000000000000000000000..20439a79631e7e8472043ab4550823b04d68b100 --- /dev/null +++ b/core/lib/Drupal/Core/Http/HtmxResponseHeaders.php @@ -0,0 +1,279 @@ +<?php + +namespace Drupal\Core\Http; + +use Drupal\Core\Url; +use Symfony\Component\HttpFoundation\HeaderBag; + +/** + * Builds HTMX response headers. + * + * Principally used in the composite Htmx value object. + * + * @see \Drupal\Core\Render\Hypermedia\Htmx + * @see https://htmx.org/reference/#response_headers + */ +class HtmxResponseHeaders implements HtmxHeaderInterface { + + /** + * Initialize empty storage. + * + * Allows for passing a populated HeaderBag to support merging. + */ + public function __construct( + private HeaderBag $headers = new HeaderBag(), + ) {} + + /** + * {@inheritdoc} + */ + public function getIterator(): \Traversable { + return $this->headers->getIterator(); + } + + /** + * {@inheritdoc} + */ + public function count(): int { + return $this->headers->count(); + } + + /** + * {@inheritdoc} + */ + public function __toString(): string { + return (string) $this->headers; + } + + /** + * {@inheritdoc} + */ + public function hasHeader($name): bool { + return $this->headers->has($name); + } + + /** + * {@inheritdoc} + */ + public function toArray(): array { + $drupalHeaders = []; + foreach ($this->headers as $name => $value) { + // Set replace to true. + $drupalHeaders[] = [$name, $value, TRUE]; + } + return $drupalHeaders; + } + + /** + * {@inheritdoc} + */ + public function merge(HtmxHeaderInterface $headers): HtmxHeaderInterface { + foreach ($headers as $name => $value) { + $this->headers->set($name, $value); + } + return $this; + } + + /** + * Set HX-Location header. + * + * @param \Drupal\Core\Url|\Drupal\htmx\Http\HtmxLocationResponseData $data + * Use Url if only a path is needed. + * + * @return \Drupal\htmx\Http\HtmxResponseHeaders + * Self for chaining. + * + * @see https://htmx.org/headers/hx-location/ + */ + public function location(Url|HtmxLocationResponseData $data): HtmxResponseHeaders { + if ($data instanceof HtmxLocationResponseData) { + $this->headers->set('HX-Location', (string) $data); + } + else { + $this->headers->set('HX-Location', $data->toString()); + } + return $this; + } + + /** + * Set HX-Push-Url header. + * + * @param \Drupal\Core\Url|false $data + * URL to push to the location bar or false to prevent a history update. + * + * @return \Drupal\htmx\Http\HtmxResponseHeaders + * Self for chaining. + * + * @see https://htmx.org/headers/hx-push-url/ + */ + public function pushUrl(Url|false $data): HtmxResponseHeaders { + if ($data instanceof Url) { + $this->headers->set('HX-Push-Url', $data->toString()); + } + else { + $this->headers->set('HX-Push-Url', 'false'); + } + return $this; + } + + /** + * Set HX-Replace-Url header. + * + * @param \Drupal\Core\Url|false $data + * URL for history replacement, false prevents updates to the current URL. + * + * @return \Drupal\htmx\Http\HtmxResponseHeaders + * Self for chaining. + * + * @see https://htmx.org/headers/hx-replace-url/ + */ + public function replaceUrl(Url|false $data): HtmxResponseHeaders { + if ($data instanceof Url) { + $this->headers->set('HX-Replace-Url', $data->toString()); + } + else { + $this->headers->set('HX-Replace-Url', 'false'); + } + return $this; + } + + /** + * Set HX-Redirect header. + * + * @param \Drupal\Core\Url $url + * Destination for a client side redirection. + * + * @return \Drupal\htmx\Http\HtmxResponseHeaders + * Self for chaining. + */ + public function redirect(Url $url): HtmxResponseHeaders { + $this->headers->set('HX-Redirect', $url->toString()); + return $this; + } + + /** + * Set HX-Refresh header. + * + * @param bool $refresh + * If set to “true” the client-side will do a full refresh of the page. + * + * @return \Drupal\htmx\Http\HtmxResponseHeaders + * Self for chaining. + */ + public function refresh(bool $refresh): HtmxResponseHeaders { + $this->headers->set('HX-Refresh', $refresh ? 'true' : 'false'); + return $this; + } + + /** + * Set HX-Reswap header. + * + * @param string $strategy + * Specify how the response will be swapped (see hx-swap). + * + * @return \Drupal\htmx\Http\HtmxResponseHeaders + * Self for chaining. + */ + public function reswap(string $strategy): HtmxResponseHeaders { + $this->headers->set('HX-Reswap', $strategy); + return $this; + } + + /** + * Set HX-Retarget header. + * + * @param string $strategy + * CSS selector that replaces the target to a different element on the page. + * + * @return \Drupal\htmx\Http\HtmxResponseHeaders + * Self for chaining. + */ + public function retarget(string $strategy): HtmxResponseHeaders { + $this->headers->set('HX-Retarget', $strategy); + return $this; + } + + /** + * Set HX-Reselect header. + * + * @param string $strategy + * CSS selector that changes the selection taken from the response. + * + * @return \Drupal\htmx\Http\HtmxResponseHeaders + * Self for chaining. + */ + public function reselect(string $strategy): HtmxResponseHeaders { + $this->headers->set('HX-Reselect', $strategy); + return $this; + } + + /** + * Set HX-Trigger header. + * + * See the documentation for the structure of the array. + * + * @param string|array $data + * An event name or an array which will be JSON encoded. + * + * @return \Drupal\htmx\Http\HtmxResponseHeaders + * Self for chaining. + * + * @see https://htmx.org/headers/hx-trigger/ + */ + public function trigger(string|array $data): HtmxResponseHeaders { + if (is_array($data)) { + $this->headers->set('HX-Trigger', json_encode($data)); + } + else { + $this->headers->set('HX-Trigger', $data); + } + return $this; + } + + /** + * Set HX-Trigger-After-Settle header. + * + * See the documentation for the structure of the array. + * + * @param string|array $data + * An event name or an array which will be JSON encoded. + * + * @return \Drupal\htmx\Http\HtmxResponseHeaders + * Self for chaining. + * + * @see https://htmx.org/headers/hx-trigger/ + */ + public function triggerAfterSettle(string|array $data): HtmxResponseHeaders { + if (is_array($data)) { + $this->headers->set('HX-Trigger-After-Settle', json_encode($data)); + } + else { + $this->headers->set('HX-Trigger-After-Settle', $data); + } + return $this; + } + + /** + * Set HX-Trigger-After-Swap header. + * + * See the documentation for the structure of the array. + * + * @param string|array $data + * An event name or an array which will be JSON encoded. + * + * @return \Drupal\htmx\Http\HtmxResponseHeaders + * Self for chaining. + * + * @see https://htmx.org/headers/hx-trigger/ + */ + public function triggerAfterSwap(string|array $data): HtmxResponseHeaders { + if (is_array($data)) { + $this->headers->set('HX-Trigger-After-Swap', json_encode($data)); + } + else { + $this->headers->set('HX-Trigger-After-Swap', $data); + } + return $this; + } + +} diff --git a/core/lib/Drupal/Core/Http/HttpMethod.php b/core/lib/Drupal/Core/Http/HttpMethod.php new file mode 100644 index 0000000000000000000000000000000000000000..52637d601736f989da6519c3ef2c511dab613166 --- /dev/null +++ b/core/lib/Drupal/Core/Http/HttpMethod.php @@ -0,0 +1,16 @@ +<?php + +namespace Drupal\Core\Http; + +/** + * Enumerates the valid HTTP methods or verbs. + */ +enum HttpMethod { + + case Get; + case Post; + case Put; + case Patch; + case Delete; + +} diff --git a/core/lib/Drupal/Core/Render/Element/Button.php b/core/lib/Drupal/Core/Render/Element/Button.php index a8f12e93963690cbcf909789678489de57420cc7..7712e394f067772bfba2d2807c6c4b72d55ae1ff 100644 --- a/core/lib/Drupal/Core/Render/Element/Button.php +++ b/core/lib/Drupal/Core/Render/Element/Button.php @@ -53,6 +53,7 @@ public function getInfo() { '#process' => [ [static::class, 'processButton'], [static::class, 'processAjaxForm'], + [static::class, 'processHtmxElement'], ], '#pre_render' => [ [static::class, 'preRenderButton'], diff --git a/core/lib/Drupal/Core/Render/Element/Checkbox.php b/core/lib/Drupal/Core/Render/Element/Checkbox.php index 65be5d22bf106195fe50894a7823f684f8cefe1b..2380fc5328b507024e5e4bbbd585742033c62cb6 100644 --- a/core/lib/Drupal/Core/Render/Element/Checkbox.php +++ b/core/lib/Drupal/Core/Render/Element/Checkbox.php @@ -35,6 +35,7 @@ public function getInfo() { '#process' => [ [static::class, 'processCheckbox'], [static::class, 'processAjaxForm'], + [static::class, 'processHtmxElement'], [static::class, 'processGroup'], ], '#pre_render' => [ diff --git a/core/lib/Drupal/Core/Render/Element/Color.php b/core/lib/Drupal/Core/Render/Element/Color.php index 254300d976f9b11c0871b3f607e76078819b7013..0c031a813e33fc78376548fa62a97289d915ebed 100644 --- a/core/lib/Drupal/Core/Render/Element/Color.php +++ b/core/lib/Drupal/Core/Render/Element/Color.php @@ -33,6 +33,7 @@ public function getInfo() { '#input' => TRUE, '#process' => [ [static::class, 'processAjaxForm'], + [static::class, 'processHtmxElement'], ], '#element_validate' => [ [static::class, 'validateColor'], diff --git a/core/lib/Drupal/Core/Render/Element/Container.php b/core/lib/Drupal/Core/Render/Element/Container.php index d5a2092718e742454abf7d7ab416e2cda2cfd238..83b400525d29db059f91457b284cdde32aee6c6c 100644 --- a/core/lib/Drupal/Core/Render/Element/Container.php +++ b/core/lib/Drupal/Core/Render/Element/Container.php @@ -58,6 +58,7 @@ public function getInfo() { '#pre_render' => [ [static::class, 'preRenderGroup'], [static::class, 'preRenderContainer'], + [static::class, 'processHtmxElement'], ], '#theme_wrappers' => ['container'], ]; diff --git a/core/lib/Drupal/Core/Render/Element/Date.php b/core/lib/Drupal/Core/Render/Element/Date.php index 8304167ae70782ea9791bcf390354a38100a6589..cd97a6031481ec6958693d8f489c2be9465e8511 100644 --- a/core/lib/Drupal/Core/Render/Element/Date.php +++ b/core/lib/Drupal/Core/Render/Element/Date.php @@ -45,6 +45,7 @@ public function getInfo() { '#theme' => 'input__date', '#process' => [ [static::class, 'processAjaxForm'], + [static::class, 'processHtmxElement'], ], '#pre_render' => [[static::class, 'preRenderDate']], '#theme_wrappers' => ['form_element'], diff --git a/core/lib/Drupal/Core/Render/Element/Details.php b/core/lib/Drupal/Core/Render/Element/Details.php index 28e7396887d8b3c6c673602a1b97eba364b09af8..b4b24f74631e90c461b3119c19ee6ef8ef178faf 100644 --- a/core/lib/Drupal/Core/Render/Element/Details.php +++ b/core/lib/Drupal/Core/Render/Element/Details.php @@ -49,6 +49,7 @@ public function getInfo() { '#process' => [ [static::class, 'processGroup'], [static::class, 'processAjaxForm'], + [static::class, 'processHtmxElement'], ], '#pre_render' => [ [static::class, 'preRenderDetails'], diff --git a/core/lib/Drupal/Core/Render/Element/Dropbutton.php b/core/lib/Drupal/Core/Render/Element/Dropbutton.php index 20bb375ea879f32a4c1097aced634fbbf547af97..09c43ed64da3dc127aeeed33e66b1e09f9845fc3 100644 --- a/core/lib/Drupal/Core/Render/Element/Dropbutton.php +++ b/core/lib/Drupal/Core/Render/Element/Dropbutton.php @@ -52,6 +52,7 @@ public function getInfo() { return [ '#pre_render' => [ [static::class, 'preRenderDropbutton'], + [static::class, 'processHtmxElement'], ], '#theme' => 'links__dropbutton', ]; diff --git a/core/lib/Drupal/Core/Render/Element/Email.php b/core/lib/Drupal/Core/Render/Element/Email.php index 82e688ce38e2cc86671c44c9dc0fef63955bb570..71b22e1079a921c3e4a5ba1041960e0f31903367 100644 --- a/core/lib/Drupal/Core/Render/Element/Email.php +++ b/core/lib/Drupal/Core/Render/Element/Email.php @@ -53,6 +53,7 @@ public function getInfo() { '#process' => [ [static::class, 'processAutocomplete'], [static::class, 'processAjaxForm'], + [static::class, 'processHtmxElement'], [static::class, 'processPattern'], ], '#element_validate' => [ diff --git a/core/lib/Drupal/Core/Render/Element/Fieldset.php b/core/lib/Drupal/Core/Render/Element/Fieldset.php index af0396789b39bfee7bb7f808bddfd67c620831cf..6a65c8b64000c472e01cd3cd1c7a743e6abca0a1 100644 --- a/core/lib/Drupal/Core/Render/Element/Fieldset.php +++ b/core/lib/Drupal/Core/Render/Element/Fieldset.php @@ -34,6 +34,7 @@ public function getInfo() { '#process' => [ [static::class, 'processGroup'], [static::class, 'processAjaxForm'], + [static::class, 'processHtmxElement'], ], '#pre_render' => [ [static::class, 'preRenderGroup'], diff --git a/core/lib/Drupal/Core/Render/Element/Hidden.php b/core/lib/Drupal/Core/Render/Element/Hidden.php index db3b23a08cced0fcf51b8bfc7732485522dfced9..98c524b14be6c335fb966e7f9f290523dcb7cdf4 100644 --- a/core/lib/Drupal/Core/Render/Element/Hidden.php +++ b/core/lib/Drupal/Core/Render/Element/Hidden.php @@ -34,6 +34,7 @@ public function getInfo() { '#input' => TRUE, '#process' => [ [static::class, 'processAjaxForm'], + [static::class, 'processHtmxElement'], ], '#pre_render' => [ [static::class, 'preRenderHidden'], diff --git a/core/lib/Drupal/Core/Render/Element/HtmlTag.php b/core/lib/Drupal/Core/Render/Element/HtmlTag.php index 3b4dbd25d462f1547cbc3137d1012383fff2cb87..d59e4189c417677d32ef878a9e7b3ee1383bdad7 100644 --- a/core/lib/Drupal/Core/Render/Element/HtmlTag.php +++ b/core/lib/Drupal/Core/Render/Element/HtmlTag.php @@ -56,6 +56,7 @@ public function getInfo() { return [ '#pre_render' => [ [static::class, 'preRenderHtmlTag'], + [static::class, 'processHtmxElement'], ], '#attributes' => [], '#value' => NULL, diff --git a/core/lib/Drupal/Core/Render/Element/Label.php b/core/lib/Drupal/Core/Render/Element/Label.php index b2dbc9841a73e80c58e4dbc6317afc0f2824175f..cefbe049adfec91d1ed5ae42db65c7a63e31a9d6 100644 --- a/core/lib/Drupal/Core/Render/Element/Label.php +++ b/core/lib/Drupal/Core/Render/Element/Label.php @@ -20,6 +20,9 @@ class Label extends RenderElementBase { public function getInfo() { return [ '#theme' => 'form_element_label', + '#pre_render' => [ + [self::class, 'processHtmxElement'], + ], ]; } diff --git a/core/lib/Drupal/Core/Render/Element/Link.php b/core/lib/Drupal/Core/Render/Element/Link.php index 2a00e0526b6872640f18057a2e67585e00298df5..73d4e6f149a9965838c9c9eb5cbc3ea688c6dfd2 100644 --- a/core/lib/Drupal/Core/Render/Element/Link.php +++ b/core/lib/Drupal/Core/Render/Element/Link.php @@ -37,6 +37,7 @@ public function getInfo() { return [ '#pre_render' => [ [static::class, 'preRenderLink'], + [static::class, 'processHtmxElement'], ], ]; } diff --git a/core/lib/Drupal/Core/Render/Element/MachineName.php b/core/lib/Drupal/Core/Render/Element/MachineName.php index ec03e46616e8714bec82669844e51f9c8ec20ee5..b6935fd0f8f2ca67238f31bebba71d8ff864d476 100644 --- a/core/lib/Drupal/Core/Render/Element/MachineName.php +++ b/core/lib/Drupal/Core/Render/Element/MachineName.php @@ -88,6 +88,7 @@ public function getInfo() { [static::class, 'processMachineName'], [static::class, 'processAutocomplete'], [static::class, 'processAjaxForm'], + [static::class, 'processHtmxElement'], ], '#element_validate' => [ [static::class, 'validateMachineName'], diff --git a/core/lib/Drupal/Core/Render/Element/Number.php b/core/lib/Drupal/Core/Render/Element/Number.php index 7096b2925beb6dbece49b9b613aa0e10b15e56de..c15da7339434ebfd19f128edcd1a5aa42a3ed3b9 100644 --- a/core/lib/Drupal/Core/Render/Element/Number.php +++ b/core/lib/Drupal/Core/Render/Element/Number.php @@ -41,6 +41,7 @@ public function getInfo() { '#step' => 1, '#process' => [ [static::class, 'processAjaxForm'], + [static::class, 'processHtmxElement'], ], '#element_validate' => [ [static::class, 'validateNumber'], diff --git a/core/lib/Drupal/Core/Render/Element/PageTitle.php b/core/lib/Drupal/Core/Render/Element/PageTitle.php index c56141de3480c7e850cbc8cc45f466f39754830a..de8bf1ea1fdd9898076ffcaccc96368047b1dcbc 100644 --- a/core/lib/Drupal/Core/Render/Element/PageTitle.php +++ b/core/lib/Drupal/Core/Render/Element/PageTitle.php @@ -21,6 +21,9 @@ public function getInfo() { // The page title: either a string for plain titles or a render array for // formatted titles. '#title' => NULL, + '#pre_render' => [ + [self::class, 'processHtmxElement'], + ], ]; } diff --git a/core/lib/Drupal/Core/Render/Element/Pager.php b/core/lib/Drupal/Core/Render/Element/Pager.php index a31c7f2f37190ff6768562c59aad7904dcd46d79..bf8cc4fff4ad7b58ae7b6039e972534eaad7efd9 100644 --- a/core/lib/Drupal/Core/Render/Element/Pager.php +++ b/core/lib/Drupal/Core/Render/Element/Pager.php @@ -41,6 +41,7 @@ public function getInfo() { return [ '#pre_render' => [ static::class . '::preRenderPager', + [self::class, 'processHtmxElement'], ], '#theme' => 'pager', // The pager ID, to distinguish between multiple pagers on the same page. diff --git a/core/lib/Drupal/Core/Render/Element/Password.php b/core/lib/Drupal/Core/Render/Element/Password.php index 0c2e99d054b73758265afff62bdc3b778e741ca0..c8abaa99cd497318ff895c891f7354775c80fb8e 100644 --- a/core/lib/Drupal/Core/Render/Element/Password.php +++ b/core/lib/Drupal/Core/Render/Element/Password.php @@ -39,6 +39,7 @@ public function getInfo() { '#maxlength' => 128, '#process' => [ [static::class, 'processAjaxForm'], + [static::class, 'processHtmxElement'], [static::class, 'processPattern'], ], '#pre_render' => [ diff --git a/core/lib/Drupal/Core/Render/Element/Radio.php b/core/lib/Drupal/Core/Render/Element/Radio.php index e7c5771ec4c537b868a468bc075b082bda0df030..33e3e5c8c4bf43fc6f33690ff3ecb0d7f48b25bf 100644 --- a/core/lib/Drupal/Core/Render/Element/Radio.php +++ b/core/lib/Drupal/Core/Render/Element/Radio.php @@ -26,6 +26,7 @@ public function getInfo() { '#default_value' => NULL, '#process' => [ [static::class, 'processAjaxForm'], + [static::class, 'processHtmxElement'], ], '#pre_render' => [ [static::class, 'preRenderRadio'], diff --git a/core/lib/Drupal/Core/Render/Element/RenderElementBase.php b/core/lib/Drupal/Core/Render/Element/RenderElementBase.php index 451df8a0e3695cfc86dff67bfbdb64f1439818fb..cae21eb90326a5c05bd8790f92aa9c48444d707c 100644 --- a/core/lib/Drupal/Core/Render/Element/RenderElementBase.php +++ b/core/lib/Drupal/Core/Render/Element/RenderElementBase.php @@ -2,11 +2,14 @@ namespace Drupal\Core\Render\Element; +use Drupal\Component\Utility\NestedArray; use Drupal\Core\Form\FormBuilderInterface; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Plugin\PluginBase; use Drupal\Core\Render\BubbleableMetadata; use Drupal\Core\Render\Element; +use Drupal\Core\Render\Hypermedia\HtmxInterface; +use Drupal\Core\Template\AttributeHelper; use Drupal\Core\Url; /** @@ -49,8 +52,8 @@ * See the "Attaching libraries in render arrays" section of the * @link theme_render Render API topic @endlink for an overview, and * \Drupal\Core\Render\AttachmentsResponseProcessorInterface::processAttachments - * for a list of what this can contain. Besides this list, it may also contain - * a 'placeholders' element; see the Placeholders section of the + * for a list of what this can contain. Besides this list, it may also + * contain a 'placeholders' element; see the Placeholders section of the * @link theme_render Render API topic @endlink for an overview. * - #attributes: (array) HTML attributes for the element. The first-level * keys are the attribute names, such as 'class', and the attributes are @@ -434,6 +437,51 @@ public static function preRenderAjaxForm($element) { return $element; } + /** + * @param mixed[] $element + * The render array for the element. + * + * @return mixed[] + * The modified array with HTMX library attachments, if appropriate. + */ + public static function processHtmxElement(array $element): array { + $processed = $element['#htmx_processed'] ?? FALSE; + // Skip already processed elements. + if ($processed) { + return $element; + } + // Initialize #htmx_processed, so we do not process this element again. + $element['#htmx_processed'] = FALSE; + + // Nothing to do if there are no HTMX settings. + if (empty($element['#htmx']) || !($element['#htmx'] instanceof HtmxInterface)) { + return $element; + } + $htmx = $element['#htmx']; + + // Process operations; + if ($htmx->hasOperations()) { + $htmx->processOperations(); + } + + // Attach HTMX and integration javascript. + $element['#attached']['library'][] = 'core/drupal.htmx'; + // Consolidate headers. + if ($htmx->headers->count() !== 0) { + $element['#attached']['http_header'] = $element['#attached']['http_header'] ?? []; + $element['#attached']['http_header'] = NestedArray::mergeDeep($element['#attached']['http_header'], $htmx->headers->toArray()); + } + if ($htmx->attributes->count() !== 0) { + // Consolidate attributes. + $element['#attributes'] = $element['#attributes'] ?? []; + $element['#attributes'] = AttributeHelper::mergeCollections($element['#attributes'], $htmx->attributes); + } + + // Indicate that HTMX processing was successful. + $element['#htmx_processed'] = TRUE; + return $element; + } + /** * Arranges elements into groups. * diff --git a/core/lib/Drupal/Core/Render/Element/Search.php b/core/lib/Drupal/Core/Render/Element/Search.php index 3c022c55e33b1786108c59500428b4533f012308..6d0f36a2520ae1e57cacdc21f932cb5b4ecf3bad 100644 --- a/core/lib/Drupal/Core/Render/Element/Search.php +++ b/core/lib/Drupal/Core/Render/Element/Search.php @@ -33,6 +33,7 @@ public function getInfo() { '#process' => [ [static::class, 'processAutocomplete'], [static::class, 'processAjaxForm'], + [static::class, 'processHtmxElement'], ], '#pre_render' => [ [static::class, 'preRenderSearch'], diff --git a/core/lib/Drupal/Core/Render/Element/Select.php b/core/lib/Drupal/Core/Render/Element/Select.php index 094b963212bd784c8f0ec3fd96fd3c7397e87df8..5f68df3184904a0b920cb01403693570017784b9 100644 --- a/core/lib/Drupal/Core/Render/Element/Select.php +++ b/core/lib/Drupal/Core/Render/Element/Select.php @@ -98,6 +98,7 @@ public function getInfo() { '#process' => [ [static::class, 'processSelect'], [static::class, 'processAjaxForm'], + [static::class, 'processHtmxElement'], ], '#pre_render' => [ [static::class, 'preRenderSelect'], diff --git a/core/lib/Drupal/Core/Render/Element/StatusMessages.php b/core/lib/Drupal/Core/Render/Element/StatusMessages.php index 4eecd9f42f1a793d6317fefdfb7259315115cc89..ff03b475b0a322e04a670f3aaa88f8cdf1503dbf 100644 --- a/core/lib/Drupal/Core/Render/Element/StatusMessages.php +++ b/core/lib/Drupal/Core/Render/Element/StatusMessages.php @@ -32,6 +32,7 @@ public function getInfo() { '#display' => NULL, '#pre_render' => [ static::class . '::generatePlaceholder', + [self::class, 'processHtmxElement'], ], '#include_fallback' => FALSE, ]; diff --git a/core/lib/Drupal/Core/Render/Element/Tel.php b/core/lib/Drupal/Core/Render/Element/Tel.php index 9d5951e7d4e66cfc83b2877f5186e96af427e6a6..9628607e4e8767e69f99d6c2b5e778b9414619dc 100644 --- a/core/lib/Drupal/Core/Render/Element/Tel.php +++ b/core/lib/Drupal/Core/Render/Element/Tel.php @@ -42,6 +42,7 @@ public function getInfo() { [static::class, 'processAutocomplete'], [static::class, 'processAjaxForm'], [static::class, 'processPattern'], + [static::class, 'processHtmxElement'], ], '#pre_render' => [ [static::class, 'preRenderTel'], diff --git a/core/lib/Drupal/Core/Render/Element/Textarea.php b/core/lib/Drupal/Core/Render/Element/Textarea.php index c3fc6021924436105a89b1f3b80c66901a2eeedb..7fcd4cf81cf96f7a7467b9121bf7efaffeed9182 100644 --- a/core/lib/Drupal/Core/Render/Element/Textarea.php +++ b/core/lib/Drupal/Core/Render/Element/Textarea.php @@ -41,6 +41,7 @@ public function getInfo() { '#process' => [ [static::class, 'processAjaxForm'], [static::class, 'processGroup'], + [static::class, 'processHtmxElement'], ], '#pre_render' => [ [static::class, 'preRenderGroup'], diff --git a/core/lib/Drupal/Core/Render/Element/Textfield.php b/core/lib/Drupal/Core/Render/Element/Textfield.php index de144ab4348df6dfc0f502a6ba3a652a89004c87..3a04f82145b0c8b8f54a9aa7f0b9d932a237ee20 100644 --- a/core/lib/Drupal/Core/Render/Element/Textfield.php +++ b/core/lib/Drupal/Core/Render/Element/Textfield.php @@ -52,6 +52,7 @@ public function getInfo() { [static::class, 'processAjaxForm'], [static::class, 'processPattern'], [static::class, 'processGroup'], + [static::class, 'processHtmxElement'], ], '#pre_render' => [ [static::class, 'preRenderTextfield'], diff --git a/core/lib/Drupal/Core/Render/Element/Url.php b/core/lib/Drupal/Core/Render/Element/Url.php index 7c5a9af2fbb458978c9e06e98a1ef0c70e925ab2..f3f20d2f3e9f80c14b06402ebf6c0614d83fb2b6 100644 --- a/core/lib/Drupal/Core/Render/Element/Url.php +++ b/core/lib/Drupal/Core/Render/Element/Url.php @@ -44,6 +44,7 @@ public function getInfo() { [static::class, 'processAutocomplete'], [static::class, 'processAjaxForm'], [static::class, 'processPattern'], + [static::class, 'processHtmxElement'], ], '#element_validate' => [ [static::class, 'validateUrl'], diff --git a/core/lib/Drupal/Core/Render/Element/VerticalTabs.php b/core/lib/Drupal/Core/Render/Element/VerticalTabs.php index bf55119913b0aaad257355f662e45fe24fb9a6a7..b580aee0bad3af3c2e1af331a3029833d01b125e 100644 --- a/core/lib/Drupal/Core/Render/Element/VerticalTabs.php +++ b/core/lib/Drupal/Core/Render/Element/VerticalTabs.php @@ -57,6 +57,7 @@ public function getInfo() { '#default_tab' => '', '#process' => [ [static::class, 'processVerticalTabs'], + [self::class, 'processHtmxElement'], ], '#pre_render' => [ [static::class, 'preRenderVerticalTabs'], diff --git a/core/lib/Drupal/Core/Render/Element/Weight.php b/core/lib/Drupal/Core/Render/Element/Weight.php index 89df69b1879f9958c176068412e26024b36ea807..c031ff247c38152a2ef56c95acb2dfa929dc92c7 100644 --- a/core/lib/Drupal/Core/Render/Element/Weight.php +++ b/core/lib/Drupal/Core/Render/Element/Weight.php @@ -39,6 +39,7 @@ public function getInfo() { '#process' => [ [static::class, 'processWeight'], [static::class, 'processAjaxForm'], + [static::class, 'processHtmxElement'], ], ]; } diff --git a/core/lib/Drupal/Core/Render/Hypermedia/Htmx.php b/core/lib/Drupal/Core/Render/Hypermedia/Htmx.php new file mode 100644 index 0000000000000000000000000000000000000000..e8bb402d7c665d9a99b08e40f730fdad39bc36dd --- /dev/null +++ b/core/lib/Drupal/Core/Render/Hypermedia/Htmx.php @@ -0,0 +1,178 @@ +<?php + +namespace Drupal\Core\Render\Hypermedia; + +use Drupal\Component\Utility\NestedArray; +use Drupal\Core\Http\HtmxHeaderInterface; +use Drupal\Core\Http\HtmxResponseHeaders; +use Drupal\Core\Render\Hypermedia\Operations\HtmxOperationInterface; +use Drupal\Core\Render\Hypermedia\Operations\HtmxRequestOperationInterface; +use Drupal\Core\Template\AttributeHelper; +use Drupal\Core\Template\HtmlAttributeInterface; +use Drupal\Core\Template\HtmxAttribute; + +/** + * Collects HTMX attributes and headers and manages complex behaviors. + * + * An instance of this object is required to add HTMX behaviors to a render + * element. + * + * Methods to configure common behaviors are provided: + * + * @code + * $htmx = new Htmx(); + * $node_url = Url::fromRoute( + * route_name: entity.node.canonical', + * route_parameters: ['node' => 123], + * ); + * $htmx->insert($node_url, 'div.example', 'article.page') + * + * $build = [ + * '#htmx' => $htmx, + * ]; + * @endcode + * + * Attributes may also be specified explicitly: + * + * @code + * $htmx = new Htmx(); + * $form_url = Url::fromRoute( + * route_name: 'config.export_single', + * route_parameters: ['config_type' => $config_type, 'config_name' => $config_name], + * ); + * + * $htmx->attributes() + * ->post($form_url) + * ->select('select[data-drupal-selector="edit-config-name"]') + * ->target('select[data-drupal-selector="edit-config-name"]') + * ->swap('outerHTML'); + * + * $build = [ + * '#htmx' => $htmx, + * ]; + * @endcode + * + * HTMX headers are added in a similar way. + * + * @code + * // Also update the browser URL. + * $push = Url::fromRoute( + * route_name: 'config.export_single', + * route_parameters: ['config_type' => $default_type, 'config_name' => $default_name], + * ); + * + * $htmx = new Htmx(); + * $htmx->headers()->pushUrl($push); + * $build = [ + * '#htmx' => $htmx, + * ]; + * @endcode + * + * @see \Drupal\Core\Template\HtmxAttribute + * @see \Drupal\Core\Http\HtmxResponseHeaders + */ +class Htmx implements HtmxInterface { + + /** + * Optional request operation. + * + * @var \Drupal\Core\Render\Hypermedia\Operations\HtmxRequestOperationInterface|null + */ + protected HtmxRequestOperationInterface|null $requestOperation = NULL; + + /** + * Additional operations that do not depend on a request. + * + * @var \Drupal\Core\Render\Hypermedia\Operations\HtmxOperationInterface[] + */ + protected array $additionalOperations = []; + + public function __construct( + public readonly HtmxAttribute $attributes = new HtmxAttribute(), + public readonly HtmxHeaderInterface $headers = new HtmxResponseHeaders(), + ) {} + + /** + * {@inheritdoc} + */ + public function attributes(): HtmxAttribute { + return $this->attributes; + } + + /** + * {@inheritdoc} + */ + public function headers(): HtmxHeaderInterface { + return $this->headers; + } + + /** + * {@inheritdoc} + */ + public function getCombinedAttributes(array|HtmlAttributeInterface $attributes): HtmlAttributeInterface|array { + return AttributeHelper::mergeCollections($attributes, $this->attributes); + } + + /** + * {@inheritdoc} + */ + public function getCombinedHeaders(array $headers): array { + return NestedArray::mergeDeep($headers, $this->headers->toArray()); + } + + /** + * {@inheritdoc} + */ + public function merge(HtmxInterface $htmx): HtmxInterface { + $this->attributes->merge($htmx->attributes()); + $this->headers->merge($htmx->headers()); + return $this; + } + + /** + * {@inheritdoc} + */ + public function setRequestOperation(HtmxRequestOperationInterface $operation): HtmxInterface { + $this->requestOperation = $operation; + return $this; + } + + /** + * {@inheritdoc} + */ + public function setAdditionalOperation(HtmxOperationInterface $operation): HtmxInterface { + if ($operation instanceof HtmxRequestOperationInterface) { + throw new \ValueError('Htmx::setRequestOperation() must be used to add HtmxRequestOperationInterface operations'); + } + $this->additionalOperations[] = $operation; + return $this; + } + + /** + * {@inheritdoc} + */ + public function hasOperations(): bool { + return $this->requestOperation instanceof HtmxRequestOperationInterface + || count($this->additionalOperations) !== 0; + } + + /** + * {@inheritdoc} + */ + public function processOperations(): void { + if ($this->hasOperations() === FALSE) { + return; + } + $operations = []; + if (count($this->additionalOperations) !== 0) { + $operations = $this->additionalOperations; + } + if ($this->requestOperation instanceof HtmxRequestOperationInterface) { + array_unshift($operations, $this->requestOperation); + } + foreach ($operations as $operation) { + $operation->setProperties($this); + } + } + +} diff --git a/core/lib/Drupal/Core/Render/Hypermedia/HtmxInterface.php b/core/lib/Drupal/Core/Render/Hypermedia/HtmxInterface.php new file mode 100644 index 0000000000000000000000000000000000000000..7fb99e66e93f730f31f0d1349c3ae26e3df58a9b --- /dev/null +++ b/core/lib/Drupal/Core/Render/Hypermedia/HtmxInterface.php @@ -0,0 +1,103 @@ +<?php + +namespace Drupal\Core\Render\Hypermedia; + +use Drupal\Core\Http\HtmxHeaderInterface; +use Drupal\Core\Render\Hypermedia\Operations\HtmxOperationInterface; +use Drupal\Core\Render\Hypermedia\Operations\HtmxRequestOperationInterface; +use Drupal\Core\Template\HtmlAttributeInterface; +use Drupal\Core\Template\HtmxAttribute; + +/** + * An interface for objects that manage HTMX behaviors. + */ +interface HtmxInterface { + + /** + * Accessor for the HtmxAttribute. + * + * @return \Drupal\Core\Template\HtmxAttribute + * The attributes object. + */ + public function attributes(): HtmxAttribute; + + /** + * Accessor for the headers, typically an instance of HtmxResponseHeader. + * + * @return \Drupal\Core\Http\HtmxHeaderInterface + * The headers object. + */ + public function headers(): HtmxHeaderInterface; + + /** + * Merges this object's attributes with an array or collection of attributes. + * + * @param \Drupal\Core\Template\HtmlAttributeInterface|array $attributes + * The data to merge. + * + * @return \Drupal\Core\Template\HtmlAttributeInterface|array + * Returns the data in the form it was recieved. + */ + public function getCombinedAttributes(HtmlAttributeInterface|array $attributes): HtmlAttributeInterface|array; + + /** + * Produces a merged Drupal 'http_header' array. + * + * @param array $headers + * A Drupal 'http_header' array to augment. + * + * @return array + * This objects headers merged with the received headers. + */ + public function getCombinedHeaders(array $headers): array; + + /** + * Merges this objects data with another instance of HtmxInterface. + * + * @param \Drupal\Core\Render\Hypermedia\HtmxInterface $htmx + * The source of additional data. + * + * @return \Drupal\Core\Render\Hypermedia\HtmxInterface + * An instance with attributes and headers from both objects. + */ + public function merge(HtmxInterface $htmx): HtmxInterface; + + /** + * Sets the HTMX request operation for the element. + * + * @param \Drupal\Core\Render\Hypermedia\Operations\HtmxRequestOperationInterface $operation + * The operation. + * + * @return \Drupal\Core\Render\Hypermedia\HtmxInterface + * Returns self to enable chained methods. + */ + public function setRequestOperation(HtmxRequestOperationInterface $operation): HtmxInterface; + + /** + * Set an additional operation that don't use a request. + * + * These should be accumulated in a stack that is processed in + * ::processOperations. + * + * @param \Drupal\Core\Render\Hypermedia\Operations\HtmxOperationInterface $operation + * The operation. + * + * @return \Drupal\Core\Render\Hypermedia\HtmxInterface + * Returns self to enable chained methods. + */ + public function setAdditionalOperation(HtmxOperationInterface $operation): HtmxInterface; + + /** + * Checks for request or additional operations. + * + * @return bool + * True if any operations are set. + */ + public function hasOperations(): bool; + + /** + * Step through all the operations, calling their ::setProperties method. + */ + public function processOperations(): void; + +} diff --git a/core/lib/Drupal/Core/Render/Hypermedia/HtmxResponseAttachmentsProcessor.php b/core/lib/Drupal/Core/Render/Hypermedia/HtmxResponseAttachmentsProcessor.php new file mode 100644 index 0000000000000000000000000000000000000000..5c8881e7412f7fed01b2dfbcb67eff8aa7b03d9c --- /dev/null +++ b/core/lib/Drupal/Core/Render/Hypermedia/HtmxResponseAttachmentsProcessor.php @@ -0,0 +1,109 @@ +<?php + +namespace Drupal\Core\Render\Hypermedia; + +use Drupal\Component\Serialization\Json; +use Drupal\Component\Utility\UrlHelper; +use Drupal\Core\Asset\AttachedAssetsInterface; +use Drupal\Core\Render\AttachmentsInterface; +use Drupal\Core\Render\HtmlResponse; +use Drupal\Core\Render\HtmlResponseAttachmentsProcessor; + +/** + * Prepares attachment for HTMX powered responses. + * + * Extends the HTML response processor encode attachment data. + * + * @see \Drupal\Core\EventSubscriber\HtmxResponseSubscriber + * @see \Drupal\Core\Render\HtmlResponseAttachmentsProcessor::processAttachments + * @see core/misc/htmx-behaviors.js + */ +class HtmxResponseAttachmentsProcessor extends HtmlResponseAttachmentsProcessor { + + /** + * Json encoded string of event name and assets to be attached. + */ + protected string $preparedAssetInfo; + + /** + * {@inheritdoc} + */ + public function processAttachments(AttachmentsInterface $response): HtmlResponse { + $processed = parent::processAttachments($response); + if (!($processed instanceof HtmlResponse)) { + // Something has gone wrong. We sent an HtmlResponse that also + // implemented AttachmentInterface and should have received the same back. + throw new \TypeError("HtmlResponseAttachmentsProcessor::processAttachments should return an HtmlResponse."); + } + $processed->headers->set('HX-Trigger-After-Swap', $this->preparedAssetInfo); + return $processed; + } + + /** + * {@inheritdoc} + */ + protected function processAssetLibraries(AttachedAssetsInterface $assets, array $placeholders) { + $request = $this->requestStack->getCurrentRequest(); + if ($request->headers->has('HX-Page-State')) { + $uncompressed = UrlHelper::uncompressQueryParameter($request->headers->get('HX-Page-State')); + $libraries = explode(',', $uncompressed); + $assets->setAlreadyLoadedLibraries($libraries); + } + $settings = []; + $variables = []; + $maintenance_mode = defined('MAINTENANCE_MODE') || \Drupal::state()->get('system.maintenance_mode'); + + // Print styles - if present. + if (isset($placeholders['styles'])) { + // Optimize CSS if necessary, but only during normal site operation. + $optimize_css = !$maintenance_mode && $this->config->get('css.preprocess'); + $variables['styles'] = $this->cssCollectionRenderer->render($this->assetResolver->getCssAssets($assets, $optimize_css, $this->languageManager->getCurrentLanguage())); + } + + // Copy and adjust parent::processAssetLibraries to adjust and + // remove drupalSettings in line with + // AjaxResponseAttachmentsProcessor::buildAttachmentsCommands + // Print scripts - if any are present. + if (isset($placeholders['scripts']) || isset($placeholders['scripts_bottom'])) { + // Optimize JS if necessary, but only during normal site operation. + $optimize_js = !$maintenance_mode && $this->config->get('js.preprocess'); + [$js_assets_header, $js_assets_footer] = $this->assetResolver + ->getJsAssets($assets, $optimize_js, $this->languageManager->getCurrentLanguage()); + $settingsHeader = $js_assets_header['drupalSettings'] ?? NULL; + $settingsFooter = $js_assets_footer['drupalSettings'] ?? NULL; + if (is_array($settingsHeader)) { + $settings = $js_assets_header['drupalSettings']['data']; + unset($js_assets_header['drupalSettings']); + } + if (is_array($settingsFooter)) { + $settings = $js_assets_footer['drupalSettings']['data']; + unset($js_assets_footer['drupalSettings']); + } + if (empty($settings)) { + $settings = $assets->getSettings(); + } + $variables['scripts'] = $this->jsCollectionRenderer->render($js_assets_header); + $variables['scripts_bottom'] = $this->jsCollectionRenderer->render($js_assets_footer); + unset($settings['path']); + $variables['settings'] = $settings; + } + // Store the prepared asset data so that it can be added to the response. + $data = [ + 'htmxDrupalAssetsAttached' => [ + 'assets' => $variables, + ], + ]; + $this->preparedAssetInfo = Json::encode($data); + // Restore assets for a standard page so that HTML state is preserved. + if (isset($settingsHeader) && is_array($settingsHeader)) { + $js_assets_header['drupalSettings'] = $settingsHeader; + $variables['scripts'] = $this->jsCollectionRenderer->render($js_assets_header); + } + if (isset($settingsFooter) && is_array($settingsFooter)) { + $js_assets_footer['drupalSettings'] = $settingsFooter; + $variables['scripts_bottom'] = $this->jsCollectionRenderer->render($js_assets_footer); + } + return $variables; + } + +} diff --git a/core/lib/Drupal/Core/Render/Hypermedia/Operations/HtmxOperationInterface.php b/core/lib/Drupal/Core/Render/Hypermedia/Operations/HtmxOperationInterface.php new file mode 100644 index 0000000000000000000000000000000000000000..f2ebf5842fd126ad3655665005befc656524b76f --- /dev/null +++ b/core/lib/Drupal/Core/Render/Hypermedia/Operations/HtmxOperationInterface.php @@ -0,0 +1,20 @@ +<?php + +namespace Drupal\Core\Render\Hypermedia\Operations; + +use Drupal\Core\Render\Hypermedia\HtmxInterface; + +/** + * An HtmxOperation adds attributes or headers to an HTMX object. + */ +interface HtmxOperationInterface { + + /** + * Add the necessary values to the Htmx object to implement the operation. + * + * @param \Drupal\Core\Render\Hypermedia\HtmxInterface $htmx + * The Htmx object collecting the attributes and headers. + */ + public function setProperties(HtmxInterface $htmx): void; + +} diff --git a/core/lib/Drupal/Core/Render/Hypermedia/Operations/HtmxRequestOperationInterface.php b/core/lib/Drupal/Core/Render/Hypermedia/Operations/HtmxRequestOperationInterface.php new file mode 100644 index 0000000000000000000000000000000000000000..e1a933724b5d8ad23a6047d70b248376feb36322 --- /dev/null +++ b/core/lib/Drupal/Core/Render/Hypermedia/Operations/HtmxRequestOperationInterface.php @@ -0,0 +1,29 @@ +<?php + +namespace Drupal\Core\Render\Hypermedia\Operations; + +use Drupal\Core\Http\HttpMethod; +use Drupal\Core\Url; + +/** + * This interface segments HTMX operations that perform and process a request. + * + * There can only be one HTMX request attribute and accompanying processing + * attributes on an HTML element. + */ +interface HtmxRequestOperationInterface extends HtmxOperationInterface { + + /** + * Configures the method and url for the request. + * + * @param \Drupal\Core\Http\HttpMethod $method + * The request method. + * @param \Drupal\Core\Url $url + * The request URL. + * + * @return static + * The instance using the trait. + */ + public function setRequest(HttpMethod $method, Url $url): static; + +} diff --git a/core/lib/Drupal/Core/Render/Hypermedia/Operations/HtmxRequestTrait.php b/core/lib/Drupal/Core/Render/Hypermedia/Operations/HtmxRequestTrait.php new file mode 100644 index 0000000000000000000000000000000000000000..55c20710ea0766c01e2a2c81562cb7c1a4b64482 --- /dev/null +++ b/core/lib/Drupal/Core/Render/Hypermedia/Operations/HtmxRequestTrait.php @@ -0,0 +1,60 @@ +<?php + +namespace Drupal\Core\Render\Hypermedia\Operations; + +use Drupal\Core\Http\HttpMethod; +use Drupal\Core\Render\Hypermedia\HtmxInterface; +use Drupal\Core\Url; + +/** + * Provides reusable methods for HtmxRequestOperationInterface objects. + */ +trait HtmxRequestTrait { + + /** + * The method to use for the request. + */ + protected HttpMethod $method; + + /** + * The url to use for the request. + */ + protected Url $url; + + /** + * {@inheritdoc} + */ + public function setRequest(HttpMethod $method, Url $url): static { + $this->method = $method; + $this->url = $url; + return $this; + } + + /** + * Map the stored parameters to HTMX attributes. + */ + public function configureRequest(HtmxInterface $htmx): void { + switch ($this->method) { + case HttpMethod::Get: + $htmx->attributes()->get($this->url); + break; + + case HttpMethod::Put: + $htmx->attributes()->put($this->url); + break; + + case HttpMethod::Patch: + $htmx->attributes()->patch($this->url); + break; + + case HttpMethod::Post: + $htmx->attributes()->post($this->url); + break; + + case HttpMethod::Delete: + $htmx->attributes()->delete($this->url); + break; + } + } + +} diff --git a/core/lib/Drupal/Core/Render/Hypermedia/Operations/HtmxSelectTrait.php b/core/lib/Drupal/Core/Render/Hypermedia/Operations/HtmxSelectTrait.php new file mode 100644 index 0000000000000000000000000000000000000000..1ce1e2f88d3fbbeb6487477ae3dc35c0d77adeac --- /dev/null +++ b/core/lib/Drupal/Core/Render/Hypermedia/Operations/HtmxSelectTrait.php @@ -0,0 +1,35 @@ +<?php + +namespace Drupal\Core\Render\Hypermedia\Operations; + +/** + * Provides reusable parameters and methods to support the use of hx-select. + * + * @see https://htmx.org/attributes/hx-select + */ +trait HtmxSelectTrait { + + + /** + * Specifies the markup to select from the returned request. + * + * A CSS query selector of the element or elements to select from the + * response. + */ + protected string $select; + + /** + * Setter method for $select. + * + * @param string $value + * The value to set. + * + * @return static + * The instance using the trait. + */ + public function select(string $value): static { + $this->select = $value; + return $this; + } + +} diff --git a/core/lib/Drupal/Core/Render/Hypermedia/Operations/HtmxTargetTrait.php b/core/lib/Drupal/Core/Render/Hypermedia/Operations/HtmxTargetTrait.php new file mode 100644 index 0000000000000000000000000000000000000000..d7997aa346430f76d6d9fe6a732599b00372bb1e --- /dev/null +++ b/core/lib/Drupal/Core/Render/Hypermedia/Operations/HtmxTargetTrait.php @@ -0,0 +1,54 @@ +<?php + +namespace Drupal\Core\Render\Hypermedia\Operations; + +/** + * Provides reusable parameters and methods to support the use of hx-target. + * + * @see https://htmx.org/attributes/hx-target + */ +trait HtmxTargetTrait { + + /** + * Specifies the element to target for replacement. + * + * The value is one of the following: + * - A CSS query selector of the element to target. + * - 'this' + * Indicates that element receiving the htmx attributes is the target. + * - 'closest <CSS selector>' + * Finds the closest ancestor element or itself, that matches the given + * CSS selector (e.g. 'closest tr' will target the closest table row to + * the element). + * - 'find <CSS selector>' + * Finds the first child descendant element that matches the given CSS + * selector. + * - 'next' + * Resolves to element.nextElementSibling + * - 'next <CSS selector>' + * Scans the DOM forward for the first element that matches the given CSS + * selector. (e.g. 'next .error' will target the closest following sibling + * element with the error class) + * - 'previous' which resolves to element.previousElementSibling + * - 'previous <CSS selector>' + * Scan the DOM backwards for the first element that matches the given CSS + * selector. (e.g. `previous .error` will target the closest previous + * sibling with the error class) + */ + protected string $target; + + /** + * Setter method for $target. + * + * @param string $value + * The value to set. + * + * @return static + * The instance using the trait. + */ + public function target(string $value): static { + $this->target = $value; + return $this; + } + +} diff --git a/core/lib/Drupal/Core/Render/Hypermedia/Operations/Insert.php b/core/lib/Drupal/Core/Render/Hypermedia/Operations/Insert.php new file mode 100644 index 0000000000000000000000000000000000000000..11602ba36ed2993d3b12ff02fc486409cf9ca116 --- /dev/null +++ b/core/lib/Drupal/Core/Render/Hypermedia/Operations/Insert.php @@ -0,0 +1,25 @@ +<?php + +namespace Drupal\Core\Render\Hypermedia\Operations; + +use Drupal\Core\Render\Hypermedia\HtmxInterface; + +/** + * Inserts the selected element as the last child of the target element. + */ +class Insert implements HtmxRequestOperationInterface { + use HtmxRequestTrait; + use HtmxSelectTrait; + use HtmxTargetTrait; + + /** + * {@inheritdoc} + */ + public function setProperties(HtmxInterface $htmx): void { + $this->configureRequest($htmx); + $htmx->attributes()->select($this->select); + $htmx->attributes()->target($this->target); + $htmx->attributes()->swap('beforeend'); + } + +} diff --git a/core/lib/Drupal/Core/Render/Hypermedia/Operations/Replace.php b/core/lib/Drupal/Core/Render/Hypermedia/Operations/Replace.php new file mode 100644 index 0000000000000000000000000000000000000000..b8f46ed93ad62a23f7baf903ec833691202c1ed1 --- /dev/null +++ b/core/lib/Drupal/Core/Render/Hypermedia/Operations/Replace.php @@ -0,0 +1,25 @@ +<?php + +namespace Drupal\Core\Render\Hypermedia\Operations; + +use Drupal\Core\Render\Hypermedia\HtmxInterface; + +/** + * Replaces the target element with the element. + */ +class Replace implements HtmxRequestOperationInterface { + use HtmxRequestTrait; + use HtmxSelectTrait; + use HtmxTargetTrait; + + /** + * {@inheritdoc} + */ + public function setProperties(HtmxInterface $htmx): void { + $this->configureRequest($htmx); + $htmx->attributes()->select($this->select); + $htmx->attributes()->target($this->target); + $htmx->attributes()->swap('outerHTML'); + } + +} diff --git a/core/lib/Drupal/Core/Template/Attribute.php b/core/lib/Drupal/Core/Template/Attribute.php index 77a56689219df28092b462afd8e950b68188df4f..104464dba835d5433daa2643bd6542458f66cc27 100644 --- a/core/lib/Drupal/Core/Template/Attribute.php +++ b/core/lib/Drupal/Core/Template/Attribute.php @@ -4,8 +4,6 @@ use Drupal\Component\Render\PlainTextOutput; use Drupal\Component\Render\MarkupInterface; -use Drupal\Component\Utility\NestedArray; -use Drupal\Core\Serialization\Attribute\JsonSchema; /** * Collects, sanitizes, and renders HTML attributes. @@ -67,14 +65,16 @@ * @see \Drupal\Component\Render\PlainTextOutput::renderFromHtml() * @see \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols() */ -class Attribute implements \ArrayAccess, \IteratorAggregate, MarkupInterface { +class Attribute implements HtmlAttributeInterface, \ArrayAccess { + + use HtmlAttributeTrait; /** * Stores the attribute data. * * @var \Drupal\Core\Template\AttributeValueBase[] */ - protected $storage = []; + protected array $storage = []; /** * Constructs a \Drupal\Core\Template\Attribute object. @@ -91,7 +91,7 @@ public function __construct($attributes = []) { /** * {@inheritdoc} */ - public function offsetGet($name): mixed { + public function offsetGet($name): ?AttributeValueBase { if (isset($this->storage[$name])) { return $this->storage[$name]; } @@ -123,7 +123,7 @@ public function offsetSet($name, $value): void { * @return \Drupal\Core\Template\AttributeValueBase * An AttributeValueBase representation of the attribute's value. */ - protected function createAttributeValue($name, $value) { + protected function createAttributeValue($name, $value): AttributeValueBase { // If the value is already an AttributeValueBase object, // return a new instance of the same class, but with the new name. if ($value instanceof AttributeValueBase) { @@ -180,7 +180,7 @@ public function offsetExists($name): bool { * * @return $this */ - public function addClass(...$args) { + public function addClass(...$args): self { if ($args) { $classes = []; foreach ($args as $arg) { @@ -215,7 +215,7 @@ public function addClass(...$args) { * * @return $this */ - public function setAttribute($attribute, $value) { + public function setAttribute($attribute, $value): self { $this->offsetSet($attribute, $value); return $this; @@ -230,7 +230,7 @@ public function setAttribute($attribute, $value) { * @return bool * Returns TRUE if the attribute exists, or FALSE otherwise. */ - public function hasAttribute($name) { + public function hasAttribute($name): bool { return array_key_exists($name, $this->storage); } @@ -242,7 +242,7 @@ public function hasAttribute($name) { * * @return $this */ - public function removeAttribute(...$args) { + public function removeAttribute(...$args): self { foreach ($args as $arg) { // Support arrays or multiple arguments. if (is_array($arg)) { @@ -266,7 +266,7 @@ public function removeAttribute(...$args) { * * @return $this */ - public function removeClass(...$args) { + public function removeClass(...$args): self { // With no class attribute, there is no need to remove. if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) { $classes = []; @@ -291,12 +291,12 @@ public function removeClass(...$args) { * * This method is implemented to take precedence over hasClass() for Twig 2.0. * - * @return \Drupal\Core\Template\AttributeValueBase + * @return \Drupal\Core\Template\AttributeArray * The class attribute value if set. * * @see twig_get_attribute() */ - public function getClass() { + public function getClass(): AttributeArray { return $this->offsetGet('class'); } @@ -309,7 +309,7 @@ public function getClass() { * @return bool * Returns TRUE if the class exists, or FALSE otherwise. */ - public function hasClass($class) { + public function hasClass($class): bool { if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) { return in_array($class, $this->storage['class']->value()); } @@ -318,37 +318,6 @@ public function hasClass($class) { } } - /** - * Implements the magic __toString() method. - */ - #[JsonSchema(['type' => 'string', 'description' => 'Rendered HTML element attributes'])] - public function __toString() { - $return = ''; - /** @var \Drupal\Core\Template\AttributeValueBase $value */ - foreach ($this->storage as $value) { - $rendered = $value->render(); - if ($rendered) { - $return .= ' ' . $rendered; - } - } - return $return; - } - - /** - * Returns all storage elements as an array. - * - * @return array - * An associative array of attributes. - */ - public function toArray() { - $return = []; - foreach ($this->storage as $name => $value) { - $return[$name] = $value->value(); - } - - return $return; - } - /** * Implements the magic __clone() method. */ @@ -366,36 +335,17 @@ public function getIterator(): \ArrayIterator { } /** - * Returns the whole array. - */ - public function storage() { - return $this->storage; - } - - /** - * Returns a representation of the object for use in JSON serialization. - * - * @return string - * The safe string content. + * {@inheritdoc} */ - public function jsonSerialize(): string { - return (string) $this; + public function count(): int { + return count($this->storage); } /** - * Merges an Attribute object into the current storage. - * - * @param \Drupal\Core\Template\Attribute $collection - * The Attribute object to merge. - * - * @return $this + * Returns the whole array. */ - public function merge(Attribute $collection) { - $merged_attributes = NestedArray::mergeDeep($this->toArray(), $collection->toArray()); - foreach ($merged_attributes as $name => $value) { - $this->storage[$name] = $this->createAttributeValue($name, $value); - } - return $this; + public function storage(): array { + return $this->storage; } } diff --git a/core/lib/Drupal/Core/Template/AttributeHelper.php b/core/lib/Drupal/Core/Template/AttributeHelper.php index c4b0fbfa1e5448a7277aa465dc39ff5843dc1d3d..264148f68603a408e6059400fc098767bba5d51f 100644 --- a/core/lib/Drupal/Core/Template/AttributeHelper.php +++ b/core/lib/Drupal/Core/Template/AttributeHelper.php @@ -22,7 +22,7 @@ private function __construct() { * * @param string $name * The name of the attribute to check for. - * @param \Drupal\Core\Template\Attribute|array $collection + * @param HtmlAttributeInterface|array $collection * An Attribute object or an array of attributes. * * @return bool @@ -32,7 +32,7 @@ private function __construct() { * When the input $collection is neither an Attribute object nor an array. */ public static function attributeExists($name, $collection) { - if ($collection instanceof Attribute) { + if ($collection instanceof HtmlAttributeInterface) { return $collection->hasAttribute($name); } elseif (is_array($collection)) { @@ -44,32 +44,33 @@ public static function attributeExists($name, $collection) { /** * Merges two attribute collections. * - * @param \Drupal\Core\Template\Attribute|array $a + * @param HtmlAttributeInterface|array $a * First Attribute object or array to merge. The returned value type will * be the same as the type of this argument. - * @param \Drupal\Core\Template\Attribute|array $b + * @param HtmlAttributeInterface|array $b * Second Attribute object or array to merge. * * @return \Drupal\Core\Template\Attribute|array - * The merged attributes, as an Attribute object or an array. + * The merged attributes in the form of the first argument. * * @throws \InvalidArgumentException * If at least one collection argument is neither an Attribute object nor an * array. */ public static function mergeCollections($a, $b) { - if (!($a instanceof Attribute || is_array($a)) || !($b instanceof Attribute || is_array($b))) { + if (!($a instanceof HtmlAttributeInterface || is_array($a)) || !($b instanceof HtmlAttributeInterface || is_array($b))) { throw new \InvalidArgumentException('Invalid collection argument'); } // If both collections are arrays, just merge them. if (is_array($a) && is_array($b)) { return NestedArray::mergeDeep($a, $b); } - // If at least one collections is an Attribute object, merge through - // Attribute::merge. + // Merge through Attribute::merge. $merge_a = $a instanceof Attribute ? $a : new Attribute($a); $merge_b = $b instanceof Attribute ? $b : new Attribute($b); $merge_a->merge($merge_b); + // If we started with an Attribute, return an Attribute. + // If we started with an array, return an array. return $a instanceof Attribute ? $merge_a : $merge_a->toArray(); } diff --git a/core/lib/Drupal/Core/Template/AttributeJson.php b/core/lib/Drupal/Core/Template/AttributeJson.php new file mode 100644 index 0000000000000000000000000000000000000000..3b0204b371db27b8b0620795d78432279c91e0e4 --- /dev/null +++ b/core/lib/Drupal/Core/Template/AttributeJson.php @@ -0,0 +1,32 @@ +<?php + +namespace Drupal\Core\Template; + +use Drupal\Component\Utility\Xss; + +/** + * Represents an attribute containing JSON formatted data. + */ +class AttributeJson extends AttributeValueBase { + + const RENDER_EMPTY_ATTRIBUTE = FALSE; + + /** + * Encode the array as JSON. + * + * @return string + * The JSON encoded array or empty string on failure. + */ + public function __toString() { + $value = $this->value(); + $value = is_array($value) ? $value : [$value]; + // Escape the values. + $data = []; + foreach ($value as $key => $item) { + $data[Xss::filter($key)] = is_string($item) ? Xss::filter($item) : $item; + } + $string = json_encode($data, JSON_FORCE_OBJECT | JSON_NUMERIC_CHECK); + return $string ?: ''; + } + +} diff --git a/core/lib/Drupal/Core/Template/AttributeString.php b/core/lib/Drupal/Core/Template/AttributeString.php index bce832e374a01bf44b2b98445117284693b22a4f..27f6cfc0d7c1edf0fdb57354f9b8f2c4a6e30576 100644 --- a/core/lib/Drupal/Core/Template/AttributeString.php +++ b/core/lib/Drupal/Core/Template/AttributeString.php @@ -2,7 +2,7 @@ namespace Drupal\Core\Template; -use Drupal\Component\Utility\Html; +use Drupal\Component\Utility\Xss; /** * A class that represents most standard HTML attributes. @@ -25,7 +25,7 @@ class AttributeString extends AttributeValueBase { * Implements the magic __toString() method. */ public function __toString() { - return Html::escape((string) $this->value); + return Xss::filter((string) $this->value); } } diff --git a/core/lib/Drupal/Core/Template/AttributeValueBase.php b/core/lib/Drupal/Core/Template/AttributeValueBase.php index 35ef176b14563962dd07799ace6fc2943da58ed8..f33455092f97cd7f7f0fb231b30097599d8f6edf 100644 --- a/core/lib/Drupal/Core/Template/AttributeValueBase.php +++ b/core/lib/Drupal/Core/Template/AttributeValueBase.php @@ -7,6 +7,7 @@ /** * Defines the base class for an attribute type. * + * @see https://html.spec.whatwg.org/#attributes-2 * @see \Drupal\Core\Template\Attribute */ abstract class AttributeValueBase { @@ -46,15 +47,19 @@ public function __construct($name, $value) { * While __toString only returns the value in a string form, render() * contains the name of the attribute as well. * - * @return string|null + * @return string * The string representation of the attribute. */ public function render() { $value = (string) $this; + $singleQuote = str_contains($value, '"'); if (isset($this->value) && static::RENDER_EMPTY_ATTRIBUTE || !empty($value)) { - return Html::escape($this->name) . '="' . $value . '"'; + // Flips the attribute quotes between single and double-quoted syntax. + $rendered = Html::escape($this->name); + $rendered .= $singleQuote ? "='" . $value . "'" : '="' . $value . '"'; + return $rendered; } - return NULL; + return ''; } /** diff --git a/core/lib/Drupal/Core/Template/ComponentsTwigExtension.php b/core/lib/Drupal/Core/Template/ComponentsTwigExtension.php index 5ff5c7e94b6bac87ddb3ae5746a6eb0ada171baa..88269ada867052cd36c5eefc9d17aaaacb5b4655 100644 --- a/core/lib/Drupal/Core/Template/ComponentsTwigExtension.php +++ b/core/lib/Drupal/Core/Template/ComponentsTwigExtension.php @@ -83,7 +83,7 @@ protected function mergeAdditionalRenderContext(Component $component, array $con } // If there is an "attributes" property, merge the additional attributes // into it if possible. - elseif ($context['attributes'] instanceof Attribute) { + elseif ($context['attributes'] instanceof HtmlAttributeInterface) { $context['attributes']->merge(new Attribute($component_attributes)); } return $context; diff --git a/core/lib/Drupal/Core/Template/HtmlAttributeInterface.php b/core/lib/Drupal/Core/Template/HtmlAttributeInterface.php new file mode 100644 index 0000000000000000000000000000000000000000..3d0954bfca04cca9785c0926a1d8c74f2c49add4 --- /dev/null +++ b/core/lib/Drupal/Core/Template/HtmlAttributeInterface.php @@ -0,0 +1,43 @@ +<?php + +namespace Drupal\Core\Template; + +use Drupal\Component\Render\MarkupInterface; + +/** + * An interface for classes that manage HTML Attributes. + * + * @extends \IteratorAggregate<string, \Drupal\Core\Template\AttributeValueBase> + */ +interface HtmlAttributeInterface extends \Countable, \IteratorAggregate, MarkupInterface { + + /** + * Checks if the storage has an attribute with the given name. + * + * @param string $name + * The name of the attribute to check for. + * + * @return bool + * Returns TRUE if the attribute exists, or FALSE otherwise. + */ + public function hasAttribute($name): bool; + + /** + * Returns all storage elements as an array. + * + * @return mixed[] + * An associative array of attributes. + */ + public function toArray(): array; + + /** + * Merges an Attribute object into the current storage. + * + * @param HtmlAttributeInterface $collection + * The Attribute object to merge. + * + * @return $this + */ + public function merge(HtmlAttributeInterface $collection): HtmlAttributeInterface; + +} diff --git a/core/lib/Drupal/Core/Template/HtmlAttributeTrait.php b/core/lib/Drupal/Core/Template/HtmlAttributeTrait.php new file mode 100644 index 0000000000000000000000000000000000000000..2efe43c776e662fd993a26cae388c4b95ee37cc6 --- /dev/null +++ b/core/lib/Drupal/Core/Template/HtmlAttributeTrait.php @@ -0,0 +1,81 @@ +<?php + +namespace Drupal\Core\Template; + +use Drupal\Component\Utility\NestedArray; +use Drupal\Core\Serialization\Attribute\JsonSchema; + +/** + * Provides a shared implementation of several HtmlAttribute methods. + * + * Methods that depend on the storage method are omitted and should be + * implemented directly. + */ +trait HtmlAttributeTrait { + + /** + * Implements the magic __toString() method. + */ + #[JsonSchema(['type' => 'string', 'description' => 'Rendered HTML element attributes'])] + public function __toString() { + $return = ''; + /** @var \Drupal\Core\Template\AttributeValueBase $value */ + foreach ($this->storage as $value) { + $rendered = $value->render(); + if ($rendered) { + $return .= ' ' . $rendered; + } + } + return $return; + } + + /** + * {@inheritdoc} + */ + public function toArray(): array { + $return = []; + foreach ($this->storage as $name => $value) { + $return[$name] = $value->value(); + } + + return $return; + } + + /** + * Returns a representation of the object for use in JSON serialization. + * + * @return string + * The safe string content. + */ + public function jsonSerialize(): string { + return (string) $this; + } + + /** + * Merges an Attribute object into the current storage. + * + * On name matches, incoming AttributeArrays run through + * NestedArray::mergeDeep. Other Attribute types replace a matching name. + * This is an equivalent behavior to converting all values arrays and + * running NestedArray::mergeDeep on the arrays which preserves the + * types of the values. + * + * @param HtmlAttributeInterface $collection + * The Attribute object to merge. + * + * @return $this + */ + public function merge(HtmlAttributeInterface $collection): self { + foreach ($collection as $name => $value) { + if (isset($this->storage[$name]) && $value instanceof AttributeArray) { + $merged_attributes = NestedArray::mergeDeep($this->storage[$name]->value(), $value->value()); + $this->storage[$name] = new AttributeArray($name, $merged_attributes); + } + else { + $this->storage[$name] = $value; + } + } + return $this; + } + +} diff --git a/core/lib/Drupal/Core/Template/HtmxAttribute.php b/core/lib/Drupal/Core/Template/HtmxAttribute.php new file mode 100644 index 0000000000000000000000000000000000000000..3d79403e57e159e4cf43ec70bfede6907383a8ab --- /dev/null +++ b/core/lib/Drupal/Core/Template/HtmxAttribute.php @@ -0,0 +1,769 @@ +<?php + +namespace Drupal\Core\Template; + +use Drupal\Core\Url; +use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter; + +/** + * Collects, sanitizes, and renders attributes for HTMX integration. + * + * This object is composed into \Drupal\Core\Ajax\Htmx. The most common usage + * will be to access it as a property there. + * + * There are times when this class is needed directly because a portion of + * HTML is being managed directly, such as a prefix + * element. + * + * @code + * $attributes = new Attribute(['id' => 'edit-export-wrapper']); + * $export_htmx_attributes = new HtmxAttribute(); + * $export_htmx_attributes->swapOob('outerHTML:#edit-export-wrapper'); + * $attributes = $attributes->merge($export_htmx_attributes); + * $form['export']['#prefix'] = '<div ' . $attributes . '>'; + * @endcode + * + * @see \Drupal\Core\Render\Hypermedia\Htmx + * @see https://htmx.org/reference/ + */ +class HtmxAttribute implements HtmlAttributeInterface { + + use HtmlAttributeTrait; + + /** + * Stores the attribute data. + * + * @var \Drupal\Core\Template\AttributeValueBase[] + */ + protected array $storage = []; + + /* ***** Internal utility methods ***** */ + + /** + * Utility method to transform camelCase strings to kebab-case strings. + * + * Passes kebab-case strings through without any transformation. + * + * @param string $identifier + * The string to verify or transform. + * + * @return string + * The original or transformed string. + */ + protected function insureKebabCase(string $identifier): string { + // Check for existing kebab case. + $kebabParts = explode('-', $identifier); + // If the number of lower case parts matches the number of parts, then + // all the parts are lower case. + $isKebab = count($kebabParts) === count(array_filter($kebabParts, function ($part) { + return preg_match('#^[[:lower:]]+$#', $part) === 1; + })); + if ($isKebab) { + return $identifier; + } + + $converter = new CamelCaseToSnakeCaseNameConverter(); + $snakeCase = $converter->normalize($identifier); + return preg_replace('#[_:]#', '-', $snakeCase); + } + + /** + * Utility method to create and store a string value as an attribute. + * + * @param string $id + * The HTMX attribute id. + * @param string $value + * The attribute value. + */ + protected function createStringAttribute(string $id, string $value): void { + $key = 'data-hx-' . $id; + $attribute = new AttributeString($key, $value); + $this->storage[$key] = $attribute; + } + + /** + * Utility method to create and store a boolean value as an attribute. + * + * @param string $id + * The HTMX attribute id. + * @param bool $value + * The attribute value. + */ + protected function createBooleanAttribute(string $id, bool $value): void { + $key = 'data-hx-' . $id; + $attribute = new AttributeBoolean($key, $value); + $this->storage[$key] = $attribute; + + } + + /** + * Utility method to create and store an array as an attribute. + * + * @param string $id + * The HTMX attribute id. + * @param array{string, string} $value + * The attribute values. + */ + protected function createJsonAttribute(string $id, array $value): void { + $key = 'data-hx-' . $id; + $attribute = new AttributeJson($key, $value); + $this->storage[$key] = $attribute; + } + + /* ***** HtmxAttribute methods ***** */ + + /** + * {@inheritdoc} + */ + public function hasAttribute($name): bool { + return array_key_exists($name, $this->storage); + } + + /** + * {@inheritdoc} + */ + public function getIterator(): \ArrayIterator { + return new \ArrayIterator($this->storage); + } + + /** + * {@inheritdoc} + */ + public function count(): int { + return count($this->storage); + } + + /* ***** Request attributes ***** */ + + /** + * Issues a GET request to the specified URL. + * + * @param \Drupal\Core\Url $url + * The URL for the GET request. + * + * @return HtmxAttribute + * returns self so that attribute methods may be chained. + * + * @see https://htmx.org/attributes/hx-get/ + */ + public function get(Url $url): HtmxAttribute { + $this->createStringAttribute('get', $url->toString()); + return $this; + } + + /** + * Issues a POST request to the specified URL. + * + * @param \Drupal\Core\Url $url + * The URL for the POST request. + * + * @return HtmxAttribute + * returns self so that attribute methods may be chained. + * + * @see https://htmx.org/attributes/hx-post/ + */ + public function post(Url $url): HtmxAttribute { + $this->createStringAttribute('post', $url->toString()); + return $this; + } + + /** + * Issues a PUT request to the specified URL. + * + * @param \Drupal\Core\Url $url + * The URL for the PUT request. + * + * @return HtmxAttribute + * returns self so that attribute methods may be chained. + * + * @see https://htmx.org/attributes/hx-put/ + */ + public function put(Url $url): HtmxAttribute { + $this->createStringAttribute('put', $url->toString()); + return $this; + } + + /** + * Issues a PATCH request to the specified URL. + * + * @param \Drupal\Core\Url $url + * The URL for the PATCH request. + * + * @return HtmxAttribute + * returns self so that attribute methods may be chained. + * + * @see https://htmx.org/attributes/hx-patch/ + */ + public function patch(Url $url): HtmxAttribute { + $this->createStringAttribute('patch', $url->toString()); + return $this; + } + + /** + * Issues a DELETE request to the specified URL. + * + * @param \Drupal\Core\Url $url + * The URL for the DELETE request. + * + * @return HtmxAttribute + * returns self so that attribute methods may be chained. + * + * @see https://htmx.org/attributes/hx-delete/ + */ + public function delete(Url $url): HtmxAttribute { + $this->createStringAttribute('delete', $url->toString()); + return $this; + } + + /* ***** Remaining HTMX 'core' attributes ***** */ + + /** + * Handle events with inline scripts on elements. + * + * @param string $event + * An event in either camelCase or kebab-case. + * @param string $action + * The action to take when the event occurs. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-on/ + */ + public function on(string $event, string $action): HtmxAttribute { + // Special case: the `::EventName` shorthand for `htmx:EventName`. + // Remove one leading `:` so that our final attribute is + // `data-hx--event-name` rather than `data-hx---event-name`. + $event = preg_replace('#^::#', ':', $event); + $formattedEvent = 'on-' . $this->insureKebabCase($event); + $this->createStringAttribute($formattedEvent, $action); + return $this; + } + + /** + * Control URLs in browser history. + * + * Use a boolean when this attribute is added along with ::get + * - true: pushes the fetched URL into history. + * - false: disables pushing the fetched URL if it would otherwise be pushed + * due to inheritance or hx-boost. + * + * Use a URL to cause a push into the location bar. This may be relative or + * absolute, as per history.pushState() + * + * @param bool|\Drupal\Core\Url $value + * Use a Url object or a boolean, depending on use case. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-push-url/ + */ + public function pushUrl(bool|Url $value): HtmxAttribute { + if ($value instanceof Url) { + $this->createStringAttribute('push-url', $value->toString()); + } + else { + $this->createStringAttribute('push-url', $value ? 'true' : 'false'); + } + return $this; + } + + /** + * Select content to swap in from a response. + * + * Uses the selector to select elements from the response. + * + * @param string $selector + * A CSS query selector. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-select/ + */ + public function select(string $selector): HtmxAttribute { + $this->createStringAttribute('select', $selector); + return $this; + } + + /** + * Select content for an out-of-band swap from a response. + * + * Each value in the comma separated list of values can specify any valid + * hx-swap strategy by separating the selector and the swap strategy with a + * colon, such as #alert:afterbegin. + * + * @param string $selectors + * A comma separated list of elements to be swapped out of band. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-select-oob/ + */ + public function selectOob(string $selectors): HtmxAttribute { + $this->createStringAttribute('select-oob', $selectors); + return $this; + } + + /** + * Controls how content will swap in. + * + * The hx-swap attribute allows you to specify how the response will be + * swapped in relative to the target of an AJAX request. + * + * @param string $strategy + * A comma separated list of elements to be swapped out of band. + * @param bool $ignoreTitle + * Instruct HTMX not to swap in the page title from the request. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-swap/ + */ + public function swap(string $strategy, bool $ignoreTitle = TRUE): HtmxAttribute { + // HTMX defaults this behavior to FALSE, that is it replaces page title. + // We believe our most common use case is to not change the title. + if ($ignoreTitle) { + $strategy .= ' ignoreTitle:true'; + } + $this->createStringAttribute('swap', $strategy); + return $this; + } + + /** + * Designate content in a response for an out-of-band swap. + * + * The hx-swap-oob attribute allows you to specify that some content in a + * response should be swapped into the DOM somewhere other than the target, + * that is “Out of Band”. This allows you to piggyback updates to other + * element updates on a response. + * + * @param string $value + * A comma separated list of elements to be swapped out of band. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-swap-oob/ + */ + public function swapOob(true|string $value): HtmxAttribute { + if ($value === TRUE) { + $this->createStringAttribute('swap-oob', 'true'); + } + else { + $this->createStringAttribute('swap-oob', $value); + } + return $this; + } + + /** + * Specifies the target element to receive the incoming markup. + * + * The hx-target attribute allows you to target a different element for + * swapping than the one issuing the AJAX request. There are a variety + * of target string syntaxes. See the URL below for details. + * + * @param string $target + * The target descriptor. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-target/ + */ + public function target(string $target): HtmxAttribute { + $this->createStringAttribute('target', $target); + return $this; + } + + /** + * Specifies what triggers a request. + * + * Used with an HTMX request attribute. Allows: + * - An event name (e.g. “click” or “my-custom-event”) followed by an event + * filter and a set of event modifiers + * - A polling definition of the form every <timing declaration> + * - A comma-separated list of such events. + * + * @param string $triggerDefinition + * The trigger definition. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-trigger/ + */ + public function trigger(string $triggerDefinition): HtmxAttribute { + $this->createStringAttribute('trigger', $triggerDefinition); + return $this; + } + + /** + * Add to the parameters that will be submitted with an HTMX request. + * + * The value of this attribute is a list of name-expression values + * which will be converted to JSON (JavaScript Object Notation) format. + * + * @param array<string, string> $values + * The values in an array of 'name' => 'value' pairs. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-trigger/ + */ + public function vals(array $values): HtmxAttribute { + $this->createJsonAttribute('vals', $values); + return $this; + } + + /* ***** Remaining HTMX 'core' attributes ***** */ + + /** + * Add progressive enhancement for links and forms. + * + * The hx-boost attribute allows you to “boost” normal anchors and form tags + * to use AJAX instead. This has the nice fallback that, if the user does not + * have javascript enabled, the site will continue to work. + * + * @param bool $value + * Should the element and its descendants be "boosted"? + * + * @return $this + * + * @see https://htmx.org/attributes/hx-boost/ + */ + public function boost(bool $value): HtmxAttribute { + if ($value === TRUE) { + $this->createStringAttribute('boost', 'true'); + } + else { + $this->createStringAttribute('boost', 'false'); + } + return $this; + } + + /** + * Shows a confirm() dialog before issuing a request. + * + * @param string $message + * The user facing message. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-confirm/ + */ + public function confirm(string $message): HtmxAttribute { + $this->createStringAttribute('confirm', $message); + return $this; + } + + /** + * Disables HTMX processing for the given node and any descendants. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-disable/ + */ + public function disable(): HtmxAttribute { + $this->createBooleanAttribute('disable', TRUE); + return $this; + } + + /** + * Adds the disabled attribute to the specified elements during a request. + * + * The descriptor syntax is the same as hx-target. See the documentation + * link below for more details. + * + * @param string $descriptor + * The attribute value. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-disabled-elt/ + */ + public function disabledElements(string $descriptor): HtmxAttribute { + $this->createStringAttribute('disabled-elt', $descriptor); + return $this; + } + + /** + * Control and disable automatic HTMX attribute inheritance for child nodes. + * + * @param string $names + * The attribute names to disinherit or * for all. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-disinherit/ + */ + public function disinherit(string $names): HtmxAttribute { + $this->createStringAttribute('disinherit', $names); + return $this; + } + + /** + * Changes the request encoding type. + * + * @param string $method + * The encoding method. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-encoding/ + */ + public function encoding(string $method = 'multipart/form-data'): HtmxAttribute { + $this->createStringAttribute('encoding', $method); + return $this; + } + + /** + * Enables HTMX extensions for an element and descendants. + * + * @param string $names + * An extension name, or a comma separated list of names. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-ext/ + */ + public function ext(string $names): HtmxAttribute { + $this->createStringAttribute('ext', $names); + return $this; + } + + /** + * Add to the headers that will be submitted with an HTMX request. + * + * @param array<string, string> $headerValues + * The header values as name => value. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-headers/ + */ + public function headers(array $headerValues): HtmxAttribute { + $this->createJsonAttribute('headers', $headerValues); + return $this; + } + + /** + * Prevent sensitive data being saved to the history cache. + * + * Set the hx-history attribute to false on any element in the current + * document, or any html fragment loaded into the current document by htmx, + * to prevent sensitive data being saved to the localStorage cache when htmx + * takes a snapshot of the page state. + * + * @param bool $value + * Sets the string value to 'true' or 'false'. Defaults to FALSE. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-history/ + */ + public function history(bool $value = FALSE): HtmxAttribute { + if ($value) { + $this->createStringAttribute('history', 'true'); + } + else { + $this->createStringAttribute('history', 'false'); + } + return $this; + } + + /** + * The element to snapshot and restore during history navigation. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-history-elt/ + */ + public function historyElement(): HtmxAttribute { + $this->createBooleanAttribute('history-elt', TRUE); + return $this; + } + + /** + * Include additional element values in HTMX requests. + * + * The descriptor syntax is the same as hx-target. See the documentation + * link below for more details. + * + * @param string $descriptors + * The element descriptors. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-include/ + */ + public function include(string $descriptors): HtmxAttribute { + $this->createStringAttribute('include', $descriptors); + return $this; + } + + /** + * The element to put the htmx-request class on during the request. + * + * @param string $selector + * The element CSS selector value. Selector may be prefixed with `closest`. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-indicator/ + */ + public function indicator(string $selector): HtmxAttribute { + $this->createStringAttribute('indicator', $selector); + return $this; + } + + /** + * Control automatic attribute inheritance for child nodes. + * + * HTMX evaluates attribute inheritance with hx-inherit in two ways when + * hx-inherit is set on a parent node: + * - data-hx-inherit="*" + * All attribute inheritance for this element will be enabled. + * - data-hx-hx-inherit="hx-select hx-get hx-target" + * Enable inheritance for only one or multiple specified attributes. + * + * @param string $attributes + * The attributes to inherit. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-inherit/ + */ + public function inherit(string $attributes): HtmxAttribute { + $this->createStringAttribute('inherit', $attributes); + return $this; + } + + /** + * Filters the parameters that will be submitted with a request. + * + * @param string $filter + * The filter string. Multiple syntax options, see the link below. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-params/ + */ + public function params(string $filter): HtmxAttribute { + $this->createStringAttribute('params', $filter); + return $this; + } + + /** + * Specifies elements to keep unchanged between requests. + * + * @param string $id + * The id attribute of the element to preserve. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-preserve/ + */ + public function preserve(string $id): HtmxAttribute { + $this->createStringAttribute('preserve', $id); + return $this; + } + + /** + * Shows a prompt() before submitting a request. + * + * @param string $message + * The message to display in the prompt. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-prompt/ + */ + public function prompt(string $message): HtmxAttribute { + $this->createStringAttribute('prompt', $message); + return $this; + } + + /** + * Control URLs in the browser location bar. + * + * Use a boolean when this attribute is added along with a request: + * - true: replaces the fetched URL in the browser navigation bar. + * - false: disables replacing the fetched URL if it would otherwise be + * replaced due to inheritance. + * + * Use a URL to replace the value in the location bar. This may be relative or + * absolute, as per history.replaceState(). + * + * @param bool|\Drupal\Core\Url $value + * Use a Url object or a boolean, depending on use case. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-replace-url/ + */ + public function replaceUrl(bool|Url $value): HtmxAttribute { + if ($value instanceof Url) { + $this->createStringAttribute('replace-url', $value->toString()); + } + else { + $this->createStringAttribute('replace-url', $value ? 'true' : 'false'); + } + return $this; + } + + /** + * Configures various aspects of the request. + * + * The hx-request attribute supports the following configuration values: + * - timeout: (integer) the timeout for the request, in milliseconds. + * - credentials: (boolean) if the request will send credentials. + * - noHeaders: (boolean) strips all headers from the request. + * + * Dynamic javascript values are not supported for security and for + * simplicity. If you need calculated values you should do determine them + * here on the server-side + * + * @param array<string, int|bool> $configValues + * The configuration values as name => value. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-headers/ + */ + public function request(array $configValues): HtmxAttribute { + $this->createJsonAttribute('request', $configValues); + return $this; + } + + /** + * Synchronize AJAX requests between multiple elements. + * + * @param string $selector + * A CSS selector followed by a strategy. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-sync/ + */ + public function sync(string $selector): HtmxAttribute { + $this->createStringAttribute('sync', $selector); + return $this; + } + + /** + * Cause an element to validate itself before it submits a request. + * + * @param bool $value + * Should the element validate before the request. + * + * @return $this + * + * @see https://htmx.org/attributes/hx-validate/ + */ + public function validate(bool $value = TRUE): HtmxAttribute { + if ($value) { + $this->createStringAttribute('validate', 'true'); + } + else { + $this->createStringAttribute('validate', 'false'); + } + return $this; + } + +} diff --git a/core/lib/Drupal/Core/Template/TwigExtension.php b/core/lib/Drupal/Core/Template/TwigExtension.php index 5afa135d02682b552c2c7df9cb4a223ba085edcf..ea6a10db144571818649bbe637e2adcf750a056c 100644 --- a/core/lib/Drupal/Core/Template/TwigExtension.php +++ b/core/lib/Drupal/Core/Template/TwigExtension.php @@ -254,7 +254,7 @@ public function getUrl($name, $parameters = [], $options = []) { * The link text for the anchor tag as a translated string. * @param \Drupal\Core\Url|string $url * The URL object or string used for the link. - * @param array|\Drupal\Core\Template\Attribute $attributes + * @param array|HtmlAttributeInterface $attributes * An optional array or Attribute object of link attributes. * * @return array @@ -262,7 +262,7 @@ public function getUrl($name, $parameters = [], $options = []) { */ public function getLink($text, $url, $attributes = []) { assert(is_string($url) || $url instanceof Url, '$url must be a string or object of type \Drupal\Core\Url'); - assert(is_array($attributes) || $attributes instanceof Attribute, '$attributes, if set, must be an array or object of type \Drupal\Core\Template\Attribute'); + assert(is_array($attributes) || $attributes instanceof HtmlAttributeInterface, '$attributes, if set, must be an array or object implementing HtmlAttributeInterface'); if (!$url instanceof Url) { $url = Url::fromUri($url); @@ -272,7 +272,7 @@ public function getLink($text, $url, $attributes = []) { // @see https://www.drupal.org/node/2842399 $url = clone $url; if ($attributes) { - if ($attributes instanceof Attribute) { + if ($attributes instanceof HtmlAttributeInterface) { $attributes = $attributes->toArray(); } $url->mergeOptions(['attributes' => $attributes]); @@ -621,14 +621,14 @@ public function safeJoin(Environment $env, $value, $glue = '') { /** * Creates an Attribute object. * - * @param Attribute|array $attributes + * @param \Drupal\Core\Template\HtmlAttributeInterface|array $attributes * (optional) An existing attribute object or an associative array of * key-value pairs to be converted to HTML attributes. * - * @return \Drupal\Core\Template\Attribute + * @return \Drupal\Core\Template\HtmlAttributeInterface * An attributes object that has the given attributes. */ - public function createAttribute(Attribute|array $attributes = []) { + public function createAttribute(HtmlAttributeInterface|array $attributes = []) { if (\is_array($attributes)) { return new Attribute($attributes); } diff --git a/core/lib/Drupal/Core/Theme/ThemeManager.php b/core/lib/Drupal/Core/Theme/ThemeManager.php index 8962896ee3ef21d3e9bd8ce7717630e2700cb4a5..470b3fa8f79b55e49dcfa609d210aa2a9643d4bf 100644 --- a/core/lib/Drupal/Core/Theme/ThemeManager.php +++ b/core/lib/Drupal/Core/Theme/ThemeManager.php @@ -7,6 +7,7 @@ use Drupal\Core\Routing\StackedRouteMatchInterface; use Drupal\Core\Extension\ModuleHandlerInterface; use Drupal\Core\Template\Attribute; +use Drupal\Core\Template\HtmlAttributeInterface; use Drupal\Core\Template\AttributeHelper; use Drupal\Core\Utility\CallableResolver; @@ -340,7 +341,7 @@ public function render($hook, array $variables) { $default_attributes = new Attribute(); } foreach (['attributes', 'title_attributes', 'content_attributes'] as $key) { - if (isset($variables[$key]) && !($variables[$key] instanceof Attribute)) { + if (isset($variables[$key]) && !($variables[$key] instanceof HtmlAttributeInterface)) { if ($variables[$key]) { $variables[$key] = new Attribute($variables[$key]); } diff --git a/core/misc/cspell/dictionary.txt b/core/misc/cspell/dictionary.txt index 83fe358eb459b73b03a8f604ee3b36a661326d0f..c0f4912e057db3cf5fda073ddabb676bcf51f69b 100644 --- a/core/misc/cspell/dictionary.txt +++ b/core/misc/cspell/dictionary.txt @@ -222,6 +222,7 @@ hmac hookname hrefs htmlcorrector +htmx httpheader httponly icann @@ -418,6 +419,8 @@ restrictor restripe restriped restui +reswap +retarget revisionable revisioned revisionid diff --git a/core/misc/htmx-behaviors.js b/core/misc/htmx-behaviors.js new file mode 100644 index 0000000000000000000000000000000000000000..add7b9502d491fb6947590871776d68c4b54c904 --- /dev/null +++ b/core/misc/htmx-behaviors.js @@ -0,0 +1,227 @@ +/** + * @file + * Connect Drupal javascript to htmx inserted content. + */ + +// Drupal core standard practice: wrap JS in an anonymous closure. +(function (Drupal, drupalSettings, once, htmx, loadjs) { + // Enforce the declared dependency on HTMX. + if (typeof htmx !== 'object' || !htmx.hasOwnProperty('process')) { + return; + } + + /** + * Attaches Drupal behaviors to markup inserted by HTMX. + * + * @param {Event} htmxLoadEvent + * Event returned from HTMX loading processes. + */ + function htmxDrupalBehaviors(htmxLoadEvent) { + // The attachBehaviors method searches within the context. + // We need to go up one level so that the loaded content is processed + // completely. + Drupal.attachBehaviors( + htmxLoadEvent.detail.elt?.parentElement, + drupalSettings, + ); + } + + /** + * Includes Drupal data with HTMX requests. + * + * @param {Event} configRequestEvent + * The event passed from HTMX as it configures a request. + */ + function htmxDrupalData(configRequestEvent) { + const url = new URL(configRequestEvent.detail.path, document.location.href); + const origin = document.location.origin; + const sameHost = origin === url.origin; + if (sameHost) { + // We only need to add this data for htmx requests back to the site. + configRequestEvent.detail.headers['HX-Page-State'] = + drupalSettings.ajaxPageState.libraries; + // Swap in drupal data selectors as #id values are altered to be unique. + configRequestEvent.detail.headers['HX-Target'] = + configRequestEvent.detail.target.dataset.drupalSelector; + configRequestEvent.detail.headers['HX-Trigger'] = + configRequestEvent.detail.elt.dataset.drupalSelector; + } + } + + /** + * Processes asset information from the response to an HTMX request. + * + * @param {Event} oobSwapEvent + * The htmx:oobAfterSwap event triggered by HTMX. + */ + function htmxDrupalAssetProcessor(oobSwapEvent) { + /** + * Local helper function to merge two objects recursively. + * + * @param current + * The object to receive the merged values. + * @param sources + * The objects to merge into current. + * + * @see https://youmightnotneedjquery.com/#deep_extend + */ + function mergeSettings(current, ...sources) { + if (!current) { + return {}; + } + + sources + .filter((obj) => Boolean(obj)) + .forEach((obj) => { + Object.entries(obj).forEach(([key, value]) => { + switch (Object.prototype.toString.call(value)) { + case '[object Object]': + current[key] = current[key] || {}; + current[key] = mergeSettings(current[key], value); + break; + + case '[object Array]': + current[key] = mergeSettings(new Array(value.length), value); + break; + + default: + current[key] = value; + } + }); + }); + + return current; + } + + // Find any inserted assets. + const assetsTag = oobSwapEvent.detail.target.querySelector( + 'script[data-drupal-selector="drupal-htmx-assets"]', + ); + if (!(assetsTag instanceof HTMLElement)) { + return; + } + // Parse assets and initialize container variables. + const assets = JSON.parse(assetsTag.textContent); + let cssItems = []; + let scriptItems = []; + let scriptBottomItems = []; + let paths = []; + if (assets.constructor.name === 'Object') { + // Variable assets should have properties 'styles', 'scripts, + // 'scripts_bottom', 'settings'. See + // HtmxResponseAttachmentsProcessor::processAssetLibraries + cssItems = new Map( + assets.styles.map((item) => [`css!${item['#attributes'].href}`, item]), + ); + scriptItems = new Map( + assets.scripts.map((item) => [item['#attributes'].src, item]), + ); + scriptBottomItems = new Map( + assets.scripts_bottom.map((item) => [item['#attributes'].src, item]), + ); + mergeSettings(drupalSettings, assets.settings); + } + // Load CSS. + if (cssItems instanceof Map && cssItems.size > 0) { + // Fetch in parallel but load in sequence. + cssItems.forEach((value, key) => paths.push(key)); + loadjs(paths, { + async: false, + before(path, linkElement) { + const item = cssItems.get(path); + Object.entries(item['#attributes']).forEach( + ([attributeKey, attributeValue]) => { + linkElement.setAttribute(attributeKey, attributeValue); + }, + ); + }, + }); + } + /* By default, loadjs appends the script to the head. When scripts + * are loaded via HTMX, their location has no impact on + * functionality. But, since Drupal loaded scripts can choose + * their parent element, we provide that option here for the sake of + * consistency. + */ + if (scriptItems instanceof Map && scriptItems.size > 0) { + paths = []; + scriptItems.forEach((value, key) => paths.push(key)); + // Load head JS. + // Fetch in parallel but load in sequence. + loadjs(paths, { + async: false, + before(path, scriptElement) { + const item = scriptItems.get(path); + Object.entries(item['#attributes']).forEach( + ([attributeKey, attributeValue]) => { + scriptElement.setAttribute(attributeKey, attributeValue); + }, + ); + }, + }); + } + if (scriptBottomItems instanceof Map && scriptBottomItems.size > 0) { + paths = []; + scriptBottomItems.forEach((value, key) => paths.push(key)); + // Fetch in parallel but load in sequence. + loadjs(paths, { + async: false, + before(path, scriptElement) { + const item = scriptBottomItems.get(path); + Object.entries(item['#attributes']).forEach( + ([attributeKey, attributeValue]) => { + scriptElement.setAttribute(attributeKey, attributeValue); + }, + ); + document.body.appendChild(scriptElement); + // Return false to bypass loadjs' default DOM insertion + // mechanism. + return false; + }, + }); + } + // Any assets now processed. Remove the found asset tag. + htmx.remove(assetsTag); + } + + /* Initialize listeners. */ + + /** + * Process new content through HTMX. + * + * @type {Drupal~behavior} + * + * @prop {Drupal~behaviorAttach} attach + * Process all new content in case any HTMX attributes are in that content. + */ + Drupal.behaviors.htmxProcess = { + attach(context) { + htmx.process(context); + }, + }; + + /** + * Set listeners for the HTMX events that power our integration. + * + * @type {{attach: Drupal.behaviors.htmxBehaviors.attach}} + */ + Drupal.behaviors.htmxBehaviors = { + attach: () => { + // JS should use native methods to enforce a single instance of our event + // handlers since we used named functions. Use the `once` library to be + // consistent with the rest of core. + if (!once('htmxBehaviors', 'html').length) { + return; + } + // Fired by HTMX before a request is sent. + window.addEventListener('htmx:configRequest', htmxDrupalData); + // Fired by HTMX after an 'out of band' content swap, which we use to add + // asset info from the response. + window.addEventListener('htmx:oobAfterSwap', htmxDrupalAssetProcessor); + // Attach Drupal behaviors after a normal HTMX content swap. + window.addEventListener('htmx:load', htmxDrupalBehaviors); + // Attach Drupal behaviors after an HTMX 'out of band' content swap. + window.addEventListener('htmx:oobAfterSwap', htmxDrupalBehaviors); + }, + }; +})(Drupal, drupalSettings, once, htmx, loadjs); diff --git a/core/modules/config/src/Form/ConfigSingleExportForm.php b/core/modules/config/src/Form/ConfigSingleExportForm.php index 963a6a1d9d41080246498c71c4e3557dcbe417ea..7b27b91d74b8d2816723ef1c31db067c7ca3c2e7 100644 --- a/core/modules/config/src/Form/ConfigSingleExportForm.php +++ b/core/modules/config/src/Form/ConfigSingleExportForm.php @@ -2,15 +2,20 @@ namespace Drupal\config\Form; +use Drupal\Component\Serialization\Yaml; use Drupal\Core\Config\Entity\ConfigEntityInterface; use Drupal\Core\Config\StorageInterface; -use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\Entity\EntityTypeInterface; +use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\Form\FormBase; -use Drupal\Core\Form\FormState; use Drupal\Core\Form\FormStateInterface; -use Drupal\Core\Serialization\Yaml; +use Drupal\Core\Http\HttpMethod; +use Drupal\Core\Render\Hypermedia\Htmx; +use Drupal\Core\Render\Hypermedia\Operations\Replace; use Drupal\Core\StringTranslation\TranslatableMarkup; +use Drupal\Core\Template\Attribute; +use Drupal\Core\Template\HtmxAttribute; +use Drupal\Core\Url; use Symfony\Component\DependencyInjection\ContainerInterface; /** @@ -74,7 +79,13 @@ public function getFormId() { /** * {@inheritdoc} */ - public function buildForm(array $form, FormStateInterface $form_state, $config_type = NULL, $config_name = NULL) { + public function buildForm(array $form, FormStateInterface $form_state, ?string $config_type = NULL, ?string $config_name = NULL) { + // Default types allow us to extend the form signature but Drupal actually + // passes NULL if the parameters are not in the route. Insure we have a + // string. + $config_type = $config_type ?? ''; + $config_name = $config_name ?? ''; + $trigger = $this->getHtmxTrigger(); $form['#prefix'] = '<div id="js-config-form-wrapper">'; $form['#suffix'] = '</div>'; foreach ($this->entityTypeManager->getDefinitions() as $entity_type => $definition) { @@ -82,6 +93,7 @@ public function buildForm(array $form, FormStateInterface $form_state, $config_t $this->definitions[$entity_type] = $definition; } } + $entity_types = array_map(function (EntityTypeInterface $definition) { return $definition->getLabel(); }, $this->definitions); @@ -90,28 +102,49 @@ public function buildForm(array $form, FormStateInterface $form_state, $config_t $config_types = [ 'system.simple' => $this->t('Simple configuration'), ] + $entity_types; + + // Prepare an Htmx object for each dynamic select. + $config_type_htmx = new Htmx(); + $config_name_htmx = new Htmx(); + + /* + * - Send a POST request to the form URL. + * - Select the config_name <select> element from the response. + * - Target the config_name <select> in the rendered form for replacement. + * - Replace uses the outerHTML strategy, which is to replace the whole tag. + */ + $form_url = Url::fromRoute( + route_name: 'config.export_single', + route_parameters: ['config_type' => $config_type, 'config_name' => $config_name], + ); + $config_type_htmx->setRequestOperation( + (new Replace()) + ->setRequest(HttpMethod::Post, $form_url) + ->select('select[data-drupal-selector="edit-config-name"]') + ->target('select[data-drupal-selector="edit-config-name"]') + ); $form['config_type'] = [ '#title' => $this->t('Configuration type'), '#type' => 'select', '#options' => $config_types, '#default_value' => $config_type, - '#ajax' => [ - 'callback' => '::updateConfigurationType', - 'wrapper' => 'js-config-form-wrapper', - ], + '#htmx' => $config_type_htmx, ]; + $default_type = $form_state->getValue('config_type', $config_type); + $config_name_htmx->setRequestOperation( + (new Replace()) + ->setRequest(HttpMethod::Post, $form_url) + ->select('#edit-export-wrapper') + ->target('#edit-export-wrapper') + ); $form['config_name'] = [ '#title' => $this->t('Configuration name'), '#type' => 'select', - '#options' => $this->findConfiguration($default_type), + '#options' => $this->findConfiguration($default_type, $form_state), + '#empty_value' => '', '#default_value' => $config_name, - '#prefix' => '<div id="edit-config-type-wrapper">', - '#suffix' => '</div>', - '#ajax' => [ - 'callback' => '::updateExport', - 'wrapper' => 'edit-export-wrapper', - ], + '#htmx' => $config_name_htmx, ]; $form['export'] = [ @@ -121,54 +154,82 @@ public function buildForm(array $form, FormStateInterface $form_state, $config_t '#prefix' => '<div id="edit-export-wrapper">', '#suffix' => '</div>', ]; - if ($config_type && $config_name) { - $fake_form_state = (new FormState())->setValues([ - 'config_type' => $config_type, - 'config_name' => $config_name, - ]); - $form['export'] = $this->updateExport($form, $fake_form_state); + if ($trigger === 'edit-config-type') { + // Type has changed. + $form['export']['#value'] = NULL; + // Also replace the wrapped export element when the response is returned. + // See https://htmx.org/attributes/hx-swap-oob/ for a detailed description + // of selection and targeting with ::swapOob. + // Since this is placed directly in the prefix string, use an + // HtmxAttribute object directly and merge it with standard attributes. + $attributes = new Attribute(['id' => 'edit-export-wrapper']); + $export_htmx_attributes = new HtmxAttribute(); + $export_htmx_attributes->swapOob('outerHTML:#edit-export-wrapper'); + $attributes = $attributes->merge($export_htmx_attributes); + $form['export']['#prefix'] = '<div ' . $attributes . '>'; + } + elseif ($trigger === 'edit-config-name') { + // A name is selected. + $default_name = $form_state->getValue('config_name', $config_name); + $form['export'] = $this->updateExport($form['export'], $default_type, $default_name); + // Also update the browser URL. + $push = Url::fromRoute( + route_name: 'config.export_single', + route_parameters: ['config_type' => $default_type, 'config_name' => $default_name], + ); + $config_name_htmx->headers->pushUrl($push); + } + elseif ($config_type && $config_name) { + $form['export'] = $this->updateExport($form['export'], $config_type, $config_name); } - return $form; - } - - /** - * Handles switching the configuration type selector. - */ - public function updateConfigurationType($form, FormStateInterface $form_state) { - $form['config_name']['#options'] = $this->findConfiguration($form_state->getValue('config_type')); - $form['export']['#value'] = NULL; return $form; } /** * Handles switching the export textarea. + * + * @param array $element + * The export element render array. + * @param string $config_type + * The config type ID. + * @param string $config_name + * The config name ID. + * + * @return array + * The modified export element render array. */ - public function updateExport($form, FormStateInterface $form_state) { + public function updateExport(array $element, string $config_type, string $config_name) { // Determine the full config name for the selected config entity. - if ($form_state->getValue('config_type') !== 'system.simple') { - $definition = $this->entityTypeManager->getDefinition($form_state->getValue('config_type')); - $name = $definition->getConfigPrefix() . '.' . $form_state->getValue('config_name'); + if (!empty($config_type) && $config_type !== 'system.simple' && !empty($config_name)) { + $definition = $this->entityTypeManager->getDefinition($config_type); + $name = $definition->getConfigPrefix() . '.' . $config_name; } // The config name is used directly for simple configuration. else { - $name = $form_state->getValue('config_name'); + $name = $config_name; } // Read the raw data for this config name, encode it, and display it. $exists = $this->configStorage->exists($name); - $form['export']['#value'] = !$exists ? NULL : Yaml::encode($this->configStorage->read($name)); - $form['export']['#description'] = !$exists ? NULL : $this->t('Filename: %name', ['%name' => $name . '.yml']); - return $form['export']; + $element['#value'] = !$exists ? NULL : Yaml::encode($this->configStorage->read($name)); + $element['#description'] = !$exists ? NULL : $this->t('Filename: %name', ['%name' => $name . '.yml']); + return $element; } /** * Handles switching the configuration type selector. + * + * @param string $config_type + * The selected configuration type. + * @param \Drupal\Core\Form\FormStateInterface $form_state + * The current form state. + * + * @return array + * An array of matching items. */ - protected function findConfiguration($config_type) { - $names = [ - '' => $this->t('- Select -'), - ]; + protected function findConfiguration($config_type, FormStateInterface $form_state) { + $names = []; // For a given entity type, load all entities. - if ($config_type && $config_type !== 'system.simple') { + if ($config_type !== 'system.simple' && !empty($config_type)) { $entity_storage = $this->entityTypeManager->getStorage($config_type); foreach ($entity_storage->loadMultiple() as $entity) { $entity_id = $entity->id(); diff --git a/core/modules/file/src/Plugin/Field/FieldFormatter/FileMediaFormatterBase.php b/core/modules/file/src/Plugin/Field/FieldFormatter/FileMediaFormatterBase.php index c00f4aeb397b7f333eb8af594dae94fbf8f1f8c7..08af0c0793b7ab3b7a36702010bd69d8b3528d24 100644 --- a/core/modules/file/src/Plugin/Field/FieldFormatter/FileMediaFormatterBase.php +++ b/core/modules/file/src/Plugin/Field/FieldFormatter/FileMediaFormatterBase.php @@ -146,7 +146,7 @@ public function viewElements(FieldItemListInterface $items, $langcode) { * Additional attributes to be applied to the HTML element. Attribute names * will be used as key and value in the HTML element. * - * @return \Drupal\Core\Template\Attribute + * @return \Drupal\Core\Template\HtmlAttributeInterface * Container with all the attributes for the HTML tag. */ protected function prepareAttributes(array $additional_attributes = []) { diff --git a/core/modules/system/tests/modules/htmx_headers_test/htmx_headers_test.info.yml b/core/modules/system/tests/modules/htmx_headers_test/htmx_headers_test.info.yml new file mode 100644 index 0000000000000000000000000000000000000000..82db4315f10bc5851fec6d642a4091552db5e2a9 --- /dev/null +++ b/core/modules/system/tests/modules/htmx_headers_test/htmx_headers_test.info.yml @@ -0,0 +1,5 @@ +name: 'HTMX Header test' +type: module +description: 'Provides routes that return render arrays for testing HtmxResponseHeader methods.' +package: Testing +version: VERSION diff --git a/core/modules/system/tests/modules/htmx_headers_test/htmx_headers_test.routing.yml b/core/modules/system/tests/modules/htmx_headers_test/htmx_headers_test.routing.yml new file mode 100644 index 0000000000000000000000000000000000000000..3afb9d8c5272efb8a825ff47b88663115e371ecf --- /dev/null +++ b/core/modules/system/tests/modules/htmx_headers_test/htmx_headers_test.routing.yml @@ -0,0 +1,103 @@ +htmx_headers_test.location_url: + path: '/test-htmx-headers/location-url' + defaults: + _title: 'Location: URL' + _controller: '\Drupal\htmx_headers_test\Controller\TestHtmxHeadersController::locationUrl' + requirements: + _permission: 'access content' + +htmx_headers_test.location_json: + path: '/test-htmx-headers/location-json' + defaults: + _title: 'Location: JSON' + _controller: '\Drupal\htmx_headers_test\Controller\TestHtmxHeadersController::locationJson' + requirements: + _permission: 'access content' + +htmx_headers_test.push_url: + path: '/test-htmx-headers/push-url' + defaults: + _title: 'Push-url' + _controller: '\Drupal\htmx_headers_test\Controller\TestHtmxHeadersController::pushUrl' + requirements: + _permission: 'access content' + +htmx_headers_test.push_url_false: + path: '/test-htmx-headers/push-url-false' + defaults: + _title: 'Push-url false' + _controller: '\Drupal\htmx_headers_test\Controller\TestHtmxHeadersController::pushUrlFalse' + requirements: + _permission: 'access content' + +htmx_headers_test.replace_url: + path: '/test-htmx-headers/replace-url' + defaults: + _title: 'Replace-url' + _controller: '\Drupal\htmx_headers_test\Controller\TestHtmxHeadersController::replaceUrl' + requirements: + _permission: 'access content' + +htmx_headers_test.replace_url_false: + path: '/test-htmx-headers/replace-url-false' + defaults: + _title: 'Replace-url false' + _controller: '\Drupal\htmx_headers_test\Controller\TestHtmxHeadersController::replaceUrlFalse' + requirements: + _permission: 'access content' + +htmx_headers_test.refresh: + path: '/test-htmx-headers/refresh' + defaults: + _title: 'Refresh' + _controller: '\Drupal\htmx_headers_test\Controller\TestHtmxHeadersController::refresh' + requirements: + _permission: 'access content' + +htmx_headers_test.reselect: + path: '/test-htmx-headers/reselect' + defaults: + _title: 'Reselect' + _controller: '\Drupal\htmx_headers_test\Controller\TestHtmxHeadersController::reselect' + requirements: + _permission: 'access content' + +htmx_headers_test.redirect: + path: '/test-htmx-headers/redirect' + defaults: + _title: 'Redirect' + _controller: '\Drupal\htmx_headers_test\Controller\TestHtmxHeadersController::redirectHeader' + requirements: + _permission: 'access content' + +htmx_headers_test.reswap: + path: '/test-htmx-headers/reswap' + defaults: + _title: 'Reswap' + _controller: '\Drupal\htmx_headers_test\Controller\TestHtmxHeadersController::reswap' + requirements: + _permission: 'access content' + +htmx_headers_test.retarget: + path: '/test-htmx-headers/retarget' + defaults: + _title: 'Retarget' + _controller: '\Drupal\htmx_headers_test\Controller\TestHtmxHeadersController::retarget' + requirements: + _permission: 'access content' + +htmx_headers_test.triggers: + path: '/test-htmx-headers/triggers' + defaults: + _title: 'Triggers' + _controller: '\Drupal\htmx_headers_test\Controller\TestHtmxHeadersController::triggers' + requirements: + _permission: 'access content' + +htmx_headers_test.triggers_json: + path: '/test-htmx-headers/triggers-json' + defaults: + _title: 'Triggers' + _controller: '\Drupal\htmx_headers_test\Controller\TestHtmxHeadersController::triggersJson' + requirements: + _permission: 'access content' diff --git a/core/modules/system/tests/modules/htmx_headers_test/src/Controller/TestHtmxHeadersController.php b/core/modules/system/tests/modules/htmx_headers_test/src/Controller/TestHtmxHeadersController.php new file mode 100644 index 0000000000000000000000000000000000000000..1180aaed50f5211c79987e7b1a8ca56b034bf662 --- /dev/null +++ b/core/modules/system/tests/modules/htmx_headers_test/src/Controller/TestHtmxHeadersController.php @@ -0,0 +1,308 @@ +<?php + +declare(strict_types=1); + +namespace Drupal\htmx_headers_test\Controller; + +use Drupal\Core\Controller\ControllerBase; +use Drupal\Core\Url; +use Drupal\Core\Http\HtmxLocationResponseData; +use Drupal\Core\Http\HtmxResponseHeaders; + +/** + * Returns responses for HTMX Header test routes. + */ +final class TestHtmxHeadersController extends ControllerBase { + + /** + * Builds the response with header. + * + * @return array + * The render array + */ + public function locationUrl(): array { + $htmxHeaders = new HtmxResponseHeaders(); + $htmxHeaders->location($this->getUrl()); + $build['content'] = [ + '#markup' => $this->t('Location'), + '#attached' => [ + 'http_header' => $htmxHeaders->toArray(), + ], + ]; + + return $build; + } + + /** + * Helper function to build a sample url. + * + * @return \Drupal\Core\Url + * The url object. + */ + protected function getUrl(): Url { + return Url::fromRoute('<front>'); + } + + /** + * Builds the response with header. + * + * @return array + * The render array + */ + public function locationJson(): array { + $htmxHeaders = new HtmxResponseHeaders(); + $data = new HtmxLocationResponseData( + path: $this->getUrl(), + source: 'source-value', + event: 'event-value', + headers: ['Header-one' => 'one'], + handler: 'handler-value', + target: 'target-value', + swap: 'swap-value', + select: 'select-value', + values: ['one' => '1', 'two' => '2'], + ); + $htmxHeaders->location($data); + $build['content'] = [ + '#type' => 'item', + '#markup' => $this->t('Location'), + '#attached' => [ + 'http_header' => $htmxHeaders->toArray(), + ], + ]; + + return $build; + } + + /** + * Builds the response with header. + * + * @return array + * The render array + */ + public function pushUrlFalse(): array { + $htmxHeaders = new HtmxResponseHeaders(); + $htmxHeaders->pushUrl(FALSE); + $build['content'] = [ + '#type' => 'item', + '#markup' => $this->t('pushUrl'), + '#attached' => [ + 'http_header' => $htmxHeaders->toArray(), + ], + ]; + + return $build; + } + + /** + * Builds the response with header. + * + * @return array + * The render array + */ + public function pushUrl(): array { + $htmxHeaders = new HtmxResponseHeaders(); + $htmxHeaders->pushUrl($this->getUrl()); + $build['content'] = [ + '#type' => 'item', + '#markup' => $this->t('pushUrl'), + '#attached' => [ + 'http_header' => $htmxHeaders->toArray(), + ], + ]; + + return $build; + } + + /** + * Builds the response with header. + * + * @return array + * The render array + */ + public function replaceUrlFalse(): array { + $htmxHeaders = new HtmxResponseHeaders(); + $htmxHeaders->replaceUrl(FALSE); + $build['content'] = [ + '#type' => 'item', + '#markup' => $this->t('pushUrl'), + '#attached' => [ + 'http_header' => $htmxHeaders->toArray(), + ], + ]; + + return $build; + } + + /** + * Builds the response with header. + * + * @return array + * The render array + */ + public function replaceUrl(): array { + $htmxHeaders = new HtmxResponseHeaders(); + $htmxHeaders->replaceUrl($this->getUrl()); + $build['content'] = [ + '#type' => 'item', + '#markup' => $this->t('replaceUrl'), + '#attached' => [ + 'http_header' => $htmxHeaders->toArray(), + ], + ]; + + return $build; + } + + /** + * Builds the response with header. + * + * @return array + * The render array + */ + public function redirectHeader(): array { + $htmxHeaders = new HtmxResponseHeaders(); + $htmxHeaders->redirect($this->getUrl()); + $build['content'] = [ + '#type' => 'item', + '#markup' => $this->t('redirect'), + '#attached' => [ + 'http_header' => $htmxHeaders->toArray(), + ], + ]; + + return $build; + } + + /** + * Builds the response with header. + * + * @return array + * The render array + */ + public function refresh(): array { + $htmxHeaders = new HtmxResponseHeaders(); + $htmxHeaders->refresh(TRUE); + $build['content'] = [ + '#type' => 'item', + '#markup' => $this->t('refresh'), + '#attached' => [ + 'http_header' => $htmxHeaders->toArray(), + ], + ]; + + return $build; + } + + /** + * Builds the response with header. + * + * @return array + * The render array + */ + public function reswap(): array { + $htmxHeaders = new HtmxResponseHeaders(); + $htmxHeaders->reswap('swap-value'); + $build['content'] = [ + '#type' => 'item', + '#markup' => $this->t('reswap'), + '#attached' => [ + 'http_header' => $htmxHeaders->toArray(), + ], + ]; + + return $build; + } + + /** + * Builds the response with header. + * + * @return array + * The render array + */ + public function retarget(): array { + $htmxHeaders = new HtmxResponseHeaders(); + $htmxHeaders->retarget('retarget-value'); + $build['content'] = [ + '#type' => 'item', + '#markup' => $this->t('retarget'), + '#attached' => [ + 'http_header' => $htmxHeaders->toArray(), + ], + ]; + + return $build; + } + + /** + * Builds the response with header. + * + * @return array + * The render array + */ + public function reselect(): array { + $htmxHeaders = new HtmxResponseHeaders(); + $htmxHeaders->reselect('reselect-value'); + $build['content'] = [ + '#type' => 'item', + '#markup' => $this->t('reselect'), + '#attached' => [ + 'http_header' => $htmxHeaders->toArray(), + ], + ]; + + return $build; + } + + /** + * Builds the response with header. + * + * @return array + * The render array + */ + public function triggers(): array { + $htmxHeaders = new HtmxResponseHeaders(); + $htmxHeaders->trigger('trigger-value') + ->triggerAfterSettle('trigger-value') + ->triggerAfterSwap('trigger-value'); + $build['content'] = [ + '#type' => 'item', + '#markup' => $this->t('reselect'), + '#attached' => [ + 'http_header' => $htmxHeaders->toArray(), + ], + ]; + + return $build; + } + + /** + * Builds the response with header. + * + * @return array + * The render array + */ + public function triggersJson(): array { + $data = [ + 'showMessage' => + [ + 'level' => 'info', + 'message' => 'Here Is A Message', + ], + ]; + $htmxHeaders = new HtmxResponseHeaders(); + $htmxHeaders->trigger($data) + ->triggerAfterSettle($data) + ->triggerAfterSwap($data); + $build['content'] = [ + '#type' => 'item', + '#markup' => $this->t('reselect'), + '#attached' => [ + 'http_header' => $htmxHeaders->toArray(), + ], + ]; + + return $build; + } + +} diff --git a/core/modules/views/views.theme.inc b/core/modules/views/views.theme.inc index 10c29c5dbf30aef72682d9dbda9409f8cc3360f2..386ae320c41c192b2a36e27b4175b170de5de755 100644 --- a/core/modules/views/views.theme.inc +++ b/core/modules/views/views.theme.inc @@ -7,6 +7,7 @@ use Drupal\Component\Utility\Html; use Drupal\Component\Utility\Xss; use Drupal\Core\Template\Attribute; +use Drupal\Core\Template\HtmlAttributeInterface; use Drupal\Core\Url; use Drupal\Core\Utility\TableSort; @@ -557,7 +558,7 @@ function template_preprocess_views_view_table(&$variables): void { if (!isset($column_reference['attributes'])) { $column_reference['attributes'] = new Attribute(); } - elseif (!($column_reference['attributes'] instanceof Attribute)) { + elseif (!($column_reference['attributes'] instanceof HtmlAttributeInterface)) { $column_reference['attributes'] = new Attribute($column_reference['attributes']); } diff --git a/core/scripts/js/vendor-update.js b/core/scripts/js/vendor-update.js index db7e8a36670b48fde9cbb70da0c50d33a837eb01..68183a2aabde35ed3ab92b0d74f2e8e3afc96746 100644 --- a/core/scripts/js/vendor-update.js +++ b/core/scripts/js/vendor-update.js @@ -79,6 +79,15 @@ const assetsFolder = `${coreFolder}/assets/vendor`; library: 'internal.backbone', files: ['backbone.js', 'backbone-min.js', 'backbone-min.js.map'], }, + { + pack: 'htmx.org', + folder: 'htmx', + library: 'htmx', + files: [ + { from: 'dist/htmx.min.js', to: 'htmx.min.js' }, + { from: 'dist/ext/debug.js', to: 'debug.js' }, + ], + }, { pack: 'jquery', files: [ diff --git a/core/tests/Drupal/KernelTests/Core/Http/HtmxHeaderTest.php b/core/tests/Drupal/KernelTests/Core/Http/HtmxHeaderTest.php new file mode 100644 index 0000000000000000000000000000000000000000..ef3fc944365a461dbc88787506039956c108b30f --- /dev/null +++ b/core/tests/Drupal/KernelTests/Core/Http/HtmxHeaderTest.php @@ -0,0 +1,126 @@ +<?php + +declare(strict_types=1); + +namespace Drupal\KernelTests\Core\Http; + +use Drupal\Core\Entity\EntityTypeManagerInterface; +use Drupal\KernelTests\KernelTestBase; +use Symfony\Component\HttpFoundation\Request; + +/** + * Test the header builder. + * + * @group Http + * + * @coversDefaultClass \Drupal\Core\Http\HtmxResponseHeaders + */ +final class HtmxHeaderTest extends KernelTestBase { + + /** + * {@inheritdoc} + */ + protected static $modules = ['system', 'user', 'htmx_headers_test']; + + /** + * Injected entity type manager. + */ + protected EntityTypeManagerInterface $entityTypeManager; + + /** + * Set up the test. + */ + protected function setUp(): void { + parent::setUp(); + $this->entityTypeManager = $this->container->get('entity_type.manager'); + $this->installEntitySchema('user_role'); + $this->installEntitySchema('user'); + $this->installConfig(['user']); + $this->container + ->get('module_handler') + ->loadInclude('user', 'install'); + user_install(); + /** @var \Drupal\user\Entity\Role $anonymous */ + $anonymous = $this->entityTypeManager->getStorage('user_role')->load('anonymous'); + $anonymous->grantPermission('access content')->save(); + } + + /** + * Test all the headers. + * + * @covers ::location + * @covers ::pushUrl + * @covers ::replaceUrl + * @covers ::refresh + * @covers ::reswap + * @dataProvider hxHeaderDataProvider + */ + public function testHeaders(string $path, string $headerName, string $headerValue): void { + $httpKernel = $this->container->get('http_kernel'); + $request = Request::create($path); + $response = $httpKernel->handle($request); + $this->assertTrue($response->headers->has($headerName)); + $value = $response->headers->get($headerName); + $this->assertEquals($headerValue, $value); + } + + /** + * Data provider for ::testHeaders. + */ + public static function hxHeaderDataProvider(): array { + return [ + ['/test-htmx-headers/location-url', 'HX-Location', '/'], + [ + '/test-htmx-headers/location-json', + 'HX-Location', + '{"path":"\/","source":"source-value","event":"event-value","headers":{"Header-one":"one"},"handler":"handler-value","target":"target-value","swap":"swap-value","select":"select-value","values":{"one":"1","two":"2"}}', + ], + ['/test-htmx-headers/push-url', 'HX-Push-Url', '/'], + ['/test-htmx-headers/push-url-false', 'HX-Push-Url', 'false'], + ['/test-htmx-headers/replace-url', 'HX-Replace-Url', '/'], + ['/test-htmx-headers/replace-url-false', 'HX-Replace-Url', 'false'], + ['/test-htmx-headers/redirect', 'HX-Redirect', '/'], + ['/test-htmx-headers/refresh', 'HX-Refresh', 'true'], + ['/test-htmx-headers/reswap', 'HX-Reswap', 'swap-value'], + ['/test-htmx-headers/retarget', 'HX-Retarget', 'retarget-value'], + ['/test-htmx-headers/reselect', 'HX-Reselect', 'reselect-value'], + ]; + } + + /** + * Test trigger headers with just an event name. + */ + public function testSimpleTriggers(): void { + $httpKernel = $this->container->get('http_kernel'); + $request = Request::create('/test-htmx-headers/triggers'); + $response = $httpKernel->handle($request); + $this->assertTrue($response->headers->has('HX-Trigger')); + $this->assertTrue($response->headers->has('HX-Trigger-After-Settle')); + $this->assertTrue($response->headers->has('HX-Trigger-After-Swap')); + $value = $response->headers->get('HX-Trigger'); + $this->assertEquals('trigger-value', $value); + $value = $response->headers->get('HX-Trigger-After-Settle'); + $this->assertEquals('trigger-value', $value); + $value = $response->headers->get('HX-Trigger-After-Swap'); + $this->assertEquals('trigger-value', $value); + } + + /** + * Test triggers with JSON payload. + */ + public function testJsonTriggers(): void { + $httpKernel = $this->container->get('http_kernel'); + $request = Request::create('/test-htmx-headers/triggers-json'); + $response = $httpKernel->handle($request); + $this->assertTrue($response->headers->has('HX-Trigger')); + $this->assertTrue($response->headers->has('HX-Trigger-After-Settle')); + $this->assertTrue($response->headers->has('HX-Trigger-After-Swap')); + $value = $response->headers->get('HX-Trigger'); + $this->assertEquals('{"showMessage":{"level":"info","message":"Here Is A Message"}}', $value); + $value = $response->headers->get('HX-Trigger-After-Settle'); + $this->assertEquals('{"showMessage":{"level":"info","message":"Here Is A Message"}}', $value); + $value = $response->headers->get('HX-Trigger-After-Swap'); + $this->assertEquals('{"showMessage":{"level":"info","message":"Here Is A Message"}}', $value); + } + +} diff --git a/core/tests/Drupal/KernelTests/Core/Template/HtmxAttributeTest.php b/core/tests/Drupal/KernelTests/Core/Template/HtmxAttributeTest.php new file mode 100644 index 0000000000000000000000000000000000000000..2536971c1f77236f619c283899baaaa759326bfd --- /dev/null +++ b/core/tests/Drupal/KernelTests/Core/Template/HtmxAttributeTest.php @@ -0,0 +1,415 @@ +<?php + +declare(strict_types=1); + +namespace Drupal\KernelTests\Core\Template; + +use Drupal\Core\Url; +use Drupal\Core\Template\HtmxAttribute; +use Drupal\KernelTests\KernelTestBase; + +/** + * Test description. + * + * @group htmx + * + * @coversDefaultClass \Drupal\Core\Template\HtmxAttribute + */ +final class HtmxAttributeTest extends KernelTestBase { + + /** + * {@inheritdoc} + */ + protected static $modules = ['common_test']; + + /** + * Class under test. + * + * @var \Drupal\Core\Template\HtmxAttribute + */ + protected HtmxAttribute $htmxAttribute; + + /** + * {@inheritdoc} + */ + protected function setUp(): void { + parent::setUp(); + $this->htmxAttribute = new HtmxAttribute(); + } + + /** + * Test get method. + * + * @covers ::get + */ + public function testHxGet(): void { + $url = Url::fromRoute('common_test.destination'); + $this->htmxAttribute->get($url); + $rendered = (string) $this->htmxAttribute; + // The paths in GitLabCI include a subfolder. + $this->assertStringStartsWith(' data-hx-get="', $rendered); + $this->assertStringEndsWith('/common-test/destination"', $rendered); + } + + /** + * Test get method. + * + * @covers ::post + */ + public function testHxPost(): void { + $url = Url::fromRoute('common_test.destination'); + $this->htmxAttribute->post($url); + $rendered = (string) $this->htmxAttribute; + // The paths in GitLabCI include a subfolder. + $this->assertStringStartsWith(' data-hx-post="', $rendered); + $this->assertStringEndsWith('/common-test/destination"', $rendered); + } + + /** + * Test get method. + * + * @covers ::put + */ + public function testHxPut(): void { + $url = Url::fromRoute('common_test.destination'); + $this->htmxAttribute->put($url); + $rendered = (string) $this->htmxAttribute; + // The paths in GitLabCI include a subfolder. + $this->assertStringStartsWith(' data-hx-put="', $rendered); + $this->assertStringEndsWith('/common-test/destination"', $rendered); + } + + /** + * Test get method. + * + * @covers ::patch + */ + public function testHxPatch(): void { + $url = Url::fromRoute('common_test.destination'); + $this->htmxAttribute->patch($url); + $rendered = (string) $this->htmxAttribute; + // The paths in GitLabCI include a subfolder. + $this->assertStringStartsWith(' data-hx-patch="', $rendered); + $this->assertStringEndsWith('/common-test/destination"', $rendered); + } + + /** + * Test get method. + * + * @covers ::delete + */ + public function testHxDelete(): void { + $url = Url::fromRoute('common_test.destination'); + $this->htmxAttribute->delete($url); + $rendered = (string) $this->htmxAttribute; + // The paths in GitLabCI include a subfolder. + $this->assertStringStartsWith(' data-hx-delete="', $rendered); + $this->assertStringEndsWith('/common-test/destination"', $rendered); + } + + /** + * Test on method. + * + * @covers ::on + * @dataProvider hxOnDataProvider + */ + public function testHxOn(string $event, string $expected): void { + $this->htmxAttribute->on($event, 'someAction'); + $rendered = (string) $this->htmxAttribute; + $expected .= 'someAction"'; + // The paths in GitLabCI include a subfolder. + $this->assertEquals($expected, $rendered); + } + + /** + * Provides data to ::testHxOn. + * + * @return array<int, string[]> + * Array of event, expected. + */ + public static function hxOnDataProvider(): array { + return [ + ['alllowercase', ' data-hx-on-alllowercase="'], + ['already-kebab-case', ' data-hx-on-already-kebab-case="'], + ['snake_case', ' data-hx-on-snake-case="'], + ['camelCaseEvent', ' data-hx-on-camel-case-event="'], + ['htmx:beforeRequest', ' data-hx-on-htmx-before-request="'], + ['::beforeRequest', ' data-hx-on--before-request="'], + ]; + } + + /** + * Test pushUrl method. + * + * @covers ::pushUrl + * @dataProvider hxPushUrlDataProvider + */ + public function testHxPushUrl(bool|Url $value, string $endsWith): void { + $startsWith = ' data-hx-push-url="'; + $this->htmxAttribute->pushUrl($value); + $rendered = (string) $this->htmxAttribute; + // The paths in GitLabCI include a subfolder. + // So treat all the results as paths. + $this->assertStringStartsWith($startsWith, $rendered); + $this->assertStringEndsWith($endsWith, $rendered); + } + + /** + * Test pushUrl method. + * + * @covers ::pushUrl + * @dataProvider hxPushUrlDataProvider + */ + public function testHxReplaceUrl(bool|Url $value, string $endsWith): void { + $startsWith = ' data-hx-replace-url="'; + $this->htmxAttribute->replaceUrl($value); + $rendered = (string) $this->htmxAttribute; + // The paths in GitLabCI include a subfolder. + // So treat all the results as paths. + $this->assertStringStartsWith($startsWith, $rendered); + $this->assertStringEndsWith($endsWith, $rendered); + } + + /** + * Provides data to ::testHxPushUrl and :testHxReplaceUrl. + * + * @return array{bool|Url, string}[] + * Array of bool|Url, expected. + */ + public static function hxPushUrlDataProvider(): array { + $url = Url::fromRoute('common_test.destination'); + return [ + [TRUE, 'true"'], + [FALSE, 'false"'], + [$url, '/common-test/destination"'], + ]; + } + + /** + * Test swapOob method. + * + * @covers ::swapOob + * @dataProvider hxSwapOobDataProvider + */ + public function testHxSwapOob(true|string $value, string $expected): void { + $this->htmxAttribute->swapOob($value); + $rendered = (string) $this->htmxAttribute; + $this->assertEquals($expected, $rendered); + } + + /** + * Provides data to ::testHxSwapOob. + * + * @return array{true|string, string}[] + * Array of true|string, expected. + */ + public static function hxSwapOobDataProvider(): array { + return [ + [TRUE, ' data-hx-swap-oob="true"'], + ['body:beforeend', ' data-hx-swap-oob="body:beforeend"'], + ]; + } + + /** + * Test vals method. + * + * @covers ::vals + */ + public function testHxVals(): void { + $values = ['myValue' => 'My Value']; + $this->htmxAttribute->vals($values); + $rendered = (string) $this->htmxAttribute; + $expected = " data-hx-vals='" . '{"myValue":"My Value"}' . "'"; + $this->assertEquals($expected, $rendered); + // AttributeJson is not tested in AttributeTest, verify safe strings. + $values = ['myValue' => '<script>alert(123)</script>']; + $this->htmxAttribute->vals($values); + $rendered = (string) $this->htmxAttribute; + $expected = " data-hx-vals='" . '{"myValue":"alert(123)"}' . "'"; + $this->assertEquals($expected, $rendered); + } + + /** + * Test swapOob method. + * + * @covers ::swapOob + * @dataProvider hxBoostDataProvider + */ + public function testHxBoost(bool $value, string $expected): void { + $this->htmxAttribute->boost($value); + $rendered = (string) $this->htmxAttribute; + $this->assertEquals($expected, $rendered); + } + + /** + * Provides data to ::testHxBoost. + * + * @return array{bool, string}[] + * Array of bool|string, expected. + */ + public static function hxBoostDataProvider(): array { + return [ + [TRUE, ' data-hx-boost="true"'], + [FALSE, ' data-hx-boost="false"'], + ]; + } + + /** + * Test headers method. + * + * @covers ::headers + */ + public function testHxHeaders(): void { + $values = ['myValue' => 'My Value']; + $this->htmxAttribute->headers($values); + $rendered = (string) $this->htmxAttribute; + $expected = " data-hx-headers='" . '{"myValue":"My Value"}' . "'"; + $this->assertEquals($expected, $rendered); + } + + /** + * Test history method. + * + * @covers ::history + * @dataProvider hxHistoryDataProvider + */ + public function testHxHistory(?bool $value, string $expected): void { + if (is_null($value)) { + $this->htmxAttribute->history(); + } + else { + $this->htmxAttribute->history($value); + } + $rendered = (string) $this->htmxAttribute; + $this->assertEquals($expected, $rendered); + } + + /** + * Provides data to ::testHxHistory. + * + * @return array{?bool, string}[] + * Array of null|bool, string, expected. + */ + public static function hxHistoryDataProvider(): array { + return [ + [TRUE, ' data-hx-history="true"'], + [FALSE, ' data-hx-history="false"'], + [NULL, ' data-hx-history="false"'], + ]; + } + + /** + * Test request method. + * + * @covers ::request + */ + public function testHxRequest(): void { + $values = ['timeout' => 100, 'credentials' => FALSE]; + $this->htmxAttribute->request($values); + $rendered = (string) $this->htmxAttribute; + $expected = " data-hx-request='" . '{"timeout":100,"credentials":false}' . "'"; + $this->assertEquals($expected, $rendered); + } + + /** + * Test swapOob method. + * + * @covers ::swapOob + * @dataProvider hxValidateDataProvider + */ + public function testHxValidate(?bool $value, string $expected): void { + if (is_null($value)) { + $this->htmxAttribute->validate(); + } + else { + $this->htmxAttribute->validate($value); + } + $rendered = (string) $this->htmxAttribute; + $this->assertEquals($expected, $rendered); + } + + /** + * Provides data to ::testHxHistory. + * + * @return array{?bool, string}[] + * Array of null|bool, string, expected. + */ + public static function hxValidateDataProvider(): array { + return [ + [TRUE, ' data-hx-validate="true"'], + [FALSE, ' data-hx-validate="false"'], + [NULL, ' data-hx-validate="true"'], + ]; + } + + /** + * Test pushUrl method. + * + * @covers ::select + * @covers ::selectOob + * @covers ::swap + * @covers ::target + * @covers ::trigger + * @covers ::confirm + * @covers ::disable + * @covers ::disabledElements + * @covers ::disinherit + * @covers ::encoding + * @covers ::history + * @covers ::historyElement + * @covers ::include + * @covers ::indicator + * @covers ::inherit + * @covers ::params + * @covers ::preserve + * @covers ::prompt + * @covers ::sync + * @covers \Drupal\Core\Template\AttributeValueBase::render + * @dataProvider hxSimpleStringAttributesDataProvider + */ + public function testHxSimpleStringAttributes(string $method, ?string $value, string $expected): void { + if (is_null($value)) { + $this->htmxAttribute->$method(); + } + else { + $this->htmxAttribute->$method($value); + } + $rendered = (string) $this->htmxAttribute; + $this->assertEquals($expected, $rendered); + } + + /** + * Provides data to ::testHxSimpleStringAttributes. + * + * @return array{string, string, string}[] + * Array of method, value, expected. + */ + public static function hxSimpleStringAttributesDataProvider(): array { + $singleQuotedSyntax = 'info[data-drupal-selector="edit-select"]'; + return [ + ['select', '#info-details', ' data-hx-select="#info-details"'], + ['select', 'info[data-drupal-selector="edit-select"]', " data-hx-select='$singleQuotedSyntax'"], + ['selectOob', '#info-details', ' data-hx-select-oob="#info-details"'], + ['selectOob', '#info-details:afterbegin, #alert', ' data-hx-select-oob="#info-details:afterbegin, #alert"'], + ['swap', 'afterbegin', ' data-hx-swap="afterbegin ignoreTitle:true"'], + ['target', 'descriptor', ' data-hx-target="descriptor"'], + ['trigger', 'event', ' data-hx-trigger="event"'], + ['confirm', 'A confirmation message', ' data-hx-confirm="A confirmation message"'], + ['disable', NULL, ' data-hx-disable'], + ['disabledElements', 'descriptor', ' data-hx-disabled-elt="descriptor"'], + ['disinherit', 'descriptor', ' data-hx-disinherit="descriptor"'], + ['encoding', NULL, ' data-hx-encoding="multipart/form-data"'], + ['encoding', 'application/x-www-form-urlencoded', ' data-hx-encoding="application/x-www-form-urlencoded"'], + ['ext', 'name, name', ' data-hx-ext="name, name"'], + ['historyElement', NULL, ' data-hx-history-elt'], + ['include', 'descriptor', ' data-hx-include="descriptor"'], + ['indicator', 'descriptor', ' data-hx-indicator="descriptor"'], + ['inherit', 'descriptor', ' data-hx-inherit="descriptor"'], + ['params', 'filter string', ' data-hx-params="filter string"'], + ['preserve', 'id', ' data-hx-preserve="id"'], + ['prompt', 'A prompt message', ' data-hx-prompt="A prompt message"'], + ['sync', 'closest form:abort', ' data-hx-sync="closest form:abort"'], + ]; + } + +} diff --git a/core/tests/Drupal/Tests/Core/Common/AttributesTest.php b/core/tests/Drupal/Tests/Core/Common/AttributesTest.php index 6a65be7f0460fe0b3be5eef664db7f0d8a4f3722..9b144858764eb7e8a0c9624af47c6db38d23ba50 100644 --- a/core/tests/Drupal/Tests/Core/Common/AttributesTest.php +++ b/core/tests/Drupal/Tests/Core/Common/AttributesTest.php @@ -24,7 +24,7 @@ public static function providerTestAttributeData() { return [ // Verify that special characters are HTML encoded. [['&"\'<>' => 'value'], ' &"'<>="value"', 'HTML encode attribute names.'], - [['title' => '&"\'<>'], ' title="&"'<>"', 'HTML encode attribute values.'], + [['title' => '&"\'<>'], ' title=\'&"\'<>\'', 'XSS filter attribute values.'], // Verify multi-value attributes are concatenated with spaces. [['class' => ['first', 'last']], ' class="first last"', 'Concatenate multi-value attributes.'], // Verify boolean attribute values are rendered correctly. diff --git a/core/tests/Drupal/Tests/Core/Render/Hypermedia/HtmxOperationsTest.php b/core/tests/Drupal/Tests/Core/Render/Hypermedia/HtmxOperationsTest.php new file mode 100644 index 0000000000000000000000000000000000000000..1ec2c137bab57d070d2f7c43ee3f80b770e2db91 --- /dev/null +++ b/core/tests/Drupal/Tests/Core/Render/Hypermedia/HtmxOperationsTest.php @@ -0,0 +1,102 @@ +<?php + +declare(strict_types=1); + +namespace Drupal\Tests\Core\Render\Hypermedia; + +use Drupal\Core\Http\HttpMethod; +use Drupal\Core\Render\Element\RenderElementBase; +use Drupal\Core\Render\Hypermedia\Htmx; +use Drupal\Core\Render\Hypermedia\Operations\Insert; +use Drupal\Core\Render\Hypermedia\Operations\Replace; +use Drupal\Core\Url; +use Drupal\Tests\UnitTestCase; +use PHPUnit\Framework\MockObject\MockObject; + +/** + * Unit tests for implementations of HtmxOperationInterface. + * + * @group Hypermedia + */ +class HtmxOperationsTest extends UnitTestCase { + + /** + * Htmx object to support operation testing. + */ + private Htmx $htmx; + + /** + * Tests for HtmxRequestOperationInterface operations need a URL. + */ + private Url|MockObject $url; + + /** + * {@inheritdoc} + */ + protected function setUp(): void { + parent::setUp(); + $this->htmx = new Htmx(); + $this->url = $this->getMockBuilder('\Drupal\Core\Url') + ->disableOriginalConstructor() + ->onlyMethods(['toString']) + ->getMock(); + $this->url->expects($this->any()) + ->method('toString') + ->willReturn('/example/path'); + } + + /** + * Helper method to process the operations as if the render callback was used. + * + * @return array + * A stub of a processed render array. + */ + protected function processOperations(): array { + return RenderElementBase::processHtmxElement(['#htmx' => $this->htmx]); + } + + /** + * @covers \Drupal\Core\Render\Hypermedia\Operations\Insert + */ + public function testInsert(): void { + $insert = (new Insert()) + ->select('#source-value') + ->target('#target-value') + ->setRequest(HttpMethod::Get, $this->url); + $this->htmx->setRequestOperation($insert); + $result = $this->processOperations(); + $headers = $result['#attached']['http_header'] ?? []; + $attributes = $result['#attributes'] ?? []; + $this->assertEquals([], $headers); + $expected = [ + 'data-hx-get' => '/example/path', + 'data-hx-select' => '#source-value', + 'data-hx-target' => '#target-value', + 'data-hx-swap' => 'beforeend ignoreTitle:true', + ]; + $this->assertEquals($expected, $attributes); + } + + /** + * @covers \Drupal\Core\Render\Hypermedia\Operations\Replace + */ + public function testReplace(): void { + $replace = (new Replace()) + ->select('#source-value') + ->target('#target-value') + ->setRequest(HttpMethod::Get, $this->url); + $this->htmx->setRequestOperation($replace); + $result = $this->processOperations(); + $headers = $result['#attached']['http_header'] ?? []; + $attributes = $result['#attributes'] ?? []; + $this->assertEquals([], $headers); + $expected = [ + 'data-hx-get' => '/example/path', + 'data-hx-select' => '#source-value', + 'data-hx-target' => '#target-value', + 'data-hx-swap' => 'outerHTML ignoreTitle:true', + ]; + $this->assertEquals($expected, $attributes); + } + +} diff --git a/core/tests/Drupal/Tests/Core/Template/AttributeTest.php b/core/tests/Drupal/Tests/Core/Template/AttributeTest.php index 8f011b46f662a62a452c1095a530f85b2c7564c0..a72c0f34e67c18dd7856f87ebf30e9f72265ea33 100644 --- a/core/tests/Drupal/Tests/Core/Template/AttributeTest.php +++ b/core/tests/Drupal/Tests/Core/Template/AttributeTest.php @@ -6,6 +6,7 @@ use Drupal\Component\Render\MarkupInterface; use Drupal\Component\Utility\Html; +use Drupal\Component\Utility\Xss; use Drupal\Core\Render\Markup; use Drupal\Core\Template\Attribute; use Drupal\Core\Template\AttributeArray; @@ -379,11 +380,11 @@ public static function providerTestAttributeValues() { $data = []; $string = '"> <script>alert(123)</script>"'; - $data['safe-object-xss1'] = [['title' => Markup::create($string)], ' title=""> alert(123)""']; - $data['non-safe-object-xss1'] = [['title' => $string], ' title="' . Html::escape($string) . '"']; + $data['safe-object-xss1'] = [['title' => Markup::create($string)], ' title=\'"> alert(123)"\'']; + $data['non-safe-object-xss1'] = [['title' => $string], ' title=\'' . Xss::filter($string) . "'"]; $string = '"><script>alert(123)</script>'; - $data['safe-object-xss2'] = [['title' => Markup::create($string)], ' title="">alert(123)"']; - $data['non-safe-object-xss2'] = [['title' => $string], ' title="' . Html::escape($string) . '"']; + $data['safe-object-xss2'] = [['title' => Markup::create($string)], ' title=\'">alert(123)\'']; + $data['non-safe-object-xss2'] = [['title' => $string], ' title="' . Xss::filter($string) . '"']; return $data; } diff --git a/core/themes/claro/claro.theme b/core/themes/claro/claro.theme index c406fed47c22b286d4c074bd10eaeb8f5e55ceb1..05409f13e5ab36b56f813a28e9e410d81270e784 100644 --- a/core/themes/claro/claro.theme +++ b/core/themes/claro/claro.theme @@ -14,6 +14,7 @@ use Drupal\Core\Link; use Drupal\Core\Render\Element; use Drupal\Core\Template\Attribute; +use Drupal\Core\Template\HtmlAttributeInterface; use Drupal\Core\Url; use Drupal\media\MediaForm; use Drupal\file\FileInterface; @@ -725,7 +726,7 @@ function claro_form_menu_link_content_form_alter(&$form, FormStateInterface $for '#group' => 'advanced', '#title' => t('Description'), '#attributes' => ['class' => ['entity-meta__description']], - '#tree' => FALSE, + '#tree' => TRUE, '#accordion' => TRUE, 'description' => $form['description'], ]; @@ -1270,7 +1271,7 @@ function claro_preprocess_system_themes_page(&$variables): void { // @todo Remove dependency on attributes after // https://www.drupal.org/project/drupal/issues/2511548 has been // resolved. - if (isset($theme_card['screenshot']['#attributes']) && $theme_card['screenshot']['#attributes'] instanceof Attribute && $theme_card['screenshot']['#attributes']->hasClass('no-screenshot')) { + if (isset($theme_card['screenshot']['#attributes']) && $theme_card['screenshot']['#attributes'] instanceof HtmlAttributeInterface && $theme_card['screenshot']['#attributes']->hasClass('no-screenshot')) { unset($theme_card['screenshot']); } diff --git a/core/themes/olivero/olivero.theme b/core/themes/olivero/olivero.theme index d10ee7d155cd78cb7f3fbf8e22252787f801e572..35e1d59092e108386f4b73ef1e3f67343fd6ee8c 100644 --- a/core/themes/olivero/olivero.theme +++ b/core/themes/olivero/olivero.theme @@ -608,7 +608,7 @@ function olivero_preprocess_table(&$variables): void { if (!empty($variables['rows'])) { $draggable_row_found = FALSE; foreach ($variables['rows'] as &$row) { - /** @var \Drupal\Core\Template\Attribute $row['attributes'] */ + /** @var \Drupal\Core\Template\Attribute $row ['attributes'] */ if (!empty($row['attributes']) && $row['attributes']->hasClass('draggable')) { if (!$draggable_row_found) { $variables['attributes']['class'][] = 'draggable-table';