feat: add distance value object and ci workflows
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"semi": true,
|
||||
"trailingComma": "es5",
|
||||
"singleQuote": false,
|
||||
"tabWidth": 2,
|
||||
"useTabs": false,
|
||||
"printWidth": 120,
|
||||
"bracketSpacing": true,
|
||||
"arrowParens": "avoid",
|
||||
"endOfLine": "lf"
|
||||
}
|
||||
+94
-17
@@ -1,23 +1,100 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
import { defineConfig } from "eslint/config";
|
||||
import tsParser from "@typescript-eslint/parser";
|
||||
import tsPlugin from "@typescript-eslint/eslint-plugin";
|
||||
import reactPlugin from "eslint-plugin-react";
|
||||
import reactHooksPlugin from "eslint-plugin-react-hooks";
|
||||
import importPlugin from "eslint-plugin-import";
|
||||
import prettierPlugin from "eslint-plugin-prettier";
|
||||
import unusedImportsPlugin from "eslint-plugin-unused-imports";
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
reactHooks.configs['recommended-latest'],
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
files: ["src/**/*.{ts,tsx}"],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
parser: tsParser,
|
||||
parserOptions: {
|
||||
project: "./tsconfig.app.json",
|
||||
sourceType: "module",
|
||||
ecmaFeatures: {
|
||||
jsx: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
settings: {
|
||||
react: {
|
||||
version: "detect",
|
||||
},
|
||||
"import/resolver": {
|
||||
typescript: {
|
||||
alwaysTryTypes: true,
|
||||
project: ["./tsconfig.json", "./tsconfig.app.json"],
|
||||
},
|
||||
node: {
|
||||
extensions: [".js", ".jsx", ".ts", ".tsx"],
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: {
|
||||
"@typescript-eslint": tsPlugin,
|
||||
react: reactPlugin,
|
||||
"react-hooks": reactHooksPlugin,
|
||||
import: importPlugin,
|
||||
prettier: prettierPlugin,
|
||||
"unused-imports": unusedImportsPlugin,
|
||||
},
|
||||
rules: {
|
||||
"react/react-in-jsx-scope": "off",
|
||||
"react/prop-types": "off",
|
||||
"react-hooks/rules-of-hooks": "error",
|
||||
"react-hooks/exhaustive-deps": "warn",
|
||||
"@typescript-eslint/no-unused-vars": [
|
||||
"warn",
|
||||
{
|
||||
vars: "all",
|
||||
varsIgnorePattern: "^_",
|
||||
args: "after-used",
|
||||
argsIgnorePattern: "^_",
|
||||
},
|
||||
],
|
||||
"no-unused-vars": "off",
|
||||
"unused-imports/no-unused-imports": "error",
|
||||
"import/default": "off",
|
||||
"import/named": "off",
|
||||
"import/namespace": "error",
|
||||
"import/export": "error",
|
||||
"import/order": [
|
||||
"error",
|
||||
{
|
||||
groups: ["builtin", "external", "internal"],
|
||||
pathGroups: [
|
||||
{
|
||||
pattern: "react",
|
||||
group: "external",
|
||||
position: "before",
|
||||
},
|
||||
],
|
||||
pathGroupsExcludedImportTypes: ["react"],
|
||||
"newlines-between": "always",
|
||||
alphabetize: {
|
||||
order: "asc",
|
||||
caseInsensitive: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
"import/extensions": [
|
||||
"error",
|
||||
"ignorePackages",
|
||||
{
|
||||
ts: "never",
|
||||
tsx: "never",
|
||||
js: "never",
|
||||
jsx: "never",
|
||||
},
|
||||
],
|
||||
"prettier/prettier": "error",
|
||||
},
|
||||
},
|
||||
])
|
||||
{
|
||||
ignores: ["dist/*"],
|
||||
},
|
||||
]);
|
||||
|
||||
Generated
+2606
File diff suppressed because it is too large
Load Diff
@@ -7,6 +7,7 @@
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -31,6 +32,8 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.36.0",
|
||||
"@typescript-eslint/eslint-plugin": "^8.24.0",
|
||||
"@typescript-eslint/parser": "^8.24.0",
|
||||
"@types/leaflet": "^1.9.12",
|
||||
"@types/node": "^24.6.0",
|
||||
"@types/react": "^19.1.16",
|
||||
@@ -39,10 +42,16 @@
|
||||
"autoprefixer": "^10.4.21",
|
||||
"babel-plugin-react-compiler": "^19.1.0-rc.3",
|
||||
"eslint": "^9.36.0",
|
||||
"eslint-import-resolver-typescript": "^3.7.0",
|
||||
"eslint-plugin-import": "^2.31.0",
|
||||
"eslint-plugin-prettier": "^5.2.1",
|
||||
"eslint-plugin-react": "^7.37.2",
|
||||
"eslint-plugin-react-hooks": "^5.2.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.22",
|
||||
"eslint-plugin-unused-imports": "^4.1.4",
|
||||
"globals": "^16.4.0",
|
||||
"postcss": "^8.5.6",
|
||||
"prettier": "^3.4.2",
|
||||
"tailwindcss": "^3.4.17",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"typescript": "~5.9.3",
|
||||
|
||||
@@ -3,4 +3,4 @@ export default {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
+283
-285
@@ -1,12 +1,13 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { Layers, Menu, PanelRightClose, PanelRightOpen } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { AppHeader } from '@/components/layout/AppHeader'
|
||||
import { ActivityPanel } from '@/components/panels/ActivityPanel'
|
||||
import { HotspotStatsPanel } from '@/components/panels/HotspotStatsPanel'
|
||||
import { OverviewPanel } from '@/components/panels/OverviewPanel'
|
||||
import { MapViewport } from '@/components/map/MapViewport'
|
||||
import { Layers, Menu, PanelRightClose, PanelRightOpen } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { AppHeader } from "@/components/layout/AppHeader";
|
||||
import { MapViewport } from "@/components/map/MapViewport";
|
||||
import { ActivityPanel } from "@/components/panels/ActivityPanel";
|
||||
import { HotspotStatsPanel } from "@/components/panels/HotspotStatsPanel";
|
||||
import { OverviewPanel } from "@/components/panels/OverviewPanel";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
@@ -16,61 +17,61 @@ import {
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { useHotspotFeed } from '@/hooks/useHotspotFeed'
|
||||
import { useLeafletHeatmap, type TileProvider } from '@/hooks/useLeafletHeatmap'
|
||||
import { useUserLocation } from '@/hooks/useUserLocation'
|
||||
import { cn, distanceInKm, formatCoordinate, formatRelativeTime, formatTimestamp } from '@/lib/utils'
|
||||
import type { Point } from '@/types/api'
|
||||
import { Toaster } from '@/components/ui/toaster'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { useAppStore } from '@/store/useAppStore'
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { Toaster } from "@/components/ui/toaster";
|
||||
import { useToast } from "@/components/ui/use-toast";
|
||||
import { useHotspotFeed } from "@/hooks/useHotspotFeed";
|
||||
import { useLeafletHeatmap, type TileProvider } from "@/hooks/useLeafletHeatmap";
|
||||
import { useUserLocation } from "@/hooks/useUserLocation";
|
||||
import { cn, distanceInKm, formatCoordinate, formatRelativeTime, formatTimestamp } from "@/lib/utils";
|
||||
import { useAppStore } from "@/store/useAppStore";
|
||||
import type { Point } from "@/types/api";
|
||||
|
||||
const RADIUS_KM = 1
|
||||
const RADIUS_KM = 1;
|
||||
|
||||
export default function App() {
|
||||
const [pendingSpot, setPendingSpot] = useState<Point | null>(null)
|
||||
const [isConfirmOpen, setIsConfirmOpen] = useState(false)
|
||||
const [isConfirming, setIsConfirming] = useState(false)
|
||||
const [tileProvider, setTileProvider] = useState<TileProvider>('openstreetmap')
|
||||
const [pendingSpot, setPendingSpot] = useState<Point | null>(null);
|
||||
const [isConfirmOpen, setIsConfirmOpen] = useState(false);
|
||||
const [isConfirming, setIsConfirming] = useState(false);
|
||||
const [tileProvider, setTileProvider] = useState<TileProvider>("openstreetmap");
|
||||
const [isDetailsOpen, setIsDetailsOpen] = useState(() => {
|
||||
if (typeof window === 'undefined') {
|
||||
return false
|
||||
if (typeof window === "undefined") {
|
||||
return false;
|
||||
}
|
||||
return window.innerWidth >= 1024
|
||||
})
|
||||
return window.innerWidth >= 1024;
|
||||
});
|
||||
const [isHeaderCollapsed, setIsHeaderCollapsed] = useState(() => {
|
||||
if (typeof window === 'undefined') {
|
||||
return false
|
||||
if (typeof window === "undefined") {
|
||||
return false;
|
||||
}
|
||||
return window.innerWidth < 768
|
||||
})
|
||||
return window.innerWidth < 768;
|
||||
});
|
||||
|
||||
const { t, i18n } = useTranslation()
|
||||
const locale = i18n.language === 'fr' ? 'fr-FR' : 'en-US'
|
||||
const { t, i18n } = useTranslation();
|
||||
const locale = i18n.language === "fr" ? "fr-FR" : "en-US";
|
||||
const distanceFormatter = useMemo(
|
||||
() =>
|
||||
new Intl.NumberFormat(locale, {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
}),
|
||||
[locale],
|
||||
)
|
||||
[locale]
|
||||
);
|
||||
|
||||
const tileOptions = useMemo(
|
||||
() => [
|
||||
{ value: 'openstreetmap' as TileProvider, label: t('map.tiles.openstreetmap') },
|
||||
{ value: 'mapbox' as TileProvider, label: t('map.tiles.mapbox') },
|
||||
{ value: "openstreetmap" as TileProvider, label: t("map.tiles.openstreetmap") },
|
||||
{ value: "mapbox" as TileProvider, label: t("map.tiles.mapbox") },
|
||||
],
|
||||
[t],
|
||||
)
|
||||
[t]
|
||||
);
|
||||
|
||||
const userLocation = useAppStore((state) => state.userLocation)
|
||||
const locationError = useAppStore((state) => state.locationError)
|
||||
const isRequestingLocation = useAppStore((state) => state.isRequestingLocation)
|
||||
const { refresh: refreshLocation } = useUserLocation()
|
||||
const userLocation = useAppStore(state => state.userLocation);
|
||||
const locationError = useAppStore(state => state.locationError);
|
||||
const isRequestingLocation = useAppStore(state => state.isRequestingLocation);
|
||||
const { refresh: refreshLocation } = useUserLocation();
|
||||
|
||||
const {
|
||||
status,
|
||||
@@ -82,123 +83,120 @@ export default function App() {
|
||||
selectVisibleLatestByUser,
|
||||
myLatestPoint,
|
||||
lastUpdated,
|
||||
} = useHotspotFeed({ userLocation: userLocation ?? null })
|
||||
} = useHotspotFeed({ userLocation: userLocation ?? null });
|
||||
|
||||
const visibleDensity = useMemo(
|
||||
() => selectVisibleDensity(userLocation ?? null),
|
||||
[selectVisibleDensity, userLocation],
|
||||
)
|
||||
[selectVisibleDensity, userLocation]
|
||||
);
|
||||
|
||||
const visiblePoints = useMemo(
|
||||
() => selectVisiblePoints(userLocation ?? null),
|
||||
[selectVisiblePoints, userLocation],
|
||||
)
|
||||
const visiblePoints = useMemo(() => selectVisiblePoints(userLocation ?? null), [selectVisiblePoints, userLocation]);
|
||||
|
||||
const visibleLatestByUser = useMemo(
|
||||
() => selectVisibleLatestByUser(userLocation ?? null),
|
||||
[selectVisibleLatestByUser, userLocation],
|
||||
)
|
||||
[selectVisibleLatestByUser, userLocation]
|
||||
);
|
||||
|
||||
const localTotals = useMemo(() => {
|
||||
const uniqueUsers = new Set<string>()
|
||||
visibleLatestByUser.forEach((point) => uniqueUsers.add(point.userKey))
|
||||
return { points: visiblePoints.length, contributors: uniqueUsers.size }
|
||||
}, [visibleLatestByUser, visiblePoints])
|
||||
const uniqueUsers = new Set<string>();
|
||||
visibleLatestByUser.forEach(point => uniqueUsers.add(point.userKey));
|
||||
return { points: visiblePoints.length, contributors: uniqueUsers.size };
|
||||
}, [visibleLatestByUser, visiblePoints]);
|
||||
|
||||
const myVisibleSignal = useMemo(() => {
|
||||
if (!myLatestPoint) {
|
||||
return null
|
||||
return null;
|
||||
}
|
||||
if (userLocation && distanceInKm(userLocation, myLatestPoint.signalLocation) > RADIUS_KM) {
|
||||
return null
|
||||
return null;
|
||||
}
|
||||
return myLatestPoint
|
||||
}, [myLatestPoint, userLocation])
|
||||
return myLatestPoint;
|
||||
}, [myLatestPoint, userLocation]);
|
||||
|
||||
const statusLabel = t(`status.${status}`)
|
||||
const lastUpdatedLabel = lastUpdated ? formatRelativeTime(lastUpdated, locale) : t('common.never')
|
||||
const isLoading = status === 'loading'
|
||||
const isPosting = status === 'posting'
|
||||
const isRefreshing = status === 'refreshing'
|
||||
const hasLocation = Boolean(userLocation)
|
||||
const showLocationCta = !hasLocation || Boolean(locationError)
|
||||
const statusLabel = t(`status.${status}`);
|
||||
const lastUpdatedLabel = lastUpdated ? formatRelativeTime(lastUpdated, locale) : t("common.never");
|
||||
const isLoading = status === "loading";
|
||||
const isPosting = status === "posting";
|
||||
const isRefreshing = status === "refreshing";
|
||||
const hasLocation = Boolean(userLocation);
|
||||
const showLocationCta = !hasLocation || Boolean(locationError);
|
||||
|
||||
const translatedLocationError = locationError ? t(locationError) : null
|
||||
const translatedLocationError = locationError ? t(locationError) : null;
|
||||
const locationHint = translatedLocationError
|
||||
? translatedLocationError
|
||||
: hasLocation
|
||||
? t('location.hint.showing', { radius: RADIUS_KM })
|
||||
? t("location.hint.showing", { radius: RADIUS_KM })
|
||||
: isRequestingLocation
|
||||
? t('location.hint.requesting')
|
||||
: t('location.hint.allow')
|
||||
? t("location.hint.requesting")
|
||||
: t("location.hint.allow");
|
||||
|
||||
const { mapContainerRef, focusOn, fitToHeat } = useLeafletHeatmap({
|
||||
heatCells: visibleDensity,
|
||||
userLocation: userLocation ?? null,
|
||||
onRequestSpot: (position) => {
|
||||
setPendingSpot(position)
|
||||
setIsConfirmOpen(true)
|
||||
onRequestSpot: position => {
|
||||
setPendingSpot(position);
|
||||
setIsConfirmOpen(true);
|
||||
},
|
||||
tileProvider,
|
||||
})
|
||||
});
|
||||
|
||||
const { toast } = useToast()
|
||||
const { toast } = useToast();
|
||||
|
||||
useEffect(() => {
|
||||
if (!error) {
|
||||
return
|
||||
return;
|
||||
}
|
||||
const description = error.detail ?? t(error.key, error.values ?? {})
|
||||
const description = error.detail ?? t(error.key, error.values ?? {});
|
||||
toast({
|
||||
variant: 'destructive',
|
||||
title: t('errors.title'),
|
||||
variant: "destructive",
|
||||
title: t("errors.title"),
|
||||
description,
|
||||
duration: 6000,
|
||||
})
|
||||
}, [error, t, toast])
|
||||
});
|
||||
}, [error, t, toast]);
|
||||
|
||||
const handleConfirmSignal = useCallback(async () => {
|
||||
if (!pendingSpot) {
|
||||
return
|
||||
return;
|
||||
}
|
||||
setIsConfirming(true)
|
||||
const result = await submitPoint(pendingSpot)
|
||||
setIsConfirming(false)
|
||||
setIsConfirming(true);
|
||||
const result = await submitPoint(pendingSpot);
|
||||
setIsConfirming(false);
|
||||
if (result.success) {
|
||||
setIsConfirmOpen(false)
|
||||
setPendingSpot(null)
|
||||
setIsConfirmOpen(false);
|
||||
setPendingSpot(null);
|
||||
}
|
||||
}, [pendingSpot, submitPoint])
|
||||
}, [pendingSpot, submitPoint]);
|
||||
|
||||
const handleRefresh = useCallback(() => {
|
||||
fetchSnapshot().catch(() => undefined)
|
||||
}, [fetchSnapshot])
|
||||
fetchSnapshot().catch(() => undefined);
|
||||
}, [fetchSnapshot]);
|
||||
|
||||
const handleFocusHeat = useCallback(() => {
|
||||
fitToHeat()
|
||||
}, [fitToHeat])
|
||||
fitToHeat();
|
||||
}, [fitToHeat]);
|
||||
|
||||
const handleLocateUser = useCallback(() => {
|
||||
if (userLocation) {
|
||||
focusOn(userLocation, 14)
|
||||
focusOn(userLocation, 14);
|
||||
} else {
|
||||
refreshLocation()
|
||||
refreshLocation();
|
||||
}
|
||||
}, [focusOn, refreshLocation, userLocation])
|
||||
}, [focusOn, refreshLocation, userLocation]);
|
||||
|
||||
const handleFocusMySignal = useCallback(() => {
|
||||
if (myVisibleSignal) {
|
||||
focusOn({ lat: myVisibleSignal.signalLocation.lat, lng: myVisibleSignal.signalLocation.lng }, 15)
|
||||
focusOn({ lat: myVisibleSignal.signalLocation.lat, lng: myVisibleSignal.signalLocation.lng }, 15);
|
||||
}
|
||||
}, [focusOn, myVisibleSignal])
|
||||
}, [focusOn, myVisibleSignal]);
|
||||
|
||||
const handleManualReport = useCallback(() => {
|
||||
if (!userLocation) {
|
||||
return
|
||||
return;
|
||||
}
|
||||
setPendingSpot(userLocation)
|
||||
setIsConfirmOpen(true)
|
||||
}, [userLocation])
|
||||
setPendingSpot(userLocation);
|
||||
setIsConfirmOpen(true);
|
||||
}, [userLocation]);
|
||||
|
||||
const dangerCells = useMemo(
|
||||
() =>
|
||||
@@ -206,239 +204,239 @@ export default function App() {
|
||||
.sort((a, b) => b.intensity - a.intensity)
|
||||
.slice(0, 5)
|
||||
.map((cell, index) => {
|
||||
const coordinates = t('common.coordinates', {
|
||||
const coordinates = t("common.coordinates", {
|
||||
lat: formatCoordinate(cell.lat, locale),
|
||||
lng: formatCoordinate(cell.lng, locale),
|
||||
})
|
||||
});
|
||||
const distanceLabel = userLocation
|
||||
? `${distanceFormatter.format(distanceInKm(userLocation, cell))} km`
|
||||
: null
|
||||
: null;
|
||||
return {
|
||||
id: `${cell.lat}-${cell.lng}-${index}`,
|
||||
title: t('hotspots.itemTitle', { index: index + 1 }),
|
||||
title: t("hotspots.itemTitle", { index: index + 1 }),
|
||||
subtitle:
|
||||
distanceLabel !== null
|
||||
? t('hotspots.itemSubtitleWithDistance', { distance: distanceLabel, coordinates })
|
||||
: t('hotspots.itemSubtitle', { coordinates }),
|
||||
? t("hotspots.itemSubtitleWithDistance", { distance: distanceLabel, coordinates })
|
||||
: t("hotspots.itemSubtitle", { coordinates }),
|
||||
intensity: cell.intensity,
|
||||
onFocus: () => focusOn({ lat: cell.lat, lng: cell.lng }, 15),
|
||||
}
|
||||
};
|
||||
}),
|
||||
[visibleDensity, userLocation, focusOn, distanceFormatter, t, locale],
|
||||
)
|
||||
[visibleDensity, userLocation, focusOn, distanceFormatter, t, locale]
|
||||
);
|
||||
|
||||
const recentActivity = useMemo(
|
||||
() =>
|
||||
[...visiblePoints]
|
||||
.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
|
||||
.slice(0, 8)
|
||||
.map((point) => {
|
||||
const coordinates = t('common.coordinates', {
|
||||
.map(point => {
|
||||
const coordinates = t("common.coordinates", {
|
||||
lat: formatCoordinate(point.signalLocation.lat, locale),
|
||||
lng: formatCoordinate(point.signalLocation.lng, locale),
|
||||
})
|
||||
});
|
||||
const distanceLabel = userLocation
|
||||
? t('activityItem.distance', {
|
||||
? t("activityItem.distance", {
|
||||
distance: `${distanceFormatter.format(distanceInKm(userLocation, point.signalLocation))} km`,
|
||||
})
|
||||
: formatTimestamp(point.createdAt, locale)
|
||||
: formatTimestamp(point.createdAt, locale);
|
||||
return {
|
||||
id: point.id,
|
||||
title: coordinates,
|
||||
subtitle: t('activityItem.user', { id: point.userKey.slice(0, 4).toUpperCase() }),
|
||||
subtitle: t("activityItem.user", { id: point.userKey.slice(0, 4).toUpperCase() }),
|
||||
timestampLabel: formatRelativeTime(point.createdAt, locale),
|
||||
distanceLabel,
|
||||
onFocus: () => focusOn({ lat: point.signalLocation.lat, lng: point.signalLocation.lng }, 15),
|
||||
}
|
||||
};
|
||||
}),
|
||||
[visiblePoints, userLocation, focusOn, distanceFormatter, t, locale],
|
||||
)
|
||||
[visiblePoints, userLocation, focusOn, distanceFormatter, t, locale]
|
||||
);
|
||||
|
||||
const confirmationLat = pendingSpot ? formatCoordinate(pendingSpot.lat, locale) : '--'
|
||||
const confirmationLng = pendingSpot ? formatCoordinate(pendingSpot.lng, locale) : '--'
|
||||
const isDialogDisabled = !pendingSpot || isConfirming
|
||||
const detailsToggleLabel = isDetailsOpen ? t('details.close') : t('details.open')
|
||||
const confirmationLat = pendingSpot ? formatCoordinate(pendingSpot.lat, locale) : "--";
|
||||
const confirmationLng = pendingSpot ? formatCoordinate(pendingSpot.lng, locale) : "--";
|
||||
const isDialogDisabled = !pendingSpot || isConfirming;
|
||||
const detailsToggleLabel = isDetailsOpen ? t("details.close") : t("details.open");
|
||||
const detailsPanelClassName = cn(
|
||||
'pointer-events-auto fixed inset-x-0 bottom-0 z-40 flex max-h-[85vh] w-full flex-col overflow-hidden rounded-t-3xl border border-border/70 bg-background/95 shadow-2xl backdrop-blur transition-transform duration-300 sm:left-auto sm:right-6 sm:top-24 sm:bottom-6 sm:max-h-[calc(100vh-8rem)] sm:w-[min(380px,calc(100vw-4rem))] sm:rounded-3xl',
|
||||
isDetailsOpen
|
||||
? 'translate-y-0 sm:translate-x-0'
|
||||
: 'translate-y-[calc(100%+1rem)] sm:translate-x-[calc(100%+2rem)]',
|
||||
)
|
||||
"pointer-events-auto fixed inset-x-0 bottom-0 z-40 flex max-h-[85vh] w-full flex-col overflow-hidden rounded-t-3xl border border-border/70 bg-background/95 shadow-2xl backdrop-blur transition-transform duration-300 sm:left-auto sm:right-6 sm:top-24 sm:bottom-6 sm:max-h-[calc(100vh-8rem)] sm:w-[min(380px,calc(100vw-4rem))] sm:rounded-3xl",
|
||||
isDetailsOpen ? "translate-y-0 sm:translate-x-0" : "translate-y-[calc(100%+1rem)] sm:translate-x-[calc(100%+2rem)]"
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="relative min-h-screen w-full overflow-hidden bg-background text-foreground">
|
||||
<MapViewport
|
||||
containerRef={mapContainerRef}
|
||||
isPosting={isPosting || isConfirming}
|
||||
isLoading={isLoading}
|
||||
confirmationHint={isConfirmOpen ? t('map.confirmationHint') : null}
|
||||
className="min-h-screen"
|
||||
/>
|
||||
isPosting={isPosting || isConfirming}
|
||||
isLoading={isLoading}
|
||||
confirmationHint={isConfirmOpen ? t("map.confirmationHint") : null}
|
||||
className="min-h-screen"
|
||||
/>
|
||||
|
||||
<div className="pointer-events-none absolute inset-0 flex flex-col">
|
||||
<div className="flex items-start justify-between gap-3 p-4 sm:p-6">
|
||||
<div className="pointer-events-auto">
|
||||
<AppHeader
|
||||
status={status}
|
||||
statusLabel={statusLabel}
|
||||
lastUpdatedLabel={lastUpdatedLabel}
|
||||
onRefresh={handleRefresh}
|
||||
onFocusHeat={handleFocusHeat}
|
||||
onLocateUser={handleLocateUser}
|
||||
onFocusMySignal={handleFocusMySignal}
|
||||
disableRefresh={isLoading || isRefreshing || isPosting}
|
||||
disableHeat={visibleDensity.length === 0}
|
||||
disableLocate={!hasLocation}
|
||||
disableMySignal={!myVisibleSignal}
|
||||
collapsed={isHeaderCollapsed}
|
||||
onToggleCollapse={() => setIsHeaderCollapsed((prev) => !prev)}
|
||||
/>
|
||||
<div className="pointer-events-none absolute inset-0 flex flex-col">
|
||||
<div className="flex items-start justify-between gap-3 p-4 sm:p-6">
|
||||
<div className="pointer-events-auto">
|
||||
<AppHeader
|
||||
status={status}
|
||||
statusLabel={statusLabel}
|
||||
lastUpdatedLabel={lastUpdatedLabel}
|
||||
onRefresh={handleRefresh}
|
||||
onFocusHeat={handleFocusHeat}
|
||||
onLocateUser={handleLocateUser}
|
||||
onFocusMySignal={handleFocusMySignal}
|
||||
disableRefresh={isLoading || isRefreshing || isPosting}
|
||||
disableHeat={visibleDensity.length === 0}
|
||||
disableLocate={!hasLocation}
|
||||
disableMySignal={!myVisibleSignal}
|
||||
collapsed={isHeaderCollapsed}
|
||||
onToggleCollapse={() => setIsHeaderCollapsed(prev => !prev)}
|
||||
/>
|
||||
</div>
|
||||
<div className="pointer-events-auto hidden sm:flex">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="icon"
|
||||
onClick={() => setIsDetailsOpen(prev => !prev)}
|
||||
aria-label={detailsToggleLabel}
|
||||
aria-expanded={isDetailsOpen}
|
||||
className="h-11 w-11 rounded-full border border-border/60 bg-background/80 shadow-lg backdrop-blur hover:bg-background"
|
||||
>
|
||||
{isDetailsOpen ? <PanelRightClose className="h-4 w-4" /> : <PanelRightOpen className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="pointer-events-auto hidden sm:flex">
|
||||
</div>
|
||||
|
||||
{!isDetailsOpen && (
|
||||
<div className="pointer-events-auto fixed bottom-4 right-4 z-30 sm:hidden">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="icon"
|
||||
onClick={() => setIsDetailsOpen((prev) => !prev)}
|
||||
size="sm"
|
||||
onClick={() => setIsDetailsOpen(true)}
|
||||
aria-label={detailsToggleLabel}
|
||||
aria-expanded={isDetailsOpen}
|
||||
className="h-11 w-11 rounded-full border border-border/60 bg-background/80 shadow-lg backdrop-blur hover:bg-background"
|
||||
className="flex items-center gap-2 rounded-full border border-border/60 bg-background/85 px-4 py-2 text-xs font-semibold uppercase tracking-wide shadow-lg backdrop-blur"
|
||||
>
|
||||
{isDetailsOpen ? <PanelRightClose className="h-4 w-4" /> : <PanelRightOpen className="h-4 w-4" />}
|
||||
<Menu className="h-4 w-4" />
|
||||
<span>{t("details.open")}</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isDetailsOpen && (
|
||||
<div className="pointer-events-auto fixed bottom-4 right-4 z-30 sm:hidden">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => setIsDetailsOpen(true)}
|
||||
aria-label={detailsToggleLabel}
|
||||
className="flex items-center gap-2 rounded-full border border-border/60 bg-background/85 px-4 py-2 text-xs font-semibold uppercase tracking-wide shadow-lg backdrop-blur"
|
||||
>
|
||||
<Menu className="h-4 w-4" />
|
||||
<span>{t('details.open')}</span>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<aside
|
||||
className={detailsPanelClassName}
|
||||
role="complementary"
|
||||
aria-label={t('details.title')}
|
||||
aria-hidden={!isDetailsOpen}
|
||||
>
|
||||
<header className="flex items-center justify-between gap-2 border-b border-border/60 bg-background/80 px-4 py-3 backdrop-blur">
|
||||
<div className="flex flex-col">
|
||||
<span className="text-sm font-semibold">{t('details.title')}</span>
|
||||
<span className="text-xs text-muted-foreground">{t('details.description')}</span>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setIsDetailsOpen(false)}
|
||||
aria-label={t('details.close')}
|
||||
className="h-9 w-9 rounded-full border border-border/60 bg-muted/60 backdrop-blur hover:bg-muted"
|
||||
>
|
||||
<PanelRightClose className="h-4 w-4" />
|
||||
</Button>
|
||||
</header>
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="flex flex-col gap-4 p-4 pb-6">
|
||||
<div className="rounded-2xl border border-border/60 bg-muted/40 p-4 shadow-sm">
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="flex h-10 w-10 items-center justify-center rounded-2xl border border-border/60 bg-background/80 text-primary">
|
||||
<Layers className="h-5 w-5" />
|
||||
</span>
|
||||
<div className="flex flex-1 flex-col">
|
||||
<span className="text-sm font-semibold">{t('map.tiles.title')}</span>
|
||||
<span className="text-xs text-muted-foreground">{t('map.tiles.subtitle')}</span>
|
||||
<aside
|
||||
className={detailsPanelClassName}
|
||||
role="complementary"
|
||||
aria-label={t("details.title")}
|
||||
aria-hidden={!isDetailsOpen}
|
||||
>
|
||||
<header className="flex items-center justify-between gap-2 border-b border-border/60 bg-background/80 px-4 py-3 backdrop-blur">
|
||||
<div className="flex flex-col">
|
||||
<span className="text-sm font-semibold">{t("details.title")}</span>
|
||||
<span className="text-xs text-muted-foreground">{t("details.description")}</span>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setIsDetailsOpen(false)}
|
||||
aria-label={t("details.close")}
|
||||
className="h-9 w-9 rounded-full border border-border/60 bg-muted/60 backdrop-blur hover:bg-muted"
|
||||
>
|
||||
<PanelRightClose className="h-4 w-4" />
|
||||
</Button>
|
||||
</header>
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="flex flex-col gap-4 p-4 pb-6">
|
||||
<div className="rounded-2xl border border-border/60 bg-muted/40 p-4 shadow-sm">
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="flex h-10 w-10 items-center justify-center rounded-2xl border border-border/60 bg-background/80 text-primary">
|
||||
<Layers className="h-5 w-5" />
|
||||
</span>
|
||||
<div className="flex flex-1 flex-col">
|
||||
<span className="text-sm font-semibold">{t("map.tiles.title")}</span>
|
||||
<span className="text-xs text-muted-foreground">{t("map.tiles.subtitle")}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
{tileOptions.map(option => (
|
||||
<Button
|
||||
key={option.value}
|
||||
type="button"
|
||||
variant={tileProvider === option.value ? "default" : "outline"}
|
||||
size="sm"
|
||||
onClick={() => setTileProvider(option.value)}
|
||||
className={cn(
|
||||
"rounded-full border border-border/60 px-4 py-1 text-xs font-medium transition-colors",
|
||||
tileProvider === option.value
|
||||
? "shadow-sm"
|
||||
: "bg-background/80 text-muted-foreground hover:bg-background"
|
||||
)}
|
||||
>
|
||||
{option.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
{tileOptions.map((option) => (
|
||||
<Button
|
||||
key={option.value}
|
||||
type="button"
|
||||
variant={tileProvider === option.value ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => setTileProvider(option.value)}
|
||||
className={cn(
|
||||
'rounded-full border border-border/60 px-4 py-1 text-xs font-medium transition-colors',
|
||||
tileProvider === option.value
|
||||
? 'shadow-sm'
|
||||
: 'bg-background/80 text-muted-foreground hover:bg-background',
|
||||
)}
|
||||
>
|
||||
{option.label}
|
||||
</Button>
|
||||
))}
|
||||
|
||||
<OverviewPanel
|
||||
nearbySignals={localTotals.points}
|
||||
uniqueContributors={localTotals.contributors}
|
||||
lastUpdatedLabel={lastUpdatedLabel}
|
||||
mySignalLabel={myVisibleSignal ? formatRelativeTime(myVisibleSignal.createdAt, locale) : null}
|
||||
error={error}
|
||||
onReport={handleManualReport}
|
||||
onRetry={handleRefresh}
|
||||
isPosting={isPosting || isConfirming}
|
||||
locationHint={locationHint}
|
||||
showLocationCta={showLocationCta}
|
||||
disableReport={!hasLocation}
|
||||
/>
|
||||
<HotspotStatsPanel
|
||||
hasLocation={hasLocation}
|
||||
radiusKm={RADIUS_KM}
|
||||
locationHint={locationHint}
|
||||
cells={dangerCells}
|
||||
/>
|
||||
<ActivityPanel items={recentActivity} emptyMessage={t("activity.empty")} />
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</aside>
|
||||
|
||||
<AlertDialog
|
||||
open={isConfirmOpen}
|
||||
onOpenChange={nextOpen => {
|
||||
setIsConfirmOpen(nextOpen);
|
||||
if (!nextOpen) {
|
||||
setPendingSpot(null);
|
||||
setIsConfirming(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t("dialog.confirmSignal.title")}</AlertDialogTitle>
|
||||
<AlertDialogDescription>{t("dialog.confirmSignal.description")}</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<div className="rounded-2xl border border-border/60 bg-muted/40 p-4 text-sm">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">{t("dialog.confirmSignal.latitude")}</span>
|
||||
<span className="font-medium text-foreground">{confirmationLat}°</span>
|
||||
</div>
|
||||
<div className="mt-3 flex items-center justify-between">
|
||||
<span className="text-muted-foreground">{t("dialog.confirmSignal.longitude")}</span>
|
||||
<span className="font-medium text-foreground">{confirmationLng}°</span>
|
||||
</div>
|
||||
<p className="mt-4 text-xs text-muted-foreground">
|
||||
{t("dialog.confirmSignal.reach", { radius: RADIUS_KM })}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<OverviewPanel
|
||||
nearbySignals={localTotals.points}
|
||||
uniqueContributors={localTotals.contributors}
|
||||
lastUpdatedLabel={lastUpdatedLabel}
|
||||
mySignalLabel={myVisibleSignal ? formatRelativeTime(myVisibleSignal.createdAt, locale) : null}
|
||||
error={error}
|
||||
onReport={handleManualReport}
|
||||
onRetry={handleRefresh}
|
||||
isPosting={isPosting || isConfirming}
|
||||
locationHint={locationHint}
|
||||
showLocationCta={showLocationCta}
|
||||
disableReport={!hasLocation}
|
||||
/>
|
||||
<HotspotStatsPanel
|
||||
hasLocation={hasLocation}
|
||||
radiusKm={RADIUS_KM}
|
||||
locationHint={locationHint}
|
||||
cells={dangerCells}
|
||||
/>
|
||||
<ActivityPanel items={recentActivity} emptyMessage={t('activity.empty')} />
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</aside>
|
||||
|
||||
<AlertDialog
|
||||
open={isConfirmOpen}
|
||||
onOpenChange={(nextOpen) => {
|
||||
setIsConfirmOpen(nextOpen)
|
||||
if (!nextOpen) {
|
||||
setPendingSpot(null)
|
||||
setIsConfirming(false)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t('dialog.confirmSignal.title')}</AlertDialogTitle>
|
||||
<AlertDialogDescription>{t('dialog.confirmSignal.description')}</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<div className="rounded-2xl border border-border/60 bg-muted/40 p-4 text-sm">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-muted-foreground">{t('dialog.confirmSignal.latitude')}</span>
|
||||
<span className="font-medium text-foreground">{confirmationLat}°</span>
|
||||
</div>
|
||||
<div className="mt-3 flex items-center justify-between">
|
||||
<span className="text-muted-foreground">{t('dialog.confirmSignal.longitude')}</span>
|
||||
<span className="font-medium text-foreground">{confirmationLng}°</span>
|
||||
</div>
|
||||
<p className="mt-4 text-xs text-muted-foreground">{t('dialog.confirmSignal.reach', { radius: RADIUS_KM })}</p>
|
||||
</div>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isConfirming}>{t('dialog.confirmSignal.cancel')}</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleConfirmSignal} disabled={isDialogDisabled}>
|
||||
{isConfirming ? t('dialog.confirmSignal.sending') : t('dialog.confirmSignal.confirm')}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isConfirming}>{t("dialog.confirmSignal.cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleConfirmSignal} disabled={isDialogDisabled}>
|
||||
{isConfirming ? t("dialog.confirmSignal.sending") : t("dialog.confirmSignal.confirm")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
<Toaster />
|
||||
</>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,28 +1,28 @@
|
||||
import { ChevronDown, ChevronUp, Flame, Focus, LocateFixed, MapPin, RefreshCw } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { ChevronDown, ChevronUp, Flame, Focus, LocateFixed, MapPin, RefreshCw } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { LanguageToggle } from '@/components/layout/LanguageToggle'
|
||||
import { ThemeToggle } from '@/components/layout/ThemeToggle'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { FeedStatus } from '@/types/api'
|
||||
import { LanguageToggle } from "@/components/layout/LanguageToggle";
|
||||
import { ThemeToggle } from "@/components/layout/ThemeToggle";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { FeedStatus } from "@/types/api";
|
||||
|
||||
interface AppHeaderProps {
|
||||
status: FeedStatus
|
||||
statusLabel: string
|
||||
lastUpdatedLabel: string
|
||||
onRefresh: () => void
|
||||
onFocusHeat: () => void
|
||||
onLocateUser: () => void
|
||||
onFocusMySignal: () => void
|
||||
disableRefresh: boolean
|
||||
disableHeat: boolean
|
||||
disableLocate: boolean
|
||||
disableMySignal: boolean
|
||||
collapsed: boolean
|
||||
onToggleCollapse: () => void
|
||||
className?: string
|
||||
status: FeedStatus;
|
||||
statusLabel: string;
|
||||
lastUpdatedLabel: string;
|
||||
onRefresh: () => void;
|
||||
onFocusHeat: () => void;
|
||||
onLocateUser: () => void;
|
||||
onFocusMySignal: () => void;
|
||||
disableRefresh: boolean;
|
||||
disableHeat: boolean;
|
||||
disableLocate: boolean;
|
||||
disableMySignal: boolean;
|
||||
collapsed: boolean;
|
||||
onToggleCollapse: () => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function AppHeader({
|
||||
@@ -41,21 +41,18 @@ export function AppHeader({
|
||||
onToggleCollapse,
|
||||
className,
|
||||
}: AppHeaderProps) {
|
||||
const { t } = useTranslation()
|
||||
const isError = status === 'error'
|
||||
const { t } = useTranslation();
|
||||
const isError = status === "error";
|
||||
|
||||
const statusBadge = (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className={cn(
|
||||
'inline-flex items-center gap-2 rounded-full border border-border/60 bg-muted/60 px-3 py-1 text-xs font-medium uppercase tracking-wide',
|
||||
collapsed && 'px-2 py-1 text-[11px] font-semibold',
|
||||
"inline-flex items-center gap-2 rounded-full border border-border/60 bg-muted/60 px-3 py-1 text-xs font-medium uppercase tracking-wide",
|
||||
collapsed && "px-2 py-1 text-[11px] font-semibold"
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={`flex items-center gap-2 ${isError ? 'text-destructive' : 'text-primary'}`}
|
||||
aria-live="polite"
|
||||
>
|
||||
<span className={`flex items-center gap-2 ${isError ? "text-destructive" : "text-primary"}`} aria-live="polite">
|
||||
<span className="relative block h-2.5 w-2.5 rounded-full bg-current">
|
||||
<span className="absolute inset-[-0.35rem] rounded-full border border-current opacity-40 animate-status-pulse" />
|
||||
</span>
|
||||
@@ -63,18 +60,18 @@ export function AppHeader({
|
||||
</span>
|
||||
{!collapsed && (
|
||||
<span className="text-[10px] uppercase text-muted-foreground">
|
||||
{t('header.badge.updated', { time: lastUpdatedLabel })}
|
||||
{t("header.badge.updated", { time: lastUpdatedLabel })}
|
||||
</span>
|
||||
)}
|
||||
</Badge>
|
||||
)
|
||||
);
|
||||
|
||||
return (
|
||||
<header
|
||||
className={cn(
|
||||
'flex w-full max-w-[420px] flex-col gap-3 rounded-3xl border border-border/60 bg-background/90 p-4 text-sm shadow-xl backdrop-blur transition-all',
|
||||
collapsed && 'max-w-[240px] bg-background/80 p-3',
|
||||
className,
|
||||
"flex w-full max-w-[420px] flex-col gap-3 rounded-3xl border border-border/60 bg-background/90 p-4 text-sm shadow-xl backdrop-blur transition-all",
|
||||
collapsed && "max-w-[240px] bg-background/80 p-3",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
@@ -83,15 +80,15 @@ export function AppHeader({
|
||||
<Flame className="h-5 w-5" />
|
||||
</span>
|
||||
<div className="flex flex-col">
|
||||
<span className="text-base font-semibold sm:text-lg">{t('app.name')}</span>
|
||||
{!collapsed && <span className="text-xs text-muted-foreground sm:text-sm">{t('app.tagline')}</span>}
|
||||
<span className="text-base font-semibold sm:text-lg">{t("app.name")}</span>
|
||||
{!collapsed && <span className="text-xs text-muted-foreground sm:text-sm">{t("app.tagline")}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={onToggleCollapse}
|
||||
aria-label={collapsed ? t('header.actions.expand') : t('header.actions.collapse')}
|
||||
aria-label={collapsed ? t("header.actions.expand") : t("header.actions.collapse")}
|
||||
className="h-9 w-9 rounded-full border border-border/50 bg-muted/60 backdrop-blur hover:bg-muted"
|
||||
>
|
||||
{collapsed ? <ChevronDown className="h-4 w-4" /> : <ChevronUp className="h-4 w-4" />}
|
||||
@@ -105,7 +102,7 @@ export function AppHeader({
|
||||
size="icon"
|
||||
onClick={onRefresh}
|
||||
disabled={disableRefresh}
|
||||
aria-label={t('header.actions.refresh')}
|
||||
aria-label={t("header.actions.refresh")}
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
</Button>
|
||||
@@ -114,7 +111,7 @@ export function AppHeader({
|
||||
size="icon"
|
||||
onClick={onFocusHeat}
|
||||
disabled={disableHeat}
|
||||
aria-label={t('header.actions.focusHeat')}
|
||||
aria-label={t("header.actions.focusHeat")}
|
||||
>
|
||||
<Focus className="h-4 w-4" />
|
||||
</Button>
|
||||
@@ -123,7 +120,7 @@ export function AppHeader({
|
||||
size="icon"
|
||||
onClick={onLocateUser}
|
||||
disabled={disableLocate}
|
||||
aria-label={t('header.actions.locate')}
|
||||
aria-label={t("header.actions.locate")}
|
||||
>
|
||||
<LocateFixed className="h-4 w-4" />
|
||||
</Button>
|
||||
@@ -132,7 +129,7 @@ export function AppHeader({
|
||||
size="icon"
|
||||
onClick={onFocusMySignal}
|
||||
disabled={disableMySignal}
|
||||
aria-label={t('header.actions.mySignal')}
|
||||
aria-label={t("header.actions.mySignal")}
|
||||
>
|
||||
<MapPin className="h-4 w-4" />
|
||||
</Button>
|
||||
@@ -141,5 +138,5 @@ export function AppHeader({
|
||||
</div>
|
||||
)}
|
||||
</header>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,28 +1,27 @@
|
||||
import { Globe } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Globe } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export function LanguageToggle() {
|
||||
const { i18n, t } = useTranslation()
|
||||
const current = i18n.language === 'fr' ? 'fr' : 'en'
|
||||
const next = current === 'en' ? 'fr' : 'en'
|
||||
const nextLabel = t(next === 'en' ? 'language.english' : 'language.french')
|
||||
const { i18n, t } = useTranslation();
|
||||
const current = i18n.language === "fr" ? "fr" : "en";
|
||||
const next = current === "en" ? "fr" : "en";
|
||||
const nextLabel = t(next === "en" ? "language.english" : "language.french");
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
i18n.changeLanguage(next).catch(() => undefined)
|
||||
i18n.changeLanguage(next).catch(() => undefined);
|
||||
}}
|
||||
aria-label={t('common.aria.language', { language: nextLabel })}
|
||||
aria-label={t("common.aria.language", { language: nextLabel })}
|
||||
className="h-9 rounded-full border border-border/60 bg-background/80 px-3 backdrop-blur"
|
||||
>
|
||||
<span className="sr-only">{t('language.label')}</span>
|
||||
<span className="sr-only">{t("language.label")}</span>
|
||||
<Globe className="h-4 w-4" />
|
||||
<span className="ml-2 text-xs font-semibold uppercase text-muted-foreground">{current.toUpperCase()}</span>
|
||||
</Button>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
import { Moon, Sun } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Moon, Sun } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useTheme } from '@/hooks/useTheme'
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useTheme } from "@/hooks/useTheme";
|
||||
|
||||
export function ThemeToggle() {
|
||||
const { toggleTheme, isDark } = useTheme()
|
||||
const { t } = useTranslation()
|
||||
const { toggleTheme, isDark } = useTheme();
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={toggleTheme}
|
||||
aria-label={isDark ? t('common.aria.theme.light') : t('common.aria.theme.dark')}
|
||||
aria-label={isDark ? t("common.aria.theme.light") : t("common.aria.theme.dark")}
|
||||
className="rounded-full border border-border/60 bg-background/80 backdrop-blur"
|
||||
>
|
||||
{isDark ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
|
||||
</Button>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,39 +1,29 @@
|
||||
import type { MutableRefObject } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import type { MutableRefObject } from "react";
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface MapViewportProps {
|
||||
containerRef: MutableRefObject<HTMLDivElement | null>
|
||||
isPosting: boolean
|
||||
isLoading: boolean
|
||||
confirmationHint?: string | null
|
||||
className?: string
|
||||
containerRef: MutableRefObject<HTMLDivElement | null>;
|
||||
isPosting: boolean;
|
||||
isLoading: boolean;
|
||||
confirmationHint?: string | null;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function MapViewport({
|
||||
containerRef,
|
||||
isPosting,
|
||||
isLoading,
|
||||
confirmationHint,
|
||||
className,
|
||||
}: MapViewportProps) {
|
||||
const { t } = useTranslation()
|
||||
export function MapViewport({ containerRef, isPosting, isLoading, confirmationHint, className }: MapViewportProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'relative h-full min-h-screen w-full overflow-hidden bg-muted/40 shadow-inner',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div ref={containerRef} className={cn('absolute inset-0 z-0', 'leaflet-wrapper')} />
|
||||
<div className={cn("relative h-full min-h-screen w-full overflow-hidden bg-muted/40 shadow-inner", className)}>
|
||||
<div ref={containerRef} className={cn("absolute inset-0 z-0", "leaflet-wrapper")} />
|
||||
<div className="pointer-events-none absolute inset-x-0 top-0 z-10 h-24 bg-gradient-to-b from-background/70 to-transparent" />
|
||||
<div className="pointer-events-none absolute inset-x-0 bottom-0 z-10 h-24 bg-gradient-to-t from-background/70 to-transparent" />
|
||||
{(isPosting || isLoading) && (
|
||||
<div className="pointer-events-none absolute inset-0 z-20 flex items-center justify-center">
|
||||
<span className="rounded-full border border-border/60 bg-background/80 px-4 py-2 text-xs font-medium uppercase tracking-wide text-muted-foreground backdrop-blur">
|
||||
{isPosting ? t('map.posting') : t('map.loading')}
|
||||
{isPosting ? t("map.posting") : t("map.loading")}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
@@ -43,5 +33,5 @@ export function MapViewport({
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,43 +1,43 @@
|
||||
import { Activity, ArrowRight } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Activity, ArrowRight } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
|
||||
interface ActivityItem {
|
||||
id: string | number
|
||||
title: string
|
||||
subtitle: string
|
||||
timestampLabel: string
|
||||
distanceLabel: string
|
||||
onFocus: () => void
|
||||
id: string | number;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
timestampLabel: string;
|
||||
distanceLabel: string;
|
||||
onFocus: () => void;
|
||||
}
|
||||
|
||||
interface ActivityPanelProps {
|
||||
items: ActivityItem[]
|
||||
emptyMessage: string
|
||||
items: ActivityItem[];
|
||||
emptyMessage: string;
|
||||
}
|
||||
|
||||
export function ActivityPanel({ items, emptyMessage }: ActivityPanelProps) {
|
||||
const { t } = useTranslation()
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Card className="h-full">
|
||||
<CardHeader className="space-y-1">
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Activity className="h-5 w-5 text-primary" />
|
||||
{t('activity.title')}
|
||||
{t("activity.title")}
|
||||
</CardTitle>
|
||||
<CardDescription>{t('activity.description')}</CardDescription>
|
||||
<CardDescription>{t("activity.description")}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{items.length === 0 && <p className="text-sm text-muted-foreground">{emptyMessage}</p>}
|
||||
{items.length > 0 && (
|
||||
<ScrollArea className="max-h-[280px] pr-2">
|
||||
<ul className="space-y-3">
|
||||
{items.map((item) => (
|
||||
{items.map(item => (
|
||||
<li key={item.id} className="rounded-2xl border border-border/60 bg-muted/50 p-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex flex-col">
|
||||
@@ -51,7 +51,7 @@ export function ActivityPanel({ items, emptyMessage }: ActivityPanelProps) {
|
||||
<div className="mt-2 flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>{item.distanceLabel}</span>
|
||||
<Button variant="ghost" size="sm" className="h-8 gap-2 text-xs" onClick={item.onFocus}>
|
||||
{t('activity.view')}
|
||||
{t("activity.view")}
|
||||
<ArrowRight className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
@@ -62,5 +62,5 @@ export function ActivityPanel({ items, emptyMessage }: ActivityPanelProps) {
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,47 +1,45 @@
|
||||
import { Flame, MapPin } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Flame, MapPin } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
|
||||
interface HotspotCellInfo {
|
||||
id: string
|
||||
title: string
|
||||
subtitle: string
|
||||
intensity: number
|
||||
onFocus: () => void
|
||||
id: string;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
intensity: number;
|
||||
onFocus: () => void;
|
||||
}
|
||||
|
||||
interface HotspotStatsPanelProps {
|
||||
hasLocation: boolean
|
||||
radiusKm: number
|
||||
locationHint: string
|
||||
cells: HotspotCellInfo[]
|
||||
hasLocation: boolean;
|
||||
radiusKm: number;
|
||||
locationHint: string;
|
||||
cells: HotspotCellInfo[];
|
||||
}
|
||||
|
||||
export function HotspotStatsPanel({ hasLocation, radiusKm, locationHint, cells }: HotspotStatsPanelProps) {
|
||||
const { t } = useTranslation()
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Card className="h-full">
|
||||
<CardHeader className="space-y-1">
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Flame className="h-5 w-5 text-primary" />
|
||||
{t('hotspots.title')}
|
||||
{t("hotspots.title")}
|
||||
</CardTitle>
|
||||
<CardDescription>{t('hotspots.description', { radius: radiusKm })}</CardDescription>
|
||||
<CardDescription>{t("hotspots.description", { radius: radiusKm })}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{!hasLocation && <p className="text-sm text-muted-foreground">{locationHint}</p>}
|
||||
{hasLocation && cells.length === 0 && (
|
||||
<p className="text-sm text-muted-foreground">{t('hotspots.empty')}</p>
|
||||
)}
|
||||
{hasLocation && cells.length === 0 && <p className="text-sm text-muted-foreground">{t("hotspots.empty")}</p>}
|
||||
{cells.length > 0 && (
|
||||
<ScrollArea className="max-h-[280px] pr-2">
|
||||
<ul className="space-y-3">
|
||||
{cells.map((cell) => (
|
||||
{cells.map(cell => (
|
||||
<li key={cell.id} className="rounded-2xl border border-border/60 bg-muted/50 p-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex flex-col">
|
||||
@@ -58,7 +56,7 @@ export function HotspotStatsPanel({ hasLocation, radiusKm, locationHint, cells }
|
||||
className="mt-2 w-full justify-center gap-2 text-xs"
|
||||
onClick={cell.onFocus}
|
||||
>
|
||||
<MapPin className="h-3.5 w-3.5" /> {t('hotspots.focus')}
|
||||
<MapPin className="h-3.5 w-3.5" /> {t("hotspots.focus")}
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
@@ -67,5 +65,5 @@ export function HotspotStatsPanel({ hasLocation, radiusKm, locationHint, cells }
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
import { AlertCircle, Radio } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { AlertCircle, Radio } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import type { FeedError } from '@/hooks/useHotspotFeed'
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import type { FeedError } from "@/hooks/useHotspotFeed";
|
||||
|
||||
interface OverviewPanelProps {
|
||||
nearbySignals: number
|
||||
uniqueContributors: number
|
||||
lastUpdatedLabel: string
|
||||
mySignalLabel: string | null
|
||||
error: FeedError | null
|
||||
onReport: () => void
|
||||
onRetry: () => void
|
||||
isPosting: boolean
|
||||
locationHint: string
|
||||
showLocationCta: boolean
|
||||
disableReport: boolean
|
||||
nearbySignals: number;
|
||||
uniqueContributors: number;
|
||||
lastUpdatedLabel: string;
|
||||
mySignalLabel: string | null;
|
||||
error: FeedError | null;
|
||||
onReport: () => void;
|
||||
onRetry: () => void;
|
||||
isPosting: boolean;
|
||||
locationHint: string;
|
||||
showLocationCta: boolean;
|
||||
disableReport: boolean;
|
||||
}
|
||||
|
||||
export function OverviewPanel({
|
||||
@@ -33,32 +33,32 @@ export function OverviewPanel({
|
||||
showLocationCta,
|
||||
disableReport,
|
||||
}: OverviewPanelProps) {
|
||||
const { t } = useTranslation()
|
||||
const errorMessage = error ? t(error.key, error.values) : null
|
||||
const { t } = useTranslation();
|
||||
const errorMessage = error ? t(error.key, error.values) : null;
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="space-y-1">
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Radio className="h-5 w-5 text-primary" />
|
||||
{t('overview.title')}
|
||||
{t("overview.title")}
|
||||
</CardTitle>
|
||||
<CardDescription>{t('overview.description')}</CardDescription>
|
||||
<CardDescription>{t("overview.description")}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="rounded-2xl border border-border/60 bg-muted/50 p-3">
|
||||
<span className="text-xs uppercase text-muted-foreground">{t('overview.stats.signals')}</span>
|
||||
<span className="text-xs uppercase text-muted-foreground">{t("overview.stats.signals")}</span>
|
||||
<p className="text-xl font-semibold">{nearbySignals}</p>
|
||||
</div>
|
||||
<div className="rounded-2xl border border-border/60 bg-muted/50 p-3">
|
||||
<span className="text-xs uppercase text-muted-foreground">{t('overview.stats.contributors')}</span>
|
||||
<span className="text-xs uppercase text-muted-foreground">{t("overview.stats.contributors")}</span>
|
||||
<p className="text-xl font-semibold">{uniqueContributors}</p>
|
||||
</div>
|
||||
</div>
|
||||
{mySignalLabel && (
|
||||
<Badge variant="secondary" className="w-full justify-center rounded-full py-2 text-xs uppercase">
|
||||
{t('overview.badge', { time: mySignalLabel })}
|
||||
{t("overview.badge", { time: mySignalLabel })}
|
||||
</Badge>
|
||||
)}
|
||||
{errorMessage ? (
|
||||
@@ -67,7 +67,7 @@ export function OverviewPanel({
|
||||
<div className="space-y-2">
|
||||
<p>{errorMessage}</p>
|
||||
<Button variant="outline" size="sm" className="text-xs" onClick={onRetry}>
|
||||
{t('overview.error.action')}
|
||||
{t("overview.error.action")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -75,17 +75,15 @@ export function OverviewPanel({
|
||||
<p className="text-sm text-muted-foreground">{locationHint}</p>
|
||||
)}
|
||||
<Button className="w-full" onClick={onReport} disabled={isPosting || disableReport}>
|
||||
{isPosting
|
||||
? t('overview.cta.sending')
|
||||
: disableReport
|
||||
? t('overview.cta.waiting')
|
||||
: t('overview.cta.send')}
|
||||
{isPosting ? t("overview.cta.sending") : disableReport ? t("overview.cta.waiting") : t("overview.cta.send")}
|
||||
</Button>
|
||||
{showLocationCta && !errorMessage && (
|
||||
<p className="text-xs text-muted-foreground">{t('overview.locationPermission')}</p>
|
||||
<p className="text-xs text-muted-foreground">{t("overview.locationPermission")}</p>
|
||||
)}
|
||||
<p className="text-[11px] uppercase text-muted-foreground">{t('overview.lastSynced', { time: lastUpdatedLabel })}</p>
|
||||
<p className="text-[11px] uppercase text-muted-foreground">
|
||||
{t("overview.lastSynced", { time: lastUpdatedLabel })}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import * as React from 'react'
|
||||
import * as AlertDialogPrimitive from '@radix-ui/react-alert-dialog'
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
|
||||
|
||||
const AlertDialog = AlertDialogPrimitive.Root
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const AlertDialogTrigger = AlertDialogPrimitive.Trigger
|
||||
const AlertDialog = AlertDialogPrimitive.Root;
|
||||
|
||||
const AlertDialogPortal = AlertDialogPrimitive.Portal
|
||||
const AlertDialogTrigger = AlertDialogPrimitive.Trigger;
|
||||
|
||||
const AlertDialogPortal = AlertDialogPrimitive.Portal;
|
||||
|
||||
const AlertDialogOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
|
||||
@@ -16,13 +17,13 @@ const AlertDialogOverlay = React.forwardRef<
|
||||
<AlertDialogPrimitive.Overlay
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
className,
|
||||
"fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName
|
||||
));
|
||||
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName;
|
||||
|
||||
const AlertDialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Content>,
|
||||
@@ -33,44 +34,40 @@ const AlertDialogContent = React.forwardRef<
|
||||
<AlertDialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-md translate-x-[-50%] translate-y-[-50%] gap-4 border border-border/70 bg-background p-6 shadow-sm duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
|
||||
className,
|
||||
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-md translate-x-[-50%] translate-y-[-50%] gap-4 border border-border/70 bg-background p-6 shadow-sm duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</AlertDialogPortal>
|
||||
))
|
||||
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName
|
||||
));
|
||||
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName;
|
||||
|
||||
const AlertDialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn('flex flex-col space-y-2 text-center sm:text-left', className)} {...props} />
|
||||
)
|
||||
AlertDialogHeader.displayName = 'AlertDialogHeader'
|
||||
<div className={cn("flex flex-col space-y-2 text-center sm:text-left", className)} {...props} />
|
||||
);
|
||||
AlertDialogHeader.displayName = "AlertDialogHeader";
|
||||
|
||||
const AlertDialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)} {...props} />
|
||||
)
|
||||
AlertDialogFooter.displayName = 'AlertDialogFooter'
|
||||
<div className={cn("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", className)} {...props} />
|
||||
);
|
||||
AlertDialogFooter.displayName = "AlertDialogFooter";
|
||||
|
||||
const AlertDialogTitle = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Title ref={ref} className={cn('text-lg font-semibold', className)} {...props} />
|
||||
))
|
||||
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName
|
||||
<AlertDialogPrimitive.Title ref={ref} className={cn("text-lg font-semibold", className)} {...props} />
|
||||
));
|
||||
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName;
|
||||
|
||||
const AlertDialogDescription = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn('text-sm text-muted-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
AlertDialogDescription.displayName = AlertDialogPrimitive.Description.displayName
|
||||
<AlertDialogPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
|
||||
));
|
||||
AlertDialogDescription.displayName = AlertDialogPrimitive.Description.displayName;
|
||||
|
||||
const AlertDialogAction = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Action>,
|
||||
@@ -78,11 +75,14 @@ const AlertDialogAction = React.forwardRef<
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Action
|
||||
ref={ref}
|
||||
className={cn('inline-flex h-10 items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background disabled:pointer-events-none disabled:opacity-50', className)}
|
||||
className={cn(
|
||||
"inline-flex h-10 items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background disabled:pointer-events-none disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName
|
||||
));
|
||||
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName;
|
||||
|
||||
const AlertDialogCancel = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
|
||||
@@ -90,11 +90,14 @@ const AlertDialogCancel = React.forwardRef<
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Cancel
|
||||
ref={ref}
|
||||
className={cn('inline-flex h-10 items-center justify-center rounded-md border border-input bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-muted focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background disabled:pointer-events-none disabled:opacity-50 sm:mr-2', className)}
|
||||
className={cn(
|
||||
"inline-flex h-10 items-center justify-center rounded-md border border-input bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-muted focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background disabled:pointer-events-none disabled:opacity-50 sm:mr-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName
|
||||
));
|
||||
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName;
|
||||
|
||||
export {
|
||||
AlertDialog,
|
||||
@@ -106,4 +109,4 @@ export {
|
||||
AlertDialogDescription,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,36 +1,33 @@
|
||||
import * as React from 'react'
|
||||
import { cva, type VariantProps } from 'class-variance-authority'
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const badgeVariants = cva(
|
||||
'inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
|
||||
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'border-transparent bg-primary/15 text-primary',
|
||||
secondary: 'border-transparent bg-secondary text-secondary-foreground',
|
||||
destructive: 'border-transparent bg-destructive/15 text-destructive',
|
||||
outline: 'text-foreground',
|
||||
success: 'border-transparent bg-emerald-500/15 text-emerald-300',
|
||||
muted: 'border-transparent bg-muted/60 text-muted-foreground',
|
||||
default: "border-transparent bg-primary/15 text-primary",
|
||||
secondary: "border-transparent bg-secondary text-secondary-foreground",
|
||||
destructive: "border-transparent bg-destructive/15 text-destructive",
|
||||
outline: "text-foreground",
|
||||
success: "border-transparent bg-emerald-500/15 text-emerald-300",
|
||||
muted: "border-transparent bg-muted/60 text-muted-foreground",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
variant: "default",
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
);
|
||||
|
||||
export interface BadgeProps
|
||||
extends React.HTMLAttributes<HTMLDivElement>,
|
||||
VariantProps<typeof badgeVariants> {}
|
||||
export interface BadgeProps extends React.HTMLAttributes<HTMLDivElement>, VariantProps<typeof badgeVariants> {}
|
||||
|
||||
const Badge = React.forwardRef<HTMLDivElement, BadgeProps>(
|
||||
({ className, variant, ...props }, ref) => (
|
||||
<div ref={ref} className={cn(badgeVariants({ variant }), className)} {...props} />
|
||||
),
|
||||
)
|
||||
Badge.displayName = 'Badge'
|
||||
const Badge = React.forwardRef<HTMLDivElement, BadgeProps>(({ className, variant, ...props }, ref) => (
|
||||
<div ref={ref} className={cn(badgeVariants({ variant }), className)} {...props} />
|
||||
));
|
||||
Badge.displayName = "Badge";
|
||||
|
||||
export { Badge }
|
||||
export { Badge };
|
||||
|
||||
@@ -1,48 +1,45 @@
|
||||
import * as React from 'react'
|
||||
import { Slot } from '@radix-ui/react-slot'
|
||||
import { cva, type VariantProps } from 'class-variance-authority'
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const buttonVariants = cva(
|
||||
'inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 focus-visible:ring-offset-background',
|
||||
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 focus-visible:ring-offset-background",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm',
|
||||
secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
|
||||
ghost: 'hover:bg-accent hover:text-accent-foreground',
|
||||
outline:
|
||||
'border border-input bg-transparent hover:bg-accent hover:text-accent-foreground shadow-sm',
|
||||
destructive:
|
||||
'bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm',
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm",
|
||||
secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
outline: "border border-input bg-transparent hover:bg-accent hover:text-accent-foreground shadow-sm",
|
||||
destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm",
|
||||
},
|
||||
size: {
|
||||
default: 'h-10 px-4 py-2',
|
||||
sm: 'h-9 rounded-md px-3',
|
||||
lg: 'h-11 rounded-md px-5 text-base',
|
||||
icon: 'h-10 w-10',
|
||||
default: "h-10 px-4 py-2",
|
||||
sm: "h-9 rounded-md px-3",
|
||||
lg: "h-11 rounded-md px-5 text-base",
|
||||
icon: "h-10 w-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
size: 'default',
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
);
|
||||
|
||||
export interface ButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
VariantProps<typeof buttonVariants> {
|
||||
asChild?: boolean
|
||||
asChild?: boolean;
|
||||
}
|
||||
|
||||
export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
({ className, variant, size, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : 'button'
|
||||
return (
|
||||
<Comp className={cn(buttonVariants({ variant, size }), className)} ref={ref} {...props} />
|
||||
)
|
||||
},
|
||||
)
|
||||
Button.displayName = 'Button'
|
||||
const Comp = asChild ? Slot : "button";
|
||||
return <Comp className={cn(buttonVariants({ variant, size }), className)} ref={ref} {...props} />;
|
||||
}
|
||||
);
|
||||
Button.displayName = "Button";
|
||||
|
||||
@@ -1,54 +1,50 @@
|
||||
import * as React from 'react'
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'rounded-xl border border-border/60 bg-card/80 text-card-foreground shadow-sm backdrop-blur',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
),
|
||||
)
|
||||
Card.displayName = 'Card'
|
||||
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"rounded-xl border border-border/60 bg-card/80 text-card-foreground shadow-sm backdrop-blur",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
Card.displayName = "Card";
|
||||
|
||||
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('flex flex-col space-y-1.5 p-6', className)} {...props} />
|
||||
),
|
||||
)
|
||||
CardHeader.displayName = 'CardHeader'
|
||||
<div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} />
|
||||
)
|
||||
);
|
||||
CardHeader.displayName = "CardHeader";
|
||||
|
||||
const CardTitle = React.forwardRef<HTMLHeadingElement, React.HTMLAttributes<HTMLHeadingElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<h3 ref={ref} className={cn('text-lg font-semibold leading-none tracking-tight', className)} {...props} />
|
||||
),
|
||||
)
|
||||
CardTitle.displayName = 'CardTitle'
|
||||
<h3 ref={ref} className={cn("text-lg font-semibold leading-none tracking-tight", className)} {...props} />
|
||||
)
|
||||
);
|
||||
CardTitle.displayName = "CardTitle";
|
||||
|
||||
const CardDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<p ref={ref} className={cn('text-sm text-muted-foreground', className)} {...props} />
|
||||
),
|
||||
)
|
||||
CardDescription.displayName = 'CardDescription'
|
||||
<p ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
|
||||
)
|
||||
);
|
||||
CardDescription.displayName = "CardDescription";
|
||||
|
||||
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('p-6 pt-0', className)} {...props} />
|
||||
),
|
||||
)
|
||||
CardContent.displayName = 'CardContent'
|
||||
({ className, ...props }, ref) => <div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
|
||||
);
|
||||
CardContent.displayName = "CardContent";
|
||||
|
||||
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('flex items-center p-6 pt-0 text-sm text-muted-foreground', className)} {...props} />
|
||||
),
|
||||
)
|
||||
CardFooter.displayName = 'CardFooter'
|
||||
<div ref={ref} className={cn("flex items-center p-6 pt-0 text-sm text-muted-foreground", className)} {...props} />
|
||||
)
|
||||
);
|
||||
CardFooter.displayName = "CardFooter";
|
||||
|
||||
export { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle }
|
||||
export { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle };
|
||||
|
||||
@@ -1,40 +1,39 @@
|
||||
import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area'
|
||||
import * as React from 'react'
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const ScrollArea = React.forwardRef<
|
||||
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<ScrollAreaPrimitive.Root ref={ref} className={cn('relative overflow-hidden', className)} {...props}>
|
||||
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollAreaPrimitive.Root ref={ref} className={cn("relative overflow-hidden", className)} {...props}>
|
||||
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">{children}</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
))
|
||||
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName
|
||||
));
|
||||
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName;
|
||||
|
||||
const ScrollBar = React.forwardRef<
|
||||
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
|
||||
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
>(({ className, orientation = 'vertical', ...props }, ref) => (
|
||||
>(({ className, orientation = "vertical", ...props }, ref) => (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
ref={ref}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
'flex touch-none select-none transition-colors',
|
||||
orientation === 'vertical' && 'h-full w-2 border-l border-l-transparent p-[1px]',
|
||||
orientation === 'horizontal' && 'h-2 border-t border-t-transparent p-[1px]',
|
||||
className,
|
||||
"flex touch-none select-none transition-colors",
|
||||
orientation === "vertical" && "h-full w-2 border-l border-l-transparent p-[1px]",
|
||||
orientation === "horizontal" && "h-2 border-t border-t-transparent p-[1px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border/60" />
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
))
|
||||
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName
|
||||
));
|
||||
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName;
|
||||
|
||||
export { ScrollArea, ScrollBar }
|
||||
export { ScrollArea, ScrollBar };
|
||||
|
||||
@@ -1,22 +1,18 @@
|
||||
import * as React from 'react'
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Separator = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement> & { orientation?: 'horizontal' | 'vertical' }
|
||||
>(({ className, orientation = 'horizontal', ...props }, ref) => (
|
||||
React.HTMLAttributes<HTMLDivElement> & { orientation?: "horizontal" | "vertical" }
|
||||
>(({ className, orientation = "horizontal", ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'shrink-0 bg-border/60',
|
||||
orientation === 'horizontal' ? 'h-px w-full' : 'h-full w-px',
|
||||
className,
|
||||
)}
|
||||
className={cn("shrink-0 bg-border/60", orientation === "horizontal" ? "h-px w-full" : "h-full w-px", className)}
|
||||
role="none"
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
Separator.displayName = 'Separator'
|
||||
));
|
||||
Separator.displayName = "Separator";
|
||||
|
||||
export { Separator }
|
||||
export { Separator };
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
import * as React from 'react'
|
||||
import * as SheetPrimitive from '@radix-ui/react-dialog'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
import * as SheetPrimitive from "@radix-ui/react-dialog";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
const Sheet = SheetPrimitive.Root
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const SheetTrigger = SheetPrimitive.Trigger
|
||||
const Sheet = SheetPrimitive.Root;
|
||||
|
||||
const SheetClose = SheetPrimitive.Close
|
||||
const SheetTrigger = SheetPrimitive.Trigger;
|
||||
|
||||
const SheetPortal = SheetPrimitive.Portal
|
||||
const SheetClose = SheetPrimitive.Close;
|
||||
|
||||
const SheetPortal = SheetPrimitive.Portal;
|
||||
|
||||
const SheetOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof SheetPrimitive.Overlay>,
|
||||
@@ -18,79 +19,78 @@ const SheetOverlay = React.forwardRef<
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SheetPrimitive.Overlay
|
||||
className={cn(
|
||||
'fixed inset-0 z-40 bg-background/60 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
className,
|
||||
"fixed inset-0 z-40 bg-background/60 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
/>
|
||||
))
|
||||
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName
|
||||
));
|
||||
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName;
|
||||
|
||||
type SheetSide = 'top' | 'bottom' | 'left' | 'right'
|
||||
type SheetSide = "top" | "bottom" | "left" | "right";
|
||||
|
||||
interface SheetContentProps extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content> {
|
||||
side?: SheetSide
|
||||
side?: SheetSide;
|
||||
}
|
||||
|
||||
const SheetContent = React.forwardRef<
|
||||
React.ElementRef<typeof SheetPrimitive.Content>,
|
||||
SheetContentProps
|
||||
>(({ side = 'bottom', className, children, ...props }, ref) => {
|
||||
const { t } = useTranslation()
|
||||
const SheetContent = React.forwardRef<React.ElementRef<typeof SheetPrimitive.Content>, SheetContentProps>(
|
||||
({ side = "bottom", className, children, ...props }, ref) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<SheetPortal>
|
||||
<SheetOverlay />
|
||||
<SheetPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed z-50 grid gap-4 bg-background p-6 shadow-sm transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out',
|
||||
side === 'bottom' && 'inset-x-0 bottom-0 rounded-t-2xl border-t',
|
||||
side === 'top' && 'inset-x-0 top-0 rounded-b-2xl border-b',
|
||||
side === 'left' && 'inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm',
|
||||
side === 'right' && 'inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm',
|
||||
className,
|
||||
)}
|
||||
data-side={side}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SheetPrimitive.Close className="absolute right-6 top-6 rounded-full border border-border/50 bg-background/60 px-3 py-1 text-xs font-medium text-muted-foreground transition hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background">
|
||||
{t('common.actions.close')}
|
||||
<span className="sr-only">{t('common.aria.sheet.close')}</span>
|
||||
</SheetPrimitive.Close>
|
||||
</SheetPrimitive.Content>
|
||||
</SheetPortal>
|
||||
)
|
||||
})
|
||||
SheetContent.displayName = SheetPrimitive.Content.displayName
|
||||
return (
|
||||
<SheetPortal>
|
||||
<SheetOverlay />
|
||||
<SheetPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed z-50 grid gap-4 bg-background p-6 shadow-sm transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out",
|
||||
side === "bottom" && "inset-x-0 bottom-0 rounded-t-2xl border-t",
|
||||
side === "top" && "inset-x-0 top-0 rounded-b-2xl border-b",
|
||||
side === "left" && "inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
|
||||
side === "right" && "inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
|
||||
className
|
||||
)}
|
||||
data-side={side}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SheetPrimitive.Close className="absolute right-6 top-6 rounded-full border border-border/50 bg-background/60 px-3 py-1 text-xs font-medium text-muted-foreground transition hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background">
|
||||
{t("common.actions.close")}
|
||||
<span className="sr-only">{t("common.aria.sheet.close")}</span>
|
||||
</SheetPrimitive.Close>
|
||||
</SheetPrimitive.Content>
|
||||
</SheetPortal>
|
||||
);
|
||||
}
|
||||
);
|
||||
SheetContent.displayName = SheetPrimitive.Content.displayName;
|
||||
|
||||
const SheetHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn('flex flex-col space-y-2 text-center sm:text-left', className)} {...props} />
|
||||
)
|
||||
SheetHeader.displayName = 'SheetHeader'
|
||||
<div className={cn("flex flex-col space-y-2 text-center sm:text-left", className)} {...props} />
|
||||
);
|
||||
SheetHeader.displayName = "SheetHeader";
|
||||
|
||||
const SheetFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)} {...props} />
|
||||
)
|
||||
SheetFooter.displayName = 'SheetFooter'
|
||||
<div className={cn("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", className)} {...props} />
|
||||
);
|
||||
SheetFooter.displayName = "SheetFooter";
|
||||
|
||||
const SheetTitle = React.forwardRef<
|
||||
React.ElementRef<typeof SheetPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SheetPrimitive.Title ref={ref} className={cn('text-lg font-semibold', className)} {...props} />
|
||||
))
|
||||
SheetTitle.displayName = SheetPrimitive.Title.displayName
|
||||
<SheetPrimitive.Title ref={ref} className={cn("text-lg font-semibold", className)} {...props} />
|
||||
));
|
||||
SheetTitle.displayName = SheetPrimitive.Title.displayName;
|
||||
|
||||
const SheetDescription = React.forwardRef<
|
||||
React.ElementRef<typeof SheetPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SheetPrimitive.Description ref={ref} className={cn('text-sm text-muted-foreground', className)} {...props} />
|
||||
))
|
||||
SheetDescription.displayName = SheetPrimitive.Description.displayName
|
||||
<SheetPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
|
||||
));
|
||||
SheetDescription.displayName = SheetPrimitive.Description.displayName;
|
||||
|
||||
export {
|
||||
Sheet,
|
||||
@@ -103,4 +103,4 @@ export {
|
||||
SheetFooter,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import * as TabsPrimitive from '@radix-ui/react-tabs'
|
||||
import * as React from 'react'
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
import * as TabsPrimitive from "@radix-ui/react-tabs";
|
||||
|
||||
const Tabs = TabsPrimitive.Root
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Tabs = TabsPrimitive.Root;
|
||||
|
||||
const TabsList = React.forwardRef<
|
||||
React.ElementRef<typeof TabsPrimitive.List>,
|
||||
@@ -11,11 +12,14 @@ const TabsList = React.forwardRef<
|
||||
>(({ className, ...props }, ref) => (
|
||||
<TabsPrimitive.List
|
||||
ref={ref}
|
||||
className={cn('inline-flex h-10 items-center justify-center rounded-full bg-muted p-1 text-muted-foreground', className)}
|
||||
className={cn(
|
||||
"inline-flex h-10 items-center justify-center rounded-full bg-muted p-1 text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
TabsList.displayName = TabsPrimitive.List.displayName
|
||||
));
|
||||
TabsList.displayName = TabsPrimitive.List.displayName;
|
||||
|
||||
const TabsTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof TabsPrimitive.Trigger>,
|
||||
@@ -24,13 +28,13 @@ const TabsTrigger = React.forwardRef<
|
||||
<TabsPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'inline-flex min-w-[120px] items-center justify-center whitespace-nowrap rounded-full px-4 py-1.5 text-sm font-medium transition focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=inactive]:opacity-70',
|
||||
className,
|
||||
"inline-flex min-w-[120px] items-center justify-center whitespace-nowrap rounded-full px-4 py-1.5 text-sm font-medium transition focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=inactive]:opacity-70",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
|
||||
));
|
||||
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
|
||||
|
||||
const TabsContent = React.forwardRef<
|
||||
React.ElementRef<typeof TabsPrimitive.Content>,
|
||||
@@ -39,12 +43,12 @@ const TabsContent = React.forwardRef<
|
||||
<TabsPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'mt-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background',
|
||||
className,
|
||||
"mt-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
TabsContent.displayName = TabsPrimitive.Content.displayName
|
||||
));
|
||||
TabsContent.displayName = TabsPrimitive.Content.displayName;
|
||||
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent }
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent };
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import * as React from 'react'
|
||||
import * as ToastPrimitives from '@radix-ui/react-toast'
|
||||
import { cva, type VariantProps } from 'class-variance-authority'
|
||||
import { X } from 'lucide-react'
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
import * as ToastPrimitives from "@radix-ui/react-toast";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import { X } from "lucide-react";
|
||||
|
||||
const ToastProvider = ToastPrimitives.Provider
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const ToastProvider = ToastPrimitives.Provider;
|
||||
|
||||
const ToastViewport = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Viewport>,
|
||||
@@ -14,28 +15,28 @@ const ToastViewport = React.forwardRef<
|
||||
<ToastPrimitives.Viewport
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed inset-x-0 top-4 z-[1000] mx-auto flex w-full max-w-sm flex-col gap-2 px-4 sm:right-4 sm:left-auto sm:mx-0 sm:w-96',
|
||||
className,
|
||||
"fixed inset-x-0 top-4 z-[1000] mx-auto flex w-full max-w-sm flex-col gap-2 px-4 sm:right-4 sm:left-auto sm:mx-0 sm:w-96",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastViewport.displayName = ToastPrimitives.Viewport.displayName
|
||||
));
|
||||
ToastViewport.displayName = ToastPrimitives.Viewport.displayName;
|
||||
|
||||
const toastVariants = cva(
|
||||
'group pointer-events-auto relative flex w-full items-start gap-3 overflow-hidden rounded-2xl border border-border bg-background p-4 shadow-lg transition-all',
|
||||
"group pointer-events-auto relative flex w-full items-start gap-3 overflow-hidden rounded-2xl border border-border bg-background p-4 shadow-lg transition-all",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'bg-background text-foreground',
|
||||
destructive: 'border-destructive/60 bg-destructive text-destructive-foreground',
|
||||
default: "bg-background text-foreground",
|
||||
destructive: "border-destructive/60 bg-destructive text-destructive-foreground",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
variant: "default",
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
);
|
||||
|
||||
const Toast = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Root>,
|
||||
@@ -45,9 +46,9 @@ const Toast = React.forwardRef<
|
||||
<ToastPrimitives.Root ref={ref} className={cn(toastVariants({ variant }), className)} {...props}>
|
||||
{props.children}
|
||||
</ToastPrimitives.Root>
|
||||
)
|
||||
})
|
||||
Toast.displayName = ToastPrimitives.Root.displayName
|
||||
);
|
||||
});
|
||||
Toast.displayName = ToastPrimitives.Root.displayName;
|
||||
|
||||
const ToastAction = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Action>,
|
||||
@@ -56,13 +57,13 @@ const ToastAction = React.forwardRef<
|
||||
<ToastPrimitives.Action
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'inline-flex h-8 shrink-0 items-center justify-center rounded-full border border-border/60 bg-background px-3 text-xs font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
|
||||
className,
|
||||
"inline-flex h-8 shrink-0 items-center justify-center rounded-full border border-border/60 bg-background px-3 text-xs font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastAction.displayName = ToastPrimitives.Action.displayName
|
||||
));
|
||||
ToastAction.displayName = ToastPrimitives.Action.displayName;
|
||||
|
||||
const ToastClose = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Close>,
|
||||
@@ -71,46 +72,38 @@ const ToastClose = React.forwardRef<
|
||||
<ToastPrimitives.Close
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'absolute right-3 top-3 rounded-full p-1 text-foreground/70 transition-colors hover:bg-foreground/10 hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
|
||||
className,
|
||||
"absolute right-3 top-3 rounded-full p-1 text-foreground/70 transition-colors hover:bg-foreground/10 hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
|
||||
className
|
||||
)}
|
||||
toast-close=""
|
||||
{...props}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</ToastPrimitives.Close>
|
||||
))
|
||||
ToastClose.displayName = ToastPrimitives.Close.displayName
|
||||
));
|
||||
ToastClose.displayName = ToastPrimitives.Close.displayName;
|
||||
|
||||
const ToastTitle = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Title ref={ref} className={cn('text-sm font-semibold leading-none tracking-tight', className)} {...props} />
|
||||
))
|
||||
ToastTitle.displayName = ToastPrimitives.Title.displayName
|
||||
<ToastPrimitives.Title
|
||||
ref={ref}
|
||||
className={cn("text-sm font-semibold leading-none tracking-tight", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
ToastTitle.displayName = ToastPrimitives.Title.displayName;
|
||||
|
||||
const ToastDescription = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Description
|
||||
ref={ref}
|
||||
className={cn('text-sm text-muted-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastDescription.displayName = ToastPrimitives.Description.displayName
|
||||
<ToastPrimitives.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
|
||||
));
|
||||
ToastDescription.displayName = ToastPrimitives.Description.displayName;
|
||||
|
||||
export type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
|
||||
export type ToastActionElement = React.ReactElement<typeof ToastAction>
|
||||
export type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>;
|
||||
export type ToastActionElement = React.ReactElement<typeof ToastAction>;
|
||||
|
||||
export {
|
||||
ToastProvider,
|
||||
ToastViewport,
|
||||
Toast,
|
||||
ToastTitle,
|
||||
ToastDescription,
|
||||
ToastClose,
|
||||
ToastAction,
|
||||
}
|
||||
export { ToastProvider, ToastViewport, Toast, ToastTitle, ToastDescription, ToastClose, ToastAction };
|
||||
|
||||
@@ -1,15 +1,8 @@
|
||||
import {
|
||||
Toast,
|
||||
ToastClose,
|
||||
ToastDescription,
|
||||
ToastProvider,
|
||||
ToastTitle,
|
||||
ToastViewport,
|
||||
} from '@/components/ui/toast'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Toast, ToastClose, ToastDescription, ToastProvider, ToastTitle, ToastViewport } from "@/components/ui/toast";
|
||||
import { useToast } from "@/components/ui/use-toast";
|
||||
|
||||
export function Toaster() {
|
||||
const { toasts, dismiss } = useToast()
|
||||
const { toasts, dismiss } = useToast();
|
||||
|
||||
return (
|
||||
<ToastProvider>
|
||||
@@ -17,9 +10,9 @@ export function Toaster() {
|
||||
<Toast
|
||||
key={id}
|
||||
{...props}
|
||||
onOpenChange={(open) => {
|
||||
onOpenChange={open => {
|
||||
if (!open) {
|
||||
dismiss(id)
|
||||
dismiss(id);
|
||||
}
|
||||
}}
|
||||
>
|
||||
@@ -33,5 +26,5 @@ export function Toaster() {
|
||||
))}
|
||||
<ToastViewport />
|
||||
</ToastProvider>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,129 +1,125 @@
|
||||
import * as React from 'react'
|
||||
import * as React from "react";
|
||||
|
||||
import type { ToastActionElement, ToastProps } from '@/components/ui/toast'
|
||||
import type { ToastActionElement, ToastProps } from "@/components/ui/toast";
|
||||
|
||||
type ToasterToast = ToastProps & {
|
||||
id: string
|
||||
title?: React.ReactNode
|
||||
description?: React.ReactNode
|
||||
action?: ToastActionElement
|
||||
}
|
||||
id: string;
|
||||
title?: React.ReactNode;
|
||||
description?: React.ReactNode;
|
||||
action?: ToastActionElement;
|
||||
};
|
||||
|
||||
type ToastState = {
|
||||
toasts: ToasterToast[]
|
||||
}
|
||||
toasts: ToasterToast[];
|
||||
};
|
||||
|
||||
type ToastAction =
|
||||
| { type: 'ADD_TOAST'; toast: ToasterToast }
|
||||
| { type: 'UPDATE_TOAST'; toast: Partial<ToasterToast> & { id: string } }
|
||||
| { type: 'DISMISS_TOAST'; toastId?: string }
|
||||
| { type: 'REMOVE_TOAST'; toastId?: string }
|
||||
| { type: "ADD_TOAST"; toast: ToasterToast }
|
||||
| { type: "UPDATE_TOAST"; toast: Partial<ToasterToast> & { id: string } }
|
||||
| { type: "DISMISS_TOAST"; toastId?: string }
|
||||
| { type: "REMOVE_TOAST"; toastId?: string };
|
||||
|
||||
const TOAST_LIMIT = 5
|
||||
const TOAST_REMOVE_DELAY = 1000
|
||||
const TOAST_LIMIT = 5;
|
||||
const TOAST_REMOVE_DELAY = 1000;
|
||||
|
||||
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
|
||||
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
|
||||
const listeners = new Set<(state: ToastState) => void>()
|
||||
const listeners = new Set<(state: ToastState) => void>();
|
||||
|
||||
let memoryState: ToastState = { toasts: [] }
|
||||
let memoryState: ToastState = { toasts: [] };
|
||||
|
||||
function dispatch(action: ToastAction) {
|
||||
memoryState = reducer(memoryState, action)
|
||||
listeners.forEach((listener) => {
|
||||
listener(memoryState)
|
||||
})
|
||||
memoryState = reducer(memoryState, action);
|
||||
listeners.forEach(listener => {
|
||||
listener(memoryState);
|
||||
});
|
||||
}
|
||||
|
||||
function reducer(state: ToastState, action: ToastAction): ToastState {
|
||||
switch (action.type) {
|
||||
case 'ADD_TOAST': {
|
||||
case "ADD_TOAST": {
|
||||
return {
|
||||
...state,
|
||||
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
|
||||
}
|
||||
};
|
||||
}
|
||||
case 'UPDATE_TOAST': {
|
||||
case "UPDATE_TOAST": {
|
||||
return {
|
||||
...state,
|
||||
toasts: state.toasts.map((toast) =>
|
||||
toast.id === action.toast.id ? { ...toast, ...action.toast } : toast,
|
||||
),
|
||||
}
|
||||
toasts: state.toasts.map(toast => (toast.id === action.toast.id ? { ...toast, ...action.toast } : toast)),
|
||||
};
|
||||
}
|
||||
case 'DISMISS_TOAST': {
|
||||
const { toastId } = action
|
||||
case "DISMISS_TOAST": {
|
||||
const { toastId } = action;
|
||||
if (toastId) {
|
||||
addToRemoveQueue(toastId)
|
||||
addToRemoveQueue(toastId);
|
||||
} else {
|
||||
state.toasts.forEach((toast) => {
|
||||
addToRemoveQueue(toast.id)
|
||||
})
|
||||
state.toasts.forEach(toast => {
|
||||
addToRemoveQueue(toast.id);
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
...state,
|
||||
toasts: state.toasts.map((toast) =>
|
||||
toast.id === toastId || toastId === undefined
|
||||
? { ...toast, open: false }
|
||||
: toast,
|
||||
toasts: state.toasts.map(toast =>
|
||||
toast.id === toastId || toastId === undefined ? { ...toast, open: false } : toast
|
||||
),
|
||||
}
|
||||
};
|
||||
}
|
||||
case 'REMOVE_TOAST': {
|
||||
case "REMOVE_TOAST": {
|
||||
if (action.toastId === undefined) {
|
||||
return { ...state, toasts: [] }
|
||||
return { ...state, toasts: [] };
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
toasts: state.toasts.filter((toast) => toast.id !== action.toastId),
|
||||
}
|
||||
toasts: state.toasts.filter(toast => toast.id !== action.toastId),
|
||||
};
|
||||
}
|
||||
default:
|
||||
return state
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
function addToRemoveQueue(toastId: string) {
|
||||
if (toastTimeouts.has(toastId)) {
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
toastTimeouts.delete(toastId)
|
||||
dispatch({ type: 'REMOVE_TOAST', toastId })
|
||||
}, TOAST_REMOVE_DELAY)
|
||||
toastTimeouts.delete(toastId);
|
||||
dispatch({ type: "REMOVE_TOAST", toastId });
|
||||
}, TOAST_REMOVE_DELAY);
|
||||
|
||||
toastTimeouts.set(toastId, timeout)
|
||||
toastTimeouts.set(toastId, timeout);
|
||||
}
|
||||
|
||||
function genId() {
|
||||
return Math.random().toString(36).slice(2, 10)
|
||||
return Math.random().toString(36).slice(2, 10);
|
||||
}
|
||||
|
||||
export function useToast() {
|
||||
const [state, setState] = React.useState<ToastState>(memoryState)
|
||||
const [state, setState] = React.useState<ToastState>(memoryState);
|
||||
|
||||
React.useEffect(() => {
|
||||
listeners.add(setState)
|
||||
listeners.add(setState);
|
||||
return () => {
|
||||
listeners.delete(setState)
|
||||
}
|
||||
}, [])
|
||||
listeners.delete(setState);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return {
|
||||
...state,
|
||||
toast: (props: Omit<ToasterToast, 'id'>) => {
|
||||
const id = genId()
|
||||
dispatch({ type: 'ADD_TOAST', toast: { ...props, id, open: true } })
|
||||
return id
|
||||
toast: (props: Omit<ToasterToast, "id">) => {
|
||||
const id = genId();
|
||||
dispatch({ type: "ADD_TOAST", toast: { ...props, id, open: true } });
|
||||
return id;
|
||||
},
|
||||
dismiss: (toastId?: string) => dispatch({ type: 'DISMISS_TOAST', toastId }),
|
||||
}
|
||||
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
|
||||
};
|
||||
}
|
||||
|
||||
export const toast = (props: Omit<ToasterToast, 'id'>) => {
|
||||
const id = genId()
|
||||
dispatch({ type: 'ADD_TOAST', toast: { ...props, id, open: true } })
|
||||
return id
|
||||
}
|
||||
export const toast = (props: Omit<ToasterToast, "id">) => {
|
||||
const id = genId();
|
||||
dispatch({ type: "ADD_TOAST", toast: { ...props, id, open: true } });
|
||||
return id;
|
||||
};
|
||||
|
||||
+146
-159
@@ -1,50 +1,43 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { distanceInKm } from '@/lib/utils'
|
||||
import type {
|
||||
ApiDensityCell,
|
||||
ApiPoint,
|
||||
ApiSnapshot,
|
||||
FeedStatus,
|
||||
Point,
|
||||
SnapshotEventPayload,
|
||||
} from '@/types/api'
|
||||
import { distanceInKm } from "@/lib/utils";
|
||||
import type { ApiDensityCell, ApiPoint, ApiSnapshot, FeedStatus, Point, SnapshotEventPayload } from "@/types/api";
|
||||
|
||||
const API_BASE = import.meta.env.VITE_API_BASE ?? 'http://localhost:8000/api/signals'
|
||||
const SNAPSHOT_LIMIT = 750
|
||||
const MERCURE_HUB = import.meta.env.VITE_MERCURE_HUB ?? 'http://localhost:3000/.well-known/mercure'
|
||||
const MERCURE_TOPIC = import.meta.env.VITE_MERCURE_TOPIC ?? 'https://points-of-interest.local/signals'
|
||||
const VISIBLE_RADIUS_KM = 1
|
||||
const API_BASE = import.meta.env.VITE_API_BASE ?? "http://localhost:8000/api/signals";
|
||||
const SNAPSHOT_LIMIT = 750;
|
||||
const MERCURE_HUB = import.meta.env.VITE_MERCURE_HUB ?? "http://localhost:3000/.well-known/mercure";
|
||||
const MERCURE_TOPIC = import.meta.env.VITE_MERCURE_TOPIC ?? "https://points-of-interest.local/signals";
|
||||
const VISIBLE_RADIUS_KM = 1;
|
||||
|
||||
type ProblemDetails = {
|
||||
detail?: unknown
|
||||
}
|
||||
detail?: unknown;
|
||||
};
|
||||
|
||||
function extractProblemDetail(payload: unknown): string | null {
|
||||
if (payload && typeof payload === 'object') {
|
||||
const { detail } = payload as ProblemDetails
|
||||
if (typeof detail === 'string' && detail.trim().length > 0) {
|
||||
return detail
|
||||
if (payload && typeof payload === "object") {
|
||||
const { detail } = payload as ProblemDetails;
|
||||
if (typeof detail === "string" && detail.trim().length > 0) {
|
||||
return detail;
|
||||
}
|
||||
}
|
||||
return null
|
||||
return null;
|
||||
}
|
||||
|
||||
interface UseHotspotFeedOptions {
|
||||
userLocation: Point | null
|
||||
snapshotLimit?: number
|
||||
mercureHub?: string
|
||||
mercureTopic?: string
|
||||
userLocation: Point | null;
|
||||
snapshotLimit?: number;
|
||||
mercureHub?: string;
|
||||
mercureTopic?: string;
|
||||
}
|
||||
|
||||
interface SubmitResult {
|
||||
success: boolean
|
||||
success: boolean;
|
||||
}
|
||||
|
||||
export interface FeedError {
|
||||
key: string
|
||||
values?: Record<string, unknown>
|
||||
detail?: string
|
||||
key: string;
|
||||
values?: Record<string, unknown>;
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
export function useHotspotFeed({
|
||||
@@ -53,228 +46,222 @@ export function useHotspotFeed({
|
||||
mercureHub = MERCURE_HUB,
|
||||
mercureTopic = MERCURE_TOPIC,
|
||||
}: UseHotspotFeedOptions) {
|
||||
const [status, setStatus] = useState<FeedStatus>('loading')
|
||||
const [error, setError] = useState<FeedError | null>(null)
|
||||
const [rawPoints, setRawPoints] = useState<ApiPoint[]>([])
|
||||
const [rawDensity, setRawDensity] = useState<ApiDensityCell[]>([])
|
||||
const [rawLatestByUser, setRawLatestByUser] = useState<ApiPoint[]>([])
|
||||
const [clientKey, setClientKey] = useState<string | null>(null)
|
||||
const [lastUpdated, setLastUpdated] = useState<string | null>(null)
|
||||
const [status, setStatus] = useState<FeedStatus>("loading");
|
||||
const [error, setError] = useState<FeedError | null>(null);
|
||||
const [rawPoints, setRawPoints] = useState<ApiPoint[]>([]);
|
||||
const [rawDensity, setRawDensity] = useState<ApiDensityCell[]>([]);
|
||||
const [rawLatestByUser, setRawLatestByUser] = useState<ApiPoint[]>([]);
|
||||
const [clientKey, setClientKey] = useState<string | null>(null);
|
||||
const [lastUpdated, setLastUpdated] = useState<string | null>(null);
|
||||
|
||||
const statusRef = useRef<FeedStatus>('loading')
|
||||
const initialLoadRef = useRef(true)
|
||||
const eventSourceRef = useRef<EventSource | null>(null)
|
||||
const statusRef = useRef<FeedStatus>("loading");
|
||||
const initialLoadRef = useRef(true);
|
||||
const eventSourceRef = useRef<EventSource | null>(null);
|
||||
|
||||
const setStatusSafe = useCallback((next: FeedStatus) => {
|
||||
statusRef.current = next
|
||||
setStatus(next)
|
||||
}, [])
|
||||
statusRef.current = next;
|
||||
setStatus(next);
|
||||
}, []);
|
||||
|
||||
const applySnapshot = useCallback(
|
||||
(snapshot: ApiSnapshot, options?: { preserveClientKey?: boolean }) => {
|
||||
setRawPoints(snapshot.points)
|
||||
setRawDensity(snapshot.density)
|
||||
setRawLatestByUser(snapshot.latestByUser)
|
||||
setRawPoints(snapshot.points);
|
||||
setRawDensity(snapshot.density);
|
||||
setRawLatestByUser(snapshot.latestByUser);
|
||||
if (!options?.preserveClientKey) {
|
||||
setClientKey(snapshot.clientKey ?? null)
|
||||
setClientKey(snapshot.clientKey ?? null);
|
||||
}
|
||||
setLastUpdated(snapshot.updatedAt ?? new Date().toISOString())
|
||||
setError(null)
|
||||
initialLoadRef.current = false
|
||||
if (statusRef.current !== 'posting') {
|
||||
setStatusSafe('idle')
|
||||
setLastUpdated(snapshot.updatedAt ?? new Date().toISOString());
|
||||
setError(null);
|
||||
initialLoadRef.current = false;
|
||||
if (statusRef.current !== "posting") {
|
||||
setStatusSafe("idle");
|
||||
}
|
||||
},
|
||||
[setStatusSafe],
|
||||
)
|
||||
[setStatusSafe]
|
||||
);
|
||||
|
||||
const fetchSnapshot = useCallback(
|
||||
async (options?: { silent?: boolean }) => {
|
||||
const silent = options?.silent ?? false
|
||||
const previousStatus = statusRef.current
|
||||
const isInitial = initialLoadRef.current
|
||||
const silent = options?.silent ?? false;
|
||||
const previousStatus = statusRef.current;
|
||||
const isInitial = initialLoadRef.current;
|
||||
|
||||
if (previousStatus !== 'posting') {
|
||||
if (previousStatus !== "posting") {
|
||||
if (isInitial) {
|
||||
setStatusSafe('loading')
|
||||
setStatusSafe("loading");
|
||||
} else if (!silent) {
|
||||
setStatusSafe('refreshing')
|
||||
setStatusSafe("refreshing");
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}?limit=${snapshotLimit}`, { cache: 'no-store' })
|
||||
const response = await fetch(`${API_BASE}?limit=${snapshotLimit}`, { cache: "no-store" });
|
||||
if (!response.ok) {
|
||||
const payload = await response.json().catch(() => null)
|
||||
const detail = extractProblemDetail(payload)
|
||||
setError({ key: 'errors.feedUnavailable', detail: detail ?? undefined })
|
||||
const payload = await response.json().catch(() => null);
|
||||
const detail = extractProblemDetail(payload);
|
||||
setError({ key: "errors.feedUnavailable", detail: detail ?? undefined });
|
||||
if (initialLoadRef.current) {
|
||||
setStatusSafe('error')
|
||||
} else if (previousStatus !== 'posting') {
|
||||
setStatusSafe('idle')
|
||||
setStatusSafe("error");
|
||||
} else if (previousStatus !== "posting") {
|
||||
setStatusSafe("idle");
|
||||
}
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
const data: ApiSnapshot = await response.json()
|
||||
applySnapshot(data)
|
||||
const data: ApiSnapshot = await response.json();
|
||||
applySnapshot(data);
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error && error.message ? error.message : null
|
||||
setError({ key: 'errors.feedUnknown', detail: detail ?? undefined })
|
||||
const detail = error instanceof Error && error.message ? error.message : null;
|
||||
setError({ key: "errors.feedUnknown", detail: detail ?? undefined });
|
||||
if (initialLoadRef.current) {
|
||||
setStatusSafe('error')
|
||||
} else if (previousStatus !== 'posting') {
|
||||
setStatusSafe('idle')
|
||||
setStatusSafe("error");
|
||||
} else if (previousStatus !== "posting") {
|
||||
setStatusSafe("idle");
|
||||
}
|
||||
}
|
||||
},
|
||||
[snapshotLimit, setStatusSafe, applySnapshot],
|
||||
)
|
||||
[snapshotLimit, setStatusSafe, applySnapshot]
|
||||
);
|
||||
|
||||
const connectToStream = useCallback(() => {
|
||||
try {
|
||||
eventSourceRef.current?.close()
|
||||
eventSourceRef.current = null
|
||||
eventSourceRef.current?.close();
|
||||
eventSourceRef.current = null;
|
||||
|
||||
const url = new URL(mercureHub)
|
||||
url.searchParams.append('topic', mercureTopic)
|
||||
const url = new URL(mercureHub);
|
||||
url.searchParams.append("topic", mercureTopic);
|
||||
|
||||
const eventSource = new EventSource(url.toString())
|
||||
eventSource.onmessage = (event) => {
|
||||
const eventSource = new EventSource(url.toString());
|
||||
eventSource.onmessage = event => {
|
||||
try {
|
||||
const payload: SnapshotEventPayload = JSON.parse(event.data)
|
||||
if (payload?.type === 'snapshot' && payload.payload) {
|
||||
applySnapshot(payload.payload, { preserveClientKey: true })
|
||||
const payload: SnapshotEventPayload = JSON.parse(event.data);
|
||||
if (payload?.type === "snapshot" && payload.payload) {
|
||||
applySnapshot(payload.payload, { preserveClientKey: true });
|
||||
}
|
||||
} catch (parseError) {
|
||||
console.error('Failed to parse stream payload', parseError)
|
||||
console.error("Failed to parse stream payload", parseError);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
eventSource.onerror = () => {
|
||||
if (statusRef.current !== 'loading') {
|
||||
setError({ key: 'errors.feedUnknown' })
|
||||
setStatusSafe('error')
|
||||
if (statusRef.current !== "loading") {
|
||||
setError({ key: "errors.feedUnknown" });
|
||||
setStatusSafe("error");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
eventSourceRef.current = eventSource
|
||||
eventSourceRef.current = eventSource;
|
||||
} catch (connectionError) {
|
||||
console.error('Unable to subscribe to live updates', connectionError)
|
||||
setError({ key: 'errors.feedUnavailable' })
|
||||
setStatusSafe('error')
|
||||
console.error("Unable to subscribe to live updates", connectionError);
|
||||
setError({ key: "errors.feedUnavailable" });
|
||||
setStatusSafe("error");
|
||||
}
|
||||
}, [applySnapshot, mercureHub, mercureTopic, setStatusSafe])
|
||||
}, [applySnapshot, mercureHub, mercureTopic, setStatusSafe]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchSnapshot().catch(() => undefined)
|
||||
connectToStream()
|
||||
fetchSnapshot().catch(() => undefined);
|
||||
connectToStream();
|
||||
|
||||
return () => {
|
||||
eventSourceRef.current?.close()
|
||||
eventSourceRef.current = null
|
||||
}
|
||||
}, [connectToStream, fetchSnapshot])
|
||||
eventSourceRef.current?.close();
|
||||
eventSourceRef.current = null;
|
||||
};
|
||||
}, [connectToStream, fetchSnapshot]);
|
||||
|
||||
const submitPoint = useCallback(
|
||||
async (target: Point): Promise<SubmitResult> => {
|
||||
if (!userLocation) {
|
||||
setError({
|
||||
key: 'errors.submitWithReason',
|
||||
values: { message: 'Location required before submitting.' },
|
||||
detail: 'Location required before submitting.',
|
||||
})
|
||||
setStatusSafe('error')
|
||||
return { success: false }
|
||||
key: "errors.submitWithReason",
|
||||
values: { message: "Location required before submitting." },
|
||||
detail: "Location required before submitting.",
|
||||
});
|
||||
setStatusSafe("error");
|
||||
return { success: false };
|
||||
}
|
||||
|
||||
setStatusSafe('posting')
|
||||
setStatusSafe("posting");
|
||||
try {
|
||||
const response = await fetch(API_BASE, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
signalLocation: target,
|
||||
userLocation,
|
||||
}),
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const payload = await response.json().catch(() => null)
|
||||
const detail = extractProblemDetail(payload)
|
||||
const payload = await response.json().catch(() => null);
|
||||
const detail = extractProblemDetail(payload);
|
||||
if (detail) {
|
||||
setError({
|
||||
key: 'errors.submitWithReason',
|
||||
key: "errors.submitWithReason",
|
||||
values: { message: detail },
|
||||
detail,
|
||||
})
|
||||
});
|
||||
} else {
|
||||
setError({ key: 'errors.submitUnavailable' })
|
||||
setError({ key: "errors.submitUnavailable" });
|
||||
}
|
||||
setStatusSafe('error')
|
||||
return { success: false }
|
||||
setStatusSafe("error");
|
||||
return { success: false };
|
||||
}
|
||||
|
||||
setError(null)
|
||||
setStatusSafe('idle')
|
||||
return { success: true }
|
||||
setError(null);
|
||||
setStatusSafe("idle");
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error && error.message ? error.message : null
|
||||
const detail = error instanceof Error && error.message ? error.message : null;
|
||||
if (detail) {
|
||||
setError({ key: 'errors.submitWithReason', values: { message: detail }, detail })
|
||||
setError({ key: "errors.submitWithReason", values: { message: detail }, detail });
|
||||
} else {
|
||||
setError({ key: 'errors.submitUnknown' })
|
||||
setError({ key: "errors.submitUnknown" });
|
||||
}
|
||||
setStatusSafe('error')
|
||||
return { success: false }
|
||||
setStatusSafe("error");
|
||||
return { success: false };
|
||||
}
|
||||
},
|
||||
[setStatusSafe, userLocation],
|
||||
)
|
||||
[setStatusSafe, userLocation]
|
||||
);
|
||||
|
||||
const hasClientKey = Boolean(clientKey)
|
||||
const hasClientKey = Boolean(clientKey);
|
||||
|
||||
const filterDensityWithinRadius = useCallback(
|
||||
(collection: ApiDensityCell[], origin: Point | null) => {
|
||||
if (!origin) {
|
||||
return collection
|
||||
}
|
||||
return collection.filter((item) => distanceInKm(origin, item) <= VISIBLE_RADIUS_KM)
|
||||
},
|
||||
[],
|
||||
)
|
||||
const filterDensityWithinRadius = useCallback((collection: ApiDensityCell[], origin: Point | null) => {
|
||||
if (!origin) {
|
||||
return collection;
|
||||
}
|
||||
return collection.filter(item => distanceInKm(origin, item) <= VISIBLE_RADIUS_KM);
|
||||
}, []);
|
||||
|
||||
const filterPointsWithinRadius = useCallback(
|
||||
(collection: ApiPoint[], origin: Point | null) => {
|
||||
if (!origin) {
|
||||
return collection
|
||||
}
|
||||
return collection.filter((item) => distanceInKm(origin, item.signalLocation) <= VISIBLE_RADIUS_KM)
|
||||
},
|
||||
[],
|
||||
)
|
||||
const filterPointsWithinRadius = useCallback((collection: ApiPoint[], origin: Point | null) => {
|
||||
if (!origin) {
|
||||
return collection;
|
||||
}
|
||||
return collection.filter(item => distanceInKm(origin, item.signalLocation) <= VISIBLE_RADIUS_KM);
|
||||
}, []);
|
||||
|
||||
const selectVisibleDensity = useCallback(
|
||||
(origin: Point | null) => filterDensityWithinRadius(rawDensity, origin),
|
||||
[filterDensityWithinRadius, rawDensity],
|
||||
)
|
||||
[filterDensityWithinRadius, rawDensity]
|
||||
);
|
||||
|
||||
const selectVisiblePoints = useCallback(
|
||||
(origin: Point | null) => filterPointsWithinRadius(rawPoints, origin),
|
||||
[filterPointsWithinRadius, rawPoints],
|
||||
)
|
||||
[filterPointsWithinRadius, rawPoints]
|
||||
);
|
||||
|
||||
const selectVisibleLatestByUser = useCallback(
|
||||
(origin: Point | null) => filterPointsWithinRadius(rawLatestByUser, origin),
|
||||
[filterPointsWithinRadius, rawLatestByUser],
|
||||
)
|
||||
[filterPointsWithinRadius, rawLatestByUser]
|
||||
);
|
||||
|
||||
const myLatestPoint = useMemo(() => {
|
||||
if (!hasClientKey) {
|
||||
return null
|
||||
return null;
|
||||
}
|
||||
return rawLatestByUser.find((point) => point.userKey === clientKey) ?? null
|
||||
}, [clientKey, hasClientKey, rawLatestByUser])
|
||||
return rawLatestByUser.find(point => point.userKey === clientKey) ?? null;
|
||||
}, [clientKey, hasClientKey, rawLatestByUser]);
|
||||
|
||||
return {
|
||||
status,
|
||||
@@ -291,5 +278,5 @@ export function useHotspotFeed({
|
||||
selectVisiblePoints,
|
||||
selectVisibleLatestByUser,
|
||||
myLatestPoint,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,66 +1,67 @@
|
||||
import { useCallback, useEffect, useRef } from 'react'
|
||||
import type { MutableRefObject } from 'react'
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import type { MutableRefObject } from "react";
|
||||
|
||||
import L, {
|
||||
type LeafletMouseEvent,
|
||||
type Map as LeafletMap,
|
||||
type LayerGroup,
|
||||
type TileLayer,
|
||||
type TileLayerOptions,
|
||||
} from 'leaflet'
|
||||
import 'leaflet.heat'
|
||||
} from "leaflet";
|
||||
import "leaflet.heat";
|
||||
|
||||
import type { ApiDensityCell, Point } from '@/types/api'
|
||||
import type { ApiDensityCell, Point } from "@/types/api";
|
||||
|
||||
type HeatPoint = [number, number, number?]
|
||||
type HeatPoint = [number, number, number?];
|
||||
|
||||
type LeafletHeatLayer = L.Layer & {
|
||||
setLatLngs(points: HeatPoint[]): LeafletHeatLayer
|
||||
getBounds?: () => L.LatLngBounds
|
||||
}
|
||||
setLatLngs(points: HeatPoint[]): LeafletHeatLayer;
|
||||
getBounds?: () => L.LatLngBounds;
|
||||
};
|
||||
|
||||
type LeafletWithHeat = typeof L & {
|
||||
heatLayer?: (points: HeatPoint[], options?: Record<string, unknown>) => LeafletHeatLayer
|
||||
}
|
||||
heatLayer?: (points: HeatPoint[], options?: Record<string, unknown>) => LeafletHeatLayer;
|
||||
};
|
||||
|
||||
interface UseLeafletHeatmapParams {
|
||||
heatCells: ApiDensityCell[]
|
||||
userLocation: Point | null
|
||||
onRequestSpot?: (position: Point) => void
|
||||
tileProvider: TileProvider
|
||||
heatCells: ApiDensityCell[];
|
||||
userLocation: Point | null;
|
||||
onRequestSpot?: (position: Point) => void;
|
||||
tileProvider: TileProvider;
|
||||
}
|
||||
|
||||
interface UseLeafletHeatmapResult {
|
||||
mapContainerRef: MutableRefObject<HTMLDivElement | null>
|
||||
focusOn: (position: Point, zoom?: number) => void
|
||||
fitToHeat: () => void
|
||||
map: LeafletMap | null
|
||||
mapContainerRef: MutableRefObject<HTMLDivElement | null>;
|
||||
focusOn: (position: Point, zoom?: number) => void;
|
||||
fitToHeat: () => void;
|
||||
map: LeafletMap | null;
|
||||
}
|
||||
|
||||
type TileSource = {
|
||||
readonly url: string
|
||||
readonly attribution: string
|
||||
readonly options?: TileLayerOptions
|
||||
}
|
||||
readonly url: string;
|
||||
readonly attribution: string;
|
||||
readonly options?: TileLayerOptions;
|
||||
};
|
||||
|
||||
const TILE_SOURCES = {
|
||||
openstreetmap: {
|
||||
url: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
|
||||
attribution: '© OpenStreetMap contributors',
|
||||
url: "https://tile.openstreetmap.org/{z}/{x}/{y}.png",
|
||||
attribution: "© OpenStreetMap contributors",
|
||||
},
|
||||
mapbox: {
|
||||
url: 'https://api.mapbox.com/styles/v1/mapbox/navigation-day-v1/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoiMWNhbnNhIiwiYSI6ImNsdzZ5cHp3bTFheWUydHJ6dHA4empteWEifQ.a3bODguIOY5HqhsVIvW48Q',
|
||||
attribution: '© Mapbox, © OpenStreetMap contributors',
|
||||
url: "https://api.mapbox.com/styles/v1/mapbox/navigation-day-v1/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoiMWNhbnNhIiwiYSI6ImNsdzZ5cHp3bTFheWUydHJ6dHA4empteWEifQ.a3bODguIOY5HqhsVIvW48Q",
|
||||
attribution: "© Mapbox, © OpenStreetMap contributors",
|
||||
options: {
|
||||
tileSize: 512,
|
||||
zoomOffset: -1,
|
||||
} satisfies TileLayerOptions,
|
||||
},
|
||||
} as const satisfies Record<string, TileSource>
|
||||
} as const satisfies Record<string, TileSource>;
|
||||
|
||||
export type TileProvider = keyof typeof TILE_SOURCES
|
||||
export type TileProvider = keyof typeof TILE_SOURCES;
|
||||
|
||||
const INITIAL_VIEW: Point = { lat: 20, lng: 0 }
|
||||
const DEFAULT_ZOOM = 3
|
||||
const INITIAL_VIEW: Point = { lat: 20, lng: 0 };
|
||||
const DEFAULT_ZOOM = 3;
|
||||
|
||||
export function useLeafletHeatmap({
|
||||
heatCells,
|
||||
@@ -68,37 +69,34 @@ export function useLeafletHeatmap({
|
||||
onRequestSpot,
|
||||
tileProvider,
|
||||
}: UseLeafletHeatmapParams): UseLeafletHeatmapResult {
|
||||
const mapRef = useRef<LeafletMap | null>(null)
|
||||
const heatLayerRef = useRef<LeafletHeatLayer | null>(null)
|
||||
const userLayerRef = useRef<LayerGroup | null>(null)
|
||||
const tileLayerRef = useRef<TileLayer | null>(null)
|
||||
const hasCenteredOnUserRef = useRef(false)
|
||||
const mapContainerRef = useRef<HTMLDivElement | null>(null)
|
||||
const onRequestSpotRef = useRef(onRequestSpot)
|
||||
const tileProviderRef = useRef<TileProvider>(tileProvider)
|
||||
const mapRef = useRef<LeafletMap | null>(null);
|
||||
const heatLayerRef = useRef<LeafletHeatLayer | null>(null);
|
||||
const userLayerRef = useRef<LayerGroup | null>(null);
|
||||
const tileLayerRef = useRef<TileLayer | null>(null);
|
||||
const hasCenteredOnUserRef = useRef(false);
|
||||
const mapContainerRef = useRef<HTMLDivElement | null>(null);
|
||||
const onRequestSpotRef = useRef(onRequestSpot);
|
||||
const tileProviderRef = useRef<TileProvider>(tileProvider);
|
||||
|
||||
const createTileLayer = useCallback(
|
||||
(provider: TileProvider) => {
|
||||
const leaflet = L as LeafletWithHeat
|
||||
const source: TileSource = TILE_SOURCES[provider]
|
||||
const options = source.options ?? {}
|
||||
return leaflet.tileLayer(source.url, {
|
||||
attribution: source.attribution,
|
||||
crossOrigin: true,
|
||||
maxZoom: 19,
|
||||
...options,
|
||||
})
|
||||
},
|
||||
[],
|
||||
)
|
||||
const createTileLayer = useCallback((provider: TileProvider) => {
|
||||
const leaflet = L as LeafletWithHeat;
|
||||
const source: TileSource = TILE_SOURCES[provider];
|
||||
const options = source.options ?? {};
|
||||
return leaflet.tileLayer(source.url, {
|
||||
attribution: source.attribution,
|
||||
crossOrigin: true,
|
||||
maxZoom: 19,
|
||||
...options,
|
||||
});
|
||||
}, []);
|
||||
|
||||
const initialiseMap = useCallback(() => {
|
||||
if (mapRef.current || !mapContainerRef.current) {
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
const leaflet = L as LeafletWithHeat
|
||||
const container = mapContainerRef.current
|
||||
const leaflet = L as LeafletWithHeat;
|
||||
const container = mapContainerRef.current;
|
||||
|
||||
const map = leaflet
|
||||
.map(container, {
|
||||
@@ -107,179 +105,179 @@ export function useLeafletHeatmap({
|
||||
zoomControl: false,
|
||||
attributionControl: false,
|
||||
})
|
||||
.setView([INITIAL_VIEW.lat, INITIAL_VIEW.lng], DEFAULT_ZOOM)
|
||||
.setView([INITIAL_VIEW.lat, INITIAL_VIEW.lng], DEFAULT_ZOOM);
|
||||
|
||||
const tileLayer = createTileLayer(tileProviderRef.current)
|
||||
tileLayer.addTo(map)
|
||||
const tileLayer = createTileLayer(tileProviderRef.current);
|
||||
tileLayer.addTo(map);
|
||||
|
||||
const heatLayer =
|
||||
typeof leaflet.heatLayer === 'function'
|
||||
typeof leaflet.heatLayer === "function"
|
||||
? leaflet.heatLayer([], {
|
||||
radius: 32,
|
||||
blur: 24,
|
||||
maxZoom: 12,
|
||||
gradient: {
|
||||
0.2: '#38bdf8',
|
||||
0.4: '#0ea5e9',
|
||||
0.6: '#fbbf24',
|
||||
0.8: '#fb923c',
|
||||
1: '#ef4444',
|
||||
0.2: "#38bdf8",
|
||||
0.4: "#0ea5e9",
|
||||
0.6: "#fbbf24",
|
||||
0.8: "#fb923c",
|
||||
1: "#ef4444",
|
||||
},
|
||||
})
|
||||
: null
|
||||
: null;
|
||||
|
||||
const userLayer = leaflet.layerGroup().addTo(map)
|
||||
const userLayer = leaflet.layerGroup().addTo(map);
|
||||
|
||||
if (heatLayer) {
|
||||
heatLayer.addTo(map)
|
||||
heatLayer.addTo(map);
|
||||
}
|
||||
|
||||
const handleClick = (event: LeafletMouseEvent) => {
|
||||
const { lat, lng } = event.latlng
|
||||
if (typeof lat === 'number' && typeof lng === 'number') {
|
||||
onRequestSpotRef.current?.({ lat, lng })
|
||||
const { lat, lng } = event.latlng;
|
||||
if (typeof lat === "number" && typeof lng === "number") {
|
||||
onRequestSpotRef.current?.({ lat, lng });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
map.on('click', handleClick)
|
||||
map.on("click", handleClick);
|
||||
|
||||
map.whenReady(() => {
|
||||
requestAnimationFrame(() => {
|
||||
map.invalidateSize()
|
||||
})
|
||||
})
|
||||
map.invalidateSize();
|
||||
});
|
||||
});
|
||||
|
||||
const onResize = () => {
|
||||
requestAnimationFrame(() => {
|
||||
map.invalidateSize()
|
||||
})
|
||||
}
|
||||
map.invalidateSize();
|
||||
});
|
||||
};
|
||||
|
||||
window.addEventListener('resize', onResize)
|
||||
window.addEventListener("resize", onResize);
|
||||
|
||||
mapRef.current = map
|
||||
heatLayerRef.current = heatLayer
|
||||
userLayerRef.current = userLayer
|
||||
tileLayerRef.current = tileLayer
|
||||
mapRef.current = map;
|
||||
heatLayerRef.current = heatLayer;
|
||||
userLayerRef.current = userLayer;
|
||||
tileLayerRef.current = tileLayer;
|
||||
|
||||
return () => {
|
||||
map.off('click', handleClick)
|
||||
window.removeEventListener('resize', onResize)
|
||||
map.remove()
|
||||
mapRef.current = null
|
||||
heatLayerRef.current = null
|
||||
userLayerRef.current = null
|
||||
tileLayerRef.current = null
|
||||
hasCenteredOnUserRef.current = false
|
||||
}
|
||||
}, [createTileLayer])
|
||||
map.off("click", handleClick);
|
||||
window.removeEventListener("resize", onResize);
|
||||
map.remove();
|
||||
mapRef.current = null;
|
||||
heatLayerRef.current = null;
|
||||
userLayerRef.current = null;
|
||||
tileLayerRef.current = null;
|
||||
hasCenteredOnUserRef.current = false;
|
||||
};
|
||||
}, [createTileLayer]);
|
||||
|
||||
useEffect(() => {
|
||||
onRequestSpotRef.current = onRequestSpot
|
||||
}, [onRequestSpot])
|
||||
onRequestSpotRef.current = onRequestSpot;
|
||||
}, [onRequestSpot]);
|
||||
|
||||
useEffect(() => {
|
||||
const cleanup = initialiseMap()
|
||||
const cleanup = initialiseMap();
|
||||
|
||||
return () => {
|
||||
if (typeof cleanup === 'function') {
|
||||
cleanup()
|
||||
if (typeof cleanup === "function") {
|
||||
cleanup();
|
||||
}
|
||||
}
|
||||
}, [initialiseMap])
|
||||
};
|
||||
}, [initialiseMap]);
|
||||
|
||||
useEffect(() => {
|
||||
tileProviderRef.current = tileProvider
|
||||
const map = mapRef.current
|
||||
tileProviderRef.current = tileProvider;
|
||||
const map = mapRef.current;
|
||||
if (!map) {
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
const nextLayer = createTileLayer(tileProvider)
|
||||
const currentLayer = tileLayerRef.current
|
||||
const nextLayer = createTileLayer(tileProvider);
|
||||
const currentLayer = tileLayerRef.current;
|
||||
|
||||
if (currentLayer) {
|
||||
currentLayer.removeFrom(map)
|
||||
currentLayer.removeFrom(map);
|
||||
}
|
||||
|
||||
nextLayer.addTo(map)
|
||||
tileLayerRef.current = nextLayer
|
||||
}, [createTileLayer, tileProvider])
|
||||
nextLayer.addTo(map);
|
||||
tileLayerRef.current = nextLayer;
|
||||
}, [createTileLayer, tileProvider]);
|
||||
|
||||
useEffect(() => {
|
||||
const heatLayer = heatLayerRef.current
|
||||
const heatLayer = heatLayerRef.current;
|
||||
if (!heatLayer) {
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
if (!heatCells.length) {
|
||||
heatLayer.setLatLngs([])
|
||||
return
|
||||
heatLayer.setLatLngs([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const maxIntensity = Math.max(...heatCells.map((cell) => cell.intensity)) || 1
|
||||
const heatPoints: HeatPoint[] = heatCells.map((cell) => [
|
||||
const maxIntensity = Math.max(...heatCells.map(cell => cell.intensity)) || 1;
|
||||
const heatPoints: HeatPoint[] = heatCells.map(cell => [
|
||||
cell.lat,
|
||||
cell.lng,
|
||||
Math.max(0.2, cell.intensity / maxIntensity),
|
||||
])
|
||||
]);
|
||||
|
||||
heatLayer.setLatLngs(heatPoints)
|
||||
}, [heatCells])
|
||||
heatLayer.setLatLngs(heatPoints);
|
||||
}, [heatCells]);
|
||||
|
||||
useEffect(() => {
|
||||
const userLayer = userLayerRef.current
|
||||
const map = mapRef.current
|
||||
const userLayer = userLayerRef.current;
|
||||
const map = mapRef.current;
|
||||
if (!userLayer || !map) {
|
||||
return
|
||||
return;
|
||||
}
|
||||
|
||||
userLayer.clearLayers()
|
||||
userLayer.clearLayers();
|
||||
|
||||
if (!userLocation) {
|
||||
hasCenteredOnUserRef.current = false
|
||||
return
|
||||
hasCenteredOnUserRef.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
L.circleMarker([userLocation.lat, userLocation.lng], {
|
||||
radius: 7,
|
||||
color: '#38bdf8',
|
||||
color: "#38bdf8",
|
||||
weight: 3,
|
||||
opacity: 0.9,
|
||||
fillColor: '#38bdf8',
|
||||
fillColor: "#38bdf8",
|
||||
fillOpacity: 0.35,
|
||||
}).addTo(userLayer)
|
||||
}).addTo(userLayer);
|
||||
|
||||
if (!hasCenteredOnUserRef.current) {
|
||||
map.setView([userLocation.lat, userLocation.lng], 13, { animate: true })
|
||||
hasCenteredOnUserRef.current = true
|
||||
map.setView([userLocation.lat, userLocation.lng], 13, { animate: true });
|
||||
hasCenteredOnUserRef.current = true;
|
||||
}
|
||||
}, [userLocation])
|
||||
}, [userLocation]);
|
||||
|
||||
const focusOn = useCallback((position: Point, zoom = 14) => {
|
||||
const map = mapRef.current
|
||||
const map = mapRef.current;
|
||||
if (!map) {
|
||||
return
|
||||
return;
|
||||
}
|
||||
map.setView([position.lat, position.lng], zoom, { animate: true })
|
||||
}, [])
|
||||
map.setView([position.lat, position.lng], zoom, { animate: true });
|
||||
}, []);
|
||||
|
||||
const fitToHeat = useCallback(() => {
|
||||
const map = mapRef.current
|
||||
const heatLayer = heatLayerRef.current
|
||||
const map = mapRef.current;
|
||||
const heatLayer = heatLayerRef.current;
|
||||
if (!map || !heatLayer) {
|
||||
return
|
||||
return;
|
||||
}
|
||||
const bounds = heatLayer.getBounds?.()
|
||||
const bounds = heatLayer.getBounds?.();
|
||||
if (bounds && bounds.isValid()) {
|
||||
map.fitBounds(bounds.pad(0.25), { animate: true })
|
||||
map.fitBounds(bounds.pad(0.25), { animate: true });
|
||||
}
|
||||
}, [])
|
||||
}, []);
|
||||
|
||||
return {
|
||||
mapContainerRef,
|
||||
focusOn,
|
||||
fitToHeat,
|
||||
map: mapRef.current,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,46 +1,46 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
|
||||
type Theme = 'light' | 'dark'
|
||||
type Theme = "light" | "dark";
|
||||
|
||||
const STORAGE_KEY = 'signalmap-theme'
|
||||
const STORAGE_KEY = "signalmap-theme";
|
||||
|
||||
function applyTheme(theme: Theme) {
|
||||
const root = document.documentElement
|
||||
if (theme === 'dark') {
|
||||
root.classList.add('dark')
|
||||
const root = document.documentElement;
|
||||
if (theme === "dark") {
|
||||
root.classList.add("dark");
|
||||
} else {
|
||||
root.classList.remove('dark')
|
||||
root.classList.remove("dark");
|
||||
}
|
||||
}
|
||||
|
||||
function getPreferredTheme(): Theme {
|
||||
if (typeof window === 'undefined') {
|
||||
return 'dark'
|
||||
if (typeof window === "undefined") {
|
||||
return "dark";
|
||||
}
|
||||
const stored = window.localStorage.getItem(STORAGE_KEY)
|
||||
if (stored === 'light' || stored === 'dark') {
|
||||
return stored
|
||||
const stored = window.localStorage.getItem(STORAGE_KEY);
|
||||
if (stored === "light" || stored === "dark") {
|
||||
return stored;
|
||||
}
|
||||
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||
return prefersDark ? 'dark' : 'light'
|
||||
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
|
||||
return prefersDark ? "dark" : "light";
|
||||
}
|
||||
|
||||
export function useTheme() {
|
||||
const [theme, setTheme] = useState<Theme>(() => getPreferredTheme())
|
||||
const [theme, setTheme] = useState<Theme>(() => getPreferredTheme());
|
||||
|
||||
useEffect(() => {
|
||||
applyTheme(theme)
|
||||
window.localStorage.setItem(STORAGE_KEY, theme)
|
||||
}, [theme])
|
||||
applyTheme(theme);
|
||||
window.localStorage.setItem(STORAGE_KEY, theme);
|
||||
}, [theme]);
|
||||
|
||||
const toggleTheme = useCallback(() => {
|
||||
setTheme((current) => (current === 'dark' ? 'light' : 'dark'))
|
||||
}, [])
|
||||
setTheme(current => (current === "dark" ? "light" : "dark"));
|
||||
}, []);
|
||||
|
||||
return {
|
||||
theme,
|
||||
setTheme,
|
||||
toggleTheme,
|
||||
isDark: theme === 'dark',
|
||||
}
|
||||
isDark: theme === "dark",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,90 +1,90 @@
|
||||
import { useCallback, useEffect, useRef } from 'react'
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
|
||||
import type { Point } from '@/types/api'
|
||||
import { useAppStore } from '@/store/useAppStore'
|
||||
import { useAppStore } from "@/store/useAppStore";
|
||||
import type { Point } from "@/types/api";
|
||||
|
||||
function geolocationErrorMessage(error: GeolocationPositionError): string {
|
||||
switch (error.code) {
|
||||
case error.PERMISSION_DENIED:
|
||||
return 'location.error.permissionDenied'
|
||||
return "location.error.permissionDenied";
|
||||
case error.POSITION_UNAVAILABLE:
|
||||
return 'location.error.unavailable'
|
||||
return "location.error.unavailable";
|
||||
case error.TIMEOUT:
|
||||
return 'location.error.timeout'
|
||||
return "location.error.timeout";
|
||||
default:
|
||||
return 'location.error.generic'
|
||||
return "location.error.generic";
|
||||
}
|
||||
}
|
||||
|
||||
export function useUserLocation() {
|
||||
const setUserLocation = useAppStore((state) => state.setUserLocation)
|
||||
const setLocationError = useAppStore((state) => state.setLocationError)
|
||||
const setIsRequestingLocation = useAppStore((state) => state.setIsRequestingLocation)
|
||||
const watchIdRef = useRef<number | null>(null)
|
||||
const setUserLocation = useAppStore(state => state.setUserLocation);
|
||||
const setLocationError = useAppStore(state => state.setLocationError);
|
||||
const setIsRequestingLocation = useAppStore(state => state.setIsRequestingLocation);
|
||||
const watchIdRef = useRef<number | null>(null);
|
||||
|
||||
const clearWatch = useCallback(() => {
|
||||
if (typeof navigator === 'undefined' || !navigator.geolocation) {
|
||||
return
|
||||
if (typeof navigator === "undefined" || !navigator.geolocation) {
|
||||
return;
|
||||
}
|
||||
if (watchIdRef.current !== null) {
|
||||
navigator.geolocation.clearWatch(watchIdRef.current)
|
||||
watchIdRef.current = null
|
||||
navigator.geolocation.clearWatch(watchIdRef.current);
|
||||
watchIdRef.current = null;
|
||||
}
|
||||
}, [])
|
||||
}, []);
|
||||
|
||||
const start = useCallback(() => {
|
||||
if (typeof navigator === 'undefined' || !navigator.geolocation) {
|
||||
setLocationError('location.error.unsupported')
|
||||
setIsRequestingLocation(false)
|
||||
return
|
||||
if (typeof navigator === "undefined" || !navigator.geolocation) {
|
||||
setLocationError("location.error.unsupported");
|
||||
setIsRequestingLocation(false);
|
||||
return;
|
||||
}
|
||||
|
||||
clearWatch()
|
||||
setIsRequestingLocation(true)
|
||||
setLocationError(null)
|
||||
clearWatch();
|
||||
setIsRequestingLocation(true);
|
||||
setLocationError(null);
|
||||
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(position) => {
|
||||
const coords: Point = { lat: position.coords.latitude, lng: position.coords.longitude }
|
||||
setUserLocation(coords)
|
||||
setIsRequestingLocation(false)
|
||||
setLocationError(null)
|
||||
position => {
|
||||
const coords: Point = { lat: position.coords.latitude, lng: position.coords.longitude };
|
||||
setUserLocation(coords);
|
||||
setIsRequestingLocation(false);
|
||||
setLocationError(null);
|
||||
},
|
||||
(geoError) => {
|
||||
setUserLocation(null)
|
||||
setLocationError(geolocationErrorMessage(geoError))
|
||||
setIsRequestingLocation(false)
|
||||
geoError => {
|
||||
setUserLocation(null);
|
||||
setLocationError(geolocationErrorMessage(geoError));
|
||||
setIsRequestingLocation(false);
|
||||
},
|
||||
{ enableHighAccuracy: true, timeout: 10000 },
|
||||
)
|
||||
{ enableHighAccuracy: true, timeout: 10000 }
|
||||
);
|
||||
|
||||
const watchId = navigator.geolocation.watchPosition(
|
||||
(position) => {
|
||||
const coords: Point = { lat: position.coords.latitude, lng: position.coords.longitude }
|
||||
setUserLocation(coords)
|
||||
setLocationError(null)
|
||||
setIsRequestingLocation(false)
|
||||
position => {
|
||||
const coords: Point = { lat: position.coords.latitude, lng: position.coords.longitude };
|
||||
setUserLocation(coords);
|
||||
setLocationError(null);
|
||||
setIsRequestingLocation(false);
|
||||
},
|
||||
(geoError) => {
|
||||
setUserLocation(null)
|
||||
setLocationError(geolocationErrorMessage(geoError))
|
||||
setIsRequestingLocation(false)
|
||||
geoError => {
|
||||
setUserLocation(null);
|
||||
setLocationError(geolocationErrorMessage(geoError));
|
||||
setIsRequestingLocation(false);
|
||||
},
|
||||
{ enableHighAccuracy: true, maximumAge: 15000, timeout: 10000 },
|
||||
)
|
||||
{ enableHighAccuracy: true, maximumAge: 15000, timeout: 10000 }
|
||||
);
|
||||
|
||||
watchIdRef.current = watchId
|
||||
}, [clearWatch, setIsRequestingLocation, setLocationError, setUserLocation])
|
||||
watchIdRef.current = watchId;
|
||||
}, [clearWatch, setIsRequestingLocation, setLocationError, setUserLocation]);
|
||||
|
||||
useEffect(() => {
|
||||
start()
|
||||
start();
|
||||
|
||||
return () => {
|
||||
clearWatch()
|
||||
}
|
||||
}, [clearWatch, start])
|
||||
clearWatch();
|
||||
};
|
||||
}, [clearWatch, start]);
|
||||
|
||||
return {
|
||||
refresh: start,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
+18
-5
@@ -1,4 +1,4 @@
|
||||
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
|
||||
@import url("https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap");
|
||||
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@@ -58,9 +58,16 @@
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Inter', system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
||||
font-family:
|
||||
"Inter",
|
||||
system-ui,
|
||||
-apple-system,
|
||||
BlinkMacSystemFont,
|
||||
"Segoe UI",
|
||||
sans-serif;
|
||||
@apply min-h-screen bg-background text-foreground antialiased;
|
||||
background-image: radial-gradient(circle at top, hsla(var(--primary) / 0.1), transparent 45%),
|
||||
background-image:
|
||||
radial-gradient(circle at top, hsla(var(--primary) / 0.1), transparent 45%),
|
||||
radial-gradient(circle at bottom, hsla(var(--destructive) / 0.08), transparent 55%);
|
||||
}
|
||||
|
||||
@@ -77,7 +84,13 @@
|
||||
}
|
||||
|
||||
.leaflet-container {
|
||||
font-family: 'Inter', system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
||||
font-family:
|
||||
"Inter",
|
||||
system-ui,
|
||||
-apple-system,
|
||||
BlinkMacSystemFont,
|
||||
"Segoe UI",
|
||||
sans-serif;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
@@ -91,7 +104,7 @@
|
||||
|
||||
@layer utilities {
|
||||
.status-dot::after {
|
||||
content: '';
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: -0.35rem;
|
||||
border-radius: 9999px;
|
||||
|
||||
+10
-12
@@ -1,11 +1,10 @@
|
||||
import i18n from 'i18next'
|
||||
import { initReactI18next } from 'react-i18next'
|
||||
import i18n from "i18next";
|
||||
import { initReactI18next } from "react-i18next";
|
||||
|
||||
import enCommon from '@/locales/en/common.json'
|
||||
import frCommon from '@/locales/fr/common.json'
|
||||
import enCommon from "@/locales/en/common.json";
|
||||
import frCommon from "@/locales/fr/common.json";
|
||||
|
||||
const browserLanguage =
|
||||
typeof window !== 'undefined' ? window.navigator.language.split('-')[0]?.toLowerCase() : 'en'
|
||||
const browserLanguage = typeof window !== "undefined" ? window.navigator.language.split("-")[0]?.toLowerCase() : "en";
|
||||
|
||||
i18n
|
||||
.use(initReactI18next)
|
||||
@@ -14,14 +13,13 @@ i18n
|
||||
en: { common: enCommon },
|
||||
fr: { common: frCommon },
|
||||
},
|
||||
lng: browserLanguage === 'fr' ? 'fr' : 'en',
|
||||
fallbackLng: 'en',
|
||||
defaultNS: 'common',
|
||||
lng: browserLanguage === "fr" ? "fr" : "en",
|
||||
fallbackLng: "en",
|
||||
defaultNS: "common",
|
||||
interpolation: {
|
||||
escapeValue: false,
|
||||
},
|
||||
})
|
||||
.catch(() => undefined)
|
||||
|
||||
export { i18n }
|
||||
.catch(() => undefined);
|
||||
|
||||
export { i18n };
|
||||
|
||||
+40
-40
@@ -1,80 +1,80 @@
|
||||
import { type ClassValue, clsx } from 'clsx'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
import { type ClassValue, clsx } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
export type Coordinates = {
|
||||
lat: number
|
||||
lng: number
|
||||
}
|
||||
lat: number;
|
||||
lng: number;
|
||||
};
|
||||
|
||||
export function cn(...inputs: ClassValue[]): string {
|
||||
return twMerge(clsx(inputs))
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
export function formatCoordinate(value: number, locale = 'en-US'): string {
|
||||
export function formatCoordinate(value: number, locale = "en-US"): string {
|
||||
const formatter = new Intl.NumberFormat(locale, {
|
||||
minimumFractionDigits: 3,
|
||||
maximumFractionDigits: 3,
|
||||
})
|
||||
return formatter.format(value)
|
||||
});
|
||||
return formatter.format(value);
|
||||
}
|
||||
|
||||
export function formatRelativeTime(dateIso: string, locale = 'en-US'): string {
|
||||
const date = new Date(dateIso)
|
||||
const now = new Date()
|
||||
const diff = Math.max(0, now.getTime() - date.getTime())
|
||||
export function formatRelativeTime(dateIso: string, locale = "en-US"): string {
|
||||
const date = new Date(dateIso);
|
||||
const now = new Date();
|
||||
const diff = Math.max(0, now.getTime() - date.getTime());
|
||||
|
||||
const seconds = Math.floor(diff / 1000)
|
||||
const rtf = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' })
|
||||
const seconds = Math.floor(diff / 1000);
|
||||
const rtf = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });
|
||||
|
||||
if (seconds < 60) {
|
||||
return rtf.format(-seconds, 'second')
|
||||
return rtf.format(-seconds, "second");
|
||||
}
|
||||
|
||||
const minutes = Math.floor(seconds / 60)
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
if (minutes < 60) {
|
||||
return rtf.format(-minutes, 'minute')
|
||||
return rtf.format(-minutes, "minute");
|
||||
}
|
||||
|
||||
const hours = Math.floor(minutes / 60)
|
||||
const hours = Math.floor(minutes / 60);
|
||||
if (hours < 24) {
|
||||
return rtf.format(-hours, 'hour')
|
||||
return rtf.format(-hours, "hour");
|
||||
}
|
||||
|
||||
const days = Math.floor(hours / 24)
|
||||
const days = Math.floor(hours / 24);
|
||||
if (days < 7) {
|
||||
return rtf.format(-days, 'day')
|
||||
return rtf.format(-days, "day");
|
||||
}
|
||||
|
||||
const weeks = Math.floor(days / 7)
|
||||
return rtf.format(-weeks, 'week')
|
||||
const weeks = Math.floor(days / 7);
|
||||
return rtf.format(-weeks, "week");
|
||||
}
|
||||
|
||||
export function formatTimestamp(dateIso: string, locale = 'en-US'): string {
|
||||
const date = new Date(dateIso)
|
||||
export function formatTimestamp(dateIso: string, locale = "en-US"): string {
|
||||
const date = new Date(dateIso);
|
||||
return new Intl.DateTimeFormat(locale, {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: 'numeric',
|
||||
minute: '2-digit',
|
||||
}).format(date)
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
}).format(date);
|
||||
}
|
||||
|
||||
const EARTH_RADIUS_KM = 6371
|
||||
const EARTH_RADIUS_KM = 6371;
|
||||
|
||||
export function distanceInKm(a: Coordinates, b: Coordinates): number {
|
||||
const lat1 = toRadians(a.lat)
|
||||
const lat2 = toRadians(b.lat)
|
||||
const deltaLat = toRadians(b.lat - a.lat)
|
||||
const deltaLng = toRadians(b.lng - a.lng)
|
||||
const lat1 = toRadians(a.lat);
|
||||
const lat2 = toRadians(b.lat);
|
||||
const deltaLat = toRadians(b.lat - a.lat);
|
||||
const deltaLng = toRadians(b.lng - a.lng);
|
||||
|
||||
const haversine =
|
||||
Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
|
||||
Math.cos(lat1) * Math.cos(lat2) * Math.sin(deltaLng / 2) * Math.sin(deltaLng / 2)
|
||||
Math.cos(lat1) * Math.cos(lat2) * Math.sin(deltaLng / 2) * Math.sin(deltaLng / 2);
|
||||
|
||||
const c = 2 * Math.atan2(Math.sqrt(haversine), Math.sqrt(1 - haversine))
|
||||
return EARTH_RADIUS_KM * c
|
||||
const c = 2 * Math.atan2(Math.sqrt(haversine), Math.sqrt(1 - haversine));
|
||||
return EARTH_RADIUS_KM * c;
|
||||
}
|
||||
|
||||
function toRadians(value: number): number {
|
||||
return (value * Math.PI) / 180
|
||||
return (value * Math.PI) / 180;
|
||||
}
|
||||
|
||||
+11
-10
@@ -1,16 +1,17 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { I18nextProvider } from 'react-i18next'
|
||||
import 'leaflet/dist/leaflet.css'
|
||||
import { StrictMode } from "react";
|
||||
|
||||
import '@/index.css'
|
||||
import App from '@/App.tsx'
|
||||
import { i18n } from '@/lib/i18n'
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { I18nextProvider } from "react-i18next";
|
||||
import "leaflet/dist/leaflet.css";
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
import "@/index.css";
|
||||
import App from "@/App";
|
||||
import { i18n } from "@/lib/i18n";
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<App />
|
||||
</I18nextProvider>
|
||||
</StrictMode>,
|
||||
)
|
||||
</StrictMode>
|
||||
);
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
import { create } from 'zustand'
|
||||
import { create } from "zustand";
|
||||
|
||||
import type { Point } from '@/types/api'
|
||||
import type { Point } from "@/types/api";
|
||||
|
||||
type Nullable<T> = T | null
|
||||
type Nullable<T> = T | null;
|
||||
|
||||
interface AppState {
|
||||
userLocation: Nullable<Point>
|
||||
locationError: Nullable<string>
|
||||
isRequestingLocation: boolean
|
||||
setUserLocation: (location: Nullable<Point>) => void
|
||||
setLocationError: (error: Nullable<string>) => void
|
||||
setIsRequestingLocation: (isRequesting: boolean) => void
|
||||
userLocation: Nullable<Point>;
|
||||
locationError: Nullable<string>;
|
||||
isRequestingLocation: boolean;
|
||||
setUserLocation: (location: Nullable<Point>) => void;
|
||||
setLocationError: (error: Nullable<string>) => void;
|
||||
setIsRequestingLocation: (isRequesting: boolean) => void;
|
||||
}
|
||||
|
||||
export const useAppStore = create<AppState>((set) => ({
|
||||
export const useAppStore = create<AppState>(set => ({
|
||||
userLocation: null,
|
||||
locationError: null,
|
||||
isRequestingLocation: false,
|
||||
setUserLocation: (userLocation) => set({ userLocation }),
|
||||
setLocationError: (locationError) => set({ locationError }),
|
||||
setIsRequestingLocation: (isRequestingLocation) => set({ isRequestingLocation }),
|
||||
}))
|
||||
setUserLocation: userLocation => set({ userLocation }),
|
||||
setLocationError: locationError => set({ locationError }),
|
||||
setIsRequestingLocation: isRequestingLocation => set({ isRequestingLocation }),
|
||||
}));
|
||||
|
||||
+20
-20
@@ -1,36 +1,36 @@
|
||||
export type FeedStatus = 'loading' | 'idle' | 'error' | 'posting' | 'refreshing'
|
||||
export type FeedStatus = "loading" | "idle" | "error" | "posting" | "refreshing";
|
||||
|
||||
export interface Point {
|
||||
lat: number
|
||||
lng: number
|
||||
lat: number;
|
||||
lng: number;
|
||||
}
|
||||
|
||||
export interface ApiPoint {
|
||||
id: number
|
||||
signalLocation: Point
|
||||
createdAt: string
|
||||
userKey: string
|
||||
id: number;
|
||||
signalLocation: Point;
|
||||
createdAt: string;
|
||||
userKey: string;
|
||||
}
|
||||
|
||||
export interface ApiDensityCell {
|
||||
lat: number
|
||||
lng: number
|
||||
intensity: number
|
||||
lat: number;
|
||||
lng: number;
|
||||
intensity: number;
|
||||
}
|
||||
|
||||
export interface ApiSnapshot {
|
||||
clientKey?: string
|
||||
points: ApiPoint[]
|
||||
density: ApiDensityCell[]
|
||||
latestByUser: ApiPoint[]
|
||||
clientKey?: string;
|
||||
points: ApiPoint[];
|
||||
density: ApiDensityCell[];
|
||||
latestByUser: ApiPoint[];
|
||||
totals: {
|
||||
points: number
|
||||
contributors: number
|
||||
}
|
||||
updatedAt: string
|
||||
points: number;
|
||||
contributors: number;
|
||||
};
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface SnapshotEventPayload {
|
||||
type: 'snapshot'
|
||||
payload: ApiSnapshot
|
||||
type: "snapshot";
|
||||
payload: ApiSnapshot;
|
||||
}
|
||||
|
||||
Vendored
+11
-14
@@ -1,22 +1,19 @@
|
||||
declare module 'leaflet.heat' {
|
||||
import type { Layer } from 'leaflet'
|
||||
declare module "leaflet.heat" {
|
||||
import type { Layer } from "leaflet";
|
||||
|
||||
export interface HeatLayer extends Layer {
|
||||
setLatLngs(latlngs: Array<[number, number, number?]>): HeatLayer
|
||||
addLatLng(latlng: [number, number, number?]): HeatLayer
|
||||
setLatLngs(latlngs: Array<[number, number, number?]>): HeatLayer;
|
||||
addLatLng(latlng: [number, number, number?]): HeatLayer;
|
||||
}
|
||||
|
||||
export interface HeatLayerOptions {
|
||||
radius?: number
|
||||
blur?: number
|
||||
maxZoom?: number
|
||||
max?: number
|
||||
minOpacity?: number
|
||||
gradient?: Record<number, string>
|
||||
radius?: number;
|
||||
blur?: number;
|
||||
maxZoom?: number;
|
||||
max?: number;
|
||||
minOpacity?: number;
|
||||
gradient?: Record<number, string>;
|
||||
}
|
||||
|
||||
export default function heatLayer(
|
||||
latlngs: Array<[number, number, number?]>,
|
||||
options?: HeatLayerOptions,
|
||||
): HeatLayer
|
||||
export default function heatLayer(latlngs: Array<[number, number, number?]>, options?: HeatLayerOptions): HeatLayer;
|
||||
}
|
||||
|
||||
+33
-32
@@ -1,63 +1,64 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
export default {
|
||||
darkMode: ['class'],
|
||||
content: ['./index.html', './src/**/*.{ts,tsx}'],
|
||||
darkMode: ["class"],
|
||||
content: ["./index.html", "./src/**/*.{ts,tsx}"],
|
||||
theme: {
|
||||
extend: {
|
||||
backgroundImage: {
|
||||
'radial-signal': 'radial-gradient(circle at top, rgba(56,189,248,0.15), transparent 45%), radial-gradient(circle at bottom, rgba(248,113,113,0.12), transparent 55%)',
|
||||
"radial-signal":
|
||||
"radial-gradient(circle at top, rgba(56,189,248,0.15), transparent 45%), radial-gradient(circle at bottom, rgba(248,113,113,0.12), transparent 55%)",
|
||||
},
|
||||
colors: {
|
||||
border: 'hsl(var(--border))',
|
||||
input: 'hsl(var(--input))',
|
||||
ring: 'hsl(var(--ring))',
|
||||
background: 'hsl(var(--background))',
|
||||
foreground: 'hsl(var(--foreground))',
|
||||
border: "hsl(var(--border))",
|
||||
input: "hsl(var(--input))",
|
||||
ring: "hsl(var(--ring))",
|
||||
background: "hsl(var(--background))",
|
||||
foreground: "hsl(var(--foreground))",
|
||||
primary: {
|
||||
DEFAULT: 'hsl(var(--primary))',
|
||||
foreground: 'hsl(var(--primary-foreground))',
|
||||
DEFAULT: "hsl(var(--primary))",
|
||||
foreground: "hsl(var(--primary-foreground))",
|
||||
},
|
||||
secondary: {
|
||||
DEFAULT: 'hsl(var(--secondary))',
|
||||
foreground: 'hsl(var(--secondary-foreground))',
|
||||
DEFAULT: "hsl(var(--secondary))",
|
||||
foreground: "hsl(var(--secondary-foreground))",
|
||||
},
|
||||
destructive: {
|
||||
DEFAULT: 'hsl(var(--destructive))',
|
||||
foreground: 'hsl(var(--destructive-foreground))',
|
||||
DEFAULT: "hsl(var(--destructive))",
|
||||
foreground: "hsl(var(--destructive-foreground))",
|
||||
},
|
||||
muted: {
|
||||
DEFAULT: 'hsl(var(--muted))',
|
||||
foreground: 'hsl(var(--muted-foreground))',
|
||||
DEFAULT: "hsl(var(--muted))",
|
||||
foreground: "hsl(var(--muted-foreground))",
|
||||
},
|
||||
accent: {
|
||||
DEFAULT: 'hsl(var(--accent))',
|
||||
foreground: 'hsl(var(--accent-foreground))',
|
||||
DEFAULT: "hsl(var(--accent))",
|
||||
foreground: "hsl(var(--accent-foreground))",
|
||||
},
|
||||
popover: {
|
||||
DEFAULT: 'hsl(var(--popover))',
|
||||
foreground: 'hsl(var(--popover-foreground))',
|
||||
DEFAULT: "hsl(var(--popover))",
|
||||
foreground: "hsl(var(--popover-foreground))",
|
||||
},
|
||||
card: {
|
||||
DEFAULT: 'hsl(var(--card))',
|
||||
foreground: 'hsl(var(--card-foreground))',
|
||||
DEFAULT: "hsl(var(--card))",
|
||||
foreground: "hsl(var(--card-foreground))",
|
||||
},
|
||||
},
|
||||
borderRadius: {
|
||||
lg: 'var(--radius)',
|
||||
md: 'calc(var(--radius) - 2px)',
|
||||
sm: 'calc(var(--radius) - 4px)',
|
||||
lg: "var(--radius)",
|
||||
md: "calc(var(--radius) - 2px)",
|
||||
sm: "calc(var(--radius) - 4px)",
|
||||
},
|
||||
keyframes: {
|
||||
'status-pulse': {
|
||||
'0%': { transform: 'scale(0.7)', opacity: '0.6' },
|
||||
'70%': { transform: 'scale(1.4)', opacity: '0' },
|
||||
'100%': { transform: 'scale(0.7)', opacity: '0' },
|
||||
"status-pulse": {
|
||||
"0%": { transform: "scale(0.7)", opacity: "0.6" },
|
||||
"70%": { transform: "scale(1.4)", opacity: "0" },
|
||||
"100%": { transform: "scale(0.7)", opacity: "0" },
|
||||
},
|
||||
},
|
||||
animation: {
|
||||
'status-pulse': 'status-pulse 2.4s ease-out infinite',
|
||||
"status-pulse": "status-pulse 2.4s ease-out infinite",
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [require('tailwindcss-animate')],
|
||||
}
|
||||
plugins: [require("tailwindcss-animate")],
|
||||
};
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
"references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }]
|
||||
}
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import { fileURLToPath, URL } from 'node:url'
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import { fileURLToPath, URL } from "node:url";
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
react({
|
||||
babel: {
|
||||
plugins: [['babel-plugin-react-compiler']],
|
||||
plugins: [["babel-plugin-react-compiler"]],
|
||||
},
|
||||
}),
|
||||
],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||
"@": fileURLToPath(new URL("./src", import.meta.url)),
|
||||
},
|
||||
},
|
||||
})
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user