Skip to content

Add offline hourly weather fallback using stored forecast data #116#123

Open
numericals-org wants to merge 2 commits into
prem-k-r:mainfrom
numericals-org:WeatherOffline
Open

Add offline hourly weather fallback using stored forecast data #116#123
numericals-org wants to merge 2 commits into
prem-k-r:mainfrom
numericals-org:WeatherOffline

Conversation

@numericals-org
Copy link
Copy Markdown

@numericals-org numericals-org commented Jan 16, 2026

Switch Weather Data Handling to Use Forecast Endpoint Fully (Offline Support) #116

📌 Description

This PR improves the weather feature by utilizing the hourly forecast data already returned by the WeatherAPI forecast endpoint.

In addition to the current weather, the extension now stores today’s hourly forecast locally and uses it as a fallback when the user is offline.

When offline, the extension displays the forecast for the current hour (e.g., 12:15 → shows 12:00 data) instead of showing no weather information.
This enhances usability, reliability, and the overall user experience without increasing API usage.


🎨 Visual Changes (Screenshots / Videos)

#Offline
image

#Online
image


🔗 Related Issues

  • Closes #<issue_number>
  • Related to #<issue_number>

✅ Checklist

  • I have read and followed the Contributing Guidelines.
  • My code follows the project's coding style and conventions.
  • I have tested my changes thoroughly to ensure expected behavior.
  • I have verified compatibility across Chrome and Firefox.
  • I have attached relevant visual evidence (screenshots/videos) if applicable.
  • I have updated the CHANGELOG.md under the appropriate categories with all my changes in this PR.

Summary

This PR adds offline support to the weather feature by implementing an hourly forecast fallback mechanism. When the user is offline, the extension displays weather information for the current hour using cached forecast data from the WeatherAPI endpoint, rather than showing no weather information.

Changes

Core Feature:

  • Implemented offline detection that retrieves and displays cached forecast data when internet connectivity is unavailable
  • Caches today's hourly forecast data locally using updated localStorage keys (e.g., weatherParsedLocation, weatherParsedData, weatherParsedTime, weatherParsedLang)
  • When offline, derives and displays the current hour's forecast including temperature, condition text, humidity, and feels-like values

Weather Data Management:

  • Refactored the getWeatherData flow with more modular rendering and caching logic
  • Improved localStorage interaction with updated cache key naming conventions
  • Enhanced language-aware formatting for weather data presentation, including temperature unit handling (°C/°F) and RTL language support

Location and API Integration:

  • Integrated location suggestion fetching from Weather API with keyboard navigation (ArrowUp/Down, Enter)
  • Added Enter-key handling for saving API keys and location data
  • Improved GPS toggle flow to update localStorage and reload the extension
  • Implemented click-outside behavior and focus handling for location suggestions

UI and Localization:

  • Reorganized visibility and disable state logic
  • Updated weather icon handling with fallback to defaultWeather.svg on error
  • Improved humidity slider sizing based on dynamic language-specific adjustments
  • Enhanced temperature, humidity, and icon rendering with better localization support

Technical Details

  • Files Modified: scripts/weather.js (+871/-544 lines)
  • Backward Compatibility: Maintained across Chrome and Firefox
  • Documentation: CHANGELOG.md updated
  • Testing: Screenshots/videos added demonstrating both online and offline weather displays

Impact

  • Improves user experience by displaying relevant weather data even when offline
  • No increase in API usage as it leverages existing forecast data already provided by the WeatherAPI
  • Maintains data freshness by caching today's hourly forecast alongside timestamp and language metadata

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jan 16, 2026

📝 Walkthrough

Walkthrough

Substantial rewrite of weather module logic in scripts/weather.js introducing location suggestion system with API integration, enhanced GPS-based location handling, offline data caching from forecast API, and language-aware formatting for temperature displays, humidity labels, and UI rendering.

Changes

