Certainly! I've reviewed your code and have some suggestions to improve it. I'll go through each of your code snippets, provide the improved version, and explain the changes made.
1. PlaceMark.ts
Issues and Improvements:
-
Interface Definition: The Properties interface extends PlaceMarkProperties and adds get and set methods. However, TypeScript already understands the properties object in ymaps.Placemark. We can simplify this by directly using ymaps.GeoObject.
-
Unnecessary Casting: Casting as unknown as string is unnecessary if we type the methods correctly.
-
Redundant Properties Object: Instead of creating a new properties object with get and set, we can directly use the properties of ymaps.Placemark.
Improved Code:
import { Coords, PlaceMarkProperties } from "../types.ts";
export class PlaceMark {
placemark: ymaps.Placemark;
coords: Coords;
options: ymaps.IPlacemarkOptions;
constructor(
coords: Coords,
properties: PlaceMarkProperties = {},
options: ymaps.IPlacemarkOptions = {}
) {
this.coords = coords;
this.options = options;
this.placemark = new window.ymaps.Placemark(coords, properties, options);
}
getProperty(property: string): any {
return this.placemark.properties.get(property);
}
setProperty(property: string, value: any): void {
this.placemark.properties.set(property, value);
}
addEventListener(eventName: string, callback: () => void): void {
this.placemark.events.add(eventName, callback);
}
}
Explanation:
- Removed the custom
Properties interface and methods.
- Added
getProperty and setProperty methods to directly interact with placemark.properties.
- Simplified the constructor by directly assigning
coords, options, and initializing placemark.
2. MapService.ts
Issues and Improvements:
- While the code is generally fine, exporting an instance at the bottom can be problematic for testing and scalability.
Improved Code:
import { Coords, PlaceMarkProperties } from "../types.ts";
import { PlaceMark } from "./PlaceMark.ts";
import { SatelliteMap } from "./SatelliteMap.ts";
export class MapService {
createMap(element: HTMLElement, options: { center?: Coords; zoom: number }) {
return new SatelliteMap(element, options);
}
createPlacemark(
coords: Coords,
properties: PlaceMarkProperties = {},
options: ymaps.IPlacemarkOptions = {}
) {
return new PlaceMark(coords, properties, options);
}
}
const mapService = new MapService();
export default mapService;
Explanation:
- Exported the
MapService class and then created an instance to export.
- This allows others to create instances of
MapService if needed, improving testability.
3. SatelliteMap.ts
Issues and Improvements:
- Consistency in method names (e.g.,
PlaceMark vs. Placemark).
- Could improve method typings.
Improved Code:
import { Coords, MapEvent } from "../types.ts";
import { PlaceMark } from "./PlaceMark.ts";
export interface SatelliteMapOptions {
center?: Coords;
zoom: number;
}
export class SatelliteMap {
yMap: ymaps.Map;
constructor(container: HTMLElement, options: SatelliteMapOptions) {
this.yMap = new window.ymaps.Map(container, options);
}
addEventListener(type: string, callback: (event: MapEvent) => void): void {
this.yMap.events.add(type, callback);
}
addPlacemark(placemark: PlaceMark): void {
this.yMap.geoObjects.add(placemark.placemark);
}
removeAllPlacemarks(): void {
this.yMap.geoObjects.removeAll();
}
removePlacemark(placemark: PlaceMark): void {
this.yMap.geoObjects.remove(placemark.placemark);
}
destroy(): void {
this.yMap.destroy();
}
}
Explanation:
- Renamed methods to
addPlacemark and removePlacemark for consistency.
- Added return types to methods for clarity.
4. MapContext.tsx
Issues and Improvements:
- State Management: Using
currentMark as a useRef may not be necessary. We can manage placemarks within the state.
- Event Listeners: Adding event listeners directly inside
useEffect without proper cleanup can cause memory leaks.
- Dependency Arrays: The dependency arrays in
useEffect may be missing dependencies.
Improved Code:
import {
createContext,
FC,
ReactNode,
useContext,
useEffect,
useState,
} from "react";
import { Coords, MapEvent } from "../types.ts";
import { PlaceMark } from "../services/PlaceMark.ts";
import { SatelliteMap } from "../services/SatelliteMap.ts";
import mapService from "../services/MapService.ts";
interface MapProviderProps {
children: ReactNode;
}
interface MapContextType {
map: SatelliteMap | null;
coords: Coords;
setCoords: (coords: Coords) => void;
placemarks: PlaceMark[];
addPlacemark: (placemark: PlaceMark) => void;
editingPlacemark: PlaceMark | null;
setEditingPlacemark: (placemark: PlaceMark | null) => void;
}
const MapContext = createContext<MapContextType | null>(null);
export const MapProvider: FC<MapProviderProps> = ({ children }) => {
const [map, setMap] = useState<SatelliteMap | null>(null);
const [coords, setCoords] = useState<Coords>([0, 0]);
const [placemarks, setPlacemarks] = useState<PlaceMark[]>([]);
const [editingPlacemark, setEditingPlacemark] = useState<PlaceMark | null>(
null
);
const addPlacemark = (placemark: PlaceMark) => {
placemark.addEventListener("click", () => {
setEditingPlacemark(placemark);
});
if (map) {
map.addPlacemark(placemark);
}
setPlacemarks((prev) => [...prev, placemark]);
};
const handleAddPlacemark = (event: MapEvent) => {
if (!map) return;
const coords = event.get("coords") as Coords;
const newPlacemark = mapService.createPlacemark(coords, {
hintContent: "Метка",
balloonContent: "Кликнули на карту",
});
addPlacemark(newPlacemark);
setCoords(coords);
};
useEffect(() => {
if (map) {
map.addEventListener("click", handleAddPlacemark);
return () => {
map.yMap.events.remove("click", handleAddPlacemark);
};
}
}, [map]);
return (
<MapContext.Provider
value={{
coords,
setCoords,
placemarks,
addPlacemark,
editingPlacemark,
setEditingPlacemark,
map,
}}
>
{children}
</MapContext.Provider>
);
};
export const useMapContext = () => {
const context = useContext(MapContext);
if (!context) {
throw new Error("useMapContext must be used within a MapProvider");
}
return context;
};
Explanation:
- Removed
currentMark and managed placemarks through the placemarks state.
- Added cleanup function in
useEffect to remove the event listener when the component unmounts or map changes.
- Included missing dependencies in
useEffect.
5. CreatePlacemarkControl.tsx
Issues and Improvements:
- State Management: Consider using controlled components for inputs.
- Unmanaged Input Fields: Inputs can be extracted into separate components for better reusability.
Improved Code:
import { FC, useState } from "react";
import { useMapContext } from "../map-context";
import mapService from "../../services/MapService.ts";
import Input from "../ui/input";
const CreatePlacemarkControl: FC = () => {
const { coords, setCoords, addPlacemark } = useMapContext();
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const [markplaceColor, setMarkplaceColor] = useState("islands#redIcon");
const handleCoordinateChange = (index: number, value: string) => {
const newCoord = parseFloat(value);
if (!isNaN(newCoord)) {
const updatedCoords = [...coords] as [number, number];
updatedCoords[index] = newCoord;
setCoords(updatedCoords);
}
};
const handleAddPlacemark = () => {
if (!title.trim()) {
alert("Название не может быть пустым.");
return;
}
const newPlacemark = mapService.createPlacemark(
coords,
{
hintContent: title,
balloonContent: description,
},
{
preset: markplaceColor,
}
);
addPlacemark(newPlacemark);
setTitle("");
setDescription("");
};
return (
<div>
<h2>Добавить метку</h2>
<div>
<Input
label="Название"
value={title}
onChange={(e) => setTitle(e.target.value)}
required
/>
</div>
<div>
<Input
label="Описание"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
</div>
<div>
<Input
label="Координата X"
value={coords[0]}
onChange={(e) => handleCoordinateChange(0, e.target.value)}
/>
<Input
label="Координата Y"
value={coords[1]}
onChange={(e) => handleCoordinateChange(1, e.target.value)}
/>
</div>
<div>
<button onClick={handleAddPlacemark}>Добавить метку</button>
</div>
</div>
);
};
export default CreatePlacemarkControl;
Explanation:
- Simplified the input handlers by directly updating state.
- Added checks to ensure the title is not empty when adding a placemark.
- Removed unused imports and variables (e.g.,
useInput, editingPlacemark, setEditingPlacemark).
6. EditPlacemark.tsx
Issues and Improvements:
- Redundant State Resets: Clearing the local state after submitting may not be necessary.
- Optimistic Updates: Consider updating the placemark properties before adding it back to the map.
Improved Code:
import { FC, useEffect, useState, ChangeEvent, FormEvent } from "react";
import { useMapContext } from "../map-context";
import Input from "../ui/input";
import { PlaceMark } from "../../services/PlaceMark";
interface EditPlacemarkProps {
placemark: PlaceMark | null;
onEdit: () => void;
}
const EditPlacemark: FC<EditPlacemarkProps> = ({ placemark, onEdit }) => {
const { map } = useMapContext();
const [title, setTitle] = useState<string>("");
const [description, setDescription] = useState<string>("");
useEffect(() => {
if (placemark) {
const initialTitle = placemark.getProperty("hintContent") ?? "";
const initialDescription = placemark.getProperty("balloonContent") ?? "";
setTitle(initialTitle);
setDescription(initialDescription);
}
}, [placemark]);
const handleSubmit = (e: FormEvent) => {
e.preventDefault();
if (!placemark || !map) return;
if (!title.trim()) {
alert("Название не может быть пустым.");
return;
}
placemark.setProperty("hintContent", title);
placemark.setProperty("balloonContent", description);
onEdit();
};
const handleCancel = () => {
onEdit();
};
return (
<div>
<h2>Редактирование метки</h2>
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="placemark-title">Название:</label>
<Input
id="placemark-title"
disabled={!placemark}
type="text"
value={title}
onChange={(e: ChangeEvent<HTMLInputElement>) =>
setTitle(e.target.value)
}
required
/>
</div>
<div>
<label htmlFor="placemark-description">Описание:</label>
<Input
id="placemark-description"
disabled={!placemark}
type="text"
value={description}
onChange={(e: ChangeEvent<HTMLInputElement>) =>
setDescription(e.target.value)
}
/>
</div>
<div>
<button type="submit" disabled={!placemark}>
Сохранить
</button>
<button type="button" onClick={handleCancel} disabled={!placemark}>
Отмена
</button>
</div>
</form>
</div>
);
};
export default EditPlacemark;
Explanation:
- Used the
getProperty and setProperty methods from the improved PlaceMark class.
- Removed the clearing of local state on submit, as the form will unmount after
onEdit() is called.
- Ensured that we check for
map availability before performing map operations.
7. Map.tsx
Issues and Improvements:
- Event Listeners: Ensure cleanup of event listeners to prevent memory leaks.
- Dependency Arrays: Correctly specify dependencies in
useEffect.
Improved Code:
import { FC, useEffect, useRef } from "react";
import { Coords } from "../../types.ts";
import { useMapContext } from "../map-context.tsx";
import { SatelliteMap } from "../../services/SatelliteMap.ts";
interface YandexMapProps {
center: Coords;
zoom: number;
}
const Map: FC<YandexMapProps> = ({ center, zoom }) => {
const mapRef = useRef<HTMLDivElement>(null);
const { map, setMap } = useMapContext();
useEffect(() => {
if (map || !window.ymaps) return;
window.ymaps.ready(() => {
const newMap = new SatelliteMap(mapRef.current!, {
center,
zoom,
});
setMap(newMap);
});
}, [map, center, zoom, setMap]);
useEffect(() => {
return () => {
if (map) {
map.destroy();
setMap(null);
}
};
}, [map, setMap]);
return (
<div
tabIndex={10}
ref={mapRef}
style={{ width: "45%", height: "80vh" }}
/>
);
};
export default Map;
Explanation:
- Removed unnecessary variables (
isMouseOverMap, event listeners on mapRef).
- Ensured that the
map is properly destroyed when the component unmounts.
- Updated the dependency arrays in
useEffect hooks.
General Improvements:
- TypeScript Typings: Improved type annotations throughout the code for better type safety.
- State Management: Simplified state management by removing unnecessary
useRef and managing placemarks through state.
- Event Listener Cleanup: Added cleanup functions in
useEffect hooks to remove event listeners and prevent memory leaks.
- Consistency: Ensured consistent naming conventions and code formatting.
Additional Suggestions:
- Error Handling: Implement better error handling and user feedback mechanisms.
- Code Organization: Consider organizing your files and components into folders by feature (e.g.,
components/map, services/mapService.ts, etc.).
- Testing: Implement unit tests for your components and services to ensure they work as expected.
I hope these improvements help enhance your code. If you have any questions or need further assistance, feel free to ask!