Skip to content
Merged
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
112 changes: 112 additions & 0 deletions .github/workflows/deploy-web.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
name: Deploy Web

on:
pull_request:
workflow_dispatch:
workflow_call:

concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
cancel-in-progress: true

permissions:
contents: read
deployments: write
pull-requests: write

env:
# Must match mise.toml, otherwise wrangler-action runs `pnpm add wrangler`, which pnpm blocks.
WRANGLER_VERSION: 4.156.0

jobs:
deploy:
runs-on: ubuntu-latest

# Fork PRs don't get repository secrets.
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository

environment:
name: ${{ github.event_name == 'pull_request' && 'web-preview' || 'web-production' }}
url: ${{ steps.deploy.outputs.deployment-url }}

steps:
- name: Checkout Repository
uses: actions/checkout@v4

- name: Install mise and dependencies
uses: jdx/mise-action@v3
with:
install_args: node pnpm github:protomaps/go-pmtiles npm:wrangler

- name: Install Dependencies
run: pnpm install

- name: Cache Basemap
id: basemap
uses: actions/cache@v4
with:
path: |
static/map/cstat.pmtiles
static/map/sprites
static/map/fonts
key: basemap-${{ hashFiles('pmtiles/cstat.sh') }}

- name: Build Basemap
if: steps.basemap.outputs.cache-hit != 'true'
run: pnpm pmtiles

# Content-addressed, so previews never overwrite the basemap production reads.
- name: Name Basemap Object
id: tiles
run: echo "key=cstat-$(sha256sum static/map/cstat.pmtiles | cut -c1-16).pmtiles" >> "$GITHUB_OUTPUT"

- name: Build Web Assets
run: pnpm build
env:
VITE_PMTILES_URL: ${{ vars.MAP_TILES_URL }}/${{ steps.tiles.outputs.key }}

# R2's REST object API rejects bucket-scoped tokens, so this uses the S3 API instead of wrangler.
- name: Upload Basemap to R2
run: >-
aws s3 cp static/map/cstat.pmtiles "s3://${{ vars.MAP_TILES_BUCKET }}/${{ steps.tiles.outputs.key }}"
--endpoint-url "https://${{ vars.CLOUDFLARE_ACCOUNT_ID }}.r2.cloudflarestorage.com"
--content-type application/vnd.pmtiles
--cache-control "public, max-age=31536000, immutable"
env:
AWS_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }}
AWS_DEFAULT_REGION: auto

# The web build reads the basemap from R2.
- name: Remove Bundled Basemap
run: rm build/map/cstat.pmtiles

- name: Deploy to Cloudflare Pages
id: deploy
uses: cloudflare/wrangler-action@v3
with:
wranglerVersion: ${{ env.WRANGLER_VERSION }}
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
command: pages deploy build --project-name=${{ vars.CLOUDFLARE_PAGES_PROJECT }} --branch=${{ github.event.pull_request.number && format('pr{0}', github.event.pull_request.number) || 'main' }}

# Edits the bot's previous comment so the PR keeps one preview link.
- name: Comment Preview URL
if: github.event_name == 'pull_request'
run: |
gh pr comment "$PR_NUMBER" --edit-last --create-if-none --body "$(cat <<BODY
### Web preview

| | |
| --- | --- |
| Preview | $PREVIEW_URL |
| This deploy | $DEPLOYMENT_URL |
| Commit | $COMMIT |
BODY
)"
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ github.event.pull_request.number }}
PREVIEW_URL: https://pr${{ github.event.pull_request.number }}.${{ vars.CLOUDFLARE_PAGES_PROJECT }}.pages.dev
DEPLOYMENT_URL: ${{ steps.deploy.outputs.deployment-url }}
COMMIT: ${{ github.event.pull_request.head.sha }}
10 changes: 10 additions & 0 deletions .github/workflows/release-please.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,13 @@ jobs:
buildPlatform: all
tagName: ${{ needs.release-please.outputs.tag_name }}
changelog: ${{ needs.release-please.outputs.body }}

deploy-web:
needs: release-please
if: needs.release-please.outputs.release_created == 'true'
uses: ./.github/workflows/deploy-web.yml
secrets: inherit
permissions:
contents: read
deployments: write
pull-requests: write
1 change: 1 addition & 0 deletions mise.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@
node = "24"
pnpm = "latest"
"github:protomaps/go-pmtiles" = "1.30.0"
"npm:wrangler" = "4.156.0"
java = "21"
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"build": "vite build",
"preview": "vite preview",
"prepare": "svelte-kit sync && pnpm sqlite:wasm || echo ''",
"sqlite:wasm": "cp node_modules/sql.js/dist/sql-wasm.wasm static/assets/sql-wasm.wasm",
"sqlite:wasm": "mkdir -p static/assets && cp node_modules/sql.js/dist/sql-wasm.wasm static/assets/sql-wasm.wasm",
"api:generate": "openapi-typescript ../api/openapi.json -o src/lib/api/openapi.d.ts",
"db:generate": "drizzle-kit generate",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
Expand Down
11 changes: 10 additions & 1 deletion src/lib/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import createClient from 'openapi-fetch';
import type { components, paths } from './openapi';
import { SyncLineError, SyncStatusError } from '$lib/sync/sync-errors';
import { syncStreamLineSchema } from './sync-lines';
import { APP_VERSION } from '$lib/utils/app-version';
import { Capacitor } from '@capacitor/core';

