katalyst-tables 3.15.0 → 3.16.0

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: bd0d472acdcc2f9a6d38866cf22fed2ea5761e032694abd745ccb05050bfb710
4
- data.tar.gz: 7cdea7b6f28127bd7092f97cf3dd3c3c7c077721802269596261f34cfa0e1048
3
+ metadata.gz: '0038dc2eceb2be90bca6807f2fd9df44f4f176a6068702cadc5eea84e0eb33e1'
4
+ data.tar.gz: b734e6d489ee47bb5f85a47bbfebdd33168a0d4dcf2fde3ab5e2c11a093ab02b
5
5
  SHA512:
6
- metadata.gz: 4b444ae85b2fe77fec493be762e2293910b671ca058ecedb6d679edd08587198382439fe397b7d90fbc35285c05860f5e516dfd5100cc3a109badff67abb75d3
7
- data.tar.gz: 928a415dfdf4ad9bb1673cbf7f86a674c4e17dc78384f93dff281a9ca19a55e93b5e61c84d5324a93d1d62781707cc7c5350d2ff23df6031c50d5bf7f7b449f6
6
+ metadata.gz: bbc31ef8c9dd67bcac8e7b44845fdc824ec6c2242c4eeb321f4cf95e780033dce2c4faa092de7c89a34993ccea7bda8460f73de098f0608372844f7784874704
7
+ data.tar.gz: 0b4b24e3aceaa17b223e592d29f27cb769d6e2087248ba60ea42e61fed1bbcf3b319a07c146276896e04b0d8fa30fed8194dd78ff29773eecdfb45198c8f4d16
data/CHANGELOG.md CHANGED
@@ -1,6 +1,29 @@
1
+ ## [3.16.0]
2
+
3
+ * Selections can be described in action buttons, e.g. "Download 2 people" (#130)
4
+ * The form component is passed to the `table_selection_with` block and provides `selection_tag`, which renders the live selection count and model name for interpolation into `_html` translations
5
+ * `count_tag`, `singular_tag` and `plural_tag` render the individual parts, and can be used more than once
6
+ * The selection summary is translated with `katalyst.tables.selectable.form_component.summary_html`
7
+
1
8
  ## [3.15.0]
2
9
 
3
10
  * Date filters on datetime columns now match whole days in `Time.zone`, including the last day of a range (#169)
11
+ * Collection inputs containing NUL bytes are treated as invalid and match nothing, instead of raising database errors (#171)
12
+ * Applies to all collection types; values in `multiple` attributes are ignored individually
13
+ * Invalid input now matches nothing for attributes with a custom `scope:`, instead of calling the scope with `nil`
14
+ * Integer filters accept bigint values and leave range checks to the database column, instead of raising `ActiveModel::RangeError` for values beyond 4 bytes
15
+ * Out of range values match nothing, out of range upper bounds are unbounded, and out of range `multiple` values are ignored
16
+ * Values longer than 16 digits are no longer truncated when cast
17
+ * Float filters treat `NaN` as invalid input and match nothing
18
+ * Blank and invalid values in `multiple` integer, float, boolean and enum filters are ignored, instead of also matching rows where the column is `NULL`
19
+ * e.g. the hidden blank value submitted by Rails multiple selects
20
+ * Only blank values (e.g. `[""]`, or `category:[]` in a query) do not filter, and are not reported as filters
21
+ * Enum filters match nothing for unknown values, instead of matching rows where the column is `NULL`
22
+ * Labels and database values are both accepted, as in Active Record
23
+ * Unknown values alongside known values are ignored
24
+ * Attributes with a custom `scope:`, or on columns without a Rails enum, are unchanged
25
+ * `Collection::Filter` no longer changes the `param_key` of the collection's model (e.g. `Person.model_name.param_key`) when its `model_name` is read, e.g. by table components or `form_with(model: collection)`
26
+ * Previously, forms for that model would be rendered with the collection's param key (e.g. `filters[name]`) until the process restarted
4
27
 
5
28
  ## [3.14.0]
6
29
 
@@ -594,9 +594,13 @@ class SelectionFormController extends Controller {
594
594
 
595
595
  countValueChanged(count) {
596
596
  this.element.toggleAttribute("hidden", count === 0);
597
- this.countTarget.textContent = count;
598
- this.singularTarget.toggleAttribute("hidden", count !== 1);
599
- this.pluralTarget.toggleAttribute("hidden", count === 1);
597
+ this.countTargets.forEach((el) => (el.textContent = count));
598
+ this.singularTargets.forEach((el) =>
599
+ el.toggleAttribute("hidden", count !== 1),
600
+ );
601
+ this.pluralTargets.forEach((el) =>
602
+ el.toggleAttribute("hidden", count === 1),
603
+ );
600
604
  }
601
605
  }
602
606
 
@@ -594,9 +594,13 @@ class SelectionFormController extends Controller {
594
594
 
595
595
  countValueChanged(count) {
596
596
  this.element.toggleAttribute("hidden", count === 0);
597
- this.countTarget.textContent = count;
598
- this.singularTarget.toggleAttribute("hidden", count !== 1);
599
- this.pluralTarget.toggleAttribute("hidden", count === 1);
597
+ this.countTargets.forEach((el) => (el.textContent = count));
598
+ this.singularTargets.forEach((el) =>
599
+ el.toggleAttribute("hidden", count !== 1),
600
+ );
601
+ this.pluralTargets.forEach((el) =>
602
+ el.toggleAttribute("hidden", count === 1),
603
+ );
600
604
  }
601
605
  }
602
606
 
@@ -1,2 +1,2 @@
1
- import{Controller as t}from"@hotwired/stimulus";class e{constructor(t,e,s){this.cursorOffset=e.offsetY,this.initialPosition=e.target.offsetTop-t.offsetTop,this.targetId=s}updateCursor(t,e,s,i){this.listOffset=t.getBoundingClientRect().top;let n=s.clientY-this.listOffset-this.cursorOffset;this.#t(t,e,n,i)}updateScroll(t,e,s){const i=this.listOffset;this.listOffset=t.getBoundingClientRect().top;const n=i-this.listOffset,r=this.position+n;this.#t(t,e,r,s)}#t(t,e,s,i){s=Math.max(s,0),s=Math.min(s,t.offsetHeight-e.offsetHeight),this.position=s;i(s-this.initialPosition)}}class s extends t{static outlets=["tables--selection--form"];static values={params:Object,checked:Boolean};tablesSelectionFormOutletConnected(t){t.visible(this.id,!0),this.checkedValue=t.isSelected(this.id)}disconnect(){this.hasTablesSelectionFormOutlet&&this.tablesSelectionFormOutlet.visible(this.id,!1)}change(t){t.preventDefault(),this.checkedValue=this.tablesSelectionFormOutlet.toggle(this.id)}get id(){return this.paramsValue.id}paramsValueChanged(t,e){this.hasTablesSelectionFormOutlet&&(e.id!==t.id&&this.tablesSelectionFormOutlet.visible(e.id,!1),this.tablesSelectionFormOutlet.visible(t.id,!0),this.checkedValue=this.tablesSelectionFormOutlet.isSelected(t.id),this.update())}checkedValueChanged(){this.hasTablesSelectionFormOutlet&&(this.checkedValue=this.tablesSelectionFormOutlet.isSelected(this.id),this.update())}async update(){return this.updating||=Promise.resolve().then(()=>{this.#e(),delete this.updating}),this.updating}#e(){this.element.querySelector("input").checked=this.checkedValue,this.dispatch("select",{detail:{id:this.id,selected:this.checkedValue}})}}class i{constructor(){this.tokens=[],this.values=null}parse(t){const e=new h(t);for(;!e.isEos();){this.push(this.skipWhitespace(e));const t=this.takeTagged(e)||this.takeUntagged(e);if(!this.push(t))break}return this}push(t){return t&&(this.values?this.values.push(t):this.tokens.push(t)),!!t}skipWhitespace(t){if(t.scan(/\s+/))return new n(t.matched(),t.position)}takeUntagged(t){if(t.scan(/\S+/))return new o(t.matched(),t.position)}takeTagged(t){if(!t.scan(/(\w+(?:\.\w+)?)(:\s*)/))return;const e=t.valueAt(1),s=t.valueAt(2),i=this.takeArrayValue(t)||this.takeSingleValue(t)||new n;return new a(e,s,i,t.position)}takeArrayValue(t){if(!t.scan(/\[\s*/))return;const e=new n(t.matched(),t.position),s=this.values=[];for(;!t.isEos()&&this.push(this.takeSingleValue(t))&&this.push(this.takeDelimiter(t)););t.scan(/\s*]/);const i=new n(t.matched(),t.position);return this.values=null,new l(e,s,i)}takeDelimiter(t){if(t.scan(/\s*,\s*/))return new n(t.matched(),t.position)}takeSingleValue(t){return this.takeQuotedValue(t)||this.takeUnquotedValue(t)}takeQuotedValue(t){if(t.scan(/"([^"]*)"/))return new r(t.matched(),t.position)}takeUnquotedValue(t){if(t.scan(/[^ \],]*/))return new r(t.matched(),t.position)}tokenAtPosition(t){return this.tokens.filter(t=>t instanceof a||t instanceof o).find(e=>e.range.includes(t))}}class n{constructor(t="",e){this.value=t,this.length=this.value.length,this.start=e-this.length,this.end=this.start+this.length,this.range=this.arrayRange(this.start,this.end)}render(){return document.createTextNode(this.value)}arrayRange(t,e){return Array.from({length:e-t+1},(e,s)=>t+s)}startOfValue(){return this.start}endOfValue(){return this.end}}class r extends n{render(){const t=document.createElement("span");return t.className="value",t.innerText=this.value,t}}class a extends n{constructor(t,e,s,i){super(),this.key=t,this.separator=e,this.value=s,this.length=t.length+e.length+s.value.length,this.start=i-this.length,this.end=this.start+this.length,this.range=this.arrayRange(this.start,this.end)}render(){const t=document.createElement("span");t.className="tag";const e=document.createElement("span");return e.className="key",e.innerText=this.key,t.appendChild(e),t.appendChild(document.createTextNode(this.separator)),t.appendChild(this.value.render()),t}startOfValue(){return this.value.startOfValue()}endOfValue(){return this.value.endOfValue()}}class o extends n{render(){const t=document.createElement("span");return t.className="untagged",t.innerText=this.value,t}}class l extends n{constructor(t,e,s){super(),this.start=t,this.values=e,this.end=s,this.range=this.arrayRange(t.start,s.range[s.length]),this.length=t.length+e.reduce((t,e)=>t+e.length,0)+s.length}render(){const t=document.createElement("span");return t.className="array-values",t.appendChild(this.start.render()),this.values.forEach(e=>{const s=document.createElement("span");s.appendChild(e.render()),t.appendChild(s)}),t.appendChild(this.end.render()),t}startOfValue(){return this.start.start}endOfValue(){return this.end.end}}class h{constructor(t){this.input=t,this.position=0,this.last=null}isEos(){return this.position>=this.input.length}scan(t){const e=t.exec(this.input.substring(this.position));return 0===e?.index?(this.last=e,this.position+=e[0].length,!0):(this.last={},!1)}matched(){return this.last&&this.last[0]}valueAt(t){return this.last&&this.last[t]}}const u=[{identifier:"tables--orderable--item",controllerConstructor:class extends t{static values={params:Object};connect(){var t;this.index=(t=this.row,Array.from(t.parentElement.children).indexOf(t))}paramsValueChanged(t){this.id=t.id_value}dragUpdate(t){this.dragOffset=t,this.row.style.position="relative",this.row.style.transform=`scale(1.01) translateY(${t}px)`,this.row.style.zIndex="1",this.row.toggleAttribute("dragging",!0)}updateVisually(t){this.row.style.transform=`translateY(${t-this.#s}px)`}captureDropPosition(){this.dropTop=this.#i}invertDropPosition(){delete this.dragOffset,this.row.removeAttribute("dragging"),this.row.style.transition="transform 0s",this.row.style.transform="",this.row.style.transform=`translateY(${this.dropTop-this.#i}px)`}playDrop(){this.row.style.transition="",this.row.style.transform=""}updateIndex(t){this.index=t}params(t){const{id_name:e,id_value:s,index_name:i}=this.paramsValue;return[{name:`${t}[${s}][${e}]`,value:this.id},{name:`${t}[${s}][${i}]`,value:this.index}]}reset(){delete this.dragOffset,delete this.dropTop,this.row.removeAttribute("style"),this.row.removeAttribute("dragging")}get hasChanges(){return this.paramsValue.index_value!==this.index}get dragPosition(){return this.dragOffset&&0!==this.dragOffset?this.#n:this.#r}get row(){return this.element.parentElement}get height(){return this.row.offsetHeight}get#r(){return this.#s+this.height/2}get#n(){const t=this.#s+this.dragOffset;return this.dragOffset<0?t:t+this.height}get#s(){return this.row.offsetTop}get#i(){return this.row.getBoundingClientRect().top}}},{identifier:"tables--orderable--list",controllerConstructor:class extends t{static outlets=["tables--orderable--item","tables--orderable--form"];static values={direction:{type:String,default:"asc"}};startDragging(t){this.dragState=t,document.addEventListener("mousemove",this.mousemove),document.addEventListener("mouseup",this.mouseup),window.addEventListener("scroll",this.scroll,!0),this.element.style.position="relative"}stopDragging({reset:t=!0}={}){const e=this.dragState;return delete this.dragState,document.removeEventListener("mousemove",this.mousemove),document.removeEventListener("mouseup",this.mouseup),window.removeEventListener("scroll",this.scroll,!0),this.element.removeAttribute("style"),t&&this.items.forEach(t=>t.reset()),e}drop(){const t=this.dragItem;if(!t)return;const e=this.items;e.forEach(t=>t.captureDropPosition()),this.#a(this.orderedItems,t),e.forEach(t=>t.invertDropPosition()),this.element.offsetHeight;const s=this.items.length;return this.items.forEach((t,e)=>{t.updateIndex("desc"===this.directionValue?s-1-e:e)}),this.commitChanges(),window.requestAnimationFrame(()=>{e.forEach(t=>t.playDrop()),window.setTimeout(()=>{e.forEach(t=>t.reset())},this.#o)}),!0}commitChanges(){this.tablesOrderableFormOutlet.clear(),this.items.forEach(t=>{t.hasChanges&&this.tablesOrderableFormOutlet.add(t)}),this.tablesOrderableFormOutlet.submit()}mousedown(t){if(this.isDragging)return;const s=this.#l(t.target);s&&(t.preventDefault(),this.startDragging(new e(this.element,t,s.id)),this.dragState.updateCursor(this.element,s.row,t,this.animate))}mousemove=t=>{this.isDragging&&(t.preventDefault(),this.ticking||(this.ticking=!0,window.requestAnimationFrame(()=>{this.ticking=!1,this.dragState?.updateCursor(this.element,this.dragItem.row,t,this.animate)})))};scroll=t=>{this.isDragging&&!this.ticking&&(this.ticking=!0,window.requestAnimationFrame(()=>{this.ticking=!1,this.dragState?.updateScroll(this.element,this.dragItem.row,this.animate)}))};mouseup=t=>{if(!this.isDragging)return;const e=this.drop();this.stopDragging({reset:!e}),this.items.forEach(t=>delete t.dragState)};tablesOrderableFormOutletConnected(t,e){t.dragState&&this.startDragging(t.dragState)}tablesOrderableFormOutletDisconnected(t,e){this.isDragging&&(t.dragState=this.stopDragging())}beforeMorphElement(t){this.isDragging&&t.preventDefault()}animate=t=>{const e=this.dragItem;e.dragUpdate(t);let s=0;this.orderedItems.forEach(t=>{t!==e&&t.updateVisually(s),s+=t.height})};get isDragging(){return!!this.dragState}get dragItem(){return this.isDragging?this.items.find(t=>t.id===this.dragState.targetId):null}get items(){return this.tablesOrderableItemOutlets.filter(t=>this.element.contains(t.element))}get orderedItems(){return this.dragItem?this.items.toSorted((t,e)=>t.dragPosition-e.dragPosition):this.items}#l(t){return this.items.find(e=>e.element===t)}#a(t,e){const s=t.indexOf(e),i=t[s-1],n=t[s+1];i?i.row.insertAdjacentElement("afterend",e.row):n&&n.row.insertAdjacentElement("beforebegin",e.row)}get#o(){const t=window.getComputedStyle(this.element).getPropertyValue("--animation-duration")||"150ms";return(e=(e=t).trim()).endsWith("ms")?parseFloat(e):e.endsWith("s")?1e3*parseFloat(e):parseFloat(e)||0;var e}}},{identifier:"tables--orderable--form",controllerConstructor:class extends t{static values={scope:String};add(t){t.params(this.scopeValue).forEach(({name:t,value:e})=>{this.element.insertAdjacentHTML("beforeend",`<input type="hidden" name="${t}" value="${e}" data-generated>`)})}submit(){0!==this.inputs.length&&this.element.requestSubmit()}clear(){this.inputs.forEach(t=>t.remove())}get inputs(){return this.element.querySelectorAll("input[data-generated]")}}},{identifier:"tables--selection--form",controllerConstructor:class extends t{static values={count:Number,primaryKey:{type:String,default:"id"}};static targets=["count","singular","plural"];connect(){this.countValue=this.inputs.length}toggle(t){const e=this.input(t);return e?e.remove():this.element.insertAdjacentHTML("beforeend",`<input type="hidden" name="${this.primaryKeyValue}[]" value="${t}">`),this.countValue=this.visibleInputs.length,!e}visible(t,e){const s=this.input(t);return s&&(s.disabled=!e),this.countValue=this.visibleInputs.length,!s}isSelected(t){return!!this.input(t)}get inputs(){return this.element.querySelectorAll(`input[name="${this.primaryKeyValue}[]"]`)}get visibleInputs(){return Array.from(this.inputs).filter(t=>!t.disabled)}input(t){return this.element.querySelector(`input[name="${this.primaryKeyValue}[]"][value="${t}"]`)}countValueChanged(t){this.element.toggleAttribute("hidden",0===t),this.countTarget.textContent=t,this.singularTarget.toggleAttribute("hidden",1!==t),this.pluralTarget.toggleAttribute("hidden",1===t)}}},{identifier:"tables--selection--item",controllerConstructor:s},{identifier:"tables--selection--table",controllerConstructor:class extends t{static targets=["header","item"];static outlets=["tables--selection--form"];itemTargetConnected(t){this.update()}itemTargetDisconnected(t){this.update()}toggleHeader(t){this.items.forEach(e=>{e.checkedValue!==t.target.checked&&(e.checkedValue=this.tablesSelectionFormOutlet.toggle(e.id))})}async update(){return this.updating||=Promise.resolve().then(()=>{this.#e(),delete this.updating}),this.updating}#e(){let t=0,e=0;this.items.forEach(s=>{t++,s.checkedValue&&e++}),this.headerInput.checked=t>0&&e===t,this.headerInput.indeterminate=e>0&&e!==t}get headerInput(){return this.headerTarget.querySelector("input")}get items(){return this.itemTargets.map(t=>this.#h(t)).filter(t=>t)}#h(t){return this.application.getControllerForElementAndIdentifier(t,"tables--selection--item")}}},{identifier:"tables--query",controllerConstructor:class extends t{static targets=["modal"];disconnect(){delete this.pending,document.removeEventListener("selectionchange",this.selection)}focus(){document.activeElement!==this.query&&(this.query.addEventListener("focusin",t=>{t.target.setSelectionRange(-1,-1)},{once:!0}),this.query.focus())}closeModal(){delete this.modalTarget.dataset.open,this.query.setAttribute("aria-expanded",!1),document.activeElement===this.query&&document.activeElement.blur(),document.removeEventListener("selectionchange",this.selection)}openModal(){this.modalTarget.dataset.open=!0,this.query.setAttribute("aria-expanded",!0),document.addEventListener("selectionchange",this.selection)}clear(){""===this.query.value?this.closeModal():(this.query.value="",this.query.dispatchEvent(new Event("input")),this.query.dispatchEvent(new Event("change")),this.update())}submit(){const t=this.isFocused,e=t&&this.query.selectionStart;this.pending&&(clearTimeout(this.pending),delete this.pending),t&&""!==this.query.value?(this.position.value=e,this.position.disabled=!1):(this.position.value="",this.position.disabled=!0),""===this.query.value&&(this.query.disabled=!0,setTimeout(()=>{this.query.disabled=!1,this.position.disabled=!1,t&&this.query.focus()},0))}update=()=>{this.pending&&clearTimeout(this.pending),this.pending=setTimeout(()=>{this.element.requestSubmit()},300)};selection=()=>{this.isFocused&&this.query.value.length>0&&this.update()};beforeMorphAttribute(t){if("data-open"===t.detail.attributeName)t.preventDefault()}moveToPreviousSuggestion(){const t=this.previousSuggestion||this.lastSuggestion;t&&this.makeSuggestionActive(t)}moveToNextSuggestion(){const t=this.nextSuggestion||this.firstSuggestion;t&&this.makeSuggestionActive(t)}selectFirstSuggestion(t){t.preventDefault(),this.firstSuggestion?.dispatchEvent(new CustomEvent("query:select"))}selectActiveSuggestion(){this.activeSuggestion?this.activeSuggestion.dispatchEvent(new CustomEvent("query:select")):this.closeModal()}selectSuggestion(t){this.query.dispatchEvent(new CustomEvent("replaceToken",{detail:{token:t.params.value,position:this.query.selectionStart}})),this.clearActiveSuggestion()}makeSuggestionActive(t){this.activeSuggestion&&this.activeSuggestion.setAttribute("aria-selected","false"),this.query.setAttribute("aria-activedescendant",t.id),t.setAttribute("aria-selected","true")}clearActiveSuggestion(){this.activeSuggestion&&(this.activeSuggestion.setAttribute("aria-selected","false"),this.query.removeAttribute("aria-activedescendant"))}get activeSuggestion(){return this.modalTarget.querySelector(`#${this.query.getAttribute("aria-activedescendant")}`)}get previousSuggestion(){return this.activeSuggestion?.previousElementSibling}get nextSuggestion(){return this.activeSuggestion?.nextElementSibling}get firstSuggestion(){return this.modalTarget.querySelector("#suggestions li:first-of-type")}get lastSuggestion(){return this.modalTarget.querySelector("#suggestions li:last-of-type")}get query(){return this.element.querySelector("[role=combobox]")}get position(){return this.element.querySelector("input[name=p]")}get isFocused(){return this.query===document.activeElement}}},{identifier:"tables--query-input",controllerConstructor:class extends t{static targets=["input","highlight"];static values={query:String};connect(){this.queryValue=this.inputTarget.value,this.element.dataset.connected=""}disconnect(){delete this.element.dataset.connected}update(){this.queryValue=this.inputTarget.value}queryValueChanged(t){this.highlightTarget.innerHTML="",(new i).parse(t).tokens.forEach(t=>{this.highlightTarget.appendChild(t.render())})}replaceToken(t){let e=t.detail.token.toString();/\s/.exec(e)&&(e=`"${e}"`);const s=t.detail.position;let n=s+e.length,r=s,a=s;const o=(new i).parse(this.queryValue).tokenAtPosition(s);o&&(e=e.trim(),r=o.startOfValue(),a=o.endOfValue(),n=r+e.length),this.inputTarget.value=this.queryValue.slice(0,r)+e+this.queryValue.slice(a),this.update(),this.inputTarget.focus(),this.inputTarget.setSelectionRange(n,n)}}}];export{u as default};
1
+ import{Controller as t}from"@hotwired/stimulus";class e{constructor(t,e,s){this.cursorOffset=e.offsetY,this.initialPosition=e.target.offsetTop-t.offsetTop,this.targetId=s}updateCursor(t,e,s,i){this.listOffset=t.getBoundingClientRect().top;let n=s.clientY-this.listOffset-this.cursorOffset;this.#t(t,e,n,i)}updateScroll(t,e,s){const i=this.listOffset;this.listOffset=t.getBoundingClientRect().top;const n=i-this.listOffset,r=this.position+n;this.#t(t,e,r,s)}#t(t,e,s,i){s=Math.max(s,0),s=Math.min(s,t.offsetHeight-e.offsetHeight),this.position=s;i(s-this.initialPosition)}}class s extends t{static outlets=["tables--selection--form"];static values={params:Object,checked:Boolean};tablesSelectionFormOutletConnected(t){t.visible(this.id,!0),this.checkedValue=t.isSelected(this.id)}disconnect(){this.hasTablesSelectionFormOutlet&&this.tablesSelectionFormOutlet.visible(this.id,!1)}change(t){t.preventDefault(),this.checkedValue=this.tablesSelectionFormOutlet.toggle(this.id)}get id(){return this.paramsValue.id}paramsValueChanged(t,e){this.hasTablesSelectionFormOutlet&&(e.id!==t.id&&this.tablesSelectionFormOutlet.visible(e.id,!1),this.tablesSelectionFormOutlet.visible(t.id,!0),this.checkedValue=this.tablesSelectionFormOutlet.isSelected(t.id),this.update())}checkedValueChanged(){this.hasTablesSelectionFormOutlet&&(this.checkedValue=this.tablesSelectionFormOutlet.isSelected(this.id),this.update())}async update(){return this.updating||=Promise.resolve().then(()=>{this.#e(),delete this.updating}),this.updating}#e(){this.element.querySelector("input").checked=this.checkedValue,this.dispatch("select",{detail:{id:this.id,selected:this.checkedValue}})}}class i{constructor(){this.tokens=[],this.values=null}parse(t){const e=new h(t);for(;!e.isEos();){this.push(this.skipWhitespace(e));const t=this.takeTagged(e)||this.takeUntagged(e);if(!this.push(t))break}return this}push(t){return t&&(this.values?this.values.push(t):this.tokens.push(t)),!!t}skipWhitespace(t){if(t.scan(/\s+/))return new n(t.matched(),t.position)}takeUntagged(t){if(t.scan(/\S+/))return new o(t.matched(),t.position)}takeTagged(t){if(!t.scan(/(\w+(?:\.\w+)?)(:\s*)/))return;const e=t.valueAt(1),s=t.valueAt(2),i=this.takeArrayValue(t)||this.takeSingleValue(t)||new n;return new a(e,s,i,t.position)}takeArrayValue(t){if(!t.scan(/\[\s*/))return;const e=new n(t.matched(),t.position),s=this.values=[];for(;!t.isEos()&&this.push(this.takeSingleValue(t))&&this.push(this.takeDelimiter(t)););t.scan(/\s*]/);const i=new n(t.matched(),t.position);return this.values=null,new l(e,s,i)}takeDelimiter(t){if(t.scan(/\s*,\s*/))return new n(t.matched(),t.position)}takeSingleValue(t){return this.takeQuotedValue(t)||this.takeUnquotedValue(t)}takeQuotedValue(t){if(t.scan(/"([^"]*)"/))return new r(t.matched(),t.position)}takeUnquotedValue(t){if(t.scan(/[^ \],]*/))return new r(t.matched(),t.position)}tokenAtPosition(t){return this.tokens.filter(t=>t instanceof a||t instanceof o).find(e=>e.range.includes(t))}}class n{constructor(t="",e){this.value=t,this.length=this.value.length,this.start=e-this.length,this.end=this.start+this.length,this.range=this.arrayRange(this.start,this.end)}render(){return document.createTextNode(this.value)}arrayRange(t,e){return Array.from({length:e-t+1},(e,s)=>t+s)}startOfValue(){return this.start}endOfValue(){return this.end}}class r extends n{render(){const t=document.createElement("span");return t.className="value",t.innerText=this.value,t}}class a extends n{constructor(t,e,s,i){super(),this.key=t,this.separator=e,this.value=s,this.length=t.length+e.length+s.value.length,this.start=i-this.length,this.end=this.start+this.length,this.range=this.arrayRange(this.start,this.end)}render(){const t=document.createElement("span");t.className="tag";const e=document.createElement("span");return e.className="key",e.innerText=this.key,t.appendChild(e),t.appendChild(document.createTextNode(this.separator)),t.appendChild(this.value.render()),t}startOfValue(){return this.value.startOfValue()}endOfValue(){return this.value.endOfValue()}}class o extends n{render(){const t=document.createElement("span");return t.className="untagged",t.innerText=this.value,t}}class l extends n{constructor(t,e,s){super(),this.start=t,this.values=e,this.end=s,this.range=this.arrayRange(t.start,s.range[s.length]),this.length=t.length+e.reduce((t,e)=>t+e.length,0)+s.length}render(){const t=document.createElement("span");return t.className="array-values",t.appendChild(this.start.render()),this.values.forEach(e=>{const s=document.createElement("span");s.appendChild(e.render()),t.appendChild(s)}),t.appendChild(this.end.render()),t}startOfValue(){return this.start.start}endOfValue(){return this.end.end}}class h{constructor(t){this.input=t,this.position=0,this.last=null}isEos(){return this.position>=this.input.length}scan(t){const e=t.exec(this.input.substring(this.position));return 0===e?.index?(this.last=e,this.position+=e[0].length,!0):(this.last={},!1)}matched(){return this.last&&this.last[0]}valueAt(t){return this.last&&this.last[t]}}const u=[{identifier:"tables--orderable--item",controllerConstructor:class extends t{static values={params:Object};connect(){var t;this.index=(t=this.row,Array.from(t.parentElement.children).indexOf(t))}paramsValueChanged(t){this.id=t.id_value}dragUpdate(t){this.dragOffset=t,this.row.style.position="relative",this.row.style.transform=`scale(1.01) translateY(${t}px)`,this.row.style.zIndex="1",this.row.toggleAttribute("dragging",!0)}updateVisually(t){this.row.style.transform=`translateY(${t-this.#s}px)`}captureDropPosition(){this.dropTop=this.#i}invertDropPosition(){delete this.dragOffset,this.row.removeAttribute("dragging"),this.row.style.transition="transform 0s",this.row.style.transform="",this.row.style.transform=`translateY(${this.dropTop-this.#i}px)`}playDrop(){this.row.style.transition="",this.row.style.transform=""}updateIndex(t){this.index=t}params(t){const{id_name:e,id_value:s,index_name:i}=this.paramsValue;return[{name:`${t}[${s}][${e}]`,value:this.id},{name:`${t}[${s}][${i}]`,value:this.index}]}reset(){delete this.dragOffset,delete this.dropTop,this.row.removeAttribute("style"),this.row.removeAttribute("dragging")}get hasChanges(){return this.paramsValue.index_value!==this.index}get dragPosition(){return this.dragOffset&&0!==this.dragOffset?this.#n:this.#r}get row(){return this.element.parentElement}get height(){return this.row.offsetHeight}get#r(){return this.#s+this.height/2}get#n(){const t=this.#s+this.dragOffset;return this.dragOffset<0?t:t+this.height}get#s(){return this.row.offsetTop}get#i(){return this.row.getBoundingClientRect().top}}},{identifier:"tables--orderable--list",controllerConstructor:class extends t{static outlets=["tables--orderable--item","tables--orderable--form"];static values={direction:{type:String,default:"asc"}};startDragging(t){this.dragState=t,document.addEventListener("mousemove",this.mousemove),document.addEventListener("mouseup",this.mouseup),window.addEventListener("scroll",this.scroll,!0),this.element.style.position="relative"}stopDragging({reset:t=!0}={}){const e=this.dragState;return delete this.dragState,document.removeEventListener("mousemove",this.mousemove),document.removeEventListener("mouseup",this.mouseup),window.removeEventListener("scroll",this.scroll,!0),this.element.removeAttribute("style"),t&&this.items.forEach(t=>t.reset()),e}drop(){const t=this.dragItem;if(!t)return;const e=this.items;e.forEach(t=>t.captureDropPosition()),this.#a(this.orderedItems,t),e.forEach(t=>t.invertDropPosition()),this.element.offsetHeight;const s=this.items.length;return this.items.forEach((t,e)=>{t.updateIndex("desc"===this.directionValue?s-1-e:e)}),this.commitChanges(),window.requestAnimationFrame(()=>{e.forEach(t=>t.playDrop()),window.setTimeout(()=>{e.forEach(t=>t.reset())},this.#o)}),!0}commitChanges(){this.tablesOrderableFormOutlet.clear(),this.items.forEach(t=>{t.hasChanges&&this.tablesOrderableFormOutlet.add(t)}),this.tablesOrderableFormOutlet.submit()}mousedown(t){if(this.isDragging)return;const s=this.#l(t.target);s&&(t.preventDefault(),this.startDragging(new e(this.element,t,s.id)),this.dragState.updateCursor(this.element,s.row,t,this.animate))}mousemove=t=>{this.isDragging&&(t.preventDefault(),this.ticking||(this.ticking=!0,window.requestAnimationFrame(()=>{this.ticking=!1,this.dragState?.updateCursor(this.element,this.dragItem.row,t,this.animate)})))};scroll=t=>{this.isDragging&&!this.ticking&&(this.ticking=!0,window.requestAnimationFrame(()=>{this.ticking=!1,this.dragState?.updateScroll(this.element,this.dragItem.row,this.animate)}))};mouseup=t=>{if(!this.isDragging)return;const e=this.drop();this.stopDragging({reset:!e}),this.items.forEach(t=>delete t.dragState)};tablesOrderableFormOutletConnected(t,e){t.dragState&&this.startDragging(t.dragState)}tablesOrderableFormOutletDisconnected(t,e){this.isDragging&&(t.dragState=this.stopDragging())}beforeMorphElement(t){this.isDragging&&t.preventDefault()}animate=t=>{const e=this.dragItem;e.dragUpdate(t);let s=0;this.orderedItems.forEach(t=>{t!==e&&t.updateVisually(s),s+=t.height})};get isDragging(){return!!this.dragState}get dragItem(){return this.isDragging?this.items.find(t=>t.id===this.dragState.targetId):null}get items(){return this.tablesOrderableItemOutlets.filter(t=>this.element.contains(t.element))}get orderedItems(){return this.dragItem?this.items.toSorted((t,e)=>t.dragPosition-e.dragPosition):this.items}#l(t){return this.items.find(e=>e.element===t)}#a(t,e){const s=t.indexOf(e),i=t[s-1],n=t[s+1];i?i.row.insertAdjacentElement("afterend",e.row):n&&n.row.insertAdjacentElement("beforebegin",e.row)}get#o(){const t=window.getComputedStyle(this.element).getPropertyValue("--animation-duration")||"150ms";return(e=(e=t).trim()).endsWith("ms")?parseFloat(e):e.endsWith("s")?1e3*parseFloat(e):parseFloat(e)||0;var e}}},{identifier:"tables--orderable--form",controllerConstructor:class extends t{static values={scope:String};add(t){t.params(this.scopeValue).forEach(({name:t,value:e})=>{this.element.insertAdjacentHTML("beforeend",`<input type="hidden" name="${t}" value="${e}" data-generated>`)})}submit(){0!==this.inputs.length&&this.element.requestSubmit()}clear(){this.inputs.forEach(t=>t.remove())}get inputs(){return this.element.querySelectorAll("input[data-generated]")}}},{identifier:"tables--selection--form",controllerConstructor:class extends t{static values={count:Number,primaryKey:{type:String,default:"id"}};static targets=["count","singular","plural"];connect(){this.countValue=this.inputs.length}toggle(t){const e=this.input(t);return e?e.remove():this.element.insertAdjacentHTML("beforeend",`<input type="hidden" name="${this.primaryKeyValue}[]" value="${t}">`),this.countValue=this.visibleInputs.length,!e}visible(t,e){const s=this.input(t);return s&&(s.disabled=!e),this.countValue=this.visibleInputs.length,!s}isSelected(t){return!!this.input(t)}get inputs(){return this.element.querySelectorAll(`input[name="${this.primaryKeyValue}[]"]`)}get visibleInputs(){return Array.from(this.inputs).filter(t=>!t.disabled)}input(t){return this.element.querySelector(`input[name="${this.primaryKeyValue}[]"][value="${t}"]`)}countValueChanged(t){this.element.toggleAttribute("hidden",0===t),this.countTargets.forEach(e=>e.textContent=t),this.singularTargets.forEach(e=>e.toggleAttribute("hidden",1!==t)),this.pluralTargets.forEach(e=>e.toggleAttribute("hidden",1===t))}}},{identifier:"tables--selection--item",controllerConstructor:s},{identifier:"tables--selection--table",controllerConstructor:class extends t{static targets=["header","item"];static outlets=["tables--selection--form"];itemTargetConnected(t){this.update()}itemTargetDisconnected(t){this.update()}toggleHeader(t){this.items.forEach(e=>{e.checkedValue!==t.target.checked&&(e.checkedValue=this.tablesSelectionFormOutlet.toggle(e.id))})}async update(){return this.updating||=Promise.resolve().then(()=>{this.#e(),delete this.updating}),this.updating}#e(){let t=0,e=0;this.items.forEach(s=>{t++,s.checkedValue&&e++}),this.headerInput.checked=t>0&&e===t,this.headerInput.indeterminate=e>0&&e!==t}get headerInput(){return this.headerTarget.querySelector("input")}get items(){return this.itemTargets.map(t=>this.#h(t)).filter(t=>t)}#h(t){return this.application.getControllerForElementAndIdentifier(t,"tables--selection--item")}}},{identifier:"tables--query",controllerConstructor:class extends t{static targets=["modal"];disconnect(){delete this.pending,document.removeEventListener("selectionchange",this.selection)}focus(){document.activeElement!==this.query&&(this.query.addEventListener("focusin",t=>{t.target.setSelectionRange(-1,-1)},{once:!0}),this.query.focus())}closeModal(){delete this.modalTarget.dataset.open,this.query.setAttribute("aria-expanded",!1),document.activeElement===this.query&&document.activeElement.blur(),document.removeEventListener("selectionchange",this.selection)}openModal(){this.modalTarget.dataset.open=!0,this.query.setAttribute("aria-expanded",!0),document.addEventListener("selectionchange",this.selection)}clear(){""===this.query.value?this.closeModal():(this.query.value="",this.query.dispatchEvent(new Event("input")),this.query.dispatchEvent(new Event("change")),this.update())}submit(){const t=this.isFocused,e=t&&this.query.selectionStart;this.pending&&(clearTimeout(this.pending),delete this.pending),t&&""!==this.query.value?(this.position.value=e,this.position.disabled=!1):(this.position.value="",this.position.disabled=!0),""===this.query.value&&(this.query.disabled=!0,setTimeout(()=>{this.query.disabled=!1,this.position.disabled=!1,t&&this.query.focus()},0))}update=()=>{this.pending&&clearTimeout(this.pending),this.pending=setTimeout(()=>{this.element.requestSubmit()},300)};selection=()=>{this.isFocused&&this.query.value.length>0&&this.update()};beforeMorphAttribute(t){if("data-open"===t.detail.attributeName)t.preventDefault()}moveToPreviousSuggestion(){const t=this.previousSuggestion||this.lastSuggestion;t&&this.makeSuggestionActive(t)}moveToNextSuggestion(){const t=this.nextSuggestion||this.firstSuggestion;t&&this.makeSuggestionActive(t)}selectFirstSuggestion(t){t.preventDefault(),this.firstSuggestion?.dispatchEvent(new CustomEvent("query:select"))}selectActiveSuggestion(){this.activeSuggestion?this.activeSuggestion.dispatchEvent(new CustomEvent("query:select")):this.closeModal()}selectSuggestion(t){this.query.dispatchEvent(new CustomEvent("replaceToken",{detail:{token:t.params.value,position:this.query.selectionStart}})),this.clearActiveSuggestion()}makeSuggestionActive(t){this.activeSuggestion&&this.activeSuggestion.setAttribute("aria-selected","false"),this.query.setAttribute("aria-activedescendant",t.id),t.setAttribute("aria-selected","true")}clearActiveSuggestion(){this.activeSuggestion&&(this.activeSuggestion.setAttribute("aria-selected","false"),this.query.removeAttribute("aria-activedescendant"))}get activeSuggestion(){return this.modalTarget.querySelector(`#${this.query.getAttribute("aria-activedescendant")}`)}get previousSuggestion(){return this.activeSuggestion?.previousElementSibling}get nextSuggestion(){return this.activeSuggestion?.nextElementSibling}get firstSuggestion(){return this.modalTarget.querySelector("#suggestions li:first-of-type")}get lastSuggestion(){return this.modalTarget.querySelector("#suggestions li:last-of-type")}get query(){return this.element.querySelector("[role=combobox]")}get position(){return this.element.querySelector("input[name=p]")}get isFocused(){return this.query===document.activeElement}}},{identifier:"tables--query-input",controllerConstructor:class extends t{static targets=["input","highlight"];static values={query:String};connect(){this.queryValue=this.inputTarget.value,this.element.dataset.connected=""}disconnect(){delete this.element.dataset.connected}update(){this.queryValue=this.inputTarget.value}queryValueChanged(t){this.highlightTarget.innerHTML="",(new i).parse(t).tokens.forEach(t=>{this.highlightTarget.appendChild(t.render())})}replaceToken(t){let e=t.detail.token.toString();/\s/.exec(e)&&(e=`"${e}"`);const s=t.detail.position;let n=s+e.length,r=s,a=s;const o=(new i).parse(this.queryValue).tokenAtPosition(s);o&&(e=e.trim(),r=o.startOfValue(),a=o.endOfValue(),n=r+e.length),this.inputTarget.value=this.queryValue.slice(0,r)+e+this.queryValue.slice(a),this.update(),this.inputTarget.focus(),this.inputTarget.setSelectionRange(n,n)}}}];export{u as default};
2
2
  //# sourceMappingURL=tables.min.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tables.min.js","sources":["../../../javascript/tables/orderable/list_controller.js","../../../javascript/tables/selection/item_controller.js","../../../javascript/tables/query_input_controller.js","../../../javascript/tables/application.js","../../../javascript/tables/orderable/item_controller.js","../../../javascript/tables/orderable/form_controller.js","../../../javascript/tables/selection/form_controller.js","../../../javascript/tables/selection/table_controller.js","../../../javascript/tables/query_controller.js"],"sourcesContent":["import { Controller } from \"@hotwired/stimulus\";\n\nexport default class OrderableListController extends Controller {\n static outlets = [\"tables--orderable--item\", \"tables--orderable--form\"];\n static values = { direction: { type: String, default: \"asc\" } };\n\n //region State transitions\n\n startDragging(dragState) {\n this.dragState = dragState;\n\n document.addEventListener(\"mousemove\", this.mousemove);\n document.addEventListener(\"mouseup\", this.mouseup);\n window.addEventListener(\"scroll\", this.scroll, true);\n\n this.element.style.position = \"relative\";\n }\n\n stopDragging({ reset = true } = {}) {\n const dragState = this.dragState;\n delete this.dragState;\n\n document.removeEventListener(\"mousemove\", this.mousemove);\n document.removeEventListener(\"mouseup\", this.mouseup);\n window.removeEventListener(\"scroll\", this.scroll, true);\n\n this.element.removeAttribute(\"style\");\n if (reset) this.items.forEach((item) => item.reset());\n\n return dragState;\n }\n\n drop() {\n // note: early returns guard against turbo updates that prevent us finding\n // the right item to drop on. In this situation it's better to discard the\n // drop than to drop in the wrong place.\n\n const dragItem = this.dragItem;\n\n if (!dragItem) return;\n\n const items = this.items;\n items.forEach((item) => item.captureDropPosition());\n\n this.#insertDragItem(this.orderedItems, dragItem);\n\n items.forEach((item) => item.invertDropPosition());\n\n // Commit the inverted transforms before enabling transitions to play out.\n this.element.offsetHeight;\n\n // reindex all items based on their new positions\n const count = this.items.length;\n this.items.forEach((item, index) => {\n item.updateIndex(\n this.directionValue === \"desc\" ? count - 1 - index : index,\n );\n });\n\n // save the changes\n this.commitChanges();\n\n window.requestAnimationFrame(() => {\n items.forEach((item) => item.playDrop());\n window.setTimeout(() => {\n items.forEach((item) => item.reset());\n }, this.#animationDuration);\n });\n\n return true;\n }\n\n commitChanges() {\n // clear any existing inputs to prevent duplicates\n this.tablesOrderableFormOutlet.clear();\n\n // insert any items that have changed position\n this.items.forEach((item) => {\n if (item.hasChanges) this.tablesOrderableFormOutlet.add(item);\n });\n\n this.tablesOrderableFormOutlet.submit();\n }\n\n //endregion\n\n //region Events\n\n mousedown(event) {\n if (this.isDragging) return;\n\n const target = this.#targetItem(event.target);\n\n if (!target) return;\n\n event.preventDefault(); // prevent built-in drag\n\n this.startDragging(new DragState(this.element, event, target.id));\n\n this.dragState.updateCursor(this.element, target.row, event, this.animate);\n }\n\n mousemove = (event) => {\n if (!this.isDragging) return;\n\n event.preventDefault(); // prevent build-in drag\n\n if (this.ticking) return;\n\n this.ticking = true;\n\n window.requestAnimationFrame(() => {\n this.ticking = false;\n this.dragState?.updateCursor(\n this.element,\n this.dragItem.row,\n event,\n this.animate,\n );\n });\n };\n\n scroll = (event) => {\n if (!this.isDragging || this.ticking) return;\n\n this.ticking = true;\n\n window.requestAnimationFrame(() => {\n this.ticking = false;\n this.dragState?.updateScroll(\n this.element,\n this.dragItem.row,\n this.animate,\n );\n });\n };\n\n mouseup = (event) => {\n if (!this.isDragging) return;\n\n const dropped = this.drop();\n this.stopDragging({ reset: !dropped });\n this.items.forEach((form) => delete form.dragState);\n };\n\n tablesOrderableFormOutletConnected(form, element) {\n if (form.dragState) {\n // restore the previous controller's state\n this.startDragging(form.dragState);\n }\n }\n\n tablesOrderableFormOutletDisconnected(form, element) {\n if (this.isDragging) {\n // cache drag state in the form\n form.dragState = this.stopDragging();\n }\n }\n\n beforeMorphElement(e) {\n // Cancel morph if dragging to prevent swapping rows from under the user\n // An alternative would be to require ids on rows so morph can accurately\n // map before/after and avoid updating the row being dragged\n if (this.isDragging) e.preventDefault();\n }\n\n //endregion\n\n //region Helpers\n\n /**\n * Updates the position of the drag item with a relative offset. Updates\n * other items relative to the new position of the drag item, as required.\n *\n * @callback {OrderableListController~animate}\n * @param {number} offset\n */\n animate = (offset) => {\n const dragItem = this.dragItem;\n\n // Visually update the dragItem so it follows the cursor\n dragItem.dragUpdate(offset);\n\n // Visually updates the position of all items in the list relative to the\n // dragged item. No actual changes to orderings at this stage.\n let nextOffset = 0;\n\n this.orderedItems.forEach((item) => {\n if (item !== dragItem) item.updateVisually(nextOffset);\n nextOffset += item.height;\n });\n };\n\n get isDragging() {\n return !!this.dragState;\n }\n\n get dragItem() {\n if (!this.isDragging) return null;\n\n return this.items.find((item) => item.id === this.dragState.targetId);\n }\n\n /**\n * Returns the current items in the list in DOM order.\n *\n * @returns {Array[OrderableRowController]}\n */\n get items() {\n // Note, item outlets may include other items as the outlets do not have a\n // mechanism to specify an element scope.\n return this.tablesOrderableItemOutlets.filter((item) =>\n this.element.contains(item.element),\n );\n }\n\n get orderedItems() {\n const dragItem = this.dragItem;\n\n if (!dragItem) return this.items;\n\n return this.items.toSorted((a, b) => a.dragPosition - b.dragPosition);\n }\n\n /**\n * Returns the item outlet that was clicked on, if any.\n *\n * @param element {HTMLElement} the clicked ordinal cell\n * @returns {OrderableRowController}\n */\n #targetItem(element) {\n return this.items.find((item) => item.element === element);\n }\n\n #insertDragItem(orderedItems, dragItem) {\n const index = orderedItems.indexOf(dragItem);\n const previousItem = orderedItems[index - 1];\n const nextItem = orderedItems[index + 1];\n\n if (previousItem) {\n previousItem.row.insertAdjacentElement(\"afterend\", dragItem.row);\n } else if (nextItem) {\n nextItem.row.insertAdjacentElement(\"beforebegin\", dragItem.row);\n }\n }\n\n get #animationDuration() {\n const duration =\n window\n .getComputedStyle(this.element)\n .getPropertyValue(\"--animation-duration\") || \"150ms\";\n\n return parseTime(duration);\n }\n\n //endregion\n}\n\nfunction parseTime(value) {\n value = value.trim();\n\n if (value.endsWith(\"ms\")) return parseFloat(value);\n if (value.endsWith(\"s\")) return parseFloat(value) * 1000;\n\n return parseFloat(value) || 0;\n}\n\n/**\n * During drag we want to be able to translate a document-relative coordinate\n * into a coordinate relative to the list element. This state object calculates\n * and stores internal state so that we can translate absolute page coordinates\n * from mouse events into relative offsets for the list items within the list\n * element.\n *\n * We also keep track of the drag target so that if the controller is attached\n * to a new element during the drag we can continue after the turbo update.\n */\nclass DragState {\n /**\n * @param list {HTMLElement} the list controller's element (tbody)\n * @param event {MouseEvent} the initial event\n * @param id {String} the id of the element being dragged\n */\n constructor(list, event, id) {\n // cursor offset is the offset of the cursor relative to the drag item\n this.cursorOffset = event.offsetY;\n\n // initial offset is the offset position of the drag item at drag start\n this.initialPosition = event.target.offsetTop - list.offsetTop;\n\n // id of the item being dragged\n this.targetId = id;\n }\n\n /**\n * Calculates the offset of the drag item relative to its initial position.\n *\n * @param list {HTMLElement} the list controller's element (tbody)\n * @param row {HTMLElement} the row being dragged\n * @param event {MouseEvent} the current event\n * @param callback {OrderableListController~animate} updates the drag item with a relative offset\n */\n updateCursor(list, row, event, callback) {\n // Calculate and store the list offset relative to the viewport\n // This value is cached so we can calculate the outcome of any scroll events\n this.listOffset = list.getBoundingClientRect().top;\n\n // Calculate the position of the cursor relative to the list.\n // Accounts for scroll offsets by using the item's bounding client rect.\n const cursorPosition = event.clientY - this.listOffset;\n\n // intended item position relative to the list, from cursor position\n let itemPosition = cursorPosition - this.cursorOffset;\n\n this.#updateItemPosition(list, row, itemPosition, callback);\n }\n\n /**\n * Animates the item's position as the list scrolls. Requires a previous call\n * to set the scroll offset.\n *\n * @param list {HTMLElement} the list controller's element (tbody)\n * @param row {HTMLElement} the row being dragged\n * @param callback {OrderableListController~animate} updates the drag item with a relative offset\n */\n updateScroll(list, row, callback) {\n const previousScrollOffset = this.listOffset;\n\n // Calculate and store the list offset relative to the viewport\n // This value is cached so we can calculate the outcome of any scroll events\n this.listOffset = list.getBoundingClientRect().top;\n\n // Calculate the change in scroll offset since the last update\n const scrollDelta = previousScrollOffset - this.listOffset;\n\n // intended item position relative to the list, from cursor position\n const position = this.position + scrollDelta;\n\n this.#updateItemPosition(list, row, position, callback);\n }\n\n #updateItemPosition(list, row, position, callback) {\n // ensure itemPosition is within the bounds of the list (tbody)\n position = Math.max(position, 0);\n position = Math.min(position, list.offsetHeight - row.offsetHeight);\n\n // cache the item's position relative to the list for use in scroll events\n this.position = position;\n\n // Item has position: relative, so we want to calculate the amount to move\n // the item relative to it's DOM position to represent how much it has been\n // dragged by.\n const offset = position - this.initialPosition;\n\n // Convert itemPosition from offset relative to list to offset relative to\n // its position within the DOM (if it hadn't moved).\n callback(offset);\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\n\n/**\n * Couples an input element in a row to the selection form which is turbo-permanent and outside the table.\n * When the input is toggled, the form will create/destroy hidden inputs. The checkbox inside this cell will follow\n * the hidden inputs.\n *\n * Cell value may change when:\n * * cell connects, e.g. when the user paginates\n * * cell is re-used by turbo-morph, e.g. pagination\n * * cell is toggled\n * * select-all/de-select-all on table header\n */\nexport default class SelectionItemController extends Controller {\n static outlets = [\"tables--selection--form\"];\n static values = {\n params: Object,\n checked: Boolean,\n };\n\n tablesSelectionFormOutletConnected(form) {\n form.visible(this.id, true);\n this.checkedValue = form.isSelected(this.id);\n }\n\n disconnect() {\n // Remove from form's list of visible selections.\n // This should be an outlet disconnect, but those events are not reliable in turbo 8.0\n if (this.hasTablesSelectionFormOutlet) {\n this.tablesSelectionFormOutlet.visible(this.id, false);\n }\n }\n\n change(e) {\n e.preventDefault();\n\n this.checkedValue = this.tablesSelectionFormOutlet.toggle(this.id);\n }\n\n get id() {\n return this.paramsValue.id;\n }\n\n /**\n * Update checked to match match selection form. This occurs when the item is re-used by turbo-morph.\n */\n paramsValueChanged(params, previous) {\n if (!this.hasTablesSelectionFormOutlet) return;\n\n // if id is changing (e.g. morph) then let the form know that the previous id is now not visible\n if (previous.id !== params.id) {\n this.tablesSelectionFormOutlet.visible(previous.id, false);\n }\n\n // tell form that our id is now visible in the table\n this.tablesSelectionFormOutlet.visible(params.id, true);\n\n // id has changed, so update checked from form\n this.checkedValue = this.tablesSelectionFormOutlet.isSelected(params.id);\n\n // propagate changes\n this.update();\n }\n\n /**\n * Update input to match checked. This occurs when the item is toggled, connected, or morphed.\n */\n checkedValueChanged() {\n if (!this.hasTablesSelectionFormOutlet) return;\n\n // ensure that checked matches the form, i.e. if morphed\n this.checkedValue = this.tablesSelectionFormOutlet.isSelected(this.id);\n\n // propagate changes\n this.update();\n }\n\n /**\n * Notify table that id or value may have changed. Note that this may fire when nothing has changed.\n *\n * Debouncing to minimise dom updates.\n */\n async update() {\n this.updating ||= Promise.resolve().then(() => {\n this.#update();\n delete this.updating;\n });\n\n return this.updating;\n }\n\n #update() {\n this.element.querySelector(\"input\").checked = this.checkedValue;\n this.dispatch(\"select\", {\n detail: { id: this.id, selected: this.checkedValue },\n });\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\n\nexport default class QueryInputController extends Controller {\n static targets = [\"input\", \"highlight\"];\n static values = { query: String };\n\n connect() {\n this.queryValue = this.inputTarget.value;\n this.element.dataset.connected = \"\";\n }\n\n disconnect() {\n delete this.element.dataset.connected;\n }\n\n update() {\n this.queryValue = this.inputTarget.value;\n }\n\n queryValueChanged(query) {\n this.highlightTarget.innerHTML = \"\";\n\n new Parser().parse(query).tokens.forEach((token) => {\n this.highlightTarget.appendChild(token.render());\n });\n }\n\n replaceToken(e) {\n let tokenToAdd = e.detail.token.toString();\n\n // wrap in quotes if it contains a spaces or special characters\n if (/\\s/.exec(tokenToAdd)) {\n tokenToAdd = `\"${tokenToAdd}\"`;\n }\n\n const indexPosition = e.detail.position;\n let caretPosition = indexPosition + tokenToAdd.length;\n let sliceStart = indexPosition;\n let sliceEnd = indexPosition;\n\n // detect if position has a token already, if so, replace it\n const existingToken = new Parser()\n .parse(this.queryValue)\n .tokenAtPosition(indexPosition);\n if (existingToken) {\n // We don't want to include the trailing space as we are replacing an existing value\n tokenToAdd = tokenToAdd.trim();\n\n // Slice up to the beginning of the tokens value (not the initial caret position)\n sliceStart = existingToken.startOfValue();\n\n // Slice after the end of the tokens value\n sliceEnd = existingToken.endOfValue();\n\n // The end position of the newly added token\n caretPosition = sliceStart + tokenToAdd.length;\n }\n\n // Replace any text within sliceStart and sliceEnd with tokenToAdd\n this.inputTarget.value =\n this.queryValue.slice(0, sliceStart) +\n tokenToAdd +\n this.queryValue.slice(sliceEnd);\n\n // Re focus the input at the end of the newly added token\n this.update();\n this.inputTarget.focus();\n this.inputTarget.setSelectionRange(caretPosition, caretPosition);\n }\n}\n\nclass Parser {\n constructor() {\n this.tokens = [];\n this.values = null;\n }\n\n parse(input) {\n const query = new StringScanner(input);\n\n while (!query.isEos()) {\n this.push(this.skipWhitespace(query));\n\n const value = this.takeTagged(query) || this.takeUntagged(query);\n\n if (!this.push(value)) break;\n }\n\n return this;\n }\n\n push(token) {\n if (token) {\n this.values ? this.values.push(token) : this.tokens.push(token);\n }\n\n return !!token;\n }\n\n skipWhitespace(query) {\n if (!query.scan(/\\s+/)) return;\n\n return new Token(query.matched(), query.position);\n }\n\n takeUntagged(query) {\n if (!query.scan(/\\S+/)) return;\n\n return new Untagged(query.matched(), query.position);\n }\n\n takeTagged(query) {\n if (!query.scan(/(\\w+(?:\\.\\w+)?)(:\\s*)/)) return;\n\n const key = query.valueAt(1);\n const separator = query.valueAt(2);\n\n const value =\n this.takeArrayValue(query) || this.takeSingleValue(query) || new Token();\n\n return new Tagged(key, separator, value, query.position);\n }\n\n takeArrayValue(query) {\n if (!query.scan(/\\[\\s*/)) return;\n\n const start = new Token(query.matched(), query.position);\n const values = (this.values = []);\n\n while (!query.isEos()) {\n if (!this.push(this.takeSingleValue(query))) break;\n if (!this.push(this.takeDelimiter(query))) break;\n }\n\n query.scan(/\\s*]/);\n const end = new Token(query.matched(), query.position);\n\n this.values = null;\n\n return new ArrayToken(start, values, end);\n }\n\n takeDelimiter(query) {\n if (!query.scan(/\\s*,\\s*/)) return;\n\n return new Token(query.matched(), query.position);\n }\n\n takeSingleValue(query) {\n return this.takeQuotedValue(query) || this.takeUnquotedValue(query);\n }\n\n takeQuotedValue(query) {\n if (!query.scan(/\"([^\"]*)\"/)) return;\n\n return new Value(query.matched(), query.position);\n }\n\n takeUnquotedValue(query) {\n if (!query.scan(/[^ \\],]*/)) return;\n\n return new Value(query.matched(), query.position);\n }\n\n tokenAtPosition(position) {\n return this.tokens\n .filter((t) => t instanceof Tagged || t instanceof Untagged)\n .find((t) => t.range.includes(position));\n }\n}\n\nclass Token {\n constructor(value = \"\", position) {\n this.value = value;\n this.length = this.value.length;\n this.start = position - this.length;\n this.end = this.start + this.length;\n this.range = this.arrayRange(this.start, this.end);\n }\n\n render() {\n return document.createTextNode(this.value);\n }\n\n arrayRange(start, stop) {\n return Array.from(\n { length: stop - start + 1 },\n (value, index) => start + index,\n );\n }\n\n startOfValue() {\n return this.start;\n }\n\n endOfValue() {\n return this.end;\n }\n}\n\nclass Value extends Token {\n render() {\n const span = document.createElement(\"span\");\n span.className = \"value\";\n span.innerText = this.value;\n\n return span;\n }\n}\n\nclass Tagged extends Token {\n constructor(key, separator, value, position) {\n super();\n\n this.key = key;\n this.separator = separator;\n this.value = value;\n this.length = key.length + separator.length + value.value.length;\n this.start = position - this.length;\n this.end = this.start + this.length;\n this.range = this.arrayRange(this.start, this.end);\n }\n\n render() {\n const span = document.createElement(\"span\");\n span.className = \"tag\";\n\n const key = document.createElement(\"span\");\n key.className = \"key\";\n key.innerText = this.key;\n\n span.appendChild(key);\n span.appendChild(document.createTextNode(this.separator));\n span.appendChild(this.value.render());\n\n return span;\n }\n\n startOfValue() {\n return this.value.startOfValue();\n }\n\n endOfValue() {\n return this.value.endOfValue();\n }\n}\n\nclass Untagged extends Token {\n render() {\n const span = document.createElement(\"span\");\n span.className = \"untagged\";\n span.innerText = this.value;\n return span;\n }\n}\n\nclass ArrayToken extends Token {\n constructor(start, values, end) {\n super();\n\n this.start = start;\n this.values = values;\n this.end = end;\n this.range = this.arrayRange(start.start, end.range[end.length]);\n this.length =\n start.length +\n values.reduce((length, value) => length + value.length, 0) +\n end.length;\n }\n\n render() {\n const array = document.createElement(\"span\");\n array.className = \"array-values\";\n array.appendChild(this.start.render());\n\n this.values.forEach((value) => {\n const span = document.createElement(\"span\");\n span.appendChild(value.render());\n array.appendChild(span);\n });\n\n array.appendChild(this.end.render());\n\n return array;\n }\n\n startOfValue() {\n return this.start.start;\n }\n\n endOfValue() {\n return this.end.end;\n }\n}\n\nclass StringScanner {\n constructor(input) {\n this.input = input;\n this.position = 0;\n this.last = null;\n }\n\n isEos() {\n return this.position >= this.input.length;\n }\n\n scan(regex) {\n const match = regex.exec(this.input.substring(this.position));\n if (match?.index === 0) {\n this.last = match;\n this.position += match[0].length;\n return true;\n } else {\n this.last = {};\n return false;\n }\n }\n\n matched() {\n return this.last && this.last[0];\n }\n\n valueAt(index) {\n return this.last && this.last[index];\n }\n}\n","import OrderableItemController from \"./orderable/item_controller\";\nimport OrderableListController from \"./orderable/list_controller\";\nimport OrderableFormController from \"./orderable/form_controller\";\nimport SelectionFormController from \"./selection/form_controller\";\nimport SelectionItemController from \"./selection/item_controller\";\nimport SelectionTableController from \"./selection/table_controller\";\nimport QueryController from \"./query_controller\";\nimport QueryInputController from \"./query_input_controller\";\n\nconst Definitions = [\n {\n identifier: \"tables--orderable--item\",\n controllerConstructor: OrderableItemController,\n },\n {\n identifier: \"tables--orderable--list\",\n controllerConstructor: OrderableListController,\n },\n {\n identifier: \"tables--orderable--form\",\n controllerConstructor: OrderableFormController,\n },\n {\n identifier: \"tables--selection--form\",\n controllerConstructor: SelectionFormController,\n },\n {\n identifier: \"tables--selection--item\",\n controllerConstructor: SelectionItemController,\n },\n {\n identifier: \"tables--selection--table\",\n controllerConstructor: SelectionTableController,\n },\n {\n identifier: \"tables--query\",\n controllerConstructor: QueryController,\n },\n {\n identifier: \"tables--query-input\",\n controllerConstructor: QueryInputController,\n },\n];\n\nexport { Definitions as default };\n","import { Controller } from \"@hotwired/stimulus\";\n\nexport default class OrderableRowController extends Controller {\n static values = {\n params: Object,\n };\n\n connect() {\n // index from server may be inconsistent with the visual ordering,\n // especially if this is a new node. Use positional indexes instead,\n // as these are the values we will send on save.\n this.index = domIndex(this.row);\n }\n\n paramsValueChanged(params) {\n this.id = params.id_value;\n }\n\n dragUpdate(offset) {\n this.dragOffset = offset;\n this.row.style.position = \"relative\";\n this.row.style.transform = `scale(1.01) translateY(${offset}px)`;\n this.row.style.zIndex = \"1\";\n this.row.toggleAttribute(\"dragging\", true);\n }\n\n /**\n * Called on items that are not the dragged item during drag. Updates the\n * visual position of the item relative to the dragged item.\n *\n * @param offset {number} intended offset of the item during drag\n */\n updateVisually(offset) {\n this.row.style.transform = `translateY(${offset - this.#offsetTop}px)`;\n }\n\n captureDropPosition() {\n this.dropTop = this.#viewportTop;\n }\n\n invertDropPosition() {\n delete this.dragOffset;\n this.row.removeAttribute(\"dragging\");\n this.row.style.transition = \"transform 0s\";\n this.row.style.transform = \"\";\n this.row.style.transform = `translateY(${this.dropTop - this.#viewportTop}px)`;\n }\n\n playDrop() {\n this.row.style.transition = \"\";\n this.row.style.transform = \"\";\n }\n\n /**\n * Set the index value of the item. This is called on all items after a drop\n * event. If the index is different to the params index then this item has\n * changed.\n *\n * @param index {number} the new index value\n */\n updateIndex(index) {\n this.index = index;\n }\n\n /** Retrieve params for use in the form */\n params(scope) {\n const { id_name, id_value, index_name } = this.paramsValue;\n return [\n { name: `${scope}[${id_value}][${id_name}]`, value: this.id },\n { name: `${scope}[${id_value}][${index_name}]`, value: this.index },\n ];\n }\n\n /**\n * Restore any visual changes made during drag and remove the drag state.\n */\n reset() {\n delete this.dragOffset;\n delete this.dropTop;\n this.row.removeAttribute(\"style\");\n this.row.removeAttribute(\"dragging\");\n }\n\n /**\n * @returns {boolean} true when the item has a change to its index value\n */\n get hasChanges() {\n return this.paramsValue.index_value !== this.index;\n }\n\n /**\n * Value for use in comparisons during drag. Used by ListController to\n * determine whether the dragged item is above or below another item.\n *\n * @returns {number}\n */\n get dragPosition() {\n return this.dragOffset && this.dragOffset !== 0\n ? this.#leadingEdge\n : this.#midpoint;\n }\n\n /**\n * The containing row element.\n *\n * @returns {HTMLElement}\n */\n get row() {\n return this.element.parentElement;\n }\n\n get height() {\n return this.row.offsetHeight;\n }\n\n get #midpoint() {\n return this.#offsetTop + this.height / 2;\n }\n\n get #leadingEdge() {\n const top = this.#offsetTop + this.dragOffset;\n\n return this.dragOffset < 0 ? top : top + this.height;\n }\n\n get #offsetTop() {\n return this.row.offsetTop;\n }\n\n get #viewportTop() {\n return this.row.getBoundingClientRect().top;\n }\n}\n\nfunction domIndex(element) {\n return Array.from(element.parentElement.children).indexOf(element);\n}\n","import { Controller } from \"@hotwired/stimulus\";\n\nexport default class OrderableFormController extends Controller {\n static values = { scope: String };\n\n add(item) {\n item.params(this.scopeValue).forEach(({ name, value }) => {\n this.element.insertAdjacentHTML(\n \"beforeend\",\n `<input type=\"hidden\" name=\"${name}\" value=\"${value}\" data-generated>`,\n );\n });\n }\n\n submit() {\n if (this.inputs.length === 0) return;\n\n this.element.requestSubmit();\n }\n\n clear() {\n this.inputs.forEach((input) => input.remove());\n }\n\n get inputs() {\n return this.element.querySelectorAll(\"input[data-generated]\");\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\n\nexport default class SelectionFormController extends Controller {\n static values = {\n count: Number,\n primaryKey: { type: String, default: \"id\" },\n };\n static targets = [\"count\", \"singular\", \"plural\"];\n\n connect() {\n this.countValue = this.inputs.length;\n }\n\n /**\n * @param id to toggle\n * @return {boolean} true if selected, false if unselected\n */\n toggle(id) {\n const input = this.input(id);\n\n if (input) {\n input.remove();\n } else {\n this.element.insertAdjacentHTML(\n \"beforeend\",\n `<input type=\"hidden\" name=\"${this.primaryKeyValue}[]\" value=\"${id}\">`,\n );\n }\n\n this.countValue = this.visibleInputs.length;\n\n return !input;\n }\n\n /**\n * @param id to toggle visibility\n * @return {boolean} true if visible, false if not visible\n */\n visible(id, visible) {\n const input = this.input(id);\n\n if (input) {\n input.disabled = !visible;\n }\n\n this.countValue = this.visibleInputs.length;\n\n return !input;\n }\n\n /**\n * @returns {boolean} true if the given id is currently selected\n */\n isSelected(id) {\n return !!this.input(id);\n }\n\n get inputs() {\n return this.element.querySelectorAll(\n `input[name=\"${this.primaryKeyValue}[]\"]`,\n );\n }\n\n get visibleInputs() {\n return Array.from(this.inputs).filter((i) => !i.disabled);\n }\n\n input(id) {\n return this.element.querySelector(\n `input[name=\"${this.primaryKeyValue}[]\"][value=\"${id}\"]`,\n );\n }\n\n countValueChanged(count) {\n this.element.toggleAttribute(\"hidden\", count === 0);\n this.countTarget.textContent = count;\n this.singularTarget.toggleAttribute(\"hidden\", count !== 1);\n this.pluralTarget.toggleAttribute(\"hidden\", count === 1);\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\n\nexport default class SelectionTableController extends Controller {\n static targets = [\"header\", \"item\"];\n static outlets = [\"tables--selection--form\"];\n\n itemTargetConnected(item) {\n this.update();\n }\n\n itemTargetDisconnected(item) {\n this.update();\n }\n\n toggleHeader(e) {\n this.items.forEach((item) => {\n if (item.checkedValue === e.target.checked) return;\n\n item.checkedValue = this.tablesSelectionFormOutlet.toggle(item.id);\n });\n }\n\n async update() {\n this.updating ||= Promise.resolve().then(() => {\n this.#update();\n delete this.updating;\n });\n\n return this.updating;\n }\n\n #update() {\n let present = 0;\n let checked = 0;\n\n this.items.forEach((item) => {\n present++;\n if (item.checkedValue) checked++;\n });\n\n this.headerInput.checked = present > 0 && checked === present;\n this.headerInput.indeterminate = checked > 0 && checked !== present;\n }\n\n get headerInput() {\n return this.headerTarget.querySelector(\"input\");\n }\n\n get items() {\n return this.itemTargets.map((el) => this.#itemOutlet(el)).filter((c) => c);\n }\n\n /**\n * Ideally we would be using outlets, but as of turbo 8.0.4 outlets do not fire disconnect events when morphing.\n *\n * Instead, we're using the targets to finds the controller.\n */\n #itemOutlet(el) {\n return this.application.getControllerForElementAndIdentifier(\n el,\n \"tables--selection--item\",\n );\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\n\nexport default class QueryController extends Controller {\n static targets = [\"modal\"];\n\n disconnect() {\n delete this.pending;\n\n document.removeEventListener(\"selectionchange\", this.selection);\n }\n\n focus() {\n if (document.activeElement === this.query) return;\n\n this.query.addEventListener(\n \"focusin\",\n (e) => {\n e.target.setSelectionRange(-1, -1);\n },\n { once: true },\n );\n\n this.query.focus();\n }\n\n closeModal() {\n delete this.modalTarget.dataset.open;\n this.query.setAttribute(\"aria-expanded\", false);\n\n if (document.activeElement === this.query) document.activeElement.blur();\n\n document.removeEventListener(\"selectionchange\", this.selection);\n }\n\n openModal() {\n this.modalTarget.dataset.open = true;\n this.query.setAttribute(\"aria-expanded\", true);\n\n document.addEventListener(\"selectionchange\", this.selection);\n }\n\n /**\n * If the user presses escape once, clear the input.\n * If the user presses escape again, get them out of here.\n */\n clear() {\n if (this.query.value === \"\") {\n this.closeModal();\n } else {\n this.query.value = \"\";\n this.query.dispatchEvent(new Event(\"input\"));\n this.query.dispatchEvent(new Event(\"change\"));\n this.update();\n }\n }\n\n submit() {\n const hasFocus = this.isFocused;\n const position = hasFocus && this.query.selectionStart;\n\n if (this.pending) {\n clearTimeout(this.pending);\n delete this.pending;\n }\n\n // add/remove current cursor position\n if (hasFocus && this.query.value !== \"\") {\n this.position.value = position;\n this.position.disabled = false;\n } else {\n this.position.value = \"\";\n this.position.disabled = true;\n }\n\n // prevent an unnecessary `?q=&p=0` parameter from appearing in the URL\n if (this.query.value === \"\") {\n this.query.disabled = true;\n\n // restore input and focus after form submission\n setTimeout(() => {\n this.query.disabled = false;\n this.position.disabled = false;\n if (hasFocus) this.query.focus();\n }, 0);\n }\n }\n\n update = () => {\n if (this.pending) clearTimeout(this.pending);\n this.pending = setTimeout(() => {\n this.element.requestSubmit();\n }, 300);\n };\n\n selection = () => {\n if (this.isFocused && this.query.value.length > 0) this.update();\n };\n\n beforeMorphAttribute(e) {\n switch (e.detail.attributeName) {\n case \"data-open\":\n e.preventDefault();\n break;\n }\n }\n\n moveToPreviousSuggestion() {\n const prev = this.previousSuggestion || this.lastSuggestion;\n\n if (prev) this.makeSuggestionActive(prev);\n }\n\n moveToNextSuggestion() {\n const next = this.nextSuggestion || this.firstSuggestion;\n\n if (next) this.makeSuggestionActive(next);\n }\n\n selectFirstSuggestion(e) {\n // This is caused by pressing the tab key. We don't want to move focus.\n // Ideally we don't want to always prevent the user from tabbing. We will address this later\n e.preventDefault();\n\n this.firstSuggestion?.dispatchEvent(new CustomEvent(\"query:select\"));\n }\n\n selectActiveSuggestion() {\n if (!this.activeSuggestion) {\n this.closeModal();\n return;\n }\n\n this.activeSuggestion.dispatchEvent(new CustomEvent(\"query:select\"));\n }\n\n selectSuggestion(e) {\n this.query.dispatchEvent(\n new CustomEvent(\"replaceToken\", {\n detail: { token: e.params.value, position: this.query.selectionStart },\n }),\n );\n\n this.clearActiveSuggestion();\n }\n\n makeSuggestionActive(node) {\n if (this.activeSuggestion) {\n this.activeSuggestion.setAttribute(\"aria-selected\", \"false\");\n }\n\n this.query.setAttribute(\"aria-activedescendant\", node.id);\n node.setAttribute(\"aria-selected\", \"true\");\n }\n\n clearActiveSuggestion() {\n if (this.activeSuggestion) {\n this.activeSuggestion.setAttribute(\"aria-selected\", \"false\");\n this.query.removeAttribute(\"aria-activedescendant\");\n }\n }\n\n get activeSuggestion() {\n return this.modalTarget.querySelector(\n `#${this.query.getAttribute(\"aria-activedescendant\")}`,\n );\n }\n\n get previousSuggestion() {\n return this.activeSuggestion?.previousElementSibling;\n }\n\n get nextSuggestion() {\n return this.activeSuggestion?.nextElementSibling;\n }\n\n get firstSuggestion() {\n return this.modalTarget.querySelector(\"#suggestions li:first-of-type\");\n }\n\n get lastSuggestion() {\n return this.modalTarget.querySelector(\"#suggestions li:last-of-type\");\n }\n\n get query() {\n return this.element.querySelector(\"[role=combobox]\");\n }\n\n get position() {\n return this.element.querySelector(\"input[name=p]\");\n }\n\n get isFocused() {\n return this.query === document.activeElement;\n }\n}\n"],"names":["DragState","constructor","list","event","id","this","cursorOffset","offsetY","initialPosition","target","offsetTop","targetId","updateCursor","row","callback","listOffset","getBoundingClientRect","top","itemPosition","clientY","updateItemPosition","updateScroll","previousScrollOffset","scrollDelta","position","Math","max","min","offsetHeight","SelectionItemController","Controller","static","params","Object","checked","Boolean","tablesSelectionFormOutletConnected","form","visible","checkedValue","isSelected","disconnect","hasTablesSelectionFormOutlet","tablesSelectionFormOutlet","change","e","preventDefault","toggle","paramsValue","paramsValueChanged","previous","update","checkedValueChanged","updating","Promise","resolve","then","element","querySelector","dispatch","detail","selected","Parser","tokens","values","parse","input","query","StringScanner","isEos","push","skipWhitespace","value","takeTagged","takeUntagged","token","scan","Token","matched","Untagged","key","valueAt","separator","takeArrayValue","takeSingleValue","Tagged","start","takeDelimiter","end","ArrayToken","takeQuotedValue","takeUnquotedValue","Value","tokenAtPosition","filter","t","find","range","includes","length","arrayRange","render","document","createTextNode","stop","Array","from","index","startOfValue","endOfValue","span","createElement","className","innerText","super","appendChild","reduce","array","forEach","last","regex","match","exec","substring","Definitions","identifier","controllerConstructor","connect","parentElement","children","indexOf","id_value","dragUpdate","offset","dragOffset","style","transform","zIndex","toggleAttribute","updateVisually","captureDropPosition","dropTop","viewportTop","invertDropPosition","removeAttribute","transition","playDrop","updateIndex","scope","id_name","index_name","name","reset","hasChanges","index_value","dragPosition","leadingEdge","midpoint","height","direction","type","String","default","startDragging","dragState","addEventListener","mousemove","mouseup","window","scroll","stopDragging","removeEventListener","items","item","drop","dragItem","insertDragItem","orderedItems","count","directionValue","commitChanges","requestAnimationFrame","setTimeout","animationDuration","tablesOrderableFormOutlet","clear","add","submit","mousedown","isDragging","targetItem","animate","ticking","dropped","tablesOrderableFormOutletConnected","tablesOrderableFormOutletDisconnected","beforeMorphElement","nextOffset","tablesOrderableItemOutlets","contains","toSorted","a","b","previousItem","nextItem","insertAdjacentElement","duration","getComputedStyle","getPropertyValue","trim","endsWith","parseFloat","scopeValue","insertAdjacentHTML","inputs","requestSubmit","remove","querySelectorAll","Number","primaryKey","countValue","primaryKeyValue","visibleInputs","disabled","i","countValueChanged","countTarget","textContent","singularTarget","pluralTarget","itemTargetConnected","itemTargetDisconnected","toggleHeader","present","headerInput","indeterminate","headerTarget","itemTargets","map","el","itemOutlet","c","application","getControllerForElementAndIdentifier","pending","selection","focus","activeElement","setSelectionRange","once","closeModal","modalTarget","dataset","open","setAttribute","blur","openModal","dispatchEvent","Event","hasFocus","isFocused","selectionStart","clearTimeout","beforeMorphAttribute","attributeName","moveToPreviousSuggestion","prev","previousSuggestion","lastSuggestion","makeSuggestionActive","moveToNextSuggestion","next","nextSuggestion","firstSuggestion","selectFirstSuggestion","CustomEvent","selectActiveSuggestion","activeSuggestion","selectSuggestion","clearActiveSuggestion","node","getAttribute","previousElementSibling","nextElementSibling","queryValue","inputTarget","connected","queryValueChanged","highlightTarget","innerHTML","replaceToken","tokenToAdd","toString","indexPosition","caretPosition","sliceStart","sliceEnd","existingToken","slice"],"mappings":"gDAqRA,MAAMA,EAMJ,WAAAC,CAAYC,EAAMC,EAAOC,GAEvBC,KAAKC,aAAeH,EAAMI,QAG1BF,KAAKG,gBAAkBL,EAAMM,OAAOC,UAAYR,EAAKQ,UAGrDL,KAAKM,SAAWP,CAClB,CAUA,YAAAQ,CAAaV,EAAMW,EAAKV,EAAOW,GAG7BT,KAAKU,WAAab,EAAKc,wBAAwBC,IAO/C,IAAIC,EAHmBf,EAAMgB,QAAUd,KAAKU,WAGRV,KAAKC,aAEzCD,MAAKe,EAAoBlB,EAAMW,EAAKK,EAAcJ,EACpD,CAUA,YAAAO,CAAanB,EAAMW,EAAKC,GACtB,MAAMQ,EAAuBjB,KAAKU,WAIlCV,KAAKU,WAAab,EAAKc,wBAAwBC,IAG/C,MAAMM,EAAcD,EAAuBjB,KAAKU,WAG1CS,EAAWnB,KAAKmB,SAAWD,EAEjClB,MAAKe,EAAoBlB,EAAMW,EAAKW,EAAUV,EAChD,CAEA,EAAAM,CAAoBlB,EAAMW,EAAKW,EAAUV,GAEvCU,EAAWC,KAAKC,IAAIF,EAAU,GAC9BA,EAAWC,KAAKE,IAAIH,EAAUtB,EAAK0B,aAAef,EAAIe,cAGtDvB,KAAKmB,SAAWA,EAShBV,EAJeU,EAAWnB,KAAKG,gBAKjC,ECxVa,MAAMqB,UAAgCC,EACnDC,eAAiB,CAAC,2BAClBA,cAAgB,CACdC,OAAQC,OACRC,QAASC,SAGX,kCAAAC,CA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9C,KAAKuR,WAAavR,KAAKwR,YAAYrN,KACrC,CAEA,iBAAAuN,CAAkB5N,GAChB9D,KAAK2R,gBAAgBC,UAAY,IAEjC,IAAInO,GAASG,MAAME,GAAOJ,OAAOuD,QAAS3C,IACxCtE,KAAK2R,gBAAgB7K,YAAYxC,EAAM0B,WAE3C,CAEA,YAAA6L,CAAarP,GACX,IAAIsP,EAAatP,EAAEe,OAAOe,MAAMyN,WAG5B,KAAK1K,KAAKyK,KACZA,EAAa,IAAIA,MAGnB,MAAME,EAAgBxP,EAAEe,OAAOpC,SAC/B,IAAI8Q,EAAgBD,EAAgBF,EAAWhM,OAC3CoM,EAAaF,EACbG,EAAWH,EAGf,MAAMI,GAAgB,IAAI3O,GACvBG,MAAM5D,KAAKuR,YACX/L,gBAAgBwM,GACfI,IAEFN,EAAaA,EAAWlF,OAGxBsF,EAAaE,EAAc7L,eAG3B4L,EAAWC,EAAc5L,aAGzByL,EAAgBC,EAAaJ,EAAWhM,QAI1C9F,KAAKwR,YAAYrN,MACfnE,KAAKuR,WAAWc,MAAM,EAAGH,GACzBJ,EACA9R,KAAKuR,WAAWc,MAAMF,GAGxBnS,KAAK8C,SACL9C,KAAKwR,YAAYvC,QACjBjP,KAAKwR,YAAYrC,kBAAkB8C,EAAeA,EACpD"}
1
+ {"version":3,"file":"tables.min.js","sources":["../../../javascript/tables/orderable/list_controller.js","../../../javascript/tables/selection/item_controller.js","../../../javascript/tables/query_input_controller.js","../../../javascript/tables/application.js","../../../javascript/tables/orderable/item_controller.js","../../../javascript/tables/orderable/form_controller.js","../../../javascript/tables/selection/form_controller.js","../../../javascript/tables/selection/table_controller.js","../../../javascript/tables/query_controller.js"],"sourcesContent":["import { Controller } from \"@hotwired/stimulus\";\n\nexport default class OrderableListController extends Controller {\n static outlets = [\"tables--orderable--item\", \"tables--orderable--form\"];\n static values = { direction: { type: String, default: \"asc\" } };\n\n //region State transitions\n\n startDragging(dragState) {\n this.dragState = dragState;\n\n document.addEventListener(\"mousemove\", this.mousemove);\n document.addEventListener(\"mouseup\", this.mouseup);\n window.addEventListener(\"scroll\", this.scroll, true);\n\n this.element.style.position = \"relative\";\n }\n\n stopDragging({ reset = true } = {}) {\n const dragState = this.dragState;\n delete this.dragState;\n\n document.removeEventListener(\"mousemove\", this.mousemove);\n document.removeEventListener(\"mouseup\", this.mouseup);\n window.removeEventListener(\"scroll\", this.scroll, true);\n\n this.element.removeAttribute(\"style\");\n if (reset) this.items.forEach((item) => item.reset());\n\n return dragState;\n }\n\n drop() {\n // note: early returns guard against turbo updates that prevent us finding\n // the right item to drop on. In this situation it's better to discard the\n // drop than to drop in the wrong place.\n\n const dragItem = this.dragItem;\n\n if (!dragItem) return;\n\n const items = this.items;\n items.forEach((item) => item.captureDropPosition());\n\n this.#insertDragItem(this.orderedItems, dragItem);\n\n items.forEach((item) => item.invertDropPosition());\n\n // Commit the inverted transforms before enabling transitions to play out.\n this.element.offsetHeight;\n\n // reindex all items based on their new positions\n const count = this.items.length;\n this.items.forEach((item, index) => {\n item.updateIndex(\n this.directionValue === \"desc\" ? count - 1 - index : index,\n );\n });\n\n // save the changes\n this.commitChanges();\n\n window.requestAnimationFrame(() => {\n items.forEach((item) => item.playDrop());\n window.setTimeout(() => {\n items.forEach((item) => item.reset());\n }, this.#animationDuration);\n });\n\n return true;\n }\n\n commitChanges() {\n // clear any existing inputs to prevent duplicates\n this.tablesOrderableFormOutlet.clear();\n\n // insert any items that have changed position\n this.items.forEach((item) => {\n if (item.hasChanges) this.tablesOrderableFormOutlet.add(item);\n });\n\n this.tablesOrderableFormOutlet.submit();\n }\n\n //endregion\n\n //region Events\n\n mousedown(event) {\n if (this.isDragging) return;\n\n const target = this.#targetItem(event.target);\n\n if (!target) return;\n\n event.preventDefault(); // prevent built-in drag\n\n this.startDragging(new DragState(this.element, event, target.id));\n\n this.dragState.updateCursor(this.element, target.row, event, this.animate);\n }\n\n mousemove = (event) => {\n if (!this.isDragging) return;\n\n event.preventDefault(); // prevent build-in drag\n\n if (this.ticking) return;\n\n this.ticking = true;\n\n window.requestAnimationFrame(() => {\n this.ticking = false;\n this.dragState?.updateCursor(\n this.element,\n this.dragItem.row,\n event,\n this.animate,\n );\n });\n };\n\n scroll = (event) => {\n if (!this.isDragging || this.ticking) return;\n\n this.ticking = true;\n\n window.requestAnimationFrame(() => {\n this.ticking = false;\n this.dragState?.updateScroll(\n this.element,\n this.dragItem.row,\n this.animate,\n );\n });\n };\n\n mouseup = (event) => {\n if (!this.isDragging) return;\n\n const dropped = this.drop();\n this.stopDragging({ reset: !dropped });\n this.items.forEach((form) => delete form.dragState);\n };\n\n tablesOrderableFormOutletConnected(form, element) {\n if (form.dragState) {\n // restore the previous controller's state\n this.startDragging(form.dragState);\n }\n }\n\n tablesOrderableFormOutletDisconnected(form, element) {\n if (this.isDragging) {\n // cache drag state in the form\n form.dragState = this.stopDragging();\n }\n }\n\n beforeMorphElement(e) {\n // Cancel morph if dragging to prevent swapping rows from under the user\n // An alternative would be to require ids on rows so morph can accurately\n // map before/after and avoid updating the row being dragged\n if (this.isDragging) e.preventDefault();\n }\n\n //endregion\n\n //region Helpers\n\n /**\n * Updates the position of the drag item with a relative offset. Updates\n * other items relative to the new position of the drag item, as required.\n *\n * @callback {OrderableListController~animate}\n * @param {number} offset\n */\n animate = (offset) => {\n const dragItem = this.dragItem;\n\n // Visually update the dragItem so it follows the cursor\n dragItem.dragUpdate(offset);\n\n // Visually updates the position of all items in the list relative to the\n // dragged item. No actual changes to orderings at this stage.\n let nextOffset = 0;\n\n this.orderedItems.forEach((item) => {\n if (item !== dragItem) item.updateVisually(nextOffset);\n nextOffset += item.height;\n });\n };\n\n get isDragging() {\n return !!this.dragState;\n }\n\n get dragItem() {\n if (!this.isDragging) return null;\n\n return this.items.find((item) => item.id === this.dragState.targetId);\n }\n\n /**\n * Returns the current items in the list in DOM order.\n *\n * @returns {Array[OrderableRowController]}\n */\n get items() {\n // Note, item outlets may include other items as the outlets do not have a\n // mechanism to specify an element scope.\n return this.tablesOrderableItemOutlets.filter((item) =>\n this.element.contains(item.element),\n );\n }\n\n get orderedItems() {\n const dragItem = this.dragItem;\n\n if (!dragItem) return this.items;\n\n return this.items.toSorted((a, b) => a.dragPosition - b.dragPosition);\n }\n\n /**\n * Returns the item outlet that was clicked on, if any.\n *\n * @param element {HTMLElement} the clicked ordinal cell\n * @returns {OrderableRowController}\n */\n #targetItem(element) {\n return this.items.find((item) => item.element === element);\n }\n\n #insertDragItem(orderedItems, dragItem) {\n const index = orderedItems.indexOf(dragItem);\n const previousItem = orderedItems[index - 1];\n const nextItem = orderedItems[index + 1];\n\n if (previousItem) {\n previousItem.row.insertAdjacentElement(\"afterend\", dragItem.row);\n } else if (nextItem) {\n nextItem.row.insertAdjacentElement(\"beforebegin\", dragItem.row);\n }\n }\n\n get #animationDuration() {\n const duration =\n window\n .getComputedStyle(this.element)\n .getPropertyValue(\"--animation-duration\") || \"150ms\";\n\n return parseTime(duration);\n }\n\n //endregion\n}\n\nfunction parseTime(value) {\n value = value.trim();\n\n if (value.endsWith(\"ms\")) return parseFloat(value);\n if (value.endsWith(\"s\")) return parseFloat(value) * 1000;\n\n return parseFloat(value) || 0;\n}\n\n/**\n * During drag we want to be able to translate a document-relative coordinate\n * into a coordinate relative to the list element. This state object calculates\n * and stores internal state so that we can translate absolute page coordinates\n * from mouse events into relative offsets for the list items within the list\n * element.\n *\n * We also keep track of the drag target so that if the controller is attached\n * to a new element during the drag we can continue after the turbo update.\n */\nclass DragState {\n /**\n * @param list {HTMLElement} the list controller's element (tbody)\n * @param event {MouseEvent} the initial event\n * @param id {String} the id of the element being dragged\n */\n constructor(list, event, id) {\n // cursor offset is the offset of the cursor relative to the drag item\n this.cursorOffset = event.offsetY;\n\n // initial offset is the offset position of the drag item at drag start\n this.initialPosition = event.target.offsetTop - list.offsetTop;\n\n // id of the item being dragged\n this.targetId = id;\n }\n\n /**\n * Calculates the offset of the drag item relative to its initial position.\n *\n * @param list {HTMLElement} the list controller's element (tbody)\n * @param row {HTMLElement} the row being dragged\n * @param event {MouseEvent} the current event\n * @param callback {OrderableListController~animate} updates the drag item with a relative offset\n */\n updateCursor(list, row, event, callback) {\n // Calculate and store the list offset relative to the viewport\n // This value is cached so we can calculate the outcome of any scroll events\n this.listOffset = list.getBoundingClientRect().top;\n\n // Calculate the position of the cursor relative to the list.\n // Accounts for scroll offsets by using the item's bounding client rect.\n const cursorPosition = event.clientY - this.listOffset;\n\n // intended item position relative to the list, from cursor position\n let itemPosition = cursorPosition - this.cursorOffset;\n\n this.#updateItemPosition(list, row, itemPosition, callback);\n }\n\n /**\n * Animates the item's position as the list scrolls. Requires a previous call\n * to set the scroll offset.\n *\n * @param list {HTMLElement} the list controller's element (tbody)\n * @param row {HTMLElement} the row being dragged\n * @param callback {OrderableListController~animate} updates the drag item with a relative offset\n */\n updateScroll(list, row, callback) {\n const previousScrollOffset = this.listOffset;\n\n // Calculate and store the list offset relative to the viewport\n // This value is cached so we can calculate the outcome of any scroll events\n this.listOffset = list.getBoundingClientRect().top;\n\n // Calculate the change in scroll offset since the last update\n const scrollDelta = previousScrollOffset - this.listOffset;\n\n // intended item position relative to the list, from cursor position\n const position = this.position + scrollDelta;\n\n this.#updateItemPosition(list, row, position, callback);\n }\n\n #updateItemPosition(list, row, position, callback) {\n // ensure itemPosition is within the bounds of the list (tbody)\n position = Math.max(position, 0);\n position = Math.min(position, list.offsetHeight - row.offsetHeight);\n\n // cache the item's position relative to the list for use in scroll events\n this.position = position;\n\n // Item has position: relative, so we want to calculate the amount to move\n // the item relative to it's DOM position to represent how much it has been\n // dragged by.\n const offset = position - this.initialPosition;\n\n // Convert itemPosition from offset relative to list to offset relative to\n // its position within the DOM (if it hadn't moved).\n callback(offset);\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\n\n/**\n * Couples an input element in a row to the selection form which is turbo-permanent and outside the table.\n * When the input is toggled, the form will create/destroy hidden inputs. The checkbox inside this cell will follow\n * the hidden inputs.\n *\n * Cell value may change when:\n * * cell connects, e.g. when the user paginates\n * * cell is re-used by turbo-morph, e.g. pagination\n * * cell is toggled\n * * select-all/de-select-all on table header\n */\nexport default class SelectionItemController extends Controller {\n static outlets = [\"tables--selection--form\"];\n static values = {\n params: Object,\n checked: Boolean,\n };\n\n tablesSelectionFormOutletConnected(form) {\n form.visible(this.id, true);\n this.checkedValue = form.isSelected(this.id);\n }\n\n disconnect() {\n // Remove from form's list of visible selections.\n // This should be an outlet disconnect, but those events are not reliable in turbo 8.0\n if (this.hasTablesSelectionFormOutlet) {\n this.tablesSelectionFormOutlet.visible(this.id, false);\n }\n }\n\n change(e) {\n e.preventDefault();\n\n this.checkedValue = this.tablesSelectionFormOutlet.toggle(this.id);\n }\n\n get id() {\n return this.paramsValue.id;\n }\n\n /**\n * Update checked to match match selection form. This occurs when the item is re-used by turbo-morph.\n */\n paramsValueChanged(params, previous) {\n if (!this.hasTablesSelectionFormOutlet) return;\n\n // if id is changing (e.g. morph) then let the form know that the previous id is now not visible\n if (previous.id !== params.id) {\n this.tablesSelectionFormOutlet.visible(previous.id, false);\n }\n\n // tell form that our id is now visible in the table\n this.tablesSelectionFormOutlet.visible(params.id, true);\n\n // id has changed, so update checked from form\n this.checkedValue = this.tablesSelectionFormOutlet.isSelected(params.id);\n\n // propagate changes\n this.update();\n }\n\n /**\n * Update input to match checked. This occurs when the item is toggled, connected, or morphed.\n */\n checkedValueChanged() {\n if (!this.hasTablesSelectionFormOutlet) return;\n\n // ensure that checked matches the form, i.e. if morphed\n this.checkedValue = this.tablesSelectionFormOutlet.isSelected(this.id);\n\n // propagate changes\n this.update();\n }\n\n /**\n * Notify table that id or value may have changed. Note that this may fire when nothing has changed.\n *\n * Debouncing to minimise dom updates.\n */\n async update() {\n this.updating ||= Promise.resolve().then(() => {\n this.#update();\n delete this.updating;\n });\n\n return this.updating;\n }\n\n #update() {\n this.element.querySelector(\"input\").checked = this.checkedValue;\n this.dispatch(\"select\", {\n detail: { id: this.id, selected: this.checkedValue },\n });\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\n\nexport default class QueryInputController extends Controller {\n static targets = [\"input\", \"highlight\"];\n static values = { query: String };\n\n connect() {\n this.queryValue = this.inputTarget.value;\n this.element.dataset.connected = \"\";\n }\n\n disconnect() {\n delete this.element.dataset.connected;\n }\n\n update() {\n this.queryValue = this.inputTarget.value;\n }\n\n queryValueChanged(query) {\n this.highlightTarget.innerHTML = \"\";\n\n new Parser().parse(query).tokens.forEach((token) => {\n this.highlightTarget.appendChild(token.render());\n });\n }\n\n replaceToken(e) {\n let tokenToAdd = e.detail.token.toString();\n\n // wrap in quotes if it contains a spaces or special characters\n if (/\\s/.exec(tokenToAdd)) {\n tokenToAdd = `\"${tokenToAdd}\"`;\n }\n\n const indexPosition = e.detail.position;\n let caretPosition = indexPosition + tokenToAdd.length;\n let sliceStart = indexPosition;\n let sliceEnd = indexPosition;\n\n // detect if position has a token already, if so, replace it\n const existingToken = new Parser()\n .parse(this.queryValue)\n .tokenAtPosition(indexPosition);\n if (existingToken) {\n // We don't want to include the trailing space as we are replacing an existing value\n tokenToAdd = tokenToAdd.trim();\n\n // Slice up to the beginning of the tokens value (not the initial caret position)\n sliceStart = existingToken.startOfValue();\n\n // Slice after the end of the tokens value\n sliceEnd = existingToken.endOfValue();\n\n // The end position of the newly added token\n caretPosition = sliceStart + tokenToAdd.length;\n }\n\n // Replace any text within sliceStart and sliceEnd with tokenToAdd\n this.inputTarget.value =\n this.queryValue.slice(0, sliceStart) +\n tokenToAdd +\n this.queryValue.slice(sliceEnd);\n\n // Re focus the input at the end of the newly added token\n this.update();\n this.inputTarget.focus();\n this.inputTarget.setSelectionRange(caretPosition, caretPosition);\n }\n}\n\nclass Parser {\n constructor() {\n this.tokens = [];\n this.values = null;\n }\n\n parse(input) {\n const query = new StringScanner(input);\n\n while (!query.isEos()) {\n this.push(this.skipWhitespace(query));\n\n const value = this.takeTagged(query) || this.takeUntagged(query);\n\n if (!this.push(value)) break;\n }\n\n return this;\n }\n\n push(token) {\n if (token) {\n this.values ? this.values.push(token) : this.tokens.push(token);\n }\n\n return !!token;\n }\n\n skipWhitespace(query) {\n if (!query.scan(/\\s+/)) return;\n\n return new Token(query.matched(), query.position);\n }\n\n takeUntagged(query) {\n if (!query.scan(/\\S+/)) return;\n\n return new Untagged(query.matched(), query.position);\n }\n\n takeTagged(query) {\n if (!query.scan(/(\\w+(?:\\.\\w+)?)(:\\s*)/)) return;\n\n const key = query.valueAt(1);\n const separator = query.valueAt(2);\n\n const value =\n this.takeArrayValue(query) || this.takeSingleValue(query) || new Token();\n\n return new Tagged(key, separator, value, query.position);\n }\n\n takeArrayValue(query) {\n if (!query.scan(/\\[\\s*/)) return;\n\n const start = new Token(query.matched(), query.position);\n const values = (this.values = []);\n\n while (!query.isEos()) {\n if (!this.push(this.takeSingleValue(query))) break;\n if (!this.push(this.takeDelimiter(query))) break;\n }\n\n query.scan(/\\s*]/);\n const end = new Token(query.matched(), query.position);\n\n this.values = null;\n\n return new ArrayToken(start, values, end);\n }\n\n takeDelimiter(query) {\n if (!query.scan(/\\s*,\\s*/)) return;\n\n return new Token(query.matched(), query.position);\n }\n\n takeSingleValue(query) {\n return this.takeQuotedValue(query) || this.takeUnquotedValue(query);\n }\n\n takeQuotedValue(query) {\n if (!query.scan(/\"([^\"]*)\"/)) return;\n\n return new Value(query.matched(), query.position);\n }\n\n takeUnquotedValue(query) {\n if (!query.scan(/[^ \\],]*/)) return;\n\n return new Value(query.matched(), query.position);\n }\n\n tokenAtPosition(position) {\n return this.tokens\n .filter((t) => t instanceof Tagged || t instanceof Untagged)\n .find((t) => t.range.includes(position));\n }\n}\n\nclass Token {\n constructor(value = \"\", position) {\n this.value = value;\n this.length = this.value.length;\n this.start = position - this.length;\n this.end = this.start + this.length;\n this.range = this.arrayRange(this.start, this.end);\n }\n\n render() {\n return document.createTextNode(this.value);\n }\n\n arrayRange(start, stop) {\n return Array.from(\n { length: stop - start + 1 },\n (value, index) => start + index,\n );\n }\n\n startOfValue() {\n return this.start;\n }\n\n endOfValue() {\n return this.end;\n }\n}\n\nclass Value extends Token {\n render() {\n const span = document.createElement(\"span\");\n span.className = \"value\";\n span.innerText = this.value;\n\n return span;\n }\n}\n\nclass Tagged extends Token {\n constructor(key, separator, value, position) {\n super();\n\n this.key = key;\n this.separator = separator;\n this.value = value;\n this.length = key.length + separator.length + value.value.length;\n this.start = position - this.length;\n this.end = this.start + this.length;\n this.range = this.arrayRange(this.start, this.end);\n }\n\n render() {\n const span = document.createElement(\"span\");\n span.className = \"tag\";\n\n const key = document.createElement(\"span\");\n key.className = \"key\";\n key.innerText = this.key;\n\n span.appendChild(key);\n span.appendChild(document.createTextNode(this.separator));\n span.appendChild(this.value.render());\n\n return span;\n }\n\n startOfValue() {\n return this.value.startOfValue();\n }\n\n endOfValue() {\n return this.value.endOfValue();\n }\n}\n\nclass Untagged extends Token {\n render() {\n const span = document.createElement(\"span\");\n span.className = \"untagged\";\n span.innerText = this.value;\n return span;\n }\n}\n\nclass ArrayToken extends Token {\n constructor(start, values, end) {\n super();\n\n this.start = start;\n this.values = values;\n this.end = end;\n this.range = this.arrayRange(start.start, end.range[end.length]);\n this.length =\n start.length +\n values.reduce((length, value) => length + value.length, 0) +\n end.length;\n }\n\n render() {\n const array = document.createElement(\"span\");\n array.className = \"array-values\";\n array.appendChild(this.start.render());\n\n this.values.forEach((value) => {\n const span = document.createElement(\"span\");\n span.appendChild(value.render());\n array.appendChild(span);\n });\n\n array.appendChild(this.end.render());\n\n return array;\n }\n\n startOfValue() {\n return this.start.start;\n }\n\n endOfValue() {\n return this.end.end;\n }\n}\n\nclass StringScanner {\n constructor(input) {\n this.input = input;\n this.position = 0;\n this.last = null;\n }\n\n isEos() {\n return this.position >= this.input.length;\n }\n\n scan(regex) {\n const match = regex.exec(this.input.substring(this.position));\n if (match?.index === 0) {\n this.last = match;\n this.position += match[0].length;\n return true;\n } else {\n this.last = {};\n return false;\n }\n }\n\n matched() {\n return this.last && this.last[0];\n }\n\n valueAt(index) {\n return this.last && this.last[index];\n }\n}\n","import OrderableItemController from \"./orderable/item_controller\";\nimport OrderableListController from \"./orderable/list_controller\";\nimport OrderableFormController from \"./orderable/form_controller\";\nimport SelectionFormController from \"./selection/form_controller\";\nimport SelectionItemController from \"./selection/item_controller\";\nimport SelectionTableController from \"./selection/table_controller\";\nimport QueryController from \"./query_controller\";\nimport QueryInputController from \"./query_input_controller\";\n\nconst Definitions = [\n {\n identifier: \"tables--orderable--item\",\n controllerConstructor: OrderableItemController,\n },\n {\n identifier: \"tables--orderable--list\",\n controllerConstructor: OrderableListController,\n },\n {\n identifier: \"tables--orderable--form\",\n controllerConstructor: OrderableFormController,\n },\n {\n identifier: \"tables--selection--form\",\n controllerConstructor: SelectionFormController,\n },\n {\n identifier: \"tables--selection--item\",\n controllerConstructor: SelectionItemController,\n },\n {\n identifier: \"tables--selection--table\",\n controllerConstructor: SelectionTableController,\n },\n {\n identifier: \"tables--query\",\n controllerConstructor: QueryController,\n },\n {\n identifier: \"tables--query-input\",\n controllerConstructor: QueryInputController,\n },\n];\n\nexport { Definitions as default };\n","import { Controller } from \"@hotwired/stimulus\";\n\nexport default class OrderableRowController extends Controller {\n static values = {\n params: Object,\n };\n\n connect() {\n // index from server may be inconsistent with the visual ordering,\n // especially if this is a new node. Use positional indexes instead,\n // as these are the values we will send on save.\n this.index = domIndex(this.row);\n }\n\n paramsValueChanged(params) {\n this.id = params.id_value;\n }\n\n dragUpdate(offset) {\n this.dragOffset = offset;\n this.row.style.position = \"relative\";\n this.row.style.transform = `scale(1.01) translateY(${offset}px)`;\n this.row.style.zIndex = \"1\";\n this.row.toggleAttribute(\"dragging\", true);\n }\n\n /**\n * Called on items that are not the dragged item during drag. Updates the\n * visual position of the item relative to the dragged item.\n *\n * @param offset {number} intended offset of the item during drag\n */\n updateVisually(offset) {\n this.row.style.transform = `translateY(${offset - this.#offsetTop}px)`;\n }\n\n captureDropPosition() {\n this.dropTop = this.#viewportTop;\n }\n\n invertDropPosition() {\n delete this.dragOffset;\n this.row.removeAttribute(\"dragging\");\n this.row.style.transition = \"transform 0s\";\n this.row.style.transform = \"\";\n this.row.style.transform = `translateY(${this.dropTop - this.#viewportTop}px)`;\n }\n\n playDrop() {\n this.row.style.transition = \"\";\n this.row.style.transform = \"\";\n }\n\n /**\n * Set the index value of the item. This is called on all items after a drop\n * event. If the index is different to the params index then this item has\n * changed.\n *\n * @param index {number} the new index value\n */\n updateIndex(index) {\n this.index = index;\n }\n\n /** Retrieve params for use in the form */\n params(scope) {\n const { id_name, id_value, index_name } = this.paramsValue;\n return [\n { name: `${scope}[${id_value}][${id_name}]`, value: this.id },\n { name: `${scope}[${id_value}][${index_name}]`, value: this.index },\n ];\n }\n\n /**\n * Restore any visual changes made during drag and remove the drag state.\n */\n reset() {\n delete this.dragOffset;\n delete this.dropTop;\n this.row.removeAttribute(\"style\");\n this.row.removeAttribute(\"dragging\");\n }\n\n /**\n * @returns {boolean} true when the item has a change to its index value\n */\n get hasChanges() {\n return this.paramsValue.index_value !== this.index;\n }\n\n /**\n * Value for use in comparisons during drag. Used by ListController to\n * determine whether the dragged item is above or below another item.\n *\n * @returns {number}\n */\n get dragPosition() {\n return this.dragOffset && this.dragOffset !== 0\n ? this.#leadingEdge\n : this.#midpoint;\n }\n\n /**\n * The containing row element.\n *\n * @returns {HTMLElement}\n */\n get row() {\n return this.element.parentElement;\n }\n\n get height() {\n return this.row.offsetHeight;\n }\n\n get #midpoint() {\n return this.#offsetTop + this.height / 2;\n }\n\n get #leadingEdge() {\n const top = this.#offsetTop + this.dragOffset;\n\n return this.dragOffset < 0 ? top : top + this.height;\n }\n\n get #offsetTop() {\n return this.row.offsetTop;\n }\n\n get #viewportTop() {\n return this.row.getBoundingClientRect().top;\n }\n}\n\nfunction domIndex(element) {\n return Array.from(element.parentElement.children).indexOf(element);\n}\n","import { Controller } from \"@hotwired/stimulus\";\n\nexport default class OrderableFormController extends Controller {\n static values = { scope: String };\n\n add(item) {\n item.params(this.scopeValue).forEach(({ name, value }) => {\n this.element.insertAdjacentHTML(\n \"beforeend\",\n `<input type=\"hidden\" name=\"${name}\" value=\"${value}\" data-generated>`,\n );\n });\n }\n\n submit() {\n if (this.inputs.length === 0) return;\n\n this.element.requestSubmit();\n }\n\n clear() {\n this.inputs.forEach((input) => input.remove());\n }\n\n get inputs() {\n return this.element.querySelectorAll(\"input[data-generated]\");\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\n\nexport default class SelectionFormController extends Controller {\n static values = {\n count: Number,\n primaryKey: { type: String, default: \"id\" },\n };\n static targets = [\"count\", \"singular\", \"plural\"];\n\n connect() {\n this.countValue = this.inputs.length;\n }\n\n /**\n * @param id to toggle\n * @return {boolean} true if selected, false if unselected\n */\n toggle(id) {\n const input = this.input(id);\n\n if (input) {\n input.remove();\n } else {\n this.element.insertAdjacentHTML(\n \"beforeend\",\n `<input type=\"hidden\" name=\"${this.primaryKeyValue}[]\" value=\"${id}\">`,\n );\n }\n\n this.countValue = this.visibleInputs.length;\n\n return !input;\n }\n\n /**\n * @param id to toggle visibility\n * @return {boolean} true if visible, false if not visible\n */\n visible(id, visible) {\n const input = this.input(id);\n\n if (input) {\n input.disabled = !visible;\n }\n\n this.countValue = this.visibleInputs.length;\n\n return !input;\n }\n\n /**\n * @returns {boolean} true if the given id is currently selected\n */\n isSelected(id) {\n return !!this.input(id);\n }\n\n get inputs() {\n return this.element.querySelectorAll(\n `input[name=\"${this.primaryKeyValue}[]\"]`,\n );\n }\n\n get visibleInputs() {\n return Array.from(this.inputs).filter((i) => !i.disabled);\n }\n\n input(id) {\n return this.element.querySelector(\n `input[name=\"${this.primaryKeyValue}[]\"][value=\"${id}\"]`,\n );\n }\n\n countValueChanged(count) {\n this.element.toggleAttribute(\"hidden\", count === 0);\n this.countTargets.forEach((el) => (el.textContent = count));\n this.singularTargets.forEach((el) =>\n el.toggleAttribute(\"hidden\", count !== 1),\n );\n this.pluralTargets.forEach((el) =>\n el.toggleAttribute(\"hidden\", count === 1),\n );\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\n\nexport default class SelectionTableController extends Controller {\n static targets = [\"header\", \"item\"];\n static outlets = [\"tables--selection--form\"];\n\n itemTargetConnected(item) {\n this.update();\n }\n\n itemTargetDisconnected(item) {\n this.update();\n }\n\n toggleHeader(e) {\n this.items.forEach((item) => {\n if (item.checkedValue === e.target.checked) return;\n\n item.checkedValue = this.tablesSelectionFormOutlet.toggle(item.id);\n });\n }\n\n async update() {\n this.updating ||= Promise.resolve().then(() => {\n this.#update();\n delete this.updating;\n });\n\n return this.updating;\n }\n\n #update() {\n let present = 0;\n let checked = 0;\n\n this.items.forEach((item) => {\n present++;\n if (item.checkedValue) checked++;\n });\n\n this.headerInput.checked = present > 0 && checked === present;\n this.headerInput.indeterminate = checked > 0 && checked !== present;\n }\n\n get headerInput() {\n return this.headerTarget.querySelector(\"input\");\n }\n\n get items() {\n return this.itemTargets.map((el) => this.#itemOutlet(el)).filter((c) => c);\n }\n\n /**\n * Ideally we would be using outlets, but as of turbo 8.0.4 outlets do not fire disconnect events when morphing.\n *\n * Instead, we're using the targets to finds the controller.\n */\n #itemOutlet(el) {\n return this.application.getControllerForElementAndIdentifier(\n el,\n \"tables--selection--item\",\n );\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\n\nexport default class QueryController extends Controller {\n static targets = [\"modal\"];\n\n disconnect() {\n delete this.pending;\n\n document.removeEventListener(\"selectionchange\", this.selection);\n }\n\n focus() {\n if (document.activeElement === this.query) return;\n\n this.query.addEventListener(\n \"focusin\",\n (e) => {\n e.target.setSelectionRange(-1, -1);\n },\n { once: true },\n );\n\n this.query.focus();\n }\n\n closeModal() {\n delete this.modalTarget.dataset.open;\n this.query.setAttribute(\"aria-expanded\", false);\n\n if (document.activeElement === this.query) document.activeElement.blur();\n\n document.removeEventListener(\"selectionchange\", this.selection);\n }\n\n openModal() {\n this.modalTarget.dataset.open = true;\n this.query.setAttribute(\"aria-expanded\", true);\n\n document.addEventListener(\"selectionchange\", this.selection);\n }\n\n /**\n * If the user presses escape once, clear the input.\n * If the user presses escape again, get them out of here.\n */\n clear() {\n if (this.query.value === \"\") {\n this.closeModal();\n } else {\n this.query.value = \"\";\n this.query.dispatchEvent(new Event(\"input\"));\n this.query.dispatchEvent(new Event(\"change\"));\n this.update();\n }\n }\n\n submit() {\n const hasFocus = this.isFocused;\n const position = hasFocus && this.query.selectionStart;\n\n if (this.pending) {\n clearTimeout(this.pending);\n delete this.pending;\n }\n\n // add/remove current cursor position\n if (hasFocus && this.query.value !== \"\") {\n this.position.value = position;\n this.position.disabled = false;\n } else {\n this.position.value = \"\";\n this.position.disabled = true;\n }\n\n // prevent an unnecessary `?q=&p=0` parameter from appearing in the URL\n if (this.query.value === \"\") {\n this.query.disabled = true;\n\n // restore input and focus after form submission\n setTimeout(() => {\n this.query.disabled = false;\n this.position.disabled = false;\n if (hasFocus) this.query.focus();\n }, 0);\n }\n }\n\n update = () => {\n if (this.pending) clearTimeout(this.pending);\n this.pending = setTimeout(() => {\n this.element.requestSubmit();\n }, 300);\n };\n\n selection = () => {\n if (this.isFocused && this.query.value.length > 0) this.update();\n };\n\n beforeMorphAttribute(e) {\n switch (e.detail.attributeName) {\n case \"data-open\":\n e.preventDefault();\n break;\n }\n }\n\n moveToPreviousSuggestion() {\n const prev = this.previousSuggestion || this.lastSuggestion;\n\n if (prev) this.makeSuggestionActive(prev);\n }\n\n moveToNextSuggestion() {\n const next = this.nextSuggestion || this.firstSuggestion;\n\n if (next) this.makeSuggestionActive(next);\n }\n\n selectFirstSuggestion(e) {\n // This is caused by pressing the tab key. We don't want to move focus.\n // Ideally we don't want to always prevent the user from tabbing. We will address this later\n e.preventDefault();\n\n this.firstSuggestion?.dispatchEvent(new CustomEvent(\"query:select\"));\n }\n\n selectActiveSuggestion() {\n if (!this.activeSuggestion) {\n this.closeModal();\n return;\n }\n\n this.activeSuggestion.dispatchEvent(new CustomEvent(\"query:select\"));\n }\n\n selectSuggestion(e) {\n this.query.dispatchEvent(\n new CustomEvent(\"replaceToken\", {\n detail: { token: e.params.value, position: this.query.selectionStart },\n }),\n );\n\n this.clearActiveSuggestion();\n }\n\n makeSuggestionActive(node) {\n if (this.activeSuggestion) {\n this.activeSuggestion.setAttribute(\"aria-selected\", \"false\");\n }\n\n this.query.setAttribute(\"aria-activedescendant\", node.id);\n node.setAttribute(\"aria-selected\", \"true\");\n }\n\n clearActiveSuggestion() {\n if (this.activeSuggestion) {\n this.activeSuggestion.setAttribute(\"aria-selected\", \"false\");\n this.query.removeAttribute(\"aria-activedescendant\");\n }\n }\n\n get activeSuggestion() {\n return this.modalTarget.querySelector(\n `#${this.query.getAttribute(\"aria-activedescendant\")}`,\n );\n }\n\n get previousSuggestion() {\n return this.activeSuggestion?.previousElementSibling;\n }\n\n get nextSuggestion() {\n return this.activeSuggestion?.nextElementSibling;\n }\n\n get firstSuggestion() {\n return this.modalTarget.querySelector(\"#suggestions li:first-of-type\");\n }\n\n get lastSuggestion() {\n return this.modalTarget.querySelector(\"#suggestions li:last-of-type\");\n }\n\n get query() {\n return this.element.querySelector(\"[role=combobox]\");\n }\n\n get position() {\n return this.element.querySelector(\"input[name=p]\");\n }\n\n get isFocused() {\n return this.query === document.activeElement;\n }\n}\n"],"names":["DragState","constructor","list","event","id","this","cursorOffset","offsetY","initialPosition","target","offsetTop","targetId","updateCursor","row","callback","listOffset","getBoundingClientRect","top","itemPosition","clientY","updateItemPosition","updateScroll","previousScrollOffset","scrollDelta","position","Math","max","min","offsetHeight","SelectionItemController","Controller","static","params","Object","checked","Boolean","tablesSelectionFormOutletConnected","form","visible","checkedValue","isSelected","disconnect","hasTablesSelectionFormOutlet","tablesSelectionFormOutlet","change","e","preventDefault","toggle","paramsValue","paramsValueChanged","previous","update","checkedValueChanged","updating","Promise","resolve","then","element","querySelector","dispatch","detail","selected","Parser","tokens","values","parse","input","query","StringScanner","isEos","push","skipWhitespace","value","takeTagged","takeUntagged","token","scan","Token","matched","Untagged","key","valueAt","separator","takeArrayValue","takeSingleValue","Tagged","start","takeDelimiter","end","ArrayToken","takeQuotedValue","takeUnquotedValue","Value","tokenAtPosition","filter","t","find","range","includes","length","arrayRange","render","document","createTextNode","stop","Array","from","index","startOfValue","endOfValue","span","createElement","className","innerText","super","appendChild","reduce","array","forEach","last","regex","match","exec","substring","Definitions","identifier","controllerConstructor","connect","parentElement","children","indexOf","id_value","dragUpdate","offset","dragOffset","style","transform","zIndex","toggleAttribute","updateVisually","captureDropPosition","dropTop","viewportTop","invertDropPosition","removeAttribute","transition","playDrop","updateIndex","scope","id_name","index_name","name","reset","hasChanges","index_value","dragPosition","leadingEdge","midpoint","height","direction","type","String","default","startDragging","dragState","addEventListener","mousemove","mouseup","window","scroll","stopDragging","removeEventListener","items","item","drop","dragItem","insertDragItem","orderedItems","count","directionValue","commitChanges","requestAnimationFrame","setTimeout","animationDuration","tablesOrderableFormOutlet","clear","add","submit","mousedown","isDragging","targetItem","animate","ticking","dropped","tablesOrderableFormOutletConnected","tablesOrderableFormOutletDisconnected","beforeMorphElement","nextOffset","tablesOrderableItemOutlets","contains","toSorted","a","b","previousItem","nextItem","insertAdjacentElement","duration","getComputedStyle","getPropertyValue","trim","endsWith","parseFloat","scopeValue","insertAdjacentHTML","inputs","requestSubmit","remove","querySelectorAll","Number","primaryKey","countValue","primaryKeyValue","visibleInputs","disabled","i","countValueChanged","countTargets","el","textContent","singularTargets","pluralTargets","itemTargetConnected","itemTargetDisconnected","toggleHeader","present","headerInput","indeterminate","headerTarget","itemTargets","map","itemOutlet","c","application","getControllerForElementAndIdentifier","pending","selection","focus","activeElement","setSelectionRange","once","closeModal","modalTarget","dataset","open","setAttribute","blur","openModal","dispatchEvent","Event","hasFocus","isFocused","selectionStart","clearTimeout","beforeMorphAttribute","attributeName","moveToPreviousSuggestion","prev","previousSuggestion","lastSuggestion","makeSuggestionActive","moveToNextSuggestion","next","nextSuggestion","firstSuggestion","selectFirstSuggestion","CustomEvent","selectActiveSuggestion","activeSuggestion","selectSuggestion","clearActiveSuggestion","node","getAttribute","previousElementSibling","nextElementSibling","queryValue","inputTarget","connected","queryValueChanged","highlightTarget","innerHTML","replaceToken","tokenToAdd","toString","indexPosition","caretPosition","sliceStart","sliceEnd","existingToken","slice"],"mappings":"gDAqRA,MAAMA,EAMJ,WAAAC,CAAYC,EAAMC,EAAOC,GAEvBC,KAAKC,aAAeH,EAAMI,QAG1BF,KAAKG,gBAAkBL,EAAMM,OAAOC,UAAYR,EAAKQ,UAGrDL,KAAKM,SAAWP,CAClB,CAUA,YAAAQ,CAAaV,EAAMW,EAAKV,EAAOW,GAG7BT,KAAKU,WAAab,EAAKc,wBAAwBC,IAO/C,IAAIC,EAHmBf,EAAMgB,QAAUd,KAAKU,WAGRV,KAAKC,aAEzCD,MAAKe,EAAoBlB,EAAMW,EAAKK,EAAcJ,EACpD,CAUA,YAAAO,CAAanB,EAAMW,EAAKC,GACtB,MAAMQ,EAAuBjB,KAAKU,WAIlCV,KAAKU,WAAab,EAAKc,wBAAwBC,IAG/C,MAAMM,EAAcD,EAAuBjB,KAAKU,WAG1CS,EAAWnB,KAAKmB,SAAWD,EAEjClB,MAAKe,EAAoBlB,EAAMW,EAAKW,EAAUV,EAChD,CAEA,EAAAM,CAAoBlB,EAAMW,EAAKW,EAAUV,GAEvCU,EAAWC,KAAKC,IAAIF,EAAU,GAC9BA,EAAWC,KAAKE,IAAIH,EAAUtB,EAAK0B,aAAef,EAAIe,cAGtDvB,KAAKmB,SAAWA,EAShBV,EAJeU,EAAWnB,KAAKG,gBAKjC,ECxVa,MAAMqB,UAAgCC,EACnDC,eAAiB,CAAC,2BAClBA,cAAgB,CACdC,OAAQC,OACRC,QAASC,SAGX,kCAAAC,CAAmCC,GACjCA,EAAKC,QAAQjC,KAAKD,IAAI,GACtBC,KAAKkC,aAAeF,EAAKG,WAAWnC,KAAKD,GAC3C,CAEA,UAAAqC,GAGMpC,KAAKqC,8BACPrC,KAAKsC,0BAA0BL,QAAQjC,KAAKD,IAAI,EAEpD,CAEA,MAAAwC,CAA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,GAAOJ,OAAOuD,QAAS3C,IACxCtE,KAAK2R,gBAAgB7K,YAAYxC,EAAM0B,WAE3C,CAEA,YAAA6L,CAAarP,GACX,IAAIsP,EAAatP,EAAEe,OAAOe,MAAMyN,WAG5B,KAAK1K,KAAKyK,KACZA,EAAa,IAAIA,MAGnB,MAAME,EAAgBxP,EAAEe,OAAOpC,SAC/B,IAAI8Q,EAAgBD,EAAgBF,EAAWhM,OAC3CoM,EAAaF,EACbG,EAAWH,EAGf,MAAMI,GAAgB,IAAI3O,GACvBG,MAAM5D,KAAKuR,YACX/L,gBAAgBwM,GACfI,IAEFN,EAAaA,EAAWlF,OAGxBsF,EAAaE,EAAc7L,eAG3B4L,EAAWC,EAAc5L,aAGzByL,EAAgBC,EAAaJ,EAAWhM,QAI1C9F,KAAKwR,YAAYrN,MACfnE,KAAKuR,WAAWc,MAAM,EAAGH,GACzBJ,EACA9R,KAAKuR,WAAWc,MAAMF,GAGxBnS,KAAK8C,SACL9C,KAAKwR,YAAYvC,QACjBjP,KAAKwR,YAAYrC,kBAAkB8C,EAAeA,EACpD"}
@@ -1,9 +1,4 @@
1
1
  <%= form_with(method: :patch, **html_attributes) do |form| %>
2
- <p class="tables--selection--summary">
3
- <span data-<%= form_target("count") %>>0</span>
4
- <span data-<%= form_target("singular") %> hidden><%= singular_name %></span>
5
- <span data-<%= form_target("plural") %>><%= plural_name %></span>
6
- selected
7
- </p>
2
+ <p class="tables--selection--summary"><%= t(".summary_html", selection: selection_tag) %></p>
8
3
  <%= content %>
9
4
  <% end %>
@@ -5,6 +5,8 @@ module Katalyst
5
5
  module Selectable
6
6
  class FormComponent < ViewComponent::Base # :nodoc:
7
7
  include Katalyst::HtmlAttributes
8
+
9
+ using Katalyst::HtmlAttributes::HasHtmlAttributes
8
10
  include Katalyst::Tables::Identifiable::Defaults
9
11
 
10
12
  attr_reader :id, :primary_key
@@ -26,6 +28,38 @@ module Katalyst
26
28
  "#<#{self.class.name} id: #{id.inspect}, primary_key: #{primary_key.inspect}>"
27
29
  end
28
30
 
31
+ # Renders the number of selected rows and the model name, e.g. "1 person" or "2 people", updated as the
32
+ # selection changes.
33
+ #
34
+ # The result is HTML safe, so it can be interpolated into an `_html` translation to describe the
35
+ # selection, e.g. `t(".download_html", selection: selection.selection_tag)`.
36
+ #
37
+ # @param options [Hash] html attributes for the wrapping span (id, aria, class, data, html)
38
+ def selection_tag(**options)
39
+ tag.span(safe_join([count_tag, " ", singular_tag, plural_tag]), **options_to_html_attributes(options))
40
+ end
41
+
42
+ # Renders a span containing the number of selected rows, updated as the selection changes.
43
+ #
44
+ # @param options [Hash] html attributes for the span (id, aria, class, data, html)
45
+ def count_tag(**options)
46
+ target_tag("count", "0", options)
47
+ end
48
+
49
+ # Renders a span containing the singular model name, visible when exactly one row is selected.
50
+ #
51
+ # @param options [Hash] html attributes for the span (id, aria, class, data, html)
52
+ def singular_tag(**options)
53
+ target_tag("singular", singular_name, options, hidden: true)
54
+ end
55
+
56
+ # Renders a span containing the plural model name, visible unless exactly one row is selected.
57
+ #
58
+ # @param options [Hash] html attributes for the span (id, aria, class, data, html)
59
+ def plural_tag(**options)
60
+ target_tag("plural", plural_name, options)
61
+ end
62
+
29
63
  private
30
64
 
31
65
  def default_html_attributes
@@ -44,8 +78,9 @@ module Katalyst
44
78
  FORM_CONTROLLER
45
79
  end
46
80
 
47
- def form_target(value)
48
- "#{FORM_CONTROLLER}-target=#{value}"
81
+ def target_tag(target, content, options, **defaults)
82
+ attributes = { data: { "#{FORM_CONTROLLER}-target": target }, **defaults }
83
+ tag.span(content, **attributes.merge_html(options_to_html_attributes(options)))
49
84
  end
50
85
 
51
86
  def singular_name
@@ -73,8 +73,12 @@ export default class SelectionFormController extends Controller {
73
73
 
74
74
  countValueChanged(count) {
75
75
  this.element.toggleAttribute("hidden", count === 0);
76
- this.countTarget.textContent = count;
77
- this.singularTarget.toggleAttribute("hidden", count !== 1);
78
- this.pluralTarget.toggleAttribute("hidden", count === 1);
76
+ this.countTargets.forEach((el) => (el.textContent = count));
77
+ this.singularTargets.forEach((el) =>
78
+ el.toggleAttribute("hidden", count !== 1),
79
+ );
80
+ this.pluralTargets.forEach((el) =>
81
+ el.toggleAttribute("hidden", count === 1),
82
+ );
79
83
  }
80
84
  }
@@ -46,7 +46,7 @@ module Katalyst
46
46
  end
47
47
 
48
48
  def model_name
49
- @model_name ||= items.model_name.tap do |name|
49
+ @model_name ||= items.model_name.dup.tap do |name|
50
50
  name.param_key = param_key
51
51
  end
52
52
  end
@@ -6,6 +6,9 @@ en:
6
6
  placeholder: "Filter %{name}"
7
7
  modal_component:
8
8
  suggestions_title: "Search options"
9
+ selectable:
10
+ form_component:
11
+ summary_html: "%{selection} selected"
9
12
  orderable:
10
13
  value:
11
14
  "⠿"
@@ -16,7 +16,7 @@ module Katalyst
16
16
  return false unless filterable?
17
17
 
18
18
  if attribute.came_from_user?
19
- attribute.value_before_type_cast.present? || value === false
19
+ !blank_input?(attribute.value_before_type_cast)
20
20
  else
21
21
  !value.nil? && !value.eql?([])
22
22
  end
@@ -39,8 +39,29 @@ module Katalyst
39
39
 
40
40
  private
41
41
 
42
+ # Blank values are removed, as for other multiple value types.
42
43
  def cast_value(value)
43
- value.to_s
44
+ value.to_s.presence
45
+ end
46
+
47
+ # Active Record filters unknown enum values on IS NULL. Unknown values
48
+ # can't match any row, so remove them, and match nothing if none remain.
49
+ def apply_filter(scope, model, attribute, value)
50
+ mapping = model.defined_enums[attribute.name.split(".").last]
51
+
52
+ # not a Rails enum, leave it to the database
53
+ return super if mapping.nil?
54
+
55
+ known = known_values(mapping, Array(value))
56
+
57
+ known.any? ? super(scope, model, attribute, known) : scope.none
58
+ end
59
+
60
+ # Accepts labels and database values, matching Active Record.
61
+ def known_values(mapping, values)
62
+ database_values = mapping.values.map(&:to_s)
63
+
64
+ values.select { |v| mapping.key?(v) || database_values.include?(v) }
44
65
  end
45
66
  end
46
67
  end
@@ -14,6 +14,15 @@ module Katalyst
14
14
  def initialize(**)
15
15
  super(**, delegate: ActiveModel::Type::Float)
16
16
  end
17
+
18
+ private
19
+
20
+ # ActiveModel accepts "NaN", but NaN is not equal to anything, so
21
+ # treat it as invalid input.
22
+ def cast_value(value)
23
+ result = super
24
+ result unless result.is_a?(::Float) && result.nan?
25
+ end
17
26
  end
18
27
  end
19
28
  end
@@ -67,6 +67,8 @@ module Katalyst
67
67
  value.grep_v(::Range)
68
68
  when ::Range
69
69
  value
70
+ when nil
71
+ []
70
72
  else
71
73
  [value]
72
74
  end
@@ -12,7 +12,17 @@ module Katalyst
12
12
  define_range_patterns(/-?\d+/)
13
13
 
14
14
  def initialize(**)
15
- super(**, delegate: ActiveModel::Type::Integer)
15
+ super(**, delegate: Unbounded)
16
+ end
17
+
18
+ # Integer values are checked against the column's range by Active
19
+ # Record when filtering, which matches nothing for out of range values.
20
+ # BigInteger skips ActiveModel's own 4 byte range check, and limit: 8
21
+ # avoids truncating bigint values when casting from strings.
22
+ class Unbounded < ActiveModel::Type::BigInteger
23
+ def initialize(**)
24
+ super(limit: 8, **)
25
+ end
16
26
  end
17
27
  end
18
28
  end
@@ -24,7 +24,7 @@ module Katalyst
24
24
  return false unless filterable?
25
25
 
26
26
  if attribute.came_from_user?
27
- attribute.value_before_type_cast.present?
27
+ !blank_input?(attribute.value_before_type_cast)
28
28
  else
29
29
  value.present?
30
30
  end
@@ -33,6 +33,11 @@ module Katalyst
33
33
  def filter(scope, attribute, value: filter_value(attribute))
34
34
  return scope unless filter?(attribute, value)
35
35
 
36
+ value = without_null_bytes(value)
37
+
38
+ # user input was supplied but it can't match anything
39
+ return scope.none if value.nil?
40
+
36
41
  if self.scope.present?
37
42
  scope.public_send(self.scope, value)
38
43
  elsif attribute.name.include?(".")
@@ -88,6 +93,34 @@ module Katalyst
88
93
  Tables::Suggestions::DatabaseValue.new(name: attribute.name, type: attribute.type, value:)
89
94
  end
90
95
 
96
+ # Strings containing NUL bytes can't be sent to the database: Postgres
97
+ # raises ArgumentError when quoting and SQLite truncates the literal.
98
+ # No row can match them, so they are removed before filtering.
99
+ def without_null_bytes(value)
100
+ case value
101
+ when ::String
102
+ value unless value.include?("\0")
103
+ when ::Array
104
+ kept = value.reject { |v| v.is_a?(::String) && v.include?("\0") }
105
+ kept unless kept.empty? && value.any?
106
+ else
107
+ value
108
+ end
109
+ end
110
+
111
+ # Blank input means nothing was chosen, e.g. the hidden blank value that
112
+ # Rails multiple selects submit. False is input for boolean filters.
113
+ def blank_input?(value)
114
+ case value
115
+ when ::Array
116
+ value.all? { |v| blank_input?(v) }
117
+ when ::String
118
+ value.blank?
119
+ else
120
+ value.nil?
121
+ end
122
+ end
123
+
91
124
  def filter_value(attribute)
92
125
  attribute.value
93
126
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: katalyst-tables
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.15.0
4
+ version: 3.16.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Katalyst Interactive