Make methods static. (#1313)

* Make methods static.

* Fix a call.

* Fix examples.

* Fix examples.

* Fix rest of examples.

* Fix yew-functional.

* Fix interval service example.

* Fix webgl example.

* Fix dialogue service example.

* Use `Default` trait instead of `new()` in `npm_and_rest` example.

* Use `Default` trait instead of `new()` in `npm_and_rest` example.

* Remove use of the `Option` algebraic data type.

* Fix clippy warnings.
This commit is contained in:
Teymour Aldridge 2020-06-22 08:32:04 +01:00 committed by GitHub
parent 7e828d5ade
commit e0aec40fe0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
26 changed files with 87 additions and 159 deletions

View File

@ -6,7 +6,6 @@ use yew::{html, Component, ComponentLink, Html, ShouldRender};
pub struct Model { pub struct Model {
link: ComponentLink<Self>, link: ComponentLink<Self>,
console: ConsoleService,
value: i64, value: i64,
} }
@ -20,22 +19,18 @@ impl Component for Model {
type Properties = (); type Properties = ();
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self { fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
Model { Model { link, value: 0 }
link,
console: ConsoleService::new(),
value: 0,
}
} }
fn update(&mut self, msg: Self::Message) -> ShouldRender { fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg { match msg {
Msg::Increment => { Msg::Increment => {
self.value += 1; self.value += 1;
self.console.log("plus one"); ConsoleService::log("plus one");
} }
Msg::Decrement => { Msg::Decrement => {
self.value -= 1; self.value -= 1;
self.console.log("minus one"); ConsoleService::log("minus one");
} }
} }
true true

View File

@ -44,7 +44,6 @@ pub enum Scene {
pub struct Model { pub struct Model {
link: ComponentLink<Self>, link: ComponentLink<Self>,
storage: StorageService, storage: StorageService,
dialog: DialogService,
database: Database, database: Database,
scene: Scene, scene: Scene,
} }
@ -72,7 +71,6 @@ impl Component for Model {
Model { Model {
link, link,
storage, storage,
dialog: DialogService::new(),
database, database,
scene: Scene::ClientsList, scene: Scene::ClientsList,
} }
@ -126,7 +124,7 @@ impl Component for Model {
}, },
Scene::Settings => match msg { Scene::Settings => match msg {
Msg::Clear => { Msg::Clear => {
let ok = { self.dialog.confirm("Do you really want to clear the data?") }; let ok = { DialogService::confirm("Do you really want to clear the data?") };
if ok { if ok {
self.database.clients.clear(); self.database.clients.clear();
self.storage.remove(KEY); self.storage.remove(KEY);

View File

@ -55,7 +55,6 @@ pub struct WsResponse {
} }
pub struct Model { pub struct Model {
ws_service: WebSocketService,
link: ComponentLink<Model>, link: ComponentLink<Model>,
fetching: bool, fetching: bool,
data: Option<u32>, data: Option<u32>,
@ -123,7 +122,6 @@ impl Component for Model {
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self { fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
Model { Model {
ws_service: WebSocketService::new(),
link, link,
fetching: false, fetching: false,
data: None, data: None,
@ -149,10 +147,9 @@ impl Component for Model {
WebSocketStatus::Opened => Msg::Ignore, WebSocketStatus::Opened => Msg::Ignore,
WebSocketStatus::Closed | WebSocketStatus::Error => WsAction::Lost.into(), WebSocketStatus::Closed | WebSocketStatus::Error => WsAction::Lost.into(),
}); });
let task = self let task =
.ws_service WebSocketService::connect("ws://localhost:9001/", callback, notification)
.connect("ws://localhost:9001/", callback, notification) .unwrap();
.unwrap();
self.ws = Some(task); self.ws = Some(task);
} }
WsAction::SendData(binary) => { WsAction::SendData(binary) => {

View File

@ -156,8 +156,7 @@ impl Component for Model {
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self { fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
let callback = link.callback(|_| Msg::Tick); let callback = link.callback(|_| Msg::Tick);
let mut interval = IntervalService::new(); let handle = IntervalService::spawn(Duration::from_millis(200), callback);
let handle = interval.spawn(Duration::from_millis(200), callback);
Model { Model {
link, link,

View File

@ -33,7 +33,7 @@ impl Agent for Worker {
fn create(link: AgentLink<Self>) -> Self { fn create(link: AgentLink<Self>) -> Self {
let duration = Duration::from_secs(3); let duration = Duration::from_secs(3);
let callback = link.callback(|_| Msg::Updating); let callback = link.callback(|_| Msg::Updating);
let task = IntervalService::new().spawn(duration, callback); let task = IntervalService::spawn(duration, callback);
Worker { Worker {
link, link,
_task: Box::new(task), _task: Box::new(task),

View File

@ -35,7 +35,7 @@ impl Agent for Worker {
fn create(link: AgentLink<Self>) -> Self { fn create(link: AgentLink<Self>) -> Self {
let duration = Duration::from_secs(3); let duration = Duration::from_secs(3);
let callback = link.callback(|_| Msg::Updating); let callback = link.callback(|_| Msg::Updating);
let task = IntervalService::new().spawn(duration, callback); let task = IntervalService::spawn(duration, callback);
link.send_message(Msg::Initialized); link.send_message(Msg::Initialized);
Worker { Worker {

View File

@ -33,7 +33,7 @@ impl Agent for Worker {
fn create(link: AgentLink<Self>) -> Self { fn create(link: AgentLink<Self>) -> Self {
let duration = Duration::from_secs(3); let duration = Duration::from_secs(3);
let callback = link.callback(|_| Msg::Updating); let callback = link.callback(|_| Msg::Updating);
let task = IntervalService::new().spawn(duration, callback); let task = IntervalService::spawn(duration, callback);
Worker { Worker {
link, link,
_task: Box::new(task), _task: Box::new(task),

View File

@ -1,26 +1,27 @@
use js_sys::{Array, Reflect}; use js_sys::{Array, Reflect};
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::JsValue;
use web_sys::console; use web_sys::console;
#[derive(Default)] use wasm_bindgen::prelude::wasm_bindgen;
pub struct CcxtService(Option<&'static JsValue>); use wasm_bindgen::JsValue;
pub struct CcxtService(&'static JsValue);
#[wasm_bindgen] #[wasm_bindgen]
extern "C" { extern "C" {
static ccxt: JsValue; static ccxt: JsValue;
} }
impl CcxtService { impl Default for CcxtService {
pub fn new() -> Self { fn default() -> CcxtService {
let lib: &JsValue = &ccxt; let lib: &JsValue = &ccxt;
CcxtService(Some(lib)) CcxtService(lib)
} }
}
impl CcxtService {
pub fn exchanges(&mut self) -> Vec<String> { pub fn exchanges(&mut self) -> Vec<String> {
let lib = self.0.as_ref().expect("ccxt library object lost");
let v = { let v = {
let exchanges = Reflect::get(lib, &JsValue::from_str("exchanges")).unwrap(); let exchanges = Reflect::get(&self.0, &JsValue::from_str("exchanges")).unwrap();
console::log_1(&exchanges); console::log_1(&exchanges);
exchanges exchanges
}; };

View File

@ -23,10 +23,6 @@ pub struct Entry {
pub struct GravatarService {} pub struct GravatarService {}
impl GravatarService { impl GravatarService {
pub fn new() -> Self {
Self {}
}
pub fn profile(&mut self, hash: &str, callback: Callback<Result<Profile, Error>>) -> FetchTask { pub fn profile(&mut self, hash: &str, callback: Callback<Result<Profile, Error>>) -> FetchTask {
let url = format!("https://en.gravatar.com/{}.json", hash); let url = format!("https://en.gravatar.com/{}.json", hash);
let handler = move |response: Response<Json<Result<Profile, Error>>>| { let handler = move |response: Response<Json<Result<Profile, Error>>>| {

View File

@ -34,8 +34,8 @@ impl Component for Model {
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self { fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
Model { Model {
link: link.clone(), link: link.clone(),
gravatar: GravatarService::new(), gravatar: GravatarService::default(),
ccxt: CcxtService::new(), ccxt: CcxtService::default(),
callback: link.callback(Msg::GravatarReady), callback: link.callback(Msg::GravatarReady),
profile: None, profile: None,
exchanges: Vec::new(), exchanges: Vec::new(),

View File

@ -6,9 +6,6 @@ use yew::{html, Callback, Component, ComponentLink, Html, ShouldRender};
pub struct Model { pub struct Model {
link: ComponentLink<Self>, link: ComponentLink<Self>,
timeout: TimeoutService,
interval: IntervalService,
console: ConsoleService,
callback_tick: Callback<()>, callback_tick: Callback<()>,
callback_done: Callback<()>, callback_done: Callback<()>,
job: Option<Box<dyn Task>>, job: Option<Box<dyn Task>>,
@ -33,14 +30,10 @@ impl Component for Model {
let callback = |_| { let callback = |_| {
println!("Example of a standalone callback."); println!("Example of a standalone callback.");
}; };
let mut interval = IntervalService::new(); let handle = IntervalService::spawn(Duration::from_secs(10), callback.into());
let handle = interval.spawn(Duration::from_secs(10), callback.into());
Model { Model {
link: link.clone(), link: link.clone(),
timeout: TimeoutService::new(),
interval,
console: ConsoleService::new(),
callback_tick: link.callback(|_| Msg::Tick), callback_tick: link.callback(|_| Msg::Tick),
callback_done: link.callback(|_| Msg::Done), callback_done: link.callback(|_| Msg::Done),
job: None, job: None,
@ -53,45 +46,43 @@ impl Component for Model {
match msg { match msg {
Msg::StartTimeout => { Msg::StartTimeout => {
{ {
let handle = self let handle =
.timeout TimeoutService::spawn(Duration::from_secs(3), self.callback_done.clone());
.spawn(Duration::from_secs(3), self.callback_done.clone());
self.job = Some(Box::new(handle)); self.job = Some(Box::new(handle));
} }
self.messages.clear(); self.messages.clear();
self.console.clear(); ConsoleService::clear();
self.messages.push("Timer started!"); self.messages.push("Timer started!");
self.console.time_named("Timer"); ConsoleService::time_named("Timer");
} }
Msg::StartInterval => { Msg::StartInterval => {
{ {
let handle = self let handle =
.interval IntervalService::spawn(Duration::from_secs(1), self.callback_tick.clone());
.spawn(Duration::from_secs(1), self.callback_tick.clone());
self.job = Some(Box::new(handle)); self.job = Some(Box::new(handle));
} }
self.messages.clear(); self.messages.clear();
self.console.clear(); ConsoleService::clear();
self.messages.push("Interval started!"); self.messages.push("Interval started!");
self.console.log("Interval started!"); ConsoleService::log("Interval started!");
} }
Msg::Cancel => { Msg::Cancel => {
self.job.take(); self.job.take();
self.messages.push("Canceled!"); self.messages.push("Canceled!");
self.console.warn("Canceled!"); ConsoleService::warn("Canceled!");
self.console.assert(self.job.is_none(), "Job still exists!"); ConsoleService::assert(self.job.is_none(), "Job still exists!");
} }
Msg::Done => { Msg::Done => {
self.messages.push("Done!"); self.messages.push("Done!");
self.console.group(); ConsoleService::group();
self.console.info("Done!"); ConsoleService::info("Done!");
self.console.time_named_end("Timer"); ConsoleService::time_named_end("Timer");
self.console.group_end(); ConsoleService::group_end();
self.job = None; self.job = None;
} }
Msg::Tick => { Msg::Tick => {
self.messages.push("Tick..."); self.messages.push("Tick...");
self.console.count_named("Tick"); ConsoleService::count_named("Tick");
} }
} }
true true

View File

@ -55,7 +55,7 @@ impl Component for Model {
// The callback to request animation frame is passed a time value which can be used for // The callback to request animation frame is passed a time value which can be used for
// rendering motion independent of the framerate which may vary. // rendering motion independent of the framerate which may vary.
let render_frame = self.link.callback(Msg::Render); let render_frame = self.link.callback(Msg::Render);
let handle = RenderService::new().request_animation_frame(render_frame); let handle = RenderService::request_animation_frame(render_frame);
// A reference to the handle must be stored, otherwise it is dropped and the render won't // A reference to the handle must be stored, otherwise it is dropped and the render won't
// occur. // occur.
@ -131,7 +131,7 @@ impl Model {
gl.draw_arrays(GL::TRIANGLES, 0, 6); gl.draw_arrays(GL::TRIANGLES, 0, 6);
let render_frame = self.link.callback(Msg::Render); let render_frame = self.link.callback(Msg::Render);
let handle = RenderService::new().request_animation_frame(render_frame); let handle = RenderService::request_animation_frame(render_frame);
// A reference to the new handle must be retained for the next render to run. // A reference to the new handle must be retained for the next render to run.
self.render_loop = Some(Box::new(handle)); self.render_loop = Some(Box::new(handle));

View File

@ -34,7 +34,7 @@ fn use_context_scoping_works() {
fn run(_props: &Self::TProps) -> Html { fn run(_props: &Self::TProps) -> Html {
if use_context::<ExampleContext>().is_some() { if use_context::<ExampleContext>().is_some() {
yew::services::ConsoleService::new().log(&format!( yew::services::ConsoleService::log(&format!(
"Context should be None here, but was {:?}!", "Context should be None here, but was {:?}!",
use_context::<ExampleContext>().unwrap() use_context::<ExampleContext>().unwrap()
)); ));

View File

@ -6,7 +6,6 @@ use yew::{html, Component, ComponentLink, Html, ShouldRender};
pub struct Model { pub struct Model {
link: ComponentLink<Self>, link: ComponentLink<Self>,
console: ConsoleService,
value: i64, value: i64,
} }
@ -20,22 +19,18 @@ impl Component for Model {
type Properties = (); type Properties = ();
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self { fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
Model { Model { link, value: 0 }
link,
console: ConsoleService::new(),
value: 0,
}
} }
fn update(&mut self, msg: Self::Message) -> ShouldRender { fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg { match msg {
Msg::Increment => { Msg::Increment => {
self.value += 1; self.value += 1;
self.console.log("plus one"); ConsoleService::log("plus one");
} }
Msg::Decrement => { Msg::Decrement => {
self.value -= 1; self.value -= 1;
self.console.log("minus one"); ConsoleService::log("minus one");
} }
} }
true true

View File

@ -31,10 +31,9 @@ impl Agent for Worker {
type Output = Response; type Output = Response;
fn create(link: AgentLink<Self>) -> Self { fn create(link: AgentLink<Self>) -> Self {
let mut interval = IntervalService::new();
let duration = Duration::from_secs(3); let duration = Duration::from_secs(3);
let callback = link.callback(|_| Msg::Updating); let callback = link.callback(|_| Msg::Updating);
let task = interval.spawn(duration, callback); let task = IntervalService::spawn(duration, callback);
Worker { Worker {
link, link,
_task: Box::new(task), _task: Box::new(task),

View File

@ -31,10 +31,9 @@ impl Agent for Worker {
type Output = Response; type Output = Response;
fn create(link: AgentLink<Self>) -> Self { fn create(link: AgentLink<Self>) -> Self {
let mut interval = IntervalService::new();
let duration = Duration::from_secs(3); let duration = Duration::from_secs(3);
let callback = link.callback(|_| Msg::Updating); let callback = link.callback(|_| Msg::Updating);
let task = interval.spawn(duration, callback); let task = IntervalService::spawn(duration, callback);
Worker { Worker {
link, link,
_task: Box::new(task), _task: Box::new(task),

View File

@ -31,10 +31,9 @@ impl Agent for Worker {
type Output = Response; type Output = Response;
fn create(link: AgentLink<Self>) -> Self { fn create(link: AgentLink<Self>) -> Self {
let mut interval = IntervalService::new();
let duration = Duration::from_secs(3); let duration = Duration::from_secs(3);
let callback = link.callback(|_| Msg::Updating); let callback = link.callback(|_| Msg::Updating);
let task = interval.spawn(duration, callback); let task = IntervalService::spawn(duration, callback);
Worker { Worker {
link, link,
_task: Box::new(task), _task: Box::new(task),

View File

@ -18,14 +18,10 @@ cfg_if! {
pub struct ConsoleService {} pub struct ConsoleService {}
impl ConsoleService { impl ConsoleService {
/// Creates a new service instance connected to `App` by provided `sender`.
pub fn new() -> Self {
Self {}
}
/// [console.log](https://developer.mozilla.org/en-US/docs/Web/API/Console/log) /// [console.log](https://developer.mozilla.org/en-US/docs/Web/API/Console/log)
/// method implementation. /// method implementation.
pub fn log(&mut self, message: &str) { /// This method outputs the provided message to the console.
pub fn log(message: &str) {
cfg_match! { cfg_match! {
feature = "std_web" => js! { @(no_return) console.log(@{message}); }, feature = "std_web" => js! { @(no_return) console.log(@{message}); },
feature = "web_sys" => console::log_1(&JsValue::from_str(message)), feature = "web_sys" => console::log_1(&JsValue::from_str(message)),
@ -34,7 +30,8 @@ impl ConsoleService {
/// [console.warn](https://developer.mozilla.org/en-US/docs/Web/API/Console/warn) /// [console.warn](https://developer.mozilla.org/en-US/docs/Web/API/Console/warn)
/// method implementation. /// method implementation.
pub fn warn(&mut self, message: &str) { /// This method outputs the provided message to the console as a warning.
pub fn warn(message: &str) {
cfg_match! { cfg_match! {
feature = "std_web" => js! { @(no_return) console.warn(@{message}); }, feature = "std_web" => js! { @(no_return) console.warn(@{message}); },
feature = "web_sys" => console::warn_1(&JsValue::from_str(message)), feature = "web_sys" => console::warn_1(&JsValue::from_str(message)),
@ -43,7 +40,8 @@ impl ConsoleService {
/// [console.info](https://developer.mozilla.org/en-US/docs/Web/API/Console/info) /// [console.info](https://developer.mozilla.org/en-US/docs/Web/API/Console/info)
/// method implementation. /// method implementation.
pub fn info(&mut self, message: &str) { /// This method outputs the provided message to the console as information.
pub fn info(message: &str) {
cfg_match! { cfg_match! {
feature = "std_web" => js! { @(no_return) console.info(@{message}); }, feature = "std_web" => js! { @(no_return) console.info(@{message}); },
feature = "web_sys" => console::info_1(&JsValue::from_str(message)), feature = "web_sys" => console::info_1(&JsValue::from_str(message)),
@ -52,7 +50,8 @@ impl ConsoleService {
/// [console.error](https://developer.mozilla.org/en-US/docs/Web/API/Console/error) /// [console.error](https://developer.mozilla.org/en-US/docs/Web/API/Console/error)
/// method implementation. /// method implementation.
pub fn error(&mut self, message: &str) { /// This method outputs the provided message to the console as an error.
pub fn error(message: &str) {
cfg_match! { cfg_match! {
feature = "std_web" => js! { @(no_return) console.error(@{message}); }, feature = "std_web" => js! { @(no_return) console.error(@{message}); },
feature = "web_sys" => console::error_1(&JsValue::from_str(message)), feature = "web_sys" => console::error_1(&JsValue::from_str(message)),
@ -61,7 +60,7 @@ impl ConsoleService {
/// [console.debug](https://developer.mozilla.org/en-US/docs/Web/API/Console/debug) /// [console.debug](https://developer.mozilla.org/en-US/docs/Web/API/Console/debug)
/// method implementation. /// method implementation.
pub fn debug(&mut self, message: &str) { pub fn debug(message: &str) {
cfg_match! { cfg_match! {
feature = "std_web" => js! { @(no_return) console.debug(@{message}); }, feature = "std_web" => js! { @(no_return) console.debug(@{message}); },
feature = "web_sys" => console::debug_1(&JsValue::from_str(message)), feature = "web_sys" => console::debug_1(&JsValue::from_str(message)),
@ -70,7 +69,7 @@ impl ConsoleService {
/// [console.count_named](https://developer.mozilla.org/en-US/docs/Web/API/Console/count_named) /// [console.count_named](https://developer.mozilla.org/en-US/docs/Web/API/Console/count_named)
/// method implementation. /// method implementation.
pub fn count_named(&mut self, name: &str) { pub fn count_named(name: &str) {
cfg_match! { cfg_match! {
feature = "std_web" => js! { @(no_return) console.count(@{name}); }, feature = "std_web" => js! { @(no_return) console.count(@{name}); },
feature = "web_sys" => console::count_with_label(name), feature = "web_sys" => console::count_with_label(name),
@ -79,7 +78,7 @@ impl ConsoleService {
/// [console.count](https://developer.mozilla.org/en-US/docs/Web/API/Console/count) /// [console.count](https://developer.mozilla.org/en-US/docs/Web/API/Console/count)
/// method implementation. /// method implementation.
pub fn count(&mut self) { pub fn count() {
cfg_match! { cfg_match! {
feature = "std_web" => js! { @(no_return) console.count(); }, feature = "std_web" => js! { @(no_return) console.count(); },
feature = "web_sys" => console::count(), feature = "web_sys" => console::count(),
@ -88,7 +87,7 @@ impl ConsoleService {
/// [console.time_named](https://developer.mozilla.org/en-US/docs/Web/API/Console/time_named) /// [console.time_named](https://developer.mozilla.org/en-US/docs/Web/API/Console/time_named)
/// method implementation. /// method implementation.
pub fn time_named(&mut self, name: &str) { pub fn time_named(name: &str) {
cfg_match! { cfg_match! {
feature = "std_web" => js! { @(no_return) console.time(@{name}); }, feature = "std_web" => js! { @(no_return) console.time(@{name}); },
feature = "web_sys" => console::time_with_label(name), feature = "web_sys" => console::time_with_label(name),
@ -97,7 +96,7 @@ impl ConsoleService {
/// [console.time_named_end](https://developer.mozilla.org/en-US/docs/Web/API/Console/time_named_end) /// [console.time_named_end](https://developer.mozilla.org/en-US/docs/Web/API/Console/time_named_end)
/// method implementation. /// method implementation.
pub fn time_named_end(&mut self, name: &str) { pub fn time_named_end(name: &str) {
cfg_match! { cfg_match! {
feature = "std_web" => js! { @(no_return) console.timeEnd(@{name}); }, feature = "std_web" => js! { @(no_return) console.timeEnd(@{name}); },
feature = "web_sys" => console::time_end_with_label(name), feature = "web_sys" => console::time_end_with_label(name),
@ -106,7 +105,7 @@ impl ConsoleService {
/// [console.time](https://developer.mozilla.org/en-US/docs/Web/API/Console/time) /// [console.time](https://developer.mozilla.org/en-US/docs/Web/API/Console/time)
/// method implementation. /// method implementation.
pub fn time(&mut self) { pub fn time() {
cfg_match! { cfg_match! {
feature = "std_web" => js! { @(no_return) console.time(); }, feature = "std_web" => js! { @(no_return) console.time(); },
feature = "web_sys" => console::time(), feature = "web_sys" => console::time(),
@ -114,7 +113,7 @@ impl ConsoleService {
} }
/// [console.time_end](https://developer.mozilla.org/en-US/docs/Web/API/Console/time_end) /// [console.time_end](https://developer.mozilla.org/en-US/docs/Web/API/Console/time_end)
/// method implementation. /// method implementation.
pub fn time_end(&mut self) { pub fn time_end() {
cfg_match! { cfg_match! {
feature = "std_web" => js! { @(no_return) console.timeEnd(); }, feature = "std_web" => js! { @(no_return) console.timeEnd(); },
feature = "web_sys" => console::time_end(), feature = "web_sys" => console::time_end(),
@ -123,7 +122,7 @@ impl ConsoleService {
/// [console.clear](https://developer.mozilla.org/en-US/docs/Web/API/Console/clear) /// [console.clear](https://developer.mozilla.org/en-US/docs/Web/API/Console/clear)
/// method implementation. /// method implementation.
pub fn clear(&mut self) { pub fn clear() {
cfg_match! { cfg_match! {
feature = "std_web" => js! { @(no_return) console.clear(); }, feature = "std_web" => js! { @(no_return) console.clear(); },
feature = "web_sys" => console::clear(), feature = "web_sys" => console::clear(),
@ -132,7 +131,7 @@ impl ConsoleService {
/// [console.group](https://developer.mozilla.org/en-US/docs/Web/API/Console/group) /// [console.group](https://developer.mozilla.org/en-US/docs/Web/API/Console/group)
/// method implementation. /// method implementation.
pub fn group(&mut self) { pub fn group() {
cfg_match! { cfg_match! {
feature = "std_web" => js! { @(no_return) console.group(); }, feature = "std_web" => js! { @(no_return) console.group(); },
feature = "web_sys" => console::group_0(), feature = "web_sys" => console::group_0(),
@ -141,7 +140,7 @@ impl ConsoleService {
/// [console.group_collapsed](https://developer.mozilla.org/en-US/docs/Web/API/Console/group_collapsed) /// [console.group_collapsed](https://developer.mozilla.org/en-US/docs/Web/API/Console/group_collapsed)
/// method implementation. /// method implementation.
pub fn group_collapsed(&mut self) { pub fn group_collapsed() {
cfg_match! { cfg_match! {
feature = "std_web" => js! { @(no_return) console.groupCollapsed(); }, feature = "std_web" => js! { @(no_return) console.groupCollapsed(); },
feature = "web_sys" => console::group_collapsed_0(), feature = "web_sys" => console::group_collapsed_0(),
@ -150,7 +149,7 @@ impl ConsoleService {
/// [console.group_end](https://developer.mozilla.org/en-US/docs/Web/API/Console/group_end) /// [console.group_end](https://developer.mozilla.org/en-US/docs/Web/API/Console/group_end)
/// method implementation. /// method implementation.
pub fn group_end(&mut self) { pub fn group_end() {
cfg_match! { cfg_match! {
feature = "std_web" => js! { @(no_return) console.groupEnd(); }, feature = "std_web" => js! { @(no_return) console.groupEnd(); },
feature = "web_sys" => console::group_end(), feature = "web_sys" => console::group_end(),
@ -159,7 +158,8 @@ impl ConsoleService {
/// [console.trace](https://developer.mozilla.org/en-US/docs/Web/API/Console/trace) /// [console.trace](https://developer.mozilla.org/en-US/docs/Web/API/Console/trace)
/// method implementation. /// method implementation.
pub fn trace(&mut self) { /// This method outputs the current stack trace to the console.
pub fn trace() {
cfg_match! { cfg_match! {
feature = "std_web" => js! { @(no_return) console.trace(); }, feature = "std_web" => js! { @(no_return) console.trace(); },
feature = "web_sys" => console::trace_0(), feature = "web_sys" => console::trace_0(),
@ -168,7 +168,7 @@ impl ConsoleService {
/// [console.assert](https://developer.mozilla.org/en-US/docs/Web/API/Console/assert) /// [console.assert](https://developer.mozilla.org/en-US/docs/Web/API/Console/assert)
/// method implementation. /// method implementation.
pub fn assert(&mut self, condition: bool, message: &str) { pub fn assert(condition: bool, message: &str) {
cfg_match! { cfg_match! {
feature = "std_web" => js! { @(no_return) console.assert(@{condition}, @{message}); }, feature = "std_web" => js! { @(no_return) console.assert(@{condition}, @{message}); },
feature = "web_sys" => console::assert_with_condition_and_data_1(condition, &String::from(message).into()), feature = "web_sys" => console::assert_with_condition_and_data_1(condition, &String::from(message).into()),

View File

@ -18,14 +18,9 @@ cfg_if! {
pub struct DialogService {} pub struct DialogService {}
impl DialogService { impl DialogService {
/// Creates a new service instance connected to `App` by provided `sender`.
pub fn new() -> Self {
Self {}
}
/// Calls [alert](https://developer.mozilla.org/en-US/docs/Web/API/Window/alert) /// Calls [alert](https://developer.mozilla.org/en-US/docs/Web/API/Window/alert)
/// function. /// function.
pub fn alert(&mut self, message: &str) { pub fn alert(message: &str) {
cfg_match! { cfg_match! {
feature = "std_web" => js! { @(no_return) alert(@{message}); }, feature = "std_web" => js! { @(no_return) alert(@{message}); },
feature = "web_sys" => utils::window().alert_with_message(message).unwrap(), feature = "web_sys" => utils::window().alert_with_message(message).unwrap(),
@ -34,7 +29,7 @@ impl DialogService {
/// Calls [confirm](https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm) /// Calls [confirm](https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm)
/// function. /// function.
pub fn confirm(&mut self, message: &str) -> bool { pub fn confirm(message: &str) -> bool {
cfg_match! { cfg_match! {
feature = "std_web" => ({ feature = "std_web" => ({
let value: Value = js! { return confirm(@{message}); }; let value: Value = js! { return confirm(@{message}); };

View File

@ -161,11 +161,6 @@ impl fmt::Debug for FetchTask {
pub struct FetchService {} pub struct FetchService {}
impl FetchService { impl FetchService {
/// Creates a new service instance connected to `App` by provided `sender`.
pub fn new() -> Self {
Self {}
}
/// Sends a request to a remote server given a Request object and a callback /// Sends a request to a remote server given a Request object and a callback
/// function to convert a Response object into a loop's message. /// function to convert a Response object into a loop's message.
/// ///

View File

@ -163,11 +163,6 @@ impl fmt::Debug for FetchTask {
pub struct FetchService {} pub struct FetchService {}
impl FetchService { impl FetchService {
/// Creates a new service instance connected to `App` by provided `sender`.
pub fn new() -> Self {
Self {}
}
/// Sends a request to a remote server given a Request object and a callback /// Sends a request to a remote server given a Request object and a callback
/// fuction to convert a Response object into a loop's message. /// fuction to convert a Response object into a loop's message.
/// ///

View File

@ -36,14 +36,9 @@ impl fmt::Debug for IntervalTask {
pub struct IntervalService {} pub struct IntervalService {}
impl IntervalService { impl IntervalService {
/// Creates a new service instance connected to `App` by provided `sender`.
pub fn new() -> Self {
Self {}
}
/// Sets interval which will call send a messages returned by a converter /// Sets interval which will call send a messages returned by a converter
/// on every intarval expiration. /// on every intarval expiration.
pub fn spawn(&mut self, duration: Duration, callback: Callback<()>) -> IntervalTask { pub fn spawn(duration: Duration, callback: Callback<()>) -> IntervalTask {
let callback = move || { let callback = move || {
callback.emit(()); callback.emit(());
}; };

View File

@ -38,13 +38,14 @@ pub use self::websocket::WebSocketService;
use std::time::Duration; use std::time::Duration;
/// An universal task of a service. /// An universal task of a service.
/// It have to be canceled when dropped. /// The task must be handled when it is cancelled.
pub trait Task: Drop { pub trait Task: Drop {
/// Returns `true` if task is active. /// Returns `true` if task is active.
fn is_active(&self) -> bool; fn is_active(&self) -> bool;
} }
#[doc(hidden)] #[doc(hidden)]
/// Converts a `Duration` into milliseconds.
fn to_ms(duration: Duration) -> u32 { fn to_ms(duration: Duration) -> u32 {
let ms = duration.subsec_millis(); let ms = duration.subsec_millis();
ms + duration.as_secs() as u32 * 1000 ms + duration.as_secs() as u32 * 1000

View File

@ -44,13 +44,8 @@ impl fmt::Debug for RenderTask {
pub struct RenderService {} pub struct RenderService {}
impl RenderService { impl RenderService {
/// Create a new instance of the service.
pub fn new() -> Self {
Self {}
}
/// Request animation frame. Callback will be notified when frame should be rendered. /// Request animation frame. Callback will be notified when frame should be rendered.
pub fn request_animation_frame(&mut self, callback: Callback<f64>) -> RenderTask { pub fn request_animation_frame(callback: Callback<f64>) -> RenderTask {
let callback = move |#[cfg(feature = "std_web")] v, let callback = move |#[cfg(feature = "std_web")] v,
#[cfg(feature = "web_sys")] v: JsValue| { #[cfg(feature = "web_sys")] v: JsValue| {
let time: f64 = cfg_match! { let time: f64 = cfg_match! {

View File

@ -35,13 +35,8 @@ impl fmt::Debug for TimeoutTask {
pub struct TimeoutService {} pub struct TimeoutService {}
impl TimeoutService { impl TimeoutService {
/// Creates a new service instance connected to `App` by provided `sender`.
pub fn new() -> Self {
Self {}
}
/// Sets timeout which sends messages from a `converter` after `duration`. /// Sets timeout which sends messages from a `converter` after `duration`.
pub fn spawn(&mut self, duration: Duration, callback: Callback<()>) -> TimeoutTask { pub fn spawn(duration: Duration, callback: Callback<()>) -> TimeoutTask {
let callback = move || { let callback = move || {
callback.emit(()); callback.emit(());
}; };

View File

@ -69,15 +69,9 @@ impl fmt::Debug for WebSocketTask {
pub struct WebSocketService {} pub struct WebSocketService {}
impl WebSocketService { impl WebSocketService {
/// Creates a new service instance connected to `App` by provided `sender`.
pub fn new() -> Self {
Self {}
}
/// Connects to a server by a websocket connection. Needs two functions to generate /// Connects to a server by a websocket connection. Needs two functions to generate
/// data and notification messages. /// data and notification messages.
pub fn connect<OUT: 'static>( pub fn connect<OUT: 'static>(
&mut self,
url: &str, url: &str,
callback: Callback<OUT>, callback: Callback<OUT>,
notification: Callback<WebSocketStatus>, notification: Callback<WebSocketStatus>,
@ -87,14 +81,14 @@ impl WebSocketService {
{ {
cfg_match! { cfg_match! {
feature = "std_web" => ({ feature = "std_web" => ({
let ws = self.connect_common(url, &notification)?.0; let ws = Self::connect_common(url, &notification)?.0;
ws.add_event_listener(move |event: SocketMessageEvent| { ws.add_event_listener(move |event: SocketMessageEvent| {
process_both(&event, &callback); process_both(&event, &callback);
}); });
Ok(WebSocketTask { ws, notification }) Ok(WebSocketTask { ws, notification })
}), }),
feature = "web_sys" => ({ feature = "web_sys" => ({
let ConnectCommon(ws, listeners) = self.connect_common(url, &notification)?; let ConnectCommon(ws, listeners) = Self::connect_common(url, &notification)?;
let listener = EventListener::new(&ws, "message", move |event: &Event| { let listener = EventListener::new(&ws, "message", move |event: &Event| {
let event = event.dyn_ref::<MessageEvent>().unwrap(); let event = event.dyn_ref::<MessageEvent>().unwrap();
process_both(&event, &callback); process_both(&event, &callback);
@ -109,7 +103,6 @@ impl WebSocketService {
/// ignored. Needs two functions to generate data and notification /// ignored. Needs two functions to generate data and notification
/// messages. /// messages.
pub fn connect_binary<OUT: 'static>( pub fn connect_binary<OUT: 'static>(
&mut self,
url: &str, url: &str,
callback: Callback<OUT>, callback: Callback<OUT>,
notification: Callback<WebSocketStatus>, notification: Callback<WebSocketStatus>,
@ -119,14 +112,14 @@ impl WebSocketService {
{ {
cfg_match! { cfg_match! {
feature = "std_web" => ({ feature = "std_web" => ({
let ws = self.connect_common(url, &notification)?.0; let ws = Self::connect_common(url, &notification)?.0;
ws.add_event_listener(move |event: SocketMessageEvent| { ws.add_event_listener(move |event: SocketMessageEvent| {
process_binary(&event, &callback); process_binary(&event, &callback);
}); });
Ok(WebSocketTask { ws, notification }) Ok(WebSocketTask { ws, notification })
}), }),
feature = "web_sys" => ({ feature = "web_sys" => ({
let ConnectCommon(ws, listeners) = self.connect_common(url, &notification)?; let ConnectCommon(ws, listeners) = Self::connect_common(url, &notification)?;
let listener = EventListener::new(&ws, "message", move |event: &Event| { let listener = EventListener::new(&ws, "message", move |event: &Event| {
let event = event.dyn_ref::<MessageEvent>().unwrap(); let event = event.dyn_ref::<MessageEvent>().unwrap();
process_binary(&event, &callback); process_binary(&event, &callback);
@ -141,7 +134,6 @@ impl WebSocketService {
/// ignored. Needs two functions to generate data and notification /// ignored. Needs two functions to generate data and notification
/// messages. /// messages.
pub fn connect_text<OUT: 'static>( pub fn connect_text<OUT: 'static>(
&mut self,
url: &str, url: &str,
callback: Callback<OUT>, callback: Callback<OUT>,
notification: Callback<WebSocketStatus>, notification: Callback<WebSocketStatus>,
@ -151,14 +143,14 @@ impl WebSocketService {
{ {
cfg_match! { cfg_match! {
feature = "std_web" => ({ feature = "std_web" => ({
let ws = self.connect_common(url, &notification)?.0; let ws = Self::connect_common(url, &notification)?.0;
ws.add_event_listener(move |event: SocketMessageEvent| { ws.add_event_listener(move |event: SocketMessageEvent| {
process_text(&event, &callback); process_text(&event, &callback);
}); });
Ok(WebSocketTask { ws, notification }) Ok(WebSocketTask { ws, notification })
}), }),
feature = "web_sys" => ({ feature = "web_sys" => ({
let ConnectCommon(ws, listeners) = self.connect_common(url, &notification)?; let ConnectCommon(ws, listeners) = Self::connect_common(url, &notification)?;
let listener = EventListener::new(&ws, "message", move |event: &Event| { let listener = EventListener::new(&ws, "message", move |event: &Event| {
let event = event.dyn_ref::<MessageEvent>().unwrap(); let event = event.dyn_ref::<MessageEvent>().unwrap();
process_text(&event, &callback); process_text(&event, &callback);
@ -169,10 +161,9 @@ impl WebSocketService {
} }
fn connect_common( fn connect_common(
&mut self,
url: &str, url: &str,
notification: &Callback<WebSocketStatus>, notification: &Callback<WebSocketStatus>,
) -> Result<ConnectCommon, &str> { ) -> Result<ConnectCommon, &'static str> {
let ws = WebSocket::new(url); let ws = WebSocket::new(url);
if ws.is_err() { if ws.is_err() {
return Err("Failed to created websocket with given URL"); return Err("Failed to created websocket with given URL");
@ -379,8 +370,7 @@ mod tests {
let status_future = CallbackFuture::<WebSocketStatus>::default(); let status_future = CallbackFuture::<WebSocketStatus>::default();
let notification: Callback<_> = status_future.clone().into(); let notification: Callback<_> = status_future.clone().into();
let mut ws = WebSocketService::new(); let mut task = WebSocketService::connect(url, callback, notification).unwrap();
let mut task = ws.connect(url, callback, notification).unwrap();
assert_eq!(status_future.await, WebSocketStatus::Opened); assert_eq!(status_future.await, WebSocketStatus::Opened);
let msg = Message { let msg = Message {
@ -408,8 +398,7 @@ mod tests {
let status_future = CallbackFuture::<WebSocketStatus>::default(); let status_future = CallbackFuture::<WebSocketStatus>::default();
let notification: Callback<_> = status_future.clone().into(); let notification: Callback<_> = status_future.clone().into();
let mut ws = WebSocketService::new(); let mut task = WebSocketService::connect_text(url, callback, notification).unwrap();
let mut task = ws.connect_text(url, callback, notification).unwrap();
assert_eq!(status_future.await, WebSocketStatus::Opened); assert_eq!(status_future.await, WebSocketStatus::Opened);
let msg = Message { let msg = Message {
@ -440,8 +429,7 @@ mod tests {
let status_future = CallbackFuture::<WebSocketStatus>::default(); let status_future = CallbackFuture::<WebSocketStatus>::default();
let notification: Callback<_> = status_future.clone().into(); let notification: Callback<_> = status_future.clone().into();
let mut ws = WebSocketService::new(); let mut task = WebSocketService::connect_binary(url, callback, notification).unwrap();
let mut task = ws.connect_binary(url, callback, notification).unwrap();
assert_eq!(status_future.await, WebSocketStatus::Opened); assert_eq!(status_future.await, WebSocketStatus::Opened);
let msg = Message { let msg = Message {