Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Zoom to select area #52

Merged
merged 14 commits into from
Sep 24, 2024
Merged
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"@phosphor-icons/react": "^2.1.7",
"@prisma/client": "5.15.0",
"@statelyai/inspect": "^0.3.1",
"@turf/bbox": "^7.1.0",
"@xstate/react": "^4.1.1",
"execa": "^9.3.0",
"framer-motion": "^11.2.0",
Expand Down
31 changes: 30 additions & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 24 additions & 3 deletions src/app/(home)/globe/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,12 @@ function GlobeInner() {
state.matches("Page is mounting")
);
const pageUrl = MachineContext.useSelector(selectors.pageUrl);
const mapBounds = MachineContext.useSelector(selectors.mapBounds);

// On mount, pass route parameters to the machine
useEffect(() => {
actorRef.send({
type: "Page has mounted",
type: "event:page:mounted",
context: { areaId: params.areaId || null },
});
}, []);
Expand All @@ -54,6 +55,16 @@ function GlobeInner() {
}
}, [router, pageUrl, pageIsMounting]);

useEffect(() => {
if (mapRef.current && mapBounds) {
const [x1, y1, x2, z2] = mapBounds;
mapRef.current.fitBounds([x1, y1, x2, z2], {
padding: 200,
duration: 500,
});
}
}, [mapBounds]);

