Tag: javascript

Skeleton Repo for PHP, JavaScript, and SCSS

Skeleton Repo for PHP, JavaScript, and SCSS

I work on a lot of different projects, and each one is unique in its own way. I often find myself installing packages manually and then configuring them. It seems like I repeat myself quite a bit, but the requirements of each project vary ever so slightly. In an attempt to prevent myself from repeating the same tasks over and over, I’ve started working on a skeleton repo that contains nearly everything I would need.

What I was doing

Most of my projects are built in PHP and augmented with JavaScript and SCSS. Occasionally I’ll make a project solely with JavaScript. So I would have to run the following commands:

  1. composer init
  2. composer require silex\silex illuminate\database
  3. npm init
  4. yarn add webpack babel-core … and many more

Then I would have to do the following:

  • Configure my composer.json to use PSR-4 autoload for my namespace
  • Create my folder structure
  • Create some interfaces, classes, and models
  • Configure webpack to use my folder structure
  • Import my SCSS

Doing all of this over and over is a waste of time.

Creating a skeleton repo

My decision to create a light skeleton repo has saved me time. Since it is light, it is very easy to scale it back to what I need. However, if I need to add more, I can do so easily. It turns out that I’m quite good at creating a skeleton repo since I’ve done it so many times. By carefully planning and using the steps above, I had one created in about a day. I’ve continued to refine it and add more features.

Conclusion

I’m sure there are some very elegant solutions on there that do what I need, but I enjoy creating these solutions for myself. Perhaps I’ll end up using something someone else created, but I hope that I’ll have a greater understanding of what they’ve done.

AMPbin

AMPbin

I’ve been working on a new project called AMPbin. It is a place for everyone to create, edit, save, and share their AMP HTML. If you need to make sure your AMP HTML is valid, then be sure to check it out, because it does that on-the-fly. If something isn’t passing validation and aren’t sure why then you can send the bin to a friend to help you.

You can find the AMPbin code is on GitHub if you would like to see how it works. It’s using Firebase Hosting, Database, and Authentication. Below is a list of some of the technologies I’m using for this project.

  • Gulp
  • Bower
  • Yarn
  • SCSS
  • Skeleton CSS

Mithril may make it on that list, I’ve added it a couple times, but still haven’t used it.

If you would like to contribute, that would be great! Or if you want to use the website, even better! You can submit issues on GitHub. You can also send me an email or join the conversation on gitter.

iframe, localStorage, postMessage

iframe, localStorage, postMessage

I recently needed to pass some data from one domain to the other. Using a server-side language, like PHP, wasn’t an option. The site that needed the data was built using Angular and communicated with an API service. I thought about it for a day or two and considered doing it a few ways.

I decided to put an iframe on the source page and pass the data to the target page using JavaScript. Doing it this way only requires me to change a little bit of the code for the Angular site. Below is some sample code that hasn’t been tested.

Parent page


<iframe src="http://localstorage.fishknee.com" frameborder="0" id="iframe"></iframe>
<button id="send">send data!</button>
<script>
var send = document.getElementById('send');
send.onclick = function() {
	var win = document.getElementById('iframe').contentWindow;
	win.postMessage(JSON.stringify({key: 'levi'}), "*");
}
</script>

Recipient page


<script>
window.onmessage = function(event) {
    console.log('received a message!');
    if(event.origin !== 'http://example.com') {
        console.error('origin is bad');
        return;
    }
    console.log('origin is good!');

    var payload = JSON.parse(event.data);
    localstorage.setItem(payload.key, JSON.stringify(payload.data));
}
</script>

Feel free to email me with any questions you may have.

Actualización rápida – Firebase

Actualización rápida – Firebase

My pal Alex and I are writing a chat app that uses Google’s Firebase products. It’s coming along nicely and we continue to add new features. The more I use the real-time database the more I love it. Their JavaScript library makes it very easy to get started. I’m still getting used to denormalizing the data, but I think I got it.

Allowing users to register and sign-in is also a breeze. We don’t have to worry about our database getting hacked. We probably wouldn’t worry about that anyway, but now we can let Google do the worrying for us.

I hope to make our chat ultra secure! It’ll use a hybrid encryption system that employs AES (symmetric) and RSA (asymmetric). The user’s private RSA key will be encrypted using AES 256. When a user sends a message, they’ll generate a unique encryption passphrase and use it to encrypt the message with AES. The passphrase will then be encrypted using each user’s public RSA key. The recipients can then decrypt the passphrase and then decrypt the message.

CSS, JS, and Gulp

CSS, JS, and Gulp

I recently tried the CSS framework Skeleton. It is a minimal framework, that only provides you with some very basic styles, which is what I like about it. It has a twelve column fluid grid with a max of 960 pixels. It uses the Google font Raleway which is a nice choice for typography. It has styles for buttons, lists, forms, and a few other must-have styles. I also like that it uses normalize.css and not a reset.css.

Other frameworks are bloated and either force you to use their design or you end up with a lot of extra CSS. I’ll continue to look into other CSS frameworks, but for now, I’m happy with Skeleton.

I really enjoy having babel, it allows me to write ES6, and have it transpiled to an older version to work with more browsers. There are a lot of improvements in ES6, but my favorite is the class syntax.

My gulpfile is getting a little long and could probably use some attention. I keep creating new gulpfile’s for each project, but I’m starting to see some commonalities between them, so I hope to create one gulpfile that I can use on multiple projects.

Visit ween.io to see what I’m doing.

Short Post

Short Post

It’s been a little while since I’ve posted anything, so here is a quick update.

Website

I finally pulled the trigger and implemented AMP. All the pages are now Accelerated Mobile Pages. I didn’t have to sacrifice anything, but I also didn’t spend very much time on the design or presentation. I’ll pretend that I was going for a “less is more” approach. Most visitors come from mobile, so they didn’t get to see any of the fancy stuff that was only for the desktops. I hope to post more often, they’ll be a lot shorter, so come back soon.

Programming

I continue to write stuff in PHP, C, JavaScript, and TypeScript. I’ve been slowly learning Angular and I like it. I’ve also been toying around with Firebase a bit more lately. Firebase is great for anyone who doesn’t want to deal with servers. Cloud Functions are really neat and I hope I get some more time to write something cool.

Primes

I might start finding primes again. The math behind it is interesting and educational.

Creating a Game

Creating a Game

Making a basic browser-based game may not be as hard as you think. I suggest that you solve one problem at a time. If you take an object-oriented approach, you combine all of your solutions into a complete game. Taking this approach will make it easier for you to add features later. I started writing this in TypeScript, which was fine, but I switched to writing ES6.

Making the map

I first got the idea from EJS, so I decided to create the map from the graphic on that site. It has some land, some lava, some coins, the sky, and a player. I wrote some HTML/CSS, and it looked okay (which means it was terrible) but fine for what I needed. I ended up redoing the HTML/CSS later, and now it looks good. I was able to redo the HTML since I was using the same concept from the first attempt. If the player is over a coin, he earns a point. If the player is over the lava, he gets hurt.

Playa’s gotta play

I bound the keydown event to a method in my class. This gives it access to all the properties and methods in the class. If the player moves up, it gets his current position and moves it up a little bit. Left, move player left, and so on. The Element.getBoundingClientRect() method is what helped me the most. It allows me to tell if one element sharing the same space as another element. Now the player can earn some coins to take out his girlfriend. The player does need to be careful because there is lava which will take away all the coins.

Sometimes the person controlling the player might intentionally try and go off the screen. We can’t let that happen so we need some checks in place to prevent it. Relying on our friend, Element.getBoundingClientRect(), allows us to prevent the player from going places we don’t see fit. Imagine the player is wearing a shock collar like one a dog may wear. It prevents unexpected moves.

Gravity

At first I thought this was going to be really difficult to accomplish. I haven’t implemented this at the time of writing this post. Here is how it will work:

  • I’ll create a setInterval if the gravity property is true
  • Every X seconds it’ll check if the user is in the air
  • If the user is in the air, the user will be moved down
  • This will repeat while the game is active

I’m pretty sure real life gravity works in a similar way, but I’m not a physics expert.

Conclusion

Some tasks may seem impossible, but they might not be. They might just take more time than you think it’s worth. The more you practice the impossible or difficult, the better you’ll get, and those tasks won’t seem as impossible anymore.

AMP Gist Component

AMP Gist Component

Erwin Mombay wrote an excellent article on creating your first AMP Component.

AMP is a way to build pages for static content that render fast. AMP extensions use the power of custom elements and allows us to create new components to enhance AMP HTML pages.

While at the AMP Conference Eriwin showed us how to create one and that is what we did. We created the usual “Hello World” that was first featured in “The C Programming Language” by Kernighan and Ritchie (K&R). Admittedly it is a pretty boring thing to do, but it helps you grasp the structure and the logic of the app or language. In Erwin’s guide, he shows us how to write tests and validation.

The AMP HTML repo has hundreds of issues open. They are nice enough to label some as GFI (Great First Issues) for people who want to start helping. One of those issues was to create a new component to display GitHub Gist so I asked if I could write it and they graciously accepted.

By writing this component, while it may be very basic, I have become more familiar with how AMP works. I believe that I’ve finished the amp-gist component yesterday. Next, I created my pull request earlier this week and I got some good feedback. And then finally I had to make some changes, but they weren’t very difficult, and I made them. Then when it was reviewed, I had some more changes to make and some were more difficult. They offered to accept my pull request if I made some of the easier changes, but I wanted to try and make the more difficult changes. The way I was creating the iframe wasn’t optimal for performance and gave me some suggestions. So I’ve done some digging, looking, researching, thinking, and a little bit of trial/error. I believe I’ve got the more difficult changes licked. This component no longer qualifies as a GFI, according to the person who reviewed my PR.

It is my opinion, as well as others, that AMP HTML is the future of the mobile web. It could also be the future of a new desktop web. No one, not even Google, knows where this will end up. Even if the piece I’m working on is small; I am still excited to be part of this. I’ve always wanted to contribute to something that people may use on a global scale.

Node.js Package

Node.js Package

Encryption has interested me for as long as I can remember. I’ve been writing a decent amount of JavaScript lately, so I decided to try ricmoo/aes-js. It works really well and does everything I was hoping it would do. Since it does so much, the interface requires a little more knowledge than the average person may have. This is why I decided to write a wrapper for it.

Wrapper

My wrapper, disguise, provides a simpler interface to the aes-js library. I wrote my code in TypeScript and compiled it into JavaScript. It provides two simple methods that accept all the needed parameters to encrypt/decrypt messages. You must pass a password, IV, and a message; these are required to encrypt/decrypt a message.

There are also two static methods that instantiate the class and encrypt/decrypt the message. It currently uses the same IV for every call, but I’ll eventually fix that. So don’t use this for anything important.

Advanced Encryption Standard

The U.S. government uses AES for TOP SECRET information. Or at least they did at one time, I don’t think anyone really knows what they do. There have been side-channel attacks on AES, but in my opinion, those don’t count. An example of a side-channel attack would be watching someone type in their password.

Tests with Mocha

You should always test your code, well maybe not always, but if you want anyone else to use it then you should. I like looking at tests that other people write, because it gives me insight into their thought process. I don’t have much experience writing tests for JavaScript, so I did some peeking at other repositories. So I wrote some basic tests and it passes!

Conclusion

My wrapper simplifies the aes-js library. I can see why people like using JavaScript for the backend and frontend. If I decide to put this package on npm then I’ll link it on the resources page.

TypeScript

TypeScript

TypeScript was created after JavaScript, but TypeScript is the parent of JavaScript. It is a little confusing, but it is similar to the what family members do in Kentucky, date their cousins.

TypeScript made JavaScript fun again (and better?). JS has been around for awhile, and it has taken some twists and turns to get to where it is today. JS and PHP have been battle tested and have emerged with a few bruises but have been victorious.

Anders Hejlsberg at Microsoft is a pretty smart dude. He was the lead architect for the team creating C#. He was also a core developer on the TypeScript project. I really like it for the fact that TypeScript adds optional class based object oriented programming to JavaScript.

There is also something called jQuery, and you’ve probably heard of it. It is a nice JavaScript library and one that I use frequently. It is rather simple to use and can speed up development time, but it can also be slower than “vanilla” JavaScript. jQuery is also extensively tested across the popular browsers, which is important.

Benefits

  • Object Oriented
  • ES6 (ECMAScript 6) support
  • Type-Checking
  • Client-side or Server-side apps
  • And more

Example

Below is some TypeScript that allows you to hide/show a specified element by a selector. TypeScript is then compiled into plain JavaScript. You can even change the compile options target to ES6.

TypeScript input

 

JavaScript output

 

Usage

 

jQuery Equivalent

It is simpler to do the same thing with jQuery, but is it better? The answer to that question is something you will need to decide. With jQuery, all you have to do is reference it in a script tag and then you have a whole bunch of functionality. Since jQuery has been around for awhile, it has been tested and enhanced. This allows you to use it and worry a little less about browser compatibility.

Example

The TypeScript/JavaScript example usage was modeled like the jQuery library. The code below is how you would do the same thing with jQuery.

Conclusion

I ran some tests even though I already knew plain JavaScript would be faster than jQuery. I then found out my tests on jsperf.com weren’t getting saved so I created my own test system. While creating my own test system, I learned a few things that I’ll share in another blog post. I put out a request on the internet for people to run the test for me, and I got a nice response. I didn’t record whether they were on a computer or using their phone. I only recorded the operations per second for each test. As I thought, JavaScript is faster than jQuery.

The test was run a total of 113 times. jQuery averaged 7045.635667 operations per second, and JavaScript averaged 169038.6408 operations per second. JavaScript is roughly 23.99196451 times faster than jQuery according to the results of this test.