refactor: Implement recursive rendering to detect and convert code blocks

Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
This commit is contained in:
2025-12-03 02:52:07 +00:00
parent 8f5dae4bdc
commit 60eefb4b27

View File

@@ -58,10 +58,52 @@ function Article({ cache }) {
}; };
const isCodeBlock = (v) => { const isCodeBlock = (v) => {
console.log(v);
return v.localName === 'pre' || v.localName === 'code' || (v.firstElementChild && v.firstElementChild.localName === 'code'); return v.localName === 'pre' || v.localName === 'code' || (v.firstElementChild && v.firstElementChild.localName === 'code');
}; };
const renderNodes = (nodes, keyPrefix = '') => {
return Array.from(nodes).map((v, k) => {
const key = `${keyPrefix}${k}`;
if (pConv.includes(key)) {
return (
<React.Fragment key={key}>
{v.innerHTML.split('\n\n').map((x, i) =>
<p key={i} dangerouslySetInnerHTML={{ __html: x }} />
)}
</React.Fragment>
);
}
if (v.nodeName === '#text') {
// Only wrap top-level text nodes in <p>
if (keyPrefix === '' && v.data.trim() !== '') {
return <p key={key}>{v.data}</p>;
}
return v.data;
}
if (v.nodeType !== Node.ELEMENT_NODE) {
return null;
}
const Tag = v.localName;
if (isCodeBlock(v)) {
return (
<React.Fragment key={key}>
<Tag dangerouslySetInnerHTML={{ __html: v.innerHTML }} />
<button onClick={() => pConvert(key)}>Convert Code to Paragraph</button>
</React.Fragment>
);
}
return (
<Tag key={key}>
{renderNodes(v.childNodes, `${key}-`)}
</Tag>
);
});
};
const nodes = (s) => { const nodes = (s) => {
if (s && s.text) { if (s && s.text) {
let div = document.createElement('div'); let div = document.createElement('div');
@@ -101,23 +143,7 @@ function Article({ cache }) {
{nodes(story) ? {nodes(story) ?
<div className='story-text'> <div className='story-text'>
{Object.entries(nodes(story)).map(([k, v]) => {renderNodes(nodes(story))}
pConv.includes(k) ?
<React.Fragment key={k}>
{v.innerHTML.split('\n\n').map((x, i) =>
<p key={i} dangerouslySetInnerHTML={{ __html: x }} />
)}
</React.Fragment>
:
(v.nodeName === '#text' ?
<p key={k}>{v.data}</p>
:
<React.Fragment key={k}>
<v.localName dangerouslySetInnerHTML={v.innerHTML ? { __html: v.innerHTML } : null} />
{isCodeBlock(v) && <button onClick={() => pConvert(k)}>Convert Code to Paragraph</button>}
</React.Fragment>
)
)}
</div> </div>
: :
<p>Problem getting article :(</p> <p>Problem getting article :(</p>