@ulb-darmstadt/shacl-form 3.2.1 → 3.3.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.
@@ -3,6 +3,8 @@ import { Term } from '@rdfjs/types';
3
3
  import { ShaclNode } from './node.js';
4
4
  import { ShaclProperty } from './property.js';
5
5
  import { Config } from './config.js';
6
- export declare function createShaclOrConstraint(options: Term[], context: ShaclNode | ShaclProperty, config: Config): HTMLElement;
6
+ import { ShaclPropertyTemplate } from './property-template.js';
7
+ export declare function createShaclOrConstraint(options: Term[], context: ShaclNode | ShaclProperty, config: Config, predicate?: string, propertyTemplate?: ShaclPropertyTemplate): HTMLElement;
8
+ export declare function createAlternativePathConstraint(property: ShaclProperty, value?: Term, linked?: boolean, forceRemovable?: boolean): HTMLElement;
7
9
  export declare function resolveShaclOrConstraintOnProperty(subjects: Term[], value: Term, config: Config): Quad[];
8
10
  export declare function resolveShaclOrConstraintOnNode(subjects: Term[], value: Term, config: Config): Term[];
@@ -0,0 +1,9 @@
1
+ import { Term } from '@rdfjs/types';
2
+ import { BlankNode, Literal, NamedNode } from 'n3';
3
+ import type { Editor } from './theme.js';
4
+ export type EditorTerm = NamedNode | BlankNode | Literal;
5
+ export declare function bindEditorTerm(editor: Editor, term: Term | null | undefined): void;
6
+ export declare function bindEditorTerms(editor: Editor, terms: Iterable<Term>): void;
7
+ export declare function rdfTermId(term: Term): string;
8
+ export declare function readEditorTerm(editor: Editor): EditorTerm | undefined;
9
+ export declare function editorToTerm(editor: Editor): EditorTerm | undefined;
package/dist/form.d.ts CHANGED
@@ -36,6 +36,7 @@ export declare class ShaclForm extends HTMLElement {
36
36
  refreshQueryFacets(): void;
37
37
  validate(ignoreEmptyValues?: boolean): Promise<ValidationReport>;
38
38
  private assertNotQueryMode;
39
+ private refreshClassInstanceEditors;
39
40
  private createValidationErrorDisplay;
40
41
  private findRootShaclShapeSubject;
41
42
  private removeFromDataGraph;
package/dist/group.d.ts CHANGED
@@ -1,2 +1,5 @@
1
1
  import { Config } from './config.js';
2
- export declare function createShaclGroup(groupSubject: string, config: Config): HTMLElement;
2
+ export declare function createShaclGroup(groupSubject: string, config: Config): {
3
+ element: HTMLElement;
4
+ order: number;
5
+ };
package/dist/index.js CHANGED
@@ -1,15 +1,19 @@
1
- import{C as e,D as t,E as n,F as r,G as i,I as a,J as o,K as s,L as c,M as l,O as u,P as d,R as f,T as p,V as m,W as h,Y as g,_,b as v,c as y,d as b,f as x,g as S,h as C,i as w,j as T,k as E,l as D,m as O,n as k,q as A,r as j,s as M,t as ee,u as N,x as P,y as F,z as I}from"./assets/query-rxkbsWqy.js";import{DataFactory as L,Literal as R,NamedNode as z,Store as B}from"n3";import{RokitButton as V,RokitCollapsible as H,RokitInput as U,RokitSelect as W,RokitTextArea as G}from"@ro-kit/ui-widgets";import{Validator as K}from"shacl-engine";var q=`
1
+ import{$ as e,A as t,B as n,C as r,E as i,F as a,G as o,H as s,I as c,J as l,M as u,N as d,Q as ee,R as f,S as p,U as m,V as h,X as g,Y as _,Z as v,_ as y,b,c as x,d as S,f as C,g as w,h as T,i as E,j as D,k as O,l as k,m as A,n as te,r as j,s as ne,t as M,u as N,v as P,w as F,y as I,z as L}from"./assets/query-CWN5zxbg.js";import{BlankNode as R,DataFactory as z,Literal as B,NamedNode as V,Store as H}from"n3";import{RokitButton as U,RokitCollapsible as W,RokitInput as G,RokitSelect as K,RokitTextArea as q}from"@ro-kit/ui-widgets";import{Validator as J}from"shacl-engine";var Y=`
2
2
  .editor:not([type='checkbox']) { border: 1px solid var(--shacl-border-color, #DDD); }
3
3
  .property-instance label { display: inline-flex; word-break: break-word; line-height: 1em; padding-top: 0.15em; padding-right: 1em; flex-shrink: 0; position: relative; }
4
4
  .property-instance:not(:first-child) > label:not(.persistent) { visibility: hidden; max-height: 0; }
5
5
  .mode-edit .property-instance label { width: var(--label-width); }
6
- `,J=class extends _{constructor(e){super(e||q),this.idCtr=0}createDefaultTemplate(e,t,n,r,a){if(r.id=`e${this.idCtr++}`,r.classList.add(`editor`),r.setAttribute(`part`,`editor`),a?.datatype?r.shaclDatatype=a.datatype:t instanceof R&&(r.shaclDatatype=t.datatype),a&&P(a)>0&&(r.dataset.minCount=String(P(a))),a?.class&&(r.dataset.class=a.class.value),a?.nodeKind)r.dataset.nodeKind=a.nodeKind.value;else if(t&&(t instanceof z||a?.nodeKind?.equals(i))&&(r.dataset.nodeKind=m+`IRI`,a)){let e=d(a.config.store.getQuads(t,null,null,null),a.config.languages);e&&(r.dataset.value=`<`+t.value+`>`,t=L.literal(e))}(a?.hasValue&&t||a?.readonly)&&(r.disabled=!0);let o=t?.value||a?.defaultValue?.value||``;a?.datatype?.equals(g)?r.checked=t?.value===`true`||a?.defaultValue?.value===`true`:r.type===`file`?r.binaryData=o||void 0:r.value=o;let s=document.createElement(`label`);s.htmlFor=r.id,s.innerText=e,s.setAttribute(`part`,`label`),a?.description&&s.setAttribute(`title`,a.description.value);let c=a?.description?a.description.value:a?.pattern?a.pattern:null;c&&r.setAttribute(`placeholder`,c),n&&(r.setAttribute(`required`,`true`),s.classList.add(`required`));let l=document.createElement(`div`);return l.setAttribute(`part`,`field`),l.appendChild(s),l.appendChild(r),l}createDateEditor(e,t,n,i){let o=new U;i.datatype?.value===`http://www.w3.org/2001/XMLSchema#dateTime`?(o.type=`datetime-local`,o.setAttribute(`step`,`1`)):o.type=`date`,o.clearable=!0,o.dense=this.dense,o.classList.add(`pr-0`);let s=this.createDefaultTemplate(e,null,n,o,i);if(t){let e=i.datatype?.value===`http://www.w3.org/2001/XMLSchema#dateTime`?r(t.value):a(t.value);e?(o.value=e.value,e.suffix&&(o.dataset.xsdTemporalSuffix=e.suffix)):console.error(`unable to parse xsd date literal`,t)}return s}createTextEditor(e,t,n,r){let i;return r.singleLine===!1?(i=new G,i.resize=`auto`):i=new U,i.dense=this.dense,r.pattern&&(i.pattern=r.pattern),r.minLength&&(i.minLength=r.minLength),r.maxLength&&(i.maxLength=r.maxLength),this.createDefaultTemplate(e,t,n,i,r)}createLangStringEditor(e,t,n,r){let i=this.createTextEditor(e,t,n,r),a=i.querySelector(`:scope .editor`),o;if(r.languageIn?.length){o=document.createElement(`select`);for(let e of r.languageIn){let t=document.createElement(`option`);t.innerText=e.value,o.appendChild(t)}}else o=document.createElement(`input`),o.maxLength=5,o.size=5,o.placeholder=`lang?`;return o.title=`Language of the text`,o.classList.add(`lang-chooser`),o.setAttribute(`part`,`lang-chooser`),o.slot=`suffix`,a.addEventListener(`change`,()=>{o.required=a.value!==``}),o.addEventListener(`change`,e=>{e.stopPropagation(),a&&(a.dataset.lang=o.value,a.dispatchEvent(new Event(`change`,{bubbles:!0})))}),t instanceof R&&(o.value=t.language),a.dataset.lang=o.value,a.appendChild(o),i}createBooleanEditor(e,t,n,r){let i=document.createElement(`input`);i.type=`checkbox`,i.classList.add(`ml-0`);let a=this.createDefaultTemplate(e,null,n,i,r);return i.removeAttribute(`required`),a.querySelector(`:scope label`)?.classList.remove(`required`),t instanceof R&&(i.checked=t.value===`true`),a}createFileEditor(e,t,n,r){let i=document.createElement(`input`);return i.type=`file`,i.addEventListener(`change`,e=>{if(i.files?.length){e.stopPropagation();let t=new FileReader;t.readAsDataURL(i.files[0]),t.onload=()=>{i.binaryData=btoa(t.result),i.parentElement?.dispatchEvent(new Event(`change`,{bubbles:!0}))}}else i.binaryData=void 0}),this.createDefaultTemplate(e,t,n,i,r)}createNumberEditor(e,t,n,r){let i=new U,a=I.has(r.datatype?.value??``);i.type=a?`text`:`number`,a&&(i.pattern=r.datatype?.value===`http://www.w3.org/2001/XMLSchema#decimal`?`[+\\-]?(?:[0-9]+(?:[.,][0-9]*)?|[.,][0-9]+)`:`[+\\-]?(?:[0-9]+(?:[.,][0-9]*)?|[.,][0-9]+)(?:[eE][+\\-]?[0-9]+)?`,i.updateComplete.then(()=>{i.inputElement.inputMode=`decimal`})),i.clearable=!0,i.dense=this.dense,i.classList.add(`pr-0`);let o=r.minInclusive===void 0?r.minExclusive===void 0?void 0:r.minExclusive+1:r.minInclusive,s=r.maxInclusive===void 0?r.maxExclusive===void 0?void 0:r.maxExclusive-1:r.maxInclusive;return o!==void 0&&(i.min=String(o)),s!==void 0&&(i.max=String(s)),!a&&r.datatype?.value!==`http://www.w3.org/2001/XMLSchema#integer`&&(i.step=`any`),this.createDefaultTemplate(e,t,n,i,r)}createListEditor(e,t,n,r,i){let a=new W;a.clearable=!0,a.dense=this.dense;let o=this.createDefaultTemplate(e,null,n,a,i),s=document.createElement(`ul`),c=!0,l=(e,t)=>{let n=document.createElement(`li`);if(typeof e.value==`string`?(n.dataset.value=e.value,n.innerText=e.label?e.label:e.value):(n.dataset.value=e.value.id,e.value instanceof z&&(n.dataset.value=`<`+n.dataset.value+`>`),n.innerText=e.label?e.label:e.value.value),t.appendChild(n),e.children?.length){c=!1;let t=document.createElement(`ul`);n.appendChild(t);for(let n of e.children)l(n,t)}};for(let e of r)l(e,s);return c||(a.collapse=!0),a.appendChild(s),t=t??i?.defaultValue??null,t&&(a.value=t.id,t instanceof z&&(a.value=`<`+a.value+`>`)),o}createButton(e,t){let n=new V;return n.dense=this.dense,n.innerHTML=e,t?(n.setAttribute(`primary`,``),n.setAttribute(`part`,`button primary`)):n.setAttribute(`part`,`button`),n}},Y=class{constructor(){this.shapes=null,this.shapesUrl=null,this.shapeSubject=null,this.values=null,this.valuesUrl=null,this.valueSubject=null,this.valuesSubject=null,this.valuesNamespace=``,this.valuesGraph=null,this.view=null,this.mode=null,this.language=null,this.loading=`Loading…`,this.proxy=null,this.ignoreOwlImports=null,this.collapse=null,this.hierarchyColors=null,this.submitButton=null,this.generateNodeShapeReference=f.value,this.showNodeIds=null,this.showRootShapeLabel=null,this.dense=`true`,this.useShadowRoot=`true`}},X=`#4c93d785, #f85e9a85, #00327385, #87001f85`,Z=class{constructor(e){this.attributes=new Y,this.mode=`edit`,this.lists={},this.groups=[],this.renderedNodes=new Set,this._store=new B,this._nodeTemplates={},this._propertyTemplates={},this.validator=new K(this._store,{details:!0,factory:L}),this.providedConformingResourceIds={},this.providedResources={},this.providedResourceLabels={},this.form=e,this._theme=new J,this.languages=[...new Set(navigator.languages.flatMap(e=>e.length>2?[e.toLocaleLowerCase(),e.substring(0,2)]:e)),``]}reset(){this.lists={},this.groups=[],this.renderedNodes.clear(),this.providedConformingResourceIds={},this.providedResources={},this.providedResourceLabels={},this._nodeTemplates={},this._propertyTemplates={}}updateAttributes(e){let t=new Y;if(Object.keys(t).forEach(n=>{let r=e.dataset[n];r!==void 0&&(t[n]=r)}),t.mode!==null&&![`edit`,`view`,`query`].includes(t.mode))throw Error(`invalid shacl-form mode: ${t.mode}`);if(this.mode=t.mode??(t.view===null?`edit`:`view`),this.theme.setDense(t.dense===`true`),this.attributes=t,this.attributes.valueSubject&&!this.attributes.valuesSubject&&(this.attributes.valuesSubject=this.attributes.valueSubject),t.language){let e=this.languages.indexOf(t.language);e>-1&&this.languages.splice(e,1),this.languages.unshift(t.language)}if(t.valuesGraph&&(this.valuesGraphId=L.namedNode(t.valuesGraph)),t.hierarchyColors!=null){let e=t.hierarchyColors.length?t.hierarchyColors:X,n=`:host { --hierarchy-colors: ${e}; --hierarchy-colors-length: ${e.split(`,`).length} }`;for(let e=8;e>=0;e--){let t=`shacl-property { --hierarchy-level: ${e} }`;for(let n=0;n<e;n++)t=`shacl-property `+t;n=n+`
7
- `+t}this.hierarchyColorsStyleSheet=new CSSStyleSheet,this.hierarchyColorsStyleSheet.replaceSync(n)}}static dataAttributes(){let e=new Y;return Object.keys(e).map(e=>(e=e.replace(/[A-Z]/g,e=>`-`+e.toLowerCase()),`data-`+e))}buildTemplateKey(e,t){let n=e.value;return t&&(t instanceof v?n+=`*`+t.id.value:n+=`*`+this.buildTemplateKey(t.id,t.parent)),n}registerNodeTemplate(e){this._nodeTemplates[this.buildTemplateKey(e.id,e.parent)]=e}registerPropertyTemplate(e){this._propertyTemplates[this.buildTemplateKey(e.id,e.parent)]=e}getNodeTemplateIds(){let e=new Set;for(let t of Object.values(this._nodeTemplates))e.add(t.id.value);return e}getNodeTemplate(e,t){let n=this.buildTemplateKey(e,t),r=this._nodeTemplates[n];return r||=new j(e,this,t),r}getPropertyTemplate(e,t){let n=this.buildTemplateKey(e,t),r=this._propertyTemplates[n];return r||=new v(e,t),r}get nodeTemplates(){return Object.values(this._nodeTemplates)}get theme(){return this._theme}set theme(e){this._theme=e,e.setDense(this.attributes.dense===`true`)}get store(){return this._store}get editMode(){return this.mode===`edit`}get queryMode(){return this.mode===`query`}set store(e){this._store=e,this.lists=T(e,{ignoreErrors:!0}),this.groups=[],e.forSubjects(e=>{this.groups.push(e.id)},h,`${m}PropertyGroup`,null),this.validator=new K(e,{details:!0,factory:L})}},Q=200,$=class extends HTMLElement{static get observedAttributes(){return Z.dataAttributes()}constructor(){super(),this.shape=null,this.styleElement=null,this.form=document.createElement(`form`),this.form.setAttribute(`part`,`form`),this.config=new Z(this.form),this.form.addEventListener(`change`,e=>{e.stopPropagation(),this.config.queryMode?this.queryController?.handleChange():this.config.editMode&&this.validate(!0).then(e=>{this.dispatchEvent(new CustomEvent(`change`,{bubbles:!0,cancelable:!1,composed:!0,detail:{valid:e.conforms,report:e}}))}).catch(e=>{console.warn(e)})})}connectedCallback(){this.config.updateAttributes(this),this.ensureRenderRoot(),this.initialize()}attributeChangedCallback(){this.config.updateAttributes(this),this.ensureRenderRoot(),this.initialize()}initialize(){clearTimeout(this.initDebounceTimeout),this.queryController?.dispose(),this.queryController=void 0,this.setAttribute(`loading`,``),this.form.replaceChildren(document.createTextNode(this.config.attributes.loading)),this.initDebounceTimeout=setTimeout(async()=>{try{this.config.reset(),this.config.store=await b({shapes:this.config.attributes.shapes,shapesUrl:this.config.attributes.shapesUrl,values:this.config.attributes.values,valuesUrl:this.config.attributes.valuesUrl,valuesSubject:this.config.attributes.valuesSubject,loadOwlImports:this.config.attributes.ignoreOwlImports===null,classInstanceProvider:this.config.classInstanceProvider,rdfUrlResolver:this.config.rdfUrlResolver,proxy:this.config.attributes.proxy}),this.config.resourceLinkProvider&&await M(this.config),this.config.attributes.valuesSubject||(this.config.attributes.valuesSubject=D(this.config.store)||null),this.form.replaceChildren();let e=this.findRootShaclShapeSubject();if(e){if(this.form.classList.forEach(e=>{this.form.classList.remove(e)}),this.form.classList.toggle(`mode-edit`,this.config.editMode),this.form.classList.toggle(`mode-view`,this.config.mode===`view`),this.form.classList.toggle(`mode-query`,this.config.queryMode),this.config.queryMode){let{QueryModeController:e}=await F(async()=>{let{QueryModeController:e}=await import(`./assets/mode-C0O1k7Tm.js`);return{QueryModeController:e}},[]);this.queryController=new e(this)}this.config.theme.apply(this.form);let t=[this.config.theme.stylesheet];this.config.hierarchyColorsStyleSheet&&t.push(this.config.hierarchyColorsStyleSheet),this.queryController&&t.push(this.queryController.stylesheet);for(let e of O())e.stylesheet&&t.push(e.stylesheet);this.applyStyles(t);let n=new j(e,this.config);for(let e of this.config.nodeTemplates)w(e);if(this.shape=new k(n,this.config.attributes.valuesSubject?L.namedNode(this.config.attributes.valuesSubject):void 0),this.form.appendChild(this.shape),this.config.attributes.showRootShapeLabel!==null&&n.label){let e=document.createElement(`h3`);e.innerText=n.label.value,this.form.prepend(e)}if(this.config.editMode){if(this.config.attributes.submitButton!==null){let e=this.config.theme.createButton(this.config.attributes.submitButton||`Submit`,!0);e.classList.add(`submit-button`);let t=e.getAttribute(`part`);e.setAttribute(`part`,`${t?t+` `:``}submit-button`),e.addEventListener(`click`,e=>{e.preventDefault(),this.form.reportValidity()&&this.validate().then(e=>{if(e?.conforms)this.dispatchEvent(new Event(`submit`,{bubbles:!0,cancelable:!0}));else{let e=this.form.querySelector(`:scope .invalid > .editor`);e?e.focus():this.form.querySelector(`:scope .invalid`)?.scrollIntoView()}})}),this.form.appendChild(e)}(async()=>{await this.shape?.ready,this.config.attributes.valuesSubject&&this.removeFromDataGraph(L.namedNode(this.config.attributes.valuesSubject)),this.validate(!0)})()}else this.config.queryMode&&(await this.shape.ready,await this.queryController?.initialize())}else if(this.config.store.countQuads(null,null,null,o)>0)throw Error(`shacl root node shape not found`)}catch(e){console.error(e);let t=document.createElement(`div`);t.innerText=String(e),this.form.replaceChildren(t)}this.removeAttribute(`loading`),await this.shape?.ready,this.dispatchEvent(new Event(`ready`))},200)}ensureRenderRoot(){this.config.attributes.useShadowRoot===`false`?(this.shadowRoot?.contains(this.form)&&this.shadowRoot.removeChild(this.form),this.contains(this.form)||this.prepend(this.form)):(this.shadowRoot||this.attachShadow({mode:`open`}),this.shadowRoot.contains(this.form)||this.shadowRoot.prepend(this.form))}applyStyles(e){if(this.config.attributes.useShadowRoot!==`false`&&this.shadowRoot){this.shadowRoot.adoptedStyleSheets=e,this.styleElement&&=(this.styleElement.remove(),null);return}let t=e.map(e=>Array.from(e.cssRules).map(e=>e.cssText).join(`
6
+ `,X=class extends b{constructor(e){super(e||Y),this.idCtr=0}createDefaultTemplate(t,n,r,i,a){let s=n??a?.defaultValue??null;if(i.id=`e${this.idCtr++}`,i.classList.add(`editor`),i.setAttribute(`part`,`editor`),a?.datatype?i.shaclDatatype=a.datatype:n instanceof B&&(i.shaclDatatype=n.datatype),a&&F(a)>0&&(i.dataset.minCount=String(F(a))),a?.class&&(i.dataset.class=a.class.value),a?.nodeKind)i.dataset.nodeKind=a.nodeKind.value;else if(n&&(n instanceof V||a?.nodeKind?.equals(_))&&(i.dataset.nodeKind=o+`IRI`,a)){let e=f(a.config.store.getQuads(n,null,null,null),a.config.languages);e&&(n=z.literal(e))}(a?.hasValue&&n||a?.readonly)&&(i.disabled=!0);let c=n?.value||a?.defaultValue?.value||``;n instanceof R?c=n.id:n instanceof V&&a?.nodeKind?.value===`http://www.w3.org/ns/shacl#IRIOrLiteral`&&(c=`<${n.value}>`),a?.datatype?.equals(e)?i.checked=n?.value===`true`||a?.defaultValue?.value===`true`:i.type===`file`?i.binaryData=c||void 0:i.value=c,y(i,s);let l=document.createElement(`label`);l.htmlFor=i.id,l.innerText=t,l.setAttribute(`part`,`label`),a?.description&&l.setAttribute(`title`,a.description.value);let u=a?.description?a.description.value:a?.pattern?a.pattern:null;u&&i.setAttribute(`placeholder`,u),r&&(i.setAttribute(`required`,`true`),l.classList.add(`required`));let d=document.createElement(`div`);return d.setAttribute(`part`,`field`),d.appendChild(l),d.appendChild(i),d}createDateEditor(e,t,r,i){let a=new G;i.datatype?.value===`http://www.w3.org/2001/XMLSchema#dateTime`?(a.type=`datetime-local`,a.setAttribute(`step`,`1`)):a.type=`date`,a.clearable=!0,a.dense=this.dense,a.classList.add(`pr-0`);let o=this.createDefaultTemplate(e,null,r,a,i);if(t){let e=i.datatype?.value===`http://www.w3.org/2001/XMLSchema#dateTime`?L(t.value):n(t.value);e?(a.value=e.value,e.suffix&&(a.dataset.xsdTemporalSuffix=e.suffix)):console.error(`unable to parse xsd date literal`,t),y(a,t)}return o}createTextEditor(e,t,n,r){let i;return r.singleLine===!1?(i=new q,i.resize=`auto`):i=new G,i.dense=this.dense,r.pattern&&(i.pattern=r.pattern),r.minLength&&(i.minLength=r.minLength),r.maxLength&&(i.maxLength=r.maxLength),this.createDefaultTemplate(e,t,n,i,r)}createLangStringEditor(e,t,n,r){let i=this.createTextEditor(e,t,n,r),a=i.querySelector(`:scope .editor`),o;if(r.languageIn?.length){o=document.createElement(`select`);for(let e of r.languageIn){let t=document.createElement(`option`);t.innerText=e.value,o.appendChild(t)}}else o=document.createElement(`input`),o.maxLength=5,o.size=5,o.placeholder=`lang?`;return o.title=`Language of the text`,o.classList.add(`lang-chooser`),o.setAttribute(`part`,`lang-chooser`),o.slot=`suffix`,a.addEventListener(`change`,()=>{o.required=a.value!==``}),o.addEventListener(`change`,e=>{e.stopPropagation(),a&&(a.dataset.lang=o.value,a.dispatchEvent(new Event(`change`,{bubbles:!0})))}),t instanceof B&&(o.value=t.language),a.dataset.lang=o.value,y(a,t??r.defaultValue),a.appendChild(o),i}createBooleanEditor(e,t,n,r){let i=document.createElement(`input`);i.type=`checkbox`,i.classList.add(`ml-0`);let a=this.createDefaultTemplate(e,null,n,i,r);return i.removeAttribute(`required`),a.querySelector(`:scope label`)?.classList.remove(`required`),t instanceof B&&(i.checked=t.value===`true`,y(i,t)),a}createFileEditor(e,t,n,r){let i=document.createElement(`input`);return i.type=`file`,i.addEventListener(`change`,e=>{if(i.files?.length){e.stopPropagation();let t=new FileReader;t.readAsDataURL(i.files[0]),t.onload=()=>{i.binaryData=btoa(t.result),i.parentElement?.dispatchEvent(new Event(`change`,{bubbles:!0}))}}else i.binaryData=void 0}),this.createDefaultTemplate(e,t,n,i,r)}createNumberEditor(e,t,n,r){let i=new G,a=m.has(r.datatype?.value??``);i.type=a?`text`:`number`,a&&(i.pattern=r.datatype?.value===`http://www.w3.org/2001/XMLSchema#decimal`?`[+\\-]?(?:[0-9]+(?:[.,][0-9]*)?|[.,][0-9]+)`:`[+\\-]?(?:[0-9]+(?:[.,][0-9]*)?|[.,][0-9]+)(?:[eE][+\\-]?[0-9]+)?`,i.updateComplete.then(()=>{i.inputElement.inputMode=`decimal`})),i.clearable=!0,i.dense=this.dense,i.classList.add(`pr-0`);let o=r.minInclusive===void 0?r.minExclusive===void 0?void 0:r.minExclusive+1:r.minInclusive,s=r.maxInclusive===void 0?r.maxExclusive===void 0?void 0:r.maxExclusive-1:r.maxInclusive;return o!==void 0&&(i.min=String(o)),s!==void 0&&(i.max=String(s)),!a&&r.datatype?.value!==`http://www.w3.org/2001/XMLSchema#integer`&&(i.step=`any`),this.createDefaultTemplate(e,t,n,i,r)}createListEditor(e,t,n,r,i){let a=new K;a.clearable=!0,a.dense=this.dense;let o=this.createDefaultTemplate(e,null,n,a,i),s=document.createElement(`ul`),c=[],l=!0,u=(e,t)=>{let n=document.createElement(`li`);if(typeof e.value==`string`?(n.dataset.value=e.value,n.innerText=e.label?e.label:e.value):(n.dataset.value=I(e.value),c.push(e.value),n.innerText=e.label?e.label:e.value.value),t.appendChild(n),e.children?.length){l=!1;let t=document.createElement(`ul`);n.appendChild(t);for(let n of e.children)u(n,t)}};for(let e of r)u(e,s);return l||(a.collapse=!0),a.appendChild(s),P(a,c),t=t??i?.defaultValue??null,t&&(a.value=I(t),y(a,t)),o}createButton(e,t){let n=new U;return n.dense=this.dense,n.innerHTML=e,t?(n.setAttribute(`primary`,``),n.setAttribute(`part`,`button primary`)):n.setAttribute(`part`,`button`),n}},Z=class{constructor(){this.shapes=null,this.shapesUrl=null,this.shapeSubject=null,this.values=null,this.valuesUrl=null,this.valueSubject=null,this.valuesSubject=null,this.valuesNamespace=``,this.valuesGraph=null,this.view=null,this.mode=null,this.language=null,this.loading=`Loading…`,this.proxy=null,this.ignoreOwlImports=null,this.collapse=null,this.hierarchyColors=null,this.submitButton=null,this.generateNodeShapeReference=s.value,this.showNodeIds=null,this.showRootShapeLabel=null,this.dense=`true`,this.useShadowRoot=`true`}},re=`#4c93d785, #f85e9a85, #00327385, #87001f85`,Q=class{constructor(e){this.attributes=new Z,this.mode=`edit`,this.lists={},this.groups=[],this.renderedNodes=new Set,this._store=new H,this._nodeTemplates={},this._propertyTemplates={},this.validator=new J(this._store,{details:!0,factory:z}),this.providedConformingResourceIds={},this.providedResources={},this.providedResourceLabels={},this.form=e,this._theme=new X,this.languages=[...new Set(navigator.languages.flatMap(e=>e.length>2?[e.toLocaleLowerCase(),e.substring(0,2)]:e)),``]}reset(){this.lists={},this.groups=[],this.renderedNodes.clear(),this.providedConformingResourceIds={},this.providedResources={},this.providedResourceLabels={},this._nodeTemplates={},this._propertyTemplates={}}updateAttributes(e){let t=new Z;if(Object.keys(t).forEach(n=>{let r=e.dataset[n];r!==void 0&&(t[n]=r)}),t.mode!==null&&![`edit`,`view`,`query`].includes(t.mode))throw Error(`invalid shacl-form mode: ${t.mode}`);if(this.mode=t.mode??(t.view===null?`edit`:`view`),this.theme.setDense(t.dense===`true`),this.attributes=t,this.attributes.valueSubject&&!this.attributes.valuesSubject&&(this.attributes.valuesSubject=this.attributes.valueSubject),t.language){let e=this.languages.indexOf(t.language);e>-1&&this.languages.splice(e,1),this.languages.unshift(t.language)}if(t.valuesGraph&&(this.valuesGraphId=z.namedNode(t.valuesGraph)),t.hierarchyColors!=null){let e=t.hierarchyColors.length?t.hierarchyColors:re,n=`:host { --hierarchy-colors: ${e}; --hierarchy-colors-length: ${e.split(`,`).length} }`;for(let e=8;e>=0;e--){let t=`shacl-property { --hierarchy-level: ${e} }`;for(let n=0;n<e;n++)t=`shacl-property `+t;n=n+`
7
+ `+t}this.hierarchyColorsStyleSheet=new CSSStyleSheet,this.hierarchyColorsStyleSheet.replaceSync(n)}}static dataAttributes(){let e=new Z;return Object.keys(e).map(e=>(e=e.replace(/[A-Z]/g,e=>`-`+e.toLowerCase()),`data-`+e))}buildTemplateKey(e,t){let n=e.value;return t&&(t instanceof r?n+=`*`+t.id.value:n+=`*`+this.buildTemplateKey(t.id,t.parent)),n}registerNodeTemplate(e){this._nodeTemplates[this.buildTemplateKey(e.id,e.parent)]=e}registerPropertyTemplate(e){this._propertyTemplates[this.buildTemplateKey(e.id,e.parent)]=e}getNodeTemplateIds(){let e=new Set;for(let t of Object.values(this._nodeTemplates))e.add(t.id.value);return e}getNodeTemplate(e,t){let n=this.buildTemplateKey(e,t),r=this._nodeTemplates[n];return r||=new j(e,this,t),r}getPropertyTemplate(e,t){let n=this.buildTemplateKey(e,t),i=this._propertyTemplates[n];return i||=new r(e,t),i}get nodeTemplates(){return Object.values(this._nodeTemplates)}get theme(){return this._theme}set theme(e){this._theme=e,e.setDense(this.attributes.dense===`true`)}get store(){return this._store}get editMode(){return this.mode===`edit`}get queryMode(){return this.mode===`query`}set store(e){this._store=e,this.lists=a(e,{ignoreErrors:!0}),this.groups=[],e.forSubjects(e=>{this.groups.push(e.id)},l,`${o}PropertyGroup`,null),this.validator=new J(e,{details:!0,factory:z})}},ie=200,$=class extends HTMLElement{static get observedAttributes(){return Q.dataAttributes()}constructor(){super(),this.shape=null,this.styleElement=null,this.form=document.createElement(`form`),this.form.setAttribute(`part`,`form`),this.config=new Q(this.form),this.form.addEventListener(`change`,e=>{e.stopPropagation(),this.config.queryMode?this.queryController?.handleChange():this.config.editMode&&this.validate(!0).then(e=>{this.refreshClassInstanceEditors(),this.dispatchEvent(new CustomEvent(`change`,{bubbles:!0,cancelable:!1,composed:!0,detail:{valid:e.conforms,report:e}}))}).catch(e=>{console.warn(e)})})}connectedCallback(){this.config.updateAttributes(this),this.ensureRenderRoot(),this.initialize()}attributeChangedCallback(){this.config.updateAttributes(this),this.ensureRenderRoot(),this.initialize()}initialize(){clearTimeout(this.initDebounceTimeout),this.queryController?.dispose(),this.queryController=void 0,this.setAttribute(`loading`,``),this.config.theme.apply(this.form),this.applyStyles([this.config.theme.stylesheet]),this.form.replaceChildren(document.createTextNode(this.config.attributes.loading)),this.initDebounceTimeout=setTimeout(async()=>{try{this.config.reset(),this.config.store=await S({shapes:this.config.attributes.shapes,shapesUrl:this.config.attributes.shapesUrl,values:this.config.attributes.values,valuesUrl:this.config.attributes.valuesUrl,valuesSubject:this.config.attributes.valuesSubject,loadOwlImports:this.config.attributes.ignoreOwlImports===null,classInstanceProvider:this.config.classInstanceProvider,rdfUrlResolver:this.config.rdfUrlResolver,proxy:this.config.attributes.proxy}),this.config.resourceLinkProvider&&await ne(this.config),this.config.attributes.valuesSubject||(this.config.attributes.valuesSubject=k(this.config.store)||null),this.form.replaceChildren();let e=this.findRootShaclShapeSubject();if(e){if(this.form.classList.forEach(e=>{this.form.classList.remove(e)}),this.form.classList.toggle(`mode-edit`,this.config.editMode),this.form.classList.toggle(`mode-view`,this.config.mode===`view`),this.form.classList.toggle(`mode-query`,this.config.queryMode),this.config.queryMode){let{QueryModeController:e}=await p(async()=>{let{QueryModeController:e}=await import(`./assets/mode-_I_CsUK6.js`);return{QueryModeController:e}},[]);this.queryController=new e(this)}this.config.theme.apply(this.form);let t=[this.config.theme.stylesheet];this.config.hierarchyColorsStyleSheet&&t.push(this.config.hierarchyColorsStyleSheet),this.queryController&&t.push(this.queryController.stylesheet);for(let e of A())e.stylesheet&&t.push(e.stylesheet);this.applyStyles(t);let n=new j(e,this.config);for(let e of this.config.nodeTemplates)E(e);if(this.shape=new te(n,this.config.attributes.valuesSubject?z.namedNode(this.config.attributes.valuesSubject):void 0),this.form.appendChild(this.shape),this.config.attributes.showRootShapeLabel!==null&&n.label){let e=document.createElement(`h3`);e.innerText=n.label.value,this.form.prepend(e)}if(this.config.editMode){if(this.config.attributes.submitButton!==null){let e=this.config.theme.createButton(this.config.attributes.submitButton||`Submit`,!0);e.classList.add(`submit-button`);let t=e.getAttribute(`part`);e.setAttribute(`part`,`${t?t+` `:``}submit-button`),e.addEventListener(`click`,e=>{e.preventDefault(),this.form.reportValidity()&&this.validate().then(e=>{if(e?.conforms)this.dispatchEvent(new Event(`submit`,{bubbles:!0,cancelable:!0}));else{let e=this.form.querySelector(`:scope .invalid > .editor`);e?e.focus():this.form.querySelector(`:scope .invalid`)?.scrollIntoView()}})}),this.form.appendChild(e)}await this.shape?.ready,this.config.attributes.valuesSubject&&this.removeFromDataGraph(z.namedNode(this.config.attributes.valuesSubject)),await this.validate(!0),this.refreshClassInstanceEditors()}else this.config.queryMode&&(await this.shape.ready,await this.queryController?.initialize())}else if(this.config.store.countQuads(null,null,null,ee)>0)throw Error(`shacl root node shape not found`)}catch(e){console.error(e);let t=document.createElement(`div`);t.innerText=String(e),this.form.replaceChildren(t)}this.config.queryMode&&this.config.queryFacetProvider&&this.queryController||this.removeAttribute(`loading`),await this.shape?.ready,this.dispatchEvent(new Event(`ready`))},200)}ensureRenderRoot(){this.config.attributes.useShadowRoot===`false`?(this.shadowRoot?.contains(this.form)&&this.shadowRoot.removeChild(this.form),this.contains(this.form)||this.prepend(this.form)):(this.shadowRoot||this.attachShadow({mode:`open`}),this.shadowRoot.contains(this.form)||this.shadowRoot.prepend(this.form))}applyStyles(e){if(this.config.attributes.useShadowRoot!==`false`&&this.shadowRoot){this.shadowRoot.adoptedStyleSheets=e,this.styleElement&&=(this.styleElement.remove(),null);return}let t=e.map(e=>Array.from(e.cssRules).map(e=>e.cssText).join(`
8
8
  `).replace(/:host\b/g,`shacl-form`)).join(`
9
- `);this.styleElement||(this.styleElement=document.createElement(`style`),this.prepend(this.styleElement)),this.styleElement.textContent=t}serialize(e=`text/turtle`,t){return this.assertNotQueryMode(`serialize`),t??=this.toRDF(),S(t.getQuads(null,null,null,null),e,u)}toRDF(e=new B){return this.assertNotQueryMode(`toRDF`),this.shape?.toRDF(e,void 0,this.config.attributes.generateNodeShapeReference),e}registerPlugin(e){C(e),this.initialize()}setTheme(e){this.config.theme=e,this.initialize()}setClassInstanceProvider(e){this.config.classInstanceProvider=e,this.initialize()}setRdfUrlResolver(e){this.config.rdfUrlResolver=e,this.initialize()}setResourceLinkProvider(e){this.config.resourceLinkProvider=e,this.initialize()}setQueryFacetProvider(e){this.config.queryFacetProvider=e,this.queryController?.refreshFacets()}getQuery(){return this.shape?this.queryController?.getQuery()??{rootShapeId:this.shape.template.id.value,targetClass:this.shape.template.targetClass?.value,criteria:[]}:{rootShapeId:``,criteria:[]}}refreshQueryFacets(){this.queryController?.refreshFacets()}async validate(e=!1){this.assertNotQueryMode(`validate`);for(let e of this.form.querySelectorAll(`:scope .validation-error`))e.remove();for(let e of this.form.querySelectorAll(`:scope .property-instance`))e.classList.remove(`invalid`),e.querySelector(`:scope > .editor`)?.value?e.classList.add(`valid`):e.classList.remove(`valid`);for(let e of this.form.querySelectorAll(`.add-button-wrapper`))e.classList.remove(`invalid`,`validation-error`);if(!this.shape)return{conforms:!0,results:[]};if(!e){let e=this.form.querySelectorAll(`.add-button-wrapper.required`);for(let t of e)t.classList.add(`invalid`),t.after(this.createValidationErrorDisplay(`Value is required`,`node`));if(e.length>0)return{conforms:!1,results:[]}}let t=this.shape;return new Promise(n=>{this.config.store.deleteGraph(this.config.valuesGraphId||``).on(`end`,async()=>{t.toRDF(this.config.store,void 0,this.config.attributes.generateNodeShapeReference);try{let r=await this.config.validator.validate({dataset:this.config.store,terms:[t.nodeId]},[{terms:[t.template.id]}]);for(let t of r.results)if(t.focusNode?.ptrs?.length)for(let n of t.focusNode.ptrs){let r=n._term;if(t.path?.length){let n=t.path[0].predicates[0],i=this.form.querySelectorAll(`
10
- :scope shacl-node[data-node-id='${r.id}'] > shacl-property > .property-instance[data-path='${n.id}'] > .editor,
11
- :scope shacl-node[data-node-id='${r.id}'] > shacl-property > .shacl-group > .property-instance[data-path='${n.id}'] > .editor,
12
- :scope shacl-node[data-node-id='${r.id}'] > .shacl-group > shacl-property > .property-instance[data-path='${n.id}'] > .editor,
13
- :scope shacl-node[data-node-id='${r.id}'] > .shacl-group > shacl-property > .shacl-group > .property-instance[data-path='${n.id}'] > .editor`);i.length===0&&(i=this.form.querySelectorAll(`
9
+ `);this.styleElement||(this.styleElement=document.createElement(`style`),this.prepend(this.styleElement)),this.styleElement.textContent=t}serialize(e=`text/turtle`,t){return this.assertNotQueryMode(`serialize`),t??=this.toRDF(),w(t.getQuads(null,null,null,null),e,u)}toRDF(e=new H){return this.assertNotQueryMode(`toRDF`),this.shape?.toRDF(e,void 0,this.config.attributes.generateNodeShapeReference),e}registerPlugin(e){T(e),this.initialize()}setTheme(e){this.config.theme=e,this.initialize()}setClassInstanceProvider(e){this.config.classInstanceProvider=e,this.initialize()}setRdfUrlResolver(e){this.config.rdfUrlResolver=e,this.initialize()}setResourceLinkProvider(e){this.config.resourceLinkProvider=e,this.initialize()}setQueryFacetProvider(e){this.config.queryFacetProvider=e,this.queryController?.refreshFacets()}getQuery(){return this.shape?this.queryController?.getQuery()??{rootShapeId:this.shape.template.id.value,targetClass:this.shape.template.targetClass?.value,criteria:[]}:{rootShapeId:``,criteria:[]}}refreshQueryFacets(){this.queryController?.refreshFacets()}async validate(e=!1){this.assertNotQueryMode(`validate`);for(let e of this.form.querySelectorAll(`:scope .validation-error`))e.remove();for(let e of this.form.querySelectorAll(`:scope .property-instance`))e.classList.remove(`invalid`),e.querySelector(`:scope > .editor`)?.value?e.classList.add(`valid`):e.classList.remove(`valid`);for(let e of this.form.querySelectorAll(`.add-button-wrapper`))e.classList.remove(`invalid`,`validation-error`);if(!this.shape)return{conforms:!0,results:[]};if(!e){let e=this.form.querySelectorAll(`.add-button-wrapper.required`);for(let t of e)t.classList.add(`invalid`),t.after(this.createValidationErrorDisplay(`Value is required`,`node`));if(e.length>0)return{conforms:!1,results:[]}}let t=this.shape;return new Promise(n=>{this.config.store.deleteGraph(this.config.valuesGraphId||``).on(`end`,async()=>{t.toRDF(this.config.store,void 0,this.config.attributes.generateNodeShapeReference);try{let r=await this.config.validator.validate({dataset:this.config.store,terms:[t.nodeId]},[{terms:[t.template.id]}]);for(let t of r.results)if(t.focusNode?.ptrs?.length)for(let n of t.focusNode.ptrs){let r=n._term;if(t.path?.length){let n=t.path[0].predicates[0],i=e=>`
10
+ :scope shacl-node[data-node-id='${r.id}'] > shacl-property > .property-instance[${e}='${n.id}'] > .editor,
11
+ :scope shacl-node[data-node-id='${r.id}'] > shacl-property > .shacl-group > .property-instance[${e}='${n.id}'] > .editor,
12
+ :scope shacl-node[data-node-id='${r.id}'] > .shacl-group > shacl-property > .property-instance[${e}='${n.id}'] > .editor,
13
+ :scope shacl-node[data-node-id='${r.id}'] > .shacl-group > shacl-property > .shacl-group > .property-instance[${e}='${n.id}'] > .editor`,a=this.form.querySelectorAll(i(`data-path`));a.length===0&&(a=this.form.querySelectorAll(i(`data-predicate`))),a.length===0&&(a=this.form.querySelectorAll(`
14
14
  :scope [data-node-id='${r.id}'] > shacl-property > .property-instance[data-path='${n.id}'],
15
- :scope [data-node-id='${r.id}'] > shacl-property > .shacl-group > .property-instance[data-path='${n.id}']`));for(let n of i)if(n.classList.contains(`editor`)){if(!e||n.value){let e=n.parentElement;e.classList.add(`invalid`),e.classList.remove(`valid`),e.appendChild(this.createValidationErrorDisplay(t));do e instanceof H&&(e.open=!0),e=e.parentElement;while(e)}}else e||(n.classList.add(`invalid`),n.classList.remove(`valid`),n.appendChild(this.createValidationErrorDisplay(t,`node`)))}else e||this.form.querySelector(`:scope [data-node-id='${r.id}']:not([part~='linked-node'])`)?.prepend(this.createValidationErrorDisplay(t,`node`))}n(r)}catch(e){console.error(e),n({conforms:!1,results:[]})}})})}assertNotQueryMode(e){if(this.config.queryMode)throw Error(`${e}() is not available in query mode; use getQuery()`)}createValidationErrorDisplay(e,t){let n=document.createElement(`span`);n.classList.add(`validation-error`),t&&n.classList.add(t);let r=typeof e==`object`&&e?e:null;return r?r.message?.length?n.title+=l(this.config.languages,r.message):r.sourceConstraintComponent?.value&&(n.title=r.sourceConstraintComponent.value):typeof e==`string`&&(n.title=e),n}findRootShaclShapeSubject(){if(this.config.attributes.shapeSubject){let e=L.namedNode(this.config.attributes.shapeSubject);if(this.config.store.getQuads(e,h,s,null).length===0){console.warn(`shapes graph does not contain requested node shape ${this.config.attributes.shapeSubject}`);return}else return e}else{if(this.config.attributes.valuesSubject&&this.config.store.countQuads(null,null,null,c)>0){let e=L.namedNode(this.config.attributes.valuesSubject),t=y(this.config.store,this.config.attributes.valuesSubject),n=this.config.store.getQuads(e,h,null,c);if(n.length===0&&console.warn(`value subject '${this.config.attributes.valuesSubject}' has neither ${h.id} nor ${f.id} statement`),t)return t;for(let e of n)if(this.config.store.getQuads(e.object,h,s,null).length>0)return e.object;let r=this.config.store.getObjects(e,h,c);for(let e of r)for(let t of this.config.store.getQuads(null,A,e,null))return t.subject}let e=this.config.store.getQuads(null,h,s,null);if(e.length==0){console.warn(`shapes graph does not contain any node shapes`);return}return e.length>1&&(console.warn(`shapes graph contains`,e.length,`node shapes. choosing first found which is`,e[0].subject.value),console.info(`hint: set the node shape to use with element attribute "data-shape-subject"`)),e[0].subject}}removeFromDataGraph(e){for(let t of this.config.store.getQuads(e,null,null,c))this.config.store.delete(t),(t.object.termType===`NamedNode`||t.object.termType===`BlankNode`)&&this.removeFromDataGraph(t.object)}};window.customElements.define(`shacl-form`,$);export{Z as Config,J as DefaultTheme,x as Plugin,$ as ShaclForm,v as ShaclPropertyTemplate,_ as Theme,p as fetchRDF,y as findConformsToShapeSubject,D as findConformsToValuesSubject,d as findLabel,N as importRDF,Q as initTimeout,ee as isRangeQueryField,b as loadGraphs,n as loadRDF,t as parseRDF,u as prefixes,e as propertyMappers,E as rdfCache,C as registerPlugin};
15
+ :scope [data-node-id='${r.id}'] > shacl-property > .shacl-group > .property-instance[data-path='${n.id}'],
16
+ :scope [data-node-id='${r.id}'] > shacl-property > .alternative-path-constraint[data-path='${n.id}'],
17
+ :scope [data-node-id='${r.id}'] > shacl-property > .shacl-group > .alternative-path-constraint[data-path='${n.id}']`)),a.length===0&&(a=this.form.querySelectorAll(`
18
+ :scope [data-node-id='${r.id}'] > shacl-property > .property-instance[data-predicate='${n.id}'],
19
+ :scope [data-node-id='${r.id}'] > shacl-property > .shacl-group > .property-instance[data-predicate='${n.id}']`));for(let n of a)if(n.classList.contains(`editor`)){if(!e||n.value){let e=n.parentElement;e.classList.add(`invalid`),e.classList.remove(`valid`),e.appendChild(this.createValidationErrorDisplay(t));do e instanceof W&&(e.open=!0),e=e.parentElement;while(e)}}else e||(n.classList.add(`invalid`),n.classList.remove(`valid`),n.appendChild(this.createValidationErrorDisplay(t,`node`)))}else e||this.form.querySelector(`:scope [data-node-id='${r.id}']:not([part~='linked-node'])`)?.prepend(this.createValidationErrorDisplay(t,`node`))}n(r)}catch(e){console.error(e),n({conforms:!1,results:[]})}})})}assertNotQueryMode(e){if(this.config.queryMode)throw Error(`${e}() is not available in query mode; use getQuery()`)}refreshClassInstanceEditors(){if(!(!this.shape||!this.config.editMode))for(let e of this.form.querySelectorAll(`shacl-property`))e.refreshClassInstances()}createValidationErrorDisplay(e,t){let n=document.createElement(`span`);n.classList.add(`validation-error`),t&&n.classList.add(t);let r=typeof e==`object`&&e?e:null;return r?r.message?.length?n.title+=c(this.config.languages,r.message):r.sourceConstraintComponent?.value&&(n.title=r.sourceConstraintComponent.value):typeof e==`string`&&(n.title=e),n}findRootShaclShapeSubject(){if(this.config.attributes.shapeSubject){let e=z.namedNode(this.config.attributes.shapeSubject);if(this.config.store.getQuads(e,l,g,null).length===0){console.warn(`shapes graph does not contain requested node shape ${this.config.attributes.shapeSubject}`);return}else return e}else{if(this.config.attributes.valuesSubject&&this.config.store.countQuads(null,null,null,h)>0){let e=z.namedNode(this.config.attributes.valuesSubject),t=x(this.config.store,this.config.attributes.valuesSubject),n=this.config.store.getQuads(e,l,null,h);if(n.length===0&&console.warn(`value subject '${this.config.attributes.valuesSubject}' has neither ${l.id} nor ${s.id} statement`),t)return t;for(let e of n)if(this.config.store.getQuads(e.object,l,g,null).length>0)return e.object;let r=this.config.store.getObjects(e,l,h);for(let e of r)for(let t of this.config.store.getQuads(null,v,e,null))return t.subject}let e=this.config.store.getQuads(null,l,g,null);if(e.length==0){console.warn(`shapes graph does not contain any node shapes`);return}return e.length>1&&(console.warn(`shapes graph contains`,e.length,`node shapes. choosing first found which is`,e[0].subject.value),console.info(`hint: set the node shape to use with element attribute "data-shape-subject"`)),e[0].subject}}removeFromDataGraph(e){for(let t of this.config.store.getQuads(e,null,null,h))this.config.store.delete(t),(t.object.termType===`NamedNode`||t.object.termType===`BlankNode`)&&this.removeFromDataGraph(t.object)}};window.customElements.define(`shacl-form`,$);export{Q as Config,X as DefaultTheme,C as Plugin,$ as ShaclForm,r as ShaclPropertyTemplate,b as Theme,O as fetchRDF,x as findConformsToShapeSubject,k as findConformsToValuesSubject,f as findLabel,N as importRDF,ie as initTimeout,M as isRangeQueryField,S as loadGraphs,t as loadRDF,D as parseRDF,u as prefixes,i as propertyMappers,d as rdfCache,T as registerPlugin};
package/dist/linker.d.ts CHANGED
@@ -1,12 +1,18 @@
1
+ import { BlankNode, NamedNode } from 'n3';
1
2
  import { Config } from './config.js';
2
3
  import { ShaclProperty } from './property.js';
3
4
  import { ShaclPropertyTemplate } from './property-template.js';
4
- import { InputListEntry } from './theme.js';
5
+ type LinkCandidate = {
6
+ value: NamedNode | BlankNode;
7
+ label: string;
8
+ template: ShaclPropertyTemplate;
9
+ };
5
10
  export declare function createLinker(property: ShaclProperty): Promise<HTMLElement | undefined>;
6
- export declare function findLinkCandidates(property: ShaclProperty): InputListEntry[];
11
+ export declare function findLinkCandidates(property: ShaclProperty): LinkCandidate[];
7
12
  export declare function loadConformingResources(property: ShaclPropertyTemplate): Promise<void>;
8
13
  export declare function loadResources(ids: Set<string>, addToStore: boolean, config: Config): Promise<{
9
14
  resourceId: string;
10
15
  resourceRDF: string;
11
16
  }[]>;
12
17
  export declare function loadUnresolvedValues(config: Config): Promise<void>;
18
+ export {};
package/dist/node.d.ts CHANGED
@@ -3,6 +3,7 @@ import { Term } from '@rdfjs/types';
3
3
  import { Config } from './config.js';
4
4
  import { ShaclNodeTemplate } from './node-template.js';
5
5
  import { ShaclPropertyTemplate } from './property-template.js';
