import { Meta, StoryFn } from "@storybook/react"; import { AppComponent } from "../StoryUtil"; import { useContext, useEffect, useState } from "react"; import { LolOpenLayersMap } from "../../map/LolOpenLayersMap"; import { Circle, Fill, Style } from "ol/style"; import Stroke from "ol/style/Stroke"; import Text from "ol/style/Text"; import { LuiIcon } from "@linzjs/lui"; import { LolOpenLayersVectorLayerDef } from "../../layerDefinition/LolOpenLayersVectorLayerDef"; import { LolOpenLayersFeatureSourceDef } from "../../sourceDefinition/LolOpenLayersFeatureSourceDef"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { FeatureLike } from "ol/Feature"; import { Feature } from "ol"; import { Geometry, Point } from "ol/geom"; import { LayerType, LolOpenLayersLayerDef, } from "../../layerDefinition/LolOpenLayersLayerDef"; import { SourceType } from "../../sourceDefinition/LolOpenLayersSourceDef"; import { ApiKeyEntry, basemap, basinReserveView, fourLineFeatures, fourLineFeaturesEPSG4326, labelledMarksLayer, MapWithLinzAerialLayer, MapWithLinzBasemapLayer, oamaruView, testLineVectorQueryLayer, tunnelLineFeature, tunnelLineFeatureEpsg4326, UNDERLYING_MARKS_SOURCE_URL, underlyingParcelsLayer, } from "./Common"; import { AutoLabelPlacementType, LolOpenLayersMapContext, LolOpenLayersMapContextProvider, } from "../../context/LolOpenLayersMapContext"; import CircleStyle from "ol/style/Circle"; import { LolOpenLayersMVTSourceDef } from "../../sourceDefinition/LolOpenLayersMVTSourceDef"; import { LolOpenLayersVectorTileLayerDef } from "../../layerDefinition/LolOpenLayersVectorTileLayerDef"; import { LolOpenLayersTileLayerDef } from "../../layerDefinition/LolOpenLayersTileLayerDef"; import { LolOpenLayersMapLibreSourceDef } from "../../sourceDefinition/LolOpenLayersMapLibreSourceDef"; import { PlacementParams } from "../../map/placement/PlacementParams"; import { clipLineToOblong } from "../../utils/Measure"; import { useLolOpenLayersPlacementEvent } from "../../events/LolOpenLayersPlacementEvent"; import { waitFor, within } from "@storybook/testing-library"; import { expect } from "@storybook/jest"; import logOpenlayersMap from "../../../src/utils/Log"; import proj4 from "proj4"; import { register } from "ol/proj/proj4"; // eslint-disable-next-line no-unused-vars export default { title: "Openlayers Map Wrapper/LolOpenLayersMap/Static", component: LolOpenLayersMap, docs: { inlineStories: false }, } as Meta; const ShowMapWithoutDefaultZoomButtonStory: StoryFn< typeof LolOpenLayersMap > = () => (

Base map without default zoom button

); export const ShowMapWithoutDefaultZoomButton = ShowMapWithoutDefaultZoomButtonStory.bind({}); const ShowMapStory: StoryFn = () => (

Base map

); // eslint-disable-next-line no-unused-vars export const ShowMap = ShowMapStory.bind({}); interface ShowLinzBasemapMapProps { excludeLayers?: string[]; layers?: LolOpenLayersLayerDef[]; } const ShowLinzBasemapMapStory: StoryFn = ({ excludeLayers, layers = [], }: ShowLinzBasemapMapProps) => { const [apiKey, setApiKey] = useState(null); return (

Linz basemap (using MapLibre layer)

{!apiKey &&

Enter key to load map

} {apiKey && ( )}
); }; // eslint-disable-next-line no-unused-vars export const ShowLinzBaseMap = ShowLinzBasemapMapStory.bind({}); ShowLinzBaseMap.args = { layers: [], }; export const ShowLinzBaseMapWithExclude = ShowLinzBasemapMapStory.bind({}); ShowLinzBaseMapWithExclude.args = { excludeLayers: ["Parcels-Ln", "All-Road-Labels"], }; const ShowLinzAerialStory: StoryFn = () => { const [apiKey, setApiKey] = useState(null); return (

