Skip to content

Commit

Permalink
feat: no longer throw error on validation failures in addFeatures and…
Browse files Browse the repository at this point in the history
… return validation status
  • Loading branch information
JamesLMilner committed Dec 15, 2024
1 parent e1b475f commit c1ab8f7
Show file tree
Hide file tree
Showing 39 changed files with 761 additions and 368 deletions.
19 changes: 15 additions & 4 deletions development/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,10 +150,17 @@ const getModes = () => {
feature: {
validation: (feature) => {
if (feature.geometry.type !== "Polygon") {
return false;
return {
valid: false,
reason: "Feature is not a valid Polygon feature",
};
}

return ValidateMinAreaSquareMeters(feature, 1000);
const result = ValidateMinAreaSquareMeters(feature, 1000);
return {
valid: result,
reason: result ? undefined : "Area too small",
};
},
draggable: true,
coordinates: {
Expand Down Expand Up @@ -182,9 +189,13 @@ const getModes = () => {
snapping: true,
validation: (feature, { updateType }) => {
if (updateType === "finish" || updateType === "commit") {
return ValidateNotSelfIntersecting(feature);
const valid = ValidateNotSelfIntersecting(feature);
return {
valid,
reason: valid ? undefined : "Polygon must not self-intersect",
};
}
return true;
return { valid: true };
},
}),
new TerraDrawRectangleMode(),
Expand Down
12 changes: 10 additions & 2 deletions e2e/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,16 @@ const example = {
this.config?.includes("validationSuccess") ||
this.config?.includes("validationFailure")
? (feature) => {
return ValidateMaxAreaSquareMeters(
const result = ValidateMaxAreaSquareMeters(
feature,
this.config?.includes("validationFailure")
? 1000000
: 2000000,
);
return {
valid: result,
reason: result ? undefined : "Area too large",
};
}
: undefined,
draggable: true,
Expand Down Expand Up @@ -151,12 +155,16 @@ const example = {
this.config?.includes("validationSuccess") ||
this.config?.includes("validationFailure")
? (feature) => {
return ValidateMaxAreaSquareMeters(
const result = ValidateMaxAreaSquareMeters(
feature,
this.config?.includes("validationFailure")
? 1000000
: 2000000,
);
return {
valid: result,
reason: "Area too large",
};
}
: undefined,
}),
Expand Down
17 changes: 16 additions & 1 deletion guides/2.STORE.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ Features can also be added to the Store programmatically using the `addFeatures`

```javascript
// Add a Point to the Store
draw.addFeatures([
const result = draw.addFeatures([
{
type: "Feature",
geometry: {
Expand All @@ -75,6 +75,21 @@ draw.addFeatures([
},
},
]);

console.log(result)

// Will log:
// [{
// id: 'aa5c8826-cbf1-4489-9b31-987c871866af',
// valid: true,
// }]
```

`addFeatures` returns an array of objects providing information about the added features such as the id and the feature was valid. Only valid features are added to the store. This allows developers to handle failure cases how they see fit:

```typescript
const invalidFeatures = result.filter(({ valid }) => !valid);
// Do something with the information
```

If you want to get an ID for a feature and create that outside Terra Draw to do something with it later, you can use the `getFeatureId` method on the Terra Draw instance, like so:
Expand Down
7 changes: 6 additions & 1 deletion guides/4.MODES.md
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ It is possible to select and deselect a feature via the draw instance, which use
draw.start();

// Add feature programmatically
draw.addFeatures([
const result = draw.addFeatures([
{
id: "f8e5a38d-ecfa-4294-8461-d9cff0e0d7f8",
type: "Feature",
Expand All @@ -384,6 +384,11 @@ It is possible to select and deselect a feature via the draw instance, which use
},
]);

// Log out if the feature passed validation or not
if (!result[0].valid) {
throw new Error(result.reason ? result.reason : 'Feature f8e5a38d-ecfa-4294-8461-d9cff0e0d7f8 was invalid')
}

// Select a given feature
draw.selectFeature("f8e5a38d-ecfa-4294-8461-d9cff0e0d7f8");

Expand Down
5 changes: 4 additions & 1 deletion src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,10 @@ type ValidationContext = Pick<
export type Validation = (
feature: GeoJSONStoreFeatures,
context: ValidationContext,
) => boolean;
) => {
valid: boolean;
reason?: string;
};

export type TerraDrawModeState =
| "unregistered"
Expand Down
21 changes: 12 additions & 9 deletions src/modes/angled-rectangle/angled-rectangle.mode.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ describe("TerraDrawAngledRectangleMode", () => {
store = new GeoJSONStore();
angledRectangleMode = new TerraDrawAngledRectangleMode({
validation: () => {
return true;
return { valid: true };
},
});
const mockConfig = MockModeConfig(angledRectangleMode.mode);
Expand Down Expand Up @@ -190,7 +190,7 @@ describe("TerraDrawAngledRectangleMode", () => {
describe("with successful validation", () => {
beforeEach(() => {
angledRectangleMode = new TerraDrawAngledRectangleMode({
validation: () => true,
validation: () => ({ valid: true }),
});
const mockConfig = MockModeConfig(angledRectangleMode.mode);

Expand Down Expand Up @@ -224,7 +224,7 @@ describe("TerraDrawAngledRectangleMode", () => {
describe("with unsuccessful validation", () => {
beforeEach(() => {
angledRectangleMode = new TerraDrawAngledRectangleMode({
validation: () => false,
validation: () => ({ valid: false, reason: "Test" }),
});
const mockConfig = MockModeConfig(angledRectangleMode.mode);

Expand Down Expand Up @@ -380,7 +380,7 @@ describe("TerraDrawAngledRectangleMode", () => {
describe("validateFeature", () => {
it("returns true for valid rectangle feature with validation that returns true", () => {
const rectangleMode = new TerraDrawAngledRectangleMode({
validation: () => true,
validation: () => ({ valid: true }),
});
rectangleMode.register(MockModeConfig("angled-rectangle"));

Expand All @@ -405,14 +405,14 @@ describe("TerraDrawAngledRectangleMode", () => {
updatedAt: 1685655518118,
},
}),
).toBe(true);
).toEqual({
valid: true,
});
});

it("returns false for valid rectangle feature but with validation that returns false", () => {
const rectangleMode = new TerraDrawAngledRectangleMode({
validation: () => {
return false;
},
validation: () => ({ valid: false, reason: "Test" }),
});
rectangleMode.register(MockModeConfig("angled-rectangle"));

Expand All @@ -437,7 +437,10 @@ describe("TerraDrawAngledRectangleMode", () => {
updatedAt: 1685655518118,
},
}),
).toBe(false);
).toEqual({
reason: "Test",
valid: false,
});
});
});

Expand Down
33 changes: 21 additions & 12 deletions src/modes/angled-rectangle/angled-rectangle.mode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,19 @@ import {
TerraDrawBaseDrawMode,
BaseModeOptions,
CustomStyling,
ModeMismatchValidationFailure,
} from "../base.mode";
import { coordinatesIdentical } from "../../geometry/coordinates-identical";
import { getDefaultStyling } from "../../util/styling";
import { FeatureId, GeoJSONStoreFeatures } from "../../store/store";
import { ValidatePolygonFeature } from "../../validations/polygon.validation";
import {
FeatureId,
GeoJSONStoreFeatures,
StoreValidation,
} from "../../store/store";
import {
ValidateNonIntersectingPolygonFeature,
ValidatePolygonFeature,
} from "../../validations/polygon.validation";
import { webMercatorDestination } from "../../geometry/measure/destination";
import { webMercatorBearing } from "../../geometry/measure/bearing";
import { midpointCoordinate } from "../../geometry/midpoint-coordinate";
Expand Down Expand Up @@ -258,7 +266,7 @@ export class TerraDrawAngledRectangleMode extends TerraDrawBaseDrawMode<PolygonS
},
);

if (!valid) {
if (!valid.valid) {
return false;
}
}
Expand Down Expand Up @@ -409,14 +417,15 @@ export class TerraDrawAngledRectangleMode extends TerraDrawBaseDrawMode<PolygonS
return styles;
}

validateFeature(feature: unknown): feature is GeoJSONStoreFeatures {
if (super.validateFeature(feature)) {
return (
feature.properties.mode === this.mode &&
ValidatePolygonFeature(feature, this.coordinatePrecision)
);
} else {
return false;
}
validateFeature(feature: unknown): StoreValidation {
return this.validateModeFeature(
feature,
(baseValidatedFeature) =>
ValidateNonIntersectingPolygonFeature(
baseValidatedFeature,
this.coordinatePrecision,
),
"Feature is not a valid simple Polygon feature",
);
}
}
52 changes: 49 additions & 3 deletions src/modes/base.mode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,20 @@ export enum ModeTypes {
Render = "render",
}

type BaseValidationResult = { valid: boolean; reason?: string };

export type BaseModeOptions<T extends CustomStyling> = {
styles?: Partial<T>;
pointerDistance?: number;
validation?: Validation;
projection?: Projection;
};

export const ModeMismatchValidationFailure = {
valid: false,
reason: "Feature mode property does not match the mode being added to",
};

export abstract class TerraDrawBaseDrawMode<T extends CustomStyling> {
protected _state: TerraDrawModeState;
get state() {
Expand Down Expand Up @@ -150,7 +157,11 @@ export abstract class TerraDrawBaseDrawMode<T extends CustomStyling> {
}
}

validateFeature(feature: unknown): feature is GeoJSONStoreFeatures {
validateFeature(feature: unknown): BaseValidationResult {
return this.performFeatureValidation(feature);
}

private performFeatureValidation(feature: unknown): BaseValidationResult {
if (this._state === "unregistered") {
throw new Error("Mode must be registered");
}
Expand All @@ -162,15 +173,50 @@ export abstract class TerraDrawBaseDrawMode<T extends CustomStyling> {

// We also want tp validate based on any specific valdiations passed in
if (this.validate) {
return this.validate(feature as GeoJSONStoreFeatures, {
const validation = this.validate(feature as GeoJSONStoreFeatures, {
project: this.project,
unproject: this.unproject,
coordinatePrecision: this.coordinatePrecision,
updateType: UpdateTypes.Provisional,
});

return {
// validatedFeature: feature as GeoJSONStoreFeatures,
valid: validStoreFeature.valid && validation.valid,
reason: validation.reason,
};
}

return {
// validatedFeature: feature as GeoJSONStoreFeatures,
valid: validStoreFeature.valid,
reason: validStoreFeature.reason,
};
}

protected validateModeFeature(
feature: unknown,
modeValidationFn: (feature: GeoJSONStoreFeatures) => boolean,
defaultError: string,
): BaseValidationResult {
const validation = this.performFeatureValidation(feature);
if (validation.valid) {
const validatedFeature = feature as GeoJSONStoreFeatures;
const matches = validatedFeature.properties.mode === this.mode;
if (!matches) {
return ModeMismatchValidationFailure;
}
const modeValidation = modeValidationFn(validatedFeature);
return {
valid: modeValidation,
reason: modeValidation ? undefined : defaultError,
};
}

return validStoreFeature;
return {
valid: false,
reason: validation.reason,
};
}

abstract start(): void;
Expand Down
17 changes: 12 additions & 5 deletions src/modes/circle/circle.mode.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ describe("TerraDrawCircleMode", () => {

beforeEach(() => {
circleMode = new TerraDrawCircleMode({
validation: () => valid,
validation: () => ({ valid }),
});
const mockConfig = MockModeConfig(circleMode.mode);

Expand Down Expand Up @@ -570,7 +570,10 @@ describe("TerraDrawCircleMode", () => {
updatedAt: 1685568435434,
},
}),
).toBe(false);
).toEqual({
reason: "Feature is not a valid simple Polygon feature",
valid: false,
});
});

it("returns true for valid circle feature", () => {
Expand Down Expand Up @@ -666,13 +669,15 @@ describe("TerraDrawCircleMode", () => {
updatedAt: 1685568435434,
},
}),
).toBe(true);
).toEqual({
valid: true,
});
});

it("returns false for valid circle feature but with validation that returns false", () => {
const circleMode = new TerraDrawCircleMode({
validation: () => {
return false;
return { valid: false };
},
styles: {
fillColor: "#ffffff",
Expand Down Expand Up @@ -765,7 +770,9 @@ describe("TerraDrawCircleMode", () => {
updatedAt: 1685568435434,
},
}),
).toBe(false);
).toEqual({
valid: false,
});
});
});
});
Loading

0 comments on commit c1ab8f7

Please sign in to comment.