UNPKG

@digital-blueprint/formalize-app

Version:

[GitHub Repository](https://github.com/digital-blueprint/formalize-app) | [npmjs package](https://www.npmjs.com/package/@digital-blueprint/formalize-app) | [Unpkg CDN](https://unpkg.com/browse/@digital-blueprint/formalize-app/) | [Formalize Bundle](https:

91 lines (88 loc) • 15 kB
/*! * License: LGPL-2.1-or-later * Dependencies: * * @webcomponents/scoped-custom-element-registry: BSD-3-Clause * @dbp-toolkit/app-shell: LGPL-2.1-or-later * lit-html: BSD-3-Clause * @dbp-toolkit/language-select: LGPL-2.1-or-later * @dbp-toolkit/auth: LGPL-2.1-or-later * @dbp-toolkit/theme-switcher: LGPL-2.1-or-later * universal-router: MIT * @dbp-toolkit/matomo: LGPL-2.1-or-later * cssfilter: MIT * xss: MIT * @dbp-toolkit/form-elements: LGPL-2.1-or-later * html2pdf.js: MIT * exceljs: MIT * jspdf-autotable: MIT * keycloak-js: Apache-2.0 * pdfjs-dist: Apache-2.0 * jszip: (MIT OR GPL-3.0-or-later) * @babel/runtime: MIT * fflate: MIT * iobuffer: MIT * pako: (MIT AND Zlib) * fast-png: MIT * jspdf: MIT * core-js: MIT * performance-now: MIT * raf: MIT * rgbcolor: MIT OR SEE LICENSE IN FEEL-FREE.md * svg-pathdata: MIT * stackblur-canvas: MIT * canvg: MIT * dompurify: (MPL-2.0 OR Apache-2.0) * i18next: MIT * @dbp-toolkit/common: LGPL-2.1-or-later * @lit/reactive-element: BSD-3-Clause * lit-element: BSD-3-Clause * @open-wc/dedupe-mixin: MIT * @open-wc/scoped-elements: MIT * dialog-polyfill: BSD * jquery: MIT * select2: MIT * @dbp-toolkit/notification: LGPL-2.1-or-later * @dbp-toolkit/tabulator-table: LGPL-2.1-or-later * tabulator-tables: MIT * @dbp-toolkit/file-handling: LGPL-2.1-or-later * webdav: MIT * jose: MIT * file-saver: MIT * @dbp-toolkit/grant-permission-dialog: LGPL-2.1-or-later * @dbp-toolkit/pdf-viewer: LGPL-2.1-or-later * @dbp-toolkit/resource-select: LGPL-2.1-or-later */ import{A as e,w as t}from"./ref.DqB7ABXf.js";import{C as n,H as r,I as i,J as a,O as o,Q as s,T as c,X as l,c as u,k as d,l as f,m as p,v as m}from"./directive-helpers.C6Xz79AM.js";import{t as h}from"./utils.BtSYiqoX.js";import{i as g,n as _,r as v,t as y}from"./select2.min.DRitHUO_.js";v();var b=/* @__PURE__ */ e(_(),1),x={select:{"component-disabled":`Diese Komponente ist deaktiviert`,loading:`Wird geladen...`,"login-required":`Anmeldung erforderlich`,placeholder:`Bitte wählen Sie einen Eintrag aus`,"placeholder-multiple":`Bitte wählen Sie einen oder mehrere Einträge aus`}},S={select:{"component-disabled":`This component is disabled`,loading:`Loading...`,"login-required":`Login required`,placeholder:`Please select an entry`,"placeholder-multiple":`Please select one or more entries`}};function C(){return s({en:S,de:x},`de`,`en`)}function w(){return{errorLoading:function(){return`Die Ergebnisse konnten nicht geladen werden.`},inputTooLong:function(e){return`Bitte `+(e.input.length-e.maximum)+` Zeichen weniger eingeben`},inputTooShort:function(e){return`Bitte `+(e.minimum-e.input.length)+` Zeichen mehr eingeben`},loadingMore:function(){return`Lade mehr Ergebnisse…`},maximumSelected:function(e){var t=`Sie können nur `+e.maximum+` Eintr`;return e.maximum===1?t+=`ag`:t+=`äge`,t+=` auswählen`,t},noResults:function(){return`Keine Übereinstimmungen gefunden`},searching:function(){return`Suche…`},removeAllItems:function(){return`Auswahl aufheben`}}}function T(){return{errorLoading:function(){return`The results could not be loaded.`},inputTooLong:function(e){var t=e.input.length-e.maximum,n=`Please delete `+t+` character`;return t!=1&&(n+=`s`),n},inputTooShort:function(e){return`Please enter `+(e.minimum-e.input.length)+` or more characters`},loadingMore:function(){return`Loading more results…`},maximumSelected:function(e){var t=`You can only select `+e.maximum+` item`;return e.maximum!=1&&(t+=`s`),t},noResults:function(){return`No results found`},searching:function(){return`Searching…`},removeAllItems:function(){return`Remove selection`}}}async function E(e,t,n){let r=[],i=e;for(;i;){let e=await fetch(i,{headers:{"Content-Type":`application/ld+json`,"Accept-Language":t,Authorization:`Bearer `+n()}});if(!e.ok)throw Error(e.statusText);let a=await e.json(),o=a[`hydra:member`];o&&(r=r.concat(o)),i=a[`hydra:view`]?.[`hydra:next`]??null,i&&=new URL(i,e.url).href}return r}var D=class extends f(u(d(p)),C){constructor(){super(),this._resources=[],this._url=null,this._lang=null,this._isSearching=!1,this._selectedObjects=/* @__PURE__ */ new Map,this._selectId=`select-resource-`+r(24),this.auth={},this.entryPointUrl=null,this.resourcePath=null,this.multiple=!1,this.values=[],this.valueObjects=[],this.value=null,this.valueObject=null,this.disabled=!1,this.perPage=100,this.fetchMode=`prefetch`,this.noDefault=!1,this.placeholder=null,this._appliedValue=this.value,this._appliedValues=this.values,this._onDocumentClicked=this._onDocumentClicked.bind(this),(0,b.default)(window,g)}static get properties(){return{...super.properties,entryPointUrl:{type:String,attribute:`entry-point-url`},resourcePath:{type:String,attribute:`resource-path`},noDefault:{type:Boolean,attribute:`no-default`},multiple:{type:Boolean,reflect:!0},value:{type:String,reflect:!0},values:{type:Array},disabled:{type:Boolean},perPage:{type:Number,attribute:`per-page`},fetchMode:{type:String,attribute:`fetch-mode`},placeholder:{type:String}}}static get scopedElements(){return{...super.scopedElements,"dbp-mini-spinner":t}}_getSelect2(){return this._$(`#`+this._selectId)}_$(e){return g(this.renderRoot.querySelector(e))}_IsSelect2Initialized(e){return e!==null&&e.hasClass(`select2-hidden-accessible`)}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this._onDocumentClicked),this._updateAll()}disconnectedCallback(){document.removeEventListener(`click`,this._onDocumentClicked),super.disconnectedCallback()}_onDocumentClicked(e){if(!e.composedPath().includes(this)){let e=this._getSelect2();e.length&&this._IsSelect2Initialized(e)&&e.select2(`close`)}}_clearSelect2(){let e=this._getSelect2();console.assert(e.length,`select2 missing`),this._IsSelect2Initialized(e)&&(e.off(`select2:select`),e.off(`select2:unselect`),e.off(`select2:clear`),e.off(`select2:closing`),e.empty().trigger(`change`),e.select2(`destroy`))}buildUrl(e,t){return t}async reset(){this._isClearable()?this._setSelection([],[]):(this._selectedObjects.clear(),this.values=[],this.valueObjects=[],this.value=null,this.valueObject=null,this._appliedValues=this.values,this._appliedValue=null),await this._updateAll()}formatResource(e,t){return t.name??t[`@id`]}loginCallback(){this._updateAll()}logoutCallback(){this._updateAll()}_getPlaceholder(){let e=this._i18n;return this.disabled?e.t(`select.component-disabled`):this.isLoggedIn()?this.placeholder===null?this.multiple?e.t(`select.placeholder-multiple`):e.t(`select.placeholder`):this.placeholder:e.t(`select.login-required`)}getCollectionQueryParameters(e){return{}}getSearchQueryParameters(e,t){return t=t.trim(),t?{search:t}:{}}getItemParameters(e){return{}}getItemQueryParameters(e){return this.getItemParameters(e)}_setQueryParameters(e,t){for(let[n,r]of new URLSearchParams(t))e.searchParams.append(n,r)}_getCollectionUrl(e){if(this.entryPointUrl===null)return null;let t=this.entryPointUrl;this.resourcePath!==null&&(t=new URL(this.resourcePath,this.entryPointUrl).href),t=this.buildUrl(this,t);let n=new URL(t);return this._setQueryParameters(n,this.getCollectionQueryParameters(this)),e!==void 0&&this._setQueryParameters(n,this.getSearchQueryParameters(this,e)),n.searchParams.has(`perPage`)||n.searchParams.set(`perPage`,String(this.perPage)),n.href}_getUrl(){return this._getCollectionUrl()}_getText(e){return this.formatResource(this,e)}_hasValue(e=this.value){return e!=null&&e!==``}_isClearable(){return this.multiple||this.fetchMode===`search`||this.noDefault}_findResource(e){for(let t of this._resources)if(t[`@id`]===e)return t;return this._selectedObjects.get(e)??null}_setSelection(e,t=null){let n=(e??[]).filter((e,t,n)=>this._hasValue(e)&&n.indexOf(e)===t);this.multiple||(n=n.slice(0,1));let r=n.map((e,n)=>t===null?this._findResource(e):t[n]??null),i=this.values.length!==n.length||n.some((e,t)=>this.values[t]!==e),a=this.valueObjects.length!==r.length||r.some((e,t)=>this.valueObjects[t]!==e);if(this._selectedObjects.clear(),n.forEach((e,t)=>{r[t]!==null&&this._selectedObjects.set(e,r[t])}),i&&(this.values=n),a&&(this.valueObjects=r),this.value=n[0]??null,this.valueObject=r[0]??null,this._appliedValues=this.values,this._appliedValue=this.value,!i&&!a)return;let o=new CustomEvent(`change`,{bubbles:!0,composed:!0,detail:{value:this.value,object:this.valueObject,values:this.values,objects:this.valueObjects}});this.dispatchEvent(o)}_getRequestedValues(){return this.values===this._appliedValues?this.value===this._appliedValue?this.values:this._hasValue(this.value)?[this.value]:[]:this.values}async _updateAll(){this._setSelection(this._getRequestedValues());let e=this._getSelect2();if(!this.isLoggedIn()){await this._setSelect2Placeholder(this._getPlaceholder());return}if(this._IsSelect2Initialized(e)||await this._setSelect2Loading(),this.fetchMode===`search`){await this._updateSelect2Search();return}await this._updateResources(),await this._updateSelect2()}async _setSelect2Placeholder(e){await this.updateComplete;let t=this._getSelect2();console.assert(t.length,`select2 missing`),this._clearSelect2(),t.select2({width:`100%`,language:this.lang===`de`?w():T(),placeholder:e,data:[],disabled:!0})}async _setSelect2Loading(){await this._setSelect2Placeholder(this._i18n.t(`select.loading`))}async _updateResources(){let e=this._getUrl();e===null||e===this._url&&this.lang===this._lang||(this._resources=await E(e,this.lang,()=>this.auth.token),this._url=e,this._lang=this.lang,this._setSelection(this.values))}async updateResources(){if(!this.isLoggedIn()){await this._setSelect2Placeholder(this._getPlaceholder());return}if(this.fetchMode===`search`){await this._updateSelect2Search();return}let e=this._getUrl();e!==null&&this.lang!==null&&(this._resources=await E(e,this.lang,()=>this.auth.token),this._url=e,this._setSelection(this.values),await this._updateSelect2())}_getResourceUrl(e){let t=h(this.entryPointUrl,e),n=new URL(t);return this._setQueryParameters(n,this.getItemQueryParameters(this)),n.href}async _fetchResource(e){let t=await fetch(this._getResourceUrl(e),{headers:{"Content-Type":`application/ld+json`,"Accept-Language":this.lang,Authorization:`Bearer `+this.auth.token}});if(!t.ok)throw Error(t.statusText);return await t.json()}async _updateSearchValue(){if(!this.values.length){this._setSelection([],[]);return}let e=await Promise.allSettled(this.values.map(e=>this._fetchResource(e))),t=this._getSelect2();t.empty();let n=[],r=[];this.values.forEach((i,a)=>{let o=e[a];if(o.status!==`fulfilled`){console.log(o.reason),n.push(i),r.push(null);return}let s=o.value,c=s[`@id`]??i;n.push(c),r.push(s);let l=new Option(this._getText(s),c,!0,!0);t.append(l)}),t.trigger(`change`),this._resources=r.filter(e=>e!==null),this._setSelection(n,r)}_renderResult(e){if(!e.loading)return e.text;let t=document.createElement(`span`);return t.classList.add(`loading-entry`),t.appendChild(this.createScopedElement(`dbp-mini-spinner`)),t.appendChild(document.createTextNode(e.text)),t}async _updateSelect2Search(){if(await this.updateComplete,this._getCollectionUrl()===null)return;let e=this._getSelect2();if(console.assert(e.length,`select2 missing`),this._clearSelect2(),e.select2({width:`100%`,language:this.lang===`de`?w():T(),minimumInputLength:2,multiple:this.multiple,allowClear:this._isClearable(),placeholder:this._getPlaceholder(),dropdownParent:this._$(`#select-resource-dropdown`),disabled:this.disabled,templateResult:e=>this._renderResult(e),ajax:{delay:300,url:e=>this._getCollectionUrl(e.term??``),data:e=>({}),contentType:`application/ld+json`,beforeSend:e=>{e.setRequestHeader(`Authorization`,`Bearer `+this.auth.token),e.setRequestHeader(`Accept-Language`,this.lang),this._isSearching=!0},processResults:e=>{let t=e[`hydra:member`]??[];return this._resources=t,{results:t.map(e=>({id:e[`@id`],_resultId:`result-${e[`@id`]}`,text:this._getText(e),resource:e}))}},complete:()=>{this._isSearching=!1}}}).on(`select2:clear`,()=>{this._setSelection([],[])}).on(`select2:select`,e=>{let t=e.params.data,n=t.resource??null;this.multiple?this._setSelection([...this.values,t.id],[...this.valueObjects,n]):this._setSelection([t.id],[n])}).on(`select2:unselect`,e=>{let t=this.values.indexOf(e.params.data.id);if(t===-1)return;let n=[...this.values],r=[...this.valueObjects];n.splice(t,1),r.splice(t,1),this._setSelection(n,r)}).on(`select2:closing`,e=>{this._isSearching&&e.preventDefault()}),this.values.length)try{await this._updateSearchValue()}catch(e){console.log(e),this._setSelection(this.values,this.values.map(()=>null))}else e.val(null).trigger(`change`)}async _updateSelect2(){await this.updateComplete;let e=this._getSelect2();console.assert(e.length,`select2 missing`);let t=this._resources.map(e=>({id:e[`@id`],text:this._getText(e)}));t.sort((e,t)=>e.text<t.text?-1:+(e.text>t.text)),this._clearSelect2(),e.select2({width:`100%`,language:this.lang===`de`?w():T(),placeholder:this._getPlaceholder(),dropdownParent:this._$(`#select-resource-dropdown`),data:t,disabled:this.disabled,multiple:this.multiple,allowClear:this._isClearable()}).on(`select2:clear`,()=>{this._setSelection([],[])}).on(`select2:select select2:unselect`,()=>{this._setSelection(e.select2(`data`).map(e=>e.id))}),!this.multiple&&!this.values.length&&t.length&&!this.noDefault&&this._setSelection([t[0].id]),e.val(this.multiple?this.values:this.value).trigger(`change`)}update(e){e.has(`multiple`)&&e.get(`multiple`)!==void 0&&this._clearSelect2(),super.update(e);let t=this.values!==this._appliedValues||this.value!==this._appliedValue;(e.has(`lang`)||t||e.has(`resourcePath`)||e.has(`entryPointUrl`)||e.has(`perPage`)||e.has(`disabled`)||e.has(`noDefault`)||e.has(`multiple`)||e.has(`fetchMode`))&&this._updateAll()}static get styles(){return[o(),m(),n(),c(),l` .select { position: relative; overflow: visible; } .select > .select2-container--open { left: 0 !important; position: absolute !important; top: 100% !important; width: 100% !important; z-index: 1; } /* The "Searching…" entry of the dropdown, see _renderResult() */ .loading-entry { display: flex; align-items: center; gap: 0.5em; } `]}render(){let e=i(y);return a` <link rel="stylesheet" href="${e}" /> <div class="select" id="select-resource-dropdown"> <div class="select2-control control"> <select id="${this._selectId}" name="select-resources" class="select" ?multiple="${this.multiple}" style="visibility: hidden;"></select> </div> <div id="select-resource-dropdown"></div> </div> `}};export{D as t}; //# sourceMappingURL=resource-select.Bx5DnWv9.js.map