lightfriend-add-frontend-page

Step-by-step guide for adding new pages to the Yew frontend

16 stars

Best use case

lightfriend-add-frontend-page is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Step-by-step guide for adding new pages to the Yew frontend

Teams using lightfriend-add-frontend-page should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/lightfriend-add-frontend-page/SKILL.md --create-dirs "https://raw.githubusercontent.com/diegosouzapw/awesome-omni-skill/main/skills/development/lightfriend-add-frontend-page/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/lightfriend-add-frontend-page/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How lightfriend-add-frontend-page Compares

Feature / Agentlightfriend-add-frontend-pageStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Step-by-step guide for adding new pages to the Yew frontend

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Adding a New Frontend Page

This skill guides you through adding a new page to the Lightfriend Yew WebAssembly frontend.

## Overview

A complete page includes:
- Page component in `frontend/src/pages/`
- Route enum variant in `main.rs`
- Route handler in switch function
- Navigation link (if applicable)

## Step-by-Step Process

### 1. Create Page Component

Create `frontend/src/pages/{page_name}.rs`:

```rust
use yew::prelude::*;
use gloo_net::http::Request;
use crate::config;

#[function_component(PageName)]
pub fn page_name() -> Html {
    // State management
    let data = use_state(|| None::<SomeData>);
    let loading = use_state(|| true);
    let error = use_state(|| None::<String>);

    // Load data on mount
    {
        let data = data.clone();
        let loading = loading.clone();
        let error = error.clone();

        use_effect_with((), move |_| {
            wasm_bindgen_futures::spawn_local(async move {
                match fetch_data().await {
                    Ok(result) => {
                        data.set(Some(result));
                        loading.set(false);
                    }
                    Err(e) => {
                        error.set(Some(e.to_string()));
                        loading.set(false);
                    }
                }
            });
        });
    }

    html! {
        <div class="page-container">
            <h1>{"Page Title"}</h1>

            if *loading {
                <p>{"Loading..."}</p>
            } else if let Some(err) = (*error).clone() {
                <p class="error">{err}</p>
            } else if let Some(content) = (*data).clone() {
                // Render content
                <div>
                    {format!("Content: {:?}", content)}
                </div>
            }
        </div>
    }
}

// Helper functions
async fn fetch_data() -> Result<SomeData, Box<dyn std::error::Error>> {
    let token = /* get from context or local storage */;
    let backend_url = config::get_backend_url();

    let response = Request::get(&format!("{}/api/endpoint", backend_url))
        .header("Authorization", &format!("Bearer {}", token))
        .send()
        .await?
        .json::<SomeData>()
        .await?;

    Ok(response)
}

#[derive(Clone, serde::Deserialize, serde::Serialize)]
struct SomeData {
    // Define your data structure
}
```

### 2. Add Module Declaration

**CRITICAL: This codebase does NOT use `mod.rs` files!**

Instead, add the module declaration to the inline `mod pages { }` block in `frontend/src/main.rs`:

```rust
mod pages {
    pub mod home;
    pub mod landing;
    pub mod {page_name};  // Add your new page here
    // ... other pages
}
```

**NEVER create a `mod.rs` file** - this is a common mistake. Lightfriend uses named module files (e.g., `home.rs`, `landing.rs`) and declares them in the inline module block in `main.rs`.

### 3. Add Route Variant

In `frontend/src/main.rs`, add a route variant to the `Route` enum:

```rust
#[derive(Clone, Routable, PartialEq)]
pub enum Route {
    #[at("/")]
    Home,
    #[at("/page-name")]
    PageName,
    // ... other routes
    #[not_found]
    #[at("/404")]
    NotFound,
}
```

### 4. Add Route Handler

In the `switch()` function in `frontend/src/main.rs`, add:

```rust
fn switch(route: Route) -> Html {
    match route {
        Route::Home => html! { <Home /> },
        Route::PageName => html! { <PageName /> },
        // ... other routes
        Route::NotFound => html! { <h1>{"404 - Page Not Found"}</h1> },
    }
}
```

### 5. Add Navigation Link (Optional)

If the page should appear in navigation, add to the `Nav` component in `frontend/src/main.rs`:

```rust
#[function_component(Nav)]
fn nav() -> Html {
    html! {
        <nav>
            <Link<Route> to={Route::Home}>{"Home"}</Link<Route>>
            <Link<Route> to={Route::PageName}>{"Page Name"}</Link<Route>>
            // ... other links
        </nav>
    }
}
```

### 6. Test the Page

```bash
cd frontend && trunk serve
```

Navigate to `http://localhost:8080/page-name`

## Common Patterns

### Protected Routes (Require Auth)

```rust
use yew_hooks::use_local_storage;

#[function_component(ProtectedPage)]
pub fn protected_page() -> Html {
    let token = use_local_storage::<String>("token".to_string());

    if token.is_none() {
        // Redirect to login
        let navigator = use_navigator().unwrap();
        navigator.push(&Route::Login);
        return html! {};
    }

    html! {
        <div>{"Protected content"}</div>
    }
}
```

