Set up seperate CSS files for Apps Script UI Service - css

With Apps Script UI service, the CSS Styling can be set with the setStyleAttributes() method of the various classes.
setStyleAttributes
Multiple CSS style attributes can be set at the same time with setStyleAttributes(). The CSS style settings can be put into an key:value object assigned to a variable, and then the variable can be used in the setStyleAttributes method.
var cssHome = {"color":"red", "cursor": "pointer", "textDecoration" : "underline", "fontSize": "small", "font-family":"Arial Black"}
var menuHome = app.createMenuItem('HOME')
menuHome.setStyleAttributes(cssHome)
Right now all my code and variables are in one .gs file, and everything is in the doGet function. Is there a way to put the CSS into another file, and call it?

If you are happy authoring the CSS as key value pairs you could either wrap them in a separate function and call it at value assignment or you could store in a flat file in Drive and UrlFetch it. Neither solution allows for conventional CSS authoring but does you ask.
As it is for a doGet the former might be preferable. You could reuse this styling across multiple scripts by wrapping in another GS and referencing it as a library.
If you used HtmlService instead of UiService your CSS options are increased by convention.

Related

gwt no CssResource'WithLookup' method

I've stumbled into a situation with gwt that does not seem to have a way around.
I've created a Composite widget with many dynamic clipped Image's so I can move the clipping like a tile-map. All went well until I start using a json as a TextResource describing the layout. The ui-binder does not work in my case.
I got ClientBundleWithLookup and ConstantsWithLookup working fine, but there is no lookup for the CSS classes. The lookup of the style() [as in the many examples] gives you this obfuscated chunk of the original css file - but there is no way to map these giberish names to what was originally in the css and in the json definitions.
I then thought of a way around is to send my css as a TextResource rather than the CssResource and process it manualy. After spending the entire day doing this - there is no styles on the browser since the generated gwt javascript look for these giberish names once running in the browser.
I need a way to lookup css style names at runtime, the ideal would be to have a CssResourceWithLookup class as well. Also there's no reflection so I cant map the java methods to pass to the setStyleName()'s.
I also spotted somewhere on google a way to produce a debug map of these names - however I don't see how this will actualy help me since these names change after every compile. So I'm throughly stuck. I just dont understand how the gwt team failed this 'lookup' functionality on half of the resource bundles.
Any one with a way around this - please?
#external may help you : it turns class names obfuscation off.
In MyStyles.css:
#external .style1, .style2;
.style1{
color: green;
}
.style2{
color: red;
}
In your Java code:
myTile1.addStyleNames("style1");
myTile2.addStyleNames("style2");

How to deal with Web Controls in a class library which have file dependancies

I could do with a little guidance if possible..
I'm building a class library to contain custom web controls. I've transformed many of the jQuery UI elements into .NET classes for dynamic use in pages. e.g.
Dim Msg As New Dialog("Dialog Title", New LiteralControl("Dialog Content"))
Msg.Width.Value = 500
Msg.Height.Value = 300
Me.Controls.Add(Msg )
The necessary scripts get inserted into the head during CreateChildControls, and any jQuery file references are added to the head e.g.
RegisterScriptFile("~/Scripts/jquery-1.5.1.js")
RegisterScriptFile("~/Scripts/UI/jquery.ui.core.js")
RegisterScriptFile("~/Scripts/UI/jquery.ui.widget.js")
RegisterScriptFile("~/Scripts/UI/jquery.ui.mouse.js")
RegisterScriptFile("~/Scripts/UI/jquery.ui.draggable.js")
RegisterScriptFile("~/Scripts/UI/jquery.ui.position.js")
RegisterScriptFile("~/Scripts/UI/jquery.ui.resizable.js")
RegisterScriptFile("~/Scripts/UI/jquery.ui.dialog.js")
The WebControl base class handles inserting the references into the Page Head.
This is brilliant, however there's a problem...the file paths may differ between applications which consume the control library.
My choices that I can see are:
A) Embed the files as resources within the library itself....however the CSS styling would be non-customisable between the individual aplications, and any changes to CSS/JS would need a re-compile.
B) Define and use a standardised file heirarchy. Each application needing a folder call 'Scripts' with a fixed file heirarchy within, so the control knows where to reference the required files. The problem I can see here is that it might not always be possible to use this standardised heirarchy and could make using the library cumbersome.
C) Create a property for each control, for each file it requires. Again this would become cumbersome and a pain to use, because each instantiated control would have to have those properties set.
D) Make some kind of ResourceUrlLibrary Dictionary like class which the consuming app can populate, then give to each control as it's instantiated. However, this seems convoluted and could cause confusion for other developers.
If anyone has come across this problem and could spare me some guidance that would be brilliant :)
If its a custom control, it has a reference to the Page class, which then has a method call ResolveClientUrl to generate a relative URL for you. So that can take care of that scenario. You may want to expose a ScriptsFolder property that allows you to store the path to the scripts rather than hard-coding it too.
If this is for your own custom project, standardizing on a folder is fine, but if you are creating a common library to be reused, requiring a specific folder isn't a good idea, and you can then use the ScriptsFolder property to remedy this, or store the folder path in the config. It's OK to standardize on the use of an application setting.
To confirm, I use Telerik controls, and they go the route of having a property that defines a custom path to the script (since they rely on one for a specific control), and they also have certain settings that can be overridden by adding an application setting.
HTH.

User generated custom css

Hey, anyone have any idea what the best way to allow users to save custom css would be? Specifically, there are about 4 color values that I would like to allow a user to choose and these colors would be used to create a custom theme for the user. I'm thinking save values in the database and then using dom:loaded with prototype to set the custom style values but I'm wondering if theres a faster way? Like dynamically creating css files or something?
and then using dom:loaded with prototype
Awww, don't do that! That won't work when JavaScript is turned off.
Approach 1: Static stylesheet, dynamic values in document head
For the sake of not having to work with a dynamically created style sheet, have a separate, static CSS file with all the definitions that won't change.
<link rel="stylesheet" href="styles/static.css" type="text/css">
<!-- Or whatever you name it -->
All the definitions that will change, you could put into the head of the HTML document, fetching the user-changeable values from a database.
<style type="text/css">
.classname { font-size: (fontsize); } <-- Insert dynamic value here
.classname { color: (color); } <-- Insert dynamic value here
....
<style>
that way, the majority of the CSS stays in static, cacheable files, while the dynamic part won't cause another HTTP request.
Approach 2: Dynamic stylesheet
If you have a lot of dynamically changing values, put the entire style sheet into a script file and output it, replacing placeholders with the values from the database.
The downside to this is that to force the browser to reload the style sheet on changes, you'll have to work with a version approach stylesheet.css?version=400 which is pretty complex to do, but can sometimes be more desirable than littering the head section with CSS.
You decide which approach suits your situation better. I find myself choosing the first one most often.
I would save the 4 values in the database and then create a css file from those values. You would want to make sure and cache the created css file for each user so you don't have to dynamically create it each page view.
Creating a custom css file adds another request the browser has to make so you would need to make sure your setting up the headers correctly to cache it. If the user does change their settings you would need do something to ensure the browser immediately stops cashing the old css file and loads the new file. One way to do this is to change the url of the css file.
Example:
/usercustom.css?version=(last saved date hash)
Instead I would use your first approach and create a JSON array that you inject into the page and then you use your javascript framework to load and use the array to style the page.
You could also store the color values in the cookie from the server and use and or write to them on the client.
I think that best way is to save it to Db, because you don't want to allow user to mess with your website. At least if some pages are public.
And I personally think that answers like "do it without JavaScript" is nothing but old school BS... Did they tried to turn of JavaScript today? I don't think so... And by this paragraph I don't mean that you have to do it using JavaScript. Do it in a way that suits your needs 🤔
Wish you nice Day

Preferred method for linking to stylesheets from a UserControl?

We primarily use an ASP.NET environment at work. Right now I'm building an application which uses "Modules", which is just a UserControl, with its' Javascript right in the control, and a link element to the stylesheet for that control. I want to keep it modular, and would like the style of this control to be independent from the markup/javascript.
So I'm wondering what the preferred method of doing this is? Obviously if I didn't want the "theme" functionality I'm after, I could just use style tags at the top of the control. Right now I have a link element, as I said, and this isn't proper I don't think.
Does anyone have any preferred methods, and if so, what and why?
I considered ASP.NET themes briefly, but the idea of these controls are a little different, I think.
It's basically a shopping cart system. I don't want to get into it all, but we are using a really neat security system, and we don't want to use a premade shopping cart. I'm developing a set of controls that can be dropped on a page, for instance in SiteFinity (which is the CMS system we use) or for any other project we might have. Normally I would compile these into a DLL so we get ACTUAL controls we can drag & drop from the toolbox, then I could use internal "generic" styling and allow for any additive styling someone might want, as well as supplying a few fancier styles as well.
This is the first time I've ever done this, or really the first time anyone in our shop has done this either so I'm kind of figuring it out as I go. I might be pretty far off-base, but hopefully I'm not.
Right, the idea for this is to have a "theme", which is really just a CSS file and a jQuery template. I have them named the same, and have a Theme property on the usercontrol to set it.
When these controls are finalized, I might refactor the javascript to a RegisterScriptBlock on the code-behind, but for now they just in script tags on the control itself.
What prompted this question was DebugBar for IE, giving me warnings that link elements are not allowed inside a div. I don't much care, but after thinking about it, I had no idea how to link to the css file without doing that. I considered very briefly having an 'empty' link tag on the master and then setting THAT in the code behind on Page_Load of the UserControl, but that just seems like ass.
I could use #import I guess but I think link tags are preferred, correct?
It sounds like you're rolling your own theme engine... why not use ASP.NET Themes?
If you're determined to do it yourself, here's some code from the CssFriendly project that may be of interest to you. (I think it should be ok to post the code as long as I cite where it's from.) The .css files are flagged as Embedded Resource and the code below is used to include them as needed.
string filePath = page.ClientScript.GetWebResourceUrl(type, css);
// if filePath is not empty, embedded CSS exists -- register it
if (!String.IsNullOrEmpty(filePath))
{
if (!Helpers.HeadContainsLinkHref(page, filePath))
{
HtmlLink link = new HtmlLink();
link.Href = page.ResolveUrl(filePath);
link.Attributes["type"] = "text/css";
link.Attributes["rel"] = "stylesheet";
page.Header.Controls.Add(link);
}
}
I think what you're supposed to do is use Page.RegisterScriptBlock to register your script blocks. Best-case you shouldn't have them inline in your ascx inside script blocks. This isn't always possible, but theoretically it's the best way.
Ideally your styles should be separate from your markup as well. Your controls can have classes and IDs, but your style is based on your application and not your controls. Controls can theoretically be used in other applications where you might want a different style.
It depends on how big your app is, and whether or not it's dependent on Themes elsewhere, IMHO.
If you're using a .skin file, or if the majority of the app is also plugged into the theme, you might as well go with the theme.
But if it's just a few styles you need, you're better off to set the stylesheet manually, keep your css file external (inline styles are a PITA and defeat one of the core purposes of css).
In either case, don't forget to set the CssClass attribute on your controls.
To be proper I would have an import.css file - structure the naming of the classes to follow your controls, and import the styles within the header of the document.
If you have a module called "30DayPricingCalc" then you could name the classes/id's:
30DayPricingCalc.css
.30daypricingcalc_main_content
{
...
}
Also if you haven't I would setup a list of generic reusable styles to save you room. Since elements will allow multiple classes per object.
Also, link tags matter a lot less now than they used to. we're well past support for IE5 generation browsers and IE6 supports the #import tag.
Cheers!

How do you dynamically load a CSS file into a Flex application?

I know that you can apply CSS in order to style objects in Flex using the StyleManager:
http://livedocs.adobe.com/flex/3/html/help.html?content=styles_07.html
You can also load compiled CSS files (SWFs) dynamically:
http://livedocs.adobe.com/flex/3/html/help.html?content=styles_10.html
However, I'm dynamically creating my CSS files using a web GUI and a server-side script.
If the CSS is changed, then the script would also need to compile the CSS into an SWF (which is not a viable option). Is there any way around this?
In this comment to an issue related to this in the Adobe bug tracker T. Busser is describing what might be a viable solution for you:
"I've created a small class that will 'parse' a CSS file read with an
HTTPService object. It takes apart the
string that is returned by the
HTTPService object, break it down into
selectors, and create a new
CSSStyleDeclaration object for each
selector that is found. Once all the
properties are assigned to the
CSSStyleDeclaration object it's added
to the StyleManager. It doesn't
perform any checks, you should make
sure the CSS file is well formed, but
it will be sufficient 99% of the time.
Stuff like #font, Embed() and
ClassReference() will hardly be used
by my customers. They do need the
ability to change colors and stuff
like that so they can easily theme the
Flex application to their house
style."
You could either try to contact this person for their solution or alternatively maybe use the code from this as3csslib project as a basis for writing something like what they're describing.
You can also implement dynamic stylesheet in flex like this . Here i found this article :
http://askmeflash.com/article_m.php?p=article&id=6
Edit: This solution does not work. All selectors that are taken out of the parser are converted to lowercase. This may work for your application but it will probably not...
I am leaving this answer here because it may help some people looking for a solution and warn others of the limitations of this method.
See my question: "Looking for CSS parser written in AS3" for a complete discussion but I found a CSS parser hidden inside the standard libraries. Here is how you can use it:
public function extractFromStyleSheet(css:String):void {
// Create a StyleSheet Object
var styleSheet:StyleSheet = new StyleSheet();
styleSheet.parseCSS(css);
// Iterate through the selector objects
var selectorNames:Array = styleSheet.styleNames;
for(var i:int=0; i<selectorNames.length; i++){
// Do something with each selector
trace("Selector: "+selelectorNames[i];
var properties:Object = styleSheet.getStyle(selectorNames[i]);
for (var property:String in properties){
// Do something with each property in the selector
trace("\t"+property+" -> "+properties[property]+"\n");
}
}
}
You can then apply the styles using:
cssStyle = new CSSStyleDeclaration();
cssStyle.setStyle("color", "<valid color>);
FlexGlobals.topLevelApplication.styleManager.setStyleDeclaration("Button", cssStyle, true);
The application of CSS in Flex is handled on the server side at compilation and not on the client side at run time.
I would see two options then for you (I'm not sure how practical either are):
Use a server side script to compile your CSS as a SWF then load them dynamically.
Parse a CSS Style sheet and use the setStyle functions in flex to apply the styles. An similar example to this approach is the Flex Style Explorer where you can check out the source.
Good luck.

Resources