6
+ import type { QueryPathSegment } from './query/index.js';
6
7
  export declare class ShaclNode extends HTMLElement {
7
8
  nodeId: NamedNode | BlankNode;
8
9
  template: ShaclNodeTemplate;
@@ -16,6 +17,6 @@ export declare class ShaclNode extends HTMLElement {
16
17
  tryResolve(options: Term[], valueSubject: NamedNode | BlankNode | undefined, config: Config): Promise<void>;
17
18
  }
18
19
  export type QueryPathContext = {
19
- path: string[];
20
+ path: QueryPathSegment[];
20
21
  shapePath: string[];
21
22
  };
@@ -1 +1 @@
1
- import{DataFactory as e}from"n3";import"rdfxml-streaming-parser";import"jsonld";var t=class{constructor(e,t){this.predicate=e.predicate,this.datatype=e.datatype,t&&(this.stylesheet=new CSSStyleSheet,this.stylesheet.replaceSync(t))}createViewer(e,t){return e.config.theme.createViewer(e.label,t,e)}},n=`http://www.w3.org/ns/shacl#`,r=`http://datashapes.org/dash#`,i=`http://www.w3.org/2001/XMLSchema#`,a=`http://www.w3.org/ns/oa#`,o=e.namedNode(`loaded-shapes`),s=e.namedNode(`loaded-data`),c=e.namedNode(`http://www.w3.org/1999/02/22-rdf-syntax-ns#type`),l=e.namedNode(`http://www.w3.org/1999/02/22-rdf-syntax-ns#langString`);e.namedNode(`http://purl.org/dc/terms/conformsTo`);var u=e.namedNode(`http://www.w3.org/2000/01/rdf-schema#subClassOf`),d=e.namedNode(`http://www.w3.org/2002/07/owl#imports`),f=e.namedNode(`http://www.w3.org/2004/02/skos/core#broader`),p=e.namedNode(`http://www.w3.org/2004/02/skos/core#narrower`);e.namedNode(`http://www.w3.org/ns/shacl#NodeShape`),e.namedNode(`http://www.w3.org/ns/shacl#IRI`),e.namedNode(`http://www.w3.org/ns/shacl#property`);var m=e.namedNode(`http://www.w3.org/ns/shacl#class`);e.namedNode(`http://www.w3.org/ns/shacl#node`),e.namedNode(`http://www.w3.org/ns/shacl#targetClass`),e.namedNode(`http://www.w3.org/ns/shacl#nodeKind`),e.namedNode(`http://www.w3.org/2001/XMLSchema#string`),e.namedNode(`http://www.w3.org/2001/XMLSchema#boolean`);function h(e,t,r=n,i){let a=``,o=g(e,t,r,i);return o&&(a=o.value),a}function g(e,t,r=n,i){let a,o=r+t;if(i?.length){for(let t of i)for(let n of e)if(n.predicate.value===o){if(n.object.id.endsWith(`@${t}`))return n.object;n.object.id.indexOf(`@`)<0?a=n.object:a||=n.object}}else for(let t of e)if(t.predicate.value===o)return t.object;return a}function _(e,t){return h(e,`prefLabel`,`http://www.w3.org/2004/02/skos/core#`,t)||h(e,`label`,`http://www.w3.org/2000/01/rdf-schema#`,t)||h(e,`title`,`http://purl.org/dc/terms/`,t)||h(e,`name`,`http://xmlns.com/foaf/0.1/`,t)}function v(e,t,n){let r=[];for(let i of e)r.push({value:i,label:_(t.getQuads(i,null,null,null),n),children:[]});return r}function y(e,t,n,r,i=new Set){for(let a of t.owlImports)i.has(a.id)||(i.add(a.id),r.push(...n.getSubjects(c,e,a)));t.parent&&y(e,t.parent,n,r,i)}function b(e,t){if(t.in){let e=t.config.lists[t.in];return v(e?.length?e:[],t.config.store,t.config.languages)}else{let n=t.config.store.getSubjects(c,e,o);n.push(...t.config.store.getSubjects(c,e,s)),y(e,t,t.config.store,n);let r=new Map,i=new Map;for(let e of n)r.set(e.id,{value:e,label:_(t.config.store.getQuads(e,null,null,null),t.config.languages),children:[]});for(let e of n){for(let n of t.config.store.getObjects(e,f,null))r.has(n.id)&&i.set(e.id,n.id);for(let n of t.config.store.getObjects(e,p,null))r.has(n.id)&&i.set(n.id,e.id);for(let n of t.config.store.getObjects(e,u,null))r.has(n.id)&&i.set(e.id,n.id)}for(let[e,t]of i.entries())r.get(t)?.children?.push(r.get(e));let a=[];for(let[e,t]of r.entries())i.has(e)||a.push(t);for(let n of t.config.store.getSubjects(u,e,null))a.push(...b(n,t));return a}}`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${r}`,`${r}`,`${a}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,d.id,m.id,`${n}`,`${n}`;function x(e){return Math.max(e.minCount??0,e.qualifiedMinCount??0)}export{l as a,i,v as n,t as o,b as r,x as t};
1
+ import{DataFactory as e}from"n3";import"rdfxml-streaming-parser";import"jsonld";var t=class{constructor(e,t){this.predicate=e.predicate,this.datatype=e.datatype,t&&(this.stylesheet=new CSSStyleSheet,this.stylesheet.replaceSync(t))}createViewer(e,t){return e.config.theme.createViewer(e.label,t,e)}},n=`http://www.w3.org/ns/shacl#`,r=`http://datashapes.org/dash#`,i=`http://www.w3.org/2001/XMLSchema#`,a=`http://www.w3.org/ns/oa#`,o=e.namedNode(`loaded-shapes`),s=e.namedNode(`loaded-data`),c=e.namedNode(`http://www.w3.org/1999/02/22-rdf-syntax-ns#type`),l=e.namedNode(`http://www.w3.org/1999/02/22-rdf-syntax-ns#langString`);e.namedNode(`http://purl.org/dc/terms/conformsTo`);var u=e.namedNode(`http://www.w3.org/2000/01/rdf-schema#subClassOf`),d=e.namedNode(`http://www.w3.org/2002/07/owl#imports`),f=e.namedNode(`http://www.w3.org/2004/02/skos/core#broader`),p=e.namedNode(`http://www.w3.org/2004/02/skos/core#narrower`);e.namedNode(`http://www.w3.org/ns/shacl#NodeShape`),e.namedNode(`http://www.w3.org/ns/shacl#IRI`),e.namedNode(`http://www.w3.org/ns/shacl#property`);var m=e.namedNode(`http://www.w3.org/ns/shacl#class`);e.namedNode(`http://www.w3.org/ns/shacl#node`),e.namedNode(`http://www.w3.org/ns/shacl#targetClass`),e.namedNode(`http://www.w3.org/ns/shacl#nodeKind`),e.namedNode(`http://www.w3.org/2001/XMLSchema#string`),e.namedNode(`http://www.w3.org/2001/XMLSchema#boolean`);function h(e,t,r=n,i){let a=``,o=g(e,t,r,i);return o&&(a=o.value),a}function g(e,t,r=n,i){let a,o=r+t;if(i?.length){for(let t of i)for(let n of e)if(n.predicate.value===o){if(n.object.id.endsWith(`@${t}`))return n.object;n.object.id.indexOf(`@`)<0?a=n.object:a||=n.object}}else for(let t of e)if(t.predicate.value===o)return t.object;return a}function _(e,t){return h(e,`prefLabel`,`http://www.w3.org/2004/02/skos/core#`,t)||h(e,`label`,`http://www.w3.org/2000/01/rdf-schema#`,t)||h(e,`title`,`http://purl.org/dc/terms/`,t)||h(e,`name`,`http://xmlns.com/foaf/0.1/`,t)}function v(e,t,n){let r=[];for(let i of e)r.push({value:i,label:_(t.getQuads(i,null,null,null),n),children:[]});return r}function y(t,n,r=new Map){r.set(o.id,o),r.set(s.id,s);let i=t.config.valuesGraphId??e.defaultGraph();r.set(i.id,i);for(let e of t.owlImports)b(e,n,r);return t.parent&&y(t.parent,n,r),[...r.values()]}function b(e,t,n){if(!n.has(e.id)){n.set(e.id,e);for(let r of t.getObjects(null,d,e))r.termType===`NamedNode`&&b(r,t,n)}}function x(e,t,n,r){return r.flatMap(r=>e.getSubjects(t,n,r))}function S(e,t,n,r){return r.flatMap(r=>e.getObjects(t,n,r))}function C(e,t){if(t.in){let e=t.config.lists[t.in];return v(e?.length?e:[],t.config.store,t.config.languages)}else{let n=y(t,t.config.store),r=x(t.config.store,c,e,n),i=new Map,a=new Map;for(let e of r)i.set(e.id,{value:e,label:_(t.config.store.getQuads(e,null,null,null),t.config.languages),children:[]});for(let e of r){for(let r of S(t.config.store,e,f,n))i.has(r.id)&&a.set(e.id,r.id);for(let r of S(t.config.store,e,p,n))i.has(r.id)&&a.set(r.id,e.id);for(let r of S(t.config.store,e,u,n))i.has(r.id)&&a.set(e.id,r.id)}for(let[e,t]of a.entries())i.get(t)?.children?.push(i.get(e));let o=[];for(let[e,t]of i.entries())a.has(e)||o.push(t);for(let r of x(t.config.store,u,e,n))o.push(...C(r,t));return o}}`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${r}`,`${r}`,`${a}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,`${n}`,d.id,m.id,`${n}`,`${n}`;function w(e){return Math.max(e.minCount??0,e.qualifiedMinCount??0)}export{l as a,i,v as n,t as o,C as r,w as t};
@@ -1 +1 @@
1
- import{o as e,t}from"./assets/property-template-DahfpzrJ.js";var n=class extends e{constructor(e,t,n){super(e),this.onChange=t,this.fileType=n}createEditor(e){let n=t(e)>0,r=e.config.theme.createFileEditor(e.label,null,n,e);return r.addEventListener(`change`,e=>{e.stopPropagation(),this.onChange(e)}),this.fileType&&r.querySelector(`input[type="file"]`)?.setAttribute(`accept`,this.fileType),r}};export{n as FileUploadPlugin};
1
+ import{o as e,t}from"./assets/property-template-r31Q9rrE.js";var n=class extends e{constructor(e,t,n){super(e),this.onChange=t,this.fileType=n}createEditor(e){let n=t(e)>0,r=e.config.theme.createFileEditor(e.label,null,n,e);return r.addEventListener(`change`,e=>{e.stopPropagation(),this.onChange(e)}),this.fileType&&r.querySelector(`input[type="file"]`)?.setAttribute(`accept`,this.fileType),r}};export{n as FileUploadPlugin};
@@ -1,4 +1,4 @@
1
- import{a as e,i as t,n,o as r,r as i,t as a}from"./assets/property-template-DahfpzrJ.js";import*as o from"leaflet";import"leaflet-editable/src/Leaflet.Editable.js";import s from"leaflet/dist/leaflet.css?raw";import c from"leaflet.fullscreen/dist/Control.FullScreen.css?raw";import"leaflet.fullscreen";import"leaflet.heat/dist/leaflet-heat.js";import{RokitButton as l}from"@ro-kit/ui-widgets";import{DataFactory as u,Literal as d}from"n3";function f(r,o,s){if(s){let s=a(r)>0;if(r.class&&!r.hasValue)return r.config.theme.createListEditor(r.label,o,s,i(r.class,r),r);if(r.in){let e=r.config.lists[r.in];if(e?.length){let t=n(e,r.config.store,r.config.languages);return r.config.theme.createListEditor(r.label,o,s,t,r)}else console.error(`list not found:`,r.in,`existing lists:`,r.config.lists)}if(r.datatype?.equals(e)||r.languageIn?.length||r.datatype===void 0&&o instanceof d&&o.language)return r.config.theme.createLangStringEditor(r.label,o,s,r);switch(r.datatype?.value.replace(t,``)){case`integer`:case`float`:case`double`:case`decimal`:return r.config.theme.createNumberEditor(r.label,o,s,r);case`date`:case`dateTime`:return r.config.theme.createDateEditor(r.label,o,s,r);case`boolean`:return r.config.theme.createBooleanEditor(r.label,o,s,r);case`base64Binary`:return r.config.theme.createFileEditor(r.label,o,s,r)}return r.config.theme.createTextEditor(r.label,o,s,r)}else return o?r.config.theme.createViewer(r.label,o,r):document.createElement(`div`)}var p=c.replace(`:root`,`:host`),m=`
1
+ import{a as e,i as t,n,o as r,r as i,t as a}from"./assets/property-template-r31Q9rrE.js";import*as o from"leaflet";import"leaflet-editable/src/Leaflet.Editable.js";import s from"leaflet/dist/leaflet.css?raw";import c from"leaflet.fullscreen/dist/Control.FullScreen.css?raw";import"leaflet.fullscreen";import"leaflet.heat/dist/leaflet-heat.js";import{RokitButton as l}from"@ro-kit/ui-widgets";import{DataFactory as u,Literal as d}from"n3";function f(r,o,s){if(s){let s=a(r)>0;if(r.class&&!r.hasValue)return r.config.theme.createListEditor(r.label,o,s,i(r.class,r),r);if(r.in){let e=r.config.lists[r.in];if(e?.length){let t=n(e,r.config.store,r.config.languages);return r.config.theme.createListEditor(r.label,o,s,t,r)}else console.error(`list not found:`,r.in,`existing lists:`,r.config.lists)}if(r.datatype?.equals(e)||r.languageIn?.length||r.datatype===void 0&&o instanceof d&&o.language)return r.config.theme.createLangStringEditor(r.label,o,s,r);switch(r.datatype?.value.replace(t,``)){case`integer`:case`float`:case`double`:case`decimal`:return r.config.theme.createNumberEditor(r.label,o,s,r);case`date`:case`dateTime`:return r.config.theme.createDateEditor(r.label,o,s,r);case`boolean`:return r.config.theme.createBooleanEditor(r.label,o,s,r);case`base64Binary`:return r.config.theme.createFileEditor(r.label,o,s,r)}return r.config.theme.createTextEditor(r.label,o,s,r)}else return o?r.config.theme.createViewer(r.label,o,r):document.createElement(`div`)}var p=c.replace(`:root`,`:host`),m=`
2
2
  #shaclMapDialog .closeButton { position: absolute; right: 0; top: 0; z-index: 1000; padding: 6px 8px; cursor: pointer; border: 0; background-color: #FFFA; font-size: 24px; }
3
3
  #shaclMapDialog { padding: 0; width:90vw; height: 90vh; margin: auto; }
4
4
  #shaclMapDialog::backdrop { background-color: #0007; }
@@ -20,6 +20,6 @@ import{a as e,i as t,n,o as r,r as i,t as a}from"./assets/property-template-Dahf
20
20
  <div id="shaclMapDialogContainer"></div>
21
21
  <div class="hint">&#x24D8; Draw a polygon or marker, then close dialog</div>
22
22
  <button class="closeButton" type="button">&#x2715;</button>
23
- </dialog>`,g={lng:8.657238961696038,lat:49.87627570549512},_=`&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>`,v=`https://tile.openstreetmap.de/{z}/{x}/{y}.png`,y=o.icon({iconUrl:`data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAApCAYAAADAk4LOAAAFgUlEQVR4Aa1XA5BjWRTN2oW17d3YaZtr2962HUzbDNpjszW24mRt28p47v7zq/bXZtrp/lWnXr337j3nPCe85NcypgSFdugCpW5YoDAMRaIMqRi6aKq5E3YqDQO3qAwjVWrD8Ncq/RBpykd8oZUb/kaJutow8r1aP9II0WmLKLIsJyv1w/kqw9Ch2MYdB++12Onxee/QMwvf4/Dk/Lfp/i4nxTXtOoQ4pW5Aj7wpici1A9erdAN2OH64x8OSP9j3Ft3b7aWkTg/Fm91siTra0f9on5sQr9INejH6CUUUpavjFNq1B+Oadhxmnfa8RfEmN8VNAsQhPqF55xHkMzz3jSmChWU6f7/XZKNH+9+hBLOHYozuKQPxyMPUKkrX/K0uWnfFaJGS1QPRtZsOPtr3NsW0uyh6NNCOkU3Yz+bXbT3I8G3xE5EXLXtCXbbqwCO9zPQYPRTZ5vIDXD7U+w7rFDEoUUf7ibHIR4y6bLVPXrz8JVZEql13trxwue/uDivd3fkWRbS6/IA2bID4uk0UpF1N8qLlbBlXs4Ee7HLTfV1j54APvODnSfOWBqtKVvjgLKzF5YdEk5ewRkGlK0i33Eofffc7HT56jD7/6U+qH3Cx7SBLNntH5YIPvODnyfIXZYRVDPqgHtLs5ABHD3YzLuespb7t79FY34DjMwrVrcTuwlT55YMPvOBnRrJ4VXTdNnYug5ucHLBjEpt30701A3Ts+HEa73u6dT3FNWwflY86eMHPk+Yu+i6pzUpRrW7SNDg5JHR4KapmM5Wv2E8Tfcb1HoqqHMHU+uWDD7zg54mz5/2BSnizi9T1Dg4QQXLToGNCkb6tb1NU+QAlGr1++eADrzhn/u8Q2YZhQVlZ5+CAOtqfbhmaUCS1ezNFVm2imDbPmPng5wmz+gwh+oHDce0eUtQ6OGDIyR0uUhUsoO3vfDmmgOezH0mZN59x7MBi++WDL1g/eEiU3avlidO671bkLfwbw5XV2P8Pzo0ydy4t2/0eu33xYSOMOD8hTf4CrBtGMSoXfPLchX+J0ruSePw3LZeK0juPJbYzrhkH0io7B3k164hiGvawhOKMLkrQLyVpZg8rHFW7E2uHOL888IBPlNZ1FPzstSJM694fWr6RwpvcJK60+0HCILTBzZLFNdtAzJaohze60T8qBzyh5ZuOg5e7uwQppofEmf2++DYvmySqGBuKaicF1blQjhuHdvCIMvp8whTTfZzI7RldpwtSzL+F1+wkdZ2TBOW2gIF88PBTzD/gpeREAMEbxnJcaJHNHrpzji0gQCS6hdkEeYt9DF/2qPcEC8RM28Hwmr3sdNyht00byAut2k3gufWNtgtOEOFGUwcXWNDbdNbpgBGxEvKkOQsxivJx33iow0Vw5S6SVTrpVq11ysA2Rp7gTfPfktc6zhtXBBC+adRLshf6sG2RfHPZ5EAc4sVZ83yCN00Fk/4kggu40ZTvIEm5g24qtU4KjBrx/BTTH8ifVASAG7gKrnWxJDcU7x8X6Ecczhm3o6YicvsLXWfh3Ch1W0k8x0nXF+0fFxgt4phz8QvypiwCCFKMqXCnqXExjq10beH+UUA7+nG6mdG/Pu0f3LgFcGrl2s0kNNjpmoJ9o4B29CMO8dMT4Q5ox8uitF6fqsrJOr8qnwNbRzv6hSnG5wP+64C7h9lp30hKNtKdWjtdkbuPA19nJ7Tz3zR/ibgARbhb4AlhavcBebmTHcFl2fvYEnW0ox9xMxKBS8btJ+KiEbq9zA4RthQXDhPa0T9TEe69gWupwc6uBUphquXgf+/FrIjweHQS4/pduMe5ERUMHUd9xv8ZR98CxkS4F2n3EUrUZ10EYNw7BWm9x1GiPssi3GgiGRDKWRYZfXlON+dfNbM+GgIwYdwAAAAASUVORK5CYII=`,shadowUrl:`data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACkAAAApCAQAAAACach9AAACMUlEQVR4Ae3ShY7jQBAE0Aoz/f9/HTMzhg1zrdKUrJbdx+Kd2nD8VNudfsL/Th///dyQN2TH6f3y/BGpC379rV+S+qqetBOxImNQXL8JCAr2V4iMQXHGNJxeCfZXhSRBcQMfvkOWUdtfzlLgAENmZDcmo2TVmt8OSM2eXxBp3DjHSMFutqS7SbmemzBiR+xpKCNUIRkdkkYxhAkyGoBvyQFEJEefwSmmvBfJuJ6aKqKWnAkvGZOaZXTUgFqYULWNSHUckZuR1HIIimUExutRxwzOLROIG4vKmCKQt364mIlhSyzAf1m9lHZHJZrlAOMMztRRiKimp/rpdJDc9Awry5xTZCte7FHtuS8wJgeYGrex28xNTd086Dik7vUMscQOa8y4DoGtCCSkAKlNwpgNtphjrC6MIHUkR6YWxxs6Sc5xqn222mmCRFzIt8lEdKx+ikCtg91qS2WpwVfBelJCiQJwvzixfI9cxZQWgiSJelKnwBElKYtDOb2MFbhmUigbReQBV0Cg4+qMXSxXSyGUn4UbF8l+7qdSGnTC0XLCmahIgUHLhLOhpVCtw4CzYXvLQWQbJNmxoCsOKAxSgBJno75avolkRw8iIAFcsdc02e9iyCd8tHwmeSSoKTowIgvscSGZUOA7PuCN5b2BX9mQM7S0wYhMNU74zgsPBj3HU7wguAfnxxjFQGBE6pwN+GjME9zHY7zGp8wVxMShYX9NXvEWD3HbwJf4giO4CFIQxXScH1/TM+04kkBiAAAAAElFTkSuQmCC`,iconSize:[25,41],shadowSize:[41,41],iconAnchor:[12,41],shadowAnchor:[14,41],popupAnchor:[-3,-76]});function b(e,t){return o.map(e,{...t,layers:[o.tileLayer(v)]})}function x(e,t){return window.L.heatLayer(e,{maxZoom:t})}function S(e,t,n){return new(o.Control.extend({options:{position:`topleft`},onAdd:()=>{let r=o.DomUtil.create(`div`,`leaflet-control leaflet-bar`),i=o.DomUtil.create(`a`,``,r);return i.href=`#`,i.title=e,i.innerHTML=t,o.DomEvent.on(i,`click`,o.DomEvent.stop).on(i,`click`,n),r}}))}var C=class extends r{constructor(e){super(e,s+`
23
+ </dialog>`,g={lng:8.657238961696038,lat:49.87627570549512},_=`&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>`,v=`https://tile.openstreetmap.de/{z}/{x}/{y}.png`,y=o.icon({iconUrl:`data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAApCAYAAADAk4LOAAAFgUlEQVR4Aa1XA5BjWRTN2oW17d3YaZtr2962HUzbDNpjszW24mRt28p47v7zq/bXZtrp/lWnXr337j3nPCe85NcypgSFdugCpW5YoDAMRaIMqRi6aKq5E3YqDQO3qAwjVWrD8Ncq/RBpykd8oZUb/kaJutow8r1aP9II0WmLKLIsJyv1w/kqw9Ch2MYdB++12Onxee/QMwvf4/Dk/Lfp/i4nxTXtOoQ4pW5Aj7wpici1A9erdAN2OH64x8OSP9j3Ft3b7aWkTg/Fm91siTra0f9on5sQr9INejH6CUUUpavjFNq1B+Oadhxmnfa8RfEmN8VNAsQhPqF55xHkMzz3jSmChWU6f7/XZKNH+9+hBLOHYozuKQPxyMPUKkrX/K0uWnfFaJGS1QPRtZsOPtr3NsW0uyh6NNCOkU3Yz+bXbT3I8G3xE5EXLXtCXbbqwCO9zPQYPRTZ5vIDXD7U+w7rFDEoUUf7ibHIR4y6bLVPXrz8JVZEql13trxwue/uDivd3fkWRbS6/IA2bID4uk0UpF1N8qLlbBlXs4Ee7HLTfV1j54APvODnSfOWBqtKVvjgLKzF5YdEk5ewRkGlK0i33Eofffc7HT56jD7/6U+qH3Cx7SBLNntH5YIPvODnyfIXZYRVDPqgHtLs5ABHD3YzLuespb7t79FY34DjMwrVrcTuwlT55YMPvOBnRrJ4VXTdNnYug5ucHLBjEpt30701A3Ts+HEa73u6dT3FNWwflY86eMHPk+Yu+i6pzUpRrW7SNDg5JHR4KapmM5Wv2E8Tfcb1HoqqHMHU+uWDD7zg54mz5/2BSnizi9T1Dg4QQXLToGNCkb6tb1NU+QAlGr1++eADrzhn/u8Q2YZhQVlZ5+CAOtqfbhmaUCS1ezNFVm2imDbPmPng5wmz+gwh+oHDce0eUtQ6OGDIyR0uUhUsoO3vfDmmgOezH0mZN59x7MBi++WDL1g/eEiU3avlidO671bkLfwbw5XV2P8Pzo0ydy4t2/0eu33xYSOMOD8hTf4CrBtGMSoXfPLchX+J0ruSePw3LZeK0juPJbYzrhkH0io7B3k164hiGvawhOKMLkrQLyVpZg8rHFW7E2uHOL888IBPlNZ1FPzstSJM694fWr6RwpvcJK60+0HCILTBzZLFNdtAzJaohze60T8qBzyh5ZuOg5e7uwQppofEmf2++DYvmySqGBuKaicF1blQjhuHdvCIMvp8whTTfZzI7RldpwtSzL+F1+wkdZ2TBOW2gIF88PBTzD/gpeREAMEbxnJcaJHNHrpzji0gQCS6hdkEeYt9DF/2qPcEC8RM28Hwmr3sdNyht00byAut2k3gufWNtgtOEOFGUwcXWNDbdNbpgBGxEvKkOQsxivJx33iow0Vw5S6SVTrpVq11ysA2Rp7gTfPfktc6zhtXBBC+adRLshf6sG2RfHPZ5EAc4sVZ83yCN00Fk/4kggu40ZTvIEm5g24qtU4KjBrx/BTTH8ifVASAG7gKrnWxJDcU7x8X6Ecczhm3o6YicvsLXWfh3Ch1W0k8x0nXF+0fFxgt4phz8QvypiwCCFKMqXCnqXExjq10beH+UUA7+nG6mdG/Pu0f3LgFcGrl2s0kNNjpmoJ9o4B29CMO8dMT4Q5ox8uitF6fqsrJOr8qnwNbRzv6hSnG5wP+64C7h9lp30hKNtKdWjtdkbuPA19nJ7Tz3zR/ibgARbhb4AlhavcBebmTHcFl2fvYEnW0ox9xMxKBS8btJ+KiEbq9zA4RthQXDhPa0T9TEe69gWupwc6uBUphquXgf+/FrIjweHQS4/pduMe5ERUMHUd9xv8ZR98CxkS4F2n3EUrUZ10EYNw7BWm9x1GiPssi3GgiGRDKWRYZfXlON+dfNbM+GgIwYdwAAAAASUVORK5CYII=`,shadowUrl:`data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACkAAAApCAQAAAACach9AAACMUlEQVR4Ae3ShY7jQBAE0Aoz/f9/HTMzhg1zrdKUrJbdx+Kd2nD8VNudfsL/Th///dyQN2TH6f3y/BGpC379rV+S+qqetBOxImNQXL8JCAr2V4iMQXHGNJxeCfZXhSRBcQMfvkOWUdtfzlLgAENmZDcmo2TVmt8OSM2eXxBp3DjHSMFutqS7SbmemzBiR+xpKCNUIRkdkkYxhAkyGoBvyQFEJEefwSmmvBfJuJ6aKqKWnAkvGZOaZXTUgFqYULWNSHUckZuR1HIIimUExutRxwzOLROIG4vKmCKQt364mIlhSyzAf1m9lHZHJZrlAOMMztRRiKimp/rpdJDc9Awry5xTZCte7FHtuS8wJgeYGrex28xNTd086Dik7vUMscQOa8y4DoGtCCSkAKlNwpgNtphjrC6MIHUkR6YWxxs6Sc5xqn222mmCRFzIt8lEdKx+ikCtg91qS2WpwVfBelJCiQJwvzixfI9cxZQWgiSJelKnwBElKYtDOb2MFbhmUigbReQBV0Cg4+qMXSxXSyGUn4UbF8l+7qdSGnTC0XLCmahIgUHLhLOhpVCtw4CzYXvLQWQbJNmxoCsOKAxSgBJno75avolkRw8iIAFcsdc02e9iyCd8tHwmeSSoKTowIgvscSGZUOA7PuCN5b2BX9mQM7S0wYhMNU74zgsPBj3HU7wguAfnxxjFQGBE6pwN+GjME9zHY7zGp8wVxMShYX9NXvEWD3HbwJf4giO4CFIQxXScH1/TM+04kkBiAAAAAElFTkSuQmCC`,iconSize:[25,41],shadowSize:[41,41],iconAnchor:[12,41],shadowAnchor:[14,41],popupAnchor:[-3,-76]});function b(e,t){return o.map(e,{...t,layers:[o.tileLayer(v)]})}function x(e,t){let n=o.default??o,r=window.L,i=n,a=r;return!i.heatLayer&&a?.heatLayer&&(i.HeatLayer=a.HeatLayer,i.heatLayer=a.heatLayer),window.L=n,i.heatLayer(e,{maxZoom:t})}function S(e,t,n){return new(o.Control.extend({options:{position:`topleft`},onAdd:()=>{let r=o.DomUtil.create(`div`,`leaflet-control leaflet-bar`),i=o.DomUtil.create(`a`,``,r);return i.href=`#`,i.title=e,i.innerHTML=t,o.DomEvent.on(i,`click`,o.DomEvent.stop).on(i,`click`,n),r}}))}var C=class extends r{constructor(e){super(e,s+`
24
24
  `+p+`
25
25
  `+m)}initEditMode(e){e.insertAdjacentHTML(`beforeend`,h);let t=e.querySelector(`#shaclMapDialogContainer`);this.map=b(t,{fullscreenControl:!0,editable:!0,zoom:5,maxBounds:A,center:g}),this.map.attributionControl.addAttribution(_);let n=this.map;this.map.addControl(S(`Create a new polygon`,`▰`,()=>{this.displayedShape?.remove(),this.displayedShape=n.editTools.startPolygon()})),this.map.addControl(S(`Create a new marker`,`•`,()=>{this.displayedShape?.remove(),this.displayedShape=n.editTools.startMarker(void 0,{icon:y})})),this.map.on(`editable:drawing:end editable:vertex:dragend`,()=>{this.saveChanges()});let r=e.querySelector(`#shaclMapDialog`);return r.addEventListener(`click`,e=>{e.target===r&&r.close()}),r.querySelector(`.closeButton`)?.addEventListener(`click`,()=>r.close()),r.addEventListener(`close`,()=>{let e=document.body.style.top;document.body.style.position=``,document.body.style.top=``,window.scrollTo(0,parseInt(e||`0`)*-1),this.currentEditor&&this.createdGeometry&&(this.currentEditor.value=N(this.createdGeometry),this.currentEditor.dispatchEvent(new Event(`change`,{bubbles:!0})))}),r}createEditor(e,t){let n=e.config.form.querySelector(`#shaclMapDialog`);n||=this.initEditMode(e.config.form);let r=e.config.theme.createButton(`Open&#160;map...`,!1);r.style.marginLeft=`5px`,r.classList.add(`open-map-button`),r.onclick=()=>{this.currentEditor=i.querySelector(`.editor`),this.createdGeometry=void 0,this.displayedShape?.remove(),this.drawAndZoomToGeometry(j(this.currentEditor.value||``),this.map),document.body.style.top=`-${window.scrollY}px`,document.body.style.position=`fixed`,n.showModal()};let i=f(e,t||null,!0);return i.appendChild(r),i}createQueryEditor(e,t){let n=document.createElement(`div`);n.classList.add(`query-editor`,`query-map-editor`),n.dataset.queryFieldId=e.id,n.setAttribute(`part`,`query-editor`);let r=document.createElement(`label`);r.textContent=t.label,t.description&&(r.title=t.description.value),n.appendChild(r);let i=document.createElement(`div`);i.classList.add(`query-controls`),n.appendChild(i);let a=document.createElement(`div`);a.classList.add(`query-map`),i.appendChild(a);let s=new l;s.classList.add(`clear`,`query-map-clear`),s.title=`Clear`,s.dense=t.config.theme.dense,s.icon=!0,s.hidden=!0,i.appendChild(s);let c=!1,d,f=b(a,{attributionControl:!1,fullscreenControl:!0,maxBoundsViscosity:1,trackResize:!1,zoom:0});f.fitBounds(A).setMaxBounds(A),f.on(`moveend`,()=>{c=f.getZoom()>0,s.hidden=!c;let e=c?T(f.getBounds()):void 0;e!==d&&(d=e,n.dispatchEvent(new Event(`change`,{bubbles:!0})))}),s.addEventListener(`click`,e=>{e.stopPropagation(),f.fitBounds(A,{animate:!1})});let p,m=o.featureGroup().addTo(f),h=e=>{if(m.clearLayers(),p=void 0,e)if(e.heatmap){if(!w(f,a)){p=e;return}let t=P(e.heatmap);t.length&&x(t,f.getZoom()||0).addTo(m)}else D(e,m)};return new ResizeObserver(()=>{a.clientWidth<=0||a.clientHeight<=0||(f.invalidateSize({debounceMoveend:!0}),p&&h(p))}).observe(a),n.getQueryCriteria=()=>!c||!d?[]:[{field:e,operator:`equals`,value:u.literal(d,t.datatype)}],n.setQueryFacet=h,n}createViewer(e,t){let n=document.createElement(`div`),r=j(t.value);if(r){let e=b(n,{fullscreenControl:!0,zoom:5,center:g,maxBounds:A});e.attributionControl.addAttribution(_),k(r,e)}return n}drawAndZoomToGeometry(e,t){this.displayedShape=k(e,t)}saveChanges(){if(this.displayedShape instanceof o.Marker){let{lng:e,lat:t}=this.displayedShape.getLatLng();this.createdGeometry={type:`Point`,coordinates:[e,t]};return}if(this.displayedShape instanceof o.Polygon){let e=this.displayedShape.getLatLngs()[0];if(!e.length){this.createdGeometry=void 0;return}let t=e.map(({lng:e,lat:t})=>[e,t]);e[0].equals(e[e.length-1])||t.push([...t[0]]),this.createdGeometry={type:`Polygon`,coordinates:[t]};return}this.createdGeometry=void 0}};function w(e,t){let n=t.getBoundingClientRect(),r=e.getSize();return n.width>0&&n.height>0&&r.x>0&&r.y>0}function T(e){let t=E(e.getSouth(),-90,90),n=E(e.getWest(),-180,180),r=E(e.getNorth(),-90,90),i=E(e.getEast(),-180,180);return`POLYGON((${n} ${t},${i} ${t},${i} ${r},${n} ${r},${n} ${t}))`}function E(e,t,n){return Math.min(n,Math.max(t,e))}function D(e,t){if(!e.buckets?.length)return;let n=Math.max(...e.buckets.map(e=>e.count));for(let r of e.buckets){let e=j(r.value.value);if(!e)continue;let i=n>0?r.count/n:0;if(e.type===`Point`){let[n,r]=e.coordinates;o.circleMarker({lat:r,lng:n},{radius:4+i*16,fillColor:`#3388ff`,fillOpacity:.4+i*.4,color:`#3388ff`,weight:1}).addTo(t)}else o.polygon(O(e.coordinates[0]),{fillColor:`#3388ff`,fillOpacity:.15+i*.35,color:`#3388ff`,weight:1}).addTo(t)}}function O(e){return e.map(([e,t])=>({lat:t,lng:e}))}function k(e,t){if(setTimeout(()=>t.invalidateSize()),e?.type===`Point`){let[n,r]=e.coordinates,i={lng:n,lat:r},a=o.marker(i,{icon:y}).addTo(t);return t.setView(i,15,{animate:!1}),a}if(e?.type===`Polygon`){let n=o.polygon(O(e.coordinates[0])).addTo(t),r=n.getBounds();return t.fitBounds(r,{animate:!1}),setTimeout(()=>{t.fitBounds(r,{animate:!1}),t.setView(n.getCenter(),void 0,{animate:!1})},1),n}t.setZoom(5)}var A=[[-90,-180],[90,180]];function j(e){let t=e.match(/^POINT\s*\(\s*([^()]+)\s*\)$/i);if(t){let e=M(t[1]);return e?{type:`Point`,coordinates:e}:void 0}let n=e.match(/^POLYGON\s*\(\(\s*(.*?)\s*\)\)$/i);if(!n)return;let r=n[1].split(`,`).map(M);if(!(r.length<3||r.some(e=>!e)))return{type:`Polygon`,coordinates:[r]}}function M(e){let t=e.trim().split(/\s+/).map(Number);return t.length===2&&t.every(Number.isFinite)?t:void 0}function N(e){return e.type===`Point`?`POINT(${e.coordinates.join(` `)})`:`POLYGON((${e.coordinates[0].map(e=>e.join(` `)).join(`,`)}))`}function P(e){let t=[];if(e.columns<=0||e.rows<=0||!Number.isFinite(e.minX)||!Number.isFinite(e.maxX)||!Number.isFinite(e.minY)||!Number.isFinite(e.maxY))return t;let n=(e.maxX-e.minX)/e.columns,r=(e.maxY-e.minY)/e.rows;for(let i=0;i<Math.min(e.rows,e.counts.length);i++){let a=e.counts[i];if(a!==null)for(let o=0;o<Math.min(e.columns,a.length);o++){if(!Number.isFinite(a[o])||a[o]<=0)continue;let s=e.maxY-(i+.5)*r,c=e.minX+(o+.5)*n;t.push([s,c,a[o]])}}return t}export{C as LeafletPlugin,N as geometryToWkt,j as wktToGeometry,A as worldBounds};
@@ -8,6 +8,8 @@ export declare class ShaclPropertyTemplate {
8
8
  name: Literal | undefined;
9
9
  description: Literal | undefined;
10
10
  path: string | undefined;
11
+ pathAlternatives: string[] | undefined;
12
+ pathAlternativeBranches: Record<string, ShaclPropertyTemplate> | undefined;
11
13
  node: NamedNode | undefined;
12
14
  group: string | undefined;
13
15
  class: NamedNode | undefined;
@@ -47,4 +49,6 @@ export declare function aggregatedMinCount(template: ShaclPropertyTemplate): num
47
49
  export declare function aggregatedMaxCount(template: ShaclPropertyTemplate): number;
48
50
  export declare function cloneProperty(template: ShaclPropertyTemplate): ShaclPropertyTemplate;
49
51
  export declare function mergeQuads(template: ShaclPropertyTemplate, quads: Quad[]): ShaclPropertyTemplate;
50
- export declare function mergeProperty(target: ShaclPropertyTemplate, source: ShaclPropertyTemplate): void;
52
+ export declare function mergeProperty(target: ShaclPropertyTemplate, source: ShaclPropertyTemplate, preferSourceDisplayMetadata?: boolean): void;
53
+ export declare function propertyPathKey(template: ShaclPropertyTemplate): string | undefined;
54
+ export declare function propertyPathSegment(template: ShaclPropertyTemplate): string | string[];
@@ -9,13 +9,15 @@ export declare class ShaclProperty extends HTMLElement {
9
9
  constructor(template: ShaclPropertyTemplate, parent: ShaclNode);
10
10
  bindValues(valueSubject: NamedNode | BlankNode | undefined, multiValuedPath?: boolean): Promise<void>;
11
11
  initializeQuery(): Promise<void>;
12
- addPropertyInstance(value?: Term, linked?: boolean, forceRemovable?: boolean): Promise<HTMLElement | undefined>;
12
+ addPropertyInstance(value?: Term, linked?: boolean, forceRemovable?: boolean, predicate?: string, insert?: boolean): Promise<HTMLElement | undefined>;
13
13
  updateControls(): Promise<void>;
14
14
  instanceCount(): number;
15
+ refreshClassInstances(): void;
15
16
  hasRecursiveNodeShape(): boolean;
16
17
  toRDF(graph: Store, subject: NamedNode | BlankNode): void;
17
18
  filterValidValues(values: Quad[], valueSubject: NamedNode | BlankNode): Promise<Quad[]>;
18
19
  createAddControls(): Promise<HTMLDivElement>;
19
20
  }
20
21
  export declare function createPropertyInstance(template: ShaclPropertyTemplate, value?: Term, forceRemovable?: boolean, linked?: boolean, parentNode?: ShaclNode): Promise<HTMLElement>;
22
+ export declare function appendRemoveButton(instance: HTMLElement, label: string, dense: boolean, colorize: boolean, forceRemovable?: boolean): void;
21
23
  export declare function createRemoveButtonWrapper(colorize: boolean): HTMLDivElement;
@@ -1,7 +1,8 @@
1
1
  import { Term } from '@rdfjs/types';
2
+ export type QueryPathSegment = string | string[];
2
3
  export type QueryField = {
3
4
  id: string;
4
- path: string[];
5
+ path: QueryPathSegment[];
5
6
  shapePath?: string[];
6
7
  datatype?: string;
7
8
  };
@@ -1,4 +1,3 @@
1
- import { NamedNode, Quad, Literal, Prefixes } from 'n3';
2
- import { Editor } from './theme.js';
1
+ import { Quad, Prefixes } from 'n3';
2
+ export { editorToTerm as toRDF } from './editor.js';
3
3
  export declare function serialize(quads: Quad[], format: string, prefixes?: Prefixes): string;
4
- export declare function toRDF(editor: Editor): NamedNode | Literal | undefined;
package/dist/sparql.js CHANGED
@@ -3,7 +3,7 @@ var e=`http://www.w3.org/1999/02/22-rdf-syntax-ns#`,t=`http://www.w3.org/2001/XM
3
3
  `),a=this.wrapDataset(i);return T(t)?`SELECT (COUNT(DISTINCT ${E}) AS ?count) (MIN(${r}) AS ?min) (MAX(${r}) AS ?max) WHERE {\n${L(a)}\n}`:`SELECT ${r} ?count ?total WHERE {\n { SELECT ${r} (COUNT(DISTINCT ${E}) AS ?count) WHERE {\n${L(L(a))}\n } GROUP BY ${r} }\n { SELECT (COUNT(DISTINCT ${E}) AS ?total) WHERE {\n${L(L(a))}\n } }\n}\nORDER BY DESC(?count)\nLIMIT ${z(n,`bucketLimit`)}`}buildFacetsSelect(e,t=100){return`SELECT ?fieldId ?facetValue ?count ?total ?min ?max WHERE {\n${e.fields.map(n=>{let r=`?facetValue`,i=[this.rootPattern(e.query),...this.criterionPatterns(e.query),this.pathPattern(n.path,r,`facet_${R(n.id)}`)].filter(Boolean).join(`
4
4
  `),a=this.wrapDataset(i),o=`BIND(${P(n.id)} AS ?fieldId)`;return T(n)?`{\n ${o}\n { SELECT (COUNT(DISTINCT ${E}) AS ?count) (MIN(${r}) AS ?min) (MAX(${r}) AS ?max) WHERE {\n${L(L(a))}\n } }\n}`:`{\n ${o}\n { SELECT ${r} (COUNT(DISTINCT ${E}) AS ?count) WHERE {\n${L(L(a))}\n } GROUP BY ${r} ORDER BY DESC(?count) LIMIT ${z(t,`bucketLimit`)} }\n { SELECT (COUNT(DISTINCT ${E}) AS ?total) WHERE {\n${L(L(a))}\n } }\n}`}).map(L).join(`
5
5
  UNION
6
- `)}\n}`}rootPattern(e){return this.options.rootPattern?this.options.rootPattern({query:e,rootVariable:E,graphVariable:this.options.dataset?.type===`named`&&!this.options.dataset.graph?`?graph`:void 0}):e.targetClass?`${E} ${A(S)} ${A(s.namedNode(e.targetClass))} .`:`${E} ${A(C)} ${A(s.namedNode(e.rootShapeId))} .`}criterionPatterns(e){return e.criteria.flatMap((e,t)=>{let n=`?value_${t}`,r=this.pathPattern(e.field.path,n,`criterion_${t}`);if(e.operator===`equals`&&e.value)return[r,`VALUES ${n} { ${A(e.value)} }`];if(e.operator===`contains`&&e.value){let t=P(e.value.value),i=[`FILTER(CONTAINS(${this.options.caseSensitive?`STR(${n})`:`LCASE(STR(${n}))`}, ${this.options.caseSensitive?t:`LCASE(${t})`}))`];return e.value.termType===`Literal`&&e.value.language&&i.push(`FILTER(LANGMATCHES(LANG(${n}), ${P(e.value.language)}))`),[r,...i]}if(e.operator===`range`){let t=[];return e.min&&t.push(`FILTER(${n} >= ${A(e.min)})`),e.max&&t.push(`FILTER(${n} <= ${A(e.max)})`),[r,...t]}return[]})}pathPattern(e,t,n){let r=E;return e.map((i,a)=>{let o=a===e.length-1?t:`?${n}_${a}`,c=`${r} ${A(s.namedNode(i))} ${o} .`;return r=o,c}).join(`
6
+ `)}\n}`}rootPattern(e){return this.options.rootPattern?this.options.rootPattern({query:e,rootVariable:E,graphVariable:this.options.dataset?.type===`named`&&!this.options.dataset.graph?`?graph`:void 0}):e.targetClass?`${E} ${A(S)} ${A(s.namedNode(e.targetClass))} .`:`${E} ${A(C)} ${A(s.namedNode(e.rootShapeId))} .`}criterionPatterns(e){return e.criteria.flatMap((e,t)=>{let n=`?value_${t}`,r=this.pathPattern(e.field.path,n,`criterion_${t}`);if(e.operator===`equals`&&e.value)return[r,`VALUES ${n} { ${A(e.value)} }`];if(e.operator===`contains`&&e.value){let t=P(e.value.value),i=[`FILTER(CONTAINS(${this.options.caseSensitive?`STR(${n})`:`LCASE(STR(${n}))`}, ${this.options.caseSensitive?t:`LCASE(${t})`}))`];return e.value.termType===`Literal`&&e.value.language&&i.push(`FILTER(LANGMATCHES(LANG(${n}), ${P(e.value.language)}))`),[r,...i]}if(e.operator===`range`){let t=[];return e.min&&t.push(`FILTER(${n} >= ${A(e.min)})`),e.max&&t.push(`FILTER(${n} <= ${A(e.max)})`),[r,...t]}return[]})}pathPattern(e,t,n){let r=E;return e.map((i,a)=>{let o=a===e.length-1?t:`?${n}_${a}`,c=Array.isArray(i)?`(${i.map(e=>A(s.namedNode(e))).join(`|`)})`:A(s.namedNode(i)),l=`${r} ${c} ${o} .`;return r=o,l}).join(`
7
7
  `)}wrapDataset(e){let t=this.options.dataset??{type:`default`};return t.type==="default"?e:`GRAPH ${t.graph?A(t.graph):`?graph`} {\n${L(e)}\n}`}},O=class{constructor(e,t={}){this.builder=new D(t),this.executor=typeof e==`string`?k(e,t.headers):e,this.bucketLimit=Math.max(0,Math.floor(t.bucketLimit??100)),this.onError=t.onError}async getFacets(e){let t=[...e.fields];if(t.length===0)return[];if(e.signal.aborted)throw new DOMException(`Facet request aborted`,`AbortError`);try{let n=this.builder.buildFacetsSelect(e,this.bucketLimit),r=(await this.executor(n,e.signal)).results?.bindings??[],i=new Map;for(let e of r){let t=e.fieldId?.value;if(t){let n=i.get(t)??[];n.push(e),i.set(t,n)}}return t.map(e=>j(e,{results:{bindings:i.get(e.id)??[]}}))}catch(n){if(e.signal.aborted)throw n;return t.map(e=>(this.onError?.(n,e),{fieldId:e.id,count:0,error:!0}))}}async select(e,t={},n=new AbortController().signal){return this.executor(this.builder.buildSelect(e,t),n)}};function k(e,t={}){let n={"content-type":`application/x-www-form-urlencoded`,accept:`application/sparql-results+json`,...t};return async(t,r)=>{let i=await fetch(e,{method:`POST`,signal:r,headers:n,body:new URLSearchParams({query:t})});if(!i.ok)throw Error(`SPARQL request failed: ${i.status}`);return i.json()}}function A(e){if(e.termType===`NamedNode`)return`<${F(e.value)}>`;if(e.termType===`BlankNode`)return`_:${I(e.value)}`;if(e.termType===`Literal`){let t=e,n=P(t.value);return t.language?`${n}@${t.language.replace(/[^A-Za-z0-9-]/g,``)}`:t.datatype?`${n}^^<${F(t.datatype.value)}>`:n}throw Error(`Unsupported RDF term in SPARQL query: ${e.termType}`)}function j(e,t){let n=t.results?.bindings??[];if(T(e)){let t=n[0]??{};return{fieldId:e.id,count:N(t.count),min:t.min?M(t.min):void 0,max:t.max?M(t.max):void 0}}let r=n.flatMap(e=>e.facetValue?[{value:M(e.facetValue),count:N(e.count)}]:[]);return{fieldId:e.id,count:N(n[0]?.total),buckets:r}}function M(e){return e.type===`uri`?s.namedNode(e.value):e.type===`bnode`?s.blankNode(e.value):e[`xml:lang`]?s.literal(e.value,e[`xml:lang`]):e.datatype?s.literal(e.value,s.namedNode(e.datatype)):s.literal(e.value)}function N(e){let t=Number(e?.value??0);return Number.isFinite(t)?t:0}function P(e){return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`)}"`}function F(e){return e.replace(/[^A-Za-z0-9\-._~:/?#[\]@!$&'()*+,;=%]/g,e=>`%`+e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`))}function I(e){return e.replace(/[^A-Za-z0-9\-_.]/g,e=>`_`+e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`))}function L(e){return e.split(`
