-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathauto-alert.rb
More file actions
48 lines (41 loc) · 1.89 KB
/
auto-alert.rb
File metadata and controls
48 lines (41 loc) · 1.89 KB
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
48
require "nokogiri"
Jekyll::Hooks.register [:pages, :documents], :post_convert do |doc|
next unless doc.output_ext == ".html"
site = doc.site
next unless site.data["plugins"]
alert_type = site.data["plugins"]["auto_alert"]
next unless alert_type
fragment = Nokogiri::HTML::DocumentFragment.parse(doc.content)
# 遍历 HTML 中的所有 blockquote 标签
fragment.css("blockquote").each do |item|
# 找出第一个子节点,用于判断是否含有 [!type] 标记
first_child = item.at_css("*:first-child")
next unless first_child
next unless first_child.name == "p"
inner_html = first_child.inner_html.downcase
# 遍历所有 alert 类型
alert_type.each do |type, data|
prefix = "[!#{type}]"
prefix_with_newline = "#{prefix}\n"
# 情况一:完整匹配 [!type] 形式 <p>[!NOTE]</p>
if inner_html == prefix
# 将 alert 类型对应的 class 加入 blockquote
item["class"] = [item["class"], data["class_name"]].compact.join(" ")
# 将 <p> 替换为 <div> 并插入标题
first_child.name = "div"
first_child.inner_html = "<strong>#{data["title"]}</strong>"
break
# 情况二:段落以 [!type]\n 开头 <p>[!NOTE]\n\n other content</p>
elsif inner_html.start_with? prefix_with_newline
# 将 alert 类型对应的 class 加入 blockquote
item["class"] = [item["class"], data["class_name"]].compact.join(" ")
# 在原段落前插入标题 <div><strong>提示</strong></div><p>[!NOTE]\n\n other content</p>
first_child.add_previous_sibling "<div><strong>#{data["title"]}</strong></div>"
# 移除段落内容开头的 [!type]\n <div><strong>提示</strong></div><p>\n other content</p>
first_child.inner_html = first_child.inner_html[prefix_with_newline.length..-1] || ""
break
end
end
end
doc.content = fragment.to_html
end