Cohort / File(s) Summary
UI Initialization and State Management
scripts/weather.js
Reworked weather UI initialization with adjusted DOM element retrieval and state application. Replaced inline toggling calls with updated equivalents for visibility and disable logic; formatting and argument handling refined while preserving functional flow.
Location Suggestion System
scripts/weather.js
Introduced comprehensive location suggestion feature: fetches suggestions from Weather API, renders dynamic suggestion list, implements keyboard navigation (ArrowUp/Down, Enter), selection logic, focus/input handling, and click-outside dismissal behavior. Replaces identifier weatherLocation with weatherParsedLocation.
GPS and Location Handling
scripts/weather.js
Reworked GPS toggle flow with updated async handling. GPS disclaimer prompt integrated into new flow; enabling/disabling now explicitly updates localStorage and UI state followed by page reload. Introduces broader user input handling for API and location data with Enter-key support.
Weather Data Caching and Offline Support
scripts/weather.js
Implemented robust offline mode leveraging cached forecast data. Adds localStorage caching for parsed weather data (weatherParsedData), timestamps, location, and language. When offline, derives and renders current hour forecast, condition text, temperatures, humidity, and feels-like values from cached hourly data instead of failing.
Localization and Responsive Rendering
scripts/weather.js
Enhanced language-aware formatting: temperature unit handling (°C/°F) with per-language spacing nuances; RTL-aware humidity label presentation; dynamic slider sizing based on humidity and language preferences. Rewritten icon URL handling with fallback to defaultWeather.svg.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant WeatherUI as Weather Module
    participant API as Weather/Forecast API
    participant Storage as localStorage
    participant Network

    User->>WeatherUI: Enter location/open app
    WeatherUI->>WeatherUI: Check cache validity
    alt Cache Valid & Online
        WeatherUI->>Storage: Retrieve cached weather data
        WeatherUI->>WeatherUI: Render from cache
        WeatherUI->>User: Display weather
    else Offline
        WeatherUI->>Storage: Retrieve cached forecast data
        WeatherUI->>WeatherUI: Extract current hour from forecast
        WeatherUI->>User: Render offline weather from cache
    else Online & Needs Refresh
        User->>WeatherUI: Request location suggestions
        WeatherUI->>API: Fetch location suggestions
        API-->>WeatherUI: Return suggestions list
        WeatherUI->>User: Display suggestions
        User->>WeatherUI: Select location
        WeatherUI->>API: Fetch weather & forecast data
        API-->>WeatherUI: Return weather & hourly forecast
        WeatherUI->>Storage: Cache weather data & forecast
        WeatherUI->>User: Render updated weather
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

  • Issue #116: Directly addresses the offline weather rendering feature by caching hourly forecast data from the Forecast API and using it to render current-hour weather conditions when the application is offline.
🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The pull request title clearly and specifically describes the main change: adding offline fallback functionality using stored hourly forecast data, which aligns with the core modifications in the changeset.
Docstring Coverage ✅ Passed Docstring coverage is 82.35% which is sufficient. The required threshold is 80.00%.
Description check ✅ Passed The PR description is comprehensive and well-structured, covering objectives, visual evidence, and a completed checklist.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Fix all issues with AI agents
In `@scripts/weather.js`:
- Around line 466-483: getForecastForNow() can return undefined causing a crash
when accessing properties; in the offline branch that checks !navigator.onLine,
first guard that the result of getForecastForNow() (from
parsedData.forecast.forecastHours) exists and early-return or fall back to
parsedData.current, then read the hourly icon from the hourly object (use
data.condition.icon) instead of parsedData.current.condition.icon; update the
same guard/fallback logic for the similar offline block around the later code
(the block at ~607-612) to avoid undefined access.
- Around line 74-80: The code loads savedLocation from weatherParsedLocation but
saveLocButton writes weatherLocation, causing manual entries to be ignored;
change the load and assignment so user input and currentUserLocation use
weatherLocation (e.g., read localStorage.getItem("weatherLocation") into
savedLocation and assign userLocInput.value and currentUserLocation from that),
and reserve weatherParsedLocation only for parsed/cache validation logic; update
any save paths (saveLocButton handler, and places that set currentUserLocation)
to consistently read/write weatherLocation while leaving weatherParsedLocation
for parsed-cache checks.
- Around line 90-103: The Enter key handler handleEnterPress currently triggers
a button click even when the suggestion list has focus; update handleEnterPress
(used by userAPIInput and userLocInput) to first detect if a suggestion is
active and, if so, return without clicking. Implement the gate by checking
common suggestion indicators used by your UI (for example: an element with a
highlighted/active suggestion class, an open suggestion list role/aria-expanded
on the input, or an aria-activedescendant on the input) and only call
document.getElementById(buttonId).click() when no active suggestion is present.
- Around line 391-399: The refresh condition currently triggers a network fetch
even when offline (so the thrown fetch error prevents falling back to cached
UI); update the refresh gating around the block that checks parsedData,
weatherParsedTime, weatherParsedLocation, and weatherParsedLang to require
navigator.onLine before attempting a network refresh, and if navigator.onLine is
false allow rendering cached parsedData (even if stale) instead of attempting
fetch; ensure retentionTime logic (retentionTime variable) remains used only to
decide freshness when online and that fetch attempts are only made when
navigator.onLine is true.
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0aaedb3 and 628eeb2.