### Page with Form

```rust
use web_sys::HtmlInputElement;

#[function_component(FormPage)]
pub fn form_page() -> Html {
    let name_ref = use_node_ref();
    let email_ref = use_node_ref();
    let submitting = use_state(|| false);

    let on_submit = {
        let name_ref = name_ref.clone();
        let email_ref = email_ref.clone();
        let submitting = submitting.clone();

        Callback::from(move |e: SubmitEvent| {
            e.prevent_default();
            let submitting = submitting.clone();

            let name = name_ref.cast::<HtmlInputElement>()
                .unwrap()
                .value();
            let email = email_ref.cast::<HtmlInputElement>()
                .unwrap()
                .value();

            submitting.set(true);

            wasm_bindgen_futures::spawn_local(async move {
                match submit_form(name, email).await {
                    Ok(_) => {
                        // Handle success
                    }
                    Err(e) => {
                        // Handle error
                    }
                }
                submitting.set(false);
            });
        })
    };

    html! {
        <form onsubmit={on_submit}>
            <input
                ref={name_ref}
                type="text"
                placeholder="Name"
                required=true
            />
            <input
                ref={email_ref}
                type="email"
                placeholder="Email"
                required=true
            />
            <button type="submit" disabled={*submitting}>
                if *submitting {
                    {"Submitting..."}
                } else {
                    {"Submit"}
                }
            </button>
        </form>
    }
}

async fn submit_form(name: String, email: String) -> Result<(), Box<dyn std::error::Error>> {
    let token = /* get from context */;

    Request::post(&format!("{}/api/submit", config::get_backend_url()))
        .header("Authorization", &format!("Bearer {}", token))
        .json(&serde_json::json!({
            "name": name,
            "email": email,
        }))?
        .send()
        .await?;

    Ok(())
}
```

### Page with Context

```rust
use yew::prelude::*;

#[derive(Clone, PartialEq)]
pub struct UserContext {
    pub user_id: i32,
    pub email: String,
}

#[function_component(ContextPage)]
pub fn context_page() -> Html {
    let user_ctx = use_context::<UserContext>()
        .expect("UserContext not found");

    html! {
        <div>
            <p>{format!("User ID: {}", user_ctx.user_id)}</p>
            <p>{format!("Email: {}", user_ctx.email)}</p>
        </div>
    }
}
```

### Page with Route Parameters

```rust
#[derive(Clone, Routable, PartialEq)]
pub enum Route {
    #[at("/users/:id")]
    UserDetail { id: i32 },
}

#[derive(Properties, PartialEq)]
pub struct UserDetailProps {
    pub id: i32,
}

#[function_component(UserDetail)]
pub fn user_detail(props: &UserDetailProps) -> Html {
    let user_data = use_state(|| None::<User>);

    {
        let user_data = user_data.clone();
        let user_id = props.id;

        use_effect_with(user_id, move |_| {
            wasm_bindgen_futures::spawn_local(async move {
                if let Ok(user) = fetch_user(user_id).await {
                    user_data.set(Some(user));
                }
            });
        });
    }

    html! {
        <div>
            if let Some(user) = (*user_data).clone() {
                <h1>{user.name}</h1>
            }
        </div>
    }
}

// In switch function:
fn switch(route: Route) -> Html {
    match route {
        Route::UserDetail { id } => html! { <UserDetail id={id} /> },
        // ...
    }
}
```

### Page with Multiple API Calls

```rust
#[function_component(DashboardPage)]
pub fn dashboard_page() -> Html {
    let stats = use_state(|| None::<Stats>);
    let activity = use_state(|| None::<Vec<Activity>>);
    let loading = use_state(|| true);

    {
        let stats = stats.clone();
        let activity = activity.clone();
        let loading = loading.clone();

        use_effect_with((), move |_| {
            wasm_bindgen_futures::spawn_local(async move {
                // Fetch multiple endpoints in parallel
                let (stats_result, activity_result) = tokio::join!(
                    fetch_stats(),
                    fetch_activity()
                );

                if let Ok(s) = stats_result {
                    stats.set(Some(s));
                }
                if let Ok(a) = activity_result {
                    activity.set(Some(a));
                }

                loading.set(false);
            });
        });
    }

    html! {
        <div>
            if *loading {
                <p>{"Loading dashboard..."}</p>
            } else {
                <div>
                    {render_stats(&stats)}
                    {render_activity(&activity)}
                </div>
            }
        </div>
    }
}
```

## Styling

**Lightfriend uses CSS style blocks within the `html!` macro, NOT inline Tailwind classes.**

Common pattern:

```rust
html! {
    <div class="page-container">
        <h1 class="page-title">{"Title"}</h1>
        <div class="content-grid">
            <div class="card">
                {"Card content"}
            </div>
        </div>

        <style>
            {r#"
            .page-container {
                max-width: 1200px;
                margin: 0 auto;
                padding: 2rem;
            }
            .page-title {
                font-size: 2rem;
                font-weight: bold;
                margin-bottom: 1rem;
            }
            .content-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
                gap: 1rem;
            }
            .card {
                background: white;
                border-radius: 8px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                padding: 1rem;
            }
            "#}
        </style>
    </div>
}
```

## Testing Checklist

- [ ] Page renders without errors
- [ ] Route works in browser
- [ ] Navigation link works (if added)
- [ ] API calls succeed
- [ ] Loading states display correctly
- [ ] Error states display correctly
- [ ] Authentication checks work (if protected)
- [ ] Mobile responsive (if applicable)

## File Reference

- Page components: `frontend/src/pages/{page}.rs`
- Routes: `frontend/src/main.rs` (Route enum + switch function)
- Navigation: `frontend/src/main.rs` (Nav component)
- Shared components: `frontend/src/components/`
- Backend config: `frontend/src/config.rs`

Related Skills

manifest-frontend

16
from diegosouzapw/awesome-omni-skill

Work with Manifest's frontend system — building, serving, dev workflow, debugging, and presets. Use when creating pages, components, debugging frontend errors, or configuring the build.

ln-114-frontend-docs-creator

16
from diegosouzapw/awesome-omni-skill

Creates design_guidelines.md for frontend projects. L3 Worker invoked CONDITIONALLY when hasFrontend detected.

livekit-nextjs-frontend

16
from diegosouzapw/awesome-omni-skill

Build and review production-grade web and mobile frontends using LiveKit with Next.js. Covers real-time video/audio/data communication, WebRTC connections, track management, and best practices for LiveKit React components.

kuroco-frontend-integration

16
from diegosouzapw/awesome-omni-skill

Kurocoとフロントエンドフレームワークの統合パターンおよびAI自動デプロイメント。使用キーワード:「Kuroco Nuxt」「Kuroco Next.js」「フロントエンド連携」「Nuxt3」「Nuxt2」「App Router」「Pages Router」「SSG」「SSR」「静的生成」「コンテンツ表示」「ログイン実装」「会員登録」「signup」「KurocoPages」「フロントエンド環境構築」「Vue」「React」「useAsyncData」「$fetch」「asyncData」「composable」「useAuth」「認証状態」「プロフィール取得」「profile」「generateStaticParams」「動的ルート」「v-html」「dangerouslySetInnerHTML」「XSS対策」「サードパーティCookie」「credentials include」「AI自動デプロイ」「Kuroco自動化」「サイト登録API」「自動ビルド」「自動デプロイ」「temp-upload」「presigned URL」「S3アップロード」「artifact_url」「KurocoFront」「プレビューデプロイ」「stage_url」「add_site」「site_key」「kuroco_front/deploy」「CI/CD」「フロントエンドビルド」「ZIP配備」「自動公開」「nuxt generate」「next build」「vite build」「デプロイAPI」「一時アップロード」「署名付きURL」。Nuxt/Next.jsでのKuroco連携、認証実装、SSG/SSR設定、AI自動デプロイに関する質問で使用。

js-reverse-automation-page-redirect-debugger

16
from diegosouzapw/awesome-omni-skill

页面跳转 JS 代码定位通杀方案:在跳转前触发 debugger 以定位调用源。仅在确认跳转定位需求时启用。

gemini-frontend-design

16
from diegosouzapw/awesome-omni-skill

Create distinctive, production-grade frontend interfaces using Gemini 3 Pro for design ideation. Use this skill when you want Gemini's creative perspective on web components, pages, or applications. Generates bold, polished code that avoids generic AI aesthetics.

frontend_mastery

16
from diegosouzapw/awesome-omni-skill

Advanced React patterns, performance optimization, and state management rules.

frontend

16
from diegosouzapw/awesome-omni-skill

Apply distinctive frontend design to React + TailwindCSS apps. Use when building UI components, pages, or improving visual design. Breaks generic "AI slop" patterns.

frontend-web-dev-expert

16
from diegosouzapw/awesome-omni-skill

Advanced frontend web development expert system that provides comprehensive modern web development services including architecture design, UI/UX implementation, performance optimization, engineering setup, and cross-platform development through expert collaboration and intelligent tool integration.

frontend-ui-tailwind-standards

16
from diegosouzapw/awesome-omni-skill

Standardized guidelines and patterns for Frontend Ui Tailwind Standards.

frontend-ui

16
from diegosouzapw/awesome-omni-skill

Create aesthetically pleasing, visually distinctive frontend UIs using research-backed prompting strategies from Anthropic's frontend aesthetics cookbook

frontend-ui-dark-ts

16
from diegosouzapw/awesome-omni-skill

Build dark-themed React applications using Tailwind CSS with custom theming, glassmorphism effects, and Framer Motion animations. Use when creating dashboards, admin panels, or data-rich interfaces...