Tag Archives: javascript

Just let TypeScript do its thing

It is a well known fact that compile-time errors during development are easier and cheaper to catch than runtime ones in production. Unfortunately people keep forgetting that simple fact. Let me tell you a little story about AWS Lambda hiccup, and how it could easily be avoided.

A developer wrote a simple Lambda function in TypeScript that would receive a parameter of the following type:

interface Notification {
    slack?: {
        notify: boolean
    };
    github?: {
        notify: boolean
    };
}

The logic is simple – if slack.notify is true – send slack notification. If github.notify is true – send github commit status notification. The function deployed without issues, and it does send slack notifications. There is one problem: often it would send the same slack notification 3 times in a row. Continue reading →

Override private methods in TypeScript

First things first: a word of caution – do this only if you absolutely have to. TypeScript has these checks for a reason, and probably in 99% of the cases you should respect and abide these restrictions. But if your scenario falls within the 1% where you must in a subclass override a private method of a superclass – this post shows a way to do this.

Let’s say we have a class that defines a generic starship, and what happens to it when it’s hit by a weapon:

type Hit = 'phaser' | 'antimatter spread' | 'photon torpedo'
 
class Starship {
    private totalDamage: number;
 
    constructor(private shipName: string) {
        this.totalDamage = 0;
    }
 
    private addDamage(damage: number) {
        this.totalDamage += damage;
    }
 
    public isHitBy(hit: Hit) {
        console.log(`${this.shipName} is hit by ${hit}!`)
 
        switch(hit) {
            case 'phaser':
                this.addDamage(100);
                break;
            case 'antimatter spread':
                this.addDamage(300);
                break;
            case 'photon torpedo':
                this.addDamage(500);
                break
        }
    }
}

You can create your own class of starship based on this generic class, then build a ship of the new class, and simulate it being hit by a weapon: Continue reading →

Reverse values into variables in tmplr

tmplr is a versatile templating tool that lets you quickly create a repository from a template customized for your needs. By running a recipe it can substitute placeholder variables with your own values making the repository truly your own. For example it can update package.json with dynamic values from git context. It can do much more, put for the purpose of this post we will concentrate on literal values in code files.

Let’s say you have a JavaScript code that performs some AWS SDK/CDK actions, and it requires AWS account IDs – for dev and prod deployment. In a regular repo you would define config.js something like this:

const awsAccounts = {
   dev: '1234567890',
   prod: '0987654321'
}

But if we’re building a template repo – we don’t want to hardcode those values. Instead we could use tmplr placeholder variables:

const awsAccounts = {
   dev: '{{ tmplr.dev_account_id }}',
   prod: '{{ tmplr.prod_account_id }}'
}

Save this file as config.tmplr.js – it becomes our template. A user of your template then can create a tmplr recipe: Continue reading →

Easily verify yourself on Mastodon with GitHub

Mastodon unlike Twitter doesn’t have official (or paid, thanks Elon Musk) verification badge for account profile, but it does offer a way to verify yourself – by placing following link tag into HTML of a website/page you own (your blog for example):

<a rel="me" href="https://your.instance/@YourHandle">Mastodon</a>

where “your.instance” and “@YourHandle” are the Mastodon server you use and your profile handle respectfully. But what if you want to verify yourself with your GitHub profile? An ideal place would be something like a README.md file. Unfortunately every link placed into a markdown file automatically gets rel="nofollow", so it’s a no-go. But there is a way to do this. Continue reading →

Writing first Mastodon bot

Over the years I’ve written quite a few Twitter bots. But since Elon Musk took over – the bird site has become unbearable, so I, like many others, migrated to Mastodon. What Mastodon is, and how it operates is a whole another story, but for our intents and purposes it is similar to Twitter: there is a home timeline where posts from people you follow appear, and you can post to the timeline as well.

Back on Twitter I used to have a bot that would tweet one-liners from Pink Floyd lyrics every hour. Follow me along as I recreate it on Mastodon.

First and foremost you have to make sure the Mastodon instance you’re on allows bots. Some do, some don’t – read the server rules to find out. I am using botsin.space instance that is specifically meant to host bots. Continue reading →

Copy/Paste image into an editable DOM element in Chrome

All major browsers allow to paste image directly into a DOM element with contentEditable property set to true. They automatically convert it into IMG element with source pointing to base64 encoded DataURI of the pasted image. That is all browsers, but Chrome. Chrome needs a little help.

In my particular case I need to be able to paste image into an IFRAME with editable body of the content document (for some reason Infragistics WebHtmlEditor ASP.NET control renders itself as this contraption). But the code below applies (with small changes) to any editable DOM element.

To achieve the result we need to perform 3 tasks:

1. Capture image from the clipboard
2. Convert the image to DataURI format
3. Create IMG element with the DataURI source and insert it into the DOM

Take a look at the code below:

if (window.chrome) {
    var elem = document.getElementById("myIframe");
    elem.onload = function () {
        elem.contentWindow.addEventListener(
          "paste", function (event) {
            var me = this;
            var items = (event.clipboardData ||
                event.originalEvent.clipboardData).items;
            var blob = null;
            for (var i = 0; i < items.length; i++) {
                if (items[i].type.indexOf("image") === 0) {
                    blob = items[i].getAsFile();
                }
            }
            if (blob !== null) {
                var reader = new FileReader();
                reader.onload = function (event) {
                    var image = new Image();
                    image.src = event.target.result;
                    image.onload = function () {
                        var range = 
                            me.getSelection().getRangeAt(0);
                        if (range) {
                            range.deleteContents();
                            range.insertNode(image);
                            me.getSelection().removeAllRanges();
                        } else {
                            me.document.body.appendChild(image)
                        }
                    }
                }
                reader.readAsDataURL(blob);
            }
        })
    }
}

Line 1 Checks the browser for chromness (well Edge if you want to pretend to be Chrome – so be it)
Lines 2-3 Grab the IFRAME element and attach onload event handler so we would know when it’s good and ready
Lines 4-8 Attach onpaste event handler and grab clipboard data when the event fires
Lines 10-14 Loop thru clipboard items and if an image is found – read it as blob file
Lines 16-17 Initiate file reader and attach onload event to it so we know when the reading (that begins on line 29) is complete
Lines 18-20 Create a new IMG element, assign DataURI result from file reader as IMG source and attach onload event so we know when the image loading is complete
Lines 21-29 Check if we’re inserting into or replacing any existing data at the target and if so – inserting image into selected range, otherwise simple append it to the target.

And that’s it – with this addition you’re now able to copy/paste images into Chrome in the same way as old respectable browsers do.

Fling a random insult at Trump after every tweet

Ok time to get political. I hate many things that Trump tweets these days and would love to reply to each tweet personally, but have neither time not desire to read his delusions. Fortunately in these modern times robots take many of our jobs. And this looked like a perfect job for a bot. Similarly to the bot described in the previous post it will be IFTTT + Scriptr combo. But this time in reverse, here’s intended flow:

  1. Twitter service at IFTTT detects when @realDonaldTrump tweets
  2. It triggers Maker service that makes HTTP request to Scriptr code
  3. Scriptr code generates random insult and posts a reply to Trump’s tweet

Here’s what IFTTT applet looks like: Continue reading →

Detect IFRAME click from parent page

If you need to detect a click on a Web Page, that’s trivial: just catch Document or Body onclick event and any element on the page you click will bubble the event to your handler.

But if one of those elements is an IFRAME – that won’t work. IFRAMEs contain other pages and their events a contained within their content and don’t bubble up. Luckily there’s a way. Take a look this snippet of jQuery code:

$('IFRAME').on('load', function () {
   $(this).contents().on('click', function () {
      alert('Click Detected!');
   })
})

It attaches handler to IFRAME’s content’s onclick event, but only after IFRAME has already been loaded. Place this code in parent page that contains IFRAMEs and it will work universally across all browsers to detect when IFRAME was clicked.

NOTE: As usual in these scenarios, this works only if parent page and children pages comply with Same Origin Policy.

Developing first Pebble.js app

    

Pebble Smartwatch has offered SDK to develop watchfaces and watchapps in C language for a while now. But most recently they tried something different: Pebble.JS a project that lets you code for Pebble in JavaScript. Unlike native app – JS code runs on your phone, so it’s not as fast, and Bluetooth communication required to display any data, but there’re numerous advantages as well.

To test it I decided to write a simple app that would use basic, but important features of Pebble.JS: displaying of information card (a la Pebble notifcation), using menu and executing an AJAX call to bring information from the Net.

Enter AutoInsult for Pebble – application that is based on autoinsult.com – it generates a random insult based on style you selected.
Continue reading →

Infragistics WebDataMenu: Manual postback from client-side Click event

There’s a a few possible scenarios when you need to manually to initiate server-side Click event of Infragistics WebDataMenu control. For example in client side click event you do some verification/user confirmation and upon positive confirmation (e.g. user clicks YES) – server-side Click event should kick in.

In a normal flow of event you can use set_cancel(bool) method to allow/disallow natural menu postback e.g.

function Menu_ItemClick(sender, eventArgs) {

   if (confirm('Are you sure?'))
       eventArgs.set_cancel(false)
   else
       eventArgs.set_cancel(true)

}

This works because this dialog stops code execution waiting for the user input. But what if you use something like jQueryUI dialog that relies on callback functions to get user feedback? In this case execution of the code continues immediately so you have to cancel postback right away and instead in the callback of the dialog initiate manual postback e.g

function Menu_ItemClick(sender, eventArgs) {

   $("#dialog").dialog({
      resizable: false,
      height:140,
      modal: true,
      buttons: {
        "Yes": function() {
          $(this).dialog("close");
          __doPostBack(sender.get_id(), 'ItemClick' + eventArgs._getPostArgs());
        },
        "No": function() {
          $(this).dialog("close");
        }
      }
   });  

   eventArgs.set_cancel(true)

}

The example above initiates modal confirmation jQuery UI dialog and immediately cancels menu postback (Line 18). Later if user clicks “Yes” button – dialog is closed and manual menu postback is initiated (Line 10) – it passes menu ID and correct postback argruments which result in server-side Click event of menu control. If user clicks “No” – dialog is closed and nothing else happens.