Skip to content
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
15 changes: 15 additions & 0 deletions packages/firecms_core/src/core/field_configs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
ArrayOfReferencesFieldBinding,
BlockFieldBinding,
DateTimeFieldBinding,
GeopointFieldBinding,
KeyValueFieldBinding,
MapFieldBinding,
MarkdownEditorFieldBinding,
Expand All @@ -32,6 +33,7 @@ import {
ListAltIcon,
ListIcon,
MailIcon,
LocationOnIcon,
NumbersIcon, PersonIcon,
RepeatIcon,
ScheduleIcon,
Expand Down Expand Up @@ -271,6 +273,17 @@ export const DEFAULT_FIELD_CONFIGS: Record<string, PropertyConfig<any>> = {
Field: DateTimeFieldBinding
}
},
geopoint: {
key: "geopoint",
name: "Geopoint",
description: "Latitude and longitude pair",
Icon: LocationOnIcon,
color: "#0ea5e9",
property: {
dataType: "geopoint",
Field: GeopointFieldBinding
}
},
group: {
key: "group",
name: "Group",
Expand Down Expand Up @@ -412,6 +425,8 @@ export function getDefaultFieldId(property: Property | ResolvedProperty) {
return "switch";
} else if (property.dataType === "date") {
return "date_time";
} else if (property.dataType === "geopoint") {
return "geopoint";
} else if (property.dataType === "reference") {
return "reference";
}
Expand Down
140 changes: 140 additions & 0 deletions packages/firecms_core/src/form/field_bindings/GeopointFieldBinding.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import React, { useEffect, useRef, useState } from "react";

import { CloseIcon, IconButton, TextField } from "@firecms/ui";
import { FieldProps, GeoPoint } from "../../types";
import { FieldHelperText, LabelWithIcon } from "../components";
import { PropertyIdCopyTooltip } from "../../components";
import { useClearRestoreValue } from "../useClearRestoreValue";
import { getIconForProperty } from "../../util";
import { formatGeoPoint, getGeoPointCoordinates, parseGeoPoint } from "../../util/geopoint";

interface GeopointFieldBindingProps extends FieldProps<GeoPoint> {
}

export function GeopointFieldBinding({
propertyKey,
value,
setValue,
error,
showError,
disabled,
autoFocus,
property,
includeDescription,
size = "large"
}: GeopointFieldBindingProps) {

const coordinates = getGeoPointCoordinates(value);
const canClear = Boolean((property as any).clearable);
const [latitude, setLatitude] = useState<string>(coordinates ? coordinates.latitude.toString() : "");
const [longitude, setLongitude] = useState<string>(coordinates ? coordinates.longitude.toString() : "");
const [localError, setLocalError] = useState<string | undefined>();
const skipSyncRef = useRef(false);

useClearRestoreValue({
property,
value,
setValue
});

useEffect(() => {
if (skipSyncRef.current) {
skipSyncRef.current = false;
return;
}
const nextCoordinates = getGeoPointCoordinates(value);
setLatitude(nextCoordinates ? nextCoordinates.latitude.toString() : "");
setLongitude(nextCoordinates ? nextCoordinates.longitude.toString() : "");
}, [value]);

const updateGeoPoint = (nextLatitude: string, nextLongitude: string) => {
skipSyncRef.current = true;
setLatitude(nextLatitude);
setLongitude(nextLongitude);

const trimmedLatitude = nextLatitude.trim();
const trimmedLongitude = nextLongitude.trim();

if (!trimmedLatitude && !trimmedLongitude) {
setLocalError(undefined);
setValue(null);
return;
}

const parsed = parseGeoPoint(`${trimmedLatitude}, ${trimmedLongitude}`);

if (parsed.error) {
setLocalError(parsed.error);
setValue(null);
return;
}

setLocalError(undefined);
setValue(parsed.point);
};

const handleClear = (event?: React.MouseEvent) => {
if (event) {
event.preventDefault();
event.stopPropagation();
}
updateGeoPoint("", "");
};

const resolvedError = localError ?? error;
const shouldShowError = Boolean(resolvedError) || Boolean(showError && error);

return (
<>
<PropertyIdCopyTooltip propertyKey={propertyKey}>
<div className="flex flex-col gap-2">
<div className="mt-1">
<LabelWithIcon
icon={getIconForProperty(property, "small")}
required={property.validation?.required}
title={property.name}
className={shouldShowError ? "text-red-500 dark:text-red-500" : "text-text-secondary dark:text-text-secondary-dark"}
/>
</div>
<div className="grid grid-cols-1 gap-2 md:grid-cols-2">
<TextField
size={size}
value={latitude}
onChange={(event) => updateGeoPoint(event.target.value, longitude)}
autoFocus={autoFocus}
label={"Latitude"}
type="number"
disabled={disabled}
endAdornment={canClear ? (
<IconButton onClick={handleClear}>
<CloseIcon />
</IconButton>
) : undefined}
error={shouldShowError && Boolean(resolvedError)}
/>
<TextField
size={size}
value={longitude}
onChange={(event) => updateGeoPoint(latitude, event.target.value)}
label={"Longitude"}
type="number"
disabled={disabled}
error={shouldShowError && Boolean(resolvedError)}
/>
</div>
{value && !resolvedError && (
<div className="text-xs text-text-secondary dark:text-text-secondary-dark font-mono">
{formatGeoPoint(value)}
</div>
)}
</div>
</PropertyIdCopyTooltip>

<FieldHelperText includeDescription={includeDescription}
showError={shouldShowError}
error={resolvedError}
disabled={disabled}
property={property}/>
</>
);
}
1 change: 1 addition & 0 deletions packages/firecms_core/src/form/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export { StorageUploadFieldBinding } from "./field_bindings/StorageUploadFieldBi
export { TextFieldBinding } from "./field_bindings/TextFieldBinding";
export { SwitchFieldBinding } from "./field_bindings/SwitchFieldBinding";
export { DateTimeFieldBinding } from "./field_bindings/DateTimeFieldBinding";
export { GeopointFieldBinding } from "./field_bindings/GeopointFieldBinding";
export { ReferenceFieldBinding } from "./field_bindings/ReferenceFieldBinding";
export { ReferenceAsStringFieldBinding } from "./field_bindings/ReferenceAsStringFieldBinding";
export { MapFieldBinding } from "./field_bindings/MapFieldBinding";
Expand Down
12 changes: 12 additions & 0 deletions packages/firecms_core/src/preview/PropertyPreview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import equal from "react-fast-compare"
import {
CMSType,
EntityReference,
GeoPoint,
ResolvedArrayProperty,
ResolvedMapProperty,
ResolvedNumberProperty,
Expand All @@ -26,12 +27,14 @@ import { ArrayPropertyEnumPreview } from "./property_previews/ArrayPropertyEnumP
import { ArrayOfStringsPreview } from "./property_previews/ArrayOfStringsPreview";
import { ArrayOneOfPreview } from "./property_previews/ArrayOneOfPreview";
import { MapPropertyPreview } from "./property_previews/MapPropertyPreview";
import { GeopointPropertyPreview } from "./property_previews/GeopointPropertyPreview";
import { ReferencePreview } from "./components/ReferencePreview";
import { DatePreview } from "./components/DatePreview";
import { BooleanPreview } from "./components/BooleanPreview";
import { NumberPropertyPreview } from "./property_previews/NumberPropertyPreview";
import { ErrorView } from "../components";
import { UserPreview } from "./components/UserPreview";
import { getGeoPointCoordinates } from "../util";

/**
* @group Preview components
Expand Down Expand Up @@ -192,6 +195,15 @@ export const PropertyPreview = React.memo(function PropertyPreview<T extends CMS
} else {
content = buildWrongValueType(propertyKey, property.dataType, value);
}
} else if (property.dataType === "geopoint") {
const coordinates = getGeoPointCoordinates(value as GeoPoint);
if (coordinates) {
content = <GeopointPropertyPreview {...props}
property={property}
value={value as GeoPoint}/>;
} else {
content = buildWrongValueType(propertyKey, property.dataType, value);
}
} else if (property.dataType === "reference") {
if (typeof property.path === "string") {
if (typeof value === "object" && "isEntityReference" in value && value.isEntityReference()) {
Expand Down
1 change: 1 addition & 0 deletions packages/firecms_core/src/preview/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export * from "./property_previews/ArrayOfStringsPreview";
export * from "./property_previews/ArrayPropertyEnumPreview";
export * from "./property_previews/ArrayOfMapsPreview";
export * from "./property_previews/NumberPropertyPreview";
export * from "./property_previews/GeopointPropertyPreview";
export * from "./property_previews/StringPropertyPreview";
export * from "./property_previews/ArrayOfStorageComponentsPreview";
export * from "./property_previews/ArrayOfReferencesPreview";
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import React from "react";

import { GeoPoint } from "../../types";
import { PropertyPreviewProps } from "../PropertyPreviewProps";
import { formatGeoPoint, getGeoPointCoordinates } from "../../util";

export function GeopointPropertyPreview({
value,
size
}: PropertyPreviewProps<GeoPoint>): React.ReactElement {

const coordinates = getGeoPointCoordinates(value);

if (!coordinates) {
return <span className={size === "small" ? "text-sm text-text-secondary dark:text-text-secondary-dark" : "text-text-secondary dark:text-text-secondary-dark"}>—</span>;
}

return (
<span className={size === "small" ? "text-sm font-mono" : "font-mono"}>
{formatGeoPoint(coordinates)}
</span>
);
}
2 changes: 2 additions & 0 deletions packages/firecms_core/src/util/entities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ export function getDefaultValueForDataType(dataType: DataType) {
return [];
} else if (dataType === "map") {
return {};
} else if (dataType === "geopoint") {
return null;
} else {
return null;
}
Expand Down
77 changes: 77 additions & 0 deletions packages/firecms_core/src/util/geopoint.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { GeoPoint } from "../types";

export type GeoPointLike = GeoPoint | {
latitude?: number;
longitude?: number;
lat?: number;
lng?: number;
_lat?: number;
_long?: number;
} | null | undefined;

export interface GeoPointCoordinates {
latitude: number;
longitude: number;
}

function toNumber(value: any): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}

export function getGeoPointCoordinates(value: GeoPointLike): GeoPointCoordinates | undefined {
if (!value) return undefined;
if (value instanceof GeoPoint) {
return { latitude: value.latitude, longitude: value.longitude };
}
if (typeof value !== "object") return undefined;

const latitude = toNumber((value as any).latitude ?? (value as any).lat ?? (value as any)._lat);
const longitude = toNumber((value as any).longitude ?? (value as any).lng ?? (value as any)._long);

if (latitude === undefined || longitude === undefined) return undefined;

return { latitude, longitude };
}

export function normalizeGeoPoint(value: GeoPointLike): GeoPoint | undefined {
const coordinates = getGeoPointCoordinates(value);
if (!coordinates) return undefined;
if (value instanceof GeoPoint) return value;
return new GeoPoint(coordinates.latitude, coordinates.longitude);
}

export function formatGeoPoint(value: GeoPointLike, options?: { maximumFractionDigits?: number }): string {
const coordinates = getGeoPointCoordinates(value);
if (!coordinates) return "";

const maximumFractionDigits = options?.maximumFractionDigits ?? 6;
const formatter = new Intl.NumberFormat(undefined, {
maximumFractionDigits,
minimumFractionDigits: Math.min(2, maximumFractionDigits)
});

return `${formatter.format(coordinates.latitude)}, ${formatter.format(coordinates.longitude)}`;
}

export function parseGeoPoint(input: string): { point: GeoPoint | null; error?: string } {
const trimmed = input.trim();
if (!trimmed) return { point: null };

const parts = trimmed.split(",").map((part) => part.trim()).filter((part) => part !== "");
if (parts.length !== 2) return { point: null, error: "Use \"lat, lng\" format" };

const latitude = parseFloat(parts[0]);
const longitude = parseFloat(parts[1]);

if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) {
return { point: null, error: "Latitude and longitude must be numbers" };
}
if (latitude < -90 || latitude > 90) {
return { point: null, error: "Latitude must be between -90 and 90" };
}
if (longitude < -180 || longitude > 180) {
return { point: null, error: "Longitude must be between -180 and 180" };
}

return { point: new GeoPoint(latitude, longitude) };
}
1 change: 1 addition & 0 deletions packages/firecms_core/src/util/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export * from "./useDebouncedCallback";
export * from "./property_utils";
export * from "./resolutions";
export * from "./permissions";
export * from "./geopoint";
export * from "./icon_list";
export * from "./icon_synonyms";
export * from "./icons";
Expand Down
Loading
Loading