Linz aerial imagery (using WMTS source)

{!apiKey &&

Enter key to load map

} {apiKey && }
); }; // eslint-disable-next-line no-unused-vars export const ShowLinzAerial = ShowLinzAerialStory.bind({}); const ShowMapWithParcelsStory: StoryFn = () => { return (

Map with underlying parcels (tile layer)

); }; // eslint-disable-next-line no-unused-vars export const ShowMapWithParcels = ShowMapWithParcelsStory.bind({}); const ShowMapWithVectorsStory: StoryFn = () => { return (

Map with (static) vector layer

) => { return new Style({ stroke: new Stroke({ color: "#1122AA", width: 2, }), }); }, source: { type: SourceType.FEATURES, data: [tunnelLineFeature], maxZoom: 28, } as LolOpenLayersFeatureSourceDef, visible: true, inInitialZoom: true, } as LolOpenLayersVectorLayerDef, ]} useLoadingIndicator={true} />
); }; export const ShowMapWithVectors = ShowMapWithVectorsStory.bind({}); const ShowMapWithAlternateProjectionStory: StoryFn< typeof LolOpenLayersMap > = () => { return (

Map with (static) vector layer, using EPSG:4326 (WGS-84) coords

) => { return new Style({ stroke: new Stroke({ color: "#1122AA", width: 2, }), }); }, source: { type: SourceType.FEATURES, data: [tunnelLineFeatureEpsg4326], projection: "EPSG:4326", maxZoom: 28, } as LolOpenLayersFeatureSourceDef, visible: true, inInitialZoom: true, } as LolOpenLayersVectorLayerDef, ]} useLoadingIndicator={true} />
); }; export const ShowMapWithAlternateProjection = ShowMapWithAlternateProjectionStory.bind({}); const pointTextStyle = (f: FeatureLike) => new Style({ text: new Text({ text: f.get("name"), font: 'bold 14px "Open Sans"', stroke: new Stroke({ color: "#1122AA" }), backgroundFill: new Fill({ color: "#CCCCCC" }), backgroundStroke: new Stroke({ color: "#1122AA" }), }), }); const ShowMapWithVectorsQueryStory: StoryFn = () => { const queryClient = new QueryClient(); return (

Map with vector/point from query (delayed load)

); }; export const ShowMapWithVectorsQuery = ShowMapWithVectorsQueryStory.bind({}); const ShowMapWithFilteredPointDataStory: StoryFn< typeof LolOpenLayersMap > = () => { const queryClient = new QueryClient(); return (

Map with filtered point from query

features .filter((f) => f.id !== 2) .map((f) => ({ ...f, name: `${f.name} (id: ${f.id})` })), source: { type: SourceType.FEATURES, maxZoom: 29, data: [ { id: 1, name: "First point", shape: { geometry: { type: "Point", coordinates: [14.785, -41.30248], }, }, }, { id: 2, name: "Second point (hidden!)", shape: { geometry: { type: "Point", coordinates: [14.79, -41.30248], }, }, }, ], } as LolOpenLayersFeatureSourceDef, visible: true, } as LolOpenLayersVectorLayerDef, ]} useLoadingIndicator={true} />
); }; export const ShowMapWithFilteredPointData = ShowMapWithFilteredPointDataStory.bind({}); const ShowMapWithLabeledMarksZoomedStory: StoryFn< typeof LolOpenLayersMap > = () => { return (

Map with labelled marks

); }; export const ShowMapWithLabeledMarksZoomed = ShowMapWithLabeledMarksZoomedStory.bind({}); const ShowMapWithLabeledMarkStyleZoomedStory: StoryFn< typeof LolOpenLayersMap > = () => { return (

Map with labelled marks (using labelStyle)

new Style({ image: new CircleStyle({ radius: 2, fill: new Fill({ color: "#ff0000" }), stroke: new Stroke({ color: "#ff0000", width: 2, }), }), }), labelStyle: (feature: FeatureLike) => { return new Style({ text: new Text({ text: feature.get("name"), }), }); }, declutterLabels: true, source: { type: SourceType.MVT, url: UNDERLYING_MARKS_SOURCE_URL, } as LolOpenLayersMVTSourceDef, visible: true, } as LolOpenLayersVectorTileLayerDef, ]} useLoadingIndicator={true} />
); }; export const ShowMapWithLabeledMarkStyleZoomed = ShowMapWithLabeledMarkStyleZoomedStory.bind({}); const ShowMapWithLabeledVectorsStory: StoryFn = () => { return (

Map with labelled vectors

) => { return new Style({ stroke: new Stroke({ color: "#1122AA", width: 2, }), }); }, labelStyle: (feature: FeatureLike) => new Style({ text: new Text({ text: feature.get("label"), font: 'bold 14px "Open Sans"', stroke: new Stroke({ color: "#1122AA" }), backgroundFill: new Fill({ color: "#CCCCCC" }), backgroundStroke: new Stroke({ color: "#1122AA" }), }), }), source: { type: SourceType.FEATURES, data: [{ ...tunnelLineFeature, label: "A line" }], maxZoom: 28, } as LolOpenLayersFeatureSourceDef, visible: true, } as LolOpenLayersVectorLayerDef, ]} useLoadingIndicator={true} />
); }; export const ShowMapWithLabeledVectors = ShowMapWithLabeledVectorsStory.bind( {} ); const CustomLoadingMapInner = () => { const mapContext = useContext(LolOpenLayersMapContext); return ( <>

Loading status: {mapContext.loading ? "Loading..." : "Loaded"}

); }; const CustomLoadingFeatureStory: StoryFn = () => { return (

Zoom in and out to trigger tile loads and see the loading status

); }; // eslint-disable-next-line no-unused-vars export const CustomLoadingIndicator = CustomLoadingFeatureStory.bind({}); const MapWithOverlayInner = () => { const mapContext = useContext(LolOpenLayersMapContext); const [overlaySet, setOverlaySet] = useState(false); useEffect(() => { if (overlaySet) return; const overlay = mapContext.getOverlayRef()?.current; if (overlay) { overlay.setPosition(basinReserveView.center); const el = overlay.getElement()!!; el.innerText = "Overlay text"; el.style.fontSize = "20pt"; el.style.color = "red"; el.style.background = "border-box green"; setOverlaySet(true); } }, [mapContext, overlaySet]); return ( ); }; const OverlayStory: StoryFn = () => (

Base map

); // eslint-disable-next-line no-unused-vars export const Overlay = OverlayStory.bind({}); const LoadsUnderlyingAfterZoomStory: StoryFn = () => { const [apiKey, setApiKey] = useState(null); const queryClient = new QueryClient(); return (

Load underlying data only after zoom to content

{!apiKey &&

Enter key to load map

} {apiKey && ( )}
); }; export const LoadsUnderlyingAfterZoom = LoadsUnderlyingAfterZoomStory.bind({}); const ShowMapWithLockedStatus: StoryFn = () => (

Base map without default zoom button

Locked by user
); export const ShowMapWithLockedStatusStory = ShowMapWithLockedStatus.bind({}); const labelledLineLayer = ( declutter: boolean = false, clipFeatures: boolean = false, projectEPSG4326: boolean = false ) => ({ type: LayerType.VECTOR, name: "test_line", minZoom: 0, maxZoom: 28, zIndex: 500, inInitialZoom: true, declutter, clipFeatures, style: (_: Feature) => { return new Style({ stroke: new Stroke({ color: "#1122AA", width: 2, }), }); }, labelStyle: (feature: Feature) => { return new Style({ text: new Text({ text: feature.get("label"), font: 'bold 14px "Open Sans"', stroke: new Stroke({ color: "#1122AA" }), backgroundFill: new Fill({ color: "#CCCCCC" }), backgroundStroke: new Stroke({ color: "#1122AA" }), }), }); }, source: { type: SourceType.FEATURES, data: projectEPSG4326 ? fourLineFeaturesEPSG4326 : fourLineFeatures, projection: projectEPSG4326 && "EPSG:4326", maxZoom: 28, } as LolOpenLayersFeatureSourceDef, visible: true, }) as LolOpenLayersVectorLayerDef; proj4.defs( "EPSG:1", "+proj=longlat +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +no_defs +pm=160" ); register(proj4); const MapWithLabelPlacement = ({ placementType, }: { placementType?: AutoLabelPlacementType; }) => { const mapContext = useContext(LolOpenLayersMapContext); const [labelPlacementLoadingState, setLabelPlacementLoadingState] = useState( "LABEL PLACEMENT LOADING..." ); useLolOpenLayersPlacementEvent((placementParams: PlacementParams) => { // simulate label placement taking 1s setTimeout(() => { // A simple label placement for labels on a line. // This clips the line to the viewport and calculates the difference // between the centre of the clipped and original lines, which gives // us the offset to make the label slide into visibility const linePlacements = Object.fromEntries( fourLineFeatures.map((lineFeature) => { let hideFeature = [ lineFeature.id.toString(), { callout: false, hide: true, offsetPixels: null, rotateRads: null, }, ]; // these are in degrees const lineCoords = lineFeature.shape.geometry.coordinates; // placement params come in as coords, so we convert to degrees const [swX, swY] = proj4("EPSG:1", "EPSG:4326", [ placementParams.swX, placementParams.swY, ]); const [neX, neY] = proj4("EPSG:1", "EPSG:4326", [ placementParams.neX, placementParams.neY, ]); // then we clip the line to the bounds const clippedCoords = clipLineToOblong( lineCoords, swX, neX, swY, neY ); // fully clipped lines should be hidden if (clippedCoords === null) { return hideFeature; } const labelWidthNominal = 40; // calculate how degrees per pixel const widthDegreesPixel = (neX - swX) / placementParams.widthPx; const heightDegreesPixel = (neY - swY) / placementParams.heightPx; // calculate original line length in pixels const lineCoordsPixels = lineCoords.map((c) => [ (c[0] - swX) / widthDegreesPixel, (c[1] - swY) / heightDegreesPixel, ]); // calculate clipped line length in pixels const clippedCoordsPixels = clippedCoords.map((c) => [ (c[0] - swX) / widthDegreesPixel, (c[1] - swY) / heightDegreesPixel, ]); // determine if the clipped line is long enough to fit label const lineLengthSquared = Math.pow(clippedCoordsPixels[1][0] - clippedCoordsPixels[0][0], 2) + Math.pow(clippedCoordsPixels[1][1] - clippedCoordsPixels[0][1], 2); if (lineLengthSquared < labelWidthNominal * labelWidthNominal) { // Line is too short return hideFeature; } // calc the centre points in px of the original and clipped lines const lineCentre = [ (lineCoordsPixels[0][0] + lineCoordsPixels[1][0]) / 2.0, (lineCoordsPixels[0][1] + lineCoordsPixels[1][1]) / 2.0, ]; const clippedCentre = [ (clippedCoordsPixels[0][0] + clippedCoordsPixels[1][0]) / 2.0, (clippedCoordsPixels[0][1] + clippedCoordsPixels[1][1]) / 2.0, ]; // calculate the offset in px by getting the difference const offset = clippedCentre.map( (clipped, index) => clipped - lineCentre[index] ); // calculate the width and height of line in px const dx = lineCoordsPixels[1][0] - lineCoordsPixels[0][0]; const dy = lineCoordsPixels[1][1] - lineCoordsPixels[0][1]; // calculate the angle of the line const rotate = dx > 0 ? Math.atan2(dy, dx) : Math.atan2(-dy, -dx); // We want the offset along the line, which is the rotated // offset in x and zero in y const alongLineOffset = [ offset[0] * Math.cos(rotate) + offset[1] * Math.sin(rotate), 0, ]; const labelCenterPoint = placementType === AutoLabelPlacementType.ABSOLUTE ? new Point( proj4("EPSG:4326", "EPSG:3857", [ clippedCentre[0] * widthDegreesPixel + swX, clippedCentre[1] * heightDegreesPixel + swY, ]) ) : undefined; return [ lineFeature.id.toString(), { callout: false, hide: false, offsetPixels: alongLineOffset, rotateRads: placementType === AutoLabelPlacementType.OFFSET ? rotate : -rotate, labelCenterPoint, }, ]; }) ); mapContext.setPlacements({ test_line: linePlacements }); setLabelPlacementLoadingState("LABEL PLACEMENT COMPLETE"); }, 1000); }); return (
{labelPlacementLoadingState}
); }; const ShowMapWithLabeledVectorAutoPlacementStory: StoryFn< typeof LolOpenLayersMap > = () => { return (

Map with automatic label placement

); }; export const ShowMapWithLabeledVectorAutoPlacement = ShowMapWithLabeledVectorAutoPlacementStory.bind({}); ShowMapWithLabeledVectorAutoPlacement.play = async ({ canvasElement }) => { const canvas = within(canvasElement); await canvas.findByText("LABEL PLACEMENT LOADING..."); await waitFor( () => { expect( canvas.queryByText("LABEL PLACEMENT COMPLETE") ).toBeInTheDocument(); }, { timeout: 15000 } ); }; const AutoLabelPlacementAbsoluteStory: StoryFn< typeof LolOpenLayersMap > = () => { return (

Map with automatic label placement

); }; export const AutoLabelPlacementAbsolutePositioning = AutoLabelPlacementAbsoluteStory.bind({}); AutoLabelPlacementAbsolutePositioning.play = async ({ canvasElement }) => { const canvas = within(canvasElement); await canvas.findByText("LABEL PLACEMENT LOADING..."); await waitFor( () => { expect( canvas.queryByText("LABEL PLACEMENT COMPLETE") ).toBeInTheDocument(); }, { timeout: 15000 } ); }; const ShowMapWithCentredClippedLabelsStory: StoryFn< typeof LolOpenLayersMap > = () => { logOpenlayersMap.setLevel(logOpenlayersMap.levels.DEBUG); return (

Map with labels centred, clipped and decluttered

); }; const closeMarksLayer = { type: LayerType.VECTOR, name: "close_marks", minZoom: 0, maxZoom: 30, zIndex: 500, inInitialZoom: true, declutter: false, clipFeatures: false, style: (f: Feature) => new Style({ image: new Circle({ fill: new Fill({ color: "#000" }), radius: 5, }), text: new Text({ text: f.get("name"), font: 'bold 14px "Open Sans"', offsetX: 20, }), }), source: { type: SourceType.FEATURES, data: [ { id: 1, name: "IT 1", shape: { geometry: { coordinates: [174.78176963, -41.30076912], type: "Point", }, }, }, { id: 2, name: "IT 2", shape: { geometry: { coordinates: [174.78176993, -41.3007694], type: "Point", }, }, }, ], projection: "EPSG:4326", maxZoom: 30, } as LolOpenLayersFeatureSourceDef, visible: true, } as LolOpenLayersVectorLayerDef; const closeMarksObsLayer = { type: LayerType.VECTOR, name: "close_marks_line", minZoom: 0, maxZoom: 30, zIndex: 300, inInitialZoom: true, declutter: false, clipFeatures: false, style: (_f: Feature) => { return new Style({ stroke: new Stroke({ color: "#1122AA", width: 2, }), }); }, labelStyle: (feature: FeatureLike) => new Style({ text: new Text({ text: feature.get("label"), font: 'bold 14px "Open Sans"', }), }), source: { type: SourceType.FEATURES, data: [ { id: 1000, label: "140°50'\n0.04", shape: { geometry: { coordinates: [ [174.78176963, -41.30076912], [174.78176993, -41.3007694], ], type: "LineString", }, }, }, ], projection: "EPSG:4326", maxZoom: 30, } as LolOpenLayersFeatureSourceDef, visible: true, } as LolOpenLayersVectorLayerDef; export const ShowMapWithCentredClippedLabels = ShowMapWithCentredClippedLabelsStory.bind({}); const CloseMarksVisibleStory: StoryFn = () => { logOpenlayersMap.setLevel(logOpenlayersMap.levels.DEBUG); return (

Map with marks very close together

); }; export const CloseMarksVisible = CloseMarksVisibleStory.bind({});