semantic-forms 5.3.16 → 5.3.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -44,6 +44,18 @@ const waiting=new Map;let observer;const setInkOffset=(form,label)=>{if(!window.
44
44
  /***/"./lib/inputEnhancements.js"(module,__unused_webpack_exports,__webpack_require__){const{insertAfter}=__webpack_require__("./lib/helpers.js");const icons={passwordShow:'<svg fill="none" height="256" viewBox="0 0 24 24" width="256" xmlns="http://www.w3.org/2000/svg"><g stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"><path d="m1 12s4-8 11-8 11 8 11 8"/><path d="m1 12s4 8 11 8 11-8 11-8"/><circle cx="12" cy="12" r="3"/></g></svg>',passwordHide:'<svg fill="none" height="256" viewBox="0 0 24 24" width="256" xmlns="http://www.w3.org/2000/svg"><g stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"><path d="m2 2 20 20"/><path d="m6.71277 6.7226c-3.04798 2.07267-4.71277 5.2774-4.71277 5.2774s3.63636 7 10 7c2.0503 0 3.8174-.7266 5.2711-1.7116m-6.2711-12.23018c.3254-.03809.6588-.05822 1-.05822 6.3636 0 10 7 10 7s-.6918 1.3317-2 2.8335"/><path d="m14 14.2362c-.5308.475-1.2316.7639-2 .7639-1.6569 0-3-1.3431-3-3 0-.8237.33193-1.5698.86932-2.11192"/></g></svg>',helpIcon:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="16" height="16" viewBox="0 0 16 16" version="1.1" style="overflow:visible;"><rect width="16" height="16" fill="none"/><path fill="currentColor" d="M8,10.5c-0.552,0-1,0.448-1,1c0,0.552,0.448,1,1,1c0.552,0,1-0.448,1-1C9,10.948,8.552,10.5,8,10.5z M8,0 C3.582,0,0,3.582,0,8c0,4.418,3.582,8,8,8s8-3.582,8-8C16,3.582,12.418,0,8,0z M12.243,12.243C11.109,13.376,9.603,14,8,14 s-3.109-0.624-4.243-1.757C2.624,11.109,2,9.603,2,8s0.624-3.109,1.757-4.243C4.891,2.624,6.397,2,8,2s3.109,0.624,4.243,1.757 C13.376,4.891,14,6.397,14,8C14,9.603,13.376,11.109,12.243,12.243z M7.927,3.755c-2.248,0-2.76,1.695-2.802,2.906h1.571 c0.028-0.256,0.101-1.418,1.221-1.418c0.672,0,1.206,0.406,1.206,1.175c0,0.695-0.724,1.155-1.303,1.711 C7.241,8.685,7.168,9.325,7.168,9.824V10c0.146,0,1.615,0,1.615,0V9.824c0-1.256,1.967-1.594,1.967-3.541 C10.75,5.059,9.874,3.755,7.927,3.755z"/></svg>'};const lookups={nodeName:["TEXTAREA","SELECT"],inputType:["checkbox","color","date","datetime-local","email","file","image","month","number","password","radio","range","search","tel","text","time","url","week"]};let lastFocusedInput;let lastClearFieldPressed;
45
45
  // browsers that implement the switch attribute expose it on the input prototype, render the control as a switch and report the switch role themselves, so nothing below is needed there
46
46
  const nativeSwitchSupport="switch"in window.HTMLInputElement.prototype;
47
+ // the stylesheet outlines a field on :user-invalid, which is the browser saying the visitor has had their turn with the field and what they left behind does not pass. aria-invalid has to say the same thing, or the outline is a message only someone looking at the screen receives
48
+
49
+ // it is read back from that selector rather than worked out again from blur events, which is how it is usually done and gets it wrong: tabbing straight through an empty required field is not a mistake the visitor has made yet, and :user-invalid already knows that
50
+ const supportsUserInvalid=(()=>{try{return window.CSS.supports("selector(:user-invalid)")}catch{return false}})();
51
+ // while setInvalid has marked a field, its message owns aria-invalid and this leaves the attribute alone
52
+ const syncAriaInvalid=input=>{if(!supportsUserInvalid||input.classList.contains("invalid"))return;if(input.matches(":user-invalid"))input.setAttribute("aria-invalid","true");else input.removeAttribute("aria-invalid")};
53
+ // blur and the invalid event are when the browser's answer can start being yes; input and change are when the visitor puts it right again
54
+ const trackUserInvalid=input=>{if(!supportsUserInvalid)return;const sync=()=>syncAriaInvalid(input);for(const name of["blur","input","change","invalid"])input.addEventListener(name,sync)};
55
+ // puts a field's help text where a screen reader will read it, which a title attribute does not do for a group of checkboxes or radios, and points the field at it
56
+
57
+ // the text is not drawn on screen: it stands in for the title the help icon carries, which only a mouse hovering the icon can reach
58
+ let helpTextCount=0;const describe=(inputs,text)=>{const host=inputs[0]?.closest("dd");if(!host)return;const note=document.createElement("span");note.className="semanticFormsVisuallyHidden";note.id=`semanticFormsHelpText_${++helpTextCount}`;note.textContent=text;host.append(note);for(const input of inputs){const describedBy=(input.getAttribute("aria-describedby")||"").split(" ").filter(Boolean);if(!describedBy.includes(note.id))input.setAttribute("aria-describedby",[...describedBy,note.id].join(" "))}};
47
59
  // lets a polyfilled switch be toggled by dragging its thumb, which is what the native control does. a pointer that never travels far enough is left alone so it still lands as a click.
48
60
  const enableSwitchDragging=input=>{input.addEventListener("pointerdown",event=>{if(input.disabled)return;const startX=event.clientX;const rightToLeft=window.getComputedStyle(input).direction==="rtl";
49
61
  // half the track is the distance the thumb travels between the two positions
@@ -57,11 +69,15 @@ input.addEventListener("click",clickEvent=>clickEvent.preventDefault(),{once:tru
57
69
  // returns the field, which is the new textarea when one was made
58
70
  const enhanceAutoGrow=(input,form)=>{if(input.getAttribute("data-auto-grow")===null)return input;
59
71
  // progressively enhance inputs into textareas
60
- if(input.nodeName==="INPUT"&&input.type==="text"){const newInput=document.createElement("textarea");newInput.id=input.id;newInput.class=input.class;newInput.innerText=input.value;newInput.setAttribute("data-auto-grow","");input.replaceWith(newInput);input=newInput}if(input.nodeName==="TEXTAREA")
72
+ if(input.nodeName==="INPUT"&&input.type==="text"){
73
+ // the textarea takes over everything the input had except what only an input has, so its name, its class, whether it's required, and so on all carry over
74
+ const newInput=document.createElement("textarea");for(const attribute of input.attributes)if(!["type","value","size","list","pattern"].includes(attribute.name))newInput.setAttribute(attribute.name,attribute.value);newInput.value=input.value;input.replaceWith(newInput);input=newInput}if(input.nodeName==="TEXTAREA")
61
75
  // when pressing enter while this input is focused, we want to submit
62
76
  input.addEventListener("keypress",e=>{if(e.key!=="Enter"||e.key==="Enter"&&e.shiftKey)return;e.preventDefault();form.requestSubmit()});return input};
63
77
  // the behavior of the control itself, as opposed to the labels and buttons placed around it: switches and textareas. this is all a field in a customLayout element gets, and every other field gets it too
64
78
  const enhanceControl=(input,type,form)=>{
79
+ // what a screen reader is told about the field matches what the stylesheet draws on it
80
+ trackUserInvalid(input);
65
81
  // a checkbox with the switch attribute is a switch; the stylesheet draws one in every browser, and where the attribute is not implemented natively the role and dragging are supplied here
66
82
  if(type==="checkbox"&&input.hasAttribute("switch")&&!nativeSwitchSupport){input.setAttribute("role","switch");enableSwitchDragging(input)}
67
83
  // add listener to shift clear button when scrollbar present
@@ -84,8 +100,8 @@ input.style.removeProperty("width");input.style.removeProperty("box-sizing");inp
84
100
  const rows=Math.round((scrollHeight-blockPadding)/lineHeight);
85
101
  // set the calculated rows attribute (limited by rowLimit)
86
102
  if(maxRows)input.setAttribute("rows",""+Math.min(rows,Number(maxRows)));else input.setAttribute("rows",""+rows)};input.addEventListener("input",handleInput);
87
- // trigger the event to set the initial rows value
88
- input.dispatchEvent(new Event("input",{bubbles:true}))}
103
+ // set the initial rows value. this calls the sizing directly rather than firing an input event, which would tell the app's own listeners the user had changed the field
104
+ handleInput()}
89
105
  // progressively enhance textarea for Firefox and Safari
90
106
  // this may be removed once fully supported in Firefox and Safari: https://caniuse.com/wf-field-sizing
91
107
  if(input.getAttribute("data-auto-grow")!==null)if(!("fieldSizing"in document.createElement("input").style)){const adjustHeight=()=>{if(input.value.length){const borderWidth=parseInt(window.getComputedStyle(input).getPropertyValue("border-width"));input.style.height=input.scrollHeight+borderWidth*2+"px"}else input.style.height=window.getComputedStyle(form).getPropertyValue("--semanticFormsInputHeight")};
@@ -94,30 +110,33 @@ input.style.height=window.getComputedStyle(form).getPropertyValue("--semanticFor
94
110
  // shifts the clear button to the right if a scrollbar is present
95
111
  const shiftClearBtn=()=>{const clearBtn=input.parentElement?.querySelector("button.clear");if(clearBtn)clearBtn.style.marginRight=input.clientHeight<input.scrollHeight?"15px":""};input.addEventListener("input",shiftClearBtn);input.addEventListener("mouseup",shiftClearBtn);shiftClearBtn()}};const enhanceInput=(input,form)=>{
96
112
  // ignore input if it has previously been formatted
97
- if(input.classList.contains("semanticform")||!input.id)return;const type=input.getAttribute("type");if(!lookups.nodeName.includes(input.nodeName)&&!lookups.inputType.includes(type))return;
113
+ if(input.classList.contains("semanticform"))return;const type=input.getAttribute("type");if(!lookups.nodeName.includes(input.nodeName)&&!lookups.inputType.includes(type))return;
114
+ // a field without an id has no label to float or place buttons beside, but the control itself is still enhanced, such as a switch being given its role and dragging
115
+ if(!input.id){input.classList.add("semanticform");enhanceControl(input,type,form);return}
98
116
  // inside a customLayout element the app lays out the <dl> itself, so nothing is added, moved or rewritten around the field: no float label, no clear or show password button, no wrapping <div>, no required asterisk or help icon, and no value appended to the label of a range. the control itself is still enhanced. it is marked like any other enhanced field so that reinitializing does not enhance it twice
99
- if(input.closest(".customLayout")){input.classList.add("semanticform");enhanceControl(enhanceAutoGrow(input,form),type,form);return}
117
+ if(input.closest(".customLayout")){input.classList.add("semanticform");input=enhanceAutoGrow(input,form);enhanceControl(input,type,form);if(type==="range"&&input.getAttribute("data-display-value")!==null)displayRangeValue(input,null);return}
100
118
  // recursively find <dl> element
101
119
  let dl=input.parentNode;while(dl&&dl.nodeName!=="DL")dl=dl.parentNode;if(!dl)return;if(!dl.classList.contains("floatLabelForm"))dl.classList.add("floatLabelForm");
102
120
  // the label is looked up in the input's own tree rather than the document, so that a form inside a shadow root finds its labels instead of coming up empty
103
- const tree=input.getRootNode();const label=input.parentNode.parentNode.id&&(type==="checkbox"||type==="radio")?tree.querySelector("label[data-for="+input.parentNode.parentNode.id.replace(/\./g,"\\.")+"]"):tree.querySelector("label[for="+input.id.replace(/\./g,"\\.")+"]");if(!label){console.error(`semantic-forms: Found an input (${input.id||input.getAttribute("name")}) without a properly associated label. Make sure there is a label for it and the label has a matching "for" attribute.`);return}input.classList.add("semanticform");
121
+ const tree=input.getRootNode();const label=input.parentNode.parentNode.id&&(type==="checkbox"||type==="radio")?tree.querySelector(`label[data-for="${window.CSS.escape(input.parentNode.parentNode.id)}"]`):tree.querySelector(`label[for="${window.CSS.escape(input.id)}"]`);if(!label){console.error(`semantic-forms: Found an input (${input.id||input.getAttribute("name")}) without a properly associated label. Make sure there is a label for it and the label has a matching "for" attribute.`);return}input.classList.add("semanticform");
104
122
  // an input outside a <dd> is reported by the checks further down, so tolerate it here
105
123
  const isWrapped=input.closest("dd")?.parentElement.nodeName==="DIV";
106
124
  // #region create labels
107
- const newLabel=document.createElement("label");newLabel.className="floatLabelFormAnimatedLabel";if(type==="checkbox"||type==="radio"){const div=isWrapped?input.closest("dd").parentElement:document.createElement("div");const dt=label.closest("dt");const dd=input.closest("dd");if(!dt||!dd){console.error(`semantic-forms: Found an input (${input.id||input.getAttribute("name")}) that is not inside a <dd> element.`);return}if(dd.firstChild.nodeName!=="LABEL"){if(type==="checkbox"&&input.parentNode.nodeName==="DD"){newLabel.setAttribute("for",input.id);input.parentNode.classList.add("singleCheckbox");newLabel.className="";label.setAttribute("hidden","hidden");insertAfter(newLabel,input)}if(type==="radio"&&input.parentNode.nodeName==="DD"){newLabel.setAttribute("for",input.id);input.parentNode.classList.add("singleRadio");newLabel.className="";label.setAttribute("hidden","hidden");insertAfter(newLabel,input)}newLabel.innerHTML=label.innerHTML;if(label.hasAttribute("title")&&label.getAttribute("data-show-help-icon")!==null&&!label.querySelector("span.help")){const text=label.getAttribute("title");label.innerHTML+=` <span title="${text}" class="help">${icons.helpIcon}</span>`;newLabel.innerHTML+=` <span title="${text}" class="help">${icons.helpIcon}</span>`}if(dd.querySelector(":required")&&label.getAttribute("data-no-asterisk")===null&&!label.querySelector("span.required")){const text=label.getAttribute("data-asterisk-text")||"This field is required.";label.innerHTML+=` <span title="${text}" class="required">*</span>`;newLabel.innerHTML+=` <span title="${text}" class="required">*</span>`}if(!dd.querySelector("label"))dd.append(newLabel)}
125
+ const newLabel=document.createElement("label");newLabel.className="floatLabelFormAnimatedLabel";if(type==="checkbox"||type==="radio"){const div=isWrapped?input.closest("dd").parentElement:document.createElement("div");const dt=label.closest("dt");const dd=input.closest("dd");if(!dt||!dd){console.error(`semantic-forms: Found an input (${input.id||input.getAttribute("name")}) that is not inside a <dd> element.`);return}if(dd.firstChild.nodeName!=="LABEL"){if(type==="checkbox"&&input.parentNode.nodeName==="DD"){newLabel.setAttribute("for",input.id);input.parentNode.classList.add("singleCheckbox");newLabel.className="";label.setAttribute("hidden","hidden");insertAfter(newLabel,input)}if(type==="radio"&&input.parentNode.nodeName==="DD"){newLabel.setAttribute("for",input.id);input.parentNode.classList.add("singleRadio");newLabel.className="";label.setAttribute("hidden","hidden");insertAfter(newLabel,input)}newLabel.innerHTML=label.innerHTML;if(label.hasAttribute("title")&&label.getAttribute("data-show-help-icon")!==null&&!label.querySelector("span.help")){const text=label.getAttribute("title");appendBadge(label,"help",text,icons.helpIcon);appendBadge(newLabel,"help",text,icons.helpIcon);describe(dd.querySelectorAll("input"),text)}if(dd.querySelector(":required")&&label.getAttribute("data-no-asterisk")===null&&!label.querySelector("span.required")){const text=label.getAttribute("data-asterisk-text")||"This field is required.";appendBadge(label,"required",text,"*");appendBadge(newLabel,"required",text,"*")}if(!dd.querySelector("label"))dd.append(newLabel)}
108
126
  // if the user did not wrap the input in a div, do it for them
109
127
  if(!isWrapped){
110
128
  // the wrapper goes where the <dt> was, so the field keeps its place in the markup. a div the author wrote is already in the right place and is deliberately left where it is: moving it would push the field past anything the enhancer does not touch, such as a <dd> holding only a button
111
129
  dt.before(div);div.append(dt,dd);
112
130
  // determine visibility of newly created <div>
113
- if(dt.style.display==="none"&&dd.style.display==="none")div.style.display="none"}}else{newLabel.setAttribute("for",input.id);newLabel.innerHTML=label.innerHTML;if(input.hasAttribute("title")&&label.getAttribute("data-show-help-icon")!==null&&!label.querySelector("span.help")){const text=input.getAttribute("title");newLabel.innerHTML+=` <span title="${text}" class="help">${icons.helpIcon}</span>`}if(input.hasAttribute("required")&&label.getAttribute("data-no-asterisk")===null&&!label.querySelector("span.required")){const text=label.getAttribute("data-asterisk-text")||"This field is required.";newLabel.innerHTML+=` <span title="${text}" class="required">*</span>`}label.setAttribute("hidden","hidden");insertAfter(newLabel,input)}
131
+ if(dt.style.display==="none"&&dd.style.display==="none")div.style.display="none"}}else{newLabel.setAttribute("for",input.id);newLabel.innerHTML=label.innerHTML;if(input.hasAttribute("title")&&label.getAttribute("data-show-help-icon")!==null&&!label.querySelector("span.help")){appendBadge(newLabel,"help",input.getAttribute("title"),icons.helpIcon);describe([input],input.getAttribute("title"))}if(input.hasAttribute("required")&&label.getAttribute("data-no-asterisk")===null&&!label.querySelector("span.required"))appendBadge(newLabel,"required",label.getAttribute("data-asterisk-text")||"This field is required.","*");label.setAttribute("hidden","hidden");insertAfter(newLabel,input)}
114
132
  // #endregion
115
133
  // #region standard inputs
116
134
  input=enhanceAutoGrow(input,form);if(type!=="checkbox"&&type!=="radio"){if(!input.getAttribute("placeholder"))input.setAttribute("placeholder"," ");const div=isWrapped?input.closest("dd").parentElement:document.createElement("div");const dt=label.closest("dt");const dd=input.closest("dd");if(!dt||!dd){console.error(`semantic-forms: Found an input (${input.id||input.getAttribute("name")}) that does not have a corresponding ${!dt?"<dt>":"<dd>"} element.`);return}
117
135
  // input clear button. a field the user cannot edit does not get one, since the button would empty it anyway. a field that only becomes uneditable later is handled in css
118
- if(input.nodeName!=="SELECT"&&type!=="range"&&!input.readOnly&&!input.disabled){const clearBtn=document.createElement("button");clearBtn.type="button";clearBtn.title=input.getAttribute("data-clear-field-text")||"Clear field";clearBtn.ariaLabel=input.getAttribute("data-clear-field-text")||"Clear field";clearBtn.tabIndex=-1;clearBtn.innerHTML='<svg viewBox="0 0 16 16" width="18" height="18"><path d="M 1 1 L 15 15 M 1 15 L 15 1" fill="none" stroke-width="2" stroke="currentColor" />';clearBtn.classList.add("clear");clearBtn.id=`semanticFormsClearButton_${input.id}`;clearBtn.addEventListener("click",()=>{input.previousValue=input.value;input.value="";input.focus();lastClearFieldPressed=input.id;
119
- // used for any other updates required by various inputs
120
- input.dispatchEvent(new Event("input",{bubbles:true}))});insertAfter(clearBtn,dd.querySelector("label"))}input.addEventListener("focus",event=>{if(event.target.nodeName==="INPUT")lastFocusedInput=event.target});
136
+ if(input.nodeName!=="SELECT"&&type!=="range"&&!input.readOnly&&!input.disabled){const clearBtn=document.createElement("button");clearBtn.type="button";clearBtn.title=input.getAttribute("data-clear-field-text")||"Clear field";clearBtn.ariaLabel=input.getAttribute("data-clear-field-text")||"Clear field";clearBtn.tabIndex=-1;clearBtn.innerHTML='<svg viewBox="0 0 16 16" width="18" height="18"><path d="M 1 1 L 15 15 M 1 15 L 15 1" fill="none" stroke-width="2" stroke="currentColor" />';clearBtn.classList.add("clear");clearBtn.setAttribute("data-semantic-forms-clear","");// (what marks it as a clear button, whatever its title says)
137
+ clearBtn.id=`semanticFormsClearButton_${input.id}`;clearBtn.addEventListener("click",()=>{input.previousValue=input.value;input.value="";input.focus();lastClearFieldPressed=input.id;
138
+ // the field has been changed, as typing in it and leaving it would change it, so it says so the same way
139
+ input.dispatchEvent(new Event("input",{bubbles:true}));input.dispatchEvent(new Event("change",{bubbles:true}))});insertAfter(clearBtn,dd.querySelector("label"))}input.addEventListener("focus",event=>{if(event.target.nodeName==="INPUT")lastFocusedInput=event.target});
121
140
  // the colspan- and col- utility classes are documented as going on the dd, but they size and place the grid item, which is the div wrapping it, so move any of them across
122
141
  for(const utility of dd.className.match(/colspan-(?:[0-9]|full)|col-[0-9]/g)||[]){dd.classList.remove(utility);div.classList.add(utility)}
123
142
  // check for max-content attribute
@@ -133,9 +152,22 @@ if(dt.style.display==="none"&&dd.style.display==="none")div.style.display="none"
133
152
  // handle file input clear btn, cannot be handled with CSS
134
153
  if(type==="file"){const clearBtn=input.parentElement.querySelector(".clear");input.addEventListener("input",event=>{clearBtn.style.display=event.target.files.length?"flex":"none"});clearBtn.addEventListener("click",()=>{clearBtn.style.display="none"})}
135
154
  // handle range inputs set to display the value. every other per-field flag in the library is a data attribute, so that is the documented way to ask for this, but the original `displayValue` class is still honored
136
- if(type==="range"&&(input.getAttribute("data-display-value")!==null||input.classList.contains("displayValue"))){const label=input.parentNode.parentNode.querySelector("dd label");label.innerHTML+=`<span class="seperator">: </span><output>${input.value}</output>`;input.addEventListener("input",event=>{const output=event.target.parentNode.parentNode.querySelector("output");output.innerHTML=event.target.value})}
155
+ if(type==="range"&&(input.getAttribute("data-display-value")!==null||input.classList.contains("displayValue")))displayRangeValue(input,input.parentNode.parentNode.querySelector("dd label"));
137
156
  // show password button
138
- if(type==="password"&&input.getAttribute("data-no-reveal")===null){const showBtn=document.createElement("button");showBtn.type="button";showBtn.title=input.getAttribute("data-show-password-text")||"Show password";showBtn.ariaLabel=input.getAttribute("data-show-password-text")||"Show password";showBtn.tabIndex=-1;showBtn.innerHTML=icons.passwordShow;showBtn.classList.add("show");showBtn.id=`semanticFormsShowButton_${input.id}`;const dd=input.closest("dd");if(!dd){console.error(`semantic-forms: Found an input (${input.id||input.getAttribute("name")}) that is not inside a <dd> element.`);return}showBtn.addEventListener("click",()=>{if(input.type==="password"){showBtn.innerHTML=icons.passwordHide;showBtn.title=input.getAttribute("data-hide-password-text")||"Hide password";showBtn.ariaLabel=input.getAttribute("data-hide-password-text")||"Hide password";input.type="text"}else{showBtn.innerHTML=icons.passwordShow;showBtn.title=input.getAttribute("data-show-password-text")||"Show password";showBtn.ariaLabel=input.getAttribute("data-show-password-text")||"Show password";input.type="password"}input.focus()});insertAfter(showBtn,dd.querySelector("label"))}enhanceControl(input,type,form)};const handleUndoRedo=event=>{
157
+ if(type==="password"&&input.getAttribute("data-no-reveal")===null){const showBtn=document.createElement("button");showBtn.type="button";showBtn.title=input.getAttribute("data-show-password-text")||"Show password";showBtn.ariaLabel=input.getAttribute("data-show-password-text")||"Show password";showBtn.tabIndex=-1;showBtn.innerHTML=icons.passwordShow;showBtn.classList.add("show");showBtn.id=`semanticFormsShowButton_${input.id}`;const dd=input.closest("dd");if(!dd){console.error(`semantic-forms: Found an input (${input.id||input.getAttribute("name")}) that is not inside a <dd> element.`);return}showBtn.addEventListener("click",()=>{if(input.type==="password"){showBtn.innerHTML=icons.passwordHide;showBtn.title=input.getAttribute("data-hide-password-text")||"Hide password";showBtn.ariaLabel=input.getAttribute("data-hide-password-text")||"Hide password";input.type="text"}else{showBtn.innerHTML=icons.passwordShow;showBtn.title=input.getAttribute("data-show-password-text")||"Show password";showBtn.ariaLabel=input.getAttribute("data-show-password-text")||"Show password";input.type="password"}input.focus()});insertAfter(showBtn,dd.querySelector("label"))}enhanceControl(input,type,form)};
158
+ // appends a help icon or a required asterisk to a label, with its title set as text, so a title holding quotes or markup is shown as it is rather than breaking the label
159
+ const appendBadge=(label,className,title,content)=>{const badge=document.createElement("span");badge.className=className;badge.title=title;badge.innerHTML=content;// (the library's own icon, or an asterisk)
160
+ label.append(" ",badge)};
161
+ // shows a range's value as it moves, formatted by its data-display-format attribute, in which {value} stands for the value, such as "{value}%"
162
+
163
+ // in a float label form the value goes after the label; in a customLayout element, where nothing is added around a field, it goes in the <output> for the range, if the page has one
164
+ const displayRangeValue=(input,label)=>{const format=()=>(input.getAttribute("data-display-format")||"{value}").replaceAll("{value}",input.value);let output;if(label){const separator=document.createElement("span");separator.className="seperator";separator.textContent=": ";output=document.createElement("output");label.append(separator,output)}else{output=input.getRootNode().querySelector(`output[for="${window.CSS.escape(input.id)}"]`);if(!output)return}output.textContent=format();input.addEventListener("input",()=>{output.textContent=format()})};
165
+ // marks a field invalid, which the stylesheet outlines, with a message saying why, which screen readers read along with the field. options.messageIn is the element to put the message in; by default it goes after the field, where the stylesheet shows it
166
+
167
+ // calling it again replaces the message, and clearInvalid undoes it
168
+ const setInvalid=(input,message,options={})=>{input.classList.add("invalid");input.setAttribute("aria-invalid","true");const id=`${input.id||"semanticFormsField"}SemanticFormsInvalid`;let text=input.getRootNode().getElementById?.(id)||document.getElementById(id);if(!text){text=document.createElement("p");text.id=id;text.className="semanticFormsInvalidText";if(options.messageIn)options.messageIn.append(text);else input.parentNode.append(text)}text.textContent=message;const describedBy=(input.getAttribute("aria-describedby")||"").split(" ").filter(token=>token&&token!==id);input.setAttribute("aria-describedby",[...describedBy,id].join(" "))};const clearInvalid=input=>{input.classList.remove("invalid");input.removeAttribute("aria-invalid");const id=`${input.id||"semanticFormsField"}SemanticFormsInvalid`;const text=input.getRootNode().getElementById?.(id)||document.getElementById(id);text?.remove();const describedBy=(input.getAttribute("aria-describedby")||"").split(" ").filter(token=>token&&token!==id);if(describedBy.length)input.setAttribute("aria-describedby",describedBy.join(" "));else input.removeAttribute("aria-describedby");
169
+ // the field may still be one the browser considers invalid, in which case the stylesheet is still outlining it and aria-invalid goes back to saying so
170
+ syncAriaInvalid(input)};const handleUndoRedo=event=>{
139
171
  // handle undo/redo
140
172
  if((event.ctrlKey||event.metaKey)&&event.key==="z"&&!event.shiftKey){
141
173
  // undo clearing a field
@@ -145,7 +177,7 @@ event.preventDefault();lastFocusedInput.redoValue=lastFocusedInput.value;lastFoc
145
177
  // redo clearing a field
146
178
  if(lastFocusedInput)if(lastFocusedInput?.parentNode?.querySelector("button.clear")?.id===`semanticFormsClearButton_${lastClearFieldPressed}`||lastFocusedInput?.parentNode?.querySelector("button.clear")?.name===`semanticFormsClearButton_${lastClearFieldPressed}`)if(lastFocusedInput.redoValue){
147
179
  // as above, the browser's own redo would otherwise apply on top of this
148
- event.preventDefault();lastFocusedInput.previousValue=lastFocusedInput.value;lastFocusedInput.value=lastFocusedInput.redoValue}};module.exports={enhanceInput,handleUndoRedo}
180
+ event.preventDefault();lastFocusedInput.previousValue=lastFocusedInput.value;lastFocusedInput.value=lastFocusedInput.redoValue}};module.exports={enhanceInput,handleUndoRedo,setInvalid,clearInvalid}
149
181
  /***/},
150
182
  /***/"./lib/keyboardShortcuts.js"(module,__unused_webpack_exports,__webpack_require__){const{getOS,insertAfter}=__webpack_require__("./lib/helpers.js");const specialCharMap={Minus:"-",Equal:"=",BracketLeft:"[",BracketRight:"]",Backslash:"\\",Semicolon:";",Quote:"'",Comma:",",Period:".",Slash:"/",Backquote:"`"};const shiftSpecialCharMap={1:"!",2:"@",3:"#",4:"$",5:"%",6:"^",7:"&",8:"*",9:"(",0:")",Minus:"_",Equal:"+",BracketLeft:"{",BracketRight:"}",Backslash:"|",Semicolon:":",Quote:'"',Comma:"<",Period:">",Slash:"?",Backquote:"~"};
151
183
  // handles keyboard shortcut events
@@ -186,24 +218,28 @@ if(input.getAttribute("title"))input.setAttribute("title",input.getAttribute("ti
186
218
 
187
219
  // the tab that opens first is the one whose fieldset carries `data-selected`, or the first fieldset when none do
188
220
 
221
+ // adding the `vertical` class to the group puts the tabs in a column beside the panels, and the up and down arrow keys move between them in place of left and right
222
+
189
223
  // form: form element to search for tab groups
190
224
  const enhanceTabs=form=>{for(const group of form.querySelectorAll(".tabs:not(.semanticFormsTabsActive)")){const panels=Array.from(group.children).filter(child=>child.nodeName==="FIELDSET");
191
225
  // one fieldset is not a set of tabs, and no fieldsets means the class is on the wrong element
192
- if(panels.length<2){if(panels.length===0)console.error("semantic-forms: Found a .tabs element with no <fieldset> children. Each tab needs to be a <fieldset> with a <legend> naming it.",group);continue}group.classList.add("semanticFormsTabsActive");const groupId=++tabGroupCount;const tabList=document.createElement("div");const tabs=[];tabList.classList.add("tabList");tabList.setAttribute("role","tablist");
226
+ if(panels.length<2){if(panels.length===0)console.error("semantic-forms: Found a .tabs element with no <fieldset> children. Each tab needs to be a <fieldset> with a <legend> naming it.",group);continue}group.classList.add("semanticFormsTabsActive");const groupId=++tabGroupCount;const vertical=group.classList.contains("vertical");const tabList=document.createElement("div");const tabs=[];tabList.classList.add("tabList");tabList.setAttribute("role","tablist");tabList.setAttribute("aria-orientation",vertical?"vertical":"horizontal");
193
227
  // shows one panel and marks its tab as the selected one
194
228
  const selectTab=(index,moveFocus)=>{for(const[i,panel]of panels.entries())panel.hidden=i!==index;for(const[i,tab]of tabs.entries()){const selected=i===index;tab.setAttribute("aria-selected",selected?"true":"false");
195
229
  // only the selected tab is in the tab order; the arrow keys reach the others
196
230
  tab.tabIndex=selected?0:-1}if(moveFocus)tabs[index].focus()};for(const[index,panel]of panels.entries()){const legend=panel.querySelector("legend");const tab=document.createElement("button");tab.type="button";tab.setAttribute("role","tab");tab.id=`semanticFormsTab_${groupId}_${index}`;tab.textContent=legend?legend.textContent:`Tab ${index+1}`;if(!panel.id)panel.id=`semanticFormsTabPanel_${groupId}_${index}`;panel.setAttribute("role","tabpanel");panel.setAttribute("aria-labelledby",tab.id);tab.setAttribute("aria-controls",panel.id);
197
231
  // the tab now names the panel, so the legend would be read out twice
198
232
  if(legend)legend.hidden=true;tab.addEventListener("click",()=>selectTab(index));tabs.push(tab);tabList.append(tab)}
199
- // the arrow keys move between tabs, which is what a tablist is expected to do
200
- tabList.addEventListener("keydown",event=>{const current=tabs.indexOf(document.activeElement);if(current===-1)return;const keys={ArrowRight:(current+1)%tabs.length,ArrowLeft:(current-1+tabs.length)%tabs.length,Home:0,End:tabs.length-1};if(!(event.key in keys))return;event.preventDefault();selectTab(keys[event.key],true)});
233
+ // the arrow keys along the strip move between tabs, which is what a tablist is expected to do
234
+ const nextKey=vertical?"ArrowDown":"ArrowRight";const previousKey=vertical?"ArrowUp":"ArrowLeft";tabList.addEventListener("keydown",event=>{const current=tabs.indexOf(document.activeElement);if(current===-1)return;const keys={[nextKey]:(current+1)%tabs.length,[previousKey]:(current-1+tabs.length)%tabs.length,Home:0,End:tabs.length-1};if(!(event.key in keys))return;event.preventDefault();selectTab(keys[event.key],true)});
201
235
  // the panel carrying [data-selected] is the one that opens, defaulting to the first. without javascript every panel is on the page at once, so the attribute only means anything once the tabs have been built
202
236
  const marked=panels.filter(panel=>panel.hasAttribute("data-selected"));if(marked.length>1)console.error('semantic-forms: Found more than one <fieldset> with a "data-selected" attribute in a tab group. Only the first one will be selected.',group);group.prepend(tabList);selectTab(marked.length?panels.indexOf(marked[0]):0)}};module.exports={enhanceTabs}
203
237
  /***/},
204
- /***/"./semanticForms.js"(module,__unused_webpack_exports,__webpack_require__){const{createKeyboardShortcut,shortcutListener}=__webpack_require__("./lib/keyboardShortcuts.js");const{enhanceInput,handleUndoRedo}=__webpack_require__("./lib/inputEnhancements.js");const{enhanceTabs}=__webpack_require__("./lib/tabs.js");const{setInkOffset}=__webpack_require__("./lib/helpers.js");
238
+ /***/"./semanticForms.js"(module,__unused_webpack_exports,__webpack_require__){const{createKeyboardShortcut,shortcutListener}=__webpack_require__("./lib/keyboardShortcuts.js");const{enhanceInput,handleUndoRedo,setInvalid,clearInvalid}=__webpack_require__("./lib/inputEnhancements.js");const{enhanceTabs}=__webpack_require__("./lib/tabs.js");const{setInkOffset}=__webpack_require__("./lib/helpers.js");
205
239
  // one observer per tree that has been handed to semanticForms, so that a shadow root gets its own without replacing the document's
206
240
  const observers=new WeakMap;
241
+ // the keyboard shortcuts every form has asked for, kept in one list with one listener for them all, since semanticForms runs again for every form added to the page. a shortcut whose field has left the page is dropped
242
+ const keyboardShortcuts=[];let listeningForShortcuts=false;const pruneShortcuts=()=>{for(let i=keyboardShortcuts.length-1;i>=0;i--)if(!keyboardShortcuts[i].input.isConnected)keyboardShortcuts.splice(i,1)};
207
243
  // progressively enhances every semanticForms form in a tree
208
244
 
209
245
  // root: document or shadow root to search; defaults to the main document
@@ -211,7 +247,7 @@ const semanticForms=(root=document)=>{
211
247
  // do some feature detection so none of the JS executes if the browser is too old
212
248
  if(typeof document.getElementsByClassName!=="function"||typeof document.querySelector!=="function"||!document.body.classList||!window.MutationObserver){console.warn("semantic-forms was loaded into an unsupported browser and will not execute.");return}
213
249
  // custom keyboard shortcut listener
214
- const keyboardShortcuts=[];document.addEventListener("keydown",e=>shortcutListener(e,keyboardShortcuts));
250
+ if(!listeningForShortcuts){document.addEventListener("keydown",e=>shortcutListener(e,keyboardShortcuts));listeningForShortcuts=true}pruneShortcuts();
215
251
  // progressively enhance form elements that have the semanticForms class
216
252
  const forms=root.querySelectorAll("form.semanticForms:not(.semanticFormsActive), table.semanticForms:not(.semanticFormsActive)");for(const form of forms){form.classList.add("semanticFormsActive");if(form.classList.contains("lowFlow"))continue;
217
253
  // how far this font's letters sit from the middle of their own line box, which the stylesheet subtracts wherever it centers text. it is measured per form rather than per field, so that a form holding nothing but buttons is corrected too
@@ -219,7 +255,7 @@ setInkOffset(form,form);
219
255
  // update each input in the semantic form
220
256
  const inputs=Array.from(form.querySelectorAll("input, textarea, select"));for(const input of inputs){enhanceInput(input,form);
221
257
  // handle keyboard shortcuts
222
- if(input.getAttribute("data-focus-key")!==null){const shortcut=createKeyboardShortcut(input,keyboardShortcuts);keyboardShortcuts.push(shortcut)}}
258
+ if(input.getAttribute("data-focus-key")!==null&&!keyboardShortcuts.some(shortcut=>shortcut.input===input)){const shortcut=createKeyboardShortcut(input,keyboardShortcuts);keyboardShortcuts.push(shortcut)}}
223
259
  // done after the inputs so that anything sizing itself measures while it is still on screen
224
260
  enhanceTabs(form)}
225
261
  // prevents multiple listeners
@@ -233,7 +269,9 @@ if(root===document)window.semanticFormsObserver=observer}semanticForms.reinitial
233
269
  // with no form given this just rescans for forms that are not active yet
234
270
  if(!form)return semanticForms(root);form.classList.remove("semanticFormsActive");
235
271
  // the form knows which tree it belongs to, so a form in a shadow root reinitializes there
236
- semanticForms(form.getRootNode())}};module.exports=semanticForms
272
+ semanticForms(form.getRootNode())}};
273
+ // marks a field invalid with a message saying why, or clears that: see the docs for setInvalid
274
+ semanticForms.setInvalid=setInvalid;semanticForms.clearInvalid=clearInvalid;module.exports=semanticForms
237
275
  /***/}
238
276
  /******/};
239
277
  /************************************************************************/