8
8
  `).map(e=>` ${e}`).join(`
9
9
  `)}function R(e){return e.replace(/[^A-Za-z0-9_]/g,`_`)}function z(e,t){if(!Number.isInteger(e)||e<0)throw Error(`${t} must be a non-negative integer`);return e}export{D as SparqlQueryBuilder,O as SparqlQueryProvider,A as termToSparql};
package/dist/theme.d.ts CHANGED
@@ -8,6 +8,14 @@ export type Editor = HTMLElement & {
8
8
  binaryData?: string;
9
9
  checked?: boolean;
10
10
  disabled?: boolean;
11
+ rdfTerm?: Term;
12
+ rdfTermState?: {
13
+ value: string;
14
+ language?: string;
15
+ checked?: boolean;
16
+ binaryData?: string;
17
+ };
18
+ rdfTerms?: Map<string, Term>;
11
19
  };
12
20
  export type InputListEntry = {
13
21
  value: Term | string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ulb-darmstadt/shacl-form",
3
- "version": "3.2.1",
3
+ "version": "3.3.0",
4
4
  "description": "SHACL form generator",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.js",
@@ -49,6 +49,7 @@
49
49
  ],
50
50
  "scripts": {
51
51
  "dev": "vite serve ./demo --host",
52
+ "build-demo": "vite build -c ./vite.config.demo.ts",
52
53
  "build": "npm run clean && tsc && npm run build-lib && npm run build-sparql && npm run build-bundle && npm run build-plugins",
53
54
  "preview": "vite preview",
54
55
  "test": "web-test-runner --config test/config.js",
@@ -85,7 +86,7 @@
85
86
  "vite": "^8.1.5"
86
87
  },
87
88
  "peerDependencies": {
88
- "@ro-kit/ui-widgets": "^1.0.50",
89
+ "@ro-kit/ui-widgets": "^1.0.51",
89
90
  "jsonld": "^9.0.0",
90
91
  "leaflet": "^1.9.4",
91
92
  "leaflet-editable": "^1.3.2",
@@ -51,17 +51,19 @@ type QueryCriterion = {
51
51
 
52
52
  type QueryField = {
53
53
  id: string
54
- path: string[]
54
+ path: QueryPathSegment[]
55
55
  shapePath?: string[]
56
56
  datatype?: string
57
57
  }
58
+
59
+ type QueryPathSegment = string | string[]
58
60
  ```
