diff --git a/src/Elastic.Markdown/Helpers/Preloader.cs b/src/Elastic.Markdown/Helpers/Preloader.cs new file mode 100644 index 000000000..53086a4ce --- /dev/null +++ b/src/Elastic.Markdown/Helpers/Preloader.cs @@ -0,0 +1,39 @@ +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + +using System.Collections.Immutable; +using System.Diagnostics; +using System.Reflection; +using System.Text.RegularExpressions; + +namespace Elastic.Markdown.Helpers; + +public static partial class FontPreloader +{ + private static IReadOnlyCollection? FontUriCache = null!; + + public static async Task> GetFontUrisAsync() => FontUriCache ??= await LoadFontUrisAsync(); + private static async Task> LoadFontUrisAsync() + { + var cachedFontUris = new List(); + var assembly = Assembly.GetExecutingAssembly(); + var stylesResourceName = assembly.GetManifestResourceNames().First(n => n.EndsWith("styles.css")); + + using var cssFileStream = new StreamReader(assembly.GetManifestResourceStream(stylesResourceName)!); + + var cssFile = await cssFileStream.ReadToEndAsync(); + var matches = FontUriRegex().Matches(cssFile); + + foreach (Match match in matches) + { + if (match.Success) + cachedFontUris.Add($"/_static/{match.Groups[1].Value}"); + } + FontUriCache = cachedFontUris; + return FontUriCache; + } + + [GeneratedRegex(@"url\([""']?([^""'\)]+?\.(woff2|ttf|otf))[""']?\)", RegexOptions.Multiline | RegexOptions.Compiled)] + private static partial Regex FontUriRegex(); +} diff --git a/src/Elastic.Markdown/Slices/Layout/_Head.cshtml b/src/Elastic.Markdown/Slices/Layout/_Head.cshtml index 8efac7915..849b0188c 100644 --- a/src/Elastic.Markdown/Slices/Layout/_Head.cshtml +++ b/src/Elastic.Markdown/Slices/Layout/_Head.cshtml @@ -1,7 +1,12 @@ @inherits RazorSlice +@using Elastic.Markdown.Helpers @Model.Title - + @foreach (var fontFile in await FontPreloader.GetFontUrisAsync()) + { + + } + @await RenderPartialAsync(_Favicon.Create())