Last active
February 8, 2019 09:01
-
-
Save GitaiQAQ/d393886b43fe822575402732c7987cb4 to your computer and use it in GitHub Desktop.
假装写了个 v-dom,实际上只有最简单的 diff
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #![allow(dead_code)] | |
| use std::collections::HashMap; | |
| use std::collections::HashSet; | |
| trait Renderable { | |
| fn render(&mut self) { | |
| unimplemented!() | |
| } | |
| } | |
| type Props = HashMap<String, String>; | |
| type NodeList = Vec<VirtualDomNode>; | |
| #[derive(Debug, PartialEq, Clone)] | |
| struct VirtualElementNode { | |
| key: String, | |
| node_type: String, | |
| props: Props, | |
| children: NodeList | |
| } | |
| impl Renderable for VirtualElementNode { | |
| fn render(&mut self) { | |
| unimplemented!() | |
| } | |
| } | |
| type VirtualTextNode = String; | |
| #[derive(Debug, PartialEq, Clone)] | |
| enum VirtualDomNode { | |
| Empty, | |
| VirtualElementNode(VirtualElementNode), | |
| VirtualTextNode(VirtualTextNode), | |
| } | |
| #[derive(Debug, PartialEq, Clone)] | |
| struct VirtualDom { | |
| node:VirtualDomNode | |
| } | |
| fn h(key: &str, node_type:&str, props: Props, children: NodeList) -> VirtualDomNode { | |
| VirtualDomNode::VirtualElementNode(VirtualElementNode{ | |
| key: String::from(key), | |
| node_type: String::from(node_type), | |
| props, | |
| children | |
| }) | |
| } | |
| fn t(text:&str) -> VirtualDomNode { | |
| VirtualDomNode::VirtualTextNode(VirtualTextNode::from(text)) | |
| } | |
| #[derive(Debug)] | |
| enum Patch { | |
| Update(PatchNode) | |
| } | |
| #[derive(Debug)] | |
| struct PatchNode { | |
| props: PatchProps, | |
| childrens: Vec<Option<PatchChildren>> | |
| } | |
| fn diff(old_dom: VirtualDomNode, new_dom: VirtualDomNode) -> Option<Patch> { | |
| if old_dom == new_dom { | |
| return None; | |
| } | |
| match (old_dom, new_dom) { | |
| (VirtualDomNode::Empty, VirtualDomNode::Empty) => None, | |
| (VirtualDomNode::VirtualElementNode(old_node), VirtualDomNode::VirtualElementNode(new_node)) => { | |
| Some(Patch::Update(PatchNode { | |
| props: diffProps(old_node.props, new_node.props), | |
| childrens: diffChildrens(old_node.children, new_node.children) | |
| })) | |
| }, | |
| (_, _) => None | |
| } | |
| } | |
| type PatchProps = HashMap<String, Option<String>>; | |
| fn |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment