Skip to content

Instantly share code, notes, and snippets.

@SQL-MisterMagoo
Last active November 23, 2020 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SQL-MisterMagoo/c6897196c66ce3bf41ca272baae1925b to your computer and use it in GitHub Desktop.
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
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);
}
}
}
@SQL-MisterMagoo
Copy link
Author

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)

@brooklynDev
Copy link

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.

@SQL-MisterMagoo
Copy link
Author

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