UNPKG

@arcgis/core

Version:

ArcGIS Maps SDK for JavaScript: A complete 2D and 3D mapping and data visualization API

6 lines (5 loc) 10.4 kB
/* All material copyright ESRI, All Rights Reserved, unless otherwise specified. See https://js.arcgis.com/4.33/esri/copyright.txt for details. */ import e from"../../../../request.js";import{createTask as t}from"../../../../core/asyncUtils.js";import s from"../../../../core/Error.js";import i from"../../../../core/Logger.js";import{isAbortError as r}from"../../../../core/promiseUtils.js";import{getJsonType as n}from"../../../../geometry/support/jsonUtils.js";import{wgs84 as a,equals as o}from"../../../../geometry/support/spatialReferenceUtils.js";import{convertFromGeometry as u,convertToGeometry as l,convertFromFeatures as d,convertToFeature as p,convertFromFeature as c}from"../../featureConversionUtils.js";import{executeQueryForSnapping as y}from"../../data/executeQueryForSnapping.js";import m from"../../data/FeatureStore.js";import{checkProjectionSupport as h,project as f}from"../../data/projectionSupport.js";import{QueryEngine as g}from"../../data/QueryEngine.js";import{inferLayerProperties as _,createOptimizedFeatures as j,validateGeoJSON as I}from"./geojson.js";import{createDefaultTemplate as F,createDefaultAttributesFunction as E,createDrawingInfo as b}from"../support/clientSideDefaults.js";import{queryBinsCapabilities as T,loadGeometryEngineForSimplify as w,mixAttributes as q,createFeatureEditSuccessResult as x,createFeatureEditErrorResult as S,simplify as R}from"../support/sourceUtils.js";import C from"../../../support/FieldsIndex.js";import{kebabDict as O}from"../../../support/fieldType.js";import{getFieldDefaultValue as k,getFieldDefaultLength as Q}from"../../../support/fieldUtils.js";import{utc as D}from"../../../../time/constants.js";const A={hasAttachments:!1,capabilities:"query, editing, create, delete, update",useStandardizedQueries:!0,supportsCoordinatesQuantization:!0,supportsReturningQueryGeometry:!0,advancedQueryCapabilities:{supportsQueryAttachments:!1,supportsQueryAttachmentOrderByFields:!1,supportsQueryBins:!0,supportsQueryWithCacheHint:!0,supportsQueryWithDistance:!0,supportsQueryWithResultType:!0,supportsStatistics:!0,supportsPercentileStatistics:!0,supportsReturningGeometryCentroid:!0,supportsDistinct:!0,supportsReturningQueryExtent:!0,supportsReturningGeometryProperties:!1,supportsHavingClause:!0,supportsOrderBy:!0,supportsPagination:!0,supportsSqlExpression:!0,supportsDisjointSpatialRel:!0},queryBinsCapabilities:T};class v{constructor(){this._queryEngine=null,this._snapshotFeatures=async e=>{const t=await this._fetch(e);return this._createFeatures(t)}}destroy(){this._queryEngine?.destroy(),this._queryEngine=this._createDefaultAttributes=null}async load(e,t={}){this._loadOptions={url:e.url,customParameters:e.customParameters};const i=[],[r]=await Promise.all([e.url?this._fetch(t?.signal):null,this._checkProjection(e.spatialReference)]),n=_(r,{geometryType:e.geometryType}),o=e.fields||n.fields||[],u=null!=e.hasZ?e.hasZ:n.hasZ,l=n.geometryType;let d=e.objectIdField||n.objectIdFieldName||"__OBJECTID";const p=e.spatialReference||a;let c=e.timeInfo;o===n.fields&&n.unknownFields.length>0&&i.push({name:"geojson-layer:unknown-field-types",message:"Some fields types couldn't be inferred from the features and were dropped",details:{unknownFields:n.unknownFields}});const y=new C(o);let h=y.get(d);h?("esriFieldTypeString"!==h.type&&(h.type="esriFieldTypeOID"),h.editable=!1,h.nullable=!1,d=h.name):(h={alias:d,name:d,type:"string"===n.objectIdFieldType?"esriFieldTypeString":"esriFieldTypeOID",editable:!1,nullable:!1},o.unshift(h));const f={};for(const a of o){if(null==a.name&&(a.name=a.alias),null==a.alias&&(a.alias=a.name),!a.name)throw new s("geojson-layer:invalid-field-name","field name is missing",{field:a});if(!O.jsonValues.includes(a.type))throw new s("geojson-layer:invalid-field-type",`invalid type for field "${a.name}"`,{field:a});if(a.name!==h.name){const e=k(a);void 0!==e&&(f[a.name]=e)}null==a.length&&(a.length=Q(a))}if(c){if(c.startTimeField){const e=y.get(c.startTimeField);e?(c.startTimeField=e.name,e.type="esriFieldTypeDate"):c.startTimeField=null}if(c.endTimeField){const e=y.get(c.endTimeField);e?(c.endTimeField=e.name,e.type="esriFieldTypeDate"):c.endTimeField=null}if(c.trackIdField){const e=y.get(c.trackIdField);e?c.trackIdField=e.name:(c.trackIdField=null,i.push({name:"geojson-layer:invalid-timeInfo-trackIdField",message:"trackIdField is missing",details:{timeInfo:c}}))}c.startTimeField||c.endTimeField||(i.push({name:"geojson-layer:invalid-timeInfo",message:"startTimeField and endTimeField are missing",details:{timeInfo:c}}),c=null)}const j=l?b(l):void 0,I=y.dateFields.length?{timeZoneIANA:D}:null,T={warnings:i,featureErrors:[],layerDefinition:{...A,drawingInfo:j??void 0,templates:F(f),extent:void 0,geometryType:l,objectIdField:d,fields:o,hasZ:!!u,timeInfo:c,dateFieldsTimeReference:I}},w={type:"object-id",fieldName:d};this._queryEngine=new g({fieldsIndex:C.fromLayerJSON({fields:o,timeInfo:c,dateFieldsTimeReference:I}),geometryType:l,hasM:!1,hasZ:u,featureIdInfo:w,spatialReference:p,timeInfo:c,featureStore:new m({geometryType:l,hasM:!1,hasZ:u})});const q=this._queryEngine.fieldsIndex.requiredFields.indexOf(h);q>-1&&this._queryEngine.fieldsIndex.requiredFields.splice(q,1),this._createDefaultAttributes=E(f,d);const x=await this._createFeatures(r);this._objectIdGenerator=this._createObjectIdGenerator(this._queryEngine,x);const S=this._normalizeFeatures(x,T.featureErrors);this._queryEngine.featureStore.addMany(S);const{fullExtent:R,timeExtent:v}=await this._queryEngine.fetchRecomputedExtents();if(T.layerDefinition.extent=R,v){const{start:e,end:t}=v;T.layerDefinition.timeInfo.timeExtent=[e,t]}return T}async applyEdits(e){const{spatialReference:t,geometryType:s}=this._queryEngine;return await Promise.all([w(t,s),h(e.adds,t),h(e.updates,t)]),await this._waitSnapshotComplete(),this._applyEdits(e)}async queryFeatures(e={},t={}){return await this._waitSnapshotComplete(),this._queryEngine.executeQuery(e,t.signal)}async queryFeatureCount(e={},t={}){return await this._waitSnapshotComplete(),this._queryEngine.executeQueryForCount(e,t.signal)}async queryObjectIds(e={},t={}){return await this._waitSnapshotComplete(),this._queryEngine.executeQueryForIds(e,t.signal)}async queryExtent(e={},t={}){return await this._waitSnapshotComplete(),this._queryEngine.executeQueryForExtent(e,t.signal)}async querySnapping(e,t={}){return await this._waitSnapshotComplete(),y(this._queryEngine,e,t.signal)}async queryAttributeBins(e,t={}){return await this._waitSnapshotComplete(),this._queryEngine.executeAttributeBinsQuery(e,t.signal)}async refresh(e){this._loadOptions.customParameters=e,this._snapshotTask?.abort(),this._snapshotTask=t(this._snapshotFeatures),this._snapshotTask.promise.then((e=>{this._queryEngine.featureStore.clear(),this._objectIdGenerator=this._createObjectIdGenerator(this._queryEngine,e);const t=this._normalizeFeatures(e);t&&this._queryEngine.featureStore.addMany(t)}),(e=>{this._queryEngine.featureStore.clear(),r(e)||i.getLogger("esri.layers.GeoJSONLayer").error(new s("geojson-layer:refresh","An error occurred during refresh",{error:e}))})),await this._waitSnapshotComplete();const{fullExtent:n,timeExtent:a}=await this._queryEngine.fetchRecomputedExtents();return{extent:n,timeExtent:a}}async _createFeatures(e){if(null==e)return[];const{geometryType:t,hasZ:s,objectIdField:i}=this._queryEngine,r=j(e,{geometryType:t,hasZ:s,objectIdField:i});if(!o(this._queryEngine.spatialReference,a))for(const n of r)null!=n.geometry&&(n.geometry=u(f(l(n.geometry,this._queryEngine.geometryType,this._queryEngine.hasZ,!1),a,this._queryEngine.spatialReference)));return r}async _waitSnapshotComplete(){if(this._snapshotTask&&!this._snapshotTask.finished){try{await this._snapshotTask.promise}catch{}return this._waitSnapshotComplete()}}async _fetch(t){const{url:s,customParameters:i}=this._loadOptions,r=(await e(s??"",{responseType:"json",query:{...i},signal:t})).data;return I(r),r}_normalizeFeatures(e,t){const{objectIdField:s,fieldsIndex:i}=this._queryEngine,r=[];for(const n of e){const e=this._createDefaultAttributes(),a=q(i,e,n.attributes,!0);a?t?.push(a):(this._assignObjectId(e,n.attributes,!0),n.attributes=e,n.objectId=e[s],r.push(n))}return r}async _applyEdits(e){const{adds:t,updates:s,deletes:i}=e,r={addResults:[],deleteResults:[],updateResults:[],uidToObjectId:{}};if(t?.length&&this._applyAddEdits(r,t),s?.length&&this._applyUpdateEdits(r,s),i?.length){for(const e of i)r.deleteResults.push(x(e));this._queryEngine.featureStore.removeManyById(i)}const{fullExtent:n,timeExtent:a}=await this._queryEngine.fetchRecomputedExtents();return{extent:n,timeExtent:a,featureEditResults:r}}_applyAddEdits(e,t){const{addResults:s}=e,{geometryType:i,hasM:r,hasZ:a,objectIdField:o,spatialReference:u,featureStore:l,fieldsIndex:p}=this._queryEngine,c=[],y={type:"object-id",fieldName:o};for(const d of t){if(d.geometry&&i!==n(d.geometry)){s.push(S("Incorrect geometry type."));continue}const t=this._createDefaultAttributes(),r=q(p,t,d.attributes);if(r)s.push(r);else{if(this._assignObjectId(t,d.attributes),d.attributes=t,null!=d.uid){const t=d.attributes[o];e.uidToObjectId[d.uid]=t}if(null!=d.geometry){const e=d.geometry.spatialReference??u;d.geometry=f(R(d.geometry,e),e,u)}c.push(d),s.push(x(d.attributes[o]))}}l.addMany(d([],c,i,a,r,y))}_applyUpdateEdits({updateResults:e},t){const{geometryType:s,hasM:i,hasZ:r,objectIdField:a,spatialReference:o,featureStore:u,fieldsIndex:l}=this._queryEngine,d={type:"object-id",fieldName:a};for(const y of t){const{attributes:t,geometry:m}=y,h=t?.[a];if(null==h){e.push(S(`Identifier field ${a} missing`));continue}if(!u.has(h)){e.push(S(`Feature with object id ${h} missing`));continue}const g=p(u.getFeature(h),s,r,i);if(null!=m){if(s!==n(m)){e.push(S("Incorrect geometry type."));continue}const t=m.spatialReference??o;g.geometry=f(R(m,t),t,o)}if(t){const s=q(l,g.attributes,t);if(s){e.push(s);continue}}u.add(c(g,s,r,i,d)),e.push(x(h))}}_createObjectIdGenerator(e,t){const s=e.fieldsIndex.get(e.objectIdField);if("esriFieldTypeString"===s.type)return()=>s.name+"-"+Date.now().toString(16);let i=Number.NEGATIVE_INFINITY;for(const r of t)r.objectId&&(i=Math.max(i,r.objectId));return i=Math.max(0,i)+1,()=>i++}_assignObjectId(e,t,s=!1){const i=this._queryEngine.objectIdField;e[i]=s&&i in t?t[i]:this._objectIdGenerator()}async _checkProjection(e){try{await h(a,e)}catch{throw new s("geojson-layer","Projection not supported")}}}export{v as default};