text
stringlengths
14
100k
source
stringclasses
1 value
repo
stringclasses
810 values
language
stringclasses
13 values
<|fim_suffix|>h, the main thread can never /// claim a task while it's blocked by the event loop. pub fn tao_waker(proxy: EventLoopProxy<UserWindowEvent>, id: WindowId) -> std::task::Waker { struct DomHandle { proxy: EventLoopProxy<UserWindowEvent>, id: WindowId, } // this should be impleme...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>{ let menu_option = cfg.menu.into(); if let Some(menu) = &menu_option { crate::menubar::init_menu_bar(menu, &window); } menu_option } else { None }; #[cfg(target_os = "windows")] { use ...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use dioxus_core::internal::HotReloadedTemplate; use dioxus_core::{ScopeId, VirtualDom}; use dioxus_signals::{GlobalKey, Signal, WritableExt}; pub use dioxus_devtools_types::*; pub use subsecond; use subsecond::PatchError; /// Applies template and literal changes to the VirtualDom /// /// Assets need to ...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use dioxus_core::internal::HotReloadTemplateWithLocation; use serde::{Deserialize, Serialize}; use std::path::PathBuf; use subsecond_types::JumpTable; /// A message the hot reloading server sends to the client #[non_exhaustive] #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] pub enum Devserver...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>#![allow(non_snake_case, non_upper_case_globals)] //! This benchmark tests just the overhead of Dioxus itself. //! //! For the JS Framework Benchmark, both the framework and the browser is benchmarked together. Dioxus prepares changes //! to be made, but the change application phase will be just as perfor...
fim
DioxusLabs/dioxus
rust
#![allow(clippy::new_without_default)] #![allow(unused)] use dioxus_config_macro::*; use dioxus_core::{Element, LaunchConfig}; use std::any::Any; use crate::prelude::*; /// Launch your Dioxus application with the given root component, context and config. /// The platform will be determined from cargo features. /// //...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>#![doc = include_str!("../README.md")] //! //! ## Dioxus Crate Features //! //! This crate has several features that can be enabled to change the active renderer and enable various integrations: //! //! - `signals`: (default) re-exports `dioxus-signals` //! - `macro`: (default) re-exports `dioxus-macro` /...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>// this script is included as an a<|fim_suffix|> for a test <|fim_middle|>sset!()<|endoftext|>
fim
DioxusLabs/dioxus
javascript
<|fim_prefix|>fn<|fim_suffix|>() .with_watching("./src/ts") .with_binding("./src/ts/head.ts", "./src/js/head.js") .run(); } <|fim_middle|> main() { // If any TS files change, re-run the build script lazy_js_bundle::LazyTypeScriptBindings::new<|endoftext|>
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use std::sync::Arc; use super::*; /// A context for the document pub type DocumentContext = Arc<dyn Document>; fn format_string_for_js(s: &str) -> String { let escaped = s .replace('\\', "\\\\") .replace('\n', "\\n") .replace('\r', "\\r") .replace('"', "\\\""); f...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>_update_warning(&props, "Link {}"); use_hook(|| { let document = document(); let mut insert_link = document.create_head_component(); if let Some(href) = &props.href && !should_insert_link(href, props.rel.as_deref()) { insert_link = false; ...
fim
DioxusLabs/dioxus
rust
use super::*; use crate::document; use dioxus_core::{VNode, use_hook}; use dioxus_html as dioxus_elements; #[non_exhaustive] /// Props for the [`Meta`] component #[derive(Clone, Props, PartialEq)] pub struct MetaProps { pub property: Option<String>, pub name: Option<String>, pub charset: Option<String>, ...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>#![doc = include_str!("../../docs/head.md")] use std::{cell::RefCell, collections::HashSet, rc::Rc}; use dioxus_core::{Attribute, DynamicNode, Element, RenderError, Runtime, ScopeId, TemplateNode}; use dioxus_core_macro::*; mod link; pub use link::*; mod stylesheet; pub use stylesheet::*; mod meta; pub...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use super::*; use crate::document; use dioxus_core::{VNode, use_hook}; use dioxus_html as dioxus_elements; #[non_exhaustive] #[derive(Clone, Props, PartialEq)] pub struct ScriptProps { /// The contents of the script tag. If present, the children must be a single text node. pub children: Element, ...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|> .should_insert(href) } <|fim_prefix|>use super::*; use crate::document; use dioxus_core::{VNode, use_hook}; use dioxus_html as dioxus_elements; #[non_exhaustive] #[derive(Clone, Props, PartialEq)] pub struct StyleProps { /// Styles are deduplicated by their href attribute pub href: Option<String...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>ment { super::Link(LinkProps { rel: Some("stylesheet".into()), r#type: Some("text/css".into()), ..props }) } <|fim_prefix|>use <|fim_middle|>super::*; /// Render a [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/link) tag into the head of th...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use dioxus_core::{VNode, use_hook}; use crate::document; use super::*; #[derive(Clone, Props, PartialEq)] pub struct TitleProps { /// The contents of the title tag. The children must be a single text node. children: Element, } /// Render the title of the page. On web renderers, this will set t...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>l Error for EvalError {} <|fim_prefix|>use std::error::Error; use std::fmt::Display; /// Represents an error when evaluating JavaScript #[derive(Debug)] #[non_exhaustive] pub enum EvalError { /// The platform does not support evaluating JavaScript. Unsupported, /// The provided JavaScript ha...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>), } } /// Receive a message from the javascript task pub async fn recv<T: serde::de::DeserializeOwned>(&mut self) -> Result<T, EvalError> { let json_value = poll_fn(|cx| match self.evaluator.try_write() { Ok(mut evaluator) => evaluator.poll_recv(cx), E...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>var createElementInHead=function(tag,attributes,children){const element=document.createElement(tag);for(let[key<|fim_suffix|>ment.createTextNode(children));document.head.appendChild(element)};window.createElementInHead=createElementInHead; <|fim_middle|>,value]of attributes)element.setAttribute(key,value)...
fim
DioxusLabs/dioxus
javascript
<|fim_suffix|>t: &str) -> Eval { document().eval(script.to_string()) } <|fim_prefix|>use std::rc::Rc; mod document; mod elements; mod error; mod eval; pub use document::*; pub use elements::*; pub use error::*; pub use eval::*; /// Get the document provider for the current platform or a no-op provider if the pla...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>// Handle communication between rust and evaluating javascript export class Channel { pending: any[]; waiting: ((data: any) => void)[]; constructor() { this.pending = []; this.waiting = []; } send(data: any) { // If there's a waiting callback, call it if (this.waiting.length >...
fim
DioxusLabs/dioxus
typescript
<|fim_suffix|>pendChild(document.createTextNode(children)); } document.head.appendChild(element); } // @ts-ignore window.createElementInHead = createElementInHead; <|fim_prefix|>// Helper functions for working with the document head functio<|fim_middle|>n createElementInHead( tag: string, attributes: [string,...
fim
DioxusLabs/dioxus
typescript
use cargo_metadata::{CompilerMessage, diagnostic::Diagnostic}; use manganis_core::BundledAsset; use serde::{Deserialize, Serialize}; use std::{borrow::Cow, collections::HashSet, path::PathBuf}; use subsecond_types::JumpTable; pub use cargo_metadata; /// The structured output for the CLI /// /// This is designed such ...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>/**@type {import('eslint').Linter.C<|fim_suffix|>s: [ 'eslint:recommended', 'plugin:@typescript-eslint/recommended', ], rules: { 'semi': [2, "always"], '@typescript-eslint/no-unused-vars': 0, '@typescript-eslint/no-explicit-any': 0, '@typescript-eslint/explicit-module-boundary-types': 0, '...
fim
DioxusLabs/dioxus
javascript
<|fim_suffix|> }, indent_size, false, ), ); block.unwrap() } #[wasm_bindgen] pub fn format_selection( raw: String, use_tabs: bool, indent_size: usize, base_indent: usize, ) -> String { let block = dioxus_autofmt::fmt_block( &raw, bas...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>formatDocument(editor.document); if (edits.length > 0) { const workspaceEdit = new vscode.WorkspaceEdit(); for (const edit of edits) { workspaceEdit.replace(editor.document.uri, edit.range, edit.newText); } await vscode.workspace.applyEdit(workspaceEdit); } } function fmtSelection() { const...
fim
DioxusLabs/dioxus
typescript
<|fim_prefix|>//@ts-check 'use strict'; const path = require('path'); con<|fim_suffix|> imported node modules extensions: ['.ts', '.js'], alias: { // provides alternate implementation for node module and source files }, fallback: { // Webpack 5 no longer polyfills Node.js core modules autom...
fim
DioxusLabs/dioxus
javascript
<|fim_prefix|>#![allow(unreachable_code)] use crate::{StreamingError, reqwest_error_to_request_error}; use bytes::Bytes; use dioxus_fullstack_core::RequestError; use futures::Stream; use futures::{TryFutureExt, TryStreamExt}; use headers::{ContentType, Header}; use http::{Extensions, HeaderMap, HeaderName, HeaderValue...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use bytes::Bytes; use serde::{Serialize, de::DeserializeOwned}; /// A trait for encoding and decoding data. /// /// This takes an owned self to make it easier for zero-copy encodings. pub trait Encoding: 'static { fn content_type() -> &'static str; fn stream_content_type() -> &'static str; fn...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>ck that allows us to staple the async initialization into a blocking context. /// /// We call the `rust-call` method of the zero-sized constructor function. This is safe because we're /// not actually dereferencing any unsafe data, just calling its vtable entry to get the future. fn blocking_initialize<T,...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>ature = "msgpack")] pub use msgpack::*; pub mod text; pub use text::*; pub mod sse; pub use sse::*; pub mod stream; pub use stream::*; pub mod files; pub use files::*; pub mod header; pub use header::*; pub mod query; pub use query::*; #[cfg(f...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>, O> where T: 'static, { type VerifyEncode = CantEncode; #[allow(clippy::manual_async_fn)] fn fetch_client( &self, _ctx: ClientRequest, _data: T, _map: fn(T) -> O, ) -> impl Future<Output = Result<ClientRespons...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|> `axum::extract::Request`. /// /// This allows converting an `axum::Request` (from server-side extraction) /// into a `ClientRequest` that can be sent as an HTTP request. The request's /// headers and body are transferred from the axum request to the client request. impl IntoRequest for axum::extract::Req...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use axum::{ body::Bytes, extract::{FromRequest, Request, rejection::BytesRejection}, http::{HeaderMap, HeaderValue, StatusCode, header}, response::{IntoResponse, Response}, }; use serde::{Serialize, de::DeserializeOwned}; /// CBOR Extractor / Response. /// /// When used as an extractor, i...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|> return builder .header("Content-Type", content_type)? .send_body_stream(stream) .await; } unimplemented!("FileStream::into_request is only implemented for web targets"); } } } impl<S> FromRequest...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use super::*; pub use axum::extract::Form; impl<T> IntoR<|fim_suffix|>erialize + 'static + DeserializeOwned, { fn into_request(self, req: ClientRequest) -> impl Future<Output = ClientResult> + 'static { async move { req.send_form(&self.0).await } } } <|fim_middle|>equest for Form<T> wher...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use super::*; pub use headers::Cookie; pub use headers::SetCookie; #[derive(Clone, Debug)] pub struct SetHeader<Data> { data: Option<Data>, } impl<T: Header> SetHeader<T> { pub fn new( value: impl TryInto<HeaderValue, Error = InvalidHeaderValue>, ) -> Result<Self, headers::Error> { ...
fim
DioxusLabs/dioxus
rust
#![forbid(unsafe_code)] use axum::{BoxError, extract::rejection::BytesRejection, http}; use axum::{ body::{Body, Bytes}, extract::{FromRequest, Request}, http::{StatusCode, header::HeaderValue}, response::{IntoResponse, Response}, }; use derive_more::{Deref, DerefMut, From}; use serde::{Serialize, de::...
fim
DioxusLabs/dioxus
rust
#![allow(unreachable_code)] use crate::{ClientRequest, ClientResponse, IntoRequest}; use axum::{ extract::{FromRequest, Request}, response::{IntoResponse, Response}, }; use dioxus_fullstack_core::RequestError; use dioxus_html::{FormData, FormEvent}; use std::{prelude::rust_2024::Future, rc::Rc}; #[cfg(feature...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>dContentType) } } } } fn postcard_content_type(headers: &HeaderMap) -> bool { let content_type = if let Some(content_type) = headers.get(header::CONTENT_TYPE) { content_type } else { return false; }; let content_type = if let Ok(content_type) = con...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use std::ops::Deref; use crate::ServerFnError; use axum::extract::FromRequestParts; use http::request::Parts; use serde::de::DeserializeOwned; /// An extractor that deserializes query parameters into the given type `T`. /// /// This uses `serde_qs` under the hood to support complex query parameter struc...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>er.set_retry(Duration::from_millis(millis)); } } _ => {} } } }, ); Ok(Self { _marker: std::marker::PhantomData, client: Some(stream), ...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>0u8; 10]; E::encode(data, &mut bytes)?; let len = (bytes.len() - 10) as u64; let opcode = 0x82; // FIN + binary opcode // Write the header directly into the allocated space. let offset = if len <= 125 { bytes[8] = opcode; bytes[9] = len as u8; 8 } else if...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use crate::{ClientResponse,<|fim_suffix|> }) } } <|fim_middle|> FromResponse}; use axum_core::response::{IntoResponse, Response}; use dioxus_fullstack_core::ServerFnError; use send_wrapper::SendWrapper; use std::future::Future; /// A simple text response type. /// /// The `T` parameter can be an...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>de: close_frame.code.into(), description: close_frame.reason.to_string(), }))); } AxumMessage::Close(None) => { return Poll::Ready(Some(Err(WebsocketError::AlreadyClosed))); ...
fim
DioxusLabs/dioxus
rust
use dioxus_fullstack_core::{RequestError, ServerFnError}; #[cfg(feature = "server")] use headers::Header; use http::response::Parts; use std::{future::Future, pin::Pin}; use crate::{ClientRequest, ClientResponse, ErrorPayload}; /// The `IntoRequest` trait allows types to be used as the body of a request to a HTTP end...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use std::future::Future; /// Spawn a task in the background. If wasm is enabled, this will use the single threaded tokio runtime pub(crate) fn spawn_platform<Fut>( f: impl FnOnce() -> Fut + Send + 'static, ) -> tokio::task::JoinHandle<Fut::Output> where Fut: Future + 'static, Fut::Output: Sen...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>#![allow(clippy::manual_async_fn)] #![allow(unused_variables)] use anyhow::Result; use axum::extract::FromRequest; use axum::response::IntoResponse; use axum::{Json, response::Html}; use byte<|fim_suffix|>; use http::StatusCode; use http_body_util::BodyExt; use serde::{Deserialize, Serialize}; use std::f...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|> } } impl<D: Document> Document for FullstackWebDocument<D> { fn eval(&self, js: String) -> Eval { self.document.eval(js) } /// Set the title of the document fn set_title(&self, title: String) { self.document.set_title(title); } /// Create a new meta tag in the h...
fim
DioxusLabs/dioxus
rust
use axum_core::response::IntoResponse; use futures_util::TryStreamExt; use http::StatusCode; use serde::{Deserialize, Serialize}; use std::fmt::Debug; use crate::HttpError; /// A default result type for server functions, which can either be successful or contain an error. The [`ServerFnResult`] type /// is a convenie...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! Contains a hydration compatible error bound<|fim_suffix|>(err)) = initial_error.get() { errors.insert_error(err); } rx_context.run_in(|| { errors.error(); }); spawn_isomorphic({ let errors = errors.clone(); async move { if rx.next().await.is_...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>y<H> { fn current_prefix(&self) -> Option<String> { self.history.current_prefix() } fn can_go_back(&self) -> bool { match_hydration(|| false, || self.history.can_go_back()) } fn can_go_forward(&self) -> bool { match_hydration(|| false, || self.history.can_go_f...
fim
DioxusLabs/dioxus
rust
use axum_core::response::IntoResponse; use http::StatusCode; use std::fmt; /// An error type that wraps an HTTP status code and optional message. #[derive(Debug, Clone, PartialEq)] pub struct HttpError { pub status: StatusCode, pub message: Option<String>, } impl HttpError { pub fn new<M: Into<String>>(st...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>t::*; /// Error types and utilities. #[macro_use] pub mod error; pub use error::*; pub mod httperror; pub use httperror::*; <|fim_prefix|>// #![warn(missing_docs)] #![doc = include_str!("../README.md")] pub mod d<|fim_middle|>ocument; pub mod history; mod errors; mod loader; mod server_cached; mod ser...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use dioxus_core::{CapturedError, RenderError, Result, SuspendedFuture}; use dioxus_core::{IntoAttributeValue, IntoDynNode, Subscribers, use_hook}; use dioxus_hooks::{Resource, use_resource, use_signal}; use dioxus_signals::{ ReadSignal, Readable, ReadableBoxExt, ReadableExt, ReadableRef, Signal, Writa...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>one, M: 'static, { let location = std::panic::Location::caller(); use_hook(|| server_cached(server_fn, location)) } pub(crate) fn server_cached<O, M>( value: impl FnOnce() -> O, #[allow(unused)] location: &'static std::panic::Location<'static>, ) -> O where O: Transportable<M> + C...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use crate::Transport<|fim_suffix|>resource.state().cloned() == UseResourceState::Pending { let task = resource.task(); if !task.paused() { return Err(suspend(task).unwrap_err()); } } Ok(resource) } <|fim_middle|>able; use dioxus_core::{RenderError, suspend, use...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>AL_SERVER_ERROR } <|fim_prefix|>use crate::{HttpError, ServerFnError}; use axum_core::extract::FromRequest; use a<|fim_middle|>xum_core::response::IntoResponse; use dioxus_core::{CapturedError, ReactiveContext}; use http::StatusCode; use http::{HeaderMap, request::Parts}; use parking_lot::RwLock; use std:...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>#![warn(missing_docs)] #![doc = include_str!("../README.md")] use base64::Engine; use dioxus_core::CapturedError; use serde::{Deserialize, Serialize, de::DeserializeOwned}; use std::{cell::RefCell, io::Cursor, rc::Rc}; #[cfg(feature = "web")] thread_local! { static CONTEXT: RefCell<Option<HydrationC...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>// TODO: Create README, uncomment this: #![doc = include_str!("../README.md")] #![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")] #![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")] use core::panic; use proc_macro::TokenStream; use proc_macro2::{Span, T...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! Configuration for how to serve a Dioxus application #![allow(non_snake_case)] use dioxus_core::LaunchConfig; use std::any::Any; use std::sync::Arc; use crate::{IncrementalRendererConfig, IndexHtml}; #[allow(unused)] pub(crate) type ContextProviders = Arc<Vec<Box<dyn Fn() -> Box<dyn Any> + Send + Sy...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! On the server, we collect any elements that should be rendered into the head in the first frame of SSR. //! After the first frame, we have already sent down the head, so we can't modify it in place. The web client //! will hydrate the head with the correct contents once it loads. use std::cell::RefCe...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use anyhow::Context; use std::path::Path; /// An `IndexHtml` represents the contents of an `index.html` file used to serve a web application. /// /// This defines the static portion of your web application, typically generated by a tool like `dx` /// in conjunction with wasm-bindgen. /// /// This structu...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>#![allow(non_snake_case)] #[cfg(not(target_arch = "wasm32"))] use crate::isrg::fs_cache::PathMapFn; use crate::IncrementalRenderer; use crate::isrg::memory_cache::InMemoryCache; use std::{ path::{Path, PathBuf}, time::Duration, }; /// A configuration for the incremental renderer. #[derive(Clon...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>ROL, http::HeaderValue::from_str(&format!("max-age={}", max_age)).unwrap(), ); } } } <|fim_prefix|>use std::time::Duration; use chrono::{DateTime, Utc}; /// Information about the freshness of a rendered response #[derive(Debug, Clone, Copy)] pub struct RenderFresh...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>cs(); let max_age = max_age.map(|max_age| max_age.as_secs()); Some(RenderFreshness::new(age, max_age?, self.timestamp.into())) } } fn decode_timestamp(timestamp: &str) -> Option<std::time::SystemTime> { let timestamp = u64::from_str_radix(timestamp, 16).ok()?; Some(std::time::...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! Inc<|fim_suffix|>ryCache { #[allow(clippy::type_complexity)] lru: Option<lru::LruCache<String, (DateTime<Utc>, Vec<u8>), BuildHasherDefault<FxHasher>>>, invalidate_after: Option<std::time::Duration>, } impl InMemoryCache { pub fn new(memory_cache_limit: usize, invalidate_after: Option...
fim
DioxusLabs/dioxus
rust
//! Incremental file based incremental rendering #![allow(non_snake_case)] mod config; mod freshness; #[cfg(not(target_arch = "wasm32"))] mod fs_cache; mod memory_cache; use std::time::Duration; use chrono::Utc; pub use config::*; pub use freshness::*; use self::memory_cache::InMemoryCache; /// A render that was ...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>} } }); } // Handle just hot-patches for now. // We don't do RSX hot-reload since usually the client handles that once the page is loaded. // // todo(jon): I *believe* SSR is resilient to RSX changes, but we s...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>mod ssr; pub(crate) mod streaming; pub use launch::router; pub use launch::serve; pub mod serverfn; pub use serverfn::*; pub mod isrg; pub use isrg::*; mod index_html; pub(crate) use index_html::IndexHtml; <|fim_prefix|>#![doc = include_str!("../README.md")] #![doc(html_logo_url = "https://avatars.git...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use std::sync::OnceLock; /// A custom header that can be set with any value to indicate /// that the server function client should redirect to a new route. /// /// This is useful because it allows returning a value from the request, /// while also indicating that a redirect should follow. This cannot be ...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use crate::{ ServeConfig, ServerFunction, ssr::{SSRError, SsrRendererPool}, }; use axum::{ body::Body, extract::State, http::{Request, StatusCode}, response::{IntoResponse, Response}, routing::*, }; use dioxus_core::{ComponentFunction, VirtualDom}; use http::header::*; use std:...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>s_mut() = StatusCode::FOUND; response.headers_mut().insert(LOCATION, referrer); } } response }) .await })...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>//! A shared pool of renderers for efficient server side rendering. use crate::isrg::{ CachedRender, IncrementalRenderer, IncrementalRendererConfig, IncrementalRendererError, RenderFreshness, }; use crate::streaming::{Mount, StreamingRenderer}; use crate::{ServeConfig, document::ServerDocument}; u...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>r<'_>) -> std::fmt::Result { if let Some(parent) = &self.parent { write!(f, "{},", parent)?; } write!(f, "{}", self.id) } } pub(crate) struct StreamingRenderer<E = std::convert::Infallible> { channel: RwLock<Sender<Result<String, E>>>, current_path: RwLock<...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>#![allow(unused)] use generational_box::*; use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; fn create<S: Storage<u32>>(owner: &Owner<S>) -> GenerationalBox<u32, S> { owner.insert(0) } fn set_read<S: Storage<u32>>(signal: GenerationalBox<u32, S>) -> u32 { si...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use crate::{ BorrowError, BorrowMutError, GenerationalLocation, GenerationalRefBorrowGuard, GenerationalRefBorrowMutGuard, }; use std::{ num::NonZeroU64, sync::atomic::{AtomicU64, Or<|fim_suffix|>o { pub(crate) fn borrow_mut_error(&self) -> BorrowMutError { #[cfg(any(debug_asse...
fim
DioxusLabs/dioxus
rust
//! Generational box errors #![allow(clippy::uninlined_format_args, reason = "causes compile error")] use std::error::Error; use std::fmt::Debug; use std::fmt::Display; use crate::GenerationalLocation; /// A result that can be returned from a borrow operation. pub type BorrowResult<T = ()> = std::result::Result<T, B...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>reating the value. The value will be dropped when the owner is dropped. pub fn insert_with_caller<T>( &self, value: T, caller: &'static std::panic::Location<'static>, ) -> GenerationalBox<T, S> where S: Storage<T>, { let location = S::new(value, call...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|> to match /// without calling [`GenerationalRefMut::deref_mut`], you will get an error like this: /// /// ```compile_fail /// # use generational_box::{Owner, UnsyncStorage, AnyStorage}; /// enum Colors { /// Red(u32), /// Green /// } /// let owner = UnsyncStorage::owner(); /// let mut value = owne...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use parking_lot::{ MappedRwLockReadGuard, MappedRwLockWriteGuard, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard, }; use std::{ any::Any, fmt::Debug, num::NonZeroU64, sync::{Arc, OnceLock}, }; use crate::{ AnyStorage, BorrowError, BorrowMutError, BorrowMutResult, BorrowResult, G...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>tr() as *const () } fn recycle(pointer: GenerationalPointer<Self>) { let mut borrow_mut = pointer.storage.data.borrow_mut(); // First check if the generation is still valid if !borrow_mut.valid(&pointer.location) { return; } borrow_mut.increme...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use generational_box::{GenerationalBox, Storage, SyncStorage, UnsyncStorage}; /// # Example /// /// ```compile_fail /// let data = String::from("hello world"); /// let owner = UnsyncStorage::owner(); /// let key = owner.insert(&data); /// drop(data); /// assert_eq!(*key.read(), "hello world"); /// ``` #[...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use generational_box::{ AlreadyBorrowedError, AlreadyBorrowedMutError, BorrowError, BorrowMutError, GenerationalBox, Owner, Storage, SyncStorage, UnsyncStorage, ValueDroppedError, }; #[track_caller] fn read_at_location<S: Storage<i32>>( value: GenerationalBox<i32, S>, ) -> (S::Ref<'static, i3...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use generational_box::{Storage, SyncStorage, UnsyncStorage}; #[test] fn reference_counting() { fn reference_counting<S: Storage<String> + 'static>() { let data = String::from("hello world"); let reference; { let outer_owner = S::owner(); { ...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>rt(1).raw_ptr(); drop(owner); } { let owner = S::owner(); let second_ptr = owner.insert(1234).raw_ptr(); assert_eq!(first_ptr, second_ptr); drop(owner); } } reused_test::<UnsyncStorage>(); reused_test::<SyncSt...
fim
DioxusLabs/dioxus
rust
// Regression test for https://github.com/DioxusLabs/dioxus/issues/2636 use std::time::Duration; use generational_box::{AnyStorage, GenerationalBox, SyncStorage}; #[test] fn race_condition_regression() { for _ in 0..100 { let handle = { let owner = SyncStorage::owner(); let key = ...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>callback. /// /// Some [`History`]s may receive URL updates from outside the router. When such /// updates are received, they should call `callback`, which will cause the router to update. #[allow(unused_variables)] fn updater(&self, callback: Arc<dyn Fn() + Send + Sync>) {} /// W...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use std::cell::RefCell; use crate::History; struct MemoryHistoryState { current: String, history: Vec<String>, future: Vec<String>, } /// A [`History`] provider that stores all navigation information in memory. pub struct MemoryHistory { state: RefCell<MemoryHistoryState>, base_path...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>id_run; pub use use_hook_did_run::*; mod use_signal; pub use use_signal::*; mod use_set_compare; pub use use_set_compare::*; mod use_after_suspense_resolved; pub use use_after_suspense_resolved::*; mod use_action; pub use use_action::*; mod use_waker; pub use use_waker::*; <|fim_prefix|>#![doc = incl...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use crate::{use_callback, use_signal}; use dioxus_core::{Callback, CapturedError, Result, Task, use_hook}; use dioxus_signals::{ReadSignal, ReadableBoxExt, ReadableExt, Signal, WritableExt}; use futures_channel::oneshot::Receiver; use futures_util::{FutureExt, future::Shared}; use std::{marker::PhantomDat...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use dioxus_core::{Runtime, use_hook}; /// Run a closure after the suspense boundary this is under is resolved. The /// closure will be run immediately if the suspense boundary is already res<|fim_suffix|>hook(|| { // If this is under a suspense boundary, we need to check if it is resolved ...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>llback) = callback.take() { // Every time this hook is called replace the inner callback with the new callback inner.replace(Box::new(callback)); } inner } <|fim_prefix|>use dioxus_core::{Callback, use_hook}; /// Create a callback that's always up <|fim_middle|>to date. Whenever ...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|> button { "Clear todos" onclick: move |_| todos.clear() } input { placeholder: "What needs to be done?" ref: input } ul { {todos.iter().map(|todo| rsx!( ...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|>xt<T: 'static + Clone>() -> T { use_hook(|| consume_context::<T>()) } /// Provide some context via the tree and return a reference to it /// /// Once the context has been provided, it is immutable. Mutations should be done via interior mutability. /// Context can be read by any child components of th...
fim
DioxusLabs/dioxus
rust
<|fim_prefix|>use crate::{UseFuture, use_context_provider, use_future}; use dioxus_core::Task; use dioxus_core::{consume_context, use_hook}; use dioxus_signals::*; pub use futures_channel::mpsc::{UnboundedReceiver, UnboundedSender}; use std::future::Future; /// Maintain a handle over a future that can be paused, resum...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|> run // 2) The effect is rerun due to an async read at any time // 3) The effect is rerun in the same tick that the component is rerun: we need to wait for the component to rerun before we can run the effect again let queue_effect_for_next_render = move || { if effect_q...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|> } } /// Allow calling a signal with signal() syntax /// /// Currently only limited to copy types, though could probably specialize for string/arc/rc impl Deref for UseFuture { type Target = dyn Fn() -> UseFutureState; fn deref(&self) -> &Self::Target { unsafe { ReadableExt::deref_im...
fim
DioxusLabs/dioxus
rust
<|fim_suffix|> let mut did_run_ = use_hook(|| CopyValue::new(false)); // Before render always set the value to false use_before_render(move || did_run_.set(false)); // Only when the outer hook is run do we want to set the value to true did_run_.set(true); // After render, we can check if the ...
fim
DioxusLabs/dioxus
rust