A Sass Module Syntax

Complex CSS projects became way more elegant since the availability of pre processors.  Nevertheless some stuff always bugged me. We define variables on a global scope inside some project-wide _variables.scss file and include those everywhere. References are scattered everywhere. If you ever tried to comprehend a 2000+ line, not that well documented, non-bem scss file, nested up to 9 levels you’ll know.

Lets modularize our Sass to make it more reusable and easier to understand.

Before we start, please take a look at some best practices and style guides that’ll enable you to write more beautiful sass. Also even if not absolutely necessary for the described approach I’d highly recommend looking into BEM structures. A super nice syntax for that is supported since Sass 3.3. (I’ll use .block__element--modifier here.)

Each of our modules (or blocks) will live inside it’s own file. Ideally we’ll have to write the module name only once inside that file. All variables used inside the module have to be defined by the module itself and must be scoped to it.
Global variables can be passed down to the module. Listing all of them in the beginning acts like some kind of pseudo-constructor feeding data into the module. If the module is adapted to another project chances are only the variable declarations have to be touched.

My first thought was to use Sass’ build in block scope: A variable defined within a block is scoped to that block. (Unless it has a !global flag.)
I went ahead created a block named after our module(.button {}). Next I redeclared all needed variables inside it’s scope ($button-border-width: 4px; $button-background-color: $some-global-color; …). Even though this works I personally do not like that solution. There is no distinction between globals and non-globals. It’s quite easy to accidentally use a global var somewhere inside a module and create an unwanted dependency. Also there is no possibility to store the module name to reuse it and keep things DRY.

My favorite approach is to fake scope. I decided to reserve a global variable for the scope. I went with $this to make it look a little OO. Meaningful names for this (no pun intended) might also be $scope or $module. The variable is set to a map, containing all configurable data. It also has the module name. After all module definitions $this is set to null to clear it. The next module will then reuse $this.

To access the scoped data one could simply use the build in map-get() function. In my opinion it is a little verbose to always call map-get() passing it $this and the desired data-key. Therefore I created a little helper function: this($key) is as simple as it gets. It always map-get()‘s the key from the $this map.

A reference to scoped data inside a module then looks like this:
color: this(color);

Sass’ interpolation feature and the fact that were stored the module name in $this allows this selector syntax at our modules root:
.#{this(module)} {

And even comments can be fed with this()' data:
/* #{this(module)} Module */

Let’s take a look at all of that put together.

// layout.scss
@function this($key) {
 	@return map-get($this, $key);
}

$some-global-color: hotpink;

// _button.scss
$this: (
	module:						          button,
  
  border-width:               3px,

	background-color:			      white,
	color:						          $some-global-color,

	background-color-hover:	    $some-global-color,
	color-hover:				        white,

	background-color-disabled:	mix(white, lightgrey),
	color-disabled:				      mix($some-global-color, lightgrey),
);

/* #{this(module)} Module */

.#{this(module)} {
	background-color: this(background-color);
	color: this(color);
  display: inline-block;
  padding: 10px 20px;
  border: this(border-width) solid this(color);
  margin: 10px;
  text-transform: uppercase;

  &:not(#{&}--disabled):hover {
		background-color: this(background-color-hover);
		color: this(color-hover);
	}

	&--disabled {
		background-color: this(background-color-disabled);
		color: this(color-disabled);
    border: this(border-width) solid this(color-disabled);
	}
}


// unset this
$this: null;

See the Pen Sass module /w faked scope by Jan Willem Henckel (@farly) on CodePen.

Don’t be afraid to store the same value in different keys. I like to think of the $this declaration as some kind of constructor. The time will come to reuse the button module, call it the fancy-button module and have the hover colors be something completely different. Because there is a map-key for all states all that has to be modified is the $this definition.

I’d love to hear your thoughts about this idea.

A modular approach (pt. 1)

Okay, I admit: I love php. People apparently don’t like hate it but I kinda grew up with that language.

Let’s see what we can do for a change. The recent versions of php gained some beautiful features as well as some syntactic sugar. Let’s build a slim framework, that allows any kind of server application to be fragmented into modules. In this part we will look into how we want our modules to look and feel. Here are some design goals:

  • modularity
  • dependency injection
  • event based

Note: This code requires at least php 5.4.

Each module is a standard php class. A singleton of that class is kept inside the main module loader. The module loader is also the factory for all modules. Everything is sitting nicely inside folders using and is included using a PSR-0 autoloader. Every time a module depends on another module the module loader kicks in and sees if that module instance already exists. If not it init()-ializes it. Either way, the module will be there – ready to use. That process is called dependency injection. To define dependencies we will just have the required modules names as parameters.

Let’s not worry how the module loader would handle dependency injection for now. But what are we going to do if we need parameters for that function? Yes you guessed right: Returning a function!

By returning a function we have the ability to sneak variables into it via the use keyword.  Let’s take this one more step further before we dig into the module loader.

Our module system is supposed to be event based. Here is our convention for events. If an event is triggered the module loader finds all registered modules, that respond to that type of event. A module responds to an event type if it implements an on<EventType>()-method. There is one problem though. Some modules need to do work before other can.

Example: Two modules are registered for the request-event. Authentication and FileSystem. Authentication checks if we are allowed to do what we want to do. FileSystem simply responds with the requested file. Neither of those modules knows what the other one does. Authentication can opt out of the chain simply be throwing an Exception. But what if for some reason the module loader choose to execute FileSystems event handler first?

Event handlers need to be prioritized. And again you guessed correctly: We return an object that has a function and a priority build in. What else?

This is a way simplified implementation of what I currently use inside my Authentication module. (object)[] cast the returned array into an stdClass object. This is simply for looks. The the value of that objects link parameter is a function. And it is the same old function we already used earlier. The priority parameter holds a number. The way this syntax looks made me call the returned object “link object”.

The module loader will execute all available event handlers for all registered modules. It’ll then sort the link objects by priority. Higher priority will execute first. (At the moment no-priority defaults to 100, but I guess this is to be discussed.) Then all link functions are executed in order.

Here is a complete module before we discuss how the module loader works internally in the next post. (Notice: calm is the name of my current application.)

Pew. The init() method is executed as soon as the module is first loaded. It is used because __construct() always returns $this. For dependency injection to work, we need to be able to return our link object. Therefore this additional step is necessary to set up stuff that requires stuff from other modules. Yay!

Part 2 will cover the internal workings of the module loader.

Captain on the bridge

How to fix “Method does not override” when subclassing UIGestureRecognizer

So I tried to create an UI Element in Swift that responds to a specific Gesture. Easy enough let’s look up how that works. The almighty Internet has answers for everything:

Subclass UIGestureRecognizer and override the methods touchesBegan, touchesMoved and touchesEnded.

override func touchesBegan - Method does not override any method from its superclass
Method does not override any method from its superclass – wat?

Okay, I can do that – but wait, what?

It seems like the most recent version of Swift is missing some public declarations for those override-able methods. Probably because access control has just landed for Xcode/Swift the other day. At least Jared Sinclair supports this theory.

He also offers a Solution: Import UIGestureRecognizerSubclass.h in your Bridging-Header. I am new to this, how do you do that? Turns out Xcode creates the Bridging-Header file for you if you create an Objective-C file in your project. Due to some back and forth I learned that it unfortunately only does that once. If you ever deleted the file it will not come back. So how do you create it manually?

  1. Create a new Objective-C Header file and name it <projectName>-Bridging-Header.h
  2. Go to your Project Root and then find “Build Settings”
  3. Scroll all the way down and locate the “Swift Compiler – Code Generation” section
  4. Insert the path to your header file into the “Objective-C Bridging Header” field (Notice that the file might be in the root folder [like mine] or somewhere else)
  5. Set “Install Objective-C Compatibility Header” to true
Objective-C Bridging Header
My Settings for the Bridging Header

Back to the actual solution. Insert this one line into the header file:

https://gist.github.com/552655716a2016b11566

And voila – it works. Suddenly all the desired Methods are avaiable. Well, that was simple.

Hashtag Swift

I recently started developing for iOS using Swift. I did a little project creating a simple tic tac toe app nearly a year ago. Written in Objective-C obviously, because Swift hasn’t been around back then. I remember being stunned by the weirdness the language had to offer; especially coming from a php and javascript background. Let me give you a little example:

https://gist.github.com/1448a92686ee40cb7db6

For people that do not know Objective-C let me guide you through this a litte. This is the implementation of a class method named getFieldTextAtRow:andCol:. It takes to Integers (row and col) and returns an NSString. In the return statement the class method getFieldAtRow:andCol: is called passing the two variables into it. It then asks for the .text property of the returned object. Wow. Calling Methods on an object requires some strange square bracket syntax. Accessing parameters on the other hand is just a plain simple Object.parameter. A dash defines a method. A simple String is a NSString (which is written as @"String") and method name and parameters are entangled. I could go on… but, lets not ramble about dem ol’ days too much: Along comes Swift.

Swift is an innovative new programming language for Cocoa and Cocoa Touch. Writing code is interactive and fun, the syntax is concise yet expressive, and apps run lightning-fast.

Let’s look at the example Method again – this time written in Swift:

https://gist.github.com/d61634ebbf747715e0cd

A String is a string; A method is defined with a func keyword and a method is called just like a function. The name of the method is just getFieldText. Because of backwards compatibility (I guess) parameter names are still in the call. Exception to the rule is the first parameter. Objective-C had it inside the first part of the method name, so Swift “needs” to do that too. func getFieldTextForRow(row: Int, col: Int) -> String would be called like getFieldTextForRow(13, col: 37). The hash symbol in front of the first parameter tells the compiler, that you do want to explicitly name it. So basically that number sign makes stuff more consistent and a little less awkward. I tend to use it all the time.

After all Swift lets you do very cool stuff and in some aspects it is miles ahead of other languages. But some of the “I-need-to-support-all-the-weirdness-of-my-grumpy-father”-aspects just leave me scratching my head.