Skip to content

Instantly share code, notes, and snippets.

@simevidas
Created December 1, 2023 21:30
Show Gist options
  • Save simevidas/1d6a2dd59c77ed153a81b334220b8a36 to your computer and use it in GitHub Desktop.
Save simevidas/1d6a2dd59c77ed153a81b334220b8a36 to your computer and use it in GitHub Desktop.
class BetterDetails extends HTMLElement {
constructor () {
super();
//Inner details
const bdetails=this.querySelector("details");
let clonedDet = bdetails.cloneNode(true);
let sumEl = clonedDet.querySelector('summary');
if (sumEl) {
sumEl.remove();
}
this.detContent=clonedDet.innerHTML + ` WTF!!!!`;
//Inner summary
const bsummary=this.querySelector("summary");
this.sumContent=bsummary.innerHTML;
}
connectedCallback() {
// Create a shadow root
const shadow = this.attachShadow({ mode: "open" });
let detwrap = document.createElement("div");
detwrap.classList.add('detwrap');
let det = document.createElement("div");
det.classList.add('det');
det.setAttribute('aria-hidden', 'true');
let detinner = document.createElement("div");
detinner.classList.add('detinner');
detinner.innerHTML=this.detContent;
det.append(detinner);
const sumwrap = document.createElement("div");
sumwrap.classList.add('sum');
sumwrap.setAttribute('aria-expanded', 'false');
sumwrap.innerHTML = this.sumContent;
detwrap.append(sumwrap);
detwrap.append(det);
sumwrap.addEventListener('click',function(){
//sumwrap.toggleAttribute('aria-expanded');
sumwrap.getAttribute('aria-expanded') == 'false' ? sumwrap.setAttribute('aria-expanded', "true") : sumwrap.setAttribute('aria-expanded', "false");
//det.toggleAttribute('aria-hidden');
det.getAttribute('aria-hidden') == 'false' ? det.setAttribute('aria-hidden', "true") : det.setAttribute('aria-hidden', "false");
});
let icon = "►";
let openicon = "▼";
const marker = this.getAttribute("marker")
if(!!marker)
icon = marker;
const openmarker = this.getAttribute("open-marker")
if(!!openmarker)
openicon = openmarker;
let stylewrap = document.createElement("style");
const styles = `
:host .det
{
display: grid;
grid-template-rows: 1fr;
transition: grid-template-rows 0.5s ease-in-out;
}
:host .detinner{
overflow: hidden;
margin-left: 1.25rem;
max-width: 80rem;
}
:host .det[aria-hidden='true']
{
grid-template-rows: 0fr;
}
:host .sum{
display: flex;
gap: .25rem;
align-items: center;
cursor: pointer;
}
:host .sum::before{
content: "${icon}";
flex: 0 0 1rem;
font-weight: bold;
}
:host .sum[aria-expanded='true']::before{
content: "${openicon}";
}
`;
stylewrap.innerHTML=styles;
detwrap.append(stylewrap);
// Append it to the shadow root
shadow.replaceChildren(detwrap);
}
};
export { BetterDetails };
customElements.define( 'better-details', BetterDetails );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment