Author: Lee Winder

Passionate about management and developing leaders. Sometimes I code and sometimes I take photographs. I also complain about our political overlords...

New Host, New Site

I’ve moved, to a site powered by Medium

This site will be around for maybe another 9 months, but after that it’s going to close down and nothing new will be posted here in the mean time.

Hopefully I’ll see you in my new place 🙂

 

Merging CSS Classes for use with ngStyle


For the release of ng-dynamic-dialog v2, I wanted to move away from defining the dialogs look in TypeScript and use standard CSS classes. This would allow the style of the dialog to be defined alongside the rest of a websites style, and make it compatible with CSS preprocessors like LESS and SASS.

What Was I Aiming For

The main goal was to provide in-built CSS classes which define the default look of the dialogs, and then allow the user to override specific attributes as needed.

They would then be able to specify these CSS classes using Ng2DynamicDialogStyle

    // Sets the style of the dialog
    private setDialogStyles() {
 
        // Initialise the style of the dialog
        let dialogStyle = new Ng2DynamicDialogStyle();
 
        dialogStyle.background = 'my-custom-background-style';
        dialogStyle.dialog = 'my-custom-dialog-style';
        dialogStyle.title = 'my-custom-title-style';
 
        dialogStyle.button.general.idle = 'my-custom-button-style';
        dialogStyle.button.general.hover = 'my-custom-button-style:hover';
 
        // Set it
        this.modalDialog.setStyle(dialogStyle);
    }

For example, the in-built style for the background uses the ng2-dynamic-dialog-background class which defines the position, scale and default colour.

.ng2-dynamic-dialog-background {
 
    position: fixed;
 
    left: 0;
    right: 0;
    top: 0;
 
    width: 100%;
    height: 100%;
 
    background: #000000;
    opacity: 0.4;
}

I wanted the user to be able to define their own class as above to change any element they wanted (for example, changing the colour to green…) without having to duplicate what has already been defined in the stock style

.my-custom-background-style {
    background: #009900;
}

Specifying this in Ng2DynamicDialogStyle should then result in the following background style applied to the background

{
    position: fixed;
 
    left: 0;
    right: 0;
    top: 0;
 
    width: 100%;
    height: 100%;
 
    background: #009900;  <-- Everything is the same except for the over-ridden colour
    opacity: 0.4;
}

What Do We Have To Start With

Since I’m passing a style to pre-defined HTML, we have the following options available
* ngClass – allows us to specify a single or set of CSS classes to be applied to the element
* ngStyle – allows us to specify a map of style attributes to be applied to the element

I was initially hopeful that ngClass would actually provide this for me. The documentation _implies_ that the specified classes are applied in order (what else does first, second, third mean if not order?) but that isn’t the case.

All ngClass does is process what is passed, and generate a “class” attribute, meaning it offers nothing above using “class” and as such the ‘order’ is simply lexicographical.

I was hoping maybe Angular 2 could resolve this, but no go.

Since ngStyle allows us to define a map of attributes to be used, I decided this would be the best place to look given the limitations on ngClass.

Accessing and Combining Styles

Finding the Users Style

Note: All code is in TypeScript, but it’s easy enough to follow should it be JavaScript

It’s easy enough to spin through the available styles in a page and find the one the user has specified in Ng2DynamicDialogStyle.

private static getStyleAttributes(styleNameToFind: string) {

  // Spin through all the styles in this document
  for (let i = 0; i < document.styleSheets.length; ++i) {

    // IE uses rules, rather than cssRules
    rulesList = (<any>document.styleSheets[i]).rules || (<any>document.styleSheets[i]).cssRules;

    for (let x = 0; x < rulesList.length; x++) {
      if (rulesList[x].selectorText != null && rulesList[x].selectorText === styleNameToFind) {
        return rulesList[x].style;
      }
    }
  }
}

But there are a few issues that make this a bit more complicated
* FireFox throws a ‘SecurityError’ if the CSS styles are coming from another domain (other browsers simply return null)
* Angular 2 appends additional naming information – [_ngcontent-ccc-n] – on class names if it’s been defined within a component style sheet (I _think_ this is the only time it appends info, there might be more)

As such, it’s slightly more complicated than the above to find what we need
* We need to catch those ‘SecurityError’ exceptions and carry on
* We need to remove the additional naming information from the style names to allow us to compare

Rather than post the entire code, you can view the complete ‘getStyleAttributes’ function on GitHub
* We append the period onto the style class name if it’s not present (it would be to easy for a user to forget to add that)
* We catch the security exception and ignore that sheet if needed (same if it defaults to null)
* We ignore all Angular 2 added naming data, but also make sure we support style information such as :hover

Combining Styles

Once we have the style, we need to combine them to generate a master style where each provided style builds upon the previous one.

It should be simple

for (let attrname in thisStyle) {
  if (thisStyle.hasOwnProperty(attrname)) {
    styleToReturn[attrname] = thisStyle[attrname];
  }
}

But this is cross-browser web development, so dream on!
* Firefox doesn’t put the style attribute data in the derived object, so ‘hasOwnProperty’ pretty much skips anything we’re interested in
* Class information contains attribute information as well as style information, which we need to ignore
* If we can’t call ‘hasOwnProperty’, there is base information we need to ignore as well
* Instances of style classes contain values for _every possible_ attribute, which means the above code will constantly over-ride previous attributes even if the user hasn’t specified them

As such we also need to
* Ignore those non-attribute properties
* Ignore the style property indices
* Check a value has actually been provided

Again, the code to do all this is available on GitHub.

Note that we also cache the styles, at the class level rather than instance level, to avoid the constant need to look up the styles every time we need to combine the user styles.

Passing Through Styles to Combine

Once we have the ability to find and combine specific CSS classes, we need to be able to provide them in the order that they should be applied. Since we pass the styles from the user through the Ng2DynamicDialogStyle, we simply merge them when needed.

// Get the list of styles we will use, in the order that we will apply them
let styleList: string[] = [
    'ng2-dynamic-dialog-modal-button-close',
];
if (this.dialogStyle.buttonClose.style != null && this.dialogStyle.buttonClose.style.length > 0) {
    styleList.push(this.dialogStyle.buttonClose.style);
}

// Get the styles we'll use
let styleToUse: any = StyleSheets.mergeStyles(styleList);

For a more complicated example of building these up, you can see the button style generation function on GitHub.

One other thing to note is that in cases we can, we cache the final merged style to avoid having to merge the styles every time they are requested.

What’s Next

This has been tested and verified on Opera, Safari, Firefox and Chrome though unfortunately I personally have not been able to test it on IE (though it’s looking promising). I’m also expecting some edge cases to pop up in the future, but at the moment it’s running exactly as expected and significantly improves the usability of ng2-dynamic-dialog.

ng2-file-drop and ng2-dynamic-dialog updated to Angular 2.0.0

Google finally finally released the official version of Angular 2 the other day.  As a result I needed to updated both ng2-file-drop and ng2-dynamic-dialog to build against the new version.

Given the hassle of going from RC4 to RC5, I wasn’t optimistic this would be a quick job.

However, other than having to change a single import for ng2-dynamic-dialog (DomSanitizationService is now DomSanitizer), everything was done in under 30 minutes!

Both packages (now sitting at 0.1.0) are available via npm.

 

Angular 2 – Dynamically Injecting Components

Note this also covers upgrading from RC4 to RC5’s ComponentFactoryResolver.

I recently upgraded from RC4 to RC5 and as a result my dynamic component injection module failed due to ComponentResolver being deprecated. Of all the changes between RC4 and RC5, this seems to be the simplest deprecation step, but though I’d document it here.

Generating and Injecting Components

To dynamically inject componets, we need to use ComponentFactoryResolver to create both the factory and the component, as opposed to ComponentResolver and ComponentFactory in RC4.

// These will be your basic imports for component injection
import {Component, ViewContainerRef, ComponentFactoryResolver, ViewChild} from '@angular/core';

ComponentFactoryResolver now does all of the work, which needs to be injected into the componet that will be responsible for doing the injection.

Previously you would have injected a ComponentResolver.

constructor(private resolver: ComponentFactoryResolver) {
}

You then need to identify where in your HTML code the component needs to be injected. You do this by using ViewContainerRef to pull out the element where you want the component to drop.

@Component({
    ...
    template: '<div #dynamicTarget></div>',
    ...
})
export class InjectedWrapperComponent {

    // Component input
    @ViewChild('dynamicTarget', { read: ViewContainerRef })
    private dynamicTarget: any;

    ...
}

Injecting the component is then as simple as creating a ComponentFactory<> using resolveComponentFactory and using that to create a new component in place of the ViewContainerRef.

let componentFactory = this.resolver.resolveComponentFactory(MyDynamicComponent);
this.dynamicTarget.createComponent(componentFactory);

You’ll now have your component beind rendered correctly within your component view.

Sort of, if you’ve put the ‘resolveComponentFactory’ code in the right place.

Injection and Life Cycle Hooks

You’ll need to hook into your components life cycle to correctly create and destroy your injected component – specifically ngOnInit and ngOnDestroy (in RC4 it was OK to use ngAfterViewInit rather than ngOnInit but this is no longer possible).

// We have a few more imports now
import {Component, ComponentRef, ViewContainerRef, ComponentFactoryResolver,
        ViewChild, OnInit, OnDestroy} from '@angular/core';

...

export class InjectedWrapperComponent implements, OnInit, OnDestroy {

    // We'll need to keep track of our injected component to manage it correctly
    private componentReference: ComponentRef;

    ngOnInit() {
        // Create our component now we're initialised
        let componentFactory = this.resolver.resolveComponentFactory(MyDynamicComponent);
        this.componentReference = this.dynamicTarget.createComponent(componentFactory);
    }

    ngOnDestroy() {
        // If we have a component, make sure we destroy it when we lose our owner
        if (this.componentReference) {
            this.componentReference.destroy();
    }
}

And that’s it, you have a component being injected and being rendered within our owners view.

Example Code

The code for the above is available on GitHub, and includes the diff when converting from RC4 to RC5. The GitHub code also shows how to change your dynamically injected component on the fly using ngOnChange to destroy the existing one and inject a new one on demand.

Ng2-dynamic-dialog 0.0.4 Released

It took me a few tries, but ng2-dynamic-dialog 0.0.4 has now been released and is available to be used by any Angular 2 apps out there.

It is currently built against RC4 (RC5 will be in 0.0.5).

The npm documentation and package is here
https://www.npmjs.com/package/ng2-dynamic-dialog

GitHub project is here
https://github.com/leewinder/ng2-dynamic-dialog

While the links above go into more detail, the following pretty sums up what it can do.

null

TypeScript, ‘this’ Scope and JavaScript callbacks

Using ‘setInterval’ caught me out today

export class SetIntervalTest {

    private someNumber: number = 1;

    trigger() {
        setInterval(this.setIntervalCallback, 400);
    }

    private setIntervalCallback() {
        console.log(this.someNumber);
    }
}

Now given any object orientated library, you would expect that after every 400 milliseconds you would get a ‘1’ in the output log. ‘setIntervalCallback’ is a member function of SetIntervalTest, it references ‘this’ which scope out dicate to be the instance of SetIntervalTest we’re running in.

But instead of a simple ‘1’, we get ‘undefined’.

Here’s the generated JavaScript

"use strict";
var SetIntervalTest = (function () {
    function SetIntervalTest() {
        this.someNumber = 1;
    }
    SetIntervalTest.prototype.trigger = function () {
        setInterval(this.setIntervalCallback, 400);
    };
    SetIntervalTest.prototype.setIntervalCallback = function () {
        console.log(this.someNumber);
    };
    return SetIntervalTest;
} ());
exports.SetIntervalTest = SetIntervalTest;
//# sourceMappingURL=interval-test.js.map

Even now, it looks to me like ‘this.someNumber’ should be within the scope of SetIntervalTest, especially as it’s the same structure of ‘SetIntervalTest.prototype.trigger’. But instead it’s pulling ‘this’ in SetIntervalTest.prototype.setIntervalCallback from the windows scope, hence someNumber is undefined.

Since, through the call to setInterval, our object method wasn’t a result of a binded function call, the body of setIntervalCallback is now referring to the windows scope, rather than the objects scope.

Not obvious in any way based on the structure of the TypeScript.

To get the correct behaviour we have to change

setInterval(this.setIntervalCallback, 400);

to

setInterval(() => this.setIntervalCallback(), 400);

This now generates the following JavaScript

"use strict";
var SetIntervalTest = (function () {
    function SetIntervalTest() {
        this.someNumber = 1;
    }
    SetIntervalTest.prototype.trigger = function () {
        var _this = this;
        setInterval(function () { return _this.setIntervalCallback(); }, 400);
    };
    SetIntervalTest.prototype.setIntervalCallback = function () {
        console.log(this.someNumber);
    };
    return SetIntervalTest;
} ());
exports.SetIntervalTest = SetIntervalTest;
//# sourceMappingURL=interval-test.js.map

The only difference is that we’re capturing the scope of this before calling setIntervalCallback which results in this.someNumber being correctly scoped.

To me this is clearly a bug in either the transpiler or the compiler not picking up the issue (either as a warning or an error), as such I’ve raised an issue here
https://github.com/Microsoft/TypeScript/issues/10285

Reply: Where to start in the Games Industry?

I received another interesting email this week asking where to even start in the games industry. I thought this would be interesting to share since it starts by asking what qualifications or roles there might be, not focusing on a specific discipline.

Here’s the original mail

Dear Mr Winder,

My name is […] and I have been interested in games and gaming for around 4 years.
I’m struggling to think on what do with my future. I started streaming on the twitch platform around a month ago and gained around 400+ followers and 1700+ views and I’ve been donated to by various people to support the stream and myself.

I want to get some sort of qualification in the gaming world or some sort of job involving the aspect of gaming.

I’ve also talked to my careers advisers at school and I was passed this email to ask you for some advice on the next step to take, As my advisers didn’t know much about this kind of topic

Yours Truly
[…]

And here’s what I sent back.

Hi […],

I don’t know what your current situation is, but since you mention your school careers advisor, I’m assuming you’re around 13 to 16 years old, which is a great place to start looking at this kind of thing.

The games industry is a big place, with a lot of different opportunities for people like you. I think the first thing to do would be to have a look at the different job roles that tend to exist in the industry, and the Game Career Guide is a good place to start. This will give you a quick overview, and should give you a good idea of what might be the best fit for you if you want to focus your qualifications in a specific direction.

http://www.gamecareerguide.com/features/746/the_.php?print=1

For example, as I entered the industry as a programmer, I had a good Math GCSE (these days a Computing qualification would be excellent as well) followed by a couple of A-Levels in Math and Computing before ending with a degree in Software Engineering. For other areas of game development, those qualifications will be different. For example, an artist will have good art GCSEs, maybe focus on fine art or a technical art degree, where-as a musician would follow a different path.

One thing to note is that designers tend to have a harder time here, there’s rarely (if any) direct qualifications for that role, people tend to show experience in other ways, and their education may be focused more towards culture and media (literature, media critiquing etc.).

But since you mentioned your Twitch stream, maybe game journalism is a more suitable path for you. In that case, I’ll be less help because it’s not an area I particularly focus on. One thing to note here is that if you are looking for information in this field, make sure the information you’re reading is recent. Games journalism is a very dynamic and fast changing area, and is very different today from what it was just a couple of years ago.

But one thing to stress above all of this, is that even with the qualifications it’s experience that matters. And luckily this isn’t a catch-22 situation anymore.

If you’re interested in developing games themselves, start making them now – there is nothing stopping you.

Download Unity (http://unity3d.com/) and start working through the tutorials, start making little games and maybe even get them released on the various app stores out there. If you struggle with one aspect of development (for example, if you can’t draw like me) find a friend who can and get them involved.

If you’re interested in the media side of things, carry on with what you’re doing with your Twitch channel. Start a blog to write about games and start a YouTube channel to discuss them. Self publishing your opinions and thoughts not only gets them out there, but allows you to improve and focus them, building on peoples feedback to make what you create even better.

Doing this alongside any qualifications will significantly improve your chances of being part of the games industry in the future. Hopefully there is something there that fits what you’re looking for. But the biggest takeaway should be – just start creating and take it from there. But even if you don’t have a strong idea about where you want to be now, that’s no big deal. You’ve plenty of time to make up your mind!

Feel free to send this mail onto your Careers Advisors incase they have other people in your situation and are not sure on what advice to give.

Good luck with what you decide to do next