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

Update to Yew 0.20 #1

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "yew-table"
version = "0.1.2"
version = "0.2.0"
authors = ["Alexis Luengas <alexis.luengas@gmail.com>"]
edition = "2018"
repository = "https://github.com/LexLuengas/yew-table"
Expand All @@ -14,5 +14,5 @@ description = "A table component for the Yew web framework"

[dependencies]
serde = { version = "1.0.93", features = ["derive"] }

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
serde = { version = "1.0.93", features = ["derive"] }
serde = { version = "1.0.197", features = ["derive"] }

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, these are outdated because that is how long this PR was open :). It should pretty much just work as is. even with the update. I just have a copy of this in my projects...

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@shimwell I ended up creating a new repo with this if you want to use it https://github.com/aknarts/yew-custom-components did not publish yet because I am not sure I can take that name and trying to think of a better one. The table example is live here: https://aknarts.github.io/yew-custom-components/#/table

Rewrote it to Function Component, and added the ability for the data to be updated in real time and the table preserves sorting.

serde-value = "0.6.0"
yew = "0.6.0"
serde-value = "0.7.0"
yew = "0.20.0"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
yew = "0.20.0"
yew = "0.21.0"

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ An example Yew app showing a plain table can be found in the _examples_ folder.
## To-dos

- [x] Add sortability
- [ ] Add searchability
- [x] Add searchability
- [ ] Improve accessibility
- [ ] Add pagination

Expand Down
18 changes: 7 additions & 11 deletions examples/app/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@
[package]
name = "yew-app"
version = "0.1.2"
version = "0.2.0"
authors = ["Alexis Luengas <alexis.luengas@gmail.com>"]
edition = "2018"

[dependencies]
log = "0.4"
chrono = { version = "0.4", features = ["serde"] }
web_logger = "0.1"
smart-default = "0.5.2"
wasm-logger = "0.2"
smart-default = "0.6.0"
serde = { version = "1.0.93", features = ["derive"] }
strum = "0.15.0"
strum_macros = "0.15.0"
serde-value = "0.6.0"
yew = "0.6.0"
strum = "0.24.1"
strum_macros = "0.24.3"
serde-value = "0.7.0"
yew = { version = "0.20.0", features = ["csr"] }
yew-table = { path = "../.." }

[dependencies.rand]
version = "0.6.5"
features = ["stdweb"]

[profile.release]
debug = true
9 changes: 0 additions & 9 deletions examples/app/Web.toml

This file was deleted.

63 changes: 63 additions & 0 deletions examples/app/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<!DOCTYPE html>
<html>
<head>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Yew Table</title>
<link rel="icon" href="data:,">
<style>
html {
font-size: 16px;
}

table.yew-table {
border: 1px solid #ccc;
border-collapse: collapse;
}

table.yew-table td, table.yew-table th {
border: 1px solid #ccc;
padding: 2px 4px;
}

table.yew-table.is-orderable thead {
cursor: pointer;
}

table.yew-table thead th > span {
display: flex;
align-items: center;
}

table.yew-table thead th i.sorting-control {
font-size: 0.5rem;
line-height: 1em;
display: inline-flex;
flex-direction: column;
align-items: center;
margin-left: 4px;
}

table.yew-table.is-orderable thead th i.sorting-control:before {
content: "▲";
color: #ccc;
}

table.yew-table.is-orderable thead th i.sorting-control:after {
content: "▼";
color: #ccc;
}

table.yew-table thead th i.sorting-control.is-sorting-descending:before {
color: black;
}

table.yew-table thead th i.sorting-control.is-sorting-ascending:after {
color: black;
}
</style>
</head>
<base data-trunk-public-url/>
</head>
</html>
4 changes: 0 additions & 4 deletions examples/app/run.sh

This file was deleted.

56 changes: 28 additions & 28 deletions examples/app/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
#![recursion_limit = "128"]

use log::info;
use rand::seq::SliceRandom;
use yew::html;
use yew::prelude::*;
use yew_table::{columns, Table, TableOptions};
use rand::Rng;
use strum::IntoEnumIterator;
use yew_app::task::*;
use chrono::prelude::*;

Expand All @@ -15,61 +12,64 @@ struct Model {
}

fn create_mock_tasks() -> Vec<Task> {
let mut rng = rand::thread_rng();
let task_statuses = TaskStatus::iter().collect::<Vec<_>>();;
(0..100)
.map(|i| Task {
let mut favorite = false;
let mut archived = true;
(0..100).map(|i| {
favorite = !favorite;
archived = !archived;
Task {
id: format!("task-{}", i + 1),
description: String::from("These are not the Lorem Ipsums you are looking for"),
due_date: Some(Utc.ymd(2014, (i % 12) + 1, 8).and_hms(12, 0, 9)),
status: task_statuses.choose(&mut rng).unwrap().to_owned(),
is_favorite: rng.gen(),
is_archived: rng.gen(),
due_date: Some(Utc.with_ymd_and_hms(2014, (i % 12) + 1, 8, 12, 0, 9).unwrap()),
status: TaskStatus::Open,
is_favorite: favorite,
is_archived: archived,
..Task::default()
})
.collect()
}
}).collect()
}

