';
+ }
+ resultdiv.append(searchitem);
+ }
+ });
+});
diff --git a/assets/js/lunr/lunr-store.js b/assets/js/lunr/lunr-store.js
new file mode 100644
index 0000000..a60d6bf
--- /dev/null
+++ b/assets/js/lunr/lunr-store.js
@@ -0,0 +1,253 @@
+var store = [{
+ "title": "使用 Octopress 架設靜態 Blog - Octopress x GitHub pages x Blog",
+ "excerpt":"為什麼要寫 Blog? 工作中受到了很多教學網站及博客文章(簡書, CSDN, Medium…)非常多的幫助,因此想寫部落格將自己學到的技術記錄下來,一方面讓自己複習,一方面也希望能幫助到有需要的人。 為什麼用 Octopress? 其實有很多現成免費的部落格平台像是 Medium, Blogger 等…,但最後我還是決定用 Octopress 來建立自己的部落格,它吸引我的原因如下: 使用 Git 做版本控管,託管於 Github 使用 Markdown 寫文章 可以學到東西 免費 Git 對軟體工程師再熟悉不過了,且託管於工程師最愛充滿開源專案的 Github 平台,用 Markdown 寫文章,也能訓練自己寫 README 語法的熟練程度,又可以學到東西,因此選擇 Octopress。 事前準備 申請Github帳號 安裝Git brew install git 安裝Ruby brew install ruby 確認版本 ruby --version 建置 Octopress git clone git://github.com/imathis/octopress.git octopress...","categories": ["Blog"],
+ "tags": ["Octopress"],
+ "url": "/blog/blog/octopress-setup/",
+ "teaser": "/blog/assets/images/alfons-morales-YLSwjSy7stw-unsplash.jpg"
+ },{
+ "title": "如何使 Octopress website 能被 Google 搜索到 - Google x Search x Blog",
+ "excerpt":"在 Google 搜尋不到我的 Blog 當我們在建立完 Jekyll Blog 後,會發現竟然 Google 不到我們的 Blog 網站,別擔心這是因為我們尚未將網站提交加入 Google Search Console 中 將網站加入 Google Search Console 進入 Google Search Console 這邊使用網址前綴方式添加,加你的 Blog domain 填入並繼續 下載 googlexxxxxxxxxx.html 檔案放到 octopress/source 目錄下,commit 上傳到 GitHub 上,點擊驗證 rake gen_deploy 驗證成功 👍 Note: 如果有任何建議、問題或不同想法,歡迎留言或寄信給我,可以一起討論進步成長🙂 ","categories": ["Blog"],
+ "tags": ["Octopress"],
+ "url": "/blog/blog/how-to-add-your-octopress-blog-website-to-google-search-console/",
+ "teaser": "/blog/assets/images/alfons-morales-YLSwjSy7stw-unsplash.jpg"
+ },{
+ "title": "使用 Jekyll + minimal-mistakes 在 Github pages 上架設自己的部落格 - Jekyll x Minimal-Mistakes x GitHub pages",
+ "excerpt":"為什麼寫 Blog 文章 工作上受到了很多教學網站及 Blog 文章非常多的幫助,因此想架設一個自己的 Blog,將工作及生活學到的技術知識記錄下來,幫助自己複習,也希望能幫助到有需要的人。 為什麼選用 Jekyll + minimal-mistakes 選用 Jekyll 的原因 可用 Markdown 語法寫文章,Jekyll 會將 markdown 轉成 html 檔案 有非常豐富的主題 可客製化 選用 Minimal-mistakes 主題的原因 較多人使用,Github 上 star 有 9k 支援 Dark skin 可以放大圖,跟 Medium 類似 其實原本我是用 Octopress ,後來因為 Octopress 已不再維護,且主題沒有 Jekyll 來得豐富,最後決定使用 Jekyll 重新架一個 Blog Octopress 廢話不多說,現在讓我們一起用...","categories": ["Blog"],
+ "tags": ["Jekyll","Minimal-Mistakes","Theme"],
+ "url": "/blog/blog/creating_a_github_pages_with_jekyll_and_minimal_mistakes/",
+ "teaser": "/blog/assets/images/alfons-morales-YLSwjSy7stw-unsplash.jpg"
+ },{
+ "title": "如何使 Jekyll website 能被 Google 搜索到 - Google x Search x Blog",
+ "excerpt":"在 Google 搜尋不到我的 Blog 當我們在建立完 Jekyll Blog 後,會發現竟然 Google 不到我們的 Blog 網站,別擔心這是因為我們尚未將網站提交加入 Google Search Console 中 將網站加入 Google Search Console 進入 Google Search Console 這邊使用網址前綴方式添加,加你的 Blog domain 填入並繼續 下載 googlexxxxxxxxxx.html 檔案放到 Jekyll 根目錄,commit 上傳到 GitHub 上,點擊驗證 驗證成功 👍 提交 Sitemap 「Sitemap」是一種用來提供網站資訊的檔案,您可以在其中列出網頁、影片和其他檔案的資訊,並呈現這些內容彼此間的關係。Google 等搜尋引擎都會讀取網站的 Sitemap 檔案,藉此以更有效率的方式檢索網站。 瞭解 Sitemap 打開 Gemfile 在 group...","categories": ["Blog"],
+ "tags": ["Jekyll","Google"],
+ "url": "/blog/blog/how-to-add-your-jekyll-blog-website-to-google-search-console/",
+ "teaser": "/blog/assets/images/alfons-morales-YLSwjSy7stw-unsplash.jpg"
+ },{
+ "title": "3D Graphic Engine Tips - 三角形 x UV mapping x Vertices & Indices",
+ "excerpt":"前言 前陣子在 iOS, Android 上開發 AR 相關的功能,因為本身沒有 3D 繪圖的相關知識,後來仔細研究,終於有一些成果,這篇用來紀錄有關 3D 繪圖的小小知識,希望可以幫助到其他人. 3D 圖形世界所有物件都是由小三角形所構成 https://www.researchgate.net/figure/3D-mesh-triangles-with-different-resolution-3D-Modelling-for-programmers-Available-at_fig2_322096576 UV mapping 將 2D 圖像投影到 3D 模型表面進行 Texture 映射的 3D 建模過程 https://en.wikipedia.org/wiki/UV_mapping 以立方體為例,將各面 Texture 壓平為 2D,在映射到 UV 座標中 UV 座標,U 為橫軸,V 為縱軸,左上為(0,0),右上為(1,1) https://wiki.povray.org/content/Reference:UV_Mapping Vertices and Indices https://www.oreilly.com/library/view/real-time-3d-graphics/9781788629690/0e5b1b24-f1a7-414d-868b-37df694749ad.xhtml 順著頂點標示出頂點的 Index,根據要畫出的三角形,以逆時鐘方向依序填入 Index 另一種方式可以用安培右手定則,旋轉方向為 index 的順序,大拇指指向方向為面朝向的方位 因此在 3D 世界要畫出雙面三角形,code...","categories": ["Mobile"],
+ "tags": ["iOS","Android","3D","OpenGL","ARKit","ARCore","Sceneform","SceneKit"],
+ "url": "/blog/mobile/3d_graphic_tips/",
+ "teaser": "/blog/assets/images/nick-brunner-k4xDXNskVsQ-unsplash.jpg"
+ },{
+ "title": "搞懂 P2P 技術 (1) - P2P x IPv4 x NAT",
+ "excerpt":"前言 之前工作上遇到需要將自家 IPCam 與 iOS/Android 手機做 P2P 串流影音,研究了許多有關 P2P 的技術,因此想寫一系列有關 P2P 技術的文章. P2P 為什麼會需要 P2P 在了解一門技術前,我們先來看看為什麼會需要這門技術,這門技術是為了解決什麼問題 Centralized vs Decentralized vs Distributed 中心化網路 (Centralized) 所有 client 都連接到同一台 Server,Server 擁有所有 client 的數據訊息 可以想成是國家央行發行貨幣,所有人的錢都來自國家央行 優點 部署簡單好維護 集中管理數據 缺點 安全及隱私風險 (中心 server 遭破解串改,全部都會受影響) 離 Server 較遠的 client 拿資料的時間會更長 server 一但故障,其他 client 都不可使用 去中心化網路 (Decentralized)...","categories": ["P2P"],
+ "tags": ["iOS","Android","IPv4","NAT"],
+ "url": "/blog/p2p/p2p-tech-1-ipv4-nat/",
+ "teaser": "/blog/assets/images/nasa-1lfI7wkGWZ4-unsplash.jpg"
+ },{
+ "title": "搞懂 P2P 技術 (2) - STUN x TURN x ICE",
+ "excerpt":"前言 上一篇介紹完中心化、去中心化、分佈式網路以及 IPv4、NAT、NAT 類型,但我們依舊還有些問題未解決 A, B 兩端要如何知道彼此的內部網路 IP 及外部網路 IP (STUN) 上篇有提到 NAT 類型如果是對稱型時,會無法打通 P2P,當遇到此情形時該 (TURN) 有沒有一種框架整合這整個 P2P 流程 (ICE) STUN STUN(Session Traversal Utilities for NAT,NAT 對談穿越應用程式)是一種網路協定,它允許位於 NAT(或多重 NAT)後的客戶端找出自己的公網位址,查出自己位於哪種類型的 NAT 之後以及 NAT 為某一個本地埠所繫結的 Internet 端埠。這些資訊被用來在兩個同時處於 NAT 路由器之後的主機之間建立 UDP 通信。該協定由 RFC 5389 定義。 STUN Wiki TURN TURN(全名 Traversal Using Relay NAT),是一種資料傳輸協定(data-transfer...","categories": ["P2P"],
+ "tags": ["iOS","Android","STUN","TURN","ICE"],
+ "url": "/blog/p2p/p2p-tech-2-stun-turn-ice/",
+ "teaser": "/blog/assets/images/nasa-1lfI7wkGWZ4-unsplash.jpg"
+ },{
+ "title": "搞懂 P2P 技術 (3) - WebRTC x AWS x KVS",
+ "excerpt":"WebRTC 全名 Web Real-Time Communication,是一個支援網頁瀏覽器進行即時語音對話或影片對話的 API WebRTC Wiki WebRTC 的底層就是使用 ICE 來進行 P2P 打洞 Signaling Server 信令伺服器,用來交換雙方的 SDP 及 Ice candidate 來完成 P2P 打洞 實作 Signaling Server WebRTC 沒有明確定義如何實作 Signaling Server,主要原因在於如果雙方一開始就知道對方的資訊,那其實就不需要 Signaling Server 來交換資訊 實作一個 Signaling Server 方式有很多種,可以用 HTTP 協議也可以用 WebSocket 協議,只要能順利將雙方的資訊做交換即可 SDP (Session Description Protocol) 會話描述協議(Session Description Protocol 或簡寫...","categories": ["P2P","AWS"],
+ "tags": ["iOS","Android","WebRTC","KVS"],
+ "url": "/blog/p2p/aws/p2p-tech-3-webrtc-kvs/",
+ "teaser": "/blog/assets/images/nasa-1lfI7wkGWZ4-unsplash.jpg"
+ },{
+ "title": "如何抓取 Android 的網路封包",
+ "excerpt":"前言 最近工作上遇到需要抓封包分析才能釐清的問題 以前在開發 iOS 非常簡單,可以用 rvictl -s [iOS UUID] 在 Mac 上創建一個虛擬網卡介面,就可以開 Wireshark 抓 iOS 上的封包了 最近開發 Android 也遇到需要抓封包的情況,上網學習了一下,在這邊紀錄,希望可以幫到其他人🙂 事前準備 一台 root 過的 Android Device tcpdump tool Wireshark 補充說明: 如果沒有 root 的 Android Device,可以嘗試用 tPacketCapture 來抓包,它的原理類似開一個類似 VPN 的 app,發送的封包此 app 會抓取,但我個人實測,有時候有些封包會好像沒發出去,影響實際情況,在此不推薦! 將 tcpdump 放入 Android 裝置 adb push tcpdump /data/local/tcpdump...","categories": ["Tools"],
+ "tags": ["Android","Network","Packet","Wireshark"],
+ "url": "/blog/tools/how-to-capture-network-packet-on-android-using-tcpdump/",
+ "teaser": "/blog/assets/images/jordan-harrison-40XgDxBfYXM-unsplash.jpg"
+ },{
+ "title": "如何抓取 iOS 的網路封包",
+ "excerpt":"前言 上一篇介紹了 如何抓取 Android 的網路封包,順便也將之前如何抓 iOS 上的網路封包紀錄一下,希望能幫助到其他人. 事前準備 iOS Device rvictl (通常安裝 XCode 時,會順便安裝附加工具) Wireshark 查看 Mac 上的網路介面 ifconfig -l lo0 gif0 stf0 anpi1 anpi0 anpi2 en4 en5 en6 en1 en2 en3 ap1 en0 awdl0 bridge0 utun0 utun1 utun2 en7 查詢 iOS 裝置網路介面 將 iOS 裝置連接到 Mac 打開 XCode ->...","categories": ["Tools"],
+ "tags": ["iOS","Network","Packet","Wireshark","rvictl"],
+ "url": "/blog/tools/how-to-capture-network-packet-on-ios/",
+ "teaser": "/blog/assets/images/jordan-harrison-40XgDxBfYXM-unsplash.jpg"
+ },{
+ "title": "Design Pattern (1) - Object-Oriented Concepts (物件導向概念)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 Object-Oriented Concepts 物件導向概念 物件導向設計的四大核心概念,為設計模式的理解奠定基礎。讓我們一同簡單探索這些概念。 Encapsulation 封裝 封裝是將屬性及方法的實作細節隱藏在類別中,只暴露必要的方法給使用者,保護內部屬性和方法不被隨意修改。 就像開車時,我們只需知道踩油門會加速,踩煞車會停止,而不必了解馬達、電瓶、發動機等原理。這些細節都被封裝在引擎蓋下。 Inheritance 繼承 繼承使子類別可以繼承父類別的屬性和方法,達到程式碼重複使用的目的。 在自然界中,狗與貓都是動物,都能呼吸和行動;花草和樹木都是植物,都能進行光合作用。這就是繼承的概念。 Polymorphism 多型 多型為不同的類別提供統一的介面或抽象類別,以操作不同的實體物件。 以 iPhone 6S 為例,不論是由台積電還是三星代工的晶片,使用者拿到的 iPhone 6S 功能都一樣。這就是多型。 Abstraction 抽象 抽象通過類型或接口隱藏實作細節,只提供必要的功能給使用者。 我們在手機上安裝的 App 是對各種應用程式的抽象名稱;去市場買水果,不論是蘋果還是香蕉,水果也是一種抽象名稱。這就是抽象。 總結 理解了物件導向的核心概念後,我們將進一步探討這些概念如何引導我們進入設計原則的世界。物件導向概念為我們提供了創建模塊化、可重用和易於維護程式碼的基礎,而設計原則則教我們如何有效地應用這些概念來解決更複雜的設計問題。接下來,我們將探討這些原則,並了解它們如何幫助我們實現高質量的軟體設計。 Object-Oriented Concepts -> Design Principle -> Design Pattern 參考 Head First Design Patterns...","categories": ["Design Pattern"],
+ "tags": ["Object-Oriented Concepts"],
+ "url": "/blog/design%20pattern/design-pattern-1-object-oriented-concepts/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ },{
+ "title": "Design Pattern (2) - Design Principles (設計原則)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 Design Principle Design Principle 是用來幫助我們改善物件導向設計的建議,幫助我們設計出更好的軟體。 SOLID 物件導向程式設計基本五大原則 Single Responsibility Principle (SRP) 單一職責原則 物件應該僅具有一種單一功能,應只會有一個理由去改變此物件 e.g. 我們要做登入頁面功能,我們會這樣寫 Swift Kotlin 依照單一職責原則,我們應該要將 API 及 DB 的功能分開,修改如下 Swift Kotlin 有些文章會說 save, delete function 也須拆開在不同 class(DeleteDBService, SaveDBService)處理, 因為 save. delete 是不同職責修改項目, 不應動到另一個 class, 但我認為這樣 Over Design 反而不好維護, 拆分職責應適當不過度 Open...","categories": ["Design Pattern"],
+ "tags": ["Design Principle"],
+ "url": "/blog/design%20pattern/design-pattern-2-design-principle/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ },{
+ "title": "Design Pattern (3) - Design Patterns (設計模式)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 Design Pattern 是什麼? Design Pattern 是在軟體工程中,用於常見問題解決的一種標準化方法。它們是經過驗證的解決方案,可以用來解決設計中的特定問題。 設計模式的組成要素 Context Context是指設計模式應用的具體場景或背景。它描述了模式應用的環境和條件。 Forces Forces是指在設計過程中需要考慮的各種因素,包括但不限於性能需求、可擴展性、維護性等。 Problem Problem是指在特定Context和Forces下,開發者面臨的具體設計問題。 Solution Solution是指設計模式提供的解決方案,它幫助開發者解決Problem,並考慮到了Forces的影響。 設計模式的應用步驟 物件導向程式分析(OOA):從高層次理解應用的需求和結構。(此步驟需要劃出UML圖) 看清楚Context:透過UML圖理解模式應用的具體場景。 察覺Forces:識別影響設計的關鍵因素。 找到Problem:明確需要解決的設計問題。 套用模式:根據Problem及Forces選擇合適的設計模式。 得到新的Resulting Context:應用模式後,獲得改進後的設計方案。(此步驟需要劃出UML圖) 誤記導向程式設計 (OOP):透過新的Resulting Context UML圖,開始撰寫程式碼實作。 Design Patterns Categories Design Pattern 可以分為三種基本的類型 Creational 創建型 創建實例化物件有關的 Patterns Factory Method Pattern Abstract Factory Pattern...","categories": ["Design Pattern"],
+ "tags": ["Design Pattern"],
+ "url": "/blog/design%20pattern/design-pattern-3-design-pattern/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ },{
+ "title": "深入解析 Google Wallet Smart Tap:未來的支付方式",
+ "excerpt":"前言 最近因工作之需,深入研究了 Google Wallet Smart Tap 相關技術,因此想撰寫這篇文章來記錄所學。這不僅能幫助我自己進行複習,也希望能對其他開發者提供幫助。🙂 什麼是 NFC NFC(Near Field Communication,近場通訊)是一種使兩個裝置在幾厘米距離內進行通訊的短距離無線通訊技術。它被廣泛應用於支付、票務、資料交換等領域。 Google Wallet Smart Tap 簡介 Smart Tap 是 Google 利用 NFC 技術開發的一種專有通訊協議。它允許用戶通過移動裝置在支持的終端機上進行快速且安全的交易和資料交換。 如果你們公司是實作 Terminal 端,必須獲得認證才能使用此協議,這部分我有寫信問 Google 得到如下回覆,需要提供資訊簽署協議,Google 才會提供機密文件讓你實作。 If you are a terminal provider and would like to certify your terminal for use with Google Wallet, please provide...","categories": ["Pay","Technology"],
+ "tags": ["Google Wallet","Smart Tap","NFC","Payment Systems"],
+ "url": "/blog/pay/technology/google-wallet-smart-tap-exploring/",
+ "teaser": "/blog/assets/images/mika-baumeister-m7HWPWVjfJ4-unsplash.jpg"
+ },{
+ "title": "Design Pattern (4) - UML (統一建模語言)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 UML (Unified Modeling Language) UML 是一種用視覺圖形化來規劃建構軟體的方法。 不要急著寫程式,尤其是遇到較複雜的功能,先思考如何設計架構畫出 UML 圖,程式才會具有可讀性、維護性及擴展性。 Class 類別 如圖分為三列依序是 Class 名稱 Attribute 屬性 Operations 方法 Interface 介面 Interface 有兩種表示法 一般表示法 一般型式與 Class 並無太大區別,只要在 Class Name 上方標註 <<interface>> 即可 棒棒糖表示法 用球狀來表示介面 Attribute 屬性 Visibility 可視範圍 Sign Modifiers + Public # Protected...","categories": ["Design Pattern"],
+ "tags": ["UML"],
+ "url": "/blog/design%20pattern/design-pattern-4-uml/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ },{
+ "title": "Design Pattern (5) - Simple Factory Pattern (簡單工廠模式)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 需求 我們的目標是創建一套能夠根據用戶選擇動態生成飲料對象的點餐系統。首先,讓我們通過UML來分析系統的基本結構。 物件導向分析 (OOA) Swift Kotlin 察覺 Forces 隨著飲料店越來越多新飲品,我們也需要修改 order 方法,但這樣容易影響不會變動的程式碼,於是我們需要找出 需要變動 以及 不需變動 的程式碼,把它們分隔開來 需要變動的程式碼 Swift Kotlin 不需變動的程式碼 Swift Kotlin 找出後該如何做呢,這時候需要用到 簡單工廠模式 來將其分離 套用 Solution 套用 Simple Factory Pattern 得到新的 Context (Resulting Context) 先來看一下 Simple Factory Pattern 的 UML 其實就是定義一個工廠類別來專門處理創建物件的邏輯 我們來將飲料點餐系統套用 Simple...","categories": ["Design Pattern"],
+ "tags": ["Simple Factory Pattern"],
+ "url": "/blog/design%20pattern/design-pattern-5-simple-factory-pattern/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ },{
+ "title": "Design Pattern (6) - Factory Method Pattern (工廠方法模式)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 引言:一個全球化的挑戰 想像一下,你的飲料點餐系統在全球範圍內大受歡迎。隨著業務的擴展,你面臨著一個挑戰:如何滿足不同地區顧客的特定偏好? 上一篇我們利用簡單工廠模式模式成功地將需要變動 以及 不需變動 的程式碼分離。今天,我們將探討如何進一步提升我們系統的靈活性和擴展性。 需求:滿足全球化的味蕾 飲料點餐系統受到客戶的喜愛,業績非常好,於是客戶在世界各地迅速擴店。但很快的問題出現了——不同地區的顧客有著不同的偏好。 案例分析: 美國喜歡錫蘭紅茶 歐洲喜歡伯爵紅茶 我們的目標是,不增加過多成本的同時,滿足這些多樣化的需求。 (成本考量我們不將所有紅茶種類都加入菜單,只用最符合當地口味的茶葉製作紅茶) 物件導向分析(OOA) 於是我們修改簡單工廠的程式碼,新增 USBeverageFactory 及 EUBeverageFactory 來製作符合美國及歐洲當地口味的飲品 Swift Kotlin 察覺 Forces 這樣做雖然可以滿足分店從不同工廠取得該地區的飲品,但每當有新的分店加入,就必須動到 BeverageShop 的程式碼來添加新的分店工廠,違反了 Open Closed Principle 套用 Solution 看清楚整個 Context,察覺 Forces 後,就可以套用 Factory Method Pattern 來解決這個問題 先來看一下 Factory Method Pattern...","categories": ["Design Pattern"],
+ "tags": ["Factory Method Pattern"],
+ "url": "/blog/design%20pattern/design-pattern-6-factory-method-pattern/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ },{
+ "title": "Design Pattern (7) - Abstract Factory Pattern (抽象工廠模式)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 引言:全球化的挑戰擴展 想像一下,隨著你的飲料點餐系統在全球範圍內的擴展,你面臨著如何滿足不同地區顧客特定偏好的挑戰。 需求:滿足全球化的味蕾 隨著業務的全球化擴展,不同地區的顧客有著不同的偏好。且我們也不能只賣紅茶及綠茶,需要為我們的菜單增加新的飲品,一邊新增菜單一邊擴展店舖。 物件導向分析(OOA) Swift Kotlin 如何處理多個產品在不同分店的組合,這時就需要用到 Abstract Factory Pattern 察覺 Forces 當我們每增加一種飲品到菜單中,我們必須要修改所有的 Factory 中的方法,違反了 Open Closed Principle 套用 Solution 看清楚整個 Context,察覺 Forces 後,就可以套用 Abstract Factory Pattern 來解決這個問題 先來看一下 Abstract Factory Pattern 的 UML 透過將工廠抽象,使子類別能創建一系列的實體物件。 抽象工廠有個重要的判斷方式,當你所要創建的產品是一整個系列產品,且不同需求要創建不同系列,這個關係能夠畫成二維關係,這時就非常適合使用抽象工廠來建立產品 如下圖 Country / Tea BlackTea GreenTea...","categories": ["Design Pattern"],
+ "tags": ["Abstract Factory Pattern"],
+ "url": "/blog/design%20pattern/design-pattern-7-abstract-factory-pattern/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ },{
+ "title": "Design Pattern (8) - Builder Pattern (建造者模式)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 需求 今天我們要設計一個能自動做出手搖飲的機器,但如果手搖飲店只賣紅茶、綠茶,肯定滿足不了廣大的客群需求,因此我們要能夠讓手搖飲加入各種配料,來吸引顧客。 珍珠 (Pearls) 椰果 (Coconut Jelly) 紅豆 (Red Beans) 仙草凍 (Grass Jelly) 布丁 (Pudding) 物件導向分析 (OOA) 理解需求後,讓我們來快速實作物件導向分析吧! 但這麼做會有一個問題,假如我們今天只要加入紅豆以及布丁,就必須在其他用不到的參數傳入 false or null,參數越多越難以維護且可讀性也不高。 因此聰明的你可能想到了,可以利用寫多個不同的 constructor 來解決,如此就不需傳入不需要的參數。 察覺 Forces 這邊我們會發現當參數越多, 所需寫的 constructor 就越多,這樣既不好維護,也使得類別的實例化過程錯綜複雜,這個現象可以稱為 telescoping constructor Telescoping constructor 是當一個類別有多個構造器,每個構造器參數數量不同,導致類別難以維護和使用的問題。 套用 Builder Pattern ( Solution ) 得到新的...","categories": ["Design Pattern"],
+ "tags": ["Builder Pattern"],
+ "url": "/blog/design%20pattern/design-pattern-8-builder-pattern/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ },{
+ "title": "How to build CHIPTool for Android",
+ "excerpt":"前言 最近因工作之需,研究了一下如何 Build CHIPTool 的 apk,因為按照官方文件步驟實作會有錯誤,自己一步一步解決最後終於成功,因此想寫一篇文章紀錄,幫助我自己進行複習,也希望能對其他開發者提供幫助。🙂 簡介 Matter(前稱為Project CHIP,即Connected Home over IP)是一個統一的開源連接標準,旨在增強智能家居設備之間的互操作性和兼容性。這個標準由連接標準聯盟(CSA)開發,成員包括亞馬遜、蘋果、谷歌和Zigbee聯盟等主要行業參與者。 Matter的目標是簡化製造商的開發過程,確保智能家居產品的安全性、可靠性和易用性。它利用互聯網協議(IP)來實現各種設備、移動應用和雲服務之間的通信,支持Thread和Wi-Fi網絡傳輸。 Matter的目標是創建一個無縫且互操作的智能家居生態系統,使不同製造商的設備能夠順利協同工作。 事前準備 因為在個人開發環境 Build 容易破壞環境,會需要修改 ANDROID_HOME & ANDROID_NDK_HOME 等等…,因為 CHIP 有提供 build 環境的 image,所以這邊我選擇用 docker 使用 CHIP 的 image 啟 container 來 build. Docker Pull Docker Image 這個步驟會需要一點時間,可以去喝杯咖啡 docker pull ghcr.io/project-chip/chip-build-android:latest Run container docker run -it -v...","categories": ["Tools"],
+ "tags": ["Android","CHIP","Matter"],
+ "url": "/blog/tools/how-to-build-chiptool-for-android/",
+ "teaser": "/blog/assets/images/matter.jpg"
+ },{
+ "title": "Design Pattern (9) - Prototype Pattern (原型模式)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 前言 這次的 Pattern 讓我想到以前做過的一個 App,但當時還沒有學習到 Pattern,所以沒有用 Pattern 來處理,現在發現這個功能很適合套用 prototype pattern 這是一個用來編輯音樂燈光秀的 App,有興趣的讀者可以下載玩玩看 🙂 Asante TapTap 3 需求 今天收到了客人的需求,客人反應編輯完一條燈光還要編輯另外六條好浪費時間,能不能新增 Copy & Paste 的功能,加快編輯以節省時間,如下圖 物件導向分析 (OOA) 理解需求後,讓我們來快速實作物件導向分析吧! 當我們需要複製 LightShowData 時,只需要同樣的 jsonObject 資料重新 new 一個 LightShowData 即可複製一份 察覺 Forces 來看看上面這樣的設計會有哪些問題 如果我們的 constructor 很複雜,參數非常多,那麼重新 new 一個實體會需要知道很多細節。 如果...","categories": ["Design Pattern"],
+ "tags": ["Prototype Pattern"],
+ "url": "/blog/design%20pattern/design-pattern-9-prototype-pattern/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ },{
+ "title": "Getting Started with GitHub Container Registry",
+ "excerpt":"為什麼會寫這篇文章 隨著公司專案數量增加,每個專案的環境需求也變得更加多樣化。我們決定將原本使用Docker建置的Android Jenkins Server轉型為更靈活的架構:一個主要的Jenkins Server(Master)搭配多個Android Build Environment(Slave),後者透過Docker創建乾淨的環境。這篇文章旨在記錄此過程,不僅作為個人學習的回顧,也希望能對其他開發者提供幫助。 文章簡介 本文將引導初學者及希望深入了解如何將GitHub的新工具融入CI/CD流程的開發者,透過簡明的指南和實用的技巧,學習如何將容器映像推送至GitHub Container Registry。我將一步步展示如何設定GitHub Actions,自動化構建與部署過程,讓你的開發工作變得更加高效。 開始之前 在深入主題之前,讓我們先透過 express 框架,快速搭建一個運行於Node.js上的簡易應用。 Create a node_sample folder mkdir node_sample cd node_sample Install node package express npm init -y npm install express Create an app.js file vim app.js const express = require('express'); const app = express(); const port...","categories": ["DevOps"],
+ "tags": ["Docker","Container Registry","GitHub Actions","CI/CD","DevOps Tools"],
+ "url": "/blog/devops/getting-started-with-github-container-registry/",
+ "teaser": "/blog/assets/images/github_container_registry.png"
+ },{
+ "title": "How to Enable RSA Encryption Algorithm Key in OpenSSH 8.8",
+ "excerpt":"前言 最近在修改公司的 jenkins CI/CD 架構,Dockerize 我們的 Android Building Environment。 在我啟動 Debian 12 container 來建構我的環境時,配置 RSA Key 到公司的 GitLab server,卻無法抓取 source code,故有了這篇文章希望未來有遇到可以拿出來快速解決問題,也希望幫助到遇到一樣問題的人。 經過分析後才發現,原來 Debian 12 預設使用 OpenSSH 8.8,而 OpenSSH 8.8 預設將 RSA 加密算法關閉,因為安全是以及過時的問題 但公司 GitLab server 較舊,目前只支援較舊的 ssh Key 演算法 RSA,因此需要找方法使其支援。 準備作業 如果你已經有環境,可以跳過此段落 首先我先用 Docker 啟一台 Debian 12 的 container 如下...","categories": ["Cryptography","OpenSSH","Security"],
+ "tags": ["RSA Encryption","OpenSSH 8.8","Encryption Support"],
+ "url": "/blog/cryptography/openssh/security/how-to-enable-rsa-encryption-algorithm-key-in-openssh-8.8/",
+ "teaser": "/blog/assets/images/rsa-algorithm.jpg"
+ },{
+ "title": "Design Pattern (10) - Singleton Pattern (單例模式)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 需求 我們收到了一個需求:開發一個應用程式,該應用程式需要與資料庫進行頻繁的交互。為了確保資料庫連接的效率和資源的合理使用,我們需要設計一個系統來管理資料庫連接。 物件導向分析 (OOA) 理解需求後,讓我們來快速實作物件導向分析吧! 我們有 CRUD 四個 function 以及 constructor 用來建立 DatabaseClient 察覺 Forces 來看看上面這樣的設計會有哪些問題 資源管理:多個資料庫連接會消耗大量資源,導致性能下降。 一致性:需要確保所有資料庫操作使用相同的連接,以避免數據不一致。 效率:頻繁創建和銷毀資料庫連接會降低系統效率。 套用 Singleton Pattern ( Solution ) 得到新的 Context ( Resulting Context ) 做完 OOA,察覺 Forces,看清楚整個 Context 後,就可以來套用 Singleton Pattern 解決這個問題 先來看一下 Singleton Pattern 的...","categories": ["Design Pattern"],
+ "tags": ["Singleton Pattern"],
+ "url": "/blog/design%20pattern/design-pattern-10-singleton-pattern/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ },{
+ "title": "Jenkins (1) - 什麼是 Jenkins",
+ "excerpt":"什麼是 Jenkins Jenkins 是一個開源的自動化伺服器,主要用於實現持續整合(CI)和持續交付(CD)。它能夠自動化各種任務,包括建置、測試和部署軟體,從而幫助開發團隊提升效率和品質。 為什麼選擇 Jenkins 開源且免費:Jenkins 是一個開源專案,任何人都可以免費使用和修改。 豐富的插件生態系統:Jenkins 擁有超過 1,500 個插件,能夠擴展其功能以滿足不同的需求。 社群支持:Jenkins 擁有一個活躍的社群,提供豐富的資源和支援。 易於整合:Jenkins 可以與多種工具和平台整合,如 Git、Docker、Kubernetes 等。 Jenkins 的核心概念 Pipeline:Jenkins Pipeline 是一套插件,支持實現和集成持續交付流水線。Pipeline 用程式碼來定義整個建置過程,包括建置、測試和部署。 Node:Node 是 Jenkins 執行工作的機器,可以是 Jenkins 主伺服器或其他代理伺服器。 Job:Job 是 Jenkins 中的基本建置單位,定義了具體的建置、測試和部署任務。 Executor:Executor 是 Jenkins 用來執行 Job 的工作單元,每個 Node 可以有多個 Executor。 總結 Jenkins 是一個功能強大且靈活的自動化伺服器,能夠幫助開發團隊實現持續整合和持續交付。通過使用 Jenkins,團隊可以顯著提高開發效率和軟體品質。如果你還沒有使用 Jenkins,現在就是開始的好時機! 想了解更多關於 Jenkins...","categories": ["DevOps"],
+ "tags": ["Jenkins","CI/CD","DevOps"],
+ "url": "/blog/devops/jenkins-1-what-is-jenkins/",
+ "teaser": "/blog/assets/images/jenkins.jpg"
+ },{
+ "title": "Jenkins (2) - 如何架設 Jenkins 伺服器",
+ "excerpt":"如何架設 Jenkins 伺服器 在這篇文章中,我們將介紹如何使用 Docker 映像檔來架設 Jenkins 伺服器。這種方法不僅簡單快捷,還能確保環境的一致性。 步驟一:拉取 Docker 映像檔 首先,我們需要從 GitHub Container Registry 拉取 Jenkins 的 Docker 映像檔。打開終端機並執行以下指令: docker pull jenkins/jenkins:lts-jdk17 # 單純 jenkins 環境 or docker pull ghcr.io/nickhuangcyh/docker-jenkins-and-android-env:v1.0.0-jdk17 # jenkins 環境 + Android 建構環境 步驟二:運行 Jenkins 容器 接下來,我們將運行 Jenkins 容器。請確保替換 ${volume path} 為你希望 Jenkins 資料儲存的本地路徑。執行以下指令: docker run...","categories": ["DevOps"],
+ "tags": ["Jenkins","CI/CD","DevOps","Docker"],
+ "url": "/blog/devops/jenkins-2-how-to-setup-jenkins-server/",
+ "teaser": "/blog/assets/images/jenkins.jpg"
+ },{
+ "title": "Jenkins (3) - 如何配置 Credentials 以透過 SSH 從 git 上拉取程式碼",
+ "excerpt":"如何配置 Credentials 以透過 SSH 從 git 上拉取程式碼 在這篇文章中,我們將介紹如何在 Jenkins 中配置憑證(Credentials),以便 Jenkins 能夠透過 SSH 安全地從版本控制系統(如 GitHub 或 GitLab)拉取程式碼。 步驟一:生成 SSH 金鑰 首先,我們需要生成一對 SSH 金鑰。打開終端機並執行以下指令: ssh-keygen -t rsa -b 4096 -C \"your_email@example.com\" 按照提示完成金鑰生成過程,並記下生成的公鑰和私鑰的路徑。 步驟二:將公鑰添加到版本控制系統 將生成的公鑰內容複製並添加到你的版本控制系統中。例如,在 GitHub 中,你可以按照以下步驟操作: 登入 GitHub,進入「Settings」。 在左側菜單中選擇「SSH and GPG keys」。 點擊「New SSH key」,並將公鑰內容貼上,然後點擊「Add SSH key」。 步驟三:在 Jenkins 中添加憑證 打開...","categories": ["DevOps"],
+ "tags": ["Jenkins","CI/CD","DevOps","Credentials","SSH"],
+ "url": "/blog/devops/jenkins-3-configure-credentials-ssh/",
+ "teaser": "/blog/assets/images/jenkins.jpg"
+ },{
+ "title": "Google AdSense",
+ "excerpt":"前言 我平時喜歡研究各種不同的技術,最近在想如何一邊分享技術幫助他人,一邊又能獲得一些收益用來再投入其他 Side Project 上,我還是想把我的內容免費提供給需要幫助的開發者,所以想採用置入一些廣告在網頁上的方式我想比較合適 什麼是 Google AdSense? Google AdSense 是一個廣告推送平台,讓網站擁有者可以在自己的網站上展示與內容相關的廣告,並透過點擊或展示量賺取收益。這是一種被動收入的好方式,適合部落客、內容創作者或網站管理員。 為什麼選擇 Google AdSense? 免費使用:註冊與使用 AdSense 完全免費。 自動化廣告投放:系統會自動根據您的網站內容匹配相關廣告。 多樣化廣告形式:可選擇文字、圖片、影片等多種形式的廣告。 透明收益報告:提供詳細的報表分析,幫助您了解廣告效益。 開始使用 Google AdSense 的步驟 1. 註冊 AdSense 帳戶 前往 Google AdSense 官方網站。 使用您的 Google 帳號登入並申請 AdSense 帳戶。 進入 AdSense 主頁面 2. 輸入資訊 點擊”輸入資訊”提供資訊 填寫你的網站 domain、國家以及接受協議 3. 選擇廣告呈現樣式 點擊”探索”廣告在網站上的呈現模樣,並選擇 4. 將...","categories": ["Google"],
+ "tags": ["AdSense"],
+ "url": "/blog/google/google-adsense/",
+ "teaser": "/blog/assets/images/google_adsense.jpg"
+ },{
+ "title": "Design Pattern (11) - Adapter Pattern (轉接器模式)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 需求 我們收到了一個需求:公司現有的 股票數據系統 使用 XML 格式 存儲與傳遞數據,而新引入的 第三方股票分析系統 僅支援 JSON 格式。為了整合兩個系統,我們需要設計一個解決方案,使得現有數據可以被第三方分析系統正確接收和處理。 物件導向分析 (OOA) 理解需求後,讓我們來快速實作物件導向分析吧! 察覺 Forces 在未使用設計模式的情況下,上述程式碼可以運行,但存在以下問題: 責任分散: Client 負責數據轉換,這違反了單一職責原則(SRP)。 一旦轉換邏輯變複雜,Client 的程式碼將變得難以維護。 重複性高: 如果其他系統需要同樣的轉換邏輯,程式碼將無法重複使用,導致重複性問題。 耦合性高: Client 必須了解 XmlStockData 與 JsonAnalyzer 的具體實現細節,導致高耦合性。 未來若資料來源或目標格式改變,Client 必須大幅修改。 無法適應變化: 若引入更多資料格式(如 CSV 或 YAML),每種格式都需要在 Client 中實現轉換邏輯,難以擴展。 套用 Adapter Pattern...","categories": ["Design Pattern"],
+ "tags": ["Adapter Pattern"],
+ "url": "/blog/design%20pattern/design-pattern-11-adapter-pattern/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ },{
+ "title": "Design Pattern (12) - Bridge Pattern (橋接模式)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 需求 我們收到了一個需求:公司現有的 保全系統,在偵測到不同類型的事件(如火警、竊盜警鈴)時,需要以多種通知方式向用戶發送警報訊息。支援的通知方式包括: APNS (Apple iOS Push) FCM (Google Android Push) Email SMS 警報事件則可能包括: Fire (火警) Burglar (竊盜警鈴) 物件導向分析 (OOA) 理解需求後,讓我們來快速實作物件導向分析吧! 察覺 Forces 在未使用設計模式的情況下,上述程式碼可以運行,但存在以下問題: 高耦合性 (Tight Coupling): 警報類型 和 通知方式 被緊密地耦合在一起,這使得每次新增警報類型或通知方式時,都必須在多個類別中進行修改。 系統的維護成本較高,每個新需求都可能導致代碼的重構。 難以擴展 (Difficulty in Extending): 每增加一種新的警報類型或通知方式,都需要在每個組合中創建新的類別,導致代碼增長迅速。 如果需求變更(例如新增一種新的通知方式或警報類型),則需要修改大量的程式碼。 重複代碼 (Code Duplication): 由於每一種通知方式與警報事件的組合都需要實現一個具體的類別,導致了大量重複代碼,增加了程式碼維護的困難。 靈活性差...","categories": ["Design Pattern"],
+ "tags": ["Bridge Pattern"],
+ "url": "/blog/design%20pattern/design-pattern-12-bridge-pattern/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ },{
+ "title": "Jenkins (3) - 如何配置 Credentials 以透過 SSH 從 git 上拉取程式碼",
+ "excerpt":"如何配置 Credentials 以透過 SSH 從 git 上拉取程式碼 在這篇文章中,我們將介紹如何在 Jenkins 中配置憑證(Credentials),以便 Jenkins 能夠透過 SSH 安全地從版本控制系統(如 GitHub 或 GitLab)拉取程式碼。 步驟一:生成 SSH 金鑰 首先,我們需要生成一對 SSH 金鑰。打開終端機並執行以下指令: ssh-keygen -t rsa -b 4096 -C \"your_email@example.com\" 按照提示完成金鑰生成過程,並記下生成的公鑰和私鑰的路徑。 步驟二:將公鑰添加到版本控制系統 將生成的公鑰內容複製並添加到你的版本控制系統中。例如,在 GitHub 中,你可以按照以下步驟操作: 登入 GitHub,進入「Settings」。 在左側菜單中選擇「SSH and GPG keys」。 點擊「New SSH key」,並將公鑰內容貼上,然後點擊「Add SSH key」。 步驟三:在 Jenkins 中添加憑證 打開...","categories": ["DevOps"],
+ "tags": ["Jenkins","CI/CD","DevOps","Credentials","SSH"],
+ "url": "/blog/devops/jenkins-3-configure-credentials-ssh/",
+ "teaser": "/blog/assets/images/jenkins.jpg"
+ },{
+ "title": "Design Pattern (13) - Composite Pattern (組合模式)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 需求 我們收到了一個需求:實作一個檔案系統,其目錄可以包含檔案或子目錄,並且需要提供統一的操作介面來列出目錄內容。此系統應支援以下功能: 支援樹狀結構的表示。 可操作單一檔案和目錄。 新增檔案或目錄時無需大幅修改現有程式碼。 物件導向分析 (OOA) 理解需求後,讓我們來快速實作物件導向分析吧! 察覺 Forces 在未使用設計模式的情況下,上述需求可能會遇到以下問題: 高耦合性 (Tight Coupling): 單一檔案和目錄集合的操作邏輯分散在多個類別中,導致系統維護困難。 重複代碼 (Code Duplication): 每次操作目錄內容時,需分別處理檔案與子目錄,導致相似邏輯多處重複。 難以擴展 (Difficulty in Extending): 新增檔案或目錄類型時,需大幅修改程式碼,影響系統穩定性。 靈活性差 (Lack of Flexibility): 操作層需清楚區分單一檔案與目錄集合,增加程式碼複雜度。 套用 Composite Pattern ( Solution ) 得到新的 Context ( Resulting Context ) 做完 OOA,察覺...","categories": ["Design Pattern"],
+ "tags": ["Composite Pattern"],
+ "url": "/blog/design%20pattern/design-pattern-13-composite-pattern/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ },{
+ "title": "Design Pattern (14) - Decorator Pattern (裝飾者模式)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 需求 我們收到了一個需求:咖啡店的 POS 系統需要計算不同咖啡及其附加選項(如牛奶、糖漿、奶泡等)的價格。具體需求如下: 咖啡種類包括基本款的 Espresso 和 House Blend。 每種咖啡都可以加不同的附加項,例如牛奶、巧克力糖漿、奶泡。 系統應該支持動態組合不同的附加項,而不需要針對每種組合定義類別。 物件導向分析 (OOA) 理解需求後,讓我們來快速實作物件導向分析吧! 察覺 Forces 在未使用設計模式的情況下,上述需求可能會遇到以下問題: 類別爆炸 (Class Explosion): 為每一種咖啡及其附加選項組合創建類別,導致類別數量迅速增長。 高耦合性 (Tight Coupling): 咖啡與附加選項緊密耦合,修改某一部分時可能影響整體。 靈活性差 (Lack of Flexibility): 系統無法動態地添加或移除附加選項,只能依賴預先定義的組合。 重複代碼 (Code Duplication): 每種組合的實作邏輯重複,導致維護困難。 套用 Decorator Pattern (Solution) 得到新的 Context (Resulting Context) 做完...","categories": ["Design Pattern"],
+ "tags": ["Decorator Pattern"],
+ "url": "/blog/design%20pattern/design-pattern-14-decorator-pattern/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ },{
+ "title": "Design Pattern (15) - Facade Pattern (外觀模式)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 需求 假設我們正在開發一個家庭影院系統,該系統包含以下子系統: DVD 播放器 環繞音響 燈光 投影機 用戶希望能輕鬆開啟或關閉家庭影院的所有功能,而不需要逐一操作各個設備。 物件導向分析 (OOA) 理解需求後,讓我們來快速實作物件導向分析吧! 察覺 Forces 在設計階段,我們注意到以下設計難題: 子系統過於複雜:需要多個步驟才能完成操作。 操作繁瑣:用戶需要熟悉每個子系統的細節。 缺乏一致性:不同子系統之間的操作方式可能不同,導致混亂。 這些 Forces 驅使我們採用外觀模式來簡化介面,減少系統的操作複雜度。 套用 Facade Pattern (Solution) 得到新的 Context (Resulting Context) 做完 OOA,察覺 Forces,看清楚整個 Context 後,就可以來套用 Facade Pattern 解決這個問題。 先來看一下 Facade Pattern 的 UML: Subsystems (子系統):表示系統中的一組類別或模組,它們各自負責不同的功能。例如,在家庭影院系統中,包括...","categories": ["Design Pattern"],
+ "tags": ["Facade Pattern"],
+ "url": "/blog/design%20pattern/design-pattern-15-facade-pattern/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ },{
+ "title": "Design Pattern (16) - Flyweight Pattern (享元模式)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 需求 假設我們正在開發一個森林場景的渲染系統,該系統需要顯示數百棵甚至數千棵樹木。 每棵樹包含兩類資料: 內部狀態 (Intrinsic State):不隨環境改變的資料,例如樹的種類、顏色、紋理等。 外部狀態 (Extrinsic State):因環境而異的資料,例如樹的座標 (x, y)。 如果為每棵樹都建立完整的物件,將導致記憶體消耗過大。因此,我們需要一種共享內部狀態的方式來優化記 物件導向分析 (OOA) 理解需求後,讓我們來快速實作物件導向分析吧! 察覺 Forces 在設計階段,我們注意到以下設計難題: 大量重複資料:每棵樹都包含相同的種類、顏色和紋理資料。 性能問題:對於數千棵樹的場景渲染,過多的物件會導致記憶體不足或性能瓶頸。 共享與獨立的平衡:如何在共享資料的同時,保留每棵樹的獨立外部狀態。 為解決這些問題,我們採用了享元模式。 套用 Flyweight Pattern (Solution) 得到新的 Context (Resulting Context) 做完 OOA,察覺 Forces,看清楚整個 Context 後,就可以來套用 Flyweight Pattern 解決這個問題。 先來看一下 flyweight Pattern 的 UML:...","categories": ["Design Pattern"],
+ "tags": ["Flyweight Pattern"],
+ "url": "/blog/design%20pattern/design-pattern-16-flyweight-pattern/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ },{
+ "title": "Design Pattern (17) - Proxy Pattern (代理模式)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 需求 我們的任務是建立一個影片播放系統,需求如下: 應用能播放多個影片,但避免每次都重複下載相同的影片。 影片需要在用戶第一次訪問時下載,之後從快取中取得以節省資源。 提供一個透明的介面,無需讓客戶端知道影片是透過代理取得的。 物件導向分析 (OOA) 理解需求後,讓我們來快速實作物件導向分析吧! 察覺 Forces 在未使用設計模式的情況下,我們可能面臨以下挑戰: 高頻寬消耗 (High Bandwidth Usage): 如果每次播放影片都重新下載,將導致不必要的頻寬浪費。 延遲時間 (High Latency): 每次下載影片會增加播放前的等待時間,影響用戶體驗。 客戶端耦合 (Client Coupling): 如果客戶端需要處理影片的下載邏輯,會增加不必要的複雜性。 套用 Proxy Pattern (Solution) 得到新的 Context (Resulting Context) 做完 OOA,察覺 Forces,看清楚整個 Context 後,就可以來套用 Proxy Pattern 解決這個問題。 Proxy Pattern 提供了解決方案,通過引入...","categories": ["Design Pattern"],
+ "tags": ["Proxy Pattern"],
+ "url": "/blog/design%20pattern/design-pattern-17-proxy-pattern/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ },{
+ "title": "Design Pattern (18) - Chain of Responsibility Pattern (責任鏈模式)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 需求 我們的任務是建立一個日誌處理系統,需求如下: 系統支持多層次日誌處理(如 Console、File、Database 等)。 請求可以被多個處理器處理,且處理器的組合應具備動態調整能力。 確保每層處理器的責任彼此獨立,並能擴展新處理器而不影響既有邏輯。 物件導向分析 (OOA) 理解需求後,讓我們來快速實作物件導向分析吧! 察覺 Forces 在未使用設計模式的情況下,我們可能面臨以下挑戰: 高耦合性 (High Coupling): 如果客戶端需要直接控制每個日誌處理器,將導致代碼過於複雜且難以維護。 缺乏靈活性 (Lack of Flexibility): 無法輕鬆地調整處理器的執行順序或新增處理器。 違反開放關閉原則 (Violates OCP): 若需支持新的日誌處理方式,必須修改客戶端邏輯,導致系統穩定性下降。 套用 Chain of Responsibility Pattern (Solution) 得到新的 Context (Resulting Context) 先來看一下 Chain of Responsibility Pattern 的 UML:...","categories": ["Design Pattern"],
+ "tags": ["Chain of Responsibility Pattern"],
+ "url": "/blog/design%20pattern/design-pattern-18-chain-of-responsibility-pattern/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ },{
+ "title": "Design Pattern (19) - Command Pattern (命令模式)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 需求 我們需要一個音樂播放器控制系統,需求如下: 使用者可以透過遙控器控制音樂播放器執行「播放」、「暫停」和「停止」操作。 支援撤銷 (Undo) 功能,例如撤銷暫停會恢復播放。 按鈕行為應保持靈活,方便未來擴充新功能,例如「下一首」或「重播」。 物件導向分析 (OOA) 理解需求後,讓我們來快速實作物件導向分析吧! 察覺 Forces 在未使用設計模式的情況下,我們可能面臨以下挑戰: 高耦合性 (High Coupling): 客戶端需要直接操作每個具體設備的功能,導致耦合度過高,不利於系統擴展。 缺乏靈活性 (Lack of Flexibility): 如果需要新增設備或操作,客戶端需要修改大量程式碼,增加了維護成本。 撤銷/重做困難 (Undo/Redo Complexity): 系統沒有統一的方式處理操作歷史,導致撤銷和重做功能難以實現。 套用 Command Pattern (Solution) 得到新的 Context (Resulting Context) 做完 OOA,察覺 Forces,看清楚整個 Context 後,就可以來套用 Command Pattern 解決這個問題。 先來看一下...","categories": ["Design Pattern"],
+ "tags": ["Command Pattern"],
+ "url": "/blog/design%20pattern/design-pattern-19-command-pattern/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ },{
+ "title": "Design Pattern (20) - Iterator Pattern (迭代器模式)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 需求 我們的任務是設計一個檔案系統搜尋工具,需求如下: 使用者可以選擇不同的檔案搜尋方式,例如 廣度優先搜尋 (BFS) 或 深度優先搜尋 (DFS)。 客戶端不需要關心搜尋邏輯的實現細節,只需使用統一的迭代器介面來遍歷搜尋結果。 系統需要具備擴展性,方便新增其他搜尋法,例如基於檔案大小排序的搜尋。 物件導向分析 (OOA) 理解需求後,讓我們來快速實作物件導向分析吧! 察覺 Forces 在未使用設計模式的情況下,我們可能面臨以下挑戰: 高耦合性 (High Coupling): 客戶端需要直接操作每種搜尋方式的實現細節,導致代碼臃腫且難以維護。 缺乏一致性 (Lack of Consistency): 不同搜尋方式的結果訪問方式可能不一致。 違反開放關閉原則 (Violates OCP): 若新增搜尋法或更改現有搜尋邏輯,需要修改客戶端程式碼。 套用 Iterator Pattern (Solution) 得到新的 Context (Resulting Context) 做完 OOA,察覺 Forces,看清楚整個 Context 後,就可以來套用 Iterator...","categories": ["Design Pattern"],
+ "tags": ["Iterator Pattern"],
+ "url": "/blog/design%20pattern/design-pattern-20-iterator-pattern/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ },{
+ "title": "Design Pattern (21) - Mediator Pattern (中介者模式)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 需求 我們的任務是設計一個 聊天室應用程式,需求如下: 使用者可以透過聊天室傳遞訊息。 每個使用者都不需要直接管理其他使用者的資訊。 新增或移除使用者不應影響其他使用者的運作。 物件導向分析 (OOA) 理解需求後,我們來快速分析: 若使用者彼此直接通信,會導致複雜的相依關係,增加維護成本。 我們需要一個集中管理的角色,來協調使用者之間的訊息傳遞。 察覺 Forces 在未使用設計模式的情況下,我們可能面臨以下挑戰: 高耦合性 (High Coupling): 使用者彼此之間直接通信,導致新增或移除使用者時需修改多處程式碼。 難以擴展 (Hard to Extend): 若要增加新功能(如訊息過濾或廣播機制),需要修改多個使用者的邏輯。 複雜度上升 (Increased Complexity): 使用者之間的關聯數量隨著使用者數量增長呈指數級增加。 套用 Mediator Pattern (Solution) 得到新的 Context (Resulting Context) 做完 OOA,察覺 Forces,看清楚整個 Context 後,就可以來套用 Mediator Pattern 解決這個問題。...","categories": ["Design Pattern"],
+ "tags": ["Mediator Pattern"],
+ "url": "/blog/design%20pattern/design-pattern-21-mediator-pattern/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ },{
+ "title": "Design Pattern (22) - Memento Pattern (備忘錄模式)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 需求 我們的任務是設計一個文字編輯器,需求如下: 使用者可以輸入文字,並隨時按下 Ctrl+Z 回復上一步。 系統需要保存歷史狀態以供回復。 客戶端不需要了解狀態保存的實現細節,只需使用一個簡單的回復操作即可。 物件導向分析 (OOA) 理解需求後,讓我們來快速實作物件導向分析吧! 察覺 Forces 在未使用設計模式的情況下,我們可能面臨以下挑戰: 資料喪失風險 (Data Loss Risk): 如果我們僅保留當前狀態,將無法回復到之前的狀態。 高耦合性 (High Coupling): 客戶端需要直接操作狀態管理邏輯,導致複雜性增加。 難以擴展 (Hard to Extend): 新增功能或改變狀態保存方式時,可能需要修改大量程式碼。 套用 Memento Pattern (Solution) 得到新的 Context (Resulting Context) 做完 OOA,察覺 Forces,看清楚整個 Context 後,就可以來套用 Memento Pattern 解決這個問題...","categories": ["Design Pattern"],
+ "tags": ["Memento Pattern"],
+ "url": "/blog/design%20pattern/design-pattern-22-memento-pattern/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ },{
+ "title": "Design Pattern (23) - Observer Pattern (觀察者模式)",
+ "excerpt":"您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。 需求 我們的任務是設計一個 安全系統主機 (Panel),需求如下: 主機負責監控不同的感測器,例如煙霧探測器或門窗感測器。 當警報觸發時,主機需要通知所有已註冊的設備,例如平板、iOS 和 Android 手機。 設備可以動態地加入或移除通知清單。 物件導向分析 (OOA) 理解需求後,讓我們來快速實作物件導向分析吧! 察覺 Forces 在未使用設計模式的情況下,我們可能面臨以下挑戰: 高耦合性 (High Coupling) 如果主機直接與每一個設備互動,程式碼會變得難以維護,每次新增或移除設備都需要修改主機邏輯。 缺乏彈性 (Lack of Flexibility) 新增設備需要修改現有程式碼,違反開放關閉原則 (OCP)。 通知不一致 (Inconsistent Notifications) 當警報觸發時,難以確保每個設備都能正確接收到通知。 套用 Observer Pattern (Solution) 得到新的 Context (Resulting Context) 做完 OOA,察覺 Forces,看清楚整個 Context 後,就可以來套用...","categories": ["Design Pattern"],
+ "tags": ["Observer Pattern"],
+ "url": "/blog/design%20pattern/design-pattern-23-observer-pattern/",
+ "teaser": "/blog/assets/images/design_patterns.jpg"
+ }]
diff --git a/assets/js/lunr/lunr.js b/assets/js/lunr/lunr.js
new file mode 100644
index 0000000..6aa370f
--- /dev/null
+++ b/assets/js/lunr/lunr.js
@@ -0,0 +1,3475 @@
+/**
+ * lunr - http://lunrjs.com - A bit like Solr, but much smaller and not as bright - 2.3.9
+ * Copyright (C) 2020 Oliver Nightingale
+ * @license MIT
+ */
+
+;(function(){
+
+/**
+ * A convenience function for configuring and constructing
+ * a new lunr Index.
+ *
+ * A lunr.Builder instance is created and the pipeline setup
+ * with a trimmer, stop word filter and stemmer.
+ *
+ * This builder object is yielded to the configuration function
+ * that is passed as a parameter, allowing the list of fields
+ * and other builder parameters to be customised.
+ *
+ * All documents _must_ be added within the passed config function.
+ *
+ * @example
+ * var idx = lunr(function () {
+ * this.field('title')
+ * this.field('body')
+ * this.ref('id')
+ *
+ * documents.forEach(function (doc) {
+ * this.add(doc)
+ * }, this)
+ * })
+ *
+ * @see {@link lunr.Builder}
+ * @see {@link lunr.Pipeline}
+ * @see {@link lunr.trimmer}
+ * @see {@link lunr.stopWordFilter}
+ * @see {@link lunr.stemmer}
+ * @namespace {function} lunr
+ */
+var lunr = function (config) {
+ var builder = new lunr.Builder
+
+ builder.pipeline.add(
+ lunr.trimmer,
+ lunr.stopWordFilter,
+ lunr.stemmer
+ )
+
+ builder.searchPipeline.add(
+ lunr.stemmer
+ )
+
+ config.call(builder, builder)
+ return builder.build()
+}
+
+lunr.version = "2.3.9"
+/*!
+ * lunr.utils
+ * Copyright (C) 2020 Oliver Nightingale
+ */
+
+/**
+ * A namespace containing utils for the rest of the lunr library
+ * @namespace lunr.utils
+ */
+lunr.utils = {}
+
+/**
+ * Print a warning message to the console.
+ *
+ * @param {String} message The message to be printed.
+ * @memberOf lunr.utils
+ * @function
+ */
+lunr.utils.warn = (function (global) {
+ /* eslint-disable no-console */
+ return function (message) {
+ if (global.console && console.warn) {
+ console.warn(message)
+ }
+ }
+ /* eslint-enable no-console */
+})(this)
+
+/**
+ * Convert an object to a string.
+ *
+ * In the case of `null` and `undefined` the function returns
+ * the empty string, in all other cases the result of calling
+ * `toString` on the passed object is returned.
+ *
+ * @param {Any} obj The object to convert to a string.
+ * @return {String} string representation of the passed object.
+ * @memberOf lunr.utils
+ */
+lunr.utils.asString = function (obj) {
+ if (obj === void 0 || obj === null) {
+ return ""
+ } else {
+ return obj.toString()
+ }
+}
+
+/**
+ * Clones an object.
+ *
+ * Will create a copy of an existing object such that any mutations
+ * on the copy cannot affect the original.
+ *
+ * Only shallow objects are supported, passing a nested object to this
+ * function will cause a TypeError.
+ *
+ * Objects with primitives, and arrays of primitives are supported.
+ *
+ * @param {Object} obj The object to clone.
+ * @return {Object} a clone of the passed object.
+ * @throws {TypeError} when a nested object is passed.
+ * @memberOf Utils
+ */
+lunr.utils.clone = function (obj) {
+ if (obj === null || obj === undefined) {
+ return obj
+ }
+
+ var clone = Object.create(null),
+ keys = Object.keys(obj)
+
+ for (var i = 0; i < keys.length; i++) {
+ var key = keys[i],
+ val = obj[key]
+
+ if (Array.isArray(val)) {
+ clone[key] = val.slice()
+ continue
+ }
+
+ if (typeof val === 'string' ||
+ typeof val === 'number' ||
+ typeof val === 'boolean') {
+ clone[key] = val
+ continue
+ }
+
+ throw new TypeError("clone is not deep and does not support nested objects")
+ }
+
+ return clone
+}
+lunr.FieldRef = function (docRef, fieldName, stringValue) {
+ this.docRef = docRef
+ this.fieldName = fieldName
+ this._stringValue = stringValue
+}
+
+lunr.FieldRef.joiner = "/"
+
+lunr.FieldRef.fromString = function (s) {
+ var n = s.indexOf(lunr.FieldRef.joiner)
+
+ if (n === -1) {
+ throw "malformed field ref string"
+ }
+
+ var fieldRef = s.slice(0, n),
+ docRef = s.slice(n + 1)
+
+ return new lunr.FieldRef (docRef, fieldRef, s)
+}
+
+lunr.FieldRef.prototype.toString = function () {
+ if (this._stringValue == undefined) {
+ this._stringValue = this.fieldName + lunr.FieldRef.joiner + this.docRef
+ }
+
+ return this._stringValue
+}
+/*!
+ * lunr.Set
+ * Copyright (C) 2020 Oliver Nightingale
+ */
+
+/**
+ * A lunr set.
+ *
+ * @constructor
+ */
+lunr.Set = function (elements) {
+ this.elements = Object.create(null)
+
+ if (elements) {
+ this.length = elements.length
+
+ for (var i = 0; i < this.length; i++) {
+ this.elements[elements[i]] = true
+ }
+ } else {
+ this.length = 0
+ }
+}
+
+/**
+ * A complete set that contains all elements.
+ *
+ * @static
+ * @readonly
+ * @type {lunr.Set}
+ */
+lunr.Set.complete = {
+ intersect: function (other) {
+ return other
+ },
+
+ union: function () {
+ return this
+ },
+
+ contains: function () {
+ return true
+ }
+}
+
+/**
+ * An empty set that contains no elements.
+ *
+ * @static
+ * @readonly
+ * @type {lunr.Set}
+ */
+lunr.Set.empty = {
+ intersect: function () {
+ return this
+ },
+
+ union: function (other) {
+ return other
+ },
+
+ contains: function () {
+ return false
+ }
+}
+
+/**
+ * Returns true if this set contains the specified object.
+ *
+ * @param {object} object - Object whose presence in this set is to be tested.
+ * @returns {boolean} - True if this set contains the specified object.
+ */
+lunr.Set.prototype.contains = function (object) {
+ return !!this.elements[object]
+}
+
+/**
+ * Returns a new set containing only the elements that are present in both
+ * this set and the specified set.
+ *
+ * @param {lunr.Set} other - set to intersect with this set.
+ * @returns {lunr.Set} a new set that is the intersection of this and the specified set.
+ */
+
+lunr.Set.prototype.intersect = function (other) {
+ var a, b, elements, intersection = []
+
+ if (other === lunr.Set.complete) {
+ return this
+ }
+
+ if (other === lunr.Set.empty) {
+ return other
+ }
+
+ if (this.length < other.length) {
+ a = this
+ b = other
+ } else {
+ a = other
+ b = this
+ }
+
+ elements = Object.keys(a.elements)
+
+ for (var i = 0; i < elements.length; i++) {
+ var element = elements[i]
+ if (element in b.elements) {
+ intersection.push(element)
+ }
+ }
+
+ return new lunr.Set (intersection)
+}
+
+/**
+ * Returns a new set combining the elements of this and the specified set.
+ *
+ * @param {lunr.Set} other - set to union with this set.
+ * @return {lunr.Set} a new set that is the union of this and the specified set.
+ */
+
+lunr.Set.prototype.union = function (other) {
+ if (other === lunr.Set.complete) {
+ return lunr.Set.complete
+ }
+
+ if (other === lunr.Set.empty) {
+ return this
+ }
+
+ return new lunr.Set(Object.keys(this.elements).concat(Object.keys(other.elements)))
+}
+/**
+ * A function to calculate the inverse document frequency for
+ * a posting. This is shared between the builder and the index
+ *
+ * @private
+ * @param {object} posting - The posting for a given term
+ * @param {number} documentCount - The total number of documents.
+ */
+lunr.idf = function (posting, documentCount) {
+ var documentsWithTerm = 0
+
+ for (var fieldName in posting) {
+ if (fieldName == '_index') continue // Ignore the term index, its not a field
+ documentsWithTerm += Object.keys(posting[fieldName]).length
+ }
+
+ var x = (documentCount - documentsWithTerm + 0.5) / (documentsWithTerm + 0.5)
+
+ return Math.log(1 + Math.abs(x))
+}
+
+/**
+ * A token wraps a string representation of a token
+ * as it is passed through the text processing pipeline.
+ *
+ * @constructor
+ * @param {string} [str=''] - The string token being wrapped.
+ * @param {object} [metadata={}] - Metadata associated with this token.
+ */
+lunr.Token = function (str, metadata) {
+ this.str = str || ""
+ this.metadata = metadata || {}
+}
+
+/**
+ * Returns the token string that is being wrapped by this object.
+ *
+ * @returns {string}
+ */
+lunr.Token.prototype.toString = function () {
+ return this.str
+}
+
+/**
+ * A token update function is used when updating or optionally
+ * when cloning a token.
+ *
+ * @callback lunr.Token~updateFunction
+ * @param {string} str - The string representation of the token.
+ * @param {Object} metadata - All metadata associated with this token.
+ */
+
+/**
+ * Applies the given function to the wrapped string token.
+ *
+ * @example
+ * token.update(function (str, metadata) {
+ * return str.toUpperCase()
+ * })
+ *
+ * @param {lunr.Token~updateFunction} fn - A function to apply to the token string.
+ * @returns {lunr.Token}
+ */
+lunr.Token.prototype.update = function (fn) {
+ this.str = fn(this.str, this.metadata)
+ return this
+}
+
+/**
+ * Creates a clone of this token. Optionally a function can be
+ * applied to the cloned token.
+ *
+ * @param {lunr.Token~updateFunction} [fn] - An optional function to apply to the cloned token.
+ * @returns {lunr.Token}
+ */
+lunr.Token.prototype.clone = function (fn) {
+ fn = fn || function (s) { return s }
+ return new lunr.Token (fn(this.str, this.metadata), this.metadata)
+}
+/*!
+ * lunr.tokenizer
+ * Copyright (C) 2020 Oliver Nightingale
+ */
+
+/**
+ * A function for splitting a string into tokens ready to be inserted into
+ * the search index. Uses `lunr.tokenizer.separator` to split strings, change
+ * the value of this property to change how strings are split into tokens.
+ *
+ * This tokenizer will convert its parameter to a string by calling `toString` and
+ * then will split this string on the character in `lunr.tokenizer.separator`.
+ * Arrays will have their elements converted to strings and wrapped in a lunr.Token.
+ *
+ * Optional metadata can be passed to the tokenizer, this metadata will be cloned and
+ * added as metadata to every token that is created from the object to be tokenized.
+ *
+ * @static
+ * @param {?(string|object|object[])} obj - The object to convert into tokens
+ * @param {?object} metadata - Optional metadata to associate with every token
+ * @returns {lunr.Token[]}
+ * @see {@link lunr.Pipeline}
+ */
+lunr.tokenizer = function (obj, metadata) {
+ if (obj == null || obj == undefined) {
+ return []
+ }
+
+ if (Array.isArray(obj)) {
+ return obj.map(function (t) {
+ return new lunr.Token(
+ lunr.utils.asString(t).toLowerCase(),
+ lunr.utils.clone(metadata)
+ )
+ })
+ }
+
+ var str = obj.toString().toLowerCase(),
+ len = str.length,
+ tokens = []
+
+ for (var sliceEnd = 0, sliceStart = 0; sliceEnd <= len; sliceEnd++) {
+ var char = str.charAt(sliceEnd),
+ sliceLength = sliceEnd - sliceStart
+
+ if ((char.match(lunr.tokenizer.separator) || sliceEnd == len)) {
+
+ if (sliceLength > 0) {
+ var tokenMetadata = lunr.utils.clone(metadata) || {}
+ tokenMetadata["position"] = [sliceStart, sliceLength]
+ tokenMetadata["index"] = tokens.length
+
+ tokens.push(
+ new lunr.Token (
+ str.slice(sliceStart, sliceEnd),
+ tokenMetadata
+ )
+ )
+ }
+
+ sliceStart = sliceEnd + 1
+ }
+
+ }
+
+ return tokens
+}
+
+/**
+ * The separator used to split a string into tokens. Override this property to change the behaviour of
+ * `lunr.tokenizer` behaviour when tokenizing strings. By default this splits on whitespace and hyphens.
+ *
+ * @static
+ * @see lunr.tokenizer
+ */
+lunr.tokenizer.separator = /[\s\-]+/
+/*!
+ * lunr.Pipeline
+ * Copyright (C) 2020 Oliver Nightingale
+ */
+
+/**
+ * lunr.Pipelines maintain an ordered list of functions to be applied to all
+ * tokens in documents entering the search index and queries being ran against
+ * the index.
+ *
+ * An instance of lunr.Index created with the lunr shortcut will contain a
+ * pipeline with a stop word filter and an English language stemmer. Extra
+ * functions can be added before or after either of these functions or these
+ * default functions can be removed.
+ *
+ * When run the pipeline will call each function in turn, passing a token, the
+ * index of that token in the original list of all tokens and finally a list of
+ * all the original tokens.
+ *
+ * The output of functions in the pipeline will be passed to the next function
+ * in the pipeline. To exclude a token from entering the index the function
+ * should return undefined, the rest of the pipeline will not be called with
+ * this token.
+ *
+ * For serialisation of pipelines to work, all functions used in an instance of
+ * a pipeline should be registered with lunr.Pipeline. Registered functions can
+ * then be loaded. If trying to load a serialised pipeline that uses functions
+ * that are not registered an error will be thrown.
+ *
+ * If not planning on serialising the pipeline then registering pipeline functions
+ * is not necessary.
+ *
+ * @constructor
+ */
+lunr.Pipeline = function () {
+ this._stack = []
+}
+
+lunr.Pipeline.registeredFunctions = Object.create(null)
+
+/**
+ * A pipeline function maps lunr.Token to lunr.Token. A lunr.Token contains the token
+ * string as well as all known metadata. A pipeline function can mutate the token string
+ * or mutate (or add) metadata for a given token.
+ *
+ * A pipeline function can indicate that the passed token should be discarded by returning
+ * null, undefined or an empty string. This token will not be passed to any downstream pipeline
+ * functions and will not be added to the index.
+ *
+ * Multiple tokens can be returned by returning an array of tokens. Each token will be passed
+ * to any downstream pipeline functions and all will returned tokens will be added to the index.
+ *
+ * Any number of pipeline functions may be chained together using a lunr.Pipeline.
+ *
+ * @interface lunr.PipelineFunction
+ * @param {lunr.Token} token - A token from the document being processed.
+ * @param {number} i - The index of this token in the complete list of tokens for this document/field.
+ * @param {lunr.Token[]} tokens - All tokens for this document/field.
+ * @returns {(?lunr.Token|lunr.Token[])}
+ */
+
+/**
+ * Register a function with the pipeline.
+ *
+ * Functions that are used in the pipeline should be registered if the pipeline
+ * needs to be serialised, or a serialised pipeline needs to be loaded.
+ *
+ * Registering a function does not add it to a pipeline, functions must still be
+ * added to instances of the pipeline for them to be used when running a pipeline.
+ *
+ * @param {lunr.PipelineFunction} fn - The function to check for.
+ * @param {String} label - The label to register this function with
+ */
+lunr.Pipeline.registerFunction = function (fn, label) {
+ if (label in this.registeredFunctions) {
+ lunr.utils.warn('Overwriting existing registered function: ' + label)
+ }
+
+ fn.label = label
+ lunr.Pipeline.registeredFunctions[fn.label] = fn
+}
+
+/**
+ * Warns if the function is not registered as a Pipeline function.
+ *
+ * @param {lunr.PipelineFunction} fn - The function to check for.
+ * @private
+ */
+lunr.Pipeline.warnIfFunctionNotRegistered = function (fn) {
+ var isRegistered = fn.label && (fn.label in this.registeredFunctions)
+
+ if (!isRegistered) {
+ lunr.utils.warn('Function is not registered with pipeline. This may cause problems when serialising the index.\n', fn)
+ }
+}
+
+/**
+ * Loads a previously serialised pipeline.
+ *
+ * All functions to be loaded must already be registered with lunr.Pipeline.
+ * If any function from the serialised data has not been registered then an
+ * error will be thrown.
+ *
+ * @param {Object} serialised - The serialised pipeline to load.
+ * @returns {lunr.Pipeline}
+ */
+lunr.Pipeline.load = function (serialised) {
+ var pipeline = new lunr.Pipeline
+
+ serialised.forEach(function (fnName) {
+ var fn = lunr.Pipeline.registeredFunctions[fnName]
+
+ if (fn) {
+ pipeline.add(fn)
+ } else {
+ throw new Error('Cannot load unregistered function: ' + fnName)
+ }
+ })
+
+ return pipeline
+}
+
+/**
+ * Adds new functions to the end of the pipeline.
+ *
+ * Logs a warning if the function has not been registered.
+ *
+ * @param {lunr.PipelineFunction[]} functions - Any number of functions to add to the pipeline.
+ */
+lunr.Pipeline.prototype.add = function () {
+ var fns = Array.prototype.slice.call(arguments)
+
+ fns.forEach(function (fn) {
+ lunr.Pipeline.warnIfFunctionNotRegistered(fn)
+ this._stack.push(fn)
+ }, this)
+}
+
+/**
+ * Adds a single function after a function that already exists in the
+ * pipeline.
+ *
+ * Logs a warning if the function has not been registered.
+ *
+ * @param {lunr.PipelineFunction} existingFn - A function that already exists in the pipeline.
+ * @param {lunr.PipelineFunction} newFn - The new function to add to the pipeline.
+ */
+lunr.Pipeline.prototype.after = function (existingFn, newFn) {
+ lunr.Pipeline.warnIfFunctionNotRegistered(newFn)
+
+ var pos = this._stack.indexOf(existingFn)
+ if (pos == -1) {
+ throw new Error('Cannot find existingFn')
+ }
+
+ pos = pos + 1
+ this._stack.splice(pos, 0, newFn)
+}
+
+/**
+ * Adds a single function before a function that already exists in the
+ * pipeline.
+ *
+ * Logs a warning if the function has not been registered.
+ *
+ * @param {lunr.PipelineFunction} existingFn - A function that already exists in the pipeline.
+ * @param {lunr.PipelineFunction} newFn - The new function to add to the pipeline.
+ */
+lunr.Pipeline.prototype.before = function (existingFn, newFn) {
+ lunr.Pipeline.warnIfFunctionNotRegistered(newFn)
+
+ var pos = this._stack.indexOf(existingFn)
+ if (pos == -1) {
+ throw new Error('Cannot find existingFn')
+ }
+
+ this._stack.splice(pos, 0, newFn)
+}
+
+/**
+ * Removes a function from the pipeline.
+ *
+ * @param {lunr.PipelineFunction} fn The function to remove from the pipeline.
+ */
+lunr.Pipeline.prototype.remove = function (fn) {
+ var pos = this._stack.indexOf(fn)
+ if (pos == -1) {
+ return
+ }
+
+ this._stack.splice(pos, 1)
+}
+
+/**
+ * Runs the current list of functions that make up the pipeline against the
+ * passed tokens.
+ *
+ * @param {Array} tokens The tokens to run through the pipeline.
+ * @returns {Array}
+ */
+lunr.Pipeline.prototype.run = function (tokens) {
+ var stackLength = this._stack.length
+
+ for (var i = 0; i < stackLength; i++) {
+ var fn = this._stack[i]
+ var memo = []
+
+ for (var j = 0; j < tokens.length; j++) {
+ var result = fn(tokens[j], j, tokens)
+
+ if (result === null || result === void 0 || result === '') continue
+
+ if (Array.isArray(result)) {
+ for (var k = 0; k < result.length; k++) {
+ memo.push(result[k])
+ }
+ } else {
+ memo.push(result)
+ }
+ }
+
+ tokens = memo
+ }
+
+ return tokens
+}
+
+/**
+ * Convenience method for passing a string through a pipeline and getting
+ * strings out. This method takes care of wrapping the passed string in a
+ * token and mapping the resulting tokens back to strings.
+ *
+ * @param {string} str - The string to pass through the pipeline.
+ * @param {?object} metadata - Optional metadata to associate with the token
+ * passed to the pipeline.
+ * @returns {string[]}
+ */
+lunr.Pipeline.prototype.runString = function (str, metadata) {
+ var token = new lunr.Token (str, metadata)
+
+ return this.run([token]).map(function (t) {
+ return t.toString()
+ })
+}
+
+/**
+ * Resets the pipeline by removing any existing processors.
+ *
+ */
+lunr.Pipeline.prototype.reset = function () {
+ this._stack = []
+}
+
+/**
+ * Returns a representation of the pipeline ready for serialisation.
+ *
+ * Logs a warning if the function has not been registered.
+ *
+ * @returns {Array}
+ */
+lunr.Pipeline.prototype.toJSON = function () {
+ return this._stack.map(function (fn) {
+ lunr.Pipeline.warnIfFunctionNotRegistered(fn)
+
+ return fn.label
+ })
+}
+/*!
+ * lunr.Vector
+ * Copyright (C) 2020 Oliver Nightingale
+ */
+
+/**
+ * A vector is used to construct the vector space of documents and queries. These
+ * vectors support operations to determine the similarity between two documents or
+ * a document and a query.
+ *
+ * Normally no parameters are required for initializing a vector, but in the case of
+ * loading a previously dumped vector the raw elements can be provided to the constructor.
+ *
+ * For performance reasons vectors are implemented with a flat array, where an elements
+ * index is immediately followed by its value. E.g. [index, value, index, value]. This
+ * allows the underlying array to be as sparse as possible and still offer decent
+ * performance when being used for vector calculations.
+ *
+ * @constructor
+ * @param {Number[]} [elements] - The flat list of element index and element value pairs.
+ */
+lunr.Vector = function (elements) {
+ this._magnitude = 0
+ this.elements = elements || []
+}
+
+
+/**
+ * Calculates the position within the vector to insert a given index.
+ *
+ * This is used internally by insert and upsert. If there are duplicate indexes then
+ * the position is returned as if the value for that index were to be updated, but it
+ * is the callers responsibility to check whether there is a duplicate at that index
+ *
+ * @param {Number} insertIdx - The index at which the element should be inserted.
+ * @returns {Number}
+ */
+lunr.Vector.prototype.positionForIndex = function (index) {
+ // For an empty vector the tuple can be inserted at the beginning
+ if (this.elements.length == 0) {
+ return 0
+ }
+
+ var start = 0,
+ end = this.elements.length / 2,
+ sliceLength = end - start,
+ pivotPoint = Math.floor(sliceLength / 2),
+ pivotIndex = this.elements[pivotPoint * 2]
+
+ while (sliceLength > 1) {
+ if (pivotIndex < index) {
+ start = pivotPoint
+ }
+
+ if (pivotIndex > index) {
+ end = pivotPoint
+ }
+
+ if (pivotIndex == index) {
+ break
+ }
+
+ sliceLength = end - start
+ pivotPoint = start + Math.floor(sliceLength / 2)
+ pivotIndex = this.elements[pivotPoint * 2]
+ }
+
+ if (pivotIndex == index) {
+ return pivotPoint * 2
+ }
+
+ if (pivotIndex > index) {
+ return pivotPoint * 2
+ }
+
+ if (pivotIndex < index) {
+ return (pivotPoint + 1) * 2
+ }
+}
+
+/**
+ * Inserts an element at an index within the vector.
+ *
+ * Does not allow duplicates, will throw an error if there is already an entry
+ * for this index.
+ *
+ * @param {Number} insertIdx - The index at which the element should be inserted.
+ * @param {Number} val - The value to be inserted into the vector.
+ */
+lunr.Vector.prototype.insert = function (insertIdx, val) {
+ this.upsert(insertIdx, val, function () {
+ throw "duplicate index"
+ })
+}
+
+/**
+ * Inserts or updates an existing index within the vector.
+ *
+ * @param {Number} insertIdx - The index at which the element should be inserted.
+ * @param {Number} val - The value to be inserted into the vector.
+ * @param {function} fn - A function that is called for updates, the existing value and the
+ * requested value are passed as arguments
+ */
+lunr.Vector.prototype.upsert = function (insertIdx, val, fn) {
+ this._magnitude = 0
+ var position = this.positionForIndex(insertIdx)
+
+ if (this.elements[position] == insertIdx) {
+ this.elements[position + 1] = fn(this.elements[position + 1], val)
+ } else {
+ this.elements.splice(position, 0, insertIdx, val)
+ }
+}
+
+/**
+ * Calculates the magnitude of this vector.
+ *
+ * @returns {Number}
+ */
+lunr.Vector.prototype.magnitude = function () {
+ if (this._magnitude) return this._magnitude
+
+ var sumOfSquares = 0,
+ elementsLength = this.elements.length
+
+ for (var i = 1; i < elementsLength; i += 2) {
+ var val = this.elements[i]
+ sumOfSquares += val * val
+ }
+
+ return this._magnitude = Math.sqrt(sumOfSquares)
+}
+
+/**
+ * Calculates the dot product of this vector and another vector.
+ *
+ * @param {lunr.Vector} otherVector - The vector to compute the dot product with.
+ * @returns {Number}
+ */
+lunr.Vector.prototype.dot = function (otherVector) {
+ var dotProduct = 0,
+ a = this.elements, b = otherVector.elements,
+ aLen = a.length, bLen = b.length,
+ aVal = 0, bVal = 0,
+ i = 0, j = 0
+
+ while (i < aLen && j < bLen) {
+ aVal = a[i], bVal = b[j]
+ if (aVal < bVal) {
+ i += 2
+ } else if (aVal > bVal) {
+ j += 2
+ } else if (aVal == bVal) {
+ dotProduct += a[i + 1] * b[j + 1]
+ i += 2
+ j += 2
+ }
+ }
+
+ return dotProduct
+}
+
+/**
+ * Calculates the similarity between this vector and another vector.
+ *
+ * @param {lunr.Vector} otherVector - The other vector to calculate the
+ * similarity with.
+ * @returns {Number}
+ */
+lunr.Vector.prototype.similarity = function (otherVector) {
+ return this.dot(otherVector) / this.magnitude() || 0
+}
+
+/**
+ * Converts the vector to an array of the elements within the vector.
+ *
+ * @returns {Number[]}
+ */
+lunr.Vector.prototype.toArray = function () {
+ var output = new Array (this.elements.length / 2)
+
+ for (var i = 1, j = 0; i < this.elements.length; i += 2, j++) {
+ output[j] = this.elements[i]
+ }
+
+ return output
+}
+
+/**
+ * A JSON serializable representation of the vector.
+ *
+ * @returns {Number[]}
+ */
+lunr.Vector.prototype.toJSON = function () {
+ return this.elements
+}
+/* eslint-disable */
+/*!
+ * lunr.stemmer
+ * Copyright (C) 2020 Oliver Nightingale
+ * Includes code from - http://tartarus.org/~martin/PorterStemmer/js.txt
+ */
+
+/**
+ * lunr.stemmer is an english language stemmer, this is a JavaScript
+ * implementation of the PorterStemmer taken from http://tartarus.org/~martin
+ *
+ * @static
+ * @implements {lunr.PipelineFunction}
+ * @param {lunr.Token} token - The string to stem
+ * @returns {lunr.Token}
+ * @see {@link lunr.Pipeline}
+ * @function
+ */
+lunr.stemmer = (function(){
+ var step2list = {
+ "ational" : "ate",
+ "tional" : "tion",
+ "enci" : "ence",
+ "anci" : "ance",
+ "izer" : "ize",
+ "bli" : "ble",
+ "alli" : "al",
+ "entli" : "ent",
+ "eli" : "e",
+ "ousli" : "ous",
+ "ization" : "ize",
+ "ation" : "ate",
+ "ator" : "ate",
+ "alism" : "al",
+ "iveness" : "ive",
+ "fulness" : "ful",
+ "ousness" : "ous",
+ "aliti" : "al",
+ "iviti" : "ive",
+ "biliti" : "ble",
+ "logi" : "log"
+ },
+
+ step3list = {
+ "icate" : "ic",
+ "ative" : "",
+ "alize" : "al",
+ "iciti" : "ic",
+ "ical" : "ic",
+ "ful" : "",
+ "ness" : ""
+ },
+
+ c = "[^aeiou]", // consonant
+ v = "[aeiouy]", // vowel
+ C = c + "[^aeiouy]*", // consonant sequence
+ V = v + "[aeiou]*", // vowel sequence
+
+ mgr0 = "^(" + C + ")?" + V + C, // [C]VC... is m>0
+ meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$", // [C]VC[V] is m=1
+ mgr1 = "^(" + C + ")?" + V + C + V + C, // [C]VCVC... is m>1
+ s_v = "^(" + C + ")?" + v; // vowel in stem
+
+ var re_mgr0 = new RegExp(mgr0);
+ var re_mgr1 = new RegExp(mgr1);
+ var re_meq1 = new RegExp(meq1);
+ var re_s_v = new RegExp(s_v);
+
+ var re_1a = /^(.+?)(ss|i)es$/;
+ var re2_1a = /^(.+?)([^s])s$/;
+ var re_1b = /^(.+?)eed$/;
+ var re2_1b = /^(.+?)(ed|ing)$/;
+ var re_1b_2 = /.$/;
+ var re2_1b_2 = /(at|bl|iz)$/;
+ var re3_1b_2 = new RegExp("([^aeiouylsz])\\1$");
+ var re4_1b_2 = new RegExp("^" + C + v + "[^aeiouwxy]$");
+
+ var re_1c = /^(.+?[^aeiou])y$/;
+ var re_2 = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/;
+
+ var re_3 = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/;
+
+ var re_4 = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/;
+ var re2_4 = /^(.+?)(s|t)(ion)$/;
+
+ var re_5 = /^(.+?)e$/;
+ var re_5_1 = /ll$/;
+ var re3_5 = new RegExp("^" + C + v + "[^aeiouwxy]$");
+
+ var porterStemmer = function porterStemmer(w) {
+ var stem,
+ suffix,
+ firstch,
+ re,
+ re2,
+ re3,
+ re4;
+
+ if (w.length < 3) { return w; }
+
+ firstch = w.substr(0,1);
+ if (firstch == "y") {
+ w = firstch.toUpperCase() + w.substr(1);
+ }
+
+ // Step 1a
+ re = re_1a
+ re2 = re2_1a;
+
+ if (re.test(w)) { w = w.replace(re,"$1$2"); }
+ else if (re2.test(w)) { w = w.replace(re2,"$1$2"); }
+
+ // Step 1b
+ re = re_1b;
+ re2 = re2_1b;
+ if (re.test(w)) {
+ var fp = re.exec(w);
+ re = re_mgr0;
+ if (re.test(fp[1])) {
+ re = re_1b_2;
+ w = w.replace(re,"");
+ }
+ } else if (re2.test(w)) {
+ var fp = re2.exec(w);
+ stem = fp[1];
+ re2 = re_s_v;
+ if (re2.test(stem)) {
+ w = stem;
+ re2 = re2_1b_2;
+ re3 = re3_1b_2;
+ re4 = re4_1b_2;
+ if (re2.test(w)) { w = w + "e"; }
+ else if (re3.test(w)) { re = re_1b_2; w = w.replace(re,""); }
+ else if (re4.test(w)) { w = w + "e"; }
+ }
+ }
+
+ // Step 1c - replace suffix y or Y by i if preceded by a non-vowel which is not the first letter of the word (so cry -> cri, by -> by, say -> say)
+ re = re_1c;
+ if (re.test(w)) {
+ var fp = re.exec(w);
+ stem = fp[1];
+ w = stem + "i";
+ }
+
+ // Step 2
+ re = re_2;
+ if (re.test(w)) {
+ var fp = re.exec(w);
+ stem = fp[1];
+ suffix = fp[2];
+ re = re_mgr0;
+ if (re.test(stem)) {
+ w = stem + step2list[suffix];
+ }
+ }
+
+ // Step 3
+ re = re_3;
+ if (re.test(w)) {
+ var fp = re.exec(w);
+ stem = fp[1];
+ suffix = fp[2];
+ re = re_mgr0;
+ if (re.test(stem)) {
+ w = stem + step3list[suffix];
+ }
+ }
+
+ // Step 4
+ re = re_4;
+ re2 = re2_4;
+ if (re.test(w)) {
+ var fp = re.exec(w);
+ stem = fp[1];
+ re = re_mgr1;
+ if (re.test(stem)) {
+ w = stem;
+ }
+ } else if (re2.test(w)) {
+ var fp = re2.exec(w);
+ stem = fp[1] + fp[2];
+ re2 = re_mgr1;
+ if (re2.test(stem)) {
+ w = stem;
+ }
+ }
+
+ // Step 5
+ re = re_5;
+ if (re.test(w)) {
+ var fp = re.exec(w);
+ stem = fp[1];
+ re = re_mgr1;
+ re2 = re_meq1;
+ re3 = re3_5;
+ if (re.test(stem) || (re2.test(stem) && !(re3.test(stem)))) {
+ w = stem;
+ }
+ }
+
+ re = re_5_1;
+ re2 = re_mgr1;
+ if (re.test(w) && re2.test(w)) {
+ re = re_1b_2;
+ w = w.replace(re,"");
+ }
+
+ // and turn initial Y back to y
+
+ if (firstch == "y") {
+ w = firstch.toLowerCase() + w.substr(1);
+ }
+
+ return w;
+ };
+
+ return function (token) {
+ return token.update(porterStemmer);
+ }
+})();
+
+lunr.Pipeline.registerFunction(lunr.stemmer, 'stemmer')
+/*!
+ * lunr.stopWordFilter
+ * Copyright (C) 2020 Oliver Nightingale
+ */
+
+/**
+ * lunr.generateStopWordFilter builds a stopWordFilter function from the provided
+ * list of stop words.
+ *
+ * The built in lunr.stopWordFilter is built using this generator and can be used
+ * to generate custom stopWordFilters for applications or non English languages.
+ *
+ * @function
+ * @param {Array} token The token to pass through the filter
+ * @returns {lunr.PipelineFunction}
+ * @see lunr.Pipeline
+ * @see lunr.stopWordFilter
+ */
+lunr.generateStopWordFilter = function (stopWords) {
+ var words = stopWords.reduce(function (memo, stopWord) {
+ memo[stopWord] = stopWord
+ return memo
+ }, {})
+
+ return function (token) {
+ if (token && words[token.toString()] !== token.toString()) return token
+ }
+}
+
+/**
+ * lunr.stopWordFilter is an English language stop word list filter, any words
+ * contained in the list will not be passed through the filter.
+ *
+ * This is intended to be used in the Pipeline. If the token does not pass the
+ * filter then undefined will be returned.
+ *
+ * @function
+ * @implements {lunr.PipelineFunction}
+ * @params {lunr.Token} token - A token to check for being a stop word.
+ * @returns {lunr.Token}
+ * @see {@link lunr.Pipeline}
+ */
+lunr.stopWordFilter = lunr.generateStopWordFilter([
+ 'a',
+ 'able',
+ 'about',
+ 'across',
+ 'after',
+ 'all',
+ 'almost',
+ 'also',
+ 'am',
+ 'among',
+ 'an',
+ 'and',
+ 'any',
+ 'are',
+ 'as',
+ 'at',
+ 'be',
+ 'because',
+ 'been',
+ 'but',
+ 'by',
+ 'can',
+ 'cannot',
+ 'could',
+ 'dear',
+ 'did',
+ 'do',
+ 'does',
+ 'either',
+ 'else',
+ 'ever',
+ 'every',
+ 'for',
+ 'from',
+ 'get',
+ 'got',
+ 'had',
+ 'has',
+ 'have',
+ 'he',
+ 'her',
+ 'hers',
+ 'him',
+ 'his',
+ 'how',
+ 'however',
+ 'i',
+ 'if',
+ 'in',
+ 'into',
+ 'is',
+ 'it',
+ 'its',
+ 'just',
+ 'least',
+ 'let',
+ 'like',
+ 'likely',
+ 'may',
+ 'me',
+ 'might',
+ 'most',
+ 'must',
+ 'my',
+ 'neither',
+ 'no',
+ 'nor',
+ 'not',
+ 'of',
+ 'off',
+ 'often',
+ 'on',
+ 'only',
+ 'or',
+ 'other',
+ 'our',
+ 'own',
+ 'rather',
+ 'said',
+ 'say',
+ 'says',
+ 'she',
+ 'should',
+ 'since',
+ 'so',
+ 'some',
+ 'than',
+ 'that',
+ 'the',
+ 'their',
+ 'them',
+ 'then',
+ 'there',
+ 'these',
+ 'they',
+ 'this',
+ 'tis',
+ 'to',
+ 'too',
+ 'twas',
+ 'us',
+ 'wants',
+ 'was',
+ 'we',
+ 'were',
+ 'what',
+ 'when',
+ 'where',
+ 'which',
+ 'while',
+ 'who',
+ 'whom',
+ 'why',
+ 'will',
+ 'with',
+ 'would',
+ 'yet',
+ 'you',
+ 'your'
+])
+
+lunr.Pipeline.registerFunction(lunr.stopWordFilter, 'stopWordFilter')
+/*!
+ * lunr.trimmer
+ * Copyright (C) 2020 Oliver Nightingale
+ */
+
+/**
+ * lunr.trimmer is a pipeline function for trimming non word
+ * characters from the beginning and end of tokens before they
+ * enter the index.
+ *
+ * This implementation may not work correctly for non latin
+ * characters and should either be removed or adapted for use
+ * with languages with non-latin characters.
+ *
+ * @static
+ * @implements {lunr.PipelineFunction}
+ * @param {lunr.Token} token The token to pass through the filter
+ * @returns {lunr.Token}
+ * @see lunr.Pipeline
+ */
+lunr.trimmer = function (token) {
+ return token.update(function (s) {
+ return s.replace(/^\W+/, '').replace(/\W+$/, '')
+ })
+}
+
+lunr.Pipeline.registerFunction(lunr.trimmer, 'trimmer')
+/*!
+ * lunr.TokenSet
+ * Copyright (C) 2020 Oliver Nightingale
+ */
+
+/**
+ * A token set is used to store the unique list of all tokens
+ * within an index. Token sets are also used to represent an
+ * incoming query to the index, this query token set and index
+ * token set are then intersected to find which tokens to look
+ * up in the inverted index.
+ *
+ * A token set can hold multiple tokens, as in the case of the
+ * index token set, or it can hold a single token as in the
+ * case of a simple query token set.
+ *
+ * Additionally token sets are used to perform wildcard matching.
+ * Leading, contained and trailing wildcards are supported, and
+ * from this edit distance matching can also be provided.
+ *
+ * Token sets are implemented as a minimal finite state automata,
+ * where both common prefixes and suffixes are shared between tokens.
+ * This helps to reduce the space used for storing the token set.
+ *
+ * @constructor
+ */
+lunr.TokenSet = function () {
+ this.final = false
+ this.edges = {}
+ this.id = lunr.TokenSet._nextId
+ lunr.TokenSet._nextId += 1
+}
+
+/**
+ * Keeps track of the next, auto increment, identifier to assign
+ * to a new tokenSet.
+ *
+ * TokenSets require a unique identifier to be correctly minimised.
+ *
+ * @private
+ */
+lunr.TokenSet._nextId = 1
+
+/**
+ * Creates a TokenSet instance from the given sorted array of words.
+ *
+ * @param {String[]} arr - A sorted array of strings to create the set from.
+ * @returns {lunr.TokenSet}
+ * @throws Will throw an error if the input array is not sorted.
+ */
+lunr.TokenSet.fromArray = function (arr) {
+ var builder = new lunr.TokenSet.Builder
+
+ for (var i = 0, len = arr.length; i < len; i++) {
+ builder.insert(arr[i])
+ }
+
+ builder.finish()
+ return builder.root
+}
+
+/**
+ * Creates a token set from a query clause.
+ *
+ * @private
+ * @param {Object} clause - A single clause from lunr.Query.
+ * @param {string} clause.term - The query clause term.
+ * @param {number} [clause.editDistance] - The optional edit distance for the term.
+ * @returns {lunr.TokenSet}
+ */
+lunr.TokenSet.fromClause = function (clause) {
+ if ('editDistance' in clause) {
+ return lunr.TokenSet.fromFuzzyString(clause.term, clause.editDistance)
+ } else {
+ return lunr.TokenSet.fromString(clause.term)
+ }
+}
+
+/**
+ * Creates a token set representing a single string with a specified
+ * edit distance.
+ *
+ * Insertions, deletions, substitutions and transpositions are each
+ * treated as an edit distance of 1.
+ *
+ * Increasing the allowed edit distance will have a dramatic impact
+ * on the performance of both creating and intersecting these TokenSets.
+ * It is advised to keep the edit distance less than 3.
+ *
+ * @param {string} str - The string to create the token set from.
+ * @param {number} editDistance - The allowed edit distance to match.
+ * @returns {lunr.Vector}
+ */
+lunr.TokenSet.fromFuzzyString = function (str, editDistance) {
+ var root = new lunr.TokenSet
+
+ var stack = [{
+ node: root,
+ editsRemaining: editDistance,
+ str: str
+ }]
+
+ while (stack.length) {
+ var frame = stack.pop()
+
+ // no edit
+ if (frame.str.length > 0) {
+ var char = frame.str.charAt(0),
+ noEditNode
+
+ if (char in frame.node.edges) {
+ noEditNode = frame.node.edges[char]
+ } else {
+ noEditNode = new lunr.TokenSet
+ frame.node.edges[char] = noEditNode
+ }
+
+ if (frame.str.length == 1) {
+ noEditNode.final = true
+ }
+
+ stack.push({
+ node: noEditNode,
+ editsRemaining: frame.editsRemaining,
+ str: frame.str.slice(1)
+ })
+ }
+
+ if (frame.editsRemaining == 0) {
+ continue
+ }
+
+ // insertion
+ if ("*" in frame.node.edges) {
+ var insertionNode = frame.node.edges["*"]
+ } else {
+ var insertionNode = new lunr.TokenSet
+ frame.node.edges["*"] = insertionNode
+ }
+
+ if (frame.str.length == 0) {
+ insertionNode.final = true
+ }
+
+ stack.push({
+ node: insertionNode,
+ editsRemaining: frame.editsRemaining - 1,
+ str: frame.str
+ })
+
+ // deletion
+ // can only do a deletion if we have enough edits remaining
+ // and if there are characters left to delete in the string
+ if (frame.str.length > 1) {
+ stack.push({
+ node: frame.node,
+ editsRemaining: frame.editsRemaining - 1,
+ str: frame.str.slice(1)
+ })
+ }
+
+ // deletion
+ // just removing the last character from the str
+ if (frame.str.length == 1) {
+ frame.node.final = true
+ }
+
+ // substitution
+ // can only do a substitution if we have enough edits remaining
+ // and if there are characters left to substitute
+ if (frame.str.length >= 1) {
+ if ("*" in frame.node.edges) {
+ var substitutionNode = frame.node.edges["*"]
+ } else {
+ var substitutionNode = new lunr.TokenSet
+ frame.node.edges["*"] = substitutionNode
+ }
+
+ if (frame.str.length == 1) {
+ substitutionNode.final = true
+ }
+
+ stack.push({
+ node: substitutionNode,
+ editsRemaining: frame.editsRemaining - 1,
+ str: frame.str.slice(1)
+ })
+ }
+
+ // transposition
+ // can only do a transposition if there are edits remaining
+ // and there are enough characters to transpose
+ if (frame.str.length > 1) {
+ var charA = frame.str.charAt(0),
+ charB = frame.str.charAt(1),
+ transposeNode
+
+ if (charB in frame.node.edges) {
+ transposeNode = frame.node.edges[charB]
+ } else {
+ transposeNode = new lunr.TokenSet
+ frame.node.edges[charB] = transposeNode
+ }
+
+ if (frame.str.length == 1) {
+ transposeNode.final = true
+ }
+
+ stack.push({
+ node: transposeNode,
+ editsRemaining: frame.editsRemaining - 1,
+ str: charA + frame.str.slice(2)
+ })
+ }
+ }
+
+ return root
+}
+
+/**
+ * Creates a TokenSet from a string.
+ *
+ * The string may contain one or more wildcard characters (*)
+ * that will allow wildcard matching when intersecting with
+ * another TokenSet.
+ *
+ * @param {string} str - The string to create a TokenSet from.
+ * @returns {lunr.TokenSet}
+ */
+lunr.TokenSet.fromString = function (str) {
+ var node = new lunr.TokenSet,
+ root = node
+
+ /*
+ * Iterates through all characters within the passed string
+ * appending a node for each character.
+ *
+ * When a wildcard character is found then a self
+ * referencing edge is introduced to continually match
+ * any number of any characters.
+ */
+ for (var i = 0, len = str.length; i < len; i++) {
+ var char = str[i],
+ final = (i == len - 1)
+
+ if (char == "*") {
+ node.edges[char] = node
+ node.final = final
+
+ } else {
+ var next = new lunr.TokenSet
+ next.final = final
+
+ node.edges[char] = next
+ node = next
+ }
+ }
+
+ return root
+}
+
+/**
+ * Converts this TokenSet into an array of strings
+ * contained within the TokenSet.
+ *
+ * This is not intended to be used on a TokenSet that
+ * contains wildcards, in these cases the results are
+ * undefined and are likely to cause an infinite loop.
+ *
+ * @returns {string[]}
+ */
+lunr.TokenSet.prototype.toArray = function () {
+ var words = []
+
+ var stack = [{
+ prefix: "",
+ node: this
+ }]
+
+ while (stack.length) {
+ var frame = stack.pop(),
+ edges = Object.keys(frame.node.edges),
+ len = edges.length
+
+ if (frame.node.final) {
+ /* In Safari, at this point the prefix is sometimes corrupted, see:
+ * https://github.com/olivernn/lunr.js/issues/279 Calling any
+ * String.prototype method forces Safari to "cast" this string to what
+ * it's supposed to be, fixing the bug. */
+ frame.prefix.charAt(0)
+ words.push(frame.prefix)
+ }
+
+ for (var i = 0; i < len; i++) {
+ var edge = edges[i]
+
+ stack.push({
+ prefix: frame.prefix.concat(edge),
+ node: frame.node.edges[edge]
+ })
+ }
+ }
+
+ return words
+}
+
+/**
+ * Generates a string representation of a TokenSet.
+ *
+ * This is intended to allow TokenSets to be used as keys
+ * in objects, largely to aid the construction and minimisation
+ * of a TokenSet. As such it is not designed to be a human
+ * friendly representation of the TokenSet.
+ *
+ * @returns {string}
+ */
+lunr.TokenSet.prototype.toString = function () {
+ // NOTE: Using Object.keys here as this.edges is very likely
+ // to enter 'hash-mode' with many keys being added
+ //
+ // avoiding a for-in loop here as it leads to the function
+ // being de-optimised (at least in V8). From some simple
+ // benchmarks the performance is comparable, but allowing
+ // V8 to optimize may mean easy performance wins in the future.
+
+ if (this._str) {
+ return this._str
+ }
+
+ var str = this.final ? '1' : '0',
+ labels = Object.keys(this.edges).sort(),
+ len = labels.length
+
+ for (var i = 0; i < len; i++) {
+ var label = labels[i],
+ node = this.edges[label]
+
+ str = str + label + node.id
+ }
+
+ return str
+}
+
+/**
+ * Returns a new TokenSet that is the intersection of
+ * this TokenSet and the passed TokenSet.
+ *
+ * This intersection will take into account any wildcards
+ * contained within the TokenSet.
+ *
+ * @param {lunr.TokenSet} b - An other TokenSet to intersect with.
+ * @returns {lunr.TokenSet}
+ */
+lunr.TokenSet.prototype.intersect = function (b) {
+ var output = new lunr.TokenSet,
+ frame = undefined
+
+ var stack = [{
+ qNode: b,
+ output: output,
+ node: this
+ }]
+
+ while (stack.length) {
+ frame = stack.pop()
+
+ // NOTE: As with the #toString method, we are using
+ // Object.keys and a for loop instead of a for-in loop
+ // as both of these objects enter 'hash' mode, causing
+ // the function to be de-optimised in V8
+ var qEdges = Object.keys(frame.qNode.edges),
+ qLen = qEdges.length,
+ nEdges = Object.keys(frame.node.edges),
+ nLen = nEdges.length
+
+ for (var q = 0; q < qLen; q++) {
+ var qEdge = qEdges[q]
+
+ for (var n = 0; n < nLen; n++) {
+ var nEdge = nEdges[n]
+
+ if (nEdge == qEdge || qEdge == '*') {
+ var node = frame.node.edges[nEdge],
+ qNode = frame.qNode.edges[qEdge],
+ final = node.final && qNode.final,
+ next = undefined
+
+ if (nEdge in frame.output.edges) {
+ // an edge already exists for this character
+ // no need to create a new node, just set the finality
+ // bit unless this node is already final
+ next = frame.output.edges[nEdge]
+ next.final = next.final || final
+
+ } else {
+ // no edge exists yet, must create one
+ // set the finality bit and insert it
+ // into the output
+ next = new lunr.TokenSet
+ next.final = final
+ frame.output.edges[nEdge] = next
+ }
+
+ stack.push({
+ qNode: qNode,
+ output: next,
+ node: node
+ })
+ }
+ }
+ }
+ }
+
+ return output
+}
+lunr.TokenSet.Builder = function () {
+ this.previousWord = ""
+ this.root = new lunr.TokenSet
+ this.uncheckedNodes = []
+ this.minimizedNodes = {}
+}
+
+lunr.TokenSet.Builder.prototype.insert = function (word) {
+ var node,
+ commonPrefix = 0
+
+ if (word < this.previousWord) {
+ throw new Error ("Out of order word insertion")
+ }
+
+ for (var i = 0; i < word.length && i < this.previousWord.length; i++) {
+ if (word[i] != this.previousWord[i]) break
+ commonPrefix++
+ }
+
+ this.minimize(commonPrefix)
+
+ if (this.uncheckedNodes.length == 0) {
+ node = this.root
+ } else {
+ node = this.uncheckedNodes[this.uncheckedNodes.length - 1].child
+ }
+
+ for (var i = commonPrefix; i < word.length; i++) {
+ var nextNode = new lunr.TokenSet,
+ char = word[i]
+
+ node.edges[char] = nextNode
+
+ this.uncheckedNodes.push({
+ parent: node,
+ char: char,
+ child: nextNode
+ })
+
+ node = nextNode
+ }
+
+ node.final = true
+ this.previousWord = word
+}
+
+lunr.TokenSet.Builder.prototype.finish = function () {
+ this.minimize(0)
+}
+
+lunr.TokenSet.Builder.prototype.minimize = function (downTo) {
+ for (var i = this.uncheckedNodes.length - 1; i >= downTo; i--) {
+ var node = this.uncheckedNodes[i],
+ childKey = node.child.toString()
+
+ if (childKey in this.minimizedNodes) {
+ node.parent.edges[node.char] = this.minimizedNodes[childKey]
+ } else {
+ // Cache the key for this node since
+ // we know it can't change anymore
+ node.child._str = childKey
+
+ this.minimizedNodes[childKey] = node.child
+ }
+
+ this.uncheckedNodes.pop()
+ }
+}
+/*!
+ * lunr.Index
+ * Copyright (C) 2020 Oliver Nightingale
+ */
+
+/**
+ * An index contains the built index of all documents and provides a query interface
+ * to the index.
+ *
+ * Usually instances of lunr.Index will not be created using this constructor, instead
+ * lunr.Builder should be used to construct new indexes, or lunr.Index.load should be
+ * used to load previously built and serialized indexes.
+ *
+ * @constructor
+ * @param {Object} attrs - The attributes of the built search index.
+ * @param {Object} attrs.invertedIndex - An index of term/field to document reference.
+ * @param {Object} attrs.fieldVectors - Field vectors
+ * @param {lunr.TokenSet} attrs.tokenSet - An set of all corpus tokens.
+ * @param {string[]} attrs.fields - The names of indexed document fields.
+ * @param {lunr.Pipeline} attrs.pipeline - The pipeline to use for search terms.
+ */
+lunr.Index = function (attrs) {
+ this.invertedIndex = attrs.invertedIndex
+ this.fieldVectors = attrs.fieldVectors
+ this.tokenSet = attrs.tokenSet
+ this.fields = attrs.fields
+ this.pipeline = attrs.pipeline
+}
+
+/**
+ * A result contains details of a document matching a search query.
+ * @typedef {Object} lunr.Index~Result
+ * @property {string} ref - The reference of the document this result represents.
+ * @property {number} score - A number between 0 and 1 representing how similar this document is to the query.
+ * @property {lunr.MatchData} matchData - Contains metadata about this match including which term(s) caused the match.
+ */
+
+/**
+ * Although lunr provides the ability to create queries using lunr.Query, it also provides a simple
+ * query language which itself is parsed into an instance of lunr.Query.
+ *
+ * For programmatically building queries it is advised to directly use lunr.Query, the query language
+ * is best used for human entered text rather than program generated text.
+ *
+ * At its simplest queries can just be a single term, e.g. `hello`, multiple terms are also supported
+ * and will be combined with OR, e.g `hello world` will match documents that contain either 'hello'
+ * or 'world', though those that contain both will rank higher in the results.
+ *
+ * Wildcards can be included in terms to match one or more unspecified characters, these wildcards can
+ * be inserted anywhere within the term, and more than one wildcard can exist in a single term. Adding
+ * wildcards will increase the number of documents that will be found but can also have a negative
+ * impact on query performance, especially with wildcards at the beginning of a term.
+ *
+ * Terms can be restricted to specific fields, e.g. `title:hello`, only documents with the term
+ * hello in the title field will match this query. Using a field not present in the index will lead
+ * to an error being thrown.
+ *
+ * Modifiers can also be added to terms, lunr supports edit distance and boost modifiers on terms. A term
+ * boost will make documents matching that term score higher, e.g. `foo^5`. Edit distance is also supported
+ * to provide fuzzy matching, e.g. 'hello~2' will match documents with hello with an edit distance of 2.
+ * Avoid large values for edit distance to improve query performance.
+ *
+ * Each term also supports a presence modifier. By default a term's presence in document is optional, however
+ * this can be changed to either required or prohibited. For a term's presence to be required in a document the
+ * term should be prefixed with a '+', e.g. `+foo bar` is a search for documents that must contain 'foo' and
+ * optionally contain 'bar'. Conversely a leading '-' sets the terms presence to prohibited, i.e. it must not
+ * appear in a document, e.g. `-foo bar` is a search for documents that do not contain 'foo' but may contain 'bar'.
+ *
+ * To escape special characters the backslash character '\' can be used, this allows searches to include
+ * characters that would normally be considered modifiers, e.g. `foo\~2` will search for a term "foo~2" instead
+ * of attempting to apply a boost of 2 to the search term "foo".
+ *
+ * @typedef {string} lunr.Index~QueryString
+ * @example
Simple single term query
+ * hello
+ * @example
Multiple term query
+ * hello world
+ * @example
term scoped to a field
+ * title:hello
+ * @example
term with a boost of 10
+ * hello^10
+ * @example
term with an edit distance of 2
+ * hello~2
+ * @example
terms with presence modifiers
+ * -foo +bar baz
+ */
+
+/**
+ * Performs a search against the index using lunr query syntax.
+ *
+ * Results will be returned sorted by their score, the most relevant results
+ * will be returned first. For details on how the score is calculated, please see
+ * the {@link https://lunrjs.com/guides/searching.html#scoring|guide}.
+ *
+ * For more programmatic querying use lunr.Index#query.
+ *
+ * @param {lunr.Index~QueryString} queryString - A string containing a lunr query.
+ * @throws {lunr.QueryParseError} If the passed query string cannot be parsed.
+ * @returns {lunr.Index~Result[]}
+ */
+lunr.Index.prototype.search = function (queryString) {
+ return this.query(function (query) {
+ var parser = new lunr.QueryParser(queryString, query)
+ parser.parse()
+ })
+}
+
+/**
+ * A query builder callback provides a query object to be used to express
+ * the query to perform on the index.
+ *
+ * @callback lunr.Index~queryBuilder
+ * @param {lunr.Query} query - The query object to build up.
+ * @this lunr.Query
+ */
+
+/**
+ * Performs a query against the index using the yielded lunr.Query object.
+ *
+ * If performing programmatic queries against the index, this method is preferred
+ * over lunr.Index#search so as to avoid the additional query parsing overhead.
+ *
+ * A query object is yielded to the supplied function which should be used to
+ * express the query to be run against the index.
+ *
+ * Note that although this function takes a callback parameter it is _not_ an
+ * asynchronous operation, the callback is just yielded a query object to be
+ * customized.
+ *
+ * @param {lunr.Index~queryBuilder} fn - A function that is used to build the query.
+ * @returns {lunr.Index~Result[]}
+ */
+lunr.Index.prototype.query = function (fn) {
+ // for each query clause
+ // * process terms
+ // * expand terms from token set
+ // * find matching documents and metadata
+ // * get document vectors
+ // * score documents
+
+ var query = new lunr.Query(this.fields),
+ matchingFields = Object.create(null),
+ queryVectors = Object.create(null),
+ termFieldCache = Object.create(null),
+ requiredMatches = Object.create(null),
+ prohibitedMatches = Object.create(null)
+
+ /*
+ * To support field level boosts a query vector is created per
+ * field. An empty vector is eagerly created to support negated
+ * queries.
+ */
+ for (var i = 0; i < this.fields.length; i++) {
+ queryVectors[this.fields[i]] = new lunr.Vector
+ }
+
+ fn.call(query, query)
+
+ for (var i = 0; i < query.clauses.length; i++) {
+ /*
+ * Unless the pipeline has been disabled for this term, which is
+ * the case for terms with wildcards, we need to pass the clause
+ * term through the search pipeline. A pipeline returns an array
+ * of processed terms. Pipeline functions may expand the passed
+ * term, which means we may end up performing multiple index lookups
+ * for a single query term.
+ */
+ var clause = query.clauses[i],
+ terms = null,
+ clauseMatches = lunr.Set.empty
+
+ if (clause.usePipeline) {
+ terms = this.pipeline.runString(clause.term, {
+ fields: clause.fields
+ })
+ } else {
+ terms = [clause.term]
+ }
+
+ for (var m = 0; m < terms.length; m++) {
+ var term = terms[m]
+
+ /*
+ * Each term returned from the pipeline needs to use the same query
+ * clause object, e.g. the same boost and or edit distance. The
+ * simplest way to do this is to re-use the clause object but mutate
+ * its term property.
+ */
+ clause.term = term
+
+ /*
+ * From the term in the clause we create a token set which will then
+ * be used to intersect the indexes token set to get a list of terms
+ * to lookup in the inverted index
+ */
+ var termTokenSet = lunr.TokenSet.fromClause(clause),
+ expandedTerms = this.tokenSet.intersect(termTokenSet).toArray()
+
+ /*
+ * If a term marked as required does not exist in the tokenSet it is
+ * impossible for the search to return any matches. We set all the field
+ * scoped required matches set to empty and stop examining any further
+ * clauses.
+ */
+ if (expandedTerms.length === 0 && clause.presence === lunr.Query.presence.REQUIRED) {
+ for (var k = 0; k < clause.fields.length; k++) {
+ var field = clause.fields[k]
+ requiredMatches[field] = lunr.Set.empty
+ }
+
+ break
+ }
+
+ for (var j = 0; j < expandedTerms.length; j++) {
+ /*
+ * For each term get the posting and termIndex, this is required for
+ * building the query vector.
+ */
+ var expandedTerm = expandedTerms[j],
+ posting = this.invertedIndex[expandedTerm],
+ termIndex = posting._index
+
+ for (var k = 0; k < clause.fields.length; k++) {
+ /*
+ * For each field that this query term is scoped by (by default
+ * all fields are in scope) we need to get all the document refs
+ * that have this term in that field.
+ *
+ * The posting is the entry in the invertedIndex for the matching
+ * term from above.
+ */
+ var field = clause.fields[k],
+ fieldPosting = posting[field],
+ matchingDocumentRefs = Object.keys(fieldPosting),
+ termField = expandedTerm + "/" + field,
+ matchingDocumentsSet = new lunr.Set(matchingDocumentRefs)
+
+ /*
+ * if the presence of this term is required ensure that the matching
+ * documents are added to the set of required matches for this clause.
+ *
+ */
+ if (clause.presence == lunr.Query.presence.REQUIRED) {
+ clauseMatches = clauseMatches.union(matchingDocumentsSet)
+
+ if (requiredMatches[field] === undefined) {
+ requiredMatches[field] = lunr.Set.complete
+ }
+ }
+
+ /*
+ * if the presence of this term is prohibited ensure that the matching
+ * documents are added to the set of prohibited matches for this field,
+ * creating that set if it does not yet exist.
+ */
+ if (clause.presence == lunr.Query.presence.PROHIBITED) {
+ if (prohibitedMatches[field] === undefined) {
+ prohibitedMatches[field] = lunr.Set.empty
+ }
+
+ prohibitedMatches[field] = prohibitedMatches[field].union(matchingDocumentsSet)
+
+ /*
+ * Prohibited matches should not be part of the query vector used for
+ * similarity scoring and no metadata should be extracted so we continue
+ * to the next field
+ */
+ continue
+ }
+
+ /*
+ * The query field vector is populated using the termIndex found for
+ * the term and a unit value with the appropriate boost applied.
+ * Using upsert because there could already be an entry in the vector
+ * for the term we are working with. In that case we just add the scores
+ * together.
+ */
+ queryVectors[field].upsert(termIndex, clause.boost, function (a, b) { return a + b })
+
+ /**
+ * If we've already seen this term, field combo then we've already collected
+ * the matching documents and metadata, no need to go through all that again
+ */
+ if (termFieldCache[termField]) {
+ continue
+ }
+
+ for (var l = 0; l < matchingDocumentRefs.length; l++) {
+ /*
+ * All metadata for this term/field/document triple
+ * are then extracted and collected into an instance
+ * of lunr.MatchData ready to be returned in the query
+ * results
+ */
+ var matchingDocumentRef = matchingDocumentRefs[l],
+ matchingFieldRef = new lunr.FieldRef (matchingDocumentRef, field),
+ metadata = fieldPosting[matchingDocumentRef],
+ fieldMatch
+
+ if ((fieldMatch = matchingFields[matchingFieldRef]) === undefined) {
+ matchingFields[matchingFieldRef] = new lunr.MatchData (expandedTerm, field, metadata)
+ } else {
+ fieldMatch.add(expandedTerm, field, metadata)
+ }
+
+ }
+
+ termFieldCache[termField] = true
+ }
+ }
+ }
+
+ /**
+ * If the presence was required we need to update the requiredMatches field sets.
+ * We do this after all fields for the term have collected their matches because
+ * the clause terms presence is required in _any_ of the fields not _all_ of the
+ * fields.
+ */
+ if (clause.presence === lunr.Query.presence.REQUIRED) {
+ for (var k = 0; k < clause.fields.length; k++) {
+ var field = clause.fields[k]
+ requiredMatches[field] = requiredMatches[field].intersect(clauseMatches)
+ }
+ }
+ }
+
+ /**
+ * Need to combine the field scoped required and prohibited
+ * matching documents into a global set of required and prohibited
+ * matches
+ */
+ var allRequiredMatches = lunr.Set.complete,
+ allProhibitedMatches = lunr.Set.empty
+
+ for (var i = 0; i < this.fields.length; i++) {
+ var field = this.fields[i]
+
+ if (requiredMatches[field]) {
+ allRequiredMatches = allRequiredMatches.intersect(requiredMatches[field])
+ }
+
+ if (prohibitedMatches[field]) {
+ allProhibitedMatches = allProhibitedMatches.union(prohibitedMatches[field])
+ }
+ }
+
+ var matchingFieldRefs = Object.keys(matchingFields),
+ results = [],
+ matches = Object.create(null)
+
+ /*
+ * If the query is negated (contains only prohibited terms)
+ * we need to get _all_ fieldRefs currently existing in the
+ * index. This is only done when we know that the query is
+ * entirely prohibited terms to avoid any cost of getting all
+ * fieldRefs unnecessarily.
+ *
+ * Additionally, blank MatchData must be created to correctly
+ * populate the results.
+ */
+ if (query.isNegated()) {
+ matchingFieldRefs = Object.keys(this.fieldVectors)
+
+ for (var i = 0; i < matchingFieldRefs.length; i++) {
+ var matchingFieldRef = matchingFieldRefs[i]
+ var fieldRef = lunr.FieldRef.fromString(matchingFieldRef)
+ matchingFields[matchingFieldRef] = new lunr.MatchData
+ }
+ }
+
+ for (var i = 0; i < matchingFieldRefs.length; i++) {
+ /*
+ * Currently we have document fields that match the query, but we
+ * need to return documents. The matchData and scores are combined
+ * from multiple fields belonging to the same document.
+ *
+ * Scores are calculated by field, using the query vectors created
+ * above, and combined into a final document score using addition.
+ */
+ var fieldRef = lunr.FieldRef.fromString(matchingFieldRefs[i]),
+ docRef = fieldRef.docRef
+
+ if (!allRequiredMatches.contains(docRef)) {
+ continue
+ }
+
+ if (allProhibitedMatches.contains(docRef)) {
+ continue
+ }
+
+ var fieldVector = this.fieldVectors[fieldRef],
+ score = queryVectors[fieldRef.fieldName].similarity(fieldVector),
+ docMatch
+
+ if ((docMatch = matches[docRef]) !== undefined) {
+ docMatch.score += score
+ docMatch.matchData.combine(matchingFields[fieldRef])
+ } else {
+ var match = {
+ ref: docRef,
+ score: score,
+ matchData: matchingFields[fieldRef]
+ }
+ matches[docRef] = match
+ results.push(match)
+ }
+ }
+
+ /*
+ * Sort the results objects by score, highest first.
+ */
+ return results.sort(function (a, b) {
+ return b.score - a.score
+ })
+}
+
+/**
+ * Prepares the index for JSON serialization.
+ *
+ * The schema for this JSON blob will be described in a
+ * separate JSON schema file.
+ *
+ * @returns {Object}
+ */
+lunr.Index.prototype.toJSON = function () {
+ var invertedIndex = Object.keys(this.invertedIndex)
+ .sort()
+ .map(function (term) {
+ return [term, this.invertedIndex[term]]
+ }, this)
+
+ var fieldVectors = Object.keys(this.fieldVectors)
+ .map(function (ref) {
+ return [ref, this.fieldVectors[ref].toJSON()]
+ }, this)
+
+ return {
+ version: lunr.version,
+ fields: this.fields,
+ fieldVectors: fieldVectors,
+ invertedIndex: invertedIndex,
+ pipeline: this.pipeline.toJSON()
+ }
+}
+
+/**
+ * Loads a previously serialized lunr.Index
+ *
+ * @param {Object} serializedIndex - A previously serialized lunr.Index
+ * @returns {lunr.Index}
+ */
+lunr.Index.load = function (serializedIndex) {
+ var attrs = {},
+ fieldVectors = {},
+ serializedVectors = serializedIndex.fieldVectors,
+ invertedIndex = Object.create(null),
+ serializedInvertedIndex = serializedIndex.invertedIndex,
+ tokenSetBuilder = new lunr.TokenSet.Builder,
+ pipeline = lunr.Pipeline.load(serializedIndex.pipeline)
+
+ if (serializedIndex.version != lunr.version) {
+ lunr.utils.warn("Version mismatch when loading serialised index. Current version of lunr '" + lunr.version + "' does not match serialized index '" + serializedIndex.version + "'")
+ }
+
+ for (var i = 0; i < serializedVectors.length; i++) {
+ var tuple = serializedVectors[i],
+ ref = tuple[0],
+ elements = tuple[1]
+
+ fieldVectors[ref] = new lunr.Vector(elements)
+ }
+
+ for (var i = 0; i < serializedInvertedIndex.length; i++) {
+ var tuple = serializedInvertedIndex[i],
+ term = tuple[0],
+ posting = tuple[1]
+
+ tokenSetBuilder.insert(term)
+ invertedIndex[term] = posting
+ }
+
+ tokenSetBuilder.finish()
+
+ attrs.fields = serializedIndex.fields
+
+ attrs.fieldVectors = fieldVectors
+ attrs.invertedIndex = invertedIndex
+ attrs.tokenSet = tokenSetBuilder.root
+ attrs.pipeline = pipeline
+
+ return new lunr.Index(attrs)
+}
+/*!
+ * lunr.Builder
+ * Copyright (C) 2020 Oliver Nightingale
+ */
+
+/**
+ * lunr.Builder performs indexing on a set of documents and
+ * returns instances of lunr.Index ready for querying.
+ *
+ * All configuration of the index is done via the builder, the
+ * fields to index, the document reference, the text processing
+ * pipeline and document scoring parameters are all set on the
+ * builder before indexing.
+ *
+ * @constructor
+ * @property {string} _ref - Internal reference to the document reference field.
+ * @property {string[]} _fields - Internal reference to the document fields to index.
+ * @property {object} invertedIndex - The inverted index maps terms to document fields.
+ * @property {object} documentTermFrequencies - Keeps track of document term frequencies.
+ * @property {object} documentLengths - Keeps track of the length of documents added to the index.
+ * @property {lunr.tokenizer} tokenizer - Function for splitting strings into tokens for indexing.
+ * @property {lunr.Pipeline} pipeline - The pipeline performs text processing on tokens before indexing.
+ * @property {lunr.Pipeline} searchPipeline - A pipeline for processing search terms before querying the index.
+ * @property {number} documentCount - Keeps track of the total number of documents indexed.
+ * @property {number} _b - A parameter to control field length normalization, setting this to 0 disabled normalization, 1 fully normalizes field lengths, the default value is 0.75.
+ * @property {number} _k1 - A parameter to control how quickly an increase in term frequency results in term frequency saturation, the default value is 1.2.
+ * @property {number} termIndex - A counter incremented for each unique term, used to identify a terms position in the vector space.
+ * @property {array} metadataWhitelist - A list of metadata keys that have been whitelisted for entry in the index.
+ */
+lunr.Builder = function () {
+ this._ref = "id"
+ this._fields = Object.create(null)
+ this._documents = Object.create(null)
+ this.invertedIndex = Object.create(null)
+ this.fieldTermFrequencies = {}
+ this.fieldLengths = {}
+ this.tokenizer = lunr.tokenizer
+ this.pipeline = new lunr.Pipeline
+ this.searchPipeline = new lunr.Pipeline
+ this.documentCount = 0
+ this._b = 0.75
+ this._k1 = 1.2
+ this.termIndex = 0
+ this.metadataWhitelist = []
+}
+
+/**
+ * Sets the document field used as the document reference. Every document must have this field.
+ * The type of this field in the document should be a string, if it is not a string it will be
+ * coerced into a string by calling toString.
+ *
+ * The default ref is 'id'.
+ *
+ * The ref should _not_ be changed during indexing, it should be set before any documents are
+ * added to the index. Changing it during indexing can lead to inconsistent results.
+ *
+ * @param {string} ref - The name of the reference field in the document.
+ */
+lunr.Builder.prototype.ref = function (ref) {
+ this._ref = ref
+}
+
+/**
+ * A function that is used to extract a field from a document.
+ *
+ * Lunr expects a field to be at the top level of a document, if however the field
+ * is deeply nested within a document an extractor function can be used to extract
+ * the right field for indexing.
+ *
+ * @callback fieldExtractor
+ * @param {object} doc - The document being added to the index.
+ * @returns {?(string|object|object[])} obj - The object that will be indexed for this field.
+ * @example
Extracting a nested field
+ * function (doc) { return doc.nested.field }
+ */
+
+/**
+ * Adds a field to the list of document fields that will be indexed. Every document being
+ * indexed should have this field. Null values for this field in indexed documents will
+ * not cause errors but will limit the chance of that document being retrieved by searches.
+ *
+ * All fields should be added before adding documents to the index. Adding fields after
+ * a document has been indexed will have no effect on already indexed documents.
+ *
+ * Fields can be boosted at build time. This allows terms within that field to have more
+ * importance when ranking search results. Use a field boost to specify that matches within
+ * one field are more important than other fields.
+ *
+ * @param {string} fieldName - The name of a field to index in all documents.
+ * @param {object} attributes - Optional attributes associated with this field.
+ * @param {number} [attributes.boost=1] - Boost applied to all terms within this field.
+ * @param {fieldExtractor} [attributes.extractor] - Function to extract a field from a document.
+ * @throws {RangeError} fieldName cannot contain unsupported characters '/'
+ */
+lunr.Builder.prototype.field = function (fieldName, attributes) {
+ if (/\//.test(fieldName)) {
+ throw new RangeError ("Field '" + fieldName + "' contains illegal character '/'")
+ }
+
+ this._fields[fieldName] = attributes || {}
+}
+
+/**
+ * A parameter to tune the amount of field length normalisation that is applied when
+ * calculating relevance scores. A value of 0 will completely disable any normalisation
+ * and a value of 1 will fully normalise field lengths. The default is 0.75. Values of b
+ * will be clamped to the range 0 - 1.
+ *
+ * @param {number} number - The value to set for this tuning parameter.
+ */
+lunr.Builder.prototype.b = function (number) {
+ if (number < 0) {
+ this._b = 0
+ } else if (number > 1) {
+ this._b = 1
+ } else {
+ this._b = number
+ }
+}
+
+/**
+ * A parameter that controls the speed at which a rise in term frequency results in term
+ * frequency saturation. The default value is 1.2. Setting this to a higher value will give
+ * slower saturation levels, a lower value will result in quicker saturation.
+ *
+ * @param {number} number - The value to set for this tuning parameter.
+ */
+lunr.Builder.prototype.k1 = function (number) {
+ this._k1 = number
+}
+
+/**
+ * Adds a document to the index.
+ *
+ * Before adding fields to the index the index should have been fully setup, with the document
+ * ref and all fields to index already having been specified.
+ *
+ * The document must have a field name as specified by the ref (by default this is 'id') and
+ * it should have all fields defined for indexing, though null or undefined values will not
+ * cause errors.
+ *
+ * Entire documents can be boosted at build time. Applying a boost to a document indicates that
+ * this document should rank higher in search results than other documents.
+ *
+ * @param {object} doc - The document to add to the index.
+ * @param {object} attributes - Optional attributes associated with this document.
+ * @param {number} [attributes.boost=1] - Boost applied to all terms within this document.
+ */
+lunr.Builder.prototype.add = function (doc, attributes) {
+ var docRef = doc[this._ref],
+ fields = Object.keys(this._fields)
+
+ this._documents[docRef] = attributes || {}
+ this.documentCount += 1
+
+ for (var i = 0; i < fields.length; i++) {
+ var fieldName = fields[i],
+ extractor = this._fields[fieldName].extractor,
+ field = extractor ? extractor(doc) : doc[fieldName],
+ tokens = this.tokenizer(field, {
+ fields: [fieldName]
+ }),
+ terms = this.pipeline.run(tokens),
+ fieldRef = new lunr.FieldRef (docRef, fieldName),
+ fieldTerms = Object.create(null)
+
+ this.fieldTermFrequencies[fieldRef] = fieldTerms
+ this.fieldLengths[fieldRef] = 0
+
+ // store the length of this field for this document
+ this.fieldLengths[fieldRef] += terms.length
+
+ // calculate term frequencies for this field
+ for (var j = 0; j < terms.length; j++) {
+ var term = terms[j]
+
+ if (fieldTerms[term] == undefined) {
+ fieldTerms[term] = 0
+ }
+
+ fieldTerms[term] += 1
+
+ // add to inverted index
+ // create an initial posting if one doesn't exist
+ if (this.invertedIndex[term] == undefined) {
+ var posting = Object.create(null)
+ posting["_index"] = this.termIndex
+ this.termIndex += 1
+
+ for (var k = 0; k < fields.length; k++) {
+ posting[fields[k]] = Object.create(null)
+ }
+
+ this.invertedIndex[term] = posting
+ }
+
+ // add an entry for this term/fieldName/docRef to the invertedIndex
+ if (this.invertedIndex[term][fieldName][docRef] == undefined) {
+ this.invertedIndex[term][fieldName][docRef] = Object.create(null)
+ }
+
+ // store all whitelisted metadata about this token in the
+ // inverted index
+ for (var l = 0; l < this.metadataWhitelist.length; l++) {
+ var metadataKey = this.metadataWhitelist[l],
+ metadata = term.metadata[metadataKey]
+
+ if (this.invertedIndex[term][fieldName][docRef][metadataKey] == undefined) {
+ this.invertedIndex[term][fieldName][docRef][metadataKey] = []
+ }
+
+ this.invertedIndex[term][fieldName][docRef][metadataKey].push(metadata)
+ }
+ }
+
+ }
+}
+
+/**
+ * Calculates the average document length for this index
+ *
+ * @private
+ */
+lunr.Builder.prototype.calculateAverageFieldLengths = function () {
+
+ var fieldRefs = Object.keys(this.fieldLengths),
+ numberOfFields = fieldRefs.length,
+ accumulator = {},
+ documentsWithField = {}
+
+ for (var i = 0; i < numberOfFields; i++) {
+ var fieldRef = lunr.FieldRef.fromString(fieldRefs[i]),
+ field = fieldRef.fieldName
+
+ documentsWithField[field] || (documentsWithField[field] = 0)
+ documentsWithField[field] += 1
+
+ accumulator[field] || (accumulator[field] = 0)
+ accumulator[field] += this.fieldLengths[fieldRef]
+ }
+
+ var fields = Object.keys(this._fields)
+
+ for (var i = 0; i < fields.length; i++) {
+ var fieldName = fields[i]
+ accumulator[fieldName] = accumulator[fieldName] / documentsWithField[fieldName]
+ }
+
+ this.averageFieldLength = accumulator
+}
+
+/**
+ * Builds a vector space model of every document using lunr.Vector
+ *
+ * @private
+ */
+lunr.Builder.prototype.createFieldVectors = function () {
+ var fieldVectors = {},
+ fieldRefs = Object.keys(this.fieldTermFrequencies),
+ fieldRefsLength = fieldRefs.length,
+ termIdfCache = Object.create(null)
+
+ for (var i = 0; i < fieldRefsLength; i++) {
+ var fieldRef = lunr.FieldRef.fromString(fieldRefs[i]),
+ fieldName = fieldRef.fieldName,
+ fieldLength = this.fieldLengths[fieldRef],
+ fieldVector = new lunr.Vector,
+ termFrequencies = this.fieldTermFrequencies[fieldRef],
+ terms = Object.keys(termFrequencies),
+ termsLength = terms.length
+
+
+ var fieldBoost = this._fields[fieldName].boost || 1,
+ docBoost = this._documents[fieldRef.docRef].boost || 1
+
+ for (var j = 0; j < termsLength; j++) {
+ var term = terms[j],
+ tf = termFrequencies[term],
+ termIndex = this.invertedIndex[term]._index,
+ idf, score, scoreWithPrecision
+
+ if (termIdfCache[term] === undefined) {
+ idf = lunr.idf(this.invertedIndex[term], this.documentCount)
+ termIdfCache[term] = idf
+ } else {
+ idf = termIdfCache[term]
+ }
+
+ score = idf * ((this._k1 + 1) * tf) / (this._k1 * (1 - this._b + this._b * (fieldLength / this.averageFieldLength[fieldName])) + tf)
+ score *= fieldBoost
+ score *= docBoost
+ scoreWithPrecision = Math.round(score * 1000) / 1000
+ // Converts 1.23456789 to 1.234.
+ // Reducing the precision so that the vectors take up less
+ // space when serialised. Doing it now so that they behave
+ // the same before and after serialisation. Also, this is
+ // the fastest approach to reducing a number's precision in
+ // JavaScript.
+
+ fieldVector.insert(termIndex, scoreWithPrecision)
+ }
+
+ fieldVectors[fieldRef] = fieldVector
+ }
+
+ this.fieldVectors = fieldVectors
+}
+
+/**
+ * Creates a token set of all tokens in the index using lunr.TokenSet
+ *
+ * @private
+ */
+lunr.Builder.prototype.createTokenSet = function () {
+ this.tokenSet = lunr.TokenSet.fromArray(
+ Object.keys(this.invertedIndex).sort()
+ )
+}
+
+/**
+ * Builds the index, creating an instance of lunr.Index.
+ *
+ * This completes the indexing process and should only be called
+ * once all documents have been added to the index.
+ *
+ * @returns {lunr.Index}
+ */
+lunr.Builder.prototype.build = function () {
+ this.calculateAverageFieldLengths()
+ this.createFieldVectors()
+ this.createTokenSet()
+
+ return new lunr.Index({
+ invertedIndex: this.invertedIndex,
+ fieldVectors: this.fieldVectors,
+ tokenSet: this.tokenSet,
+ fields: Object.keys(this._fields),
+ pipeline: this.searchPipeline
+ })
+}
+
+/**
+ * Applies a plugin to the index builder.
+ *
+ * A plugin is a function that is called with the index builder as its context.
+ * Plugins can be used to customise or extend the behaviour of the index
+ * in some way. A plugin is just a function, that encapsulated the custom
+ * behaviour that should be applied when building the index.
+ *
+ * The plugin function will be called with the index builder as its argument, additional
+ * arguments can also be passed when calling use. The function will be called
+ * with the index builder as its context.
+ *
+ * @param {Function} plugin The plugin to apply.
+ */
+lunr.Builder.prototype.use = function (fn) {
+ var args = Array.prototype.slice.call(arguments, 1)
+ args.unshift(this)
+ fn.apply(this, args)
+}
+/**
+ * Contains and collects metadata about a matching document.
+ * A single instance of lunr.MatchData is returned as part of every
+ * lunr.Index~Result.
+ *
+ * @constructor
+ * @param {string} term - The term this match data is associated with
+ * @param {string} field - The field in which the term was found
+ * @param {object} metadata - The metadata recorded about this term in this field
+ * @property {object} metadata - A cloned collection of metadata associated with this document.
+ * @see {@link lunr.Index~Result}
+ */
+lunr.MatchData = function (term, field, metadata) {
+ var clonedMetadata = Object.create(null),
+ metadataKeys = Object.keys(metadata || {})
+
+ // Cloning the metadata to prevent the original
+ // being mutated during match data combination.
+ // Metadata is kept in an array within the inverted
+ // index so cloning the data can be done with
+ // Array#slice
+ for (var i = 0; i < metadataKeys.length; i++) {
+ var key = metadataKeys[i]
+ clonedMetadata[key] = metadata[key].slice()
+ }
+
+ this.metadata = Object.create(null)
+
+ if (term !== undefined) {
+ this.metadata[term] = Object.create(null)
+ this.metadata[term][field] = clonedMetadata
+ }
+}
+
+/**
+ * An instance of lunr.MatchData will be created for every term that matches a
+ * document. However only one instance is required in a lunr.Index~Result. This
+ * method combines metadata from another instance of lunr.MatchData with this
+ * objects metadata.
+ *
+ * @param {lunr.MatchData} otherMatchData - Another instance of match data to merge with this one.
+ * @see {@link lunr.Index~Result}
+ */
+lunr.MatchData.prototype.combine = function (otherMatchData) {
+ var terms = Object.keys(otherMatchData.metadata)
+
+ for (var i = 0; i < terms.length; i++) {
+ var term = terms[i],
+ fields = Object.keys(otherMatchData.metadata[term])
+
+ if (this.metadata[term] == undefined) {
+ this.metadata[term] = Object.create(null)
+ }
+
+ for (var j = 0; j < fields.length; j++) {
+ var field = fields[j],
+ keys = Object.keys(otherMatchData.metadata[term][field])
+
+ if (this.metadata[term][field] == undefined) {
+ this.metadata[term][field] = Object.create(null)
+ }
+
+ for (var k = 0; k < keys.length; k++) {
+ var key = keys[k]
+
+ if (this.metadata[term][field][key] == undefined) {
+ this.metadata[term][field][key] = otherMatchData.metadata[term][field][key]
+ } else {
+ this.metadata[term][field][key] = this.metadata[term][field][key].concat(otherMatchData.metadata[term][field][key])
+ }
+
+ }
+ }
+ }
+}
+
+/**
+ * Add metadata for a term/field pair to this instance of match data.
+ *
+ * @param {string} term - The term this match data is associated with
+ * @param {string} field - The field in which the term was found
+ * @param {object} metadata - The metadata recorded about this term in this field
+ */
+lunr.MatchData.prototype.add = function (term, field, metadata) {
+ if (!(term in this.metadata)) {
+ this.metadata[term] = Object.create(null)
+ this.metadata[term][field] = metadata
+ return
+ }
+
+ if (!(field in this.metadata[term])) {
+ this.metadata[term][field] = metadata
+ return
+ }
+
+ var metadataKeys = Object.keys(metadata)
+
+ for (var i = 0; i < metadataKeys.length; i++) {
+ var key = metadataKeys[i]
+
+ if (key in this.metadata[term][field]) {
+ this.metadata[term][field][key] = this.metadata[term][field][key].concat(metadata[key])
+ } else {
+ this.metadata[term][field][key] = metadata[key]
+ }
+ }
+}
+/**
+ * A lunr.Query provides a programmatic way of defining queries to be performed
+ * against a {@link lunr.Index}.
+ *
+ * Prefer constructing a lunr.Query using the {@link lunr.Index#query} method
+ * so the query object is pre-initialized with the right index fields.
+ *
+ * @constructor
+ * @property {lunr.Query~Clause[]} clauses - An array of query clauses.
+ * @property {string[]} allFields - An array of all available fields in a lunr.Index.
+ */
+lunr.Query = function (allFields) {
+ this.clauses = []
+ this.allFields = allFields
+}
+
+/**
+ * Constants for indicating what kind of automatic wildcard insertion will be used when constructing a query clause.
+ *
+ * This allows wildcards to be added to the beginning and end of a term without having to manually do any string
+ * concatenation.
+ *
+ * The wildcard constants can be bitwise combined to select both leading and trailing wildcards.
+ *
+ * @constant
+ * @default
+ * @property {number} wildcard.NONE - The term will have no wildcards inserted, this is the default behaviour
+ * @property {number} wildcard.LEADING - Prepend the term with a wildcard, unless a leading wildcard already exists
+ * @property {number} wildcard.TRAILING - Append a wildcard to the term, unless a trailing wildcard already exists
+ * @see lunr.Query~Clause
+ * @see lunr.Query#clause
+ * @see lunr.Query#term
+ * @example
+ * query.term('foo', {
+ * wildcard: lunr.Query.wildcard.LEADING | lunr.Query.wildcard.TRAILING
+ * })
+ */
+
+lunr.Query.wildcard = new String ("*")
+lunr.Query.wildcard.NONE = 0
+lunr.Query.wildcard.LEADING = 1
+lunr.Query.wildcard.TRAILING = 2
+
+/**
+ * Constants for indicating what kind of presence a term must have in matching documents.
+ *
+ * @constant
+ * @enum {number}
+ * @see lunr.Query~Clause
+ * @see lunr.Query#clause
+ * @see lunr.Query#term
+ * @example
query term with required presence
+ * query.term('foo', { presence: lunr.Query.presence.REQUIRED })
+ */
+lunr.Query.presence = {
+ /**
+ * Term's presence in a document is optional, this is the default value.
+ */
+ OPTIONAL: 1,
+
+ /**
+ * Term's presence in a document is required, documents that do not contain
+ * this term will not be returned.
+ */
+ REQUIRED: 2,
+
+ /**
+ * Term's presence in a document is prohibited, documents that do contain
+ * this term will not be returned.
+ */
+ PROHIBITED: 3
+}
+
+/**
+ * A single clause in a {@link lunr.Query} contains a term and details on how to
+ * match that term against a {@link lunr.Index}.
+ *
+ * @typedef {Object} lunr.Query~Clause
+ * @property {string[]} fields - The fields in an index this clause should be matched against.
+ * @property {number} [boost=1] - Any boost that should be applied when matching this clause.
+ * @property {number} [editDistance] - Whether the term should have fuzzy matching applied, and how fuzzy the match should be.
+ * @property {boolean} [usePipeline] - Whether the term should be passed through the search pipeline.
+ * @property {number} [wildcard=lunr.Query.wildcard.NONE] - Whether the term should have wildcards appended or prepended.
+ * @property {number} [presence=lunr.Query.presence.OPTIONAL] - The terms presence in any matching documents.
+ */
+
+/**
+ * Adds a {@link lunr.Query~Clause} to this query.
+ *
+ * Unless the clause contains the fields to be matched all fields will be matched. In addition
+ * a default boost of 1 is applied to the clause.
+ *
+ * @param {lunr.Query~Clause} clause - The clause to add to this query.
+ * @see lunr.Query~Clause
+ * @returns {lunr.Query}
+ */
+lunr.Query.prototype.clause = function (clause) {
+ if (!('fields' in clause)) {
+ clause.fields = this.allFields
+ }
+
+ if (!('boost' in clause)) {
+ clause.boost = 1
+ }
+
+ if (!('usePipeline' in clause)) {
+ clause.usePipeline = true
+ }
+
+ if (!('wildcard' in clause)) {
+ clause.wildcard = lunr.Query.wildcard.NONE
+ }
+
+ if ((clause.wildcard & lunr.Query.wildcard.LEADING) && (clause.term.charAt(0) != lunr.Query.wildcard)) {
+ clause.term = "*" + clause.term
+ }
+
+ if ((clause.wildcard & lunr.Query.wildcard.TRAILING) && (clause.term.slice(-1) != lunr.Query.wildcard)) {
+ clause.term = "" + clause.term + "*"
+ }
+
+ if (!('presence' in clause)) {
+ clause.presence = lunr.Query.presence.OPTIONAL
+ }
+
+ this.clauses.push(clause)
+
+ return this
+}
+
+/**
+ * A negated query is one in which every clause has a presence of
+ * prohibited. These queries require some special processing to return
+ * the expected results.
+ *
+ * @returns boolean
+ */
+lunr.Query.prototype.isNegated = function () {
+ for (var i = 0; i < this.clauses.length; i++) {
+ if (this.clauses[i].presence != lunr.Query.presence.PROHIBITED) {
+ return false
+ }
+ }
+
+ return true
+}
+
+/**
+ * Adds a term to the current query, under the covers this will create a {@link lunr.Query~Clause}
+ * to the list of clauses that make up this query.
+ *
+ * The term is used as is, i.e. no tokenization will be performed by this method. Instead conversion
+ * to a token or token-like string should be done before calling this method.
+ *
+ * The term will be converted to a string by calling `toString`. Multiple terms can be passed as an
+ * array, each term in the array will share the same options.
+ *
+ * @param {object|object[]} term - The term(s) to add to the query.
+ * @param {object} [options] - Any additional properties to add to the query clause.
+ * @returns {lunr.Query}
+ * @see lunr.Query#clause
+ * @see lunr.Query~Clause
+ * @example
adding a single term to a query
+ * query.term("foo")
+ * @example
adding a single term to a query and specifying search fields, term boost and automatic trailing wildcard
")),e.inlineElement=o}return h.updateStatus("ready"),h._parseMarkup(t,{},e),t}}});function N(){I&&l(document.body).removeClass(I)}function j(){N(),h.req&&h.req.abort()}var I,L="ajax";l.magnificPopup.registerModule(L,{options:{settings:null,cursor:"mfp-ajax-cur",tError:'The content could not be loaded.'},proto:{initAjax:function(){h.types.push(L),I=h.st.ajax.cursor,c(u+"."+L,j),c("BeforeChange."+L,j)},getAjax:function(r){I&&l(document.body).addClass(I),h.updateStatus("loading");var e=l.extend({url:r.src,success:function(e,t,n){n={data:e,xhr:n};d("ParseAjax",n),h.appendContent(l(n.data),L),r.finished=!0,N(),h._setFocus(),setTimeout(function(){h.wrap.addClass(w)},16),h.updateStatus("ready"),d("AjaxContentAdded")},error:function(){N(),r.finished=r.loadError=!0,h.updateStatus("error",h.st.ajax.tError.replace("%url%",r.src))}},h.st.ajax.settings);return h.req=l.ajax(e),""}}});var D;l.magnificPopup.registerModule("image",{options:{markup:'
',cursor:"mfp-zoom-out-cur",titleSrc:"title",verticalFit:!0,tError:'The image could not be loaded.'},proto:{initImage:function(){var e=h.st.image,t=".image";h.types.push("image"),c(b+t,function(){"image"===h.currItem.type&&e.cursor&&l(document.body).addClass(e.cursor)}),c(u+t,function(){e.cursor&&l(document.body).removeClass(e.cursor),C.off("resize"+x)}),c("Resize"+t,h.resizeImage),h.isLowIE&&c("AfterChange",h.resizeImage)},resizeImage:function(){var e,t=h.currItem;t&&t.img&&h.st.image.verticalFit&&(e=0,h.isLowIE&&(e=parseInt(t.img.css("padding-top"),10)+parseInt(t.img.css("padding-bottom"),10)),t.img.css("max-height",h.wH-e))},_onImageHasSize:function(e){e.img&&(e.hasSize=!0,D&&clearInterval(D),e.isCheckingImgSize=!1,d("ImageHasSize",e),e.imgHidden&&(h.content&&h.content.removeClass("mfp-loading"),e.imgHidden=!1))},findImageSize:function(t){var n=0,r=t.img[0],o=function(e){D&&clearInterval(D),D=setInterval(function(){0
',srcAction:"iframe_src",patterns:{youtube:{index:"youtube.com",id:"v=",src:"//www.youtube.com/embed/%id%?autoplay=1"},vimeo:{index:"vimeo.com/",id:"/",src:"//player.vimeo.com/video/%id%?autoplay=1"},gmaps:{index:"//maps.google.",src:"%id%&output=embed"}}},proto:{initIframe:function(){h.types.push(P),c("BeforeChange",function(e,t,n){t!==n&&(t===P?H():n===P&&H(!0))}),c(u+"."+P,function(){H()})},getIframe:function(e,t){var n=e.src,r=h.st.iframe;l.each(r.patterns,function(){if(-1',preload:[0,2],navigateByImgClick:!0,arrows:!0,tPrev:"Previous (Left arrow key)",tNext:"Next (Right arrow key)",tCounter:"%curr% of %total%"},proto:{initGallery:function(){var i=h.st.gallery,e=".mfp-gallery";if(h.direction=!0,!i||!i.enabled)return!1;g+=" mfp-gallery",c(b+e,function(){i.navigateByImgClick&&h.wrap.on("click"+e,".mfp-img",function(){if(1=h.index,h.index=e,h.updateItemHTML()},preloadNearbyImages:function(){for(var e=h.st.gallery.preload,t=Math.min(e[0],h.items.length),n=Math.min(e[1],h.items.length),r=1;r<=(h.direction?n:t);r++)h._preloadItem(h.index+r);for(r=1;r<=(h.direction?t:n);r++)h._preloadItem(h.index-r)},_preloadItem:function(e){var t;e=q(e),h.items[e].preloaded||((t=h.items[e]).parsed||(t=h.parseEl(e)),d("LazyLoad",t),"image"===t.type&&(t.img=l('').on("load.mfploader",function(){t.hasSize=!0}).on("error.mfploader",function(){t.hasSize=!0,t.loadError=!0,d("LazyLoadError",t)}).attr("src",t.src)),t.preloaded=!0)}}});var _="retina";l.magnificPopup.registerModule(_,{options:{replaceSrc:function(e){return e.src.replace(/\.\w+$/,function(e){return"@2x"+e})},ratio:1},proto:{initRetina:function(){var n,r;1t.durationMax?t.durationMax:t.durationMin&&e=u)return b.cancelScroll(!0),e=t,n=g,0===(t=r)&&document.body.focus(),n||(t.focus(),document.activeElement!==t&&(t.setAttribute("tabindex","-1"),t.focus(),t.style.outline="none"),x.scrollTo(0,e)),E("scrollStop",m,r,o),!(y=f=null)},h=function(e){var t,n,r;l+=e-(f=f||e),d=i+s*(n=d=1<(d=0===c?0:l/c)?1:d,"easeInQuad"===(t=m).easing&&(r=n*n),"easeOutQuad"===t.easing&&(r=n*(2-n)),"easeInOutQuad"===t.easing&&(r=n<.5?2*n*n:(4-2*n)*n-1),"easeInCubic"===t.easing&&(r=n*n*n),"easeOutCubic"===t.easing&&(r=--n*n*n+1),"easeInOutCubic"===t.easing&&(r=n<.5?4*n*n*n:(n-1)*(2*n-2)*(2*n-2)+1),"easeInQuart"===t.easing&&(r=n*n*n*n),"easeOutQuart"===t.easing&&(r=1- --n*n*n*n),"easeInOutQuart"===t.easing&&(r=n<.5?8*n*n*n*n:1-8*--n*n*n*n),"easeInQuint"===t.easing&&(r=n*n*n*n*n),"easeOutQuint"===t.easing&&(r=1+--n*n*n*n*n),"easeInOutQuint"===t.easing&&(r=n<.5?16*n*n*n*n*n:1+16*--n*n*n*n*n),(r=t.customEasing?t.customEasing(n):r)||n),x.scrollTo(0,Math.floor(d)),p(d,a)||(y=x.requestAnimationFrame(h),f=e)},0===x.pageYOffset&&x.scrollTo(0,0),t=r,e=m,g||history.pushState&&e.updateURL&&history.pushState({smoothScroll:JSON.stringify(e),anchor:t.id},document.title,t===document.documentElement?"#top":"#"+t.id),"matchMedia"in x&&x.matchMedia("(prefers-reduced-motion)").matches?x.scrollTo(0,Math.floor(a)):(E("scrollStart",m,r,o),b.cancelScroll(!0),x.requestAnimationFrame(h)))};function t(e){if(!e.defaultPrevented&&!(0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey)&&"closest"in e.target&&(o=e.target.closest(r))&&"a"===o.tagName.toLowerCase()&&!e.target.closest(v.ignore)&&o.hostname===x.location.hostname&&o.pathname===x.location.pathname&&/#/.test(o.href)){var t,n;try{n=a(decodeURIComponent(o.hash))}catch(e){n=a(o.hash)}if("#"===n){if(!v.topOnEmptyHash)return;t=document.documentElement}else t=document.querySelector(n);(t=t||"#top"!==n?t:document.documentElement)&&(e.preventDefault(),n=v,history.replaceState&&n.updateURL&&!history.state&&(e=(e=x.location.hash)||"",history.replaceState({smoothScroll:JSON.stringify(n),anchor:e||x.pageYOffset},document.title,e||x.location.href)),b.animateScroll(t,o))}}function i(e){var t;null!==history.state&&history.state.smoothScroll&&history.state.smoothScroll===JSON.stringify(v)&&("string"==typeof(t=history.state.anchor)&&t&&!(t=document.querySelector(a(history.state.anchor)))||b.animateScroll(t,null,{updateURL:!1}))}b.destroy=function(){v&&(document.removeEventListener("click",t,!1),x.removeEventListener("popstate",i,!1),b.cancelScroll(),y=n=o=v=null)};return function(){if(!("querySelector"in document&&"addEventListener"in x&&"requestAnimationFrame"in x&&"closest"in x.Element.prototype))throw"Smooth Scroll: This browser does not support the required JavaScript methods and browser APIs.";b.destroy(),v=w(S,e||{}),n=v.header?document.querySelector(v.header):null,document.addEventListener("click",t,!1),v.updateURL&&v.popstate&&x.addEventListener("popstate",i,!1)}(),b}}),function(e,t){"function"==typeof define&&define.amd?define([],function(){return t(e)}):"object"==typeof exports?module.exports=t(e):e.Gumshoe=t(e)}("undefined"!=typeof global?global:"undefined"!=typeof window?window:this,function(c){"use strict";function f(e,t,n){n.settings.events&&(n=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n}),t.dispatchEvent(n))}function n(e){var t=0;if(e.offsetParent)for(;e;)t+=e.offsetTop,e=e.offsetParent;return 0<=t?t:0}function d(e){e&&e.sort(function(e,t){return n(e.content)=Math.max(document.body.scrollHeight,document.documentElement.scrollHeight,document.body.offsetHeight,document.documentElement.offsetHeight,document.body.clientHeight,document.documentElement.clientHeight)}function p(e,t){var n,r,o=e[e.length-1];if(n=o,r=t,!(!s()||!a(n.content,r,!0)))return o;for(var i=e.length-1;0<=i;i--)if(a(e[i].content,t))return e[i]}function h(e,t){var n;!e||(n=e.nav.closest("li"))&&(n.classList.remove(t.navClass),e.content.classList.remove(t.contentClass),r(n,t),f("gumshoeDeactivate",n,{link:e.nav,content:e.content,settings:t}))}var m={navClass:"active",contentClass:"active",nested:!1,nestedClass:"active",offset:0,reflow:!1,events:!0},r=function(e,t){!t.nested||(e=e.parentNode.closest("li"))&&(e.classList.remove(t.nestedClass),r(e,t))},g=function(e,t){!t.nested||(e=e.parentNode.closest("li"))&&(e.classList.add(t.nestedClass),g(e,t))};return function(e,t){var n,o,i,r,a,s={setup:function(){n=document.querySelectorAll(e),o=[],Array.prototype.forEach.call(n,function(e){var t=document.getElementById(decodeURIComponent(e.hash.substr(1)));t&&o.push({nav:e,content:t})}),d(o)}};s.detect=function(){var e,t,n,r=p(o,a);r?i&&r.content===i.content||(h(i,a),t=a,!(e=r)||(n=e.nav.closest("li"))&&(n.classList.add(t.navClass),e.content.classList.add(t.contentClass),g(n,t),f("gumshoeActivate",n,{link:e.nav,content:e.content,settings:t})),i=r):i&&(h(i,a),i=null)};function u(e){r&&c.cancelAnimationFrame(r),r=c.requestAnimationFrame(s.detect)}function l(e){r&&c.cancelAnimationFrame(r),r=c.requestAnimationFrame(function(){d(o),s.detect()})}s.destroy=function(){i&&h(i,a),c.removeEventListener("scroll",u,!1),a.reflow&&c.removeEventListener("resize",l,!1),a=r=i=n=o=null};return a=function(){var n={};return Array.prototype.forEach.call(arguments,function(e){for(var t in e){if(!e.hasOwnProperty(t))return;n[t]=e[t]}}),n}(m,t||{}),s.setup(),s.detect(),c.addEventListener("scroll",u,!1),a.reflow&&c.addEventListener("resize",l,!1),s}}),$(document).ready(function(){$("#main").fitVids();function e(){(0===$(".author__urls-wrapper button").length?1024<$(window).width():!$(".author__urls-wrapper button").is(":visible"))?$(".sidebar").addClass("sticky"):$(".sidebar").removeClass("sticky")}e(),$(window).resize(function(){e()}),$(".author__urls-wrapper button").on("click",function(){$(".author__urls").toggleClass("is--visible"),$(".author__urls-wrapper button").toggleClass("open")}),$(document).keyup(function(e){27===e.keyCode&&$(".initial-content").hasClass("is--hidden")&&($(".search-content").toggleClass("is--visible"),$(".initial-content").toggleClass("is--hidden"))}),$(".search__toggle").on("click",function(){$(".search-content").toggleClass("is--visible"),$(".initial-content").toggleClass("is--hidden"),setTimeout(function(){$(".search-content input").focus()},400)});new SmoothScroll('a[href*="#"]',{offset:20,speed:400,speedAsDuration:!0,durationMax:500});0<$("nav.toc").length&&new Gumshoe("nav.toc a",{navClass:"active",contentClass:"active",nested:!1,nestedClass:"active",offset:20,reflow:!0,events:!0}),$("a[href$='.jpg'],a[href$='.jpeg'],a[href$='.JPG'],a[href$='.png'],a[href$='.gif'],a[href$='.webp']").addClass("image-popup"),$(".image-popup").magnificPopup({type:"image",tLoading:"Loading image #%curr%...",gallery:{enabled:!0,navigateByImgClick:!0,preload:[0,1]},image:{tError:'Image #%curr% could not be loaded.'},removalDelay:500,mainClass:"mfp-zoom-in",callbacks:{beforeOpen:function(){this.st.image.markup=this.st.image.markup.replace("mfp-figure","mfp-figure mfp-with-anim")}},closeOnContentClick:!0,midClick:!0}),$(".page__content").find("h1, h2, h3, h4, h5, h6").each(function(){var e,t=$(this).attr("id");t&&((e=document.createElement("a")).className="header-link",e.href="#"+t,e.innerHTML='Permalink',e.title="Permalink",$(this).append(e))})});
\ No newline at end of file
diff --git a/assets/js/plugins/gumshoe.js b/assets/js/plugins/gumshoe.js
new file mode 100644
index 0000000..713b6eb
--- /dev/null
+++ b/assets/js/plugins/gumshoe.js
@@ -0,0 +1,484 @@
+/*!
+ * gumshoejs v5.1.1
+ * A simple, framework-agnostic scrollspy script.
+ * (c) 2019 Chris Ferdinandi
+ * MIT License
+ * http://github.com/cferdinandi/gumshoe
+ */
+
+(function (root, factory) {
+ if ( typeof define === 'function' && define.amd ) {
+ define([], (function () {
+ return factory(root);
+ }));
+ } else if ( typeof exports === 'object' ) {
+ module.exports = factory(root);
+ } else {
+ root.Gumshoe = factory(root);
+ }
+})(typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : this, (function (window) {
+
+ 'use strict';
+
+ //
+ // Defaults
+ //
+
+ var defaults = {
+
+ // Active classes
+ navClass: 'active',
+ contentClass: 'active',
+
+ // Nested navigation
+ nested: false,
+ nestedClass: 'active',
+
+ // Offset & reflow
+ offset: 0,
+ reflow: false,
+
+ // Event support
+ events: true
+
+ };
+
+
+ //
+ // Methods
+ //
+
+ /**
+ * Merge two or more objects together.
+ * @param {Object} objects The objects to merge together
+ * @returns {Object} Merged values of defaults and options
+ */
+ var extend = function () {
+ var merged = {};
+ Array.prototype.forEach.call(arguments, (function (obj) {
+ for (var key in obj) {
+ if (!obj.hasOwnProperty(key)) return;
+ merged[key] = obj[key];
+ }
+ }));
+ return merged;
+ };
+
+ /**
+ * Emit a custom event
+ * @param {String} type The event type
+ * @param {Node} elem The element to attach the event to
+ * @param {Object} detail Any details to pass along with the event
+ */
+ var emitEvent = function (type, elem, detail) {
+
+ // Make sure events are enabled
+ if (!detail.settings.events) return;
+
+ // Create a new event
+ var event = new CustomEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ detail: detail
+ });
+
+ // Dispatch the event
+ elem.dispatchEvent(event);
+
+ };
+
+ /**
+ * Get an element's distance from the top of the Document.
+ * @param {Node} elem The element
+ * @return {Number} Distance from the top in pixels
+ */
+ var getOffsetTop = function (elem) {
+ var location = 0;
+ if (elem.offsetParent) {
+ while (elem) {
+ location += elem.offsetTop;
+ elem = elem.offsetParent;
+ }
+ }
+ return location >= 0 ? location : 0;
+ };
+
+ /**
+ * Sort content from first to last in the DOM
+ * @param {Array} contents The content areas
+ */
+ var sortContents = function (contents) {
+ if(contents) {
+ contents.sort((function (item1, item2) {
+ var offset1 = getOffsetTop(item1.content);
+ var offset2 = getOffsetTop(item2.content);
+ if (offset1 < offset2) return -1;
+ return 1;
+ }));
+ }
+ };
+
+ /**
+ * Get the offset to use for calculating position
+ * @param {Object} settings The settings for this instantiation
+ * @return {Float} The number of pixels to offset the calculations
+ */
+ var getOffset = function (settings) {
+
+ // if the offset is a function run it
+ if (typeof settings.offset === 'function') {
+ return parseFloat(settings.offset());
+ }
+
+ // Otherwise, return it as-is
+ return parseFloat(settings.offset);
+
+ };
+
+ /**
+ * Get the document element's height
+ * @private
+ * @returns {Number}
+ */
+ var getDocumentHeight = function () {
+ return Math.max(
+ document.body.scrollHeight, document.documentElement.scrollHeight,
+ document.body.offsetHeight, document.documentElement.offsetHeight,
+ document.body.clientHeight, document.documentElement.clientHeight
+ );
+ };
+
+ /**
+ * Determine if an element is in view
+ * @param {Node} elem The element
+ * @param {Object} settings The settings for this instantiation
+ * @param {Boolean} bottom If true, check if element is above bottom of viewport instead
+ * @return {Boolean} Returns true if element is in the viewport
+ */
+ var isInView = function (elem, settings, bottom) {
+ var bounds = elem.getBoundingClientRect();
+ var offset = getOffset(settings);
+ if (bottom) {
+ return parseInt(bounds.bottom, 10) < (window.innerHeight || document.documentElement.clientHeight);
+ }
+ return parseInt(bounds.top, 10) <= offset;
+ };
+
+ /**
+ * Check if at the bottom of the viewport
+ * @return {Boolean} If true, page is at the bottom of the viewport
+ */
+ var isAtBottom = function () {
+ if (window.innerHeight + window.pageYOffset >= getDocumentHeight()) return true;
+ return false;
+ };
+
+ /**
+ * Check if the last item should be used (even if not at the top of the page)
+ * @param {Object} item The last item
+ * @param {Object} settings The settings for this instantiation
+ * @return {Boolean} If true, use the last item
+ */
+ var useLastItem = function (item, settings) {
+ if (isAtBottom() && isInView(item.content, settings, true)) return true;
+ return false;
+ };
+
+ /**
+ * Get the active content
+ * @param {Array} contents The content areas
+ * @param {Object} settings The settings for this instantiation
+ * @return {Object} The content area and matching navigation link
+ */
+ var getActive = function (contents, settings) {
+ var last = contents[contents.length-1];
+ if (useLastItem(last, settings)) return last;
+ for (var i = contents.length - 1; i >= 0; i--) {
+ if (isInView(contents[i].content, settings)) return contents[i];
+ }
+ };
+
+ /**
+ * Deactivate parent navs in a nested navigation
+ * @param {Node} nav The starting navigation element
+ * @param {Object} settings The settings for this instantiation
+ */
+ var deactivateNested = function (nav, settings) {
+
+ // If nesting isn't activated, bail
+ if (!settings.nested) return;
+
+ // Get the parent navigation
+ var li = nav.parentNode.closest('li');
+ if (!li) return;
+
+ // Remove the active class
+ li.classList.remove(settings.nestedClass);
+
+ // Apply recursively to any parent navigation elements
+ deactivateNested(li, settings);
+
+ };
+
+ /**
+ * Deactivate a nav and content area
+ * @param {Object} items The nav item and content to deactivate
+ * @param {Object} settings The settings for this instantiation
+ */
+ var deactivate = function (items, settings) {
+
+ // Make sure their are items to deactivate
+ if (!items) return;
+
+ // Get the parent list item
+ var li = items.nav.closest('li');
+ if (!li) return;
+
+ // Remove the active class from the nav and content
+ li.classList.remove(settings.navClass);
+ items.content.classList.remove(settings.contentClass);
+
+ // Deactivate any parent navs in a nested navigation
+ deactivateNested(li, settings);
+
+ // Emit a custom event
+ emitEvent('gumshoeDeactivate', li, {
+ link: items.nav,
+ content: items.content,
+ settings: settings
+ });
+
+ };
+
+
+ /**
+ * Activate parent navs in a nested navigation
+ * @param {Node} nav The starting navigation element
+ * @param {Object} settings The settings for this instantiation
+ */
+ var activateNested = function (nav, settings) {
+
+ // If nesting isn't activated, bail
+ if (!settings.nested) return;
+
+ // Get the parent navigation
+ var li = nav.parentNode.closest('li');
+ if (!li) return;
+
+ // Add the active class
+ li.classList.add(settings.nestedClass);
+
+ // Apply recursively to any parent navigation elements
+ activateNested(li, settings);
+
+ };
+
+ /**
+ * Activate a nav and content area
+ * @param {Object} items The nav item and content to activate
+ * @param {Object} settings The settings for this instantiation
+ */
+ var activate = function (items, settings) {
+
+ // Make sure their are items to activate
+ if (!items) return;
+
+ // Get the parent list item
+ var li = items.nav.closest('li');
+ if (!li) return;
+
+ // Add the active class to the nav and content
+ li.classList.add(settings.navClass);
+ items.content.classList.add(settings.contentClass);
+
+ // Activate any parent navs in a nested navigation
+ activateNested(li, settings);
+
+ // Emit a custom event
+ emitEvent('gumshoeActivate', li, {
+ link: items.nav,
+ content: items.content,
+ settings: settings
+ });
+
+ };
+
+ /**
+ * Create the Constructor object
+ * @param {String} selector The selector to use for navigation items
+ * @param {Object} options User options and settings
+ */
+ var Constructor = function (selector, options) {
+
+ //
+ // Variables
+ //
+
+ var publicAPIs = {};
+ var navItems, contents, current, timeout, settings;
+
+
+ //
+ // Methods
+ //
+
+ /**
+ * Set variables from DOM elements
+ */
+ publicAPIs.setup = function () {
+
+ // Get all nav items
+ navItems = document.querySelectorAll(selector);
+
+ // Create contents array
+ contents = [];
+
+ // Loop through each item, get it's matching content, and push to the array
+ Array.prototype.forEach.call(navItems, (function (item) {
+
+ // Get the content for the nav item
+ var content = document.getElementById(decodeURIComponent(item.hash.substr(1)));
+ if (!content) return;
+
+ // Push to the contents array
+ contents.push({
+ nav: item,
+ content: content
+ });
+
+ }));
+
+ // Sort contents by the order they appear in the DOM
+ sortContents(contents);
+
+ };
+
+ /**
+ * Detect which content is currently active
+ */
+ publicAPIs.detect = function () {
+
+ // Get the active content
+ var active = getActive(contents, settings);
+
+ // if there's no active content, deactivate and bail
+ if (!active) {
+ if (current) {
+ deactivate(current, settings);
+ current = null;
+ }
+ return;
+ }
+
+ // If the active content is the one currently active, do nothing
+ if (current && active.content === current.content) return;
+
+ // Deactivate the current content and activate the new content
+ deactivate(current, settings);
+ activate(active, settings);
+
+ // Update the currently active content
+ current = active;
+
+ };
+
+ /**
+ * Detect the active content on scroll
+ * Debounced for performance
+ */
+ var scrollHandler = function (event) {
+
+ // If there's a timer, cancel it
+ if (timeout) {
+ window.cancelAnimationFrame(timeout);
+ }
+
+ // Setup debounce callback
+ timeout = window.requestAnimationFrame(publicAPIs.detect);
+
+ };
+
+ /**
+ * Update content sorting on resize
+ * Debounced for performance
+ */
+ var resizeHandler = function (event) {
+
+ // If there's a timer, cancel it
+ if (timeout) {
+ window.cancelAnimationFrame(timeout);
+ }
+
+ // Setup debounce callback
+ timeout = window.requestAnimationFrame((function () {
+ sortContents(contents);
+ publicAPIs.detect();
+ }));
+
+ };
+
+ /**
+ * Destroy the current instantiation
+ */
+ publicAPIs.destroy = function () {
+
+ // Undo DOM changes
+ if (current) {
+ deactivate(current, settings);
+ }
+
+ // Remove event listeners
+ window.removeEventListener('scroll', scrollHandler, false);
+ if (settings.reflow) {
+ window.removeEventListener('resize', resizeHandler, false);
+ }
+
+ // Reset variables
+ contents = null;
+ navItems = null;
+ current = null;
+ timeout = null;
+ settings = null;
+
+ };
+
+ /**
+ * Initialize the current instantiation
+ */
+ var init = function () {
+
+ // Merge user options into defaults
+ settings = extend(defaults, options || {});
+
+ // Setup variables based on the current DOM
+ publicAPIs.setup();
+
+ // Find the currently active content
+ publicAPIs.detect();
+
+ // Setup event listeners
+ window.addEventListener('scroll', scrollHandler, false);
+ if (settings.reflow) {
+ window.addEventListener('resize', resizeHandler, false);
+ }
+
+ };
+
+
+ //
+ // Initialize and return the public APIs
+ //
+
+ init();
+ return publicAPIs;
+
+ };
+
+
+ //
+ // Return the Constructor
+ //
+
+ return Constructor;
+
+}));
\ No newline at end of file
diff --git a/assets/js/plugins/jquery.ba-throttle-debounce.js b/assets/js/plugins/jquery.ba-throttle-debounce.js
new file mode 100644
index 0000000..fa30bdf
--- /dev/null
+++ b/assets/js/plugins/jquery.ba-throttle-debounce.js
@@ -0,0 +1,252 @@
+/*!
+ * jQuery throttle / debounce - v1.1 - 3/7/2010
+ * http://benalman.com/projects/jquery-throttle-debounce-plugin/
+ *
+ * Copyright (c) 2010 "Cowboy" Ben Alman
+ * Dual licensed under the MIT and GPL licenses.
+ * http://benalman.com/about/license/
+ */
+
+// Script: jQuery throttle / debounce: Sometimes, less is more!
+//
+// *Version: 1.1, Last updated: 3/7/2010*
+//
+// Project Home - http://benalman.com/projects/jquery-throttle-debounce-plugin/
+// GitHub - http://github.com/cowboy/jquery-throttle-debounce/
+// Source - http://github.com/cowboy/jquery-throttle-debounce/raw/master/jquery.ba-throttle-debounce.js
+// (Minified) - http://github.com/cowboy/jquery-throttle-debounce/raw/master/jquery.ba-throttle-debounce.min.js (0.7kb)
+//
+// About: License
+//
+// Copyright (c) 2010 "Cowboy" Ben Alman,
+// Dual licensed under the MIT and GPL licenses.
+// http://benalman.com/about/license/
+//
+// About: Examples
+//
+// These working examples, complete with fully commented code, illustrate a few
+// ways in which this plugin can be used.
+//
+// Throttle - http://benalman.com/code/projects/jquery-throttle-debounce/examples/throttle/
+// Debounce - http://benalman.com/code/projects/jquery-throttle-debounce/examples/debounce/
+//
+// About: Support and Testing
+//
+// Information about what version or versions of jQuery this plugin has been
+// tested with, what browsers it has been tested in, and where the unit tests
+// reside (so you can test it yourself).
+//
+// jQuery Versions - none, 1.3.2, 1.4.2
+// Browsers Tested - Internet Explorer 6-8, Firefox 2-3.6, Safari 3-4, Chrome 4-5, Opera 9.6-10.1.
+// Unit Tests - http://benalman.com/code/projects/jquery-throttle-debounce/unit/
+//
+// About: Release History
+//
+// 1.1 - (3/7/2010) Fixed a bug in where trailing callbacks
+// executed later than they should. Reworked a fair amount of internal
+// logic as well.
+// 1.0 - (3/6/2010) Initial release as a stand-alone project. Migrated over
+// from jquery-misc repo v0.4 to jquery-throttle repo v1.0, added the
+// no_trailing throttle parameter and debounce functionality.
+//
+// Topic: Note for non-jQuery users
+//
+// jQuery isn't actually required for this plugin, because nothing internal
+// uses any jQuery methods or properties. jQuery is just used as a namespace
+// under which these methods can exist.
+//
+// Since jQuery isn't actually required for this plugin, if jQuery doesn't exist
+// when this plugin is loaded, the method described below will be created in
+// the `Cowboy` namespace. Usage will be exactly the same, but instead of
+// $.method() or jQuery.method(), you'll need to use Cowboy.method().
+
+(function(window,undefined){
+ '$:nomunge'; // Used by YUI compressor.
+
+ // Since jQuery really isn't required for this plugin, use `jQuery` as the
+ // namespace only if it already exists, otherwise use the `Cowboy` namespace,
+ // creating it if necessary.
+ var $ = window.jQuery || window.Cowboy || ( window.Cowboy = {} ),
+
+ // Internal method reference.
+ jq_throttle;
+
+ // Method: jQuery.throttle
+ //
+ // Throttle execution of a function. Especially useful for rate limiting
+ // execution of handlers on events like resize and scroll. If you want to
+ // rate-limit execution of a function to a single time, see the
+ // method.
+ //
+ // In this visualization, | is a throttled-function call and X is the actual
+ // callback execution:
+ //
+ // > Throttled with `no_trailing` specified as false or unspecified:
+ // > ||||||||||||||||||||||||| (pause) |||||||||||||||||||||||||
+ // > X X X X X X X X X X X X
+ // >
+ // > Throttled with `no_trailing` specified as true:
+ // > ||||||||||||||||||||||||| (pause) |||||||||||||||||||||||||
+ // > X X X X X X X X X X
+ //
+ // Usage:
+ //
+ // > var throttled = jQuery.throttle( delay, [ no_trailing, ] callback );
+ // >
+ // > jQuery('selector').bind( 'someevent', throttled );
+ // > jQuery('selector').unbind( 'someevent', throttled );
+ //
+ // This also works in jQuery 1.4+:
+ //
+ // > jQuery('selector').bind( 'someevent', jQuery.throttle( delay, [ no_trailing, ] callback ) );
+ // > jQuery('selector').unbind( 'someevent', callback );
+ //
+ // Arguments:
+ //
+ // delay - (Number) A zero-or-greater delay in milliseconds. For event
+ // callbacks, values around 100 or 250 (or even higher) are most useful.
+ // no_trailing - (Boolean) Optional, defaults to false. If no_trailing is
+ // true, callback will only execute every `delay` milliseconds while the
+ // throttled-function is being called. If no_trailing is false or
+ // unspecified, callback will be executed one final time after the last
+ // throttled-function call. (After the throttled-function has not been
+ // called for `delay` milliseconds, the internal counter is reset)
+ // callback - (Function) A function to be executed after delay milliseconds.
+ // The `this` context and all arguments are passed through, as-is, to
+ // `callback` when the throttled-function is executed.
+ //
+ // Returns:
+ //
+ // (Function) A new, throttled, function.
+
+ $.throttle = jq_throttle = function( delay, no_trailing, callback, debounce_mode ) {
+ // After wrapper has stopped being called, this timeout ensures that
+ // `callback` is executed at the proper times in `throttle` and `end`
+ // debounce modes.
+ var timeout_id,
+
+ // Keep track of the last time `callback` was executed.
+ last_exec = 0;
+
+ // `no_trailing` defaults to falsy.
+ if ( typeof no_trailing !== 'boolean' ) {
+ debounce_mode = callback;
+ callback = no_trailing;
+ no_trailing = undefined;
+ }
+
+ // The `wrapper` function encapsulates all of the throttling / debouncing
+ // functionality and when executed will limit the rate at which `callback`
+ // is executed.
+ function wrapper() {
+ var that = this,
+ elapsed = +new Date() - last_exec,
+ args = arguments;
+
+ // Execute `callback` and update the `last_exec` timestamp.
+ function exec() {
+ last_exec = +new Date();
+ callback.apply( that, args );
+ };
+
+ // If `debounce_mode` is true (at_begin) this is used to clear the flag
+ // to allow future `callback` executions.
+ function clear() {
+ timeout_id = undefined;
+ };
+
+ if ( debounce_mode && !timeout_id ) {
+ // Since `wrapper` is being called for the first time and
+ // `debounce_mode` is true (at_begin), execute `callback`.
+ exec();
+ }
+
+ // Clear any existing timeout.
+ timeout_id && clearTimeout( timeout_id );
+
+ if ( debounce_mode === undefined && elapsed > delay ) {
+ // In throttle mode, if `delay` time has been exceeded, execute
+ // `callback`.
+ exec();
+
+ } else if ( no_trailing !== true ) {
+ // In trailing throttle mode, since `delay` time has not been
+ // exceeded, schedule `callback` to execute `delay` ms after most
+ // recent execution.
+ //
+ // If `debounce_mode` is true (at_begin), schedule `clear` to execute
+ // after `delay` ms.
+ //
+ // If `debounce_mode` is false (at end), schedule `callback` to
+ // execute after `delay` ms.
+ timeout_id = setTimeout( debounce_mode ? clear : exec, debounce_mode === undefined ? delay - elapsed : delay );
+ }
+ };
+
+ // Set the guid of `wrapper` function to the same of original callback, so
+ // it can be removed in jQuery 1.4+ .unbind or .die by using the original
+ // callback as a reference.
+ if ( $.guid ) {
+ wrapper.guid = callback.guid = callback.guid || $.guid++;
+ }
+
+ // Return the wrapper function.
+ return wrapper;
+ };
+
+ // Method: jQuery.debounce
+ //
+ // Debounce execution of a function. Debouncing, unlike throttling,
+ // guarantees that a function is only executed a single time, either at the
+ // very beginning of a series of calls, or at the very end. If you want to
+ // simply rate-limit execution of a function, see the
+ // method.
+ //
+ // In this visualization, | is a debounced-function call and X is the actual
+ // callback execution:
+ //
+ // > Debounced with `at_begin` specified as false or unspecified:
+ // > ||||||||||||||||||||||||| (pause) |||||||||||||||||||||||||
+ // > X X
+ // >
+ // > Debounced with `at_begin` specified as true:
+ // > ||||||||||||||||||||||||| (pause) |||||||||||||||||||||||||
+ // > X X
+ //
+ // Usage:
+ //
+ // > var debounced = jQuery.debounce( delay, [ at_begin, ] callback );
+ // >
+ // > jQuery('selector').bind( 'someevent', debounced );
+ // > jQuery('selector').unbind( 'someevent', debounced );
+ //
+ // This also works in jQuery 1.4+:
+ //
+ // > jQuery('selector').bind( 'someevent', jQuery.debounce( delay, [ at_begin, ] callback ) );
+ // > jQuery('selector').unbind( 'someevent', callback );
+ //
+ // Arguments:
+ //
+ // delay - (Number) A zero-or-greater delay in milliseconds. For event
+ // callbacks, values around 100 or 250 (or even higher) are most useful.
+ // at_begin - (Boolean) Optional, defaults to false. If at_begin is false or
+ // unspecified, callback will only be executed `delay` milliseconds after
+ // the last debounced-function call. If at_begin is true, callback will be
+ // executed only at the first debounced-function call. (After the
+ // throttled-function has not been called for `delay` milliseconds, the
+ // internal counter is reset)
+ // callback - (Function) A function to be executed after delay milliseconds.
+ // The `this` context and all arguments are passed through, as-is, to
+ // `callback` when the debounced-function is executed.
+ //
+ // Returns:
+ //
+ // (Function) A new, debounced, function.
+
+ $.debounce = function( delay, at_begin, callback ) {
+ return callback === undefined
+ ? jq_throttle( delay, at_begin, false )
+ : jq_throttle( delay, callback, at_begin !== false );
+ };
+
+})(this);
diff --git a/assets/js/plugins/jquery.fitvids.js b/assets/js/plugins/jquery.fitvids.js
new file mode 100644
index 0000000..5c2f85c
--- /dev/null
+++ b/assets/js/plugins/jquery.fitvids.js
@@ -0,0 +1,82 @@
+/*jshint browser:true */
+/*!
+* FitVids 1.1
+*
+* Copyright 2013, Chris Coyier - http://css-tricks.com + Dave Rupert - http://daverupert.com
+* Credit to Thierry Koblentz - http://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/
+* Released under the WTFPL license - http://sam.zoy.org/wtfpl/
+*
+*/
+
+;(function( $ ){
+
+ 'use strict';
+
+ $.fn.fitVids = function( options ) {
+ var settings = {
+ customSelector: null,
+ ignore: null
+ };
+
+ if(!document.getElementById('fit-vids-style')) {
+ // appendStyles: https://github.com/toddmotto/fluidvids/blob/master/dist/fluidvids.js
+ var head = document.head || document.getElementsByTagName('head')[0];
+ var css = '.fluid-width-video-wrapper{width:100%;position:relative;padding:0;}.fluid-width-video-wrapper iframe,.fluid-width-video-wrapper object,.fluid-width-video-wrapper embed {position:absolute;top:0;left:0;width:100%;height:100%;}';
+ var div = document.createElement("div");
+ div.innerHTML = '
x
';
+ head.appendChild(div.childNodes[1]);
+ }
+
+ if ( options ) {
+ $.extend( settings, options );
+ }
+
+ return this.each(function(){
+ var selectors = [
+ 'iframe[src*="player.vimeo.com"]',
+ 'iframe[src*="youtube.com"]',
+ 'iframe[src*="youtube-nocookie.com"]',
+ 'iframe[src*="kickstarter.com"][src*="video.html"]',
+ 'object',
+ 'embed'
+ ];
+
+ if (settings.customSelector) {
+ selectors.push(settings.customSelector);
+ }
+
+ var ignoreList = '.fitvidsignore';
+
+ if(settings.ignore) {
+ ignoreList = ignoreList + ', ' + settings.ignore;
+ }
+
+ var $allVideos = $(this).find(selectors.join(','));
+ $allVideos = $allVideos.not('object object'); // SwfObj conflict patch
+ $allVideos = $allVideos.not(ignoreList); // Disable FitVids on this video.
+
+ $allVideos.each(function(count){
+ var $this = $(this);
+ if($this.parents(ignoreList).length > 0) {
+ return; // Disable FitVids on this video.
+ }
+ if (this.tagName.toLowerCase() === 'embed' && $this.parent('object').length || $this.parent('.fluid-width-video-wrapper').length) { return; }
+ if ((!$this.css('height') && !$this.css('width')) && (isNaN($this.attr('height')) || isNaN($this.attr('width'))))
+ {
+ $this.attr('height', 9);
+ $this.attr('width', 16);
+ }
+ var height = ( this.tagName.toLowerCase() === 'object' || ($this.attr('height') && !isNaN(parseInt($this.attr('height'), 10))) ) ? parseInt($this.attr('height'), 10) : $this.height(),
+ width = !isNaN(parseInt($this.attr('width'), 10)) ? parseInt($this.attr('width'), 10) : $this.width(),
+ aspectRatio = height / width;
+ if(!$this.attr('id')){
+ var videoID = 'fitvid' + count;
+ $this.attr('id', videoID);
+ }
+ $this.wrap('').parent('.fluid-width-video-wrapper').css('padding-top', (aspectRatio * 100)+'%');
+ $this.removeAttr('height').removeAttr('width');
+ });
+ });
+ };
+// Works with either jQuery or Zepto
+})( window.jQuery || window.Zepto );
\ No newline at end of file
diff --git a/assets/js/plugins/jquery.greedy-navigation.js b/assets/js/plugins/jquery.greedy-navigation.js
new file mode 100644
index 0000000..d8f3237
--- /dev/null
+++ b/assets/js/plugins/jquery.greedy-navigation.js
@@ -0,0 +1,127 @@
+/*
+GreedyNav.js - http://lukejacksonn.com/actuate
+Licensed under the MIT license - http://opensource.org/licenses/MIT
+Copyright (c) 2015 Luke Jackson
+*/
+
+$(function() {
+
+ var $btn = $("nav.greedy-nav .greedy-nav__toggle");
+ var $vlinks = $("nav.greedy-nav .visible-links");
+ var $hlinks = $("nav.greedy-nav .hidden-links");
+ var $nav = $("nav.greedy-nav");
+ var $logo = $('nav.greedy-nav .site-logo');
+ var $logoImg = $('nav.greedy-nav .site-logo img');
+ var $title = $("nav.greedy-nav .site-title");
+ var $search = $('nav.greedy-nav button.search__toggle');
+
+ var numOfItems, totalSpace, closingTime, breakWidths;
+
+ // This function measures both hidden and visible links and sets the navbar breakpoints
+ // This is called the first time the script runs and everytime the "check()" function detects a change of window width that reached a different CSS width breakpoint, which affects the size of navbar Items
+ // Please note that "CSS width breakpoints" (which are only 4) !== "navbar breakpoints" (which are as many as the number of items on the navbar)
+ function measureLinks(){
+ numOfItems = 0;
+ totalSpace = 0;
+ closingTime = 1000;
+ breakWidths = [];
+
+ // Adds the width of a navItem in order to create breakpoints for the navbar
+ function addWidth(i, w) {
+ totalSpace += w;
+ numOfItems += 1;
+ breakWidths.push(totalSpace);
+ }
+
+ // Measures the width of hidden links by making a temporary clone of them and positioning under visible links
+ function hiddenWidth(obj){
+ var clone = obj.clone();
+ clone.css("visibility","hidden");
+ $vlinks.append(clone);
+ addWidth(0, clone.outerWidth());
+ clone.remove();
+ }
+ // Measure both visible and hidden links widths
+ $vlinks.children().outerWidth(addWidth);
+ $hlinks.children().each(function(){hiddenWidth($(this))});
+ }
+ // Get initial state
+ measureLinks();
+
+ var winWidth = $( window ).width();
+ // Set the last measured CSS width breakpoint: 0: <768px, 1: <1024px, 2: < 1280px, 3: >= 1280px.
+ var lastBreakpoint = winWidth < 768 ? 0 : winWidth < 1024 ? 1 : winWidth < 1280 ? 2 : 3;
+
+ var availableSpace, numOfVisibleItems, requiredSpace, timer;
+
+ function check() {
+
+ winWidth = $( window ).width();
+ // Set the current CSS width breakpoint: 0: <768px, 1: <1024px, 2: < 1280px, 3: >= 1280px.
+ var curBreakpoint = winWidth < 768 ? 0 : winWidth < 1024 ? 1 : winWidth < 1280 ? 2 : 3;
+ // If current breakpoint is different from last measured breakpoint, measureLinks again
+ if(curBreakpoint !== lastBreakpoint) measureLinks();
+ // Set the last measured CSS width breakpoint with the current breakpoint
+ lastBreakpoint = curBreakpoint;
+
+ // Get instant state
+ numOfVisibleItems = $vlinks.children().length;
+ // Decrease the width of visible elements from the nav innerWidth to find out the available space for navItems
+ availableSpace = /* nav */ $nav.innerWidth()
+ - /* logo */ ($logo.length !== 0 ? $logo.outerWidth(true) : 0)
+ - /* title */ $title.outerWidth(true)
+ - /* search */ ($search.length !== 0 ? $search.outerWidth(true) : 0)
+ - /* toggle */ (numOfVisibleItems !== breakWidths.length ? $btn.outerWidth(true) : 0);
+ requiredSpace = breakWidths[numOfVisibleItems - 1];
+
+ // There is not enought space
+ if (requiredSpace > availableSpace) {
+ $vlinks.children().last().prependTo($hlinks);
+ numOfVisibleItems -= 1;
+ check();
+ // There is more than enough space. If only one element is hidden, add the toggle width to the available space
+ } else if (availableSpace + (numOfVisibleItems === breakWidths.length - 1?$btn.outerWidth(true):0) > breakWidths[numOfVisibleItems]) {
+ $hlinks.children().first().appendTo($vlinks);
+ numOfVisibleItems += 1;
+ check();
+ }
+ // Update the button accordingly
+ $btn.attr("count", numOfItems - numOfVisibleItems);
+ if (numOfVisibleItems === numOfItems) {
+ $btn.addClass('hidden');
+ } else $btn.removeClass('hidden');
+ }
+
+ // Window listeners
+ $(window).resize(function() {
+ check();
+ });
+
+ $btn.on('click', function() {
+ $hlinks.toggleClass('hidden');
+ $(this).toggleClass('close');
+ clearTimeout(timer);
+ });
+
+ $hlinks.on('mouseleave', function() {
+ // Mouse has left, start the timer
+ timer = setTimeout(function() {
+ $hlinks.addClass('hidden');
+ }, closingTime);
+ }).on('mouseenter', function() {
+ // Mouse is back, cancel the timer
+ clearTimeout(timer);
+ })
+
+ // check if page has a logo
+ if($logoImg.length !== 0){
+ // check if logo is not loaded
+ if(!($logoImg[0].complete || $logoImg[0].naturalWidth !== 0)){
+ // if logo is not loaded wait for logo to load or fail to check
+ $logoImg.one("load error", check);
+ // if logo is already loaded just check
+ } else check();
+ // if page does not have a logo just check
+ } else check();
+
+});
diff --git a/assets/js/plugins/jquery.magnific-popup.js b/assets/js/plugins/jquery.magnific-popup.js
new file mode 100644
index 0000000..7d1d197
--- /dev/null
+++ b/assets/js/plugins/jquery.magnific-popup.js
@@ -0,0 +1,1860 @@
+/*! Magnific Popup - v1.1.0 - 2016-02-20
+* http://dimsemenov.com/plugins/magnific-popup/
+* Copyright (c) 2016 Dmitry Semenov; */
+;(function (factory) {
+ if (typeof define === 'function' && define.amd) {
+ // AMD. Register as an anonymous module.
+ define(['jquery'], factory);
+ } else if (typeof exports === 'object') {
+ // Node/CommonJS
+ factory(require('jquery'));
+ } else {
+ // Browser globals
+ factory(window.jQuery || window.Zepto);
+ }
+ }(function($) {
+
+ /*>>core*/
+ /**
+ *
+ * Magnific Popup Core JS file
+ *
+ */
+
+
+ /**
+ * Private static constants
+ */
+ var CLOSE_EVENT = 'Close',
+ BEFORE_CLOSE_EVENT = 'BeforeClose',
+ AFTER_CLOSE_EVENT = 'AfterClose',
+ BEFORE_APPEND_EVENT = 'BeforeAppend',
+ MARKUP_PARSE_EVENT = 'MarkupParse',
+ OPEN_EVENT = 'Open',
+ CHANGE_EVENT = 'Change',
+ NS = 'mfp',
+ EVENT_NS = '.' + NS,
+ READY_CLASS = 'mfp-ready',
+ REMOVING_CLASS = 'mfp-removing',
+ PREVENT_CLOSE_CLASS = 'mfp-prevent-close';
+
+
+ /**
+ * Private vars
+ */
+ /*jshint -W079 */
+ var mfp, // As we have only one instance of MagnificPopup object, we define it locally to not to use 'this'
+ MagnificPopup = function(){},
+ _isJQ = !!(window.jQuery),
+ _prevStatus,
+ _window = $(window),
+ _document,
+ _prevContentType,
+ _wrapClasses,
+ _currPopupType;
+
+
+ /**
+ * Private functions
+ */
+ var _mfpOn = function(name, f) {
+ mfp.ev.on(NS + name + EVENT_NS, f);
+ },
+ _getEl = function(className, appendTo, html, raw) {
+ var el = document.createElement('div');
+ el.className = 'mfp-'+className;
+ if(html) {
+ el.innerHTML = html;
+ }
+ if(!raw) {
+ el = $(el);
+ if(appendTo) {
+ el.appendTo(appendTo);
+ }
+ } else if(appendTo) {
+ appendTo.appendChild(el);
+ }
+ return el;
+ },
+ _mfpTrigger = function(e, data) {
+ mfp.ev.triggerHandler(NS + e, data);
+
+ if(mfp.st.callbacks) {
+ // converts "mfpEventName" to "eventName" callback and triggers it if it's present
+ e = e.charAt(0).toLowerCase() + e.slice(1);
+ if(mfp.st.callbacks[e]) {
+ mfp.st.callbacks[e].apply(mfp, $.isArray(data) ? data : [data]);
+ }
+ }
+ },
+ _getCloseBtn = function(type) {
+ if(type !== _currPopupType || !mfp.currTemplate.closeBtn) {
+ mfp.currTemplate.closeBtn = $( mfp.st.closeMarkup.replace('%title%', mfp.st.tClose ) );
+ _currPopupType = type;
+ }
+ return mfp.currTemplate.closeBtn;
+ },
+ // Initialize Magnific Popup only when called at least once
+ _checkInstance = function() {
+ if(!$.magnificPopup.instance) {
+ /*jshint -W020 */
+ mfp = new MagnificPopup();
+ mfp.init();
+ $.magnificPopup.instance = mfp;
+ }
+ },
+ // CSS transition detection, http://stackoverflow.com/questions/7264899/detect-css-transitions-using-javascript-and-without-modernizr
+ supportsTransitions = function() {
+ var s = document.createElement('p').style, // 's' for style. better to create an element if body yet to exist
+ v = ['ms','O','Moz','Webkit']; // 'v' for vendor
+
+ if( s['transition'] !== undefined ) {
+ return true;
+ }
+
+ while( v.length ) {
+ if( v.pop() + 'Transition' in s ) {
+ return true;
+ }
+ }
+
+ return false;
+ };
+
+
+
+ /**
+ * Public functions
+ */
+ MagnificPopup.prototype = {
+
+ constructor: MagnificPopup,
+
+ /**
+ * Initializes Magnific Popup plugin.
+ * This function is triggered only once when $.fn.magnificPopup or $.magnificPopup is executed
+ */
+ init: function() {
+ var appVersion = navigator.appVersion;
+ mfp.isLowIE = mfp.isIE8 = document.all && !document.addEventListener;
+ mfp.isAndroid = (/android/gi).test(appVersion);
+ mfp.isIOS = (/iphone|ipad|ipod/gi).test(appVersion);
+ mfp.supportsTransition = supportsTransitions();
+
+ // We disable fixed positioned lightbox on devices that don't handle it nicely.
+ // If you know a better way of detecting this - let me know.
+ mfp.probablyMobile = (mfp.isAndroid || mfp.isIOS || /(Opera Mini)|Kindle|webOS|BlackBerry|(Opera Mobi)|(Windows Phone)|IEMobile/i.test(navigator.userAgent) );
+ _document = $(document);
+
+ mfp.popupsCache = {};
+ },
+
+ /**
+ * Opens popup
+ * @param data [description]
+ */
+ open: function(data) {
+
+ var i;
+
+ if(data.isObj === false) {
+ // convert jQuery collection to array to avoid conflicts later
+ mfp.items = data.items.toArray();
+
+ mfp.index = 0;
+ var items = data.items,
+ item;
+ for(i = 0; i < items.length; i++) {
+ item = items[i];
+ if(item.parsed) {
+ item = item.el[0];
+ }
+ if(item === data.el[0]) {
+ mfp.index = i;
+ break;
+ }
+ }
+ } else {
+ mfp.items = $.isArray(data.items) ? data.items : [data.items];
+ mfp.index = data.index || 0;
+ }
+
+ // if popup is already opened - we just update the content
+ if(mfp.isOpen) {
+ mfp.updateItemHTML();
+ return;
+ }
+
+ mfp.types = [];
+ _wrapClasses = '';
+ if(data.mainEl && data.mainEl.length) {
+ mfp.ev = data.mainEl.eq(0);
+ } else {
+ mfp.ev = _document;
+ }
+
+ if(data.key) {
+ if(!mfp.popupsCache[data.key]) {
+ mfp.popupsCache[data.key] = {};
+ }
+ mfp.currTemplate = mfp.popupsCache[data.key];
+ } else {
+ mfp.currTemplate = {};
+ }
+
+
+
+ mfp.st = $.extend(true, {}, $.magnificPopup.defaults, data );
+ mfp.fixedContentPos = mfp.st.fixedContentPos === 'auto' ? !mfp.probablyMobile : mfp.st.fixedContentPos;
+
+ if(mfp.st.modal) {
+ mfp.st.closeOnContentClick = false;
+ mfp.st.closeOnBgClick = false;
+ mfp.st.showCloseBtn = false;
+ mfp.st.enableEscapeKey = false;
+ }
+
+
+ // Building markup
+ // main containers are created only once
+ if(!mfp.bgOverlay) {
+
+ // Dark overlay
+ mfp.bgOverlay = _getEl('bg').on('click'+EVENT_NS, function() {
+ mfp.close();
+ });
+
+ mfp.wrap = _getEl('wrap').attr('tabindex', -1).on('click'+EVENT_NS, function(e) {
+ if(mfp._checkIfClose(e.target)) {
+ mfp.close();
+ }
+ });
+
+ mfp.container = _getEl('container', mfp.wrap);
+ }
+
+ mfp.contentContainer = _getEl('content');
+ if(mfp.st.preloader) {
+ mfp.preloader = _getEl('preloader', mfp.container, mfp.st.tLoading);
+ }
+
+
+ // Initializing modules
+ var modules = $.magnificPopup.modules;
+ for(i = 0; i < modules.length; i++) {
+ var n = modules[i];
+ n = n.charAt(0).toUpperCase() + n.slice(1);
+ mfp['init'+n].call(mfp);
+ }
+ _mfpTrigger('BeforeOpen');
+
+
+ if(mfp.st.showCloseBtn) {
+ // Close button
+ if(!mfp.st.closeBtnInside) {
+ mfp.wrap.append( _getCloseBtn() );
+ } else {
+ _mfpOn(MARKUP_PARSE_EVENT, function(e, template, values, item) {
+ values.close_replaceWith = _getCloseBtn(item.type);
+ });
+ _wrapClasses += ' mfp-close-btn-in';
+ }
+ }
+
+ if(mfp.st.alignTop) {
+ _wrapClasses += ' mfp-align-top';
+ }
+
+
+
+ if(mfp.fixedContentPos) {
+ mfp.wrap.css({
+ overflow: mfp.st.overflowY,
+ overflowX: 'hidden',
+ overflowY: mfp.st.overflowY
+ });
+ } else {
+ mfp.wrap.css({
+ top: _window.scrollTop(),
+ position: 'absolute'
+ });
+ }
+ if( mfp.st.fixedBgPos === false || (mfp.st.fixedBgPos === 'auto' && !mfp.fixedContentPos) ) {
+ mfp.bgOverlay.css({
+ height: _document.height(),
+ position: 'absolute'
+ });
+ }
+
+
+
+ if(mfp.st.enableEscapeKey) {
+ // Close on ESC key
+ _document.on('keyup' + EVENT_NS, function(e) {
+ if(e.keyCode === 27) {
+ mfp.close();
+ }
+ });
+ }
+
+ _window.on('resize' + EVENT_NS, function() {
+ mfp.updateSize();
+ });
+
+
+ if(!mfp.st.closeOnContentClick) {
+ _wrapClasses += ' mfp-auto-cursor';
+ }
+
+ if(_wrapClasses)
+ mfp.wrap.addClass(_wrapClasses);
+
+
+ // this triggers recalculation of layout, so we get it once to not to trigger twice
+ var windowHeight = mfp.wH = _window.height();
+
+
+ var windowStyles = {};
+
+ if( mfp.fixedContentPos ) {
+ if(mfp._hasScrollBar(windowHeight)){
+ var s = mfp._getScrollbarSize();
+ if(s) {
+ windowStyles.marginRight = s;
+ }
+ }
+ }
+
+ if(mfp.fixedContentPos) {
+ if(!mfp.isIE7) {
+ windowStyles.overflow = 'hidden';
+ } else {
+ // ie7 double-scroll bug
+ $('body, html').css('overflow', 'hidden');
+ }
+ }
+
+
+
+ var classesToadd = mfp.st.mainClass;
+ if(mfp.isIE7) {
+ classesToadd += ' mfp-ie7';
+ }
+ if(classesToadd) {
+ mfp._addClassToMFP( classesToadd );
+ }
+
+ // add content
+ mfp.updateItemHTML();
+
+ _mfpTrigger('BuildControls');
+
+ // remove scrollbar, add margin e.t.c
+ $('html').css(windowStyles);
+
+ // add everything to DOM
+ mfp.bgOverlay.add(mfp.wrap).prependTo( mfp.st.prependTo || $(document.body) );
+
+ // Save last focused element
+ mfp._lastFocusedEl = document.activeElement;
+
+ // Wait for next cycle to allow CSS transition
+ setTimeout(function() {
+
+ if(mfp.content) {
+ mfp._addClassToMFP(READY_CLASS);
+ mfp._setFocus();
+ } else {
+ // if content is not defined (not loaded e.t.c) we add class only for BG
+ mfp.bgOverlay.addClass(READY_CLASS);
+ }
+
+ // Trap the focus in popup
+ _document.on('focusin' + EVENT_NS, mfp._onFocusIn);
+
+ }, 16);
+
+ mfp.isOpen = true;
+ mfp.updateSize(windowHeight);
+ _mfpTrigger(OPEN_EVENT);
+
+ return data;
+ },
+
+ /**
+ * Closes the popup
+ */
+ close: function() {
+ if(!mfp.isOpen) return;
+ _mfpTrigger(BEFORE_CLOSE_EVENT);
+
+ mfp.isOpen = false;
+ // for CSS3 animation
+ if(mfp.st.removalDelay && !mfp.isLowIE && mfp.supportsTransition ) {
+ mfp._addClassToMFP(REMOVING_CLASS);
+ setTimeout(function() {
+ mfp._close();
+ }, mfp.st.removalDelay);
+ } else {
+ mfp._close();
+ }
+ },
+
+ /**
+ * Helper for close() function
+ */
+ _close: function() {
+ _mfpTrigger(CLOSE_EVENT);
+
+ var classesToRemove = REMOVING_CLASS + ' ' + READY_CLASS + ' ';
+
+ mfp.bgOverlay.detach();
+ mfp.wrap.detach();
+ mfp.container.empty();
+
+ if(mfp.st.mainClass) {
+ classesToRemove += mfp.st.mainClass + ' ';
+ }
+
+ mfp._removeClassFromMFP(classesToRemove);
+
+ if(mfp.fixedContentPos) {
+ var windowStyles = {marginRight: ''};
+ if(mfp.isIE7) {
+ $('body, html').css('overflow', '');
+ } else {
+ windowStyles.overflow = '';
+ }
+ $('html').css(windowStyles);
+ }
+
+ _document.off('keyup' + EVENT_NS + ' focusin' + EVENT_NS);
+ mfp.ev.off(EVENT_NS);
+
+ // clean up DOM elements that aren't removed
+ mfp.wrap.attr('class', 'mfp-wrap').removeAttr('style');
+ mfp.bgOverlay.attr('class', 'mfp-bg');
+ mfp.container.attr('class', 'mfp-container');
+
+ // remove close button from target element
+ if(mfp.st.showCloseBtn &&
+ (!mfp.st.closeBtnInside || mfp.currTemplate[mfp.currItem.type] === true)) {
+ if(mfp.currTemplate.closeBtn)
+ mfp.currTemplate.closeBtn.detach();
+ }
+
+
+ if(mfp.st.autoFocusLast && mfp._lastFocusedEl) {
+ $(mfp._lastFocusedEl).focus(); // put tab focus back
+ }
+ mfp.currItem = null;
+ mfp.content = null;
+ mfp.currTemplate = null;
+ mfp.prevHeight = 0;
+
+ _mfpTrigger(AFTER_CLOSE_EVENT);
+ },
+
+ updateSize: function(winHeight) {
+
+ if(mfp.isIOS) {
+ // fixes iOS nav bars https://github.com/dimsemenov/Magnific-Popup/issues/2
+ var zoomLevel = document.documentElement.clientWidth / window.innerWidth;
+ var height = window.innerHeight * zoomLevel;
+ mfp.wrap.css('height', height);
+ mfp.wH = height;
+ } else {
+ mfp.wH = winHeight || _window.height();
+ }
+ // Fixes #84: popup incorrectly positioned with position:relative on body
+ if(!mfp.fixedContentPos) {
+ mfp.wrap.css('height', mfp.wH);
+ }
+
+ _mfpTrigger('Resize');
+
+ },
+
+ /**
+ * Set content of popup based on current index
+ */
+ updateItemHTML: function() {
+ var item = mfp.items[mfp.index];
+
+ // Detach and perform modifications
+ mfp.contentContainer.detach();
+
+ if(mfp.content)
+ mfp.content.detach();
+
+ if(!item.parsed) {
+ item = mfp.parseEl( mfp.index );
+ }
+
+ var type = item.type;
+
+ _mfpTrigger('BeforeChange', [mfp.currItem ? mfp.currItem.type : '', type]);
+ // BeforeChange event works like so:
+ // _mfpOn('BeforeChange', function(e, prevType, newType) { });
+
+ mfp.currItem = item;
+
+ if(!mfp.currTemplate[type]) {
+ var markup = mfp.st[type] ? mfp.st[type].markup : false;
+
+ // allows to modify markup
+ _mfpTrigger('FirstMarkupParse', markup);
+
+ if(markup) {
+ mfp.currTemplate[type] = $(markup);
+ } else {
+ // if there is no markup found we just define that template is parsed
+ mfp.currTemplate[type] = true;
+ }
+ }
+
+ if(_prevContentType && _prevContentType !== item.type) {
+ mfp.container.removeClass('mfp-'+_prevContentType+'-holder');
+ }
+
+ var newContent = mfp['get' + type.charAt(0).toUpperCase() + type.slice(1)](item, mfp.currTemplate[type]);
+ mfp.appendContent(newContent, type);
+
+ item.preloaded = true;
+
+ _mfpTrigger(CHANGE_EVENT, item);
+ _prevContentType = item.type;
+
+ // Append container back after its content changed
+ mfp.container.prepend(mfp.contentContainer);
+
+ _mfpTrigger('AfterChange');
+ },
+
+
+ /**
+ * Set HTML content of popup
+ */
+ appendContent: function(newContent, type) {
+ mfp.content = newContent;
+
+ if(newContent) {
+ if(mfp.st.showCloseBtn && mfp.st.closeBtnInside &&
+ mfp.currTemplate[type] === true) {
+ // if there is no markup, we just append close button element inside
+ if(!mfp.content.find('.mfp-close').length) {
+ mfp.content.append(_getCloseBtn());
+ }
+ } else {
+ mfp.content = newContent;
+ }
+ } else {
+ mfp.content = '';
+ }
+
+ _mfpTrigger(BEFORE_APPEND_EVENT);
+ mfp.container.addClass('mfp-'+type+'-holder');
+
+ mfp.contentContainer.append(mfp.content);
+ },
+
+
+ /**
+ * Creates Magnific Popup data object based on given data
+ * @param {int} index Index of item to parse
+ */
+ parseEl: function(index) {
+ var item = mfp.items[index],
+ type;
+
+ if(item.tagName) {
+ item = { el: $(item) };
+ } else {
+ type = item.type;
+ item = { data: item, src: item.src };
+ }
+
+ if(item.el) {
+ var types = mfp.types;
+
+ // check for 'mfp-TYPE' class
+ for(var i = 0; i < types.length; i++) {
+ if( item.el.hasClass('mfp-'+types[i]) ) {
+ type = types[i];
+ break;
+ }
+ }
+
+ item.src = item.el.attr('data-mfp-src');
+ if(!item.src) {
+ item.src = item.el.attr('href');
+ }
+ }
+
+ item.type = type || mfp.st.type || 'inline';
+ item.index = index;
+ item.parsed = true;
+ mfp.items[index] = item;
+ _mfpTrigger('ElementParse', item);
+
+ return mfp.items[index];
+ },
+
+
+ /**
+ * Initializes single popup or a group of popups
+ */
+ addGroup: function(el, options) {
+ var eHandler = function(e) {
+ e.mfpEl = this;
+ mfp._openClick(e, el, options);
+ };
+
+ if(!options) {
+ options = {};
+ }
+
+ var eName = 'click.magnificPopup';
+ options.mainEl = el;
+
+ if(options.items) {
+ options.isObj = true;
+ el.off(eName).on(eName, eHandler);
+ } else {
+ options.isObj = false;
+ if(options.delegate) {
+ el.off(eName).on(eName, options.delegate , eHandler);
+ } else {
+ options.items = el;
+ el.off(eName).on(eName, eHandler);
+ }
+ }
+ },
+ _openClick: function(e, el, options) {
+ var midClick = options.midClick !== undefined ? options.midClick : $.magnificPopup.defaults.midClick;
+
+
+ if(!midClick && ( e.which === 2 || e.ctrlKey || e.metaKey || e.altKey || e.shiftKey ) ) {
+ return;
+ }
+
+ var disableOn = options.disableOn !== undefined ? options.disableOn : $.magnificPopup.defaults.disableOn;
+
+ if(disableOn) {
+ if($.isFunction(disableOn)) {
+ if( !disableOn.call(mfp) ) {
+ return true;
+ }
+ } else { // else it's number
+ if( _window.width() < disableOn ) {
+ return true;
+ }
+ }
+ }
+
+ if(e.type) {
+ e.preventDefault();
+
+ // This will prevent popup from closing if element is inside and popup is already opened
+ if(mfp.isOpen) {
+ e.stopPropagation();
+ }
+ }
+
+ options.el = $(e.mfpEl);
+ if(options.delegate) {
+ options.items = el.find(options.delegate);
+ }
+ mfp.open(options);
+ },
+
+
+ /**
+ * Updates text on preloader
+ */
+ updateStatus: function(status, text) {
+
+ if(mfp.preloader) {
+ if(_prevStatus !== status) {
+ mfp.container.removeClass('mfp-s-'+_prevStatus);
+ }
+
+ if(!text && status === 'loading') {
+ text = mfp.st.tLoading;
+ }
+
+ var data = {
+ status: status,
+ text: text
+ };
+ // allows to modify status
+ _mfpTrigger('UpdateStatus', data);
+
+ status = data.status;
+ text = data.text;
+
+ mfp.preloader.html(text);
+
+ mfp.preloader.find('a').on('click', function(e) {
+ e.stopImmediatePropagation();
+ });
+
+ mfp.container.addClass('mfp-s-'+status);
+ _prevStatus = status;
+ }
+ },
+
+
+ /*
+ "Private" helpers that aren't private at all
+ */
+ // Check to close popup or not
+ // "target" is an element that was clicked
+ _checkIfClose: function(target) {
+
+ if($(target).hasClass(PREVENT_CLOSE_CLASS)) {
+ return;
+ }
+
+ var closeOnContent = mfp.st.closeOnContentClick;
+ var closeOnBg = mfp.st.closeOnBgClick;
+
+ if(closeOnContent && closeOnBg) {
+ return true;
+ } else {
+
+ // We close the popup if click is on close button or on preloader. Or if there is no content.
+ if(!mfp.content || $(target).hasClass('mfp-close') || (mfp.preloader && target === mfp.preloader[0]) ) {
+ return true;
+ }
+
+ // if click is outside the content
+ if( (target !== mfp.content[0] && !$.contains(mfp.content[0], target)) ) {
+ if(closeOnBg) {
+ // last check, if the clicked element is in DOM, (in case it's removed onclick)
+ if( $.contains(document, target) ) {
+ return true;
+ }
+ }
+ } else if(closeOnContent) {
+ return true;
+ }
+
+ }
+ return false;
+ },
+ _addClassToMFP: function(cName) {
+ mfp.bgOverlay.addClass(cName);
+ mfp.wrap.addClass(cName);
+ },
+ _removeClassFromMFP: function(cName) {
+ this.bgOverlay.removeClass(cName);
+ mfp.wrap.removeClass(cName);
+ },
+ _hasScrollBar: function(winHeight) {
+ return ( (mfp.isIE7 ? _document.height() : document.body.scrollHeight) > (winHeight || _window.height()) );
+ },
+ _setFocus: function() {
+ (mfp.st.focus ? mfp.content.find(mfp.st.focus).eq(0) : mfp.wrap).focus();
+ },
+ _onFocusIn: function(e) {
+ if( e.target !== mfp.wrap[0] && !$.contains(mfp.wrap[0], e.target) ) {
+ mfp._setFocus();
+ return false;
+ }
+ },
+ _parseMarkup: function(template, values, item) {
+ var arr;
+ if(item.data) {
+ values = $.extend(item.data, values);
+ }
+ _mfpTrigger(MARKUP_PARSE_EVENT, [template, values, item] );
+
+ $.each(values, function(key, value) {
+ if(value === undefined || value === false) {
+ return true;
+ }
+ arr = key.split('_');
+ if(arr.length > 1) {
+ var el = template.find(EVENT_NS + '-'+arr[0]);
+
+ if(el.length > 0) {
+ var attr = arr[1];
+ if(attr === 'replaceWith') {
+ if(el[0] !== value[0]) {
+ el.replaceWith(value);
+ }
+ } else if(attr === 'img') {
+ if(el.is('img')) {
+ el.attr('src', value);
+ } else {
+ el.replaceWith( $('').attr('src', value).attr('class', el.attr('class')) );
+ }
+ } else {
+ el.attr(arr[1], value);
+ }
+ }
+
+ } else {
+ template.find(EVENT_NS + '-'+key).html(value);
+ }
+ });
+ },
+
+ _getScrollbarSize: function() {
+ // thx David
+ if(mfp.scrollbarSize === undefined) {
+ var scrollDiv = document.createElement("div");
+ scrollDiv.style.cssText = 'width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;';
+ document.body.appendChild(scrollDiv);
+ mfp.scrollbarSize = scrollDiv.offsetWidth - scrollDiv.clientWidth;
+ document.body.removeChild(scrollDiv);
+ }
+ return mfp.scrollbarSize;
+ }
+
+ }; /* MagnificPopup core prototype end */
+
+
+
+
+ /**
+ * Public static functions
+ */
+ $.magnificPopup = {
+ instance: null,
+ proto: MagnificPopup.prototype,
+ modules: [],
+
+ open: function(options, index) {
+ _checkInstance();
+
+ if(!options) {
+ options = {};
+ } else {
+ options = $.extend(true, {}, options);
+ }
+
+ options.isObj = true;
+ options.index = index || 0;
+ return this.instance.open(options);
+ },
+
+ close: function() {
+ return $.magnificPopup.instance && $.magnificPopup.instance.close();
+ },
+
+ registerModule: function(name, module) {
+ if(module.options) {
+ $.magnificPopup.defaults[name] = module.options;
+ }
+ $.extend(this.proto, module.proto);
+ this.modules.push(name);
+ },
+
+ defaults: {
+
+ // Info about options is in docs:
+ // http://dimsemenov.com/plugins/magnific-popup/documentation.html#options
+
+ disableOn: 0,
+
+ key: null,
+
+ midClick: false,
+
+ mainClass: '',
+
+ preloader: true,
+
+ focus: '', // CSS selector of input to focus after popup is opened
+
+ closeOnContentClick: false,
+
+ closeOnBgClick: true,
+
+ closeBtnInside: true,
+
+ showCloseBtn: true,
+
+ enableEscapeKey: true,
+
+ modal: false,
+
+ alignTop: false,
+
+ removalDelay: 0,
+
+ prependTo: null,
+
+ fixedContentPos: 'auto',
+
+ fixedBgPos: 'auto',
+
+ overflowY: 'auto',
+
+ closeMarkup: '',
+
+ tClose: 'Close (Esc)',
+
+ tLoading: 'Loading...',
+
+ autoFocusLast: true
+
+ }
+ };
+
+
+
+ $.fn.magnificPopup = function(options) {
+ _checkInstance();
+
+ var jqEl = $(this);
+
+ // We call some API method of first param is a string
+ if (typeof options === "string" ) {
+
+ if(options === 'open') {
+ var items,
+ itemOpts = _isJQ ? jqEl.data('magnificPopup') : jqEl[0].magnificPopup,
+ index = parseInt(arguments[1], 10) || 0;
+
+ if(itemOpts.items) {
+ items = itemOpts.items[index];
+ } else {
+ items = jqEl;
+ if(itemOpts.delegate) {
+ items = items.find(itemOpts.delegate);
+ }
+ items = items.eq( index );
+ }
+ mfp._openClick({mfpEl:items}, jqEl, itemOpts);
+ } else {
+ if(mfp.isOpen)
+ mfp[options].apply(mfp, Array.prototype.slice.call(arguments, 1));
+ }
+
+ } else {
+ // clone options obj
+ options = $.extend(true, {}, options);
+
+ /*
+ * As Zepto doesn't support .data() method for objects
+ * and it works only in normal browsers
+ * we assign "options" object directly to the DOM element. FTW!
+ */
+ if(_isJQ) {
+ jqEl.data('magnificPopup', options);
+ } else {
+ jqEl[0].magnificPopup = options;
+ }
+
+ mfp.addGroup(jqEl, options);
+
+ }
+ return jqEl;
+ };
+
+ /*>>core*/
+
+ /*>>inline*/
+
+ var INLINE_NS = 'inline',
+ _hiddenClass,
+ _inlinePlaceholder,
+ _lastInlineElement,
+ _putInlineElementsBack = function() {
+ if(_lastInlineElement) {
+ _inlinePlaceholder.after( _lastInlineElement.addClass(_hiddenClass) ).detach();
+ _lastInlineElement = null;
+ }
+ };
+
+ $.magnificPopup.registerModule(INLINE_NS, {
+ options: {
+ hiddenClass: 'hide', // will be appended with `mfp-` prefix
+ markup: '',
+ tNotFound: 'Content not found'
+ },
+ proto: {
+
+ initInline: function() {
+ mfp.types.push(INLINE_NS);
+
+ _mfpOn(CLOSE_EVENT+'.'+INLINE_NS, function() {
+ _putInlineElementsBack();
+ });
+ },
+
+ getInline: function(item, template) {
+
+ _putInlineElementsBack();
+
+ if(item.src) {
+ var inlineSt = mfp.st.inline,
+ el = $(item.src);
+
+ if(el.length) {
+
+ // If target element has parent - we replace it with placeholder and put it back after popup is closed
+ var parent = el[0].parentNode;
+ if(parent && parent.tagName) {
+ if(!_inlinePlaceholder) {
+ _hiddenClass = inlineSt.hiddenClass;
+ _inlinePlaceholder = _getEl(_hiddenClass);
+ _hiddenClass = 'mfp-'+_hiddenClass;
+ }
+ // replace target inline element with placeholder
+ _lastInlineElement = el.after(_inlinePlaceholder).detach().removeClass(_hiddenClass);
+ }
+
+ mfp.updateStatus('ready');
+ } else {
+ mfp.updateStatus('error', inlineSt.tNotFound);
+ el = $('