Skip to content
Closed
Show file tree
Hide file tree
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
19 changes: 9 additions & 10 deletions src/LinkDotNet.Blog.Web/App.razor
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
<html lang="en">
<head>
<meta charset="utf-8"/>
@* Runs before first paint; the preferred-theme entry in ProtectedLocalStorage is encrypted and unreadable here *@
<script>
document.documentElement.dataset.bsTheme = localStorage.getItem('theme')
?? (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
Expand All @@ -22,17 +21,17 @@
<meta name="theme-color" media="(prefers-color-scheme: light)" content="#f5f5f7" />
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="#111113" />
<meta name="color-scheme" content="light dark" />
<ImportMap />
<HeadOutlet @rendermode="RenderMode.InteractiveServer"/>
<link rel="dns-prefetch" href="//cdnjs.cloudflare.com" />
<link rel="preconnect" href="//cdnjs.cloudflare.com" />
<link rel="preconnect" href="//cdn.jsdelivr.net" />
<link rel="preconnect" href="//cdn.jsdelivr.net" crossorigin />
<link rel="preload" href="css/fonts/icons.woff2" as="font" type="font/woff2" crossorigin />
<link href="css/basic.css" rel="stylesheet" />
<link href="css/icons.css" rel="stylesheet" />
<link href="css/markdown-editor.css" rel="stylesheet" />
<link rel="preload" href="LinkDotNet.Blog.Web.styles.css" as="style">
<link href="LinkDotNet.Blog.Web.styles.css" rel="stylesheet"/>
<link href="@Assets["css/basic.css"]" rel="stylesheet" />
<link href="@Assets["css/icons.css"]" rel="stylesheet" />
<link href="@Assets["css/markdown-editor.css"]" rel="stylesheet" />
<link href="@Assets["LinkDotNet.Blog.Web.styles.css"]" rel="stylesheet"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.12.0/styles/github-dark-dimmed.min.css" media="print" onload="this.media='all'" integrity="sha512-zcatBMvxa7rT7dDklfjauWsfiSFParF+hRfCdf4Zr40/MmA1gkFcBRbop0zMpvYF3FmznYFgcL8wlcuO/GwHoA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@6.0.0-alpha.1/dist/css/bootstrap.min.css" integrity="sha384-B/GM4XqrwHnWXNOWMbloTmrYXZg10cakYGmpfsR/bbzQ6JAJI4ihuyADKLnBgrCe" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.2/font/bootstrap-icons.min.css">
Expand All @@ -51,9 +50,9 @@
<a href="/" class="reload">Reload</a>
<a class="dismiss" role="button">x</a>
</div>
<script src="js/markdown-editor.js"></script>
<script src="js/code-highlighting.js"></script>
<script src="_framework/blazor.web.js"></script>
<script src="@Assets["js/markdown-editor.js"]"></script>
<script src="@Assets["js/code-highlighting.js"]"></script>
<script src="@Assets["_framework/blazor.web.js"]"></script>
<script async src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.12.0/highlight.min.js" onload="highlightCodeBlocks()" integrity="sha512-gzqHAlI1hVdzJ4wiQj/MkppDr6zgEdCoBsrXKRidcaZsSPvNQ3Fy5p7PpMt/8mltxTxMHj1Ur5NWbJdqIfpxgA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="module" src="https://cdn.jsdelivr.net/npm/bootstrap@6.0.0-alpha.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-1a/pXj49ZQ1aHEmrJ+gMw1otqoVsYwlEnlD8mIfY2TV03r20Y0CN7uqx1tQogjPL" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="module">
Expand All @@ -65,7 +64,7 @@
}
};
</script>
<script defer src="components/slideshow.js" ></script>
<script defer src="@Assets["components/slideshow.js"]" ></script>
</body>
</html>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,7 @@

var tagsChanged = BlogPost is not null && !HaveSameTagSet(BlogPost.Tags, version.Tags);
await OnVersionRestored.InvokeAsync(version);
_ = InstantJobRegistry.RunInstantJob<SimilarBlogPostJob>(parameter: true);
if (tagsChanged)
{
await TagQueryService.ClearTagCacheAsync();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
@page "/short-codes"
@using LinkDotNet.Blog.Domain
@using LinkDotNet.Blog.Infrastructure.Persistence
@using LinkDotNet.Blog.Web.Features.Services

@inject IRepository<ShortCode> ShortCodeRepository
@inject IRepository<BlogPost> BlogPostRepository
@inject IToastService ToastService
@inject IJSRuntime JSRuntime
@inject ZiggyCreatures.Caching.Fusion.IFusionCache FusionCache

<PageTitle>Shortcodes</PageTitle>

Expand Down Expand Up @@ -344,6 +346,8 @@
shortCodes.Add(newShortCode);
}

await ShortCodeCache.RemoveAsync(FusionCache);

await LoadUsage();
ToastService.ShowSuccess("Shortcode saved");
CloseEditor();
Expand All @@ -359,6 +363,7 @@
}

await ShortCodeRepository.DeleteAsync(shortCode.Id);
await ShortCodeCache.RemoveAsync(FusionCache);
shortCodes.Remove(shortCode);
ToastService.ShowSuccess("Shortcode deleted");
}
Expand Down
7 changes: 5 additions & 2 deletions src/LinkDotNet.Blog.Web/Features/Archive/ArchivePage.razor
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
protected override async Task OnInitializedAsync()
{
BlogPosts ??= (await Repository.GetAllByProjectionAsync(
p => new BlogPostPerYear(p.Id, p.Slug, p.Title, p.UpdatedDate),
p => new BlogPostPerYear(p.Id, p.Title, p.UpdatedDate),
p => p.IsPublished)).ToList();

blogPostCount = BlogPosts.Count;
Expand All @@ -64,5 +64,8 @@

private static string HeadingKey(int year) => $"heading{year}";

public sealed record BlogPostPerYear(string Id, string Slug, string Title, DateTime UpdatedDate);
public sealed record BlogPostPerYear(string Id, string Title, DateTime UpdatedDate)
{
public string Slug => BlogPost.CreateSlug(Title);
}
}
51 changes: 32 additions & 19 deletions src/LinkDotNet.Blog.Web/Features/Bookmarks/BookmarkService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ namespace LinkDotNet.Blog.Web.Features.Bookmarks;

public class BookmarkService : IBookmarkService
{
private const string Key = "bookmarks";
private readonly ILocalStorageService localStorageService;
private Task<HashSet<string>>? inFlightRead;

public BookmarkService(ILocalStorageService localStorageService)
{
Expand All @@ -17,43 +19,54 @@ public BookmarkService(ILocalStorageService localStorageService)
public async Task<bool> IsBookmarked(string postId)
{
ArgumentException.ThrowIfNullOrEmpty(postId);
await InitializeIfNotExists();
var bookmarks = await localStorageService.GetItemAsync<HashSet<string>>("bookmarks");

return bookmarks.Contains(postId);
return (await GetBookmarksAsync()).Contains(postId);
}

public async Task<IReadOnlyList<string>> GetBookmarkedPostIds()
{
await InitializeIfNotExists();
return await localStorageService.GetItemAsync<IReadOnlyList<string>>("bookmarks");
}
public async Task<IReadOnlyList<string>> GetBookmarkedPostIds() => [.. await GetBookmarksAsync()];

public async Task SetBookmark(string postId, bool isBookmarked)
{
ArgumentException.ThrowIfNullOrEmpty(postId);
await InitializeIfNotExists();

var bookmarks = await localStorageService.GetItemAsync<HashSet<string>>("bookmarks");

if (!isBookmarked)
var current = await ReadBookmarksAsync();
if (isBookmarked)
{
bookmarks.Remove(postId);
current.Add(postId);
}
else
{
bookmarks.Add(postId);
current.Remove(postId);
}

await localStorageService.SetItemAsync("bookmarks", bookmarks);
await localStorageService.SetItemAsync(Key, current);
}

// Cards on one page ask at the same time; sharing only the pending read keeps later pages in sync with other tabs
private async Task<HashSet<string>> GetBookmarksAsync()
{
var read = inFlightRead ??= ReadBookmarksAsync();
try
{
return await read;
}
finally
{
if (inFlightRead == read)
{
inFlightRead = null;
}
}
}

private async Task InitializeIfNotExists()
private async Task<HashSet<string>> ReadBookmarksAsync()
{
if (!await localStorageService.ContainsKeyAsync("bookmarks"))
try
{
return await localStorageService.GetItemAsync<HashSet<string>>(Key);
}
catch (KeyNotFoundException)
{
await localStorageService.SetItemAsync("bookmarks", new List<string>());
return [];
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,10 @@
if (firstRender)
{
isBookmarked = await BookmarkService.IsBookmarked(BlogPost.Id);
StateHasChanged();
if (isBookmarked)
{
StateHasChanged();
}
}
}
}
84 changes: 28 additions & 56 deletions src/LinkDotNet.Blog.Web/Features/Home/Components/ThemeToggler.razor
Original file line number Diff line number Diff line change
@@ -1,71 +1,43 @@
@using LinkDotNet.Blog.Web.Features.Services
@inject IJSRuntime JSRuntime
@inject ILocalStorageService LocalStorageService

<div class="position-relative d-inline-flex align-items-center @Class" role="button" @onclick="ToggleMode" title="Toggle theme">

@if (currentTheme == "light")
{
<svg xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
class="fg-secondary">
<circle cx="12" cy="12" r="5"/>
<line x1="12" y1="1" x2="12" y2="3"/>
<line x1="12" y1="21" x2="12" y2="23"/>
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/>
<line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/>
<line x1="1" y1="12" x2="3" y2="12"/>
<line x1="21" y1="12" x2="23" y2="12"/>
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/>
<line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>
</svg>
}
else
{
<svg xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
class="fg-white">
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
</svg>
}
<svg xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
class="theme-icon-light fg-secondary">
<circle cx="12" cy="12" r="5"/>
<line x1="12" y1="1" x2="12" y2="3"/>
<line x1="12" y1="21" x2="12" y2="23"/>
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/>
<line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/>
<line x1="1" y1="12" x2="3" y2="12"/>
<line x1="21" y1="12" x2="23" y2="12"/>
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/>
<line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>
</svg>
<svg xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
class="theme-icon-dark fg-white">
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
</svg>
<span class="xl:d-none">Toggle theme</span>
</div>

@code {
[Parameter]
public string Class { get; set; } = string.Empty;

private const string StorageKey = "preferred-theme";
private string? currentTheme;

protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await using var _ = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./Features/Home/Components/ThemeToggler.razor.js");

var hasStoredTheme = await LocalStorageService.ContainsKeyAsync(StorageKey);
currentTheme = hasStoredTheme
? await LocalStorageService.GetItemAsync<string>(StorageKey)
: await JSRuntime.InvokeAsync<string>("getCurrentSystemPreference");

await JSRuntime.InvokeVoidAsync("setTheme", currentTheme, hasStoredTheme);
StateHasChanged();
}
}

private async Task ToggleMode()
{
currentTheme = currentTheme == "light" ? "dark" : "light";
await JSRuntime.InvokeVoidAsync("setTheme", currentTheme, true);
await LocalStorageService.SetItemAsync(StorageKey, currentTheme);
await using var _ = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./Features/Home/Components/ThemeToggler.razor.js");
await JSRuntime.InvokeVoidAsync("toggleTheme");
}
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,5 @@
window.setTheme = (theme, remember) => {
const resolved = theme === 'auto' ? window.getCurrentSystemPreference() : theme
document.documentElement.setAttribute('data-bs-theme', resolved)
if (remember) {
localStorage.setItem('theme', resolved)
} else {
localStorage.removeItem('theme')
}
}

window.getCurrentSystemPreference = () => {
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
window.toggleTheme = () => {
const theme = document.documentElement.dataset.bsTheme === 'dark' ? 'light' : 'dark'
document.documentElement.dataset.bsTheme = theme
localStorage.setItem('theme', theme)
}
18 changes: 12 additions & 6 deletions src/LinkDotNet.Blog.Web/Features/LazyLoadImageExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,26 @@ internal sealed class LazyLoadImageExtension : IMarkdownExtension
{
public void Setup(MarkdownPipelineBuilder pipeline)
{
pipeline.DocumentProcessed -= AddLazyLoading;
pipeline.DocumentProcessed += AddLazyLoading;
pipeline.DocumentProcessed -= AddLoadingHints;
pipeline.DocumentProcessed += AddLoadingHints;
}

public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer)
{
}

private static void AddLazyLoading(MarkdownDocument document)
private static void AddLoadingHints(MarkdownDocument document)
{
var allImagesBesidesFirst = document.Descendants<LinkInline>().Where(link => link.IsImage).Skip(1);
foreach (var image in allImagesBesidesFirst)
var images = document.Descendants<LinkInline>().Where(link => link.IsImage).Select(link => link.GetAttributes()).ToList();
foreach (var attributes in images)
{
image.GetAttributes().AddPropertyIfNotExist("loading", "lazy");
attributes.AddPropertyIfNotExist("decoding", "async");
}

images.FirstOrDefault()?.AddPropertyIfNotExist("fetchpriority", "high");
foreach (var attributes in images.Skip(1))
{
attributes.AddPropertyIfNotExist("loading", "lazy");
}
}
}
30 changes: 30 additions & 0 deletions src/LinkDotNet.Blog.Web/Features/Services/ShortCodeCache.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using LinkDotNet.Blog.Domain;
using LinkDotNet.Blog.Infrastructure.Persistence;
using ZiggyCreatures.Caching.Fusion;

namespace LinkDotNet.Blog.Web.Features.Services;

public static class ShortCodeCache
{
private const string Key = "shortcodes";

public static async ValueTask<IReadOnlyCollection<ShortCode>> GetAsync(IFusionCache cache, IRepository<ShortCode> repository)
{
ArgumentNullException.ThrowIfNull(cache);
ArgumentNullException.ThrowIfNull(repository);

return await cache.GetOrSetAsync<IReadOnlyCollection<ShortCode>>(
Key,
async _ => await repository.GetAllAsync(),
TimeSpan.FromDays(7));
}

public static ValueTask RemoveAsync(IFusionCache cache)
{
ArgumentNullException.ThrowIfNull(cache);
return cache.RemoveAsync(Key);
}
}
Loading
Loading