UNPKG

@twind/with-react

Version:

Seamless integration of Twind in a React project

50 lines (49 loc) 2.58 kB
import { consume, stringify, tw, identity, noop } from '@twind/core'; import diff from 'fast-diff'; function createState(options = {}) { let { tw: tw$1 = tw , minify =identity } = 'function' == typeof options ? { tw: options } : options, buffer = '', lastStyle = null, restoreCurrentState = noop; return { push: (chunk)=>{ return buffer += chunk, null === lastStyle ? buffer.endsWith('</body></html>') : buffer.endsWith('</script>'); }, flush: ()=>{ if (buffer) { let restore = tw$1.snapshot(); restoreCurrentState(); let html = consume(buffer, tw$1), nextStyle = minify(stringify(tw$1.target), html); restoreCurrentState = tw$1.snapshot(); restore(); if (null === lastStyle) // inital shell is ready html = html.replace('</head>', `<style data-twind>${nextStyle}</style></head>`); else { // a suspense chunk let styleDiff = [], offset = 0; for (let [type, text] of diff(lastStyle, nextStyle)){ 1 === type && // insert styleDiff.push([ offset, text ]); // must be equal: type === 0 offset += text.length; } styleDiff.length && // add style patch script that will update the previously created style element content // but only if client side twind hasn't taken over yet (data-twind="claimed") // ;(function (style, diff) { // if (style) { // style.textContent = diff.reduce(function (textContent, change) { // return textContent.slice(0, change[0]) + change[1] + textContent.slice(change[0]) // }, style.textContent || '') // } // })(document.querySelector('style[data-twind=""]'), []) (html = `<script>!function(e,n){e&&(e.textContent=n.reduce((function(e,n){return e.slice(0,n[0])+n[1]+e.slice(n[0])}),e.textContent||''))}(document.querySelector('style[data-twind=""]'),${JSON.stringify(styleDiff)})</script>${html}`); } return buffer = '', lastStyle = nextStyle, html; } } }; } export { createState }; //# sourceMappingURL=internal-55eec367.js.map