Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: comment naming rule of dom id #8

Merged
merged 2 commits into from
Mar 31, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions src/main/java/run/halo/comment/widget/DefaultCommentWidget.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import org.pf4j.PluginWrapper;
import org.springframework.stereotype.Component;
import org.springframework.util.PropertyPlaceholderHelper;
import org.springframework.util.Assert;
import org.springframework.util.PropertyPlaceholderHelper;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.model.IAttribute;
import org.thymeleaf.model.IProcessableElementTag;
Expand Down Expand Up @@ -61,13 +63,14 @@ private String commentHtml(IAttribute groupAttribute, IAttribute kindAttribute,
properties.setProperty("kind", kindAttribute.getValue());
properties.setProperty("name", nameAttribute.getValue());
properties.setProperty("colorScheme", getColorScheme(colorSchemeAttribute));
properties.setProperty("domId", domIdFrom(group, kindAttribute.getValue(), nameAttribute.getValue()));

return PROPERTY_PLACEHOLDER_HELPER.replacePlaceholders("""
<div id="comment"></div>
<div id="${domId}"></div>
<script src="/plugins/PluginCommentWidget/assets/static/comment-widget.iife.js?version=${version}"></script>
<script>
CommentWidget.init(
"#comment",
"#${domId}",
"/plugins/PluginCommentWidget/assets/static/style.css?version=${version}",
{
group: "${group}",
Expand All @@ -80,6 +83,14 @@ private String commentHtml(IAttribute groupAttribute, IAttribute kindAttribute,
""", properties);
}

private String domIdFrom(String group, String kind, String name) {
Assert.notNull(name, "The name must not be null.");
Assert.notNull(kind, "The kind must not be null.");
String groupKindNameAsDomId = String.join("-", group, kind, name);
return "comment-" + groupKindNameAsDomId.replaceAll("[^\\-_a-zA-Z0-9\\s]", "-")
.replaceAll("(-)+", "-");
}

private String getGroup(IAttribute groupAttribute) {
return groupAttribute.getValue() == null ? ""
: StringUtils.defaultString(groupAttribute.getValue());
Expand Down