text stringlengths 14 100k | source stringclasses 1
value | repo stringclasses 810
values | language stringclasses 13
values |
|---|---|---|---|
<|fim_prefix|>use cra<|fim_suffix|>ler))
}
<|fim_middle|>te::use_callback;
use dioxus_core::use_hook;
use dioxus_signals::Memo;
#[doc = include_str!("../docs/derived_state.md")]
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
#[track_caller]
pub fn use_memo<R:... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>use dio<|fim_suffix|> instead, which has the same functionality.")]
pub fn use_on_unmount<D: FnOnce() + 'static>(destroy: D) {
use_drop(destroy);
}
<|fim_middle|>xus_core::use_drop;
#[deprecated(note = "Use `use_drop`<|endoftext|> | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>use dioxus_signals::{ReadableExt, WritableExt};
use crate::use_signal;
/// A dependency is a trait that can be used to determine if a effect or selector should be re-run.
#[rustversion::attr(
since(1.78.0),
diagnostic::on_unimplemented(
message = "`Dependency` is not implemented for `{Se... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>://github.com/DioxusLabs/awesome-dioxus/blob/{revision}/awesome.json")).await
/// });
///
/// // We can use the `finished` method to check if the future is finished
/// if resource.finished() {
/// rsx! {
/// "The resource is finished"
/// ... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|> always provide a logger, we can insert a default logger if one doesn't exist.
/// use_root_context(|| Logger)
/// }
/// ```
#[doc = include_str!("../docs/rules_of_hooks.md")]
#[doc = include_str!("../docs/moving_state_around.md")]
pub fn use_root_context<T: 'static + Clone>(new: impl FnOnce() -> T) -... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>/// button {
/// // This will only rerender the child with the old and new value of i == count
/// // Because we are using a set compare, this will be O(1) instead of the O(n) performance of a selector
/// onclick: move |_| count += 1,
/// "Increment... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>use dioxus_core::use_hook;
use dioxus_signals::{Signal, SignalData, Storage, SyncStorage, UnsyncStorage};
/// Creates a new Signal. Signals are a Copy state management solution with automatic dependency tracking.
///
/// ```rust
/// use dioxus::prelude::*;
/// use dioxus_signals::*;
///
/// fn App() -> E... | fim | DioxusLabs/dioxus | rust |
use std::cmp::Ordering;
use std::ops::DerefMut;
use crate::use_memo;
use dioxus_signals::{ReadSignal, Signal};
pub fn use_sorted<V: 'static, T: PartialEq>(
collection: impl FnMut() -> Signal<V>,
) -> ReadSignal<Vec<T>>
// pub fn use_sorted<S, I, T>(iterable: impl FnMut() -> Signal<V>) -> ReadSignal<T>
// where
//... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>hen the task is woken.
pub async fn wait(&self) -> Result<T, Canceled> {
self.task_rx.cloned().await
}
}
// Can await the waker to be woken.
// We use `.peek()` here to avoid reacting to changes in the underlying task_rx which could lead
// to an effect/future loop.
impl<T: Clone + 'stati... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>#![allow(unused, non_upper_case_globals, non_snake_case)]
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::time::Duration;
use dioxus::prelude::*;
use dioxus_core::ElementId;
use dioxus_signals::*;
#[tokio::test]
async fn effects_rerun() {
#[derive(Default)]
struc... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>use dioxus_core::generation;
#[tokio::test]
async fn memo_updates() {
use std::cell::RefCell;
use dioxus::prelude::*;
thread_local! {
static VEC_SIGNAL: RefCell<Option<Signal<Vec<usize>, SyncStorage>>> = const { RefCell::new(None) };
}
fn app() -> Element {
let mut ... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>ll-snap-type>
scroll_snap_type: "scroll-snap-type" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/shape-image-threshold>
shape_image_threshold: "shape-image-threshold" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/shape-inside>
shape_inside: "sh... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>{
fn from(drag: &DragData) -> Self {
let data_transfer = drag.data_transfer();
Self::from_data_transfer(&data_transfer)
}
}
}
<|fim_prefix|>pub struct DataTransfer {
inner: Box<dyn NativeDataTransfer>,
}
impl DataTransfer {
pub fn new(inner: impl Native... | fim | DioxusLabs/dioxus | rust |
#![allow(non_upper_case_globals)]
use dioxus_core::HasAttributes;
use dioxus_core::IntoAttributeValue;
#[cfg(feature = "hot-reload-context")]
use dioxus_core_types::HotReloadingContext;
use dioxus_html_internal_macro::impl_extension_attributes;
#[cfg(feature = "hot-reload-context")]
use crate::{map_global_attributes,... | fim | DioxusLabs/dioxus | rust |
use dioxus_core::Event;
pub type AnimationEvent = Event<AnimationData>;
pub struct AnimationData {
inner: Box<dyn HasAnimationData>,
}
impl AnimationData {
/// Create a new AnimationData
pub fn new(inner: impl HasAnimationData + 'static) -> Self {
Self {
inner: Box::new(inner),
... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>reInputData::new(
"insertText".to_string(),
Some("a".to_string()),
false,
"hello".to_string(),
));
assert_eq!(event.input_type(), InputType::InsertText);
assert_eq!(event.data().as_deref(), Some("a"));
assert!(!event.is_compo... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>)]
impl From<&CancelData> for SerializedCancelData {
fn from(_: &CancelData) -> Self {
Self {}
}
}
#[cfg(feature = "serialize")]
impl HasCancelData for SerializedCancelData {
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[cfg(feature = "serialize")]
impl serde::Seria... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>les().is_empty());
}
#[test]
fn paste_text_round_trips_through_serde() {
let payload = r#"{
"data_transfer": {
"items": [
{ "kind": "string", "type_": "text/plain", "data": "round trip" }
],
"files": [],
... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>use dioxus_core::Event;
pub type CompositionEvent = Event<CompositionData>;
pub struct CompositionData {
inner: Box<dyn HasCompositionData>,
}
impl std::fmt::Debug for CompositionData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CompositionData"... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>use crate::input_data::{MouseButton, MouseButtonSet};
use crate::*;
use crate::{
data_transfer::DataTransfer,
geometry::{ClientPoint, Coordinates, ElementPoint, PagePoint, ScreenPoint},
};
use dioxus_core::Event;
use keyboard_types::Modifiers;
use crate::HasMouseData;
pub type DragEvent = Event... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>pl<'de> serde::Deserialize<'de> for FocusData {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let data = SerializedFocusData::deserialize(deserializer)?;
Ok(Self {
inner: Box::new(data),
})
}
}
pub trait HasFocusData: ... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>a.downcast::<SerializedFormData>() {
return data.clone();
}
let values = data
.values()
.iter()
.map(|(key, value)| match value {
FormValue::Text(s) => SerializedFormObject {
... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|> #[events = [
ontouchstart => touchstart,
ontouchmove => touchmove,
ontouchend => touchend,
ontouchcancel => touchcancel,
]]
Touch(TouchData),
#[convert = convert_transition... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>mageData
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedImageData {
#[cfg_attr(feature = "serialize", serde(default))]
load_error: bool,
}
#[cfg(feature = "serialize")]
impl From<&ImageData> for SerializedImageData {
fn from(data: &ImageData) -> ... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|> // previous, = 177
// stop, = 178
// play/pause, = 179
// e-mail, = 180
// mute/unmute (firefox), = 181
// decrease volume level (firefox), = 182
// increase volume level (firefox), = 183
Semicolon = 186,
EqualSign = 187,
Comma = 188,
Dash = 189,
Period = 190,
... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|> inner: Box::new(data),
})
}
}
pub trait HasMediaData: std::any::Any {
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
}
<|fim_prefix|>use dioxus_core::Event;
pub type MediaEvent = Event<MediaData>;
pub struct MediaData {
inner: Box<dyn HasMediaData>,
}
impl<E:... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>#![doc = include_str!("../../docs/event_handlers.md")]
use std::any::Any;
use std::sync::RwLock;
macro_rules! impl_event {
(
$data:ty;
$(
$( #[$attr:meta] )*
$name:ident $( : $js_name:expr )?;
)*
) => {
$(
$( #[$attr] )*
... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|> size of an element's content, including content not visible on the screen due to overflow
#[allow(clippy::type_complexity)]
fn get_scroll_size(&self) -> Pin<Box<dyn Future<Output = MountedResult<PixelsSize>>>> {
Box::pin(async { Err(MountedError::NotSupported) })
}
/// Get the bo... | fim | DioxusLabs/dioxus | rust |
use crate::geometry::{ClientPoint, Coordinates, ElementPoint, PagePoint, ScreenPoint};
use crate::input_data::{MouseButton, MouseButtonSet};
use crate::*;
use dioxus_core::Event;
use keyboard_types::Modifiers;
pub type MouseEvent = Event<MouseData>;
/// A synthetic event that wraps a web-style [`MouseEvent`](https://... | fim | DioxusLabs/dioxus | rust |
use dioxus_core::Event;
use keyboard_types::Modifiers;
use crate::{geometry::*, input_data::*, *};
/// A synthetic event that wraps a web-style [`PointerEvent`](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent)
pub type PointerEvent = Event<PointerData>;
pub struct PointerData {
inner: Box<dyn HasPo... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>) -> Self {
Self {
inner: Box::new(inner),
}
}
/// Get the border box size of the observed element
pub fn get_border_box_size(&self) -> ResizeResult<PixelsSize> {
self.inner.get_border_box_size()
}
/// Get the content box size of the observed eleme... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>use dioxus_core::Event;
pub type ScrollEvent = Event<ScrollData>;
pub struct ScrollData {
inner: Box<dyn HasScrollData>,
}
impl<E: HasScrollData> From<E> for ScrollData {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl ScrollData {
/// Create a new ScrollData
p... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>
}
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
}
#[cfg(all(test, feature = "serialize"))]
mod tests {
use super::*;
#[test]
fn serialized_selection_data_deserializes_missing_fields() {
let data: SerializedSelectionData = serde_json::from_str("{}").unwr... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>ew(inner: impl HasToggleData + 'static) -> Self {
Self {
inner: Box::new(inner),
}
}
/// Downcast this event to a concrete event type
#[inline(always)]
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.inner.as_any().downcast_ref::<T>()
}
}
#... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|> rotation_angle: point.rotation(),
}
}
}
#[cfg(feature = "serialize")]
impl HasTouchPointData for SerializedTouchPoint {
/// A unique identifier for this touch point that will be the same for the duration of the touch
fn identifier(&self) -> i32 {
self.identifier
}
//... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>atic) -> Self {
Self {
inner: Box::new(inner),
}
}
/// Downcast this event to a concrete event type
#[inline(always)]
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.inner.as_any().downcast_ref::<T>()
}
}
#[cfg(feature = "serialize")]
/// A... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>alize")]
impl serde::Serialize for VisibleData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SerializedVisibleData::from(self).serialize(serializer)
}
}
#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for VisibleData {
fn deser... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>use dioxus_core::Event;
use keyboard_types::Modifiers;
use std::fmt::Formatter;
use crate::{
InteractionElementOffset,
input_data::{MouseButton, MouseButtonSet},
};
use crate::{InteractionLocation, ModifiersInteraction, PointerInteraction, geometry::*};
use super::HasMouseData;
/// A synthetic ... | fim | DioxusLabs/dioxus | rust |
use bytes::Bytes;
use futures_util::Stream;
use std::{path::PathBuf, pin::Pin, prelude::rust_2024::Future};
#[derive(Clone)]
pub struct FileData {
inner: std::sync::Arc<dyn NativeFileData>,
}
impl FileData {
pub fn new(inner: impl NativeFileData + 'static) -> Self {
Self {
inner: std::sync... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>//! Geometry primitives for representing e.g. mouse events
/// A re-export of euclid, which we use for geometry primitives
pub use euclid;
use euclid::*;
/// Coordinate space relative to the screen
pub struct ScreenSpace;
/// A point in ScreenSpace
pub type ScreenPoint = Point2D<f64, ScreenSpace>;
///... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|> MouseButton::Fourth;
}
if code & 0b10000 != 0 {
set |= MouseButton::Fifth;
}
if code & (!0b11111) != 0 {
set |= MouseButton::Unknown;
}
}
set
}
pub fn encode_mouse_button_set(set: MouseButtonSet) -> u16 {
let mut code = 0;
... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|> benefit of this approach is the ability to lend comprehensive documentation on how to use these elements inside
//! of the Rsx and Html macros. Each element comes with a substantial amount of documentation on how to best use it, hopefully
//! making the development cycle quick.
//!
//! All elements are u... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>use keyboard_types::Modifiers;
use crate::{
geometry::{ClientPoint, Coordinates, ElementPo<|fim_suffix|>ut modifiers = Modifiers::empty();
if self.alt_key {
modifiers.insert(Modifiers::ALT);
}
if self.ctrl_key {
modifiers.insert(Modifiers::CONTROL);
... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>use dioxus_core::{Template, TemplateAttribute, TemplateNode};
use std::fmt::Write;
/// Render a template to an HTML string
///
/// Useful for sending over the wire. Can be used to with innerHtml to create templates with little work
pub fn render_template_to_html(template: &Template) -> String {
let m... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>use std::{any::Any, rc::Rc};
use crate::events::*;
use dioxus_core::ElementId;
use serde::{Deserialize, Serialize};
#[cfg(feature = "serialize")]
#[derive(Serialize, Debug, PartialEq)]
pub struct HtmlEvent {
pub element: ElementId,
pub name: String,
pub bubbles: bool,
pub data: EventData... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>use proc_macro::TokenStream;
use convert_case::{Case, Casing};
use proc_macro2::TokenStream as TokenStream2;
use quote::{ToTokens, TokenStreamExt, quote};
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::{Ident, Token, braced, parse_macro_input};
#[proc_macro]
pub fn impl_... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>fn main() <|fim_suffix|>}
<|fim_middle|>{<|endoftext|> | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>#[test]
fn tests() {
let t <|fim_suffix|>new();
t.pass("tests/01-simple.rs");
}
<|fim_middle|>= trybuild::TestCases::<|endoftext|> | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>./src/js/patch_console.js")
.with_binding(
"./src/ts/initialize_streaming.ts",
"./src/js/initialize_streaming.js",
)
.run();
}
<|fim_prefix|>fn main() {
// If any <|fim_middle|>TS files change, re-run the build script
lazy_js_bundle::LazyTypeScriptBi... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>function setAttributeInner(node,field,value,ns){if(ns==="style"){node.style.setProperty(field,value);return}if(ns){node.setAttributeNS(ns,field,value);return}switch(field){case"value":if(node.tagName==="OPTION")setAttributeDefault(node,field,value);else if(node.value!==value)node.value=value;break;case"in... | fim | DioxusLabs/dioxus | javascript |
<|fim_suffix|>target=entry.target,event=new CustomEvent("resize",{bubbles:!1,detail:entry});target.dispatchEvent(event)}createResizeObserver(element){if(!this.resizeObserver)this.resizeObserver=new ResizeObserver((entries)=>{for(let entry of entries)this.handleResizeEvent(entry)});this.resizeObserver.observe(element)}r... | fim | DioxusLabs/dioxus | javascript |
<|fim_prefix|>function register_rehydrate_chunk_for_streaming(callback){return register_rehydrate_chunk_for_stre<|fim_suffix|>}function register_rehydrate_chunk_for_streaming_debug(callback){window.hydration_callback=callback;for(let i=0;i<window.hydrate_queue.length;i++){let[id,data,debug_types,debug_locations]=window... | fim | DioxusLabs/dioxus | javascript |
<|fim_suffix|>ebug_locations])};
<|fim_prefix|>window.hydrate_queue=[<|fim_middle|>];window.dx_hydrate=(id,data,debug_types,debug_locations)=>{let decoded=atob(data),bytes=Uint8Array.from(decoded,(c)=>c.charCodeAt(0));if(window.hydration_callback)window.hydration_callback(id,bytes,debug_types,debug_locations);else wind... | fim | DioxusLabs/dioxus | javascript |
<|fim_prefix|>function serializeEvent(event,target){let contents={},extend=(obj)=>contents={...contents,...obj};if(event instanceof WheelEvent)extend(serializeWheelEvent(event));if(event instanceof MouseEvent)extend(serializeMouseEvent(event));if(event instanceof KeyboardEvent)extend(serializeKeyboardEvent(event));if(e... | fim | DioxusLabs/dioxus | javascript |
<|fim_prefix|>function monkeyPatchConsole(ws){let console=window.console,log=console.log,info=console.info,warn=console.warn,error=console.error,debug=console.debug;console.log=function(...args){if(ws.readyState===WebSocket.OPEN)ws.send(JSON.stringify({Log:{level:"log",messages:args}}));log.apply(console,args)},console... | fim | DioxusLabs/dioxus | javascript |
<|fim_prefix|>function setAttributeInner(node,field,value,ns){if(ns==="style"){node.style.setProperty(field,value);return}if(ns){node.setAttributeNS(ns,field,value);return}switch(field){case"value":if(node.tagName==="OPTION")setAttributeDefault(node,field,value);else if(node.value!==value)node.value=value;break;case"in... | fim | DioxusLabs/dioxus | javascript |
<|fim_suffix|>ort of consistency between web, desktop, and liveview
#[wasm_bindgen(module = "/src/js/set_attribute.js")]
extern "C" {
/// Set the attribute of the node
pub fn setAttributeInner(node: JsValue, name: &str, value: JsValue, ns: Option<&str>);
}
#[wasm_bindgen(module = "/src/... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>// The root interpreter class that holds state about the mapping between DOM and VirtualDom
// This always lives in the JS side of things, and is extended by the native and web interpreters
import { setAttributeInner } from "./set_attribute";
export type NodeId = number;
export class BaseInterpreter {
... | fim | DioxusLabs/dioxus | typescript |
import "./hydrate_types";
import { HydrationCallback } from "./hydrate_types";
export function register_rehydrate_chunk_for_streaming(callback: HydrationCallback): void {
return register_rehydrate_chunk_for_streaming_debug(callback);
}
export function register_rehydrate_chunk_for_streaming_debug(
callback: Hydrat... | fim | DioxusLabs/dioxus | typescript |
<|fim_prefix|>export { };
export type Hydrat<|fim_suffix|>ull
) => void;
declare global {
interface Window {
hydrate_queue: [number[], Uint8Array, string[] | null, string[] | null][];
hydration_callback:
| null
| HydrationCallback;
}
}
<|fim_middle|>ionCallback = (
id: number[],
data: Uint8Arr... | fim | DioxusLabs/dioxus | typescript |
<|fim_prefix|>import "./hydrate_types";
// Chunks may load before the wasm has loaded and the callback to hydrate the dom is registered. We queue up hydration ids and data until the wasm is ready
window.hydrate_queue = [];
// @ts-ignore
window.dx_hydrate = (
id: number[],
data: stri<|fim_suffix|>
// First conve... | fim | DioxusLabs/dioxus | typescript |
<|fim_suffix|>= this.stack.splice(this.stack.length - many);
for (let k = 0; k < many; k++) {
root.appendChild(els[k]);
}
}
handleEvent(event: Event, name: string, bubbles: boolean) {
const target = event.target!;
const element = getTargetId(target)!;
const contents = serializeEvent(even... | fim | DioxusLabs/dioxus | typescript |
<|fim_suffix|>g", messages: args }
}));
}
debug.apply(console, args);
};
}
<|fim_prefix|>
export function monkeyPatchConsole(ws: WebSocket) {
const console = window.console;
const log = console.log;
const info = console.info;
const warn = console.warn;
const error = console.error;
const debu... | fim | DioxusLabs/dioxus | typescript |
<|fim_prefix|>// Handle serialization of the event data across the IPC boundary
//
// Note that for files, we don't serialize their contents, expecting the renderer itself to handle
// reading the file contents if needed. Reading files is an async operation, and should be done lazily
// if the app needs it.
export typ... | fim | DioxusLabs/dioxus | typescript |
<|fim_prefix|>// A unified interface for setting attributes on a node
// this function should try and stay fast, if possible
export function setAttributeInner(
node: HTMLElement,
field: string,
value: string,
ns: string
) {
// we support a single namespace by default: style
if (ns === "style") {
node.s... | fim | DioxusLabs/dioxus | typescript |
<|fim_suffix|>er(event_name, this_node, bubbles, (event) => {
this.handler(event, event_name, bubbles);
});
}"#
}
/// Assign the ID
#[cfg(feature = "binary-protocol")]
fn assign_id_ref(array: &[u8], id: u32) {
"{this.nodes[$id$] = this.loadChild($array$);}"
}
#[... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|> } = attr
{
self.channel
.set_top_attribute(name, value, namespace.unwrap_or_default())
}
}
// Add each child to the stack
for child in *children {
... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>tations
<|fim_prefix|>//! Ensure that the interpret<|fim_middle|>er loads, has no errors, and writes mu<|endoftext|> | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>//! Ensure<|fim_suffix|>orrectly.
<|fim_middle|> that events are serialized and deserialized c<|endoftext|> | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>use std::collections::hash_map::DefaultHasher;
use std::path::{Path, PathBuf};
use std::{hash::Hasher, process::Command};
struct Binding {
input_path: PathBuf,
output_path: PathBuf,
}
/// A builder for generating TypeScript bindings lazily
#[derive(Default)]
pub struct LazyTypeScriptBindings {
... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>use axum::Router;
use dioxus::prelude::*;
use dioxus_liveview::LiveviewRouter;
fn app(<|fim_suffix|>
rsx! {
div {
"hello axum! {num}"
button { onclick: move |_| num += 1, "Increment" }
}
}
}
#[tokio::main]
async fn main() {
dioxus::logger::initialize_d... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>use axum::{Router, extract::ws::WebSocketUpgrade, response::Html, routing::get};
use dioxus::prelude::*;
fn app() -> Element {
let mut state = use_signal(|| 0);
use_future(move || async move {
loop {
state += 1;
tokio::time::sleep(std::time::Duration::from_millis(1... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>ove || async move { index_page_with_glue(&interpreter_glue(&ws_path)) }),
)
}
async fn start(self, address: impl Into<std::net::SocketAddr>) {
let listener = tokio::net::TcpListener::bind(address.into()).await.unwrap();
if let Err(err) = axum::serve(listener, self.into_mak... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>m a component
fn with_app(self, route: &str, app: fn() -> Element) -> Self
where
Self: Sized,
{
self.with_virtual_dom(route, move || VirtualDom::new(app))
}
/// Add a liveview route to the server from a virtual dom.
fn with_virtual_dom(
self,
route:... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>use dioxus_core::{LaunchConfig, VirtualDom};
use crate::LiveviewRouter;
pub(crate) fn app_title() -> String {
dioxus_cli_config::app_title().unwrap_or_else(|| "Dioxus Liveview App".to_string())
}
/// A configuration for the LiveView server.
pub struct Config<R: LiveviewRouter> {
router: R,
... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>pt_contents().ok(),
));
});
}
/// Create a new style tag in the head
fn create_style(&self, props: StyleProps) {
let myself = self.clone();
queue_effect(move || {
myself.eval(create_element_in_head(
"style",
&prop... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>use dioxus_core::ElementId;
use dioxus_html::{
MountedResult, RenderedElementBacking,
geometry::{PixelsRect, PixelsSize, PixelsVector2D},
};
use crate::query::QueryEngine;
/// A mounted element passed to onmounted events
#[derive(Clone)]
pub struct LiveviewElement {
id: ElementId,
query:... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>ap()
.into()
}
fn convert_pointer_data(&self, event: &PlatformEventData) -> PointerData {
event
.downcast::<SerializedPointerData>()
.cloned()
.unwrap()
.into()
}
fn convert_resize_data(&self, event: &PlatformEventData) ... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>use dioxus_core::spawn;
use dioxus_document::Eval;
use dioxus_history::History;
use serde::{Deserialize, Serialize};
use std::rc::Rc;
use std::sync::{Mutex, RwLock};
use std::{collections::BTreeMap, sync::Arc};
/// A [`History`] that evaluates history through JS.
pub(crate) struct LiveviewHistory {
a... | fim | DioxusLabs/dioxus | rust |
use dioxus_core::*;
use std::any::Any;
pub type Config = crate::Config<axum::Router>;
/// Launches the WebView and runs the event loop, with configuration and root props.
pub fn launch(
root: fn() -> Element,
contexts: Vec<Box<dyn Fn() -> Box<dyn Any> + Send + Sync>>,
platform_configs: Vec<Box<dyn Any>>,
... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|> name: name,
element: parseInt(realId),
data: contents,
bubbles,
});
window.ipc.postMessage(message);
}
read_files();
return;
}
}"#;
let mut interpreter = format!(
r#"
// Bring the... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>;
ws.onerror = (err) => {
// todo: retry the connection
};
ws.onmessage = (message) => {
const u8view = new Uint8Array(message.data);
const binaryFrame = u8view[0] == 1;
const messageData = message.data.slice(1);
// The first byte tells the shim if this is a bin... | fim | DioxusLabs/dioxus | javascript |
use crate::{
LiveViewError,
document::init_document,
element::LiveviewElement,
events::SerializedHtmlEventConverter,
query::{QueryEngine, QueryResult},
};
use dioxus_core::{Element, Event, ScopeId, VirtualDom, provide_context};
use dioxus_html::{EventData, HtmlEvent, PlatformEventData};
use dioxus_... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>d;
_ = self.query_engine.query_tx.send(format!(
r#"
if (!window.{QUEUE_NAME}) {{
window.{QUEUE_NAME} = [];
}}
if (window.{QUEUE_NAME}[{queue_id}]) {{
window.{QUEUE_NAME}[{queue_id}] = [];
}}
"... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|> .add_directive("hyper_util=warn".parse().unwrap()), // hyper has `debug!` sitting around in some places that are spammy
);
if !dioxus_cli_config::is_cli_enabled() {
return set_global_default(sub.finish());
}
// todo(jon): this is a small hack to clea... | fim | DioxusLabs/dioxus | rust |
use jni::{JNIEnv, JavaVM, objects::JObject};
use std::sync::OnceLock;
/// Cached reference to the Android activity.
static ACTIVITY: OnceLock<jni::objects::GlobalRef> = OnceLock::new();
static JAVA_VM: OnceLock<JavaVM> = OnceLock::new();
/// Execute a JNI operation with a cached activity reference.
///
/// This funct... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>[unsafe(no_mangle)]
unsafe extern "C" fn rust_callback<'a>(
mut env: JNIEnv<'a>,
_class: JObject<'a>,
handler_ptr_high: jlong,
handler_ptr_low: jlong,
location: JObject<'a>,
) {
// Reconstruct the pointer from two i64 values (for 64-bit pointers)
#[cfg(not(target_pointer_width ... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>-> Result<JClass<'env>> {
let class_name_jstring = new_string(env, class_name)?;
let class = env.call_static_method(
"java/lang/Class",
"forName",
"(Ljava/lang/String;)Ljava/lang/Class;",
&[JValue::Object(&class_name_jstring)],
)?;
Ok(class.l()?.into())
}
<|... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>//! Android metadata wrappers for linker-based collection.
pub use manganis_core::AndroidArtifactMetadata;
pub type AndroidMetadataBuffer = crate::macro_helpers::ConstVec<u8, 4096>;
p<|fim_suffix|>erialize_android_artifact(meta)
}
<|fim_middle|>ub const fn serialize_android_metadata(meta: &AndroidArtif... | fim | DioxusLabs/dioxus | rust |
//! Android-specific utilities for mobile APIs
#[cfg(target_os = "android")]
pub mod activity;
#[cfg(target_os = "android")]
pub mod callback;
#[cfg(target_os = "android")]
pub mod java;
#[cfg(target_os = "android")]
pub mod metadata;
#[doc(hidden)]
pub mod macro_helpers {
//! Helper functions for macro expansion... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>ge(meta)
}
}
<|fim_prefix|>//! Darwin (iOS/macOS) shared utilities for objc2-based APIs
//!
//! This module provides shared utilities for both iOS and macOS platforms
//! since they share the same Objective-C runtime<|fim_middle|> and threading requirements
//! through objc2.
/// Re-export MainThread... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>used types for convenience
#[cfg(target_os = "android")]
pub use jni;
// Re-export objc2 for FFI macro generated code
#[cfg(any(target_os = "ios", target_os = "macos"))]
pub use objc2;
/// Re-export the ffi attribute macro for native FFI bindings
/// This macro generates direct FFI bindings between Rust... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>// Re-export const_serialize types for generated code.
pub use const_serialize;
pub use const_serialize::{ConstStr, ConstVec, SerializeConst};
use manganis_core::{
AndroidArtifactMetadata, AssetOptions, BundledAsset, SwiftPackageMetadata, SymbolData,
};
/// Copy a slice into a constant sized buffer ... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>use crate::AssetO<|fim_suffix|>bool {
self.absolute_source_path == other.absolute_source_path
&& self.bundled_path == other.bundled_path
&& self.options == other.options
}
}
impl PartialOrd for BundledAsset {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>).with_preload(true));
/// ```
pub const fn with_preload(mut self, preload: bool) -> Self {
self.variant.preload = preload;
self
}
/// Convert the options into options for a generic asset
pub const fn into_asset_options(self) -> AssetOptions {
AssetOptions {
... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>comment start: /*
'*' if comment_start => {
comment_start = false;
in_comment_scope = true;
}
// Mark start of comment end if in comment scope: */
'*' if in_comment_scope => comment_end = true,
... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>, ErrMode<ContextError>> {
repeat(range, f).fold(|| (), |_, _| ()).take()
}
fn ws<'s>(input: &mut &'s str) -> ModalResult<&'s str> {
recognize_repeat(
0..,
alt((
line_comment,
block_comment,
take_while(1.., (AsChar::is_space, '\n', '\r')),
... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>name: ConstStr,
pub artifact_path: ConstStr,
pub gradle_dependencies: ConstStr,
}
impl AndroidArtifactMetadata {
pub const fn new(
plugin_name: &'static str,
artifact_path: &'static str,
gradle_dependencies: &'static str,
) -> Self {
Self {
plug... | fim | DioxusLabs/dioxus | rust |
<|fim_suffix|>ons::folder()
}
/// Create a default folder asset options
pub const fn default() -> Self {
Self {}
}
}
impl AssetOptions {
/// Create a new folder asset builder
///
/// ```rust
/// # use manganis::{asset, Asset, AssetOptions};
/// const _: Asset = asset!("/ass... | fim | DioxusLabs/dioxus | rust |
<|fim_prefix|>use const_serialize::SerializeConst;
use crate::{AssetOptions, AssetOptionsBuilder, AssetVariant};
/// The type of an image. You can read more about the tradeoffs between image formats [here](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types)
#[derive(
Debug,
Eq,
Partial... | fim | DioxusLabs/dioxus | rust |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.