Skip to content

Commit

Permalink
3.0.0-alpha-05
Browse files Browse the repository at this point in the history
  • Loading branch information
chanan committed Apr 22, 2020
1 parent 1097367 commit 2e942c0
Show file tree
Hide file tree
Showing 16 changed files with 449 additions and 114 deletions.
2 changes: 1 addition & 1 deletion src/BlazorStyled/BlazorStyled.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<LangVersion>8.0</LangVersion>
<AddRazorSupportForMvc>true</AddRazorSupportForMvc>
<PackageId>BlazorStyled</PackageId>
<Version>3.0.0-alpha-04</Version>
<Version>3.0.0-alpha-05</Version>
<Authors>Chanan Braunstein</Authors>
<Title>BlazorStyled</Title>
<Description>CSS in Blazor Components</Description>
Expand Down
23 changes: 14 additions & 9 deletions src/BlazorStyled/IStyled.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,27 @@ namespace BlazorStyled
{
public interface IStyled
{
Task ClearStyles();
Task ClearStylesAsync();
void ClearStyles();
Task<string> CssAsync(string css);
Task<string> CssAsync(string className, string css);
Task<string> CssAsync(List<string> classes, string css);
string Css(string css);
string Css(string className, string css);
string Css(List<string> classes, string css);
Task<string> Keyframes(string css);
Task Fontface(string css);
Task AddGoogleFonts(List<GoogleFont> googleFonts);
Task<string> KeyframesAsync(string css);
Task FontfaceAsync(string css);
Task AddGoogleFontsAsync(List<GoogleFont> googleFonts);
string Keyframes(string css);
void Fontface(string css);
void AddGoogleFonts(List<GoogleFont> googleFonts);
IStyled WithId(string id);
IStyled WithId(string id, int priority = 1000);
Task SetThemeValue(string name, string value);
Task<IDictionary<string, string>> GetThemeValues();
Task SetGlobalStyle(string name, string classname);
Task<IDictionary<string, string>> GetGlobalStyles();
Task<string> GetGlobalStyle(string name);
Task SetThemeValueAsync(string name, string value);
void SetThemeValue(string name, string value);
Task<IDictionary<string, string>> GetThemeValuesAsync();
void SetGlobalStyle(string name, string classname);
IDictionary<string, string> GetGlobalStyles();
string GetGlobalStyle(string name);
}
}
292 changes: 277 additions & 15 deletions src/BlazorStyled/Internal/ScriptManager.cs

Large diffs are not rendered by default.

97 changes: 52 additions & 45 deletions src/BlazorStyled/Internal/Scripts.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@
window.BlazorStyled.writeRule(sheet, updatedRule, logger);
} else {
try {
if (updatedRule.indexOf(":-moz") !== -1 && "MozBoxSizing" in document.body.style) {
if (updatedRule.indexOf(':-moz') !== -1 && 'MozBoxSizing' in document.body.style) {
window.BlazorStyled.insertRule(sheet.sheet, updatedRule, logger);
} else if (updatedRule.indexOf(":-moz") === -1) {
} else if (updatedRule.indexOf(':-moz') === -1) {
window.BlazorStyled.insertRule(sheet.sheet, updatedRule, logger);
} else {
logger.warn("Mozilla rule not inserted: ", updatedRule);
logger.warn('Mozilla rule not inserted: ', updatedRule);
}
} catch (err) {
logger.error("Failed to insert: ", updatedRule);
logger.error('Failed to insert: ', updatedRule);
logger.error(err);
}
}
Expand All @@ -38,7 +38,7 @@
try {
window.BlazorStyled.updatedInsertedRule(sheet.sheet, oldRule, updatedRule, logger);
} catch (err) {
logger.error("Failed to update: ", rule);
logger.error('Failed to update: ', rule);
logger.error(err);
}
}
Expand All @@ -48,7 +48,7 @@
const sheet = document.getElementById(stylesheetId);
if (sheet) {
document.head.removeChild(sheet);
logger.log("Cleared stylesheet: ", stylesheetName);
logger.log('Cleared stylesheet: ', stylesheetName);
}
},
setThemeValue: function (stylesheetId, stylesheetName, priority, name, value, development, debug) {
Expand All @@ -61,10 +61,10 @@
const rule = theme.rules[i];
if (rule.indexOf(name) !== -1) {
if (oldValue) {
const selector = rule.substring(0, rule.indexOf("{"));
const selector = rule.substring(0, rule.indexOf('{'));
const oldRule = window.BlazorStyled.parseTheme(
stylesheetId,
rule.replace("[" + name + "]", oldValue),
rule.replace('[' + name + ']', oldValue),
logger
);
if (oldRule) {
Expand All @@ -85,72 +85,69 @@
}
}
} catch (err) {
logger.error("Failed to update: ", rule);
logger.error('Failed to update: ', rule);
logger.error(err);
}
},
getThemeValues: function (stylesheetId) {
const theme = window.BlazorStyled.getOrCreateTheme(stylesheetId);
return theme.values;
},
setGlobalStyle: function (stylesheetId, name, value) {
const theme = window.BlazorStyled.getOrCreateTheme(stylesheetId);
theme.globalStyles[name] = value;
},
getGlobalStyles: function (stylesheetId) {
const theme = window.BlazorStyled.getOrCreateTheme(stylesheetId);
return theme.globalStyles;
},
parseTheme: function (stylesheetId, rule, logger) {
if (rule.indexOf("[") === -1) {
if (rule.indexOf('[') === -1) {
return rule;
}
const theme = window.BlazorStyled.getOrCreateTheme(stylesheetId);
if (!theme.rules.find((r) => r === rule)) {
theme.rules.push(rule);
}
const themeValueName = rule.substring(rule.indexOf("[") + 1, rule.indexOf("]"));
const themeValueName = rule.substring(rule.indexOf('[') + 1, rule.indexOf(']'));
const themeValue = theme.values[themeValueName];
if (themeValue === undefined) {
return undefined;
}
const updated = rule.replace("[" + themeValueName + "]", themeValue);
const updated = rule.replace('[' + themeValueName + ']', themeValue);
return window.BlazorStyled.parseTheme(stylesheetId, updated, logger);
},
getOrCreateTheme: function (stylesheetId) {
if (window.BlazorStyled.themes[stylesheetId] === undefined) {
window.BlazorStyled.themes[stylesheetId] = {
values: {},
rules: [],
globalStyles: {},
};
}
return window.BlazorStyled.themes[stylesheetId];
},
initLogger: function (debug) {
this.debug = {};
if (debug) {
for (var m in console) {
if (typeof console[m] === "function") {
this.debug[m] = console[m].bind(window.console);
if (!window.BlazorStyled.debug.init) {
for (var m in console) {
if (typeof console[m] === 'function') {
window.BlazorStyled.debug[m] = console[m].bind(window.console);
}
}
window.BlazorStyled.debug.init = true;
}
return window.BlazorStyled.debug;
} else {
for (var m2 in console) {
if (typeof console[m2] === "function") {
this.debug[m2] = function () {};
if (!window.BlazorStyled.fakeDebug.init) {
for (var m2 in console) {
if (typeof console[m2] === 'function') {
window.BlazorStyled.fakeDebug[m2] = function () {};
}
}
window.BlazorStyled.fakeDebug.init = true;
}
return window.BlazorStyled.fakeDebug;
}
return this.debug;
},
getOrCreateSheet: function (stylesheetId, stylesheetName, priority, logger) {
const DATA_PRIORITY = "data-blazorstyled-priority";
const DATA_NAME = "data-blazorstyled-name";
const DATA_PRIORITY = 'data-blazorstyled-priority';
const DATA_NAME = 'data-blazorstyled-name';
const sheet = document.getElementById(stylesheetId);
if (sheet) return sheet;
const styleEl = document.createElement("style");
const id = document.createAttribute("id");
const styleEl = document.createElement('style');
const id = document.createAttribute('id');
id.value = stylesheetId;
styleEl.setAttributeNode(id);
const dataName = document.createAttribute(DATA_NAME);
Expand Down Expand Up @@ -183,37 +180,34 @@
} else {
head.appendChild(styleEl);
}
logger.log("Inserted stylesheet: ", styleEl);
logger.log('Inserted stylesheet: ', styleEl);
return styleEl;
},
writeRule: function (sheet, rule, logger) {
if (!sheet.innerText) {
sheet.innerText = rule;
logger.log("Written: ", rule);
logger.log('Written: ', rule);
} else {
if (sheet.innerText.indexOf(rule) === -1) {
sheet.innerText = rule.startsWith("@import") ? rule + sheet.innerText : sheet.innerText + rule;
logger.log("Written: ", rule);
sheet.innerText = rule.startsWith('@import') ? rule + sheet.innerText : sheet.innerText + rule;
logger.log('Written: ', rule);
}
}
},
insertRule: function (sheet, rule, logger) {
const index = rule.startsWith("@import") ? 0 : sheet.cssRules.length;
const index = rule.startsWith('@import') ? 0 : sheet.cssRules.length;
sheet.insertRule(rule, index);
logger.log("Inserted at " + index + ": ", rule);
logger.log('Inserted at ' + index + ': ', rule);
},
updateWrittenRule: function (sheet, oldRule, rule, logger) {
if (!sheet.innerText) {
sheet.innerText = rule;
}
sheet.innerText = sheet.innerText.replace(oldRule, rule);
logger.log("Updated old rule: " + oldRule + " to new rule: " + rule);
logger.log('Updated old rule: ' + oldRule + ' to new rule: ' + rule);
},
updatedInsertedRule: function (sheet, oldRule, rule, logger) {
const temp = window.BlazorStyled.getOrCreateSheet("temp", "temp", window.BlazorStyled.initLogger(false));
temp.sheet.insertRule(oldRule);
const oldCssText = temp.sheet.cssRules[0].cssText;
document.head.removeChild(temp);
const oldCssText = window.BlazorStyled.getRuleText(rule);
let index = -1;
for (var i = 0; i < sheet.cssRules.length; i++) {
if (sheet.cssRules[i].cssText === oldCssText) {
Expand All @@ -223,8 +217,21 @@
if (index !== -1) {
sheet.deleteRule(index);
sheet.insertRule(rule, index);
logger.log("Updated old rule at " + index + ": " + oldRule + " to new rule: " + rule);
logger.log('Updated old rule at ' + index + ': ' + oldRule + ' to new rule: ' + rule);
}
},
getRuleText: function (rule) {
const head = document.head;
const styleEl = document.createElement('style');
window.BlazorStyled.debug.log(styleEl);
window.BlazorStyled.debug.dir(StyleEl);
head.appendChild(styleEl);
styleEl.sheet.insertRule(rule);
const text = temp.sheet.cssRules[0].cssText;
head.removeChild(styleEl);
return text;
},
themes: {},
debug: {},
fakeDebug: {},
};
77 changes: 65 additions & 12 deletions src/BlazorStyled/Internal/StyledImpl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ public string Css(List<string> classes, string css)
return sb.ToString().Trim();
}

public async Task<string> Keyframes(string css)
public async Task<string> KeyframesAsync(string css)
{
try
{
Expand All @@ -130,7 +130,26 @@ public async Task<string> Keyframes(string css)
}
}

public async Task Fontface(string css)
public string Keyframes(string css)
{
try
{
css = "@keyframes &{" + css.RemoveComments().RemoveDuplicateSpaces() + "}";
IList<ParsedClass> parsedClasses = css.GetClasses();
Task.Run(() => _scriptManager.UpdatedParsedClasses(_id.GetStableHashCodeString(), _id, _priority, parsedClasses));
return parsedClasses.First().Hash;
}
catch (StyledException e)
{
throw e;
}
catch (Exception e)
{
throw StyledException.GetException(css, e);
}
}

public async Task FontfaceAsync(string css)
{
try
{
Expand All @@ -146,19 +165,48 @@ public async Task Fontface(string css)
}
}

public async Task ClearStyles()
public void Fontface(string css)
{
try
{
Css(css);
}
catch (StyledException e)
{
throw e;
}
catch (Exception e)
{
throw StyledException.GetException(css, e);
}
}

public async Task ClearStylesAsync()
{
await _scriptManager.ClearStyles(_id.GetStableHashCodeString(), _id);
}

public async Task AddGoogleFonts(List<GoogleFont> googleFonts)
public void ClearStyles()
{
Task.Run(() => _scriptManager.ClearStyles(_id.GetStableHashCodeString(), _id));
}

public async Task AddGoogleFontsAsync(List<GoogleFont> googleFonts)
{
string fontString = string.Join("|", googleFonts.Select(googleFont => googleFont.Name.Replace(' ', '+') + ':' + string.Join(",", googleFont.Styles)));
string uri = $"//fonts.googleapis.com/css?family={fontString}&display=swap";
IList<ParsedClass> parsedClasses = new List<ParsedClass> { new ParsedClass(uri) };
await _scriptManager.UpdatedParsedClasses(_id.GetStableHashCodeString(), _id, _priority, parsedClasses);
}

public void AddGoogleFonts(List<GoogleFont> googleFonts)
{
string fontString = string.Join("|", googleFonts.Select(googleFont => googleFont.Name.Replace(' ', '+') + ':' + string.Join(",", googleFont.Styles)));
string uri = $"//fonts.googleapis.com/css?family={fontString}&display=swap";
IList<ParsedClass> parsedClasses = new List<ParsedClass> { new ParsedClass(uri) };
Task.Run(() => _scriptManager.UpdatedParsedClasses(_id.GetStableHashCodeString(), _id, _priority, parsedClasses));
}

public IStyled WithId(string id)
{
return WithId(id, 1000);
Expand All @@ -174,29 +222,34 @@ public IStyled WithId(string id, int priority)
return new StyledImpl(_scriptManager, id.Replace(" ", "-"), priority);
}

public async Task SetThemeValue(string name, string value)
public async Task SetThemeValueAsync(string name, string value)
{
await _scriptManager.SetThemeValue(_id.GetStableHashCodeString(), _id, _priority, name, value);
}

public async Task<IDictionary<string, string>> GetThemeValues()
public void SetThemeValue(string name, string value)
{
Task.Run(() => _scriptManager.SetThemeValue(_id.GetStableHashCodeString(), _id, _priority, name, value));
}

public async Task<IDictionary<string, string>> GetThemeValuesAsync()
{
return await _scriptManager.GetThemeValues(_id.GetStableHashCodeString());
}

public async Task SetGlobalStyle(string name, string classname)
public string GetGlobalStyle(string name)
{
await _scriptManager.SetGlobalStyle(_id.GetStableHashCodeString(), name, classname);
return _scriptManager.GetGlobalStyle(_id.GetStableHashCodeString(), name);
}

public async Task<IDictionary<string, string>> GetGlobalStyles()
public void SetGlobalStyle(string name, string classname)
{
return await _scriptManager.GetGlobalStyles(_id.GetStableHashCodeString());
_scriptManager.SetGlobalStyle(_id.GetStableHashCodeString(), name, classname);
}

public async Task<string> GetGlobalStyle(string name)
public IDictionary<string, string> GetGlobalStyles()
{
return await _scriptManager.GetGlobalStyle(_id.GetStableHashCodeString(), name);
return _scriptManager.GetGlobalStyles(_id.GetStableHashCodeString());
}
}
}
Loading

0 comments on commit 2e942c0

Please sign in to comment.