Skip to content

Commit

Permalink
Allow for some config values to be set after build
Browse files Browse the repository at this point in the history
  • Loading branch information
danielfdsilva committed Oct 21, 2024
1 parent 56079a4 commit b9efa34
Show file tree
Hide file tree
Showing 9 changed files with 62 additions and 15 deletions.
33 changes: 31 additions & 2 deletions webapp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,38 @@ These files are used to simplify the configuration of the app and should not con

Run the project locally by copying the `.env` to `.env.local` and setting the following environment variables:

| | |
| ----------------- | --------------------------------------- |
| `APP_TITLE` | Application title (For meta tags) |
| `APP_DESCRIPTION` | Application description (For meta tags) |
| `PUBLIC_URL` | Full url for the app |
| `MAPBOX_TOKEN` | Mapbox token |
| `STAC_API` | STAC API endpoint |
| `TILER_API` | TILER API endpoint |

### Runtime configuration
It is possible to change some configuration after the app is built by providing the configuration via the `app_config.js` file.

The file should be placed in the root of the `dist` directory and should contain a single object:

```js
window.__APP_CONFIG__ = {
{{VARIABLE}}: {{value}}
};
```
A JSON object can also be used but needs to be converted to an object.

```js
window.__APP_CONFIG__ = JSON.parse('{{JSON_STRING}}');
```

The following variables can be changed at runtime, while the other ones are needed during the build process:
| | |
| -------------- | ------------------ |
| `MAPBOX_TOKEN` | Mapbox token |
| `STAC_API` | STAC API endpoint |
| `TILER_API` | TILER API endpoint |

| --- | --- |
| `{{VARIABLE}}` | {{description}} |

### Starting the app

Expand Down
11 changes: 6 additions & 5 deletions webapp/app/components/aois/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,12 @@ import { DataIndicator, IndicatorLegend } from './data-indicator';
import { PointStats } from './point-stats';
import { ShareOptions } from './share-options';

import { AreaTitle } from '$components/common/area-title';
import config from '$utils/config';
import {
IndicatorProperties,
FeatureProperties
} from '$utils/loaders';
import { AreaTitle } from '$components/common/area-title';
import { FloatBox } from '$components/common/shared';
import { Timeline } from '$components/common/timeline';
import { DatePicker } from '$components/common/calendar';
Expand Down Expand Up @@ -173,7 +174,7 @@ function LakesSingle(props: LakesLoaderData) {
daysToRequest.forEach((day) => {
dataFetcher.fetchData({
key: ['lakes', lake.properties.idhidro, day.toISOString()],
url: `${process.env.STAC_API}/collections/whis-lakes-labelec-scenes-c2rcc/items/${lake.properties.idhidro}_${format(day, 'yyyyMMdd')}`
url: `${config.STAC_API}/collections/whis-lakes-labelec-scenes-c2rcc/items/${lake.properties.idhidro}_${format(day, 'yyyyMMdd')}`
});
});
}, 500),
Expand Down Expand Up @@ -258,7 +259,7 @@ function LakesSingle(props: LakesLoaderData) {
[lake]
);

const lakeIndicatorTileUrl = `${process.env.TILER_API}/collections/whis-lakes-labelec-scenes-c2rcc/items/${itemId}/tiles/{z}/{x}/{y}?assets=${activeIndicator.id}&rescale=${[valueMin, valueMax].join(',')}&colormap_name=${colorName}`;
const lakeIndicatorTileUrl = `${config.TILER_API}/collections/whis-lakes-labelec-scenes-c2rcc/items/${itemId}/tiles/{z}/{x}/{y}?assets=${activeIndicator.id}&rescale=${[valueMin, valueMax].join(',')}&colormap_name=${colorName}`;

