-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit c8617c2
Showing
17 changed files
with
331 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
name: All in One | ||
|
||
on: | ||
push: | ||
branches: | ||
- main | ||
|
||
jobs: | ||
build: | ||
runs-on: ubuntu-latest | ||
permissions: | ||
contents: write # чтобы action мог push делать | ||
steps: | ||
- name: Checkout repository | ||
uses: actions/checkout@v4 | ||
|
||
- name: Install Rust | ||
uses: actions-rs/toolchain@v1 | ||
with: | ||
profile: minimal # этот профиль включает как можно меньше компонентов для работы компилятора. Он устанавливает rustc (компилятор Rust), rust-std (стандартную библиотеку Rust) и cargo (систему сборки и менеджер пакетов Rust) | ||
toolchain: nightly # ночная версия rust, а не стабильная, т.к. некоторые фишки практичнее здесь | ||
target: wasm32-unknown-unknown # обозначает платформу, для которой вы компилируете ваш код. В данном случае, wasm32-unknown-unknown указывает на то, что мы компилируем код для WebAssembly (wasm32) без конкретной операционной системы или процессора (unknown-unknown). | ||
override: true # следует ли перезаписать существующую установку Rust на вашей машине. установит указанный вами toolchain и target, даже если на вашей машине уже установлен другой toolchain или target | ||
|
||
- name: Install Trunk | ||
run: cargo install --locked trunk # установить trunk. --locked для гарантии, что Cargo будет использовать точные версии зависимостей, указанные в файле Cargo.lock. | ||
|
||
- name: Build with Trunk | ||
run: trunk build --release # сборка в статические файлы(html, js, wasm, favicon...) | ||
|
||
- name: Deploy to GitHub Pages | ||
uses: JamesIves/github-pages-deploy-action@v4 # специально разработан для деплоя на GitHub Pages | ||
with: | ||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} | ||
BRANCH: gh-pages # в ветку gh-pages | ||
FOLDER: dist # из папки dist(формируется после сборки leptos) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
target/ | ||
dist/ | ||
Cargo.lock | ||
tailwindcss | ||
.DS_Store |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
[package] | ||
name = "leptos-wasm_github-pages" | ||
version = "0.1.0" | ||
edition = "2021" | ||
authors = ["smir-ant"] | ||
|
||
[dependencies] | ||
leptos = { version = "0.6", features = ["csr", "nightly"] } | ||
leptos_meta = { version = "0.6", features = ["csr", "nightly"] } | ||
leptos_router = { version = "0.6", features = ["csr", "nightly"] } | ||
# console_log = "1" | ||
# log = "0.4" | ||
# console_error_panic_hook = "0.1" | ||
|
||
# [dev-dependencies] | ||
# wasm-bindgen = "0.2" | ||
# wasm-bindgen-test = "0.3" | ||
# web-sys = { version = "0.3", features = ["Document", "Window"] } | ||
|
||
|
||
[profile.release] # Этот раздел содержит настройки для сборки вашего проекта в режиме release. | ||
opt-level = 'z' # сargo будет стараться минимизировать размер бинарного файла. | ||
lto = true # включает оптимизацию всего программного обеспечения (Link Time Optimization, LTO) | ||
codegen-units = 1 # вы говорите компилятору обрабатывать всю вашу программу как одну единицу кодогенерации. Это может привести к более эффективной оптимизации кода, потому что компилятор видит всю программу целиком, но это также может замедлить процесс компиляции, потому что он не может использовать параллелизм для ускорения | компромисс между скоростью компиляции и эффективностью оптимизации. | ||
panic = "abort" # что делать при панике. abort означает, что процесс должен немедленно завершиться | ||
|
||
|
||
[[workspace.metadata.leptos]] | ||
tailwind-input-file = "input.css" | ||
# output-name = "{{project-name}}" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
[build] | ||
public_url = "/wasm_ghpages/" # фикс путей для github-pages конкретно во всех dist файлах(т.к. в gh-pages мы начинаем не с "user.github.io/", а с "user.github.io/repository_name") | ||
|
||
# ниже альтернативный путь для tailwind, но бесполезный, так как встроенная поддержка уже есть в leptos | ||
# [[hooks]] | ||
# stage = "pre_build" | ||
# command = "sh" | ||
|
||
# command_arguments = ["-c", "./tailwindcss -i input.css -o public/tailwind.css --minify"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
<!DOCTYPE html> | ||
<html> | ||
<head> | ||
<!-- +wasm: https://rustwasm.github.io/docs/wasm-bindgen/reference/weak-references.html --> | ||
<link data-trunk rel="rust" data-wasm-opt="z" data-weak-refs /> | ||
|
||
<!-- +tailwind: https://trunkrs.dev/assets/#tailwind --> | ||
<link data-trunk rel="tailwind-css" href="/public/tailwind.css" /> | ||
|
||
<!-- +css: https://trunkrs.dev/assets/#css --> | ||
<link data-trunk rel="css" href="/public/styles.css" /> | ||
|
||
<!-- +favicon: https://trunkrs.dev/assets/#icon --> | ||
<link data-trunk rel="icon" href="/public/favicon.ico" /> | ||
</head> | ||
<body class=" | ||
bg-neutral-100 dark:bg-neutral-900 | ||
bg-gradient-to-r from-orange-300"></body> | ||
</html> |
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
.counter { | ||
margin: 20px 0px; | ||
} | ||
|
||
.counter > * { | ||
margin-right: 10px; | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
@tailwind base; | ||
@tailwind components; | ||
@tailwind utilities; | ||
|
||
@layer components { | ||
.counter_label { | ||
@apply px-2 py-4 bg-violet-500 rounded-xl; | ||
} | ||
|
||
button { | ||
@apply p-3 rounded-lg bg-white text-black dark:bg-black dark:text-white; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
[toolchain] | ||
channel = "nightly" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
use leptos::*; | ||
|
||
/// A parameterized incrementing button | ||
#[component] | ||
pub fn Button(#[prop(default = 1)] increment: i32) -> impl IntoView { | ||
let (count, set_count) = create_signal(0); | ||
view! { | ||
<button | ||
on:click= move |_| { | ||
set_count(count() + increment) | ||
} | ||
> | ||
"Click me: " {count} | ||
</button> | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
pub mod counter_btn; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
use leptos::*; | ||
use leptos_meta::*; | ||
use leptos_router::*; | ||
|
||
// Modules | ||
mod components; | ||
mod pages; | ||
|
||
// Top-Level pages | ||
use crate::pages::home::Home; | ||
// use crate::pages::not_found::NotFound; | ||
|
||
/// Маргрутизатор, который формирует домашнюю страницу (можно и другие пути, например 404 через добавление Route в Routes) | ||
#[component] | ||
pub fn App() -> impl IntoView { | ||
provide_meta_context(); // контекст, который управляет различными аспектами веб-страницы, такими как стили, заголовки, мета-теги и т.д. | ||
// “контекст” обычно относится к набору данных или состоянию, которое доступно всему приложению или определенной его части | ||
|
||
view! { | ||
<Html lang="en" dir="ltr" /> // ltr (слева-направо направление текста) | ||
<Title text="Wasm(Leptos) via Github Pages"/> // название страницы | ||
<Meta charset="UTF-8"/> | ||
<Meta name="viewport" content="width=device-width, initial-scale=1.0"/> | ||
// <Stylesheet id="tailwind" href="/public/tailwind.css"/> | ||
|
||
<Router> | ||
<Routes> | ||
<Route path="/wasm_ghpages/*" view=Home /> | ||
</Routes> | ||
</Router> | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
use leptos::*; | ||
use leptos_wasm_github_pages::App; | ||
|
||
fn main() { | ||
// стандартное логирование, но вдруг кому пригодится | ||
// _ = console_log::init_with_level(log::Level::Debug); | ||
// console_error_panic_hook::set_once(); | ||
|
||
mount_to_body(|| { | ||
view! { | ||
<App /> | ||
} | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,120 @@ | ||
// use leptos::logging::log; // стандартные средства логирования leptos, опять-таки, вдруг пригодится | ||
use leptos::*; | ||
|
||
#[derive(Debug, Clone)] | ||
pub struct CounterData { | ||
pub id: u32, | ||
pub value: (ReadSignal<i32>, WriteSignal<i32>), | ||
} | ||
|
||
impl CounterData { | ||
pub fn new(id: &mut u32, value: &mut i32) -> Self { | ||
let counter = Self { | ||
id: id.to_owned(), | ||
value: create_signal(value.clone()), | ||
}; | ||
*id += 1; | ||
*value += 10; | ||
counter | ||
} | ||
} | ||
|
||
/// Функция, создающая компонент Counter | ||
/// Параметры: | ||
/// - `counter`: сигнал для отслеживания значения счетчика | ||
/// - `on_increase_click`: опциональный колбэк для увеличения значения | ||
/// - `on_decrease_click`: опциональный колбэк для уменьшения значения | ||
/// - `on_remove_click`: опциональный колбэк для удаления счетчика | ||
#[component] | ||
pub fn Counter( | ||
counter: ReadSignal<i32>, | ||
#[prop(into, optional)] on_increase_click: Option<Callback<i32>>, | ||
#[prop(into, optional)] on_decrease_click: Option<Callback<()>>, | ||
#[prop(into, optional)] on_remove_click: Option<Callback<()>>, | ||
) -> impl IntoView { | ||
// Замыкание для обработки клика по кнопке увеличения | ||
let increase = move |_| { | ||
on_increase_click.as_ref().map(|f| f(counter())); | ||
}; | ||
// Замыкание для обработки клика по кнопке уменьшения | ||
let decrease = move |_| { | ||
on_decrease_click.as_ref().map(|f| f(())); | ||
}; | ||
// Замыкание для обработки клика по кнопке удаления | ||
let remove = move |_| { | ||
on_remove_click.as_ref().map(|f| f(())); | ||
}; | ||
|
||
// Определение структуры представления (view) для компонента | ||
view! { | ||
<div class="counter"> | ||
<button on:click=increase>"Увеличить"</button> | ||
<button on:click=decrease>"Уменьшить"</button> | ||
<span class="counter_label">{counter}</span> | ||
<button class="text-red-400" on:click=remove>"Удалить"</button> | ||
</div> | ||
} | ||
} | ||
|
||
/// Домашняя страница | ||
#[component] | ||
pub fn Home() -> impl IntoView { | ||
// Инициализация счетчика идентификаторов | ||
let mut id = 0u32; | ||
// Инициализация начального значения счетчика | ||
let mut initial_value = 0i32; | ||
// Создание сигнала для списка счетчиков | ||
let (counters, set_counters) = create_signal::<Vec<CounterData>>(vec![ | ||
CounterData::new(&mut id, &mut initial_value), | ||
CounterData::new(&mut id, &mut initial_value), | ||
CounterData::new(&mut id, &mut initial_value), | ||
]); | ||
|
||
// Функция для добавления нового счетчика | ||
let mut add_counter = move || { | ||
set_counters | ||
.update(|counters| counters.push(CounterData::new(&mut id, &mut initial_value))); | ||
}; | ||
|
||
// Обработчик клика для удаления счетчика | ||
let handle_click_remove = move |id: u32| { | ||
set_counters.update(|counters| { | ||
counters.retain(|c| match c.id != id { | ||
true => true, | ||
false => { | ||
c.value.0.dispose(); // данный сигнал больше не нужен и может быть удалён | ||
false | ||
} | ||
}) | ||
}) | ||
}; | ||
|
||
// Обработчик клика для увеличения значения счетчика | ||
let handle_increase_click = move |set_count: WriteSignal<i32>| { | ||
set_count.update(|v| *v += 10); | ||
}; | ||
|
||
// Обработчик клика для уменьшения значения счетчика | ||
let handle_decrease_click = move |set_count: WriteSignal<i32>| { | ||
set_count.update(|v| *v -= 10); | ||
}; | ||
|
||
// Определение структуры представления (view) для домашней страницы | ||
view! { | ||
<button on:click=move|_| { add_counter(); }>"Добавить счётчик"</button> | ||
<For each=counters key=|counter| counter.id children=move |counter| view! { | ||
<Counter counter={counter.value.0} | ||
on_increase_click = move |_value| { | ||
// log!("{_value}"); | ||
handle_increase_click(counter.value.1) | ||
} | ||
on_remove_click = move |_| { | ||
handle_click_remove(counter.id) | ||
} | ||
on_decrease_click = move |_| { | ||
handle_decrease_click(counter.value.1) | ||
} | ||
/> | ||
} /> | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
pub mod home; | ||
pub mod not_found; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
use leptos::*; | ||
|
||
/// 404 Not Found | Вдруг пригодится | ||
#[component] | ||
pub fn NotFound() -> impl IntoView { | ||
view! { <h1>"Uh oh!" <br/> "We couldn't find that page!"</h1> } | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
/** @type {import('tailwindcss').Config} */ | ||
module.exports = { | ||
content: { | ||
files: ["*.html", "src/pages/*.rs"], | ||
}, | ||
theme: { | ||
extend: { | ||
colors: { // переопределяем цвета | ||
neutral: { // группы neutral | ||
100: '#F1F1F1', | ||
800: '#202020' | ||
} | ||
} | ||
}, | ||
}, | ||
plugins: [], | ||
} |