const PRODUCTION_API_URL = 'https://api.maroonrides.app';
const LINE_SEPARATOR = '\n';
Expand All @@ -22,7 +24,14 @@ export type TripWalkStep = Schemas['TripWalkStep'];
export type TripLegType = Schemas['TripLegType'];
export type TripTimeKind = Schemas['TripTimeKind'];

const client = createClient<paths>({ baseUrl: API_URL });
// Browsers can't set the User-Agent, so the platform and version also go in headers.
const client = createClient<paths>({
baseUrl: API_URL,
headers: {
'X-App-Platform': Capacitor.getPlatform(),
'X-App-Version': APP_VERSION,
},
});

export async function getSupportedVersion(): Promise<string> {
const { data, error } = await client.GET('/api/version/supported');
Expand Down
11 changes: 10 additions & 1 deletion src/lib/components/ui/bottom-sheet/sheet.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import { beforeNavigate, goto } from '$app/navigation';
import * as Card from '$lib/components/ui/card';
import { cn, type WithElementRef } from '$lib/utils.js';
import { SIDE_SHEET_GUTTER_PX, SIDE_SHEET_WIDTH_PX, sideSheetLayout } from '$lib/utils/layout';
import { clamp, last, minBy, range, throttle } from 'lodash-es';
import { onMount, setContext, tick } from 'svelte';
import type { HTMLAttributes } from 'svelte/elements';
Expand Down Expand Up @@ -632,7 +633,15 @@
{#if visible}
<div
bind:this={containerRef}
class={cn('pointer-events-none fixed inset-x-0 bottom-0 z-50 flex flex-col', className)}
class={cn(
'pointer-events-none fixed bottom-0 z-50 flex flex-col',
!sideSheetLayout.current && 'inset-x-0',
className,
)}
style:left={sideSheetLayout.current
? `calc(env(safe-area-inset-left) + ${SIDE_SHEET_GUTTER_PX}px)`
: undefined}
style:width={sideSheetLayout.current ? `${SIDE_SHEET_WIDTH_PX}px` : undefined}
in:fly={{ y: 200, duration: enableTransitions ? animationDuration : 0, opacity: 1 }}
out:fly|global={{ y: currentHeight + safeAreaBottom, duration: animationDuration, opacity: 1 }}
{...restProps}
Expand Down
11 changes: 6 additions & 5 deletions src/lib/components/ui/map/Map.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import { PMTiles, Protocol } from 'pmtiles';
import { onDestroy, onMount, setContext } from 'svelte';
import Spinner from '../spinner/spinner.svelte';
import { PMTILES_URL, resolveMapStyle } from './map-style';

type MapStyleOption = string | MapLibreGL.StyleSpecification;

Expand Down Expand Up @@ -54,6 +55,8 @@

const isReady = $derived(isMounted && isLoaded);

const transformStyle = resolveMapStyle(window.location.href, PMTILES_URL);

export type MapContext = {
getMap: () => MapLibreGL.Map | null;
getBounds: () => MapLibreGL.LngLatBounds | null;
Expand All @@ -79,9 +82,7 @@
const protocol = new Protocol();
MapLibreGL.addProtocol('pmtiles', protocol.tile);

const PMTILE_URL = '/map/cstat.pmtiles';

const p = new PMTiles(PMTILE_URL);
const p = new PMTiles(PMTILES_URL);

// The JS code and the map renderer share this one instance.
protocol.add(p);
Expand All @@ -94,7 +95,6 @@

const mapInstance = new MapLibreGL.Map({
container: mapContainer,
style: requestedStyle,
renderWorldCopies: false,
// TODO move attribution elsewhere
attributionControl: false,
Expand All @@ -120,6 +120,7 @@
loadedStyle = requestedStyle;
});

mapInstance.setStyle(requestedStyle, { transformStyle });
map = mapInstance;
});

Expand All @@ -132,7 +133,7 @@

requestedStyle = style;
loadedStyle = null;
map.setStyle(style, { diff: false });
map.setStyle(style, { diff: false, transformStyle });
});

