chore: cleanup workspace

This commit is contained in:
Jonathan Kelley committed 2021-07-15 18:40:12 -04:00
1 parent 3bedcb93ca
commit 8f0bb5dc5b
54 files changed
+691 -1822

No files matched your search

+43
View File
@@ -0,0 +1,43 @@
//! webview dom
use dioxus_core::{DomEdit, RealDom, RealDomNode, ScopeId};
use DomEdit::*;
pub struct WebviewRegistry {}
impl WebviewRegistry {
pub fn new() -> Self {
Self {}
}
}
pub struct WebviewDom<'bump> {
pub edits: Vec<DomEdit<'bump>>,
pub node_counter: u64,
pub registry: WebviewRegistry,
}
impl WebviewDom<'_> {
pub fn new(registry: WebviewRegistry) -> Self {
Self {
edits: Vec::new(),
node_counter: 0,
registry,
}
}
// Finish using the dom (for its edit list) and give back the node and event registry
pub fn consume(self) -> WebviewRegistry {
self.registry
}
}
impl<'bump> RealDom<'bump> for WebviewDom<'bump> {
fn raw_node_as_any(&self) -> &mut dyn std::any::Any {
todo!()
// self.edits.push(PushRoot { root });
}
fn request_available_node(&mut self) -> RealDomNode {
self.node_counter += 1;
RealDomNode::from_u64(self.node_counter)
}
}
+81
View File
@@ -0,0 +1,81 @@
use std::fmt::{self, Write};
/// Escape a string to pass it into JavaScript.
///
/// # Example
///
/// ```rust,no_run
/// # use web_view::WebView;
/// # use std::mem;
/// #
/// # let mut view: WebView<()> = unsafe { mem::uninitialized() };
/// #
/// let string = "Hello, world!";
///
/// // Calls the function callback with "Hello, world!" as its parameter.
///
/// view.eval(&format!("callback({});", web_view::escape(string)));
/// ```
pub fn escape(string: &str) -> Escaper {
Escaper(string)
}
// "All code points may appear literally in a string literal except for the
// closing quote code points, U+005C (REVERSE SOLIDUS), U+000D (CARRIAGE
// RETURN), U+2028 (LINE SEPARATOR), U+2029 (PARAGRAPH SEPARATOR), and U+000A
// (LINE FEED)." - ES6 Specification
pub struct Escaper<'a>(&'a str);
const SPECIAL: &[char] = &[
'\n', // U+000A (LINE FEED)
'\r', // U+000D (CARRIAGE RETURN)
'\'', // U+0027 (APOSTROPHE)
'\\', // U+005C (REVERSE SOLIDUS)
'\u{2028}', // U+2028 (LINE SEPARATOR)
'\u{2029}', // U+2029 (PARAGRAPH SEPARATOR)
];
impl<'a> fmt::Display for Escaper<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let &Escaper(mut string) = self;
f.write_char('\'')?;
while !string.is_empty() {
if let Some(i) = string.find(SPECIAL) {
if i > 0 {
f.write_str(&string[..i])?;
}
let mut chars = string[i..].chars();
f.write_str(match chars.next().unwrap() {
'\n' => "\\n",
'\r' => "\\r",
'\'' => "\\'",
'\\' => "\\\\",
'\u{2028}' => "\\u2028",
'\u{2029}' => "\\u2029",
_ => unreachable!(),
})?;
string = chars.as_str();
} else {
f.write_str(string)?;
break;
}
}
f.write_char('\'')?;
Ok(())
}
}
#[test]
fn test() {
let plain = "ABC \n\r' abc \\ \u{2028} \u{2029}123";
let escaped = escape(plain).to_string();
assert!(escaped == "'ABC \\n\\r\\' abc \\\\ \\u2028 \\u2029123'");
}
+139
View File
@@ -0,0 +1,139 @@
<!DOCTYPE html>
<html>
<head>
<script>
class Interpreter {
constructor(root) {
this.stack = [root];
this.listeners = {};
this.lastNodeWasText = false;
this.nodes = {
0: root
};
}
top() {
return this.stack[this.stack.length - 1];
}
pop() {
return this.stack.pop();
}
}
class OPTABLE {
PushRoot(self, edit) {
const id = edit.root;
const node = self.nodes[id];
self.stack.push(node);
}
AppendChildren(self, edit) {
let root = self.stack[self.stack.length - (edit.many + 1)];
for (let i = 0; i < edit.many; i++) {
console.log("popping ", i, edit.many);
let node = self.pop();
root.appendChild(node);
}
}
ReplaceWith(self, edit) {
let root = self.stack[self.stack.length - (edit.many + 1)];
let els = [];
for (let i = 0; i < edit.many; i++) {
els.push(self.pop());
}
root.replaceWith(...els);
}
Remove(self, edit) {
const node = self.stack.pop();
node.remove();
}
RemoveAllChildren(self, edit) {
}
CreateTextNode(self, edit) {
self.stack.push(document.createTextNode(edit.text));
}
CreateElement(self, edit) {
const tagName = edit.tag;
console.log(`creating element: `, edit);
self.stack.push(document.createElement(tagName));
}
CreateElementNs(self, edit) {
self.stack.push(document.createElementNS(edit.ns, edit.tag));
}
CreatePlaceholder(self, edit) {
const a = `self.stack.push(document.createElement("pre"))`;
self.stack.push(document.createComment("vroot"));
}
NewEventListener(self, edit) {
}
RemoveEventListener(self, edit) {
}
SetText(self, edit) {
self.top().textContent = edit.text;
}
SetAttribute(self, edit) {
const name = edit.field;
const value = edit.value;
const node = self.top(self.stack);
node.setAttribute(name, value);
if ((name === "value", self)) {
node.value = value;
}
if ((name === "checked", self)) {
node.checked = true;
}
if ((name === "selected", self)) {
node.selected = true;
}
}
RemoveAttribute(self, edit) {
const name = edit.field;
const node = self.top(self.stack);
node.removeAttribute(name);
if ((name === "value", self)) {
node.value = null;
}
if ((name === "checked", self)) {
node.checked = false;
}
if ((name === "selected", self)) {
node.selected = false;
}
}
}
const op_table = new OPTABLE();
async function initialize() {
const reply = await rpc.call('initiate');
const interpreter = new Interpreter(window.document.getElementById("_dioxusroot"));
console.log(reply);
for (let x = 0; x < reply.length; x++) {
let edit = reply[x];
console.log(edit);
op_table[edit.type](interpreter, edit);
}
console.log("stack completed: ", interpreter.stack);
}
console.log("initializing...");
initialize();
</script>
</head>
<body>
<div id="_dioxusroot">
</div>
</body>
</html>
+230
View File
@@ -0,0 +1,230 @@
use std::borrow::BorrowMut;
use std::ops::{Deref, DerefMut};
use std::sync::mpsc::channel;
use std::sync::{Arc, RwLock};
use dioxus_core::*;
pub use wry;
use wry::application::event::{Event, WindowEvent};
use wry::application::event_loop::{ControlFlow, EventLoop};
use wry::application::window::Fullscreen;
use wry::webview::WebViewBuilder;
use wry::{
application::window::{Window, WindowBuilder},
webview::{RpcRequest, RpcResponse},
};
mod dom;
mod escape;
static HTML_CONTENT: &'static str = include_str!("./index.html");
pub fn launch(
root: FC<()>,
builder: impl FnOnce(WindowBuilder) -> WindowBuilder,
) -> anyhow::Result<()> {
launch_with_props(root, (), builder)
}
pub fn launch_with_props<P: Properties + 'static>(
root: FC<P>,
props: P,
builder: impl FnOnce(WindowBuilder) -> WindowBuilder,
) -> anyhow::Result<()> {
WebviewRenderer::run(root, props, builder)
}
/// The `WebviewRenderer` provides a way of rendering a Dioxus Virtual DOM through a bridge to a Webview instance.
/// Components used in WebviewRenderer instances can directly use system libraries, access the filesystem, and multithread with ease.
pub struct WebviewRenderer<T> {
/// The root component used to render the Webview
root: FC<T>,
}
enum RpcEvent<'a> {
Initialize {
//
edits: Vec<DomEdit<'a>>,
},
}
impl<T: Properties + 'static> WebviewRenderer<T> {
pub fn run(
root: FC<T>,
props: T,
user_builder: impl FnOnce(WindowBuilder) -> WindowBuilder,
) -> anyhow::Result<()> {
Self::run_with_edits(root, props, user_builder, None)
}
pub fn run_with_edits(
root: FC<T>,
props: T,
user_builder: impl FnOnce(WindowBuilder) -> WindowBuilder,
redits: Option<Vec<DomEdit<'static>>>,
) -> anyhow::Result<()> {
let event_loop = EventLoop::new();
let window = user_builder(WindowBuilder::new()).build(&event_loop)?;
let vir = VirtualDom::new_with_props(root, props);
// todo: combine these or something
let vdom = Arc::new(RwLock::new(vir));
let registry = Arc::new(RwLock::new(Some(WebviewRegistry::new())));
let webview = WebViewBuilder::new(window)?
// .with_visible(false)
// .with_transparent(true)
.with_url(&format!("data:text/html,{}", HTML_CONTENT))?
.with_rpc_handler(move |_window: &Window, mut req: RpcRequest| {
match req.method.as_str() {
"initiate" => {
let edits = if let Some(edits) = &redits {
serde_json::to_value(edits).unwrap()
} else {
let mut lock = vdom.write().unwrap();
let mut reg_lock = registry.write().unwrap();
// Create the thin wrapper around the registry to collect the edits into
let mut real = dom::WebviewDom::new(reg_lock.take().unwrap());
// Serialize the edit stream
let edits = {
let mut edits = Vec::new();
lock.rebuild(&mut real, &mut edits).unwrap();
serde_json::to_value(edits).unwrap()
};
// Give back the registry into its slot
*reg_lock = Some(real.consume());
edits
};
// Return the edits into the webview runtime
Some(RpcResponse::new_result(req.id.take(), Some(edits)))
}
"user_event" => {
let mut lock = vdom.write().unwrap();
let mut reg_lock = registry.write().unwrap();
// Create the thin wrapper around the registry to collect the edits into
let mut real = dom::WebviewDom::new(reg_lock.take().unwrap());
// Serialize the edit stream
let edits = {
let mut edits = Vec::new();
lock.rebuild(&mut real, &mut edits).unwrap();
serde_json::to_value(edits).unwrap()
};
// Give back the registry into its slot
*reg_lock = Some(real.consume());
// Return the edits into the webview runtime
Some(RpcResponse::new_result(req.id.take(), Some(edits)))
}
_ => todo!("this message failed"),
}
})
.build()?;
event_loop.run(move |event, _, control_flow| {
*control_flow = ControlFlow::Poll;
match event {
Event::WindowEvent {
event, window_id, ..
} => match event {
WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
WindowEvent::Resized(_) | WindowEvent::Moved(_) => {
let _ = webview.resize();
}
_ => {}
},
Event::MainEventsCleared => {
webview.resize();
// window.request_redraw();
}
_ => {} // Event::WindowEvent { event, .. } => {
// //
// match event {
// WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
// _ => {}
// }
// }
// _ => {
// // let _ = webview.resize();
// }
}
});
}
/// Create a new text-renderer instance from a functional component root.
/// Automatically progresses the creation of the VNode tree to completion.
///
/// A VDom is automatically created. If you want more granular control of the VDom, use `from_vdom`
// pub fn new(root: FC<T>, builder: impl FnOnce() -> WVResult<WebView<'static, ()>>) -> Self {
// Self { root }
// }
/// Create a new text renderer from an existing Virtual DOM.
/// This will progress the existing VDom's events to completion.
pub fn from_vdom() -> Self {
todo!()
}
/// Pass new args to the root function
pub fn update(&mut self, _new_val: T) {
todo!()
}
/// Modify the root function in place, forcing a re-render regardless if the props changed
pub fn update_mut(&mut self, _modifier: impl Fn(&mut T)) {
todo!()
}
}
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::dom::WebviewRegistry;
#[derive(Debug, Serialize, Deserialize)]
struct MessageParameters {
message: String,
}
fn HANDLER(window: &Window, mut req: RpcRequest) -> Option<RpcResponse> {
let mut response = None;
if &req.method == "fullscreen" {
if let Some(params) = req.params.take() {
if let Ok(mut args) = serde_json::from_value::<Vec<bool>>(params) {
if !args.is_empty() {
if args.swap_remove(0) {
window.set_fullscreen(Some(Fullscreen::Borderless(None)));
} else {
window.set_fullscreen(None);
}
};
response = Some(RpcResponse::new_result(req.id.take(), None));
}
}
} else if &req.method == "send-parameters" {
if let Some(params) = req.params.take() {
if let Ok(mut args) = serde_json::from_value::<Vec<MessageParameters>>(params) {
let result = if !args.is_empty() {
let msg = args.swap_remove(0);
Some(Value::String(format!("Hello, {}!", msg.message)))
} else {
// NOTE: in the real-world we should send an error response here!
None
};
// Must always send a response as this is a `call()`
response = Some(RpcResponse::new_result(req.id.take(), result));
}
}
}
response
}