{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "latlng-input",
  "title": "Lat/Lng Input",
  "description": "Two boxes for one point that takes decimal degrees or degrees-minutes-seconds in either of them, and reports what it could not read instead of substituting a number. Reach for it wherever a person types a place rather than a count: registering a shop, depot, site or asset, drawing a geofence, a collection or drop point for delivery, a survey station or drone waypoint, a wildlife or sensor observation, a property or incident location, and the numeric readout beside a map where somebody nudges a dragged pin. Common asks it answers: \"latlng input react\", \"lat lng input react\", \"shadcn coordinate input\", \"latitude longitude input component\", \"coordinate input react\", \"dms input react\", \"decimal degrees to dms javascript\", \"dms to decimal degrees javascript\", \"parse 35°41'22\"N javascript\", \"degrees minutes seconds parser js\", \"convert coordinates react form\", \"latitude longitude form validation\", \"validate latitude longitude javascript\", \"latitude range -90 90 validation\", \"longitude wrap 180 javascript\", \"normalize longitude -180 180\", \"antimeridian 180 or -180\", \"wrapped longitude 180 becomes -180\", \"lat lng swapped bug\", \"geojson coordinates order lat lng\", \"why are my coordinates reversed\", \"leaflet latlng vs geojson order\", \"mapbox coordinates wrong order\", \"-0 latitude javascript\", \"Object.is(-0, 0) coordinate\", \"toFixed loses negative zero\", \"0 degrees south sign lost\", \"35°59'60\" invalid seconds\", \"dms rounding 60 seconds carry\", \"how many decimal places latitude longitude\", \"5 decimal places latitude meters\", \"6 decimals gps accuracy\", \"how precise is 7 decimal places coordinates\", \"metres per degree longitude latitude\", \"degree to meters conversion latitude\", \"cos latitude longitude distance\", \"store coordinates how many digits\", \"coordinate input Number('') is 0\", \"empty latitude posts 0 0\", \"gulf of guinea 0 0 bug\", \"paste coordinate from google maps react\", \"accept both decimal and dms in one input\", \"geofence coordinate entry form\", \"store location picker numeric input\", \"survey station coordinate entry\", \"drone waypoint latitude longitude form\", \"asset location form react\", \"緯度経度 入力 react\", \"緯度経度 コンポーネント\", \"度分秒 変換 javascript\", \"緯度経度 入れ替わり\", \"経度 180 巻き戻り\", \"緯度経度 小数 桁数 精度\", \"緯度経度 バリデーション\", \"南緯 マイナスゼロ\". **The two boxes are not one field with two labels, and all three of their differences are load-bearing.** Latitude stops at ±90 and longitude comes back round the other side; one number of decimals is worth a different distance on each of them; and only one of them has a legitimate value whose sign the language cannot store. Everything below follows from those three. **A latitude past 90 is refused and a longitude past 180 is offered a correction, because only one of them has an unambiguous reading.** 181° is 179°W, the same meridian, so it is folded and the field says so. There is no reading of 95°N that does not also move the longitude 180°, so clamping it to 90 — which is what \"saturate the axis\" produces — moves the reader's point while reporting success, and it is reported as out of range instead. **The longitude fold has a guard that the formula everybody writes does not.** Measured, `((x + 180) % 360 + 360) % 360 - 180` turns `180` into `-180`: the same meridian, but the other side of the dateline, so a Fiji longitude comes back rewritten. Anything already inside ±180 is handed back untouched and only an out-of-range value is folded, into (-180, 180]. The combination is what makes it dangerous rather than untidy — rounding 179.9999999 to three decimal seconds lands on exactly 180° (measured), so an unguarded wrap takes a point just short of the dateline and puts it across. **0°00'00\"S keeps its hemisphere, which costs a separate piece of state and is the only way it survives.** Measured: `String(-0)` is `\"0\"`, `(-0).toFixed(5)` is `\"0.00000\"` and `JSON.stringify(-0)` is `0`, while `-0 === 0` is `true` — so a point on the equator in the southern half, or on the prime meridian in the western half, loses its sign the moment anything renders it, and no guard written `< 0` will ever find it again. `Object.is` is the only thing that can see it, the exported `signOf` is built on it, and the hemisphere is a letter on screen rather than a minus sign inferred from the number. **No reading ever says sixty seconds, because the seconds are rounded before the carry rather than after.** Measured, 35.99999997222222° split naively prints `35°59'60.000\"` — the seconds come out as 59.9999 and `(59.9995).toFixed(2)` is `\"60.00\"`. The rounded seconds roll into the minutes and the rounded minutes into the degrees, so the same value prints `36°00'00.000\"`. `toFixed` is also not round-half-up (`(1.005).toFixed(2)` is `\"1.00\"` and `(2.675).toFixed(2)` is `\"2.67\"`, both measured), which is why the rounding happens in one declared place instead of at each point of display. **It says what a decimal place is worth, and the answer is different on the two axes.** The quoted \"111,320 m per degree\" is the equatorial longitude degree; the equatorial latitude degree is 110,574.3 m, 746 m shorter, because the meridian is the flatter curve there — so one figure used for both is wrong about one axis everywhere. The longitude degree then falls away with the cosine of the latitude: measured off WGS84, 91,288.2 m at 35°, 55,800.0 m at 60° and 9,734.5 m at 85°. Six decimal places is therefore 11 cm north-south everywhere and 11 cm, 9.1 cm, 5.6 cm or 1 cm east-west depending on where the other box points, and the field prints that sentence rather than leaving the reader to guess. **It will tell you when the digits have stopped being precision.** Five decimals is 1.11 m, where a phone's GPS sits; seven is 1.11 cm, which is survey-grade RTK; eight is 1.1 mm. Nothing in positioning resolves the ninth, so twelve decimal places — 111 nanometres, inside the wavelength of visible light — is not a more exact location, it is the arithmetic residue of whatever converted it. The number is perfectly representable (float64's own step at 180° is 2.8e-14°, about 3 nm); the claim is what is false, and the sentence says so instead of truncating data to make the point. **A swapped pair is flagged and never silently fixed, and the reason is that it can only be found half the time.** GeoJSON writes a point as `[longitude, latitude]` (RFC 7946), the reverse of the order people say out loud, which is why the mistake is so common. A Tokyo pair entered backwards is caught outright, because 139.69 cannot be a latitude. A London pair is not: 51.5072 and -0.1276 are both legal in both boxes, as is every pair whose longitude is inside ±90 — half the planet. Measured over six cities on five continents, four were undetectable. So there is a warning and an explicit Swap control, and no automatic correction that would quietly move the other half of the data. **An empty box and an unreadable box are different answers, and conflating them is the costliest thing this component could do.** `Number(\"\")` is `0` (measured) and 0,0 is a real point in the Gulf of Guinea, so a cleared field that posts it is the default behaviour of the obvious implementation. Empty parses to `null` and junk to `NaN`, and neither is posted. The grammar is strict for the rest of the same reason: measured, `Number(\"1e3\")` is 1000, `Number(\"0x10\")` is 16, `Number(\"Infinity\")` is `Infinity` and `Number(\" 35 \")` is 35, and none of those is a latitude — while `35.` and `.5` do pass, because that is what a half-typed decimal looks like. **The characters a pasted coordinate actually carries are normalised, including the one that makes `Number` give up.** `º` U+00BA for the degree sign, `′` and `″` U+2032/U+2033 against the keyboard's `'` and `\"`, and `−` U+2212, the mathematical minus, on which `Number(\"−35\")` is `NaN` (measured). A hemisphere letter is read from either end and checked against the axis, so `N` in a longitude box is reported rather than applied; a letter and a `-` that contradict each other (`-35S`) are refused rather than resolved either way; and `35°60'00\"` is treated as junk rather than normalised, because normalising it hides that the source was broken. Accessibility and form behaviour: the pair is one `role=\"group\"` with a label, each box separately labelled with an `sr-only` hint naming which way its axis runs, one polite `role=\"status\"` line carries the verdict for the whole group through `aria-describedby` (two live regions race each other and neither gets read), `aria-invalid` follows the actual fault rather than a non-empty box, a folded longitude reads as a note instead of an error, the Swap control is `type=\"button\"` so it cannot submit the form it sits in, and a `name` posts canonical signed decimal degrees through hidden inputs at no fewer than six places however few are displayed — and posts nothing at all when the pair is one it would not stand behind. `parseCoordinate`, `checkCoordinate`, `wrapLongitude`, `toDmsParts`, `fromDmsParts`, `formatDms`, `formatDecimal`, `signOf`, `hemisphereOf`, `looksSwapped`, `metresPerDegree`, `metresForDecimals` and `precisionNote` are exported as plain functions, so the route handler that receives the two strings reaches the same verdict the field showed instead of carrying a second copy of the rules. WGS84 is kept as its two defining numbers with the radii derived, so the figures agree with the ellipsoid rather than with a remembered table. Official shadcn/ui has nothing of the kind and the measurement is not close: fetching every entry in its registry today — 65 listed, 62 fetchable, `code-block`, `questionnaire` and `trace` 404 on both style tracks — and searching all 223,287 bytes, `latitude`, `longitude`, `coordinate`, `coordinates`, `geohash`, `decimalDegrees`, `DMS`, `GeoJSON`, `hemisphere`, `meridian`, `WGS84`, `Object.is` and `toFixed` are every one of them a zero hit; its `input` is a bare text box and `input-group` only puts ornaments either side of one. Within pulld it is the other half of the location pair: `geolocation-button` asks the device where it is and this asks a person where something is, `number-range-input` holds one axis' worth of from-and-to, `unit-input` one value whose unit is part of it, and `masked-input` fixes the shape of a field whose two halves do not have different rules. No dependencies beyond React and your `cn`.",
  "dependencies": [],
  "files": [
    {
      "path": "registry/ui/latlng-input.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\n/**\n * Which axis a box holds. The two are not the same field with a different label.\n *\n * Latitude runs to ±90 and stops there; longitude runs to ±180 and comes back round the other\n * side. One number of decimals means a different distance on each of them, and only one of them\n * has a legitimate value whose sign cannot be stored (see `signOf`). Everything below that reads\n * `axis` is reading one of those three differences, not a label.\n */\nexport type Axis = \"lat\" | \"lng\"\n\n/** The last degree each axis reaches. Measured against nothing — this is the definition. */\nexport const AXIS_LIMIT: Record<Axis, number> = { lat: 90, lng: 180 }\n\n/** The two letters each axis uses, negative one second. */\nexport const HEMISPHERES: Record<Axis, readonly [string, string]> = {\n  lat: [\"N\", \"S\"],\n  lng: [\"E\", \"W\"],\n}\n\n/**\n * WGS84, the ellipsoid every consumer GPS and every web map reports against.\n *\n * Kept as the two defining numbers with the rest derived, rather than a table of metres per\n * degree, because the derived figures disagree with the ones usually quoted and the derivation is\n * the only way to see why. \"111,320 m per degree\" is the equatorial *longitude* degree; the\n * equatorial *latitude* degree is 110,574 m, 746 m shorter, because the meridian is the flatter\n * of the two curves there. A component that uses one figure for both is wrong about one axis\n * everywhere.\n */\nexport const WGS84 = { a: 6378137, f: 1 / 298.257223563 } as const\n\nconst E2 = (() => {\n  const b = WGS84.a * (1 - WGS84.f)\n  return (WGS84.a * WGS84.a - b * b) / (WGS84.a * WGS84.a)\n})()\n\n/**\n * How many metres one degree of `axis` covers at latitude `atLat`.\n *\n * Measured on this formula: at the equator a latitude degree is 110,574.3 m and a longitude degree\n * 111,319.5 m; at 35° they are 110,940.6 m and 91,288.2 m; at 60°, 111,412.3 m and 55,800.0 m; at\n * 85°, 111,685.4 m and 9,734.5 m.\n *\n * **The longitude figure is the one that matters for a form.** It falls away with the cosine of\n * the latitude, so the same six decimals that pin a point to 11 cm in Nairobi pin it to 1 cm in\n * Reykjavík — and the field cannot say what a decimal is worth without knowing where on the\n * planet the other box is pointing. That is why `precisionNote` takes the latitude.\n */\nexport function metresPerDegree(axis: Axis, atLat = 0): number {\n  const phi = (atLat * Math.PI) / 180\n  const s = Math.sin(phi)\n  if (axis === \"lat\") {\n    // Meridian radius of curvature.\n    return ((WGS84.a * (1 - E2)) / Math.pow(1 - E2 * s * s, 1.5)) * (Math.PI / 180)\n  }\n  // Radius of the parallel: the prime vertical radius times cos(phi).\n  return ((WGS84.a * Math.cos(phi)) / Math.sqrt(1 - E2 * s * s)) * (Math.PI / 180)\n}\n\n/** What the last of `decimals` decimal places is worth on the ground, in metres. */\nexport function metresForDecimals(decimals: number, axis: Axis, atLat = 0): number {\n  return metresPerDegree(axis, atLat) * Math.pow(10, -decimals)\n}\n\n/**\n * The decimal place past which the digits are not precision.\n *\n * Measured against a latitude degree: five decimals is 1.11 m, which is where a phone's GPS sits;\n * six is 11 cm; seven is 1.11 cm, which is survey-grade RTK; eight is 1.1 mm. **Nothing in\n * positioning resolves the ninth**, so a field that stores twelve decimal places — 111 nanometres,\n * well inside the wavelength of visible light — is not storing a more exact location, it is\n * storing the arithmetic residue of whatever converted it. The number is representable; float64's\n * own step at 180° is 2.8e-14°, about 3 nm. The claim is what is false, not the storage.\n *\n * Returned rather than enforced: a value that arrived with twelve places is still the value, and\n * truncating somebody's data to make a point is worse than saying what the places mean.\n */\nexport const MEANINGFUL_DECIMALS = 8\n\n/**\n * Whether a coordinate is in the southern or western half, including the value that cannot say so\n * for itself.\n *\n * **`-0` does not survive being displayed or stored.** Measured: `String(-0)` is `\"0\"`,\n * `(-0).toFixed(5)` is `\"0.00000\"` and `JSON.stringify(-0)` is `0`, while `-0 === 0` is `true` and\n * only `Object.is(-0, 0)` is `false`. A point on the equator at 0°00'00\"S, or on the prime\n * meridian at 0°00'00\"W, therefore loses its hemisphere the moment anything renders it — and no\n * comparison with `< 0` will find it again.\n *\n * So the sign is read through `Object.is` here, and the component carries the hemisphere letter as\n * its own piece of state rather than deriving it from the number on every keystroke. That is the\n * whole reason the letter is a control and not a decoration.\n */\nexport function signOf(degrees: number): -1 | 1 {\n  return degrees < 0 || Object.is(degrees, -0) ? -1 : 1\n}\n\n/** The hemisphere letter `degrees` falls in. */\nexport function hemisphereOf(degrees: number, axis: Axis): string {\n  return HEMISPHERES[axis][signOf(degrees) < 0 ? 1 : 0]\n}\n\n/**\n * Brings a longitude back inside ±180 without moving one that is already there.\n *\n * **The guard is the component, not an optimisation.** The formula everybody writes,\n * `((x + 180) % 360 + 360) % 360 - 180`, is correct for every out-of-range value and wrong for one\n * in-range value: measured, it turns `180` into `-180`. Those are the same meridian but not the\n * same answer — 180 is how the eastern side of the dateline is written, and a field that silently\n * rewrites a Fiji longitude to the western form has moved the reader's data while reporting\n * success. Worse in combination: rounding 179.9999999 to three decimal seconds lands on exactly\n * 180° (measured), so an unguarded wrap takes a point just short of the dateline and puts it on\n * the far side.\n *\n * Anything already in `[-180, 180]` is handed back untouched, sign of zero included. Only a value\n * outside it is folded, into `(-180, 180]`.\n */\nexport function wrapLongitude(degrees: number): number {\n  if (!Number.isFinite(degrees)) return Number.NaN\n  if (degrees >= -180 && degrees <= 180) return degrees\n  const folded = (((degrees + 180) % 360) + 360) % 360 - 180\n  // The fold sends an exact multiple of 360 to -180; 180 is the form that keeps the sign of the\n  // input, which is the half of the dateline the reader was on.\n  return folded === -180 && degrees > 0 ? 180 : folded\n}\n\nexport interface DmsParts {\n  /** -1 for the southern or western half. Separate from the numbers, so 0°S survives. */\n  sign: -1 | 1\n  degrees: number\n  minutes: number\n  seconds: number\n}\n\n/**\n * Splits a signed decimal degree into degrees, minutes and seconds.\n *\n * **The seconds are rounded before the carry, and the carry is the point.** Round afterwards and\n * the field prints times that do not exist: measured, 35.99999997222222° formatted naively is\n * `35°59'60.000\"`, because the seconds come out as 59.9999 and `(59.9995).toFixed(2)` is `\"60.00\"`.\n * Sixty seconds is not a reading. So the rounded seconds roll into the minutes and the rounded\n * minutes into the degrees, and the same value prints as `36°00'00.000\"`.\n *\n * `toFixed` is also not round-half-up, which is why the rounding has to happen in one declared\n * place rather than at each point of display: measured, `(1.005).toFixed(2)` is `\"1.00\"` and\n * `(2.675).toFixed(2)` is `\"2.67\"`, both a hair below the half because neither value is exactly\n * representable. Two call sites that each round will eventually disagree by one in the last place.\n */\nexport function toDmsParts(degrees: number, secondDigits = 3): DmsParts {\n  const sign = signOf(degrees)\n  const abs = Math.abs(degrees)\n  let d = Math.floor(abs)\n  const minutesFloat = (abs - d) * 60\n  let m = Math.floor(minutesFloat)\n  let s = Number(((minutesFloat - m) * 60).toFixed(secondDigits))\n  if (s >= 60) {\n    s = 0\n    m += 1\n  }\n  if (m >= 60) {\n    m = 0\n    d += 1\n  }\n  return { sign, degrees: d, minutes: m, seconds: s }\n}\n\n/** Puts degrees, minutes and seconds back together as a signed decimal degree. */\nexport function fromDmsParts({ sign, degrees, minutes, seconds }: DmsParts): number {\n  const magnitude = degrees + minutes / 60 + seconds / 3600\n  // `0 * -1` is `-0`, which is deliberate: it is the only way the southern zero exists at all, and\n  // `signOf` is built to find it again.\n  return sign < 0 ? -magnitude : magnitude\n}\n\n/**\n * Writes a coordinate as degrees, minutes and seconds with its hemisphere letter.\n *\n * The letter carries the sign rather than a leading `-`, because this is the notation people\n * paste out of a map and because it is the only form in which the southern zero is legible: `-0`\n * prints as `0` (measured) while `0°00'00.000\"S` says what it means.\n */\nexport function formatDms(degrees: number, axis: Axis, secondDigits = 3): string {\n  if (!Number.isFinite(degrees)) return \"\"\n  const p = toDmsParts(degrees, secondDigits)\n  const seconds = p.seconds.toFixed(secondDigits)\n  const padded = secondDigits > 0 ? seconds.padStart(secondDigits + 3, \"0\") : seconds.padStart(2, \"0\")\n  const letter = HEMISPHERES[axis][p.sign < 0 ? 1 : 0]\n  return `${p.degrees}°${String(p.minutes).padStart(2, \"0\")}'${padded}\"${letter}`\n}\n\n/** Writes a coordinate as a plain signed decimal degree, with the southern zero kept legible. */\nexport function formatDecimal(degrees: number, decimals = 6): string {\n  if (!Number.isFinite(degrees)) return \"\"\n  const text = Math.abs(degrees).toFixed(decimals)\n  return signOf(degrees) < 0 ? `-${text}` : text\n}\n\n/**\n * The characters that mean degree, minute, second and minus once a value has been pasted.\n *\n * Every one of these is in real data. `º` is U+00BA, the masculine ordinal, which is what a Mac\n * types with Option-0 and is not the degree sign U+00BA is mistaken for; `′` and `″` are the\n * typographic prime and double prime that map sites emit, against the `'` and `\"` a keyboard\n * produces; `−` is U+2212, the mathematical minus, which **`Number` refuses outright** (measured:\n * `Number(\"−35\")` is `NaN`). Normalising them is not tidying, it is the difference between\n * accepting a pasted coordinate and rejecting it for a character the reader cannot see.\n */\nconst NORMALISE: Record<string, string> = {\n  \"º\": \"°\", // º masculine ordinal -> degree sign\n  \"′\": \"'\", // prime\n  \"″\": '\"', // double prime\n  \"’\": \"'\", // right single quote\n  \"”\": '\"', // right double quote\n  \"−\": \"-\", // minus sign\n  \"–\": \"-\", // en dash\n  \"－\": \"-\", // fullwidth hyphen-minus\n  \"´\": \"'\", // acute accent\n}\n\nexport type CoordinateFormat = \"decimal\" | \"dms\"\n\nexport interface ParseResult {\n  /** The value, or `null` for an empty box, or `NaN` for text that is not a coordinate. */\n  degrees: number | null\n  /** Which notation it was read as. `null` when there was nothing to read. */\n  format: CoordinateFormat | null\n}\n\n/**\n * Reads one box as a coordinate on `axis`, in either notation.\n *\n * **Empty and wrong are kept apart.** An empty box is `null` and junk is `NaN`, because collapsing\n * them is what `Number` does — `Number(\"\")` is `0`, measured — and zero is a real coordinate off\n * the coast of Ghana. A cleared box that posts a point in the Gulf of Guinea is the single most\n * expensive mistake this component can make, and it is the default behaviour of the obvious\n * implementation.\n *\n * The grammar is strict for the reason this registry's `number-range-input` gives, and the list of\n * things `Number` accepts that nobody typed is worth naming because it is longer than it looks:\n * measured, `Number(\"1e3\")` is 1000, `Number(\"0x10\")` is 16, `Number(\"Infinity\")` is `Infinity`\n * and `Number(\" 35 \")` is 35. None of those is a latitude. `35.` and `.5` do pass, because that is\n * what a half-typed decimal looks like and a box that refuses them cannot be typed into.\n *\n * A hemisphere letter may lead or trail, and it is checked against the axis: `N` in a longitude\n * box is a mistake worth reporting, not a sign to apply. A letter and a `-` together contradict\n * each other (`-35S`) and are refused rather than resolved, since either reading loses half the\n * readers.\n */\nexport function parseCoordinate(text: string, axis: Axis): ParseResult {\n  let bare = \"\"\n  for (const char of text.trim()) bare += NORMALISE[char] ?? char\n  bare = bare.trim()\n  if (bare === \"\") return { degrees: null, format: null }\n\n  const [positive, negative] = HEMISPHERES[axis]\n  const other = HEMISPHERES[axis === \"lat\" ? \"lng\" : \"lat\"]\n  let letter: string | null = null\n\n  // The letter is taken from either end, once.\n  const head = bare[0]?.toUpperCase()\n  const tail = bare[bare.length - 1]?.toUpperCase()\n  const isAny = (c?: string) =>\n    c === positive || c === negative || c === other[0] || c === other[1]\n  if (isAny(head)) {\n    letter = head!\n    bare = bare.slice(1).trim()\n  } else if (isAny(tail)) {\n    letter = tail!\n    bare = bare.slice(0, -1).trim()\n  }\n  // A letter from the other axis is a mistake to report, not a sign to apply.\n  if (letter === other[0] || letter === other[1]) return { degrees: Number.NaN, format: null }\n\n  let sign: -1 | 1 = 1\n  if (bare[0] === \"+\" || bare[0] === \"-\") {\n    if (letter) return { degrees: Number.NaN, format: null }\n    sign = bare[0] === \"-\" ? -1 : 1\n    bare = bare.slice(1).trim()\n  } else if (letter === negative) {\n    sign = -1\n  }\n  if (bare === \"\") return { degrees: Number.NaN, format: null }\n\n  // Degrees-minutes-seconds, with the separators optional once the symbols are there.\n  const dms = /^(\\d+)\\s*°\\s*(?:(\\d+)\\s*'\\s*(?:(\\d+(?:\\.\\d+)?)\\s*\"?\\s*)?)?$/.exec(bare)\n  if (dms) {\n    const d = Number(dms[1])\n    const m = dms[2] === undefined ? 0 : Number(dms[2])\n    const s = dms[3] === undefined ? 0 : Number(dms[3])\n    // Sixty is the next unit up, not a reading; a paste carrying it is junk rather than something\n    // to normalise, because normalising it hides that the source was broken.\n    if (m >= 60 || s >= 60) return { degrees: Number.NaN, format: \"dms\" }\n    return { degrees: fromDmsParts({ sign, degrees: d, minutes: m, seconds: s }), format: \"dms\" }\n  }\n  // A space- or colon-separated triple, which is how a GIS export and a handheld GPS both write it.\n  const triple = /^(\\d+)[\\s:]+(\\d+)(?:[\\s:]+(\\d+(?:\\.\\d+)?))?$/.exec(bare)\n  if (triple) {\n    const m = Number(triple[2])\n    const s = triple[3] === undefined ? 0 : Number(triple[3])\n    if (m >= 60 || s >= 60) return { degrees: Number.NaN, format: \"dms\" }\n    return {\n      degrees: fromDmsParts({ sign, degrees: Number(triple[1]), minutes: m, seconds: s }),\n      format: \"dms\",\n    }\n  }\n  // Plain decimal degrees, with a trailing degree sign allowed because pasted values carry one.\n  const decimal = /^(\\d+(?:\\.\\d*)?|\\.\\d+)\\s*°?$/.exec(bare)\n  if (decimal) {\n    const magnitude = Number(decimal[1])\n    if (!Number.isFinite(magnitude)) return { degrees: Number.NaN, format: \"decimal\" }\n    return { degrees: sign < 0 ? -magnitude : magnitude, format: \"decimal\" }\n  }\n  return { degrees: Number.NaN, format: null }\n}\n\nexport interface AxisIssue {\n  axis: Axis\n  code: \"not-a-number\" | \"out-of-range\" | \"wrapped\"\n  message: string\n}\n\n/**\n * Judges one parsed value against its axis.\n *\n * **The two axes are judged differently, and neither is silently corrected.** Latitude past ±90 is\n * refused: there is no reading of 95°N that does not also move the longitude 180°, so clamping it\n * to 90 would put the point somewhere the reader did not ask for while reporting success.\n * Longitude past ±180 has an unambiguous reading — 181° is 179°W, the same meridian — so it is\n * offered as a correction (`wrapped`) rather than an error, and `wrapLongitude` is the thing that\n * does it, with the dateline guard described there.\n */\nexport function checkCoordinate(\n  degrees: number | null,\n  axis: Axis,\n  { wrap = true }: { wrap?: boolean } = {}\n): { value: number | null; issue: AxisIssue | null } {\n  if (degrees === null) return { value: null, issue: null }\n  const name = axis === \"lat\" ? \"Latitude\" : \"Longitude\"\n  if (!Number.isFinite(degrees)) {\n    return {\n      value: Number.NaN,\n      issue: { axis, code: \"not-a-number\", message: `${name} is not a coordinate.` },\n    }\n  }\n  const limit = AXIS_LIMIT[axis]\n  if (Math.abs(degrees) <= limit) return { value: degrees, issue: null }\n  if (axis === \"lng\" && wrap) {\n    const wrapped = wrapLongitude(degrees)\n    return {\n      value: wrapped,\n      issue: {\n        axis,\n        code: \"wrapped\",\n        message: `${formatDecimal(degrees, 4)}° is the same meridian as ${formatDecimal(wrapped, 4)}°.`,\n      },\n    }\n  }\n  return {\n    value: Number.NaN,\n    issue: {\n      axis,\n      code: \"out-of-range\",\n      message: `${name} runs from -${limit} to ${limit}.`,\n    },\n  }\n}\n\n/**\n * Whether the pair can only be the wrong way round.\n *\n * **This finds half the mistakes it is asked about, and saying which half is the honest part.** A\n * latitude past ±90 cannot be a latitude, so a Tokyo pair entered backwards (139.69 in the\n * latitude box) is caught outright. A London pair backwards is not: 51.5072 and -0.1276 are both\n * legal in both boxes, and so is every pair whose longitude is inside ±90 — which is half the\n * planet. Measured over six cities on five continents, four of the six were undetectable.\n *\n * So this is wired to a warning and an explicit swap control, and never to an automatic\n * correction. GeoJSON is the reason the mistake is so common — RFC 7946 writes a point as\n * `[longitude, latitude]`, the reverse of the order people say out loud — and an automatic fix\n * that is right half the time would move the other half of the data without telling anyone.\n */\nexport function looksSwapped(lat: number | null, lng: number | null): boolean {\n  // One guard, not two: `Number.isFinite(null)` is `false`, so a separate `=== null` check is the\n  // same condition written twice. Mutation testing found it by changing the `||` to `&&` in either\n  // line without any test noticing, which is what two spellings of one rule look like from outside.\n  if (!Number.isFinite(lat) || !Number.isFinite(lng)) return false\n  return Math.abs(lat as number) > AXIS_LIMIT.lat && Math.abs(lng as number) <= AXIS_LIMIT.lat\n}\n\n/** A sentence saying what the decimals on screen are worth at this latitude. */\nexport function precisionNote(decimals: number, atLat: number | null): string {\n  // Same single guard as `looksSwapped`: this catches `null` and `NaN` alike.\n  const lat = Number.isFinite(atLat) ? (atLat as number) : 0\n  const metres = metresForDecimals(decimals, \"lng\", lat)\n  const latMetres = metresForDecimals(decimals, \"lat\", lat)\n  // Each tier down to micrometres, because the tier is the answer. Stopping at centimetres prints\n  // \"0.0 cm\" for twelve decimal places, which is the one case this sentence exists to explain.\n  const say = (m: number) => {\n    if (m >= 1000) return `${(m / 1000).toFixed(m / 1000 >= 10 ? 0 : 1)} km`\n    if (m >= 1) return `${m.toFixed(m >= 10 ? 0 : 2)} m`\n    if (m >= 0.01) return `${(m * 100).toFixed(m * 100 >= 10 ? 0 : 1)} cm`\n    if (m >= 0.001) return `${(m * 1000).toFixed(1)} mm`\n    if (m >= 1e-6) return `${(m * 1e6).toFixed(m * 1e6 >= 10 ? 0 : 1)} \\u00b5m`\n    return \"less than a micrometre\"\n  }\n  const beyond =\n    decimals > MEANINGFUL_DECIMALS\n      ? \" — finer than any positioning system resolves, so the extra places are arithmetic, not accuracy\"\n      : \"\"\n  return `${decimals} decimal places: ${say(latMetres)} north-south, ${say(metres)} east-west at this latitude${beyond}.`\n}\n\nexport interface LatLng {\n  lat: number\n  lng: number\n}\n\nexport interface LatLngInputProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"onChange\" | \"defaultValue\"> {\n  /** The point, in signed decimal degrees. Controlled when supplied. */\n  value?: LatLng | null\n  defaultValue?: LatLng | null\n  /** Called with a complete, in-range point, or `null` while either box is empty or wrong. */\n  onValueChange?: (value: LatLng | null) => void\n  /** Which notation the boxes show. Typing the other one is always accepted. */\n  format?: CoordinateFormat\n  /** Decimal places shown in `decimal` format. */\n  decimals?: number\n  /** Decimal places on the seconds in `dms` format. */\n  secondDigits?: number\n  /** Offer to fold an out-of-range longitude onto its own meridian. */\n  wrapLongitudeBeyondRange?: boolean\n  /** Posts `lat` and `lng` as canonical signed decimal degrees, and posts nothing when invalid. */\n  name?: string\n  label?: string\n  disabled?: boolean\n}\n\nconst LABELS: Record<Axis, string> = { lat: \"Latitude\", lng: \"Longitude\" }\n\n/**\n * Two boxes for one point, which is a different component from two number fields.\n *\n * What it is for: registering a shop or site, a geofence, a collection point, a survey station or\n * drone waypoint, a wildlife or sensor observation, and checking the numbers after dragging a pin.\n * It takes decimal degrees or degrees-minutes-seconds in either box, in either order, and reports\n * what it could not read rather than quietly substituting zero.\n *\n * Within pulld, `geolocation-button` asks the device where it is and this asks a person where\n * something is; `number-range-input` holds one axis' worth of from-and-to, and `unit-input` one\n * value with its unit.\n */\nexport function LatLngInput({\n  value,\n  defaultValue = null,\n  onValueChange,\n  format = \"decimal\",\n  decimals = 6,\n  secondDigits = 3,\n  wrapLongitudeBeyondRange = true,\n  name,\n  label = \"Coordinates\",\n  disabled,\n  className,\n  ...rest\n}: LatLngInputProps) {\n  const isControlled = value !== undefined\n  const reactId = React.useId()\n  // `Number.isFinite` already answers `false` for `null`, so it is the whole guard — the third\n  // place in this file where a separate null check was the same condition written twice.\n  const write = (axis: Axis, v: number | null) =>\n    !Number.isFinite(v)\n      ? \"\"\n      : format === \"dms\"\n        ? formatDms(v as number, axis, secondDigits)\n        : formatDecimal(v as number, decimals)\n\n  const seed = isControlled ? value : defaultValue\n  const seedText: Record<Axis, string> = {\n    lat: write(\"lat\", seed?.lat ?? null),\n    lng: write(\"lng\", seed?.lng ?? null),\n  }\n  const [text, setText] = React.useState<Record<Axis, string>>(seedText)\n\n  // A controlled value that changes from outside is rewritten into the boxes, but only when it is\n  // a different point from the one on screen. Comparing the rendered text instead of the numbers\n  // is what keeps a half-typed \"35.\" from being erased by the parent echoing 35 back. Seeded from\n  // the same strings the boxes started with rather than a second copy of that expression.\n  const lastPushed = React.useRef<string>(`${seedText.lat}|${seedText.lng}`)\n  React.useEffect(() => {\n    if (!isControlled) return\n    const next = `${write(\"lat\", value?.lat ?? null)}|${write(\"lng\", value?.lng ?? null)}`\n    if (next === lastPushed.current) return\n    lastPushed.current = next\n    const [lat, lng] = next.split(\"|\")\n    setText({ lat, lng })\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [isControlled, value?.lat, value?.lng, format, decimals, secondDigits])\n\n  const parsed: Record<Axis, ParseResult> = {\n    lat: parseCoordinate(text.lat, \"lat\"),\n    lng: parseCoordinate(text.lng, \"lng\"),\n  }\n  const checkedLat = checkCoordinate(parsed.lat.degrees, \"lat\")\n  const checkedLng = checkCoordinate(parsed.lng.degrees, \"lng\", {\n    wrap: wrapLongitudeBeyondRange,\n  })\n  const issues = [checkedLat.issue, checkedLng.issue].filter(Boolean) as AxisIssue[]\n  const swapped = looksSwapped(parsed.lat.degrees, parsed.lng.degrees)\n  const complete =\n    checkedLat.value !== null &&\n    checkedLng.value !== null &&\n    Number.isFinite(checkedLat.value) &&\n    Number.isFinite(checkedLng.value)\n  const point: LatLng | null = complete\n    ? { lat: checkedLat.value as number, lng: checkedLng.value as number }\n    : null\n\n  // The parent hears about a point, not about a keystroke. Emitting on every edit would hand it\n  // `null` between the two boxes being filled, which reads as \"cleared\" to anything that stores it.\n  const lastEmitted = React.useRef<string>(\"\\u0000\")\n  React.useEffect(() => {\n    const key = point ? `${point.lat},${point.lng}` : \"null\"\n    if (key === lastEmitted.current) return\n    lastEmitted.current = key\n    onValueChange?.(point)\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [point?.lat, point?.lng])\n\n  const edit = (axis: Axis, next: string) => setText((t) => ({ ...t, [axis]: next }))\n\n  const swap = () => setText((t) => ({ lat: t.lng, lng: t.lat }))\n\n  const statusId = `${reactId}-status`\n  const noteId = `${reactId}-note`\n  const atLat = Number.isFinite(checkedLat.value as number) ? (checkedLat.value as number) : null\n\n  return (\n    <div\n      role=\"group\"\n      aria-label={label}\n      className={cn(\"flex w-full flex-col gap-2\", className)}\n      {...rest}\n    >\n      <div className=\"flex flex-wrap items-end gap-2\">\n        {([\"lat\", \"lng\"] as Axis[]).map((axis) => {\n          const issue = issues.find((i) => i.axis === axis)\n          const bad = issue?.code === \"not-a-number\" || issue?.code === \"out-of-range\"\n          return (\n            <div key={axis} className=\"flex min-w-[9rem] flex-1 flex-col gap-1\">\n              <label\n                htmlFor={`${reactId}-${axis}`}\n                className=\"text-xs font-medium text-muted-foreground\"\n              >\n                {LABELS[axis]}\n                <span className=\"sr-only\">\n                  {axis === \"lat\"\n                    ? \", north and south, -90 to 90\"\n                    : \", east and west, -180 to 180\"}\n                </span>\n              </label>\n              <input\n                id={`${reactId}-${axis}`}\n                // `type=\"text\"` rather than `type=\"number\"`: a number input discards text it cannot\n                // parse, so `35°41'22\"N` would vanish from under the reader instead of being read.\n                type=\"text\"\n                inputMode=\"text\"\n                autoComplete=\"off\"\n                spellCheck={false}\n                disabled={disabled}\n                value={text[axis]}\n                aria-invalid={bad || undefined}\n                aria-describedby={`${statusId} ${noteId}`}\n                placeholder={axis === \"lat\" ? \"35.689500\" : \"139.691700\"}\n                onChange={(e) => edit(axis, e.target.value)}\n                className={cn(\n                  \"h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors\",\n                  \"placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring\",\n                  \"disabled:cursor-not-allowed disabled:opacity-50\",\n                  bad && \"border-destructive focus-visible:ring-destructive\"\n                )}\n              />\n            </div>\n          )\n        })}\n        <button\n          type=\"button\"\n          onClick={swap}\n          disabled={disabled}\n          className={cn(\n            \"h-9 shrink-0 rounded-md border border-input px-3 text-xs font-medium transition-colors\",\n            \"hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring\",\n            \"disabled:cursor-not-allowed disabled:opacity-50\",\n            swapped && \"border-destructive text-destructive\"\n          )}\n        >\n          Swap\n          <span className=\"sr-only\"> latitude and longitude</span>\n        </button>\n      </div>\n\n      {/* One polite status line for the whole group: two live regions racing each other is how a\n          screen reader ends up reading neither. */}\n      <p\n        id={statusId}\n        role=\"status\"\n        aria-live=\"polite\"\n        className={cn(\n          \"text-xs\",\n          issues.some((i) => i.code !== \"wrapped\") || swapped\n            ? \"text-destructive\"\n            : \"text-muted-foreground\"\n        )}\n      >\n        {swapped\n          ? `That latitude is past ${AXIS_LIMIT.lat}°, so the two are the wrong way round. GeoJSON writes longitude first.`\n          : issues.length > 0\n            ? issues.map((i) => i.message).join(\" \")\n            : point\n              ? `${formatDms(point.lat, \"lat\", secondDigits)} ${formatDms(point.lng, \"lng\", secondDigits)} — ${formatDecimal(point.lat, decimals)}, ${formatDecimal(point.lng, decimals)}`\n              : \"Decimal degrees or degrees-minutes-seconds, either box.\"}\n      </p>\n      <p id={noteId} className=\"text-xs text-muted-foreground\">\n        {precisionNote(decimals, atLat)}\n      </p>\n\n      {name ? (\n        <>\n          <input\n            type=\"hidden\"\n            name={`${name}.lat`}\n            value={point ? formatDecimal(point.lat, Math.max(decimals, 6)) : \"\"}\n            disabled={!point}\n          />\n          <input\n            type=\"hidden\"\n            name={`${name}.lng`}\n            value={point ? formatDecimal(point.lng, Math.max(decimals, 6)) : \"\"}\n            disabled={!point}\n          />\n        </>\n      ) : null}\n    </div>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui",
  "docs": "Install any pulld component by name: add \"@pulld\": \"https://pulld.pages.dev/r/{name}.json\" to the registries block in components.json, then `npx shadcn add @pulld/<name>`. All 149 components: https://pulld.pages.dev/?utm_source=cli"
}