onDestroy(() => {
Expand Down
4 changes: 2 additions & 2 deletions src/lib/components/ui/map/MapControls.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@
const loaded = $derived(mapCtx.isLoaded());

const positionClasses = {
'top-left': 'top-16 left-2',
'top-right': 'top-16 right-2',
'top-left': 'top-[calc(env(safe-area-inset-top)+8px)] left-2',
'top-right': 'top-[calc(env(safe-area-inset-top)+8px)] right-2',
'bottom-left': 'bottom-2 left-2',
'bottom-right': 'bottom-10 right-2',
};
Expand Down
47 changes: 47 additions & 0 deletions src/lib/components/ui/map/map-style.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import type { StyleSpecification } from 'maplibre-gl';
import { describe, expect, it } from 'vitest';
import { resolveMapStyle } from './map-style';

const BASE_URL = 'https://web.maroonrides.app/route/1';
const R2_PMTILES = 'https://tiles.maroonrides.app/cstat-abc.pmtiles';

const STYLE: StyleSpecification = {
version: 8,
sprite: '/map/sprites/light',
glyphs: '/map/fonts/{fontstack}/{range}.pbf',
sources: {
protomaps: { type: 'vector', url: 'pmtiles:///map/cstat.pmtiles', attribution: 'OSM' },
routes: { type: 'geojson', data: { type: 'FeatureCollection', features: [] } },
},
layers: [],
};

describe('resolveMapStyle', () => {
it('points the basemap at the given pmtiles url', () => {
const style = resolveMapStyle(BASE_URL, R2_PMTILES)(undefined, STYLE);

expect(style.sources.protomaps).toEqual({
type: 'vector',
url: `pmtiles://${R2_PMTILES}`,
attribution: 'OSM',
});
});

it('keeps the bundled basemap url when given the bundled path', () => {
const style = resolveMapStyle(BASE_URL, '/map/cstat.pmtiles')(undefined, STYLE);

expect(style.sources.protomaps).toMatchObject({ url: 'pmtiles:///map/cstat.pmtiles' });
});

it('makes the sprite url absolute against the page origin', () => {
const style = resolveMapStyle(BASE_URL, R2_PMTILES)(undefined, STYLE);

expect(style.sprite).toBe('https://web.maroonrides.app/map/sprites/light');
});

it('leaves other sources untouched', () => {
const style = resolveMapStyle(BASE_URL, R2_PMTILES)(undefined, STYLE);

expect(style.sources.routes).toBe(STYLE.sources.routes);
});
});
22 changes: 22 additions & 0 deletions src/lib/components/ui/map/map-style.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import type { TransformStyleFunction, VectorSourceSpecification } from 'maplibre-gl';

/** Web builds point this at R2, since Cloudflare Pages ignores the Range headers PMTiles needs. */
export const PMTILES_URL: string = import.meta.env.VITE_PMTILES_URL ?? '/map/cstat.pmtiles';

const BASEMAP_SOURCE = 'protomaps';

export function resolveMapStyle(baseUrl: string, pmtilesUrl: string): TransformStyleFunction {
return (_previous, next) => {
const basemap = next.sources[BASEMAP_SOURCE] as VectorSourceSpecification;

return {
...next,
// MapLibre rejects relative sprite URLs.
sprite: typeof next.sprite === 'string' ? new URL(next.sprite, baseUrl).href : next.sprite,
sources: {
...next.sources,
[BASEMAP_SOURCE]: { ...basemap, url: `pmtiles://${pmtilesUrl}` },
},
};
};
}
30 changes: 23 additions & 7 deletions src/lib/managers/map.manager.svelte.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Location, Route, Stop } from '$lib/data/types';
import { findBoundingBox } from '$lib/utils/geo';
import { SIDE_SHEET_OCCUPIED_PX, sideSheetLayout } from '$lib/utils/layout';
import MapLibreGL, { type VectorSourceSpecification } from 'maplibre-gl';

export type MapSelection = { type: 'bus'; id: string } | { type: 'stop'; id: string } | null;
Expand Down Expand Up @@ -92,10 +93,30 @@ class MapManager {
center: [stop.location.longitude, stop.location.latitude],
zoom: 17,
duration: 750,
offset: [0, -this.mapHeight * 0.225],
offset: sideSheetLayout.current
? [SIDE_SHEET_OCCUPIED_PX / 2, 0]
: [0, -this.mapHeight * 0.225],
});
}

#sheetPadding(): MapLibreGL.PaddingOptions {
if (sideSheetLayout.current) {
return {
top: this.mapHeight * 0.1,
bottom: this.mapHeight * 0.1,
left: SIDE_SHEET_OCCUPIED_PX + 40,
right: 40,
};
}

return {
top: this.mapHeight * 0.1,
bottom: this.mapHeight * 0.45 + 8,
left: 40,
right: 40,
};
}

zoomToFitPoints(points: Location[]) {
const [min, max] = findBoundingBox(points);
if (!min || !max) return;
Expand All @@ -108,12 +129,7 @@ class MapManager {
[max.longitude, max.latitude],
],
{
padding: {
top: this.mapHeight * 0.1,
bottom: this.mapHeight * 0.45 + 8,
left: 40,
right: 40,
},
padding: this.#sheetPadding(),
duration: 1000,
maxZoom: 16,
},
Expand Down
7 changes: 7 additions & 0 deletions src/lib/utils/layout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { MediaQuery } from 'svelte/reactivity';

export const SIDE_SHEET_WIDTH_PX = 420;
export const SIDE_SHEET_GUTTER_PX = 16;
export const SIDE_SHEET_OCCUPIED_PX = SIDE_SHEET_WIDTH_PX + SIDE_SHEET_GUTTER_PX;

export const sideSheetLayout = new MediaQuery('(orientation: landscape) and (min-width: 768px)');
Loading