<?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 Luc Humanhighway on Medium]]></title>
        <description><![CDATA[Stories by Luc Humanhighway on Medium]]></description>
        <link>https://medium.com/@humanhighway?source=rss-4737e3221992------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Pg77S8Pluex37Spt.jpg</url>
            <title>Stories by Luc Humanhighway on Medium</title>
            <link>https://medium.com/@humanhighway?source=rss-4737e3221992------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 20:05:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@humanhighway/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[functional programming 筆記 (1)]]></title>
            <link>https://humanhighway.medium.com/functional-programming-%E7%AD%86%E8%A8%98-1-e218f3683e2e?source=rss-4737e3221992------2</link>
            <guid isPermaLink="false">https://medium.com/p/e218f3683e2e</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[natural-transformation]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functor]]></category>
            <category><![CDATA[monads]]></category>
            <dc:creator><![CDATA[Luc Humanhighway]]></dc:creator>
            <pubDate>Sun, 02 May 2021 06:07:26 GMT</pubDate>
            <atom:updated>2021-05-05T07:56:36.449Z</atom:updated>
            <content:encoded><![CDATA[<p>functor / applicative / either &amp; task monad / natural transformation</p><h4>Funtor (函子)</h4><p>在 haskell 裡 Functor 是一個具有 fmap行為的 <a href="https://openhome.cc/Gossip/CodeData/HaskellTutorial/TypeClass.html">typeclass</a>.</p><p>先將值放在容器 (Context) 裡面, 操作時打開容器取出值, 操作結束以後(映射成另一個值)再將值包裹到新的容器當中。在 javascript 裡面最<strong>接近</strong> functor 的就是 Array , 例如 array.map 在 Array 內操作 Array 裡面的數值並返回一個新的 Array.</p><p>在上述的概念下實作一個 Box:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cca69f47835d7c39460d94e517180d2/href">https://medium.com/media/1cca69f47835d7c39460d94e517180d2/href</a></iframe><ul><li>映射函數。</li><li>單元律。</li><li>保持原有數據結構，執行函數 map 後永遠回傳同一個 box type.</li></ul><h4>Applicative functor</h4><p>雖然這個說法不太準確，個人認為 Applicative 可以視為 Functor 之間運算行為的定義。</p><p>舉例來說， Box(10) 跟 Box(20) 要做相乘後成為 Box(200). 定義相乘這個運算行為即是 applicative, 將一個封裝過的函數運用到一個封裝的值上。</p><p>在上述例子下嘗試實作 applicative functor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9310d59cd55d3bc77e9c73fdecfada5b/href">https://medium.com/media/9310d59cd55d3bc77e9c73fdecfada5b/href</a></iframe><h4>Monad</h4><p>根據 <a href="http://dev.stephendiehl.com/hask/#monad-myths">http://dev.stephendiehl.com/hask/#monad-myths</a> 的解釋</p><blockquote><strong>Monad Myths</strong></blockquote><blockquote>The following are all <strong>false</strong>:</blockquote><blockquote>Monads are impure.</blockquote><blockquote>Monads are about effects.</blockquote><blockquote>Monads are about state.</blockquote><blockquote>Monads are about imperative sequencing.</blockquote><blockquote>Monads are about IO.</blockquote><blockquote>Monads are dependent on laziness.</blockquote><blockquote>Monads are a “back-door” in the language to perform side-effects.</blockquote><blockquote>Monads are an embedded imperative language inside Haskell.</blockquote><blockquote>Monads require knowing abstract mathematics.</blockquote><blockquote>Monads are unique to Haskell.</blockquote><p>雖然這說法也不太正確，但個人理解是 monad 是一種组合函数後操作抽象的方式(在執行程式餵值之前，這時我們並不知道被運算的對象是誰，但依然能定義出運算行為)。透過函數式編程的特性將所需要的函數組合封裝起來後，目的即是封裝實現了對於各種函數運算的 typeclass。而當使用 monad 時像建立一個獨立運算環境的結構，餵值運算後將結果放入新的 context 後回傳。</p><h4>Either Monad</h4><p>以 Either monad 來說，當在執行 pipe 或 compose 串聯的的組成函數, 某些函數執行可能會有 side effect, 例如 fetch 資料沒有成功 , parse 一個 非正規的 json object, 在這些操作中就需要處理額外的錯誤行為。Either monad 的設計可以讓函數能持續 map / chain 到最後 fold 時才處理遇到的錯誤異常。</p><p><strong>Left (sad)&amp; Right (happy) / fromNullable / tryCatch</strong></p><p>Right/Left 跟 Box 的差別在於改變 fold 變成 fold(errorHandler, successHandler).而 Right 在 fold 只會執行 success handler, 反之 Left 執行 error handler. 另外 Left 在每次 map 時則是<strong>不執行參數函數f</strong>, 直接將錯誤的結果包裹在 Left 後回傳。</p><p>透過 Left &amp; Right 實作兩個函數fromNullable tryCatch , 當錯誤發生時回傳 Left, 成功則回傳 Right.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1af24dc8e4d750e9c05a6e96ce850857/href">https://medium.com/media/1af24dc8e4d750e9c05a6e96ce850857/href</a></iframe><h4>Task Monad</h4><p>Task monad (Future)是個類似 Promise 行為的 monad, 擁有 reject , resolve 的函數流程。而 task 在執行 fork 才是真正開始執行函數，實現了惰性求值( 在呼叫 fold 之前，都是在組合函數, keep pure.)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d934e971ee8ad4917fe578d1a2896be/href">https://medium.com/media/3d934e971ee8ad4917fe578d1a2896be/href</a></iframe><blockquote>task 為 Brian Lonsdorf 提供的 type.js, 可參考原始碼 <br><a href="https://github.com/FrontendMasters/hardcore-functional-js-v2/blob/master/types.js">https://github.com/FrontendMasters/hardcore-functional-js-v2/blob/master/types.js</a></blockquote><h4>Natural transformation</h4><p>指的是將一個 Functor 容器轉變為另一個 Functor 容器 — 轉換容器的過程( Functor 之間的 morphism )。</p><p>以 either monad to task monad 為例：</p><pre>const eitherToTask  = (e) =&gt; e.fold(Task.rejected, Task.of);</pre><p>Either Monad 的 fold(left, right) 轉換為當失敗則回傳Task.rejected, 成功則用 Task.of 產生一個新的 task 包裹成功結果。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/689be17af97855439d69cd6044f80af1/href">https://medium.com/media/689be17af97855439d69cd6044f80af1/href</a></iframe><p>Reference:</p><ul><li><a href="https://frontendmasters.com/courses/hardcore-js-v2/">Hardcore Functional Programming in JS</a></li><li><a href="https://kwijibo.github.io/task-monad-in-javascript/">The Task Monad in Javascript: pure asynchronous effects you can compose</a></li><li><a href="https://zh.wikipedia.org/zh-tw/%E8%87%AA%E7%84%B6%E8%AE%8A%E6%8F%9B">自然變換 - 维基百科，自由的百科全书</a></li><li><a href="https://ithelp.ithome.com.tw/articles/10247881">Natural transformation - iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天</a></li><li><a href="https://blog.joecwu.com/2015/08/scava-scala-functor-applicative-monad.html">Category theory(範疇論)之什麼是Functor, Applicative, Monad, Semigroup, Monoid?</a></li><li><a href="https://medium.com/hannah-lin/2020-it-%E9%90%B5%E4%BA%BA%E8%B3%BD%E4%B9%8B-%E9%96%8B%E5%A7%8B%E7%94%A8-javascript-%E5%AD%B8-functional-programming-%E5%9B%89-f7b050a60406">2020 IT 鐵人賽之 — 開始用 javaScript 學 Functional Programming 囉</a></li><li><a href="https://ithelp.ithome.com.tw/users/20103390/ironman/3740">mostly:functional 從零開始的異世界程式觀 --- 函數式程式設計的試煉 :: 第 12 屆 iT 邦幫忙鐵人賽</a></li><li><a href="https://ithelp.ithome.com.tw/users/20121700/ironman/3271">Functional Programming in Kotlin :: 第 12 屆 iT 邦幫忙鐵人賽</a></li><li><a href="https://www.ithome.com.tw/voice/93723">探索Haskell的Monad</a></li><li><a href="https://www.zhihu.com/question/338211892">如何向初中生解释什么是Monad？</a></li><li><a href="https://www.zhihu.com/question/24972880">怎样用简单的语言解释 monad？</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e218f3683e2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Summary about React Optimization]]></title>
            <link>https://humanhighway.medium.com/summary-about-react-optimization-b31711c6eda0?source=rss-4737e3221992------2</link>
            <guid isPermaLink="false">https://medium.com/p/b31711c6eda0</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-performance]]></category>
            <category><![CDATA[notes]]></category>
            <category><![CDATA[react-optimization]]></category>
            <category><![CDATA[summary]]></category>
            <dc:creator><![CDATA[Luc Humanhighway]]></dc:creator>
            <pubDate>Tue, 03 Nov 2020 13:25:51 GMT</pubDate>
            <atom:updated>2022-04-08T10:08:21.513Z</atom:updated>
            <content:encoded><![CDATA[<p>Summary about React Optimization</p><h4>前言</h4><p>這篇主要是整理一些 react 開發時可以做哪些相關優化摘要並附上連結以便快速查詢。</p><blockquote>不定期更新。最後一次更新為 2020/11/03</blockquote><p>基本上分為以下四種面向去探討。分別為 render / user experience / data &amp; state management / Tools.</p><h4><strong>Render</strong></h4><p>指的是效能上的優化 — 所有跟 render 相關的部分。要做的事情就是儘量減少 render trigger 的可能，或者降低一但 render 後所連帶引起的運算效應。</p><ul><li><strong>Memo / PureComponent</strong>: 將資料不常變動的 component 切割出來並使用 Memo / PureComponent，或者 custom memo equal function / override shouldComponentUpdate 客製化觸發 render 函數。</li></ul><p><em>reference: </em><a href="https://dmitripavlutin.com/use-react-memo-wisely/"><em>use react memo wisely</em></a></p><ul><li><strong>不會隨著 props / states 資料相關變動的常數 / 函數: </strong>如固定的 css style object 或者與 component props, states 無關的 util function, 直接宣告在外面類似 static const variable/function 使用即可。</li><li><strong>useCallback:</strong> for memorization, 使用 useCallback 包裝宣告與 props, state 相關聯的函數 , don’t use inline function.</li><li><strong>useMemo:</strong> 跟上面一樣, 目的是 memorization, 將可能透過 props 或 states 的資料取得的相關運算，或是不常變動的 component 透過 useMemo 包裝。</li></ul><p>但你也不需要太在意 inline function 的使用，參考此篇: <a href="https://www.matthewgerstman.com/tech/performance-testing-anonymous-functions/">Performance Testing React With Anonymous Functions</a></p><ul><li><strong>css:</strong> 使用 css opacity 代替卸載/加載 react 組件做隱藏效果。</li><li><strong>useLayoutEffect:</strong> 一些可能 trigger browser reflow 如 clientWidth / offsetWidth 之類的 js 操作，可移至 useLayoutEffect 來執行。</li></ul><p><em>reference:</em><a href="https://blog.logrocket.com/useeffect-vs-uselayouteffect/"><em> useEffect vs. useLayoutEffect in plain, approachable language</em></a></p><ul><li><strong>React.Fragment: </strong>少包一層&lt;div&gt;.</li><li><strong>Shallow compare check</strong>: 避免 props 傳入 NaN, 因為 NaN !== NaN. shallow compare 會失效。</li></ul><h4>User Experience</h4><p>指的是使用體驗上的優化，例如延後載入程式碼/圖片, 延後渲染, 以及前端或 component 資料尚未完全載入時先提供 placeholder 的漸進式體驗等。</p><ul><li><strong>Server Side Render</strong></li><li><strong>React lazy &amp; React Suspense:</strong> component 程式碼分割以及載入中使用 placeholder 功能。</li><li><strong>Intersection Observer API 優化 offscreen 行為: </strong>如 <a href="https://www.npmjs.com/package/react-lazy-load-image-component">react-lazy-load-image-component</a> 或 <a href="https://www.npmjs.com/package/react-intersection-observer">react-intersection-observer</a> . 實作 offscreen toggle 也可以 skip 掉一些不必要的更新(例如 css transition, keyframes 效果)。</li></ul><h4><strong>Data &amp; State Management</strong></h4><p>資料設計面上的優化。例如減少資料複雜度或者資料在組件之間設計或傳遞的簡化或優化。</p><ul><li>避免 props drill, 善用 React Context API 或者相關 State Management 框架。</li><li>Redux 不要設計太過複雜的 state data, 儘量 flat. 如果只是部分組件共享資料，可直接使用 React Context API 。</li><li>React Context API 需要注意 re-render bail out 的問題。</li></ul><p><em>reference: </em><a href="https://blog.techbridge.cc/2020/09/13/use-context-selector-src-analysis/"><em>Context API 效能問題 — use-context-selector 解析</em></a></p><h4>Tools</h4><p>藉由一些相關工具檢查或監測效能。</p><ul><li><a href="https://zh-hant.reactjs.org/blog/2018/09/10/introducing-the-react-profiler.html">React Profiler</a> performance record 看火焰圖，或者一般錄製 dev tool 火焰圖也能看出函數的 use heavy performance 狀況。</li><li><a href="https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi">React Development Tool</a> 勾選Highlight updates when components render 直觀看出 component 渲染頻率。</li><li>使用 <a href="https://www.npmjs.com/package/@welldone-software/why-did-you-render">why-did-you-render component</a> log 找出 renderer 不必要的部分。</li><li><a href="https://developers.google.com/speed/pagespeed/insights/?hl=zh-TW">Google PageSpeed insights</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b31711c6eda0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Note about Event Loop at browser & node.js]]></title>
            <link>https://humanhighway.medium.com/note-about-event-loop-at-browser-node-js-8dfab1a4f5c2?source=rss-4737e3221992------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dfab1a4f5c2</guid>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[browsers]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Luc Humanhighway]]></dc:creator>
            <pubDate>Fri, 16 Oct 2020 15:47:37 GMT</pubDate>
            <atom:updated>2020-10-22T14:30:45.393Z</atom:updated>
            <content:encoded><![CDATA[<p>太久沒複習 js 環境的基本概念，前幾天突然被人問到一時之間不知該怎麼回答，這邊做個簡短的筆記幫助自己日後遇到同樣問題可以快速解答。</p><h4>Event Loop at Browser</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AIDg1LWTJ1pktU-tRdxrfw.png" /><figcaption>Event Loop at Browser</figcaption></figure><p>Javascript 的執行環境上無論是在 node.js 或 browser 都是 single thread, 而 browser event loop 的流程順序為：</p><ul><li>檢查 call stack (execution context stack)是否有需要直接執行的同步函數，如果有則直接執行，若執行函數裡面也有需要執行的同步函數，則遵循先進後出的 stack flow 執行完畢後離開 call stack。</li><li>若執行到非同步的函數時：會分為兩個類型 macrotask 跟 mircotask :</li></ul><h4><strong>marcotask</strong></h4><p>當呼叫到例如 Browser 內建的 <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope">WebAPI</a> 所提供的 setTimeout/setInterval / postMessage / MessageChannel , I/O / UI 互動事件非同步函數，會註冊函數至 event table 並在指定時間完成後將函數推至 event queue, 接著等 call stack 的函數執行完畢以後，再開始執行 event queue 的函數隊列，此時則遵循先進先出的 queue flow.</p><h4>microtask</h4><p>例如 built-in-objects 的 promise.then/ async, WebAPI 的MutationObserver . microtask 會被安排在每個 macrotask 執行完成後再執行其關聯的 microtask 。microtask 執行完畢後會接著執行下一個 macrotask.另外 microtask 會在渲染前執行完畢。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*DfDf5N2nEmhhOz3p6rSXjg.png" /><figcaption>microtasks</figcaption></figure><h4>Event Loop at Node.js</h4><p>node.js 則是透過底層的 libuv 封裝不同平台的操作並提供統一的 I/O API 以及 event loop 供使用。在 node.js 裡走完一趟 event loop 即代表一個 tick, 根據 <a href="https://github.com/libuv/libuv/blob/v1.40.0/src/unix/core.c#L365-L413">uv_run</a> 函數執行流程主要分為幾個步驟:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*QFcXc8ClBwe_F8nQgnfa0A.png" /><figcaption>node.js event loop</figcaption></figure><ul><li>timers: 執行 setTimeout, setInterval的 callback.</li><li>I/O callbacks (pending callback): 執行一些系統層級操作的 callback, 例如網路通信的錯誤 callback.</li><li>idle, prepare: 只供 nodejs 內部 libuv 使用。</li><li>poll: 等待新 I/O 事件的觸發，以及執行 I/O 相關 callback. 除了 setTimeout , setInterval , setImmediate 以外的 callback 大多都在這邊被執行。當 poll 階段的 queue 執行完畢後，會檢查是否有 setImmediate 的 callback , 如果有則進入 check 階段。另外也會檢查是否有到期的 timer 則放入 timer queue 等到下一階段的 timers 執行。如果兩者都沒有則會停在 poll 階段，並等待 i/o 事件觸發的 callback 並立即執行。</li><li>check: 執行 setImmediate 的 callback.</li><li>close callbacks: 執行一些關閉事件的 callback, 例如 socket.on(‘close’, callback)</li></ul><h4>microtask (node.js)</h4><ul><li>node.js 的 process.nextTick優先執行權比 promise.then 高。</li><li>在 Node.js 11.0.0 之後，macrotask 與 microtask 的執行順序已經與瀏覽器行為一致，當執行完一個 marcotask, 則會執行相關聯的 microtask callback queue 直至清空。</li></ul><h4>setImmediate &amp; setTimeout 的執行順序</h4><ul><li>假使在 poll 階段的 I/O callback 執行到 setImmediate 跟 setTimeout(fn, 0) , 則會先進去 check 階段執行 setImmediate .</li><li>假使在 timers 階段的 setTimeout callback 內執行 setImmediate 跟 setTimeout(fn, 0), 則 setTimeout 會被塞入下一個 timers 階段，而 setImmediate 會到 check 階段時被執行。</li><li>如果在最外層執行 setImmediate 跟 setTimeout(fn, 0) (在 node.js 會強制改為 <a href="https://nodejs.org/api/timers.html#timers_settimeout_callback_delay_args">1ms</a>) , setImmediate 被放入 check 階段, 而 setTimeout 被放入 times 階段。如果在進入 times 階段時這 1ms 前還沒到，則 setTimeout 只能等下個循環到 timers 階段才被執行，而在當前循環到了 check 階段則執行 setImmediate，所以有可能會依照當前執行狀況不同而順序不同。</li></ul><p>reference:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F96425312%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F96425312&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F476470428_1280.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1280" height="720" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa72263a82b9fef711b4798f4b658a54/href">https://medium.com/media/fa72263a82b9fef711b4798f4b658a54/href</a></iframe><ul><li><a href="http://www.ruanyifeng.com/blog/2018/02/node-event-loop.html">Node 定时器详解</a></li><li><a href="https://zhuanlan.zhihu.com/p/80458653">正确理解 Node.js 的 Event loop</a></li><li><a href="https://morosedog.gitlab.io/nodejs-20200121-Nodejs-9/">Node.js | 深入理解事件循環機制(Node.js篇) | J.J.&#39;s Blogs</a></li><li><a href="https://segmentfault.com/a/1190000022449328">从 libuv 看 nodejs 事件循环</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dfab1a4f5c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebAssembly with Web worker]]></title>
            <link>https://humanhighway.medium.com/webassembly-with-web-worker-9b5bbb5a596b?source=rss-4737e3221992------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b5bbb5a596b</guid>
            <category><![CDATA[webworker]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[wasm]]></category>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[workerize-loader]]></category>
            <dc:creator><![CDATA[Luc Humanhighway]]></dc:creator>
            <pubDate>Thu, 10 Sep 2020 17:07:30 GMT</pubDate>
            <atom:updated>2020-09-11T02:22:36.956Z</atom:updated>
            <content:encoded><![CDATA[<h3>WebAssembly with Web Worker</h3><p>本文目的是將 WebAssembly 的執行部分交給 Web Worker 執行進而達到 main thread 的 UI 運作順暢，範例將由上一篇 <a href="https://medium.com/@humanhighway/rust-wasm-%E4%BD%BF%E7%94%A8-rust-%E9%96%8B%E7%99%BC-webassembly-%E8%88%87-node-js-server-%E4%BD%9C%E5%8A%A0%E8%A7%A3%E5%AF%86%E6%BA%9D%E9%80%9A-34b33e3952b9">Rust + WebAssembly</a> 的範例做改版。</p><p>範例原始碼 <a href="https://github.com/humanhighway/rust-wasm-crypto-demo/tree/webworker">rust-wasm-crypto-demo</a> (webworker branch)</p><h4>workerize-loader</h4><p><a href="https://github.com/developit/workerize-loader">workerize-loader</a> 除了實作輕量的 RPC (Remote Process Call)implementation 外還能在 worker 裡面使用 async await feature, 整合上也幾乎無痛引入。</p><p><strong>loader 設定流程：</strong></p><ol><li>安裝 loader: yarn add workerize-loader --dev</li><li>增加 loader 設定針對 .worker.js 檔案做相關處理。</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14556a925926ac3124300a9d89abd5ea/href">https://medium.com/media/14556a925926ac3124300a9d89abd5ea/href</a></iframe><h4>Webpack globalObject 設定</h4><p>因為 webpack v4 預設編譯將模塊綁至 window object, 所以在 output 需增加設定 <a href="https://webpack.js.org/configuration/output/#outputglobalobject">globalObject</a>: ‘this’ . 此設定是避免因為 worker 無法取得 DOM reference 的 window is undefined 錯誤。</p><h4><strong>撰寫 worker</strong></h4><p>因為原本透過 wasm-bindgen 設定的 wasm (rust) -&gt; call js function 的綁定是在 window object, 移至 worker 以後則將綁定函數移至 worker 環境的 self function. 被 trigger 的 self function 再透過 worker.postMessage 轉發出去。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f83a79d20e9319a90889a19ec22dcfb/href">https://medium.com/media/6f83a79d20e9319a90889a19ec22dcfb/href</a></iframe><h4>使用 worker</h4><p>建立 worker 後監聽 message event 拿到從 wasm -&gt; worker 一路轉發的資料。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d4128c02ce6f8877e58278bcd4e6165/href">https://medium.com/media/3d4128c02ce6f8877e58278bcd4e6165/href</a></iframe><p>範例原始碼 <a href="https://github.com/humanhighway/rust-wasm-crypto-demo/tree/webworker">rust-wasm-crypto-demo</a> (webworker branch)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b5bbb5a596b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust + Wasm : 使用 rust 開發 WebAssembly 與 node.js server 作加解密溝通]]></title>
            <link>https://humanhighway.medium.com/rust-wasm-%E4%BD%BF%E7%94%A8-rust-%E9%96%8B%E7%99%BC-webassembly-%E8%88%87-node-js-server-%E4%BD%9C%E5%8A%A0%E8%A7%A3%E5%AF%86%E6%BA%9D%E9%80%9A-34b33e3952b9?source=rss-4737e3221992------2</link>
            <guid isPermaLink="false">https://medium.com/p/34b33e3952b9</guid>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Luc Humanhighway]]></dc:creator>
            <pubDate>Thu, 10 Sep 2020 00:52:47 GMT</pubDate>
            <atom:updated>2020-09-10T16:47:01.348Z</atom:updated>
            <content:encoded><![CDATA[<p>Rust + WebAssembly : 使用 rust 開發 WebAssembly 與 node.js server 作 aes 加解密溝通</p><p>最近在研究如何使用 WebAssembly 在前端開發的各種進階應用。而本文是用 rust 編譯成 wasm 建立 websocket 串接並與後端 nodejs server 加解密訊息溝通。除了前端效能提升的考量以外，也能封裝與 server 加解密溝通邏輯的敏感資訊到 wasm, 較不容易像 js 識別其程式流程。</p><p>範例原始碼: <a href="https://github.com/humanhighway/rust-wasm-crypto-demo">rust-wasm-crypto-demo</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oq1XeNhHUt9xijqs7uaFag.gif" /><figcaption>demo.gif</figcaption></figure><h4><strong>前端流程</strong></h4><ol><li>js 讀取 wasm module.(WasmSocket.js)</li><li>wasm 建立 websocket 與後端連線。(lib.rs)</li><li>wasm 收到後端加密訊息時先解密後再回給 js. (server.js, lib.rs)</li><li>wasm 使用 Aes-256 cbc+ base64 加密訊息發送給後端。(lib.rs, server.js)</li></ol><h4>Rust ＆ Wasm</h4><p>前端採用的編譯方案是 <a href="https://github.com/rustwasm">rustwasm</a> 團隊開發的 <a href="https://rustwasm.github.io/wasm-pack/">wasm-pack</a> , 能夠快速建立 wasm 與 js 溝通的函數。編譯後還能自動產生 js 相關 api 的<a href="https://github.com/DefinitelyTyped/DefinitelyTyped">DefinitelyTyped</a> ts 檔案。</p><h4><strong>Websocket Client</strong></h4><p>WebSocket 是採用 <a href="https://rustwasm.github.io/wasm-bindgen/examples/dom.html">web-sys</a> crate 所提供的 <a href="https://rustwasm.github.io/wasm-bindgen/examples/websockets.html">web_sys::WebSocket</a>. 該 crate 封裝所有對 dom 物件的建立與操作。</p><h4>Rust &amp; node.js crypto (aes-256 cbc + base64)</h4><p>加解密部分用的是 <a href="https://crates.io/crates/aes">aes</a> <a href="https://crates.io/crates/block-modes">block-modes</a> <a href="https://crates.io/crates/base64">base64</a> 這三個 crate.</p><p>步驟先將要加密的部分做一次 aes256 cbc 加密再轉 base64 ，解密則反之。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f95f05fead516541eb9b638db1bd2f7a/href">https://medium.com/media/f95f05fead516541eb9b638db1bd2f7a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*APCiCItjbA73D-ecu6ZOlA.png" /><figcaption>wasm client log</figcaption></figure><p>而在 node.js 部分使用內建的 <a href="https://nodejs.org/api/crypto.html">crypto</a> module 來做一樣的加解密行為。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37ca896a23cfeef396a4c507bcb6975a/href">https://medium.com/media/37ca896a23cfeef396a4c507bcb6975a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZoB96OLVIWrRI2zh8gQ3dQ.png" /><figcaption>node.js server log</figcaption></figure><h4>Rust singleton</h4><p>使用 <a href="https://crates.io/crates/lazy_static">lazy_static</a> create 做 static initialized 實現。</p><h4>Rust 與 JS 之間的型別轉換</h4><p>雖然 wasm 傳輸只支援四種型別 i32 / i64 / f32 /f64。不過目前已經有現成的 crate 提供一些基本 js 型別的轉換，範例採用的是 <a href="https://crates.io/crates/js-sys">js_sys</a> 的 JsString.</p><p>如果要自行做相關物件轉換:</p><ul><li>可參考 <a href="https://rustwasm.github.io/wasm-bindgen/contributing/design/importing-js-struct.html#importing-a-class-from-js">Importing a class from JS</a> 文內方式使用 extern C + pub type + #[wasm_birdgen] attribute</li><li>可使用 <a href="https://github.com/serde-rs/serde">serde</a> ctate 實作序列跟反序列。</li></ul><blockquote>wasm proposal 有研議新的型別 <a href="https://github.com/WebAssembly/js-types/blob/master/proposals/js-types/Overview.md">https://github.com/WebAssembly/js-types/blob/master/proposals/js-types/Overview.md</a></blockquote><h4><strong>Rust 新手踩雷部分</strong></h4><ol><li>因為是編譯至 wasm32-unknown-unknown 環境, 所以有些 crate 是無法編譯到 wasm 環境下執行，找到合適的 crate 試誤要花上一些時間。</li><li>singleton websocket 部分使用 unsafe send/sync struct 避掉編譯的 cannot be shared between threads safely 感覺不是很妥當的方法，等 rust 熟一點再看有沒有什麼更 rust way 的解決方式 🤔️。</li></ol><p>範例原始碼: <a href="https://github.com/humanhighway/rust-wasm-crypto-demo">rust-wasm-crypto-demo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34b33e3952b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[xstate 初探 (3) 使用 @xstate/test + cypress 執行 Model Based Testing]]></title>
            <link>https://humanhighway.medium.com/xstate-%E5%88%9D%E6%8E%A2-3-%E4%BD%BF%E7%94%A8-xstate-test-cypress-%E5%9F%B7%E8%A1%8C-model-based-testing-fde24e9d77a4?source=rss-4737e3221992------2</link>
            <guid isPermaLink="false">https://medium.com/p/fde24e9d77a4</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[model-based-testing]]></category>
            <category><![CDATA[cypressio]]></category>
            <category><![CDATA[xstate]]></category>
            <dc:creator><![CDATA[Luc Humanhighway]]></dc:creator>
            <pubDate>Tue, 21 Jul 2020 07:46:58 GMT</pubDate>
            <atom:updated>2020-07-21T07:58:08.914Z</atom:updated>
            <content:encoded><![CDATA[<h3>xstate 初探 (3) : 使用 @xstate/test + cypress 執行 Model Based Testing</h3><p><strong>MBT (Model Based Testing) 基於模型的驅動測試</strong></p><p>xstate 除了 finite state machine 以及 actor model 的架構外，基於 fsm 架構去延伸引入了一個相當強大的測試方式: <a href="https://en.wikipedia.org/wiki/Model-based_testing">model based testing</a>.</p><p>MBT 是一種根據應用程序模型自動生成測試用例的方法，finite state machine 也正是適合給 MBT 使用的 model 之一。</p><p>因為 xstate fsm 已經把所有 state 路徑以及 event 定義出來，所以當一個專案的狀態機設計好之後就能依照模型路徑自動生成測試化用例。而當專案的狀態機被加入新的狀態時，MBT 也能根據 fsm 自動再生成新的測試路徑，如此一來寫測試就可以更專注在 <a href="https://martinfowler.com/bliki/GivenWhenThen.html">Give When Then</a> 的原則於 state -&gt; event -&gt; state 的流程下編寫相對應測試。</p><p>基本上 David Khourshid 這篇 <a href="https://css-tricks.com/model-based-testing-in-react-with-state-machines/">model based testing react with state machine</a> 及內附的 <a href="https://www.youtube.com/watch?v=tpNmPKjPSFQ&amp;feature=emb_title">session talk</a> 已經親自說明關於 xstate/test 與 MBT 的實作方式。</p><h4>範例概覽</h4><p>接下來以實作簡單的問券介面為例子來寫測試。</p><p>UI demo page : <a href="https://humanhighway.github.io/xstate-questionaire/">https://humanhighway.github.io/xstate-questionaire/</a></p><p>repo: <a href="https://github.com/humanhighway/xstate-questionaire">https://github.com/humanhighway/xstate-questionaire</a></p><p>此專案提供了兩個不同的測試例子：對專案的測試機做測試 跟 對 UI 行為做測試。</p><p>兩個測試的路徑流程都一樣：user 填完名字後，接著填 q1 q2 的問題，然後 user 反悔回到 q1 重填，所以測試流程是 input user name -&gt; q1 -&gt; q2 -&gt; q3 -&gt; q2 -&gt; q1 -&gt; q2 -&gt; q3 -&gt; confirmed.</p><ul><li><a href="https://github.com/humanhighway/xstate-questionaire/blob/master/src/fsm/questionaireMachine.test.js"><strong>questionaireMachine.test.js</strong></a> : 此測試只對專案開發的狀態機 questionaireMachine.js 做測試，所以不涉及任何 UI，執行 yarn test 啟動 jest 測試就可看到結果。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e2nA_Pl8Ui2hXGjt8gkQKg.png" /><figcaption>測試專案實作狀態機的 model based testing.</figcaption></figure><ul><li><a href="https://github.com/humanhighway/xstate-questionaire/blob/master/cypress/integration/examples/e2e.spec.js"><strong>cypress/integration/examples/e2e.spec.js</strong></a> : 此測試是對從 yarn dev 所建立出來的 localhost:8080 做 UI Testing, 這邊採用的 e2e 工具是 <a href="https://www.cypress.io/">cypress</a> . 步驟是先 yarn dev , 然後再 yarn cy:open打開 cypress 的介面，並點選 e2e.spec.js 就會開始對 localhost:8080 做 UI Testing.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ju6AEellzWoZtI0Fanghhg.gif" /><figcaption>測試 e2e 的 model based testing.</figcaption></figure><h4>xstate/test 開發流程</h4><p>接下來簡單介紹 <a href="https://xstate.js.org/docs/packages/xstate-test/">xstate/test</a> 的開發步驟為：</p><p><strong>1. 建立 machine</strong></p><p>此寫法跟之前開發 xstate fsm 的方式一樣，但在需要測試的 state 加上 meta.test property, meta.test 的測試函數會在進入 state 後執行，而在函數內使用 assertion (斷言)來檢驗進入這個 state 的結果是否正確。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f47668b4030fa782a9faefc66718269/href">https://medium.com/media/8f47668b4030fa782a9faefc66718269/href</a></iframe><p><strong>2. 建立 model</strong></p><p>建立好 machine 之後，就可以使用 xstate/test 提供的 <a href="https://xstate.js.org/docs/packages/xstate-test/#createmodel-machine-options">createModel(machine).withEvents</a> 建立出 model instance 進行測試。event 的 property 主要有 exec 跟 cases .</p><ul><li><strong>exec</strong>: 主要是撰寫對測試對象做相關操作的行為，以第一個例子 questionaireMachine.test.js 為例則是操作專案的狀態機發出事件更改狀態。而在第二個 e2e 的例子，則是直接對頁面 UI 做點選或填寫的操作，再檢驗 UI 在互動後的過程是否符合測試結果。</li><li><strong>cases</strong>: 提供所需要的測試資料數據，以上面兩個測試例子為例，在玩家填寫名字的 cases 則是 cases: [ { usename: &#39;Luc&#39; }]。</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57bbf26d41e9d476142d468ac66552f9/href">https://medium.com/media/57bbf26d41e9d476142d468ac66552f9/href</a></iframe><p>TestModel 提供兩個生成測試路徑的方式: getShortestPathPlan &amp;getSimplePathPlans ，再藉著呼叫產出的路徑組合執行 path.test ，最後再呼叫 Model.testCoverage() 執行測試覆蓋。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba33cb6566d5bf60e030fc568ab91290/href">https://medium.com/media/ba33cb6566d5bf60e030fc568ab91290/href</a></iframe><p><strong>要點：</strong></p><ul><li>一開始寫 xstate 的 MBT 測試最容易誤會的雷區應該是<strong>專案開發的狀態機跟 TestModel 的狀態機是各自獨立不相干的狀態機，所以寫 MBT 的狀態機主要目的是寫出目標測試的路徑流程，而非拿原本開發專案寫好的狀態機流程來沿用。</strong>例如上述的問券狀態開發路徑是 input name &gt; q1 &gt; q2&gt; q3 &gt; confirmed. 但假設測試路徑是要測試當使用者在填到 q2 時發現 q1 填錯而按前一頁改完答案再繼續填寫, 那 TestModel 狀態路徑就會是: input name &gt; q1 &gt; q2 &gt; back to q1 &gt; q2 &gt; q3 &gt; confirmed.</li><li>xstate/test 所以提供的 testModel 可以用在任何不同的測試對象及任何方式開發的 UI page 上，只要把需要測試的路徑依照 fsm 建立後跑測試即可。</li></ul><p>reference:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FtpNmPKjPSFQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DtpNmPKjPSFQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FtpNmPKjPSFQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5be2abf04ffd87ecedaebc4d74bcf74/href">https://medium.com/media/c5be2abf04ffd87ecedaebc4d74bcf74/href</a></iframe><ul><li><a href="https://slides.com/davidkhourshid/mbt#">Write Fewer Tests!</a></li><li><a href="https://css-tricks.com/model-based-testing-in-react-with-state-machines/">Model-Based Testing in React with State Machines | CSS-Tricks</a></li><li><a href="https://timdeschryver.dev/blog/generated-tests-with-xstate-and-cypress">Generated tests with XState and Cypress</a></li><li><a href="https://spectrum.chat/statecharts/general/xstate-test-with-usemachine-hook~dd820853-dc78-4ecf-a9e9-8331e543602d">@xstate/test with useMachine hook · Statecharts</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fde24e9d77a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[xstate 初探 (2): 使用 spawn / send 建立 widget state machine 與父層傳遞事件溝通]]></title>
            <link>https://humanhighway.medium.com/xstate-%E5%88%9D%E6%8E%A2-2-%E4%BD%BF%E7%94%A8-spawn-send-%E5%BB%BA%E7%AB%8B-widget-state-machine-%E8%88%87%E7%88%B6%E5%B1%A4%E5%82%B3%E9%81%9E%E4%BA%8B%E4%BB%B6%E6%BA%9D%E9%80%9A-cc346fedab3a?source=rss-4737e3221992------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc346fedab3a</guid>
            <category><![CDATA[actors]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[actor-model]]></category>
            <category><![CDATA[xstate]]></category>
            <category><![CDATA[state-machine]]></category>
            <dc:creator><![CDATA[Luc Humanhighway]]></dc:creator>
            <pubDate>Fri, 17 Jul 2020 03:47:51 GMT</pubDate>
            <atom:updated>2020-07-17T03:47:51.372Z</atom:updated>
            <content:encoded><![CDATA[<p>基本上當專案的元件複雜度都高到一個程度時，只有一個 state machine 是無法滿足專案的狀態變化需求，所以需要再規劃架構時對每個元件的複雜度建立不同的 state machine.。所以本文目的是實作父層如何建立子層的 state machine 並互相溝通。</p><p>在實作前可以先大致了解一下 <a href="https://xstate.js.org/docs/guides/actors.html#spawning-actors">spawn actor</a>章節。xstate 除了核心的 fsm 架構之外，還引用了 actor model 來達到關注點分離。</p><p>關於 actor model 幾項特性：</p><ul><li>actor 可以建立一或多個 actor.</li><li>actor 透過 message ( 在 xstate 裡指的是 event )與其他 actor 溝通。</li><li>actor 可以指定如何處理下一個 message.</li><li>actor 有自己的 local state 並且處於 isolate 狀態。</li><li>actor 是輕量的，容易被建立。</li></ul><p>也因為 actor model 特性，所以 machine 與 machine 之間溝通透過 event 來傳遞，並在各自的 local state 做資料處理。</p><blockquote>actor model 相關資料放在<a href="#991a">文末</a></blockquote><h4><strong>實作 Widget List</strong></h4><p>以一個簡單的 widget list 為例，父容器 List 可以透過事件發送給子容器 Widget 更新資料，而子容器的 Widget 可往上發送事件給父層刪除資料。</p><p>先看已完成的範例: Widget List 與 Widget 有各自獨立的 state machine. 並且有各自的 loading / idle 狀態。widget list 可以統一發送更新時間的事件, 而 widget 的移除按鈕點選可呼叫上層 machine event 刪除 widget 相關 context 資料。</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fxstate-widgets-demo%3Fembed%3D1%26file%3Dcomponents%252FRoot.js&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fxstate-widgets-demo%3Ffile%3Dcomponents%252FRoot.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-1d2450aadcf984376236c23cd2ab0ba231ddd1d85c9b72990ed2ede5b4974d1b.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/69f104cbb4ee58a1a7e26a02c7ee6108/href">https://medium.com/media/69f104cbb4ee58a1a7e26a02c7ee6108/href</a></iframe><p>主要的程式碼是著重在 widgetListMachine 跟 widgetMachine 這兩個 machine config.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35cdf7cc2c509620a14d1e0bcc5dd192/href">https://medium.com/media/35cdf7cc2c509620a14d1e0bcc5dd192/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d76d67be7dfa3cfc2042097dbdf859a/href">https://medium.com/media/1d76d67be7dfa3cfc2042097dbdf859a/href</a></iframe><p><strong>要點：</strong></p><ul><li><strong>上層建立子 widget 的 state machine</strong>: 上層的 widgetListMachine 在 loading state 透過 <a href="https://xstate.js.org/docs/guides/communication.html#invoking-promises">invoking promise</a> 跟後端要相關資料，並在 onDone 時透過 spawn 建立的 <a href="https://xstate.js.org/docs/guides/actors.html#actor-api">actor</a>+ Machine.withContext建立 widgetMachine 及初始 context.</li><li><strong>上層發送事件給 widget</strong>: 請參考 widgetListMachine updateTimeToWidgets action，使用 <a href="https://xstate.js.org/docs/guides/actions.html#pure-action">pure action</a> 建立動態 actions 並從 context 取出 actor 逐一 <a href="https://xstate.js.org/docs/guides/actions.html#send-action">send action</a>。而在 widgetMachine updateTime action 則收到發出的 update Time event 並取得更新資料。</li><li><strong>widget 發送事件給上層:</strong> 請參考 widgetMachine 的 remove action 透過 <a href="https://xstate.js.org/docs/guides/communication.html#sending-events">sendParent</a> 送出事件並 tigger widgetListMachine 的 removeWidget action. 然後再更新上層的 context 資料移除掉 widget.</li></ul><p>reference:</p><p><em>actor model reference:</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FELwEdb_pD0k%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DELwEdb_pD0k&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FELwEdb_pD0k%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bcdb83bb29927e3ed09556cff7f0e05/href">https://medium.com/media/2bcdb83bb29927e3ed09556cff7f0e05/href</a></iframe><ul><li><a href="https://www.monades.dev/get-to-know-the-actor-model/">Get to know the Actor Model</a></li><li><a href="https://en.wikipedia.org/wiki/Actor_model">Actor model - Wikipedia</a></li><li><a href="https://blog.techbridge.cc/2019/06/21/actor-model-in-web/">46 年老技術與 Web 的新火花 - Actor Model in Web</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc346fedab3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[xstate 初探: 實作簡易遊戲模型]]></title>
            <link>https://humanhighway.medium.com/xstate-%E5%88%9D%E6%8E%A2-%E5%AF%A6%E4%BD%9C%E7%B0%A1%E6%98%93%E9%81%8A%E6%88%B2%E6%A8%A1%E5%9E%8B-a72075398ef?source=rss-4737e3221992------2</link>
            <guid isPermaLink="false">https://medium.com/p/a72075398ef</guid>
            <category><![CDATA[fsm]]></category>
            <category><![CDATA[finite-state-machine]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[pixijs]]></category>
            <category><![CDATA[xstate]]></category>
            <dc:creator><![CDATA[Luc Humanhighway]]></dc:creator>
            <pubDate>Wed, 08 Jul 2020 07:52:25 GMT</pubDate>
            <atom:updated>2020-07-14T17:19:02.494Z</atom:updated>
            <content:encoded><![CDATA[<h3>xstate 初探: xstate + react &amp; pixi.js 實作簡易遊戲模型</h3><p>幾年前曾經在專案上用過<a href="https://github.com/jakesgordon/javascript-state-machine"> javascript-state-machine</a> 作為專案狀態管理的核心流程，該 libray 也是以 <a href="https://zh.wikipedia.org/wiki/%E6%9C%89%E9%99%90%E7%8A%B6%E6%80%81%E6%9C%BA">有限狀態機</a> 為架構核心，不過同樣以 FSM 為核心的 xstate 強大超過不止一個等級。去年也曾在 jsdc 2019 看作者本人來台 <a href="https://slides.com/davidkhourshid/mind-reading-jsdc?token=3MdsnYUG">演講</a> xstate 的相關內容。</p><p>簡言之，<a href="https://xstate.js.org/">xstate</a> 是一個實作 <a href="https://zh.wikipedia.org/wiki/%E6%9C%89%E9%99%90%E7%8A%B6%E6%80%81%E6%9C%BA">有限狀態機</a> 並使用 <a href="https://en.wikipedia.org/wiki/State_diagram">statecharts</a> 將流程狀態視覺化的狀態管理 library.</p><h4>react / redux 的 state 痛點</h4><p>雖然在 react 有 setState / useState / useReducer 等各種設定狀態資料的方式， redux 有 reducer 合併的 store state . 但這兩個設計其實存在了幾個常見的問題：</p><ul><li>react state 的設計模式很難從概觀看出所有定義的 state 有哪些，開發者可輕易從 setState 塞進各種資料而造成各種日後 side effect 埋雷的可能，或者造成 refactor 的困難 — 尤其在越多的 state 變化需要判定的情況下。例如多個isLoading /isEnabled /isInitialized 的 reducer, 在數個集合的狀態組合下很難看出與 UI 的狀態切換 (enabled / disabled )的關聯性。</li><li>較難直觀了解 state 之間關聯及順序 : 以 react /redux 來說，一但系統的複雜性越高, 就越難避免將狀態變化跟資料混雜在一起。也較難直接看出每一個 state 變化的相依性及順序。舉例來說，紅綠燈在一個 reducer function 像是如下範例：</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b51af8e4646a9d9e996ff24918ae3ecf/href">https://medium.com/media/b51af8e4646a9d9e996ff24918ae3ecf/href</a></iframe><p>假設這個紅綠燈的狀態變化正確順序為 紅 -&gt; 黃 -&gt; 綠 -&gt; 紅 -&gt; 黃 -&gt; 綠 …在不熟規則的情況下就有可能在紅燈狀態 dispatch CHANGE_TO_YELLOW 的 action 而導致錯誤的順序更新。</p><h4>使用 XState 的好處</h4><ul><li>透過 fsm 的核心設計強迫實作者把各種狀態流程及相關順序完整規劃出來藉以釐清各種狀態，並透過 <a href="https://xstate.js.org/docs/guides/states.html">states</a> &amp; <a href="https://xstate.js.org/docs/guides/context.html">context</a> 達到狀態(state)與資料(context)分離。</li><li>透用 <a href="https://xstate.js.org/viz/">stateschart visualizer</a> 產出狀態視覺互動 flow 方便與非程式人員討論。</li><li>已規劃好的 state 路徑設計完成後，可透過資料分析對路徑做統計及規劃，找出對使用者更常用更便捷的路徑，提高使用者體驗。</li><li>易於跟不同實作的 UI Layer 耦合或遷移，因為狀態跟資料都統一由 xstate fsm 控管，也能讓 UI component 內部大多專注於 UI 自己應有的行為而不需管理過多的 local state.</li></ul><h4><strong>利用 xstate 實作簡單的抽獎遊戲</strong></h4><p>一個簡單的抽獎遊戲：使用者每次下注會扣除 10 元，隨機機率中獎 10 元。以 fsm 為狀態處理架構，並實作 react 跟 pixi.js 兩個版本的 UI Layer.</p><h4>1. 建立一個基本 Machine，規劃 states / eventTypes 流程並產生 Visualizer Graph.</h4><p>以一個簡易的抽獎機為例, 大致上會有以下幾個步驟：</p><ol><li>初始階段等待 login 完成的UNINITIALIZEDstate.</li><li>進入可以操作下注的的 IDLE state.</li><li>若下注檢查通過，玩家下注後送出 request 後等待 server response 的 BET_REQUESTING state. 檢查不過則進入 BET_NOT_ENOUGH state, 然後再回到 IDLE state.</li><li>拿到 server response 後演繹抽獎動畫的 TRANSITION_EFFECTS_PLAYINGstate.</li><li>中獎則演繹抽獎動畫的 WIN_EFFECTS_PLAYING state，最後或直接回到 IDLE state.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7caa25da853fe29eb322b7dfe621ec6/href">https://medium.com/media/d7caa25da853fe29eb322b7dfe621ec6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*su7s7c8j9ofqx10L1sffwg.png" /><figcaption>Lottery FSM Graph.</figcaption></figure><p><a href="https://xstate.js.org/viz/?gist=96c690f78cc68b786bc46e039ebc5ab9">XState Visualizer</a></p><p><strong>要點：</strong></p><ul><li>定義相關 states &amp; eventTypes.</li><li>設定 machine config 給 <a href="https://xstate.js.org/docs/guides/machines.html#configuration">Machinefactory</a> function 建立出 instance.</li><li>使用 <a href="https://xstate.js.org/docs/guides/interpretation.html#interpreter">interpreter</a> 來建立 service 發送事件或取得更新的 state transition.</li><li>state 切換依靠 send event: 從 state 切換至下一個 state，如果是同層的 state, 則發送 event target: eventType 即可, 但如果從 nested state 跳至上層 state, 則需指定 state id.</li></ul><p><em>send event by type:</em></p><pre>// UNINITIALIZED state -&gt; IDLE state<br>// 透過 eventTypes.LOGIN_SUCCEED trigger</pre><pre>[states.UNINITIALIZED]: {<br>on: {<br>    <strong>[eventTypes.LOGIN_SUCCEED]: states.IDLE,</strong><br>  },<br>}</pre><p><em>send event by state id:</em></p><pre>// IDLE.NORMAL state -&gt; PLATING state<br>// 透過 target state id trigger.</pre><pre>[states.NORMAL]: {<br>  on: {<br>    <strong>[eventTypes.PLAY]: &#39;#playing&#39;,</strong><br>  },<br>},</pre><p><strong>2. 定義 context，使用 invoking services 銜接 server 端資料來源，在 state on: event 被 trigger 時使用 assign actions 更新 context.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05a56709fe3f52639ce1e115879b6add/href">https://medium.com/media/05a56709fe3f52639ce1e115879b6add/href</a></iframe><p><strong>要點：</strong></p><ul><li>規劃 context 的一般資料: username / user balance / win balance, 並將所需的 socket service 也注入到 context.</li></ul><pre>....</pre><pre>const machine = Machine({<br>  id: &#39;lotteryMachine&#39;,<br>  initial: states.UNINITIALIZED,<br>  <strong>context: {<br>    username: &#39;&#39;,<br>    balance: 0,<br>    win: 0,<br>    socketService: new SockerService(),<br>  },</strong></pre><pre>....</pre><ul><li>使用 <a href="https://xstate.js.org/docs/guides/communication.html">invoking services</a> 串接後端資料來源：一般的 fetch / ajax call 可用 <a href="https://xstate.js.org/docs/guides/communication.html#invoking-promises">invoking promises</a>, 不過這邊的範例資料對象是 socket , 改用 <a href="https://xstate.js.org/docs/guides/communication.html#invoking-callbacks">invoking callbacks</a> 更為適合。</li></ul><blockquote>與 socket 串接的 <a href="https://xstate.js.org/docs/guides/communication.html#invoking-callbacks">invoking callbacks</a> 放在 machine config 最上層，所以會在 <a href="https://xstate.js.org/docs/guides/interpretation.html#interpreter">interpreter</a> 建立的 service 執行 stop 時才會執行回收函數。</blockquote><ul><li>監聽 socker service 並透過呼叫 callback 送出 event 及更新 server 端資料到 context.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3dbf9ec4c758bf0d9848bc93d832e28/href">https://medium.com/media/a3dbf9ec4c758bf0d9848bc93d832e28/href</a></iframe><ul><li>撰寫 actions, 並透過 <a href="https://xstate.js.org/docs/guides/context.html#assign-action">assign action</a> 更新 context 資料:</li></ul><p>以 UNINITIALIZED -&gt; IDLE state transition 為例：</p><ol><li>socket service 拿到的使用者資料會在送出 LOGIN_SUCCEED事件時更新 username / balance context data.</li><li>state on property 送出 event -&gt; state transition 的設定增加 <a href="https://xstate.js.org/docs/guides/context.html#assign-action">assign action</a> update context.</li></ol><pre>// 原本的版本<br>[eventTypes.LOGIN_SUCCEED]: states.iDLE,</pre><pre>//----------------------------------------------------------</pre><pre>// 增加 action assign 後:</pre><pre>// 定義 actions<br>const actions = {<br>  updateUserLoginData: assign({<br>    username: (ctx, event) =&gt; (event.username),<br>    balance: (ctx, event) =&gt; (event.balance),</pre><pre>  })</pre><pre>};</pre><pre>....<br>// 設定 actions</pre><pre>[eventTypes.LOGIN_SUCCEED]: {<br>  target: states.iDLE,<br>  actions: [&#39;afterLoginSucceed&#39;]</pre><pre>},</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/584159c4903099588381d5caf0d395a3/href">https://medium.com/media/584159c4903099588381d5caf0d395a3/href</a></iframe><ul><li>使用 <a href="https://xstate.js.org/docs/guides/guards.html#guards-condition-functions">guards condition</a>檢查玩家下注前餘額是否足夠: cond 能拿到當前的 context 跟 event data 並做檢查, 回傳 true | false 來決定是否滿足到下一個 transition.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1edff4fab24f045b52780381817e872/href">https://medium.com/media/b1edff4fab24f045b52780381817e872/href</a></iframe><p><strong>3. 實作銜接 react UI 部分</strong></p><p>使用 <a href="https://xstate.js.org/docs/packages/xstate-react/">@xstate/react</a> 所提供的 useService hook 提供 current state 跟 send function. 每個 react component 藉由 current state 取的相關 state 跟 context 做相對應處理。</p><p>以 Bet Button 下注按鈕為例:</p><ul><li>只開放在 IDLE 狀態可以點選。</li><li>玩家點選後 send play event 及下注金額資料切換 state.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86f2c549a30665e2c83c5f0db6fb1932/href">https://medium.com/media/86f2c549a30665e2c83c5f0db6fb1932/href</a></iframe><p>以 User Panel 為例:</p><ul><li>在從 UNINITIALIZE 到 IDLE 狀態時更新一次 username 跟 balance.</li><li>在 BET_REQUESTING 玩家下注時 balance 扣除下注金。</li><li>玩家若中獎, 在 WIN_EFFECTS_PLAYING 才會更新 balance.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b59ddc46c8fb719ce592a02ba4ccbc0/href">https://medium.com/media/1b59ddc46c8fb719ce592a02ba4ccbc0/href</a></iframe><p><strong>要點：</strong></p><ul><li>判定多個 states 條件: 使用 array.some + state.matches</li></ul><pre>if ([&#39;idle&#39;, &#39;playing&#39;]).some(current.matches)) {</pre><pre>  // do something..<br>}</pre><p><strong>4. 實作銜接 pixi.js UI 部分</strong></p><p>pixi.js 與 xstate 銜接的方式其實跟 <a href="https://xstate.js.org/docs/recipes/react.html#class-components">react class component</a> 很類似，只要取得 service instance 則可以使用 onTransition 監聽每次 state 變動後的相關資料以及用 service.send 發送事件。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa6793e46f0de65af972f5165c48afce/href">https://medium.com/media/fa6793e46f0de65af972f5165c48afce/href</a></iframe><blockquote>pixi 一樣使用 <a href="https://zh.wikipedia.org/zh-tw/%E4%B8%AD%E4%BB%8B%E8%80%85%E6%A8%A1%E5%BC%8F">mediator pattern</a> + closure function 切開與 view component 內部行為無關的邏輯。</blockquote><p>example:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fxstate-simple-lottery%3Fembed%3D1&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fxstate-simple-lottery&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-1d2450aadcf984376236c23cd2ab0ba231ddd1d85c9b72990ed2ede5b4974d1b.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d66a795d0b899f452dae0d76b1a82e9b/href">https://medium.com/media/d66a795d0b899f452dae0d76b1a82e9b/href</a></iframe><p><a href="https://stackblitz.com/edit/xstate-simple-lottery">範例碼 source</a></p><p>Reference:</p><ul><li><a href="https://xstate.js.org/">XState - JavaScript State Machines and Statecharts</a></li><li><a href="https://blog.jerry-hong.com/posts/xstate-introduction/">XState 簡介</a></li><li><a href="https://bestofjs.org/projects/xstate">Best of JavaScript</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fd8V5vcZOQe4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dd8V5vcZOQe4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fd8V5vcZOQe4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3df52f81db7d628a47d6cd7eac20838c/href">https://medium.com/media/3df52f81db7d628a47d6cd7eac20838c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a72075398ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[pixi.js with redux]]></title>
            <link>https://humanhighway.medium.com/pixi-js-with-redux-20a62e5d3c45?source=rss-4737e3221992------2</link>
            <guid isPermaLink="false">https://medium.com/p/20a62e5d3c45</guid>
            <category><![CDATA[pixijs]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux-watch]]></category>
            <dc:creator><![CDATA[Luc Humanhighway]]></dc:creator>
            <pubDate>Fri, 10 Apr 2020 03:47:59 GMT</pubDate>
            <atom:updated>2020-07-17T14:33:25.904Z</atom:updated>
            <content:encoded><![CDATA[<h3>pixi.js with redux &amp; react</h3><p>網路上似乎沒有找到太多關於 redux與 pixi.js整合應用心得，所以在這邊分享之前研究如何讓 react component 跟 pixi component 透過 redux 整合溝通，也能讓開發兩邊不同 component view 的 developer 可以共享同樣的 redux state flow。</p><p>重點在於 pixi.js 自定義的視覺元件該如何</p><ol><li><strong>拿到 redux store state 初始值</strong>: 取得 store reference 使用 store.getState 。</li><li><strong>發送 action</strong>: 取得 store reference 使用 store.dispatch 。</li><li><strong>接收 redux store state 變化並更新</strong>: 可使用 redux-watch 或者 rxjs 來監聽 state 變化。</li></ol><p>另外 pixi component 的整合是使用 <a href="https://en.wikipedia.org/wiki/Mediator_pattern">mediator pattern</a> 寫一個 function closure 來串接 pixi 與 redux store 的相關綁定。</p><h4>使用 redux-watch 為例</h4><p>透過 redux-watch watch 去偵測 state tree 需要關注的資料變化在做相對應的更新。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02dde062a00d46356cf8892b8114fc6d/href">https://medium.com/media/02dde062a00d46356cf8892b8114fc6d/href</a></iframe><h4>使用 rxjs 為例</h4><p>使用 from , pluck , distinctUntilChanged 組合監聽某一個 state property 的變化。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdb8efef35e01806d730691b7118d317/href">https://medium.com/media/cdb8efef35e01806d730691b7118d317/href</a></iframe><p>以上範例已放在下方連結，點選 pixi.js circle view 跟 react button 都會發出 action, 而在 reducer 的 clickedCount 值變化時，會同步更新 pixi component view.</p><p><a href="https://react-pixi-with-redux-example.stackblitz.io/">example</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-pixi-with-redux-example%3Fembed%3D1%26file%3Dindex.js&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-pixi-with-redux-example%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-1d2450aadcf984376236c23cd2ab0ba231ddd1d85c9b72990ed2ede5b4974d1b.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/b01e3f656fa055a6406278c6a2ad5739/href">https://medium.com/media/b01e3f656fa055a6406278c6a2ad5739/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20a62e5d3c45" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tips about how to make a landscape fullscreen webpage in iOS Safari.]]></title>
            <link>https://humanhighway.medium.com/tips-about-how-to-make-a-landscape-fullscreen-webpage-in-ios-safari-2d6d0e94d324?source=rss-4737e3221992------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d6d0e94d324</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ios-safari]]></category>
            <category><![CDATA[web-games]]></category>
            <category><![CDATA[canvas]]></category>
            <category><![CDATA[fullscreen]]></category>
            <dc:creator><![CDATA[Luc Humanhighway]]></dc:creator>
            <pubDate>Wed, 08 Apr 2020 02:52:02 GMT</pubDate>
            <atom:updated>2020-04-08T02:52:02.719Z</atom:updated>
            <content:encoded><![CDATA[<p>話先說前頭，自從 <a href="https://absolide.tumblr.com/post/100022548384/the-minimal-ui-is-dead-long-live-the-minimal-ui">iOS7 minimal-ui viewport property</a> 廢掉以後，目前在 iOS safari <strong>沒有任何原生方式</strong>可達成 landscape fullscreen page.</p><p>所以，以下提供的兩種方式都是藉由一些 tricky 來完成所謂的 fullscreen mode，而這些應用多半是用在做 fullscreen canvas game 居多。</p><h4>1. 顯示一個可以 swipe up 的 div 讓使用者可以上滑並藉由原生行為隱藏上下狀態列。</h4><p>作法是 setInterval 定時偵測 innerHeight 跟 screenHeight 比對是否有功能列的產生，如果有則顯示一個可以 scroll 的 div 高度，等到 user scroll 收合功能後再做隱藏。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*1CjRIA2d6G892Lih2ZCflA.gif" /></figure><p><a href="https://swipe-up-make-fullscreen-example.stackblitz.io/">example</a> ( 請使用 iOS safari 開啟 )</p><p><a href="https://stackblitz.com/edit/swipe-up-make-fullscreen-example?file=index.js">source</a></p><p>主要看這段 useEffect 偵測畫面高度變化做 css show hide 的開關來切換 swipe up 的 div 何時顯示給用戶。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da25863d3cfc9e327e7bb12e9c5252ad/href">https://medium.com/media/da25863d3cfc9e327e7bb12e9c5252ad/href</a></iframe><h4>2. 在尺寸較大的 iOS device 橫向時多頁面會顯示 <a href="https://support.apple.com/guide/safari/use-tabs-for-webpages-sfri11576/mac">tabs view</a>，所以在直轉橫的情況下會自動多出 tabs 的狀態列, 而目的是做出在多個 tab pages 的狀態下直轉橫自動隱藏 tab 的功能。</h4><p>作法是製作一個隱藏且超過可視範圍高度的 div， 並呼叫 window.scrollTo 到最下面, 而 safari 的原生行為會在當網頁的 window.scrollTop 為一定高度時，自動判定隱藏原生 tab。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*MjeWVAH5hq1TGvy9ZqNG6w.gif" /></figure><p><a href="https://portrait-to-landscape-make-fullscreen-example.stackblitz.io/">example</a> (請用 iOS safari 開啟)</p><p><a href="https://stackblitz.com/edit/portrait-to-landscape-make-fullscreen-example?file=index.js">source</a></p><p>主要看這段 useEffec 當每次 window resize 並做相關檢查，當處於 landscape mode， 則 scroll 到 0, 而在 portrait mode 則 scroll to bottom，讓每次 手機在橫轉直時可以保持在 scrollTop 的數值都會被判定成自動隱藏橫向 tab。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/049d31c89b2b5d67726a2013896106b6/href">https://medium.com/media/049d31c89b2b5d67726a2013896106b6/href</a></iframe><p>另外在畫面上要放一個 hidden div 撐開網頁的頁面內容。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d9d73439cb7591a5d7e5cc708921f14/href">https://medium.com/media/2d9d73439cb7591a5d7e5cc708921f14/href</a></iframe><blockquote><em>不過這個作法會需要將主要內容固定(fixed)在最上面，所以在版面設計上會有一定的侷限性。</em></blockquote><p>搭配這兩個方式就能儘可能讓橫向的應用頁面保持在 fullscreen 的模式。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d6d0e94d324" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>