Skip to content

Commit

Permalink
用 StringBuilder 代替集合
Browse files Browse the repository at this point in the history
优化 JS 脚本
  • Loading branch information
wherewhere committed Jun 4, 2024
1 parent 8f64d18 commit 53ebfba
Show file tree
Hide file tree
Showing 7 changed files with 79 additions and 90 deletions.
31 changes: 14 additions & 17 deletions Wherlog/Controls/MarkdownSection.razor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,30 +34,27 @@ public string InternalContent
get => _content;
set
{
_content = value;
HtmlContent = ConvertToMarkupString(_content);

if (OnContentConverted.HasDelegate)
if (_content != value)
{
OnContentConverted.InvokeAsync();
_content = value;

HtmlContent = string.IsNullOrWhiteSpace(value)
? new MarkupString(value)
: ConvertToMarkupString(_content);

if (OnContentConverted.HasDelegate)
{
OnContentConverted.InvokeAsync();
}

_raiseContentConverted = true;
StateHasChanged();
}
_raiseContentConverted = true;
StateHasChanged();
}
}

public MarkupString HtmlContent { get; private set; }

protected override void OnInitialized()
{
if (Content == null)
{
throw new ArgumentNullException(nameof(Content), "You need to provide either Content or FromAsset parameter");
}

InternalContent = Content;
}

protected override void OnParametersSet() => InternalContent = Content;