59
61
 
60
62
  - `rootShapeId` identifies the selected root node shape.
61
63
  - `targetClass` is its `sh:targetClass`, when present.
62
64
  - `criteria` contains only controls with an active value. An empty form therefore has an empty array.
63
65
  - `field.id` is an opaque, form-generated identifier. Use it to correlate a field with facet results; do not derive backend meaning from it.
64
- - `field.path` is the complete RDF predicate path from the root resource to the value. A nested field can therefore have a path such as `[ex:author, ex:name]`.
66
+ - `field.path` is the complete RDF predicate path from the root resource to the value. A nested field can therefore have a path such as `[ex:author, ex:name]`. An array-valued segment represents `sh:alternativePath`, for example `[[ex:father, ex:mother], ex:name]`.
65
67
  - `field.shapePath` identifies the property-shape branch. It distinguishes qualified or alternative branches that have the same RDF predicate path.
66
68
  - `field.datatype` is the field's datatype IRI when the shape supplies one.
67
69
 
@@ -125,7 +127,7 @@ type QueryFacet = {
125
127
 
126
128
  An inactive leaf with `count: 0` is given the `query-unavailable` class and hidden by the default theme. An active field remains visible even when its count becomes zero. Structural parent branches are hidden when they contain no available leaf. The host element receives `query-facets-empty` when no filter is available and affected properties receive `query-facet-error` for field-level failures.
127
129
 
128
- If a provider is installed before initialization, the form has `query-facets-pending` and displays the configured loading text until the first facets arrive. Call `form.refreshQueryFacets()` after filters maintained outside the component change; it makes a new facet request without changing or emitting the query. The method is a no-op outside query mode.
130
+ While a query-mode component initializes, the `shacl-form` host has the `loading` attribute. If a provider is installed before initialization, the attribute remains and the configured loading text is displayed until the first facets arrive. Applications can use `shacl-form[loading]` to style both loading phases without reaching into the shadow root. Call `form.refreshQueryFacets()` after filters maintained outside the component change; it makes a new facet request without changing or emitting the query. The method is a no-op outside query mode.
129
131
 
130
132
  If `getFacets` throws, the component emits a bubbling, composed `queryerror` event whose `detail` is the thrown value. Aborted requests do not emit this event.
131
133
 
@@ -239,7 +241,7 @@ For each refresh, the provider builds one request containing a `UNION` branch fo
239
241
  - Discrete fields are grouped by value. Bucket counts and the total field count use `COUNT(DISTINCT ?root)`.
240
242
  - Numeric and temporal fields return `COUNT(DISTINCT ?root)`, `MIN(?facetValue)`, and `MAX(?facetValue)`.
241
243
  - `bucketLimit` is applied independently to each discrete field.
242
- - Nested `field.path` values become a sequence of triple patterns from `?root` to the facet value.
244
+ - Nested `field.path` values become a sequence of triple patterns from `?root` to the facet value. Array-valued segments become SPARQL alternative paths such as `(<father>|<mother>)`.
243
245
 
244
246
  Because all active criteria are included, facet results describe the already-filtered result set. This includes a criterion on the field currently being faceted.
245
247
 
@@ -1,13 +0,0 @@
1
- import{A as e,B as t,N as n,S as r,U as i,Y as a,a as o,n as s,o as c,p as l,t as u,v as d,w as f,z as p}from"./query-rxkbsWqy.js";import{DataFactory as m}from"n3";import{RokitInput as h,RokitSelect as g,RokitSlider as _,epochToDate as v}from"@ro-kit/ui-widgets";function y(e,t){let n=document.createElement(`div`),r=!!(t.in||t.class||t.datatype?.equals(a));n.classList.add(`query-editor`),n.dataset.queryFieldId=e.id,n.setAttribute(`part`,`query-editor`);let o=document.createElement(`label`);o.textContent=t.label,t.description&&(o.title=t.description.value),n.appendChild(o);let s=document.createElement(`div`);s.classList.add(`query-controls`),n.appendChild(s);let c,l=O(t),d,f=(e=``)=>{let n=document.createElement(`div`);n.classList.add(`query-value-row`);let r=new g;r.classList.add(`editor`,`query-choice`),r.clearable=!0,r.dense=t.config.theme.dense,r.placeholder=``,r.setAttribute(`exportparts`,`facet-count`);let i=document.createElement(`ul`);for(let e of l){let t=document.createElement(`li`);if(t.dataset.value=N(e.term),t.textContent=e.label,e.count!==void 0){let n=document.createElement(`span`);n.classList.add(`facet-count`),n.setAttribute(`part`,`facet-count`),n.dataset.count=String(e.count),t.append(` `,n)}i.appendChild(t)}return r.appendChild(i),r.value=e,n.appendChild(r),n},p=(e=[])=>{s.replaceChildren(),s.appendChild(f(e[0]??``))},m=(e,n=``)=>{let r=new h;return r.classList.add(`editor`,`query-range-bound`),r.type=M(t),r.label=e,r.clearable=!0,r.dense=t.config.theme.dense,r.value=n,r},v=e=>{s.replaceChildren();let n=b(t,c);n&&n[0]<n[1]&&(d=n);let r=D(n,e&&d);if(!r||r[0]===r[1]){s.append(m(`Minimum`,e?.min?.value),m(`Maximum`,e?.max?.value));return}let i=new _;i.classList.add(`editor`,`query-range-slider`),i.dense=t.config.theme.dense,i.clearable=!0,i.range=``,i.setAttribute(`range`,``),i.min=String(r[0]),i.max=String(r[1]),i.step=String(x(t,r)),i.labelFormatter=e=>S(e,t);let a=e?.min?C(e.min,t):r[0],o=e?.max?C(e.max,t):r[1];i.value=JSON.stringify([E(a??r[0],r[0],r[1]),E(o??r[1],r[0],r[1])]),i.dataset.active=e?.min||e?.max?`true`:`false`,i.addEventListener(`change`,()=>{i.dataset.active=`true`}),s.appendChild(i)};return n.getQueryCriteria=()=>{if(u(e)){let n=s.querySelector(`rokit-slider`);if(n){if(n.dataset.active!==`true`)return[];let r=T(n.value);return r?[{field:e,operator:`range`,min:w(r[0],t),max:w(r[1],t)}]:[]}let r=s.querySelectorAll(`rokit-input`),i=A(r[0]?.value,t),a=A(r[1]?.value,t);return i||a?[{field:e,operator:`range`,min:i,max:a}]:[]}if(r)return Array.from(s.querySelectorAll(`rokit-select`)).flatMap(t=>{if(!t.value)return[];let n=l.find(e=>N(e.term)===t.value)?.term;return n?[{field:e,operator:`equals`,value:n}]:[]});let n=j(t)&&!t.class&&!t.nodeKind?.value.endsWith(`#IRI`)?`contains`:`equals`;return Array.from(s.querySelectorAll(`.query-value-row`)).flatMap(r=>{let i=r.querySelector(`.query-value`),a=r.querySelector(`.query-language`)?.value,o=A(i?.value,t,a);return o?[{field:e,operator:n,value:o}]:[]})},n.setQueryFacet=i=>{let a=n.getQueryCriteria();if(c=i,r&&c?.buckets){let e=new Map(O(t).map(e=>[N(e.term),e])),n=new Map(a.flatMap(e=>e.value?[[N(e.value),e.value]]:[]));l=c.buckets.flatMap(n=>{let r=e.get(N(n.value));return t.in&&!r?[]:[{term:n.value,label:n.label??r?.label??n.value.value,count:n.count}]});for(let[t,r]of n)l.some(e=>N(e.term)===t)||l.push({term:r,label:e.get(t)?.label??r.value,count:0});p([...n.keys()])}else if(u(e)){let e=a[0];v(e?{min:e.min,max:e.max}:void 0)}else if(!i)for(let e of s.querySelectorAll(`.query-value`))e.value=``},u(e)?v():r?p():(s.replaceChildren(),s.appendChild((()=>{let e=document.createElement(`div`);e.classList.add(`query-value-row`);let r=new h;r.classList.add(`editor`,`query-value`),r.type=M(t),r.clearable=!0,r.dense=t.config.theme.dense;let a;if(r.addEventListener(`input`,()=>{clearTimeout(a),a=setTimeout(()=>{n.dispatchEvent(new Event(`change`,{bubbles:!0}))},300)}),e.appendChild(r),t.datatype?.equals(i)){let n=t.languageIn?.length?document.createElement(`select`):document.createElement(`input`);if(n.classList.add(`lang-chooser`,`query-language`),n.title=`Language of the text`,n.setAttribute(`aria-label`,`Language of the text`),n instanceof HTMLSelectElement)for(let e of t.languageIn??[]){let t=document.createElement(`option`);t.value=e.value,t.textContent=e.value,n.appendChild(t)}else n.maxLength=35,n.placeholder=`lang?`,n.value=t.config.languages.find(e=>e.length>0)??``;e.appendChild(n)}return e})())),n}function b(e,t){let n=t?.min?C(t.min,e):void 0,r=t?.max?C(t.max,e):void 0,i=e.minInclusive??(e.minExclusive===void 0?void 0:e.minExclusive+1),a=e.maxInclusive??(e.maxExclusive===void 0?void 0:e.maxExclusive-1),o=n===void 0?i:i===void 0?n:Math.max(n,i),s=r===void 0?a:a===void 0?r:Math.min(r,a);return o!==void 0&&s!==void 0&&Number.isFinite(o)&&Number.isFinite(s)&&o<=s?[o,s]:void 0}function x(e,t){return e.datatype?.value===`http://www.w3.org/2001/XMLSchema#integer`?1:e.datatype?.value===`http://www.w3.org/2001/XMLSchema#date`?86400:e.datatype?.value===`http://www.w3.org/2001/XMLSchema#dateTime`?1:Math.max((t[1]-t[0])/1e3,2**-52)}function S(e,t){return t.datatype?.value===`http://www.w3.org/2001/XMLSchema#date`?v(e,!0):t.datatype?.value===`http://www.w3.org/2001/XMLSchema#dateTime`?v(e):String(Math.round(e*1e3)/1e3)}function C(e,t){if(t.datatype?.value===`http://www.w3.org/2001/XMLSchema#date`||t.datatype?.value===`http://www.w3.org/2001/XMLSchema#dateTime`){let t=Date.parse(e.value);return Number.isFinite(t)?t/1e3:void 0}let n=Number(e.value);return Number.isFinite(n)?n:void 0}function w(e,t){let n=t.datatype;return n?.value===`http://www.w3.org/2001/XMLSchema#date`?m.literal(v(e,!0),n):n?.value===`http://www.w3.org/2001/XMLSchema#dateTime`?m.literal(v(e),n):m.literal(String(e),n)}function T(e){try{let t=JSON.parse(e);return Array.isArray(t)&&t.length===2&&t.every(Number.isFinite)?[Number(t[0]),Number(t[1])]:void 0}catch{return}}function E(e,t,n){return Math.min(n,Math.max(t,e))}function D(e,t){return e&&e[0]<e[1]?e:t||e}function O(t){if(t.datatype?.equals(a))return[{term:m.literal(`true`,a),label:`true`},{term:m.literal(`false`,a),label:`false`}];let r=[];return t.in?r=e(t.config.lists[t.in]??[],t.config.store,t.config.languages):t.class&&(r=n(t.class,t)),k(r)}function k(e){return e.flatMap(e=>[...typeof e.value==`string`?[]:[{term:e.value,label:e.label||e.value.value}],...k(e.children??[])])}function A(e,t,n){if(e)return t.class||t.nodeKind?.value.endsWith(`#IRI`)?m.namedNode(e):t.datatype?.equals(i)?n?m.literal(e,n):void 0:t.datatype?m.literal(e,t.datatype):m.literal(e)}function j(e){return!e.datatype||e.datatype.value===`http://www.w3.org/2001/XMLSchema#string`||e.datatype.equals(i)}function M(e){let t=e.datatype?.value;return[`http://www.w3.org/2001/XMLSchema#integer`,`http://www.w3.org/2001/XMLSchema#float`,`http://www.w3.org/2001/XMLSchema#double`,`http://www.w3.org/2001/XMLSchema#decimal`].includes(t??``)?`number`:t===`http://www.w3.org/2001/XMLSchema#date`?`date`:t===`http://www.w3.org/2001/XMLSchema#dateTime`?`datetime-local`:`text`}function N(e){if(e.termType===`Literal`){let t=e;return`${e.termType}:${e.value}:${t.language}:${t.datatype?.value}`}return`${e.termType}:${e.value}`}var P=`form.mode-query { padding: 0; }
2
- form.mode-query.query-facets-pending > shacl-node { display: none; }
3
- .mode-query shacl-property.query-unavailable { display: none; }
4
- .mode-query .shacl-group:not(:has(shacl-property:not(.query-unavailable))), .mode-query shacl-node:not(:has(shacl-property:not(.query-unavailable))) { display: none; }
5
- .query-editor { display: flex; align-items: center; width: 100%; padding: 3px 0; }
6
- .query-editor > label { width: var(--label-width); flex-shrink: 0; padding-right: 1em; word-break: break-word; }
7
- .query-controls { display: flex; flex: 1; min-width: 0; }
8
- .query-controls > rokit-input, .query-controls > rokit-slider, .query-value-row > rokit-input, .query-value-row > rokit-select { min-height: 28px; width: 100%; flex-grow: 1; }
9
- .query-value-row { display: flex; flex: 1; width: 100%; min-width: 0; gap: 4px; }
10
- .query-language { min-height: 28px; flex: 0 0 auto; }
11
- .query-range-slider[data-active='false'] { opacity: 0.7; }
12
- .query-facet-error .query-editor > label { color: var(--shacl-error-color); }
13
- `,F=0,I=class{constructor(e){this.stylesheet=new CSSStyleSheet,this.facetRequest=0,this.facetsApplied=!1,this.host=e,this.stylesheet.replaceSync(P)}async initialize(){await this.emitQueryAndRefreshFacets()}handleChange(){this.emitQueryAndRefreshFacets()}getQuery(){let e=this.host.shape;return e?{rootShapeId:e.template.id.value,targetClass:e.template.targetClass?.value,criteria:Array.from(this.host.form.querySelectorAll(`.query-editor`)).flatMap(e=>e.getQueryCriteria())}:{rootShapeId:``,criteria:[]}}refreshFacets(){this.host.shape&&this.requestFacets(this.getQuery())}dispose(){this.facetAbortController?.abort(),this.host.classList.remove(`query-facets-empty`)}async emitQueryAndRefreshFacets(){if(!this.host.shape)return;let e=this.getQuery();this.host.dispatchEvent(new CustomEvent(`query`,{bubbles:!0,composed:!0,detail:e})),await this.requestFacets(e)}async requestFacets(e){let t=this.host.config.queryFacetProvider;if(!t)return;this.facetAbortController?.abort();let n=new AbortController;this.facetAbortController=n;let r=++this.facetRequest;this.facetsApplied||this.setFacetsPending(!0);try{let i=Array.from(this.host.form.querySelectorAll(`.query-editor`)).map(e=>e.queryField),a=await t.getFacets({query:e,fields:i,signal:n.signal});if(n.signal.aborted||r!==this.facetRequest)return;this.applyFacets(a),this.facetsApplied=!0,this.setFacetsPending(!1)}catch(e){if(n.signal.aborted)return;this.setFacetsPending(!1),this.host.dispatchEvent(new CustomEvent(`queryerror`,{bubbles:!0,composed:!0,detail:e}))}}applyFacets(e){let t=new Map(e.map(e=>[e.fieldId,e]));for(let e of Array.from(this.host.form.querySelectorAll(`.query-editor`))){let n=t.get(e.queryField.id),r=e.getQueryCriteria().length>0;e.setQueryFacet(n);let i=e.closest(`shacl-property`);i?.classList.toggle(`query-unavailable`,n?.count===0&&!r),i?.classList.toggle(`query-facet-error`,n?.error===!0)}let n=Array.from(this.host.form.querySelectorAll(`shacl-property`)).reverse();for(let e of n){if(e.querySelector(`:scope > .query-editor, :scope > .collapsible > .query-editor`))continue;let t=Array.from(e.querySelectorAll(`.query-editor`)).some(e=>!e.closest(`shacl-property`)?.classList.contains(`query-unavailable`));e.classList.toggle(`query-unavailable`,!t)}let r=Array.from(this.host.form.querySelectorAll(`.query-editor`)).some(e=>!e.closest(`shacl-property`)?.classList.contains(`query-unavailable`));this.host.classList.toggle(`query-facets-empty`,!r)}setFacetsPending(e){this.host.form.classList.toggle(`query-facets-pending`,e);let t=this.host.form.querySelector(`.query-facets-loading`);if(!e)t?.remove();else if(!t){let e=document.createElement(`div`);e.classList.add(`query-facets-loading`),e.textContent=this.host.config.attributes.loading,this.host.form.prepend(e)}}};async function L(e){let t=e.template;if(t.or?.length||t.xone?.length){let n=V(t);if(n){e.container.appendChild(R(n,e.parent));return}let r=t.or?.length?t.or:t.xone;e.container.appendChild(d(r,e,t.config));return}if(!t.nodeShapes.size){e.container.appendChild(R(t,e.parent));return}for(let n of t.nodeShapes){let r=new Set(e.parent.ancestorShapeIds);if(r.add(e.parent.template.id.value),r.has(n.id.value))continue;let i=e.parent.queryContext??{path:[],shapePath:[]},a=new s(n,void 0,t.nodeKind,t.label,!1,r,{path:[...i.path,t.path],shapePath:[...i.shapePath,H(t)]}),o=document.createElement(`div`);o.classList.add(`property-instance`,`query-structure`),o.setAttribute(`part`,`property-instance`),t.config.hierarchyColorsStyleSheet!==void 0&&o.appendChild(c(!0)),o.appendChild(a),e.container.appendChild(o),await a.ready}}function R(e,t){let n=t.queryContext??{path:[],shapePath:[]},r={id:`qf${(F++).toString(36)}`,path:[...n.path,e.path],shapePath:[...n.shapePath,H(e)],datatype:e.datatype?.value},i=l(e.path,e.datatype?.value)?.createQueryEditor?.(r,e)??y(r,e);return i.queryField=r,i.classList.add(`property-instance`,`query-editor`),i.dataset.path=e.path,i}async function z(e,t){if(!e.length)return;for(let t of e)await t.initializeQuery();let n=e[0];t.replaceWith(n);for(let t=1;t<e.length;t++)n.after(e[t]),n=e[t];n.dispatchEvent(new Event(`change`,{bubbles:!0}))}async function B(e,t,n){e.or=void 0,e.xone=void 0;let r=new o(e,t.parent);await r.initializeQuery(),n.replaceWith(r),r.dispatchEvent(new Event(`change`,{bubbles:!0}))}function V(e){let n=e.or??e.xone;if(!n?.length)return;let i=n.map(t=>{let n=r(e);return n.or=void 0,n.xone=void 0,f(n,e.config.store.getQuads(t,null,null,null)),n.nodeShapes.size===0?n.datatype:void 0});if(i.some(e=>!e||!t.has(e.value)))return;let a=r(e);return a.or=void 0,a.xone=void 0,a.datatype=i.find(e=>e&&p.has(e.value))??i[0],a}function H(e){return e.qualifiedValueShape?e.id.value:e.path}export{I as QueryModeController,z as activateNodeConstraintOption,B as activatePropertyConstraintOption,L as initializeQueryProperty};
@@ -1,13 +0,0 @@
1
- import{A as e,E as t,H as n,J as r,M as i,Q as a,Y as o,a as s,b as c,h as l,it as u,m as d,n as f,o as p,ot as m,p as h,t as g,v as _,z as v}from"./query-igazZxn_.js";function y(e,t){let n=document.createElement(`div`),r=!!(t.in||t.class||t.datatype?.equals(u));n.classList.add(`query-editor`),n.dataset.queryFieldId=e.id,n.setAttribute(`part`,`query-editor`);let i=document.createElement(`label`);i.textContent=t.label,t.description&&(i.title=t.description.value),n.appendChild(i);let o=document.createElement(`div`);o.classList.add(`query-controls`),n.appendChild(o);let s,c=O(t),f,p=(e=``)=>{let n=document.createElement(`div`);n.classList.add(`query-value-row`);let r=new d;r.classList.add(`editor`,`query-choice`),r.clearable=!0,r.dense=t.config.theme.dense,r.placeholder=``,r.setAttribute(`exportparts`,`facet-count`);let i=document.createElement(`ul`);for(let e of c){let t=document.createElement(`li`);if(t.dataset.value=N(e.term),t.textContent=e.label,e.count!==void 0){let n=document.createElement(`span`);n.classList.add(`facet-count`),n.setAttribute(`part`,`facet-count`),n.dataset.count=String(e.count),t.append(` `,n)}i.appendChild(t)}return r.appendChild(i),r.value=e,n.appendChild(r),n},m=(e=[])=>{o.replaceChildren(),o.appendChild(p(e[0]??``))},h=(e,n=``)=>{let r=new l;return r.classList.add(`editor`,`query-range-bound`),r.type=M(t),r.label=e,r.clearable=!0,r.dense=t.config.theme.dense,r.value=n,r},v=e=>{o.replaceChildren();let n=b(t,s);n&&n[0]<n[1]&&(f=n);let r=D(n,e&&f);if(!r||r[0]===r[1]){o.append(h(`Minimum`,e?.min?.value),h(`Maximum`,e?.max?.value));return}let i=new _;i.classList.add(`editor`,`query-range-slider`),i.dense=t.config.theme.dense,i.clearable=!0,i.range=``,i.setAttribute(`range`,``),i.min=String(r[0]),i.max=String(r[1]),i.step=String(x(t,r)),i.labelFormatter=e=>S(e,t);let a=e?.min?C(e.min,t):r[0],c=e?.max?C(e.max,t):r[1];i.value=JSON.stringify([E(a??r[0],r[0],r[1]),E(c??r[1],r[0],r[1])]),i.dataset.active=e?.min||e?.max?`true`:`false`,i.addEventListener(`change`,()=>{i.dataset.active=`true`}),o.appendChild(i)};return n.getQueryCriteria=()=>{if(g(e)){let n=o.querySelector(`rokit-slider`);if(n){if(n.dataset.active!==`true`)return[];let r=T(n.value);return r?[{field:e,operator:`range`,min:w(r[0],t),max:w(r[1],t)}]:[]}let r=o.querySelectorAll(`rokit-input`),i=A(r[0]?.value,t),a=A(r[1]?.value,t);return i||a?[{field:e,operator:`range`,min:i,max:a}]:[]}if(r)return Array.from(o.querySelectorAll(`rokit-select`)).flatMap(t=>{if(!t.value)return[];let n=c.find(e=>N(e.term)===t.value)?.term;return n?[{field:e,operator:`equals`,value:n}]:[]});let n=j(t)&&!t.class&&!t.nodeKind?.value.endsWith(`#IRI`)?`contains`:`equals`;return Array.from(o.querySelectorAll(`.query-value-row`)).flatMap(r=>{let i=r.querySelector(`.query-value`),a=r.querySelector(`.query-language`)?.value,o=A(i?.value,t,a);return o?[{field:e,operator:n,value:o}]:[]})},n.setQueryFacet=i=>{let a=n.getQueryCriteria();if(s=i,r&&s?.buckets){let e=new Map(O(t).map(e=>[N(e.term),e])),n=new Map(a.flatMap(e=>e.value?[[N(e.value),e.value]]:[]));c=s.buckets.flatMap(n=>{let r=e.get(N(n.value));return t.in&&!r?[]:[{term:n.value,label:n.label??r?.label??n.value.value,count:n.count}]});for(let[t,r]of n)c.some(e=>N(e.term)===t)||c.push({term:r,label:e.get(t)?.label??r.value,count:0});m([...n.keys()])}else if(g(e)){let e=a[0];v(e?{min:e.min,max:e.max}:void 0)}else if(!i)for(let e of o.querySelectorAll(`.query-value`))e.value=``},g(e)?v():r?m():(o.replaceChildren(),o.appendChild((()=>{let e=document.createElement(`div`);e.classList.add(`query-value-row`);let r=new l;r.classList.add(`editor`,`query-value`),r.type=M(t),r.clearable=!0,r.dense=t.config.theme.dense;let i;if(r.addEventListener(`input`,()=>{clearTimeout(i),i=setTimeout(()=>{n.dispatchEvent(new Event(`change`,{bubbles:!0}))},300)}),e.appendChild(r),t.datatype?.equals(a)){let n=t.languageIn?.length?document.createElement(`select`):document.createElement(`input`);if(n.classList.add(`lang-chooser`,`query-language`),n.title=`Language of the text`,n.setAttribute(`aria-label`,`Language of the text`),n instanceof HTMLSelectElement)for(let e of t.languageIn??[]){let t=document.createElement(`option`);t.value=e.value,t.textContent=e.value,n.appendChild(t)}else n.maxLength=35,n.placeholder=`lang?`,n.value=t.config.languages.find(e=>e.length>0)??``;e.appendChild(n)}return e})())),n}function b(e,t){let n=t?.min?C(t.min,e):void 0,r=t?.max?C(t.max,e):void 0,i=e.minInclusive??(e.minExclusive===void 0?void 0:e.minExclusive+1),a=e.maxInclusive??(e.maxExclusive===void 0?void 0:e.maxExclusive-1),o=n===void 0?i:i===void 0?n:Math.max(n,i),s=r===void 0?a:a===void 0?r:Math.min(r,a);return o!==void 0&&s!==void 0&&Number.isFinite(o)&&Number.isFinite(s)&&o<=s?[o,s]:void 0}function x(e,t){return e.datatype?.value===`http://www.w3.org/2001/XMLSchema#integer`?1:e.datatype?.value===`http://www.w3.org/2001/XMLSchema#date`?86400:e.datatype?.value===`http://www.w3.org/2001/XMLSchema#dateTime`?1:Math.max((t[1]-t[0])/1e3,2**-52)}function S(e,t){return t.datatype?.value===`http://www.w3.org/2001/XMLSchema#date`?h(e,!0):t.datatype?.value===`http://www.w3.org/2001/XMLSchema#dateTime`?h(e):String(Math.round(e*1e3)/1e3)}function C(e,t){if(t.datatype?.value===`http://www.w3.org/2001/XMLSchema#date`||t.datatype?.value===`http://www.w3.org/2001/XMLSchema#dateTime`){let t=Date.parse(e.value);return Number.isFinite(t)?t/1e3:void 0}let n=Number(e.value);return Number.isFinite(n)?n:void 0}function w(e,t){let n=t.datatype;return n?.value===`http://www.w3.org/2001/XMLSchema#date`?m.literal(h(e,!0),n):n?.value===`http://www.w3.org/2001/XMLSchema#dateTime`?m.literal(h(e),n):m.literal(String(e),n)}function T(e){try{let t=JSON.parse(e);return Array.isArray(t)&&t.length===2&&t.every(Number.isFinite)?[Number(t[0]),Number(t[1])]:void 0}catch{return}}function E(e,t,n){return Math.min(n,Math.max(t,e))}function D(e,t){return e&&e[0]<e[1]?e:t||e}function O(e){if(e.datatype?.equals(u))return[{term:m.literal(`true`,u),label:`true`},{term:m.literal(`false`,u),label:`false`}];let t=[];return e.in?t=v(e.config.lists[e.in]??[],e.config.store,e.config.languages):e.class&&(t=n(e.class,e)),k(t)}function k(e){return e.flatMap(e=>[...typeof e.value==`string`?[]:[{term:e.value,label:e.label||e.value.value}],...k(e.children??[])])}function A(e,t,n){if(e)return t.class||t.nodeKind?.value.endsWith(`#IRI`)?m.namedNode(e):t.datatype?.equals(a)?n?m.literal(e,n):void 0:t.datatype?m.literal(e,t.datatype):m.literal(e)}function j(e){return!e.datatype||e.datatype.value===`http://www.w3.org/2001/XMLSchema#string`||e.datatype.equals(a)}function M(e){let t=e.datatype?.value;return[`http://www.w3.org/2001/XMLSchema#integer`,`http://www.w3.org/2001/XMLSchema#float`,`http://www.w3.org/2001/XMLSchema#double`,`http://www.w3.org/2001/XMLSchema#decimal`].includes(t??``)?`number`:t===`http://www.w3.org/2001/XMLSchema#date`?`date`:t===`http://www.w3.org/2001/XMLSchema#dateTime`?`datetime-local`:`text`}function N(e){if(e.termType===`Literal`){let t=e;return`${e.termType}:${e.value}:${t.language}:${t.datatype?.value}`}return`${e.termType}:${e.value}`}var P=`form.mode-query { padding: 0; }
2
- form.mode-query.query-facets-pending > shacl-node { display: none; }
3
- .mode-query shacl-property.query-unavailable { display: none; }
4
- .mode-query .shacl-group:not(:has(shacl-property:not(.query-unavailable))), .mode-query shacl-node:not(:has(shacl-property:not(.query-unavailable))) { display: none; }
5
- .query-editor { display: flex; align-items: center; width: 100%; padding: 3px 0; }
6
- .query-editor > label { width: var(--label-width); flex-shrink: 0; padding-right: 1em; word-break: break-word; }
7
- .query-controls { display: flex; flex: 1; min-width: 0; }
8
- .query-controls > rokit-input, .query-controls > rokit-slider, .query-value-row > rokit-input, .query-value-row > rokit-select { min-height: 28px; width: 100%; flex-grow: 1; }
9
- .query-value-row { display: flex; flex: 1; width: 100%; min-width: 0; gap: 4px; }
10
- .query-language { min-height: 28px; flex: 0 0 auto; }
11
- .query-range-slider[data-active='false'] { opacity: 0.7; }
12
- .query-facet-error .query-editor > label { color: var(--shacl-error-color); }
13
- `,F=0,I=class{constructor(e){this.stylesheet=new CSSStyleSheet,this.facetRequest=0,this.facetsApplied=!1,this.host=e,this.stylesheet.replaceSync(P)}async initialize(){await this.emitQueryAndRefreshFacets()}handleChange(){this.emitQueryAndRefreshFacets()}getQuery(){let e=this.host.shape;return e?{rootShapeId:e.template.id.value,targetClass:e.template.targetClass?.value,criteria:Array.from(this.host.form.querySelectorAll(`.query-editor`)).flatMap(e=>e.getQueryCriteria())}:{rootShapeId:``,criteria:[]}}refreshFacets(){this.host.shape&&this.requestFacets(this.getQuery())}dispose(){this.facetAbortController?.abort(),this.host.classList.remove(`query-facets-empty`)}async emitQueryAndRefreshFacets(){if(!this.host.shape)return;let e=this.getQuery();this.host.dispatchEvent(new CustomEvent(`query`,{bubbles:!0,composed:!0,detail:e})),await this.requestFacets(e)}async requestFacets(e){let t=this.host.config.queryFacetProvider;if(!t)return;this.facetAbortController?.abort();let n=new AbortController;this.facetAbortController=n;let r=++this.facetRequest;this.facetsApplied||this.setFacetsPending(!0);try{let i=Array.from(this.host.form.querySelectorAll(`.query-editor`)).map(e=>e.queryField),a=await t.getFacets({query:e,fields:i,signal:n.signal});if(n.signal.aborted||r!==this.facetRequest)return;this.applyFacets(a),this.facetsApplied=!0,this.setFacetsPending(!1)}catch(e){if(n.signal.aborted)return;this.setFacetsPending(!1),this.host.dispatchEvent(new CustomEvent(`queryerror`,{bubbles:!0,composed:!0,detail:e}))}}applyFacets(e){let t=new Map(e.map(e=>[e.fieldId,e]));for(let e of Array.from(this.host.form.querySelectorAll(`.query-editor`))){let n=t.get(e.queryField.id),r=e.getQueryCriteria().length>0;e.setQueryFacet(n);let i=e.closest(`shacl-property`);i?.classList.toggle(`query-unavailable`,n?.count===0&&!r),i?.classList.toggle(`query-facet-error`,n?.error===!0)}let n=Array.from(this.host.form.querySelectorAll(`shacl-property`)).reverse();for(let e of n){if(e.querySelector(`:scope > .query-editor, :scope > .collapsible > .query-editor`))continue;let t=Array.from(e.querySelectorAll(`.query-editor`)).some(e=>!e.closest(`shacl-property`)?.classList.contains(`query-unavailable`));e.classList.toggle(`query-unavailable`,!t)}let r=Array.from(this.host.form.querySelectorAll(`.query-editor`)).some(e=>!e.closest(`shacl-property`)?.classList.contains(`query-unavailable`));this.host.classList.toggle(`query-facets-empty`,!r)}setFacetsPending(e){this.host.form.classList.toggle(`query-facets-pending`,e);let t=this.host.form.querySelector(`.query-facets-loading`);if(!e)t?.remove();else if(!t){let e=document.createElement(`div`);e.classList.add(`query-facets-loading`),e.textContent=this.host.config.attributes.loading,this.host.form.prepend(e)}}};async function L(e){let n=e.template;if(n.or?.length||n.xone?.length){let r=V(n);if(r){e.container.appendChild(R(r,e.parent));return}let i=n.or?.length?n.or:n.xone;e.container.appendChild(t(i,e,n.config));return}if(!n.nodeShapes.size){e.container.appendChild(R(n,e.parent));return}for(let t of n.nodeShapes){let r=new Set(e.parent.ancestorShapeIds);if(r.add(e.parent.template.id.value),r.has(t.id.value))continue;let i=e.parent.queryContext??{path:[],shapePath:[]},a=new f(t,void 0,n.nodeKind,n.label,!1,r,{path:[...i.path,n.path],shapePath:[...i.shapePath,H(n)]}),o=document.createElement(`div`);o.classList.add(`property-instance`,`query-structure`),o.setAttribute(`part`,`property-instance`),n.config.hierarchyColorsStyleSheet!==void 0&&o.appendChild(p(!0)),o.appendChild(a),e.container.appendChild(o),await a.ready}}function R(e,t){let n=t.queryContext??{path:[],shapePath:[]},r={id:`qf${(F++).toString(36)}`,path:[...n.path,e.path],shapePath:[...n.shapePath,H(e)],datatype:e.datatype?.value},i=c(e.path,e.datatype?.value)?.createQueryEditor?.(r,e)??y(r,e);return i.queryField=r,i.classList.add(`property-instance`,`query-editor`),i.dataset.path=e.path,i}async function z(e,t){if(!e.length)return;for(let t of e)await t.initializeQuery();let n=e[0];t.replaceWith(n);for(let t=1;t<e.length;t++)n.after(e[t]),n=e[t];n.dispatchEvent(new Event(`change`,{bubbles:!0}))}async function B(e,t,n){e.or=void 0,e.xone=void 0;let r=new s(e,t.parent);await r.initializeQuery(),n.replaceWith(r),r.dispatchEvent(new Event(`change`,{bubbles:!0}))}function V(t){let n=t.or??t.xone;if(!n?.length)return;let a=n.map(n=>{let r=e(t);return r.or=void 0,r.xone=void 0,i(r,t.config.store.getQuads(n,null,null,null)),r.nodeShapes.size===0?r.datatype:void 0});if(a.some(e=>!e||!o.has(e.value)))return;let s=e(t);return s.or=void 0,s.xone=void 0,s.datatype=a.find(e=>e&&r.has(e.value))??a[0],s}function H(e){return e.qualifiedValueShape?e.id.value:e.path}export{I as QueryModeController,z as activateNodeConstraintOption,B as activatePropertyConstraintOption,L as initializeQueryProperty};