<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by András Szepesházi on Medium]]></title>
        <description><![CDATA[Stories by András Szepesházi on Medium]]></description>
        <link>https://medium.com/@aszepeshazi?source=rss-1f96b723b818------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*QIzRCp6PeiVYXgqU.</url>
            <title>Stories by András Szepesházi on Medium</title>
            <link>https://medium.com/@aszepeshazi?source=rss-1f96b723b818------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 08:02:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aszepeshazi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Printing selected Elements on a web page from JavaScript]]></title>
            <link>https://medium.com/@aszepeshazi/printing-selected-elements-on-a-web-page-from-javascript-a878ac873828?source=rss-1f96b723b818------2</link>
            <guid isPermaLink="false">https://medium.com/p/a878ac873828</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[printing]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[András Szepesházi]]></dc:creator>
            <pubDate>Sun, 10 Mar 2019 16:18:38 GMT</pubDate>
            <atom:updated>2019-03-10T16:18:38.465Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*_JN-V9yaVzgv72QP42E7sQ.jpeg" /></figure><p>Recently I had a task where I had to print specific parts of a web page dynamically, from JavaScript. This certainly does not sound like the most complicated problem in the world. Still, when searching for solutions, I was surprised to find that popular approaches all have caveats that I wasn’t eager to put up with.</p><p>If you would— as I did — search on StackOverflow for “print specific div” or some similar expression, you’d find a dozen questions and a bunch of answers for each. And every high-voted answer will have an equally high-voted comment that goes along the lines of “this does not work in situations when…”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*W3CEW1tduUIXXk73dNOdmA.jpeg" /><figcaption>An SO comment warning about using visibility:none for non-printable blocks</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*A01X4TA9eRz7zXNwlaukow.jpeg" /><figcaption>Another SO comment: a fair warning about replacing the current document body</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*hOW4ZecIACJAOW4llqAkxQ.jpeg" /><figcaption>And another SO comment refers to losing styles when creating a new window element for printing</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*UYv3W_e64PkgwAle4Yurzw.jpeg" /><figcaption>Yet another SO comment about troubles when using a fixed div for printing</figcaption></figure><p>I found two main approaches for the above problem. One is to use media specific stylesheets and / or CSS definitions. The other is to create a new window object, insert the selected node’s html content into this new window’s document body, and call print() on the window.</p><h4>Media specific styles</h4><p>Using media specific stylesheet or media specific css definitions is a clean solution for defining your page’s print view, and does not require any JavaScript. When the user prints the page, all the @media print rules kick in and will define how your page will look like once printed. However, you ‘ll have to know in advance what is the desired print output for each page of your web application. You’ll also need to maintain all those print-specific CSS files and styles along your regular, non-print stylesheets. That is a lot of work. And if you need to have multiple print views of a page, depending on some application state or other condition, you are out of luck — pure CSS will not help you.</p><h4>Insert selected content into a window object</h4><p>This approach has the benefit of being dynamic — you can invoke it with any HTML node content. The simplest (and at the same time the most invasive and troubling) way is to reuse the current window object like this:</p><pre>function printMe(element) {<br>     var printContent = element.innerHTML;<br>     var originalContent = window.document.body.innerHTML;<br>     window.document.body.innerHTML = printContent;<br>     window.print();<br>     window.document.body.innerHTML = originalContent;<br>}</pre><p>But please don’t do this. Wiping out and recreating the innerHTML of the document body will have serious side effects on most pages. For one, all dynamically attached event handlers will be removed from your nodes.</p><p>Other variants create a new window object, then create some body boilerplate, and the printable content gets injected into this body. A better approach, but does not preserve styles — you’ll need to inject the stylesheets from the original document to the new one. And the print window will open as a new tab or window, which is unattractive.</p><p>Not being able to find a satisfactory solution, I rolled my own. It is a tiny JavaScript module (75 lines of source code) with a supplementary CSS of ~10 lines, and works like this.</p><p>It has a single exposed function called PrintElements.print(elements) which expects an array of DOM Elements. If you’d print a single node obtained as var node = document.getElementById(&quot;someId&quot;), you’d call the function as PrintElements.print([node]). If you’d print all nodes matching a certain class name, you’d write var nodes = document.getElementsByClassName(&quot;someClass&quot;), then call the function as PrintElements.print(nodes).</p><p>The function iterates through the passed nodes, and for each node, it traverses up the DOM tree until the BODY element. At each level, including the initial one (which is the to-be-printed node’s level), it attaches a marker class (pe-preserve-print) to the current node. Then attaches another marker class (pe-no-print) to all siblings of the current node, but only if there is no pe-preserve-printclass on them. As a third act, it also attaches another class to preserved ancestor elements pe-preserve-ancestor.</p><p>Let’s say we have the following document tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*Z32YHoZNEgAHCaozilfDIA.png" /><figcaption>DOM tree example borrowed from <a href="http://www.openbookproject.net/tutorials/getdown/css/lesson4.html">http://www.openbookproject.net/tutorials/getdown/css/lesson4.html</a></figcaption></figure><p>Now if we’d like to print only the second and third paragraph of the section element, we’d be calling PrintElements.print([p2Ref, p3Ref]) with those two elements. The function will attach the following classes to the DOM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*jXkuieyjvu8DOAkbayN-hQ.png" /></figure><p>The css rules for these marker classes are dead simple. pe-no-printhas a display:noneproperty, and that’s it. pe-preserve-print has no style definitions, it simply serves as a marker, so we don’t remove any nodes that already have been preserved, when traversing the tree in multiple passes. pe-preserve-ancestor is a bit trickier, and I suspect there is no magic set of rules that will universally fit all websites. You can skip style definitions for this class altogether, and the print result will already be better than with any other methods. But I found that resetting ancestor borders, box-shadows, margin and padding usually brings a bit of extra improvement for the print view. Here is my suggested set of styles for this class.</p><pre>.pe-preserve-ancestor {        <br>  display: block !important;<br>  margin: 0 !important;<br>  padding: 0 !important;<br>  border: none !important;<br>  box-shadow: none !important;    <br>}</pre><p>You should experiment with styles for this class to find the best solution for your specific needs.</p><p>And now, reward time for getting through the article (or just scrolling down quickly). Check out PrintElements in <a href="https://szepeshazi.github.io/print-elements/example/">action</a>. You’ll find four buttons in the top semi-transparent menu that’ll print different sections of the page. Notice how only the requested content will be printed, and how all styles are preserved. Also check out the <a href="https://github.com/szepeshazi/print-elements">source code.</a> Let me know if it works for your specific use cases.</p><p>Enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a878ac873828" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An invasive surgery: upgrading a full-stack Dart application to Dart2 / Angular5]]></title>
            <link>https://medium.com/@aszepeshazi/an-invasive-surgery-upgrading-a-full-stack-dart-application-to-dart2-angular5-9df743359f72?source=rss-1f96b723b818------2</link>
            <guid isPermaLink="false">https://medium.com/p/9df743359f72</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[András Szepesházi]]></dc:creator>
            <pubDate>Wed, 12 Dec 2018 16:56:00 GMT</pubDate>
            <atom:updated>2018-12-13T07:55:29.325Z</atom:updated>
            <content:encoded><![CDATA[<p>At <a href="https://en.skawa.hu/">Skawa Innovation</a> we like to take the road less traveled. Living on the bleeding edge (technology wise) is not uncommon for us. We have been early adopters of many new technologies, <a href="https://www.dartlang.org/">Dart</a> being one of them. <a href="https://www.easyling.com/">Easyling</a>, our website translation platform contains traces of Dart since the beginning of 2014.</p><p>In 2017 we were contracted to create a modern web application helping mothers to get in shape after giving birth. The contract came from the “Gyerünk, anyukám!” — loosely translated “‘C’mon, Mum!” — movement in Hungary. The owners already had a website, but it was not meeting their expectations neither feature-, nor performance-wise. We were given the green light to create a new platform from scratch — just the dream of every development team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*vrmzPOWt_ipztX82HZA1lg.jpeg" /><figcaption>Nóri, founder of the movement with her boys</figcaption></figure><p>Our team was long waiting for an opportunity to utilize Dart both on the front- and the back end. We were aiming for a highly scalable, high-availability solution, and chose the following stack:</p><ol><li>Google Datastore for persistence</li><li>Google App Engine Flexible Environment with Dart runtime for back end</li><li>Angular Dart front end</li></ol><p>Using Dart on both the front- and the back end opened up the possibility for extensive code sharing. We used shared message objects passed between client and server, serialized and deserialized by <a href="https://pub.dartlang.org/packages/dartson">Dartson</a>, which saved us the tedious work of creating serialization boilerplate for each class.</p><p><a href="https://events.dartlang.org/2016/summit/">Google claimed</a> that for some of their internal Dart projects (like AdWords and AdSense) development teams reported up to 100% increase in productivity, solely attributed to Dart language features. I don’t know if we could claim such a productivity boost, but in our project Dart certainly felt <em>easy </em>and <em>natural — </em>it<em> </em>seemed like just the right tool for the job.</p><p>6 moths and ~125k lines of source code later, on January 4, 2018, we went live with the <a href="https://www.gyerunkanyukam.hu/">new application</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*fePoWzGFuQ-7rUuswaxXww.jpeg" /></figure><p>We used Dart 1.24 and Angular 3.1 for our development, and due to tight deadlines couldn’t allocate time to upgrade to Angular 4. After going live, the next couple of months were still dedicated to intense bug fixing and rolling out new features that before launch were pushed back to the backlog. It was early summer when we finally caught our breath, and had enough time to plan for the inevitable foundation layer upgrade.</p><p>Angular 4 was appealing, but a much bigger promise was hovering on the horizon: Dart 2 with its sound type system, and Angular 5 with many sexy features like generic components, better tooling and significantly smaller production code, when compiled JavaScript. Weighting all the pros and cons, we opted to wait for the new versions — the possible benefits were so overwhelming that it seemed simply<em> stupid </em>not to.</p><p>The summer went by, as we checked the status of open issues for both Dart 2 and Angular 5 daily. There were times when there was only a single issue remaining for the 2.0 milestone, but the next day our hopes for a stable version were shattered by newly found critical issues and postponed due dates.</p><p>Finally, late August, both Dart 2.0 and Angular 5.0.0 debuted in the stable channel. We felt like racehorses kept for too long in the stable. We wanted it all, and we wanted it immediately. Our estimation for the total upgrade effort was two weeks. We got the approval. That’s where it all started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*fePoWzGFuQ-7rUuswaxXww.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hhuNjGseKhFK2cdvoRDNow.jpeg" /></figure><h4>The first bumps</h4><p>There are two quick guides on how to execute the upgrade (<a href="https://webdev.dartlang.org/dart-2">here</a> and <a href="https://webdev.dartlang.org/angular/note/migrating-to-v5">here</a>) which gave us a good starting point. Our strategy was roughly along the lines of</p><ol><li>Update dependencies</li><li>Eliminate all errors discovered by static analysis</li><li>Rewrite conceptually deprecated parts (like transformers)</li><li>Create a build</li><li>Pass tests and deploy to a development server through CI</li><li>Do a full regression test</li><li>Roll out</li></ol><p>As a first step, we updated all dependencies, and there came the first surprise. Angular 5 was stable, but a very integral part of Angular, the router, was only at alpha state. This was a clear warning sign that maybe — despite being in the stable channel — the products weren’t so stable after all. But our initial momentum and optimism laughed in the face of experience, and we thought, how bad could it be? We <em>just assumed </em>that the router will soon reach stable, so we went on with the upgrade. It has been four months since, and the router <a href="https://pub.dartlang.org/packages/angular_router">is still alpha</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*kJsDa52D1EVbrG0OlSbWFg.jpeg" /></figure><p>After all the dependency updates and running pub get, the analyzer painted the whole landscape red with errors, which was expected. What was unexpected though, the 5000+ errors and similar amount of warnings, hints and lints crashed the analyzer server quite frequently, which was working against our imminent goal — i.e. to eliminate all static analysis errors.</p><p>There were many easy fixes, and we were grateful for those. Renaming JSON.encode to jsonEncode or Duration.MILLISECONDS_SINCE_EPOCH to Duration.millisecondsSinceEpoch required little thinking but eliminated a bunch of errors, just by doing a search and replace. There is even an <a href="https://pub.dartlang.org/packages/dart2_fix">upgrade tool</a> to do most of these replacements automatically for you (we didn’t use it though). Apart from the search and replace operations, there were other low hanging fruits. Take, for example, the syntax change of int.parse — for input-safe parsing, in Dart 2.0 we would write int.tryParse(value) ?? 0 instead of int.parse(value, onError: () =&gt; 0). These light changes were done quite effortlessly.</p><h4>The heavy lifting</h4><p>A lot more effort went into adjusting our codebase to fundamental, conceptual changes.</p><p><strong>Angular routing </strong>was <a href="https://webdev.dartlang.org/angular/note/router/migration">turned upside down </a>between angular_router package version 1 and 2. We had several dozens of modules with their own sub-routes, router links cross-linking the whole site, and so on. For each module we had to throw away the old, annotation based route configuration, create new classes (for RoutePaths and RouteDefinitions, replace old array based RouterLink configurations. The new router relies on generated factory constructors instead of class references. Router lifecycle callbacks have changed. Classes our code depended on were removed (Instruction and RouteParams, for example).</p><p>This was all anticipated, but we still managed to significantly underestimate this part of the effort. What we did not anticipate was that the <a href="https://www.w3.org/DesignIssues/MatrixURIs.html">matrix url notation</a> that we used for optional parameters in 1.0, just disappeared without any trace from 2.0. Well, not without any trace, because the <a href="https://webdev.dartlang.org/angular/guide/router/3">documentation </a>mentions it, but unfortunately it isn’t implemented. Not cool at all.</p><p>The new <strong>sound type system</strong> also gave us a lot of work on both the front and the back end. We thought that we were type-disciplined enough already with our Dart 1.24 code, but Dart 2 proved us wrong. Later on we ran into many runtime type exceptions, especially when passing around composite objects with nested generic types — we needed to tighten many function signatures and introduce additional template parameters to comply with the new, strict regulations. For some generic typed classes, we started to use the covariant keyword which came very handy allowing certain type overrides.</p><p><strong>Transformers </strong>were gone, the whole concept replaced by the new build system. Again, we knew that when preparing for the upgrade, it just turned out to be a bit more actual work than planned. We had some custom transformers, like inserting version information and Google Tag Manager code snippet into our index.html, and all those had to be re-implemented as build steps.</p><p><strong>Dartson</strong>, that we used for serialization, was also gone. Although there is the official json_serializable <a href="https://pub.dartlang.org/packages/json_serializable">package</a>, we weren’t too keen to adopt it. Mostly because it would have made necessary to introduce build at the back end. And our back end was doing fine without any build steps, simply running on Dart VM, and doing all the serialization magic through the dart:mirrors library. So, in the end, we rolled our own serialization library, that used mirrors on the back end, and code generation on the front.</p><p>Extensive use of <strong>generated code references </strong>in Angular 5 took its toll on us as well. What used to be a simple class reference, became a reference to a generated factory constructor. Imports had to be supplemented with further imports of compiled code. Bootstrapping logic has significantly changed. All this, of course, in favor of better tree-shaking and producing smaller code, but it still can get confusing coming from earlier versions of Angular.</p><p>There were many other parts of our code we had to update — I’ll give you some git statistics at the end of this article. Some changes were straightforward, some less so. For example: do you remember the @Injectable() annotation on classes? Did you know that now it shouldn’t be used any more as it can increase <a href="https://webdev.dartlang.org/angular/note/effective/dependency-injection#annotations">the code-size of your app somewhat dramatically</a>? But do you also know that if you use legacy bootstrapping, then you still have to use the annotation? So many questions. I think we are not the only ones who found the answers by many iterations of trial and error.</p><p>Despite all the above difficulties, the upgrade process was more or less in line with our expectations, except for the, how to put it nicely, perceived immaturity of the whole platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*_OtshuktrzsQENesJu5reQ.jpeg" /></figure><h4>From the rock bottom of my heart</h4><p>As we moved deeper and deeper into the migration, we started to hit <a href="https://github.com/dart-lang/sdk/issues/34288">SDK bugs</a>. And <a href="https://github.com/dart-lang/angular/issues/1605">builder bugs</a>. And <a href="https://github.com/dart-lang/angular_analyzer_plugin/issues/618">analyzer bugs</a>. And <a href="https://github.com/dart-lang/sdk/issues/35341">dart2js bugs</a>.</p><p>All in all, the environment was adding another layer of challenge to an already stretched situation. I think the low point came when we already had a successful local build, but our CI pipeline failed the front end build task about 80% of the cases. I’m not kidding. Most of the times it failed with the very informative dart2js exited due to unknown reason message. But occasionally it managed to finish without errors and produce the build artifacts. I was sitting over the failed pipeline, pressing the job restart button several times, hoping for the version to finally crawl out to our development server, and fantasizing about a different career in either coal mining or human resources.</p><p>As we later tracked down, the underlying issue for the failed builds was that that particular version of dart2js was a memory hog. It simply ate up all the available memory on the 8Gb Kubernetes nodes trying to compile our Angular application. The flaky behavior was due to Kubernetes’ non-deterministic node utilization, leaving sometimes more, sometimes less available memory for the container, which proved to be the breaking point for dart2js in this particular case. We redirected this job to a high memory dedicated VM and suddenly we had a consistently working pipeline.</p><p>We were long past our originally estimated two weeks, but nowhere near going live, when time pressure and feature squeeze closed upon us. We needed to start rolling out new features on top of the old version. That meant an increasingly painful master merge into the migration branch after each release. We were developing new features with the sinking feeling of producing code that was already obsolete, and there wasn’t much we could do about it.</p><p>Looking back, I estimate that features we rolled out during this period had an average of 20% overhead due to the compulsory refactoring for Dart 2 and Angular 5.</p><h4>The light fantastic</h4><p>Somehow during all the new feature developments and merges back to the migration branch, we increasingly got closer to a working version of our upgraded application. We already had a working pipeline, a running development environment, and we kept hunting down and fixing runtime issues at the cost of extra hours we put into the project.</p><p>Meanwhile Dart 2.1 and Angular 5.1 appeared in the stable channel with a lot of bug fixes. So in the middle of our ongoing upgrade, we decided to up the ante and updated our dependencies to Dart 2.1 and Angular 5.1. This, finally, was a good decision. Nothing broke. Some things improved. Confidence grew.</p><p>Soon, we felt we were ready to go live.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*fePoWzGFuQ-7rUuswaxXww.jpeg" /></figure><p>Going into production with our upgraded application was a battle very easy to lose, and almost impossible to win — at least from our customer’s perspective. We didn’t add any feature to this release, so the best thing to happen was a big, fat nothing. We were particularly worried about browser support, as the <a href="https://webdev.dartlang.org/faq">docs</a> stated:</p><blockquote>The production compiler (dart2js) supports Internet Explorer 11 and the last two versions of the following browsers</blockquote><p>and we knew that about 3–4 percentage of our user base didn’t satisfy this requirement. Despite all tension, switching over was a breeze. We caught a couple of early bugs by intensely looking at log files. Some of our users with really old mobile devices complained about broken features. Apart from that, after three months of punishment, we were finally in the clear.</p><h4>Have some fries — here are some takeaways</h4><p>I promised to give you some git statistics. Here is a single line that sums it up quite well, the result of a git diff --shortstat on before and after hashes:</p><blockquote>1078 files changed, 14893 insertions(+), 28304 deletions(-)</blockquote><p>During the upgrade, we’ve touched about 30% of our total codebase, and slimmed down the LOC total with about 10%. Front end was a lot more affected than back end. The reduction in the source code came primarily from utilizing component inheritance. Our admin UI benefited mostly from this — whereas before we had separate admin list components for all entity types, now we had a single generic component with type parameters and a shared template file. Non-minified Javascript code enjoyed about 10% reduction in size.</p><p>We could have mitigated migration risks by upgrading first to Angular 4, and only afterwards to Dart 2 and Angular 5. I don’t think it would have made all the difference, but it would have been certainly be the more conservative and sensible approach. A lesson was learned here.</p><p>Another conclusion we arrived at was that migrating to a major version we only read about in announcements and change logs is risky. We simply didn’t have on hand experience with the new Angular router and all the other cool features. It was hard to refactor code while, for weeks, we were unable to try it, lacking a build. I ended up creating an Angular 5 kitchen sink application where I started to test various new features of the framework. It was a lot easier to refactor our main application once I saw how a particular feature actually works.</p><p>I would say I will be a lot more cautious with our next upgrade. But wait a minute… What?! <a href="https://github.com/dart-lang/angular/blob/master/angular/CHANGELOG.md">Angular 5.2.0</a> just got published? See you later, I’m off to upgrade again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9df743359f72" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>