TagSpaces is an offline, open source, document manager with tagging support
chore: updating the mgrs lib, refactoring the geo utils and unit tests
Ilian Sapundshiev95fd10bc19c8
diff --git a/package-lock.json b/package-lock.jsonindex 9b901fb06..ccf849a14 100644--- a/package-lock.json+++ b/package-lock.json@@ -44,7 +44,7 @@"i18next-http-backend": "^2.2.2","leaflet": "1.9.4","marked": "17.0.1",- "mgrs": "1.0.0",+ "mgrs": "2.1.0","music-metadata": "11.11.1","ollama": "0.6.3","open-location-code": "1.0.3",@@ -84,7 +84,6 @@"zod-to-json-schema": "3.25.1"},"devDependencies": {- "@electron/notarize": "^2.5.0","@electron/rebuild": "^3.7.2","@playwright/test": "^1.53.2","@pmmmwh/react-refresh-webpack-plugin": "0.6.2",@@ -32298,7 +32297,9 @@}},"node_modules/mgrs": {- "version": "1.0.0",+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/mgrs/-/mgrs-2.1.0.tgz",+ "integrity": "sha512-/pjuM02PUAhp4dazfccTSKBGTGPFkRz9LKwGJKusc/B20apcGG/CYnRHx0kXmLXy4m5O3p6y6nOVxEnErPpFvQ==","license": "MIT"},"node_modules/micromark": {diff --git a/package.json b/package.jsonindex 35b97ae9e..6de591565 100644--- a/package.json+++ b/package.json@@ -195,7 +195,7 @@"i18next-http-backend": "^2.2.2","leaflet": "1.9.4","marked": "17.0.1",- "mgrs": "1.0.0",+ "mgrs": "2.1.0","music-metadata": "11.11.1","ollama": "0.6.3","open-location-code": "1.0.3",diff --git a/src/renderer/utils/geo.ts b/src/renderer/utils/geo.tsindex 153b0e0c6..fb254c8c4 100644--- a/src/renderer/utils/geo.ts+++ b/src/renderer/utils/geo.ts@@ -18,73 +18,122 @@import mgrs from 'mgrs';import OpenLocationCode from 'open-location-code-typescript';-export function parseGeoLocation(code: string): any {+// Regex patterns for coordinate validation+const PLUS_CODE_REGEX =+ /(^|\s)([23456789C][23456789CFGHJMPQRV][23456789CFGHJMPQRVWX]{6}\+[23456789CFGHJMPQRVWX]{2,3})(\s|$)/;+const MGRS_REGEX =+ /^(\d{1,2})([C-HJ-NP-X])\s*([A-HJ-NP-Z])([A-HJ-NP-V])\s*(\d{1,5}\s*\d{1,5})$/i;+const LAT_LON_REGEX =+ /^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/;+const WHITESPACE_REGEX = /\s+/g;++// Type definitions+interface Coordinates {+ lat: number;+ lng?: number;+ lon?: number;+}++/**+ * Parses geographic location from Plus Code or MGRS format+ * @param code - A Plus Code (e.g., 8FWH4HVG+3V) or MGRS code (e.g., 18SUJ7082315291)+ * @returns Coordinates object with lat/lng, or undefined if parsing fails+ */+export function parseGeoLocation(code: string): Coordinates | undefined {+ if (!code) {+ return undefined;+ }+if (isPlusCode(code)) {- const coord = OpenLocationCode.decode(code);- const lat = Number(coord.latitudeLo.toFixed(7)); // latitudeCenter.toFixed(7));- const lng = Number(coord.longitudeLo.toFixed(7));- return { lat, lng };+ try {+ const coord = OpenLocationCode.decode(code);+ const lat = Number(coord.latitudeLo.toFixed(7));+ const lng = Number(coord.longitudeLo.toFixed(7));+ return { lat, lng };+ } catch (error) {+ console.warn('Failed to parse Plus Code:', code, error);+ return undefined;+ }}+if (isMgrsString(code)) {try {const [lng, lat] = mgrs.toPoint(code);return { lat, lng };- } catch (e) {- console.log('parseGeoLocation', e);+ } catch (error) {+ console.warn('Failed to parse MGRS code:', code, error);+ return undefined;}}+return undefined;}+/**+ * Checks if a string is a valid geographic tag (Plus Code or MGRS format)+ * @param code - String to validate+ * @returns true if the code is a valid Plus Code or MGRS code, false otherwise+ */export function isGeoTag(code: string): boolean {return isPlusCode(code) || isMgrsString(code);}-/** Returns true is a string is plus code e.g. 8FWH4HVG+3V 8FWH4HVG+ 8FWH4H+ */+/**+ * Validates if a string is a valid Plus Code+ * Plus Codes are hierarchical geocodes with format: 8FWH4HVG+3V (10 chars) or shorter versions+ * @param plusCode - String to validate+ * @returns true if the string is a valid Plus Code format, false otherwise+ */export function isPlusCode(plusCode: string): boolean {- if (!plusCode) {+ if (!plusCode || typeof plusCode !== 'string') {return false;}- const upperCasedPlusCode = plusCode.toUpperCase(); // needed only lowercased index- return /(^|\s)([23456789C][23456789CFGHJMPQRV][23456789CFGHJMPQRVWX]{6}\+[23456789CFGHJMPQRVWX]{2,3})(\s|$)/.test(- upperCasedPlusCode,- );+ const upperCasedPlusCode = plusCode.toUpperCase();+ return PLUS_CODE_REGEX.test(upperCasedPlusCode);}-/** Returns true is a string is MGRS code e.g. 18SUJ7082315291 18SUJ70821529 18SUJ708152 */-export function isMgrsString(c) {- if (!c) {+/**+ * Validates if a string is a valid MGRS (Military Grid Reference System) code+ * MGRS codes are used for military grid coordinates: 18SUJ7082315291+ * @param code - String to validate+ * @returns true if the string is a valid MGRS code format, false otherwise+ */+export function isMgrsString(code: string): boolean {+ if (!code || typeof code !== 'string') {return false;}- const coord = c.replace(/\s+/g, '');- const MGRS =- /^(\d{1,2})([C-HJ-NP-X])\s*([A-HJ-NP-Z])([A-HJ-NP-V])\s*(\d{1,5}\s*\d{1,5})$/i;- return MGRS.test(coord);+ const cleanedCoord = code.replace(WHITESPACE_REGEX, '');+ return MGRS_REGEX.test(cleanedCoord);}/**- * @deprecated use coordinate-parser lib instead- * @param latLongInput+ * Parses latitude and longitude from a comma-separated string+ * Format: "40.7128,-74.0060" or "40.7128 , -74.0060"+ * Latitude range: -90 to 90 | Longitude range: -180 to 180+ * @deprecated Use coordinate-parser library instead+ * @param latLongInput - String in format "latitude,longitude"+ * @returns Object with lat/lon properties, or false if invalid format*/export function parseLatLon(latLongInput: string,): { lat: number; lon: number } | false {- const cleanedInput = latLongInput.replace(/\s+/g, ''); // cleaning spaces- if (- !/^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/.test(- cleanedInput,- )- ) {+ if (!latLongInput || typeof latLongInput !== 'string') {return false;}- const latLongArray = cleanedInput.split(',');- const lat = parseFloat(latLongArray[0]);- const lon = parseFloat(latLongArray[1]);- if (!isNaN(lat) && !isNaN(lon)) {- return {- lat,- lon,- };++ const cleanedInput = latLongInput.replace(WHITESPACE_REGEX, '');++ if (!LAT_LON_REGEX.test(cleanedInput)) {+ return false;+ }++ const [latStr, lonStr] = cleanedInput.split(',');+ const lat = parseFloat(latStr);+ const lon = parseFloat(lonStr);++ if (isNaN(lat) || isNaN(lon)) {+ return false;}- return false;++ return { lat, lon };}diff --git a/tests/unit/geo.test.js b/tests/unit/geo.test.jsnew file mode 100644index 000000000..de8a1e970--- /dev/null+++ b/tests/unit/geo.test.js@@ -0,0 +1,165 @@+import {+ isGeoTag,+ isMgrsString,+ isPlusCode,+ parseLatLon,+} from '-/utils/geo';+import { describe, expect, test } from '@playwright/test';++describe('Geo Utilities', () => {+ describe('isPlusCode', () => {+ test('should return true for valid plus code 8FWH4HVG+3V', () => {+ expect(isPlusCode('8FWH4HVG+3V')).toBe(true);+ });++ test('should return true for valid plus code 8FWH4HVG+2X', () => {+ expect(isPlusCode('8FWH4HVG+2X')).toBe(true);+ });++ test('should return true for valid plus code with 3 suffix chars 8FWH4HVG+2XQ', () => {+ expect(isPlusCode('8FWH4HVG+2XQ')).toBe(true);+ });++ test('should return true for plus code with surrounding spaces', () => {+ expect(isPlusCode(' 8FWH4HVG+3V ')).toBe(true);+ });++ test('should return false for empty string', () => {+ expect(isPlusCode('')).toBe(false);+ });++ test('should return false for null or undefined', () => {+ expect(isPlusCode(null)).toBe(false);+ expect(isPlusCode(undefined)).toBe(false);+ });++ test('should return false for invalid plus code without +', () => {+ expect(isPlusCode('8FWH4HVG3V')).toBe(false);+ });++ test('should return false for invalid characters', () => {+ expect(isPlusCode('INVALID+CODE')).toBe(false);+ });++ test('should handle lowercase plus codes', () => {+ expect(isPlusCode('8fwh4hvg+3v')).toBe(true);+ });+ });++ describe('isMgrsString', () => {+ test('should return true for valid MGRS code 18SUJ7082315291', () => {+ expect(isMgrsString('18SUJ7082315291')).toBe(true);+ });++ test('should return true for valid MGRS code 18SUJ70821529', () => {+ expect(isMgrsString('18SUJ70821529')).toBe(true);+ });++ test('should return true for valid MGRS code 18SUJ708152', () => {+ expect(isMgrsString('18SUJ708152')).toBe(true);+ });++ test('should return true for MGRS code with spaces', () => {+ expect(isMgrsString('18 SUJ 708 152')).toBe(true);+ });++ test('should return true for lowercase MGRS code', () => {+ expect(isMgrsString('18suj7082315291')).toBe(true);+ });++ test('should return false for empty string', () => {+ expect(isMgrsString('')).toBe(false);+ });++ test('should return false for null or undefined', () => {+ expect(isMgrsString(null)).toBe(false);+ expect(isMgrsString(undefined)).toBe(false);+ });++ test('should return false for invalid MGRS format', () => {+ expect(isMgrsString('INVALID')).toBe(false);+ expect(isMgrsString('ABC')).toBe(false);+ });++ test('should return false for wrong zone letter', () => {+ // 'B' is not valid for zone letter+ expect(isMgrsString('18BUJ7082315291')).toBe(false);+ });+ });++ describe('parseLatLon', () => {+ test('should parse valid latitude and longitude', () => {+ const result = parseLatLon('40.7128,-74.0060');+ expect(result).not.toBe(false);+ expect(result.lat).toBe(40.7128);+ expect(result.lon).toBe(-74.006);+ });++ test('should parse coordinates with spaces', () => {+ const result = parseLatLon('40.7128 , -74.0060');+ expect(result).not.toBe(false);+ expect(result.lat).toBe(40.7128);+ expect(result.lon).toBe(-74.006);+ });++ test('should handle positive coordinates', () => {+ const result = parseLatLon('35.6895,139.6917');+ expect(result).not.toBe(false);+ expect(result.lat).toBe(35.6895);+ expect(result.lon).toBe(139.6917);+ });++ test('should handle maximum valid latitude (90)', () => {+ const result = parseLatLon('90,0');+ expect(result).not.toBe(false);+ expect(result.lat).toBe(90);+ });++ test('should handle maximum valid longitude (180)', () => {+ const result = parseLatLon('0,180');+ expect(result).not.toBe(false);+ expect(result.lon).toBe(180);+ });++ test('should return false for empty string', () => {+ expect(parseLatLon('')).toBe(false);+ });++ test('should return false for invalid format (no comma)', () => {+ expect(parseLatLon('40.7128 -74.0060')).toBe(false);+ });++ test('should return false for out of range latitude', () => {+ expect(parseLatLon('91,0')).toBe(false);+ expect(parseLatLon('-91,0')).toBe(false);+ });++ test('should return false for out of range longitude', () => {+ expect(parseLatLon('0,181')).toBe(false);+ expect(parseLatLon('0,-181')).toBe(false);+ });++ test('should return false for non-numeric input', () => {+ expect(parseLatLon('abc,def')).toBe(false);+ });+ });++ describe('isGeoTag', () => {+ test('should return true for valid plus code', () => {+ expect(isGeoTag('8FWH4HVG+3V')).toBe(true);+ });++ test('should return true for valid MGRS code', () => {+ expect(isGeoTag('18SUJ7082315291')).toBe(true);+ });++ test('should return false for non-geo strings', () => {+ expect(isGeoTag('random text')).toBe(false);+ expect(isGeoTag('12345')).toBe(false);+ });++ test('should return false for empty string', () => {+ expect(isGeoTag('')).toBe(false);+ });+ });+});