TRAINING LIBRARY / Website development
FIELD GUIDE 01 HTML · CSS · JAVASCRIPT

由檔案到網站。
自己寫,先識得審。

你識 CLI、HTTP 同網絡。
而家由第一行 HTML 開始,
一路寫到可以交付嘅 dist/。

08 個實作階段07 個 Bug lab離線可用
link-dashboard
01<html>結構 / Structure
02{ style }排版 / Layout
03function()互動 / Behaviour
npm run build ↓
▱dist/READY FOR HANDOFF
VANILLA JS + VITE通用靜態網站 · IT Links DashboardCHECKED 2026.12.06
START HERE

點用呢份 training

QUICK REVISION

想快啲溫習?記住呢 10 點。

已有基本概念,先用呢張清單查漏,再做章節小測。第一次學,可以按左邊目錄逐步做。

開始手寫 labs
  1. Static hosting 送現成檔案;互動喺 browser 做。
  2. HTML 係結構,CSS 係排版,JS 係行為。
  3. DOM 係運行中嘅樹,唔等於磁碟 HTML。
  4. URL 同 import 大細楷要完全吻合。
  5. index.html 係 Vite entry,唔放入 public/。
  6. State → filter → render;改 state 後要 update。
  7. localStorage 只存字串,要 catch 同驗證 shape。
  8. VITE_ 值會入 client bundle,絕對唔放 secret。
  9. build 出 dist;用 HTTP preview 驗收 module app。
  10. Build pass 仲要測手機、keyboard、Console 同 Network。

由第一個念頭,到可以交付

本篇:Plan → Build

撳流程節點跳去對應章節。後半段由 Cloudflare deploy training 接手。

同系列嘅另一個 training

Cloudflare deploy training

Power Platform training

兩份指南都可以獨立使用。
返頁頂 ↑
01 / DEFINE THE JOB

Plan:先定義你要整乜

一個 IT Links Dashboard:將 Router admin、NAS、Monitoring 同 Docs 分類;可以搜尋、揀分類、加最愛,同睇示例 status badge。資料喺 JS array,最愛喺 localStorage,冇登入同共享 database。

類型邊度做工作適合乜
StaticServer 送現成 HTML / CSS / JS;browser 處理篩選小工具、docs、連結清單
Dynamic / SSRServer 根據 request 產生 HTML 或存取 database帳戶、共享資料、需要保護嘅 server API
ROUTE CHOOSER

今次應該揀邊條路?

需求寫成可以驗收嘅句子
  • 搜尋 Router 只顯示相關連結;分類同搜尋係 AND。
  • 冇結果要有文字提示;status 只係示例,唔聲稱做過 ping。
  • 最愛 reload 後保留;壞 storage 唔令頁面崩潰。
  • 390px 唔橫向溢出;Tab 可以到每個 control;Esc 關 dialog。
返頁頂 ↑
02 / FROM URL TO PIXELS

Browser 同 request 點行

Browser 攞 index.html,parse 成 DOM;發現 stylesheet 同 script 再載入。CSS 變 CSSOM;render tree 決定要畫乜,layout 算位置,paint 畫 pixels。CSS 同 JS request 可以並行,唔係一條固定串行隊列。

位置 / 規則實際意思
/style.css由網站根路徑開始;子路徑部署可能搵錯
./style.css由目前 document URL 所在目錄開始
../style.css上層目錄;import 則由引用嗰個 module URL 計
/docs/通常映射 docs/index.html,但係 hosting 規則,唔係 browser 保證
Main.js ≠ main.jsLinux hosting 大細楷敏感;Windows 本機成功唔代表線上成功
MIME / CORSModule 必須用正確 JS MIME;回傳 HTML fallback 唔等於 JS 成功
file:// vs http://教學頁用 classic scripts 可離線;Vite source / dist modules 要 HTTP server
URL RESOLVER

呢個 path 會去邊?

深入:event loop 同 main thread

同步 JS 霸住 main thread;長 blocking loop 會令 click 同畫面停住。Call stack 清空之後,Promise microtasks 先清空,browser 再有 render 機會。重工作唔好塞入 click listener。呢啲係一般 browser 知識,唔係效能測量結果。

返頁頂 ↑
03 / KNOW YOUR FILES

Project structure:分清 source 同成果

手寫 s0–s2Vite s3–s7責任
index.htmlindex.htmlEntry,同 semantic landmarks
style.cssstyle.cssTokens、排版、響應式
app.jssrc/main.jsDOM、state、events、render
寫喺 HTMLsrc/data.js資料 schema 同連結清單
冇public/favicon.svg固定檔名,build 後原樣喺根目錄
冇vite.config.jss7 自己加 base 設定
原始三個檔dist/Vite build 後先交付 dist,唔交 node_modules
檔案地圖
link-dashboard/
├─ index.html  → /src/main.js
├─ style.css     ↑ import ../style.css
├─ src/
│  ├─ main.js  → ./data.js
│  └─ data.js
├─ public/favicon.svg
├─ package.json
└─ vite.config.js

# npm run build 後
dist/
├─ index.html
├─ favicon.svg
└─ assets/index-[hash].js + index-[hash].css
AI 俾你一大個 folder,邊個先 deploy?

先讀 package.json scripts 同 entry。Vite 先 install/build,再查真正 output 係咪 dist;唔好估整個 repository 都係成果。先固定功能,再抽 CSS、pure functions,最後抽 DOM 副作用;每搬一步都做同一組操作比較。

返頁頂 ↑
04 / STRUCTURE WITH MEANING

HTML:語義係介面合約

header / nav / main / section / footer 係文件路標。每頁一個 h1,按內容層次用 h2 / h3。動作用 button,去另一個位置用 a。原生 controls 已有 keyboard 同讀屏行為。

Vite HTML 摘錄
<label for="search">搜尋連結</label>
<input id="search" type="search">
<button aria-pressed="false">只睇最愛</button>
<p id="count" role="status"></p>
<script type="module" src="/src/main.js"></script>
元素 / attribute用途
lang="zh-Hant-HK"語言、讀音同字型提示
meta viewport跟裝置闊度排版,唔係縮細 desktop
label for / id將清楚名稱連去輸入欄
aria-pressedToggle 狀態,唔淨靠顏色
role="status" / aria-live="polite"更新數量時唔搶焦點
type="module"令 import/export 有效,預設 deferred,獨立 scope
用 keyboard 驗收

