Last active
November 23, 2020 19:08
-
-
Save SQL-MisterMagoo/c6897196c66ce3bf41ca272baae1925b to your computer and use it in GitHub Desktop.
Helper class to calculate the Scoped Css id that Blazor will use
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class CssHelper | |
{ | |
public static string GenerateScope(string targetName, string relativePath) | |
{ | |
using var hash = SHA256.Create(); | |
var bytes = Encoding.UTF8.GetBytes(relativePath.ToLowerInvariant().Replace("\\", "//") + targetName); | |
var hashBytes = hash.ComputeHash(bytes); | |
var builder = new StringBuilder(); | |
builder.Append("b-"); | |
builder.Append(ToBase36(hashBytes)); | |
return builder.ToString(); | |
string ToBase36(byte[] hash) | |
{ | |
const string chars = "0123456789abcdefghijklmnopqrstuvwxyz"; | |
var result = new char[10]; | |
var dividend = BigInteger.Abs(new BigInteger(hash.AsSpan().Slice(0, 9).ToArray())); | |
for (var i = 0; i < 10; i++) | |
{ | |
dividend = BigInteger.DivRem(dividend, 36, out var remainder); | |
result[i] = chars[(int)remainder]; | |
} | |
return new string(result); | |
} | |
} | |
} |
This is very cool, thank you! Am I correct in assuming that this is relying on the current implementation of the scoped id? E.g. it can likely change in the future? Nice find though.
Yes, most definitely a possibility for it to change.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you want to know what scoped CSS id will be used in your component, this helper will calculate it for you
var scopeId = CssHelper.GenerateScope("MyProjectName","PathTo\\MyComponent.razor.css");
This can then be passed to other components should you wish (instead of relying on ::deep)