React & Didact

A DIY guide to build your own React

https://github.com/pomber/didact

https://github.com/pomber/didact/blob/master/didact.js

demo

https://codesandbox.io/s/react-didact-kvegz


// import React from "react";
// import ReactDOM from "react-dom";
// import React, { Component } from 'react';
// import { render } from "react-dom"; function createElement(type, props, ...children) {
return {
type,
props: {
...props,
children: children.map(child =>
typeof child === "object" ? child : createTextElement(child)
)
}
};
} function createTextElement(text) {
return {
type: "TEXT_ELEMENT",
props: {
nodeValue: text,
children: []
}
};
} function createDom(fiber) {
const dom =
fiber.type === "TEXT_ELEMENT"
? document.createTextNode("")
: document.createElement(fiber.type); updateDom(dom, {}, fiber.props); return dom;
} const isEvent = key => key.startsWith("on");
const isProperty = key => key !== "children" && !isEvent(key);
const isNew = (prev, next) => key => prev[key] !== next[key];
const isGone = (prev, next) => key => !(key in next);
function updateDom(dom, prevProps, nextProps) {
//Remove old or changed event listeners
Object.keys(prevProps)
.filter(isEvent)
.filter(key => !(key in nextProps) || isNew(prevProps, nextProps)(key))
.forEach(name => {
const eventType = name.toLowerCase().substring(2);
dom.removeEventListener(eventType, prevProps[name]);
}); // Remove old properties
Object.keys(prevProps)
.filter(isProperty)
.filter(isGone(prevProps, nextProps))
.forEach(name => {
dom[name] = "";
}); // Set new or changed properties
Object.keys(nextProps)
.filter(isProperty)
.filter(isNew(prevProps, nextProps))
.forEach(name => {
dom[name] = nextProps[name];
}); // Add event listeners
Object.keys(nextProps)
.filter(isEvent)
.filter(isNew(prevProps, nextProps))
.forEach(name => {
const eventType = name.toLowerCase().substring(2);
dom.addEventListener(eventType, nextProps[name]);
});
} function commitRoot() {
deletions.forEach(commitWork);
commitWork(wipRoot.child);
currentRoot = wipRoot;
wipRoot = null;
} function commitWork(fiber) {
if (!fiber) {
return;
} let domParentFiber = fiber.parent;
while (!domParentFiber.dom) {
domParentFiber = domParentFiber.parent;
}
const domParent = domParentFiber.dom; if (fiber.effectTag === "PLACEMENT" && fiber.dom != null) {
domParent.appendChild(fiber.dom);
} else if (fiber.effectTag === "UPDATE" && fiber.dom != null) {
updateDom(fiber.dom, fiber.alternate.props, fiber.props);
} else if (fiber.effectTag === "DELETION") {
commitDeletion(fiber, domParent);
} commitWork(fiber.child);
commitWork(fiber.sibling);
} function commitDeletion(fiber, domParent) {
if (fiber.dom) {
domParent.removeChild(fiber.dom);
} else {
commitDeletion(fiber.child, domParent);
}
} function render(element, container) {
wipRoot = {
dom: container,
props: {
children: [element]
},
alternate: currentRoot
};
deletions = [];
nextUnitOfWork = wipRoot;
} let nextUnitOfWork = null;
let currentRoot = null;
let wipRoot = null;
let deletions = null; function workLoop(deadline) {
let shouldYield = false;
while (nextUnitOfWork && !shouldYield) {
nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
shouldYield = deadline.timeRemaining() < 1;
} if (!nextUnitOfWork && wipRoot) {
commitRoot();
} requestIdleCallback(workLoop);
} requestIdleCallback(workLoop); function performUnitOfWork(fiber) {
const isFunctionComponent = fiber.type instanceof Function;
if (isFunctionComponent) {
updateFunctionComponent(fiber);
} else {
updateHostComponent(fiber);
}
if (fiber.child) {
return fiber.child;
}
let nextFiber = fiber;
while (nextFiber) {
if (nextFiber.sibling) {
return nextFiber.sibling;
}
nextFiber = nextFiber.parent;
}
} let wipFiber = null;
let hookIndex = null; function updateFunctionComponent(fiber) {
wipFiber = fiber;
hookIndex = 0;
wipFiber.hooks = [];
const children = [fiber.type(fiber.props)];
reconcileChildren(fiber, children);
} function useState(initial) {
const oldHook =
wipFiber.alternate &&
wipFiber.alternate.hooks &&
wipFiber.alternate.hooks[hookIndex];
const hook = {
state: oldHook ? oldHook.state : initial,
queue: []
}; const actions = oldHook ? oldHook.queue : [];
actions.forEach(action => {
hook.state = action(hook.state);
}); const setState = action => {
hook.queue.push(action);
wipRoot = {
dom: currentRoot.dom,
props: currentRoot.props,
alternate: currentRoot
};
nextUnitOfWork = wipRoot;
deletions = [];
}; wipFiber.hooks.push(hook);
hookIndex++;
return [hook.state, setState];
} function updateHostComponent(fiber) {
if (!fiber.dom) {
fiber.dom = createDom(fiber);
}
reconcileChildren(fiber, fiber.props.children);
} function reconcileChildren(wipFiber, elements) {
let index = 0;
let oldFiber = wipFiber.alternate && wipFiber.alternate.child;
let prevSibling = null; while (index < elements.length || oldFiber != null) {
const element = elements[index];
let newFiber = null; const sameType = oldFiber && element && element.type === oldFiber.type; if (sameType) {
newFiber = {
type: oldFiber.type,
props: element.props,
dom: oldFiber.dom,
parent: wipFiber,
alternate: oldFiber,
effectTag: "UPDATE"
};
}
if (element && !sameType) {
newFiber = {
type: element.type,
props: element.props,
dom: null,
parent: wipFiber,
alternate: null,
effectTag: "PLACEMENT"
};
}
if (oldFiber && !sameType) {
oldFiber.effectTag = "DELETION";
deletions.push(oldFiber);
} if (oldFiber) {
oldFiber = oldFiber.sibling;
} if (index === 0) {
wipFiber.child = newFiber;
} else if (element) {
prevSibling.sibling = newFiber;
} prevSibling = newFiber;
index++;
}
} const Didact = {
createElement,
render,
useState
}; /** @jsx Didact.createElement */
function Counter() {
const [state, setState] = Didact.useState(1);
return (
<h1
onClick={() => setState(c => c + 1)}
style={{
"user-select": "none"
}}
>
Count: {state}
</h1>
);
}
const element = <Counter />;
const container = document.getElementById("root");
// ReactDOM.render(element, container);
Didact.render(element, container); /* Didact.render is deprecated since React 0.14.0,
use ReactDOM.render instead (react/no-deprecated)eslint */

React & Didact的更多相关文章

  1. Build your own React

    Build your own React https://pomb.us/build-your-own-react/ https://github.com/pomber/didact demo htt ...

  2. react组件的生命周期

    写在前面: 阅读了多遍文章之后,自己总结了一个.一遍加强记忆,和日后回顾. 一.实例化(初始化) var Button = React.createClass({ getInitialState: f ...

  3. 十分钟介绍mobx与react

    原文地址:https://mobxjs.github.io/mobx/getting-started.html 写在前面:本人英语水平有限,主要是写给自己看的,若有哪位同学看到了有问题的地方,请为我指 ...

  4. RxJS + Redux + React = Amazing!(译一)

    今天,我将Youtube上的<RxJS + Redux + React = Amazing!>翻译(+机译)了下来,以供国内的同学学习,英文听力好的同学可以直接看原版视频: https:/ ...

  5. React 入门教程

    React 起源于Facebook内部项目,是一个用来构建用户界面的 javascript 库,相当于MVC架构中的V层框架,与市面上其他框架不同的是,React 把每一个组件当成了一个状态机,组件内 ...

  6. 通往全栈工程师的捷径 —— react

    腾讯Bugly特约作者: 左明 首先,我们来看看 React 在世界范围的热度趋势,下图是关键词“房价”和 “React” 在 Google Trends 上的搜索量对比,蓝色的是 React,红色的 ...

  7. 2017-1-5 天气雨 React 学习笔记

    官方example 中basic-click-counter <script type="text/babel"> var Counter = React.create ...

  8. RxJS + Redux + React = Amazing!(译二)

    今天,我将Youtube上的<RxJS + Redux + React = Amazing!>的后半部分翻译(+机译)了下来,以供国内的同学学习,英文听力好的同学可以直接看原版视频: ht ...

  9. React在开发中的常用结构以及功能详解

    一.React什么算法,什么虚拟DOM,什么核心内容网上一大堆,请自行google. 但是能把算法说清楚,虚拟DOM说清楚的聊聊无几.对开发又没卵用,还不如来点干货看看咋用. 二.结构如下: impo ...

随机推荐

  1. https://github.com/golang/go/wiki/CommonMistakes

    CommonMistakes https://golang.org/doc/faq#closures_and_goroutines Why is there no goroutine ID? ¶ Go ...

  2. Git提交代码规范 而且规范的Git提交历史,还可以直接生成项目发版的CHANGELOG(semantic-release)

    Git提交代码规范 - 木之子梦之蝶 - 博客园 https://www.cnblogs.com/liumengdie/p/7885210.html Commit message 的格式 Git 每次 ...

  3. JavaScript基础知识-基本概念

    typeof操作符 typeof 操作符返回一个字符串,表示未经计算的操作数的类型. // 数值 typeof 37 === 'number'; typeof 3.14 === 'number'; t ...

  4. win10自带输入法突然变成了繁体

    有可能是在使用Eclipse/MyEclipse的Ctrl + Shift + F进行代码格式化的时候与输入法的热键冲突了

  5. 你真的知道为什么要使用void(0)代替undefined吗?

    我们平时用到的\(\color{#FF3030}{undefined}\)只是\(\color{#FF3030}{window}\)对象下的一个属性. Object.getOwnPropertyDes ...

  6. PowerBI系列组件关系详解

    随着数据分析工具的不断更新,我们所熟知的Excel可能已经不是你想象中的样子了. Excel和Power BI又有何千丝万缕的联系? M语言和DAX语言又是什么样的存在? 操作他们又需要掌握什么样的技 ...

  7. jQuery——操作DOM

    所谓Web体验,就是Web服务器与Web浏览器之间的合作.过去,都是由服务器生成HTML文档,然后浏览器负责解释并显示该文档.后来,我们可以用CSS技术来动态修改页面的外观. ###操作属性 jQue ...

  8. Linux提权常用漏洞速查表

    漏洞列表 #CVE #Description #Kernels CVE–2018–18955 [map_write() in kernel/user_namespace.c allows privil ...

  9. 云服务器镜像问题("Couldn't resolve host 'mirrors.tencentyun.com')

    云服务器镜像问题("Couldn't resolve host 'mirrors.tencentyun.com') 原因: 腾讯云服务器内网yum源的域名 mirrors.tencentyu ...

  10. dedecms不能保存jpeg格式图片的解决方法

    方法如下: 进入织梦的后台管理目录,默认是dede文件夹,找到/inc/inc_archives_functions.php文件. 在文件里查找gif|jpg|,我找到了4个, 在它们后面加jpeg的 ...