Last active
August 21, 2020 20:01
-
-
Save yishengjiang99/cafcf7769e85eb6bc302b9b429758f19 to your computer and use it in GitHub Desktop.
fast ssr.js (wip)
This file contains 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
function ssr(req, res) { | |
const { createElement } = require("react"); | |
const {renderToStaticMarkup, renderToString, renderToNodeSream} = require("react-dom/server"); | |
const queue = [], stack=[]; | |
const visited=Set(); | |
queue.push("<DOCTYPE !html>"); | |
const buffer=""; | |
let parentElement; | |
const elementStreamMixer = new StreamInterWeaver(); | |
const synchronousTagInput = new TransformStream(); | |
res.write(`<html><head>${seo+critcss}</head>`); | |
res.write( | |
`<script> | |
var qdata = {}; | |
var nodeStreamElements={}; | |
function q(str[]){ | |
const eleId = str[0]; | |
const cdata = str.splice(0,1); | |
nodeStreamElements[eleId].appendData(cdata); | |
}</script>`); | |
while(queue.length){ | |
const next=queue[0]; | |
queue=queue.splice(0,1); | |
let todo=0, i=0; | |
for(; i<vs_dag[i].length; i++){ | |
if(!visited.has(child)){ | |
queue.push(child) && todo++; | |
} | |
} | |
if(upstreamIO[next]){ | |
/* none blocking */ | |
Promise.resolve(upstreamIO[next]) | |
.then(resp=>resp.arrayBuffer) | |
.then(chunks=> createElement(chunkSelector(chunks))) | |
.then(element=> renderToNodeStream(element)) | |
.then(stream=> stream.pipe(elementStreamMixer)); | |
}else{ | |
synchronousTagInput.write(openTag`${next} ${JSON.stringify(props[next])}`); | |
} | |
visited.add(next); | |
if(todo) stack.push(next); | |
else{ | |
synchronousTagInput.write(closeTag`${next}`); | |
stack.pop(); | |
} | |
} | |
} | |
function ssrtest(){ | |
const containers=['div1','h3','span3']; | |
const vs_dag = { | |
'<DOCTYPE !html>': ['head','body'], | |
'head': ['title', 'seo', 'critcss', 'main.runtime'], | |
'body': ['navbar', 'main'], | |
'main': ['list1', 'list2','list3'], | |
}; | |
const upstreamIO ={ | |
'list1': fetch("/api/list1"), | |
'list2': fetch("/api/list2"), | |
'list3': fetch("/api/list3") | |
} | |
const props={ | |
'title': { innerText: 'super retail', style: 'font: 3em'}, | |
'seo': { innerText: 'great groceries'} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment