File size: 1,688 Bytes
53fc829
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""
代码 HTML 构建模块 - 生成带有行号和高亮的代码 HTML
"""

import html
from code_highlighting import highlight_python_line


def build_code_html(code: str, line_numbers: dict) -> str:
    """
    构建带有交互式标记的代码 HTML
    用于在演示中突出显示关键代码行和标记
    """
    lines = code.splitlines()
    rendered = ['<div id="rosa-code" class="rosa-code">']
    marker_t = "__TOK_T__"
    marker_k = "__TOK_K__"
    marker_v = "__TOK_V__"

    for index, line in enumerate(lines, start=1):
        line_with_markers = line
        if index == line_numbers["LINE_TRY"]:
            line_with_markers = line_with_markers.replace("kkk[j:j+w]", marker_k, 1)
            line_with_markers = line_with_markers.replace("t", marker_t, 1)
        if index == line_numbers["LINE_ASSIGN"]:
            line_with_markers = line_with_markers.replace("vvv[j+w]", marker_v, 1)

        highlighted = highlight_python_line(line_with_markers)
        highlighted = highlighted.replace(
            marker_t, '<span class="code-token" data-token="t">t</span>'
        )
        highlighted = highlighted.replace(
            marker_k, '<span class="code-token" data-token="k">kkk[j:j+w]</span>'
        )
        highlighted = highlighted.replace(
            marker_v, '<span class="code-token" data-token="v">vvv[j+w]</span>'
        )

        rendered.append(
            '<div class="code-line" data-line="{line}">'
            '<span class="line-no">{line}</span>'
            '<span class="line-text">{text}</span>'
            "</div>".format(line=index, text=highlighted)
        )
    rendered.append("</div>")
    return "\n".join(rendered)