@arcgis/core 4.34.0-next.90 → 4.34.0-next.92
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/assets/esri/core/workers/RemoteClient.js +1 -1
- package/config.js +1 -1
- package/graphic/graphicOriginUtils.js +1 -1
- package/interfaces.d.ts +140 -21
- package/kernel.js +1 -1
- package/package.json +1 -1
- package/support/revision.js +1 -1
- package/widgets/Editor/EditorViewModel.js +1 -1
- package/widgets/Editor/SplitFeatureWorkflow.d.ts +4 -0
- package/widgets/Editor/SplitFeatureWorkflow.js +1 -1
- package/widgets/Editor/SplitFeatureWorkflowData.d.ts +4 -0
- package/widgets/Editor/UpdateRecordWorkflowData.js +1 -1
- package/widgets/Editor/UpdateWorkflow.js +1 -1
- package/widgets/Editor/UpdateWorkflowData.js +1 -1
- package/widgets/Editor/support/EditorItem.js +1 -1
- package/widgets/Editor/workflowUtils.js +1 -1
- package/widgets/Search/SearchViewModel.js +1 -1
- package/widgets/support/decorators/vmEvent.js +1 -1
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
|
|
3
3
|
See https://js.arcgis.com/4.34/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
import{__decorate as e}from"tslib";import t from"../../Graphic.js";import i from"../../core/Error.js";import{makeHandle as a}from"../../core/handleUtils.js";import o from"../../core/Logger.js";import{abortMaybe as r}from"../../core/maybe.js";import{debounce as s,createResolver as n,onAbort as l,createAbortError as d,throwIfAborted as c}from"../../core/promiseUtils.js";import p from"../../core/Queue.js";import{whenOnce as u,watch as w,sync as h,when as f}from"../../core/reactiveUtils.js";import{last as g}from"../../core/SetUtils.js";import{property as v}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/RandomLCG.js";import{subclass as k}from"../../core/accessorSupport/decorators/subclass.js";import{isEditableLayer as m}from"../../layers/support/editableLayers.js";import{isFeatureLayer as y,isSubtypeSublayer as W,isSubtypeGroupLayer as A,isTable as _}from"../../layers/support/layerUtils.js";import{createFeatureServices as b}from"../../rest/featureService/utils.js";import C from"../../views/draw/support/HighlightHelper.js";import{ViewEventPriorities as F}from"../../views/input/InputManager.js";import{temporaryHighlightName as S}from"../../views/support/HighlightDefaults.js";import M from"./CreateFeaturesWorkflow.js";import I from"./SplitFeatureWorkflow.js";import{UpdateFeatureWorkflow as E}from"./UpdateFeatureWorkflow.js";import{UpdateRecordWorkflow as R}from"./UpdateRecordWorkflow.js";import V from"./UpdateWorkflowData.js";import U from"./Workflow.js";import{findEditorItemForLayer as j,isSplitFeatureWorkflow as P,isUpdateRecordWorkflow as L,isParentWorkflow as x,findEditorItemForLayerOrThrow as T,createWorkflowSteps as H,fetchCandidates as N}from"./workflowUtils.js";import{findUtilityNetwork as O,isGraphicForRelatableFeatureSupportedLayer as D}from"../Feature/support/featureUtils.js";var q;let G=q=class extends U{constructor(e){super(e),this._workflowStack=new p(g),this._sketchStack=new p(g),this.data=void 0,this.type="update"}destroy(){this._drainWorkflowStack(e=>e.cancel({force:!0}))}get activeEditorItem(){return this.activeWorkflow?.data.editorItem??void 0}get activeFeatureFormViewModel(){return this.activeWorkflow?.featureFormViewModel}get activeUtilityNetworkAssociationAddAssociationViewModel(){return"add-association"===this.activeWorkflow?.type?this.activeWorkflow.utilityNetworkAssociationAddAssociationViewModel:null}get activeSketchViewModel(){return this._sketchStack.peek()?.viewModel}get canDeleteAssociation(){const{activeFeatureFormViewModel:e}=this;if(!this.activeWorkflow||!this.data.viewModel.view?.map||!e)return!1;const{activeAssociation:t,feature:i}=e;return!(!t||!i?.sourceLayer||!y(i?.sourceLayer)&&!W(i?.sourceLayer))}get activeWorkflow(){return this._workflowStack.last()}get updating(){return this._updatingHandles.updating||!!this.activeWorkflow?.updating}get hasPreviousStep(){const e=this.activeWorkflow?.featureFormViewModel;return this._stepIndex>0||this.nestedWorkflowCount>1||null!=e?.relationshipId||"view"!==this.data.viewModel.attachmentsViewModel.mode||null!=e?.associationId||null!=e?.associatedLayer}get hasUpdatableCandidates(){const{candidates:e,viewModel:t}=this.data;return e.some(({layer:e})=>j(t.editorItems,e)?.supportsUpdateWorkflow)}get nestedWorkflowCount(){return this._workflowStack.length}get shouldShowAttachments(){return!!this.activeEditorItem?.capabilities.attachments.enabled}get shouldAllowAttachmentEditing(){return!!this.activeEditorItem?.capabilities.update.attachments.enabled}get hasPendingEdits(){return Array.from(this._workflowStack).some(e=>e.hasPendingEdits)}get helpMessage(){return this.activeWorkflow?.helpMessage?this.activeWorkflow.helpMessage:"awaiting-feature-to-update"===this.stepId?"select":void 0}get reliesOnOwnerAdminPrivileges(){return this.activeWorkflow?.reliesOnOwnerAdminPrivileges??!1}get hasInvalidFormTemplate(){return!!this.activeEditorItem?.hasInvalidFormTemplate}async back(e=()=>Promise.resolve(!0)){const{activeWorkflow:t}=this,i=t?.featureFormViewModel;if(i?.activeRelationshipInput){const e=i.activeRelationshipInput;if(e.activeCategory)return void(e.activeCategory=null);if(null!=i.relationshipId)return void(i.relationshipId=null);if(e.showAllEnabled)return void(e.showAllEnabled=!1)}if("add-association"===t?.type){const{activeUtilityNetworkAssociationAddAssociationViewModel:e}=this;if(e?.filterOptionsVisible)return void(e.filterOptionsVisible=!1);e?.featureSpatialItems.length&&e.reset()}if(null==i?.associatedLayer)if(null==i?.associationId)if("create-features"===t?.type&&t.hasPreviousStep)await t.previous({cancelCurrentStep:!0});else if(t){if(t.hasPendingEdits&&!i?.disabled){if(!await e())return}t.hasPreviousStep?await t.previous({cancelCurrentStep:!0}):await this.cancelActiveWorkflow({force:!0})}else this.hasPreviousStep?await this.previous({cancelCurrentStep:!0}):await this.cancel({force:!0});else i.associationId=null;else i.associatedLayer=null}async cancelActiveWorkflow(e){await(this.activeWorkflow?.cancel(e)),await this._popWorkflowAndReconcile()}async commit(){await this._drainWorkflowStack(e=>e.commit()),await super.commit()}static create(e){const{startAt:t,applyEdits:i,applyEditsFeatureService:a,...o}=e,r=new q({data:new V({applyEditsCallback:i,applyEditsFeatureServiceCallback:a,...o}),onCommit:async()=>{}});return r._set("steps",this._createWorkflowSteps(r,t)),r}async save(){const{activeFeatureFormViewModel:e}=this;if(e){if(e.submit(),!e.submittable||e.pendingSubtypeChoice)return;const t=e.getValues();if(e.validateContingencyConstraints(t,{includeIncompleteViolations:!0}).length>0)return}if(this.nestedWorkflowCount<2)return await this.commit();const{activeWorkflow:t}=this;if(await(t?.commit()),!P(t))return void await this._popWorkflowAndReconcile();this._popWorkflow();const i=this._workflowStack.peek();if(i&&i===t?.parent&&(await i.cancel(),this._popWorkflow(),0===this.nestedWorkflowCount))return await this.commit();await this._reconcileWorkflowStack()}async startCreatingRelatedRecord(e){try{const t=this._createNestedCreateFeaturesWorkflow(e);await this._pushWorkflowAndReconcile(t)}catch(t){throw new i("editor:unable-to-start-creating","Could not begin updating the provided feature or table record.",{error:t})}}async startSplittingFeature(e){try{const t=await this._createNestedSplitFeatureWorkflow(e);await this._pushWorkflowAndReconcile(t)}catch(t){throw new i("editor:unable-to-start-splitting","Could not begin splitting the provided feature.",{error:t})}}async startUpdating(e,t,a=!1){try{const i=await this._createNestedUpdateWorkflow(e,a,t);await this._pushWorkflowAndReconcile(i)}catch(o){throw new i("editor:unable-to-start-updating","Could not begin updating the provided feature or table record.",{error:o})}}async startAddAssociation(e,t,a){try{const i=await this._createNestedAddAssociationWorkflow(e,t,a);await this._pushWorkflowAndReconcile(i)}catch(o){throw new i("editor:unable-to-start-updating","Could not begin updating the provided feature or table record.",{error:o})}}async deleteActiveFeature(){const{activeWorkflow:e}=this;if(!e)throw new i("editor:nothing-to-delete","There is no feature to delete");const t=L(e);t?(e.stageDelete(),e.data.edits.feature===this.data.rootFeature&&this._removeRootFeatureFromCandidates()):await e.cancel(),this.nestedWorkflowCount<2?t?await this.commit():await this.cancel({force:!0}):(t&&await e.commit(),await this._popWorkflowAndReconcile(),await this._returnToPageWithContent())}async deleteActiveAssociation(){if(!this.canDeleteAssociation)throw new i("editor:nothing-to-delete","There is no association to delete");await this._deleteActiveAssociation(),await this._popWorkflowAndReconcile(),await this._returnToPageWithContent()}async cancelAll(){await this._drainWorkflowStack(e=>e.cancel({force:!0}))}async _deleteActiveAssociation(){const{activeFeatureFormViewModel:e,data:t}=this,{activeAssociation:a,feature:o}=e,{applyEditsFeatureServiceCallback:r,viewModel:s}=t,{sourceLayer:n}=o,l=W(n)&&n.parent?n.parent:n,d=b([l]),c=d.values().next().value?.featureService;if(!c)throw new i("editor:failed-to-delete-association","Could not retrieve feature service needed to delete association");await(c?.load());const p=s.view.map,u=O(p,l);await(u?.networkSystemLayers.loadAssociationsTable());const w=u?.generateDeleteAssociations([a]);if(!w)throw new i("editor:failed-to-delete-association","Could not create payload needed to delete association");const h=u?.gdbVersion??void 0;await r(c,[w],{gdbVersion:h,globalIdUsed:!0})}_removeRootFeatureFromCandidates(){const{candidates:e,rootFeature:t}=this.data;if(0===e.length||!t)return;const i=e.indexOf(t);i>-1&&e.splice(i,1)}async _returnToPageWithContent(){const{activeFeatureFormViewModel:e}=this;if(!e?.activeAssociationInput)return;const{activeAssociationInput:t,associationId:i}=e;await t.refresh(),t.associatedLayer&&!t.associatedFeatures?.length&&(e.associatedLayer=null),null==i||t.associatedFeatureInfos.size||(e.associationId=null)}_createNestedCreateFeaturesWorkflow(e){const{relatedLayer:t}=e,{addAttachmentsCallback:a,applyEditsCallback:o,applyEditsFeatureServiceCallback:r,sketchOptions:s,snappingManager:n,viewModel:l}=this.data;if(!m(t))throw new i("editor:unsupported-layer","Editing is not supported on the provided layer");const d=this._getCreationInfoForNestedCreateFeaturesWorkflow(e),c=d.template||d.initialFeature?"creating-features":"awaiting-feature-creation-info",p=x(this.activeWorkflow)?this.activeWorkflow:void 0;return M.create({addAttachmentsCallback:a,applyEdits:o,applyEditsFeatureService:r,creationInfo:d,isNested:!0,parent:p,sketchOptions:s,snappingManager:n,startAt:c,viewModel:l})}_getCreationInfoForNestedCreateFeaturesWorkflow(e){const{relatedLayer:a}=e;if(!m(a)||A(a))throw new i("editor:unsupported-layer","Editing is not supported on the provided layer");const{viewModel:o}=this.data,r={layer:a,maxFeatures:1},s=this._makeRelatedRecordAttributes(e),n=o.getTemplatesForLayer(a);return n?.length>0?(r.attributeOverrides=s,1===n.length&&(r.template=n[0])):r.initialFeature=new t({sourceLayer:a,attributes:s}),r}async _createNestedUpdateWorkflow(e,t,i){const a=_(e.sourceLayer)?R:E,{applyEditsCallback:o,applyEditsFeatureServiceCallback:r,sketchOptions:s,snappingManager:n,viewModel:l}=this.data,d=x(this.activeWorkflow)?this.activeWorkflow:void 0,c=await a.create({association:i,feature:e,parent:d,sketchOptions:s,snappingManager:n,viewModel:l,readOnly:t,applyEdits:o,applyEditsFeatureService:r,featureFormCallbacks:{addRelatedRecord:async e=>await this._updatingHandles.addPromise(this.startCreatingRelatedRecord(e)),editRelatedRecord:async({relatedFeature:e,readOnly:t})=>await this._updatingHandles.addPromise(this.startUpdating(e,void 0,t)),selectAssociatedFeature:async({feature:e,association:i})=>await this._updatingHandles.addPromise(this.startUpdating(e,i,t)),addAssociation:async e=>await this._updatingHandles.addPromise(this.startAddAssociation(e.feature,e.utilityNetwork,e.associationType))}});return await u(()=>!c.updating),c}async _createNestedAddAssociationWorkflow(e,t,i){const{AddAssociationWorkflow:a}=await import("./AddAssociationWorkflow.js"),{applyEditsCallback:o,applyEditsFeatureServiceCallback:r,viewModel:s}=this.data,n=x(this.activeWorkflow)?this.activeWorkflow:void 0,l=this.activeFeatureFormViewModel?.activeAssociationInput,d=await a.create({utilityNetwork:t,associationType:i,feature:e,parent:n,viewModel:s,associationInput:l,applyEdits:o,applyEditsFeatureService:r});return await u(()=>!d.updating),d}async _createNestedSplitFeatureWorkflow(e){const{applyEditsCallback:t,applyEditsFeatureServiceCallback:i,viewModel:a}=this.data,o=x(this.activeWorkflow)?this.activeWorkflow:void 0,r=T(a.editorItems,e.sourceLayer),s=I.create({applyEdits:t,applyEditsFeatureService:i,editorItem:r,originalFeature:e,parent:o,viewModel:a});return await u(()=>!s.updating),s}async _drainWorkflowStack(e){const t=this._workflowStack,i=[];for(const a of t){const t=e(a).finally(()=>a.destroy());this._updatingHandles.addPromise(t),i.push(t)}await Promise.all(i),this._workflowStack.clear(),this._sketchStack.clear()}_makeRelatedRecordAttributes(e){const{parentFeature:t,relatedLayer:i,relationshipId:a}=e;if(!D(t))return;const o=i.relationships?.find(e=>e.id===a);if(!o)return void this._logContinuingWithoutRelationshipWarning("relationship-not-found","Could not begin creating a related record because the relationship specified could not be found on the destination layer.");if("origin"===o.role)return void this._logContinuingWithoutRelationshipWarning("unsupported-role","Creating new related records in the 'origin' table of a relationship is not yet supported");const r=t.sourceLayer;o.relatedTableId!==r.layerId&&this._logContinuingWithoutRelationshipWarning("invalid-argument-combination","The given parent feature does not belong to the relationship designated by the given relationship ID.");const s=r.relationships?.find(e=>e.id===a);if(!s)return void this._logContinuingWithoutRelationshipWarning("relationship-not-found","Could not begin creating a related record because the relationship specified could not be found on the origin layer.");const n=z(r,s),l=t.getAttribute(n);l||this._logContinuingWithoutRelationshipWarning("no-key-on-origin-feature","The given parent feature does not have a value for the relationship's origin primary key field.");const d=z(i,o);return{[d]:l}}_popWorkflow(){this._workflowStack.pop()?.destroy(),this._sketchStack.pop()}async _popWorkflowAndReconcile(){this._popWorkflow();const e=await this._reconcileWorkflowStack();if(e.failureCount>0)throw new i("editor:next-workflow-failed","Popped the top workflow, but the next workflow in the stack failed to activate",e)}async _pushWorkflowAndReconcile(e){const t=this._workflowRequiresSketchViewModel(e);this.activeWorkflow?.exit({removeSketchHandles:t});const a=this._sketchStack,o=await(e?.start()),r=a.peek();o?(r?.exit(),a.push(o)):a.push(this._cloneSketchController(r)),this._workflowStack.push(e);const s=await this._reconcileWorkflowStack();if(s.failureCount>0)throw new i("editor:failed-to-start-updating-feature","Failed to enter the provided workflow.",s)}async _reconcileWorkflowStack(){const e=this._workflowStack,t=this._sketchStack;try{const i=e.peek();return await(i?.enter()),await(t.peek()?.enter()),{activeWorkflow:i,failureCount:0}}catch(i){e.pop().destroy(),t.pop();const{activeWorkflow:a,failureCount:o}=await this._reconcileWorkflowStack();return{activeWorkflow:a,failureCount:o+1}}}_cloneSketchController(e){return{enter:e?.enter??(async()=>{}),exit:e?.exit??(async()=>{}),viewModel:e?.viewModel}}_workflowRequiresSketchViewModel(e){const{type:t}=e;return"update-feature"===t||"create-features"===t&&!_(e.data.creationInfo?.layer)}static _createWorkflowSteps(e,t="awaiting-feature-to-update"){const{data:o}=e;return H(["awaiting-feature-to-update","awaiting-update-feature-candidate","editing-existing-feature","adding-attachment","editing-attachment"],t,{"awaiting-feature-to-update":()=>({id:"awaiting-feature-to-update",async setUp(){const{spinnerViewModel:t}=o.viewModel,i=o.viewModel.view;i.activeTool=null;let s=null;e.addHandles(a(()=>{s=r(s)}),this.id),o.rootFeature=null,o.candidates=[];const p=i.on("immediate-click",async a=>{const r=n();e._updatingHandles.addPromise(r.promise);try{t.location=a.mapPoint,t.visible=!0,s?.abort();const{editorItems:r}=o.viewModel;s=new AbortController;const n=await a.defer(()=>new Promise((e,t)=>{l(s?.signal,()=>t(d())),e(N(r,i,a,s?.signal))}));if(c(s),o.candidates=n.filter(e=>"fulfilled"===e.status).flatMap(e=>e.value).filter(e=>!e.isAggregate),t.visible=1===o.candidates.length,0===o.candidates.length)return;a.stopPropagation(),1===o.candidates.length?(o.rootFeature=o.candidates[0],e.go("editing-existing-feature").catch(()=>{}).then(()=>t.visible=!1)):e.next()}finally{r.resolve()}},F.TOOL),u=f(()=>null!=i.activeTool,()=>e.cancel({force:!0}),{once:!0});i.focus(),e.addHandles([p,u],this.id)},async tearDown(){0===o.candidates.length&&(o.viewModel.spinnerViewModel.visible=!1),e.removeHandles(this.id)}}),"awaiting-update-feature-candidate":()=>({id:"awaiting-update-feature-candidate",async setUp(){o.rootFeature=null;const{view:t}=o.viewModel;if(!t)return;const i=new C({view:t,highlightName:S});e.addHandles([w(()=>o.rootFeature,(e,t)=>{i.remove(t),i.add(e)},h),a(()=>i.removeAll())],this.id)},async tearDown(){e.removeHandles(this.id)}}),"editing-existing-feature":()=>({id:"editing-existing-feature",async setUp(){const{data:t}=e,{rootFeature:a}=t;if(!a)throw new i("editor:no-feature-specified","Cannot setup the 'updating-existing-feature' step until the root feature is defined");"split"===t.rootWorkflowType?await e.startSplittingFeature(a):await e.startUpdating(a),t.viewModel.spinnerViewModel.visible=!1;const o=s(async()=>{await u(()=>!e.updating),e.previous()});e.addHandles([w(()=>e.nestedWorkflowCount,(e,t)=>{0===e&&0!==t&&o()},h)],this.id)},async tearDown(){await e.cancelAll(),e.removeHandles(this.id)}}),"adding-attachment":()=>({id:"adding-attachment",parent:"editing-existing-feature",async setUp(){},async tearDown(){o.viewModel.attachmentsViewModel.mode="view"}}),"editing-attachment":()=>({id:"editing-attachment",parent:"editing-existing-feature",async setUp(){},async tearDown(){o.viewModel.attachmentsViewModel.mode="view"}})})}_logContinuingWithoutRelationshipWarning(e,t){o.getLogger(this).warn(`editor:${e}`,t,"The create operation will be allowed to proceed, but the resulting feature may not be related to the given parent feature.")}};function z(e,{keyField:t}){return e.getField(t)?.name??t}e([v()],G.prototype,"activeEditorItem",null),e([v()],G.prototype,"activeFeatureFormViewModel",null),e([v()],G.prototype,"activeUtilityNetworkAssociationAddAssociationViewModel",null),e([v()],G.prototype,"activeSketchViewModel",null),e([v()],G.prototype,"canDeleteAssociation",null),e([v()],G.prototype,"activeWorkflow",null),e([v()],G.prototype,"updating",null),e([v()],G.prototype,"data",void 0),e([v()],G.prototype,"hasPreviousStep",null),e([v()],G.prototype,"hasUpdatableCandidates",null),e([v()],G.prototype,"nestedWorkflowCount",null),e([v()],G.prototype,"shouldShowAttachments",null),e([v()],G.prototype,"shouldAllowAttachmentEditing",null),e([v()],G.prototype,"hasPendingEdits",null),e([v()],G.prototype,"helpMessage",null),e([v()],G.prototype,"reliesOnOwnerAdminPrivileges",null),e([v()],G.prototype,"hasInvalidFormTemplate",null),G=q=e([k("esri.widgets.Editor.UpdateWorkflow")],G);const Q=G;export{Q as default};
|
|
5
|
+
import{__decorate as t}from"tslib";import e from"../../Graphic.js";import i from"../../core/Error.js";import{makeHandle as a}from"../../core/handleUtils.js";import o from"../../core/Logger.js";import{abortMaybe as r}from"../../core/maybe.js";import{debounce as s,createResolver as n,onAbort as l,createAbortError as d,throwIfAborted as c}from"../../core/promiseUtils.js";import p from"../../core/Queue.js";import{whenOnce as u,watch as w,sync as h,when as f}from"../../core/reactiveUtils.js";import{last as g}from"../../core/SetUtils.js";import{property as v}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/RandomLCG.js";import{subclass as k}from"../../core/accessorSupport/decorators/subclass.js";import{isEditableLayer as m}from"../../layers/support/editableLayers.js";import{isFeatureLayer as y,isSubtypeSublayer as W,isSubtypeGroupLayer as A,isTable as _}from"../../layers/support/layerUtils.js";import{createFeatureServices as b}from"../../rest/featureService/utils.js";import C from"../../views/draw/support/HighlightHelper.js";import{ViewEventPriorities as F}from"../../views/input/InputManager.js";import{temporaryHighlightName as S}from"../../views/support/HighlightDefaults.js";import M from"./CreateFeaturesWorkflow.js";import I from"./SplitFeatureWorkflow.js";import{UpdateFeatureWorkflow as E}from"./UpdateFeatureWorkflow.js";import{UpdateRecordWorkflow as R}from"./UpdateRecordWorkflow.js";import V from"./UpdateWorkflowData.js";import U from"./Workflow.js";import{findEditorItemForLayer as j,isSplitFeatureWorkflow as P,isUpdateRecordWorkflow as L,isParentWorkflow as x,findEditorItemForLayerOrThrow as O,createWorkflowSteps as T,fetchCandidates as H}from"./workflowUtils.js";import{findUtilityNetwork as N,isGraphicForRelatableFeatureSupportedLayer as D}from"../Feature/support/featureUtils.js";var q;let G=q=class extends U{constructor(t){super(t),this._workflowStack=new p(g),this._sketchStack=new p(g),this.data=void 0,this.type="update"}destroy(){this._drainWorkflowStack(t=>t.cancel({force:!0}))}get activeEditorItem(){return this.activeWorkflow?.data.editorItem??void 0}get activeFeatureFormViewModel(){return this.activeWorkflow?.featureFormViewModel}get activeUtilityNetworkAssociationAddAssociationViewModel(){return"add-association"===this.activeWorkflow?.type?this.activeWorkflow.utilityNetworkAssociationAddAssociationViewModel:null}get activeSketchViewModel(){return this._sketchStack.peek()?.viewModel}get canDeleteAssociation(){const{activeFeatureFormViewModel:t}=this;if(!this.activeWorkflow||!this.data.viewModel.view?.map||!t)return!1;const{activeAssociation:e,feature:i}=t;return!(!e||!i?.sourceLayer||!y(i?.sourceLayer)&&!W(i?.sourceLayer))}get activeWorkflow(){return this._workflowStack.last()}get updating(){return this._updatingHandles.updating||!!this.activeWorkflow?.updating}get hasPreviousStep(){const t=this.activeWorkflow?.featureFormViewModel;return this._stepIndex>0||this.nestedWorkflowCount>1||null!=t?.relationshipId||"view"!==this.data.viewModel.attachmentsViewModel.mode||null!=t?.associationId||null!=t?.associatedLayer}get hasUpdatableCandidates(){const{candidates:t,viewModel:e}=this.data;return t.some(({layer:t})=>j(e.editorItems,t)?.supportsUpdateWorkflow)}get nestedWorkflowCount(){return this._workflowStack.length}get shouldShowAttachments(){return!!this.activeEditorItem?.capabilities.attachments.enabled}get shouldAllowAttachmentEditing(){return!!this.activeEditorItem?.capabilities.update.attachments.enabled}get hasPendingEdits(){return Array.from(this._workflowStack).some(t=>t.hasPendingEdits)}get helpMessage(){return this.activeWorkflow?.helpMessage?this.activeWorkflow.helpMessage:"awaiting-feature-to-update"===this.stepId?"select":void 0}get reliesOnOwnerAdminPrivileges(){return this.activeWorkflow?.reliesOnOwnerAdminPrivileges??!1}get hasInvalidFormTemplate(){return!!this.activeEditorItem?.hasInvalidFormTemplate}async back(t=()=>Promise.resolve(!0)){const{activeWorkflow:e}=this,i=e?.featureFormViewModel;if(i?.activeRelationshipInput){const t=i.activeRelationshipInput;if(t.activeCategory)return void(t.activeCategory=null);if(null!=i.relationshipId)return void(i.relationshipId=null);if(t.showAllEnabled)return void(t.showAllEnabled=!1)}if("add-association"===e?.type){const{activeUtilityNetworkAssociationAddAssociationViewModel:t}=this;if(t?.filterOptionsVisible)return void(t.filterOptionsVisible=!1);t?.featureSpatialItems.length&&t.reset()}if(null==i?.associatedLayer)if(null==i?.associationId)if("create-features"===e?.type&&e.hasPreviousStep)await e.previous({cancelCurrentStep:!0});else if(e){if(e.hasPendingEdits&&!i?.disabled){if(!await t())return}e.hasPreviousStep?await e.previous({cancelCurrentStep:!0}):await this.cancelActiveWorkflow({force:!0})}else this.hasPreviousStep?await this.previous({cancelCurrentStep:!0}):await this.cancel({force:!0});else i.associationId=null;else i.associatedLayer=null}async cancelActiveWorkflow(t){await(this.activeWorkflow?.cancel(t)),await this._popWorkflowAndReconcile()}async commit(){await this._drainWorkflowStack(t=>t.commit()),await super.commit()}static create(t){const{startAt:e,applyEdits:i,applyEditsFeatureService:a,...o}=t,r=new q({data:new V({applyEditsCallback:i,applyEditsFeatureServiceCallback:a,...o}),onCommit:async()=>{}});return r._set("steps",this._createWorkflowSteps(r,e)),r}async save(){const{activeFeatureFormViewModel:t}=this;if(t){if(t.submit(),!t.submittable||t.pendingSubtypeChoice)return;const e=t.getValues();if(t.validateContingencyConstraints(e,{includeIncompleteViolations:!0}).length>0)return}if(this.nestedWorkflowCount<2)return await this.commit();const{activeWorkflow:e}=this;if(await(e?.commit()),!P(e))return void await this._popWorkflowAndReconcile();this._popWorkflow();const i=this._workflowStack.peek();if(i&&i===e?.parent&&(await i.cancel(),this._popWorkflow(),0===this.nestedWorkflowCount))return await this.commit();await this._reconcileWorkflowStack()}async startCreatingRelatedRecord(t){try{const e=this._createNestedCreateFeaturesWorkflow(t);await this._pushWorkflowAndReconcile(e)}catch(e){throw new i("editor:unable-to-start-creating","Could not begin updating the provided feature or table record.",{error:e})}}async startSplittingFeature(t,e){try{const i=await this._createNestedSplitFeatureWorkflow(t,e);await this._pushWorkflowAndReconcile(i)}catch(a){throw new i("editor:unable-to-start-splitting","Could not begin splitting the provided feature.",{error:a})}}async startUpdating(t,e){try{const i=await this._createNestedUpdateWorkflow(t,e);await this._pushWorkflowAndReconcile(i)}catch(a){throw new i("editor:unable-to-start-updating","Could not begin updating the provided feature or table record.",{error:a})}}async startAddAssociation(t,e,a){try{const i=await this._createNestedAddAssociationWorkflow(t,e,a);await this._pushWorkflowAndReconcile(i)}catch(o){throw new i("editor:unable-to-start-updating","Could not begin updating the provided feature or table record.",{error:o})}}async deleteActiveFeature(){const{activeWorkflow:t}=this;if(!t)throw new i("editor:nothing-to-delete","There is no feature to delete");const e=L(t);e?(t.stageDelete(),t.data.edits.feature===this.data.rootFeature&&this._removeRootFeatureFromCandidates()):await t.cancel(),this.nestedWorkflowCount<2?e?await this.commit():await this.cancel({force:!0}):(e&&await t.commit(),await this._popWorkflowAndReconcile(),await this._returnToPageWithContent())}async deleteActiveAssociation(){if(!this.canDeleteAssociation)throw new i("editor:nothing-to-delete","There is no association to delete");await this._deleteActiveAssociation(),await this._popWorkflowAndReconcile(),await this._returnToPageWithContent()}async cancelAll(){await this._drainWorkflowStack(t=>t.cancel({force:!0}))}async _deleteActiveAssociation(){const{activeFeatureFormViewModel:t,data:e}=this,{activeAssociation:a,feature:o}=t,{applyEditsFeatureServiceCallback:r,viewModel:s}=e,{sourceLayer:n}=o,l=W(n)&&n.parent?n.parent:n,d=b([l]),c=d.values().next().value?.featureService;if(!c)throw new i("editor:failed-to-delete-association","Could not retrieve feature service needed to delete association");await(c?.load());const p=s.view.map,u=N(p,l);await(u?.networkSystemLayers.loadAssociationsTable());const w=u?.generateDeleteAssociations([a]);if(!w)throw new i("editor:failed-to-delete-association","Could not create payload needed to delete association");const h=u?.gdbVersion??void 0;await r(c,[w],{gdbVersion:h,globalIdUsed:!0})}_removeRootFeatureFromCandidates(){const{candidates:t,rootFeature:e}=this.data;if(0===t.length||!e)return;const i=t.indexOf(e);i>-1&&t.splice(i,1)}async _returnToPageWithContent(){const{activeFeatureFormViewModel:t}=this;if(!t?.activeAssociationInput)return;const{activeAssociationInput:e,associationId:i}=t;await e.refresh(),e.associatedLayer&&!e.associatedFeatures?.length&&(t.associatedLayer=null),null==i||e.associatedFeatureInfos.size||(t.associationId=null)}_createNestedCreateFeaturesWorkflow(t){const{relatedLayer:e}=t,{addAttachmentsCallback:a,applyEditsCallback:o,applyEditsFeatureServiceCallback:r,sketchOptions:s,snappingManager:n,viewModel:l}=this.data;if(!m(e))throw new i("editor:unsupported-layer","Editing is not supported on the provided layer");const d=this._getCreationInfoForNestedCreateFeaturesWorkflow(t),c=d.template||d.initialFeature?"creating-features":"awaiting-feature-creation-info",p=x(this.activeWorkflow)?this.activeWorkflow:void 0;return M.create({addAttachmentsCallback:a,applyEdits:o,applyEditsFeatureService:r,creationInfo:d,isNested:!0,parent:p,sketchOptions:s,snappingManager:n,startAt:c,viewModel:l})}_getCreationInfoForNestedCreateFeaturesWorkflow(t){const{relatedLayer:a}=t;if(!m(a)||A(a))throw new i("editor:unsupported-layer","Editing is not supported on the provided layer");const{viewModel:o}=this.data,r={layer:a,maxFeatures:1},s=this._makeRelatedRecordAttributes(t),n=o.getTemplatesForLayer(a);return n?.length>0?(r.attributeOverrides=s,1===n.length&&(r.template=n[0])):r.initialFeature=new e({sourceLayer:a,attributes:s}),r}async _createNestedUpdateWorkflow(t,e={}){const i=_(t.sourceLayer)?R:E,{applyEditsCallback:a,applyEditsFeatureServiceCallback:o,sketchOptions:r,snappingManager:s,viewModel:n}=this.data,l=x(this.activeWorkflow)?this.activeWorkflow:void 0,d=await i.create({feature:t,parent:l,sketchOptions:r,snappingManager:s,viewModel:n,applyEdits:a,applyEditsFeatureService:o,featureFormCallbacks:{addRelatedRecord:async t=>await this._updatingHandles.addPromise(this.startCreatingRelatedRecord(t)),editRelatedRecord:async({relatedFeature:t,readOnly:e})=>await this._updatingHandles.addPromise(this.startUpdating(t,{readOnly:e})),selectAssociatedFeature:async({feature:t,association:e})=>await this._updatingHandles.addPromise(this.startUpdating(t,{association:e})),addAssociation:async t=>await this._updatingHandles.addPromise(this.startAddAssociation(t.feature,t.utilityNetwork,t.associationType))},...e});return await u(()=>!d.updating),d}async _createNestedAddAssociationWorkflow(t,e,i){const{AddAssociationWorkflow:a}=await import("./AddAssociationWorkflow.js"),{applyEditsCallback:o,applyEditsFeatureServiceCallback:r,viewModel:s}=this.data,n=x(this.activeWorkflow)?this.activeWorkflow:void 0,l=this.activeFeatureFormViewModel?.activeAssociationInput,d=await a.create({utilityNetwork:e,associationType:i,feature:t,parent:n,viewModel:s,associationInput:l,applyEdits:o,applyEditsFeatureService:r});return await u(()=>!d.updating),d}async _createNestedSplitFeatureWorkflow(t,e){const{applyEditsCallback:i,applyEditsFeatureServiceCallback:a,viewModel:o}=this.data,r=x(this.activeWorkflow)?this.activeWorkflow:void 0,s=O(o.editorItems,t.sourceLayer),n=I.create({applyEdits:i,applyEditsFeatureService:a,editorItem:s,originalFeature:t,parent:r,viewModel:o,...e});return await u(()=>!n.updating),n}async _drainWorkflowStack(t){const e=this._workflowStack,i=[];for(const a of e){const e=t(a).finally(()=>a.destroy());this._updatingHandles.addPromise(e),i.push(e)}await Promise.all(i),this._workflowStack.clear(),this._sketchStack.clear()}_makeRelatedRecordAttributes(t){const{parentFeature:e,relatedLayer:i,relationshipId:a}=t;if(!D(e))return;const o=i.relationships?.find(t=>t.id===a);if(!o)return void this._logContinuingWithoutRelationshipWarning("relationship-not-found","Could not begin creating a related record because the relationship specified could not be found on the destination layer.");if("origin"===o.role)return void this._logContinuingWithoutRelationshipWarning("unsupported-role","Creating new related records in the 'origin' table of a relationship is not yet supported");const r=e.sourceLayer;o.relatedTableId!==r.layerId&&this._logContinuingWithoutRelationshipWarning("invalid-argument-combination","The given parent feature does not belong to the relationship designated by the given relationship ID.");const s=r.relationships?.find(t=>t.id===a);if(!s)return void this._logContinuingWithoutRelationshipWarning("relationship-not-found","Could not begin creating a related record because the relationship specified could not be found on the origin layer.");const n=z(r,s),l=e.getAttribute(n);l||this._logContinuingWithoutRelationshipWarning("no-key-on-origin-feature","The given parent feature does not have a value for the relationship's origin primary key field.");const d=z(i,o);return{[d]:l}}_popWorkflow(){this._workflowStack.pop()?.destroy(),this._sketchStack.pop()}async _popWorkflowAndReconcile(){this._popWorkflow();const t=await this._reconcileWorkflowStack();if(t.failureCount>0)throw new i("editor:next-workflow-failed","Popped the top workflow, but the next workflow in the stack failed to activate",t)}async _pushWorkflowAndReconcile(t){const e=this._workflowRequiresSketchViewModel(t);this.activeWorkflow?.exit({removeSketchHandles:e});const a=this._sketchStack,o=await(t?.start()),r=a.peek();o?(r?.exit(),a.push(o)):a.push(this._cloneSketchController(r)),this._workflowStack.push(t);const s=await this._reconcileWorkflowStack();if(s.failureCount>0)throw new i("editor:failed-to-start-updating-feature","Failed to enter the provided workflow.",s)}async _reconcileWorkflowStack(){const t=this._workflowStack,e=this._sketchStack;try{const i=t.peek();return await(i?.enter()),await(e.peek()?.enter()),{activeWorkflow:i,failureCount:0}}catch(i){t.pop().destroy(),e.pop();const{activeWorkflow:a,failureCount:o}=await this._reconcileWorkflowStack();return{activeWorkflow:a,failureCount:o+1}}}_cloneSketchController(t){return{enter:t?.enter??(async()=>{}),exit:t?.exit??(async()=>{}),viewModel:t?.viewModel}}_workflowRequiresSketchViewModel(t){const{type:e}=t;return"update-feature"===e||"create-features"===e&&!_(t.data.creationInfo?.layer)}static _createWorkflowSteps(t,e="awaiting-feature-to-update"){const{data:o}=t;return T(["awaiting-feature-to-update","awaiting-update-feature-candidate","editing-existing-feature","adding-attachment","editing-attachment"],e,{"awaiting-feature-to-update":()=>({id:"awaiting-feature-to-update",async setUp(){const{spinnerViewModel:e}=o.viewModel,i=o.viewModel.view;i.activeTool=null;let s=null;t.addHandles(a(()=>{s=r(s)}),this.id),o.rootFeature=null,o.candidates=[];const p=i.on("immediate-click",async a=>{const r=n();t._updatingHandles.addPromise(r.promise);try{e.location=a.mapPoint,e.visible=!0,s?.abort();const{editorItems:r}=o.viewModel;s=new AbortController;const n=await a.defer(()=>new Promise((t,e)=>{l(s?.signal,()=>e(d())),t(H(r,i,a,s?.signal))}));if(c(s),o.candidates=n.filter(t=>"fulfilled"===t.status).flatMap(t=>t.value).filter(t=>!t.isAggregate),e.visible=1===o.candidates.length,0===o.candidates.length)return;a.stopPropagation(),1===o.candidates.length?(o.rootFeature=o.candidates[0],t.go("editing-existing-feature").catch(()=>{}).then(()=>e.visible=!1)):t.next()}finally{r.resolve()}},F.TOOL),u=f(()=>null!=i.activeTool,()=>t.cancel({force:!0}),{once:!0});i.focus(),t.addHandles([p,u],this.id)},async tearDown(){0===o.candidates.length&&(o.viewModel.spinnerViewModel.visible=!1),t.removeHandles(this.id)}}),"awaiting-update-feature-candidate":()=>({id:"awaiting-update-feature-candidate",async setUp(){o.rootFeature=null;const{view:e}=o.viewModel;if(!e)return;const i=new C({view:e,highlightName:S});t.addHandles([w(()=>o.rootFeature,(t,e)=>{i.remove(e),i.add(t)},h),a(()=>i.removeAll())],this.id)},async tearDown(){t.removeHandles(this.id)}}),"editing-existing-feature":()=>({id:"editing-existing-feature",async setUp(){const{data:e}=t,{rootFeature:a}=e;if(!a)throw new i("editor:no-feature-specified","Cannot setup the 'updating-existing-feature' step until the root feature is defined");"split"===e.rootWorkflowOptions?.type?await t.startSplittingFeature(a,e.rootWorkflowOptions.props):await t.startUpdating(a),e.viewModel.spinnerViewModel.visible=!1;const o=s(async()=>{await u(()=>!t.updating),t.previous()});t.addHandles([w(()=>t.nestedWorkflowCount,(t,e)=>{0===t&&0!==e&&o()},h)],this.id)},async tearDown(){await t.cancelAll(),t.removeHandles(this.id)}}),"adding-attachment":()=>({id:"adding-attachment",parent:"editing-existing-feature",async setUp(){},async tearDown(){o.viewModel.attachmentsViewModel.mode="view"}}),"editing-attachment":()=>({id:"editing-attachment",parent:"editing-existing-feature",async setUp(){},async tearDown(){o.viewModel.attachmentsViewModel.mode="view"}})})}_logContinuingWithoutRelationshipWarning(t,e){o.getLogger(this).warn(`editor:${t}`,e,"The create operation will be allowed to proceed, but the resulting feature may not be related to the given parent feature.")}};function z(t,{keyField:e}){return t.getField(e)?.name??e}t([v()],G.prototype,"activeEditorItem",null),t([v()],G.prototype,"activeFeatureFormViewModel",null),t([v()],G.prototype,"activeUtilityNetworkAssociationAddAssociationViewModel",null),t([v()],G.prototype,"activeSketchViewModel",null),t([v()],G.prototype,"canDeleteAssociation",null),t([v()],G.prototype,"activeWorkflow",null),t([v()],G.prototype,"updating",null),t([v()],G.prototype,"data",void 0),t([v()],G.prototype,"hasPreviousStep",null),t([v()],G.prototype,"hasUpdatableCandidates",null),t([v()],G.prototype,"nestedWorkflowCount",null),t([v()],G.prototype,"shouldShowAttachments",null),t([v()],G.prototype,"shouldAllowAttachmentEditing",null),t([v()],G.prototype,"hasPendingEdits",null),t([v()],G.prototype,"helpMessage",null),t([v()],G.prototype,"reliesOnOwnerAdminPrivileges",null),t([v()],G.prototype,"hasInvalidFormTemplate",null),G=q=t([k("esri.widgets.Editor.UpdateWorkflow")],G);const Q=G;export{Q as default};
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
|
|
3
3
|
See https://js.arcgis.com/4.34/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
import{__decorate as t}from"tslib";import o from"../../core/Accessor.js";import{property as e}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/Logger.js";import"../../core/RandomLCG.js";import{subclass as r}from"../../core/accessorSupport/decorators/subclass.js";import s from"../../views/interactive/sketch/SketchOptions.js";let p=class extends o{constructor(t){super(t),this.addAttachmentsCallback=null,this.applyEditsCallback=null,this.applyEditsFeatureServiceCallback=null,this.candidates=[],this.rootFeature=null,this.
|
|
5
|
+
import{__decorate as t}from"tslib";import o from"../../core/Accessor.js";import{property as e}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/Logger.js";import"../../core/RandomLCG.js";import{subclass as r}from"../../core/accessorSupport/decorators/subclass.js";import s from"../../views/interactive/sketch/SketchOptions.js";let p=class extends o{constructor(t){super(t),this.addAttachmentsCallback=null,this.applyEditsCallback=null,this.applyEditsFeatureServiceCallback=null,this.candidates=[],this.rootFeature=null,this.rootWorkflowOptions={type:"update"},this.sketchOptions=new s,this.snappingManager=null,this.viewModel=null}};t([e()],p.prototype,"addAttachmentsCallback",void 0),t([e()],p.prototype,"applyEditsCallback",void 0),t([e()],p.prototype,"applyEditsFeatureServiceCallback",void 0),t([e()],p.prototype,"candidates",void 0),t([e()],p.prototype,"rootFeature",void 0),t([e()],p.prototype,"rootWorkflowOptions",void 0),t([e({constructOnly:!0})],p.prototype,"sketchOptions",void 0),t([e()],p.prototype,"snappingManager",void 0),t([e()],p.prototype,"viewModel",void 0),p=t([r("esri.widgets.Editor.UpdateWorkflowData")],p);const i=p;export{i as default};
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
|
|
3
3
|
See https://js.arcgis.com/4.34/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
import{__decorate as e}from"tslib";import t from"../../../core/Accessor.js";import{property as r}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/has.js";import"../../../core/Logger.js";import"../../../core/RandomLCG.js";import{subclass as
|
|
5
|
+
import{__decorate as e}from"tslib";import t from"../../../core/Accessor.js";import{property as r}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/has.js";import"../../../core/Logger.js";import"../../../core/RandomLCG.js";import{subclass as o}from"../../../core/accessorSupport/decorators/subclass.js";import{isTable as s}from"../../../layers/support/layerUtils.js";import l from"./EditorEditingCapabilities.js";import{formTemplateHasInvalidFields as i}from"../../FeatureForm/featureFormUtils.js";let a=class extends t{constructor(e){super(e),this.disabled=!1,this.layer=null,this.layerInfo=null,this.layerView=null}get _suspended(){return!!this.layerView?.suspended}get capabilities(){return new l({layer:this.layer,layerInfo:this.layerInfo,layerView:this.layerView})}get editable(){const{create:e,relationship:t,update:r,delete:{enabled:o}}=this.capabilities,s=e.attachments.enabled||r.attachments.enabled;return!this.disabled&&(e.enabled||r.enabled||s||o||t.enabled)}get formTemplate(){return this.capabilities.formTemplate}get hasInvalidFormTemplate(){return i(this.layer,this.formTemplate)}get isTable(){return s(this.layer)}get supportsCreateFeaturesWorkflow(){if(this.disabled)return!1;const{enabled:e,geometry:t}=this.capabilities.create;return this.isTable?e:e&&t}get supportsSplitFeatureWorkflow(){const{capabilities:e}=this;return!this.disabled&&e.update.enabled&&e.update.geometry&&e.create.enabled}get supportsUpdateWorkflow(){const{capabilities:e}=this;return!this.disabled&&(e.update.enabled||e.update.attachments.enabled||e.delete.enabled)}get visible(){const{layer:e}=this,t=e.parent;return!this._suspended&&e.visible&&(!t||!("visible"in t)||t.visible)}};e([r()],a.prototype,"_suspended",null),e([r()],a.prototype,"capabilities",null),e([r()],a.prototype,"disabled",void 0),e([r()],a.prototype,"editable",null),e([r()],a.prototype,"formTemplate",null),e([r()],a.prototype,"hasInvalidFormTemplate",null),e([r()],a.prototype,"isTable",null),e([r()],a.prototype,"layer",void 0),e([r()],a.prototype,"layerInfo",void 0),e([r()],a.prototype,"layerView",void 0),e([r()],a.prototype,"supportsCreateFeaturesWorkflow",null),e([r()],a.prototype,"supportsSplitFeatureWorkflow",null),e([r()],a.prototype,"supportsUpdateWorkflow",null),e([r()],a.prototype,"visible",null),a=e([o("esri.widgets.Editor.support.EditorItem")],a);const p=a;export{p as default};
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
|
|
3
3
|
See https://js.arcgis.com/4.34/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
import e from"../../Color.js";import t from"../../Graphic.js";import{isSome as r,equals as n,addMany as o}from"../../core/arrayUtils.js";import{createTask as a}from"../../core/asyncUtils.js";import"../../core/has.js";import i from"../../core/Error.js";import{handlesGroup as s,makeHandle as l,abortHandle as c}from"../../core/handleUtils.js";import{clone as u}from"../../core/lang.js";import d from"../../core/Logger.js";import{getOrCreateMapValue as p}from"../../core/MapUtils.js";import{debounce as f,isPromiseLike as y,throwIfAborted as m,whenOrAbort as h}from"../../core/promiseUtils.js";import{watch as g,on as b,whenOnce as w}from"../../core/reactiveUtils.js";import{px2pt as I}from"../../core/screenUtils.js";import{addMany as v}from"../../core/SetUtils.js";import{diff as T}from"../../core/accessorSupport/diffUtils.js";import{isSharedTemplateOrMetadata as S,isSharedGroupTemplate as F,isSharedTemplate as j,isSharedPresetTemplate as k,isStandardFeatureTemplate as A,isSharedFeatureTemplate as L}from"../../editing/templateUtils.js";import{getSharedTemplateProvider as U}from"../../editing/sharedTemplates/SharedTemplateProvider.js";import V from"../../layers/GraphicsLayer.js";import{featureHasFields as M,fixFields as O,getDisplayFieldName as x}from"../../layers/support/fieldUtils.js";import{isSubtypeSublayer as q}from"../../layers/support/layerUtils.js";import{calculateTolerance as z}from"../../renderers/support/clickToleranceUtils.js";import{meterIn as E}from"../../renderers/support/lengthUtils.js";import{isRenderer as P}from"../../renderers/support/typeUtils.js";import{getTransformationType as C}from"../../renderers/visualVariables/support/sizeVariableUtils.js";import D from"../../symbols/SimpleFillSymbol.js";import R from"../../symbols/SimpleLineSymbol.js";import G from"../../symbols/SimpleMarkerSymbol.js";import{to3D as B}from"../../symbols/support/symbolConversion.js";import{getDisplayedSymbol as N}from"../../symbols/support/symbolUtils.js";import{getServices as Z}from"../../undoredo/support/Services.js";import{GraphicState as W}from"../../views/3d/layers/graphics/GraphicState.js";import{defaultDrawingMode as Q}from"../../views/draw/DrawingMode.js";import{createQueryGeometry as $}from"../../views/support/drapedUtils.js";import{filterGraphicHits as J,hitTestSelectSimilarDistance as H}from"../../views/support/hitTestSelectUtils.js";import{dependencySort as K}from"./support/dependencySort.js";import{isDrawGraphicTool as X}from"../Sketch/support/sketchUtils.js";const Y=()=>d.getLogger("esri.widgets.Editor.workflowUtils");function _(e){return!!e&&"features"in e}function ee(e){return null!=e&&"create-features"===e.type}function te(e){return null!=e&&"update-features"===e.type}function re(e){return null!=e&&e.type.includes("update-")&&"fullFeature"in e}function ne(e){return null!=e&&"update"===e.type}function oe(e){return null!=e&&"split-feature"===e.type}function ae(e){const t=e?.type;return"update-feature"===t||"update-table-record"===t||"split-feature"===t}function ie(e){const t=e&&"renderer"in e?e.renderer:null;if(!fe(t))return{rotation:null,size:null};const r=t.getVisualVariablesForType("rotation").filter(e=>(!e.axis||"heading"===e.axis)&&e.field&&!e.valueExpression),n=t.getVisualVariablesForType("size").filter(e=>e.field&&!e.useSymbolValue&&!e.valueExpression&&"real-world-size"===C(e));return{rotation:1===r.length?r[0]:null,size:1===n.length?n[0]:null}}function se(e){const t=e.sourceLayer;if(!(t&&"renderer"in t&&fe(t.renderer)))return{rotation:null,size:null};const{rotation:r,size:n}=ie(t);let o=null,a=null;if(r){const e=t.fields?.filter(e=>e.name===r.field),n=1===e?.length?e[0]:null;o=le(r,n)}if(n){const e=t.fields?.filter(e=>e.name===n.field),r=1===e?.length?e[0]:null;a=de(n,r)}return{rotation:o,size:a}}function le(e,t){const r="heading"===(e.axis||"heading")&&"arithmetic"===e.rotationType?-1:1,n=t?.type??"double",o={initial:0,current:0};return{field:e.field,fieldType:n,getDefaultValue:()=>Promise.resolve(0),getValue:e=>(o.current=o.initial-r*e,pe((o.current+360)%360,n)),setInitialValue:e=>{o.initial=e,o.current=0},isUpdatingInteractively:!1,rotationType:e.rotationType??"geographic"}}function ce(e,t){switch(t){case"width":return e[0];case"depth":return e[1];case"height":return e[2];default:return e[2]||e[1]||e[0]}}async function ue(e,t,r){if(null==t)return 0;const{symbol:n}=B(t);if(null==n||"web-style"===n.type||"cim"===n.type)return 0;const o=n.symbolLayers.at(0);if(!o)return 0;switch(o.type){case"icon":{const{computeIconLayerResourceSize:e}=await import("../../symbols/support/symbolLayerUtils.js");return Math.min(tt.icon,(await e(o,tt.icon))[0])||tt.icon}case"text":return tt.text;case"line":return tt.line;case"object":{const{computeObjectLayerResourceSize:t}=await import("../../symbols/support/symbolLayerUtils.js");return ce(await t(o,e.scale/tt.viewScaleSizeFactor),r)}case"path":case"extrude":return e.scale/tt.viewScaleSizeFactor;default:return 0}}function de(e,t){const r=e.axis,n=t?.type??"double",o={initial:0,current:0},a=E[e.valueUnit]??1;let i;return i="area"===e.valueRepresentation?e=>(e*a/2)**2*Math.PI:"radius"===e.valueRepresentation||"distance"===e.valueRepresentation?e=>e*a/2:e=>e*a,{field:e.field,fieldType:n,getDefaultValue:async(e,t)=>pe(i(await ue(t,e,r)),n),getValue:(e,t)=>(o.initial||(o.initial=t.pixelSizeAt(t.center)),o.current=o.initial*e,pe(o.current,n)),setInitialValue:e=>{o.initial=e,o.current=0},isUpdatingInteractively:!1,displayUnit:ot(e.valueUnit),axis:e.axis}}function pe(e,t){switch(t){case"small-integer":case"integer":case"long":return Math.round(e);case"double":case"single":return e;default:return 0}}function fe(e){if(!P(e))return!1;switch(e?.type){case"class-breaks":case"simple":case"unique-value":case"dot-density":case"dictionary":case"pie-chart":return!0;default:return!1}}async function ye(e,t,r){const n=await N(e,{useSourceLayer:!0,ignoreGraphicSymbol:!0,webStyleCache:t,scale:r});null!=T(e.symbol,n)&&(e.symbol=n)}function me(e,t){if(!e||!t)throw new Error("no geometry type");if("multipatch"===e)return{tool:"mesh",createOptions:{mode:"hybrid"}};const r=new Map;r.set("circle",{mode:"freehand"}),r.set("rectangle",{mode:"freehand"});const n={mode:Q,optionsPerTool:r};if(S(t)){const o=t.defaultTool,a=F(t)?t.definition?.inputGeometryType??e:e;switch(o){case"freehand":case"stream-line":return{tool:"polyline"===a?"freehandPolyline":"freehandPolygon",createOptions:n};case"autocomplete-freehand-polygons":case"stream-polygon":return{tool:"freehandPolygon",createOptions:n};case"autocomplete-polygons":case"difference-polygon":case"create-structures":case"polygon":case"trace":return{tool:"polygon"===a?"polygon":"polyline",createOptions:n};case"circle":return r.get("circle").preserveAspectRatio=!0,{tool:"circle",createOptions:n};case"ellipse":return r.get("circle").preserveAspectRatio=!1,{tool:"circle",createOptions:n};case"create-points-along-line":case"multipoint":return{tool:"multipoint",createOptions:n};case"line":case"radial-line":case"right-angle-line":case"split":case"two-point-line":return{tool:"polyline",createOptions:n};case"rectangle":case"regular-polygon":case"right-angle-polygon":return{tool:"rectangle",createOptions:n};case"elevation-point-from-contour":case"elevation-point-from-dem":case"parcel-seed":case"point":case"point-and-rotation":case"point-at-end-of-line":return{tool:"point",createOptions:n}}}else{const o=t.drawingTool;if("circle"===o||"ellipse"===o)return r.get("circle").preserveAspectRatio="circle"===o,{tool:"circle",createOptions:n};if("rectangle"===o)return{tool:"rectangle",createOptions:n};if("freehand"===o)return{tool:"polygon"===e?"freehandPolygon":"freehandPolyline",createOptions:n}}return{tool:e,createOptions:n}}async function he(e,t,r,n){const{creationInfo:o,fullTemplate:a}=r;if(!o)throw new i("featureworkflow","No creation info provided.");const s=o.layer,l=qe(a,o.attributeOverrides),{view:c}=e,u="2d"===c?.type;F(a)||k(a)||await ze(e,s,l,n,u?c.scale:null);const{capabilities:d}=s;t.elevationInfo=s.elevationInfo;const p=me(s.geometryType,a);e.defaultCreateOptions={graphicProperties:{attributes:l,sourceLayer:s},mode:p.createOptions.mode,optionsPerTool:p.createOptions.optionsPerTool,preserveAspectRatio:p.createOptions.preserveAspectRatio,hasZ:d.data.supportsZ,defaultZ:(u?d.editing.zDefault:null)??e.defaultCreateOptions.defaultZ},null==o.geometryToPlace?await e.create(p.tool):await e.place(o.geometryToPlace,{graphicProperties:{attributes:l,sourceLayer:s}})}async function ge(e){return s([be(e),we(e)])}function be({creationAttributes:e,data:t,sketchViewModel:r,view:n,webStyleCache:o}){const{creationInfo:a}=t,{fullTemplate:i}=t;if(!a||"2d"!==n?.type||F(i)||k(i))return null;const s=f(t=>ze(r,a.layer,e,o,t));return g(()=>n.scale,e=>s(e))}function we({data:t,sketchViewModel:r,view:n}){const{templateExecutorInfo:o}=t;if(!o)return null;const a=r.activeComponent;if(!n||!X(a))return Y().error(new i("featureworkflow","Failed to set up template feedback.")),null;const c=new V({effect:"saturate(0.6) opacity(0.8)",listMode:"hide",title:"Shared Template Feedback Graphics"});n.map?.add(c);const{executor:u,serviceLayersById:d}=o,p=n.theme?.accentColor??new e([255,165,0,1]);return s([b(()=>a,["cursor-update","vertex-add"],()=>{c.removeAll();const e=a.graphic?.geometry;if(!e||!Ie(e))return;const t=u(e,"digitizing");if(!y(t))for(const r of t.edits){const e=d.get(r.id);if(e&&r.addFeatures&&0!==r.addFeatures.length)for(const t of e)if(!t.isTable)for(const e of r.addFeatures){const t=ve(e,p);t&&c.add(t)}}}),l(()=>{n.map.remove(c),c.destroy()})])}function Ie(e){switch(e.type){case"point":case"multipoint":return!0;case"polyline":return e.paths[0].length>1;case"polygon":{const t=e.rings[0];return n(t.at(0),t.at(-1))?t.length>2:t.length>1}default:return!1}}function ve(e,r){let n=null;switch(e.geometry?.type){case"point":case"multipoint":n=new G({angle:0,color:r,outline:new R({cap:"round",color:r,join:"round",miterLimit:1,style:"solid",width:1}),path:"undefined",size:8,style:"circle",xoffset:0,yoffset:0});break;case"polygon":n=new D({color:r,outline:new R({cap:"round",color:r,join:"round",miterLimit:1,style:"solid",width:3}),style:"none"});break;case"polyline":n=new R({cap:"round",color:r,join:"round",miterLimit:1,style:"solid",width:2});break;default:return null}return new t({geometry:e.geometry,symbol:n,attributes:{...e.attributes}})}async function Te(e,t){const r=await Z(t).load(),n=q(e)?e.parent:e;return r.tablesAndLayersLookup.get(n)}async function Se(e,t){const r=await Te(e,t);if(!r)return new Map;const n=new Map;for(const o of r.layersAndTables)p(n,o.layerId,()=>[]).push(o);return n}function Fe(e){const t=e.objectIdField,r=e.globalIdField??"";return{id:e.layerId,identifierFields:{objectIdField:t,globalIdField:r},addFeatures:[],deleteAttachments:[],addAttachments:[],deleteFeatures:[],updateFeatures:[]}}function je(e){const{edits:t,serviceInfo:n,view:o,findOriginalFeature:a}=e,i=ke(n.layersAndTables),s=n.layersAndTables.toArray(),{allEditData:l,editDataByLayerIdMap:c,editDataByIdMap:u}=Le(t,i,a),d=Ue(l,Ae(s,c),c);if(o&&Oe(l,d,o),0===d.length)return t;const p=K(d,{continueOnCircularDependency:!0}).map(e=>u.get(e)).filter(r),f=new Map;for(const r of p)f.set(r.uniqueId,r);const y=[];for(const r of l)f.has(r.uniqueId)||y.push(r);const m=[];let h=null;for(const r of p){const{layer:e}=r;switch(null==h?h=Fe(e):h.id!==e.layerId&&(m.push(h),h=Fe(e)),r.operationType){case"add":case"modify":h.addFeatures.push(r.after);break;case"delete":h.deleteFeatures.push(r.before)}}null!==h&&m.push(h);for(const r of y){const e=r.layer.layerId,t=m.find(t=>t.id===e)??Fe(r.layer);switch(m.includes(t)||m.push(t),r.operationType){case"add":t.addFeatures.push(r.after);break;case"modify":t.updateFeatures.push(r.after);break;case"delete":t.deleteFeatures.push(r.before);break;case"deleteAttachment":t.deleteAttachments.push(r.attachmentId);break;case"addAttachment":t.addAttachments.push(r.attachment)}}for(const r of m)void 0!==r.deleteAttachments&&0===r.deleteAttachments.length&&delete r.deleteAttachments,void 0!==r.addAttachments&&0===r.addAttachments.length&&delete r.addAttachments;return m}function ke(e){const t=new Map;for(const r of e)t.set(r.layerId,r);return t}function Ae(e,t){const r=new Map;for(const n of e)for(const e of n.relationships??[])if(r.set(Ve(n,e),""),t.has(e.relatedTableId)){const o=t.get(e.relatedTableId);if(o.length>0)for(const t of o[0].layer.relationships??[])if(t.id===e.id){r.set(Ve(n,e),t.keyField);break}}return r}function Le(e,t,r){const n=new Map,o=[],a=new Map;let s=1;for(const l of e){const e=[],c=t.get(l.id);if(!c)throw new i("featureworkflow",`Failed to prepare applyEdits payload. Layer with id ${l.id} not found.`);for(const t of l.addFeatures??[])e.push({uniqueId:"T"+s++,operationType:"add",layer:c,after:t});for(const t of l.deleteFeatures??[])e.push({uniqueId:"T"+s++,operationType:"delete",before:t,layer:c});for(const t of l.deleteAttachments??[])e.push({uniqueId:"T"+s++,operationType:"deleteAttachment",attachmentId:t,layer:c});for(const t of l.addAttachments??[])e.push({uniqueId:"T"+s++,operationType:"addAttachment",attachment:t,layer:c});for(const t of l.updateFeatures??[])e.push({uniqueId:"T"+s++,operationType:"modify",before:r(t),after:t,layer:c});n.set(c.layerId,e);for(const t of e)o.push(t),a.set(t.uniqueId,t)}return{allEditData:o,editDataByIdMap:a,editDataByLayerIdMap:n}}function Ue(e,t,r){const n=[];for(const o of e){const e=o.layer.relationships??[],{uniqueId:a}=o;for(const i of e){const e=i.keyField;if("origin"===i.role){const s=r.get(i.relatedTableId);if(!s||0===s.length)continue;const l=Ve(o.layer,i),c=t.get(l);if(void 0===c||""===c)continue;switch(o.operationType){case"add":for(const t of s)t!==o&&("add"!==t.operationType&&"modify"!==t.operationType||t.after.attributes[c]===o.after.attributes[e]&&n.push([a,t.uniqueId]));break;case"modify":if(o.before.attributes[e]!==o.after.attributes[e])for(const t of s){const r=t.uniqueId;t!==o&&("delete"===t.operationType?t.before.attributes[c]===o.before.attributes[e]?n.push([r,a]):t.before.attributes[c]===o.after.attributes[e]&&n.push([a,r]):"add"===t.operationType?t.after.attributes[c]===o.after.attributes[e]?n.push([a,r]):t.after.attributes[c]===o.before.attributes[e]&&n.push([r,a]):"modify"===t.operationType&&(t.before.attributes[c]!==t.after.attributes[c]?t.after.attributes[c]===o.after.attributes[e]?n.push([a,r]):n.push([r,a]):n.push([a,r])))}break;case"delete":for(const t of s)t!==o&&("delete"!==t.operationType&&"modify"!==t.operationType||t.before.attributes[c]===o.before.attributes[e]&&n.push([t.uniqueId,a]))}}}}return n}function Ve(e,t){return`${e.layerId}:${t.id}`}function Me(e,t){return!!(t?.map&&"utilityNetworks"in t.map&&t.map.utilityNetworks?.length&&t.map.utilityNetworks.some(t=>!(!t.loaded||!e.url?.startsWith(t.featureServiceUrl)||e.layerId!==t.networkSystemLayers.associationsTableId)))}function Oe(e,t,r){const n=[];for(const a of e)Me(a.layer,r)&&n.push(a);if(0===n.length)return;let o=[];for(const a of n){const r=a.layer;switch(a.operationType){case"delete":o=[...xe(a.before.attributes[r.fieldsIndex.get("fromglobalid").name],e),...xe(a.before.attributes[r.fieldsIndex.get("toglobalid").name],e)];for(const e of o)t.push([a.uniqueId,e.uniqueId]);break;case"add":o=[...xe(a.after.attributes[r.fieldsIndex.get("fromglobalid").name],e),...xe(a.after.attributes[r.fieldsIndex.get("toglobalid").name],e)];for(const e of o)t.push([e.uniqueId,a.uniqueId])}}}function xe(e,t){const r=[],n=t.filter(({layer:e})=>""!==e.globalIdField&&null!=e.globalIdField);for(const o of n){const t=o.layer.globalIdField;("before"in o&&o.before?.attributes[t]===e||"after"in o&&o.after?.attributes[t]===e)&&r.push(o)}return r}function qe(e,t={}){return F(e)||k(e)?{}:A(e)?{...e.prototype.attributes,...t}:L(e)?{...e.definition?.defaultValues,...t}:{...t}}async function ze(e,r,n,o,a){const i=new t({sourceLayer:r,attributes:n}),{rotation:s,size:l}=se(i);let c=await N(i,{useSourceLayer:!0,webStyleCache:o,scale:a}),u=!1;for(const t of[l,s]){if(null==t)continue;null==n[t.field]&&(n[t.field]=await t.getDefaultValue(c,e.view),u=!0)}switch(u&&(c=await N(i,{useSourceLayer:!0,webStyleCache:o,scale:a})),c?.type){case"simple-fill":case"polygon-3d":e.polygonSymbol=c;break;case"simple-line":case"line-3d":e.polylineSymbol=c;break;case"simple-marker":case"picture-marker":case"point-3d":case"cim":e.pointSymbol=c;break;case"mesh-3d":e.meshSymbol=c}Ee(e.tooltipOptions,l,s)}function Ee(e,t,r){e.visualVariables=null!=t||null!=r?{size:null!=t?{unit:t.displayUnit,axis:t.axis,valueType:t.fieldType}:null,rotation:null!=r?{valueType:r.fieldType,rotationType:r.rotationType??"geographic"}:null}:null}function Pe(e,t){return e.find(e=>e.layer===t)}function Ce(e,t){const r=Pe(e,t);if(null==r)throw new i("no-editorItem-found","The EditorViewModel provided did not have an EditorItem associated with the specified layer");return r}function De(e,t){return e?.find(e=>e.layer===t)}async function Re(e,t,r,n){switch(t.type){case"3d":return Ge(e,t,r,n);case"2d":return Be(e,t,r,n)}}async function Ge(e,t,r,n){if(0===e.length)return[];const{updatable:a,graphicsByLayer:i}=await r.defer(async()=>{const{results:o}=await h(H(t,r),n),a=new Map,i=e=>{const t=e.layer,r=a.get(t);if(!r){const e=new Array;return a.set(t,e),e}return r};J(o).forEach(({graphic:e})=>i(e).push(e));const s=e.filter(({capabilities:e,layer:t})=>e.update.enabled&&a.has(t));return 0!==s.length&&r.stopPropagation(),{updatable:s,graphicsByLayer:a}});return h(Promise.allSettled(a.map(async({layer:e})=>{const t=i.get(e),r=Ne(e);if(t.every(e=>M(e,r)))return t;const a=[];for(const n of t){a.push(n.getObjectId());const e=Object.keys(n.attributes);o(r,e)}const s=e.createQuery();return s.returnGeometry=!1,s.objectIds=a,s.outFields=O(e.fieldsIndex,r),e.queryFeatures(s,{signal:n}).then(({features:e})=>e)})),n)}async function Be(e,t,r,n){if(0===e.length)return[];const{mapPoint:o}=r;if(null==o)return[];let a=null;const i=await r.defer(async()=>{const{results:o}=await h(t.hitTest(r),n);if(0===o.length)return[];const i=new Set;a=J(o),a.forEach(({graphic:e})=>e&&i.add(e.layer));const s=e.filter(e=>i.has(e.layer)&&e.supportsUpdateWorkflow);return s.length>0&&r.stopPropagation(),s});return h(Promise.allSettled(i.map(async({layer:e})=>{const i=e.createQuery();i.returnGeometry=!0,i.outFields=Ne(e);const s="renderer"in e?z({renderer:e.renderer,pointerType:r.pointerType}):0;i.geometry=$(o,s,t),i.outSpatialReference=t.spatialReference;const{features:l}=await e.queryFeatures(i,{signal:n});return a?.forEach(({graphic:t})=>{t.layer!==e||l.some(e=>e.getObjectId()===t.getObjectId())||l.push(t)}),l})),n)}function Ne(e){return O(e.fieldsIndex,[e.objectIdField,x({displayField:"displayField"in e?e.displayField:null,fields:e.fields})])}async function Ze(e,t,n,o){const a=t.createQuery();a.objectIds=e.map(e=>e.getObjectId()).filter(r),a.outFields=["*"],a.returnM=t.capabilities.data.supportsM,a.returnZ=t.capabilities.data.supportsZ,"scene"===t.type&&null!=t.infoFor3D||(a.outSpatialReference=n);const i=await t.queryFeatures(a,{signal:o});return m(o),i.features}function We(e){const t=new Map;for(const r of e){const e=r.sourceLayer,n=q(e)?e.parent:e;p(t,n,()=>[]).push(r)}return t}async function Qe(e){const{graphic:t,sketchViewModel:r,sourceLayer:n,visualVariables:o}=e;await $e(e);const a={multipleSelectionEnabled:!1};return"point"===n.geometryType&&(a.enableRotation=null!=o.rotation,a.enableScaling=null!=o.size),r.update(t,a)}async function $e(e){const{graphic:t,sketchLayer:r,sketchViewModel:n,sourceLayer:o,visualVariables:a,webStyleCache:i}=e;let s=!1;const{rotation:l,size:c}=a;for(const u of[l,c]){if(null==u)continue;const e=t.getAttribute(u.field);if(null!=e)u.setInitialValue(e);else{const e=await u.getDefaultValue(t.symbol,n.view);u.setInitialValue(e),t.setAttribute(u.field,e),s=!0}}if(s){const e="2d"===n.view?.type?n.view.scale:null;await ye(t,i,e)}Ee(n.tooltipOptions,c,l),r.elevationInfo=o.elevationInfo}function Je(e){return null==e||"rotate-start"!==e.type&&"rotate"!==e.type&&"rotate-stop"!==e.type?null:e}function He(e){return null==e||"scale-start"!==e.type&&"scale"!==e.type&&"scale-stop"!==e.type?null:e}function Ke(e,t,r,n){if(null==t.geometry||"point"!==t.geometry?.type)return!1;const o=t.attributes;let a=!1;const i=n.rotation,s=Je(r.toolEventInfo);if(null!=i&&null!=s){const{field:r,getValue:n}=i;if("rotate-stop"===s.type)i.isUpdatingInteractively=!1,i.setInitialValue(t.getAttribute(r));else{i.isUpdatingInteractively=!0;const l=n(s.angle,e);l!==o[r]&&t.setAttribute(r,l),a=!0}}const l=n.size,c=He(r.toolEventInfo);if(null!=l&&null!=c){const{field:r,getValue:n}=l;if("scale-stop"===c.type)l.isUpdatingInteractively=!1,l.setInitialValue(t.getAttribute(r));else{l.isUpdatingInteractively=!0;const i=n(c.xScale,e);i!==o[r]&&t.setAttribute(r,i),a=!0}}return a}async function Xe({feature:e,featureClone:t,visualVariableAttributes:r,sketchLayer:n,sketchViewModel:o,view:a,onUpdate:i,webStyleCache:u,addUpdatingPromise:d,addHandle:p}){await ye(t,u,"2d"===a.type?a.scale:null);let y=null;if("2d"===o?.view?.type){const e=f(e=>ye(t,u,e));y=g(()=>o?.view?.scale,t=>e(t))}const m=t.sourceLayer,h=st(a,m);await Qe({graphic:t,sketchLayer:n,sketchViewModel:o,sourceLayer:m,visualVariables:r,webStyleCache:u});let b=null;h.then(e=>b=e).catch(()=>{});const I=r.size,v=r.rotation,T=g(()=>e.attributes,async e=>{let r=!1;for(const n in e){const o=e[n];o!==t.getAttribute(n)&&(t.setAttribute(n,o),null==I||I.isUpdatingInteractively||I.field!==n||I.setInitialValue(o),null==v||v.isUpdatingInteractively||v.field!==n||v.setInitialValue(o),(null==b||b.requiredFields.includes(n))&&(r=!0))}r&&await ye(t,u,"2d"===a.type?a.scale:null)}),S=o.on("update",async e=>{const t=e.graphics[0],s={graphic:t,sketchLayer:n,sketchViewModel:o,sourceLayer:m,visualVariables:r,webStyleCache:u};if("complete"===e.state){if(null===a.activeTool)return Qe(s);const e=new AbortController,t=c(e);return p(t),d(w(()=>null===a.activeTool,e.signal).then(async()=>{if(!e.signal.aborted)return e.abort(),Qe(s)}))}Ke(a,t,e,r)&&await ye(t,u,"2d"===a.type?a.scale:null),i(ct(t),e)}),F=o.on(["undo","redo"],e=>{i(ct(e.graphics[0]),e)});return s([F,S,l(()=>o.cancel()),T,y])}async function Ye(e,t,r,n){e.add(n);const o=r.sourceLayer,i=r.getAttribute(o.objectIdField);let c=null;function u(e){c?.abort(),c=a(async r=>{const n=await st(t,o);m(r),n.setVisibility?.(i,e)})}return await et(t,n),u(!1),s([_e(t,n,e=>u(!e)),l(async()=>{u(!0);try{if(!t.destroyed){const e=await st(t,o).catch(()=>{});e&&!e.destroyed&&await w(()=>!e.updating)}}finally{e.remove(n)}})])}function _e(e,t,r){if("3d"===e.type){const n=new W({graphic:t});return s([e.trackGraphicState(n),g(()=>n.displaying,r)])}return g(()=>t.visible,r)}async function et(e,t){if("3d"===e.type){const r=new W({graphic:t}),n=e.trackGraphicState(r);await w(()=>r.displaying||r.error),n.remove()}else await w(()=>t.visible)}const tt={icon:I(24),text:I(12),line:I(1),viewScaleSizeFactor:100};function rt(e,t,r){let n=!1;return e.filter(e=>!!n||(n=e===t,n)).map(e=>r[e]())}function nt(e,t){e.viewModel.syncFeatureTemplates();const r=e.creationInfo;if("awaiting-feature-creation-info"===t[0].id&&r){const n=r.layer,o=e.viewModel.getTemplatesForLayer(n);1===o.length&&"scene"!==n.type&&(r.template=o[0],t.shift())}return t}function ot(e){return"unknown"===e?null:e}function at(e){e.filesEnabled=!0,e.mode="view",e.capabilities={editing:!0,operations:{add:!0,update:!0,delete:!0}}}const it=e=>e.includes("-stop")||e.includes("vertex-"),st=(e,t)=>{const r="subtype-sublayer"===t.type?t.parent:t;return e.whenLayerView(r)};function lt(e){return"createInteractiveEditSession"in e}function ct(e){const t=e.geometry;if("mesh"===t?.type){const r=e.cloneShallow();return r.attributes=u(e.attributes),r.geometry=t.cloneShallow(),r.geometry.transform=t.transform?.clone()??null,r}return e.clone()}function ut(e){return e.acquireCursor("progress")}async function dt(e,t){const{template:r}=e;if(null==r)return null;if(j(r))return r.load();if(S(r)){const e=(await import("../../editing/sharedTemplates/SharedTemplate.js")).default,n=U(t,{makeSharedTemplateFromJSON:t=>e.fromJSON(t)}),o=await n.getTemplates({templateIds:[r.templateId],featureService:r.featureService});if(0===o.length)throw new i("editor:failed-to-load-template","Unable to load the provided template");return o[0].load()}return r}function pt(e){for(const t of e){const{destinationGraphic:e,destinationField:r,sourceGraphic:n,sourceField:o}=t;e.setAttribute(r,n.getAttribute(o))}}function ft(e){const t=e.templateExecutorInfo?.completionResults;return t?.length?(t.forEach(e=>pt(e.relationships)),t.flatMap(e=>e.edits)):null}function yt(e){if(null==e)return[];if(te(e))return e.data.layers;const t=ne(e)?e.activeWorkflow:e,r=t?.layer;return r?[r]:[]}function mt(){return new i("editing:multiple-layers-not-supported","UpdateFeaturesWorkflow does not support updating features from multiple layers.")}function ht({attributes:e},t){const r=new Set;r.add(t.objectIdField),"uniqueIdFields"in t&&t.uniqueIdFields&&t.uniqueIdFields.length>0&&v(r,t.uniqueIdFields);const n={};for(const o of r)null!=e[o]&&(n[o]=e[o]);if("scene"===t.type&&null!=t.infoFor3D){const r=t.associatedLayer?.globalIdField;null!=r&&(e[r]=e[r])}return n}export{Oe as appendAllUtilityNetworkAssociationRelationships,nt as avoidFeatureTemplateSelectionWithOnlyOneItem,lt as canCreateInteractiveEditSession,ct as cloneGraphicExceptMesh,ke as createLayerIdMap,Ae as createRelationshipKeyMap,me as createToolFromGeometryType,rt as createWorkflowSteps,Re as fetchCandidates,Ze as fetchFullFeatures,Ue as findAllDependencies,xe as findChangesByGlobalId,Pe as findEditorItemForLayer,Ce as findEditorItemForLayerOrThrow,De as findLayerInfo,Ve as generateHashForRelationship,qe as getCreationAttributes,dt as getFullTemplateForCreationInfo,yt as getLayersFromWorkflow,le as getRotationVariableAttribute,ft as getServiceEditsFromWorkflowData,Te as getServiceInfoForLayer,Se as getServiceLayersById,de as getSizeVariableAttribute,se as getVisualVariableAttributes,ie as getVisualVariablesForLayer,We as groupFeaturesByLayer,_ as isBatchAttributeFormViewModel,ee as isCreateFeaturesWorkflow,ae as isParentWorkflow,oe as isSplitFeatureWorkflow,it as isTerminalUpdateEventType,te as isUpdateFeaturesWorkflow,re as isUpdateRecordWorkflow,ne as isUpdateWorkflow,Me as isUtilityNetworkAssociationsTable,ht as makeMinimalAttributes,mt as makeMultipleSourceLayersError,je as orderEditsByRelationshipDependencies,at as prepareAttachmentsForCreateFeaturesWorkflow,pt as setRelationshipFields,Xe as setUpGeometryUpdate,ge as setUpSketchCreateWatchers,$e as setVisualVariablesAndElevationInfoForUpdate,ut as showProgressCursor,tt as sizeDefaults,ot as sizeVariableUnitToLengthUnit,he as startCreatingNewFeature,Qe as startUpdatingFeatureGeometry,Ye as swapForEditingSession,ye as updateGraphicSymbolWhenRequired,Ke as visualVariableInteractiveUpdate,st as whenEditorLayerView,et as whenGraphicDisplayed};
|
|
5
|
+
import e from"../../Color.js";import t from"../../Graphic.js";import{isSome as r,equals as n,addMany as o}from"../../core/arrayUtils.js";import{createTask as a}from"../../core/asyncUtils.js";import"../../core/has.js";import i from"../../core/Error.js";import{handlesGroup as s,makeHandle as l,abortHandle as c}from"../../core/handleUtils.js";import{clone as u}from"../../core/lang.js";import d from"../../core/Logger.js";import{getOrCreateMapValue as p}from"../../core/MapUtils.js";import{debounce as f,isPromiseLike as y,throwIfAborted as m,whenOrAbort as h}from"../../core/promiseUtils.js";import{watch as g,on as b,whenOnce as w}from"../../core/reactiveUtils.js";import{px2pt as I}from"../../core/screenUtils.js";import{addMany as v}from"../../core/SetUtils.js";import{diff as T}from"../../core/accessorSupport/diffUtils.js";import{isSharedTemplateOrMetadata as S,isSharedGroupTemplate as F,isSharedTemplate as k,isSharedPresetTemplate as j,isStandardFeatureTemplate as A,isSharedFeatureTemplate as L}from"../../editing/templateUtils.js";import{getSharedTemplateProvider as U}from"../../editing/sharedTemplates/SharedTemplateProvider.js";import V from"../../layers/GraphicsLayer.js";import{featureHasFields as M,fixFields as O,getDisplayFieldName as x}from"../../layers/support/fieldUtils.js";import{isSubtypeSublayer as q}from"../../layers/support/layerUtils.js";import{calculateTolerance as z}from"../../renderers/support/clickToleranceUtils.js";import{meterIn as E}from"../../renderers/support/lengthUtils.js";import{isRenderer as P}from"../../renderers/support/typeUtils.js";import{getTransformationType as C}from"../../renderers/visualVariables/support/sizeVariableUtils.js";import D from"../../symbols/SimpleFillSymbol.js";import R from"../../symbols/SimpleLineSymbol.js";import G from"../../symbols/SimpleMarkerSymbol.js";import{to3D as B}from"../../symbols/support/symbolConversion.js";import{getDisplayedSymbol as N}from"../../symbols/support/symbolUtils.js";import{getServices as Z}from"../../undoredo/support/Services.js";import{GraphicState as W}from"../../views/3d/layers/graphics/GraphicState.js";import{defaultDrawingMode as Q}from"../../views/draw/DrawingMode.js";import{createQueryGeometry as $}from"../../views/support/drapedUtils.js";import{filterGraphicHits as J,hitTestSelectSimilarDistance as H}from"../../views/support/hitTestSelectUtils.js";import{dependencySort as K}from"./support/dependencySort.js";import{isDrawGraphicTool as X}from"../Sketch/support/sketchUtils.js";const Y=()=>d.getLogger("esri.widgets.Editor.workflowUtils");function _(e){return!!e&&"features"in e}function ee(e){return null!=e&&"create-features"===e.type}function te(e){return null!=e&&"update-features"===e.type}function re(e){return null!=e&&e.type.includes("update-")&&"fullFeature"in e}function ne(e){return null!=e&&"update"===e.type}function oe(e){return null!=e&&"split-feature"===e.type}function ae(e){const t=e?.type;return"update-feature"===t||"update-table-record"===t||"split-feature"===t}function ie(e){const t=e&&"renderer"in e?e.renderer:null;if(!fe(t))return{rotation:null,size:null};const r=t.getVisualVariablesForType("rotation").filter(e=>(!e.axis||"heading"===e.axis)&&e.field&&!e.valueExpression),n=t.getVisualVariablesForType("size").filter(e=>e.field&&!e.useSymbolValue&&!e.valueExpression&&"real-world-size"===C(e));return{rotation:1===r.length?r[0]:null,size:1===n.length?n[0]:null}}function se(e){const t=e.sourceLayer;if(!(t&&"renderer"in t&&fe(t.renderer)))return{rotation:null,size:null};const{rotation:r,size:n}=ie(t);let o=null,a=null;if(r){const e=t.fields?.filter(e=>e.name===r.field),n=1===e?.length?e[0]:null;o=le(r,n)}if(n){const e=t.fields?.filter(e=>e.name===n.field),r=1===e?.length?e[0]:null;a=de(n,r)}return{rotation:o,size:a}}function le(e,t){const r="heading"===(e.axis||"heading")&&"arithmetic"===e.rotationType?-1:1,n=t?.type??"double",o={initial:0,current:0};return{field:e.field,fieldType:n,getDefaultValue:()=>Promise.resolve(0),getValue:e=>(o.current=o.initial-r*e,pe((o.current+360)%360,n)),setInitialValue:e=>{o.initial=e,o.current=0},isUpdatingInteractively:!1,rotationType:e.rotationType??"geographic"}}function ce(e,t){switch(t){case"width":return e[0];case"depth":return e[1];case"height":return e[2];default:return e[2]||e[1]||e[0]}}async function ue(e,t,r){if(null==t)return 0;const{symbol:n}=B(t);if(null==n||"web-style"===n.type||"cim"===n.type)return 0;const o=n.symbolLayers.at(0);if(!o)return 0;switch(o.type){case"icon":{const{computeIconLayerResourceSize:e}=await import("../../symbols/support/symbolLayerUtils.js");return Math.min(tt.icon,(await e(o,tt.icon))[0])||tt.icon}case"text":return tt.text;case"line":return tt.line;case"object":{const{computeObjectLayerResourceSize:t}=await import("../../symbols/support/symbolLayerUtils.js");return ce(await t(o,e.scale/tt.viewScaleSizeFactor),r)}case"path":case"extrude":return e.scale/tt.viewScaleSizeFactor;default:return 0}}function de(e,t){const r=e.axis,n=t?.type??"double",o={initial:0,current:0},a=E[e.valueUnit]??1;let i;return i="area"===e.valueRepresentation?e=>(e*a/2)**2*Math.PI:"radius"===e.valueRepresentation||"distance"===e.valueRepresentation?e=>e*a/2:e=>e*a,{field:e.field,fieldType:n,getDefaultValue:async(e,t)=>pe(i(await ue(t,e,r)),n),getValue:(e,t)=>(o.initial||(o.initial=t.pixelSizeAt(t.center)),o.current=o.initial*e,pe(o.current,n)),setInitialValue:e=>{o.initial=e,o.current=0},isUpdatingInteractively:!1,displayUnit:ot(e.valueUnit),axis:e.axis}}function pe(e,t){switch(t){case"small-integer":case"integer":case"long":return Math.round(e);case"double":case"single":return e;default:return 0}}function fe(e){if(!P(e))return!1;switch(e?.type){case"class-breaks":case"simple":case"unique-value":case"dot-density":case"dictionary":case"pie-chart":return!0;default:return!1}}async function ye(e,t,r){const n=await N(e,{useSourceLayer:!0,ignoreGraphicSymbol:!0,webStyleCache:t,scale:r});null!=T(e.symbol,n)&&(e.symbol=n)}function me(e,t){if(!e||!t)throw new Error("no geometry type");if("multipatch"===e)return{tool:"mesh",createOptions:{mode:"hybrid"}};const r=new Map;r.set("circle",{mode:"freehand"}),r.set("rectangle",{mode:"freehand"});const n={mode:Q,optionsPerTool:r};if(S(t)){const o=t.defaultTool,a=F(t)?t.definition?.inputGeometryType??e:e;switch(o){case"freehand":case"stream-line":return{tool:"polyline"===a?"freehandPolyline":"freehandPolygon",createOptions:n};case"autocomplete-freehand-polygons":case"stream-polygon":return{tool:"freehandPolygon",createOptions:n};case"autocomplete-polygons":case"difference-polygon":case"create-structures":case"polygon":case"trace":return{tool:"polygon"===a?"polygon":"polyline",createOptions:n};case"circle":return r.get("circle").preserveAspectRatio=!0,{tool:"circle",createOptions:n};case"ellipse":return r.get("circle").preserveAspectRatio=!1,{tool:"circle",createOptions:n};case"create-points-along-line":case"multipoint":return{tool:"multipoint",createOptions:n};case"line":case"radial-line":case"right-angle-line":case"split":case"two-point-line":return{tool:"polyline",createOptions:n};case"rectangle":case"regular-polygon":case"right-angle-polygon":return{tool:"rectangle",createOptions:n};case"elevation-point-from-contour":case"elevation-point-from-dem":case"parcel-seed":case"point":case"point-and-rotation":case"point-at-end-of-line":return{tool:"point",createOptions:n}}}else{const o=t.drawingTool;if("circle"===o||"ellipse"===o)return r.get("circle").preserveAspectRatio="circle"===o,{tool:"circle",createOptions:n};if("rectangle"===o)return{tool:"rectangle",createOptions:n};if("freehand"===o)return{tool:"polygon"===e?"freehandPolygon":"freehandPolyline",createOptions:n}}return{tool:e,createOptions:n}}async function he(e,t,r,n){const{creationInfo:o,fullTemplate:a}=r;if(!o)throw new i("featureworkflow","No creation info provided.");const s=o.layer,l=qe(a,o.attributeOverrides),{view:c}=e,u="2d"===c?.type;F(a)||j(a)||await ze(e,s,l,n,u?c.scale:null);const{capabilities:d}=s;t.elevationInfo=s.elevationInfo;const p=me(s.geometryType,a);e.defaultCreateOptions={graphicProperties:{attributes:l,sourceLayer:s},mode:p.createOptions.mode,optionsPerTool:p.createOptions.optionsPerTool,preserveAspectRatio:p.createOptions.preserveAspectRatio,hasZ:d.data.supportsZ,defaultZ:(u?d.editing.zDefault:null)??e.defaultCreateOptions.defaultZ},null==o.geometryToPlace?await e.create(p.tool):await e.place(o.geometryToPlace,{graphicProperties:{attributes:l,sourceLayer:s}})}async function ge(e){return s([be(e),we(e)])}function be({creationAttributes:e,data:t,sketchViewModel:r,view:n,webStyleCache:o}){const{creationInfo:a}=t,{fullTemplate:i}=t;if(!a||"2d"!==n?.type||F(i)||j(i))return null;const s=f(t=>ze(r,a.layer,e,o,t));return g(()=>n.scale,e=>s(e))}function we({data:t,sketchViewModel:r,view:n}){const{templateExecutorInfo:o}=t;if(!o)return null;const a=r.activeComponent;if(!n||!X(a))return Y().error(new i("featureworkflow","Failed to set up template feedback.")),null;const c=new V({effect:"saturate(0.6) opacity(0.8)",listMode:"hide",title:"Shared Template Feedback Graphics"});n.map?.add(c);const{executor:u,serviceLayersById:d}=o,p=n.theme?.accentColor??new e([255,165,0,1]);return s([b(()=>a,["cursor-update","vertex-add"],()=>{c.removeAll();const e=a.graphic?.geometry;if(!e||!Ie(e))return;const t=u(e,"digitizing");if(!y(t))for(const r of t.edits){const e=d.get(r.id);if(e&&r.addFeatures&&0!==r.addFeatures.length)for(const t of e)if(!t.isTable)for(const e of r.addFeatures){const t=ve(e,p);t&&c.add(t)}}}),l(()=>{n.map.remove(c),c.destroy()})])}function Ie(e){switch(e.type){case"point":case"multipoint":return!0;case"polyline":return e.paths[0].length>1;case"polygon":{const t=e.rings[0];return n(t.at(0),t.at(-1))?t.length>2:t.length>1}default:return!1}}function ve(e,r){let n=null;switch(e.geometry?.type){case"point":case"multipoint":n=new G({angle:0,color:r,outline:new R({cap:"round",color:r,join:"round",miterLimit:1,style:"solid",width:1}),path:"undefined",size:8,style:"circle",xoffset:0,yoffset:0});break;case"polygon":n=new D({color:r,outline:new R({cap:"round",color:r,join:"round",miterLimit:1,style:"solid",width:3}),style:"none"});break;case"polyline":n=new R({cap:"round",color:r,join:"round",miterLimit:1,style:"solid",width:2});break;default:return null}return new t({geometry:e.geometry,symbol:n,attributes:{...e.attributes}})}async function Te(e,t){const r=await Z(t).load(),n=q(e)?e.parent:e;return r.tablesAndLayersLookup.get(n)}async function Se(e,t){const r=await Te(e,t);if(!r)return new Map;const n=new Map;for(const o of r.layersAndTables)p(n,o.layerId,()=>[]).push(o);return n}function Fe(e){const t=e.objectIdField,r=e.globalIdField??"";return{id:e.layerId,identifierFields:{objectIdField:t,globalIdField:r},addFeatures:[],deleteAttachments:[],addAttachments:[],deleteFeatures:[],updateFeatures:[]}}function ke(e){const{edits:t,serviceInfo:n,view:o,findOriginalFeature:a}=e,i=je(n.layersAndTables),s=n.layersAndTables.toArray(),{allEditData:l,editDataByLayerIdMap:c,editDataByIdMap:u}=Le(t,i,a),d=Ue(l,Ae(s,c),c);if(o&&Oe(l,d,o),0===d.length)return t;const p=K(d,{continueOnCircularDependency:!0}).map(e=>u.get(e)).filter(r),f=new Map;for(const r of p)f.set(r.uniqueId,r);const y=[];for(const r of l)f.has(r.uniqueId)||y.push(r);const m=[];let h=null;for(const r of p){const{layer:e}=r;switch(null==h?h=Fe(e):h.id!==e.layerId&&(m.push(h),h=Fe(e)),r.operationType){case"add":case"modify":h.addFeatures.push(r.after);break;case"delete":h.deleteFeatures.push(r.before)}}null!==h&&m.push(h);for(const r of y){const e=r.layer.layerId,t=m.find(t=>t.id===e)??Fe(r.layer);switch(m.includes(t)||m.push(t),r.operationType){case"add":t.addFeatures.push(r.after);break;case"modify":t.updateFeatures.push(r.after);break;case"delete":t.deleteFeatures.push(r.before);break;case"deleteAttachment":t.deleteAttachments.push(r.attachmentId);break;case"addAttachment":t.addAttachments.push(r.attachment)}}for(const r of m)void 0!==r.deleteAttachments&&0===r.deleteAttachments.length&&delete r.deleteAttachments,void 0!==r.addAttachments&&0===r.addAttachments.length&&delete r.addAttachments;return m}function je(e){const t=new Map;for(const r of e)t.set(r.layerId,r);return t}function Ae(e,t){const r=new Map;for(const n of e)for(const e of n.relationships??[])if(r.set(Ve(n,e),""),t.has(e.relatedTableId)){const o=t.get(e.relatedTableId);if(o.length>0)for(const t of o[0].layer.relationships??[])if(t.id===e.id){r.set(Ve(n,e),t.keyField);break}}return r}function Le(e,t,r){const n=new Map,o=[],a=new Map;let s=1;for(const l of e){const e=[],c=t.get(l.id);if(!c)throw new i("featureworkflow",`Failed to prepare applyEdits payload. Layer with id ${l.id} not found.`);for(const t of l.addFeatures??[])e.push({uniqueId:"T"+s++,operationType:"add",layer:c,after:t});for(const t of l.deleteFeatures??[])e.push({uniqueId:"T"+s++,operationType:"delete",before:t,layer:c});for(const t of l.deleteAttachments??[])e.push({uniqueId:"T"+s++,operationType:"deleteAttachment",attachmentId:t,layer:c});for(const t of l.addAttachments??[])e.push({uniqueId:"T"+s++,operationType:"addAttachment",attachment:t,layer:c});for(const t of l.updateFeatures??[])e.push({uniqueId:"T"+s++,operationType:"modify",before:r(t),after:t,layer:c});n.set(c.layerId,e);for(const t of e)o.push(t),a.set(t.uniqueId,t)}return{allEditData:o,editDataByIdMap:a,editDataByLayerIdMap:n}}function Ue(e,t,r){const n=[];for(const o of e){const e=o.layer.relationships??[],{uniqueId:a}=o;for(const i of e){const e=i.keyField;if("origin"===i.role){const s=r.get(i.relatedTableId);if(!s||0===s.length)continue;const l=Ve(o.layer,i),c=t.get(l);if(void 0===c||""===c)continue;switch(o.operationType){case"add":for(const t of s)t!==o&&("add"!==t.operationType&&"modify"!==t.operationType||t.after.attributes[c]===o.after.attributes[e]&&n.push([a,t.uniqueId]));break;case"modify":if(o.before.attributes[e]!==o.after.attributes[e])for(const t of s){const r=t.uniqueId;t!==o&&("delete"===t.operationType?t.before.attributes[c]===o.before.attributes[e]?n.push([r,a]):t.before.attributes[c]===o.after.attributes[e]&&n.push([a,r]):"add"===t.operationType?t.after.attributes[c]===o.after.attributes[e]?n.push([a,r]):t.after.attributes[c]===o.before.attributes[e]&&n.push([r,a]):"modify"===t.operationType&&(t.before.attributes[c]!==t.after.attributes[c]?t.after.attributes[c]===o.after.attributes[e]?n.push([a,r]):n.push([r,a]):n.push([a,r])))}break;case"delete":for(const t of s)t!==o&&("delete"!==t.operationType&&"modify"!==t.operationType||t.before.attributes[c]===o.before.attributes[e]&&n.push([t.uniqueId,a]))}}}}return n}function Ve(e,t){return`${e.layerId}:${t.id}`}function Me(e,t){return!!(t?.map&&"utilityNetworks"in t.map&&t.map.utilityNetworks?.length&&t.map.utilityNetworks.some(t=>!(!t.loaded||!e.url?.startsWith(t.featureServiceUrl)||e.layerId!==t.networkSystemLayers.associationsTableId)))}function Oe(e,t,r){const n=[];for(const a of e)Me(a.layer,r)&&n.push(a);if(0===n.length)return;let o=[];for(const a of n){const r=a.layer;switch(a.operationType){case"delete":o=[...xe(a.before.attributes[r.fieldsIndex.get("fromglobalid").name],e),...xe(a.before.attributes[r.fieldsIndex.get("toglobalid").name],e)];for(const e of o)t.push([a.uniqueId,e.uniqueId]);break;case"add":o=[...xe(a.after.attributes[r.fieldsIndex.get("fromglobalid").name],e),...xe(a.after.attributes[r.fieldsIndex.get("toglobalid").name],e)];for(const e of o)t.push([e.uniqueId,a.uniqueId])}}}function xe(e,t){const r=[],n=t.filter(({layer:e})=>""!==e.globalIdField&&null!=e.globalIdField);for(const o of n){const t=o.layer.globalIdField;("before"in o&&o.before?.attributes[t]===e||"after"in o&&o.after?.attributes[t]===e)&&r.push(o)}return r}function qe(e,t={}){return F(e)||j(e)?{}:A(e)?{...e.prototype.attributes,...t}:L(e)?{...e.definition?.defaultValues,...t}:{...t}}async function ze(e,r,n,o,a){const i=new t({sourceLayer:r,attributes:n}),{rotation:s,size:l}=se(i);let c=await N(i,{useSourceLayer:!0,webStyleCache:o,scale:a}),u=!1;for(const t of[l,s]){if(null==t)continue;null==n[t.field]&&(n[t.field]=await t.getDefaultValue(c,e.view),u=!0)}switch(u&&(c=await N(i,{useSourceLayer:!0,webStyleCache:o,scale:a})),c?.type){case"simple-fill":case"polygon-3d":e.polygonSymbol=c;break;case"simple-line":case"line-3d":e.polylineSymbol=c;break;case"simple-marker":case"picture-marker":case"point-3d":case"cim":e.pointSymbol=c;break;case"mesh-3d":e.meshSymbol=c}Ee(e.tooltipOptions,l,s)}function Ee(e,t,r){e.visualVariables=null!=t||null!=r?{size:null!=t?{unit:t.displayUnit,axis:t.axis,valueType:t.fieldType}:null,rotation:null!=r?{valueType:r.fieldType,rotationType:r.rotationType??"geographic"}:null}:null}function Pe(e,t){return e.find(e=>e.layer===t)}function Ce(e,t){const r=Pe(e,t);if(null==r)throw new i("no-editorItem-found","The EditorViewModel provided did not have an EditorItem associated with the specified layer");return r}function De(e,t){return e?.find(e=>e.layer===t)}async function Re(e,t,r,n){switch(t.type){case"3d":return Ge(e,t,r,n);case"2d":return Be(e,t,r,n)}}async function Ge(e,t,r,n){if(0===e.length)return[];const{updatable:a,graphicsByLayer:i}=await r.defer(async()=>{const{results:o}=await h(H(t,r),n),a=new Map,i=e=>{const t=e.layer,r=a.get(t);if(!r){const e=new Array;return a.set(t,e),e}return r};J(o).forEach(({graphic:e})=>i(e).push(e));const s=e.filter(({capabilities:e,layer:t})=>e.update.enabled&&a.has(t));return 0!==s.length&&r.stopPropagation(),{updatable:s,graphicsByLayer:a}});return h(Promise.allSettled(a.map(async({layer:e})=>{const t=i.get(e),r=Ne(e);if(t.every(e=>M(e,r)))return t;const a=[];for(const n of t){a.push(n.getObjectId());const e=Object.keys(n.attributes);o(r,e)}const s=e.createQuery();return s.returnGeometry=!1,s.objectIds=a,s.outFields=O(e.fieldsIndex,r),e.queryFeatures(s,{signal:n}).then(({features:e})=>e)})),n)}async function Be(e,t,r,n){if(0===e.length)return[];const{mapPoint:o}=r;if(null==o)return[];let a=null;const i=await r.defer(async()=>{const{results:o}=await h(t.hitTest(r),n);if(0===o.length)return[];const i=new Set;a=J(o),a.forEach(({graphic:e})=>e&&i.add(e.layer));const s=e.filter(e=>i.has(e.layer)&&e.supportsUpdateWorkflow);return s.length>0&&r.stopPropagation(),s});return h(Promise.allSettled(i.map(async({layer:e})=>{const i=e.createQuery();i.returnGeometry=!0,i.outFields=Ne(e);const s="renderer"in e?z({renderer:e.renderer,pointerType:r.pointerType}):0;i.geometry=$(o,s,t),i.outSpatialReference=t.spatialReference;const{features:l}=await e.queryFeatures(i,{signal:n});return a?.forEach(({graphic:t})=>{t.layer!==e||l.some(e=>e.getObjectId()===t.getObjectId())||l.push(t)}),l})),n)}function Ne(e){return O(e.fieldsIndex,[e.objectIdField,x({displayField:"displayField"in e?e.displayField:null,fields:e.fields})])}async function Ze(e,t,n,o){const a=t.createQuery();a.objectIds=e.map(e=>e.getObjectId()).filter(r),a.outFields=["*"],a.returnM=t.capabilities.data.supportsM,a.returnZ=t.capabilities.data.supportsZ,"scene"===t.type&&null!=t.infoFor3D||(a.outSpatialReference=n);const i=await t.queryFeatures(a,{signal:o});return m(o),i.features}function We(e){const t=new Map;for(const r of e){const e=r.sourceLayer,n=q(e)?e.parent:e;p(t,n,()=>[]).push(r)}return t}async function Qe(e){const{graphic:t,sketchViewModel:r,sourceLayer:n,visualVariables:o}=e;await $e(e);const a={multipleSelectionEnabled:!1};return"point"===n.geometryType&&(a.enableRotation=null!=o.rotation,a.enableScaling=null!=o.size),r.update(t,a)}async function $e(e){const{graphic:t,sketchLayer:r,sketchViewModel:n,sourceLayer:o,visualVariables:a,webStyleCache:i}=e;let s=!1;const{rotation:l,size:c}=a;for(const u of[l,c]){if(null==u)continue;const e=t.getAttribute(u.field);if(null!=e)u.setInitialValue(e);else{const e=await u.getDefaultValue(t.symbol,n.view);u.setInitialValue(e),t.setAttribute(u.field,e),s=!0}}if(s){const e="2d"===n.view?.type?n.view.scale:null;await ye(t,i,e)}Ee(n.tooltipOptions,c,l),r.elevationInfo=o.elevationInfo}function Je(e){return null==e||"rotate-start"!==e.type&&"rotate"!==e.type&&"rotate-stop"!==e.type?null:e}function He(e){return null==e||"scale-start"!==e.type&&"scale"!==e.type&&"scale-stop"!==e.type?null:e}function Ke(e,t,r,n){if(null==t.geometry||"point"!==t.geometry?.type)return!1;const o=t.attributes;let a=!1;const i=n.rotation,s=Je(r.toolEventInfo);if(null!=i&&null!=s){const{field:r,getValue:n}=i;if("rotate-stop"===s.type)i.isUpdatingInteractively=!1,i.setInitialValue(t.getAttribute(r));else{i.isUpdatingInteractively=!0;const l=n(s.angle,e);l!==o[r]&&t.setAttribute(r,l),a=!0}}const l=n.size,c=He(r.toolEventInfo);if(null!=l&&null!=c){const{field:r,getValue:n}=l;if("scale-stop"===c.type)l.isUpdatingInteractively=!1,l.setInitialValue(t.getAttribute(r));else{l.isUpdatingInteractively=!0;const i=n(c.xScale,e);i!==o[r]&&t.setAttribute(r,i),a=!0}}return a}async function Xe({feature:e,featureClone:t,visualVariableAttributes:r,sketchLayer:n,sketchViewModel:o,view:a,onUpdate:i,webStyleCache:u,addUpdatingPromise:d,addHandle:p}){await ye(t,u,"2d"===a.type?a.scale:null);let y=null;if("2d"===o?.view?.type){const e=f(e=>ye(t,u,e));y=g(()=>o?.view?.scale,t=>e(t))}const m=t.sourceLayer,h=st(a,m);await Qe({graphic:t,sketchLayer:n,sketchViewModel:o,sourceLayer:m,visualVariables:r,webStyleCache:u});let b=null;h.then(e=>b=e).catch(()=>{});const I=r.size,v=r.rotation,T=g(()=>e.attributes,async e=>{let r=!1;for(const n in e){const o=e[n];o!==t.getAttribute(n)&&(t.setAttribute(n,o),null==I||I.isUpdatingInteractively||I.field!==n||I.setInitialValue(o),null==v||v.isUpdatingInteractively||v.field!==n||v.setInitialValue(o),(null==b||b.requiredFields.includes(n))&&(r=!0))}r&&await ye(t,u,"2d"===a.type?a.scale:null)}),S=o.on("update",async e=>{const t=e.graphics[0],s={graphic:t,sketchLayer:n,sketchViewModel:o,sourceLayer:m,visualVariables:r,webStyleCache:u};if("complete"===e.state){if(null===a.activeTool)return Qe(s);const e=new AbortController,t=c(e);return p(t),d(w(()=>null===a.activeTool,e.signal).then(async()=>{if(!e.signal.aborted)return e.abort(),Qe(s)}))}Ke(a,t,e,r)&&await ye(t,u,"2d"===a.type?a.scale:null),i(ct(t),e)}),F=o.on(["undo","redo"],e=>{i(ct(e.graphics[0]),e)});return s([F,S,l(()=>o.cancel()),T,y])}async function Ye(e,t,r,n){e.add(n);const o=r.sourceLayer,i=r.getAttribute(o.objectIdField);let c=null;function u(e){c?.abort(),c=a(async r=>{const n=await st(t,o);m(r),n.setVisibility?.(i,e)})}return await et(t,n),u(!1),s([_e(t,n,e=>u(!e)),l(async()=>{u(!0);try{if(!t.destroyed){const e=await st(t,o).catch(()=>{});e&&!e.destroyed&&await w(()=>!e.updating)}}finally{e.remove(n)}})])}function _e(e,t,r){if("3d"===e.type){const n=new W({graphic:t});return s([e.trackGraphicState(n),g(()=>n.displaying,r)])}return g(()=>t.visible,r)}async function et(e,t){if("3d"===e.type){const r=new W({graphic:t}),n=e.trackGraphicState(r);await w(()=>r.displaying||r.error),n.remove()}else await w(()=>t.visible)}const tt={icon:I(24),text:I(12),line:I(1),viewScaleSizeFactor:100};function rt(e,t,r){let n=!1;return e.filter(e=>!!n||(n=e===t,n)).map(e=>r[e]())}function nt(e,t){e.viewModel.syncFeatureTemplates();const r=e.creationInfo;if("awaiting-feature-creation-info"===t[0].id&&r){const n=r.layer,o=e.viewModel.getTemplatesForLayer(n);1===o.length&&"scene"!==n.type&&(r.template=o[0],t.shift())}return t}function ot(e){return"unknown"===e?null:e}function at(e){e.filesEnabled=!0,e.mode="view",e.capabilities={editing:!0,operations:{add:!0,update:!0,delete:!0}}}const it=e=>e.includes("-stop")||e.includes("vertex-"),st=(e,t)=>{const r="subtype-sublayer"===t.type?t.parent:t;return e.whenLayerView(r)};function lt(e){return"createInteractiveEditSession"in e}function ct(e){const t=e.geometry;if("mesh"===t?.type){const r=e.cloneShallow();return r.attributes=u(e.attributes),r.geometry=t.cloneShallow(),r.geometry.transform=t.transform?.clone()??null,r}return e.clone()}function ut(e){return e.acquireCursor("progress")}async function dt(e,t){const{template:r}=e;if(null==r)return null;if(k(r))return r.load();if(S(r)){const e=(await import("../../editing/sharedTemplates/SharedTemplate.js")).default,n=U(t,{makeSharedTemplateFromJSON:t=>e.fromJSON(t)}),o=await n.getTemplates({templateIds:[r.templateId],featureService:r.featureService});if(0===o.length)throw new i("editor:failed-to-load-template","Unable to load the provided template");return o[0].load()}return r}function pt(e){for(const t of e){const{destinationGraphic:e,destinationField:r,sourceGraphic:n,sourceField:o}=t;e.setAttribute(r,n.getAttribute(o))}}function ft(e){const t=e.templateExecutorInfo?.completionResults;return t?.length?(t.forEach(e=>pt(e.relationships)),t.flatMap(e=>e.edits)):null}function yt(e){if(null==e)return[];if(te(e))return e.data.layers;const t=ne(e)?e.activeWorkflow:e,r=t?.layer;return r?[r]:[]}function mt(){return new i("editing:multiple-layers-not-supported","UpdateFeaturesWorkflow does not support updating features from multiple layers.")}function ht({attributes:e},t){const r=new Set;r.add(t.objectIdField),"uniqueIdFields"in t&&t.uniqueIdFields&&t.uniqueIdFields.length>0&&v(r,t.uniqueIdFields);const n={};for(const o of r)null!=e[o]&&(n[o]=e[o]);if("scene"===t.type&&null!=t.infoFor3D){const r=t.associatedLayer?.globalIdField;null!=r&&(e[r]=e[r])}return n}function gt(e){if(!e.supportsSplitFeatureWorkflow)throw new i("editing:unsupported-workflow","Split feature workflow requires that both creating features and updating their geometries are allowed.")}export{Oe as appendAllUtilityNetworkAssociationRelationships,gt as assertSplitWorkflowCapabilities,nt as avoidFeatureTemplateSelectionWithOnlyOneItem,lt as canCreateInteractiveEditSession,ct as cloneGraphicExceptMesh,je as createLayerIdMap,Ae as createRelationshipKeyMap,me as createToolFromGeometryType,rt as createWorkflowSteps,Re as fetchCandidates,Ze as fetchFullFeatures,Ue as findAllDependencies,xe as findChangesByGlobalId,Pe as findEditorItemForLayer,Ce as findEditorItemForLayerOrThrow,De as findLayerInfo,Ve as generateHashForRelationship,qe as getCreationAttributes,dt as getFullTemplateForCreationInfo,yt as getLayersFromWorkflow,le as getRotationVariableAttribute,ft as getServiceEditsFromWorkflowData,Te as getServiceInfoForLayer,Se as getServiceLayersById,de as getSizeVariableAttribute,se as getVisualVariableAttributes,ie as getVisualVariablesForLayer,We as groupFeaturesByLayer,_ as isBatchAttributeFormViewModel,ee as isCreateFeaturesWorkflow,ae as isParentWorkflow,oe as isSplitFeatureWorkflow,it as isTerminalUpdateEventType,te as isUpdateFeaturesWorkflow,re as isUpdateRecordWorkflow,ne as isUpdateWorkflow,Me as isUtilityNetworkAssociationsTable,ht as makeMinimalAttributes,mt as makeMultipleSourceLayersError,ke as orderEditsByRelationshipDependencies,at as prepareAttachmentsForCreateFeaturesWorkflow,pt as setRelationshipFields,Xe as setUpGeometryUpdate,ge as setUpSketchCreateWatchers,$e as setVisualVariablesAndElevationInfoForUpdate,ut as showProgressCursor,tt as sizeDefaults,ot as sizeVariableUnitToLengthUnit,he as startCreatingNewFeature,Qe as startUpdatingFeatureGeometry,Ye as swapForEditingSession,ye as updateGraphicSymbolWhenRequired,Ke as visualVariableInteractiveUpdate,st as whenEditorLayerView,et as whenGraphicDisplayed};
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
|
|
3
3
|
See https://js.arcgis.com/4.34/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
import{__decorate as e}from"tslib";import{getAssetUrl as t}from"../../assets.js";import r from"../../Graphic.js";import s from"../../PopupTemplate.js";import{isSome as o}from"../../core/arrayUtils.js";import i from"../../core/Collection.js";import l from"../../core/Error.js";import{EventedAccessor as a}from"../../core/Evented.js";import n from"../../core/Logger.js";import{mappedFind as u}from"../../core/maybe.js";import{eachAlways as c,after as h}from"../../core/promiseUtils.js";import{watch as p,initial as g,whenOnce as d}from"../../core/reactiveUtils.js";import{property as m}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import{subclass as y}from"../../core/accessorSupport/decorators/subclass.js";import f from"../../geometry/Point.js";import S from"../../geometry/SpatialReference.js";import{getPointFromGeometry as _,getPointWithElevation as v}from"../../geometry/support/geometryUtils.js";import w from"../../portal/Portal.js";import{isApiKeyApplicable as b}from"../../support/apiKeyUtils.js";import x from"../../symbols/PictureMarkerSymbol.js";import L from"../../symbols/SimpleFillSymbol.js";import I from"../../symbols/SimpleLineSymbol.js";import T from"../../symbols/TextSymbol.js";import{highlightsSupported as R}from"../../views/support/layerViewUtils.js";import E from"./LayerSearchSource.js";import F from"./LocatorSearchSource.js";import P from"./SearchSource.js";import{isArcGISWorldGeocoder as j,meteredArcGISLocatorUrl as C,isProxiedArcGISWorldGeocoder as G,isMeteredArcGISWorldGeocoder as O}from"./support/locatorUtils.js";import{supported as A,getCurrentPosition as N,positionToPoint as D}from"../support/geolocationUtils.js";import{GoTo as M}from"../support/GoTo.js";function V(e,t){return e.hasOwnProperty(t)&&null!=e[t]&&""!==e[t]}const J="highlight",U=i.ofType({key:e=>e.layer?"layer":"locator",base:P,typeMap:{layer:E,locator:F}}),k=S.WGS84,H="esri/images/search/search-symbol-32.png",B=/<[\s\S]*?>/g,Q=-1;let Z=class extends(M(a)){constructor(e){super(e),this._defaultPopupTemplate=new s({content:"{Match_addr}"}),this._gotoController=null,this._searching=null,this._updatingPromise=null,this._createdFeatureLayers=[],this.autoNavigate=!0,this.autoSelect=!0,this.defaultSources=new U,this.defaultSymbols={point:new x({url:t(H),size:24,width:24,height:24}),polyline:new I({color:[130,130,130,1],width:2}),polygon:new L({color:[235,235,235,.4],outline:{color:[130,130,130,1],width:2}})},this.includeDefaultSources=!0,this.maxInputLength=128,this.maxResults=6,this.maxSuggestions=6,this.messages=null,this.minSuggestCharacters=3,this.popupEnabled=!0,this.popupTemplate=null,this.portal=w.getDefault(),this.resultCount=null,this.resultGraphicEnabled=!0,this.resultGraphic=null,this.results=null,this.selectedSuggestion=null,this.searchAllEnabled=!0,this.selectedResult=null,this.sources=new U,this.suggestionDelay=350,this.suggestionCount=null,this.suggestions=null,this.suggestionsEnabled=!0,this.view=null}initialize(){this.addHandles([p(()=>[this.includeDefaultSources,this.view,this.portal],()=>this._update(),g),p(()=>this.messages,()=>{this._defaultPopupTemplate.title=this.messages?.searchResult??"",this._update()},g)])}destroy(){this._destroyFeatureLayers(),this._abortGoTo(),this.clearGraphics()}static{this.ALL_INDEX=Q}get activeSource(){return this.allSources.at(this.activeSourceIndex)??null}get activeSourceIndex(){return 1===this.allSources.length||!this.searchAllEnabled?0:Q}set activeSourceIndex(e){this._overrideIfSome("activeSourceIndex",e)}get allPlaceholder(){return this.messages?.allPlaceholder}set allPlaceholder(e){this._overrideIfSome("allPlaceholder",e)}get allSources(){const{sources:e,defaultSources:t,includeDefaultSources:r}=this,s="function"==typeof r?r.call(null,{sources:e,defaultSources:t}):r?t.concat(e):e,o=this._get("allSources")||new U;return o.removeAll(),o.addMany(s.filter(Boolean)),o}get defaultPopupTemplate(){return this._defaultPopupTemplate}set defaultPopupTemplate(e){this._overrideIfSome("defaultPopupTemplate",e)}get locationEnabled(){return this._get("locationEnabled")||A()}set locationEnabled(e){if(void 0===e)return void this._clearOverride("locationEnabled");const t=A();if(e&&!t){const e=new l("locationEnabled:geolocation-unsupported","Geolocation API is unsupported.",{geolocation:navigator.geolocation});n.getLogger(this).error(e)}this._override("locationEnabled",!!e&&t)}get placeholder(){const{allSources:e,activeSourceIndex:t,allPlaceholder:r}=this;if(t===Q)return r??"";const s=e.at(t);return s?.placeholder??""}set searchTerm(e){this._set("searchTerm",e||""),this.clearGraphics(),this.selectedSuggestion&&this.selectedSuggestion.text!==e&&this._set("selectedSuggestion",null),""===e&&this._clear()}get searchTerm(){return this._get("searchTerm")||""}get state(){return this._searching?"searching":this.updating?"loading":0===this.allSources.length?"disabled":"ready"}get updating(){return null!=this._updatingPromise}clear(){this.searchTerm=""}clearGraphics(){this._removeHighlight(),this._closePopup();const{view:e,resultGraphic:t}=this;e&&t&&e.graphics.remove(t),this._set("resultGraphic",null)}search(e,t){this.emit("search-start"),this.clearGraphics();const r=this._createSuggestionForSearch(e),s=(async()=>{try{await this.when();const e=await this._getResultsFromSources(r,t);if(t?.signal?.aborted)return null;const s={activeSourceIndex:this.activeSourceIndex,searchTerm:r.text??"",numResults:0,numErrors:0,errors:[],results:[]};this._formatResponse(s,e,r);const o=this._getFirstResult(s.results),i=r.location&&o?o.name:r.text,l=i?.replaceAll(B,"");return this._set("searchTerm",l),(r.key&&"number"==typeof r.sourceIndex||r.location)&&this._set("selectedSuggestion",r),this._set("results",s.results),this._set("resultCount",s.results.reduce((e,t)=>e+(t.results?.length??0),0)),this.emit("search-complete",s),await this._selectFirstResult(o),s}finally{this._clearSearching()}})();return this._searching=s,s}async searchNearby(e){if(!this.locationEnabled){const e=new l("searchNearby:geolocation-unsupported","Geolocation API is unsupported.",{geolocation:navigator.geolocation});throw n.getLogger(this).error(e),e}const t=(async()=>{try{const t=await N(),r=await D({position:t,view:this.view},e);return await this.search(r,e)}finally{this._clearSearching()}})();return this._searching=t,t}async select(e){if(this.clearGraphics(),!e){const t=new l("select:missing-parameter","Cannot select without a searchResult.",{value:e});throw n.getLogger(this).error(t),t}const{view:t}=this,s=V(e,"sourceIndex")?e.sourceIndex:this._getSourceIndexOfResult(e),o=null!=s?this.allSources.at(s):null;if(!o){const e=new l("select:missing-source","Cannot select without a source.",{source:o});throw n.getLogger(this).error(e),e}const i=o instanceof E?this._getLayerSourcePopupTemplate(o):o.popupTemplate,a=o.resultSymbol||this._getDefaultSymbol(e),u=V(o,"resultGraphicEnabled")?o.resultGraphicEnabled:this.resultGraphicEnabled,h=V(o,"autoNavigate")?o.autoNavigate:this.autoNavigate,p=V(o,"popupEnabled")?o.popupEnabled:this.popupEnabled,g=p?i||this.popupTemplate||this.defaultPopupTemplate:null,{feature:d}=e;if(!d){const e=new l("select:missing-feature","Cannot select without a feature.",{feature:d});throw n.getLogger(this).error(e),e}const{attributes:m,geometry:y,layer:f,sourceLayer:S}=d,w=y?_(y):null,b={layerViewQuery:this._getLayerView(d),elevationQuery:t&&null!=w?v(w,t):Promise.resolve(w)},x=await c(b),L=x.layerViewQuery.value,I=x.elevationQuery.value;a instanceof T&&(a.text=e.name);const F=t&&h?e.target||e.extent:null,P=null!=F?this._goToSearchResult(F):Promise.resolve();await P;const j=L?d:new r({geometry:y,symbol:a,attributes:m,layer:f,sourceLayer:S,popupTemplate:g}),C=t?.popup,G=C&&p&&j.getEffectivePopupTemplate(C.defaultPopupTemplateEnabled);return G&&await t.openPopup({features:[j],location:I}),L&&R(L)&&!G&&this._highlightFeature({graphic:j,layerView:L}),!L&&u&&t&&t.graphics.push(j),this._setResultFloor(e),this._set("selectedResult",e),this._set("resultGraphic",j),this.emit("select-result",{result:e,source:o,sourceIndex:s}),e}async suggest(e,t,r){const s=e||this.searchTerm;this.emit("suggest-start",{searchTerm:s}),await this._suggestTimer(t,r);const o=await this._suggestImmediate(s,r);return this._set("suggestions",o?.results),this._set("suggestionCount",o?.results.reduce((e,t)=>e+(t.results?.length??0),0)??null),this.emit("suggest-complete",o),o}async when(){await d(()=>!this.updating)}async _update(){const{portal:e,view:t}=this;if(this.includeDefaultSources){const r=this._updatingPromise=c([e?.load(),t?.when()]);if(this.destroyed)return;if(await r,r!==this._updatingPromise)return}this.destroyed||this._updateDefaultSources(),this._updatingPromise=null}_clearSearching(){this._searching=null}_convertHelperServices(){const e=this.portal?.helperServices?.geocode;if(!e)return[];return e.map(e=>{if(!1===e.placefinding)return;const t=j(e.url)&&b(e.url)?{url:C}:null,r=F.fromJSON({...e,...t}),s=r.url;if(j(s)||G(s)||O(s)){const e=r.outFields??["Addr_type","Match_addr","StAddr","City"],t=(r.placeholder||this.messages?.placeholder)??"",s="number"==typeof r.defaultZoomScale?r.defaultZoomScale:2500;r.singleLineFieldName="SingleLine",r.outFields=e,r.placeholder=t,r.defaultZoomScale=s}return r.singleLineFieldName?r:void 0}).filter(o)}_destroyFeatureLayers(){this._createdFeatureLayers.forEach(e=>e?.destroy()),this._createdFeatureLayers=[]}_getLayerSources(e,t){const r=this.view?.map;return e.map(e=>{const s=r.findLayerById(e.id);if(!s)return;const o=this._getLayerJSON(e),i=E.fromJSON(o);return i.placeholder=t,this._getLayer(s,o).then(e=>{i.layer=e}),i}).filter(o).toArray()}_getTableSources(e,t){const r=this.view?.map;return e.map(e=>{if(!e.id)return;const s=r.findTableById(e.id);if(!s)return;const o=this._getLayerJSON(e),i=E.fromJSON(o);return i.placeholder=t,this._getLayer(s,o).then(e=>{i.layer=e}),i}).filter(o).toArray()}_convertApplicationProperties(){const e=this.view?.map,t=e?.applicationProperties?.viewing?.search;if(!t)return[];const{enabled:r,hintText:s,layers:o,tables:i}=t;if(!r)return[];return[...this._getLayerSources(o,s),...this._getTableSources(i,s)]}async _getSubLayer(e,t){if(await e.load(),!e.allSublayers)throw new Error;const r=e.allSublayers.find(e=>e.id===t.subLayer);if(!r)throw new Error;const s=await(r.createFeatureLayer?.());if(!s)throw new Error;return this._createdFeatureLayers.push(s),s}async _getBuildingSubLayer(e,t){await e.load();const r=e.allSublayers.find(e=>e.id===t.subLayer);if("building-component"!==r?.type)throw new Error;if(await r.load(),null==r.associatedLayer)throw new Error;return await r.associatedLayer.load(),r}async _getLayer(e,t){if("feature"===e.type||"scene"===e.type||"csv"===e.type||"geojson"===e.type||"ogc-feature"===e.type)return e;if("map-image"===e.type)try{return await this._getSubLayer(e,t)}catch(r){const t=new l("search:create-featurelayer","Could not create a FeatureLayer from the MapImageLayer",{layer:e});return n.getLogger(this).error(t),null}return"building-scene"===e.type?this._getBuildingSubLayer(e,t):null}_getLayerJSON(e){return"function"==typeof e.toJSON?e.toJSON():e}_updateDefaultSources(){const{defaultSources:e,includeDefaultSources:t}=this;this._destroyFeatureLayers(),e.removeAll(),t&&e.addMany([...this._convertApplicationProperties(),...this._convertHelperServices()])}_abortGoTo(){this._gotoController&&this._gotoController.abort(),this._gotoController=null}_clear(){this._abortGoTo(),this._set("resultCount",null),this._set("results",null),this._set("suggestions",null),this._set("suggestionCount",null),this._set("selectedResult",null),this._set("selectedSuggestion",null),this.emit("search-clear")}_closePopup(){const e=this.view?.popup,{resultGraphic:t}=this;if(!e||!t)return;const r="selectedFeature"in e,s=r?e.selectedFeature:null;r&&(s&&s===t)&&e.close()}_suggestTimer(e,t){const r=null!=e?e:this.suggestionDelay;return h(r,null,t?.signal)}_createLocationForSearch(e){return e instanceof r&&e.geometry?_(e.geometry):e instanceof f?e:Array.isArray(e)&&2===e.length?new f({longitude:e[0],latitude:e[1]}):null}_createSuggestionForSearch(e){if(e&&V(e,"key")&&V(e,"text")&&V(e,"sourceIndex"))return e;const t=this._createLocationForSearch(e),r="string"==typeof e?e:this.searchTerm,{selectedSuggestion:s,selectedResult:o}=this,i=!e&&s&&o,l=i&&s.key===o.key&&s.sourceIndex===o.sourceIndex,a=i&&s.location;return l||a?s:{location:t,text:t?"":r,sourceIndex:null,key:null}}_getFirstResult(e){return u(e,({results:e})=>e?.[0])??null}async _selectFirstResult(e){return this.autoSelect&&e?this.select(e):null}async _suggestImmediate(e,t){await this.when();const r=await this._getSuggestionsFromSources(e,t);if(t?.signal?.aborted)return null;const s={activeSourceIndex:this.activeSourceIndex,searchTerm:e??"",numResults:0,numErrors:0,errors:[],results:[]};return this._formatResponse(s,r),s}_formatSourceResponse(e,t,r){const s=t?.value||[],o=t?.error,i=this.allSources.at(r);if(o){const t={sourceIndex:r,source:i,error:o};e.errors.push(t),n.getLogger(this).error(o),e.numErrors++}else{const t={sourceIndex:r,source:i,results:s};e.results.push(t),e.numResults+=s.length}}_formatResponse(e,t,r){if(t)if(e.activeSourceIndex===Q){const s=r&&V(r,"sourceIndex")&&-1!==r.sourceIndex?r.sourceIndex:void 0;t.forEach((t,r)=>{const o=void 0!==s?s:r;this._formatSourceResponse(e,t,o)})}else this._formatSourceResponse(e,t[0],e.activeSourceIndex)}async _getResultsFromSources(e,t){const{allSources:r}=this,s=!e.location&&V(e,"sourceIndex")?e.sourceIndex:this.activeSourceIndex,o=[];if(!r.length){const e=new l("search:no-sources-defined","At least one source is required.",{allSources:r});throw n.getLogger(this).error(e),e}return s===Q?r.forEach((r,s)=>{o.push(this._getResultsFromSource(e,s,t))}):o.push(this._getResultsFromSource(e,s,t)),c(o)}async _getSuggestionsFromSources(e,t){const{allSources:r,activeSourceIndex:s}=this,o=[];if(!r.length){const e=new l("suggest:no-sources-defined","At least one source is required.",{allSources:r});throw n.getLogger(this).error(e),e}return s===Q?r.forEach((r,s)=>{o.push(this._getSuggestionsFromSource(e,s,t))}):o.push(this._getSuggestionsFromSource(e,s,t)),c(o)}async _getResultsFromSource(e,t,r){const s=null!=t?this.allSources.at(t):null;if(!s)return null;const{location:o=null}=e,i=this.view?.spatialReference??k,l=V(s,"maxResults")?s.maxResults:this.maxResults,a=!!(s instanceof E&&V(s,"exactMatch"))&&s.exactMatch,{view:n}=this;return s.getResults?.({exactMatch:a,location:o,maxResults:l,sourceIndex:t,spatialReference:i,suggestResult:e,view:n},r)}async _getSuggestionsFromSource(e,t,r){const s=this.allSources.at(t);if(!s)return null;e??="";const o=V(s,"suggestionsEnabled")?s.suggestionsEnabled:this.suggestionsEnabled,i=e?.length,l=V(s,"minSuggestCharacters")?s.minSuggestCharacters:this.minSuggestCharacters;if(o&&e.trim()&&i>=l){const o=this.view?.spatialReference||k,i=V(s,"maxSuggestions")?s.maxSuggestions:this.maxSuggestions,{view:l}=this,a=!!(s instanceof E&&V(s,"exactMatch"))&&s.exactMatch;return s.getSuggestions?.({view:l,sourceIndex:t,suggestTerm:e,spatialReference:o,maxSuggestions:i,exactMatch:a},r)}return null}_getLayerSourcePopupTemplate(e){const{layer:t}=e;if(t)return V(e,"popupTemplate")?e.popupTemplate:t.popupTemplate}_getSourceIndexOfResult(e){return u(this.results??[],({results:t,sourceIndex:r})=>{const s=t?.includes(e);return s?r:null})??null}async _goToSearchResult(e){this._abortGoTo();const t=new AbortController;this._gotoController=t;const r={target:{target:e},options:{signal:t.signal}};e||(r.options.animate=!1),await this.callGoTo(r),this._gotoController=null}_getDefaultSymbol(e){const{defaultSymbols:t}=this,r=e.feature?.geometry;if(null==r)return null;switch(r.type){case"point":case"multipoint":return t.point;case"polyline":return t.polyline;case"extent":case"polygon":return t.polygon;default:return null}}_removeHighlight(){this.removeHandles(J)}async _getLayerView(e){const{view:t}=this;if(!e||!t)return null;const{layer:r,sourceLayer:s}=e,o=r??s;return o&&"building-component"!==o.type&&"subtype-sublayer"!==o.type?(await t.when(),t.whenLayerView(o)):null}_highlightFeature(e){const{graphic:t,layerView:r}=e,{attributes:s,layer:o,sourceLayer:i}=t,l=o??i,{objectIdField:a}=l,n=(a&&s?.[a])??null,u=r.highlight(n??t);this.addHandles(u,J)}_setResultFloor(e){const{view:t}=this,r=e.feature?.attributes,s=e.feature?.sourceLayer;if(s&&"floorInfo"in s&&s?.floorInfo?.floorField&&r){const e=r[s.floorInfo.floorField];t?.emit("select-result-floor",e)}}};e([m()],Z.prototype,"_searching",void 0),e([m()],Z.prototype,"_updatingPromise",void 0),e([m({readOnly:!0,value:null})],Z.prototype,"activeSource",null),e([m()],Z.prototype,"activeSourceIndex",null),e([m()],Z.prototype,"allPlaceholder",null),e([m({readOnly:!0})],Z.prototype,"allSources",null),e([m()],Z.prototype,"autoNavigate",void 0),e([m()],Z.prototype,"autoSelect",void 0),e([m({type:s})],Z.prototype,"defaultPopupTemplate",null),e([m({readOnly:!0})],Z.prototype,"defaultSources",void 0),e([m()],Z.prototype,"defaultSymbols",void 0),e([m()],Z.prototype,"includeDefaultSources",void 0),e([m()],Z.prototype,"locationEnabled",null),e([m()],Z.prototype,"maxInputLength",void 0),e([m()],Z.prototype,"maxResults",void 0),e([m()],Z.prototype,"maxSuggestions",void 0),e([m()],Z.prototype,"messages",void 0),e([m()],Z.prototype,"minSuggestCharacters",void 0),e([m({readOnly:!0})],Z.prototype,"placeholder",null),e([m()],Z.prototype,"popupEnabled",void 0),e([m({type:s})],Z.prototype,"popupTemplate",void 0),e([m({type:w})],Z.prototype,"portal",void 0),e([m()],Z.prototype,"resultCount",void 0),e([m()],Z.prototype,"resultGraphicEnabled",void 0),e([m({readOnly:!0})],Z.prototype,"resultGraphic",void 0),e([m({readOnly:!0})],Z.prototype,"results",void 0),e([m({readOnly:!0})],Z.prototype,"selectedSuggestion",void 0),e([m()],Z.prototype,"searchAllEnabled",void 0),e([m({readOnly:!0})],Z.prototype,"selectedResult",void 0),e([m()],Z.prototype,"searchTerm",null),e([m({type:U})],Z.prototype,"sources",void 0),e([m({readOnly:!0})],Z.prototype,"state",null),e([m()],Z.prototype,"suggestionDelay",void 0),e([m()],Z.prototype,"suggestionCount",void 0),e([m({readOnly:!0})],Z.prototype,"suggestions",void 0),e([m()],Z.prototype,"suggestionsEnabled",void 0),e([m({readOnly:!0})],Z.prototype,"updating",null),e([m()],Z.prototype,"view",void 0),e([m()],Z.prototype,"clear",null),Z=e([y("esri.widgets.Search.SearchViewModel")],Z);const q=Z;export{q as default};
|
|
5
|
+
import{__decorate as e}from"tslib";import{getAssetUrl as t}from"../../assets.js";import r from"../../Graphic.js";import s from"../../PopupTemplate.js";import{isSome as o}from"../../core/arrayUtils.js";import i from"../../core/Collection.js";import l from"../../core/Error.js";import{EventedAccessor as a}from"../../core/Evented.js";import n from"../../core/Logger.js";import{mappedFind as u}from"../../core/maybe.js";import{eachAlways as c,after as h}from"../../core/promiseUtils.js";import{watch as p,initial as g,whenOnce as d}from"../../core/reactiveUtils.js";import{property as m}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import{subclass as y}from"../../core/accessorSupport/decorators/subclass.js";import f from"../../geometry/Point.js";import S from"../../geometry/SpatialReference.js";import{getPointFromGeometry as _,getPointWithElevation as v}from"../../geometry/support/geometryUtils.js";import w from"../../portal/Portal.js";import{isApiKeyApplicable as b}from"../../support/apiKeyUtils.js";import x from"../../symbols/PictureMarkerSymbol.js";import L from"../../symbols/SimpleFillSymbol.js";import I from"../../symbols/SimpleLineSymbol.js";import T from"../../symbols/TextSymbol.js";import{highlightsSupported as R}from"../../views/support/layerViewUtils.js";import E from"./LayerSearchSource.js";import F from"./LocatorSearchSource.js";import P from"./SearchSource.js";import{isArcGISWorldGeocoder as j,meteredArcGISLocatorUrl as C,isProxiedArcGISWorldGeocoder as G,isMeteredArcGISWorldGeocoder as O}from"./support/locatorUtils.js";import{supported as A,getCurrentPosition as N,positionToPoint as D}from"../support/geolocationUtils.js";import{GoTo as M}from"../support/GoTo.js";function V(e,t){return e.hasOwnProperty(t)&&null!=e[t]&&""!==e[t]}const J="highlight",U=i.ofType({key:e=>e.layer?"layer":"locator",base:P,typeMap:{layer:E,locator:F}}),k=S.WGS84,H="esri/images/search/search-symbol-32.png",B=/<[\s\S]*?>/g,Q=-1;let Z=class extends(M(a)){constructor(e){super(e),this._defaultPopupTemplate=new s({content:"{Match_addr}"}),this._gotoController=null,this._searching=null,this._updatingPromise=null,this._createdFeatureLayers=[],this.autoNavigate=!0,this.autoSelect=!0,this.defaultSources=new U,this.defaultSymbols={point:new x({url:t(H),size:24,width:24,height:24}),polyline:new I({color:[130,130,130,1],width:2}),polygon:new L({color:[235,235,235,.4],outline:{color:[130,130,130,1],width:2}})},this.includeDefaultSources=!0,this.maxInputLength=128,this.maxResults=6,this.maxSuggestions=6,this.messages=null,this.minSuggestCharacters=3,this.popupEnabled=!0,this.popupTemplate=null,this.portal=w.getDefault(),this.resultCount=null,this.resultGraphicEnabled=!0,this.resultGraphic=null,this.results=null,this.selectedSuggestion=null,this.searchAllEnabled=!0,this.selectedResult=null,this.sources=new U,this.suggestionDelay=350,this.suggestionCount=null,this.suggestions=null,this.suggestionsEnabled=!0,this.view=null}initialize(){this.addHandles([p(()=>[this.includeDefaultSources,this.view,this.portal],()=>this._update(),g),p(()=>this.messages,()=>{this._defaultPopupTemplate.title=this.messages?.searchResult??"",this._update()},g)])}destroy(){this._destroyFeatureLayers(),this._abortGoTo(),this.clearGraphics()}static{this.ALL_INDEX=Q}get activeSource(){return this.allSources.at(this.activeSourceIndex)??null}get activeSourceIndex(){return 1===this.allSources.length||!this.searchAllEnabled?0:Q}set activeSourceIndex(e){this._overrideIfSome("activeSourceIndex",e)}get allPlaceholder(){return this.messages?.allPlaceholder}set allPlaceholder(e){this._overrideIfSome("allPlaceholder",e)}get allSources(){const{sources:e,defaultSources:t,includeDefaultSources:r}=this,s="function"==typeof r?r.call(null,{sources:e,defaultSources:t}):r?t.concat(e):e,o=this._get("allSources")||new U;return o.removeAll(),o.addMany(s.filter(Boolean)),o}get defaultPopupTemplate(){return this._defaultPopupTemplate}set defaultPopupTemplate(e){this._overrideIfSome("defaultPopupTemplate",e)}get locationEnabled(){return this._get("locationEnabled")||A()}set locationEnabled(e){if(void 0===e)return void this._clearOverride("locationEnabled");const t=A();if(e&&!t){const e=new l("locationEnabled:geolocation-unsupported","Geolocation API is unsupported.",{geolocation:navigator.geolocation});n.getLogger(this).error(e)}this._override("locationEnabled",!!e&&t)}get placeholder(){const{allSources:e,activeSourceIndex:t,allPlaceholder:r}=this;if(t===Q)return r??"";const s=e.at(t);return s?.placeholder??""}set searchTerm(e){this._set("searchTerm",e||""),this.clearGraphics(),this.selectedSuggestion&&this.selectedSuggestion.text!==e&&this._set("selectedSuggestion",null),""===e&&this._clear()}get searchTerm(){return this._get("searchTerm")||""}get state(){return this._searching?"searching":this.updating?"loading":0===this.allSources.length?"disabled":"ready"}get updating(){return null!=this._updatingPromise}clear(){this.searchTerm=""}clearGraphics(){this._removeHighlight(),this._closePopup();const{view:e,resultGraphic:t}=this;e&&t&&e.graphics.remove(t),this._set("resultGraphic",null)}search(e,t){this.emit("search-start"),this.clearGraphics();const r=this._createSuggestionForSearch(e),s=(async()=>{try{await this.when();const e=await this._getResultsFromSources(r,t);if(t?.signal?.aborted)return null;const s={activeSourceIndex:this.activeSourceIndex,searchTerm:r.text??"",numResults:0,numErrors:0,errors:[],results:[]};this._formatResponse(s,e,r);const o=this._getFirstResult(s.results),i=r.location&&o?o.name:r.text,l=i?.replaceAll(B,"");return this._set("searchTerm",l),(r.key&&"number"==typeof r.sourceIndex||r.location)&&this._set("selectedSuggestion",r),this._set("results",s.results),this._set("resultCount",s.results.reduce((e,t)=>e+(t.results?.length??0),0)),this.emit("search-complete",s),await this._selectFirstResult(o),s}finally{this._clearSearching()}})();return this._searching=s,s}async searchNearby(e){if(!this.locationEnabled){const e=new l("searchNearby:geolocation-unsupported","Geolocation API is unsupported.",{geolocation:navigator.geolocation});throw n.getLogger(this).error(e),e}const t=(async()=>{try{const t=await N(),r=await D({position:t,view:this.view},e);return await this.search(r,e)}finally{this._clearSearching()}})();return this._searching=t,t}async select(e){if(this.clearGraphics(),!e){const t=new l("select:missing-parameter","Cannot select without a searchResult.",{value:e});throw n.getLogger(this).error(t),t}const{view:t}=this,s=V(e,"sourceIndex")?e.sourceIndex:this._getSourceIndexOfResult(e),o=null!=s?this.allSources.at(s):null;if(!o){const e=new l("select:missing-source","Cannot select without a source.",{source:o});throw n.getLogger(this).error(e),e}const i=o instanceof E?this._getLayerSourcePopupTemplate(o):o.popupTemplate,a=o.resultSymbol||this._getDefaultSymbol(e),u=V(o,"resultGraphicEnabled")?o.resultGraphicEnabled:this.resultGraphicEnabled,h=V(o,"autoNavigate")?o.autoNavigate:this.autoNavigate,p=V(o,"popupEnabled")?o.popupEnabled:this.popupEnabled,g=p?i||this.popupTemplate||this.defaultPopupTemplate:null,{feature:d}=e;if(!d){const e=new l("select:missing-feature","Cannot select without a feature.",{feature:d});throw n.getLogger(this).error(e),e}const{attributes:m,geometry:y,layer:f,sourceLayer:S}=d,w=y?_(y):null,b={layerViewQuery:this._getLayerView(d),elevationQuery:t&&null!=w?v(w,t):Promise.resolve(w)},x=await c(b),L=x.layerViewQuery.value,I=x.elevationQuery.value;a instanceof T&&(a.text=e.name);const F=t&&h?e.target||e.extent:null,P=null!=F?this._goToSearchResult(F):Promise.resolve();await P;const j=L?d:new r({geometry:y,symbol:a,attributes:m,layer:f,sourceLayer:S,popupTemplate:g}),C=t?.popup,G=C&&p&&j.getEffectivePopupTemplate(C.defaultPopupTemplateEnabled);return G&&await t.openPopup({features:[j],location:I}),L&&R(L)&&!G&&this._highlightFeature({graphic:j,layerView:L}),!L&&u&&t&&t.graphics.push(j),this._setResultFloor(e),this._set("selectedResult",e),this._set("resultGraphic",j),this.emit("select-result",{result:e,source:o,sourceIndex:s}),e}async suggest(e,t,r){const s=e||this.searchTerm;this.emit("suggest-start",{searchTerm:s}),await this._suggestTimer(t,r);const o=await this._suggestImmediate(s,r);return this._set("suggestions",o?.results),this._set("suggestionCount",o?.results.reduce((e,t)=>e+(t.results?.length??0),0)??null),this.emit("suggest-complete",o),o}async when(e,t){await d(()=>!this.updating)}async _update(){const{portal:e,view:t}=this;if(this.includeDefaultSources){const r=this._updatingPromise=c([e?.load(),t?.when()]);if(this.destroyed)return;if(await r,r!==this._updatingPromise)return}this.destroyed||this._updateDefaultSources(),this._updatingPromise=null}_clearSearching(){this._searching=null}_convertHelperServices(){const e=this.portal?.helperServices?.geocode;if(!e)return[];return e.map(e=>{if(!1===e.placefinding)return;const t=j(e.url)&&b(e.url)?{url:C}:null,r=F.fromJSON({...e,...t}),s=r.url;if(j(s)||G(s)||O(s)){const e=r.outFields??["Addr_type","Match_addr","StAddr","City"],t=(r.placeholder||this.messages?.placeholder)??"",s="number"==typeof r.defaultZoomScale?r.defaultZoomScale:2500;r.singleLineFieldName="SingleLine",r.outFields=e,r.placeholder=t,r.defaultZoomScale=s}return r.singleLineFieldName?r:void 0}).filter(o)}_destroyFeatureLayers(){this._createdFeatureLayers.forEach(e=>e?.destroy()),this._createdFeatureLayers=[]}_getLayerSources(e,t){const r=this.view?.map;return e.map(e=>{const s=r.findLayerById(e.id);if(!s)return;const o=this._getLayerJSON(e),i=E.fromJSON(o);return i.placeholder=t,this._getLayer(s,o).then(e=>{i.layer=e}),i}).filter(o).toArray()}_getTableSources(e,t){const r=this.view?.map;return e.map(e=>{if(!e.id)return;const s=r.findTableById(e.id);if(!s)return;const o=this._getLayerJSON(e),i=E.fromJSON(o);return i.placeholder=t,this._getLayer(s,o).then(e=>{i.layer=e}),i}).filter(o).toArray()}_convertApplicationProperties(){const e=this.view?.map,t=e?.applicationProperties?.viewing?.search;if(!t)return[];const{enabled:r,hintText:s,layers:o,tables:i}=t;if(!r)return[];return[...this._getLayerSources(o,s),...this._getTableSources(i,s)]}async _getSubLayer(e,t){if(await e.load(),!e.allSublayers)throw new Error;const r=e.allSublayers.find(e=>e.id===t.subLayer);if(!r)throw new Error;const s=await(r.createFeatureLayer?.());if(!s)throw new Error;return this._createdFeatureLayers.push(s),s}async _getBuildingSubLayer(e,t){await e.load();const r=e.allSublayers.find(e=>e.id===t.subLayer);if("building-component"!==r?.type)throw new Error;if(await r.load(),null==r.associatedLayer)throw new Error;return await r.associatedLayer.load(),r}async _getLayer(e,t){if("feature"===e.type||"scene"===e.type||"csv"===e.type||"geojson"===e.type||"ogc-feature"===e.type)return e;if("map-image"===e.type)try{return await this._getSubLayer(e,t)}catch(r){const t=new l("search:create-featurelayer","Could not create a FeatureLayer from the MapImageLayer",{layer:e});return n.getLogger(this).error(t),null}return"building-scene"===e.type?this._getBuildingSubLayer(e,t):null}_getLayerJSON(e){return"function"==typeof e.toJSON?e.toJSON():e}_updateDefaultSources(){const{defaultSources:e,includeDefaultSources:t}=this;this._destroyFeatureLayers(),e.removeAll(),t&&e.addMany([...this._convertApplicationProperties(),...this._convertHelperServices()])}_abortGoTo(){this._gotoController&&this._gotoController.abort(),this._gotoController=null}_clear(){this._abortGoTo(),this._set("resultCount",null),this._set("results",null),this._set("suggestions",null),this._set("suggestionCount",null),this._set("selectedResult",null),this._set("selectedSuggestion",null),this.emit("search-clear")}_closePopup(){const e=this.view?.popup,{resultGraphic:t}=this;if(!e||!t)return;const r="selectedFeature"in e,s=r?e.selectedFeature:null;r&&(s&&s===t)&&e.close()}_suggestTimer(e,t){const r=null!=e?e:this.suggestionDelay;return h(r,null,t?.signal)}_createLocationForSearch(e){return e instanceof r&&e.geometry?_(e.geometry):e instanceof f?e:Array.isArray(e)&&2===e.length?new f({longitude:e[0],latitude:e[1]}):null}_createSuggestionForSearch(e){if(e&&V(e,"key")&&V(e,"text")&&V(e,"sourceIndex"))return e;const t=this._createLocationForSearch(e),r="string"==typeof e?e:this.searchTerm,{selectedSuggestion:s,selectedResult:o}=this,i=!e&&s&&o,l=i&&s.key===o.key&&s.sourceIndex===o.sourceIndex,a=i&&s.location;return l||a?s:{location:t,text:t?"":r,sourceIndex:null,key:null}}_getFirstResult(e){return u(e,({results:e})=>e?.[0])??null}async _selectFirstResult(e){return this.autoSelect&&e?this.select(e):null}async _suggestImmediate(e,t){await this.when();const r=await this._getSuggestionsFromSources(e,t);if(t?.signal?.aborted)return null;const s={activeSourceIndex:this.activeSourceIndex,searchTerm:e??"",numResults:0,numErrors:0,errors:[],results:[]};return this._formatResponse(s,r),s}_formatSourceResponse(e,t,r){const s=t?.value||[],o=t?.error,i=this.allSources.at(r);if(o){const t={sourceIndex:r,source:i,error:o};e.errors.push(t),n.getLogger(this).error(o),e.numErrors++}else{const t={sourceIndex:r,source:i,results:s};e.results.push(t),e.numResults+=s.length}}_formatResponse(e,t,r){if(t)if(e.activeSourceIndex===Q){const s=r&&V(r,"sourceIndex")&&-1!==r.sourceIndex?r.sourceIndex:void 0;t.forEach((t,r)=>{const o=void 0!==s?s:r;this._formatSourceResponse(e,t,o)})}else this._formatSourceResponse(e,t[0],e.activeSourceIndex)}async _getResultsFromSources(e,t){const{allSources:r}=this,s=!e.location&&V(e,"sourceIndex")?e.sourceIndex:this.activeSourceIndex,o=[];if(!r.length){const e=new l("search:no-sources-defined","At least one source is required.",{allSources:r});throw n.getLogger(this).error(e),e}return s===Q?r.forEach((r,s)=>{o.push(this._getResultsFromSource(e,s,t))}):o.push(this._getResultsFromSource(e,s,t)),c(o)}async _getSuggestionsFromSources(e,t){const{allSources:r,activeSourceIndex:s}=this,o=[];if(!r.length){const e=new l("suggest:no-sources-defined","At least one source is required.",{allSources:r});throw n.getLogger(this).error(e),e}return s===Q?r.forEach((r,s)=>{o.push(this._getSuggestionsFromSource(e,s,t))}):o.push(this._getSuggestionsFromSource(e,s,t)),c(o)}async _getResultsFromSource(e,t,r){const s=null!=t?this.allSources.at(t):null;if(!s)return null;const{location:o=null}=e,i=this.view?.spatialReference??k,l=V(s,"maxResults")?s.maxResults:this.maxResults,a=!!(s instanceof E&&V(s,"exactMatch"))&&s.exactMatch,{view:n}=this;return s.getResults?.({exactMatch:a,location:o,maxResults:l,sourceIndex:t,spatialReference:i,suggestResult:e,view:n},r)}async _getSuggestionsFromSource(e,t,r){const s=this.allSources.at(t);if(!s)return null;e??="";const o=V(s,"suggestionsEnabled")?s.suggestionsEnabled:this.suggestionsEnabled,i=e?.length,l=V(s,"minSuggestCharacters")?s.minSuggestCharacters:this.minSuggestCharacters;if(o&&e.trim()&&i>=l){const o=this.view?.spatialReference||k,i=V(s,"maxSuggestions")?s.maxSuggestions:this.maxSuggestions,{view:l}=this,a=!!(s instanceof E&&V(s,"exactMatch"))&&s.exactMatch;return s.getSuggestions?.({view:l,sourceIndex:t,suggestTerm:e,spatialReference:o,maxSuggestions:i,exactMatch:a},r)}return null}_getLayerSourcePopupTemplate(e){const{layer:t}=e;if(t)return V(e,"popupTemplate")?e.popupTemplate:t.popupTemplate}_getSourceIndexOfResult(e){return u(this.results??[],({results:t,sourceIndex:r})=>{const s=t?.includes(e);return s?r:null})??null}async _goToSearchResult(e){this._abortGoTo();const t=new AbortController;this._gotoController=t;const r={target:{target:e},options:{signal:t.signal}};e||(r.options.animate=!1),await this.callGoTo(r),this._gotoController=null}_getDefaultSymbol(e){const{defaultSymbols:t}=this,r=e.feature?.geometry;if(null==r)return null;switch(r.type){case"point":case"multipoint":return t.point;case"polyline":return t.polyline;case"extent":case"polygon":return t.polygon;default:return null}}_removeHighlight(){this.removeHandles(J)}async _getLayerView(e){const{view:t}=this;if(!e||!t)return null;const{layer:r,sourceLayer:s}=e,o=r??s;return o&&"building-component"!==o.type&&"subtype-sublayer"!==o.type?(await t.when(),t.whenLayerView(o)):null}_highlightFeature(e){const{graphic:t,layerView:r}=e,{attributes:s,layer:o,sourceLayer:i}=t,l=o??i,{objectIdField:a}=l,n=(a&&s?.[a])??null,u=r.highlight(n??t);this.addHandles(u,J)}_setResultFloor(e){const{view:t}=this,r=e.feature?.attributes,s=e.feature?.sourceLayer;if(s&&"floorInfo"in s&&s?.floorInfo?.floorField&&r){const e=r[s.floorInfo.floorField];t?.emit("select-result-floor",e)}}};e([m()],Z.prototype,"_searching",void 0),e([m()],Z.prototype,"_updatingPromise",void 0),e([m({readOnly:!0,value:null})],Z.prototype,"activeSource",null),e([m()],Z.prototype,"activeSourceIndex",null),e([m()],Z.prototype,"allPlaceholder",null),e([m({readOnly:!0})],Z.prototype,"allSources",null),e([m()],Z.prototype,"autoNavigate",void 0),e([m()],Z.prototype,"autoSelect",void 0),e([m({type:s})],Z.prototype,"defaultPopupTemplate",null),e([m({readOnly:!0})],Z.prototype,"defaultSources",void 0),e([m()],Z.prototype,"defaultSymbols",void 0),e([m()],Z.prototype,"includeDefaultSources",void 0),e([m()],Z.prototype,"locationEnabled",null),e([m()],Z.prototype,"maxInputLength",void 0),e([m()],Z.prototype,"maxResults",void 0),e([m()],Z.prototype,"maxSuggestions",void 0),e([m()],Z.prototype,"messages",void 0),e([m()],Z.prototype,"minSuggestCharacters",void 0),e([m({readOnly:!0})],Z.prototype,"placeholder",null),e([m()],Z.prototype,"popupEnabled",void 0),e([m({type:s})],Z.prototype,"popupTemplate",void 0),e([m({type:w})],Z.prototype,"portal",void 0),e([m()],Z.prototype,"resultCount",void 0),e([m()],Z.prototype,"resultGraphicEnabled",void 0),e([m({readOnly:!0})],Z.prototype,"resultGraphic",void 0),e([m({readOnly:!0})],Z.prototype,"results",void 0),e([m({readOnly:!0})],Z.prototype,"selectedSuggestion",void 0),e([m()],Z.prototype,"searchAllEnabled",void 0),e([m({readOnly:!0})],Z.prototype,"selectedResult",void 0),e([m()],Z.prototype,"searchTerm",null),e([m({type:U})],Z.prototype,"sources",void 0),e([m({readOnly:!0})],Z.prototype,"state",null),e([m()],Z.prototype,"suggestionDelay",void 0),e([m()],Z.prototype,"suggestionCount",void 0),e([m({readOnly:!0})],Z.prototype,"suggestions",void 0),e([m()],Z.prototype,"suggestionsEnabled",void 0),e([m({readOnly:!0})],Z.prototype,"updating",null),e([m()],Z.prototype,"view",void 0),e([m()],Z.prototype,"clear",null),Z=e([y("esri.widgets.Search.SearchViewModel")],Z);const q=Z;export{q as default};
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
|
|
3
3
|
See https://js.arcgis.com/4.34/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
function e(e){return a=>{a.hasOwnProperty("_delegatedEventNames")||(a._delegatedEventNames=a._delegatedEventNames?a._delegatedEventNames.slice():[]);const n=a._delegatedEventNames
|
|
5
|
+
function e(e){return a=>{a.hasOwnProperty("_delegatedEventNames")||(a._delegatedEventNames=a._delegatedEventNames?a._delegatedEventNames.slice():[]);const n=a._delegatedEventNames;e=Array.isArray(e)?e:t(e),n.push(...e)}}function t(e){return e.split(",").map(e=>e.trim())}export{e as vmEvent};
|