Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Copy the map image to clipboard #428

Open
wants to merge 21 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
## Changes in version 1.4.0 (in development)

### New Features

* Users can now copy snapshots of a map into the clipboard by clicking a new
camera icon on a map's action bar. (#290)

### Other changes

* Updated dependencies, development dependencies and updated TypeScript code base accordingly.
Expand Down Expand Up @@ -35,15 +40,11 @@

* Updated language translations (German and Swedish) for `Add Statistics`
and `Style Place`.

## Changes in version 1.3.0

### New Features

* Users can now copy snapshots of a time-series charts and statistics
into the clipboard by clicking a new camera icon on a chart's action bar.
(#290)

* It is now possible to change the color and opacity of user places
and hence associated time-series and statistic charts. (#97, #216)

Expand All @@ -69,6 +70,7 @@
* Now recognising new custom color maps from xcube server, for details
refer to https://github.com/xcube-dev/xcube/issues/1046. (#392)


### Enhancements

* Avoiding confusion regarding variable comparison.
Expand Down
5 changes: 5 additions & 0 deletions src/components/MapInteractionsBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ import i18n from "@/i18n";
import { MapInteraction } from "@/states/controlState";
import { WithLocale } from "@/util/lang";
import { commonStyles } from "@/components/common-styles";
import { MessageType } from "@/states/messageLogState";
import MapSnapshotButton from "./MapSnapshotButton";

const StyledFromControl = styled(FormControl)(({ theme }) => ({
marginTop: theme.spacing(2),
Expand All @@ -49,11 +51,13 @@ const StyledFromControl = styled(FormControl)(({ theme }) => ({
interface MapInteractionsBarProps extends WithLocale {
mapInteraction: MapInteraction;
setMapInteraction: (interaction: MapInteraction) => void;
postMessage: (messageType: MessageType, messageText: string | Error) => void;
}

export default function MapInteractionsBar({
mapInteraction,
setMapInteraction,
postMessage
}: MapInteractionsBarProps) {
function handleChange(
_event: React.MouseEvent<HTMLElement>,
Expand Down Expand Up @@ -124,6 +128,7 @@ export default function MapInteractionsBar({
<FileUploadIcon />
</Tooltip>
</ToggleButton>
<MapSnapshotButton mapRef={"map"} postMessage={postMessage} fontSize="medium" isToggle={true} />
</ToggleButtonGroup>
</StyledFromControl>
);
Expand Down
72 changes: 72 additions & 0 deletions src/components/MapSnapshotButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019-2024 by the xcube development team and contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

import { RefObject } from "react";
import { default as OlMap } from "ol/Map";
import SnapshotButton from "./SnapshotButton";
import { MAP_OBJECTS } from "@/states/controlState";
import { MessageType } from "@/states/messageLogState";
import { WithLocale } from "@/util/lang";

interface MapSnapshotButtonProps extends WithLocale {
mapRef: string;
postMessage: (messageType: MessageType, messageText: string | Error) => void;
fontSize?: "small" | "inherit" | "medium" | "large";
isToggle?: boolean;
}

export default function MapSnapshotButton({
mapRef,
postMessage,
fontSize = "inherit",
isToggle = false,
}: MapSnapshotButtonProps) {
const getMapElement = (): RefObject<HTMLDivElement | null> => {
const targetElement = MAP_OBJECTS[mapRef]
? (MAP_OBJECTS[mapRef] as OlMap).getTargetElement()
: null;
return { current: targetElement as HTMLDivElement | null };
};

const getHiddenElements = (element: HTMLDivElement | null): HTMLElement[] => {
if (!element) return [];
return [
element.querySelector(".ol-unselectable.ol-control.MuiBox-root.css-0"),
element.querySelector(".ol-zoom.ol-unselectable.ol-control"),
].filter(Boolean) as HTMLElement[];
};

const elementRef = getMapElement();
const hiddenElements = getHiddenElements(elementRef.current);

return (
<SnapshotButton
elementRef={elementRef}
hiddenElements={hiddenElements}
postMessage={postMessage}
fontSize={fontSize}
isToggle={isToggle}
/>
);
}
62 changes: 26 additions & 36 deletions src/components/SnapshotButton.tsx
Original file line number Diff line number Diff line change
@@ -1,45 +1,28 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019-2024 by the xcube development team and contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

import { RefObject } from "react";
import CameraAltIcon from "@mui/icons-material/CameraAlt";

import i18n from "@/i18n";
import { WithLocale } from "@/util/lang";
import { MessageType } from "@/states/messageLogState";
import { exportElement } from "@/util/export";
import ToolButton from "@/components/ToolButton";

interface SnapshotButtonProps extends WithLocale {
elementRef: RefObject<HTMLDivElement | null>;
elementRef?: RefObject<HTMLDivElement | null>;
postMessage: (messageType: MessageType, messageText: string | Error) => void;
fontSize?: "small" | "inherit" | "medium" | "large";
isToggle?: boolean;
hiddenElements?: HTMLElement[];
}

export default function SnapshotButton({
elementRef,
postMessage,
fontSize = "inherit",
isToggle = false,
hiddenElements = [],
}: SnapshotButtonProps) {
const pixelRatio = 1;

const handleExportSuccess = () => {
postMessage("success", i18n.get("Snapshot copied to clipboard"));
};
Expand All @@ -50,24 +33,31 @@ export default function SnapshotButton({
postMessage("error", i18n.get(message));
};

const handleButtonClick = () => {
if (elementRef.current) {
exportElement(elementRef.current!, {
format: "png",
width: 2000,
handleSuccess: handleExportSuccess,
handleError: handleExportError,
});
const handleButtonClick = async () => {
if (elementRef?.current) {
try {
exportElement(elementRef.current, {
format: "png",
width: 2000,
handleSuccess: handleExportSuccess,
handleError: handleExportError,
pixelRatio: pixelRatio,
hiddenElements
});
} catch (error) {
handleExportError(error);
}
} else {
handleExportError(new Error("missing element reference"));
}
};

return (
<ToolButton
tooltipText={i18n.get("Copy snapshot of chart to clipboard")}
tooltipText={i18n.get("Copy snapshot to clipboard")}
onClick={handleButtonClick}
icon={<CameraAltIcon fontSize="inherit" />}
toggle={isToggle}
icon={<CameraAltIcon fontSize={fontSize} />}
/>
);
}
13 changes: 11 additions & 2 deletions src/components/ol/layer/Tile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ let trace: (message?: string, ...optionalParams: unknown[]) => void;
if (import.meta.env.DEV && DEBUG) {
trace = console.debug;
} else {
trace = () => {};
trace = () => { };
}

// noinspection JSUnusedGlobalSymbols
Expand All @@ -66,12 +66,21 @@ export function OSMBlackAndWhite(): JSX.Element {

interface TileProps
extends MapComponentProps,
OlTileLayerOptions<OlTileSource> {}
OlTileLayerOptions<OlTileSource> { }

export class Tile extends MapComponent<OlTileLayer<OlTileSource>, TileProps> {
addMapObject(map: OlMap): OlTileLayer<OlTileSource> {
const layer = new OlTileLayer(this.props);
layer.set("id", this.props.id);

//The below lines of code of setting source as "Anonymous" is for allowing
//to copy image on clipboard as we have custom tiles. If the source is
//not set to anonymous it will give the CORS error and image will not be copied.
//Source link: https://openlayers.org/en/latest/examples/wms-custom-proj.html
const source = layer.getSource() as OlTileSource & { crossOrigin?: string };
if (source && 'crossOrigin' in source) {
source.crossOrigin = "Anonymous";
}
Comment on lines +80 to +83
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a comment that explains why this is needed. Add a link to the source too.

map.getLayers().push(layer);
return layer;
}
Expand Down
2 changes: 2 additions & 0 deletions src/connected/MapInteractionsBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { connect } from "react-redux";
import _MapInteractionsBar from "@/components/MapInteractionsBar";
import { AppState } from "@/states/appState";
import { setMapInteraction } from "@/actions/controlActions";
import { postMessage } from "@/actions/messageLogActions";

const mapStateToProps = (state: AppState) => {
return {
Expand All @@ -36,6 +37,7 @@ const mapStateToProps = (state: AppState) => {

const mapDispatchToProps = {
setMapInteraction,
postMessage,
};

const MapInteractionsBar = connect(
Expand Down
6 changes: 3 additions & 3 deletions src/resources/lang.json
Original file line number Diff line number Diff line change
Expand Up @@ -466,9 +466,9 @@
"se": "Hjälp"
},
{
"en": "Copy snapshot of chart to clipboard",
"de": "Schnappschuss des Diagramms in die Zwischenablage kopieren",
"se": "Kopiera ögonblicksbild av diagrammet till urklipp"
"en": "Copy snapshot to clipboard",
"de": "Schnappschuss in die Zwischenablage kopieren",
"se": "Kopiera ögonblicksbild till urklipp"
},
{
"en": "Snapshot copied to clipboard",
Expand Down
5 changes: 5 additions & 0 deletions src/selectors/controlSelectors.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -833,6 +833,11 @@ function getOlXYZSource(
// level at minZoom when zooming out!
// minZoom: tileLevelMin,
maxZoom: tileLevelMax,
crossOrigin: "Anonymous",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment why this is needed.

//crossOrigin is set to "Anonymous", for allowing
//to copy image on clipboard as we have custom tiles. If the source is
//not set to anonymous it will give the CORS error and image will not be copied.
//Source link: https://openlayers.org/en/latest/examples/wms-custom-proj.html
});
}

Expand Down
3 changes: 2 additions & 1 deletion src/states/controlState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ export type MapInteraction =
| "Point"
| "Polygon"
| "Circle"
| "Geometry";
| "Geometry"
| "Export";

export type ViewMode = "text" | "list" | "code" | "python";

Expand Down
Loading
Loading