Skip to content

Commit c14f33c

Browse files
Refactor and enhance STAC data handling and user interface
- Improved STAC data structure and properties for better clarity and usability. - Enhanced frontend functionality with Tailwind CSS integration for improved styling. - Streamlined data fetching in index.vue, optimizing dataset selection and polygon drawing features. - Updated package dependencies to include @nuxtjs/tailwindcss and lucide-vue-next. - Improved user experience with clearer indicators for dataset availability and enhanced download options.
1 parent b5537b7 commit c14f33c

27 files changed

+911
-0
lines changed

app/components/CollectionSelector.vue

+171
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
<script lang="ts" setup>
2+
import { Eye, EyeOff } from 'lucide-vue-next'
3+
import { CollectionType, LayerLink } from '../types'
4+
import type { Ref } from 'vue'
5+
6+
let { collection, onChangeActive, activeValue } = defineProps<{
7+
collection: CollectionType & { href: string }
8+
activeValue?: LayerLink
9+
onChangeActive(link?: LayerLink): void
10+
}>()
11+
12+
let baseURL = collection.href.replace('/collection.json', '')
13+
14+
let summaries = computed(() => {
15+
return collection?.summaries
16+
})
17+
18+
let propertyOrder = computed(() => Object.keys(summaries.value))
19+
20+
let variables: Ref<Record<string, string | undefined>> = ref({})
21+
22+
function resetVariables() {
23+
variables.value = Object.keys(summaries.value ?? {}).reduce((acc, key) => {
24+
return {
25+
...acc,
26+
[key]: undefined,
27+
}
28+
}, {} as Record<string, string | undefined>)
29+
}
30+
31+
resetVariables()
32+
33+
function getValidOptionsForProperty(property: string) {
34+
if (!variables.value) return []
35+
36+
let currentIndex = propertyOrder.value.indexOf(property)
37+
let relevantProperties = propertyOrder.value.slice(0, currentIndex)
38+
39+
let validItems = collection.links
40+
.filter((link) => link.rel === 'item')
41+
.filter((link) => {
42+
if (!variables.value) return false
43+
return Object.entries(variables.value)
44+
.filter(([key]) => relevantProperties.includes(key))
45+
.every(
46+
([key, option]) =>
47+
!option ||
48+
link.properties?.[key as keyof typeof link.properties] === option,
49+
)
50+
})
51+
52+
return [
53+
...new Set(
54+
validItems.map(
55+
(item) => item?.properties?.[property as keyof typeof item.properties],
56+
),
57+
),
58+
]
59+
}
60+
61+
function selectOption(property: string, option: string) {
62+
if (!variables.value) return
63+
64+
if (variables.value[property] === option) {
65+
variables.value[property] = undefined
66+
} else {
67+
variables.value[property] = option
68+
}
69+
70+
let currentIndex = propertyOrder.value.indexOf(property)
71+
for (let i = currentIndex + 1; i < propertyOrder.value.length; i++) {
72+
let nextProperty = propertyOrder.value[i]
73+
if (!variables.value) break
74+
75+
variables.value[nextProperty] = undefined
76+
77+
let validOptions = getValidOptionsForProperty(nextProperty)
78+
if (validOptions.length === 1) {
79+
variables.value[nextProperty] = validOptions[0]
80+
}
81+
}
82+
}
83+
84+
watchEffect(() => {
85+
if (!summaries.value || !variables.value) return
86+
87+
let foundLink = collection.links
88+
.filter((l) => l.rel === 'item')
89+
.find((link) => {
90+
return Object.entries(variables.value ?? {}).every(
91+
([key, option]) =>
92+
link.properties?.[key as keyof typeof link.properties] === option,
93+
)
94+
})
95+
96+
if (foundLink) {
97+
onChangeActive({
98+
type: 'item',
99+
href: baseURL + '/' + foundLink.href,
100+
})
101+
} else {
102+
onChangeActive(undefined)
103+
}
104+
})
105+
106+
function toggleActive(value: boolean) {
107+
if (!value) {
108+
onChangeActive(undefined)
109+
resetVariables()
110+
} else {
111+
if (summaries.value) {
112+
// do nothing
113+
} else {
114+
const geoserverLink = collection.assets?.['geoserver_link'] as
115+
| { href: string }
116+
| undefined
117+
if (geoserverLink) {
118+
onChangeActive({
119+
type: 'raster',
120+
href: geoserverLink.href,
121+
})
122+
}
123+
}
124+
}
125+
}
126+
</script>
127+
128+
<template>
129+
<div v-if="!summaries">
130+
<div class="flex items-center gap-3 bg-white p-3 shadow">
131+
<button
132+
@click="toggleActive(!activeValue)"
133+
class="size-8 flex items-center justify-center shrink-0 rounded-md hover:bg-gray-100"
134+
>
135+
<Eye class="size-4" v-if="!!activeValue" />
136+
<EyeOff class="size-4" v-if="!activeValue" />
137+
</button>
138+
<div class="text-sm font-medium">{{ collection.title }}</div>
139+
</div>
140+
</div>
141+
<v-expansion-panel v-if="summaries">
142+
<v-expansion-panel-title>
143+
<div class="flex items-center gap-3">
144+
<button
145+
@click.stop="!!activeValue && toggleActive(false)"
146+
class="z-10 size-8 flex items-center justify-center shrink-0 rounded-md hover:bg-gray-100"
147+
>
148+
<Eye class="size-4" v-if="!!activeValue" />
149+
<EyeOff class="size-4" v-if="!activeValue" />
150+
</button>
151+
<div>{{ collection.title }}</div>
152+
</div>
153+
</v-expansion-panel-title>
154+
<v-expansion-panel-text>
155+
<div class="grid grid-flow-row gap-1.5 py-3">
156+
<div
157+
v-for="(options, key) in summaries"
158+
:key="key"
159+
class="empty:hidden"
160+
>
161+
<v-select
162+
:label="key"
163+
:items="getValidOptionsForProperty(key)"
164+
:model-value="variables?.[key]"
165+
@update:model-value="selectOption(key, $event)"
166+
/>
167+
</div>
168+
</div>
169+
</v-expansion-panel-text>
170+
</v-expansion-panel>
171+
</template>

app/components/ItemLayer.vue

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<script setup lang="ts">
2+
import { ItemType } from '~/types'
3+
4+
let { href } = defineProps<{
5+
href: string
6+
}>()
7+
8+
let { data: jsonString } = await useFetch<ItemType>(href)
9+
10+
let item = computed(() => JSON.parse(jsonString.value))
11+
</script>
12+
13+
<template>
14+
<RasterLayer :id="item.id" :href="item.assets.visual.href" />
15+
</template>

app/components/Layer.vue

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<script setup lang="ts">
2+
import { LayerLink } from '~/types'
3+
4+
let { link } = defineProps<{
5+
link: LayerLink
6+
}>()
7+
</script>
8+
9+
<template>
10+
<ItemLayer v-if="link.type === 'item'" :href="link.href" />
11+
<RasterLayer
12+
v-if="link.type === 'raster'"
13+
:href="link.href"
14+
:id="link.href"
15+
/>
16+
</template>

app/components/RasterLayer.vue

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<script setup lang="ts">
2+
import { MapboxLayer } from '@studiometa/vue-mapbox-gl'
3+
4+
let { id, href } = defineProps<{
5+
id: string
6+
href: string
7+
}>()
8+
9+
let layer = computed(() => {
10+
return {
11+
id,
12+
type: 'raster',
13+
source: {
14+
type: 'raster',
15+
tiles: [href],
16+
tileSize: 256,
17+
},
18+
}
19+
})
20+
</script>
21+
22+
<template>
23+
<MapboxLayer v-if="layer" :key="layer.id" :id="layer.id" :options="layer" />
24+
</template>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Copyright 2020 Google, LLC.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# Use the official lightweight Python image.
16+
# https://hub.docker.com/_/python
17+
FROM python:3.11-slim
18+
19+
# Allow statements and log messages to immediately appear in the Knative logs
20+
ENV PYTHONUNBUFFERED True
21+
22+
# Copy local code to the container image.
23+
ENV APP_HOME /app
24+
WORKDIR $APP_HOME
25+
COPY . ./
26+
27+
# Install production dependencies.
28+
RUN pip install -r requirements.txt
29+
30+
# Run the web service on container startup. Here we use the gunicorn
31+
# webserver, with one worker process and 8 threads.
32+
# For environments with multiple CPU cores, increase the number of workers
33+
# to be equal to the cores available.
34+
CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 main:app
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Developing the report-python-cloud-run Function
2+
3+
## Prerequisites
4+
5+
Create a virtual environment and install the dependencies:
6+
7+
```bash
8+
pip install -r requirements.txt
9+
```
10+
11+
## Testing
12+
13+
Run the report function locally:
14+
15+
```bash
16+
python report.py
17+
```
18+
19+
## Deploying
20+
21+
Deploying to Cloud run is done using github actions. The workflow is defined in `.github/workflows/deploy_function.yml`. The workflow is triggered on push to the `main` branch.

app/functions/report-python-cloud-run/__init__.py

Whitespace-only changes.
Binary file not shown.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import json
2+
import os
3+
4+
from shapely import Polygon # type: ignore
5+
from shapely.geometry import shape # type: ignore
6+
from flask import Flask, make_response, render_template_string, request
7+
8+
from report.report import (
9+
create_report_html,
10+
create_report_pdf,
11+
POLYGON_DEFAULT,
12+
STAC_ROOT_DEFAULT,
13+
)
14+
15+
app = Flask(__name__)
16+
17+
18+
@app.route("/", methods=["GET"])
19+
def return_report():
20+
"""Return a report for the given polygon"""
21+
polygon_str = request.args.get("polygon")
22+
23+
if not polygon_str:
24+
polygon_str = POLYGON_DEFAULT
25+
26+
origin = request.headers.get("Referer")
27+
print(f"detected origin: {origin}")
28+
29+
# For now we pin the stac_root on a default because we
30+
# don't have a way to pass it in from the client and cant handle the password
31+
# protected preview deployments
32+
stac_root = STAC_ROOT_DEFAULT
33+
34+
polygon = shape(json.loads(polygon_str))
35+
if not isinstance(polygon, Polygon):
36+
raise ValueError("Invalid polygon")
37+
38+
web_page_content = create_report_html(polygon=polygon, stac_root=stac_root)
39+
pdf_object = create_report_pdf(web_page_content)
40+
41+
response = make_response(pdf_object.getvalue())
42+
response.headers["Content-Type"] = "application/pdf"
43+
response.headers["Content-Disposition"] = "inline; filename=coastal_report.pdf"
44+
response.headers["Access-Control-Allow-Origin"] = "*" # CORS
45+
return response
46+
47+
48+
@app.route("/html")
49+
def return_html():
50+
"""Return a report for the given polygon"""
51+
polygon_str = request.args.get("polygon")
52+
53+
if not polygon_str:
54+
polygon_str = POLYGON_DEFAULT
55+
56+
origin = request.headers.get("Referer")
57+
print(f"detected origin: {origin}")
58+
59+
# For now we pin the stac_root on a default because we
60+
# don't have a way to pass it in from the client and cant handle the password
61+
# protected preview deployments
62+
stac_root = STAC_ROOT_DEFAULT
63+
64+
polygon = shape(json.loads(polygon_str))
65+
if not isinstance(polygon, Polygon):
66+
raise ValueError("Invalid polygon")
67+
68+
web_page_content = create_report_html(polygon=polygon, stac_root=stac_root)
69+
70+
response = make_response(render_template_string(web_page_content))
71+
response.headers["Access-Control-Allow-Origin"] = "*" # CORS
72+
return response
73+
74+
75+
if __name__ == "__main__":
76+
app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))

app/functions/report-python-cloud-run/report/__init__.py

Whitespace-only changes.

app/functions/report-python-cloud-run/report/datasets/__init__.py

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from typing import Optional
2+
import xarray as xr
3+
4+
from .datasetcontent import DatasetContent
5+
from .esl import get_esl_content
6+
7+
8+
def get_dataset_content(dataset_id: str, xarr: xr.Dataset) -> Optional[DatasetContent]:
9+
match dataset_id:
10+
case "esl_gwl":
11+
return get_esl_content(xarr)
12+
case _:
13+
return None
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
from dataclasses import dataclass
2+
from typing import Optional
3+
4+
5+
@dataclass
6+
class DatasetContent:
7+
dataset_id: str
8+
title: str
9+
text: str
10+
image_base64: Optional[str] = None
11+
image_svg: Optional[str] = None

0 commit comments

Comments
 (0)