Tab / Shift+Tab 行晒 controls;Enter / Space 操作;focus-visible 清楚。Native dialog 用 showModal(),背景 inert;Esc 關閉後,focus 返開啟嗰個掣。唔好用 div 加 click 當完成 button。

返頁頂 ↑
05 / SPACE, LAYOUT, CASCADE

CSS:由一個盒到手機排版

盒模型係 content → padding → border → margin。box-sizing: border-box 將 padding 同 border 計入 width,margin 仍喺外面。Custom properties 用 var(--accent),可以繼承同局部覆寫。

Mobile-first
:root { --accent: #096750; }
* { box-sizing: border-box; }
.grid { display: grid; grid-template-columns: 1fr; gap: 16px; }
@media (min-width: 640px) {
  .grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
@media (prefers-reduced-motion: reduce) {
  * { transition: none !important; scroll-behavior: auto !important; }
}
BOX MODEL LAB

Width 200px,實際佔幾多?

content

選擇適合 / 規則
Flexbox單方向 toolbar,同 flex-wrap 配合
Grid行同列;auto-fill + minmax 按可用空間加欄
button → .chip:hover → #grid .cardSpecificity 0/0/1 → 0/2/0 → 1/1/0
同 specificity同 origin / importance / layer 條件下,後面規則贏;inline style 通常高過一般 rule
返頁頂 ↑
06 / ONE UPDATE PIPELINE

JavaScript:data → state → UI

一個 link 係 object,links 係 array。State 記而家揀咗乜;filter 係 pure function;render 做 DOM 副作用。每次 input / click 改 state,再 render,一個流程先唔會互相蓋過結果。

State + pure filter
const state = { query: '', category: 'all', onlyFavs: false }
const shown = links.filter(item =>
  (state.category === 'all' || item.category === state.category) &&
  item.title.toLowerCase().includes(state.query.toLowerCase())
)
// AND:每個條件都要過;空 query 會 matches 全部。
語法點讀
const / letBinding 唔重綁 / 可以重新賦值;const object 內容仍可改
map / filter / includes轉換每項 / 保留合條件 / 包唔包含
every / some全部 true(AND)/ 至少一個 true(OR)
...items / { ...state }展開 iterable / 淺複製 object
?. / ??遇 null/undefined 停止 / 只對 null/undefined 用預設
template literal / destructure反引號插值 / 從 array 或 object 抽值
export / import模組公開介面 / 引用;頂層 const 唔會變 window property
localStorage:防守唔只 catch JSON.parse

每個 origin(scheme + host + port)各有同步字串 key/value store,唔係跨裝置同步。容量有限,讀寫都可能失敗,唔適合 secret。Set 要先 [...favourites] 轉 array 再 stringify;讀返要 Array.isArray、驗證 string 同有效 id,再 new Set 去重。

Storage shape validation
try {
  const saved = JSON.parse(localStorage.getItem(KEY) ?? '[]')
  if (Array.isArray(saved)) {
    favourites = new Set(saved.filter(id =>
      typeof id === 'string' && links.some(item => item.id === id)
    ))
  }
} catch { /* 用空 Set,頁面照行 */ }
安全 render、event delegation 同 dialog

資料用 createElement + textContent,任意文字唔會變 markup。Template + innerHTML 每次插值都要正確 escape;escape 唔係 URL / JS / CSS 嘅萬能 sanitizer。URL 另行驗證 protocol,唔收 javascript:。

用穩定 parent 接 bubbling event,再 event.target.closest() 搵 button;render 換走子元素都唔會失去 listener。重畫後恢復 focus。Dialog 用 showModal()、form method="dialog" 同 close listener 回焦點。

隨機項目嘅一般寫法係 pool[Math.floor(Math.random() * pool.length)];先處理空 pool,唔好用 round 或 length + 1。今次 dashboard 唔需要隨機功能。

返頁頂 ↑
07 / READ THE REAL SOURCE

Starter walkthrough:逐行追一次

以下 code 由實際 sample/link-dashboard/ 檔案喺 build 時注入,Copy 係完整原文。行號版方便對照,唔會混入複製內容。先順住 entry → import → state → filter → render → event 讀。

package.json 14 lines · 完整原檔
  1. L1–14 dev/build/preview 分別呼叫 Vite;釘住 8.4.1,npm install 後留低 lockfile。
package.json
{
  "name": "link-dashboard",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "devDependencies": {
    "vite": "8.4.1"
  }
}
1{
2 "name": "link-dashboard",
3 "version": "1.0.0",
4 "private": true,
5 "type": "module",
6 "scripts": {
7 "dev": "vite",
8 "build": "vite build",
9 "preview": "vite preview"
10 },
11 "devDependencies": {
12 "vite": "8.4.1"
13 }
14}
index.html 34 lines · 完整原檔
  1. L1–10 由 doctype 到 title:UTF-8、viewport、description 同固定 favicon。
  2. L11–27 label/search、categories 同 only-favs 將選項交俾 JS。
  3. L28–34 count 宣告 status,grid 接 render;dialog 有獨立標題,module script 喺最後。
index.html
<!doctype html>
<html lang="zh-Hant-HK">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="分類、搜尋同收藏常用 IT 連結。">
  <link rel="icon" href="/favicon.svg" type="image/svg+xml">
  <title>IT Links Dashboard</title>
</head>
<body>
  <header><p>YOUR DAILY SHORTCUTS</p><h1>IT Links Dashboard</h1></header>
  <main>
    <label for="search">搜尋連結</label>
    <input id="search" type="search" placeholder="試下 Router 或 Docs">
    <nav id="categories" aria-label="連結分類">
      <button data-cat="all" aria-pressed="true">全部</button>
      <button data-cat="Network" aria-pressed="false">Network</button>
      <button data-cat="Storage" aria-pressed="false">Storage</button>
      <button data-cat="Monitoring" aria-pressed="false">Monitoring</button>
      <button data-cat="Docs" aria-pressed="false">Docs</button>
    </nav>
    <button id="only-favs" aria-pressed="false">只睇最愛</button>
    <p id="count" role="status"></p>
    <div id="grid" class="grid"></div>
    <p id="storage-status" role="status"></p>
  </main>
  <dialog id="info" aria-labelledby="info-title">
    <h2 id="info-title"></h2><p id="info-text"></p>
    <form method="dialog"><button>關閉</button></form>
  </dialog>
  <footer>狀態係示例資料,唔係即時監察結果。</footer>
  <script type="module" src="/src/main.js"></script>
</body>
</html>
1<!doctype html>
2<html lang="zh-Hant-HK">
3<head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1">
6 <meta name="description" content="分類、搜尋同收藏常用 IT 連結。">
7 <link rel="icon" href="/favicon.svg" type="image/svg+xml">
8 <title>IT Links Dashboard</title>
9</head>
10<body>
11 <header><p>YOUR DAILY SHORTCUTS</p><h1>IT Links Dashboard</h1></header>
12 <main>
13 <label for="search">搜尋連結</label>
14 <input id="search" type="search" placeholder="試下 Router 或 Docs">
15 <nav id="categories" aria-label="連結分類">
16 <button data-cat="all" aria-pressed="true">全部</button>
17 <button data-cat="Network" aria-pressed="false">Network</button>
18 <button data-cat="Storage" aria-pressed="false">Storage</button>
19 <button data-cat="Monitoring" aria-pressed="false">Monitoring</button>
20 <button data-cat="Docs" aria-pressed="false">Docs</button>
21 </nav>
22 <button id="only-favs" aria-pressed="false">只睇最愛</button>
23 <p id="count" role="status"></p>
24 <div id="grid" class="grid"></div>
25 <p id="storage-status" role="status"></p>
26 </main>
27 <dialog id="info" aria-labelledby="info-title">
28 <h2 id="info-title"></h2><p id="info-text"></p>
29 <form method="dialog"><button>關閉</button></form>
30 </dialog>
31 <footer>狀態係示例資料,唔係即時監察結果。</footer>
32 <script type="module" src="/src/main.js"></script>
33</body>
34</html>
src/data.js 9 lines · 完整原檔
  1. L1–9 id 係穩定識別;title/category/url/status/note 只存資料,唔塞 DOM 操作。
src/data.js
// URL 係本機示例位置;正式使用前換成你有權存取嘅網址。
export const links = [
  { id: 'router', title: 'Router admin', category: 'Network', url: '#router', status: 'Ready', note: '路由器管理入口;需要授權先可以操作。' },
  { id: 'switch', title: 'Switch admin', category: 'Network', url: '#switch', status: 'Review', note: '檢查 VLAN 同 port 設定。' },
  { id: 'nas', title: 'NAS', category: 'Storage', url: '#nas', status: 'Ready', note: '檔案儲存同備份入口。' },
  { id: 'backup', title: 'Backup reports', category: 'Storage', url: '#backup', status: 'Review', note: '核對最近一次備份紀錄。' },
  { id: 'monitor', title: 'Monitoring', category: 'Monitoring', url: '#monitor', status: 'Ready', note: '系統監察 dashboard。' },
  { id: 'docs', title: 'Docs', category: 'Docs', url: '#docs', status: 'Ready', note: '常用操作程序同技術文件。' }
]
1// URL 係本機示例位置;正式使用前換成你有權存取嘅網址。
2export const links = [
3 { id: 'router', title: 'Router admin', category: 'Network', url: '#router', status: 'Ready', note: '路由器管理入口;需要授權先可以操作。' },
4 { id: 'switch', title: 'Switch admin', category: 'Network', url: '#switch', status: 'Review', note: '檢查 VLAN 同 port 設定。' },
5 { id: 'nas', title: 'NAS', category: 'Storage', url: '#nas', status: 'Ready', note: '檔案儲存同備份入口。' },
6 { id: 'backup', title: 'Backup reports', category: 'Storage', url: '#backup', status: 'Review', note: '核對最近一次備份紀錄。' },
7 { id: 'monitor', title: 'Monitoring', category: 'Monitoring', url: '#monitor', status: 'Ready', note: '系統監察 dashboard。' },
8 { id: 'docs', title: 'Docs', category: 'Docs', url: '#docs', status: 'Ready', note: '常用操作程序同技術文件。' }
9]
style.css 24 lines · 完整原檔
  1. L1–12 頭段定色、字型、box-sizing 同 controls。
  2. L13–24 Grid 先一欄,640px 兩欄,900px 三欄;最後尊重 reduced-motion。
style.css
/* Tokens → reset → layout → controls → responsive */
:root { color-scheme: light; --ink: #142c3e; --accent: #096750; --line: #c7d5de; }
* { box-sizing: border-box; }
body { margin: 0; padding: 24px; background: #f2f6f9; color: var(--ink); font: 16px/1.7 "Noto Sans CJK HK", "Microsoft JhengHei", sans-serif; }
header, main, footer { max-width: 960px; margin: auto; }
h1 { font-size: clamp(1.6rem, 5vw, 2.5rem); }
button, input { font: inherit; min-height: 44px; border: 1px solid var(--line); border-radius: 8px; padding: 8px 12px; }
button { background: white; color: var(--ink); cursor: pointer; }
button[aria-pressed="true"] { background: var(--accent); color: white; }
:focus-visible { outline: 3px solid #ab4900; outline-offset: 3px; }
input { display: block; width: 100%; margin: 8px 0 16px; }
nav { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
.grid { display: grid; grid-template-columns: 1fr; gap: 16px; }
article { background: white; padding: 20px; border: 1px solid var(--line); border-radius: 12px; min-width: 0; }
article h2 { font-size: 1.2rem; }
article a { color: #075b8c; overflow-wrap: anywhere; }
.badge { display: inline-block; border: 1px solid var(--line); padding: 2px 8px; border-radius: 20px; }
article button { margin: 6px 6px 0 0; }
footer { margin-top: 24px; }
dialog { width: min(90%, 480px); border: 1px solid var(--line); border-radius: 12px; color: var(--ink); }
dialog::backdrop { background: rgb(10 25 40 / 60%); }
@media (min-width: 640px) { .grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (min-width: 900px) { .grid { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
@media (prefers-reduced-motion: reduce) { * { scroll-behavior: auto !important; transition: none !important; } }
1/* Tokens → reset → layout → controls → responsive */
2:root { color-scheme: light; --ink: #142c3e; --accent: #096750; --line: #c7d5de; }
3* { box-sizing: border-box; }
4body { margin: 0; padding: 24px; background: #f2f6f9; color: var(--ink); font: 16px/1.7 "Noto Sans CJK HK", "Microsoft JhengHei", sans-serif; }
5header, main, footer { max-width: 960px; margin: auto; }
6h1 { font-size: clamp(1.6rem, 5vw, 2.5rem); }
7button, input { font: inherit; min-height: 44px; border: 1px solid var(--line); border-radius: 8px; padding: 8px 12px; }
8button { background: white; color: var(--ink); cursor: pointer; }
9button[aria-pressed="true"] { background: var(--accent); color: white; }
10:focus-visible { outline: 3px solid #ab4900; outline-offset: 3px; }
11input { display: block; width: 100%; margin: 8px 0 16px; }
12nav { display: flex; flex-wrap: wrap; gap: 8px; margin: 12px 0; }
13.grid { display: grid; grid-template-columns: 1fr; gap: 16px; }
14article { background: white; padding: 20px; border: 1px solid var(--line); border-radius: 12px; min-width: 0; }
15article h2 { font-size: 1.2rem; }
16article a { color: #075b8c; overflow-wrap: anywhere; }
17.badge { display: inline-block; border: 1px solid var(--line); padding: 2px 8px; border-radius: 20px; }
18article button { margin: 6px 6px 0 0; }
19footer { margin-top: 24px; }
20dialog { width: min(90%, 480px); border: 1px solid var(--line); border-radius: 12px; color: var(--ink); }
21dialog::backdrop { background: rgb(10 25 40 / 60%); }
22@media (min-width: 640px) { .grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
23@media (min-width: 900px) { .grid { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
24@media (prefers-reduced-motion: reduce) { * { scroll-behavior: auto !important; transition: none !important; } }
src/main.js 109 lines · 完整原檔
  1. L1–2 Import ../style.css 同 ./data.js;路徑由 src/main.js 出發,唔係由 index.html 計。
  2. L4–11 filterLinks 接 items/state/favourites。filter 保留三組 AND 條件都符合嘅項;includes 空字串會收全部;唔改 DOM 或原資料。
  3. L13–17 Versioned KEY、唯一 state、grid/status DOM references,同空 favourites Set。
  4. L18–25 讀字串再 JSON.parse;Array.isArray 驗證 shape,filter string + 已知 id;catch 令 denied storage / 壞 JSON 唔 crash。
  5. L27–30 Set 展開成 array,JSON.stringify 轉字串先儲存;寫入失敗只報狀態,唔中斷互動。
  6. L32–38 new URL 以目前位置解相對 path;只接受 http/https,其他 protocol 或解析失敗就用 #。
  7. L40–48 Render 先計 shown,再 map 建 article/h2/a;標題用 textContent,href 用 safeUrl,唔將資料當 HTML。
  8. L49–53 建立 status badge 同 category;className 控制外觀,文字照樣用 textContent。
  9. L54–62 建立 favourite/info 原生 buttons;dataset 存穩定 id,aria-label 有 link 名,aria-pressed 同 Set 狀態一致。
  10. L63–71 Append 卡片內容,replaceChildren 一次換 grid。更新 count 同每個分類 / favourite toggle 嘅 aria-pressed。
  11. L73–77 Search input event 改 state.query,再 render;一條更新流程,唔另外維護重複結果。
  12. L78–83 Categories parent 接 click;closest 搵命中 button,冇命中就 return;更新 category 再 render。
  13. L84–87 Only-favs click 反轉 boolean,再 render;唔改原始 links array。
  14. L88–98 記住 opener 同 dialog。Grid parent delegation 接最愛事件;Set 刪/加 id,save/render,再搵新 button 恢復 focus,消失就 fallback。
  15. L99–107 Info button 用 id 搵資料;title/note 用 textContent,記低 opener,再 showModal 令背景 inert。
  16. L108–109 Dialog close(包括 Esc)回到 opener;最後 render() 做首次顯示,漏咗就要等第一個 event 先有卡。
src/main.js
import '../style.css'
import { links } from './data.js'

// Pure function:同一組 input,永遠得同一組結果。
export function filterLinks(items, state, favourites) {
  return items.filter(item =>
    (state.category === 'all' || item.category === state.category) &&
    item.title.toLowerCase().includes(state.query.toLowerCase()) &&
    (!state.onlyFavs || favourites.has(item.id))
  )
}

const KEY = 'link-dashboard:favs:v1'
const state = { query: '', category: 'all', onlyFavs: false }
const grid = document.querySelector('#grid')
const storageStatus = document.querySelector('#storage-status')
let favourites = new Set()
try {
  const saved = JSON.parse(localStorage.getItem(KEY) ?? '[]')
  if (Array.isArray(saved)) {
    favourites = new Set(saved.filter(id => typeof id === 'string' && links.some(item => item.id === id)))
  }
} catch {
  storageStatus.textContent = '讀唔到儲存資料;今次由空最愛開始。'
}

function save() {
  try { localStorage.setItem(KEY, JSON.stringify([...favourites])) }
  catch { storageStatus.textContent = '儲存唔到;今次操作仍然有效。' }
}

// 只接受相對位置同 http(s),文字用 textContent,唔將資料當 HTML。
function safeUrl(value) {
  try {
    const url = new URL(value, location.href)
    return ['http:', 'https:'].includes(url.protocol) ? url.href : '#'
  } catch { return '#' }
}

function render() {
  const shown = filterLinks(links, state, favourites)
  grid.replaceChildren(...shown.map(item => {
    const card = document.createElement('article')
    const heading = document.createElement('h2')
    const anchor = document.createElement('a')
    anchor.textContent = item.title
    anchor.href = safeUrl(item.url)
    heading.append(anchor)
    const badge = document.createElement('span')
    badge.className = 'badge'
    badge.textContent = item.status
    const category = document.createElement('p')
    category.textContent = item.category
    const fav = document.createElement('button')
    fav.textContent = favourites.has(item.id) ? '已收藏' : '加最愛'
    fav.dataset.fav = item.id
    fav.setAttribute('aria-label', item.title + ' 最愛')
    fav.setAttribute('aria-pressed', String(favourites.has(item.id)))
    const info = document.createElement('button')
    info.textContent = '詳情'
    info.dataset.info = item.id
    info.setAttribute('aria-label', item.title + ' 詳情')
    card.append(heading, badge, category, fav, info)
    return card
  }))
  document.querySelector('#count').textContent = shown.length ? `搵到 ${shown.length} 個連結` : '冇結果,試下改搜尋或分類。'
  document.querySelectorAll('[data-cat]').forEach(button => {
    button.setAttribute('aria-pressed', String(button.dataset.cat === state.category))
  })
  document.querySelector('#only-favs').setAttribute('aria-pressed', String(state.onlyFavs))
}

// 一個 state → filter → render;listener 放喺唔會被換走嘅 parent。
document.querySelector('#search').addEventListener('input', event => {
  state.query = event.target.value
  render()
})
document.querySelector('#categories').addEventListener('click', event => {
  const button = event.target.closest('[data-cat]')
  if (!button) return
  state.category = button.dataset.cat
  render()
})
document.querySelector('#only-favs').addEventListener('click', () => {
  state.onlyFavs = !state.onlyFavs
  render()
})
let opener
const dialog = document.querySelector('#info')
grid.addEventListener('click', event => {
  const fav = event.target.closest('[data-fav]')
  if (fav) {
    const id = fav.dataset.fav
    favourites.has(id) ? favourites.delete(id) : favourites.add(id)
    save()
    render()
    ;(grid.querySelector(`[data-fav="${id}"]`) ?? document.querySelector('#only-favs')).focus()
  }
  const info = event.target.closest('[data-info]')
  if (info) {
    const item = links.find(link => link.id === info.dataset.info)
    opener = info
    document.querySelector('#info-title').textContent = item.title
    document.querySelector('#info-text').textContent = item.note
    dialog.showModal()
  }
})
dialog.addEventListener('close', () => opener?.focus())
render()
1import '../style.css'
2import { links } from './data.js'
3
4// Pure function:同一組 input,永遠得同一組結果。
5export function filterLinks(items, state, favourites) {
6 return items.filter(item =>
7 (state.category === 'all' || item.category === state.category) &&
8 item.title.toLowerCase().includes(state.query.toLowerCase()) &&
9 (!state.onlyFavs || favourites.has(item.id))
10 )
11}
12
13const KEY = 'link-dashboard:favs:v1'
14const state = { query: '', category: 'all', onlyFavs: false }
15const grid = document.querySelector('#grid')
16const storageStatus = document.querySelector('#storage-status')
17let favourites = new Set()
18try {
19 const saved = JSON.parse(localStorage.getItem(KEY) ?? '[]')
20 if (Array.isArray(saved)) {
21 favourites = new Set(saved.filter(id => typeof id === 'string' && links.some(item => item.id === id)))
22 }
23} catch {
24 storageStatus.textContent = '讀唔到儲存資料;今次由空最愛開始。'
25}
26
27function save() {
28 try { localStorage.setItem(KEY, JSON.stringify([...favourites])) }
29 catch { storageStatus.textContent = '儲存唔到;今次操作仍然有效。' }
30}
31
32// 只接受相對位置同 http(s),文字用 textContent,唔將資料當 HTML。
33function safeUrl(value) {
34 try {
35 const url = new URL(value, location.href)
36 return ['http:', 'https:'].includes(url.protocol) ? url.href : '#'
37 } catch { return '#' }
38}
39
40function render() {
41 const shown = filterLinks(links, state, favourites)
42 grid.replaceChildren(...shown.map(item => {
43 const card = document.createElement('article')
44 const heading = document.createElement('h2')
45 const anchor = document.createElement('a')
46 anchor.textContent = item.title
47 anchor.href = safeUrl(item.url)
48 heading.append(anchor)
49 const badge = document.createElement('span')
50 badge.className = 'badge'
51 badge.textContent = item.status
52 const category = document.createElement('p')
53 category.textContent = item.category
54 const fav = document.createElement('button')
55 fav.textContent = favourites.has(item.id) ? '已收藏' : '加最愛'
56 fav.dataset.fav = item.id
57 fav.setAttribute('aria-label', item.title + ' 最愛')
58 fav.setAttribute('aria-pressed', String(favourites.has(item.id)))
59 const info = document.createElement('button')
60 info.textContent = '詳情'
61 info.dataset.info = item.id
62 info.setAttribute('aria-label', item.title + ' 詳情')
63 card.append(heading, badge, category, fav, info)
64 return card
65 }))
66 document.querySelector('#count').textContent = shown.length ? `搵到 ${shown.length} 個連結` : '冇結果,試下改搜尋或分類。'
67 document.querySelectorAll('[data-cat]').forEach(button => {
68 button.setAttribute('aria-pressed', String(button.dataset.cat === state.category))
69 })
70 document.querySelector('#only-favs').setAttribute('aria-pressed', String(state.onlyFavs))
71}
72
73// 一個 state → filter → render;listener 放喺唔會被換走嘅 parent。
74document.querySelector('#search').addEventListener('input', event => {
75 state.query = event.target.value
76 render()
77})
78document.querySelector('#categories').addEventListener('click', event => {
79 const button = event.target.closest('[data-cat]')
80 if (!button) return
81 state.category = button.dataset.cat
82 render()
83})
84document.querySelector('#only-favs').addEventListener('click', () => {
85 state.onlyFavs = !state.onlyFavs
86 render()
87})
88let opener
89const dialog = document.querySelector('#info')
90grid.addEventListener('click', event => {
91 const fav = event.target.closest('[data-fav]')
92 if (fav) {
93 const id = fav.dataset.fav
94 favourites.has(id) ? favourites.delete(id) : favourites.add(id)
95 save()
96 render()
97 ;(grid.querySelector(`[data-fav="${id}"]`) ?? document.querySelector('#only-favs')).focus()
98 }
99 const info = event.target.closest('[data-info]')
100 if (info) {
101 const item = links.find(link => link.id === info.dataset.info)
102 opener = info
103 document.querySelector('#info-title').textContent = item.title
104 document.querySelector('#info-text').textContent = item.note
105 dialog.showModal()
106 }
107})
108dialog.addEventListener('close', () => opener?.focus())
109render()
public/favicon.svg 1 lines · 完整原檔
  1. L1–1 簡單本機 SVG,冇外部引用。
public/favicon.svg
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#096750"/><path d="M18 22h28v7H18zm0 14h28v7H18z" fill="white"/></svg>
1<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#096750"/><path d="M18 22h28v7H18zm0 14h28v7H18z" fill="white"/></svg>
vite.config.js 2 lines · 完整原檔
  1. L1–2 vanilla scaffold 原本冇呢份檔;s7 自己加 base ./。
vite.config.js
import { defineConfig } from 'vite'
export default defineConfig({ base: './' })
1import { defineConfig } from 'vite'
2export default defineConfig({ base: './' })

完整 Dashboard · Live preview

本機內嵌

可以即刻搜尋、分類、收藏同開詳情。Sandbox 冇 same-origin,最愛喺呢個預覽唔會跨 reload 保存;請喺真正 dev/preview 測 persistence。

返頁頂 ↑
08 / LEARN BY BUILDING

由空資料夾手寫:s0 → s7

前 3 階段用普通 static server;s3 先引入 npm 同 ES modules。link-dashboard-vite 保留上一份手寫練習;正式 sample folder 叫 link-dashboard。每一步都先寫、再開 solution、再對照預覽。

s0

三個檔案,由一張卡開始

HTML 同 CSS 即使冇 JS 都仲喺度;role=status 訊息由 app.js 更新。

Terminal
mkdir link-dashboard
cd link-dashboard
# 建立下面 solution 嘅檔案
python3 -m http.server 8000 --bind 127.0.0.1
顯示 solution · 完整 snapshot

先自己打一次,再對照。每個 snapshot 獨立完整,唔引用其他 stage。

s1

Semantic HTML,六張卡

用 header/main/section/footer 分清區域;按鈕要原生元素。

Terminal
# 沿用 link-dashboard,將下面 snapshot 檔案換入
python3 -m http.server 8000 --bind 127.0.0.1
顯示 solution · 完整 snapshot

先自己打一次,再對照。每個 snapshot 獨立完整,唔引用其他 stage。

s2

Mobile-first CSS 排版

Grid 一欄起步,闊屏加欄,Tab 時見到 focus。

Terminal
# 沿用 link-dashboard,將下面 snapshot 檔案換入
python3 -m http.server 8000 --bind 127.0.0.1
顯示 solution · 完整 snapshot

先自己打一次,再對照。每個 snapshot 獨立完整,唔引用其他 stage。

s3

Vite + data modules

卡片由 links array 產生;改 src/data.js 加連結,唔改 render。

Terminal
cd ..
npm create vite@latest link-dashboard-vite -- --template vanilla --no-interactive
cd link-dashboard-vite
npm install
# 換入 solution 檔案,移除未使用嘅 scaffold 示例
npm run dev
顯示 solution · 完整 snapshot

先自己打一次,再對照。每個 snapshot 獨立完整,唔引用其他 stage。

s4

搜尋同分類:AND filter

同一個 state,搜尋 Router + Network 應只留 Router;空結果有文字。

Terminal
# 喺 link-dashboard-vite 更新下面 solution 檔案
npm run dev
# Ctrl+C 停 server 後
npm run build
npm run preview
顯示 solution · 完整 snapshot

先自己打一次,再對照。每個 snapshot 獨立完整,唔引用其他 stage。

s5

Favourites + 防守 storage

收藏再 reload 應保留;壞 JSON、null、object、混合 array 都要測。

Terminal
# 喺 link-dashboard-vite 更新下面 solution 檔案
npm run dev
# Ctrl+C 停 server 後
npm run build
npm run preview
顯示 solution · 完整 snapshot

先自己打一次,再對照。每個 snapshot 獨立完整,唔引用其他 stage。

s6

Native dialog 同 focus

詳情顯示 note;Esc 關閉之後焦點返原掣。

Terminal
# 喺 link-dashboard-vite 更新下面 solution 檔案
npm run dev
# Ctrl+C 停 server 後
npm run build
npm run preview
顯示 solution · 完整 snapshot

先自己打一次,再對照。每個 snapshot 獨立完整,唔引用其他 stage。

s7

Metadata、public assets、dist

自己加 vite.config.js;build/preview 後查 hash assets 同 favicon。

Terminal
# 喺 link-dashboard-vite 更新下面 solution 檔案
npm run dev
# Ctrl+C 停 server 後
npm run build
npm run preview
顯示 solution · 完整 snapshot

先自己打一次,再對照。每個 snapshot 獨立完整,唔引用其他 stage。

Stage preview · s0

純本機內嵌,唔發外部 request。s0–s2 係三個檔案;s3 起用 build 時合併嘅模組預覽。Storage persistence 請用真 HTTP sample 測。

返頁頂 ↑
09 / OBSERVE BEFORE YOU FIX

本機測試:用 DevTools 搵證據

先重現,再縮細範圍。Dev server 預設 http://localhost:5173,HMR 幫你快啲見到改動;port 忙可能換號,跟 terminal URL。Build 後 npm run preview 預設 http://localhost:4173,只做本機驗收。

Panel做乜想搵嘅證據
Elements揀張卡,改 CSS,睇 box modelDOM 有冇卡?邊條 rule 贏?Reload 會還原 live edits
Console讀 error stack,log state,用 $0Runtime error 定邏輯錯?冇 error 唔代表冇 bug
Sources喺 filter/render 落 breakpoint,step over邊個條件排走條 link?
NetworkReload;睇 path/status/MIME/responsewrong import 喺 dev 可係 500;其他缺檔可係 404
Device toolbar390×844,鍵盤、focus、捲動有冇 overflow 或控件出界?
ApplicationLocal Storage 改 link-dashboard:favs:v1 做 {oopsReload 有冇 crash?最愛係咪回空?
兩種 server 各自驗收
npm run dev
# 修改 title,觀察 HMR
# Ctrl+C 後
npm run build
npm run preview

Bug lab:先估症狀,再切換修復

七個無害示範,唔會執行惡意 code 或製造真 Console error。b4 / b5 係明確標示嘅模擬診斷;其他會改變真實 DOM / state 行為。

返頁頂 ↑
10 / THE BUILD TOOL

Vite:由 dev source 去 dist

Vite 根目錄嘅 index.html 係 entry。Dev 用 native ESM 按需送 source,dependency 預先處理;HMR 更新改動模組。Production 仲要 bundle,減少 nested imports 嘅 network round trips。Vite 8 用 Rolldown(Rust)做 bundler、Oxc 做 parse / transform / minify。

完整 npm workflow
npm create vite@latest my-app -- --template vanilla
# 可重複非互動 scaffold:
npm create vite@latest my-app -- --template vanilla --no-interactive
cd my-app
npm install
npm run dev
npm run build
npm run preview
base:根目錄同子路徑
vite.config.js
import { defineConfig } from 'vite'
export default defineConfig({ base: './' })

預設 / 適合根網址;./ 令 build assets URL 相對。呢個係 URL rewriting,唔會解除 file:// module CORS 限制。Vanilla scaffold 冇 vite.config.js,要自己加。

public/ vs import assets

public/icon.png 喺 source 用 /icon.png,原名原樣複製去 dist 根,適合 favicon、robots。一般圖片優先 import,回傳處理後 URL:dev 可係 /src/img.png,build 通常帶 content hash;小過 assetsInlineLimit 可 inline base64。亦支援 new URL('./img.png', import.meta.url).href。

Env 同 mode:公開設定先可以入 client
Env / mode
.env
.env.local
.env.[mode]
.env.[mode].local
# .gitignore 加:
*.local

# staging mode
npm run build -- --mode staging
# 直接 Vite 寫法(已安裝 Vite)
npx vite build --mode staging
npx vite build --watch

import.meta.env 提供 MODE / BASE_URL / PROD / DEV / SSR。VITE_ prefix 嘅值會入 client bundle,唔好放 secret。值係 string,"false" 唔係 boolean false。Mode-specific 覆蓋一般 .env;process 已有嘅 env 優先;改 .env 要 restart dev server。預設 build 係 production mode。Watch 只係 rebuild,唔係 hosting。

版本同 browser baseline

來源核對 2026-12-06:Vite 8.4.1、create-vite 9.4.0。Vite 要 Node 20.19+ / 22.12+;Node 20 已 EOL,新裝用仍受支援嘅 LTS。來源當日列 Node LTS v26.14.0,另有 v24.23.0 / v22.23.5。Windows .msi、macOS .pkg,裝完開新 terminal。

Build 預設 targets:Chrome ≥111、Edge ≥111、Firefox ≥114、Safari ≥16.4。只係 syntax baseline,唔保證所有新 Web API 有 polyfill。@latest 會變;lockfile 先可以鎖住重現。

新 terminal 檢查
node -v
npm -v
返頁頂 ↑
11 / SHIP AN ARTIFACT

Build → dist:交付前檢查

npm run build 唔係部署。先睇 exit status 同 warnings,再用 preview 按真功能,最後查 dist 實物。唔好 double-click module app 嘅 dist/index.html 判斷係咪壞咗。

驗收 routine
npm run build
npm run preview
# Browser: Console / Network → 390px → keyboard → reload
# dist/ 應有 index.html、assets/ 同原名 favicon.svg
Hash、cache 同 bundle size

Hash 將內容版本放入檔名,適合長期 immutable cache;HTML 應 revalidate,例如 Cache-Control: no-cache,避免舊 HTML 指去被刪嘅舊 hash。no-cache 係要驗證,唔係完全唔儲存。固定檔名 public 資源要另外諗更新策略。呢度只講概念;hosting 設定去另一個 training。

原參考 s7 嘅數字唔會當成本 dashboard 嘅結果。實際 sizes 以你自己 build report 為準,比較新增依賴、gzip 同前一版。

NEXT TRAINING

Build 完之後點算?

帶住驗收過嘅 dist,去 Cloudflare deploy training 處理 Deploy → Domain → Protect → Update / Rollback。

Cloudflare deploy training

返頁頂 ↑
12 / ASK FOR EVIDENCE

點樣指揮同 review AI code

Prompt 先講需求、schema、檔案責任同驗收條件。Review 唔好只問「靚唔靚」:睇 source、再做 browser 操作,對照結果。

Scaffold prompt
Prompt template
用 vanilla Vite,建立 IT Links Dashboard:index.html、style.css、src/main.js、src/data.js、public/favicon.svg、vite.config.js。先列 schema 同檔案責任。唔用 framework、CDN 或外部 requests。搜尋 + 分類 AND filter,status 係示例資料。HTML 用 zh-Hant-HK、semantic landmarks、labels 同原生 controls。資料用 textContent,URL 驗證 protocol。提供 dev/build/preview 同測試證據。
Add feature prompt
Prompt template
加 favourites:versioned localStorage key,讀寫 try/catch、Array.isArray、string 同有效 id 驗證。用 Set 去重。main.js 用 parent event delegation;重畫後保留 keyboard focus。測正常、壞 JSON、null、object、混合型 array 同 denied storage。
Refactor prompt
Prompt template
先固定行為,畫 import graph。將 data、pure filter、render、events 同 CSS 分開;每步比較相同 inputs 嘅 outputs。唔改 UI 行為。最後 build 同 browser smoke test。
Fix with evidence prompt
Prompt template
先重現:[步驟、預期、實際、Console/Network 證據]。定位最細原因,做最細修復。提供修復前後同一操作嘅結果,唔好只報 build pass。
Accessibility prompt
Prompt template
檢查 landmarks、heading、labels、aria-pressed、status、Tab/Enter/Esc、dialog 焦點返回、focus-visible、4.5:1 同 44px。逐項引用元素同證據。
Mobile prompt
Prompt template
喺 390×844 同 1280×800 測。查 scrollWidth、code box 自己 scroll、grid、drawer、dialog 邊界。交 screenshots;唔用 body overflow-x:hidden 掩飾。
Security prompt
Prompt template
檢查 innerHTML、insertAdjacentHTML、URL、localStorage 同 VITE_。唔好放 secret。用無害標記測 textContent;唔用 regex 假扮萬能 sanitizer。列依賴同外部 requests。
Explain code prompt
Prompt template
用識 CLI 同網絡但未寫過 web 嘅讀者角度,解釋 entry → import → state → filter → render → event。附檔案同真行號,分清 pure function、DOM 副作用同 storage。唔改 code。
Red flag追問 / 修法
一個巨型 inline script邊個擁有 state?有冇 pure functions 可以抽?
innerHTML = 外來文字可以用 textContent?URL 有冇獨立驗證?
VITE_SECRET / hard-coded keyClient 人人讀到,移除或重新設計 server 層
JSON.parse 冇 catch壞 JSON、舊 schema、denied storage 會點?
只報 build pass有冇操作、reload、keyboard、窄屏證據?
刪 outline / 只靠 hover鍵盤同 touch 用家點知道焦點?
返頁頂 ↑
13 / YOUR TERMINAL COMPANION

Cheat sheet:用嗰陣先查

返頁頂 ↑
14 / DIAGNOSE, THEN REPAIR

Troubleshooting:由症狀去原因

先 Console + Network,再 DOM 同 state,最後先調樣式。有啲 bug 完全冇 Console error。

開 module app 一片空白

可能原因:file:// module CORS,或者錯 entry / MIME。

修復同驗證:先用 npm run dev / preview;Console 讀 stack,Network 查 script path/status/MIME。

本機得,Linux 唔得

可能原因:import 或 asset 大細楷唔一致。

修復同驗證:逐字核對 src/data.js;唔好靠 OS 自動忽略大小寫。

Filter 按咗冇變

可能原因:State 改咗,未 render;或者 listener 被換走。

修復同驗證:Sources breakpoint 睇 state;集中 update,用 parent delegation。

子路徑 CSS / JS 404

可能原因:base / 導覽 URL 策略唔吻合。

修復同驗證:先查 dist/index.html URL;考慮 base ./ 後重新 build,再 HTTP preview。

Unexpected token / JSON.parse crash

可能原因:壞 JSON 或儲存格式轉咗。

修復同驗證:讀寫 try/catch;Array.isArray、string/id 驗證;用 versioned key。

Build pass 但冇 JS

可能原因:漏咗 type="module" 可能只出 warning。

修復同驗證:讀 warning,查 dist 有冇 JS asset,再 preview 真操作。

VITE_ 改咗都冇變

可能原因:Env 喺啟動/建置時讀取,或者值係 string。

修復同驗證:Restart dev / rebuild;mode-specific 覆蓋一般檔,唔將 "false" 當 false。

Mobile 橫向溢出

可能原因:固定闊度、grid min-content 或長 code。

修復同驗證:查最闊元素;minmax(0,1fr)、min-width:0;code/table 盒內 scroll。

最愛保存唔到

可能原因:Origin 變咗、storage denied / full、file:// 政策。

修復同驗證:核對 scheme/host/port;catch 寫入錯誤顯示狀態;用本機 HTTP 測。

返頁頂 ↑
15 / ACTIVE RECALL

Flashcards:主動記,唔淨係睇

先答一次,再翻牌。撳「識喇」記入進度;「再溫」會移除已識標記。章節篩選同 shuffle 唔會清除記錄。

返頁頂 ↑
16 / CHECK YOUR UNDERSTANDING

章節小測:睇你記得幾多

0 / 12

每章小測有即時解釋。可以重試;記錄保存最後選擇。重設會清除所有答案。

返頁頂 ↑
17 / PROVE YOU CAN BUILD

Capstone:自己由零做一次

唔睇答案,用一個新 folder 做同類 dashboard。用以下 checklist 同逐章勾選追蹤;所有記錄只存喺本機 browser,唔會傳出去。

你嘅學習進度

0%

只清除此 training 嘅 checklist、quiz 同 flashcards;保留主題。

返頁頂 ↑
18 / SPEAK THE LANGUAGE

Glossary:識得用自己說話解釋

English term廣東話解釋
DOMbrowser 記憶體入面嘅文件樹
CSSOMparse 咗嘅 CSS 規則樹
Render tree實際要排版同繪畫嘅結構
Layout計算元素尺寸同位置
Paint將樣式畫成 pixels
Static siteserver 只需送現成檔案
SSRserver 先產生 HTML
Entry開始載入嘅檔案
ES module有獨立 scope、import/export 嘅 JS 檔
Import graph模組互相引用嘅關係
HMR開發時局部替換改咗嘅模組
Bundle將依賴整理成可交付檔案
Minify縮細 code 但保留行為
Content hash由內容產生嘅版本識別
Cache busting換 URL 令 client 攞新內容
base部署資源 URL 嘅前綴策略
Artifact可重複 build 出嚟嘅交付成果
Viewportbrowser 用嚟排版嘅可見區域
Box modelcontent、padding、border、margin 層次
Cascade多條 CSS 規則決定最終值嘅次序
Specificity同來源規則之間嘅 selector 權重
Flexbox沿主軸分配空間嘅 layout
Grid同時處理行同列嘅 layout
State而家選項同互動嘅記憶
Pure function同 input 同 output,冇外部副作用
Event delegationparent 接住 descendant 嘅冒泡事件
Event loop安排 JS tasks 同 render 機會嘅流程
localStorageorigin 私有、同步嘅字串 key/value 儲存
Originscheme + host + port 嘅組合
CORSbrowser 對跨 origin 存取嘅規則
XSS唔可信資料變成可執行內容嘅攻擊
Escape將特別符號轉成純文字表示
ARIA補充輔助工具理解嘅語義同狀態
Focus trapmodal 開住時將 Tab 留喺 modal
Reduced motion用戶要求減少動畫嘅偏好
Modebuild/dev 使用嘅設定環境名稱
返頁頂 ↑
19 / SOURCE-BACKED

Sources 同核對記錄

Checked:2026-12-06 · 來源版本:Vite 8.4.1 / create-vite 9.4.0。配套部署來源核對 Wrangler 4.171.0,本篇唔教部署指令。

本機實測版本同結果見工作資料夾 RESULT.md。版本事實根據提供嘅 FACTS-VITE.md 同技術指南;下次使用 @latest 前,要再查 LTS / EOL、engines、prompts 同 browser targets。

一般 browser / CSS / JS 解釋屬一般知識;「類比」有獨立標示。呢個 training 頁用 classic scripts 離線運作,sample 係 Vite ES modules,要本機 HTTP。

返頁頂 ↑