|
1 |
| -from mkdocs import plugins |
| 1 | +import re |
2 | 2 |
|
3 |
| -from bs4 import BeautifulSoup |
| 3 | +from mkdocs import plugins |
4 | 4 |
|
5 | 5 |
|
6 | 6 | # https://www.mkdocs.org/dev-guide/plugins/#events
|
7 | 7 |
|
8 |
| -colors = { |
9 |
| - "简单": "#46c6c2", |
10 |
| - "中等": "#fac31d", |
11 |
| - "困难": "#f8615c", |
12 |
| - "Easy": "#46c6c2", |
13 |
| - "Medium": "#fac31d", |
14 |
| - "Hard": "#f8615c", |
15 |
| -} |
16 |
| - |
17 | 8 |
|
18 |
| -@plugins.event_priority(90) |
19 |
| -def on_post_page(output, page, config): |
20 |
| - is_cn_problem_page = (page.edit_url or "").endswith("README.md") |
| 9 | +@plugins.event_priority(100) |
| 10 | +def on_page_markdown(markdown, page, config, files): |
21 | 11 | difficulty = page.meta.get("difficulty")
|
22 | 12 | rating = page.meta.get("rating")
|
23 | 13 | if not difficulty and not rating:
|
24 |
| - return output |
| 14 | + return markdown |
| 15 | + is_cn_problem_page = (page.edit_url or "").endswith("README.md") |
| 16 | + images = [] |
| 17 | + if difficulty: |
| 18 | + title = "难度" if is_cn_problem_page else "Difficulty" |
| 19 | + images.append( |
| 20 | + f'<img src="https://img.shields.io/badge/{title}-{difficulty}-4051B5?style=flat-square">' |
| 21 | + ) |
25 | 22 | if rating:
|
26 |
| - rating = f"难度分 {rating}" if is_cn_problem_page else f"Rating {rating}" |
27 |
| - html = str(output) |
28 |
| - soup = BeautifulSoup(html, "html.parser") |
29 |
| - div = soup.new_tag("div", attrs={"class": "rating"}) |
30 |
| - soup.select_one("h1").insert_after(div) |
31 |
| - color = colors.get(difficulty) or "black" |
32 |
| - for s in (difficulty, rating): |
33 |
| - if not s: |
34 |
| - continue |
35 |
| - sub = soup.new_tag("div", attrs={"class": "rating-item"}) |
36 |
| - sub.string = str(s) |
37 |
| - sub["style"] = f"color: {color};" |
38 |
| - div.append(sub) |
39 |
| - return str(soup) |
| 23 | + title = "难度分" if is_cn_problem_page else "Rating" |
| 24 | + images.append( |
| 25 | + f'<img src="https://img.shields.io/badge/{title}-{rating}-4051B5?style=flat-square">' |
| 26 | + ) |
| 27 | + # 将 images 放到 <p> 标签中 |
| 28 | + images_html = '<p>' + " ".join(images) + "</p>" |
| 29 | + heading_pattern = re.compile(r"(^# .+?$)", re.MULTILINE) |
| 30 | + match = heading_pattern.search(markdown) |
| 31 | + if match: |
| 32 | + insert_position = match.end() |
| 33 | + markdown = ( |
| 34 | + markdown[:insert_position] |
| 35 | + + "\n\n" |
| 36 | + + images_html |
| 37 | + + "\n\n" |
| 38 | + + markdown[insert_position:] |
| 39 | + ) |
| 40 | + |
| 41 | + return markdown |
0 commit comments