diff --git a/README.md b/README.md index 8a76118..807badf 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ MDHelper 是一个本地 Markdown / 代码文档阅读器,使用 PySide6 构 - 导出支持 PDF、HTML、DOCX、MHTML;DOCX 可选择 `pandoc` 或 `python-docx` 相关实现。 - 退出时检查未保存内容;另存为到其他目录会复制相对引用图片。MHTML 保存已渲染的图片、公式、图表及样式资源,支持离线携带。 - 图片点击放大,支持缩放、旋转、适应窗口、原始大小、保存图片和在文件夹中显示。 -- 表格支持横向滚动和一键复制。 +- 表格按内容分配列宽,长文字和网址可换行,宽表格支持横向滚动;移入或聚焦时显示复制按钮。提供网格、仅横线、无边框和可选隔行底纹,并同步到 Word 表格样式;支持跨页重复表头和行跨页设置。 - 支持导入/导出配置 JSON,便于迁移主题、书签、最近文件、阅读位置、样式和外部程序映射。 - 提供文档检查命令,用于扫描缺失的本地链接和媒体资源。 - 运行日志保存到用户可写目录,打包 exe 后也能记录启动和运行状态。 diff --git a/docs/user_manual.md b/docs/user_manual.md index 14293aa..24d8a1f 100644 --- a/docs/user_manual.md +++ b/docs/user_manual.md @@ -154,7 +154,7 @@ Markdown 支持: - 正文、一级到六级标题、引用、无序/有序/任务列表、代码块、表头文字和单元格文字。 - 加粗、强调、删除线、超链接、行内代码采用字符样式;可设置下划线、删除线和背景色,未设置的字体与字号继承所在段落。 -- 表格基准可设置边框颜色、宽度、实线/虚线/无边框等样式和单元格内边距;列表可设置标记形式与嵌套层级缩进。 +- 表格基准可设置边框颜色、宽度、线型和单元格内边距,并选择网格、仅横线、无边框,开启隔行底纹及指定底纹颜色。表头底色在“表头文字”中设置;列表可设置标记形式与嵌套层级缩进。 - 中文字体和英文字体分开设置。 - 字号支持磅(pt)、像素(px)和中文常用字号,例如五号 10.5 磅;可设置加粗、斜体、字体颜色和字符间距。 - 对齐支持左对齐、居中、右对齐和两端对齐。 @@ -177,6 +177,8 @@ Markdown 支持: 三个 Word 导出引擎均创建 `MDHelper 正文`、`MDHelper 标题 1`、`MDHelper 加粗` 等命名样式。导出后,在 Word 的样式面板中修改相应样式,即可统一调整引用该样式的内容;正文的字体和字号也会传递到未单独设置字体的加粗、强调和链接文字。表格边框及内边距通过 Word 表格样式修改。 +表格默认使用浅色表头和细网格,列宽按内容自动调整。表头、隔行底纹、边框及内边距保存在共享的 Word 表格样式中;字体和对齐继续由段落、字符样式控制。默认跨页重复表头,并尽量保持一行内容在同一页;可在“表格基准”关闭重复表头或允许行跨页。超过整页高度的行仍由 Word 自行分页。 + Word 每段文字只能引用一个字符样式,因此加粗链接等组合会生成 `MDHelper 超链接+加粗` 等组合样式。不同嵌套顺序分别保存,按 Markdown 从外到内应用格式;含链接的组合以超链接为基准,内层明确设置可覆盖外层。组合不会同时继承多个字符样式,其他组合属性可通过对应组合样式统一修改。嵌套列表使用基于对应列表样式的层级样式,层级缩进可单独修改。 内层明确设置与基准的初始值相同时,也会保留该覆盖关系;之后修改基准不会改变内层的明确设置。列表的缩进由命名段落样式控制,编号只负责标记和序号,因此在 Word 样式面板调整首行、悬挂和左右缩进可以继续生效。 @@ -193,6 +195,8 @@ Word 的字符样式会把加粗、斜体和删除线作为与段落格式叠加 核心同步覆盖对象的常规选择器,例如 `p`、`.reader p`、`h1`、`.reader h1`、`strong`、`em`、`s`、`a`,以及程序生成的 `data-mdh-style` 语义选择器。可识别的属性包括字体、字号、颜色、字符间距、`text-decoration-line`、`background-color`、对齐、行距、缩进、四向间距、换行分页,以及 `border-color` / `border-width`、表格 `padding` 和 `list-style-type`。支持常见字体简写、间距简写和 `!important`;重置当前对象只清除其核心设置,保留扩展效果。 +表格的组合选项使用 `.reader table` 上的扩展属性双向同步:`--mdhelper-table-borders`(`grid` / `horizontal` / `none`)、`--mdhelper-table-banded-rows`、`--mdhelper-table-stripe-color`、`--mdhelper-table-repeat-header`、`--mdhelper-table-allow-row-split`。开关值为 `true` / `false`,颜色使用 `#RRGGBB`。未指定的选项保留默认行为;已有字体、字号、内边距和明确的单元格底色继续生效。 + 独立的 `th`、`td`、`pre` 设置分别对应表头、单元格和代码块,不会串用到其他对象。旧版生成的 `table, th, td` 和 `pre, code` 合并规则仍作为兼容基准,未单独设置的子样式继续继承。 普通 `p` 选择器也作用于引用和宽松列表中的段落,Word 会保留这些上下文格式;紧凑列表没有独立段落元素,不受该选择器影响。表头和单元格的段前、段后及左右间距作用于内部文字区域,表格内边距仍独立设置。明显无效的 CSS 值(例如 `font-size:nope`)会被忽略并提示,前面的有效声明继续同步;有效但不能转换为 Word 的扩展表达式仍保留为 CSS。 @@ -223,8 +227,9 @@ Word 的字符样式会把加粗、斜体和删除线作为与段落格式叠加 表格: -- 宽表格支持横向滚动。 -- 可一键复制为制表符分隔文本。 +- 列宽随内容分配,长文字、网址和行内代码可以换行;超过可用空间的宽表格支持横向滚动,聚焦表格后也可用键盘滚动。 +- 移入表格或用键盘聚焦时,右上方显示“复制表格”按钮,可复制为制表符分隔文本。按钮位于内容之外,不遮挡表头,打印及 PDF 中隐藏。 +- 默认表头为浅灰蓝底色,竖线比横线更淡;深色主题自动使用相应配色。可选隔行底纹,明确设置的单元格底色优先。 ## 11. 自动刷新 @@ -267,7 +272,7 @@ DOCX 导出可选择 `pandoc` 或 `python-docx` 相关实现。正式安装版 Pandoc、python-docx 和内置基础导出均保留图形设置中的字体、字号、颜色、字符间距、对齐、缩进、段间距、行距和分页选项。正文、各级标题、列表、引用、代码和表格分别应用对应设置;Markdown 中显式加粗、斜体的局部文本仍保留强调。Word 字号按其支持的半磅精度写入;自动颜色使用 Word 自动文字颜色。 -高级 CSS 中可识别的核心属性会同步到图形设置,并用于 Word 导出;背景、边框、条件规则等扩展 CSS 不转换为 Word 格式。阅读器是连续页面,固定值/最小值行距及分页效果可能与 Word 显示不同;导出文件分别保留 Word 的固定值、最小值和分页属性。三个引擎的表格、复杂 Markdown、图片或公式支持范围仍按各自能力处理。 +高级 CSS 中可识别的核心属性会同步到图形设置,并用于 Word 导出;复杂条件规则等扩展 CSS 不转换为 Word 格式。阅读器是连续页面,固定值/最小值行距及分页效果可能与 Word 显示不同;导出文件分别保留 Word 的固定值、最小值和分页属性。三个引擎的表格、复杂 Markdown、图片或公式支持范围仍按各自能力处理。 ## 13. 配置与迁移 diff --git a/mdhelper/document_style.py b/mdhelper/document_style.py index 89e15c7..235b26d 100644 --- a/mdhelper/document_style.py +++ b/mdhelper/document_style.py @@ -8,6 +8,7 @@ from __future__ import annotations import math import re from typing import Any +from .table_style import TABLE_OPTIONS, TABLE_BOOL_FIELDS STYLE_TARGETS = ( ("paragraph", "正文段落", ".reader p:not(:where(li p, blockquote p, .admonition p, th p, td p))"), @@ -61,13 +62,14 @@ def normalize_rule(value: object) -> dict[str, Any]: if field + "_value" in rule: unit = rule.get(field + "_unit", "multiple") rule[field + "_unit"] = "em" if unit == "multiple" else unit - for key in BOOL_FIELDS: + for key in (*BOOL_FIELDS, *TABLE_BOOL_FIELDS): if key in rule and not isinstance(rule[key], bool): rule.pop(key) - for key in ('font_color', 'background_color', 'border_color'): + for key in ('font_color', 'background_color', 'border_color', 'table_stripe_color'): if key in rule and not re.fullmatch(r"auto|transparent|inherit|#[0-9a-fA-F]{6}", str(rule[key])): rule.pop(key) for key, allowed in {"alignment": {"left", "center", "right", "justify"}, + 'table_border_mode': {'grid', 'horizontal', 'none'}, "border_style": {'none','hidden','solid','dotted','dashed','double','groove','ridge','inset','outset'}, "indent_mode": {"none", "first", "hanging"}, "line_spacing_mode": {"multiple", "exact", "at_least"}}.items(): @@ -192,6 +194,10 @@ def css_declarations(value: dict) -> list[str]: out.append(f"border-style: {r['border_style']};") if 'cell_padding' in r: out.append(f"padding: {fmt(r['cell_padding'])}pt;") + for field, prop in TABLE_OPTIONS.items(): + if field in r: + value = str(r[field]).lower() if field in TABLE_BOOL_FIELDS else r[field] + out.append(f'{prop}: {value};') if 'list_marker' in r: out.append(f"list-style-type: {r['list_marker']};") if 'level_indent' in r: diff --git a/mdhelper/docx_semantic.py b/mdhelper/docx_semantic.py index bf98cea..cc63d83 100644 --- a/mdhelper/docx_semantic.py +++ b/mdhelper/docx_semantic.py @@ -14,6 +14,7 @@ from .document_style import resolved_rules, normalize_rule, font_points, length_ from .style_catalog import CATALOG, CHARACTER_DEFAULTS, explicit_rules, parent_style, style_name, legacy_base from .docx_style import W, NS, child, val, properties, _run_properties, _paragraph_properties, _order_properties from .docx_inline import source_style_order, ordered_styles, LIST_PARAGRAPH_STYLE, QUOTED_LIST_PARAGRAPH_STYLE, SOURCE_PARAGRAPH_STYLES +from .table_style import HEADER_COLOR, STRIPE_COLOR, BORDER_COLOR, VERTICAL_BORDER_COLOR RUN_FIELDS = 'rFonts sz szCs b bCs i iCs color spacing u strike shd'.split() PARAGRAPH_FIELDS = 'jc spacing ind shd snapToGrid contextualSpacing keepNext keepLines pageBreakBefore widowControl rPr outlineLvl'.split() @@ -118,6 +119,7 @@ class WordStyles: if base_id not in self.created: table_text = self.new(base_id, 'paragraph', 'MDHelper 表格文字基准') _paragraph_properties(child(table_text, 'pPr'), self.effective['table']) + remove_fields(child(table_text, 'pPr'), ('shd',)) _run_properties(child(table_text, 'rPr'), self.effective['table']) remove_fields(child(table_text, 'rPr'), ('shd',)) base = 'table' @@ -125,6 +127,7 @@ class WordStyles: rule = dict(self.effective[key]) if rule.get('font_color') == 'inherit': rule['font_color'] = 'auto' _paragraph_properties(child(style, 'pPr'), rule) + if key in ('table_head', 'table_cell'): remove_fields(child(style, 'pPr'), ('shd',)) _run_properties(child(style, 'rPr'), rule) remove_fields(child(style, 'rPr'), ('shd',)) if base: @@ -368,21 +371,28 @@ class WordStyles: style = self.new(identifier, 'table', 'MDHelper ' + style_name('table', self.rules)) rule = self.effective['table'] props = child(style, 'tblPr') + val(props, 'tblStyleRowBandSize', 1) borders = child(props, 'tblBorders') + mode = rule.get('table_border_mode', 'grid') for edge in ('top', 'left', 'bottom', 'right', 'insideH', 'insideV'): element = child(borders, edge) width = number(rule.get('border_width', .5)) - color = str(rule.get('border_color', '#d0d7de')) + vertical = edge in ('left', 'right', 'insideV') + color = str(rule.get('border_color', VERTICAL_BORDER_COLOR if vertical else BORDER_COLOR)) border = {'none':'none','hidden':'none','solid':'single','dotted':'dotted','dashed':'dashed','double':'double','groove':'threeDEngrave','ridge':'threeDEmboss','inset':'inset','outset':'outset'}.get(rule.get('border_style'), 'single') - element.attrib.update({W + 'val': border if width and color != 'transparent' else 'none', W + 'sz': str(max(2, round(width * 8))), W + 'color': color.lstrip('#') if color != 'transparent' else 'auto'}) - if 'cell_padding' in rule: - margins = child(props, 'tblCellMar') - for side in ('top', 'left', 'bottom', 'right'): - child(margins, side).attrib.update({W + 'w': str(round(number(rule['cell_padding']) * 20)), W + 'type': 'dxa'}) + visible = width and color != 'transparent' and mode != 'none' and not (mode == 'horizontal' and vertical) + element.attrib.update({W + 'val': border if visible else 'none', W + 'sz': str(max(2, round(width * 8))), W + 'color': color.lstrip('#') if color != 'transparent' else 'auto'}) + margins = child(props, 'tblCellMar') + for side in ('top', 'left', 'bottom', 'right'): + padding = number(rule.get('cell_padding', font_points(rule) * (.76 if side in ('left', 'right') else .62))) + child(margins, side).attrib.update({W + 'w': str(round(padding * 20)), W + 'type': 'dxa'}) if 'background_color' in rule: child(child(style, 'tcPr'), 'shd').attrib.update({W + 'val': 'clear', W + 'fill': str(rule['background_color']).lstrip('#') if rule['background_color'] != 'transparent' else 'auto'}) for target, condition in (('table_head', 'firstRow'), ('table_cell', 'band1Horz'), ('table_cell', 'band2Horz')): color = self.explicit[target].get('background_color') + if not color and target == 'table_head': color = HEADER_COLOR + if not color and condition == 'band2Horz' and rule.get('table_banded_rows'): + color = rule.get('table_stripe_color', STRIPE_COLOR) if color: conditional = ET.SubElement(style, W + 'tblStylePr', {W + 'type': condition}) child(child(conditional, 'tcPr'), 'shd').attrib.update({W + 'val': 'clear', W + 'fill': color.lstrip('#') if color != 'transparent' else 'auto'}) @@ -444,10 +454,19 @@ class WordStyles: props = properties(table, 'tblPr') remove_fields(props, ('tblBorders', 'tblCellMar', 'shd')) val(props, 'tblStyle', style_id('table')) + child(props, 'tblLayout').set(W + 'type', 'autofit') + child(props, 'tblW').attrib.update({W + 'type': 'pct', W + 'w': '5000'}) child(props, 'tblLook').attrib.update({W + 'val': '0020', W + 'firstRow': '1', W + 'noHBand': '0', W + 'noVBand': '1'}) + rule = self.effective['table'] + for index, row in enumerate(table.findall(W + 'tr')): + row_props = properties(row, 'trPr') + val(row_props, 'tblHeader', int(index == 0 and rule.get('table_repeat_header', True))) + val(row_props, 'cantSplit', int(not rule.get('table_allow_row_split', False))) for cell in table.iter(W + 'tc'): tcpr = cell.find(W + 'tcPr') - if tcpr is not None: remove_fields(tcpr, ('shd', 'tcBorders', 'tcMar')) + if tcpr is not None: + remove_fields(tcpr, ('shd', 'tcBorders', 'tcMar')) + child(tcpr, 'tcW').attrib.update({W + 'type': 'auto', W + 'w': '0'}) def apply_semantic_styles(path, rules, **defaults): diff --git a/mdhelper/docx_style.py b/mdhelper/docx_style.py index cdff149..d9c76ac 100644 --- a/mdhelper/docx_style.py +++ b/mdhelper/docx_style.py @@ -38,6 +38,7 @@ def _order_properties(root): 'style': 'name aliases basedOn next link autoRedefine hidden uiPriority semiHidden unhideWhenUsed qFormat locked personal personalCompose personalReply rsid pPr rPr tblPr trPr tcPr tblStylePr', 'tblPr': 'tblStyle tblpPr tblOverlap bidiVisual tblStyleRowBandSize tblStyleColBandSize tblW jc tblCellSpacing tblInd tblBorders shd tblLayout tblCellMar tblLook tblCaption tblDescription tblPrChange', 'tcPr': 'cnfStyle tcW gridSpan hMerge vMerge tcBorders shd noWrap tcMar textDirection tcFitText vAlign hideMark cellIns cellDel cellMerge tcPrChange', + 'trPr': 'cnfStyle divId gridBefore gridAfter wBefore wAfter cantSplit trHeight tblHeader tblCellSpacing jc hidden ins del trPrChange', "pPr": "pStyle keepNext keepLines pageBreakBefore framePr widowControl numPr suppressLineNumbers pBdr shd tabs suppressAutoHyphens kinsoku wordWrap overflowPunct topLinePunct autoSpaceDE autoSpaceDN bidi adjustRightInd snapToGrid spacing ind contextualSpacing mirrorIndents suppressOverlap jc textDirection textAlignment textboxTightWrap outlineLvl divId cnfStyle rPr sectPr pPrChange", "rPr": "rStyle rFonts b bCs i iCs caps smallCaps strike dstrike outline shadow emboss imprint noProof snapToGrid vanish webHidden color spacing w kern position sz szCs highlight u effect bdr shd fitText vertAlign rtl cs em lang eastAsianLayout specVanish oMath rPrChange", } diff --git a/mdhelper/markdown_renderer.py b/mdhelper/markdown_renderer.py index 4acf8ff..578c902 100644 --- a/mdhelper/markdown_renderer.py +++ b/mdhelper/markdown_renderer.py @@ -98,6 +98,8 @@ class MarkdownRenderer: elif token.type == 'list_item_open': key = 'list_task' if 'task-list-item' in (token.attrGet('class') or '') else (lists[-1] if lists else 'list_bullet') token.attrSet('data-mdh-style', key) + elif token.type == 'table_open': + token.attrSet('data-mdh-table', '') elif token.type in ('th_open', 'td_open'): token.attrSet('data-mdh-style', 'table_head' if token.type == 'th_open' else 'table_cell') for child in token.children or []: diff --git a/mdhelper/resources/reader.css b/mdhelper/resources/reader.css index 93ee9c0..89fd96a 100644 --- a/mdhelper/resources/reader.css +++ b/mdhelper/resources/reader.css @@ -209,57 +209,45 @@ table { } .table-wrapper { - margin: 1.2em 0; + position: relative; + margin: max(1.2em, 28px) 0 1.2em; +} + +.table-scroll { overflow-x: auto; - border: 1px solid #d5dbe5; - border-radius: 8px; + border-radius: 6px; background: #ffffff; } .table-wrapper table { - min-width: 640px; margin: 0; - border: 0; -} - -.table-wrapper th:first-child, -.table-wrapper td:first-child { - border-left: 0; -} - -.table-wrapper th:last-child, -.table-wrapper td:last-child { - border-right: 0; -} - -.table-wrapper tr:first-child th, -.table-wrapper tr:first-child td { - border-top: 0; -} - -.table-wrapper tr:last-child th, -.table-wrapper tr:last-child td { - border-bottom: 0; + table-layout: auto; } .table-tools { - position: sticky; - left: 0; + position: absolute; + bottom: 100%; + right: 2px; + margin-bottom: 4px; display: flex; justify-content: flex-end; - gap: 0.45em; - padding: 0.44em 0.52em; - border-bottom: 1px solid #d5dbe5; - background: #f7f9fc; + opacity: 0; + pointer-events: none; +} + +.table-wrapper:hover .table-tools, +.table-wrapper:focus-within .table-tools { + opacity: 1; + pointer-events: auto; } .copy-table-button { - padding: 0.25em 0.62em; + padding: 2px 8px; border: 1px solid #c8d0dc; border-radius: 5px; background: #ffffff; color: #354052; - font: 600 0.78em "Segoe UI", "Microsoft YaHei UI", sans-serif; + font: 600 12px/18px "Segoe UI", "Microsoft YaHei UI", sans-serif; cursor: pointer; } @@ -267,14 +255,21 @@ table { background: #f0f4f8; } -:where(html[data-theme="dark"]) .table-wrapper { - border-color: #3a4352; +.copy-table-button:focus-visible { + outline: 2px solid #3578c8; + outline-offset: 2px; +} + +@media (hover: none) { + .table-tools { opacity: 1; pointer-events: auto; } +} + +:where(html[data-theme="dark"]) .table-scroll { background: #20242c; } -:where(html[data-theme="dark"]) .table-tools { - border-bottom-color: #3a4352; - background: #242b36; +:where(html[data-theme="dark"]) .reader { + --reader-table-stripe: #252c37; } :where(html[data-theme="dark"]) .copy-table-button { @@ -290,12 +285,15 @@ table { th, td { border: 1px solid #d5dbe5; + border-left-color: #e8ecf2; + border-right-color: #e8ecf2; padding: 0.62em 0.76em; vertical-align: top; + overflow-wrap: anywhere; } th { - background: #edf1f6; + background: #f1f5f9; font-weight: 650; text-align: left; } @@ -303,12 +301,28 @@ th { :where(html[data-theme="dark"]) th, :where(html[data-theme="dark"]) td { border-color: #3a4352; + border-left-color: #303845; + border-right-color: #303845; } :where(html[data-theme="dark"]) th { background: #2b3340; } +:where(th, td) code { + white-space: normal; + overflow-wrap: anywhere; +} + +thead { display: table-header-group; } +tr { break-inside: avoid; } + +@media print { + .table-tools { display: none; } + .table-wrapper { margin: 1.2em 0; } + .table-scroll { overflow: visible; border-radius: 0; } +} + code { font-family: "Cascadia Mono", Consolas, "Courier New", monospace; } diff --git a/mdhelper/resources/reader.js b/mdhelper/resources/reader.js index 93618ab..6689e0e 100644 --- a/mdhelper/resources/reader.js +++ b/mdhelper/resources/reader.js @@ -195,6 +195,12 @@ document.addEventListener("DOMContentLoaded", () => { const wrapper = document.createElement("div"); wrapper.className = "table-wrapper"; + const scroll = document.createElement("div"); + scroll.className = "table-scroll"; + scroll.tabIndex = 0; + scroll.setAttribute("role", "region"); + scroll.setAttribute("aria-label", "表格内容,可横向滚动"); + table.setAttribute("data-mdh-table", ""); const tools = document.createElement("div"); tools.className = "table-tools"; @@ -203,6 +209,8 @@ document.addEventListener("DOMContentLoaded", () => { copyButton.type = "button"; copyButton.className = "copy-table-button"; copyButton.textContent = "复制表格"; + copyButton.setAttribute("aria-label", "复制表格"); + copyButton.title = "复制表格"; copyButton.addEventListener("click", async () => { const rows = [...table.querySelectorAll("tr")].map((row) => @@ -220,7 +228,8 @@ document.addEventListener("DOMContentLoaded", () => { tools.appendChild(copyButton); table.parentNode.insertBefore(wrapper, table); wrapper.appendChild(tools); - wrapper.appendChild(table); + wrapper.appendChild(scroll); + scroll.appendChild(table); }); const lightbox = document.createElement("div"); diff --git a/mdhelper/style_catalog.py b/mdhelper/style_catalog.py index 916ab19..f438b6e 100644 --- a/mdhelper/style_catalog.py +++ b/mdhelper/style_catalog.py @@ -2,6 +2,7 @@ from __future__ import annotations from dataclasses import dataclass from copy import deepcopy +from .table_style import TABLE_ONLY_FIELDS @dataclass(frozen=True) @@ -94,7 +95,7 @@ def explicit_rules(rules): inherited = {**CHARACTER_DEFAULTS.get(base, {}), **inherited} if key in ('table_head', 'table_cell') and not base and legacy_base(key, rules): legacy = rules.get('table') if isinstance(rules.get('table'), dict) else {} - inherited.update({k: v for k, v in legacy.items() if k not in {'border_color', 'border_width', 'border_style', 'cell_padding'}}) + inherited.update({k: v for k, v in legacy.items() if k not in TABLE_ONLY_FIELDS}) if key == 'inline_code' and not base and legacy_base(key, rules): legacy = rules.get('code') if isinstance(rules.get('code'), dict) else {} inherited.update({k: v for k, v in legacy.items() if k in CHARACTER_FIELDS}) diff --git a/mdhelper/style_dialog.py b/mdhelper/style_dialog.py index 7fcb0b1..a39e36a 100644 --- a/mdhelper/style_dialog.py +++ b/mdhelper/style_dialog.py @@ -221,6 +221,22 @@ class DocumentStyleEditorDialog(QDialog): form.addRow('边框颜色 / 宽度 / 样式', self._row(self.border_color_edit, self.border_width_spin, self.border_style_combo)) self.padding_row = form.rowCount() form.addRow('内边距', self.cell_padding_spin) + self.table_rows = [] + self.table_border_mode_box = self._combo([('继承', None), ('浅色网格', 'grid'), ('仅横线', 'horizontal'), ('无边框', 'none')]) + self.table_banded_rows_box = self._combo([('继承(关闭)', None), ('开启', True), ('关闭', False)]) + self.table_stripe_color_edit = QLineEdit() + self.table_stripe_color_edit.setPlaceholderText('随主题 / #RRGGBB') + self.table_repeat_header_box = self._combo([('继承(开启)', None), ('开启', True), ('关闭', False)]) + self.table_allow_row_split_box = self._combo([('继承(禁止)', None), ('允许', True), ('禁止', False)]) + for label, widget in ( + ('表格边框布局', self.table_border_mode_box), + ('隔行底纹 / 颜色', self._row(self.table_banded_rows_box, self.table_stripe_color_edit)), + ('跨页重复表头', self.table_repeat_header_box), + ('表格行跨页', self.table_allow_row_split_box), + ): + self.table_rows.append(form.rowCount()) + form.addRow(label, widget) + self.table_stripe_color_edit.editingFinished.connect(self._store_and_refresh) self.list_marker_box = self._combo([('继承', None), ('圆点', 'disc'), ('空心圆', 'circle'), ('方块', 'square'), ('数字', 'decimal'), ('小写字母', 'lower-alpha'), ('大写字母', 'upper-alpha'), ('小写罗马', 'lower-roman'), ('大写罗马', 'upper-roman'), ('无', 'none')]) self.marker_row = form.rowCount() @@ -457,6 +473,8 @@ class DocumentStyleEditorDialog(QDialog): for row in range(self.paragraph_row_start, self.paragraph_row_end): self.form.setRowVisible(row, not character) self.form.setRowVisible(self.border_row, self._current_target == 'table') self.form.setRowVisible(self.padding_row, self._current_target == 'table') + for row in self.table_rows: + self.form.setRowVisible(row, self._current_target == 'table') self.form.setRowVisible(self.marker_row, self._current_target.startswith('list')) self.form.setRowVisible(self.level_row, self._current_target.startswith('list')) self.background_edit.setText(rule.get('background_color', '')) @@ -464,6 +482,10 @@ class DocumentStyleEditorDialog(QDialog): self.border_width_spin.setValue(number(rule.get('border_width'), -1)) self._select(self.border_style_combo, rule.get('border_style')) self.cell_padding_spin.setValue(number(rule.get('cell_padding'), -1)) + for field, box in (('table_border_mode', self.table_border_mode_box), ('table_banded_rows', self.table_banded_rows_box), + ('table_repeat_header', self.table_repeat_header_box), ('table_allow_row_split', self.table_allow_row_split_box)): + self._select(box, rule.get(field)) + self.table_stripe_color_edit.setText(rule.get('table_stripe_color', '')) self.level_indent_spin.setValue(number(rule.get('level_indent'), -1)) self._select(self.list_marker_box, rule.get('list_marker')) rule = normalize_rule(rule) @@ -520,6 +542,11 @@ class DocumentStyleEditorDialog(QDialog): put(key, widget.value() if widget.value() >= 0 else None) put('list_marker', self.list_marker_box.currentData()) put('border_style', self.border_style_combo.currentData()) + for field, box in (('table_border_mode', self.table_border_mode_box), ('table_banded_rows', self.table_banded_rows_box), + ('table_repeat_header', self.table_repeat_header_box), ('table_allow_row_split', self.table_allow_row_split_box)): + put(field, box.currentData()) + stripe_color = self.table_stripe_color_edit.text().strip() + put('table_stripe_color', stripe_color if re.fullmatch(r'#[0-9a-fA-F]{6}|transparent', stripe_color) else None) color = self.color_combo.currentData() put("font_color", self.color_button.text() if color == "custom" else color) direction = self.character_spacing_combo.currentData() diff --git a/mdhelper/style_sync.py b/mdhelper/style_sync.py index f0f14f3..a99e19f 100644 --- a/mdhelper/style_sync.py +++ b/mdhelper/style_sync.py @@ -14,6 +14,7 @@ from tinycss2.color3 import parse_color from .document_style import (STYLE_TARGETS, normalize_rule, css_declarations, build_document_style_css, fmt, font_points, resolved_rules) +from .table_style import TABLE_OPTIONS, TABLE_BOOL_FIELDS, TABLE_ONLY_FIELDS, table_helper_css SELECTORS = {key: selector for key, _, selector in STYLE_TARGETS} LABELS = {key: label for key, label, _ in STYLE_TARGETS} @@ -28,6 +29,7 @@ GROUPS = { **{side: (f"{side}_indent_value", f"{side}_indent_unit") for side in ("left", "right")}, **{side: (f"space_{side}_value", f"space_{side}_unit") for side in ("before", "after")}, **{name: (name,) for name in ("contextual_spacing", "keep_with_next", "keep_lines_together", "page_break_before", "widow_control")}, + **{name: (name,) for name in TABLE_OPTIONS}, } PROPERTIES = { "fonts": {"font-family", "--mdhelper-font-chinese", "--mdhelper-font-english"}, @@ -43,6 +45,7 @@ PROPERTIES = { "keep_with_next": {"break-after", "page-break-after"}, "keep_lines_together": {"break-inside", "page-break-inside"}, "page_break_before": {"break-before", "page-break-before"}, "widow_control": {"widows", "orphans"}, + **{name: {prop} for name, prop in TABLE_OPTIONS.items()}, } CORE_PROPERTIES = set().union(*PROPERTIES.values()) @@ -346,7 +349,7 @@ def _collect_cascade(source: str, result: Analysis): for selector, origin in aliases.items(): child = {'th': 'table_head', 'td': 'table_cell', 'code': 'code_block', 'pre': 'code_block'}.get(selector.removeprefix('.reader ')) if child and origin in ('table', 'code'): - if origin == 'table' and prop in PROPERTIES['border_color'] | PROPERTIES['border_width'] | PROPERTIES['border_style'] | PROPERTIES['padding']: continue + if origin == 'table' and prop in PROPERTIES['border_color'] | PROPERTIES['border_width'] | PROPERTIES['border_style'] | PROPERTIES['padding'] | set(TABLE_OPTIONS.values()): continue bindings.append((child, origin, 1, _specificity(selector))) character_props = set().union(*(PROPERTIES[g] for g in ('fonts','size','bold','italic','color','tracking','decoration'))) for target, origin, direct, specificity in bindings: @@ -383,6 +386,10 @@ class _CoreRuleReader: for prop, field in (('border-width', 'border_width'), ('padding', 'cell_padding'), ('--mdhelper-list-level-indent', 'level_indent')): self.read(prop, lambda value, field=field: self.effect_length(value, field)) self.choice('border-style','border_style',{name:name for name in ('none','hidden','solid','dotted','dashed','double','groove','ridge','inset','outset')}) + self.choice(TABLE_OPTIONS['table_border_mode'], 'table_border_mode', {name: name for name in ('grid', 'horizontal', 'none')}) + for field in TABLE_BOOL_FIELDS: + self.choice(TABLE_OPTIONS[field], field, {'true': True, 'false': False}) + self.read(TABLE_OPTIONS['table_stripe_color'], lambda value: self.effect_color(value, 'table_stripe_color')) self.choice('list-style-type', 'list_marker', {x: x for x in ('none', 'disc', 'circle', 'square', 'decimal', 'lower-alpha', 'upper-alpha', 'lower-roman', 'upper-roman')}) self.read('line-height', self.line) for side, prefix in (('left', 'left_indent'), ('right', 'right_indent'), ('top', 'space_before'), ('bottom', 'space_after')): @@ -392,7 +399,7 @@ class _CoreRuleReader: self.choice('--mdhelper-contextual-spacing', 'contextual_spacing', {'true': True, 'false': False}) from .style_catalog import CATALOG, CHARACTER_FIELDS unsupported = set() - if self.target != 'table': unsupported.update(('border_color', 'border_width', 'border_style', 'cell_padding')) + if self.target != 'table': unsupported.update(TABLE_ONLY_FIELDS) if not self.target.startswith('list'): unsupported.update(('list_marker', 'level_indent')) if CATALOG[self.target].kind == 'character': unsupported.update(set(self.rule) - CHARACTER_FIELDS) for field in sorted(unsupported & self.rule.keys()): @@ -667,6 +674,7 @@ def render_css(source: str, rules: dict, font_family: str = '', font_size_px: fl inherited = {key: {field: value for field, value in rule.items() if field not in rules.get(key, {})} for key, rule in inherited.items()} contextual = {key: {"contextual_spacing": True} for key, rule in rules.items() if isinstance(rule, dict) and rule.get("contextual_spacing")} helpers = build_document_style_css(contextual, reset_list_paragraphs=False) + helpers += '\n' + table_helper_css(rules.get('table', {})) # Emit the same font variables as the authored rules; a child's Chinese # font declaration must not shadow an inherited English font declaration. for key, rule in inherited.items(): diff --git a/mdhelper/table_style.py b/mdhelper/table_style.py new file mode 100644 index 0000000..a16da91 --- /dev/null +++ b/mdhelper/table_style.py @@ -0,0 +1,36 @@ +"""Table-only options shared by the style editor, CSS and Word exporter.""" + +TABLE_OPTIONS = { + 'table_border_mode': '--mdhelper-table-borders', + 'table_banded_rows': '--mdhelper-table-banded-rows', + 'table_stripe_color': '--mdhelper-table-stripe-color', + 'table_repeat_header': '--mdhelper-table-repeat-header', + 'table_allow_row_split': '--mdhelper-table-allow-row-split', +} +TABLE_BOOL_FIELDS = ('table_banded_rows', 'table_repeat_header', 'table_allow_row_split') +TABLE_ONLY_FIELDS = {'border_color', 'border_width', 'border_style', 'cell_padding', *TABLE_OPTIONS} +HEADER_COLOR = '#f1f5f9' +STRIPE_COLOR = '#f8fafc' +BORDER_COLOR = '#d5dbe5' +VERTICAL_BORDER_COLOR = '#e8ecf2' + + +def table_helper_css(rule): + """Companion rules for options that affect descendants of the table.""" + parts = [] + selector = '.reader table[data-mdh-table]' + mode = rule.get('table_border_mode') + if mode in ('horizontal', 'none'): + declarations = 'border-style: none;' if mode == 'none' else 'border-left-style: none; border-right-style: none;' + parts.append(f'{selector}, {selector} th, {selector} td {{ {declarations} }}') + if rule.get('table_banded_rows'): + color = rule.get('table_stripe_color', 'var(--reader-table-stripe, #f8fafc)') + # Low specificity lets explicit cell backgrounds remain authoritative. + parts.append(f':where(.reader table) tbody tr:where(:nth-child(even)) td {{ background-color: {color}; }}') + if 'table_repeat_header' in rule: + display = 'table-header-group' if rule['table_repeat_header'] else 'table-row-group' + parts.append(f'{selector} thead {{ display: {display}; }}') + if 'table_allow_row_split' in rule: + value = 'auto' if rule['table_allow_row_split'] else 'avoid' + parts.append(f'{selector} tr {{ break-inside: {value}; }}') + return '\n'.join(parts) diff --git a/tests/test_renderer.py b/tests/test_renderer.py index 0f573e5..8ae2b9e 100644 --- a/tests/test_renderer.py +++ b/tests/test_renderer.py @@ -22,7 +22,7 @@ def test_sample_media_and_code_rendering() -> None: renderer = MarkdownRenderer(project_root) html = renderer.render_file(project_root / "sample.md") - assert "