megacolorboy

Abdush Shakoor's Weblog

Writings, experiments & ideas.

Dark/Light mode with CSS and JavaScript

A simple guide on how to implement a dark/light theme switcher with CSS and JavaScript

It's quite common these days that many websites let their users to decide their preferred color scheme(s). Giving this sort of customizability offers good user experience.

In this article, I'll provide a simple step-by-step guide on how to implement a dark/light theme switcher with HTML, CSS and JavaScript.

Prerequisites

This article assumes that the reader has a basic know-how on HTML, CSS, JavaScript and basic knowledge on using the command-line.

Using CSS variables

I always wanted to implement one for this website too and I thought of making use of CSS variables as I found it to be quite straight forward and I don't have to worry too much about browser support.

Try adding the below CSS to your stylesheet:

    :root {
        --background-color: white;
        --font-color: black;
        --accent-color: red;
        --alt-background-color: black;
        --alt-font-color: white;
        --alt-accent-color: yellow;
    }

    html {
        background-color: var(--background-color);
        color: var(--font-color);
    }

    a {
        color: var(--accent-color);
    }

    html[data-theme="dark"] {
        background-color: var(--alt-background-color);
        color: var(--alt-font-color);
    }

    html[data-theme="dark"] a {
        color: var(--alt-accent-color);
    }
   

The :root selector contains a set of default values and in this case, these are just different colors, kind of like how we initialize variables in other programming languages.

For example, whenever the data-theme attribute is set to dark, the default values will be overidden by the html[data-theme="dark"] CSS rule for the theme to take effect.

Really, it's that simple!

Add some markup

That depends on what you really want to have in your website but for this tutorial, you can just place a simple button somewhere in your navigation bar or anywhere you like:

<button class="themeSwitcher">Dark/Light</button>

Toggle between light and dark themes

Yes, we are getting there and you just have to write a simple logic that checks if whether the current theme is dark or light based on the class used on the <body> element.

$('.themeSwitcher').on('click', function(){
    switch($('body').attr('data-theme')){
        case "dark":
            $('body').attr('data-theme', 'dark');
            break;

        case "light":
        default:
            $('body').attr('data-theme', '');
            break;
    }
});

Save user's preference in their browser

If your button works as expected, good! Now, once you refresh the page, the background would return to it's default mode but that's not what we wanted, right?

But why does it return instead of staying dark? Because your "preference" is not stored in your browser.

Modify your code to store your preferences in your browser:

<script>
$('.themeSwitcher').on('click', function(){
    switch($('body').attr('data-theme')){
        case "dark":
            $('body').attr('data-theme', 'dark');
            localStorage.setItem("theme", "dark");
            break;

        case "light":
        default:
            $('body').attr('data-theme', '');
            localStorage.setItem("theme", "");
            break;
    }
});
</script>

This should work fine but you'll want to avoid the "flickering" issue while changing themes or refreshing the page, in order to do that, make sure that you check the user preference before the page is completely loaded:

<script>
    if(localStorage.theme){
        document.documentElement.setAttribute('data-theme', localStorage.getItem("theme"));
    }
</script>

Conclusion

Well, if you've noticed, I wrote a simple theme switcher for my blog too. Try it out and you can inspect the code to see how it works.

Hope you enjoyed this article!

Stay tuned for more!

One year of writing TIL articles

A little self-reflection on how writing TIL articles has improved my productivity and learning.

Last year, around this time, I was working from home due to the COVID-19 restrictions placed by the UAE Government.

During this time, I noticed that I ran out of ideas for my blog and didn't even get time to maintain it for a long time.

Then, I came across Josh Branchaud's TIL collection, which inspired me to start my own TIL section in my blog. At first, I had the idea of merging it with my main blog but then, I thought of keeping it separate and well, fast-forward to a year now, it's been one of the most productive platforms for writing short articles based on whatever I have learnt or solved.

As for those of you who might not know, TIL a.k.a stands for Today I Learned and what I really liked about it is that there isn't any barrier that stops you from writing a short article and that was the one thing that motivated me to write something on my blog.

Has it helped it you?

Yes, it did help me in two ways.

Professionally, it has motivated me to learn more about my field and share my knowledge about whatever I learned while solving a particular problem or a tip that I found useful. The idea was likened to a personal StackOverflow repository that I would often revisit to refresh my memory.

Personally, it helped me reflect my values as a programmer and made me realize that there's a lot of things to learn out there and it's pretty much endless as there's always something to learn every single day. And yes, it helped me improve my writing abilities too.

Although, this article resides in a what I would call it as a "Technical blog", I guess, this applies to everyone who wants to refresh their writing productivity and help them get started back on the tracks again.

Hope you liked reading this article.

Stay tuned for more!

Understanding SPF, DKIM and DMARC protocols

An insight into the three main email security protocols that protects your email from malicious attackers.

Today, email spam is one of the most common cyberattacks conducted by people with malicious intent intending to steal your passwords and personal credentials, leading users to phishing sites to steal bank account details, identity theft and so on.

Because of this, ISPs and email providers such as Gmail and Office 365 are taking anti-spam measures by enforcing stricter protocols in the type of emails that they receive, so it's good to implement those protocols and ensure that your email gets delivered and not delayed or worse, rejected by the mail servers.

So, what are those protocols?

SPF, DKIM and DMARC are the three main secure protocols used to authenticate your mail server and this will prove the ISPs and other mail service providers that the mail being sent is legitimate and authorized.

What is SPF?

It's an acronym for Sender Policy Framework. SPF is nothing but a DNS TXT record that specifies the server(s) and IP addresses that are allowed to send email from a specific domain.

Assuming you are the sender, just think of sending a postcard to your friend in which you add your address as well, so that your friend knows who the recipient is and he/she would most likely open it because they trust it.

But in technical terms, the actual recipient is not the user but rather the mail server that receives the mail.

Create an SPF record

An SPF record is a very simple string and it can be easily created. However, there are a few parts to it:

  1. Version of SPF used.
  2. IP addresses that are authorized to send emails.
  3. Third party domain(s) that are authorized to send emails.
  4. An ending tag named "all" which tells the receiving server on what policy to apply if the sending server is not a part of the SPF record.

So, let's what does it look like and what each part of it does:

v=spf1 ip4:111.111.111.111 include:example-domain.com -all

v=spf1 states the SPF version being implemented. Currently, there's no any other version at this point. So, it should always stay as this version until another version is released.

ip4:111.111.111.111 is the IP address of the mail server/domain that's authorized to send emails for that domain. You can use multiple IP addresses and can be listed individually like this ip4:111.111.111.111 ip4:222.222.222.222 or through a CIDR like ip4:111.111.111.0/20. If both IPv4 and IPv6 addresses are being used by mail server, make sure that both of those addresses are being listed.

include:example-domain.com is a secondary domain that's authorized to send emails on behalf of the primary mail domain(s) listed. Just like the previous rule above, you can add multiple secondary domains but bear in mind that only a maximum of 10 domains are allowed for any sending domain.

-all is a tag that instructs the receiving server on how to handle messages from a domain that isn't a part of the SPF record. There are some options and they are all dictated by a single character that precedes the all keyword. The options are:

  • -all means hard fail. The receiving server should reject the email if the sender domain is not authorized.
  • ~all means soft fail. The receiving server can flag it as a possible spam if the sender domain is not authorized.
  • +all means authorized. The receiving server allows the email even if the sender domain is not authorized. Now, this is not recommended and please do not use this option.

What is DKIM?

It's an acronym for DomainKeys Identified Mail a.k.a Email signing. Just like SPF, DKIM is also a simple DNS TXT record that tells the receiving server that the mail is certified which allows to build a trust between both the sending and receiving servers.

To handle this trust, DKIM makes uses of an RSA cryptographic algorithm to create a pair of public and private encryption keys. The private key will remain on the server (i.e. the mail server) whereas the public key is placed in your DNS records.

How to create a DKIM record?

Depending on your mail provider, it can be easily generated by tools provided by them and once generated, it can be copy-pasted to the DNS records.

This is how a typical DKIM record would look like:

v=DKIM1; k=rsa;
p=iHeFQ+7rCiSQs3DPjR2eUSZSv4i/Kp+sipRfVH7BGf+SxcwOkX7X8R1RVObMQsFcbIxnrq7Ba2QCf0YZlL9iqJf32V+baDI8IykuDztuoNUF2Kk0pawZkbSPNHYRtLxV2CTOtc+x4eIeSeYptaiu7g7GupekLZ2DE1ODHhuP4I=

Regardless of how it's being generated, this is what each part of the header means:

v=DKIM1 is the DKIM protocol version used.

p= is the Base64 encoded public key generated.

k= is the mechanism used to decode the DKIM signature. The encryption key is usually based on rsa-sha1 or rsa-sha256 signing algorithm.

You can use DMARC analyzer's DKIM checker to check if your DKIM record is valid.

What is DMARC?

It's an acronym for Domain-based Message Authentication, Reporting and Conformance. This protocol is built around SPF and DKIM and it ensures the following:

  1. Verifies that the sender's email is protected by SPF and DKIM protocols.
  2. Instructs the receiving mail server on what to do if the authentication fails.
  3. Provides a way for the receiving server to send a report to the sender about the DMARC evaluation i.e. whether it passed or failed.

If you have come this far in the article, you might have understood why both SPF and DKIM were explained and why they are quite necessary.

How to create a DMARC record?

Once you have both SPF and DKIM records in place, then it's easy to create your DMARC record. There are many sites and I would recommend you to try MXToolbox's DMARC Record Generator.

This is how a DMARC record would look like:

v=DMARC1; p=none; fo=1; rua=mailto:address@example.com;

And here's what each part of the header translates to:

v is the version tag, similar to the SPF record. It should always be DMARC1 in the record.

p is the policy tag. none means to not do anything to the email, quarantine means to flag it as spam and reject means to reject the email.

fo is the tag that lets the receiving servers know that failed messages must be returned to the sender or not. There are four values for this tag:

  • 0: Generate a report if both DKIM and SPF produce a "Pass" result.
  • 1: Generate a report if both DKIM and SPF produce a result other than "Pass".
  • d: Generate a report if the email had failed the DKIM evaluation.
  • s: Generate a report if the email had failed the SPF evaluation.

It's actually recommended to use fo=1 which can help you look for any email delivery issues.

rua tells the receiving server on where to send the aggregate reports. This could provide insights into the health of the email server and can help identify any malicious activities.

There are many optional tags that can be used but these are the tags are most commonly used by default.

Conclusion

With the increase in spam emails, it's good to take such preventive measures to ensure that you are following best practices and doing your part to prevent malicious emails and other security related issues.

If you want to read more about these protocols, you can read the following links recommended below:

Hope you liked reading this article! 😄

Make your own generative pixel art in less than 100 lines of code

By modifying my old random pixel generator, I was able to generate a Space Invaders-esque pixel art.

Try it out!

Refresh the page to generate unique Space Invader-esque patterns as the results are unpredictable!

Generative art is a topic that still fascinates me because of the fact that you can produce something unique by just writing few (sometimes, more) lines of code. Especially, if it's self-generating art that makes use of fixed rules and a slight dash of randomness to produce unique results.

When it comes to writing code, it's quite straightforward. You come up with the rules and constraints and voila, you have something that works. Having said that, setting up rules for generative art can get quite tricky.

You might have read about my previous post about The Game of Life, it contains only four rules and each of them took a part in evolving the system through each generation. With generative systems like that, you can never predict the results as complex patterns will emerge due to it's randomness.

In my view, a combination of predictability and randomness is needed in order to create a good looking generative art.

Why you should explore it?

There could be many reasons, maybe you're bored, curious or passionate to learn something new. Who knows? Open up your editor and try it for yourself.

Exploring the craft of making generative art has allowed me to:

  • Gain different experiences — It allows you to sharpen your algorithms & data structures and maybe even, learn a new technique.
  • Create something visually appealing — A picture is equal to a thousand words.
  • Instant results that makes you feel good — I mean, it's hard to explain but y'know what I mean, right?

Where to start?

Just like any other project, you just need:

  • An inspiration or an idea that you can work on.
  • The right kind of technology to use.

With today's article, I'll be showing you how I built a Space Invader-esque pixel art generator in JavaScript that makes use of the Canvas API.

Building a generator

I'd like to give a shout out to the person who built a twitterbot that generates random sprites using Python's Pillow image library.

I was inspired and I thought of writing it in JavaScript and as you can see above, it did turn out pretty well.

Here's the code for your reference and please read the comments to know how it functions:

// To store any used colors
var colorStack = [];

// Selected color palette
var colors = [
    '#30e3ca',
    '#ff5a5f',
    '#40514e',
    '#e4f9f5',
    '#40514e',
    '#e4f9f5',
    '#e4f9f5',
];

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext('2d');

var width = canvas.width;
var height = canvas.height;

function createSquare(squareDimensions, color, element, spriteDim) {
    const {squareX, squareY, squareWidth, squareHeight} = squareDimensions;

    // If it's a middle element, apply a color
    if (element == parseInt(spriteDim/2)) {
        ctx.fillStyle = color;
        ctx.fillRect(parseInt(squareX), parseInt(squareY), parseInt(squareWidth/squareX)+3, parseInt(squareHeight/squareY)+3);
    }
    // If it's the last element, then use the color that you saved previously
    else if (colorStack.length == element + 1) {
        ctx.fillStyle = colorStack.pop();
        ctx.fillRect(parseInt(squareX), parseInt(squareY), parseInt(squareWidth/squareX)+3, parseInt(squareHeight/squareY)+3);  
    }
    // Else, apply a color and save this for the last element.
    else {
        colorStack.push(color);
        ctx.fillStyle = color;
        ctx.fillRect(parseInt(squareX), parseInt(squareY), parseInt(squareWidth/squareX)+3, parseInt(squareHeight/squareY)+3);      
    }
}

function createInvader(invaderDimensions, spriteDim) { 

    var {posX, posY, invaderWidth, invaderHeight} = invaderDimensions;
    var squareSize = (invaderWidth - posX) / spriteDim;

    var cellPosition = 1;
    var element = 0;

    for(var y=0; y<spriteDim; y++){
        // Starts from the left side of the grid.
        // Think of it as something like this:
        // [-3,-2,-1,0,1,2,3]
        cellPosition *= -1;

        // First element
        element = 0;

        for(var x=0; x<spriteDim; x++) {
            squareX = x * squareSize + posX;
            squareY = y * squareSize + posY;
            squareWidth = squareX + squareSize;
            squareHeight = squareY + squareSize;

            // Pick a random color from the color palette
            var color = colors[Math.floor(Math.random() * colors.length)];

            var squareDimensions = {
                'squareX': squareX+2,
                'squareY':squareY+2,
                'squareWidth':squareWidth,
                'squareHeight':squareHeight,
            };

            // Create a square with a color and desired dimensions.
            createSquare(squareDimensions, color, element, spriteDim);

             // If it's the middle element or the starting element, 
             // then shift it's position to the leftmost.
            if(element == parseInt(spriteDim/2) || element == 0) {
                cellPosition *= -1;
            }

            element += cellPosition;
        }
    }
}

function main() {
    var spriteDim = 7;
    var numberOfInvaders = 15;
    var invadersSize = parseInt(width / numberOfInvaders);
    var padding = parseInt(invadersSize / spriteDim);

    for(var x=0; x<numberOfInvaders; x++) {
        for(var y=0; y<numberOfInvaders; y++) {
            var posX = (x * invadersSize) + padding + 2;
            var posY = (y * invadersSize) + padding + 2;
            var invaderWidth = posX + invadersSize - (padding * 3);
            var invaderHeight = posY + invadersSize - (padding * 3);

            var invaderDimensions = {
                'posX': posX,
                'posY': posY,
                'invaderWidth': invaderWidth,
                'invaderHeight': invaderHeight
            };

            createInvader(invaderDimensions, spriteDim);
        }
    }   
}

main();

Well, I won't say that is a perfect solution but hey, it works and yes, it doesn't take a lot of code to achieve something like this.

Explanation

I'll try my best to explain how this whole thing works.

First, you need to initialize a <canvas> DOM element of the desired width and height. Then in the main() function, you determine the size of each invader by specifying the number of invaders and dividing it with the width of the canvas. These values will then be used to determine the coordinates for each invader.

Second, the function createInvader() follows nearly the same process as the main function except that the coordinates for each pixel is determined by calculating the width of the invader and subtracting it's x position divided by the dimensions of each invader.

Third, as you can see in the function createSquare(), it contains 3 simple rules in which all of them draws a square with a color but with an emphasis that each invader has a symmetrical pattern.

The code looks deceptively simple but achieving this complexity did take a lot of trial and error and a little bit of simple calculus 😂.

Conclusion

Generative art might be something that you may not need to explore but it's quite fun and you may never know what you might be able to produce by combining both code and visuals.

Hope you liked reading this article.

Stay tuned for more! 🤘

Built a new static site generator using Python 3.7

Thought of giving it some new upgrades and finally decided to open-source it.

Since 2019, I always used a custom static site generator for the website. The previous one was written in Python 2.7 but ever since Python decided to sunset it, I decided to rewrite it using Python 3.7.

Unlike the previous one, it's quite flexible and I thought of giving it some new features that would help me maintain it with ease.

The new features I have added are:

  • A neat CLI to build the entire site or certain parts of the website
  • Able to switch between different templates
  • Archive mode
  • Pagination
  • Generates RSS Feeds and JSON files

Why rewrite it again?

Over the past few months, I didn't really maintain my blog and when I visited the old codebase, I realized it wasn't flexible and it didn't have many features and it was slow, too.

Recently, I got new ideas of building different sections for the website and thus, is why I had the motivation to rewrite everything and make it modular and flexible enough to build a powerful yet simple custom static site generator.

Have a look

I have decided to open-source my static site generator on my GitHub repository and I'm having plans of writing a new documentation for it, so that if people are interested, they could contribute or use it for their own personal uses.

Conclusion

If you've been following my blog posts, you may know that I have a knack of displaying JavaScript widgets on some of my previous blog posts. Well, I've decided to rewrite all of those widgets, one-by-one, using ReactJS and hopefully, write more tutorials for each of them.

Hope you liked reading this article.

Do we really need to use pointers?

Did a little digging on whether it's useful to make use of pointers in your application

The topic about pointers isn't new as you're probably introduced to this concept in your first computer science class. I started learning Go and once again, I came across the concept of using Pointers and wanted to finally understand, why are they used and do we really need to use it?

Frankly, I don't really remember using pointers when I was developing web applications in PHP and JavaScript but it was quite a refresher to get back on track again.

Well, what is a pointer?

In it's basic form, a pointer is a variable that contains the memory address of another variable.

For example, you have a variable named x that contains some data, in this case, we'll store an integer:

package main

import "fmt"

func main() {
    x := 10
    fmt.Println(x) // prints 10
}

The code above prints the variable x by referring to it's name. We can do the same using pointers by referring to it's memory address via another variable that points to variable x.

To do this, we must use & operator to get the address and * to return the value stored in the address of variable x like this:

package main

import "fmt"

func main() {
    x := 10
    p := &x
    fmt.Println(x)   // prints 10
    fmt.Println(*p)  // also, prints 10
}

Hmm, that was pretty straight forward.

So, why was it created?

In the modern era, most high-level programming languages are capable of handling memory allocation (like Java or C#), automatically.

But when C was developed, computers weren't as powerful as today but that also meant the programmers must create systems that made use of memory and speed, efficiently. Which is why some tasks do require it when programming low-level embedded systems or microcontrollers.

Why use them?

Whenever you pass a variable to a function, you're basically creating a copy of the variable. But if you're using pointers, you just have to pass the address of the variable and in most cases, a pointer is much smaller in size than the value being pointed at.

It allows you share data and it's quite appropriate when it comes to modifying the data being passed to it.

To some extent, it might seem efficient but there are some tradeoffs, when you're going to talk about optimization.

Do pointers really optimize your application?

I was thinking if pointers are used to optimize applications, I mean, you don't have to duplicate data and it saves memory, so why not?

Turns out that there are a few points that I came across:

  1. Accessing values can use up memory though not so much but it can add up.
  2. Data will be placed on top of heap stack which increases the memory overhead and can be cleaned up the garbage collector.

Most programmers tend to avoid using it in order to make their codebase less complex and reduce the increased work for the garbage collector.

Apart from that, there are some concerns when it comes to the security of the application implying that it could be unsafe when using pointers.

Takeaway

Pointers are useful but don't think of using it, blindly, by assuming that it might give you a boost in performance.

Hope you found this article useful!

Readings

Launched a microblog site

A tiny experiment to see how it could improve my writing productivity.

Ever since I've been working from home (due to COVID19 pandemic), I hardly find time to write any posts on my blog and I felt that it was counter-productive whenever I wanted to start a new one after a long time.

And then, I came across this trend of TIL a.k.a Today I Learned on GitHub and one of my favorite ones is written by Josh Branchaud.

What is this about?

Unlike writing long articles, which takes a lot of time, I believe that by having a microblog and writing short articles could help improve my productivity in writing.

So, I thought of sharing whatever I have learned on a day-to-day basis and accumulate this knowledge in a "repository" where anyone could learn from, thus is why I started this microblog. Besides, as of writing this article, I wrote 25 short articles in a month.

What kind of articles can we expect?

It'd be wonderful to say that I can talk about anything over here but currently, I'm restricting it to Computer Science, Mathematics, Software Engineering and Digital Design.

So what about your main blog?

Oh, I'm not ignoring it! The main blog will be there but now that I have segregated it, it'll allow me to take some time to plan and write content-heavy articles. There'll be more articles coming in a few months time.

Click here to view my microblog and let me know what you think about it! 😄

Stay tuned for more!

Writing a book on how to build ReactJS applications

I'm challenging myself to write a book on how to build simple applications using ReactJS

Over the past few months, I've been spending some of my free time to learn ReactJS and I've got to say, I really like it and got a hang of it after lots of trials and errors.

Just to make it clear, I didn't become a ReactJS expert or something but I figured that writing a book on something that you've learnt would help you understand the material much more deeper.

And since I do believe in it, I decided to challenge myself to write a book on it.

What's the aim of the book?

I aim to cover the fundamentals and concepts of ReactJS using a progressive and an example-driven approach. You know like on how to write reusable UI components, handle user events and interactions and managing state and props of a component.

By the end of this book, the reader will have solid understanding of React's concepts and be able to build cool applications using it.

When's it going to be released?

Honestly, I didn't plan on the size of the book yet but the practical content for it i.e. the actual code and applications are ready. I aim to release it somewhere around late April 2020.

Are you planning to monetize it?

Umm, nope! I believe that knowledge should be accessible for everyone and I plan on making the book open source, so that it can get updated as per the latest changes.

Conclusion

I know it's a short article but I feel like I wanted to challenge myself with a small goal for this year.

Let's see how it goes!