Code reading : a PoC of virtual router in less of 100 lines of JavaScript

Foreword



This is all about what the codes does, and how to read and (try to) write about code.
As such, first is the code in all its brutality, then, I am gonna try to help through the code and understand it.



What is a PoC ?



Nowadays : it is PLAIN BULLSHIT.

Normally a PoC is a proof of concept. Which in its own word could have been anything.

However in the context of the craftman ship of software, where the salarymen do actual code, it used to have more precise meaning.

It used to be a way for someone caught having a bug because of a design bug, proposing a new design change, to illustrate it to fellow coders, managers and sysadmin in a way that proved MINIMILASTICALLY that your design ideas where implementable. Minimilastically is important there. If as a coder you are annoyed by let's say a an inconsistent concurrent access to a database you can either decide to enforce concurrency on the database side or design of code side. Both are costly, so you'd rather invovle the minimum teams in the process.

It also implies that no Proof Of Concept without identifying a problem TO SOLVE.



Scratching an itch : self embedded multi route HTML



You see it is important to give context to reading. To be minimalistic to solve a code problem with a new design you have to say which problem it solves befoire commenting the HOW it does it (the code).
And context is broader minimizing dependances in another project. Why ? Because the less line, the less code I do on my non salaryman time, I want it to be über simple. It is my Beruf, not my WORK.
My pride lies in always minimizing, and not caring about the other craftsmen, bosses, or king.

My motto is KISS : Keet it Simpler and Simpler.

I don't like the Keep it Simple, Stupid acronym, I see it as a writer a useless gross attitude towards the reader by adding an unworhty insulting information.

Why would I fucking call you Stupid, dear reader ?

So my point -if you were shocked you made the point- is that you should be nice to your reader, at least as much as you intend to be unnice...

And with this code, I expect a lot of fellow coders being pissed but what you are gonna see.

So I hate useless requirements, dependencies, I am poor, with few stuffs, including time. So my interest as an amateur it to do well and be clean. Why, when I have a dynamic server in flask that does everything I need to serve the pages would I want to merge them in one and do it abusing javascript, the DOM and the limit of support ?

Because, above all, I want one asset, and my concept I want to prove the html side with javascript is a hell of a good concept to get rid of flask.

You see I am also a sysadmin, and having a dynamic web server exposes me to nightmares because a new attack vector came out.

But as a sysadmin I know that a freaking static web page for something that is vanity (yes looking at your logs is vanity most of the time, and else, you are troubleshooting a complex trouble and would like less annoyance of requirements to read the freaking stats) is bullet proof to security risks.

If I have the choice between a good enough solution that works from a crontab generating a stupid HTML page every let's each say 10 minutes, and a dynamic website accurate to the nanosecond using grafana and costing me an arm and exposing me to useless risks for a vanity stuff, I will choose the static web page with a sigh of relief.

That is the itch that scratches me, the minimum solution for showing more than one web page in one.

Spoileur alert I use it in one of my project to build this more complete example. An exemple I invite you to download (save as) and to open the exemple in chromium or firefox as a file, because complexity is increased a lot. And you see how much real code and proof of concepts both differs in a lot of lines but are the exacte same in the technique employed.

Wihtout further ado ...

The expected result



You have two links and when you click on them two different contents are shown AND the URL is expected to change because YOU OBVIOUSLY CLICKED a link, and thus history to work and that if you share the URL everybody has got the same result :

When you click ou route2, you see the content «route 2». Easy peasy. Giving the impression you have more than one page in a single page.

The code



<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<style>
.content { visibility: none }
</style>
<script>
$(document).ready(() => {
    $(".router").each( (i,e) => {
        var query = new URLSearchParams( e.attributes.href.value )
        $(e).addClass("a" + query.get("route"))
    })
    $(".router").click( (e) => {
        e.preventDefault()
        var href=$(e.target)[0].attributes.href
        history.pushState({}, null,  href.value)
        var query = new URLSearchParams( href.value )
        var route = query.get("route");
        ({
            "route1": () => { $(".content").hide(); $("." + route).show() },
            "route2": () => { $(".content").hide(); $("." + route).show() },
        })[route]()
    })
    var query = new URLSearchParams(window.location.search )
    route = query.get("route")
    if (route == undefined ) {
        console.log("default route")
        $(".aroute1").click()
    } else {
        $(".a" + route).click()
    }
    console.log("ready")
})
</script>
<ul>
    <li><a class="router" href=?route=route1>route1</a></li>
    <li><a class="router" href=?route=route2>route2</a></li>
</ul>
<div class='content route1'>route 1</div>
<div class='content route2'>route 2</div>


The how to read the code



The UGLY



So, normally here I have 100% of fully seasoned salarymen raging and drooling, because that's not how you do it, and I contradict myself.

I am contradicting myself in this that I introduced a useless requirements on jquery. I also use a non valid HTML page to show code that must work in very web browser and should be in perfect, valid idiot proof way.

Well, I hear, but I dare say it's the opposite, and I will come back to my reliance on the « quirk » mode very lax interpretation of the DOM later.

A proof of concept should work in all case, isn't it ?

I write the proof of concept trying as a writer to discard useless noise, and I use the indentation to show the 2 important piece of information : the document ready part, and something about route, and 2 element li. I went as far as making sure they were on the same level so that you cannot miss them.
And what I like with jquery is the small terse mode of adressing all elements by complex css selector.

I use the quirk mode of firefox and chromium (sacrificing a lot of users) because I rely on this browsers to add the missing information in a way I am used to.

I also sacrifice w3m Users.

My way of reading/writing code



So indentation matters, you understood.

Brievety matters so that you are not overwhelmed by memory pollution.

You eyes are catching the « ready » normally easily. That's where to begin reading from.

What comes before ?

Me clicking on what seems to be a route ? O_o

Where are you gonna follow then ?

It depends both below and above you have an answer.

Below the 6 lines of the HTML body (where it matters to look with css selector : THERE IS NO element with a class of ".a" + name of a route, so there is dynamic magic involved.

But ... they are contents that are two li related to the name of the route. Nice. Simple. I see what you are gonna do. CSS class name almost used as a comment.
If your bet was at the beginning, you already have the answers : some magic takes all the html elements of class route wich have an href element and create dynmically the class used to click on the element. In which purpose ?

Strange, but, ok, question answered, next.

I hijack and disable the onclick event of all element a of CSS class route.

Hinting that the route and the element a of classe route are the same. It's called semantic CSS :D like using the class content so that you know where the content is even if I don't use it.



Here, first thing first I claim we emulate the a href on click default behaviour which normally is, modify the URL, the history (so back can work) and load the content. When you click on a it fills the history with its incomplete href betting the navigator will fill the blank information. Next.

Then I use the native fonction to get the GET paremeter of the URL to unveil the content pointed at in my own href (introspection is better than being explicit).

Then, I put ";", and "()" to avoid syntax errors due to also I rely on a non conservative quirky javascript that is making the code look inconsistent.

And then instead of using a switch case structure I dislike I use a good old dispatch table based on dict. I emulate the on load event of executing javascript when a page is called. Next. But before ...

Some say it is snobism, some say it is geeky, most say stupid (and worse) and finally it is not the way I am used to see it done.

Why don't you respect your readers and write in a clear usual VERBOSE way. And in javsacript we call it an object not a dict, dict is coming from python .... bla bla

I keep it intentionnally short to mean : DONT READ IT. so people just shudder and pass their eyes somewhere else, and yes I am a noob in languages and geek jargon and I don't care, because what I love is to show something that can work, I know nothing of the name of everything because, well I prefer spending less of my precious spare time of assumed noob in JS to code in python or bash. I like your language when I can solve problems elsewhere by adding 20 lines of your vanilla (or almost) to make magic. It maybe obvious to you seasoned developers on how to do it. If it was an easy knowledge, believe me, I would have copy pasted it from stack overflow and not TOUCHED javascript. But I had the intuition it was doable, so I tried and yes, I must admit, javascript is sometimes also pleasant to work with.

I know it is perturbing for the grammar nazis of the one best way that confuses the form of the code without it's intentions when it is about respecting norms of clericals. But, when WE human beings are CODING by hand, what matters maybe to offer a visual help by removing useless semi colons, double quotes (like in my html), NOISE.

Tersity matters in a proof of concept, and you may want to convey what should be clear by sometimes using obfuscated shortest code where it doesn't matter.

Stack overflow greatest answers have all proof of concept made in an extremely terse writing. I love stackoverflow way more than stuff like ChatGPT, because people works their ass off doing non « business code », but minimalistic, at the point I stole the use of quirk mode in PoC from some of my read of stack overflow answers. Sometime the best trick is the code not being syntaxically correct.

So basically when you click on a a element ... it calls a function named route2 or route1 that hides everyhing but element with the CSS selector of the route.

Repeating the function is also made for the reader that calling the fonction doesn't matter, it's what the function does (so if nothing different than what is in the function : DONT USE A DISPATCH TABLE IF YOU DON'T NEED IT IT'S OVERKILL.

In my final needs I knew I needed to embedd different path of JS execution per page. To replace scriptsections. And that's it's also an expected behaviour of loading a page : loading the javascript in it if required. So for my selfish needs ; it matters.


Now that we finished the onclick event of the links respecting the moral contract of the original element, let's look at the remaining piece of this small puzzle : we parse the location of the current page in the address bar for the query to see if there is a route keyword in the asked window location.

Yep, we have the information, there, why not pick it ?

If no route is given in the route= GET parameter, I pick up any route as the default route. Since, you want to route, I guess, there is at least one route, so I pick up 0 by lazyness.

And then I click on WUT ? 0_o

Ah I remember ... the class dynimcally tagged with the css column ".a" + route by creating « an introspection » between the a.href HTML and the link that clicked it. Putting the same information of the route clicked in the DOM this time.

This double bijection being the minimum base of this great con, for minimal virtual routing is to create and idclass in the DOM from which I can go biredctionnaly with the route name in JS and maybe in the addressbar ^^



And that's finished. When I see that this was seriously given me as a must have framework of Javascript needed on top of react, I get angry sometimes.

So, because coding is sometimes a way of mocking, I do have some violence directed towards some of my fellow coders who are trying to impress me with framework for doing excatly this.

My code is terse, in a brooken insulting way for a lot of those whose job is at writing fucking uselessly bloated web pages that are killing kittens by the thousands because of the global warming it generates in useless stuffs dedicated to vanity.

This code reflect the vanity of doing as much as looking at your stats. And I embrace the critic I give to the others.

I spent hours on an internet that does not read me to make a point to someone that does exists only in my fantasies, and will never read me.



Vanity, all is vanity : stats, code, texts, HTML, javascript and all. But, I like it :D

No comments: