Context 跟 Compound Component
Compound Component 的介紹應該可以不用提太細,詳細概念可以參考: https://www.patterns.dev/react/compound-pattern/
簡單來說是將複雜的相依關聯用同個 Context 串起來同步狀態,方便外部 caller 不需要手動傳入每個 props,只需要使用需要的部分就可以。
比較值得注意的是為了避免過度 rerender,這裡使用的 Context 只提供三個 state:
- mode: 'lightbox' | 'thumbnail':代表現在在縮圖還是放大的狀態,Item、Overlay 會需要這個 state 來決定是否要顯示某些東西、或是是否需要綁定滑鼠、滾輪、觸控事件。
- currentFocusIndex:目前開啟或關閉的 item index,這個會用來決定哪張圖片需要 ViewTransition。這個 state 只會在 openLightbox/closeLightbox 時從 ref 取出同步,不會常態更新觸發不必要的 re-render 跟 reflow。
- isControlsHidden:用來控制互動控制元件(上/下一張圖片、關閉 Lightbox、影片播放控制)是否應該隱藏。
其他的狀態都是用 ref 的方式隱藏在 Context Provider 內,提供 set function 給 children component 使用。這樣可以確保各種動畫(捲動、縮放、平移)不會觸發 reflow。