const onClick = useCallback((event: MapMouseEvent) => {
if (mapRef.current) {
const features = mapRef.current.queryRenderedFeatures(event.point, {
Expand All @@ -62,8 +73,18 @@ function GlobeInner() {

if (features.length > 0) {
const feature = features[0];
if (feature?.properties?.id) {
router.push(`/area/${feature.properties.id}`);
if (feature) {
actorRef.send({
type: "event:area:select",
area: {
type: "Feature",
geometry: feature.geometry,
properties: {
id: feature.properties.id,
name: feature.properties.name,
},
},
});
}
}
}
Expand Down
158 changes: 30 additions & 128 deletions src/app/(home)/globe/state/machine.ts
Original file line number Diff line number Diff line change
@@ -1,178 +1,80 @@
import {
CountryCapitalsGeoJSON,
CountryLimitsGeoJSON,
} from "@/types/countries";
import { assign, createMachine, assertEvent, fromPromise } from "xstate";
import { bbox } from "@turf/bbox";
import { assign, createMachine, assertEvent } from "xstate";
import { StateContext, StateActions, StateEvents } from "./types";

export const globeViewMachine = createMachine(
{
/** @xstate-layout N4IgpgJg5mDOIC5RQDYHsBGYBqBLMA7gHQCyAhgA4AEusV6ZEuAdlAMQRrNhEsBuaANY8AZmAAuAYwAW5CgBEy4sgG0ADAF1EoCmli5xuLtpAAPRAEYALAFYiAThsB2J-YAc9gGxqATF4DMTgA0IACeiAC0bhZE-jZuTv7+9u5uVm7+VgC+WSGomDj4xHI0dAxMrGxgAE7VaNVEFChKIvUAtkRiUrKUisrqWkgguvqGxkPmCMluRBY2VmrWFvZWPpkWIeEIERZunkRONn7RLnE+Pp6eOXnoWHiERACSzAa4ZChU+VhUfEVsAMpgFBgSTiKhkapgVSaEwjV7jUCTNSbRBqa4gL6FB4AYTQAFdmOJqqFSlRYECQeJIGxscCIeDIWQyRTQUZmANYXp4cwTEiUQg0bkMbcscRcQSiSTaMzgaDqYDZWCIVCOUM4WMeRNIv41ERPPZrGorPYfK5PLZTfyrBYnEQrFYktavJ4-D5skLMfdiAAFMgwUltfGEljsX3+6RkOiBiWQVU6Lka3mWWx2zwWQILNxpE2+fkRHUzfwZOIm2zufwWHJC5hoCBwEyeoqc0ZspPbJwzfWG42mry2fx59IzNbWLNqOL2xLoxsPErS8oh5vcttOKx6qwu+xnCxqRIrPM+CwxNzxFw2LwWQ+Vj0ir1PF6Gd6fEU-JtqhOtrUIOb+IjRfz6moQEdm6-KOH+q6eB2HhFrs0TTreRREOKhLEqS5KKpAS6Jl+FjeAc45xJcZ5dvySQxFu5xOD4ajeOOThXDeBR3gAqtwpgUJSkBUDUdTVNhn6IogdGzCsiw2EciwrAOYSRHBRA2LslHxMaUE2IxNzMUhYZgAGQaGKwAkImYlhHEQtELDqW7uE44mDos5n2jRajOPMyzujkQA */
id: "globeView",

types: {
context: {} as {
areaId: string | null;
countryLimitsGeoJSON: CountryLimitsGeoJSON | null;
countryCapitalsGeoJSON: CountryCapitalsGeoJSON | null;
},
events: {} as
| {
type: "Page has mounted";
context: {
areaId: string | null;
};
}
| {
type: "Select area";
areaId: string;
}
| {
type: "Clear area selection";
},
actions: {} as
| {
type: "initContext";
context: {
areaId: string | null;
};
}
| {
type: "setAreaId";
areaId: string;
}
| {
type: "clearAreaId";
}
| {
type: "assignMapData";
countryLimitsGeojson: CountryLimitsGeoJSON;
countryCapitalsGeojson: CountryCapitalsGeoJSON;
},
context: {} as StateContext,
events: {} as StateEvents,
actions: {} as StateActions,
},

context: {
areaId: null,
countryLimitsGeoJSON: null,
countryCapitalsGeoJSON: null,
mapBounds: null,
},

states: {
"Map is loading": {
invoke: {
id: "fetchMapData",
src: "fetchMapData",
onError: {
target: "Unexpected error",
},
onDone: {
target: "Initial globe view",
actions: assign({
countryLimitsGeoJSON: ({ event }) =>
event.output.countryLimitsGeojson,
countryCapitalsGeoJSON: ({ event }) =>
event.output.countryCapitalsGeojson,
}),
},
},
},

"Initial globe view": {
initial: {
on: {
"Select area": {
target: "Country is selected",
actions: "setAreaId",
"event:area:select": {
target: "area:selected",
actions: "action:area:select",
},
},
},

"Country is selected": {
"area:selected": {
on: {
"Clear area selection": {
target: "Initial globe view",
actions: "clearAreaId",
"event:area:clear": {
target: "initial",
actions: "action:area:clear",
},

"Select area": {
target: "Country is selected",
actions: "setAreaId",
"event:area:select": {
target: "area:selected",
actions: "action:area:select",
},
},
},

"Unexpected error": {},

"Page is mounting": {
"page:mounting": {
on: {
"Page has mounted": {
target: "Map is loading",
"event:page:mounted": {
target: "initial",
reenter: true,
actions: "initContext",
actions: "action:initializeContext",
},
},
},
},

initial: "Page is mounting",
initial: "page:mounting",
},
{
actions: {
initContext: assign(({ event }) => {
assertEvent(event, "Page has mounted");
"action:initializeContext": assign(({ event }) => {
assertEvent(event, "event:page:mounted");
return {
...event.context,
};
}),
setAreaId: assign(({ event }) => {
assertEvent(event, "Select area");
"action:area:select": assign(({ event }) => {
assertEvent(event, "event:area:select");
return {
areaId: event.areaId,
areaId: event.area.properties.id,
mapBounds: bbox(event.area),
};
}),
clearAreaId: assign({
"action:area:clear": assign({
areaId: undefined,
}),
},
actors: {
fetchMapData: fromPromise(async () => {
const countryLimitsGeojson = await fetch(
"/naturalearth-3.3.0/ne_50m_admin_0_countries.geojson"
)
.then((response) => response.json() as Promise<CountryLimitsGeoJSON>)
.then((data) => ({
...data,
features: data.features
.map((feature) => ({
...feature,
properties: {
...feature.properties,
id: feature.properties.iso_a2,
},
}))
.filter((feature) => feature.properties.id !== "-99"),
}));

const countryCapitalsGeojson = await fetch(
"/naturalearth-3.3.0/ne_50m_populated_places_adm0cap.geojson"
)
.then(
(response) => response.json() as Promise<CountryCapitalsGeoJSON>
)
.then((data) => ({
...data,
features: data.features.map((feature) => ({
...feature,
properties: {
...feature.properties,
id: feature.properties.ISO_A2,
},
})),
}));

return {
countryLimitsGeojson,
countryCapitalsGeojson,
};
}),
},
}
);
Loading