streams-demo-append-child-isvalid.html (2874B)
1 <!DOCTYPE html> 2 <meta charset="utf-8"> 3 <title>Append child writable stream demo</title> 4 5 <script src="transforms/transform-stream-polyfill.js"></script> 6 <script src="transforms/text-encode-transform.js"></script> 7 <script src="transforms/parse-json.js"></script> 8 <script src="transforms/split-stream.js"></script> 9 <script src="resources/highlight.pack.js"></script> 10 <script src="resources/web-animations.min.js"></script> 11 <script src="tags/view-source.js"></script> 12 13 <link rel=stylesheet href="resources/common.css"> 14 <link rel=stylesheet href="resources/commits.css"> 15 16 <h1>Append child writable stream demo</h1> 17 <a id=back-to-index href=index.html>Back to demo index</a> 18 <view-source></view-source> 19 20 <div id=buttons> 21 <button id="load">Load JSON stream</button> 22 <button id="reset">Reset</button> 23 </div> 24 25 <div id=target></div> 26 27 <script> 28 'use strict'; 29 const loadButton = document.querySelector('#load'); 30 const resetButton = document.querySelector('#reset'); 31 const targetDiv = document.querySelector('#target'); 32 const FIELDS = ['Hash', 'Date', 'Author', 'Subject']; 33 const FIELDS_LOWERCASE = FIELDS.map(string => string.toLowerCase()); 34 35 function createTable(parentElement) { 36 const table = document.createElement('table'); 37 table.id = 'commits'; 38 const tr = document.createElement('tr'); 39 for (const heading of FIELDS) { 40 const th = document.createElement('th'); 41 th.textContent = heading; 42 tr.appendChild(th); 43 } 44 table.appendChild(tr); 45 parentElement.appendChild(table); 46 return table; 47 } 48 49 // BEGIN SOURCE TO VIEW 50 function appendChildWritableStream(parentNode) { 51 return new WritableStream({ 52 write(chunk) { 53 parentNode.appendChild(chunk); 54 } 55 }); 56 } 57 58 async function fetchThenJSONToDOM() { 59 const jsonToElementTransform = new TransformStream({ 60 transform(chunk, controller) { 61 const tr = document.createElement('tr'); 62 for (const cell of FIELDS_LOWERCASE) { 63 const td = document.createElement('td'); 64 td.textContent = chunk[cell]; 65 tr.appendChild(td); 66 } 67 controller.enqueue(tr); 68 } 69 }); 70 71 const response = await fetch('data/commits.json', 72 { 73 mode: 'same-origin', 74 headers: { 75 'Cache-Control': 'no-cache, no-store' 76 } 77 }); 78 79 const table = createTable(targetDiv); 80 return response.body 81 .pipeThrough(new TextDecoder()) 82 .pipeThrough(splitStream('\n')) 83 .pipeThrough(parseJSON()) 84 .pipeThrough(jsonToElementTransform) 85 .pipeTo(appendChildWritableStream(table)); 86 } 87 // END SOURCE TO VIEW 88 89 loadButton.onclick = () => { 90 loadButton.disabled = true; 91 setTimeout(fetchThenJSONToDOM, 0); 92 }; 93 94 resetButton.onclick = () => { 95 targetDiv.innerHTML = ''; 96 loadButton.disabled = false; 97 }; 98 </script>