UNPKG

@twind/with-react

Version:

Seamless integration of Twind in a React project

51 lines (50 loc) 2.66 kB
'use strict'; const core = require('@twind/core'), diff = require('fast-diff'), diff__default = /*#__PURE__*/ diff && diff.__esModule ? diff : { default: diff }; exports.createState = function(options = {}) { let { tw =core.tw , minify =core.identity } = 'function' == typeof options ? { tw: options } : options, buffer = '', lastStyle = null, restoreCurrentState = core.noop; return { push: (chunk)=>{ return buffer += chunk, null === lastStyle ? buffer.endsWith('</body></html>') : buffer.endsWith('</script>'); }, flush: ()=>{ if (buffer) { let restore = tw.snapshot(); restoreCurrentState(); let html = core.consume(buffer, tw), nextStyle = minify(core.stringify(tw.target), html); restoreCurrentState = tw.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__default.default(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; } } }; }; //# sourceMappingURL=internal-8328aafb.cjs.map