Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow viewing offline PWA #31

Merged
merged 1 commit into from
Nov 10, 2024
Merged

Allow viewing offline PWA #31

merged 1 commit into from
Nov 10, 2024

Conversation

5ouma
Copy link
Owner

@5ouma 5ouma commented Nov 10, 2024

⚠️ Issue

close #


✏️ Description

Cache all files locally including fonts and images.


🔄 Type of the Change

  • 🎉 New Feature
  • 🧰 Bug
  • 🛡️ Security
  • 📖 Documentation
  • 🏎️ Performance
  • 🧹 Refactoring
  • 🧪 Testing
  • 🔧 Maintenance
  • 🎽 CI
  • 🧠 Meta

Cache all files locally includes fonts and images.
@prlabeler prlabeler bot added the 🎉 New Feature Introduce a new feature label Nov 10, 2024
Copy link

coderabbitai bot commented Nov 10, 2024

Walkthrough

The pull request introduces enhancements to the Astro project configuration, specifically for the AstroPWA integration in astro.config.ts, by adding a comprehensive caching setup. It also updates the TypeScript definitions in src/env.d.ts to include types from vite-plugin-pwa/client, improving type support. Additionally, a service worker registration script is added to src/layouts/Layout.astro, enabling better Progressive Web App (PWA) functionality.

Changes

File Change Summary
astro.config.ts Added workbox configuration with properties for caching, including maximumFileSizeToCacheInBytes, globPatterns, navigateFallback, and runtimeCaching.
src/env.d.ts Added a reference to vite-plugin-pwa/client for TypeScript type recognition.
src/layouts/Layout.astro Introduced a <script> block to register a service worker using registerSW, including a callback for updates.

Possibly related PRs


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between cfe8c23 and 47595c2.