protected override async Task OnAfterRenderAsync(bool firstRender)
Expand Down
20 changes: 9 additions & 11 deletions Wherlog/Controls/MarkdownSection.razor.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,27 @@
export function highlight() {
var preTagList = document.getElementsByTagName('pre');
var numberOfPreTags = preTagList.length;
for (var i = 0; i < numberOfPreTags; i++) {
var codeTag = preTagList[i].getElementsByTagName('code');
const preTagList = document.getElementsByTagName('pre');
const numberOfPreTags = preTagList.length;
for (let i = 0; i < numberOfPreTags; i++) {
const codeTag = preTagList[i].getElementsByTagName('code');
hljs.highlightElement(codeTag[0]);
}
}

export function addCopyButton() {
var snippets = document.querySelectorAll('.snippet');
var numberOfSnippets = snippets.length;
for (var i = 0; i < numberOfSnippets; i++) {
const snippets = document.querySelectorAll('.snippet');
const numberOfSnippets = snippets.length;
for (let i = 0; i < numberOfSnippets; i++) {
let copyButton = snippets[i].getElementsByClassName("hljs-copy")
if (copyButton.length === 0) {
let code = snippets[i].getElementsByTagName('code')[0].innerText;
snippets[i].innerHTML = snippets[i].innerHTML + '<button class="hljs-copy">Copy</button>'; // append copy button

copyButton[0].addEventListener("click", function () {
copyButton[0].addEventListener("click", () => {
navigator.clipboard.writeText(code);

this.innerText = 'Copied!';
let button = this;
setTimeout(function () {
button.innerText = 'Copy';
}, 1000)
setTimeout(() => button.innerText = 'Copy', 1000)
});
}
}
Expand Down
20 changes: 10 additions & 10 deletions Wherlog/Controls/PostCard.razor.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export function highlight() {
var elements = document.getElementsByClassName('highlight');
var numberOfElements = elements.length;
for (var i = 0; i < numberOfElements; i++) {
const elements = document.getElementsByClassName('highlight');
const numberOfElements = elements.length;
for (let i = 0; i < numberOfElements; i++) {
setElements(elements[i]);
}
function setElements(element) {
Expand All @@ -11,20 +11,20 @@
if (element?.className) {
element.className = 'hljs-' + element.className;
}
var numberOfElements = +element?.children.length;
for (var i = 0; i < numberOfElements; i++) {
const numberOfElements = +element?.children.length;
for (let i = 0; i < numberOfElements; i++) {
setElements(element.children[i]);
}
}
}

export function fixEmoji() {
var images = document.getElementsByClassName('emoji');
var numberOfElements = images.length;
for (var i = 0; i < numberOfElements; i++) {
var image = images[i];
const images = document.getElementsByClassName('emoji');
const numberOfElements = images.length;
for (let i = 0; i < numberOfElements; i++) {
const image = images[i];
if (image.tagName === 'IMG') {
var src = image.getAttribute('data-src');
const src = image.getAttribute('data-src');
if (src) {
image.removeAttribute('data-src');
image.setAttribute('src', src);
Expand Down
15 changes: 5 additions & 10 deletions Wherlog/Controls/TableOfContents.razor.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
const article = document.getElementById('article');
const headings = article.querySelectorAll("h2, h3, h4");

let tocArray = new Array()
const tocArray = [];
let chapter = null;
let subchapter = null;

Expand All @@ -17,7 +17,7 @@
"level": element.nodeName,
"text": element.innerText,
"href": "#" + element.id,
"anchors": new Array()
"anchors": []
};

if ("H3" === element.nodeName) {
Expand All @@ -34,32 +34,27 @@
else {
chapter = anchor;
tocArray.push(chapter);

}
}
}
return tocArray;
}

let backToTopButton = document.getElementById("backtotop");
const backToTopButton = document.getElementById("backtotop");

// When the user scrolls down 20px from the top of the document, show the button
let bodycontent = document.getElementById('body-content');
if (!bodycontent) {
bodycontent = document.body;
}

bodycontent.onscroll = function () {
scrollFunction()
};

function scrollFunction() {
bodycontent.onscroll = () => {
if (document.body.scrollTop > 20 || document.getElementById('body-content').scrollTop > 20 || document.documentElement.scrollTop > 20) {
backToTopButton.style.display = "flex";
} else {
backToTopButton.style.display = "none";
}
}
};

// When the user clicks on the button, scroll to the top of the document
export function backToTop() {
Expand Down
64 changes: 33 additions & 31 deletions Wherlog/Pages/ToolsPages/BiliBiliCardPage.razor
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@
private string id;
private string url;
private string json;
private string imageProxy = "https://images.weserv.nl/?url=";
private string example = string.Empty;
private string imageProxy;
private string example;

private string ID
{
Expand Down Expand Up @@ -81,31 +81,34 @@
JsonDocument token = JsonDocument.Parse(json);
if (token.RootElement.TryGetProperty("data", out JsonElement data))
{
List<string> attributes = new(9)
StringBuilder builder =
new StringBuilder("<bilibili-card")
.Append(" vid=\"").Append(data.GetProperty("bvid").GetString()).Append('"')
.Append(" title=\"").Append(data.GetProperty("title").GetString()).Append('"')
.Append(" author=\"").Append(data.GetProperty("owner").GetProperty("name").GetString()).Append('"')
.Append(" cover=\"").Append(data.GetProperty("pic").GetString()).Append('"')
.Append(" duration=\"").Append(FormatSecondsToTime(data.GetProperty("duration").GetInt64())).Append('"');

if (data.TryGetProperty("stat", out JsonElement stat))
{
"bilibili-card",
$"vid=\"{data.GetProperty("bvid").GetString()}\"",
$"title=\"{data.GetProperty("title").GetString()}\"",
$"author=\"{data.GetProperty("owner").GetProperty("name").GetString()}\"",
$"cover=\"{data.GetProperty("pic").GetString()}\"",
$"duration=\"{FormatSecondsToTime(data.GetProperty("duration").GetInt64())}\"",
};
JsonElement stat = data.GetProperty("stat");
attributes.Add($"views=\"{FormatLargeNumber(stat.GetProperty("view").GetInt64())}\"");
attributes.Add($"danmakus=\"{FormatLargeNumber(stat.GetProperty("danmaku").GetInt64())}\"");
_ = builder.Append(" views=\"").Append(FormatLargeNumber(stat.GetProperty("view").GetInt64())).Append('"')
.Append(" danmakus=\"").Append(FormatLargeNumber(stat.GetProperty("danmaku").GetInt64())).Append('"');
}

if (!string.IsNullOrEmpty(imageProxy))
{
attributes.Add($"views=\"{imageProxy}\"");
_ = builder.Append(" image-proxy=\"").Append(imageProxy).Append('"');
}
string element = $"<{string.Join(" ", attributes)}></bilibili-card>";

string element = builder.Append("></bilibili-card>").ToString();
const string script = "<script src=\"https://unpkg.com/hexo-tag-bilibili-card/components/bilibili-card/bilibili-card.js\"></script>";
example = new StringBuilder()
.AppendLine(script)
.AppendLine(element)
.AppendLine("```html")
.AppendLine(element)
.Append("```")
.ToString();
.AppendLine(script)
.AppendLine(element)
.AppendLine("```html")
.AppendLine(element)
.Append("```")
.ToString();
}
}
}
Expand Down Expand Up @@ -133,28 +136,27 @@
}
}


private static string FormatLargeNumber(long num)
{
return (num >= 100000000)
? $"{num / 100000000:F1}亿"
? $"{num / 100000000d:F1}亿"
: (num >= 10000)
? $"{num / 10000:F1}万"
? $"{num / 10000d:F1}万"
: num.ToString();
}

private static string FormatSecondsToTime(long second)
{
TimeSpan time = TimeSpan.FromSeconds(second);
int sec = time.Seconds;
int min = time.Minutes;
int hour = time.Hours;
List<int> times = new(3);
StringBuilder builder = new();
ulong hour = (ulong)time.TotalHours;
if (hour > 0)
{
times.Add(hour);
_ = builder.Append(hour.ToString("D2")).Append(':');
}
times.Add(min);
times.Add(sec);
return string.Join(":", times.Select(n => n.ToString("D2")));
_ = builder.Append(time.Minutes.ToString("D2")).Append(':')
.Append(time.Seconds.ToString("D2"));
return builder.ToString();
}
}
6 changes: 3 additions & 3 deletions Wherlog/wwwroot/js/highlight-extensions.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ highlight.onload = () => {
// Switch highlight Dark/Light theme
const theme = document.querySelector('fluent-design-theme');
if (theme != null) {
theme.addEventListener('onchange', (e) => {
theme.addEventListener('onchange', e => {
if (e.detail.name == 'mode') {
if (e.detail.newValue === 'undefined') return;
if (e.detail.newValue === 'undefined') { return; }
const isDark = e.detail.newValue.includes('dark');
hljs_ColorSwitcher(isDark);
}
Expand All @@ -27,7 +27,7 @@ highlight.onload = () => {

// Detect system theme changing
window.matchMedia('(prefers-color-scheme: dark)')
.addEventListener('change', (e) => {
.addEventListener('change', _ => {
hljs_ColorSystem();
});

Expand Down
13 changes: 5 additions & 8 deletions Wherlog/wwwroot/js/loading-theme.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
// When it is, we'll remove this invisibility from the body.

class LoadingTheme extends HTMLElement {

className = "hidden-body";
defaultDarkColor = "#272727";
defaultLightColor = "#fbfbfb";
Expand All @@ -17,7 +16,6 @@ class LoadingTheme extends HTMLElement {

// Custom element added to page.
connectedCallback() {

// If LocalStorage is not available, do nothing.
if (localStorage == null) {
return;
Expand Down Expand Up @@ -49,7 +47,7 @@ class LoadingTheme extends HTMLElement {

// Create a ".hidden-unstyled-body" class
// where the background-color is dark or light.
var css = `.${this.className} { visibility: hidden; background-color: ${bgColor}; }`;
const css = `.${this.className} { visibility: hidden; background-color: ${bgColor}; }`;

// Add a <style> element to the <head> element
const head = document.head || document.getElementsByTagName('head')[0];
Expand All @@ -60,7 +58,6 @@ class LoadingTheme extends HTMLElement {

document.body.classList.add(this.className);


// Add a <fluent-design-theme mode="dark|light" /> sub-element
// Do not add the "storage-name"" to avoid unwanted local storage.
const designTheme = document.createElement("fluent-design-theme");
Expand All @@ -76,9 +73,9 @@ class LoadingTheme extends HTMLElement {
}

// Attributes has changed.
attributeChangedCallback(name, oldValue, newValue) {

}
attributeChangedCallback(name, oldValue, newValue) { }
}

customElements.define("loading-theme", LoadingTheme);
if (!customElements.get("loading-theme")) {
customElements.define("loading-theme", LoadingTheme);
}

0 comments on commit 53ebfba

Please sign in to comment.