@urban-toolkit/autk-grammar 4.4.1 → 5.0.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.
- package/README.md +275 -5
- package/build/autk-grammar-schema.json +945 -425
- package/dist/autk-grammar.js +752 -426
- package/dist/autk-grammar.js.map +1 -1
- package/dist/autk-grammar.umd.cjs +2 -2
- package/dist/autk-grammar.umd.cjs.map +1 -1
- package/dist/data/autk-grammar-data.cjs +2 -0
- package/dist/data/autk-grammar-data.cjs.map +1 -0
- package/dist/data/autk-grammar-data.d.ts +349 -0
- package/dist/data/autk-grammar-data.js +165 -0
- package/dist/data/autk-grammar-data.js.map +1 -0
- package/dist/index.d.ts +555 -75
- package/package.json +7 -2
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(function(m,M){typeof exports=="object"&&typeof module<"u"?M(exports,require("@urban-toolkit/autk-db"),require("@urban-toolkit/autk-map"),require("@urban-toolkit/autk-plot"),require("@urban-toolkit/autk-core"),require("@urban-toolkit/autk-compute")):typeof define=="function"&&define.amd?define(["exports","@urban-toolkit/autk-db","@urban-toolkit/autk-map","@urban-toolkit/autk-plot","@urban-toolkit/autk-core","@urban-toolkit/autk-compute"],M):(m=typeof globalThis<"u"?globalThis:m||self,M(m["autk-grammar"]={},m.autkDb,m.autkMap,m.autkPlot,m.autkCore,m.autkCompute))})(this,(function(m,M,L,C,_,it){"use strict";function x(t){const{spec:e,adapters:r}=t;let o;async function i(){let a;if(e.data)for(const s of e.data)a=await r.db.resolveSource(a,s);if(e.compute)for(const s of e.compute)a=await r.compute.resolveCompute(a,s);if(e.map)if(Array.isArray(e.map))for(let s=0;s<e.map.length;s++){let u=e.map[s];await r.map.resolveMap(a,u,s)}else await r.map.resolveMap(a,e.map);if(e.plot)if(Array.isArray(e.plot))for(const s of e.plot)await r.plot.resolvePlot(a,s);else await r.plot.resolvePlot(a,e.plot);o=a}function n(a){return console.log("Spec to update",a),new Promise(s=>{s()})}function l(){console.log("Function not implemented yet")}return{run:i,updatedSpec:n,destroy:l,get context(){return o}}}var U=(t=>(t.CAT_ACCENT="schemeAccent",t.CAT_DARK2="schemeDark2",t.CAT_CATEGORY10="schemeCategory10",t.CAT_OBSERVABLE10="schemeObservable10",t.CAT_PAIRED="schemePaired",t.CAT_PASTEL1="schemePastel1",t.CAT_PASTEL2="schemePastel2",t.CAT_SET1="schemeSet1",t.CAT_SET2="schemeSet2",t.CAT_SET3="schemeSet3",t.CAT_TABLEAU10="schemeTableau10",t.SEQ_REDS="interpolateReds",t.SEQ_BLUES="interpolateBlues",t.SEQ_GREENS="interpolateGreens",t.SEQ_GREYS="interpolateGreys",t.SEQ_ORANGES="interpolateOranges",t.SEQ_PURPLES="interpolatePurples",t.SEQ_TURBO="interpolateTurbo",t.SEQ_VIRIDIS="interpolateViridis",t.SEQ_INFERNO="interpolateInferno",t.SEQ_MAGMA="interpolateMagma",t.SEQ_PLASMA="interpolatePlasma",t.SEQ_CIVIDIS="interpolateCividis",t.SEQ_WARM="interpolateWarm",t.SEQ_COOL="interpolateCool",t.SEQ_CUBEHELIX_DEFAULT="interpolateCubehelixDefault",t.SEQ_BU_GN="interpolateBuGn",t.SEQ_BU_PU="interpolateBuPu",t.SEQ_GN_BU="interpolateGnBu",t.SEQ_OR_RD="interpolateOrRd",t.SEQ_PU_BU_GN="interpolatePuBuGn",t.SEQ_PU_BU="interpolatePuBu",t.SEQ_PU_RD="interpolatePuRd",t.SEQ_RD_PU="interpolateRdPu",t.SEQ_YL_GN_BU="interpolateYlGnBu",t.SEQ_YL_GN="interpolateYlGn",t.SEQ_YL_OR_BR="interpolateYlOrBr",t.SEQ_YL_OR_RD="interpolateYlOrRd",t.DIV_BR_BG="interpolateBrBG",t.DIV_PR_GN="interpolatePRGn",t.DIV_PI_YG="interpolatePiYG",t.DIV_PU_OR="interpolatePuOr",t.DIV_RED_BLUE="interpolateRdBu",t.DIV_RED_GREY="interpolateRdGy",t.DIV_RED_YELLOW_BLUE="interpolateRdYlBu",t.DIV_RED_YELLOW_GREEN="interpolateRdYlGn",t.DIV_SPECTRAL="interpolateSpectral",t))(U||{}),T=(t=>(t.MIN_MAX="minMax",t.PERCENTILE="percentile",t))(T||{});function st(t){const{queryArea:e}=t;if(e.bbox===void 0)return{geocodeArea:e.geocodeArea,areas:e.areas};const r=s=>new Error(`OSM source "${t.outputTableName}": ${s}`);if(e.geocodeArea!==void 0||e.areas!==void 0)throw r("queryArea takes either bbox or geocodeArea with areas, not both.");const o=e.bbox;if(!Array.isArray(o)||o.length!==4||!o.every(s=>typeof s=="number"&&Number.isFinite(s)))throw r("queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.");const[i,n,l,a]=e.bbox;if(Math.abs(i)>180||Math.abs(l)>180)throw r("queryArea.bbox west and east must be longitudes from -180 to 180.");if(Math.abs(n)>90||Math.abs(a)>90)throw r("queryArea.bbox south and north must be latitudes from -90 to 90.");if(i>=l)throw r(`queryArea.bbox west (${i}) must be less than east (${l}); a box across the antimeridian is not supported.`);if(n>=a)throw r(`queryArea.bbox south (${n}) must be less than north (${a}).`);return{bbox:[i,n,l,a]}}function lt(t){const{autoLoadLayers:e,...r}=t;return{...r,queryArea:st(t),autoLoadLayers:{layers:e?.layers??[]}}}function Q(t){return`${t?`coordinateFormat is set to "${t}"`:"no coordinateFormat was specified, so it defaults to EPSG:4326 (WGS84 per RFC 7946)"}. Verify that coordinateFormat matches the actual CRS of the input data.`}function ut(t){let e=1/0,r=1/0,o=-1/0,i=-1/0;const n=a=>{if(Array.isArray(a)){if(typeof a[0]=="number"){const[s,u]=a;s<e&&(e=s),s>o&&(o=s),u<r&&(r=u),u>i&&(i=u);return}for(const s of a)n(s)}},l=a=>{a&&(a.type==="GeometryCollection"?a.geometries.forEach(l):n(a.coordinates))};for(const a of t.features??[])l(a?.geometry);return e<=o?[e,r,o,i]:void 0}function ct(t,e){function r(o,i){if(!i||!i.db)return;const n=document.getElementById(i.db);if(n){const l=o.getTablesMetadata();n.innerHTML+="<ul>";for(const a of l)n.innerHTML+=`<li>${a.name}: (${a.source}, ${a.type}) </li>`;n.innerHTML+="</ul>",n.innerHTML+=`<p>Number of tables: ${l.length}</p>`}}return{async resolveSource(o,i){let n=o;n||(n=new M.AutkDb,await n.init());let{type:l,...a}=i;switch(l){case"osm":return await n.loadOsm(lt(a)),r(n,t),n;case"csv":return await n.loadCsv(a),r(n,t),n;case"json":return await n.loadJson(a),r(n,t),n;case"geojson":{const s=a;let u;s.geojsonFileUrl?u=await(await fetch(s.geojsonFileUrl)).json():u=s.geojsonObject,e&&u&&e.set(s.outputTableName,u);const c=u?(()=>{const f={...s,geojsonObject:u};return delete f.geojsonFileUrl,f})():s,h=/^EPSG:4326$/i.test(c.coordinateFormat??"EPSG:4326"),p=u&&h?ut(u):void 0;if(p&&(p[1]<-90||p[3]>90))throw new Error(`GeoJSON layer "${c.outputTableName}" has y coordinates outside -90 to 90 (bbox: [${p.join(", ")}]), so they cannot be EPSG:4326 degrees. ${Q(c.coordinateFormat)}`);try{await n.loadGeojson(c)}catch(f){throw new Error(`Failed to load GeoJSON layer "${c.outputTableName}": ${f instanceof Error?f.message:String(f)}`)}try{const f=await n.getBoundingBoxFromLayer(c.outputTableName),d=25e6;if(!isFinite(f.minLon)||!isFinite(f.minLat)||!isFinite(f.maxLon)||!isFinite(f.maxLat)||Math.abs(f.minLon)>d||Math.abs(f.maxLon)>d||Math.abs(f.minLat)>d||Math.abs(f.maxLat)>d)throw new Error(`Geometry bounding box after transform is invalid for layer "${c.outputTableName}" (bbox: [${f.minLon}, ${f.minLat}, ${f.maxLon}, ${f.maxLat}]). ${Q(c.coordinateFormat)} The workspace uses ${M.DEFAULT_WORKSPACE_COORDINATE_FORMAT}; input is expected in EPSG:4326 by default.`)}catch(f){if(f instanceof Error&&f.message.includes("bounding box after transform"))throw f}return r(n,t),n}case"heatmap":{const s=a;return await n.buildHeatmap({tableJoinName:s.tableJoinName,near:{distance:s.near.distance},outputTableName:s.outputTableName,grid:s.grid,...s.groupBy&&{groupBy:s.groupBy}}),r(n,t),n}case"join":{const s=a;if(await n.spatialQuery({tableRootName:s.tableRootName,tableJoinName:s.tableJoinName,...s.near&&{near:s.near},...s.groupBy&&{groupBy:s.groupBy}}),e){const u=await n.getLayer(s.tableRootName);e.set(s.tableRootName,u)}return r(n,t),n}default:return}}}}function N(t){return typeof t.title=="string"&&t.title!==""?t.title:t.dataRef}function ft(t,e){const r=new Set;for(const o of t.layerRefs){const i=N(o);if(r.has(i))throw new Error(`Map ${e} draws two layers with the id "${i}". A layer's id is its title, else its dataRef: give each layer of a map its own title.`);r.add(i)}}const pt=/^#[0-9a-fA-F]{6}$/;function k(t,e,r){if(!pt.test(t))throw new Error(`Layer "${r}": ${e} must be a color written #rrggbb, not "${t}".`);return _.ColorMap.hexToRgb(t)}function mt(t,e){const r={};return t.color!=null&&(r.color=k(t.color,"color",e)),t.stroke===!1?r.showBorders=!1:t.stroke!=null&&(r.strokeColor=k(t.stroke,"stroke",e)),t.width!=null&&(r.polylinesWidth=t.width),r}function dt(t,e){return t.isColorMap!=null?t.isColorMap:e==="raster"?t.colorMapInterpolator!=null||t.colorMapRange!=null||t.colorMapCenter!=null||t.colorMapReverse===!0:t.color!=null?!1:t.colorMapInterpolator!=null||t.getFnv!=null}function ht(t,e){const r=t.features?.[0]?.properties?.[e];return r instanceof Float32Array?r:ArrayBuffer.isView(r)&&!(r instanceof DataView)||Array.isArray(r)?Float32Array.from(r,o=>Number.isFinite(Number(o))?Number(o):NaN):null}function yt(t,e,r,o,i){if(_.ColorMap.isCategorical(e.interpolator))return;if(i!=null){const u=r!=null?[i[0],r,i[1]]:[i[0],i[1]];return o===!0?u.reverse():u}if(!t)return;let n=0,l=0;for(let u=0;u<t.length;u++){const c=t[u];Number.isFinite(c)&&(l++,r!=null&&(n=Math.max(n,Math.abs(c-r))))}const a=r!=null&&n>0;if(l===0||!a&&o!==!0)return;const s=a&&r!=null?[r-n,r,r+n]:_.ColorMap.resolveDomainFromData(t,e);return o===!0?[...s].reverse():s}function gt(t,e){if(!(e==null||_.ColorMap.isCategorical(t.interpolator)))return[e[0],e[1]]}function bt(t){const e=t.colorMapRange;if(e===void 0)return;const r=l=>new Error(`Layer "${N(t)}": ${l}`);if(!Array.isArray(e)||e.length!==2||!e.every(l=>typeof l=="number"&&Number.isFinite(l)))throw r("colorMapRange must hold two numbers, [low, high].");const[o,i]=e;if(o>=i)throw r(`colorMapRange low (${o}) must be less than high (${i}).`);if(t.colorMapDomain!==void 0)throw r("set colorMapRange or colorMapDomain, not both.");const n=t.colorMapCenter;if(n!=null&&(n<o||n>i))throw r(`colorMapCenter (${n}) must lie within colorMapRange [${o}, ${i}].`)}function _t(t,e){return e&&e.length>0?{type:_.ColorMapDomainStrategy.USER,params:e}:t?.mode===T.PERCENTILE?t.lowerPercentile!==void 0||t.upperPercentile!==void 0?{type:_.ColorMapDomainStrategy.PERCENTILE,params:[t.lowerPercentile??0,t.upperPercentile??100]}:{type:_.ColorMapDomainStrategy.PERCENTILE}:{type:_.ColorMapDomainStrategy.MIN_MAX}}function Et(t,e){return e.split(".").reduce((r,o)=>{if(!(r==null||typeof r!="object"))return r[o]},t)}function At(t,e,r){const o=e.split("."),i={...t};let n=i;for(let l=0;l<o.length-1;l++)n[o[l]]={...n[o[l]]??{}},n=n[o[l]];return n[o[o.length-1]]=r,i}function wt(t,e){const o=t.features?.[0]?.properties?.bands??[];return o.find(n=>n.id===e||n.label===e?.replace(/\./g,"_"))?.id??o[0]?.id??e??""}function Mt(t,e,r,o,i){async function n(l,a,s){let u={};for(const c of a.getTablesMetadata())c.type!==void 0&&(u[c.name]=c.type);for(const c of s.layerRefs){const h=c.dataRef,p=N(c),f=u[h],d=c.getFnv,y=r?.get(h)??await a.getLayer(h),g=f==="raster"?y:{...y,features:(y.features??[]).filter(b=>b.geometry!=null)},R=f==="raster"?wt(g,d):"";f==="raster"?l.loadCollection(p,{collection:g,type:"raster",property:R}):l.loadCollection(p,{collection:g,type:f}),c.opacity!=null&&l.updateRenderInfo(p,{opacity:c.opacity});const S=mt(c,p);Object.keys(S).length>0&&l.updateRenderInfo(p,S),dt(c,f)&&l.updateRenderInfo(p,{isColorMap:!0}),c.isPick&&l.updateRenderInfo(p,{isPick:!0}),c.isSkip&&l.updateRenderInfo(p,{isSkip:!0});const{catchAllCategory:A,colorMapDomain:v}=c;let et=g,rt=v;if(d&&A&&v?.length){const b=new Set(v);et={...g,features:g.features.map(w=>{const at=w.properties,j=Et(at,d);return j==null||!b.has(String(j))?{...w,properties:At(at,d,A)}:w})},rt=b.has(A)?v:[...v,A]}const ot=f==="raster"&&c.transferFunction!=null;ot&&l.layerManager.searchByLayerId(p)?.setTransferFunction?.(c.transferFunction);const F=c.colorMapRange,nt=f==="raster"&&(F!=null||c.colorMapCenter!=null||c.colorMapReverse===!0);if(c.colorMapInterpolator||nt||F){const b={interpolator:c.colorMapInterpolator??l.layerManager.searchByLayerId(p)?.layerRenderInfo.colormap.config.interpolator??_.ColorMapInterpolator.SEQ_REDS,domainSpec:_t(c.normalization,rt)};let w;nt?w=yt(ht(g,R),b,c.colorMapCenter,c.colorMapReverse,F):f!=="raster"&&(w=gt(b,F)),w&&(b.domainSpec={type:_.ColorMapDomainStrategy.USER,params:w}),l.updateColorMap(p,{colorMap:b})}else ot&&l.updateColorMap(p,{colorMap:{}});if(d&&f!=="raster"){const b=d.startsWith("properties.")?d:`properties.${d}`;l.updateThematic(p,{collection:et,property:b})}}}return{async resolveMap(l,a,s=0){if(t&&t.map&&l){ft(a,s);for(const h of a.layerRefs)bt(h);let u;if(Array.isArray(t.map)?u=document.getElementById(t.map[s]):u=document.getElementById(t.map),!u)throw new Error("Could not find rendering target for map: "+t.map);if(!(u instanceof HTMLCanvasElement))throw new Error("Target for map is not a canvas: "+t.map);const c=new L.AutkMap(u);a.style&&c.style.setPredefinedStyle(a.style),await c.init(),await n(c,l,a);for(const h of a.layerRefs)e?.set(h.dataRef,c),i?.set(h.dataRef,N(h));o&&(o[s]=c),c.draw()}}}}function Rt(t){return{scatter:"scatterplot",bar:"barchart",line:"linechart",linechart:"linechart","parallel-coordinates":"parallel-coordinates",table:"table",heatmatrix:"heatmatrix"}[t]}function St(t,e,r,o,i,n){return{async resolvePlot(l,a){if(!t||!t.plot)return;const s=document.getElementById(t.plot);if(!s)throw new Error(`Could not find plot target: ${t.plot}`);const u=l;if(!u)throw new Error("No data context available for plot.");const c=i?.get(a.dataRef)??await u.getLayer(a.dataRef),h=a.events??[],p=new C.AutkPlot(s,{type:Rt(a.mark),collection:c,attributes:{axis:a.axis,...a.color&&{color:a.color}},labels:{axis:a.axis,title:a.title},events:h,...a.width&&{width:a.width},...a.height&&{height:a.height},...a.margins&&{margins:a.margins},...a.transform&&{transform:a.transform}});if(r?.set(a.dataRef,p),a.mapRef&&o?.set(a.dataRef,a.mapRef),a.mapRef&&e){const f=e.get(a.mapRef),d=n?.get(a.mapRef)??a.mapRef;if(f){f.updateRenderInfo(d,{isPick:!0}),f.events.on(L.MapEvent.PICKING,({selection:y})=>{p.setSelection(y)});for(const y of h)p.events.on(y,({selection:g})=>{f.setHighlightedIds(d,g)})}}}}}const B=134217728,Ct=4,It=32;function Y(t){return Array.isArray(t)?t.join(`
|
|
2
|
-
`):t}function E(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.fromFeature=="object"&&t.fromFeature!==null}function I(t,e){return t instanceof Map?t.get(e):t[e]}function P(t,e){return e.split(".").reduce((r,o)=>{if(!(r==null||typeof r!="object"))return r[o]},t)}function V(t){const e=[];for(const r of[t.uniforms,t.uniformMatrices])for(const o of Object.values(r??{}))E(o)&&e.push(o);return e}function H(t){return[...new Set([t.dataRef,...V(t).map(e=>e.fromFeature.layer)])]}function O(t){for(const e of V(t)){const{iterate:r,layer:o}=e.fromFeature;if(r==="all"||r==="batched")return{mode:r,layer:o}}return null}function q(t,e,r){const o=t.fromFeature,i=r!==void 0&&o.iterate==="all"?r:o.index??0,n=I(e,o.layer)?.features?.[i];return n?P(n,o.path):void 0}function D(t,e,r){if(!t)return;const o={};for(const[i,n]of Object.entries(t)){if(!E(n)){o[i]=n;continue}const l=Number(q(n,e,r)??NaN);Number.isFinite(l)?o[i]=l:typeof n.default=="number"&&(o[i]=n.default)}return o}function G(t,e,r){if(!t)return;const o={};for(const[i,n]of Object.entries(t)){if(!E(n)){o[i]=n;continue}const l=q(n,e,r),a=Array.isArray(l)?l:Array.isArray(n.default)?n.default:void 0;if(!a)continue;const s=n.cols??(Array.isArray(a[0])?a[0].length:0);s>0?o[i]={data:a,cols:s}:console.warn(`[autk-grammar] uniform matrix "${i}" has no column count; entry dropped`)}return o}function vt(t){return t!=null&&!(typeof t=="number"&&!Number.isFinite(t))}function W(t){return E(t)&&t.fromFeature.iterate==="batched"}function X(t,e){return Object.values(e??{}).some(W)?It:Object.values(t??{}).some(W)?Ct:0}function J(t,e,r=B){const o=X(t,e);return o>0?Math.floor(r/o):Number.POSITIVE_INFINITY}function K(t,e,r,o=B){const i={},n={},l=[];for(const s of[t,e])for(const u of Object.values(s??{}))E(u)&&u.fromFeature.iterate==="batched"&&u.fromFeature.required&&l.push(u.fromFeature.path);if(l.length>0){const s=r.length;r=r.filter(u=>l.every(c=>vt(P(u,c)))),r.length<s&&console.info(`[autk-grammar] batched compute dropped ${s-r.length} feature(s) missing ${l.join(", ")}`)}const a=J(t,e,o);r.length>a&&(console.warn(`[autk-grammar] batched compute capped at ${a} features (got ${r.length}): its largest packed array takes ${X(t,e)} B per feature, and a storage buffer binding holds ${o} B`),r=r.slice(0,a));for(const[s,u]of Object.entries(t??{}))if(E(u)&&u.fromFeature.iterate==="batched"){const c=typeof u.default=="number"?u.default:void 0;n[s]=r.map(h=>{const p=Number(P(h,u.fromFeature.path)??c);return Number.isFinite(p)?p:0})}else typeof u=="number"&&(i[s]=u);for(const[s,u]of Object.entries(e??{})){if(!E(u)||u.fromFeature.iterate!=="batched")continue;const c=[];for(const h of r){const p=P(h,u.fromFeature.path);let f=1/0,d=1/0,y=-1/0,g=-1/0;if(Array.isArray(p))for(const R of p){if(!Array.isArray(R)||R.length<2)continue;const S=Number(R[0]),A=Number(R[1]);!Number.isFinite(S)||!Number.isFinite(A)||(f=Math.min(f,S),d=Math.min(d,A),y=Math.max(y,S),g=Math.max(g,A))}Number.isFinite(f)||(f=0,d=0,y=0,g=0),c.push(f,d,y,d,y,g,f,g)}n[s]=c}return i.num_features=r.length,{uniforms:i,uniformArrays:n}}function $(t,e,r){const o=I(e,t.dataRef);if(!o)throw new Error(`compute: table "${t.dataRef}" is not loaded`);const i={collection:o,variableMapping:t.attributes,wgslBody:Y(t.wglsFunction)};t.attributeArrays&&(i.attributeArrays=t.attributeArrays),t.attributeMatrices&&(i.attributeMatrices=t.attributeMatrices),t.uniformArrays&&(i.uniformArrays=t.uniformArrays),t.outputColumnName&&(i.resultField=t.outputColumnName),t.outputColumns&&(i.outputColumns=t.outputColumns);const n=O(t);if(n?.mode==="batched"){const u=I(e,n.layer)?.features??[],c=K(t.uniforms,t.uniformMatrices,u),h=D(Z(t.uniforms),e)??{},p=G(Z(t.uniformMatrices),e);return i.uniforms={...h,...c.uniforms},i.uniformArrays={...i.uniformArrays??{},...c.uniformArrays},p&&Object.keys(p).length>0&&(i.uniformMatrices=p),i}const l=n?.mode==="all"?r:void 0,a=D(t.uniforms,e,l),s=G(t.uniformMatrices,e,l);return a&&(i.uniforms=a),s&&(i.uniformMatrices=s),i}function Z(t){if(t)return Object.fromEntries(Object.entries(t).filter(([,e])=>!(E(e)&&e.fromFeature.iterate==="batched")))}function Lt(t){return t.outputColumns??(t.outputColumnName?[t.outputColumnName]:[])}async function z(t,e,r){const o=O(t);if(o?.mode!=="all")return r($(t,e));const i=I(e,t.dataRef);if(!i)throw new Error(`compute: table "${t.dataRef}" is not loaded`);const n=Lt(t),l=structuredClone(i);for(const s of l.features){const u=s.properties??={},c=u.compute??={};for(const h of n)c[h]=0}const a=I(e,o.layer)?.features?.length??0;for(let s=0;s<a;s++){const u=await r({...$(t,e,s),collection:l});l.features.forEach((c,h)=>{const p=c.properties?.compute,f=u.features[h]?.properties?.compute;if(!(!p||!f))for(const d of n){const y=Number(f[d]);Number.isFinite(y)&&(p[d]+=y)}})}return l}function Nt(t){return{async resolveCompute(e,r){if(e){const o={};for(const l of H(r)){const a=t?.get(l);if(a)o[l]=a;else if(l===r.dataRef)o[l]=await e.getLayer(l);else try{o[l]=await e.getLayer(l)}catch{o[l]=void 0}}const i=new it.AutkComputeEngine,n=await z(r,o,l=>i.gpgpuPipeline(l));return t&&t.set(r.dataRef,n),e}}}}class tt{_listeners=new Map;on(e,r){this._listeners.has(e)||this._listeners.set(e,new Set);const o=this._listeners.get(e);return o.add(r),()=>o.delete(r)}emit(e,r){this._listeners.get(e)?.forEach(o=>o(r))}}class Pt{dataAdapter;mapAdapter;plotAdapter;computeAdapter;grammarEngine;_computeCache=new Map;_data={};_mapRegistry=new Map;_mapLayerIds=new Map;_maps=[];_plotRegistry=new Map;_fwdCleanups=[];_plotMapLinks=new Map;interactions=new tt;constructor(e){const r=new Map;this.dataAdapter=ct(e,r),this.mapAdapter=Mt(e,this._mapRegistry,this._computeCache,this._maps,this._mapLayerIds),this.plotAdapter=St(e,this._mapRegistry,this._plotRegistry,this._plotMapLinks,r,this._mapLayerIds),this.computeAdapter=Nt(this._computeCache)}get workspaceCrs(){return M.DEFAULT_WORKSPACE_COORDINATE_FORMAT}get data(){return this._data}get maps(){return this._maps}mapLayer(e){const r=this._mapRegistry.get(e);return r?{map:r,layerId:this._mapLayerIds.get(e)??e}:void 0}async run(e){if(!this.dataAdapter)throw new Error("Database adapter not initialized. Please call the constructor first.");if(!this.mapAdapter)throw new Error("Map engine not initialized. Please call the constructor first.");if(!this.plotAdapter)throw new Error("Plot adapter not initialized. Please call the constructor first.");if(!this.computeAdapter)throw new Error("Compute adapter not initialized. Please call the constructor first.");this._mapRegistry.clear(),this._mapLayerIds.clear(),this._maps.length=0,this._plotRegistry.clear(),this._plotMapLinks.clear(),this._computeCache.clear(),this.grammarEngine=x({spec:e,adapters:{db:this.dataAdapter,map:this.mapAdapter,plot:this.plotAdapter,compute:this.computeAdapter}}),await this.grammarEngine.run(),this._rewireInteractions();const r=this.grammarEngine.context;if(!r){console.warn("Grammar engine produced no data context."),this._data={};return}const o={};for(const i of r.getLayersMetadata())Object.defineProperty(o,i.name,{get:()=>{const n=this._computeCache.get(i.name);return n?Promise.resolve(n):r.getLayer(i.name)},enumerable:!0,configurable:!0});this._data=o}highlightOnMap(e,r){const o=this.mapLayer(e);o?.map.setHighlightedIds(o.layerId,r);for(const[i,n]of this._plotMapLinks)n===e&&this._plotRegistry.get(i)?.setSelection(r)}clearHighlightOnMap(e){const r=this.mapLayer(e);r?.map.clearHighlightedIds(r.layerId);for(const[o,i]of this._plotMapLinks)i===e&&this._plotRegistry.get(o)?.setSelection([])}clearHighlightOnPlot(e){this._plotRegistry.get(e)?.setSelection([]);const r=this._plotMapLinks.get(e),o=r?this.mapLayer(r):void 0;o?.map.clearHighlightedIds(o.layerId)}setPlotSelection(e,r){this._plotRegistry.get(e)?.setSelection(r);const o=this._plotMapLinks.get(e),i=o?this.mapLayer(o):void 0;i?.map.setHighlightedIds(i.layerId,r)}_rewireInteractions(){for(const r of this._fwdCleanups)r();this._fwdCleanups=[];const e=new Set;for(const[r,o]of this._mapRegistry){if(e.has(o))continue;e.add(o);const i=({selection:n})=>{this.interactions.emit("map:picking",{layerId:r,selection:n})};o.events.on(L.MapEvent.PICKING,i),this._fwdCleanups.push(()=>o.events.off(L.MapEvent.PICKING,i))}for(const[r,o]of this._plotRegistry)for(const i of[C.PlotEvent.CLICK,C.PlotEvent.BRUSH,C.PlotEvent.BRUSH_X,C.PlotEvent.BRUSH_Y]){const n=({selection:l})=>{this.interactions.emit("plot:selection",{plotId:r,event:i,selection:l})};o.events.on(i,n),this._fwdCleanups.push(()=>o.events.off(i,n))}}}m.AutkGrammar=Pt,m.ColorMapInterpolator=U,m.GrammarEventEmitter=tt,m.NormalizationMode=T,m.STORAGE_BUFFER_BINDING_SIZE=B,m.buildBatchedUniforms=K,m.computeLayerNames=H,m.createEngine=x,m.findIterateSource=O,m.isFromFeature=E,m.joinWgsl=Y,m.maxBatchedFeatures=J,m.resolveComputeParams=$,m.resolveUniformMatrices=G,m.resolveUniforms=D,m.runCompute=z,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
|
|
1
|
+
(function(h,E){typeof exports=="object"&&typeof module<"u"?E(exports,require("@urban-toolkit/autk-db"),require("@urban-toolkit/autk-map"),require("@urban-toolkit/autk-plot"),require("@urban-toolkit/autk-core"),require("@urban-toolkit/autk-compute")):typeof define=="function"&&define.amd?define(["exports","@urban-toolkit/autk-db","@urban-toolkit/autk-map","@urban-toolkit/autk-plot","@urban-toolkit/autk-core","@urban-toolkit/autk-compute"],E):(h=typeof globalThis<"u"?globalThis:h||self,E(h["autk-grammar"]={},h.autkDb,h.autkMap,h.autkPlot,h.autkCore,h.autkCompute))})(this,(function(h,E,F,N,A,J){"use strict";function K(t){const{spec:e,adapters:r}=t;let o;async function n(){let i;if(e.data)for(const l of e.data)i=await r.db.resolveSource(i,l);if(e.compute)for(const l of e.compute)i=await r.compute.resolveCompute(i,l);if(e.map)if(Array.isArray(e.map))for(let l=0;l<e.map.length;l++){let u=e.map[l];await r.map.resolveMap(i,u,l)}else await r.map.resolveMap(i,e.map);if(e.plot)if(Array.isArray(e.plot))for(let l=0;l<e.plot.length;l++)await r.plot.resolvePlot(i,e.plot[l],l);else await r.plot.resolvePlot(i,e.plot);o=i}function a(i){return console.log("Spec to update",i),new Promise(l=>{l()})}function s(){console.log("Function not implemented yet")}return{run:n,updatedSpec:a,destroy:s,get context(){return o}}}function X(t){return t===void 0?[]:Array.isArray(t)?t:[t]}function $t(t){const e=t.layout??{},r=e.type??"vertical";if(r!=="vertical"&&r!=="horizontal"&&r!=="grid")throw new Error(`Layout type must be vertical, horizontal or grid, not ${JSON.stringify(r)}.`);const o=e.gap??0;if(typeof o!="number"||!Number.isFinite(o)||o<0)throw new Error(`Layout gap must be a number of pixels, 0 or more, not ${JSON.stringify(o)}.`);const n=e.columns??2;if(!Number.isInteger(n)||n<1)throw new Error(`Layout columns must be a whole number, 1 or more, not ${JSON.stringify(n)}.`);const a=[...X(t.map).map((l,u)=>({kind:"map",index:u,id:l.id,key:l.id??u})),...X(t.plot).map((l,u)=>({kind:"plot",index:u,id:l.id,key:l.id??l.dataRef}))],s=r==="vertical"?1:r==="horizontal"?Math.max(a.length,1):n,i=a.map(({kind:l,index:u,id:c,key:f},p)=>({kind:l,index:u,...c!==void 0&&{id:c},key:f,row:Math.floor(p/s),column:p%s}));return{type:r,rows:Math.ceil(a.length/s),columns:s,gap:o,panes:i}}var z=(t=>(t.CAT_ACCENT="schemeAccent",t.CAT_DARK2="schemeDark2",t.CAT_CATEGORY10="schemeCategory10",t.CAT_OBSERVABLE10="schemeObservable10",t.CAT_PAIRED="schemePaired",t.CAT_PASTEL1="schemePastel1",t.CAT_PASTEL2="schemePastel2",t.CAT_SET1="schemeSet1",t.CAT_SET2="schemeSet2",t.CAT_SET3="schemeSet3",t.CAT_TABLEAU10="schemeTableau10",t.SEQ_REDS="interpolateReds",t.SEQ_BLUES="interpolateBlues",t.SEQ_GREENS="interpolateGreens",t.SEQ_GREYS="interpolateGreys",t.SEQ_ORANGES="interpolateOranges",t.SEQ_PURPLES="interpolatePurples",t.SEQ_TURBO="interpolateTurbo",t.SEQ_VIRIDIS="interpolateViridis",t.SEQ_INFERNO="interpolateInferno",t.SEQ_MAGMA="interpolateMagma",t.SEQ_PLASMA="interpolatePlasma",t.SEQ_CIVIDIS="interpolateCividis",t.SEQ_WARM="interpolateWarm",t.SEQ_COOL="interpolateCool",t.SEQ_CUBEHELIX_DEFAULT="interpolateCubehelixDefault",t.SEQ_BU_GN="interpolateBuGn",t.SEQ_BU_PU="interpolateBuPu",t.SEQ_GN_BU="interpolateGnBu",t.SEQ_OR_RD="interpolateOrRd",t.SEQ_PU_BU_GN="interpolatePuBuGn",t.SEQ_PU_BU="interpolatePuBu",t.SEQ_PU_RD="interpolatePuRd",t.SEQ_RD_PU="interpolateRdPu",t.SEQ_YL_GN_BU="interpolateYlGnBu",t.SEQ_YL_GN="interpolateYlGn",t.SEQ_YL_OR_BR="interpolateYlOrBr",t.SEQ_YL_OR_RD="interpolateYlOrRd",t.DIV_BR_BG="interpolateBrBG",t.DIV_PR_GN="interpolatePRGn",t.DIV_PI_YG="interpolatePiYG",t.DIV_PU_OR="interpolatePuOr",t.DIV_RED_BLUE="interpolateRdBu",t.DIV_RED_GREY="interpolateRdGy",t.DIV_RED_YELLOW_BLUE="interpolateRdYlBu",t.DIV_RED_YELLOW_GREEN="interpolateRdYlGn",t.DIV_SPECTRAL="interpolateSpectral",t))(z||{}),j=(t=>(t.MIN_MAX="minMax",t.PERCENTILE="percentile",t))(j||{});async function P(t,e){const r=e??E.DEFAULT_WORKSPACE_NAME;t.getCurrentWorkspace()!==r&&await t.setWorkspace(r)}function M(t,e){return t===void 0||t===E.DEFAULT_WORKSPACE_NAME?e:`${t}/${e}`}function Z(t){const e=new Set;for(const o of t)o?.id!=null&&e.add(JSON.stringify(o.id));const r=new Set;return t.map((o,n)=>{if(o?.id!=null)return o.id;let a=`autk-feature-${n}`;for(;e.has(JSON.stringify(a))||r.has(JSON.stringify(a));)a=`${a}-generated`;return r.add(JSON.stringify(a)),a})}function tt(t){const e=new Map;return Z(t).map(r=>{const o=JSON.stringify(r),n=e.get(o)??0;return e.set(o,n+1),n===0?o:`${o} ${n}`})}const et=new WeakMap;function Ft(t){let e=et.get(t);return e||(e=new Map,t.forEach((r,o)=>{const n=e.get(r);n?n.push(o):e.set(r,[o])}),et.set(t,e),e)}function B(t,e,r){const o=Ft(r),n=new Set;for(const a of t){const s=e[a];if(s!==void 0)for(const i of o.get(s)??[])n.add(i)}return[...n]}const Bt={type:"GeometryCollection",geometries:[]};function kt(t){const e=t.features??[],r=Z(e);let o=!1;const n=e.map((s,i)=>s==null||s.id!=null&&s.geometry!=null?s:(o=!0,{...s,id:r[i],geometry:s.geometry??Bt})),a=e.findIndex(s=>s?.geometry!=null);return a>0&&e[0]!=null&&e[0].geometry==null&&([n[0],n[a]]=[n[a],n[0]],o=!0),o?{...t,features:n}:t}function Gt(t){const{queryArea:e}=t;if(e.bbox===void 0)return{geocodeArea:e.geocodeArea,areas:e.areas};const r=l=>new Error(`OSM source "${t.outputTableName}": ${l}`);if(e.geocodeArea!==void 0||e.areas!==void 0)throw r("queryArea takes either bbox or geocodeArea with areas, not both.");const o=e.bbox;if(!Array.isArray(o)||o.length!==4||!o.every(l=>typeof l=="number"&&Number.isFinite(l)))throw r("queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.");const[n,a,s,i]=e.bbox;if(Math.abs(n)>180||Math.abs(s)>180)throw r("queryArea.bbox west and east must be longitudes from -180 to 180.");if(Math.abs(a)>90||Math.abs(i)>90)throw r("queryArea.bbox south and north must be latitudes from -90 to 90.");if(n>=s)throw r(`queryArea.bbox west (${n}) must be less than east (${s}); a box across the antimeridian is not supported.`);if(a>=i)throw r(`queryArea.bbox south (${a}) must be less than north (${i}).`);return{bbox:[n,a,s,i]}}function Dt(t){const{autoLoadLayers:e,...r}=t;return{...r,queryArea:Gt(t),autoLoadLayers:{layers:e?.layers??[]}}}function rt(t){return`${t?`coordinateFormat is set to "${t}"`:"no coordinateFormat was specified, so it defaults to EPSG:4326 (WGS84 per RFC 7946)"}. Verify that coordinateFormat matches the actual CRS of the input data.`}function ot(t){let e=1/0,r=1/0,o=-1/0,n=-1/0;const a=i=>{if(Array.isArray(i)){if(typeof i[0]=="number"){const[l,u]=i;l<e&&(e=l),l>o&&(o=l),u<r&&(r=u),u>n&&(n=u);return}for(const l of i)a(l)}},s=i=>{i&&(i.type==="GeometryCollection"?i.geometries.forEach(s):a(i.coordinates))};for(const i of t.features??[])s(i?.geometry);return e<=o?[e,r,o,n]:void 0}function nt(t,e){function r(o,n){if(!n||!n.db)return;const a=document.getElementById(n.db);if(a){const s=o.getTablesMetadata();a.innerHTML+="<ul>";for(const i of s)a.innerHTML+=`<li>${i.name}: (${i.source}, ${i.type}) </li>`;a.innerHTML+="</ul>",a.innerHTML+=`<p>Number of tables: ${s.length}</p>`}}return{async resolveSource(o,n){let a=o;a||(a=new E.AutkDb,await a.init());const{workspace:s}=n;await P(a,s);let{type:i,workspace:l,...u}=n;switch(i){case"osm":return await a.loadOsm(Dt(u)),r(a,t),a;case"csv":return await a.loadCsv(u),r(a,t),a;case"json":return await a.loadJson(u),r(a,t),a;case"geojson":{const c=u;let f;c.geojsonFileUrl?f=await(await fetch(c.geojsonFileUrl)).json():f=c.geojsonObject,e&&f&&e.set(M(s,c.outputTableName),f);const p=f?(()=>{const m={...c,geojsonObject:kt(f)};return delete m.geojsonFileUrl,m})():c,g=/^EPSG:4326$/i.test(p.coordinateFormat??"EPSG:4326"),d=f&&g?ot(f):void 0;if(d&&(d[1]<-90||d[3]>90))throw new Error(`GeoJSON layer "${p.outputTableName}" has y coordinates outside -90 to 90 (bbox: [${d.join(", ")}]), so they cannot be EPSG:4326 degrees. ${rt(p.coordinateFormat)}`);try{await a.loadGeojson(p)}catch(m){throw new Error(`Failed to load GeoJSON layer "${p.outputTableName}": ${m instanceof Error?m.message:String(m)}`)}try{const m=await a.getBoundingBoxFromLayer(p.outputTableName),y=25e6;if(!isFinite(m.minLon)||!isFinite(m.minLat)||!isFinite(m.maxLon)||!isFinite(m.maxLat)||Math.abs(m.minLon)>y||Math.abs(m.maxLon)>y||Math.abs(m.minLat)>y||Math.abs(m.maxLat)>y)throw new Error(`Geometry bounding box after transform is invalid for layer "${p.outputTableName}" (bbox: [${m.minLon}, ${m.minLat}, ${m.maxLon}, ${m.maxLat}]). ${rt(p.coordinateFormat)} The workspace uses ${E.DEFAULT_WORKSPACE_COORDINATE_FORMAT}; input is expected in EPSG:4326 by default.`)}catch(m){if(m instanceof Error&&m.message.includes("bounding box after transform"))throw m}return r(a,t),a}case"geotiff":return await a.loadGeoTiff(u),r(a,t),a;case"heatmap":{const c=u;if(c.groupBy?.some(f=>f.aggregateFn==="collect"))throw new Error(`Heatmap "${c.outputTableName}": aggregateFn "collect" lists the rows near a cell, and a cell holds one value; use sum, avg, count, min, max or weighted.`);return await a.buildHeatmap({tableJoinName:c.joinDataRef,near:c.near,outputTableName:c.outputTableName,grid:c.grid,...c.groupBy&&{groupBy:c.groupBy}}),r(a,t),a}case"join":{const c=u;if(await a.spatialQuery({tableRootName:c.dataRef,tableJoinName:c.joinDataRef,...c.near&&{near:c.near},...c.groupBy&&{groupBy:c.groupBy}}),e){const f=await a.getLayer(c.dataRef);e.set(M(s,c.dataRef),f)}return r(a,t),a}default:return}}}}function at(t,e,r){if(!t)return r();let o=t.get(e);return o||(o=r(),t.set(e,o)),o}function it(t,e){return t?.id??e}function x(t,e){return e===void 0?!0:typeof e=="number"?t.mapIndex===e:t.mapId===e}function st(t,e,r){const o=t?.get(e)??[];o.includes(r)||t?.set(e,[...o,r])}const lt=6378137,U=.0818191908426215;function jt(t,e){if(t===void 0||typeof t=="number"&&Number.isFinite(t)&&t>0)return;const r=typeof t=="number"?String(t):JSON.stringify(t);throw new Error(`Layer "${e}": pointSize must be a number of meters greater than 0, not ${r}.`)}function xt(t){const e=Math.exp(-t/lt);let r=Math.PI/2-2*Math.atan(e);for(let o=0;o<10;o++){const n=U*Math.sin(r),a=Math.PI/2-2*Math.atan(e*((1-n)/(1+n))**(U/2));if(Math.abs(a-r)<1e-12)return a;r=a}return r}function Ut(t,e){if(/^EPSG:3395$/i.test(t)){const r=xt(e),o=U*Math.sin(r);return Math.sqrt(1-o*o)/Math.cos(r)}return/^EPSG:3857$/i.test(t)?Math.cosh(e/lt):1}function Qt(t,e,r,o){if(t===void 0||e!=="points")return;const n=o();if(n)return t*Ut(r,(n[1]+n[3])/2)}function I(t){return typeof t.title=="string"&&t.title!==""?t.title:t.dataRef}function Yt(t,e){const r=new Set;for(const o of t.layerRefs){const n=I(o);if(r.has(n))throw new Error(`Map ${e} draws two layers with the id "${n}". A layer's id is its title, else its dataRef: give each layer of a map its own title.`);r.add(n)}}const Vt=/^#[0-9a-fA-F]{6}$/;function ut(t,e,r){if(!Vt.test(t))throw new Error(`Layer "${r}": ${e} must be a color written #rrggbb, not "${t}".`);return A.ColorMap.hexToRgb(t)}function Wt(t,e){const r={};return t.color!=null&&(r.color=ut(t.color,"color",e)),t.stroke===!1?r.showBorders=!1:t.stroke!=null&&(r.strokeColor=ut(t.stroke,"stroke",e)),t.width!=null&&(r.polylinesWidth=t.width),r}function Ht(t,e){return t.isColorMap!=null?t.isColorMap:e==="raster"?t.colorMapInterpolator!=null||t.colorMapRange!=null||t.colorMapCenter!=null||t.colorMapReverse===!0:t.color!=null?!1:t.colorMapInterpolator!=null||t.getFnv!=null}function qt(t,e){const r=t.features?.[0]?.properties?.[e];return r instanceof Float32Array?r:ArrayBuffer.isView(r)&&!(r instanceof DataView)||Array.isArray(r)?Float32Array.from(r,o=>Number.isFinite(Number(o))?Number(o):NaN):null}function Jt(t,e,r,o,n){if(A.ColorMap.isCategorical(e.interpolator))return;if(n!=null){const u=r!=null?[n[0],r,n[1]]:[n[0],n[1]];return o===!0?u.reverse():u}if(!t)return;let a=0,s=0;for(let u=0;u<t.length;u++){const c=t[u];Number.isFinite(c)&&(s++,r!=null&&(a=Math.max(a,Math.abs(c-r))))}const i=r!=null&&a>0;if(s===0||!i&&o!==!0)return;const l=i&&r!=null?[r-a,r,r+a]:A.ColorMap.resolveDomainFromData(t,e);return o===!0?[...l].reverse():l}function Kt(t,e){if(!(e==null||A.ColorMap.isCategorical(t.interpolator)))return[e[0],e[1]]}function Xt(t){const e=t.colorMapRange;if(e===void 0)return;const r=s=>new Error(`Layer "${I(t)}": ${s}`);if(!Array.isArray(e)||e.length!==2||!e.every(s=>typeof s=="number"&&Number.isFinite(s)))throw r("colorMapRange must hold two numbers, [low, high].");const[o,n]=e;if(o>=n)throw r(`colorMapRange low (${o}) must be less than high (${n}).`);if(t.colorMapDomain!==void 0)throw r("set colorMapRange or colorMapDomain, not both.");const a=t.colorMapCenter;if(a!=null&&(a<o||a>n))throw r(`colorMapCenter (${a}) must lie within colorMapRange [${o}, ${n}].`)}function zt(t,e){return e&&e.length>0?{type:A.ColorMapDomainStrategy.USER,params:e}:t?.mode===j.PERCENTILE?t.lowerPercentile!==void 0||t.upperPercentile!==void 0?{type:A.ColorMapDomainStrategy.PERCENTILE,params:[t.lowerPercentile??0,t.upperPercentile??100]}:{type:A.ColorMapDomainStrategy.PERCENTILE}:{type:A.ColorMapDomainStrategy.MIN_MAX}}function Zt(t,e){return e.split(".").reduce((r,o)=>{if(!(r==null||typeof r!="object"))return r[o]},t)}function te(t,e,r){const o=e.split("."),n={...t};let a=n;for(let s=0;s<o.length-1;s++)a[o[s]]={...a[o[s]]??{}},a=a[o[s]];return a[o[o.length-1]]=r,n}function ee(t,e){const o=t.features?.[0]?.properties?.bands??[];return o.find(a=>a.id===e||a.label===e?.replace(/\./g,"_"))?.id??o[0]?.id??e??""}function ct(t,e){if(e.zoom===void 0&&!e.pitch&&!e.bearing)return;const r=t.camera,[o,n]=r.getLookAt(),a=e.zoom!==void 0?1e4/Math.pow(2,e.zoom-10):Math.abs(r.getEye()[2]),s=(e.pitch??0)*Math.PI/180,i=(e.bearing??0)*Math.PI/180,l=[o-a*Math.sin(s)*Math.sin(i),n-a*Math.sin(s)*Math.cos(i),a*Math.cos(s)];r.resetCamera([Math.sin(i),Math.cos(i),0],[o,n,0],l)}function re(t,e,r,o){const a=t.layerManager.searchByLayerId(e)?.components;return Array.isArray(a)?a.map((s,i)=>{const l=Number.isInteger(s?.featureIndex)?s.featureIndex:i;return r[o[l]]??""}):o.map(s=>r[s]??"")}function oe(t,e,r,o,n,a){async function s(i,l,u){let c={};for(const p of l.getTablesMetadata())p.type!==void 0&&(c[p.name]=p.type);const f=[];for(const p of u.layerRefs){const g=p.dataRef,d=I(p),m=M(u.workspace,g),y=n?.get(m)??c[g],w=p.getFnv,R=r?.get(m)??(y==="raster"?await l.getRaster(g):await at(a,m,()=>l.getLayer(g))),_=R.features??[],St=y==="raster"?[]:_.flatMap((b,S)=>b?.geometry!=null?[S]:[]),C=y==="raster"?R:{...R,features:St.map(b=>_[b])},vt=y==="raster"?ee(C,w):"";y==="raster"?i.loadCollection(d,{collection:C,type:"raster",property:vt}):i.loadCollection(d,{collection:C,type:y}),p.opacity!=null&&i.updateRenderInfo(d,{opacity:p.opacity});const Ct=Wt(p,d);Object.keys(Ct).length>0&&i.updateRenderInfo(d,Ct);const me=l.getWorkspaceConfiguration().coordinateFormat,It=Qt(p.pointSize,y,me,()=>ot(C));It!==void 0&&i.updateRenderInfo(d,{pointSize:It}),Ht(p,y)&&i.updateRenderInfo(d,{isColorMap:!0}),p.isPick&&i.updateRenderInfo(d,{isPick:!0}),p.isSkip&&i.updateRenderInfo(d,{isSkip:!0});const{catchAllCategory:G,colorMapDomain:$}=p;let Pt=C,Lt=$;if(w&&G&&$?.length){const b=new Set($);Pt={...C,features:C.features.map(S=>{const Ot=S.properties,q=Zt(Ot,w);return q==null||!b.has(String(q))?{...S,properties:te(Ot,w,G)}:S})},Lt=b.has(G)?$:[...$,G]}const Nt=y==="raster"&&p.transferFunction!=null;Nt&&i.layerManager.searchByLayerId(d)?.setTransferFunction?.(p.transferFunction);const D=p.colorMapRange,Tt=y==="raster"&&(D!=null||p.colorMapCenter!=null||p.colorMapReverse===!0);if(p.colorMapInterpolator||Tt||D){const b={interpolator:p.colorMapInterpolator??i.layerManager.searchByLayerId(d)?.layerRenderInfo.colormap.config.interpolator??A.ColorMapInterpolator.SEQ_REDS,domainSpec:zt(p.normalization,Lt)};let S;Tt?S=Jt(qt(C,vt),b,p.colorMapCenter,p.colorMapReverse,D):y!=="raster"&&(S=Kt(b,D)),S&&(b.domainSpec={type:A.ColorMapDomainStrategy.USER,params:S}),i.updateColorMap(d,{colorMap:b})}else Nt&&i.updateColorMap(d,{colorMap:{}});if(w&&y!=="raster"){const b=w.startsWith("properties.")?w:`properties.${w}`;i.updateThematic(d,{collection:Pt,property:b})}f.push(y==="raster"?[]:re(i,d,tt(_),St))}return f}return{async resolveMap(i,l,u=0){if(t&&t.map&&i){Yt(l,u);for(const d of l.layerRefs)Xt(d),jt(d.pointSize,I(d));let c;if(Array.isArray(t.map)?c=document.getElementById(t.map[u]):c=document.getElementById(t.map),!c)throw new Error("Could not find rendering target for map: "+t.map);if(!(c instanceof HTMLCanvasElement))throw new Error("Target for map is not a canvas: "+t.map);const f=new F.AutkMap(c);let p;try{l.style&&f.style.setPredefinedStyle(l.style),await f.init(),await P(i,l.workspace),p=await s(f,i,l)}catch(d){try{f.destroy()}catch{}throw d}const g=it(l,u);l.layerRefs.forEach((d,m)=>e?.push({map:f,mapIndex:u,mapId:g,layerId:I(d),dataRef:d.dataRef,rows:p[m]})),o&&(o[u]=f),l.camera&&ct(f,l.camera),f.draw()}}}}function ne(t){return{scatter:"scatterplot",bar:"barchart",line:"linechart",linechart:"linechart","parallel-coordinates":"parallel-coordinates",table:"table",heatmatrix:"heatmatrix"}[t]}function T(t){return t.id??t.dataRef}function ft(t,e,r,o){const{map:n,layerId:a}=o;n.updateRenderInfo(a,{isPick:!0}),n.events.on(F.MapEvent.PICKING,({layerId:s,selection:i})=>{s===a&&t.setSelection(B(i,o.rows,e))});for(const s of r)t.events.on(s,({selection:i})=>{n.setHighlightedIds(a,B(i,e,o.rows))})}async function ae(t,e,r,o){const n=t.getTablesMetadata().find(a=>a.name===e);return n&&!E.isRenderableTable(n)?{type:"FeatureCollection",features:(await t.getTable(e)).map(s=>({type:"Feature",geometry:null,properties:s}))}:at(o,r,()=>t.getLayer(e))}function ie(t,e,r,o,n,a,s,i){return{async resolvePlot(l,u,c=0){if(!t||!t.plot)return;const f=Array.isArray(t.plot)?t.plot[c]:t.plot;if(f===void 0)throw new Error(`Plot ${c} has no target: the plot targets name ${t.plot.length} elements.`);const p=document.getElementById(f);if(!p)throw new Error(`Could not find plot target: ${f}`);const g=l;if(!g)throw new Error("No data context available for plot.");await P(g,u.workspace);const d=M(u.workspace,u.dataRef),m=a?.get(d)??n?.get(d)??await ae(g,u.dataRef,d,i),y=u.events??[],w=new N.AutkPlot(p,{type:ne(u.mark),collection:m,attributes:{axis:u.axis,...u.color&&{color:u.color}},labels:{axis:u.axis,title:u.title},events:y,...u.width&&{width:u.width},...u.height&&{height:u.height},...u.margins&&{margins:u.margins},...u.transform&&{transform:u.transform}});r?.set(T(u),w);const R=tt(m.features??[]);s?.set(T(u),R);for(const _ of e??[])!u.mapRef||_.dataRef!==u.mapRef||(ft(w,R,y,_),st(o,T(u),_))}}}const Q=134217728,se=4,le=32;function pt(t){return Array.isArray(t)?t.join(`
|
|
2
|
+
`):t}function v(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.fromFeature=="object"&&t.fromFeature!==null}function O(t,e){return t instanceof Map?t.get(e):t[e]}function k(t,e){return e.split(".").reduce((r,o)=>{if(!(r==null||typeof r!="object"))return r[o]},t)}function dt(t){const e=[];for(const r of[t.uniforms,t.uniformMatrices])for(const o of Object.values(r??{}))v(o)&&e.push(o);return e}function mt(t){return[...new Set([t.dataRef,...dt(t).map(e=>e.fromFeature.layer)])]}function Y(t){for(const e of dt(t)){const{iterate:r,layer:o}=e.fromFeature;if(r==="all"||r==="batched")return{mode:r,layer:o}}return null}function ht(t,e,r){const o=t.fromFeature,n=r!==void 0&&o.iterate==="all"?r:o.index??0,a=O(e,o.layer)?.features?.[n];return a?k(a,o.path):void 0}function V(t,e,r){if(!t)return;const o={};for(const[n,a]of Object.entries(t)){if(!v(a)){o[n]=a;continue}const s=Number(ht(a,e,r)??NaN);Number.isFinite(s)?o[n]=s:typeof a.default=="number"&&(o[n]=a.default)}return o}function W(t,e,r){if(!t)return;const o={};for(const[n,a]of Object.entries(t)){if(!v(a)){o[n]=a;continue}const s=ht(a,e,r),i=Array.isArray(s)?s:Array.isArray(a.default)?a.default:void 0;if(!i)continue;const l=a.cols??(Array.isArray(i[0])?i[0].length:0);l>0?o[n]={data:i,cols:l}:console.warn(`[autk-grammar] uniform matrix "${n}" has no column count; entry dropped`)}return o}function ue(t){return t!=null&&!(typeof t=="number"&&!Number.isFinite(t))}function yt(t){return v(t)&&t.fromFeature.iterate==="batched"}function gt(t,e){return Object.values(e??{}).some(yt)?le:Object.values(t??{}).some(yt)?se:0}function wt(t,e,r=Q){const o=gt(t,e);return o>0?Math.floor(r/o):Number.POSITIVE_INFINITY}function bt(t,e,r,o=Q){const n={},a={},s=[];for(const l of[t,e])for(const u of Object.values(l??{}))v(u)&&u.fromFeature.iterate==="batched"&&u.fromFeature.required&&s.push(u.fromFeature.path);if(s.length>0){const l=r.length;r=r.filter(u=>s.every(c=>ue(k(u,c)))),r.length<l&&console.info(`[autk-grammar] batched compute dropped ${l-r.length} feature(s) missing ${s.join(", ")}`)}const i=wt(t,e,o);r.length>i&&(console.warn(`[autk-grammar] batched compute capped at ${i} features (got ${r.length}): its largest packed array takes ${gt(t,e)} B per feature, and a storage buffer binding holds ${o} B`),r=r.slice(0,i));for(const[l,u]of Object.entries(t??{}))if(v(u)&&u.fromFeature.iterate==="batched"){const c=typeof u.default=="number"?u.default:void 0;a[l]=r.map(f=>{const p=Number(k(f,u.fromFeature.path)??c);return Number.isFinite(p)?p:0})}else typeof u=="number"&&(n[l]=u);for(const[l,u]of Object.entries(e??{})){if(!v(u)||u.fromFeature.iterate!=="batched")continue;const c=[];for(const f of r){const p=k(f,u.fromFeature.path);let g=1/0,d=1/0,m=-1/0,y=-1/0;if(Array.isArray(p))for(const w of p){if(!Array.isArray(w)||w.length<2)continue;const R=Number(w[0]),_=Number(w[1]);!Number.isFinite(R)||!Number.isFinite(_)||(g=Math.min(g,R),d=Math.min(d,_),m=Math.max(m,R),y=Math.max(y,_))}Number.isFinite(g)||(g=0,d=0,m=0,y=0),c.push(g,d,m,d,m,y,g,y)}a[l]=c}return n.num_features=r.length,{uniforms:n,uniformArrays:a}}function H(t,e,r){const o=O(e,t.dataRef);if(!o)throw new Error(`compute: table "${t.dataRef}" is not loaded`);const n={collection:o,variableMapping:t.attributes,wgslBody:pt(t.wgslFunction)};t.attributeArrays&&(n.attributeArrays=t.attributeArrays),t.attributeMatrices&&(n.attributeMatrices=t.attributeMatrices),t.uniformArrays&&(n.uniformArrays=t.uniformArrays),t.outputColumnName&&(n.resultField=t.outputColumnName),t.outputColumns&&(n.outputColumns=t.outputColumns);const a=Y(t);if(a?.mode==="batched"){const u=O(e,a.layer)?.features??[],c=bt(t.uniforms,t.uniformMatrices,u),f=V(_t(t.uniforms),e)??{},p=W(_t(t.uniformMatrices),e);return n.uniforms={...f,...c.uniforms},n.uniformArrays={...n.uniformArrays??{},...c.uniformArrays},p&&Object.keys(p).length>0&&(n.uniformMatrices=p),n}const s=a?.mode==="all"?r:void 0,i=V(t.uniforms,e,s),l=W(t.uniformMatrices,e,s);return i&&(n.uniforms=i),l&&(n.uniformMatrices=l),n}function _t(t){if(t)return Object.fromEntries(Object.entries(t).filter(([,e])=>!(v(e)&&e.fromFeature.iterate==="batched")))}function ce(t){return t.outputColumns??(t.outputColumnName?[t.outputColumnName]:[])}async function Et(t,e,r){const o=Y(t);if(o?.mode!=="all")return r(H(t,e));const n=O(e,t.dataRef);if(!n)throw new Error(`compute: table "${t.dataRef}" is not loaded`);const a=ce(t),s=structuredClone(n);for(const l of s.features){const u=l.properties??={},c=u.compute??={};for(const f of a)c[f]=0}const i=O(e,o.layer)?.features?.length??0;for(let l=0;l<i;l++){const u=await r({...H(t,e,l),collection:s});s.features.forEach((c,f)=>{const p=c.properties?.compute,g=u.features[f]?.properties?.compute;if(!(!p||!g))for(const d of a){const m=Number(g[d]);Number.isFinite(m)&&(p[d]+=m)}})}return s}const At=["surface","parks","water","roads","buildings","polygons","polylines"];function fe(t,e,r,o){return o?.get(M(r,e))??t.getTablesMetadata().find(n=>n.name===e)?.type}function Mt(t,e){async function r(s,i,l){return t?.get(M(l,i))??await s.getLayer(i)}function o(s,i,l,u,c){if(!t)return;const f=u.outputTableName??l;t.set(M(u.workspace,f),i);const p=u.layerType??c??fe(s,l,u.workspace,e);u.outputTableName&&p&&e?.set(M(u.workspace,f),p)}async function n(s,i){for(const c of i.layers)if(!At.includes(c.type))throw new Error(`Render pass "${i.outputTableName}": layer "${c.id}" has the type "${c.type}", which a render pass cannot draw. A layer's type is one of ${At.join(", ")}.`);const l=await Promise.all(i.layers.map(async c=>({id:c.id,collection:await r(s,c.dataRef,i.workspace),type:c.type,objectIdProperty:c.objectIdProperty}))),u=await new J.AutkComputeEngine().renderPipeline({layers:l,viewpoints:{collection:await r(s,i.viewpoints.dataRef,i.workspace),strategy:i.viewpoints.strategy,sampling:i.viewpoints.sampling},aggregation:i.aggregation,camera:i.camera,tileSize:i.tileSize});o(s,u,i.viewpoints.dataRef,i,i.viewpoints.strategy?.type==="building-windows"?"points":void 0)}async function a(s,i){const l={};for(const f of mt(i)){const p=t?.get(M(i.workspace,f));if(p)l[f]=p;else if(f===i.dataRef)l[f]=await s.getLayer(f);else try{l[f]=await s.getLayer(f)}catch{l[f]=void 0}}const u=new J.AutkComputeEngine,c=await Et(i,l,f=>u.gpgpuPipeline(f));o(s,c,i.dataRef,i)}return{async resolveCompute(s,i){if(s)return await P(s,i.workspace),i.type==="render"?await n(s,i):await a(s,i),s}}}class Rt{_listeners=new Map;on(e,r){this._listeners.has(e)||this._listeners.set(e,new Set);const o=this._listeners.get(e);return o.add(r),()=>o.delete(r)}emit(e,r){this._listeners.get(e)?.forEach(o=>o(r))}}function L(t){return t===void 0?[]:Array.isArray(t)?t:[t]}function pe(t){const e=new Set;for(const o of[...L(t.map),...L(t.plot)])if(o.id!==void 0){if(o.id==="")throw new Error("A map or plot has an empty id.");if(e.has(o.id))throw new Error(`Two maps or plots have the id "${o.id}"; an id names one view.`);e.add(o.id)}const r=new Map;for(const o of L(t.plot)){const n=T(o),a=r.get(n);if(a)throw new Error(a.id===void 0&&o.id===void 0?`Two plots of the table "${n}" have no id; give each plot an id.`:`A plot's id "${n}" is the dataRef of a plot without an id; give each plot an id.`);r.set(n,o)}}class de{dataAdapter;mapAdapter;plotAdapter;computeAdapter;grammarEngine;_computeCache=new Map;_computeTypes=new Map;_data={};_layers=[];_maps=[];_plotRegistry=new Map;_fwdCleanups=[];_plotLinks=new Map;_plotRows=new Map;_exports=new Map;_geojsonCache=new Map;interactions=new Rt;constructor(e){this.dataAdapter=nt(e,this._geojsonCache),this.mapAdapter=oe(e,this._layers,this._computeCache,this._maps,this._computeTypes,this._exports),this.plotAdapter=ie(e,this._layers,this._plotRegistry,this._plotLinks,this._geojsonCache,this._computeCache,this._plotRows,this._exports),this.computeAdapter=Mt(this._computeCache,this._computeTypes)}get workspaceCrs(){return E.DEFAULT_WORKSPACE_COORDINATE_FORMAT}get data(){return this._data}get maps(){return this._maps}mapLayers(e,r){return this._layersOf(e,r).map(({map:o,layerId:n})=>({map:o,layerId:n}))}mapLayer(e,r){return this.mapLayers(e,r).pop()}_layersOf(e,r){return this._layers.filter(o=>o.dataRef===e&&x(o,r))}destroy(){for(const e of this._fwdCleanups)e();this._fwdCleanups=[];for(const e of this._maps)e.destroy();this._maps.length=0,this._layers.length=0,this._plotRegistry.clear(),this._plotLinks.clear(),this._plotRows.clear(),this._exports.clear(),this._geojsonCache.clear(),this._computeCache.clear(),this._computeTypes.clear(),this.grammarEngine=void 0,this._data={}}async run(e){if(!this.dataAdapter)throw new Error("Database adapter not initialized. Please call the constructor first.");if(!this.mapAdapter)throw new Error("Map engine not initialized. Please call the constructor first.");if(!this.plotAdapter)throw new Error("Plot adapter not initialized. Please call the constructor first.");if(!this.computeAdapter)throw new Error("Compute adapter not initialized. Please call the constructor first.");pe(e),this.destroy(),this.grammarEngine=K({spec:e,adapters:{db:this.dataAdapter,map:this.mapAdapter,plot:this.plotAdapter,compute:this.computeAdapter}}),await this.grammarEngine.run();const r=this.grammarEngine.context;if(r&&await P(r),this._wireLinks(e),this._rewireInteractions(e),!r){console.warn("Grammar engine produced no data context."),this._data={};return}const o={};for(const n of r.getLayersMetadata())Object.defineProperty(o,n.name,{get:()=>{const a=this._computeCache.get(n.name);return a?Promise.resolve(a):r.getLayer(n.name)},enumerable:!0,configurable:!0});for(const n of this._computeCache.keys())n in o||Object.defineProperty(o,n,{get:()=>Promise.resolve(this._computeCache.get(n)),enumerable:!0,configurable:!0});this._data=o}highlightOnMap(e,r,o){const n=this._layersOf(e,o);for(const{map:a,layerId:s}of n)a.setHighlightedIds(s,r);this._selectInLinkedPlots(n,r)}clearHighlightOnMap(e,r){const o=this._layersOf(e,r);for(const{map:n,layerId:a}of o)n.clearHighlightedIds(a);this._selectInLinkedPlots(o,[])}clearHighlightOnPlot(e,r){this._plotRegistry.get(e)?.setSelection([]);for(const o of this._plotLinks.get(e)??[])x(o,r)&&o.map.clearHighlightedIds(o.layerId)}setPlotSelection(e,r,o){this._plotRegistry.get(e)?.setSelection(r);const n=this._plotRows.get(e)??[];for(const a of this._plotLinks.get(e)??[])x(a,o)&&a.map.setHighlightedIds(a.layerId,B(r,n,a.rows))}_selectInLinkedPlots(e,r){for(const[o,n]of this._plotLinks){const a=n.filter(l=>e.includes(l));if(a.length===0)continue;const s=this._plotRows.get(o)??[],i=new Set(a.flatMap(l=>B(r,l.rows,s)));this._plotRegistry.get(o)?.setSelection([...i])}}_wireLinks(e){const r=L(e.map),o=L(e.plot);for(const n of e.links??[]){const a=o.find(f=>T(f)===n.source),s=this._plotRegistry.get(n.source);if(!a||!s)throw new Error(`Link source "${n.source}" is not the id (or the dataRef) of a plot of this specification.`);const i=r.findIndex(f=>f.id===n.target),l=this._maps[i];if(i<0||!l)throw new Error(`Link target "${n.target}" is not the id of a map of this specification.`);const u=r[i].layerRefs.find(f=>n.layer!==void 0?I(f)===n.layer:f.dataRef===a.dataRef);if(!u)throw new Error(n.layer!==void 0?`Link from "${n.source}": map "${n.target}" has no layer "${n.layer}".`:`Link from "${n.source}": map "${n.target}" draws no layer of the table "${a.dataRef}"; name the layer.`);const c=this._layers.find(f=>f.mapIndex===i&&f.layerId===I(u));c&&(ft(s,this._plotRows.get(n.source)??[],a.events??[],c),st(this._plotLinks,n.source,c))}}_rewireInteractions(e){for(const o of this._fwdCleanups)o();this._fwdCleanups=[];const r=L(e.map);this._maps.forEach((o,n)=>{const a=it(r[n],n),s=({layerId:i,selection:l})=>{this.interactions.emit("map:picking",{mapId:a,layerId:i,selection:l})};o.events.on(F.MapEvent.PICKING,s),this._fwdCleanups.push(()=>o.events.off(F.MapEvent.PICKING,s))});for(const[o,n]of this._plotRegistry)for(const a of[N.PlotEvent.CLICK,N.PlotEvent.BRUSH,N.PlotEvent.BRUSH_X,N.PlotEvent.BRUSH_Y]){const s=({selection:i})=>{this.interactions.emit("plot:selection",{plotId:o,event:a,selection:i})};n.events.on(a,s),this._fwdCleanups.push(()=>n.events.off(a,s))}}}h.AutkGrammar=de,h.ColorMapInterpolator=z,h.GrammarEventEmitter=Rt,h.NormalizationMode=j,h.STORAGE_BUFFER_BINDING_SIZE=Q,h.applyCamera=ct,h.arrangeViews=$t,h.buildBatchedUniforms=bt,h.computeLayerNames=mt,h.createComputeAdapter=Mt,h.createDataAdapter=nt,h.createEngine=K,h.enterWorkspace=P,h.findIterateSource=Y,h.isFromFeature=v,h.joinWgsl=pt,h.maxBatchedFeatures=wt,h.resolveComputeParams=H,h.resolveUniformMatrices=W,h.resolveUniforms=V,h.runCompute=Et,h.tableKey=M,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})}));
|
|
3
3
|
//# sourceMappingURL=autk-grammar.umd.cjs.map
|