📒 Files selected for processing (1)
  • scripts/weather.js
🧰 Additional context used
🧬 Code graph analysis (1)
scripts/weather.js (2)
scripts/languages.js (3)
  • translations (10-42)
  • isRTL (364-364)
  • feelsLikeElement (376-376)
scripts/alert-modal.js (2)
  • agreeText (151-151)
  • cancelText (152-152)
🔇 Additional comments (1)
scripts/weather.js (1)

943-948: The scope analysis in this comment is incorrect. minMaxTempCheckbox is declared at the top-level (line 82), not inside getWeatherData. Since both the declaration and event handler are in the same scope, there is no ReferenceError risk here. No changes are needed to this code.

Likely an incorrect or invalid review comment.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

Comment thread scripts/weather.js
Comment thread scripts/weather.js
Comment thread scripts/weather.js
Comment thread scripts/weather.js
@numericals-org
Copy link
Copy Markdown
Author

Morning @prem-k-r

Just following up on this PR in case it was missed.

Whenever you have time, I’d appreciate your feedback.

Thanks!

@prem-k-r
Copy link
Copy Markdown
Owner

Sure, I'll have a look next week

@numericals-org
Copy link
Copy Markdown
Author

Thank you, I appreciate it!

@SharadhNaidu
Copy link
Copy Markdown

@prem-k-r can you please assign this pr to me ?

Thank you.

@prem-k-r
Copy link
Copy Markdown
Owner

@prem-k-r can you please assign this pr to me ?

Thank you.

Not at the moment. I haven’t reviewed this PR yet, and it’s not in an abandoned state that can be discarded where it can be reassigned.
But, please feel free to review the PR and share any suggestions :)

@numericals-org
Copy link
Copy Markdown
Author

Morning @prem-k-r
Thank you, I appreciate it!

@prem-k-r prem-k-r added enhancement New feature or request under-review Currently being reviewed. Please wait for feedback. labels Jan 27, 2026
@numericals-org
Copy link
Copy Markdown
Author

Morning @prem-k-r
Just checking in on this PR.
Let me know if any changes are needed from my side. Thanks!

@prem-k-r
Copy link
Copy Markdown
Owner

prem-k-r commented Feb 2, 2026

@numericals-org, apologies I am busy in work, I'll take a look when I got some free time for the review.

@Devyaansh2
Copy link
Copy Markdown

Devyaansh2 commented Feb 2, 2026

Morning @prem-k-r
For sure

@numericals-org
Copy link
Copy Markdown
Author

Morning @prem-k-r
Just checking in on this PR.
Let me know if any changes are needed from my side. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request under-review Currently being reviewed. Please wait for feedback.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Switch Weather Data Handling to Use Forecast Endpoint Fully (Offline Support)

4 participants