| 1 | """把主题排版转成大鱼号保存接口和预览均能保留的 HTML 表现属性。""" |
| 2 | from patchright.async_api import Page |
| 3 | |
| 4 | |
| 5 | async def render_dayu_compatible_html(page: Page, html: str, images: list[str]) -> dict: |
| 6 | """保留文字和图片顺序,以 font/table 属性表达颜色、背景和近似字号,不把正文转成图片。""" |
| 7 | return await page.evaluate("""({html, images}) => { |
| 8 | const root = document.createElement('div'); root.innerHTML = html; |
| 9 | const sourceImages = root.querySelectorAll('img'); |
| 10 | if (sourceImages.length !== images.length) throw Error('主题原稿与上传图片数量不符'); |
| 11 | const uploaded = images.map(html => { |
| 12 | const holder = document.createElement('div'); holder.innerHTML = html; |
| 13 | const image = holder.firstElementChild; |
| 14 | if (image?.tagName !== 'IMG' || image.dataset.infoed !== '1') throw Error('图片缺少平台上传元数据'); |
| 15 | return image; |
| 16 | }); |
| 17 | // 用浏览器解析颜色并合成透明色;旧式 color/bgcolor 属性只能表达不透明 RGB。 |
| 18 | const canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; |
| 19 | const context = canvas.getContext('2d'); |
| 20 | function color(value, background) { |
| 21 | context.clearRect(0, 0, 1, 1); context.fillStyle = value; context.fillRect(0, 0, 1, 1); |
| 22 | const rgba = context.getImageData(0, 0, 1, 1).data; |
| 23 | const rgb = [...rgba].slice(0, 3).map((n, i) => Math.round(n * rgba[3] / 255 + background[i] * (1 - rgba[3] / 255))); |
| 24 | return {rgb, hex: '#' + rgb.map(n => n.toString(16).padStart(2, '0')).join(''), css: `rgb(${rgb.join(', ')})`}; |
| 25 | } |
| 26 | function pixels(value, parent) { |
| 27 | if (!value || value === 'inherit') return parent; |
| 28 | // 渲染器的 calc(1.2 * 16px) 经浏览器解析后为 calc(19.2px);保留其确定的像素值。 |
| 29 | const calculated = value.match(/^calc\\(([+-]?[\\d.]+)px\\)$/); |
| 30 | if (calculated) return Number(calculated[1]); |
| 31 | const n = parseFloat(value); |
| 32 | if (!Number.isFinite(n)) throw Error(`不支持的主题尺寸: ${value}`); |
| 33 | if (value.endsWith('rem')) return n * 16; |
| 34 | if (value.endsWith('em')) return n * parent; |
| 35 | if (value.endsWith('%')) return n * parent / 100; |
| 36 | return n; |
| 37 | } |
| 38 | const fontSizes = [10, 13, 16, 18, 24, 32, 48]; |
| 39 | function borderPixels(value) { |
| 40 | // Chromium 的边框关键字对应 1/3/5px;none/hidden 在调用处按不可见边框处理。 |
| 41 | const keywords = {thin: 1, medium: 3, thick: 5}; |
| 42 | return value in keywords ? keywords[value] : pixels(value || '0px', 0); |
| 43 | } |
| 44 | let imageIndex = 0; |
| 45 | function visit(node, inherited) { |
| 46 | if (node.nodeType === Node.TEXT_NODE) { |
| 47 | if (!node.nodeValue.trim()) return document.createTextNode(node.nodeValue); |
| 48 | const font = document.createElement('font'); font.textContent = node.nodeValue; |
| 49 | const foreground = color(inherited.color, inherited.background); |
| 50 | font.setAttribute('color', foreground.hex); |
| 51 | font.setAttribute('face', inherited.fontFamily); |
| 52 | let nearest = 0; |
| 53 | fontSizes.forEach((size, i) => { |
| 54 | if (Math.abs(size - inherited.fontSize) < Math.abs(fontSizes[nearest] - inherited.fontSize)) nearest = i; |
| 55 | }); |
| 56 | font.setAttribute('size', String(nearest + 1)); |
| 57 | return font; |
| 58 | } |
| 59 | if (node.nodeType !== Node.ELEMENT_NODE) return document.createTextNode(''); |
| 60 | const style = node.style; |
| 61 | const backgroundValue = style.backgroundColor; |
| 62 | const background = backgroundValue && backgroundValue !== 'transparent' |
| 63 | ? color(backgroundValue, inherited.background) : null; |
| 64 | const state = { |
| 65 | color: style.color || inherited.color, |
| 66 | background: background ? background.rgb : inherited.background, |
| 67 | fontFamily: style.fontFamily || inherited.fontFamily, |
| 68 | fontSize: pixels(style.fontSize, inherited.fontSize), |
| 69 | align: style.textAlign || inherited.align, |
| 70 | }; |
| 71 | if (node.tagName === 'IMG') { |
| 72 | const image = uploaded[imageIndex++].cloneNode(true); |
| 73 | for (const name of ['alt', 'title']) if (node.hasAttribute(name)) image.setAttribute(name, node.getAttribute(name)); |
| 74 | return image; |
| 75 | } |
| 76 | // 主题容器改用 div,避免平台把 section 变成含块级内容的 span;语义标题/引用/列表仍保留。 |
| 77 | const tag = ['SECTION', 'FIGURE'].includes(node.tagName) ? 'div' : node.tagName.toLowerCase(); |
| 78 | const element = document.createElement(tag); |
| 79 | for (const attr of node.attributes) { |
| 80 | if (!['style', 'id', 'class'].includes(attr.name)) element.setAttribute(attr.name, attr.value); |
| 81 | } |
| 82 | if (['left', 'center', 'right', 'justify'].includes(state.align)) element.setAttribute('align', state.align); |
| 83 | for (const child of node.childNodes) element.appendChild(visit(child, state)); |
| 84 | if (tag === 'hr') { |
| 85 | const visible = ['Top', 'Right', 'Bottom', 'Left'].filter(side => |
| 86 | style[`border${side}Style`] && !['none', 'hidden'].includes(style[`border${side}Style`])); |
| 87 | if (visible.length) element.setAttribute('color', color(style[`border${visible[0]}Color`], state.background).hex); |
| 88 | element.setAttribute('size', String(Math.max(1, ...visible.map(side => borderPixels(style[`border${side}Width`]))))); |
| 89 | return element; |
| 90 | } |
| 91 | const sides = ['Top', 'Right', 'Bottom', 'Left']; |
| 92 | const borders = sides.map(side => ({ |
| 93 | side, width: ['none', 'hidden', ''].includes(style[`border${side}Style`]) ? 0 : borderPixels(style[`border${side}Width`]), |
| 94 | color: style[`border${side}Color`], |
| 95 | })).filter(border => border.width > 0); |
| 96 | const padding = Math.max(...sides.map(side => pixels(style[`padding${side}`] || '0px', state.fontSize))); |
| 97 | if (!background && !borders.length && !padding) return element; |
| 98 | // 实测保存及预览保留这些 table 属性;不依赖会被移除的 CSS,也不伪造平台图片标记。 |
| 99 | const table = document.createElement('table'); |
| 100 | table.setAttribute('width', '100%'); table.setAttribute('cellspacing', '0'); |
| 101 | table.setAttribute('cellpadding', String(Math.round(padding))); |
| 102 | table.setAttribute('border', borders.length ? String(Math.round(borders[0].width)) : '0'); |
| 103 | if (background) table.setAttribute('bgcolor', background.hex); |
| 104 | if (borders.length) { |
| 105 | table.setAttribute('bordercolor', color(borders[0].color, state.background).hex); |
| 106 | const frames = {Top: 'above', Bottom: 'below', Left: 'lhs', Right: 'rhs'}; |
| 107 | table.setAttribute('frame', borders.length === 1 ? frames[borders[0].side] : 'box'); |
| 108 | table.setAttribute('rules', 'none'); |
| 109 | } |
| 110 | const row = table.insertRow(), cell = row.insertCell(); |
| 111 | cell.setAttribute('valign', 'top'); cell.appendChild(element); |
| 112 | return table; |
| 113 | } |
| 114 | const output = document.createElement('div'); |
| 115 | const defaults = {color: '#333333', background: [255, 255, 255], fontFamily: 'Microsoft YaHei, sans-serif', fontSize: 16, align: 'left'}; |
| 116 | for (const child of root.childNodes) output.appendChild(visit(child, defaults)); |
| 117 | const textColors = [...output.querySelectorAll('font[color]')].map(font => ({ |
| 118 | text: font.textContent.replace(/[\\s\\u200b\\ufeff]+/g, ''), |
| 119 | color: color(font.getAttribute('color'), [255, 255, 255]).css, |
| 120 | })); |
| 121 | const backgroundColors = [...output.querySelectorAll('table[bgcolor]')].map(table => color(table.getAttribute('bgcolor'), [255, 255, 255]).css); |
| 122 | return {html: output.innerHTML, expectations: {text_colors: textColors, background_colors: backgroundColors}, |
| 123 | mode: 'dayu-compatible', limitations: ['圆角不保留', '字号映射为平台可保留的字体等级', '间距和边框可能与本地主题不同']}; |
| 124 | }""", {"html": html, "images": images}) |
| 125 |