Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/components/cards/value.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ export default function ValueCard({
const setHref = useStore((store) => store.setHref);
const selfHref = getSelfHref(value);
const thumbnailAsset = getThumbnailAsset(value);
const description = value.description as string | undefined;
const description = (value.description ??
(value.properties as { description?: string } | undefined)?.description) as
string | undefined;

return (
<Card.Root
Expand Down
12 changes: 2 additions & 10 deletions src/components/collections.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { type BBox2D, useStore } from "@/store";
import type { StacCollections } from "@/types/stac";
import { bboxIntersectsViewport } from "@/utils/bbox";
import {
collectionMatchesFilter,
getCollectionsDatetimeExtent,
Expand Down Expand Up @@ -327,16 +328,7 @@ function isCollectionInBbox(
return includeGlobalCollections;
}
const collectionBbox = collection?.extent?.spatial?.bbox?.[0];
if (collectionBbox) {
return !(
collectionBbox[0] > bbox[2] ||
collectionBbox[1] > bbox[3] ||
collectionBbox[2] < bbox[0] ||
collectionBbox[3] < bbox[1]
);
} else {
return false;
}
return collectionBbox ? bboxIntersectsViewport(collectionBbox, bbox) : false;
}

function isGlobalCollection(collection: StacCollection) {
Expand Down
9 changes: 2 additions & 7 deletions src/components/items.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { type BBox2D, useStore } from "@/store";
import { bboxIntersectsViewport } from "@/utils/bbox";
import { getItemsDatetimeExtent, itemMatchesFilter } from "@/utils/datetime";
import { fitBoundsToBbox } from "@/utils/map";
import { fetchStacValue, getSelfHref } from "@/utils/stac";
Expand Down Expand Up @@ -244,11 +245,5 @@ function getItemsBbox(items: StacItem[]): BBox2D | undefined {
function isItemInBbox(item: StacItem, bbox: BBox2D): boolean {
const itemBbox = toBbox2D(item.bbox);
if (!itemBbox) return false;
if (bbox[2] - bbox[0] >= 360) return true;
return !(
itemBbox[0] > bbox[2] ||
itemBbox[1] > bbox[3] ||
itemBbox[2] < bbox[0] ||
itemBbox[3] < bbox[1]
);
return bboxIntersectsViewport(itemBbox, bbox);
}
20 changes: 12 additions & 8 deletions src/components/queryables.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,15 +85,18 @@ function QueryableField({
</Field.Label>
<NativeSelect.Root size={"sm"}>
<NativeSelect.Field
value={value?.eq ?? ""}
onChange={(e) =>
onChange(e.target.value ? { eq: e.target.value } : undefined)
}
value={value?.eq === undefined ? "" : String(value.eq)}
onChange={(e) => {
const option = property.enum?.find(
(option) => String(option) === e.target.value
);
onChange(option === undefined ? undefined : { eq: option });
}}
>
<option value="">Any</option>
{property.enum.map((option) => (
<option key={option} value={option}>
{option}
<option key={String(option)} value={String(option)}>
{String(option)}
</option>
))}
</NativeSelect.Field>
Expand All @@ -103,7 +106,8 @@ function QueryableField({
);
}

if (property.type === "number" || property.type === "integer") {
const types = [property.type].flat();
if (types.includes("number") || types.includes("integer")) {
return (
<Field.Root orientation={"horizontal"}>
<Field.Label color={"fg.muted"} fontWeight={"normal"}>
Expand Down Expand Up @@ -148,7 +152,7 @@ function QueryableField({
</Field.Label>
<Input
size={"sm"}
value={value?.eq ?? ""}
value={value?.eq === undefined ? "" : String(value.eq)}
onChange={(e) =>
onChange(e.target.value ? { eq: e.target.value } : undefined)
}
Expand Down
5 changes: 3 additions & 2 deletions src/components/value.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,13 @@ export default function Value({
const setProjection = useStore((store) => store.setProjection);
const version = value.stac_version as string;
const thumbnailAsset = getThumbnailAsset(value);
const description = value.description as string;
const properties = value.properties as GeoJsonProperties | undefined;
const description = (value.description ?? properties?.description) as
string | undefined;
const collectionsLink = getLink(value, "data");
const childLinks = value.links?.filter((link) => link.rel === "child");
const itemLinks = value.links?.filter((link) => link.rel === "item");
const rootLink = getLink(value, "root");
const properties = value.properties as GeoJsonProperties | undefined;
const assets = value.assets as StacAssets | undefined;

useEffect(() => {
Expand Down
34 changes: 34 additions & 0 deletions src/utils/bbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,37 @@ export function normalizeViewport(bbox: BBox2D): BBox2D[] | null {
[-180, s, e - 360, n],
];
}

/**
* Whether a STAC bbox (2D or 3D) intersects a map viewport.
*
* The viewport may run past ±180 when the map is panned across the
* antimeridian, and the bbox may cross it too (west greater than east).
*/
export function bboxIntersectsViewport(
bbox: number[],
viewport: BBox2D
): boolean {
const views = normalizeViewport(viewport);
if (!views) return true;
const [west, south, east, north] =
bbox.length === 6 ? [bbox[0], bbox[1], bbox[3], bbox[4]] : bbox;
const boxes =
west > east
? [
[west, south, 180, north],
[-180, south, east, north],
]
: [[west, south, east, north]];
return views.some((view) =>
boxes.some(
(box) =>
!(
box[0] > view[2] ||
box[1] > view[3] ||
box[2] < view[0] ||
box[3] < view[1]
)
)
);
}
4 changes: 2 additions & 2 deletions src/utils/cql2.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
export interface QueryableFilter {
eq?: string;
eq?: string | number | boolean;
gte?: number;
lte?: number;
}

export type Cql2Expression =
| { op: "="; args: [{ property: string }, string] }
| { op: "="; args: [{ property: string }, string | number | boolean] }
| { op: ">=" | "<="; args: [{ property: string }, number] }
| { op: "and"; args: Cql2Expression[] };

Expand Down
25 changes: 21 additions & 4 deletions src/utils/stac.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,23 @@ function buildAuthHeaders(href: string): Record<string, string> {
return headers;
}

/**
* An error for a failed request: the status code, the status text when there
* is one (HTTP/2 and HTTP/3 have none) and the `description` of a STAC API
* error body.
*/
export async function responseError(href: string, response: Response) {
let description: unknown;
try {
description = (await response.json())?.description;
Comment thread
jo-chemla marked this conversation as resolved.
Resolved
} catch {
// Not JSON: the status says enough
}
const parts = [`GET ${href}: ${response.status}`, response.statusText];
if (typeof description === "string") parts.push(`(${description})`);
return new Error(parts.filter(Boolean).join(" "));
}

export async function fetchStacValue({
href,
uploadedFile,
Expand All @@ -36,7 +53,7 @@ export async function fetchStacValue({
makeHrefsAbsolute(applyGuessedType(json), href.toString())
);
} else {
throw new Error(`GET ${href}: ${response.statusText}`);
throw await responseError(href, response);
}
});
} else if (uploadedFile) {
Expand Down Expand Up @@ -149,8 +166,8 @@ export function getQueryablesHref(value: { links?: Array<StacLink> }) {
}

export interface QueryableProperty {
type?: string;
enum?: (string | number)[];
type?: string | string[];
enum?: (string | number | boolean)[];
minimum?: number;
maximum?: number;
title?: string;
Expand All @@ -169,7 +186,7 @@ export async function fetchQueryablesSchema(
headers: buildAuthHeaders(href),
});
if (!response.ok) {
throw new Error(`GET ${href}: ${response.statusText}`);
throw await responseError(href, response);
}
return response.json();
}
Expand Down
37 changes: 37 additions & 0 deletions tests/utils/bbox.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import {
bboxIntersectsViewport,
clampToGlobalExtents,
normalizeViewport,
resolveInitialBbox,
Expand Down Expand Up @@ -113,3 +114,39 @@ describe("normalizeViewport", () => {
]);
});
});

describe("bboxIntersectsViewport", () => {
const samoa = [-172.8, -14.1, -171.4, -13.4];
const fiji = [177, -19, -178, -16];

it("matches a plain overlap and rejects a plain miss", () => {
expect(bboxIntersectsViewport(samoa, [-180, -20, -160, -10])).toBe(true);
expect(bboxIntersectsViewport(samoa, [0, 40, 10, 50])).toBe(false);
});

it("matches a bbox on the far side of a viewport panned past 180", () => {
expect(bboxIntersectsViewport(samoa, [150, -30, 200, 0])).toBe(true);
});

it("matches a bbox on the far side of a viewport panned past -180", () => {
expect(
bboxIntersectsViewport([170, -20, 179, -10], [-200, -30, -150, 0])
).toBe(true);
});

it("handles a bbox that itself crosses the antimeridian", () => {
expect(bboxIntersectsViewport(fiji, [-179, -20, -170, -10])).toBe(true);
expect(bboxIntersectsViewport(fiji, [178, -20, 179, -10])).toBe(true);
expect(bboxIntersectsViewport(fiji, [0, -20, 10, -10])).toBe(false);
});

it("reads the horizontal extent of a 3D bbox", () => {
expect(
bboxIntersectsViewport([10, 40, 0, 11, 41, 100], [10.5, 40.5, 12, 42])
).toBe(true);
});

it("matches everything when the viewport spans every longitude", () => {
expect(bboxIntersectsViewport(samoa, [-300, -80, 300, 80])).toBe(true);
});
});
9 changes: 9 additions & 0 deletions tests/utils/cql2.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@ import { describe, expect, it } from "vitest";
import { buildCql2Json } from "../../src/utils/cql2";
import { loadCql2Wasm } from "../../src/utils/cql2-wasm";

describe("buildCql2Json with a boolean", () => {
it("keeps the boolean as a boolean", () => {
expect(buildCql2Json({ "ogdc:usable": { eq: true } })).toEqual({
op: "=",
args: [{ property: "ogdc:usable" }, true],
});
});
});

describe("buildCql2Json", () => {
it("returns undefined for an empty queryables map", () => {
expect(buildCql2Json({})).toBeUndefined();
Expand Down
20 changes: 20 additions & 0 deletions tests/utils/stac.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
getStacType,
getThumbnailAsset,
guessStacType,
responseError,
sanitizeBbox,
} from "../../src/utils/stac";

Expand Down Expand Up @@ -140,6 +141,25 @@ describe("fetchStacValue", () => {
});
});

describe("responseError", () => {
it("gives the status code when there is no status text", async () => {
const response = new Response("not json", { status: 404 });
const error = await responseError("https://example.com/x", response);
expect(error.message).toBe("GET https://example.com/x: 404");
});

it("adds the status text and a STAC API error description", async () => {
const response = new Response(
JSON.stringify({ code: "NotFoundError", description: "No such catalog" }),
{ status: 404, statusText: "Not Found" }
);
const error = await responseError("https://example.com/x", response);
expect(error.message).toBe(
"GET https://example.com/x: 404 Not Found (No such catalog)"
);
});
});

describe("getStacId", () => {
it("returns the id when present", () => {
expect(getStacId(makeCatalog({ id: "my-id" }))).toBe("my-id");
Expand Down
Loading