{"version":3,"file":"generate-timezone-options.mjs","names":[],"sources":["../../../src/timezone-picker/generate-timezone-options.ts"],"sourcesContent":["/*!\n *\n *  Copyright (c) \"Neo4j\"\n *  Neo4j Sweden AB [http://neo4j.com]\n *\n *  This file is part of Neo4j.\n *\n *  Neo4j is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\nexport interface TimeZoneOption {\n  value: string;\n  label: string;\n  offset: string;\n  offsetMinutes: number;\n}\n\n/**\n * Gets the offset in minutes for a timezone at a specific date\n */\nconst getOffsetMinutes = (timezone: string, date: Date): number => {\n  try {\n    // Create dates in UTC and in the target timezone\n    const utcDate = new Date(date.toLocaleString('en-US', { timeZone: 'UTC' }));\n    const tzDate = new Date(\n      date.toLocaleString('en-US', { timeZone: timezone }),\n    );\n\n    // Calculate the difference in minutes\n    const diffMs = tzDate.getTime() - utcDate.getTime();\n    return Math.round(diffMs / (1000 * 60));\n  } catch {\n    return 0;\n  }\n};\n\n/**\n * Formats a UTC offset using the Intl API for consistent formatting\n * @param offsetHours - The offset in hours (can be fractional)\n * @returns Formatted UTC offset string (e.g., \"UTC+5:30\", \"UTC-3\")\n */\nconst formatUTCOffset = (offsetHours: number): string => {\n  if (offsetHours === 0) {\n    return 'UTC';\n  }\n\n  const sign = offsetHours >= 0 ? '+' : '-';\n  const absHours = Math.abs(offsetHours);\n  const hours = Math.floor(absHours);\n  const minutes = Math.round((absHours - hours) * 60);\n\n  // Use Intl.NumberFormat for consistent number formatting\n  const numberFormatter = new Intl.NumberFormat('en-US', {\n    maximumFractionDigits: 0,\n    minimumIntegerDigits: 1,\n  });\n\n  const formattedHours = numberFormatter.format(hours);\n  const formattedMinutes =\n    minutes > 0 ? `:${String(minutes).padStart(2, '0')}` : '';\n\n  return `UTC${sign}${formattedHours}${formattedMinutes}`;\n};\n\n/**\n * Extracts unique UTC offsets from all supported timezones using the Intl API\n * @param referenceDate - The date to use for calculating timezone offsets (defaults to current date)\n * @returns Set of unique offset values in minutes\n */\nconst getUniqueOffsetsFromAPI = (referenceDate?: Date): Set<number> => {\n  const uniqueOffsets = new Set<number>();\n  const now = referenceDate || new Date();\n\n  try {\n    // Get all supported timezones from the Intl API\n    const timezones = Intl.supportedValuesOf('timeZone');\n\n    // Extract unique offsets from each timezone\n    for (const tz of timezones) {\n      try {\n        const offsetMinutes = getOffsetMinutes(tz, now);\n        uniqueOffsets.add(offsetMinutes);\n      } catch {\n        // Skip timezones that can't be processed\n        continue;\n      }\n    }\n  } catch {\n    // Fallback to empty set if API is not available\n  }\n\n  // Always include UTC (offset 0)\n  uniqueOffsets.add(0);\n\n  return uniqueOffsets;\n};\n\n/**\n * Generates UTC-only timezone options derived from the Intl API\n * Uses the Intl API to discover which UTC offsets are actually used by supported timezones\n * @param referenceDate - The date to use for calculating timezone offsets (defaults to current date)\n */\nexport const generateUTCTimeZoneOptions = (\n  referenceDate?: Date,\n): TimeZoneOption[] => {\n  // Get unique offsets from all supported timezones via the Intl API\n  const uniqueOffsets = getUniqueOffsetsFromAPI(referenceDate);\n\n  // Convert offset minutes to hours (can be fractional)\n  const offsetHours = Array.from(uniqueOffsets)\n    .map((minutes) => minutes / 60)\n    .sort((offsetA, offsetB) => offsetA - offsetB);\n\n  // Convert to TimeZoneOption format\n  const options: TimeZoneOption[] = offsetHours.map((offsetHours) => {\n    const offsetStr = formatUTCOffset(offsetHours);\n\n    return {\n      label: offsetStr,\n      offset: offsetStr,\n      offsetMinutes: Math.round(offsetHours * 60),\n      value: offsetStr,\n    };\n  });\n\n  return options;\n};\n\n/**\n * Generates a list of common timezone options with their UTC offsets\n * @param referenceDate - The date to use for calculating timezone offsets (defaults to current date)\n * @param excludeUTC - Whether to exclude the UTC timezone from the list (useful when combining with UTC-only options)\n */\nexport const generateTimeZoneOptions = (\n  referenceDate?: Date,\n  excludeUTC = false,\n): TimeZoneOption[] => {\n  // Common timezones with their IANA identifiers\n  const timezones = Intl.supportedValuesOf('timeZone');\n\n  const now = referenceDate || new Date();\n\n  // Filter out UTC if requested\n  const filteredTimezones = excludeUTC\n    ? timezones.filter((tz) => tz !== 'UTC')\n    : timezones;\n\n  return filteredTimezones\n    .map((tz) => {\n      try {\n        // Get the offset for this timezone\n        const formatter = new Intl.DateTimeFormat('en-US', {\n          timeZone: tz,\n          timeZoneName: 'shortOffset',\n        });\n\n        const parts = formatter.formatToParts(now);\n        const offsetPart = parts.find((part) => part.type === 'timeZoneName');\n        const offset = offsetPart?.value ?? '';\n\n        // Calculate offset in minutes for proper sorting\n        const offsetMinutes = getOffsetMinutes(tz, now);\n\n        // Format the label\n        const cityName = tz.split('/').pop()?.replace(/_/g, ' ') ?? tz;\n        const label = `${cityName} (${offset})`;\n\n        return {\n          label,\n          offset,\n          offsetMinutes,\n          value: tz,\n        };\n      } catch {\n        // Fallback if timezone is not supported\n        return {\n          label: tz.replace(/_/g, ' '),\n          offset: '',\n          offsetMinutes: 0,\n          value: tz,\n        };\n      }\n    })\n    .sort((optionA, optionB) => {\n      // Sort by offset (negative to positive), then by label\n      if (optionA.offsetMinutes !== optionB.offsetMinutes) {\n        return optionA.offsetMinutes - optionB.offsetMinutes;\n      }\n\n      return optionA.label.localeCompare(optionB.label);\n    });\n};\n\n/**\n * Gets the user's current timezone\n */\nexport const getUserTimeZone = (): string => {\n  try {\n    return Intl.DateTimeFormat().resolvedOptions().timeZone;\n  } catch {\n    return 'UTC';\n  }\n};\n\n/**\n * Parses a custom UTC offset string (e.g., \"UTC+5:30\", \"UTC-3:45\")\n * @param input - The input string to parse\n * @returns The parsed timezone value or null if invalid\n */\nexport const parseCustomUTCOffset = (input: string): string | null => {\n  // Match patterns like: UTC+5:30, UTC-3:45, UTC+1, UTC-12, etc.\n  // Also accepts single digit minutes which will be padded\n  const utcPattern = /^UTC([+-])?(\\d{1,2})(?::(\\d{1,2}))?$/i;\n  const match = input.trim().match(utcPattern);\n\n  if (!match) {\n    return null;\n  }\n\n  const sign = match[1] === '-' ? '-' : '+';\n  const hours = parseInt(match[2], 10);\n  const minutes = match[3] ? parseInt(match[3], 10) : 0;\n\n  // Validate ranges based on sign\n  if (sign === '+') {\n    if (hours < 0 || hours > 14) {\n      return null;\n    }\n    if (hours === 14 && minutes > 0) {\n      return null;\n    } // UTC+14 is max\n  } else {\n    // sign === '-'\n    if (hours < 0 || hours > 12) {\n      return null;\n    } // UTC-12 is min\n    if (hours === 12 && minutes > 0) {\n      return null;\n    } // UTC-12 is min\n  }\n\n  if (minutes < 0 || minutes > 59) {\n    return null;\n  }\n\n  return `UTC${sign}${hours}${minutes > 0 ? `:${String(minutes).padStart(2, '0')}` : ''}`;\n};\n\n/**\n * Validates if a string is a valid UTC timezone format\n * @param input - The input string to validate\n * @returns True if valid UTC timezone format\n */\nexport const isValidUTCFormat = (input: string): boolean => {\n  return parseCustomUTCOffset(input) !== null || input.toUpperCase() === 'UTC';\n};\n\n/**\n * Formats a timezone for display\n * @param timezone - The IANA timezone identifier or UTC offset\n * @param referenceDate - The date to use for calculating the offset (defaults to current date)\n */\nexport const formatTimeZone = (\n  timezone: string,\n  referenceDate?: Date,\n): string => {\n  // If it's already a UTC format, return as-is\n  if (timezone.toUpperCase().startsWith('UTC')) {\n    return timezone;\n  }\n\n  try {\n    const now = referenceDate || new Date();\n    const formatter = new Intl.DateTimeFormat('en-US', {\n      timeZone: timezone,\n      timeZoneName: 'shortOffset',\n    });\n\n    const parts = formatter.formatToParts(now);\n    const offsetPart = parts.find((part) => part.type === 'timeZoneName');\n    const offset = offsetPart?.value ?? '';\n\n    const cityName = timezone.split('/').pop()?.replace(/_/g, ' ') ?? timezone;\n    return `${cityName} (${offset})`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