Showing posts with label WPO. Show all posts
Showing posts with label WPO. Show all posts
Tuesday, October 6, 2015
Occuper inutilement votre bande passante pour tester vos équipements
Un de mes responsables de tests favoris me demandait comment réaliser une occupation de bande passante pour ses tests CPL et IAD (des box aussi appelées Gateways). Il travaille essentiellement sur Windows.
Ma solution est assez simple et peut vous être utile. Il suffit d'installer wget et de déposer sur l'IAD un fichier bien volumineux. La plupart des IAD du marché sont équipées d'un DMS : un serveur de médias de type UPnP A/V & DLNA. Ces petites bêtes sont alors visibles tels de simple serveur HTTP.
Il faut alors repérer l'URL du fichier déposer. Je vous conseille l'excellente suite d'outils UPnP Tools pour y arriver. Vous avez l'adresse ! Alors, rendez-vous à la dernière étape, elle consiste à utiliser un fichier BATCH (old school mais très simple) de façon à requérir le fameux fichier indéfiniment. C'est sur cette requête que vous appliquer l'occupation souhaitée de bande passante.
Voici le petit script
Read more »
Ma solution est assez simple et peut vous être utile. Il suffit d'installer wget et de déposer sur l'IAD un fichier bien volumineux. La plupart des IAD du marché sont équipées d'un DMS : un serveur de médias de type UPnP A/V & DLNA. Ces petites bêtes sont alors visibles tels de simple serveur HTTP.
Il faut alors repérer l'URL du fichier déposer. Je vous conseille l'excellente suite d'outils UPnP Tools pour y arriver. Vous avez l'adresse ! Alors, rendez-vous à la dernière étape, elle consiste à utiliser un fichier BATCH (old school mais très simple) de façon à requérir le fameux fichier indéfiniment. C'est sur cette requête que vous appliquer l'occupation souhaitée de bande passante.
Voici le petit script
bandwidth_alloc.bat ::startDans ce script, la limitation est placée à 30ko.
wget -r --limit-rate=30k http//url_sur_l_iad/grosfichier.mkv -o wgetlog
goto start
Faciliter l'intégration d'images responsives avec Grunt
Dernièrement, j'ai eu l'occasion de travailler avec Shiawuen sur une technique appelée Clowncar. Cette technique permet une intégration simple de vos images en mode responsive : en fonction du périphérique (ordinateur, tablette ou modèle de smartphone), seul l'image dans sa résolution la plus appropriée est chargée. Cette technique est basée sur les articles d'Estelle Weyl.
En quoi consiste cette technique et ce plugin Grunt ?
Et bien, c'est assez futé et simple. Vous centralisez toutes vos photos (ou image pour votre site) dans un unique répertoire. Grunt et le plugin Grunt-Clowncar vont automatiquement créer un fichier SVG par photo (le 'car') et des miniatures (les 'clowns') de ces photos pour chaque résolution des périphériques visés.
Dans chaque SVG se trouve des directives de type media query permettant de pointer vers les miniatures en fonction des périphériques.
Au global, vous insérer les fichiers SVG tels de simples images dans votre page web. Automatiquement, le navigateur de votre périphérique ira chercher la miniature correspondante de la photo : la miniature est la plus appropriée à votre résolution. Nous sommes bien dans le cas d'images responsives mais en ne faisant qu'une petite ligne de code. Simple et efficace.
J'ai fait un petit 'livre de cuisine' (un cookbook) dispo ici : https://github.com/shiawuen/grunt-clowncar#cookbook.
Read more »
En quoi consiste cette technique et ce plugin Grunt ?
Et bien, c'est assez futé et simple. Vous centralisez toutes vos photos (ou image pour votre site) dans un unique répertoire. Grunt et le plugin Grunt-Clowncar vont automatiquement créer un fichier SVG par photo (le 'car') et des miniatures (les 'clowns') de ces photos pour chaque résolution des périphériques visés.
Dans chaque SVG se trouve des directives de type media query permettant de pointer vers les miniatures en fonction des périphériques.
Au global, vous insérer les fichiers SVG tels de simples images dans votre page web. Automatiquement, le navigateur de votre périphérique ira chercher la miniature correspondante de la photo : la miniature est la plus appropriée à votre résolution. Nous sommes bien dans le cas d'images responsives mais en ne faisant qu'une petite ligne de code. Simple et efficace.
J'ai fait un petit 'livre de cuisine' (un cookbook) dispo ici : https://github.com/shiawuen/grunt-clowncar#cookbook.
Do we need HTML and CSS when we got JavaScript or more? A case for AbsurdJS, Meteor, Famo.us and CoffeeScript.
Introduction
AbsurdJS is an amazing project. What is it about? A processor for your HTML and CSS in JavaScript. In JSON to be more precise.The problem
CSS was invented for designers. But do you really know that much designers that are able to provide you with a nice CSS rules that will be awesome on all screens? You are favored by gods if it is your case. Most of the time, they will provide you with some PSD (what an ugly form of design), AI (if you are lucky), Sketch or SVG (here, it is not anymore based on luck, it is like having an angel upon your shoulders).The same goes with HTML. Semantics that appears with HTML5 were added for SEO. But do you know that much SEO guys that will give you the right HTML code? I haven't seen any in my whole 20 years on the web carrier(though SEO is not that long of a job).
Thus, why are we using 3 languages for writing our codes. Is that right? Do we have to? Is it done for helping us and keeping separation of concerns? Funny. Patterns like this exists since the dawn of design patterns from the GoF. And what if we need to synchronize this HTML, CSS and JS back together for animations purposes? We request back in our code the HTML tags that we have just declared? We hooks on the CSS? If we need a color theme, do we have to write it twice or more? Funny, too. Even media queries for responsive web designs, seems like an odd way of reproducing the abstract factory pattern (or the bridge depending on if you know to who you are distributing your files).
The solutions
There are many. Generally, I was keen on using preprocessors: SASS, LESS, Stylus, YAML, Jade, Blade, CoffeeScript, Typescript, Dart, ... But, it finally does not give me a proper answer to the problems previously mentioned. It still need glue code to make all of this work together properly. Things started to shape up when I end up using Meteor, Famo.us and Velocity.js. The Blaze component of Meteor is transforming your HTML, more precisely, your HTML templates using Spacebar, a derivative of Mustache, into JS code. The same goes with Famo.us. It creates HTML and CSS rules that plays well together so that they limit layout trashing issues and combines this technics with advanced physic and animation engine. The same goes with Velocity.js. This jQuery plugins brings back synchronized CSS animations in with JS.Still, plain vanilla JavaScript is a pain to write. While there are plenty of transpilers that could lessen the burden (like Dart and Typescript, to mention the most used ones), none have proven to be as easy as CoffeeScript to me.
Conclusion
Now the solution starts to shape up. Why not use the power of AbsurdJS, Meteor, Famo.us and CoffeeScript? This combination would be a real full stack. It would goes from the persistance layer, the application server to the front end with one and only one language. A transpiled one that even lessen the number of lines that you need to write.
Labels:
CoffeeScript,
Innovation,
Jade,
Meteor,
Meteor.js,
SEO,
WPO
Responsive SVG devices for famo.us and Meteor
Introduction
When creating a landing page or when demonstrating an app, there are often some smartphone, tablet or desktop screenshots. This pattern of demonstration could be a bit enhanced if instead of simple screenshots, the real app could be demonstrated. That would be the power of HTML5 sets in motion.The base component
Famo.us has a nice component that could be leverage for that: the ContainerSurface. It is basically a small context that can be clipped. By living in the same space of your main web site, it allows interesting demonstration patterns where you could demonstrate your app. The problem is to display this context exactly on the device that you want to present.By using an adaptive or a responsive SVG, you can extract coordinates of the device screen where you want to present your app. You can then instantiates a ContainerSurface on this same coordinates and put you app as its content.
In this little plugin fview-devices for famous-views, a Meteor package, this is exactly what is done. Here is a little demonstration of it:
You can also play with it in this live demo: fview-devices.
Conclusion
Beyond this little example, some interesting points emerge such as the capability to mix SVG and Famo.us. It paves the way to further enhancements. For instance, CSS Transform and Animation are possible in SVG. Unfortunately, they are not hardware accelerated. Worst, some browsers have very uneasy bugs to circumvent. By extracting portions of SVG and putting them into Famo.us surfaces, you regain hardware acceleration and circumvent issues from wrong implementations. Basically, you open up wider the capability to use SVG to the mobile platforms.It seems to me that a new story of apps using SVG, Famo.us and Meteor is about to begin. Happy coding.
Labels:
CoffeeScript,
Famo.us,
Innovation,
Jade,
Meteor,
Meteor.js,
SVG,
WPO
Un livre de chevet sur le métier WPO (Web Performance Optimization)
Pour tout architecte se respectant, quelques livres viennent marquer votre vie. "High Performance Browser Networking" fait parti de cette catégorie.
Orienté Web, il est aussi utile à toute personne désirant améliorer son infrastructure, comprendre les mécanismes et implications des protocoles utilisés. Il est notamment particulièrement intéressant pour les applications mobiles, natives comme hybrides. Il reste très didactique et comme j'ai l'habitude de le dire, il se lit comme un roman de plage. Bref, un 'must have' de la part d'Ilya Grigorik.
PS : Je vous recommande la lecture de son site ainsi que ses vidéos disponibles sur YouTube.
Read more »
Orienté Web, il est aussi utile à toute personne désirant améliorer son infrastructure, comprendre les mécanismes et implications des protocoles utilisés. Il est notamment particulièrement intéressant pour les applications mobiles, natives comme hybrides. Il reste très didactique et comme j'ai l'habitude de le dire, il se lit comme un roman de plage. Bref, un 'must have' de la part d'Ilya Grigorik.
PS : Je vous recommande la lecture de son site ainsi que ses vidéos disponibles sur YouTube.
150K customers and up on a single UNIX node
Each session whether you allow SocketIO or REST in long polling consumes a file descriptor. UNIXes are configured with a limited number of file descriptors per user. This default configuration limits the number of open sessions for your customer's applications preventing a flexible scalability.
To overcome this issue, UNIXes may be configured to allow a scalability that goes over 150K clients. For a given user and its group (rights allocated for your server), the best approach consists in increasing only this user and group limits.
First, we start by checking the current limitations with the following command:
To increase this really low value for a user 'server' and its associated group, edit your file
Now, you must add a new security policy by adding the following line to your file
Note on NodeJS
The current status of NodeJS limits the heap memory to 1.4 GB per processus. Therefore, vertical scalability is limited to 250 K connections depending on your server's consumptions. There is 2 methods to overcome this issue:
Read more »
To overcome this issue, UNIXes may be configured to allow a scalability that goes over 150K clients. For a given user and its group (rights allocated for your server), the best approach consists in increasing only this user and group limits.
First, we start by checking the current limitations with the following command:
ulimit -aThe line
-n describes the maximum number of opened file descriptor. Usually, this value is set to 1024.To increase this really low value for a user 'server' and its associated group, edit your file
/etc/security/limits.conf with root privileges and add or modify the following values:server soft nofile 150000
server hard nofile 200000
Now, you must add a new security policy by adding the following line to your file
/etc/pam.d/common-session, editing it with root privileges:session required pam_limits.soFor taking this new value into account, a reboot of your server is necessary. Use the
ulimit command to check if your new value has been properly set. Note on NodeJS
The current status of NodeJS limits the heap memory to 1.4 GB per processus. Therefore, vertical scalability is limited to 250 K connections depending on your server's consumptions. There is 2 methods to overcome this issue:
Modern HTML5 assembly line
Just a little infography that I've done for identifying tools and libraries used for developing modern HTML5 apps.
SPDY: Shorten your page load time like no other
SPDY (say 'speedy') is a mature protocol from Google which supersets HTTP 1.1. It is available on NGINX, Apache2, NodeJS and more.
For browsers capable of talking SPDY (Chrome, Opera, Firefox), this protocol provides:
Guy Podjamy, CTO of Akamai, presents a nice introductory video on SPDY. A must watch.
Read more »
For browsers capable of talking SPDY (Chrome, Opera, Firefox), this protocol provides:
- Prevention of the browsers to resend information like user-agent, browser properties. In a way, it creates a session state on a normally stateless protocol.
- Avoidance of the HTTP pipelining mechanisms and an ability to prioritize the sent assets to its clients.
- A push mechanism that can pre-fill the browsers cache just like it was doing some page prefetching. If you prefer to lower the outgoing bandwidth of your servers, there are server hints that informs the browsers of the prefetching they could if they wish it.
Guy Podjamy, CTO of Akamai, presents a nice introductory video on SPDY. A must watch.
Jade within Atom.io: Fasten your HTML and SVG authoring and template debugging
When writing HTML, XML, SVG or templates based on this language, it is cumbersome to open and close tags. Even with a good editor that closes tags for you or a good plugin that write snippet codes, you end up with unreadable and long source files. Jade removes this hassle by providing a simple and elegant code that transpiles to tagged code.
Here's an example of Jade transpiled to HTML:
However, it is sometime handy to seen what your generated code will look like. I've published another Atom.io plugin that preview the generated results with ctrl+alt+j.
The package is available on Atom.io's repository: https://atom.io/packages/jade-compile
And its code source is available on Github: https://github.com/PEM--/jade-compile
Read more »
Here's an example of Jade transpiled to HTML:
However, it is sometime handy to seen what your generated code will look like. I've published another Atom.io plugin that preview the generated results with ctrl+alt+j.
The package is available on Atom.io's repository: https://atom.io/packages/jade-compile
And its code source is available on Github: https://github.com/PEM--/jade-compile
Put your HTML, CSS and JS in a single file using Meteor
It could be a bit cumbersome to switch from your HTML template file to your JS logic to your CSS stylesheets. I consider that the method exposed hereafter isn't tailored for novice users. Still, it can help you understanding how Meteor works.
Actually, the method is quite simple. It all drills down to how the HTML files are generated using Blaze, the reactive UI. During the build process of your app, Meteor builds JS file out of your HTML template file and exposes / sends them to your clients. This method short-circuits the build process. If you write directly your HTML using Blaze, the reactive UI, you remove the HTML file. The second step is to use JS to write your CSS. Here, I use the CSSC package for Meteor.
Here is the results for an equivalent of the default Meteor app.
You could think of it as a small component into a larger app.
And now, here is the code to create this small component. As promised, a single file, in CoffeeScript for brevity:
If you want to test it yourself, here is the set of required commands:
At the beginning, it may look a bit weird. But this could be useful from time to time. Note that you can put some nice additions to this sample. For instance, instead of using the events helpers which will scan you DOM for the button, you could directly affect the click event logic when you are creating the button element. If you are looking for performances on some parts of your app, this could be an interesting technic.
Read more »
Actually, the method is quite simple. It all drills down to how the HTML files are generated using Blaze, the reactive UI. During the build process of your app, Meteor builds JS file out of your HTML template file and exposes / sends them to your clients. This method short-circuits the build process. If you write directly your HTML using Blaze, the reactive UI, you remove the HTML file. The second step is to use JS to write your CSS. Here, I use the CSSC package for Meteor.
Here is the results for an equivalent of the default Meteor app.
You could think of it as a small component into a larger app.
And now, here is the code to create this small component. As promised, a single file, in CoffeeScript for brevity:
# Render the body when Meteor is ready
Meteor.startup Template.body.renderToDocument
# HTML
# ----
# Instantiate a main template
Template['main'] = new Template 'Template.main', ->
# Return a table of DOM elements
[
# A 'p' tag with a reactive variable
HTML.P 'Count ', Blaze.View => Spacebars.mustache @lookup 'count'
# A 'button' tag
HTML.BUTTON '+1'
]
# JS logic
# --------
# Declare a reactive variable
Session.set 'count', 0
# Expose the reactive variable to the template
Template.main.helpers 'count': -> Session.get 'count'
# Handle template events
Template.main.events
'click button': (e,t) ->
e.preventDefault()
Session.set 'count', 1 + Session.get 'count'
# Add the template to the document's body
Template.body.addContent ->
Spacebars.include @lookupTemplate 'main'
# CSS
# ---
# Instantiate a stylesheet
css = new CSSC
# Style the body and the text
css.add 'body',
margin: CSSC.px 20
backgroundColor: CSSC.navy
color: CSSC.aqua
# Style the button
.add 'button',
width: CSSC.px 50
border: "#{CSSC.px 1} #{CSSC.maroon} solid"
borderRadius: CSSC.px 3
backgroundColor: CSSC.red
color: CSSC.yellow
If you want to test it yourself, here is the set of required commands:
# Start by creating a simple app.
meteor create singlefile
cd singlefile
# Remove the Meteor's default app.
rm *
# We are going to focus only on the front.
# Our single file is being placed in the client directory.
mkdir client
# Add the necessary packages.
meteor add coffeescript pierreeric:cssc pierreeric:cssc-colors pierreeric:cssc-normalize
# Create your single file and start editing it.
touch client/main.coffee
At the beginning, it may look a bit weird. But this could be useful from time to time. Note that you can put some nice additions to this sample. For instance, instead of using the events helpers which will scan you DOM for the button, you could directly affect the click event logic when you are creating the button element. If you are looking for performances on some parts of your app, this could be an interesting technic.
Labels:
CoffeeScript,
Innovation,
Meteor,
Meteor.js,
WPO
Location:
Paris, France
The fastest loading screen for Meteor
Introduction
Meteor offers a great way to build web apps at an incomparable speed. It leverages the power of Javascript anywhere. In production, its powerful server side build system named Isobuild transpiles all your HTML files into JS files, thanks to Blaze, and packs them with your JS files. This operation leads to a single JS file loaded by a tiny initial HTML loader that bootstraps your app.Depending on your development strategy, this single JS file can end up very fat. This could seriously annoy your first time users who will wait many seconds before seing something on their screen. Of course, proxying your servers with Gzip or SPDY capable fronts greatly helps lowering this initial loading. Truncating this JS file could also help. Using a multiple domains strategy and CDNs also offer great loading time cuts. Still, on mobile, with a bad network access like GPRS, these several seconds rapidly become a problem. To understand the ins and outs of web performance optimization, WPO, I strongly recommend reading the book High Performance Browser Networking by Ilya Grigorik.
What is this about?
Not to be confused with the great masterpiece fast render from Arunoda Susiripala which is used for fastening the initial data required from your collections, the technic that I expose hereafter tackles the initial page load time, PLT. The first paints on the screen, if you prefer. This first paint comes even before the tiny initial HTML loader is fully loaded by your users's terminal.On a regular Meteor app, while your users connect to your site and till the initial load of the JS file, their browser remains blank. Of course, they could see that something is happening. Almost all browser display at least a progress indicator. But users may not notice it and think that your site is either dead or hosted on a distant other planet. That is just very bad for user acquisition, isn't it? If you want to better understand how this affects user's perceptions as well as your search engine optimization strategy, SEO, Paul Irish has covered this in great details in his incredibly informative talk: Fast enough (check the comments for the slides and the Youtube video). What you need to know is that your PLT will be nice if your initial screen painting is under 14k. That seems like an impossible goal to achieve with an out-of-the-box Meteor app with an average weight of ~50k of compressed initial JS file.
But Meteor is far from being a classic website approach and is definitely not a low end build tool. You can use the raw power of its Isobuild to ask your servers for an injection of your initial screen content directly within the tiny initial HTML loader. It is the key to unlock the 14k barrier.
Performing the injection
This could be a bit scary for the majority of Meteor devs. But once again, Arunoda has you well covered. By using another great masterpiece from Arunoda and Gadi Cohen, this injection process is a no brainer: inject initial. Let us jump in the code.In your app, installing inject initial is the one step classical stance:
meteor add meteorhacks:inject-initialFor the sake of brevity, the codes hereafter are in CoffeeScript.
In your server code, you can perform the initial injection. Hereafter, I'm just putting a little CSS spinner. Nothing fancy.
/server/startup.coffee
Inject.rawHead 'loader-style',Here we have somewhat altered, the DOM structure of our app. Indeed, we have just created a body while the head of your your initial HTML loader wasn't even finished to get build. Is that a big problem? No. Your server will carry on filling the rest of your app in the body section that you have created (the styles, the scripts, ...).
# Force the initial scale for Android and iOS as our spinner may be
# distorted by their default viewport values.
'<meta name="viewport" content="width=device-width,maximum-scale=1,' +
'initial-scale=1,user-scalable=no">' +
# The loading spinner needs some theming.
'<style>' +
'html{background-color: #36342e;}' +
'body{color:#ddd;overflow:hidden;width:100%;}' +
'.spinner {' +
'bottom:0;height:80px;left:0;margin:auto;position:absolute;' +
'top:0;right:0;width:80px;' +
'-webkit-animation: rotation .6s infinite linear;' +
'animation: rotation .6s infinite linear;' +
'border-left:6px solid rgba(255,194,0,.20);' +
'border-right:6px solid rgba(255,194,0,.20);' +
'border-bottom:6px solid rgba(255,194,0,.20);' +
'border-top:6px solid rgba(255,194,0,.9);' +
'border-radius:100%;' +
'}' +
'@-webkit-keyframes rotation {' +
'from {-webkit-transform: rotate(0deg);}' +
'to {-webkit-transform: rotate(359deg);}' +
'}' +
'@-moz-keyframes rotation {' +
'from {-moz-transform: rotate(0deg);}' +
'to {-moz-transform: rotate(359deg);}' +
'}' +
'@-o-keyframes rotation {' +
'from {-o-transform: rotate(0deg);}' +
'to {-o-transform: rotate(359deg);}' +
'}' +
'@keyframes rotation {' +
'from {transform: rotate(0deg);}' +
'to {transform: rotate(359deg);}' +
'}' +
'</style>'
# The loading spinner is a CSS animation.
# /!\ WARNING: The trick is to create a fake body by injecting data
# in the HTML's head as Meteor is requesting JS file in a blocking
# fashion and mobile only allow 1 HTTP request at a time on a GPRS network.
Inject.rawHead 'loader-body2', '<body><div class="spinner"></div></body>'
At this point, you could tell me: "But wait? There is now a title and meta tags in the body of my app. That's just a disgusting code.". You are right. But the browsers are really not impacted by this. I could reply back: "Who care?". But, indeed, I care. Simply because one of the biggest interest of web technology is that all your codes are readable. It is important to let other developers having the possibility to understand how stuff works. It is part of the learning legacy that we owe to the web. So let us put things in the correct order.
Cleaning our loaded codes is done directly on the client side. We do that once everything is loaded. No hurry as it has no impact except a good readability of our DOM structure.
/client/startup.coffee
Meteor.startup ->That's it. Nice and clean.
# Reshape DOM: put back title and meta elements in the head.
# style and script tags can leave in the body tag.
$head = $ 'head'
for tag in ['meta', 'title']
$tags = $ tag
$head.append $tags.clone()
$tags.remove()
Testing it
There are several ways of testing these results and their behavior. On Mac, I use Network link conditionner, a handy tool provided by Apple. It allows you to modify the behavior of you TCP stack and use GPRS, 3G, ... profiles. Very neat when you are testing hybrid or native apps.If you are testing full web apps, I strongly recommend using Chrome DevTools. The mobile emulator as a special feature allowing to change the network throttling.
Some constraints you need to be aware of
When your initial HTML loader and your initial JS file are being loaded, the JS engine and the SVG rendering engine are paused. I've always been annoyed by this browser behavior but we have to live with it. Thus, you can't put JS loaders or SVG animated loaders. You should favor CSS loader and choose the one that will be the less CPU intensive. Here, you should favor CSS3 animated loader which are animated by the GPU as the CPU will be intensively interpreting what it is finishing pumping from you servers.A side note to finish this little article. This technic is not here to bypass the necessary work of making your app as lightweight as possible. It is still a good practice to ensure that your app will avoid consuming the data subscription of your users ;-)
Location:
Paris, France
PageSpeed: Turbo ON for your sites - The Google I/O presentation from Ilya Grigorik
PageSpeed comes in two flavors : a Chrome extension, an Apache module and a NGINX module.
The first one provides you with a great analysis tool of your current sites. The second does almost all the optimization for you. It is pure voodoo. Google has done a tremendous job. Thanks a lot.
Read more »
The first one provides you with a great analysis tool of your current sites. The second does almost all the optimization for you. It is pure voodoo. Google has done a tremendous job. Thanks a lot.
Monday, October 5, 2015
CSS color manipulation and normalize in CoffeeScript
Following my former article Create your CSS styles in CoffeeScript for Meteor, I've updated the CSSC packages to Meteor 1.0.0 and add some new features and plugins. You can now add multiple rules in one call and calls are chainable:
Read more »
if Meteor.isClientA new plugin allows to create the same rules as Normalize.css: CSSC-Normalize. Just add it classically:
Meteor.startup ->
@maincss = new CSSC
@maincss
.add 'html',
backgroundColor: CSSC.yellow
fontFamily: 'Helvetica Neue, Arial, sans-serif'
.add 'body',
fontSize: CSSC.px 20
.add ['h1', 'h2'],
backgroundColor: CSSC.red
The CSSC-Colors has been updated with color manipulation features:
meteor add pierreeric:cssc-normalize
# You can create basic RGB color from an hex String
c = new CSSC.Clr '#FF4136'
# From an hex string with alpha transparency
c = new CSSC.Clr ['#FF4136', .3]
# From the provided colors
c = new CSSC.Clr CSSC.yellow
# From some RGB value
c = new CSSC.Clr [255, 60, 0]
# From some RGB value with alpha transparency
c = new CSSC.Clr [255, 60, 0, .3]
# From some HSL value
c = new CSSC.Clr ['hsl', .5, 1, .5]
# From some HSL value with alpha transparency
c = new CSSC.Clr ['hsl', .5, 1, .5, .3]
# Once you have chosen your color, whatever the color schemes
# that you use, you can modify its value.
# Lets add some 20% saturation
c.set 's', 1.2 * c.get 's'
# Lets lighten it by 30%
c.set 'l', 1.3 * c.get 'l'
# Lets make less opaque by 10%
c.set 'a', .9 * c.get 'a'
# Now that we are finished with it use as a simple string where you want.
# Through an automatic conversion
String c
# As a regular hex string
c.toString()
# As a CSS rgba value
c.rgba() # rgba(255, 60, 0, .3)
# As a CSS hsl value
c.hsl() # hsl(240, 100%, 50%)
# As a CSS hsla value
c.hsla() # hsl(240, 100%, 50%, .3)
Labels:
CoffeeScript,
Innovation,
Meteor,
Meteor.js,
WPO
Location:
Paris, France
Integrate your responsive images in one line in your HTML: the Clowncar's cookbook
Introduction
This is just a post from a cookbook that I've integrated into grunt-clowncar plugin a few month ago.This technique for handling responsive images without polluting your HTML's code has been first mentioned by Estelle Weyl. It's like an abstract factory pattern for responsive image.
The goal is to create automagically an SVG file (the clowncar) which acts as a container. You just include the SVG file whenever you need responsive images. The SVG files contains all the necessary redirection to all the images and it loads only the appropriate ones.
Here is my original cookbook that I simply repost hereafter.
Preparing the circus
First thing first, we import the necessary tooling.This cookbook has been created using OSX. But there's no hassle doing it with your operating system of choice.With your favorite terminal, hop into an empty directory and create a
package.json file for your project, if it's not already done.npm initWe are using the following directory structure:
.
├── Gruntfile.coffee
├── dist
├── package.json
├── src
│ ├── img
│ │ └── photo001.jpg
│ └── index.jade
└── tmp
With :
Gruntfile.coffee: Our Grunt file in coffee.dist: A directory for our generated web files.tmp: A directory for temporary files (unminified stuff, for instance).src: A directory containing all our source files that need treatment.src/index.jade: The main jade file that generates ourindex.htmlfile.src/img: A directory containing all the image that we are about to clown.
Now, we import our grunt plugins and a some other neat stuff:
npm install --save-dev grunt grunt-clowncar \
grunt-contrib-jade grunt-svgmin grunt-contrib-clean \
grunt-contrib-watch grunt-express grunt-contrib-copy \
grunt-open matchdep
And, if you haven't done it already, install GraphicsMagick system wide. Here's the command on OSX for convenience:
brew install graphicsmagick
OK. Now, we can proceed with the 1st recipe.
Embedded SVG in HTML code
So, we start with our Grunt fileGruntfile.coffee which should look something like:# Grunt tasks
module.exports = (grunt) ->
# Load all plugings from our package.json files
require('matchdep').filterDev('grunt-*').forEach grunt.loadNpmTasks
# Project configuration
grunt.initConfig
# CLOWNCAR
# Here comes the fun part. Your image are going to be clowned!
# Every image stored in 'src/img' produces an SVG file and all
# the resolution required by responsive image depending on the
# screens that you are targeting.
# Hereafter, the sizes matches the ones from the default
# Twitter's Bootstrap CSS framework.
# Feel free to adapt them to the screens that you are targeting.
# All our produced stuff go in the 'tmp' dir as some additional
# and optimizing steps are required for our beloved mobile users.
clowncar:
options: sizes: [1280, 992, 768, 400]
all: files: [{
expand: true
cwd: 'src/img/'
src: ['*.jpg']
dest: 'tmp/'
ext: '.svg'
}]
# Minify the produced SVG (our clown cars).
svgmin:
options: datauri: 'base64'
clowned: files: [{
expand: true
cwd: 'tmp/'
src: ['*.svg']
dest: 'tmp/minified/'
ext: '.min.svg'
}]
# Copy our multi-resolution images (the clowns under the car)
# to our production dir 'dist'.
copy: clowned:
expand: true
cwd: 'tmp/'
src: ['*-*.jpg']
dest: 'dist/'
# Use jade to produce HTML.
jade: compile:
options:
# Minify our produced HTML file automatically.
pretty: false
files: 'dist/index.html': ['src/index.jade']
# Remove everything created so far.
clean: [ 'dist', 'tmp' ]
# Create a custom Express server on the fly.
express: all: options:
port: 9000
hostname: '0.0.0.0'
bases: ['dist/']
livereload: true
# Open a browser when site is ready.
open: all: path: 'http://localhost:<%= express.all.options.port %>'
# Watch every changes in the 'src' dir and fire up the buuild task.
watch:
options:
# Note: Livereload is not set in this task as it's already provided
# by the express server (the grunt task).
livereload: false
all: files: 'src/**', tasks: ['build']
# Build tasks.
grunt.registerTask 'build', ['clowncar', 'svgmin', 'copy', 'jade']
# Default task.
grunt.registerTask 'default', [
'clean', 'copy', 'build', 'express', 'open', 'watch'
]
Pfeww, that was long. But, we've provided you with a real world example with comments. Comments that should be worth reading.
Note that there's no need in minifying our produced image with
grunt-contrib-imagemin. grunt-clowncar does it for you. It uses GraphicsMagick's 'convert & thumbnail' feature that does the job pretty well.So, the produced SVG (the clown car) are in the
tmp/minified dir. On the other hand, the responsive images (the clowns or the reduced JPEGs) are directly provided in dist, the production dir. Let's target these with a neat HTML file written in Jade:- var pageTitle = 'Check the clowns'
!!!5
html
head
title= pageTitle
body
h1= pageTitle
include ../tmp/minified/photo001.min.svg
That's it! A oneliner for every included image.
Now, just hit the
grunt command and watch your image being clowned:grunt
Check the dev tools to see the image downloaded from the server while redimensioning your browser.
Meteor walktrough: Samples from JSConf 2013
Introduction
Meteor is a full stack JS framework: JS is used on the server side as well as on the client side. This allows a code mutualisation between this generally separated world. Meteor really shines in its way of handling this mutualisation. It allows you to specify where your code will be used. It relies on a Node and MongoDB.In October 2013, Emily Stark, one of the core developper behind Meteor, has presented at the Asia JSConf 2013 a nice tutorial. I simply provides hereafter the transformed files in CoffeeScript, Jade and Stylus that will help you out understanding and playing with it while watching the associated video:
Settings
First, you need a running installation of MongoDB and Node. On OSX, it is done using Homebrew:brew install mongodb nodeNow, it is time to import Meteor:
curl https://install.meteor.com/ | shNote: The regular installation through NPM does not import the sample application for the generators. Therefore, I recommend using the regular automated shell script.
Meteor comes with an handy package management named Meteorite and its official repository Atmosphere. In essence, its purpose is to handle all packages that merges the world of the server side, NPM, and the world of the client, Bower. It is installed as regular Node package:
npm install -g meteorite
Preparing the playground
Now create a sample app:mrt create JsConfAsia
cd JsConfAsia
Remove unused package and add some nice other ones:
mrt remove autopublishJust remove the created file, that we are going to recreate:
mrt add meteor-jade
mrt add meteor-coffeescript
mrt add meteor-bootstrap-3
mrt add meteor-stylus
rm JsConfAsia.*
Replacing the files
Now, in order to better follow the nice video, I propose you this set of simple file:JsConfAsia.stylbody
font-family: Helvetica, Arial, sans-serif
p
margin: 0
padding: 0
li
padding-bottom: 5pxJsConfAsia.jade.htmlhead
title JsConfAsia
body
.container
+header
+talksList
template(name='header')
h2 Judge jsconf.asia talks
h3 Be ruthless
template(name='talksList')
ul
each talks
li
p: <strong>#{title}</strong> by #{speaker} (#{votes} votes)
.btn-group.btn-group-sm
button.btn.btn-success.upvote
<span class="glyphicon glyphicon-thumbs-up"></span> +1
button.btn.btn-danger.downvote
<span class="glyphicon glyphicon-thumbs-down"></span> -1JsConfAsia.jade.htmlTalks = new Meteor.Collection 'talks'
Meteor.methods
upvote: (talkId) ->
talk = Talks.findOne talkId
Talks.update talkId, {$set: {votes: talk.votes + 1}}
downvote: (talkId) ->
talk = Talks.findOnedOne talkId
if talk.votes isnt 0
Talks.update talkId, {$set: {votes: talk.votes - 1}}
if Meteor.isServer
Meteor.publish 'talks', ->
Talks.find()
else if Meteor.isClient
Meteor.subscribe 'talks'
Template.talksList.talks = ->
Talks.find {}, {sort: {votes: -1}}
Template.talksList.events
'click .upvote': ->
Meteor.call 'upvote', @_id
'click .downvote': ->
Meteor.call 'downvote', @_id
Adding some sample data into MongoDB
Meteor eases the use of MongoDB shell with this little command:
mrt mongoNow, simply cut and paste the following value:
db.talks.insert({title: "Clone Toy Story in 24h with CSS", speaker: "Lea Verou", votes: 0});
db.talks.insert({title: "Enhance! Enhance!", speaker: "That Adobe guy", votes: 0});
db.talks.insert({title: "Templates: the child of Satan", speaker: "Peter Hunt", votes: 0});
To exit and come back to your shell CLI, hit the classic key stroke: ctrl+c.Execute Meteor
Just execute the basic command:
mrtAnd open your browser of choice on http://localhost:3000.
This should provide the following reactive and multi-users web app in less than 100 lines of codes:
Classy!
Subscribe to:
Posts (Atom)



