GithubHelp home page GithubHelp logo

leptos-rs / book Goto Github PK

View Code? Open in Web Editor NEW
71.0 71.0 60.0 2.37 MB

The home for the Leptos book, which can be found deployed at https://book.leptos.dev

License: MIT License

CSS 94.95% Dockerfile 2.09% Shell 0.82% JavaScript 2.13%

book's People

Contributors

alilee avatar andrewp2 avatar anvlkv avatar aschweig avatar benwis avatar blorbb avatar chrisp60 avatar crowdedlight avatar crs117 avatar diversable avatar gbj avatar gihrig avatar gulbrand avatar lexika979 avatar matormentor avatar mscherer avatar ncura avatar niclas-ahden avatar nikolaisavinkin avatar nuke-web3 avatar qussaif10 avatar ratulb avatar rlovell3 avatar shivdhar avatar silaslock avatar simonderidder avatar titaniumtraveler avatar williameliasson-dev avatar wollaston avatar yasutakekazu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

book's Issues

Where is the source code used in the book?

Hi,

I would like to download and open the source in my local vscode then press F12 and jump into the source code of leptos or any other librarys.

Any link of the source code pack so that I can download?

Premature Reference to `create_resource` in Section 4.2

In 4.2. Responding to Changes with create_effect, at the very end of the page, the book is saying

Like create_resource, watch takes a first argument ...

However, create_resource hasn't been introduced at this point. The first mention of create_resource is in 6.1. Loading Data with Resources. This might be due to a reordering of the content. It's a minor issue, but I wanted to bring it to your attention in case the phrase needs to be updated for clarity.

Really small docs issue in router section, no mention about leptos_router required features

Describe the bug
Documentation: It’s easy to get started with the router. First things first, make sure you’ve added the leptos_router package to your dependencies.
That's absolutely true, but it would be nice for beginners to tell them about package features that they have to install.
Yes, I know - console_error_panic_hook describes everything in console dev tools tab, but it would be nice to tell the user beforehand.

Leptos Dependencies
None, it's documentation issue.

To Reproduce
Steps to reproduce the behavior:

  1. Go to Leptos docs - router section

Expected behavior
I think it just should be written in docs.

Screenshots
With or without console_error_panic_hook - does not matter, everything compiles.
obraz

Error without console_error_panic_hook
obraz

Error with console_error_panic_hook
obraz

Additional context
None

Deployment workflow deletes custom domain

The book is set up in GitHub Settings to be deployed at book.leptos.dev

The deployment workflow, maybe because it deletes the gh-pages it creates, seems to unset this every time, causing a 404 unless I reset it.

Bug in Sample Code in chapter "A Basic Component"

There is a bug in the first sample code in chapter "A Basic Component". set_count(3) should be set_count.set(3).

#[component]
fn App() -> impl IntoView {
    let (count, set_count) = create_signal(0);

    view! {
        <button
            on:click=move |_| {
                set_count(3);
            }
        >
            "Click me: "


            {move || count.get()}
        </button>
    }
}

Screenshot from 2024-01-29 01-17-57

Update Needed: Closure of Linked PR in document

Hi, while i was trying to get info about The Jetbrains intellij-rust plugin (https://book.leptos.dev/getting_started/leptos_dx.html#admonition-info), i found that this open PR is now closed. so I'd like to propose an update to reflect the closure of the PR linked in the document.

As the GitHub repository it targeted has been deprecated(see https://github.com/intellij-rust/intellij-rust?tab=readme-ov-file#deprecation-notice). Therefore, the information provided is no longer valid.

Example for Set up `console_error_panic_hook`

In 2.1 Set up console_error_panic_hook the example listed in

If this is unclear, click here for an example.

Uses a dependency console_log that was not imported to my environment. Although I understand the use of this example because of the line

console_error_panic_hook::set_once();

I believe that a code block in the book using the example main.rs that was created in 2 Hello World! Getting Set up for Leptos CSR Development has a better flow for the reader. Something like

use leptos::*;

fn main() {
    console_error_panic_hook::set_once();
    mount_to_body(|| view! {<p> "Hello World. This is me!" </p>});
}

"Global State Management" Chapter - add a "struct of signals" option & example

Add a new option and example to the Global State Management chapter that describes passing state down using a struct of signals.

Recommended by 'gbj' on Discord:
"""
Skimming over it[the Global State Management chapter], I see the recommendations as
you do not need this chapter
Option 1 URL should drive global state
Option 2 passing signals through context or props
Option 3 global state struct and slices

Maybe 3 should be 4, and a new Option 3 should be inserted with a struct of signals
"""

Codesandbox highjacks scrolling on page load

When you go to a new page in the book that contains an example in codesandbox, the page jumps down to the codesandbox element when it loads. The interactive examples are a great addition but those are often at the bottom of the page and its pretty disorienting when a new page loads to be jumped around, especially to the bottom.

"Advanced topics"

It would be useful to have a section at the end that just links to the main docs/points out the existence of a few advanced topics: :undelegated for opting out of event delegation is one example that's come up, and I know there are other things that are difficult to discover in the main docs if you don't already know they exist, but also aren't covered in the book.

Pages auto scrolling to code sandbox (only on FF and Linux)

The code sandbox causes the page to scroll to it once it loads, this makes reading confusing as you don't notice you aren't starting at the top of the page sometimes. Also makes linking directly to sections not work.

Example: https://leptos-rs.github.io/leptos/view/05_forms.html#controlled-inputs
Wait a few seconds after opening that link and once the code sandbox loads it scrolls down to it. Note that link was specifically targeted at the "Controlled Inputs" header which is normally useful for linking people to specific content, but the automatic scrolling to the code sandbox breaks that functionality.

Edit: Only happens for me on Firefox (stable channel v120 64 bit) linux. Does not happen on Chrome on linux and does not happen on Windows. I'm on EndeavorOS (Arch based Linux)

Working with web_sys or js_sys doc section

Lots of questions about how to integrate a js lib, or how to handle conversion between leptos and web_sys types, or how to do event listeners.

Could probably use a fleshed out section on that

section on `use_query` outdated?

Basing my tests on the book I wrote the following

use leptos::*;
use leptos_router::*;

#[derive(Params)]
struct UrlQuery {
    armies: String,
}

#[component]
fn App() -> impl IntoView {
    let query = use_query::<UrlQuery>();

First error is I get is UrlQuery should implement PartialEq for use with use_query - the book example does not use it, is the doc just a bit outdated, or is there anything more subtle than that?

And then

39 |     armies: String,
   |             ^^^^^^ the trait `IntoParam` is not implemented for `std::string::String`

In https://docs.rs/leptos_router/latest/leptos_router/trait.IntoParam.html we see it is only implemented for Option<T>

Indeed using Option<String> allows the code to compile, so I guess the example should really be updated.

"Deployment" Chapter - add starter templates for deploying to Deno & Cloudflare

In the long term, starter templates should be added to cargo-leptos to make the 'getting started' experience as smooth as possible. In the meantime, there have been questions from users in Discord about how to deploy Leptos websites/apps to multiple platforms.

So, as a follow-up to leptos-rs/leptos#2032:
We should refactor the "Deployment" chapter to separate CSR app deployment from SSR app deployment.

In the CSR deployment chapter, add:

https://github.com/diversable/leptos-spin-CSR

In the SSR deployment chapter, add a template for AWS Lambda: see below

Deploying to WinterCG-enabled environments (Deno Deploy, Cloudflare,etc):
see https://github.com/leptos-rs/leptos/releases/tag/v0.5.0

Also, look into creating templates for:

  • Deno Deploy
  • Cloudflare
  • Spin SSR (*if the req'd PR gets merged to enable this setup)

cf. 'gbj' comment on Discord:
"""
It would be great to also have Deno Deploy, Cloudflare, Spin starters. The easier we make it for people the better
"""

"Leptos DX" chapter - remove component macro from ignored list

Remove "component" from the list of procMacro.ignored... for all code editors listed, since rust-analyzer support is now enabled inside #[component] macros in Leptos > v0.5.3.

For reference:

From Leptos v0.5.3 release notes:
Release v0.5.3 · leptos-rs/leptos · GitHub
"""
Improved rust-analyzer support in #[component] macro body

Good LSP support for proc macros is hard, because proc macros depend on parsing a stream of input into a valid Rust syntax tree, but while typing you are constantly creating a stream of new, invalid trees. This release tweaks how the #[component] macro emits code in order to enable better rust-analyzer support within the body of components.

If you've disabled rust-analyzer inside #[component] for better DX, try toggling that off and see if this is a better experience than it was before!

Apologies for any regressions this causes. Please report any issues that arise.

There is still additional work to be done to support rust-analyzer in the view! macro. The hoped-for improvements here are solely inside the #[component]body.

"""

Add `start-trunk` template option to book

There continues to be questions from the community about setting up error handling & using the Leptos Router for CSR apps.

We now have a start-trunk template in the leptos-rs org that demonstrates how to set those up; it would be good to mention that CSR template near the beginning of the book, so people can easily code along with the examples using a standardized template, similar to the process for SSR apps.

Documentation Enhancement: Note on Styling Issues with experimental-islands

This is more a Documentation request than a feature request, but there was no issue template for that.

I can do a PR my question just would be where to add this documentation ? Maybe inside the islands section in the book ?

Is your feature request related to a problem? Please describe.
Yes, after migrating my application to use experimental-islands, I encountered styling issues. Specifically, some CSS styles broke and did not apply as expected.

Describe the solution you'd like
I would like the documentation to include a section on how to address styling issues that arise when using experimental-islands. Specifically, a guide on adding the following CSS rule to the project's main stylesheet could be very helpful:

leptos-island {
  display: contents;
}

This rule makes the leptos-island component act "transparent" in the DOM, ensuring that the children of the island are styled correctly as if the island component wasn't there. Including this in the documentation would aid developers in ensuring their applications maintain their intended styles. As I am no CSS-wiz I am not entirely sure there aren't any unintended consequences, but to me this seems like a solid solution.

Describe alternatives you've considered
An alternative could be to implement a built-in solution within the experimental-islands framework that automatically applies this styling fix, using inline styles, and/or provides a configuration option to enable such behavior. However, documenting the current workaround is a quick and effective solution that can immediately assist developers. Also a "built-in" solution would probably also cause unexpected behavior for existing users of islands and would therefore at least require a version bump.

Additional context
None

Add part about `on_cleanup`

on_cleanup is never mentioned, yet needed when dealing with for example set_timeout/set_interval. Their callback still gets run after navigating to a different page, even though any resources it accesses no longer exist, leading to an error. This can only be prevented by clearing them in on_cleanup.

"DX" chapter - add suggestions for Rust compilation time improvements; add tw & emmet support instructions as well

Compile-time decreases lead to a major "quality of life" improvement - advice in the DX chapter should be added to help improve Rust compile times in Leptos apps:
See: https://benw.is/posts/how-i-improved-my-rust-compile-times-by-seventy-five-percent

Also, since tailwind and emmet support are not natively set up for Rust, add instructions on how to add support for tailwind and emmet to VSCode (and other editors, if possible).

See the instructions for tw & emmet here:
https://github.com/leptos-rs/leptos/blob/main/examples/tailwind_csr/README.md

Add imports to Server example (not reproducible)

Thank you very much for this book! It's very helpful and i'm learning a lot.

The leptos book introduces server functions in chapter 14. Prior to this, in chapter 13 we are guided in creating a leptos app using SSR with cargo leptos.

In the very first example of using server functions https://book.leptos.dev/server/25_server_functions.html#using-server-functions we create an add_todo() in todo.rs this does not include any imports to the code chunk leaving the reader (who most likely is like me, has no idea what imports are needed) to figure out what imports are needed.

Adding the standard use leptos::*; does not fix the compiler error. Guess work with the rust analyzer leads me to use leptos_server::*; none of which gets the to compile and are left with a compiler error

  |
5 | #[server(AddTodo, "/api")]
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^ can't find crate

It would be really nice if the content of the book can be reproduced and followed along with!

Sandbox fails to compile 'Transition' chapter

Describe the bug
A clear and concise description of what the bug is.

To Reproduce

  1. Go here: https://book.leptos.dev/async/12_transition.html
  2. wait a little
  3. "Setup failed 1/1"
  4. press at it to see logs

logs:

[200 ms] Resolving Feature dependencies for 'ghcr.io/codesandbox/devcontainer-features/codesandbox:0.1.4'...
[1239 ms] Start: Run: /usr/bin/podman build -t dev_container_feature_content_temp -f /tmp/devcontainercli-pitcher-host/container-features/0.50.2-1697618681031/Dockerfile.buildContent /tmp/devcontainercli-pitcher-host/container-features/0.50.2-1697618681031
STEP 1/2: FROM scratch
Error: creating build container: creating container: creating read-write layer with ID "66a2a70d456607e3a3efdce8e46450925fee9231f9c8dd8473167e1c4dee1244": write /project/.cache/podman-shared/overlay/66a2a70d456607e3a3efdce8e46450925fee9231f9c8dd8473167e1c4dee1244/link: no space left on device
{"outcome":"error","message":"Command failed: /usr/bin/podman build -t dev_container_feature_content_temp -f /tmp/devcontainercli-pitcher-host/container-features/0.50.2-1697618681031/Dockerfile.buildContent /tmp/devcontainercli-pitcher-host/container-features/0.50.2-1697618681031","description":"An error occurred building the container."}
Failed to run containers Command failed with exit code 1: devcontainer build --buildkit=never --docker-path=/usr/bin/podman --workspace-folder=/tmp/csb-devcontainers --image-name=localhost/codesandbox/dev-image:latest

Add Examples: integrating JS libs, integrating Bevy

The book is missing a few "quality of life" examples which have been requested several times from the community.

In a section titled something like "Real-World Leptos" add the following examples:

  • integrating a JS lib - with the example being Google Maps
  • integrating a Bevy game

leptos_dx: rust-analyzer support in Kate

Kate's LSP client configuration is its own science. Therefore I want to share my configuration that includes ssr and leptosfmt override:

{
    "servers": {
        "rust": {
            "initializationOptions": {
                "procMacro": {
                    "ignored": {
                        "leptos_macro": [
                            "server"
                        ]
                    }
                },
                "cargo": {
                    "features": ["ssr"]
                },
                "rustfmt": {
                    "overrideCommand": [
                        "leptosfmt", "--stdin", "--rustfmt"
                    ]
                }
            }
        }
    }
}

I did not include the comments

// optional:
// "component",
…
// if code that is cfg-gated for the `ssr` feature is shown as inactive,
// you may want to tell rust-analyzer to enable the `ssr` feature by default
//
// you can also use `rust-analyzer.cargo.allFeatures` to enable all features

because a warning appears that the JSON was invalid if comments are in them. Maybe someone can incorporate this in the book or find another good place where Kate users can find it and @bram209 might find this useful as well for rustfmt.

"Global State Management" Chapter - add new `<Provider />` component description

Issues to Address in 'Global State Management' Chapter

1. Add New <Provider /> Component Description & Example

A new <Provider /> component was added in Leptos v0.5.3 - a description of the component and an example of usage should be added alongside the other options for state management.

For more info, see:

From Leptos 0.5.3 release notes:
Release v0.5.3 · leptos-rs/leptos · GitHub
"""
Optional Context <Provider/> Component

Since 0.5.0, there've been a couple instances of bugs or confusing behavior related to the fact that context now follows the reactive graph, not the component tree (see #1986#2038).

This release includes a <Provider/> component that provides a certain value via context only to its children:

#[component]
pub fn App() -> impl IntoView {
    // each Provider will only provide the value to its children
    view! {
        <Provider value=1u8>
            // correctly gets 1 from context
            {use_context::<u8>().unwrap_or(0)}
        </Provider>
        <Provider value=2u8>
            // correctly gets 2 from context
            {use_context::<u8>().unwrap_or(0)}
        </Provider>
        // does not find any u8 in context
        {use_context::<u8>().unwrap_or(0)}
    }
}

provide_context continues working as it has since 0.5.0, and if you're using it without problems you can ignore this, or use it if you prefer to aesthetics. If you're in a situation where you need to provide multiple context values of the same type and ensure that they are scoped correctly and that siblings do not overwrite one another, use <Provider/>. If you have no idea what I mean, check the issues above for examples of the bugs this fixes.
"""

Can't pass `Callback` as an event handler

Describe the bug
In the Leptos book it mentions that I can pass a Callback<_> as an event handler from a parent to a child, however this doesn't seem to work, I get the following error:

expected an `FnMut(MouseEvent)` closure, found `leptos::Callback<MouseEvent>

Using a closure does work, however.

Leptos Dependencies

leptos = { version = "0.6", features = ["csr"] }

To Reproduce

#[component]
fn Effect(
    #[prop(into)] on_remove: Callback<ev::MouseEvent>,
) -> impl IntoView {
        view! {
             <div on:click=on_remove>Remove</div>
        }
}

and in the parent:

                     <Effect
                         on_remove=move |ev: ev::MouseEvent| {
                              log!("testing");
                         } />

Expected behavior

Should compile with the callback.

Describe Current Leptos Features Presently Missing From The Book

There have been a few Leptos features which were brought up in discussion which should be described in the book (see reference, below).

It is possible that some of these features should be listed in a new section, "Part 3: Advanced Topics" (see here for that issue: #8)

Pt 2: SSR-related features

  • common / recommended middleware

  • explicitly talking about changing headers and status in responses for server bodies

  • ...

As of yet, I'm not sure where these features should fit into the book: suggestions, help writing these up, and other topics missed in the list above, are all welcome.
The list above will be updated with new suggestions from any comments on this issue.


leptos-rs/leptos#2007 (comment)

"""

i think one problem is discoverability - there are quite a few (mostly recent) features that were added but aren't included in the book (#[prop(attrs)], #[slot]s, , slice!, Callback, TextProp, ViewFn, MaybeProp, extra signal stuff (batch, untrack, on_cleanup)) that I think could be beneficial for people to know of.

Maybe a full discussion of the features doesn't need to be included in the book, but simply mentioning that these exist could be helpful, so that people don't try to reinvent the wheel. For example, the Components and Props section could mention (and briefly describe the use cases of) #[slot]s, the handy types like Callback, TextProp, MaybeProp and ViewFn, with links to the docs.rs pages. Same thing in the Reactivity section, the signal helper functions batch and untrack could be briefly mentioned.

Perhaps a more ambitious undertaking could be restructuring the leptos modules. Currently, pretty much everything is just re-exported in leptos::*, which makes it easy to use in code but difficult to navigate the docs. Maybe having more public modules (e.g. components for all the components provided by leptos, props for all the extra structs) but still re-exporting in the crate root could help. Maybe some functions like batch and untrack could be moved to be associated functions of the Signal type?

...
"""

Getting started section does not work in GitHub Codespaces

When building the project with cargo-leptos watch, get error messages:

note: rust-lld: error: unknown argument: -fuse-ld=lld
rust-lld: warning: /usr/local/rustup/toolchains/1.79.0-x86_64-unknown-linux-gnu/lib/rustlib/wasm32-unknown-unknown/lib/libcompiler_builtins-ede2c28f442d84af.rlib: archive member '45c91108d938afe8-absvdi2.o' is neither Wasm object file nor LLVM bitcode
<= for various libraries
error: could not compile `wasm-streams` (lib) due to 1 previous error

My setup ("devcontainer.json"):

{
	"name": "Rust",
	"dockerComposeFile": "docker-compose.yml",
	"service": "app",
	"workspaceFolder": "/workspaces/${localWorkspaceFolderBasename}",
	"features": {
		"ghcr.io/devcontainers/features/rust:1": {
			"version": "1.79",
			"profile": "minimal",
			"targets": "aarch64-unknown-linux-gnu"
		}
	}
}

Setting up / preparing project (SSR) with:

cargo install cargo-leptos
cargo leptos new --git leptos-rs/start-axum
rustup target add wasm32-unknown-unknown

The fuse-ld=lld comes from the .cargo/config.toml generated by Codespace:

[build]
rustflags = ["-C", "link-arg=-fuse-ld=lld"]

Does anyone has this experience? Did anyone found a solution?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.