<?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 Yevgen Safronov on Medium]]></title>
        <description><![CDATA[Stories by Yevgen Safronov on Medium]]></description>
        <link>https://medium.com/@sejoker?source=rss-b4e9d06d535c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9V2bvYF6IG8SJ9mYl2Ji8w.jpeg</url>
            <title>Stories by Yevgen Safronov on Medium</title>
            <link>https://medium.com/@sejoker?source=rss-b4e9d06d535c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 18:03:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sejoker/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[Проверка на прочность]]></title>
            <link>https://medium.com/@sejoker/%D0%BF%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D0%BA%D0%B0-%D0%BD%D0%B0-%D0%BF%D1%80%D0%BE%D1%87%D0%BD%D0%BE%D1%81%D1%82%D1%8C-c900551e6eec?source=rss-b4e9d06d535c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c900551e6eec</guid>
            <category><![CDATA[triathlon]]></category>
            <category><![CDATA[triathlon-training]]></category>
            <dc:creator><![CDATA[Yevgen Safronov]]></dc:creator>
            <pubDate>Sun, 28 Apr 2019 19:56:47 GMT</pubDate>
            <atom:updated>2019-04-29T12:29:52.097Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J_ypqDdSdZVOi8nM4mfzDQ.jpeg" /><figcaption>рассвет в Торевьехе</figcaption></figure><p>Не так давно по интернетам прошла до слез уморительная статья <a href="https://ironman43blog.wordpress.com/2017/10/13/%D0%BF%D0%B8%D1%81%D1%8C%D0%BC%D0%BE-%D0%B6%D0%B5%D0%BD%D1%8B-%D1%82%D1%80%D0%B8%D0%B0%D1%82%D0%BB%D0%BE%D0%BD%D0%B8%D1%81%D1%82%D0%B0-%D0%BD%D0%B5-%D0%BC%D0%BE%D0%B5%D0%B9/">“Письмо жены триатлониста”</a>, почитайте. Там классно описаны стадии трансформации триатлона из хобби в стиль жизни. По-моему я таки перешел на новый уровень, не описанный в статье — когда вместо отпуска с женой ты отправляешься на <a href="http://trakhimchyk.com/torrevieja">суровые сборы</a> по триатлону ;). Суровые по нескольких причинам:</p><ul><li>Первый опыт сборов, неизвестно как будет вести себя организм при таких нагрузках</li><li>15 дней ежедневных тренировок (утром и вечером)</li><li>Велотренировки протяженностью 4+ часов по испанским дорогам с ветром и подъемами (дома катал только на станке так как в Лондоне еще было холодно на улице)</li><li>В конце сборов тренировка в виде половины айронмена: 1.5км плавание, 84км вело, 20км бег (из опыта лишь 2 олимпийские дистанции (в 2 раза короче) в прошлом сезоне)</li></ul><p>Полная загрузка организма в первую неделю (24 часов тренировок) привела к тому, что на 8й день ноги просто не хотели крутить педали и ребятам пришлось регулярно меня ждать, но больше 160ватт я выжать из себя не мог.</p><p>Вторая неделя была полегче — организм адаптировался и тренер организовал небольшую подводку к воскресному старту на половинке.</p><p>По старту скажу что вышло очень неплохо. Наделал ошибок, но обошлось без грубых. Финишировал из 5 часов, хотя необходимо сделать скидку на очень быстрое плавание из-за течения, но все равно приятно! Главное, что смог финишировать на новой для себя дистанции. Открытие сезона вышло успешным.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FFgYx1rbGSD9173izOa8iw.jpeg" /></figure><p>Важной составляющей всего тренировочного процесса было исправление проблем в технике плавания, бега и навыков велопоездок в группе. Мой тренер <a href="https://www.facebook.com/trakhimshyk?__tn__=%2CdlC-R-R&amp;eid=ARAVoO_5KxAqvNpB6BLADMoT0tyGDAvutsy-17zXP-v8cWSsTIbhozRC_MmAw_JEqPZGbECBQ68kI8iX&amp;hc_ref=ARR0EVBhEJw9ParCsItr5XOPFLtHSK_hc5y26on3Qmz4JwjIOKayrLhJNllZgZicflc">Алексей Трохимчик</a> смог передать немалый объем своих знаний и опыта за столь сжатый промежуток времени. По-настоящему на новый уровень в плавании помогла выйти <a href="https://ru.wikipedia.org/wiki/%D0%A7%D0%B0%D1%83%D0%BD,_%D0%90%D0%BD%D0%B0%D1%81%D1%82%D0%B0%D1%81%D0%B8%D1%8F_%D0%AD%D0%B4%D1%83%D0%B0%D1%80%D0%B4%D0%BE%D0%B2%D0%BD%D0%B0">Анастасия Кучерук</a>. Подробный анализ наших ошибок и работа над их исправлением добавили легкость и свободу в плавании, а главное уверенность в себе.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Ys0BaEGLCZPY5Zn4UibFA.jpeg" /></figure><p>Впечатления от сборов вышли насыщенными, такие испытания как <a href="https://www.strava.com/activities/2265279374/segments/57205230433">3 подъема на холмик с 20% уклоном</a>, <a href="https://www.strava.com/activities/2262273512">4500м плавания</a>, <a href="https://www.strava.com/activities/2289320061">половинка</a> <a href="https://www.strava.com/activities/2289320348">айрон</a> <a href="https://www.strava.com/activities/2289320161">мена</a> мне глубоко врезались в память.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E6BfErQAt6NzRGgD1_9cWw.jpeg" /></figure><p>В итоге я бы выделил 3 составляющих успешного сбора</p><ul><li>Тренировочная дисциплина (тренерские “не надо жечь спички” емко это выражают)</li><li>Самоотдача и желание выкладываться на полную</li><li>Доверие процессу</li></ul><p>Впереди ждет насыщенный сезон с 2мя основными стартами в олимпийской дистанции. Уверен, проделанный объем работы станет крепким фундаментом в моем спортивном развитии.</p><p>P.S. Спасибо <a href="https://www.facebook.com/scady.abramova?__tn__=%2CdlC-R-R&amp;eid=ARDnRNMp4yATDtqdwLoBC8ghTF2ZmL0M5jmFEU1YI8m8D_Rz5IaK9uNkpkDCDV_3aFdqbgAjAgU1L5Hw&amp;hc_ref=ARR0EVBhEJw9ParCsItr5XOPFLtHSK_hc5y26on3Qmz4JwjIOKayrLhJNllZgZicflc">Skady</a> за вдохновение и рекомендацию тренера! Не вериться, что я выступил на этих же соревнованиях всего год спустя. Помню что читал твои <a href="https://www.facebook.com/scady.abramova/posts/10209576034032721">впечатления о соревнованиях</a> и искренне восхищался.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c900551e6eec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code-splitting with Webpack on the component level]]></title>
            <link>https://medium.com/@sejoker/code-splitting-with-webpack-on-the-component-level-ac50748d80de?source=rss-b4e9d06d535c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac50748d80de</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[code-splitting]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Yevgen Safronov]]></dc:creator>
            <pubDate>Sun, 09 Apr 2017 22:28:54 GMT</pubDate>
            <atom:updated>2017-04-09T22:36:24.540Z</atom:updated>
            <content:encoded><![CDATA[<p>Following based practices of modern Web development we minimize and bundle JS in a single file to the client. As a next step we split vendor and application code into separate bundles to achieve better <a href="https://survivejs.com/webpack/building/bundle-splitting/#the-idea-of-bundle-splitting">client caching</a>. Nevertheless, most of the time we load extra bits of the code that aren’t required for the current page.</p><p>Definition of the code-splitting by <a href="https://medium.com/u/2508e4c7a8ec">Addy Osmani</a>:</p><blockquote>Code-splitting is one answer to the problem of monolithic bundles. It’s the idea that by defining split-points in your code, it can be split into different files that are lazy loaded on demand. This improves startup time and help us get to being interactive sooner.</blockquote><p>I found an excellent introduction into the topic in his article:</p><p><a href="https://medium.com/@addyosmani/progressive-web-apps-with-react-js-part-2-page-load-performance-33b932d97cf2">Progressive Web Apps with React.js: Part 2 — Page Load Performance</a></p><p>I recommend to read the whole series about <a href="https://medium.com/@addyosmani/progressive-web-apps-with-react-js-part-i-introduction-50679aef2b12#.ysn8uhvkq">Progressive Web Apps</a>.</p><p>The application feature set was constantly growing. At that time the size of the JS bundle was about 1.1 MB of minified unzipped code. With the help of <a href="https://github.com/th0r/webpack-bundle-analyzer">Webpack bundle analyzer</a>, I found out that some of bigger libraries like <a href="https://github.com/erikras/redux-form">redux-form</a> and <a href="https://github.com/reactjs/react-modal">react-modal</a> are used on the few pages but loaded everywhere. I decided to explore the possibility of using Webpack code-splitting to minimize the initial size of the JavaScript we load.</p><p>I will describe the idea behind the implementation of code-splitting and learned lessons along the way.</p><h3>Code-splitting by routes</h3><p>The common approach to code-splitting using Webpack and React based application is to utilize<a href="https://webpack.github.io/docs/code-splitting.html"> Webpack&#39;s require.ensure</a> and <a href="https://github.com/reactjs/react-router">React Router</a> <a href="https://github.com/ReactTraining/react-router/blob/master/docs/guides/DynamicRouting.md">dynamic routing</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b6b17aed97fa68cdb2c7134d3295664/href">https://medium.com/media/7b6b17aed97fa68cdb2c7134d3295664/href</a></iframe><p>Using this approach components code will be loaded asynchronously and only for requested routes.</p><p>You will need a polyfill for <em>require.ensure</em> to run SSR (server-side rendering)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e57d7bd50becca968c79acc0624176b5/href">https://medium.com/media/e57d7bd50becca968c79acc0624176b5/href</a></iframe><h3>Code-splitting by component</h3><p>Unfortunately the approach using react-router dynamic routing is not always applicable. This was a case with our application. Although we use react-router, the decision about which React components should be rendered on the page is driven by a modules tree represented in the following structure:</p><pre>{<br> &quot;modules&quot;: {<br>  &quot;content_type&quot;: &quot;page&quot;,<br>  &quot;items&quot;: [{<br>    &quot;content_type&quot;: &quot;section&quot;,<br>    &quot;items&quot;: [{<br>     &quot;content_type&quot;: &quot;block&quot;,<br>     &quot;items&quot;: [],<br>     &quot;content&quot;: {<br>      &quot;size&quot;: 12<br>     },<br>    }],<br>    &quot;content&quot;: {<br>      ...<br>    },<br>    &quot;locale&quot;: &quot;en&quot;<br>   }, {<br>    &quot;content_type&quot;: &quot;carousel&quot;,<br>    &quot;items&quot;: [{<br>      &quot;content_type&quot;: &quot;carousel_item&quot;,<br>      &quot;content&quot;: {<br>        ...<br>      },<br>     },<br>     ...<br>    ],<br>   },<br>   ...<br>   {<br>    &quot;content_type&quot;: &quot;section&quot;,<br>    &quot;items&quot;: [],<br>    &quot;content&quot;: {<br>     ...<br>    },<br>   }<br>  ],<br>  }<br>}</pre><p>Then in our code we have following mapping factory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/068e7aaceec32496729c8adf9872ce80/href">https://medium.com/media/068e7aaceec32496729c8adf9872ce80/href</a></iframe><p>And finally EntryFactory component glues everything together:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65da5eaf61d7aaedbaef94e4e7a21daf/href">https://medium.com/media/65da5eaf61d7aaedbaef94e4e7a21daf/href</a></iframe><p>In the code above, it traverses modules tree and calls render on each component returned from the contentTypes mapping file.</p><p>The initial plan was the following:</p><ul><li>add require.ensure split points inside the contentTypes factory</li><li>EntryFactory will traverse modules structure and initiate necessary requests for the additional code chunks to be loaded from the server.</li><li>Until the code is loaded we will render empty content for some components and rerender when download will be completed</li><li>All possible artifacts due to async loading nature of code chunks will be compensated with SSR payload.</li></ul><p>After some investigation I stick with a simple <a href="https://github.com/capaj/react-async">react-promise</a> component and this changes in the contentTypes factory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a706af8f900e32814b3e39f0810a123/href">https://medium.com/media/9a706af8f900e32814b3e39f0810a123/href</a></iframe><p>For calendar component Webpack will generate separate calendar.js chunk module. We return unresolved promise on the first call to render calendar content type. As soon as the file is downloaded we resolve the promise and cache result in the promises object.</p><p>The changes in the EntryFactory to support promise rendering:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a70f6fcf008b70b20197b6209a8825c/href">https://medium.com/media/4a70f6fcf008b70b20197b6209a8825c/href</a></iframe><p>The open questions:</p><ul><li>current implementation broke server-side rendering</li><li>returning promises from the render function felt wrong</li></ul><p>On the positive side of the things:</p><ul><li>ultimate flexibility with split points, you can group chunk modules whatever you like. In our case, we ended up with 4 additional files each containing from 1 to 10 components.</li><li>code changes touched only 2 files, no code changes in the components itself</li></ul><h3>Fixing SSR</h3><p>After some testing, I found out that <a href="https://facebook.github.io/react/docs/react-dom-server.html#rendertostring">ReactDOMServer.renderToString(c)</a> returned empty markup for any component which required chunk loading.</p><p>Apparently, there is a long-standing open issue on Github devoted to exactly this topic:</p><p><a href="https://github.com/facebook/react/issues/1739">Support asynchronous server rendering (waiting for data before rendering) · Issue #1739 · facebook/react</a></p><p>In summary, you should preload any async data upfront before rendering on the server.</p><p>The quote from the <a href="https://github.com/facebook/react/issues/1739#issuecomment-135123560">core team member</a>:</p><blockquote>We don’t currently support per-component async fetching. We’d like to add it. This issue tracks our progress, though no one is actively working on it and it will take major restructuring so it will be a while.</blockquote><p>So, I wrote a small module which did preloading of all code chunks before rendering components tree:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7984777c867d80577868fee8f777c03/href">https://medium.com/media/d7984777c867d80577868fee8f777c03/href</a></iframe><p>You can use it like:</p><pre>fetchDependencies(getInitialState(), store).then(() =&gt; render());</pre><p>Minor changes in the contentTypes factory to expose modules promises and cache resolved components in modules object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43df64a9601cf7d636b36917cd9ce45b/href">https://medium.com/media/43df64a9601cf7d636b36917cd9ce45b/href</a></iframe><p>With modulesResolver in place, EntryFactory returned to its original pre react-promise version.</p><h3>Prevent FOUC</h3><p>By default additional files required with Webpack&#39;s <strong>require.ensure</strong> contain embedded styles. That results into <a href="https://en.wikipedia.org/wiki/Flash_of_unstyled_content">Flash of unstyled content</a> on the initial load.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aebpz6jH1w8l2DdIHIxMrQ.png" /><figcaption>FOUT on calendar page</figcaption></figure><p>To include all styles into combined css file I simply pass {<strong>allChunks: true} </strong>into <a href="https://webpack.github.io/docs/stylesheets.html#styles-from-initial-chunks-into-separate-css-output-file">ExtractTextPlugin</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b66db5bf47c789e8d45dfd807596d01/href">https://medium.com/media/9b66db5bf47c789e8d45dfd807596d01/href</a></iframe><h3>Redux async reducers</h3><p>In this chapter I will explain how to load Redux reducers asynchronously using popular library <a href="https://github.com/erikras/redux-form">redux-form</a> as an example. <a href="https://github.com/th0r/webpack-bundle-analyzer">Webpack bundle analyses</a> highlighted a heavy dependency of <a href="https://github.com/erikras/redux-form">redux-form</a> as a good candidate for chunk loading. The issue is with a way it integrates into an application:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb070e4066ddfdcd780508198136e0cc/href">https://medium.com/media/bb070e4066ddfdcd780508198136e0cc/href</a></iframe><p>The import directive will always ensure to include library into js bundle.</p><p>I found a nice solution from <a href="https://medium.com/u/a3a8af6addc1">Dan Abramov</a> how to dynamically load reducers:</p><p><a href="http://stackoverflow.com/a/33044701/540802">How to dynamically load reducers for code splitting in a Redux application?</a></p><p>It&#39;s almost 1 to 1 implementation provided in the original answer. I provide it to show how generic the approach is to apply with <strong>require.ensure.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f67afb1d67452c48f3070313ef81354d/href">https://medium.com/media/f67afb1d67452c48f3070313ef81354d/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5bf17b93baf25b60edbeffbf798acca/href">https://medium.com/media/d5bf17b93baf25b60edbeffbf798acca/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f92816912fc0aabe3ab1f67742252bbb/href">https://medium.com/media/f92816912fc0aabe3ab1f67742252bbb/href</a></iframe><h3>Measurements</h3><p>Any performance related changes won&#39;t be justified unless we compare metrics before and after changes. I used <a href="https://github.com/paulirish/pwmetrics">pwmetrics</a> CLI tool powered by <a href="https://github.com/GoogleChrome/lighthouse/">Lighthouse</a>. Every result is a median of 5 runs. I measured 4 most visited type of pages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MZCUo2yTY5ZX5-bdoT_CwQ.png" /><figcaption>Home page before</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qpCLq6s1eXpYjll8Jz9d6g.png" /><figcaption>Home page after</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S1gTWpPXiaOjrD_hSlYLYg.png" /><figcaption>Calendar page before</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cyf2fV_CGbTghiNdLVlVhA.png" /><figcaption>Calendar page after</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vPdyhscPmaYbR4CwfAWu4g.png" /><figcaption>Auction page before</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8tmvKKw00MLXAthcADqew.png" /><figcaption>Auction page after</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4PYODupCo7sV9HLK8lGqFg.png" /><figcaption>Lot page before</figcaption></figure><p>There is an <a href="https://github.com/paulirish/pwmetrics/issues/28">open issue</a> which prevented to run metric multiple times on Lot page, so only single run metric is available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZQ_F8VC5hlJNbRRyx6VPLg.png" /><figcaption>Lot page after</figcaption></figure><p>On average Time to Interactive was improved by 650 ms with the most improvement on the pages where least amount of Javascript is required to load. Another takeaway is that chunk loading has a positive improvement on every page of the website. This is awesome!</p><h3>Conclusions</h3><p>It was a valuable exercise with positive outcomes on the website performance. It allowed me to have a better understanding of the technology stack: React SSR, Redux, Webpack. Most importantly this makes a good foundation of growing web application without sacrificing client side performance. I hope my overview will inspire others to have a look on code-splitting in their projects.</p><p>Learned lessons:</p><ul><li>explore JS bundle with <a href="https://github.com/th0r/webpack-bundle-analyzer">Webpack bundle analyzer</a></li><li>return promises from React render functions proved to be a bad idea: doesn’t work with ReactDOMServer.renderToString, <a href="https://github.com/facebook/react/issues/1739">https://github.com/facebook/react/issues/1739</a></li><li>enable allChunks setting in Webpack to prevent FOUT <a href="https://webpack.github.io/docs/stylesheets.html#styles-in-commons-chunk">https://webpack.github.io/docs/stylesheets.html#styles-in-commons-chunk</a></li><li>Redux allows loading reducers dynamically <a href="http://stackoverflow.com/a/33044701/540802">http://stackoverflow.com/a/33044701/540802</a></li></ul><p><a href="http://bit.ly/code-splitting-example">Code repo</a> to play with.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac50748d80de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How we reduced CSS by the factor of 50]]></title>
            <link>https://medium.com/@sejoker/how-we-reduced-css-by-the-factor-of-50-ac8576798f4a?source=rss-b4e9d06d535c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac8576798f4a</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-performance]]></category>
            <dc:creator><![CDATA[Yevgen Safronov]]></dc:creator>
            <pubDate>Wed, 20 Apr 2016 20:09:35 GMT</pubDate>
            <atom:updated>2016-04-20T20:09:35.412Z</atom:updated>
            <content:encoded><![CDATA[<p>In the summer of 2015, we released a new version of <a href="https://auctionata.com/en">auctionata.com</a>. We built it with the following stack:</p><ul><li><em>Node.js</em></li><li><em>React.js</em></li><li><em>SCSS</em></li></ul><p>One particular story I want to share is how we evolve our CSS styles since the initial launch.</p><h4>The bug</h4><p>Yes, this is true. Our original version of the CSS file weighted 1 Mb, and it was obviously a bug. We are using the component-based approach for our front end. We define styles for the component in the separate file and then import it into component’s source file:</p><p>Each <em>.scss</em> file contains the import of the <em>setup.scss</em>, where we declare our global variables, mixins and other shared code:</p><p>The problem was that <em>_fonts.scss</em> included a declaration of 2 custom font-face declarations like this:</p><p>During a build process, all fonts files were embedded not once but for each component we use on the home page. This way out of 1 Mb 99% contained duplicated fonts. The fix was obvious, we moved font-face declarations out of <em>_fonts.scss</em> and imported it once in the root container. As a result, our CSS file shrank to 100 Kb.</p><h4>WOFF only</h4><p>A 10x improvement was impressive, but 100 Kb of CSS still seemed too much. Furthermore, style declaration blocked rendering until the file was loaded and parsed in all browsers. So having the will to decrease the size of CSS even further I started to explore.</p><p>Auctionata is the leading online auction house for art and luxury collectibles. Our customer base is mostly using modern versions of the browsers. As a consequence, we support two last versions of the major browsers (Chrome, Firefox, Safari, IE, Edge). Luckily, WOFF format has great support in the <a href="http://caniuse.com/#feat=woff">browsers</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xDnCUoCUryPCDDt4jqVaZw.png" /></figure><p>With that said we left only WOFF format and the result CSS was reduced by 33% to more appropriate 65 Kb.</p><h4>Loading fonts asynchronously</h4><p>Let’s take a step aside and review our assumptions why we started with embedding fonts into stylesheet file initially. What issues would we have if fonts are loaded separately? A good explanation of the problem called FOIT (flash of invisible text) I found in the article <a href="https://www.filamentgroup.com/lab/font-loading.html">“How we use web fonts responsibly, or, avoiding a @font-face-palm”</a> written by <a href="https://www.filamentgroup.com/about/#zach-leatherman">Zach Leatherman</a>.</p><blockquote>When you reference an external web font using @font-face, most browsers will make any text that uses that font completely invisible while the external font is loading.</blockquote><p>On the same blog, I’ve found a fantastic article <a href="https://www.filamentgroup.com/lab/font-events.html">“Font Loading Revisited with Font Events”</a> by <a href="https://www.filamentgroup.com/about/#scott-jehl">Scott Jehl </a>devoted to the exact problem I was trying to solve. I briefly highlight the suggested approach:</p><ul><li>Load fonts async using <a href="https://github.com/bramstein/fontfaceobserver">FontFaceObserver</a> written by Bram Stein.</li><li>As soon as fonts are loaded apply a <em>fonts-loaded </em>class to the body.</li><li>Rewrite styles to use fallback fonts initially and custom fonts when a <em>fonts-loaded</em> class is available.</li><li>Cache fonts locally.</li><li>Use cookies to apply a <em>fonts-loaded</em> class on the server.</li></ul><p>The biggest challenge was to rewrite of the existing styles. It wasn’t an enjoyable process, but a reward was worth it.</p><p>In the end, our CSS file was decreased one more time to 20 Kb. As a result of the refactoring, we disabled embedding of the fonts. It opened the room for one more improvement: we started to serve WOFF2 format again which has support in the latest version of Firefox and Chrome. Normally, it has 30% less file size.</p><h4>Conclusion</h4><p>Although we made 50 times an improvement in comparison to the initial version, we are not close to the end. <a href="https://developers.google.com/speed/pagespeed/insights/?url=https%3A%2F%2Fauctionata.com%2Fen&amp;tab=desktop">Google Page Insights</a> still complains that our CSS file blocks rendering of the page. My favorite choice at the moment would be to extract and inline above the fold CSS using a <a href="https://github.com/addyosmani/critical"><em>Critical</em></a> library authored by Addy Osmani and load main CSS asynchronously with JavaScript.</p><p>By this example, I want to highlight the process of continuous improvement that could be applied to any field of your everyday activities. It is a good habit to challenge the initial assumptions, most of the time we should regularly review them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac8576798f4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Android component for React Native]]></title>
            <link>https://medium.com/@sejoker/writing-android-component-for-react-native-e34802bf3377?source=rss-b4e9d06d535c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e34802bf3377</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Yevgen Safronov]]></dc:creator>
            <pubDate>Sun, 25 Oct 2015 12:46:21 GMT</pubDate>
            <atom:updated>2016-02-15T21:24:08.926Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Update: migrated source code to support React Native 0.19.</em></p><p>For whose who are not familiar with <a href="http://facebook.github.io/react-native/">React Native</a>, I would refer to a small guide I wrote some time ago.</p><p>In my current company, I came up with an idea to prototype Android port of <a href="https://itunes.apple.com/de/app/auctionata-live/id859958380?mt=8">our iOS application</a>. It was just 2 weeks after React-native added support for Android and I thought it would be a fun project to play with RN.</p><p>Obviously the most challenging part of the application is handling live video stream, because it requires switching stream’s video quality based on available Internet bandwidth. But first things first — I needed a RN native component to show any video stream. There is a popular <a href="https://github.com/brentvatne/react-native-video">video component</a> for RN but it has support for iOS only. I decided to write my own RN component wrapper around <a href="https://github.com/yixia/VitamioBundle">Vitamio player</a>. It is well known open-source project and has support of RTMP protocol we use for mobile app.</p><p>I had no prior experience with writing native RN components so I went directly to RN documentation on how to create one. A guide I refer to is called <a href="http://facebook.github.io/react-native/docs/native-components-android.html#content">Native UI Components</a>, there is similar one for iOS. There are several essential parts to declare:</p><ul><li>Implement custom ViewManager (Android part)</li><li>Register the ViewManager (Android part)</li><li>Implement the JavaScript module</li><li>Register the module (Android part)</li></ul><h4>Implement custom ViewManager</h4><p>Referring to the <a href="https://github.com/yixia/VitamioBundle/blob/master/vitamio-sample%2Fsrc%2Fio%2Fvov%2Fvitamio%2Fdemo%2FVideoViewDemo.java">example</a> of declaring VideoView for Vitamio this is how the essence of VideoView declaration looks like:</p><pre>public class VideoViewDemo extends Activity {<br> @Override public void onCreate(Bundle icicle) {<br>   super.onCreate(icicle);<br>   if (!LibsChecker.checkVitamioLibs(this))<br>     return;<br>   setContentView(R.layout.videoview);<br>   mEditText = (EditText) findViewById(R.id.url);<br>   mVideoView = (VideoView) findViewById(R.id.surface_view);<br>   if (path == &quot;&quot;) { return; }<br>   mVideoView.setVideoPath(path);<br>   mVideoView.setMediaController(new MediaController(this));<br>   mVideoView.requestFocus();<br> }<br>...<br>}</pre><p>The code looks quite straightforward. Apart from passing a reference to Activity into LibsChecker, VideoView requires a path to a video stream and instance of MediaController.</p><p>Let’s start with declaring our own custom ViewManager, the code is quite similar to the <a href="http://facebook.github.io/react-native/docs/native-components-android.html#1-create-the-viewmanager-subclass">reference example</a> in docs:</p><pre>...<br>public class VitamioViewManager extends SimpleViewManager&lt;VideoView&gt;{ <br> public static final String REACT_CLASS = “RCTVitamioView”;<br> @Override<br> public String getName() {<br>   return REACT_CLASS;<br> }<br></pre><p>expose setStreamUrl setter using ReactProp:</p><pre>@ReactProp(name = &quot;streamUrl&quot;)<br>public void setStreamUrl(VideoView view, @Nullable String streamUrl) {<br>   if (!LibsChecker.checkVitamioLibs(mActivity))<br>      return;<br>    <br>   view.setVideoPath(streamUrl);       <br>   view.setMediaController(new MediaController(mContext));<br>   view.requestFocus();       <br>}</pre><p>add createViewInstance implementation:</p><pre>private ThemedReactContext mContext = null;<br>private Activity mActivity = null;</pre><pre>@Override<br>public VideoView createViewInstance(ThemedReactContext context){<br>  mContext = context;   <br>  return new VideoView(context);<br>}</pre><p>One note about the code. Because LibsChecker requires an instance of Activity we will receive it via constructor, it will reference root activity used for RN application;</p><pre>public VitamioViewManager(Activity activity) {<br>  mActivity = activity;<br>}</pre><h3>Eugene Safronov on Twitter</h3><p>How to access Activity from a RN Android module? http://stackoverflow.com/a/32825290/540802?stw=2 ... Clean approach for android react native components #react-native</p><h4>Register the ViewManager</h4><p>The final Java step is to register the ViewManager to the application, this happens via the applications package member function createViewManagers:</p><pre>...<br>public class VitamioViewPackage implements ReactPackage {<br><br>  private Activity mActivity = null;<br><br>  public VitamioViewPackage(Activity activity) {<br>      mActivity = activity;<br>  }<br><br><br>  @Override    <br>  public List&lt;NativeModule&gt;<br>  createNativeModules(ReactApplicationContext reactContext) {<br>     return Collections.emptyList();<br>  }  </pre><pre>  @Override<br>  public List&lt;Class&lt;? extends JavaScriptModule&gt;&gt; createJSModules() {<br>    return Collections.emptyList();<br>  }     </pre><pre>  @Override<br>  public List&lt;ViewManager&gt;<br>  createViewManagers(ReactApplicationContext reactContext) {<br>    return Arrays.&lt;ViewManager&gt;asList(<br>      new VitamioViewManager(mActivity)<br>    );    <br>  }<br>}</pre><h4>Implement the JavaScript module</h4><p>In order to expose custom UI component in JavaScript it is necessary to call special requireNativeComponent function:</p><pre>var { requireNativeComponent, PropTypes } = require(&#39;react-native&#39;);<br><br>var iface = {<br>  name: &#39;VideoView&#39;,<br>  propTypes: {<br>    streamUrl: PropTypes.string<br>  }<br>};<br><br>module.exports = requireNativeComponent(&#39;RCTVitamioView&#39;, iface);</pre><h4>Register the module</h4><p>Although it’s not mentioned as required step in official documentation we need it because of reference to the root activity:</p><pre>package com.vitamio_demo;<br><br>import com.facebook.react.ReactActivity;<br>import com.facebook.react.ReactPackage;<br>import com.facebook.react.shell.MainReactPackage;<br><br>import java.util.Arrays;<br>import java.util.List;<br><br>import com.sejoker.VitamView.VitamioViewPackage; // &lt;--- import<br><br>public class MainActivity extends ReactActivity {<br><br>    /**<br>     * Returns the name of the main component registered from JavaScript.<br>     * This is used to schedule rendering of the component.<br>     */<br>    @Override<br>    protected String getMainComponentName() {<br>        return &quot;vitamio_demo&quot;;<br>    }<br><br>    /**<br>     * Returns whether dev mode should be enabled.<br>     * This enables e.g. the dev menu.<br>     */<br>    @Override<br>    protected boolean getUseDeveloperSupport() {<br>        return BuildConfig.DEBUG;<br>    }<br><br>   /**<br>   * A list of packages used by the app. If the app uses additional views<br>   * or modules besides the default ones, add more packages here.<br>   */<br>    @Override<br>    protected List&lt;ReactPackage&gt; getPackages() {<br>      return Arrays.&lt;ReactPackage&gt;asList(<br>        new MainReactPackage(),<br>        new VitamioViewPackage(this)          // &lt;------ add here<br>      );<br>    }<br>}</pre><h4>Example of usage</h4><p>Install the package in a project:</p><pre>npm i react-native-android-vitamio --save</pre><p>DeclareVideoView:</p><pre>var VitamioView = require(&#39;react-native-android-vitamio&#39;);<br><br>class VideoScreen extends React.Component {<br>  render() {<br>    return (<br>      &lt;View&gt;<br>        &lt;VitamioView style={styles.video} streamUrl=&quot;rtmp://fms.12E5.edgecastcdn.net/0012E5/mp4:videos/8Juv1MVa-485.mp4&quot;/&gt;<br>      &lt;/View&gt;<br>    );<br>  }<br>}<br><br><br>var styles = StyleSheet.create({<br>  video: {<br>      flex: 1,<br>      flexDirection: &#39;row&#39;,<br>      height: 400,<br>    }<br>})<br><br>module.exports = VideoScreen;</pre><h4>Thoughts</h4><p>I was thrilled with the fact that I could expose iOS and Android existing components in RN application. I stumbled over a couple of issues during the development process, although I found very active community around RN and Android team is working hard on bringing parity with iOS counterpart and fixing found issues. The <a href="https://github.com/facebook/react-native/releases">releases</a> are regular and I predict RN for Android will be quite mature by the end of the year.</p><h4>References</h4><ul><li><a href="https://github.com/sejoker/react-native-android-vitamio">Source code</a></li><li><a href="https://github.com/ms88privat/react-native-video-gstreamer">Android Video component with GStreamer</a></li><li><a href="https://github.com/jondot/awesome-react-native">Awesome list for React-native</a></li><li><a href="http://brentvatne.ca/react-native-newsletter/">React Native newsletter</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e34802bf3377" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pebble app development with Pebble.js]]></title>
            <link>https://medium.com/@sejoker/pebble-app-development-with-pebble-js-ab9af8c8ce50?source=rss-b4e9d06d535c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab9af8c8ce50</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[pebble]]></category>
            <dc:creator><![CDATA[Yevgen Safronov]]></dc:creator>
            <pubDate>Sat, 04 Jul 2015 17:07:26 GMT</pubDate>
            <atom:updated>2015-07-04T18:23:53.390Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pebble</h3><p>Pebble is a smartwatch that pairs with both Android and iPhone devices via Bluetooth. It has an e-paper display with LED backlight, accelerometer and compass sensors. On top of that battery lasts up to a week between charges. From the beginning Pebble team embraced the Developer community which resulted in powerful SDK. Although a primary language for apps development is C, there is a room for JavaScript developers as well.</p><h3>PebbleKit JS</h3><p><a href="http://developer.getpebble.com/guides/js-apps/pebblekit-js">PebbleKit JavaScript framework</a>. This framework expands the ability of Pebble app to run Javascript logic on the phone. It allows fast access to data location from the phone and has API for getting data from the web. Unfortunately app development still requires programming in C. I could recommend <a href="http://www.sitepoint.com/pebble-watch-development-javascript/">some</a> <a href="http://developer.getpebble.com/guides/js-apps/pebblekit-js">great</a> articles on how to get started.</p><h3>Pebble.js</h3><p><a href="http://developer.getpebble.com/guides/js-apps/pebble-js/">Pebble.js</a> in contrast to PebbleKit JS allows developers to create watchapp using only JavaScript code. It is simple yet powerfull enough for creating watchapps that fetch and display data from various web services or remotely control other smartdevices. The downside of that approach is connected to the way how Pebble.js works. It is built on top of the standard Pebble SDK and PebbleKit JS. It consists of C app that runs on the watch and interacts with the phone in order to process user actions. The Pebble.js library provides API to build user interface and then remotely controls the C app to display it. As a consequence of the described approach watchapp couldn’t function without a connection to the phone. On a side note I would mention that library is <a href="https://github.com/pebble/pebblejs">open-source</a> and still in beta, so breaking API changes are possible.</p><h3>First steps</h3><p>There are 2 options getting started with Pebble.js:</p><ul><li>Install <a href="http://developer.getpebble.com/sdk/">Pebble SDK</a> on you local machine. This option allows you to customize Pebble.js</li><li>Create <a href="https://cloudpebble.net/">CloudPebble</a> account and work with your appwatch projects online. It is the easiest way to begin Pebble development.</li></ul><h3>CloudPebble</h3><p>CloudPebble environment allows you to write, build and deploy your appwatch applications both on simulator and physical device. Everything is stored in the cloud so no headache with compilers, virtual machines or python dependencies (in my case installation of boost-python end up with errors on MacOS).</p><h3>Hello world</h3><p>As introduction let’s build Hello World application with Pebble.js. Create a new project in CloudPebble:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*tKJDjgBDLNVGEetC." /></figure><p>Then write the following code in the app.js file:</p><pre>// Import the UI elements <br><strong>var</strong> UI = <strong>require</strong>(&#39;ui&#39;); </pre><pre>// Create a simple Card<br><strong>var</strong> card = <strong>new</strong> UI.Card({<br>  title: &#39;Hello World&#39;,<br>  body: &#39;This is your first Pebble app!&#39;<br>}); </pre><pre>// Display to the user<br>card.show();</pre><p>Start the code on Pebble watch or simulator and you will get the same screen as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/0*vJ0sgroobEDVZIds." /><figcaption>Hello World</figcaption></figure><h3>StackExchange profile</h3><p>Getting some data from web services like weather or news is easy with ajax library call. For example let’s construct an app view of your StackExchange profile:</p><pre><strong>var</strong> UI = <strong>require</strong>(&#39;ui&#39;);<br><strong>var</strong> ajax = <strong>require</strong>(&#39;ajax&#39;);<br><br>// Create a Card with title and subtitle<br><strong>var</strong> card = <strong>new</strong> UI.Card({<br>  title:&#39;Profile&#39;,<br>  subtitle:&#39;Fetching...&#39;<br>});<br><br>// Display the Card<br>card.show();<br><br>// Construct URL<br>//https://api.stackexchange.com/docs/me#order=desc&amp;sort=reputation&amp;//filter=default&amp;site=stackoverflow&amp;run=true<br><strong>var</strong> API_TOKEN = &#39;put api token here&#39;;<br><strong>var</strong> API_KEY = &#39;secret key&#39;;<br><strong>var</strong> URL = &#39;https://api.stackexchange.com/2.2/me?key=&#39; + API_KEY + &#39;&amp;order=desc&amp;sort=reputation&amp;access_token=&#39; + API_TOKEN + &#39;&amp;filter=default&#39;;<br><br>// Make the request<br>ajax(<br>  {<br>    url: URL,<br>    type: &#39;json&#39;<br>  },<br>  <strong>function</strong> (data) {<br>    // Success!<br>    console.log(&#39;Successfully fetched StackOverflow profile&#39;);<br><br>    <strong>var</strong> profile = data.items[0];<br><br>    <strong>var</strong> badges = &#39;Badges: &#39; + profile.badge_counts.gold +<br>  &#39; &#39; + profile.badge_counts.silver +<br>  &#39; &#39; + profile.badge_counts.bronze;<br>    // Show to user<br>    card.subtitle(&#39;Rep: &#39; + profile.reputation);<br>    card.body(badges + &#39;\nDaily change:&#39; + profile.reputation_change_day + &#39;\nWeekly change:&#39; + profile.reputation_change_week + &#39;\nMonthly change:&#39; + profile.reputation_change_month);<br>  },<br>  <strong>function </strong>(error) {<br>    // Failure!<br>    console.log(&#39;Failed fetching Stackoverflow data: &#39; + JSON.stringify(error));<br>  }<br>);</pre><p>The app’s view after the start:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/0*W5I_rCz8gFsvlV8q." /><figcaption>Stackoverflow profile</figcaption></figure><h3>Egg timer</h3><p>Lastly I would like to create a small real life watchapp. I will demonstrate how to compose Timer app for boiling eggs. Let’s start with building blocks we need:</p><ul><li>Window is the basic building block in Pebble application. It allows to add different elements and specify a position and size for them.</li><li>A menu is a type of Window that displays a standard Pebble menu.</li><li>Vibe allows you to trigger vibration on the wrist. It will signal that eggs are boiled.</li></ul><h4>Egg size screen</h4><p>Users are able to select eggs size from options:</p><pre><strong>var</strong> UI = <strong>require</strong>(&#39;ui&#39;);<br><strong>var</strong> menu = <strong>new</strong> UI.Menu({<br>  sections: [{<br>    title: &#39;Egg size&#39;,<br>    items: [{<br>     title: &#39;Medium&#39;,<br> }, {<br>     title: &#39;Large&#39;<br> }, {<br>     title: &#39;Extra-large&#39;<br>    }]<br>  }]<br>}); </pre><pre>menu.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/0*gbqdplHVQmSDKKsh." /><figcaption>Egg size screen</figcaption></figure><h4>Timer selection screen</h4><p>On the next step user selects timer duration. It depends whether he wants soft-boiled or hard-boiled eggs. The second level menu for medium size looks like:</p><pre><strong>var</strong> mdMenu = <strong>new</strong> UI.Menu({<br>    sections: [{<br>      title: &#39;Egg timer&#39;,<br>      items: [{<br>        title: &#39;Runny&#39;,<br>        subtitle: &#39;2m&#39;<br>      }, {<br>        title: &#39;Soft&#39;,<br>        subtitle: &#39;3m&#39;<br>      }, {<br>        title: &#39;Firm&#39;,<br>        subtitle: &#39;4m&#39;<br>      }, {<br>        title: &#39;Hard&#39;,<br>        subtitle: &#39;5m&#39;<br>      }]<br>    }]<br>  });<br><br>  // open second level menu from the main<br>  menu.on(&#39;select&#39;, function(e) {<br>    <strong>if</strong> (e.itemIndex === 0){<br>      mdMenu.show();<br>    } <strong>else</strong> <strong>if</strong> (e.itemIndex === 1){<br>      lgMenu.show();<br>    } <strong>else</strong> {<br>      xlMenu.show();<br>    }<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/0*M7_bHQIA4tyUu19O." /><figcaption>Timer selection screen</figcaption></figure><h4>Timer screen</h4><p>When timer duration is selected we start a countdown.</p><pre>mdMenu.on(&#39;select&#39;, onTimerSelect);<br>lgMenu.on(&#39;select&#39;, onTimerSelect);<br>xlMenu.on(&#39;select&#39;, onTimerSelect);<br><br>// timeouts mapping from header to seconds<br><strong>var</strong> timeouts = {<br>  &#39;2m&#39;: 120,<br>  &#39;3m&#39;: 180,<br>  &#39;4m&#39;: 240,<br>  &#39;5m&#39;: 300,<br>  &#39;6m&#39;: 360,<br>  &#39;7m&#39;: 420<br>};<br><br><strong>function</strong> onTimerSelect (e) {<br>  <strong>var</strong> timeout = timeouts[e.item.subtitle];<br>  timer(timeout);<br>}</pre><p>The final bit of the watchapp is to display timer, show message and notify the user with vibration on the wrist when time is elapsed.</p><pre><strong>var</strong> readyMessage = <strong>new</strong> UI.Card({<br>  title: &#39;Done&#39;,<br>  body: &#39;Your eggs are ready!&#39;<br>});<br><br><strong>function</strong> timer (timerInSec) {<br>  <strong>var</strong> intervalId = setInterval(function(){<br>    timerInSec--;<br><br>    // notify with double vibration<br>    <strong>if</strong> (timerInSec == 1){<br>      Vibe.vibrate(&#39;double&#39;);<br>    }<br>    <strong>if</strong> (timerInSec &gt; 0){<br>      timerText.text(getTimeString(timerInSec));<br>    } else {<br>      readyMessage.show();<br>      timerWindow.hide();<br><br>      clearInterval(intervalId);<br><br>      // notify with long vibration<br>      Vibe.vibrate(&#39;long&#39;);<br>    }<br>  }, 1000);<br><br>  <strong>var</strong> timerWindow = <strong>new</strong> UI.Window();<br>  <strong>var</strong> timerText = <strong>new</strong> UI.Text({<br>    position: <strong>new</strong> Vector2(0, 50),<br>    size: <strong>new</strong> Vector2(144, 30),<br>    font: &#39;bitham-42-light&#39;,<br>    text: getTimeString(timerInSec),<br>    textAlign: &#39;center&#39;<br>  });<br><br>  timerWindow.add(timerText);<br>  timerWindow.show();<br>  timerWindow.on(&#39;hide&#39;, function(){<br>    clearInterval(intervalId);<br>  });<br>}<br><br>// format remaining time into 00:00 string<br><strong>function</strong> getTimeString (timeInSec) {<br>  <strong>var</strong> minutes = parseInt(timeInSec / 60);<br>  <strong>var</strong> seconds = timeInSec % 60;<br>  <strong>return</strong> minutes + &#39;:&#39; + (seconds &lt; 10 ? (&#39;0&#39; + seconds) : seconds);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/0*Q2F-w0cDpfc0tvHE." /><figcaption>Timer screen</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/0*zpsEPg1knjI_mRlU." /><figcaption>Done message</figcaption></figure><h3>Conclusion</h3><p>You can do much more with Pebble.js:</p><ul><li>Get accelerometer values</li><li>Display complex UI mixing geometric elements, text and images</li><li>Animate elements on the screen</li><li>Use the GPS and LocalStorage on the phone</li><li>Timeline API is coming</li></ul><p>Pebble.js is best suited for quick prototyping and applications that require access to the internet. The pity part of the JS written applications is the requirement of constant connection to the phone. Usually Pebble.js apps need more power and respond slower than a similar native app.</p><h3>Useful links</h3><ul><li><a href="http://developer.getpebble.com/getting-started/pebble-js-tutorial/part1/#introduction">Pebble.js tutorial</a></li><li><a href="https://developer.getpebble.com/blog/">Pebble blog</a></li><li><a href="https://pebble.github.io/pebblejs/">Pebble.js docs</a></li><li><a href="https://gist.github.com/sejoker/426e4b10f7dc6a3a5218">Egg timer code</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab9af8c8ce50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Alternative React Native tutorial]]></title>
            <link>https://medium.com/@sejoker/alternative-react-native-tutorial-510dce242112?source=rss-b4e9d06d535c------2</link>
            <guid isPermaLink="false">https://medium.com/p/510dce242112</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Yevgen Safronov]]></dc:creator>
            <pubDate>Sat, 04 Jul 2015 16:43:34 GMT</pubDate>
            <atom:updated>2015-07-04T18:24:31.204Z</atom:updated>
            <content:encoded><![CDATA[<h3>React</h3><p>React is an open-sourced JavaScript library made by Facebook for building UI applications. The project has a strong emphasis on the component based approach and utilizes full power of JavaScript for constructing all elements. React Native project was introduced on the first React conference in January 2015. It allows you to build native mobile applications using the same concepts from React. In this tutorial I am going to explain the main building blocks of React Native by the example of iOS demo application. I assume that readers have previous experience in writing web applications with React.</p><h3>Setup</h3><p>Please go through <a href="http://facebook.github.io/react-native/docs/getting-started.html">getting started section</a> on React Native website if you would like to build an application on your machine.</p><h3>Quick start</h3><p>When all necessary tools are installed let’s initialize new React application with command:</p><pre>react-native init LastFmTopArtists</pre><p>After the command fetches code and dependencies you can open new project (LastFmTopArtists/LastFmTopArtists.xcodeproj) in Xcode. Then build and run the app with cmd+R. You will see a similar screen on iOS simulator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/0*La6N7ymuQOkihVLl." /><figcaption>First start</figcaption></figure><p>You can make changes in index.ios.js, then press cmd+R and see instant changes in the simulator.</p><h3>Demo app</h3><p>In this tutorial I will show you how to build a list of popular artists using <a href="http://www.last.fm/api/show/geo.getTopArtists">Last.fm api</a>. We will display them with help of <a href="http://facebook.github.io/react-native/docs/listview.html#content">ListView</a> component and redirect on artist page using <a href="http://facebook.github.io/react-native/docs/webview.html#content">WebView</a>.</p><h3>First screen</h3><p>Lets start with adding a new screen into our application. For now it will contain dump text. Create fileArtistListScreen with the following code:</p><pre><strong>var</strong> React = <strong>require</strong>(&#39;react-native&#39;);</pre><pre><strong>var</strong> {<br>  ListView,<br>  StyleSheet,<br>  Text,<br>  View,<br>} = React;</pre><pre><strong>class</strong> ArtistListScreen <strong>extends</strong> React.Component {<br>  render() {<br>    <strong>return</strong> (<br>      &lt;View style={styles.container}&gt;<br>      &lt;Text&gt;Artist list would be here&lt;/Text&gt;<br>      &lt;/View&gt;<br>    );<br>  }<br>}</pre><pre><strong>var</strong> styles = StyleSheet.create({<br>  container: {<br>    flex: 1,<br>    backgroundColor: &#39;white&#39;,<br>    marginTop: 64<br>  }<br>})</pre><pre><strong>module.</strong>exports = ArtistListScreen;</pre><p>Here are some things to note:</p><ul><li>I declare react components with <a href="http://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#plain-javascript-classes">ES6 Classes</a> syntax.</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">ES6 Destructuring assignment</a> syntax is used for React objects declaration.</li><li><a href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/">FlexBox</a> is a default layout system in React Native. Flex values can be either integers or doubles, indicating the relative size of the box. So, when you have multiple elements they will fill the relative proportion of the view based on their flex value.</li><li>ListView is declared but will be used later.</li></ul><p>From index.ios.js we call ArtistListScreen using <a href="http://facebook.github.io/react-native/docs/navigatorios.html#content">NavigatorIOS</a> component:</p><pre><strong>var</strong> React = <strong>require</strong>(&#39;react-native&#39;);<br><strong>var</strong> ArtistListScreen = <strong>require</strong>(&#39;./ArtistListScreen&#39;);</pre><pre><strong>var</strong> {<br>  AppRegistry,<br>  NavigatorIOS,<br>  StyleSheet<br>} = React;</pre><pre><strong>var</strong> LastFmArtists = React.createClass({<br>  render: <strong>function</strong>() {<br>    <strong>return</strong> (<br>     &lt;NavigatorIOS<br>      style={styles.container}<br>      initialRoute={{<br>        title: &quot;last.fm Top Artists&quot;,<br>        component: ArtistListScreen<br>      }}<br>      /&gt;<br>    );<br>  }<br>});</pre><pre><strong>var</strong> styles = StyleSheet.create({<br>  container: {<br>    flex: 1,<br>    backgroundColor: &#39;white&#39;,<br>  },<br>});</pre><p>Switch to iOS Simulator, refresh with cmd+R and you will see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/0*Cr7ehy4vIzhxxhnh." /><figcaption>Empty artists list</figcaption></figure><h3>ListView</h3><p>After we have got empty screen, let’s render some mock data in a ListView component. This component has a number of performance improvements such as rendering of only visible elements and removing which are off screen. The new version of ArtistListScreen looks like the following:</p><pre><strong>class</strong> ArtistListScreen <strong>extends</strong> React.Component {<br>  <strong>constructor</strong>(props) {<br>      <strong>super</strong>(props)<br>      this.state = {<br>        isLoading: false,<br>        dataSource: <strong>new</strong> ListView.DataSource({<br>          rowHasChanged: (row1, row2) =&gt; row1 !== row2<br>        })<br>      }<br>    }</pre><pre>  componentDidMount() {<br>    this.loadArtists();<br>  }</pre><pre>  loadArtists() {<br>    this.setState({<br>      dataSource: this.getDataSource([{name: &#39;Muse&#39;}, {name: &#39;Radiohead&#39;}])<br>    })<br>  }</pre><pre>  getDataSource(artists: Array&lt;any&gt;): ListView.DataSource {<br>    return this.state.dataSource.cloneWithRows(artists);<br>  }</pre><pre>  renderRow(artist) {<br>    return (<br>      &lt;Text&gt;{artist.name}&lt;/Text&gt;<br>    );<br>  }</pre><pre>  render() {<br>    return (<br>      &lt;View style={styles.container}&gt;<br>        &lt;ListView<br>          dataSource={this.state.dataSource}<br>          renderRow={this.renderRow.bind(this)}<br>          automaticallyAdjustContentInsets={false}<br>        /&gt;<br>      &lt;/View&gt;<br>    );<br>  }<br>}</pre><p>Side notes:</p><ul><li>The DataSource is an interface that ListView is using to determine which rows have changed over the course of updates.</li><li>ES6 constructor is an analog of getInitialState</li></ul><p>The end result of the changes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/0*12I7iTiNaPirPCR2." /><figcaption>Screen with mock data</figcaption></figure><h3>Api token</h3><p>Last.fm web api free to use but you will need personal api token in order to access it. At first it is necessary to <a href="http://www.last.fm/join">join Last.fm</a> and then <a href="http://www.last.fm/api/account/create">get an API account</a>.</p><h3>Fetching real data</h3><p>Assume you have successfully setup API account. Let’s call a real web service using <a href="http://facebook.github.io/react-native/docs/network.html#fetch">fetch API</a>:</p><pre><strong>const</strong> API_KEY=&#39;put token here&#39;;<br><strong>const</strong> API_URL = &#39;http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&amp;country=ukraine&amp;format=json&amp;limit=40&#39;;<br><strong>const</strong> REQUEST_URL = API_URL + &#39;&amp;api_key=&#39; + API_KEY;</pre><pre>loadArtists() {<br>      this.setState({<br>        isLoading: true<br>      });</pre><pre>      fetch(REQUEST_URL)<br>        .then((response) =&gt; response.json())<br>        .catch((error) =&gt; {<br>          <strong>console</strong>.error(error);<br>        })<br>        .then((responseData) =&gt; {<br>          this.setState({<br>            isLoading: false,<br>            dataSource: this.getDataSource(responseData.topartists.artist)<br>          })<br>        })<br>        .done();<br>    }</pre><p>After refresh the iOS simulator should display:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/0*B63x5aobB54DiLVR." /><figcaption>Screen with real data</figcaption></figure><h3>ArtistCell</h3><p>Since we have real data, it is time to add artist’s images and rank them on the display. Let’s move artist cell display logic into separate component ArtistCell:</p><pre>&#39;use strict&#39;;</pre><pre><strong>var</strong> React = <strong>require</strong>(&#39;react-native&#39;);</pre><pre><strong>var</strong> {<br>  Image,<br>  View,<br>  Text,<br>  TouchableHighlight,<br>  StyleSheet<br>} = React;</pre><pre><strong>class</strong> ArtistCell <strong>extends</strong> React.Component {<br>  render() {<br>    <strong>return</strong> (<br>      &lt;View&gt;<br>        &lt;View style={styles.container}&gt;<br>          &lt;Image <br>            source={{uri: this.props.artist.image[2][&quot;#text&quot;]}}<br>            style={styles.artistImage}<br>          /&gt;<br>          &lt;View style={styles.rightContainer}&gt;<br>            &lt;Text style={styles.rank}&gt;## {this.props.artist[&quot;@attr&quot;].rank}&lt;/Text&gt;<br>            &lt;Text style={styles.name}&gt;{this.props.artist.name}&lt;/Text&gt;<br>          &lt;/View&gt;<br>        &lt;/View&gt;<br>        &lt;View style={styles.separator}/&gt;<br>      &lt;/View&gt;<br>    );<br>  }<br>}</pre><pre><strong>var</strong> styles = StyleSheet.create({<br>  container: {<br>    flex: 1,<br>    flexDirection: &#39;row&#39;,<br>    justifyContent: &#39;center&#39;,<br>    alignItems: &#39;center&#39;,<br>    padding: 5<br>  },<br>  artistImage: {<br>    height: 84,<br>    width: 126,<br>    marginRight: 10<br>  },<br>  rightContainer: {<br>    flex: 1<br>  },<br>  name: {<br>    textAlign: &#39;center&#39;,<br>    fontSize: 14,<br>    color: &#39;#999999&#39;<br>  },<br>  rank: {<br>    textAlign: &#39;center&#39;,<br>    marginBottom: 2,<br>    fontWeight: &#39;500&#39;,<br>    fontSize: 16<br>  },<br>  separator: {<br>    height: 1,<br>    backgroundColor: &#39;#E3E3E3&#39;,<br>    flex: 1<br>  }<br>})</pre><pre><strong>module</strong>.exports = ArtistCell;</pre><p>Changes in ArtistListScreen:</p><pre>// declare new component<br><strong>var</strong> ArtistCell = <strong>require</strong>(&#39;./ArtistCell&#39;);</pre><pre>// use it in renderRow method:<br>  renderRow(artist) {<br>    <strong>return</strong> (<br>        &lt;ArtistCell <br>          artist={artist} <br>        /&gt;<br>      );<br>  }</pre><p>Press cmd+R in iOS Simulator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/0*uLfvZA-kQZCbymDC." /></figure><h3>WebView</h3><p>The last piece of the application would be to open a web page by clicking in ListView. Declare new component WebView:</p><pre>&#39;use strict&#39;;</pre><pre><strong>var</strong> React = <strong>require</strong>(&#39;react-native&#39;);</pre><pre><strong>var</strong> {<br>  View,<br>  WebView,<br>  StyleSheet<br>} = React;</pre><pre><strong>class</strong> Web <strong>extends</strong> React.Component {<br>  render() {<br>    <strong>return</strong> (<br>      &lt;View style={styles.container}&gt;<br>        &lt;WebView url={this.props.url}/&gt;<br>      &lt;/View&gt;<br>    );<br>  }<br>}</pre><pre><strong>var</strong> styles = StyleSheet.create({<br>  container: {<br>    flex: 1,<br>    backgroundColor: &#39;#F6F6EF&#39;,<br>    flexDirection: &#39;column&#39;,<br>  },<br>});</pre><pre>Web.propTypes = {<br>  url: React.PropTypes.string.isRequired<br>};</pre><pre><strong>module</strong>.exports = Web;</pre><p>Then by using <a href="http://facebook.github.io/react-native/docs/touchablehighlight.html#content">TouchableHighlight</a> we will call onOpenPage from ArtistCell:</p><pre><strong>class</strong> ArtistCell <strong>extends</strong> React.Component {<br>  render() {<br>    <strong>return</strong> (<br>      &lt;View&gt;<br>       &lt;TouchableHighlight<br>          onPress={this.props.onOpenPage}<br>          underlayColor=&#39;transparent&#39;&gt;<br>          &lt;View style={styles.container}&gt;<br>            &lt;Image <br>              source={{uri: this.props.artist.image[2][&quot;#text&quot;]}}<br>              style={styles.artistImage}<br>            /&gt;<br>            &lt;View style={styles.rightContainer}&gt;<br>              &lt;Text style={styles.rank}&gt;## {this.props.artist[&quot;@attr&quot;].rank}&lt;/Text&gt;<br>              &lt;Text style={styles.name}&gt;{this.props.artist.name}&lt;/Text&gt;<br>            &lt;/View&gt;<br>          &lt;/View&gt;<br>        &lt;/TouchableHighlight&gt;<br>        &lt;View style={styles.separator}/&gt;<br>      &lt;/View&gt;<br>    );<br>  }<br>}</pre><p>Finally open web page from ArtistListScreen component:</p><pre>// declare new component<br><strong>var</strong> WebView = <strong>require</strong>(&#39;WebView&#39;);</pre><pre><br><strong>class</strong> ArtistListScreen <strong>extends</strong> React.Component {<br>  // will be called on touch from ArtistCell<br>  openPage(url) {<br>    this.props.navigator.push({<br>      title: &#39;Web View&#39;,<br>      component: WebView,<br>      passProps: {url}<br>    });<br>  }</pre><pre>  renderRow(artist) {<br>    <strong>return</strong> (<br>        &lt;ArtistCell <br>          artist={artist}<br>          // specify artist&#39;s url on render<br>          onOpenPage={this.openPage.bind(this, artist.url)}<br>        /&gt;<br>      );<br>  }</pre><pre>}</pre><p>Now a touch on any cell in ListView will load a web page for selected artist:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/0*j2sFNtvHwA-UpurS." /></figure><h3>Conclusion</h3><p>You can explore source code of the app on <a href="https://github.com/sejoker/react-native-lastfm-artists">Github repo</a>. For me it was a real fun to play with React Native. I found debugging in Chrome and error stack messages extremely easy to work with. By using React’s component-based approach you can build complex UI without much effort. I highly recommend to explore this technology for rapid prototyping and maybe for your next awesome project.</p><h3>Useful links</h3><ul><li><a href="http://herman.asia/building-a-flashcard-app-with-react-native">Building a flashcard app with React Native</a></li><li><a href="https://github.com/facebook/react-native/tree/master/Examples">Examples of React Native apps</a></li><li><a href="http://facebook.github.io/react-native/docs/videos.html#content">React Native Videos</a></li><li><a href="https://egghead.io/series/react-native-fundamentals">Video course on React Native</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=510dce242112" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>