return (
<>
Expand Down Expand Up @@ -295,7 +296,7 @@ function LakesSingle(props: LakesLoaderData) {
onOptionChange={onMapOptionChange}
/>
<Map
mapboxAccessToken={process.env.MAPBOX_TOKEN}
mapboxAccessToken={config.MAPBOX_TOKEN}
initialViewState={{
bounds: lake.bbox as LngLatBoundsLike,
fitBoundsOptions: {
Expand Down Expand Up @@ -330,7 +331,7 @@ function LakesSingle(props: LakesLoaderData) {
<Source
type='raster'
tiles={[
`${process.env.TILER_API}/collections/whis-lakes-labelec-scenes-c2rcc/items/${itemId}/tiles/{z}/{x}/{y}?assets=TCI`
`${config.TILER_API}/collections/whis-lakes-labelec-scenes-c2rcc/items/${itemId}/tiles/{z}/{x}/{y}?assets=TCI`
]}
>
<Layer
Expand Down
8 changes: 5 additions & 3 deletions webapp/app/components/aois/point-stats.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { format } from 'date-fns/format.js';

import { PointStatsPopover } from './point-stats-popover';

import config from '$utils/config';

const markerPulse = keyframes`
0% {
opacity: 0;
Expand Down Expand Up @@ -54,7 +56,7 @@ export function PointStats(props: PointStatsProps) {
setData({ state: 'loading', data: null });
const cogUrl = getCogUrl(lakeId, indicatorId, date);
const stats = await axios.get(
`${process.env.TILER_API}/cog/point/${lngLat?.join(',')}?url=${cogUrl}`
`${config.TILER_API}/cog/point/${lngLat?.join(',')}?url=${cogUrl}`
);
const prevMeasurement = await searchPrevMeasurement(
lakeId,
Expand Down Expand Up @@ -163,7 +165,7 @@ async function searchPrevMeasurement(
};

const candidatesData = await axios.post(
`${process.env.STAC_API}/search`,
`${config.STAC_API}/search`,
candidateQuery
);

Expand All @@ -176,7 +178,7 @@ async function searchPrevMeasurement(
const cogUrl = getCogUrl(lakeId, indicatorId, date);
try {
const stats = await axios.get(
`${process.env.TILER_API}/cog/point/${lngLat?.join(',')}?url=${cogUrl}`
`${config.TILER_API}/cog/point/${lngLat?.join(',')}?url=${cogUrl}`
);
return {
date,
Expand Down
5 changes: 3 additions & 2 deletions webapp/app/components/home/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { Layer, Map, Source, useMap } from 'react-map-gl';
import centroid from '@turf/centroid';
import bbox from '@turf/bbox';

import config from '$utils/config';
import SmartLink from '$components/common/smart-link';
import { FeatureProperties } from '$utils/loaders';
import { AreaTitle } from '$components/common/area-title';
Expand Down Expand Up @@ -49,7 +50,7 @@ export function Component() {
<Box as='main' flex='1'>
<Map
{...viewState}
mapboxAccessToken={process.env.MAPBOX_TOKEN}
mapboxAccessToken={config.MAPBOX_TOKEN}
style={{ inset: '0', position: 'absolute' }}
mapStyle='mapbox://styles/devseed/cm2bn62f500px01pe9wrl0igs'
maxBounds={[
Expand Down Expand Up @@ -148,7 +149,7 @@ function LakeList(props: LakeListProps) {
width='18rem'
fontSize='sm'
fontWeight='600'
bg={`url('https://api.mapbox.com/styles/v1/mapbox/satellite-v9/static/[${bbox(f).join(',')}]/288x152@2x?access_token=${process.env.MAPBOX_TOKEN}')`}
bg={`url('https://api.mapbox.com/styles/v1/mapbox/satellite-v9/static/[${bbox(f).join(',')}]/288x152@2x?access_token=${config.MAPBOX_TOKEN}')`}
bgSize='cover'
color='surface.500'
to={`/aois/${f.id}`}
Expand Down
1 change: 1 addition & 0 deletions webapp/app/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ <h1><img src='./media/layout/polder--logomark.svg' alt='logotype' width='188' he
}
</script>

<script src='{{baseurl}}/app_config.js'></script>
<script src='./main.tsx' type='module'></script>
</body>

Expand Down
8 changes: 8 additions & 0 deletions webapp/app/utils/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export default {
MAPBOX_TOKEN: process.env.MAPBOX_TOKEN,
STAC_API: process.env.STAC_API,
TILER_API: process.env.TILER_API,

/* @ts-expect-error __APP_CONFIG__ is the global config injected data */
...window.__APP_CONFIG__
};
7 changes: 5 additions & 2 deletions webapp/app/utils/loaders.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import axios from 'axios';
import { Feature, FeatureCollection, MultiPolygon } from 'geojson';
import { defer } from 'react-router-dom';

import { round } from './format';

import config from '$utils/config';

interface StacSearchResponse
extends FeatureCollection<MultiPolygon, FeatureProperties> {
context: {
Expand Down Expand Up @@ -69,7 +72,7 @@ export interface IndicatorProperties {
export async function requestLakes() {
const dataPromise = async () => {
const data = await axios.get<StacSearchResponse>(
`${process.env.STAC_API}/collections/whis-lakes-labelec-features-c2rcc/items?limit=100`
`${config.STAC_API}/collections/whis-lakes-labelec-features-c2rcc/items?limit=100`
);

return data.data;
Expand All @@ -88,7 +91,7 @@ export async function requestSingleLake({
const dataPromise = async () => {
try {
const { data: lakeData } = await axios.get<StacItemResponse>(
`${process.env.STAC_API}/collections/whis-lakes-labelec-features-c2rcc/items/${params.id}`,
`${config.STAC_API}/collections/whis-lakes-labelec-features-c2rcc/items/${params.id}`,
{
signal: request.signal
}
Expand Down
3 changes: 2 additions & 1 deletion webapp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,8 @@
"use-pan-and-zoom": "^0.6.5"
},
"parcelIgnore": [
".*/meta/"
".*/meta/",
".*/app_config.js"
],
"alias": {
"$components": "~/app/components",
Expand Down
1 change: 1 addition & 0 deletions webapp/static/app_config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
window.__APP_CONFIG__ = {};

0 comments on commit b9efa34

Please sign in to comment.