💡

In this article, I will explain the UX features implemented in the Astro blog with code.

Introduction

To improve the blog user experience, “I have implemented the following 10 features.

FeatureDescription
Reading Position SaveAllows continuing reading from where you left off on next visit
Floating ShareOne-tap sharing on mobile
Code Copy ButtonCopy functionality for code blocks
Keyboard ShortcutsJump to search with Cmd+K
Toast NotificationsOperation feedback display
Reading Progress BarVisualizes how far you’ve read in an article
Table of Contents ScrollspyHighlights the section you are currently reading
Print StylesOptimization for printing articles
Dark Mode SupportTheme switching via CSS variables
View TrackingCounts via Astro DB

1. Saving Reading Position

A feature that proposes “Would you like to continue reading from where you left off?” when a user revisits after leaving mid-article.

// ReadingPositionSave.astro (Excerpt)
const slug = window.location.pathname.split(").filter(Boolean).pop();
const storageKey = `reading-position-${slug}`;

// Save scroll position
window.addEventListener("scroll", () => {
 const percent = (scrollTop / docHeight) * 100;
 localStorage.setItem(storageKey, String(percent));
});

Key Points:

  • Persistence of position via localStorage
  • Propose restoration only if read within last 24 hours & more than 10%
  • Automatically close toast after 5 seconds

2. Floating Share Button

A floating button displayed when scrolling on mobile.

User
User

Share buttons are hard to press on mobile.

Bot
Bot

With a floating button, “it”s always displayed within reach of your thumb!

Supported Platforms:

  • X (Twitter)
  • LINE
  • Link Copy

3. Code Copy Button

Automatically adds a copy button to all <pre> tags.

// CopyCodeButton.astro
document.querySelectorAll("pre").forEach((block) => {
 const button = document.createElement("button");
 button.textContent = "Copy";
 button.addEventListener("click", async () => {
 await navigator.clipboard.writeText(block.textContent);
 button.textContent = "Copied!";
 });
 block.appendChild(button);
});

4. Keyboard Shortcuts

Shortcut functions for power users.

ShortcutAction
Cmd/Ctrl + KFocus on search
EscapeBlur from search
/Focus on search

5. Toast Notification System

Notifications can be displayed from anywhere via window.showToast().

// Usage Example
window.showToast({
 message: "Copied", type: "success", // success, error, info, warning
 duration: 3000,
});

Summary

These features are integrated in PostLayout.astro and are automatically enabled on all article pages.

All Component List
  • ReadingProgress.astro - FloatingShare.astro - CopyCodeButton.astro - KeyboardShortcuts.astro - Toast.astro - ReadingPositionSave.astro - ViewCounter.astro

Next time, I will explain the implementation of view tracking in detail.