impl Component for Model {
type Message = ();
type Properties = ();

fn create(_props: Self::Properties, _link: ComponentLink<Self>) -> Self {
fn create(_ctx: &Context<Self>) -> Self {
Model {
tasks: create_mock_tasks()
}
}

fn update(&mut self, _msg: Self::Message) -> ShouldRender {
fn update(&mut self, _ctx: &Context<Self>, _msg: Self::Message) -> bool {
true
}
}

impl Renderable<Model> for Model {
fn view(&self) -> Html<Self> {
fn view(&self, _ctx: &Context<Self>) -> Html {
let columns = columns![
("id", "Id.")
("description", "Description")
("due_date", "Due date")
("status", "Status")
("is_favorite", "Favorite", "Fav.")
("is_archived", "Archived", "Arch.")
("id", "Id.", "Id.", true)
("description", "Description", "Description", true)
("due_date", "Due date", "Due date", true)
("status", "Status", "Status", true)
("is_favorite", "Favorite", "Fav.", true)
("is_archived", "Archived", "Arch.", true)
];

let options = TableOptions {
orderable: true,
unordered_class: None,
ascending_class: Some("is-sorting-ascending".to_string()),
descending_class: Some("is-sorting-descending".to_string()),
orderable_classes: vec!["sorting-control".to_string()],
};

html! {
<>
<Table<Task>: columns=columns, data=&self.tasks, options=Some(options),/>
<Table<Task> {options} classes={classes!("yew-table", "is-orderable")} {columns} data={self.tasks.clone()}/>
</>
}
}
}

fn main() {
web_logger::init();
wasm_logger::init(wasm_logger::Config::new(log::Level::Trace));
info!("Starting SPA");
yew::start_app::<Model>();
yew::Renderer::<Model>::new().render();
}
38 changes: 25 additions & 13 deletions examples/app/src/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,13 @@ use chrono::prelude::*;
use serde::Serialize;
use serde_value::Value;
use smart_default::SmartDefault;
use strum_macros::{EnumIter, ToString};
use strum_macros::{EnumIter};
use yew::html;
use yew::prelude::*;
use yew_table::{Table, TableData, TableError, Result as TableResult};
use yew_table::{TableData, Error, Result as TableResult};

#[derive(
Clone, PartialOrd, Eq, PartialEq, Ord,
Serialize, EnumIter, ToString, SmartDefault)]
#[derive(Clone, PartialOrd, Eq, PartialEq, Ord,
Serialize, EnumIter, Debug, SmartDefault)]
#[strum(serialize_all = "snake_case")]
pub enum TaskStatus {
#[default]
Expand All @@ -18,6 +17,12 @@ pub enum TaskStatus {
Closed = 2,
}

impl std::fmt::Display for TaskStatus {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}

#[derive(Default, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
pub struct Task {
pub id: String,
Expand All @@ -32,7 +37,7 @@ pub struct Task {
}

impl TableData for Task {
fn get_field_as_html(&self, field_name: &str) -> TableResult<Html<Table<Self>>> {
fn get_field_as_html(&self, field_name: &str) -> TableResult<Html> {
let html_repr = match field_name {
"id" => html! {
{ &self.id }
Expand All @@ -54,31 +59,38 @@ impl TableData for Task {
{ self.progress.to_string() + "%" }
},
"is_favorite" => html! {
<input type="checkbox", checked=self.is_favorite,/>
<input type="checkbox" checked={self.is_favorite} disabled={true}/>
},
"is_archived" => html! {
<input type="checkbox", checked=self.is_archived,/>
<input type="checkbox" checked={self.is_archived} disabled={true}/>
},
n => return Err(TableError::NonRenderableField(n.to_owned())),
n => return Err(Error::NonRenderableField(n.to_owned())),
};
Ok(html_repr)
}

fn get_field_as_value(&self, field_name: &str) -> TableResult<Value> {
let value = match field_name {
"id" => serde_value::to_value(
&self.id
.chars().skip(5).collect::<String>() // omit prefix "task-"
.parse::<i32>().unwrap() // parse the number as integer
&self.id.chars().skip(5).collect::<String>() // omit prefix "task-".parse::<i32>().unwrap() // parse the number as integer
),
"description" => serde_value::to_value(&self.description),
"status" => serde_value::to_value(self.status.to_string()),
"due_date" => serde_value::to_value(self.due_date.map_or(0, |d| d.timestamp())),
"progress" => serde_value::to_value(self.progress),
"is_favorite" => serde_value::to_value(self.is_favorite),
"is_archived" => serde_value::to_value(self.is_archived),
n => return Err(TableError::InvalidFieldName(n.to_owned())),
n => return Err(Error::InvalidFieldName(n.to_owned())),
};
Ok(value.unwrap())
}

fn matches_search(&self, needle: Option<String>) -> bool {
match needle {
None => { true }
Some(search) => {
self.description.to_lowercase().contains(&search.to_lowercase())
}
}
}
}
66 changes: 0 additions & 66 deletions examples/app/static/index.html

This file was deleted.

Loading