📒 Files selected for processing (3)
  • astro.config.ts (1 hunks)
  • src/env.d.ts (1 hunks)
  • src/layouts/Layout.astro (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/env.d.ts
🔇 Additional comments (2)
astro.config.ts (1)

Line range hint 12-21: LGTM: PWA manifest configuration is well-structured.

The manifest configuration includes all necessary fields and follows PWA best practices.

src/layouts/Layout.astro (1)

Line range hint 2-2: LGTM: PWA setup is properly configured.

The PWA information is correctly imported and utilized in the layout template.

Also applies to: 2-2


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Nov 10, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (cfe8c23) to head (47595c2).
Report is 1 commits behind head on main.

✅ All tests successful. No failed tests found.

Additional details and impacted files
@@            Coverage Diff            @@
##              main       #31   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           11        11           
  Lines          153       153           
  Branches        16        16           
=========================================
  Hits           153       153           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Contributor

🔦 Lighthouse Result

performance accessibility best-practices seo
🟢 100 🟢 100 🟢 100 🟧 63
📊 Score Scale
Fail Average Pass
🔺 0-49 🟧 50-89 🟢 90-100

Copy link

@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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (1)
src/layouts/Layout.astro (1)

PWA configuration needs icon assets and manifest file

The PWA configuration is incomplete. While the service worker and PWA integration are properly set up in astro.config.ts, critical assets are missing:

  • No PWA icons found in the public/icons/ directory
  • No manifest file present in the public directory
  • The configuration references icons through meta.icon, but the actual icon assets are not present

Required actions:

  • Add PWA icons in various sizes to public/icons/
  • Ensure the manifest file is generated or present in the public directory
  • Verify that meta.icon path in the configuration points to an existing icon
🔗 Analysis chain

Line range hint 2-2: Verify PWA prerequisites are complete.

Let's ensure all required PWA assets and configurations are in place.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify PWA configuration completeness

# Check for manifest file
echo "Checking for manifest file..."
fd -e webmanifest -e json . public/

# Check for PWA icons
echo "Checking for PWA icons..."
fd -e png -e ico . public/

# Check for service worker configuration in astro config
echo "Checking for service worker configuration..."
rg "defineConfig|AstroPWA" -A 10 "astro.config"

# Check for PWA types
echo "Checking for PWA types..."
rg "virtual:pwa" "src/env.d.ts"

Length of output: 487


Script:

#!/bin/bash
# Let's check for astro config with different extensions and manifest files in root
echo "Checking for astro config..."
fd "astro.config" .

echo "Checking for manifest in root..."
fd "manifest" .

# Check for PWA-related imports and configurations
echo "Checking PWA imports and configurations..."
rg "import.*pwa|pwa.*import" .

# Check for service worker registrations
echo "Checking service worker..."
rg "registerSW|serviceWorker" .

# Check package.json for PWA dependencies
echo "Checking PWA dependencies..."
rg "@vite-pwa|@astrojs/pwa" package.json

Length of output: 977


Script:

#!/bin/bash
# Let's check the astro config for PWA configuration
echo "Checking PWA configuration in astro.config.ts..."
cat astro.config.ts

# Check for manifest content
echo "Checking for manifest content in public directory..."
fd -e webmanifest -e json . public/ -x cat {}

# Check for icon assets
echo "Checking for icon assets..."
fd -t f . public/icons/ || echo "No icons directory found"

Length of output: 1844

🛑 Comments failed to post (3)
astro.config.ts (2)

23-25: 🛠️ Refactor suggestion

Review and adjust caching configuration for better offline experience.

The current configuration has several potential limitations:

  1. The 2.2MB cache size limit might be too restrictive for a PWA that needs to work offline
  2. The globPatterns are missing critical file types like CSS, SVG, PNG, and other image formats

Consider applying these improvements:

- maximumFileSizeToCacheInBytes: 1024 * 1024 * 2.2,
- globPatterns: ["**/*.{html,js,woff2}"],
+ maximumFileSizeToCacheInBytes: 1024 * 1024 * 5, // Increased to 5MB
+ globPatterns: ["**/*.{html,js,css,woff2,png,svg,jpg,jpeg,gif,ico}"],

Also, consider creating a dedicated offline fallback page:

- navigateFallback: "/",
+ navigateFallback: "/offline.html",

Committable suggestion skipped: line range outside the PR's diff.


26-32: 🛠️ Refactor suggestion

Optimize caching strategies for different resource types.

The current configuration uses a single NetworkFirst strategy with a misleading cache name for all resources. This approach isn't optimal for PWA performance.

Consider implementing different strategies for different resource types:

  runtimeCaching: [
    {
-     handler: "NetworkFirst",
-     options: { cacheName: "icon" },
-     urlPattern: () => true,
+     urlPattern: /\.(png|jpg|jpeg|svg|gif|ico)$/i,
+     handler: "CacheFirst",
+     options: {
+       cacheName: "images",
+       expiration: {
+         maxEntries: 50,
+         maxAgeSeconds: 30 * 24 * 60 * 60 // 30 days
+       }
+     }
    },
+   {
+     urlPattern: /\.(js|css|woff2)$/i,
+     handler: "StaleWhileRevalidate",
+     options: {
+       cacheName: "static-resources",
+       expiration: {
+         maxEntries: 30,
+         maxAgeSeconds: 7 * 24 * 60 * 60 // 7 days
+       }
+     }
+   },
+   {
+     urlPattern: /^https:\/\/api\./i,
+     handler: "NetworkFirst",
+     options: {
+       cacheName: "api-cache",
+       networkTimeoutSeconds: 10,
+       expiration: {
+         maxEntries: 50,
+         maxAgeSeconds: 24 * 60 * 60 // 1 day
+       }
+     }
+   }
  ],

This configuration:

  • Uses CacheFirst for images
  • Uses StaleWhileRevalidate for static resources
  • Uses NetworkFirst for API calls
  • Adds appropriate cache expiration policies
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      runtimeCaching: [
        {
          urlPattern: /\.(png|jpg|jpeg|svg|gif|ico)$/i,
          handler: "CacheFirst",
          options: {
            cacheName: "images",
            expiration: {
              maxEntries: 50,
              maxAgeSeconds: 30 * 24 * 60 * 60 // 30 days
            }
          }
        },
        {
          urlPattern: /\.(js|css|woff2)$/i,
          handler: "StaleWhileRevalidate",
          options: {
            cacheName: "static-resources",
            expiration: {
              maxEntries: 30,
              maxAgeSeconds: 7 * 24 * 60 * 60 // 7 days
            }
          }
        },
        {
          urlPattern: /^https:\/\/api\./i,
          handler: "NetworkFirst",
          options: {
            cacheName: "api-cache",
            networkTimeoutSeconds: 10,
            expiration: {
              maxEntries: 50,
              maxAgeSeconds: 24 * 60 * 60 // 1 day
            }
          }
        }
      ],
src/layouts/Layout.astro (1)

64-73: 🛠️ Refactor suggestion

Improve service worker registration and update handling.

The current implementation has several areas for improvement:

  1. The automatic update without user consent could disrupt the user experience
  2. Missing error handling for service worker registration
  3. No visual feedback during updates
  4. No indication of offline availability

Consider implementing this enhanced version:

 <script>
   import { registerSW } from "virtual:pwa-register";
   if ("serviceWorker" in navigator) {
     const updateSW = registerSW({
       onNeedRefresh() {
-        updateSW(true);
+        // Show update notification to user
+        if (confirm('New content available. Reload to update?')) {
+          updateSW(true);
+        }
+      },
+      onRegistered(r) {
+        // Optionally show offline capability notification
+        console.log('SW registered:', r);
+      },
+      onRegisterError(error) {
+        console.error('SW registration error:', error);
       },
     });
   }
 </script>

+<script>
+  // Add offline detection
+  window.addEventListener('online', () => {
+    document.body.classList.remove('offline');
+  });
+  window.addEventListener('offline', () => {
+    document.body.classList.add('offline');
+  });
+</script>
+
+<style>
+  /* Add offline indicator styles */
+  body.offline::before {
+    content: 'Offline Mode';
+    position: fixed;
+    top: 1rem;
+    right: 1rem;
+    background: var(--background);
+    padding: 0.5rem 1rem;
+    border-radius: 0.5rem;
+    z-index: 1000;
+  }
+</style>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

<script>
  import { registerSW } from "virtual:pwa-register";
  if ("serviceWorker" in navigator) {
    const updateSW = registerSW({
      onNeedRefresh() {
        // Show update notification to user
        if (confirm('New content available. Reload to update?')) {
          updateSW(true);
        }
      },
      onRegistered(r) {
        // Optionally show offline capability notification
        console.log('SW registered:', r);
      },
      onRegisterError(error) {
        console.error('SW registration error:', error);
      },
    });
  }
</script>

<script>
  // Add offline detection
  window.addEventListener('online', () => {
    document.body.classList.remove('offline');
  });
  window.addEventListener('offline', () => {
    document.body.classList.add('offline');
  });
</script>

<style>
  /* Add offline indicator styles */
  body.offline::before {
    content: 'Offline Mode';
    position: fixed;
    top: 1rem;
    right: 1rem;
    background: var(--background);
    padding: 0.5rem 1rem;
    border-radius: 0.5rem;
    z-index: 1000;
  }
</style>

@5ouma 5ouma merged commit feaf663 into main Nov 10, 2024
12 checks passed
@5ouma 5ouma deleted the feat-pwa-offline branch November 10, 2024 11:00
@github-actions github-actions bot mentioned this pull request Nov 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🎉 New Feature Introduce a new feature
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant