diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..2ff2c91 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,10 @@ +# ค่าเริ่มต้นของ Git สำหรับ repo นี้ +* text=auto eol=lf +*.json text eol=lf +*.js text eol=lf +*.mjs text eol=lf +*.css text eol=lf +*.html text eol=lf +*.md text eol=lf +*.woff2 binary +*.png binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ac8893d --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +# ไฟล์/โฟลเดอร์ที่ไม่ขึ้น Git +node_modules/ +.DS_Store +Thumbs.db +*.log +.env +.env.* diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..94f1e6b --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,79 @@ +# AGENTS.md — คู่มือสำหรับ agent ที่เข้ามาแก้โปรเจคนี้ + +## ภาพรวม + +Static PWA + SPA (ไม่มี build step) สำหรับหน้ารายชื่อโปรเจคอดิเรก + หลังบ้านแก้ข้อมูล +สแตก: HTML + CSS + ES modules ตรง ๆ · Node 22 สำหรับเซิร์ฟเวอร์หลังบ้าน (ไม่มี dependency) +Repository: `hobbypj-contents` (Gitea org `hobbyproject-list`) · deploy เป้าหมาย `www.hobbypj.com` + +## คำสั่งที่ใช้บ่อย + +```bash +node server/publish.mjs # เซิร์ฟเวอร์ + หลังบ้าน → http://localhost:8090 +npm run check # ตรวจ syntax ทุกไฟล์ JS/MJS +PORT=8090 ADMIN_TOKEN=xxx node server/publish.mjs # โหมดมีรหัสเผยแพร่ +PUBLISH_PUSH=0 node server/publish.mjs # เขียน+commit แต่ไม่ push +``` + +## กติกาที่ห้ามละเมิด + +1. **แก้ที่ repo นี้เท่านั้น** — `data/projects.json` คือข้อมูลจริง ไม่มีฐานข้อมูลอื่น +2. **ห้ามแก้อิโมจิลงหน้าเว็บ** — ไอคอนทุกตัวมาจาก `ui/ui.js` (`icon("ชื่อ")`) +3. **ภาษาไทยทั้งหน้า** — ห้ามใส่คำอังกฤษเป็นหัวข้อ/ป้าย (โดเมนและคำเทคนิคเท่านั้น) +4. **สีต้องมาจาก `assets/css/theme.css`** — ห้ามใส่ hex ใหม่ในไฟล์ view; ถ้าต้องเพิ่มสี ให้เพิ่มเป็นโทเคน + อัปเดต `DESIGN.md` +5. **ตัวอักษรต้อง ≥ 4.5:1** บนพื้นของตัวเอง — เพิ่มสีใหม่ต้องคำนวณคอนทราสต์ ไม่เดาจากสายตา +6. **ปุ่ม/ลิงก์ต้องมีพื้นที่กด ≥ 44×44px** และมี `aria-label` เมื่อเป็นไอคอนเดี่ยว +7. **แก้ `sw.js` หรือรายการ `PRECACHE` → bump `VERSION`** ใน `sw.js` และ `` ใน `index.html` ให้ตรงกัน (แก้ HTML/CSS/JSON อย่างเดียวไม่ต้อง bump) +8. **PWA boot บน plain HTTP ไม่ได้** — ต้อง HTTPS หรือ localhost +9. การเปลี่ยนคำ/ค่าออกแบบ → อัปเดต `DESIGN.md` และ `README.md` (เครดิต) ด้วยในคอมมิตเดียวกัน + +## แผนที่ไฟล์ + +| ไฟล์ | หน้าที่ | +|---|---| +| `index.html` | shell: header/footer, meta, manifest, mount `#main` | +| `ui/app.js` | boot: โหลดข้อมูล → ผูก router → เรนเดอร์ view, อัปเดต footer | +| `ui/router.js` | hash router (`#/`, `#/admin`) + `aria-current` ของเมนู | +| `ui/data.js` | อ่าน/เขียนข้อมูล, normalize, ฉบับร่าง (localStorage), `PUT api/projects` | +| `ui/ui.js` | ชุดไอคอน SVG, escape, toast, ตรวจ URL/อีเมล | +| `ui/views/home.js` | ฮีโร่ + ค้นหา + การ์ดโปรเจค | +| `ui/views/admin.js` | หลังบ้าน: ฟอร์มแก้ไข, เรียงลำดับ, ลบ, เผยแพร่, ดาวน์โหลด JSON | +| `server/publish.mjs` | static server + `GET/PUT api/projects` + git commit/push | +| `data/projects.json` | ข้อมูลจริง (คีย์เต็มคำ: `project_name`, `project_description`, `project_url`, `contact_email`, `icon`) | + +## สัญญาข้อมูล (schema) + +```json +{ + "schema_version": 1, + "updated_at": "ISO-8601", + "owner_name": "", + "site": { "site_title": "", "welcome_message": "", "contact_email": "", "ssl_note": "" }, + "projects": [ + { "project_id": "", "project_name": "", "project_description": "", + "project_url": "https://…", "contact_email": "", "icon": "folder" } + ] +} +``` + +- `project_id` ต้องไม่ซ้ำ (ตัว normalize เติมให้อัตโนมัติถ้าซ้ำ) +- `project_url` ต้องมี scheme `http(s)` — เซิร์ฟเวอร์ตอบ 422 ถ้าไม่ผ่าน +- `icon` ต้องเป็นคีย์ใน `ICON_LABELS` (`ui/views/admin.js`) ไม่งั้นจะ fallback เป็น `folder` + +## ขั้นตอนตรวจก่อนส่งงาน + +```bash +npm run check +node server/publish.mjs +curl -s localhost:8090/api/projects | head -5 +# เปิด http://localhost:8090/ และ http://localhost:8090/#/admin +``` + +ในเบราว์เซอร์: `Page.getAppManifest` ต้องได้ `errors: []`, `navigator.serviceWorker.controller` ต้องไม่ว่าง, ไม่มี error ใน console, และทดสอบที่ 375 / 768 / 1440 px (`scrollWidth === innerWidth`) + +## กับดักที่เคยเจอ + +- ฟอนต์: `assets/css/theme.css` อ้าง `../../fonts/…` — ถ้าย้าย CSS ให้แก้ path ไม่งั้นฟอนต์ไทยหลุดเป็นฟอนต์ระบบ +- `PUT api/projects` เขียนทับทั้งไฟล์: ส่งข้อมูลที่ normalize แล้วเท่านั้น ไม่งั้นคีย์จะหาย +- กดเผยแพร่ซ้ำโดยไม่แก้อะไรจะได้ commit ใหม่ (เพราะ `updated_at` เปลี่ยน) — ปกติ ไม่ใช่บั๊ก +- ถ้าเปิดเว็บด้วย `python -m http.server` API จะ 404 → หน้าหลังบ้านจะขึ้นสถานะ “เปิดแบบไฟล์นิ่ง” และใช้ดาวน์โหลด JSON แทน diff --git a/DESIGN.md b/DESIGN.md new file mode 100644 index 0000000..be19bae --- /dev/null +++ b/DESIGN.md @@ -0,0 +1,75 @@ +# DESIGN.md — กติกาการออกแบบ (ใช้กับทุกหน้าในโปรเจคนี้) + +เอกสารนี้คือ “รัฐธรรมนูญ” ของหน้าตา เว็บนี้ ถ้าจะเปลี่ยนสี ระยะ หรือส่วนประกอบ ต้องแก้ไฟล์นี้ก่อนแล้วจึงแก้โค้ด + +## 1. แนวคิด + +- เว็บรวมโปรเจคอดิเรกส่วนตัว: **เรียบ อบอุ่น อ่านง่าย** ไม่ใช่เว็บขายของ +- โครงหน้าและจังหวะการวางอ้างอิง **fastwork.com** (ฮีโร่ + ช่องค้นหา + การ์ดเป็นตาราง + ฟุตเตอร์ 3 คอลัมน์) +- ธีมสี: **น้ำตาล + ขาว** เลือกเฉดน้ำตาลที่ “สดและสว่าง” (โมก้า-คาราเมล) หลีกเลี่ยงน้ำตาลเข้มแบบซีเปีย/วินเทจที่สื่อถึงความเก่า +- ภาษาไทยทั้งหน้า ไม่มีคำอังกฤษลอยเป็นป้าย/หัวข้อ (ชื่อโดเมนและคำเทคนิคเท่านั้นที่คงอังกฤษ) + +## 2. โทเคนสี (ตรวจคอนทราสต์บนพื้นขาวแล้ว) + +| โทเคน | ค่า | คอนทราสต์บน #FFFFFF | ใช้กับ | +|---|---|---|---| +| `--brand-50` | `#FDF7F2` | — | พื้นอ่อน, พื้นไอคอน | +| `--brand-100` | `#FAEADF` | — | ป้ายนับจำนวน, พื้น chip ที่เลือก | +| `--brand-200` | `#F3D5C1` | — | เส้นขอบอ่อน | +| `--brand-300` | `#E8B695` | — | เส้นขอบ hover | +| `--brand-400` | `#D99368` | 2.52:1 | **กราฟิกเท่านั้น ห้ามใช้เป็นตัวอักษร** | +| `--brand-500` | `#C4703C` | 3.66:1 | ไอคอน/เส้นตกแต่ง (ไม่ใช่เนื้อหา) | +| `--brand-600` | `#A85A2C` | 5.04:1 | ตัวอักษรเน้น, โฟกัสริง | +| `--brand-700` | `#8A4722` | 6.99:1 | ปุ่มหลัก, ลิงก์ | +| `--brand-800` | `#6B3620` | 9.66:1 | หัวข้อย่อย, ตัวอักษรเน้นเข้ม | +| `--brand-900` | `#3D241A` | 14.33:1 | หัวข้อหลัก | +| `--foreground` | `#241A15` | 17.02:1 | เนื้อความ | +| `--muted-foreground` | `#6F6159` | 5.95:1 | คำอธิบาย, ข้อความรอง | +| `--border` | `#EADFD6` | — | เส้นขอบการ์ด | +| `--border-strong` | `#DCCABA` | — | ขอบช่องกรอก/เส้นแบ่งที่ต้องเห็นชัด | +| `--surface-2` | `#FBF6F1` | — | พื้นพาเนล/ฟุตเตอร์ | + +กติกา: ตัวอักษรทุกตัวต้อง ≥ 4.5:1 บนพื้นของตัวเอง · ปุ่มหลักใช้พื้น `--brand-700` + ตัวอักษรขาว (6.99:1) + +## 3. ตัวอักษร + +- ฟอนต์: **K2D** (ฝังใน `fonts/`, 3 น้ำหนัก: 400 / 500 / 700) — ไทยมีหัว อ่านง่ายบนจอเล็ก +- ฐาน: `16px`, `line-height 1.6`; หัวข้อ `line-height 1.25` และ `letter-spacing` ติดลบเล็กน้อย +- หัวเรื่องฮีโร่: `clamp(1.6rem, 1.15rem + 2.05vw, 2.5rem)` กว้างสุด `24ch` (ข้อความต้อนรับยาว จึงต้องคุมความกว้าง) +- ห้ามใช้ตัวอักษรเล็กกว่า 12px ในเนื้อหา + +## 4. ระยะ / มุม / เงา + +- สเกลระยะ: 4 · 8 · 12 · 16 · 20 · 24 · 32 · 40 · 48 · 64 · 80 px +- มุมโค้ง: `8 / 12 / 16 / 22 / pill` — การ์ดใช้ 16, ช่องกรอกใช้ 12, ปุ่มใช้ pill +- เงา: ใช้เฉพาะตอนยกการ์ดขึ้น (hover) และปุ่มหลัก — ไม่ใส่เงาซ้อนหลายชั้น + +## 5. ส่วนประกอบ + +- **Header**: สูง 64px (มือถือ) / 72px (≥900px), sticky, พื้นขาว 92% + blur, ขอบล่าง 1px +- **ปุ่ม**: สูงขั้นต่ำ 44px (44×44 ตาม WCAG 2.5.8) · `primary` (น้ำตาลเข้ม+ขาว) · `ghost` (ขาว+ขอบ) · `quiet` · `danger` +- **ช่องค้นหา**: pill, เงา, ไอคอนซ้าย, ปุ่มล้างคำค้นหา 32×32 (มี label ให้ screen reader) +- **การ์ดโปรเจค**: ไอคอน 46×46 (พื้น `--brand-50`), ชื่อเป็นลิงก์ที่ขยายพื้นที่คลิกเต็มใบด้วย `::after`, คำอธิบาย 3 บรรทัดตัดด้วย `-webkit-line-clamp`, ท้ายการ์ดมี host + “เปิดเว็บไซต์” +- **ฮีโร่**: พื้นไล่เฉดอุ่นอ่อน + การ์ดลอย 3 ใบจากข้อมูลจริง (แสดงเฉพาะ ≥1080px, `aria-hidden`) +- **หลังบ้าน**: พาเนล + การ์ดรายการ, ปุ่มเลื่อนขึ้น/ลง/ลบ, แถบบันทึกแบบ sticky ด้านล่าง, `` ยืนยันการลบ/ทิ้งการแก้ไข + +## 6. สิ่งที่ห้าม + +- ห้ามใช้อิโมจิเป็นไอคอน (ใช้ SVG เส้น 1.7px ใน `ui/ui.js`) +- ห้ามใช้สีน้ำตาลเข้ม `#3E2A20`-ลงไปเป็นพื้นปุ่มใหญ่ (ดูแก่) — ใช้ได้แค่ตัวอักษร +- ห้ามใส่คำอังกฤษลอยเป็นหัวข้อ/ป้ายบนหน้าไทย +- ห้ามลบ focus ring; ทุกองค์ประกอบที่โฟกัสได้ต้องเห็น ring น้ำตาล +- ห้ามใช้ `transform`/animation กับการเปลี่ยน layout; ต้องเคารพ `prefers-reduced-motion` + +## 7. Responsive + +- มือถือก่อน: การ์ด 1 คอลัมน์ (<700px) → 2 (≥700px) → 3 (≥1000px) +- การ์ดลอยในฮีโร่แสดงเฉพาะ ≥1080px +- ตรวจที่ 375 / 768 / 1024 / 1440 px และต้องไม่มี horizontal scroll + +## 8. PWA + +- `manifest.json`: `display: standalone`, `start_url: ./`, `theme_color: #8A4722` +- ไอคอน PNG จริง 192 / 512 / 512-maskable / 180 (สร้างจาก `make_icons` ด้วย PIL ไม่ใช้ตัวอักษร) +- `sw.js`: network-first สำหรับ HTML/CSS/JS/JSON, cache-first สำหรับรูป/ฟอนต์, ข้าม `/api/` +- แก้ `sw.js` หรือรายการ `PRECACHE` → ต้อง bump `VERSION` และ `` พร้อมกัน diff --git a/README.md b/README.md index d3e41ee..e8b15bd 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,75 @@ -# hobbypj-contents +# hobbypj-contents — หน้ารายชื่อโปรเจคอดิเรก -Test commit to verify push access. +หน้าเว็บรวมรายชื่อโปรเจคอดิเรกของเรา (PWA + SPA แบบไม่มี build step) พร้อม **หลังบ้าน** สำหรับแก้ชื่อโปรเจค คำอธิบายใต้ชื่อ และลิงก์ + +- เว็บจริง: https://www.hobbypj.com +- ข้อมูลทั้งหมดอยู่ในไฟล์เดียว: `data/projects.json` +- หน้าแก้ไข: `#/admin` (หรือกดปุ่ม “แก้ไขรายการ” มุมขวาบน) + +## รันในเครื่อง + +```bash +node server/publish.mjs # → http://localhost:8090 +``` + +เปิดแบบไฟล์นิ่งก็ได้ (`python -m http.server 8090`) แต่จะ **เผยแพร่จากหน้าเว็บไม่ได้** เพราะไม่มีเซิร์ฟเวอร์มารับการบันทึก — ใช้ปุ่ม “ดาวน์โหลด JSON” แทน + +## ระบบหลังบ้านทำงานอย่างไร + +``` +เบราว์เซอร์ (#/admin) + │ PUT /api/projects (JSON ทั้งก้อน) + ▼ +server/publish.mjs + ├─ ตรวจข้อมูล (ชื่อว่าง / ลิงก์ผิด / อีเมลผิด → 422) + ├─ เขียนทับ data/projects.json + └─ git add + commit + push ขึ้น Gitea (repo นี้) +``` + +ตัวเลือกที่ใช้ได้: + +| ตัวแปร | ค่าเริ่มต้น | ความหมาย | +|---|---|---| +| `PORT` | `8090` | พอร์ตของเซิร์ฟเวอร์ | +| `ADMIN_TOKEN` | ว่าง | ถ้าตั้ง ต้องกรอกรหัสในหน้า “ตั้งรหัสเผยแพร่” ก่อนบันทึก (แนะนำเมื่อเปิดให้เครื่องอื่นเข้า) | +| `PUBLISH_PUSH` | `1` | `0` = เขียนไฟล์ + commit แต่ไม่ push | +| `HOST` | `0.0.0.0` | ถ้าไม่ตั้ง `ADMIN_TOKEN` จะรับเฉพาะ request จากเครื่องเดียวกัน | + +ถ้าไม่ได้ตั้ง `ADMIN_TOKEN` เซิร์ฟเวอร์จะอนุญาตเฉพาะเครื่องที่รันมันอยู่ — เปิดให้เครื่องอื่นแก้ต้องตั้งรหัสเสมอ + +## เนื้อหาเริ่มต้น (มาจากตารางรายชื่อโปรเจค) + +| ชื่อโปรเจค | ซับโดเมน | อีเมล | +|---|---|---| +| หน้ารายชื่อโปรเจค | www.hobbypj.com | — | +| ใช้ทำงานประจำ | dashboard.hobbypj.com | — | +| รวบรวมโรงหนัง | alterflixhub.hobbypj.com | alterflixhub@hobbypj.com | +| รวบรวมรถประจำทาง | atroute.hobbypj.com | atroute@hobbypj.com | +| ออกแบบสปริงเกลอร์ | irrcal.hobbypj.com | irrcal@hobbypj.com | +| ขายเคสคอมปรับแต่ง | kth.hobbypj.com | kth@hobbypj.com | +| ตัวอย่างรถประจำทางอุดมคติ | at2pch.hobbypj.com | — | +| ขายแผ่น Bluray และรายชื่อหนังมาดูซ้ำ | flixdisc.hobbypj.com | flixdisc@hobbypj.com | +| รายชื่อหนังสือส่วนตัว | mylib.hobbypj.com | — | +| รายชื่อเครื่องมือช่างส่วนตัว | mytool.hobbypj.com | — | + +ทุกเว็บใช้ SSL ฟรี ต่ออายุอัตโนมัติ + +## โครงไฟล์ + +``` +index.html shell ของ SPA (header/footer + จุด mount) +manifest.json manifest ของ PWA +sw.js service worker (ออฟไลน์ + อัปเดตอัตโนมัติ) +assets/css/ theme.css (โทเคน/ส่วนประกอบกลาง) · home.css · admin.css +ui/ app.js · router.js · data.js · ui.js · pwa.js · views/ +data/projects.json ข้อมูลจริง (แก้ผ่านหลังบ้านเท่านั้น) +server/publish.mjs เซิร์ฟเวอร์หลังบ้าน (static + API + git) +fonts/ K2D ฝังในโปรเจค (SIL OFL 1.1) +icons/ ไอคอน PWA (สร้างจากสคริปต์ PIL ไม่ใช้ emoji) +``` + +## เครดิต + +- ฟอนต์ K2D — Cadson Demak, SIL Open Font License 1.1 +- โครงหน้า/จังหวะการวางเลย์เอาต์อ้างอิงจาก fastwork.co (ไม่ได้ลอกสีหรือสินทรัพย์ใด ๆ) — ธีมสีเป็นน้ำตาล-ขาวของโปรเจคนี้เอง +- ไอคอนเป็น SVG วาดเองตามสไตล์เส้น 1.7px (ไม่มีอิโมจิในหน้าเว็บ) diff --git a/assets/css/admin.css b/assets/css/admin.css new file mode 100644 index 0000000..7d995be --- /dev/null +++ b/assets/css/admin.css @@ -0,0 +1,312 @@ +/* ========================================================================== + admin.css — หน้าจัดการข้อมูล (หลังบ้าน) + ========================================================================== */ + +.admin-head { + display: flex; + flex-wrap: wrap; + align-items: flex-start; + justify-content: space-between; + gap: var(--space-4); + padding-bottom: var(--space-5); + border-bottom: 1px solid var(--border); +} +.admin-head__title { + font-size: clamp(1.35rem, 1.15rem + 0.9vw, 1.75rem); +} +.admin-head__sub { + margin-top: 6px; + color: var(--muted-foreground); + font-size: 14.5px; + max-width: 52ch; +} +.admin-head__actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-2); +} + +.panel { + margin-top: var(--space-6); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + background: var(--surface); + overflow: hidden; +} +.panel__head { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-3); + padding: var(--space-4) var(--space-5); + background: var(--surface-2); + border-bottom: 1px solid var(--border); +} +.panel__title { + font-size: 1rem; + font-weight: 700; + color: var(--brand-900); +} +.panel__body { + padding: var(--space-5); +} + +/* ------------------------------------------------------------- fields */ +.field { + display: flex; + flex-direction: column; + gap: 6px; +} +.field + .field { + margin-top: var(--space-4); +} +.field__label { + font-size: 14px; + font-weight: 500; + color: var(--brand-800); +} +.field__hint { + font-size: 12.5px; + color: var(--muted-foreground); +} +.field input[type="text"], +.field input[type="url"], +.field input[type="email"], +.field textarea, +.field select { + width: 100%; + min-height: 44px; + padding: 10px 14px; + border: 1px solid var(--border-strong); + border-radius: var(--radius-md); + background: #fff; + font-size: 15px; + transition: + border-color 150ms var(--ease), + box-shadow 150ms var(--ease); +} +.field textarea { + min-height: 84px; + resize: vertical; + line-height: 1.55; +} +.field input:hover, +.field textarea:hover { + border-color: var(--brand-300); +} +.field input:focus, +.field textarea:focus { + outline: none; + border-color: var(--brand-500); + box-shadow: 0 0 0 4px rgba(196, 112, 60, 0.15); +} +.field--error input, +.field--error textarea { + border-color: #b3391f; + box-shadow: 0 0 0 4px rgba(179, 57, 31, 0.12); +} +.field__error { + font-size: 12.5px; + color: #8f2c19; + font-weight: 500; +} +.field__error:empty { + display: none; +} + +/* ------------------------------------------------------------- rows */ +.admin-list { + display: flex; + flex-direction: column; + gap: var(--space-4); +} +.admin-item { + border: 1px solid var(--border); + border-radius: var(--radius-md); + background: var(--surface); + padding: var(--space-4); +} +.admin-item__head { + display: flex; + align-items: center; + gap: var(--space-3); + padding-bottom: var(--space-3); + border-bottom: 1px solid var(--brand-50); + margin-bottom: var(--space-4); +} +.admin-item__index { + flex: none; + display: grid; + place-items: center; + width: 30px; + height: 30px; + border-radius: 9px; + background: var(--brand-100); + color: var(--brand-800); + font-size: 13px; + font-weight: 700; +} +.admin-item__label { + flex: 1 1 auto; + min-width: 0; + font-weight: 500; + color: var(--brand-900); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.admin-item__tools { + display: flex; + flex-wrap: wrap; + gap: 6px; +} +.admin-item__tools .btn { + min-height: 36px; + padding: 6px 10px; + font-size: 13px; + border-radius: var(--radius-sm); +} +.admin-item__tools .btn svg { + width: 16px; + height: 16px; +} + +.admin-grid-2 { + display: grid; + gap: var(--space-4); + margin-top: var(--space-4); +} +.admin-item .admin-grid-2:first-of-type { + margin-top: 0; +} +.admin-item .field + .field { + margin-top: var(--space-4); +} + +/* ------------------------------------------------------------- publish */ +.publish-status { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 14px; + padding: 12px 16px; + border-radius: var(--radius-md); + background: var(--brand-50); + border: 1px solid var(--brand-200); + color: var(--brand-800); + font-size: 14px; +} +.publish-status__dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--brand-500); +} +.publish-status[data-state="ok"] .publish-status__dot { + background: #2f7a44; +} +.publish-status[data-state="warn"] { + background: #fdf3e7; + border-color: #f0cfa8; + color: #7c4a13; +} +.publish-status[data-state="error"] { + background: #fdf1ee; + border-color: #e7c4bb; + color: #8f2c19; +} + +.admin-hint { + margin-top: var(--space-3); + font-size: 13px; + color: var(--muted-foreground); +} +.admin-hint code { + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; + font-size: 12.5px; + background: var(--surface-2); + border: 1px solid var(--border); + border-radius: 6px; + padding: 1px 6px; +} + +.dirty-bar { + position: sticky; + bottom: 12px; + margin-top: var(--space-5); + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: var(--space-3); + padding: 12px 16px; + border-radius: var(--radius-lg); + background: rgba(61, 36, 26, 0.96); + color: #fff; + box-shadow: var(--shadow-lg); +} +.dirty-bar[hidden] { + display: none; +} +.dirty-bar__text { + font-size: 14px; +} +.dirty-bar__actions { + display: flex; + gap: 8px; +} +.dirty-bar .btn--ghost { + background: transparent; + border-color: rgba(255, 255, 255, 0.35); + color: #fff; +} +.dirty-bar .btn--ghost:hover { + background: rgba(255, 255, 255, 0.12); +} +.dirty-bar .btn--primary { + background: #fff; + color: var(--brand-800); +} +.dirty-bar .btn--primary:hover { + background: var(--brand-100); +} + +/* ------------------------------------------------------------- dialog */ +.dialog { + width: min(560px, calc(100vw - 32px)); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + padding: 0; + color: var(--foreground); + box-shadow: var(--shadow-lg); +} +.dialog::backdrop { + background: rgba(36, 26, 21, 0.45); + backdrop-filter: blur(2px); +} +.dialog__head { + padding: var(--space-5); + border-bottom: 1px solid var(--border); +} +.dialog__title { + font-size: 1.05rem; +} +.dialog__body { + padding: var(--space-5); +} +.dialog__foot { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: var(--space-2); + padding: var(--space-4) var(--space-5); + border-top: 1px solid var(--border); + background: var(--surface-2); +} + +@media (min-width: 760px) { + .admin-grid-2 { + grid-template-columns: 1fr 1fr; + gap: var(--space-4) var(--space-5); + } +} diff --git a/assets/css/home.css b/assets/css/home.css new file mode 100644 index 0000000..7d7181f --- /dev/null +++ b/assets/css/home.css @@ -0,0 +1,470 @@ +/* ========================================================================== + home.css — หน้าแรก: ฮีโร่ + ช่องค้นหา + การ์ดโปรเจค + ========================================================================== */ + +.hero { + position: relative; + overflow: hidden; + border: 1px solid var(--border); + border-radius: var(--radius-xl); + background: + radial-gradient(120% 140% at 12% 0%, #fff 0%, var(--brand-50) 46%, var(--brand-100) 100%); + padding: var(--space-8) var(--space-5); +} +.hero__inner { + position: relative; + z-index: 1; + max-width: 46rem; +} +.hero__eyebrow { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 6px 14px; + border-radius: var(--radius-pill); + background: #fff; + border: 1px solid var(--brand-200); + color: var(--brand-700); + font-size: 13px; + font-weight: 500; +} +.hero__eyebrow svg { + width: 15px; + height: 15px; +} +.hero__title { + margin-top: var(--space-4); + font-size: clamp(1.6rem, 1.15rem + 2.05vw, 2.5rem); + letter-spacing: -0.015em; + line-height: 1.35; + max-width: 24ch; +} +.hero__title em { + font-style: normal; + color: var(--brand-600); +} +.hero__lead { + margin-top: var(--space-3); + max-width: 44ch; + color: #4b3a30; + font-size: clamp(0.98rem, 0.94rem + 0.3vw, 1.08rem); +} + +/* ------------------------------------------------------------- searchbar */ +.searchbar { + margin-top: var(--space-6); + display: flex; + align-items: center; + gap: 8px; + padding: 8px; + border: 1px solid var(--border-strong); + border-radius: var(--radius-pill); + background: #fff; + box-shadow: var(--shadow-md); + max-width: 560px; +} +.searchbar:focus-within { + border-color: var(--brand-500); + box-shadow: 0 0 0 4px rgba(196, 112, 60, 0.16); +} +.searchbar__icon { + flex: none; + margin-left: 8px; + color: var(--brand-500); +} +.searchbar__icon svg { + width: 20px; + height: 20px; +} +.searchbar input { + flex: 1 1 auto; + min-width: 0; + border: 0; + background: transparent; + padding: 8px 0; + font-size: 15px; +} +.searchbar input:focus { + outline: none; +} +.searchbar input::placeholder { + color: #8d7d73; +} +.searchbar__clear { + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + border: 0; + border-radius: 50%; + background: var(--brand-50); + color: var(--brand-700); + cursor: pointer; +} +.searchbar__clear[hidden] { + display: none; +} +.searchbar__clear svg { + width: 16px; + height: 16px; +} + +.hero__meta { + margin-top: var(--space-5); + display: flex; + flex-wrap: wrap; + gap: var(--space-3) var(--space-6); + font-size: 14px; + color: var(--muted-foreground); +} +.hero__meta span { + display: inline-flex; + align-items: center; + gap: 6px; +} +.hero__meta svg { + width: 16px; + height: 16px; + color: var(--brand-500); +} + +/* --------------------------------------------------- ฮีโร่: การ์ดลอย (จอใหญ่) */ +.hero__deco { + display: none; +} + +@media (min-width: 1080px) { + .hero__deco { + display: flex; + flex-direction: column; + gap: 12px; + position: absolute; + top: 50%; + inset-inline-end: var(--space-10); + width: 302px; + transform: translateY(-50%); + pointer-events: none; + } + .hero__deco-card { + display: flex; + align-items: center; + gap: 10px; + padding: 12px 16px; + border: 1px solid var(--border-strong); + border-radius: var(--radius-md); + background: #fff; + box-shadow: var(--shadow-md); + font-size: 14px; + font-weight: 500; + color: var(--brand-900); + transform: translateX(calc(var(--i) * 14px)) rotate(calc((var(--i) - 1) * -0.8deg)); + opacity: 0.97; + } + .hero__deco-card:nth-child(2) { + border-color: var(--brand-300); + } + .hero__deco-icon { + flex: none; + display: grid; + place-items: center; + width: 30px; + height: 30px; + border-radius: 9px; + background: var(--brand-50); + border: 1px solid var(--brand-200); + color: var(--brand-700); + } + .hero__deco-icon svg { + width: 17px; + height: 17px; + } + .hero__deco-name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } +} + +/* ---------------------------------------------------------------- chips */ +.chips { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: var(--space-8); +} +.chip { + display: inline-flex; + align-items: center; + gap: 7px; + min-height: 40px; + padding: 8px 16px; + border: 1px solid var(--border); + border-radius: var(--radius-pill); + background: #fff; + color: var(--brand-800); + font-size: 14px; + font-weight: 500; + cursor: pointer; + transition: + background 160ms var(--ease), + border-color 160ms var(--ease), + color 160ms var(--ease); +} +.chip:hover { + background: var(--brand-50); + border-color: var(--brand-300); +} +.chip[aria-pressed="true"] { + background: var(--brand-700); + border-color: var(--brand-700); + color: var(--on-brand); +} +.chip svg { + width: 16px; + height: 16px; +} + +/* ------------------------------------------------------------- section */ +.section-head { + display: flex; + align-items: flex-end; + justify-content: space-between; + gap: var(--space-4); + margin-top: var(--space-12); + margin-bottom: var(--space-5); +} +.section-head__title { + font-size: clamp(1.15rem, 1.05rem + 0.5vw, 1.4rem); +} +.section-head__sub { + margin-top: 4px; + font-size: 14px; + color: var(--muted-foreground); +} +.section-head__count { + flex: none; + font-size: 13px; + color: var(--brand-700); + background: var(--brand-100); + border-radius: var(--radius-pill); + padding: 5px 12px; + font-weight: 500; + white-space: nowrap; +} + +/* ---------------------------------------------------------------- grid */ +.project-grid { + display: grid; + gap: var(--space-4); + grid-template-columns: 1fr; +} + +.project-card { + position: relative; + display: flex; + flex-direction: column; + gap: var(--space-3); + padding: var(--space-5); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + background: var(--surface); + transition: + border-color 180ms var(--ease), + box-shadow 180ms var(--ease), + transform 180ms var(--ease); +} +.project-card:hover, +.project-card:focus-within { + border-color: var(--brand-300); + box-shadow: var(--shadow-md); + transform: translateY(-2px); +} +.project-card__top { + display: flex; + align-items: flex-start; + gap: var(--space-3); +} +.project-card__icon { + flex: none; + display: grid; + place-items: center; + width: 46px; + height: 46px; + border-radius: 13px; + background: var(--brand-50); + border: 1px solid var(--brand-200); + color: var(--brand-700); +} +.project-card__icon svg { + width: 24px; + height: 24px; +} +.project-card__heading { + min-width: 0; + flex: 1 1 auto; +} +.project-card__name { + font-size: 1.02rem; + font-weight: 700; + color: var(--brand-900); + line-height: 1.35; +} +.project-card__name a { + color: inherit; + text-decoration: none; +} +.project-card__name a::after { + /* ขยายพื้นที่คลิกให้ครอบการ์ดทั้งใบ */ + content: ""; + position: absolute; + inset: 0; + border-radius: inherit; +} +.project-card__name a:hover { + text-decoration: none; +} +.project-card__desc { + margin-top: 6px; + color: var(--muted-foreground); + font-size: 14.5px; + line-height: 1.55; + display: -webkit-box; + -webkit-line-clamp: 3; + -webkit-box-orient: vertical; + overflow: hidden; +} +.project-card__foot { + margin-top: auto; + padding-top: var(--space-3); + border-top: 1px solid var(--brand-50); + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-3); +} +.project-card__host { + font-size: 13px; + color: var(--muted-foreground); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.project-card__go { + flex: none; + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 14px; + font-weight: 500; + color: var(--brand-700); + pointer-events: none; +} +.project-card__go svg { + width: 16px; + height: 16px; + transition: transform 160ms var(--ease); +} +.project-card:hover .project-card__go svg { + transform: translateX(3px); +} +.badge { + position: absolute; + top: var(--space-4); + inset-inline-end: var(--space-4); + padding: 3px 10px; + border-radius: var(--radius-pill); + background: var(--brand-100); + color: var(--brand-800); + font-size: 12px; + font-weight: 500; +} +.project-card[draggable="true"] { + cursor: grab; +} + +/* ------------------------------------------------------------ empty state */ +.empty { + margin-top: var(--space-4); + padding: var(--space-10) var(--space-5); + border: 1px dashed var(--border-strong); + border-radius: var(--radius-lg); + background: var(--surface-2); + text-align: center; +} +.empty__icon { + display: inline-grid; + place-items: center; + width: 48px; + height: 48px; + border-radius: 14px; + background: #fff; + border: 1px solid var(--brand-200); + color: var(--brand-600); + margin-bottom: var(--space-3); +} +.empty__icon svg { + width: 24px; + height: 24px; +} +.empty__title { + font-weight: 700; + color: var(--brand-900); +} +.empty__text { + margin-top: 6px; + color: var(--muted-foreground); + font-size: 14.5px; +} + +/* -------------------------------------------------------- skeleton/loading */ +.loading { + display: grid; + gap: var(--space-4); + grid-template-columns: 1fr; + margin-top: var(--space-4); +} +.skeleton { + height: 168px; + border-radius: var(--radius-lg); + border: 1px solid var(--border); + background: linear-gradient(100deg, var(--surface-2) 30%, #fff 50%, var(--surface-2) 70%); + background-size: 220% 100%; + animation: shimmer 1.3s linear infinite; +} +@keyframes shimmer { + from { + background-position: 130% 0; + } + to { + background-position: -30% 0; + } +} + +@media (min-width: 700px) { + .project-grid, + .loading { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + .hero { + padding: var(--space-12) var(--space-10); + } +} + +@media (min-width: 1000px) { + .project-grid, + .loading { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } +} + +@media (prefers-reduced-motion: reduce) { + .skeleton { + animation: none; + } + .project-card:hover, + .project-card:focus-within { + transform: none; + } +} diff --git a/assets/css/theme.css b/assets/css/theme.css new file mode 100644 index 0000000..f466093 --- /dev/null +++ b/assets/css/theme.css @@ -0,0 +1,503 @@ +/* ========================================================================== + theme.css — โทเคนสี/ตัวอักษร/ส่วนประกอบที่ใช้ร่วมทุกหน้า + โทน: น้ำตาลโมก้า-คาราเมล + ขาว (ธีมอ้างอิงโครงจาก fastwork.com) + หมายเหตุ: สีน้ำตาลทุกตัวคุมให้ "สด-สว่าง" ไม่เป็นน้ำตาลซีเปีย/แก่ + ========================================================================== */ + +@font-face { + font-family: "K2D"; + font-style: normal; + font-weight: 400; + font-display: swap; + src: url("../../fonts/k2d-400-thai.woff2") format("woff2"); + unicode-range: U+0E01-0E5B, U+200C-200D, U+25CC; +} +@font-face { + font-family: "K2D"; + font-style: normal; + font-weight: 400; + font-display: swap; + src: url("../../fonts/k2d-400-latin-ext.woff2") format("woff2"); + unicode-range: U+0100-024F, U+1E00-1EFF; +} +@font-face { + font-family: "K2D"; + font-style: normal; + font-weight: 400; + font-display: swap; + src: url("../../fonts/k2d-400-latin.woff2") format("woff2"); + unicode-range: U+0000-00FF, U+2010-2027; +} +@font-face { + font-family: "K2D"; + font-style: normal; + font-weight: 500; + font-display: swap; + src: url("../../fonts/k2d-500-thai.woff2") format("woff2"); + unicode-range: U+0E01-0E5B, U+200C-200D, U+25CC; +} +@font-face { + font-family: "K2D"; + font-style: normal; + font-weight: 500; + font-display: swap; + src: url("../../fonts/k2d-500-latin-ext.woff2") format("woff2"); + unicode-range: U+0100-024F, U+1E00-1EFF; +} +@font-face { + font-family: "K2D"; + font-style: normal; + font-weight: 500; + font-display: swap; + src: url("../../fonts/k2d-500-latin.woff2") format("woff2"); + unicode-range: U+0000-00FF, U+2010-2027; +} +@font-face { + font-family: "K2D"; + font-style: normal; + font-weight: 700; + font-display: swap; + src: url("../../fonts/k2d-700-thai.woff2") format("woff2"); + unicode-range: U+0E01-0E5B, U+200C-200D, U+25CC; +} +@font-face { + font-family: "K2D"; + font-style: normal; + font-weight: 700; + font-display: swap; + src: url("../../fonts/k2d-700-latin-ext.woff2") format("woff2"); + unicode-range: U+0100-024F, U+1E00-1EFF; +} +@font-face { + font-family: "K2D"; + font-style: normal; + font-weight: 700; + font-display: swap; + src: url("../../fonts/k2d-700-latin.woff2") format("woff2"); + unicode-range: U+0000-00FF, U+2010-2027; +} + +:root { + /* --- คู่สีหลัก (ตรวจคอนทราสต์บน #FFFFFF แล้ว) --- */ + --brand-50: #fdf7f2; + --brand-100: #faeadf; + --brand-200: #f3d5c1; + --brand-300: #e8b695; + --brand-400: #d99368; /* 2.52:1 — ใช้เป็นกราฟิกเท่านั้น ห้ามใช้เป็นตัวอักษร */ + --brand-500: #c4703c; /* 3.66:1 — เส้น/ไอคอน/พื้นการ์ด */ + --brand-600: #a85a2c; /* 5.04:1 — ตัวอักษรบนขาวผ่าน AA */ + --brand-700: #8a4722; /* 6.99:1 — ปุ่มหลัก/ลิงก์ */ + --brand-800: #6b3620; /* 9.66:1 */ + --brand-900: #3d241a; /* 14.33:1 — หัวข้อ */ + + --background: #ffffff; + --surface: #ffffff; + --surface-2: #fbf6f1; + --foreground: #241a15; + --muted-foreground: #6f6159; /* 5.95:1 */ + --border: #eadfd6; + --border-strong: #dccaba; + --ring: #a85a2c; + --on-brand: #ffffff; + + /* --- ระยะ/มุม --- */ + --space-1: 4px; + --space-2: 8px; + --space-3: 12px; + --space-4: 16px; + --space-5: 20px; + --space-6: 24px; + --space-8: 32px; + --space-10: 40px; + --space-12: 48px; + --space-16: 64px; + --space-20: 80px; + + --radius-sm: 8px; + --radius-md: 12px; + --radius-lg: 16px; + --radius-xl: 22px; + --radius-pill: 999px; + + --wrap: 1120px; + --header-h: 64px; + + --shadow-sm: 0 1px 2px rgba(61, 36, 26, 0.06); + --shadow-md: 0 6px 18px -6px rgba(61, 36, 26, 0.18); + --shadow-lg: 0 18px 40px -18px rgba(61, 36, 26, 0.28); + + --ease: cubic-bezier(0.22, 0.61, 0.36, 1); +} + +*, +*::before, +*::after { + box-sizing: border-box; +} + +html { + -webkit-text-size-adjust: 100%; + scroll-behavior: smooth; +} + +body { + margin: 0; + min-height: 100dvh; + display: flex; + flex-direction: column; + background: var(--background); + color: var(--foreground); + font-family: "K2D", "Noto Sans Thai", "Sarabun", system-ui, -apple-system, sans-serif; + font-size: 16px; + line-height: 1.6; + -webkit-font-smoothing: antialiased; +} + +h1, +h2, +h3, +h4, +p, +figure { + margin: 0; +} + +h1, +h2, +h3, +h4 { + color: var(--brand-900); + font-weight: 700; + line-height: 1.25; + letter-spacing: -0.01em; +} + +a { + color: var(--brand-700); + text-decoration: none; +} +a:hover { + text-decoration: underline; + text-underline-offset: 3px; +} + +img, +svg { + display: block; + max-width: 100%; +} + +button, +input, +textarea, +select { + font: inherit; + color: inherit; +} + +:focus-visible { + outline: 3px solid var(--brand-600); + outline-offset: 2px; + border-radius: var(--radius-sm); +} + +.wrap { + width: 100%; + max-width: var(--wrap); + margin-inline: auto; + padding-inline: var(--space-5); +} + +.site-main { + flex: 1 0 auto; + padding-block: var(--space-10) var(--space-16); +} +.site-main:focus { + outline: none; +} + +.skip-link { + position: absolute; + left: 50%; + top: -100px; + transform: translateX(-50%); + z-index: 30; + padding: 10px 18px; + border-radius: var(--radius-pill); + background: var(--brand-700); + color: var(--on-brand); + font-weight: 500; + transition: top 160ms var(--ease); +} +.skip-link:focus { + top: 10px; + text-decoration: none; +} + +/* ---------------------------------------------------------------- header */ +.site-header { + position: sticky; + top: 0; + z-index: 20; + background: rgba(255, 255, 255, 0.92); + backdrop-filter: blur(10px); + border-bottom: 1px solid var(--border); +} + +.site-header__inner { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-4); + min-height: var(--header-h); +} + +.brand { + display: inline-flex; + align-items: center; + gap: 10px; + color: var(--brand-700); + text-decoration: none; +} +.brand:hover { + text-decoration: none; +} +.brand__mark svg { + color: var(--brand-700); +} +.brand__text { + display: flex; + flex-direction: column; + line-height: 1.15; +} +.brand__text strong { + font-size: 17px; + color: var(--brand-900); + letter-spacing: -0.01em; +} +.brand__text small { + font-size: 12px; + color: var(--muted-foreground); + letter-spacing: 0.02em; +} + +.site-nav { + display: flex; + align-items: center; + gap: var(--space-2); +} +.site-nav__link { + display: none; + padding: 8px 12px; + border-radius: var(--radius-sm); + color: var(--muted-foreground); + font-weight: 500; + font-size: 15px; +} +.site-nav__link:hover { + color: var(--brand-800); + background: var(--brand-50); + text-decoration: none; +} +.site-nav__link[aria-current="page"] { + color: var(--brand-800); + background: var(--brand-100); +} + +/* ---------------------------------------------------------------- buttons */ +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 8px; + min-height: 44px; + padding: 10px 20px; + border: 1px solid transparent; + border-radius: var(--radius-pill); + background: transparent; + color: var(--foreground); + font-weight: 500; + font-size: 15px; + line-height: 1.2; + cursor: pointer; + transition: + background 160ms var(--ease), + border-color 160ms var(--ease), + color 160ms var(--ease), + transform 160ms var(--ease), + box-shadow 160ms var(--ease); +} +.btn:hover { + text-decoration: none; +} +.btn:active { + transform: translateY(1px); +} +.btn[disabled] { + opacity: 0.55; + cursor: not-allowed; + transform: none; +} +.btn--primary { + background: var(--brand-700); + color: var(--on-brand); + box-shadow: var(--shadow-sm); +} +.btn--primary:hover { + background: var(--brand-800); + box-shadow: var(--shadow-md); +} +.btn--ghost { + background: #fff; + border-color: var(--border-strong); + color: var(--brand-800); +} +.btn--ghost:hover { + background: var(--brand-50); + border-color: var(--brand-300); +} +.btn--quiet { + background: var(--brand-50); + color: var(--brand-800); +} +.btn--quiet:hover { + background: var(--brand-100); +} +.btn--danger { + background: #fff; + border-color: #e7c4bb; + color: #8f2c19; +} +.btn--danger:hover { + background: #fdf1ee; + border-color: #d0a094; +} +.btn--sm { + min-height: 40px; + padding: 8px 14px; + font-size: 14px; +} +.btn--icon { + width: 40px; + min-height: 40px; + padding: 0; + border-radius: var(--radius-md); +} +.btn svg { + width: 18px; + height: 18px; + flex: none; +} + +/* ---------------------------------------------------------------- footer */ +.site-footer { + border-top: 1px solid var(--border); + background: var(--surface-2); + padding-block: var(--space-10); + font-size: 14px; +} +.site-footer__inner { + display: grid; + gap: var(--space-6); +} +.site-footer__brand { + font-weight: 700; + color: var(--brand-900); + font-size: 15px; +} +.site-footer__title { + font-weight: 500; + color: var(--brand-800); + margin-bottom: 2px; +} +.site-footer__note { + color: var(--muted-foreground); + max-width: 34ch; +} + +/* ---------------------------------------------------------------- toast */ +.toast-stack { + position: fixed; + inset-inline: 0; + bottom: 20px; + z-index: 40; + display: flex; + flex-direction: column; + align-items: center; + gap: 8px; + padding-inline: var(--space-4); + pointer-events: none; +} +.toast { + max-width: 92vw; + padding: 12px 18px; + border-radius: var(--radius-pill); + background: var(--brand-900); + color: #fff; + font-size: 14px; + box-shadow: var(--shadow-lg); + animation: toast-in 200ms var(--ease); +} +.toast--error { + background: #7d2617; +} +@keyframes toast-in { + from { + opacity: 0; + transform: translateY(8px); + } + to { + opacity: 1; + transform: none; + } +} + +.noscript { + padding-block: var(--space-10); + color: var(--brand-800); +} + +/* ---------------------------------------------------------------- helpers */ +.visually-hidden { + position: absolute !important; + width: 1px; + height: 1px; + margin: -1px; + padding: 0; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; + border: 0; +} + +@media (min-width: 640px) { + .site-footer__inner { + grid-template-columns: 1.4fr 1fr 1fr; + gap: var(--space-8); + } +} + +@media (min-width: 900px) { + :root { + --header-h: 72px; + } + .site-nav__link { + display: inline-flex; + } + .site-main { + padding-block: var(--space-12) var(--space-20); + } +} + +@media (prefers-reduced-motion: reduce) { + html { + scroll-behavior: auto; + } + *, + *::before, + *::after { + animation-duration: 0.001ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.001ms !important; + } +} diff --git a/data/projects.json b/data/projects.json new file mode 100644 index 0000000..76ddc9b --- /dev/null +++ b/data/projects.json @@ -0,0 +1,93 @@ +{ + "schema_version": 1, + "updated_at": "2026-11-19T00:00:00+07:00", + "owner_name": "", + "site": { + "site_title": "โปรเจคอดิเรกของเรา", + "welcome_message": "สวัสดี คนที่เข้ามาดูโปรเจคอดิเรกของเรา เลือกโปรเจคที่อยากดู ขอบคุณครับ", + "contact_email": "", + "ssl_note": "ทุกเว็บใช้ SSL ฟรี ต่ออายุอัตโนมัติ" + }, + "projects": [ + { + "project_id": "hobbypj-home", + "project_name": "หน้ารายชื่อโปรเจค", + "project_description": "รวมทุกโปรเจคอดิเรกไว้ที่เดียว เลือกดูได้ตามใจ", + "project_url": "https://www.hobbypj.com", + "contact_email": "", + "icon": "folder" + }, + { + "project_id": "dashboard", + "project_name": "ใช้ทำงานประจำ", + "project_description": "เครื่องมือที่ใช้ทำงานทุกวัน รวมไว้ในหน้าเดียว", + "project_url": "https://dashboard.hobbypj.com", + "contact_email": "", + "icon": "dashboard" + }, + { + "project_id": "alterflixhub", + "project_name": "รวบรวมโรงหนัง", + "project_description": "รวมโรงหนังและรอบฉายไว้ดูเล่น สำหรับคนชอบดูหนัง", + "project_url": "https://alterflixhub.hobbypj.com", + "contact_email": "alterflixhub@hobbypj.com", + "icon": "film" + }, + { + "project_id": "atroute", + "project_name": "รวบรวมรถประจำทาง", + "project_description": "รวมสายรถประจำทาง ตารางเวลา และจุดจอดที่ใช้จริง", + "project_url": "https://atroute.hobbypj.com", + "contact_email": "atroute@hobbypj.com", + "icon": "bus" + }, + { + "project_id": "irrcal", + "project_name": "ออกแบบสปริงเกลอร์", + "project_description": "คำนวณและออกแบบระบบสปริงเกลอร์สำหรับแปลงเกษตร", + "project_url": "https://irrcal.hobbypj.com", + "contact_email": "irrcal@hobbypj.com", + "icon": "droplet" + }, + { + "project_id": "kth", + "project_name": "ขายเคสคอมปรับแต่ง", + "project_description": "รวมเคสคอมพิวเตอร์พร้อมข้อมูลสเปกสำหรับคนชอบประกอบเอง", + "project_url": "https://kth.hobbypj.com", + "contact_email": "kth@hobbypj.com", + "icon": "cpu" + }, + { + "project_id": "at2pch", + "project_name": "ตัวอย่างรถประจำทางอุดมคติ", + "project_description": "ตัวอย่างข้อมูลรถประจำทางในแบบที่อยากให้มีจริง", + "project_url": "https://at2pch.hobbypj.com", + "contact_email": "", + "icon": "bus" + }, + { + "project_id": "flixdisc", + "project_name": "ขายแผ่น Bluray และรายชื่อหนังมาดูซ้ำ", + "project_description": "รายชื่อหนังที่อยากดูซ้ำ พร้อมแผ่น Bluray ที่ปล่อยต่อ", + "project_url": "https://flixdisc.hobbypj.com", + "contact_email": "flixdisc@hobbypj.com", + "icon": "disc" + }, + { + "project_id": "mylib", + "project_name": "รายชื่อหนังสือส่วนตัว", + "project_description": "ชั้นหนังสือของผม เรียงตามที่อ่านจริงและอยากแนะนำ", + "project_url": "https://mylib.hobbypj.com", + "contact_email": "", + "icon": "book" + }, + { + "project_id": "mytool", + "project_name": "รายชื่อเครื่องมือช่างส่วนตัว", + "project_description": "เครื่องมือช่างที่มีอยู่จริง พร้อมบันทึกการใช้งาน", + "project_url": "https://mytool.hobbypj.com", + "contact_email": "", + "icon": "wrench" + } + ] +} diff --git a/fonts/k2d-400-latin-ext.woff2 b/fonts/k2d-400-latin-ext.woff2 new file mode 100644 index 0000000..50c1784 Binary files /dev/null and b/fonts/k2d-400-latin-ext.woff2 differ diff --git a/fonts/k2d-400-latin.woff2 b/fonts/k2d-400-latin.woff2 new file mode 100644 index 0000000..68f4e9e Binary files /dev/null and b/fonts/k2d-400-latin.woff2 differ diff --git a/fonts/k2d-400-thai.woff2 b/fonts/k2d-400-thai.woff2 new file mode 100644 index 0000000..61fe798 Binary files /dev/null and b/fonts/k2d-400-thai.woff2 differ diff --git a/fonts/k2d-500-latin-ext.woff2 b/fonts/k2d-500-latin-ext.woff2 new file mode 100644 index 0000000..dbfca96 Binary files /dev/null and b/fonts/k2d-500-latin-ext.woff2 differ diff --git a/fonts/k2d-500-latin.woff2 b/fonts/k2d-500-latin.woff2 new file mode 100644 index 0000000..5b26f6a Binary files /dev/null and b/fonts/k2d-500-latin.woff2 differ diff --git a/fonts/k2d-500-thai.woff2 b/fonts/k2d-500-thai.woff2 new file mode 100644 index 0000000..363ffb5 Binary files /dev/null and b/fonts/k2d-500-thai.woff2 differ diff --git a/fonts/k2d-700-latin-ext.woff2 b/fonts/k2d-700-latin-ext.woff2 new file mode 100644 index 0000000..b0da5f8 Binary files /dev/null and b/fonts/k2d-700-latin-ext.woff2 differ diff --git a/fonts/k2d-700-latin.woff2 b/fonts/k2d-700-latin.woff2 new file mode 100644 index 0000000..b44ff05 Binary files /dev/null and b/fonts/k2d-700-latin.woff2 differ diff --git a/fonts/k2d-700-thai.woff2 b/fonts/k2d-700-thai.woff2 new file mode 100644 index 0000000..b6d29c9 Binary files /dev/null and b/fonts/k2d-700-thai.woff2 differ diff --git a/icons/favicon-64.png b/icons/favicon-64.png new file mode 100644 index 0000000..dc5f812 Binary files /dev/null and b/icons/favicon-64.png differ diff --git a/icons/icon-180.png b/icons/icon-180.png new file mode 100644 index 0000000..c7dd0af Binary files /dev/null and b/icons/icon-180.png differ diff --git a/icons/icon-192.png b/icons/icon-192.png new file mode 100644 index 0000000..d7e4d55 Binary files /dev/null and b/icons/icon-192.png differ diff --git a/icons/icon-512-maskable.png b/icons/icon-512-maskable.png new file mode 100644 index 0000000..32aace3 Binary files /dev/null and b/icons/icon-512-maskable.png differ diff --git a/icons/icon-512.png b/icons/icon-512.png new file mode 100644 index 0000000..f3e4ae5 Binary files /dev/null and b/icons/icon-512.png differ diff --git a/index.html b/index.html new file mode 100644 index 0000000..7675bd5 --- /dev/null +++ b/index.html @@ -0,0 +1,81 @@ + + + + + + โปรเจคอดิเรกของเรา + + + + + + + + + + + + + + + + + + + +
+ + + +
+ + + + diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..dceadfb --- /dev/null +++ b/manifest.json @@ -0,0 +1,36 @@ +{ + "id": "/", + "name": "โปรเจคอดิเรกของเรา", + "short_name": "โปรเจคอดิเรก", + "description": "รายชื่อโปรเจคอดิเรกของเรา เลือกโปรเจคที่อยากดูได้เลย", + "lang": "th", + "dir": "ltr", + "start_url": "./", + "scope": "./", + "display": "standalone", + "display_override": ["standalone", "minimal-ui"], + "orientation": "any", + "theme_color": "#8A4722", + "background_color": "#FFFFFF", + "categories": ["productivity", "entertainment"], + "icons": [ + { + "src": "icons/icon-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "any" + }, + { + "src": "icons/icon-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "any" + }, + { + "src": "icons/icon-512-maskable.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..a08320e --- /dev/null +++ b/package.json @@ -0,0 +1,11 @@ +{ + "name": "hobbypj-contents", + "version": "1.0.0", + "private": true, + "type": "module", + "description": "หน้ารายชื่อโปรเจคอดิเรก (PWA + SPA) พร้อมหลังบ้านแก้ไขรายการ", + "scripts": { + "start": "node server/publish.mjs", + "check": "node --check ui/app.js && node --check ui/data.js && node --check ui/router.js && node --check ui/ui.js && node --check ui/pwa.js && node --check ui/views/home.js && node --check ui/views/admin.js && node --check sw.js && node --check server/publish.mjs" + } +} diff --git a/server/publish.mjs b/server/publish.mjs new file mode 100644 index 0000000..8f7d527 --- /dev/null +++ b/server/publish.mjs @@ -0,0 +1,304 @@ +#!/usr/bin/env node +/** + * server/publish.mjs — เซิร์ฟเวอร์หลังบ้าน (ไม่มี dependency ภายนอก) + * + * GET /api/projects อ่านข้อมูลปัจจุบัน + * PUT /api/projects เขียน data/projects.json แล้ว commit + push ขึ้น Gitea + * static เสิร์ฟไฟล์หน้าเว็บจาก root ของโปรเจค + * + * ใช้งาน: + * node server/publish.mjs # http://localhost:8090 + * PORT=8090 ADMIN_TOKEN=xxxx node server/publish.mjs + * PUBLISH_PUSH=0 node server/publish.mjs # เขียนไฟล์ + commit แต่ไม่ push + * + * ความปลอดภัย: + * - ถ้าตั้ง ADMIN_TOKEN ไว้ ต้องส่ง header x-admin-token ให้ตรงทุกครั้งที่เขียน + * - ถ้าไม่ได้ตั้ง อนุญาตเฉพาะ request ที่มาจากเครื่องเดียวกัน (loopback) + */ + +import { createServer } from "node:http"; +import { readFile, stat, writeFile, mkdir } from "node:fs/promises"; +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { timingSafeEqual } from "node:crypto"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const execFileAsync = promisify(execFile); +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const ROOT = path.resolve(HERE, ".."); +const DATA_FILE = path.join(ROOT, "data", "projects.json"); +const PORT = Number(process.env.PORT || 8090); +const HOST = process.env.HOST || "0.0.0.0"; +const ADMIN_TOKEN = (process.env.ADMIN_TOKEN || "").trim(); +const SHOULD_PUSH = process.env.PUBLISH_PUSH !== "0"; + +const MIME = { + ".html": "text/html; charset=utf-8", + ".css": "text/css; charset=utf-8", + ".js": "text/javascript; charset=utf-8", + ".mjs": "text/javascript; charset=utf-8", + ".json": "application/json; charset=utf-8", + ".webmanifest": "application/manifest+json; charset=utf-8", + ".png": "image/png", + ".jpg": "image/jpeg", + ".svg": "image/svg+xml", + ".ico": "image/x-icon", + ".woff2": "font/woff2", + ".txt": "text/plain; charset=utf-8", +}; + +const NO_CACHE = { + "cache-control": "no-cache, no-store, must-revalidate", + "access-control-allow-origin": "*", +}; + +function sendJson(res, status, body) { + const payload = JSON.stringify(body, null, 2); + res.writeHead(status, { + "content-type": "application/json; charset=utf-8", + "content-length": Buffer.byteLength(payload), + ...NO_CACHE, + }); + res.end(payload); +} + +function isLoopback(req) { + const address = req.socket.remoteAddress || ""; + return address === "127.0.0.1" || address === "::1" || address === "::ffff:127.0.0.1"; +} + +function tokenMatches(provided) { + if (!ADMIN_TOKEN) return false; + const a = Buffer.from(String(provided || ""), "utf8"); + const b = Buffer.from(ADMIN_TOKEN, "utf8"); + if (a.length !== b.length) return false; + return timingSafeEqual(a, b); +} + +function canWrite(req) { + if (!ADMIN_TOKEN) return isLoopback(req); + return tokenMatches(req.headers["x-admin-token"]); +} + +function validate(payload) { + const errors = []; + if (!payload || typeof payload !== "object") return ["ข้อมูลที่ส่งมาไม่ใช่ JSON object"]; + const site = payload.site; + if (!site || typeof site !== "object") errors.push("ขาดข้อมูล site"); + else { + if (typeof site.welcome_message !== "string" || !site.welcome_message.trim()) + errors.push("ข้อความต้อนรับว่าง"); + if (site.contact_email && !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(site.contact_email).trim())) + errors.push("อีเมลติดต่อของเว็บไม่ถูกต้อง"); + } + if (!Array.isArray(payload.projects)) { + errors.push("projects ต้องเป็น array"); + return errors; + } + payload.projects.forEach((project, index) => { + const label = `รายการที่ ${index + 1}`; + if (!project || typeof project !== "object") { + errors.push(`${label}: ไม่ใช่ object`); + return; + } + if (!String(project.project_name || "").trim()) errors.push(`${label}: ไม่มีชื่อโปรเจค`); + const url = String(project.project_url || "").trim(); + if (!/^https?:\/\/[^\s/?#]+\.[^\s/?#]+/i.test(url)) + errors.push(`${label}: ลิงก์ไม่ถูกต้อง (${url || "ว่าง"})`); + if (project.contact_email && !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(project.contact_email).trim())) + errors.push(`${label}: อีเมลไม่ถูกต้อง`); + }); + return errors; +} + +/** เขียน payload ให้คีย์เรียงคงที่ อ่านง่ายแบบมนุษย์ + ลงท้ายด้วย newline */ +function serialize(payload) { + const ordered = { + schema_version: 1, + updated_at: payload.updated_at, + owner_name: payload.owner_name || "", + site: { + site_title: payload.site.site_title || "", + welcome_message: payload.site.welcome_message || "", + contact_email: payload.site.contact_email || "", + ssl_note: payload.site.ssl_note || "", + }, + projects: payload.projects.map((project) => ({ + project_id: String(project.project_id || "").trim(), + project_name: String(project.project_name || "").trim(), + project_description: String(project.project_description || "").trim(), + project_url: String(project.project_url || "").trim().replace(/\/$/, ""), + contact_email: String(project.contact_email || "").trim(), + icon: String(project.icon || "folder").trim(), + })), + }; + return `${JSON.stringify(ordered, null, 2)}\n`; +} + +async function gitPublish() { + const rel = path.relative(ROOT, DATA_FILE); + const result = { committed: false, pushed: false, commit: null, message: "" }; + try { + await execFileAsync("git", ["-C", ROOT, "add", rel]); + const changed = await execFileAsync("git", ["-C", ROOT, "status", "--porcelain", "--", rel]); + if (!changed.stdout.trim()) { + result.message = "ไฟล์ไม่เปลี่ยน ไม่มี commit ใหม่"; + return result; + } + const commit = await execFileAsync("git", [ + "-C", + ROOT, + "-c", + "user.name=" + (process.env.GIT_AUTHOR_NAME || "hobbypj-backoffice"), + "-c", + "user.email=" + (process.env.GIT_AUTHOR_EMAIL || "backoffice@hobbypj.com"), + "commit", + "-m", + "content: update project list from backoffice", + ]); + result.committed = true; + result.commit = (commit.stdout.match(/\[[^\]]+ ([0-9a-f]{7,})\]/) || [])[1] || null; + if (!SHOULD_PUSH) { + result.message = "commit แล้ว (ข้าม push ตาม PUBLISH_PUSH=0)"; + return result; + } + await execFileAsync("git", ["-C", ROOT, "-c", "http.version=HTTP/1.1", "push", "origin", "HEAD"]); + result.pushed = true; + result.message = "commit + push เรียบร้อย"; + return result; + } catch (error) { + const detail = (error.stderr || error.stdout || error.message || "").toString().trim(); + result.message = `git ผิดพลาด: ${detail.split("\n").slice(0, 3).join(" | ")}`; + return result; + } +} + +async function readData() { + const raw = await readFile(DATA_FILE, "utf8"); + return JSON.parse(raw); +} + +async function handleApi(req, res, pathname) { + if (pathname === "/api/projects" && req.method === "GET") { + try { + const data = await readData(); + sendJson(res, 200, { ok: true, writable: canWrite(req) || isLoopback(req), data }); + } catch (error) { + sendJson(res, 500, { ok: false, error: `อ่านไฟล์ข้อมูลไม่ได้: ${error.message}` }); + } + return; + } + + if (pathname === "/api/projects" && req.method === "PUT") { + if (!canWrite(req)) { + sendJson(res, 403, { + ok: false, + error: ADMIN_TOKEN ? "รหัสเผยแพร่ไม่ถูกต้อง" : "อนุญาตเฉพาะเครื่องที่รันเซิร์ฟเวอร์", + }); + return; + } + let body = ""; + for await (const chunk of req) { + body += chunk; + if (body.length > 1_000_000) { + sendJson(res, 413, { ok: false, error: "ข้อมูลใหญ่เกินไป" }); + return; + } + } + let payload; + try { + payload = JSON.parse(body); + } catch { + sendJson(res, 400, { ok: false, error: "JSON ไม่ถูกต้อง" }); + return; + } + const errors = validate(payload); + if (errors.length) { + sendJson(res, 422, { ok: false, error: errors.join(" · "), errors }); + return; + } + try { + payload.updated_at = new Date().toISOString(); + await mkdir(path.dirname(DATA_FILE), { recursive: true }); + await writeFile(DATA_FILE, serialize(payload), "utf8"); + } catch (error) { + sendJson(res, 500, { ok: false, error: `เขียนไฟล์ไม่ได้: ${error.message}` }); + return; + } + const git = await gitPublish(); + sendJson(res, 200, { + ok: true, + updated_at: payload.updated_at, + projects: payload.projects.length, + git, + }); + return; + } + + if (pathname.startsWith("/api/")) { + sendJson(res, 404, { ok: false, error: "ไม่พบ API นี้" }); + return; + } + + serveStatic(req, res, pathname); +} + +async function serveStatic(req, res, pathname) { + let rel = decodeURIComponent(pathname); + if (rel.endsWith("/")) rel += "index.html"; + const filePath = path.resolve(ROOT, `.${rel}`); + if (!filePath.startsWith(ROOT) || filePath.includes(`${path.sep}.git${path.sep}`)) { + res.writeHead(403).end("Forbidden"); + return; + } + try { + const info = await stat(filePath); + if (info.isDirectory()) { + res.writeHead(301, { location: `${pathname}/` }).end(); + return; + } + const ext = path.extname(filePath).toLowerCase(); + const headers = { "content-type": MIME[ext] || "application/octet-stream" }; + if ([".html", ".css", ".js", ".mjs", ".json"].includes(ext) || ext === "") { + Object.assign(headers, NO_CACHE); + } else { + headers["cache-control"] = "public, max-age=86400"; + } + headers["service-worker-allowed"] = "/"; + res.writeHead(200, headers); + res.end(await readFile(filePath)); + } catch { + res.writeHead(404, { "content-type": "text/html; charset=utf-8" }); + res.end( + `ไม่พบหน้านี้ +
+

ไม่พบหน้านี้

กลับไปหน้ารายชื่อโปรเจค

+
`, + ); + } +} + +const server = createServer((req, res) => { + const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`); + if (req.method === "OPTIONS") { + res.writeHead(204, { + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, PUT, OPTIONS", + "access-control-allow-headers": "content-type, x-admin-token", + "access-control-max-age": "600", + }); + res.end(); + return; + } + handleApi(req, res, url.pathname).catch((error) => { + sendJson(res, 500, { ok: false, error: error.message }); + }); +}); + +server.listen(PORT, HOST, () => { + const writable = ADMIN_TOKEN ? "เฉพาะผู้มีรหัสเผยแพร่" : "เฉพาะเครื่องนี้ (ยังไม่ตั้ง ADMIN_TOKEN)"; + console.log(`[hobbypj] เซิร์ฟเวอร์ทำงานที่ http://localhost:${PORT}`); + console.log(`[hobbypj] เขียนข้อมูลได้: ${writable}`); + console.log(`[hobbypj] ไฟล์ข้อมูล: ${path.relative(ROOT, DATA_FILE)} · push: ${SHOULD_PUSH ? "เปิด" : "ปิด"}`); +}); diff --git a/sw.js b/sw.js new file mode 100644 index 0000000..f40446b --- /dev/null +++ b/sw.js @@ -0,0 +1,110 @@ +/* sw.js — service worker: ออฟไลน์ได้ + อัปเดตอัตโนมัติ + กติกา: bump VERSION เฉพาะเมื่อแก้ไฟล์นี้หรือรายการ PRECACHE + เนื้อหา (HTML/CSS/JS/JSON) ใช้ network-first จึงไม่ต้อง bump */ + +const VERSION = "2026.11.19.1"; +const CACHE = `hobbypj-${VERSION}`; + +const PRECACHE = [ + "./", + "./index.html", + "./manifest.json", + "./assets/css/theme.css", + "./assets/css/home.css", + "./assets/css/admin.css", + "./ui/app.js", + "./ui/router.js", + "./ui/ui.js", + "./ui/data.js", + "./ui/pwa.js", + "./ui/views/home.js", + "./ui/views/admin.js", + "./data/projects.json", + "./icons/icon-192.png", + "./icons/icon-512.png", + "./fonts/k2d-400-thai.woff2", + "./fonts/k2d-700-thai.woff2", +]; + +self.addEventListener("install", (event) => { + self.skipWaiting(); + event.waitUntil(precacheAll(PRECACHE)); +}); + +async function precacheAll(urls) { + const cache = await caches.open(CACHE); + await Promise.all( + urls.map(async (url) => { + try { + // fetch แบบ no-store เพื่อไม่ให้ HTTP cache ของเบราว์เซอร์ใส่ของเก่าลง precache + const res = await fetch(url, { cache: "no-store" }); + if (res.ok) await cache.put(url, res.clone()); + } catch { + /* ไฟล์ใดไฟล์หนึ่งพลาดต้องไม่ทำให้ install ทั้งหมดล้ม */ + } + }), + ); +} + +self.addEventListener("activate", (event) => { + event.waitUntil( + caches + .keys() + .then((keys) => Promise.all(keys.filter((key) => key !== CACHE).map((key) => caches.delete(key)))) + .then(() => self.clients.claim()), + ); +}); + +self.addEventListener("fetch", (event) => { + const { request } = event; + if (request.method !== "GET") return; + + const url = new URL(request.url); + if (url.origin !== self.location.origin) return; + + // อย่าแตะ API: คำขอเผยแพร่/อ่านข้อมูลสดต้องถึงเซิร์ฟเวอร์เสมอ + if (url.pathname.includes("/api/")) return; + + const isContent = + request.destination === "document" || + url.pathname.endsWith(".html") || + url.pathname.endsWith(".css") || + url.pathname.endsWith(".js") || + url.pathname.endsWith(".json") || + url.pathname === "/" || + url.pathname.endsWith("/"); + + if (isContent) { + event.respondWith(networkFirst(request)); + return; + } + + event.respondWith(cacheFirst(request)); +}); + +async function networkFirst(request) { + const cache = await caches.open(CACHE); + try { + const res = await fetch(request, { cache: "no-store" }); + if (res.ok) cache.put(request, res.clone()); + return res; + } catch { + const hit = (await cache.match(request)) || (await caches.match(request, { ignoreSearch: true })); + if (hit) return hit; + if (request.destination === "document") return (await cache.match("./index.html")) || Response.error(); + return Response.error(); + } +} + +async function cacheFirst(request) { + const hit = await caches.match(request); + if (hit) return hit; + const cache = await caches.open(CACHE); + try { + const res = await fetch(request, { cache: "no-store" }); + if (res.ok) cache.put(request, res.clone()); + return res; + } catch { + return Response.error(); + } +} diff --git a/ui/app.js b/ui/app.js new file mode 100644 index 0000000..a7c399e --- /dev/null +++ b/ui/app.js @@ -0,0 +1,103 @@ +/* app.js — จุดเริ่มของแอป: โหลดข้อมูล → ผูก router → เรนเดอร์หน้า */ + +import { hydrateIcons, toast } from "./ui.js"; +import { loadProjects, normalizeData } from "./data.js"; +import { defineRoutes, markActiveNav, onRouteChange, startRouter } from "./router.js"; +import { homeView } from "./views/home.js"; +import { adminView } from "./views/admin.js"; +import "./pwa.js"; + +const main = document.getElementById("main"); + +const state = { + data: normalizeData({}), + source: "empty", +}; + +const ctx = { + get data() { + return state.data; + }, + get source() { + return state.source; + }, + setData(data) { + state.data = normalizeData(data); + state.source = "server"; + updateChrome(); + }, + async reload() { + const result = await loadProjects(); + state.data = result.data; + state.source = result.source; + updateChrome(); + return result; + }, +}; + +let activeView = null; + +const TITLES = { + "/": "โปรเจคอดิเรกของเรา", + "/admin": "จัดการข้อมูล · โปรเจคอดิเรก", +}; + +function renderRoute({ path, view }) { + if (activeView && typeof activeView.destroy === "function") activeView.destroy(); + main.replaceChildren(); + activeView = view(ctx); + activeView.mount(main); + markActiveNav(path); + document.title = TITLES[path] || TITLES["/"]; + window.scrollTo({ top: 0, behavior: "auto" }); + main.focus({ preventScroll: true }); +} + +function updateChrome() { + const site = state.data.site || {}; + const contact = main?.closest("body")?.querySelector("[data-contact-link]"); + if (contact) { + if (site.contact_email) { + contact.href = `mailto:${site.contact_email}`; + contact.textContent = site.contact_email; + } else { + contact.href = "#/admin"; + contact.textContent = "เพิ่มอีเมลติดต่อได้ในหน้าจัดการ"; + } + } + document.querySelectorAll("[data-ssl-note]").forEach((node) => { + if (site.ssl_note) node.textContent = site.ssl_note; + }); +} + +function skeleton() { + main.innerHTML = ` +
+
+ +

กำลังโหลดรายชื่อโปรเจค

+
`; +} + +async function boot() { + hydrateIcons(); + skeleton(); + const result = await loadProjects(); + state.data = result.data; + state.source = result.source; + updateChrome(); + + defineRoutes({ "/": homeView, "/admin": adminView }, "/"); + onRouteChange(renderRoute); + startRouter(); + + if (result.source === "cache") { + toast("เปิดแบบออฟไลน์ — แสดงข้อมูลที่บันทึกไว้ในเครื่อง"); + } else if (result.source === "empty") { + toast("อ่านข้อมูลโปรเจคไม่ได้ — เข้าไปเพิ่มรายการได้ที่หน้า “จัดการข้อมูล”", "error"); + } +} + +boot(); diff --git a/ui/data.js b/ui/data.js new file mode 100644 index 0000000..adff58f --- /dev/null +++ b/ui/data.js @@ -0,0 +1,209 @@ +/* data.js — ชั้นข้อมูล: อ่าน data/projects.json, ฉบับร่าง, เผยแพร่ผ่าน API ของเซิร์ฟเวอร์ */ + +export const DATA_URL = "data/projects.json"; +export const API_URL = "api/projects"; +const CACHE_KEY = "hobbypj.projects.cache.v1"; +const DRAFT_KEY = "hobbypj.projects.draft.v1"; +const TOKEN_KEY = "hobbypj.publish.token.v1"; + +export const DEFAULT_SITE = { + site_title: "โปรเจคอดิเรกของเรา", + welcome_message: + "สวัสดี คนที่เข้ามาดูโปรเจคอดิเรกของเรา เลือกโปรเจคที่อยากดู ขอบคุณครับ", + contact_email: "", + ssl_note: "ทุกเว็บใช้ SSL ฟรี ต่ออายุอัตโนมัติ", +}; + +const DEFAULT_PROJECT = { + project_id: "", + project_name: "", + project_description: "", + project_url: "", + contact_email: "", + icon: "folder", +}; + +/** ทำข้อมูลให้อยู่ในรูปมาตรฐานเสมอ (คีย์ครบ อ่านง่าย) */ +export function normalizeData(raw) { + const source = raw && typeof raw === "object" ? raw : {}; + const site = { ...DEFAULT_SITE, ...(source.site && typeof source.site === "object" ? source.site : {}) }; + const list = Array.isArray(source.projects) ? source.projects : []; + const seen = new Set(); + const projects = list.map((item, index) => { + const row = { ...DEFAULT_PROJECT, ...(item && typeof item === "object" ? item : {}) }; + const out = { + project_id: String(row.project_id || "").trim() || `project-${index + 1}`, + project_name: String(row.project_name || "").trim(), + project_description: String(row.project_description || "").trim(), + project_url: String(row.project_url || "").trim(), + contact_email: String(row.contact_email || "").trim(), + icon: String(row.icon || "folder").trim() || "folder", + }; + if (seen.has(out.project_id)) out.project_id = `${out.project_id}-${index + 1}`; + seen.add(out.project_id); + return out; + }); + return { + schema_version: Number(source.schema_version) || 1, + updated_at: source.updated_at || "", + owner_name: String(source.owner_name || ""), + site, + projects, + }; +} + +/** shape ที่ส่งขึ้นเซิร์ฟเวอร์ — คีย์เรียงคงที่และอ่านง่ายแบบมนุษย์ */ +export function toPublishPayload(data) { + return { + schema_version: 1, + updated_at: new Date().toISOString(), + owner_name: data.owner_name || "", + site: { + site_title: data.site.site_title, + welcome_message: data.site.welcome_message, + contact_email: data.site.contact_email, + ssl_note: data.site.ssl_note, + }, + projects: data.projects.map((p) => ({ + project_id: p.project_id, + project_name: p.project_name, + project_description: p.project_description, + project_url: p.project_url, + contact_email: p.contact_email, + icon: p.icon, + })), + }; +} + +export function createProject(index = 0) { + return { ...DEFAULT_PROJECT, project_id: `project-${Date.now()}-${index}` }; +} + +/* ---------------------------------------------------------------- loading */ +export async function loadProjects() { + try { + const res = await fetch(DATA_URL, { cache: "no-store" }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + const json = await res.json(); + const data = normalizeData(json); + try { + localStorage.setItem(CACHE_KEY, JSON.stringify(data)); + } catch { + /* โควต้าเต็ม — ไม่เป็นไร ใช้ข้อมูลออนไลน์ได้ */ + } + return { data, source: "server" }; + } catch (error) { + const cached = readCache(); + if (cached) return { data: cached, source: "cache", error }; + return { data: normalizeData({}), source: "empty", error }; + } +} + +function readCache() { + try { + const raw = localStorage.getItem(CACHE_KEY); + if (!raw) return null; + return normalizeData(JSON.parse(raw)); + } catch { + return null; + } +} + +/* ------------------------------------------------------------------ draft */ +export function readDraft() { + try { + const raw = localStorage.getItem(DRAFT_KEY); + if (!raw) return null; + return normalizeData(JSON.parse(raw)); + } catch { + return null; + } +} + +export function writeDraft(data) { + try { + localStorage.setItem(DRAFT_KEY, JSON.stringify(data)); + } catch { + /* เก็บไม่ได้ก็ไม่ทำให้หน้าเจ๊ง */ + } +} + +export function clearDraft() { + try { + localStorage.removeItem(DRAFT_KEY); + } catch { + /* ignore */ + } +} + +/* ------------------------------------------------------------------ token */ +export function readToken() { + try { + return localStorage.getItem(TOKEN_KEY) || ""; + } catch { + return ""; + } +} + +export function writeToken(token) { + try { + if (token) localStorage.setItem(TOKEN_KEY, token); + else localStorage.removeItem(TOKEN_KEY); + } catch { + /* ignore */ + } +} + +/* ---------------------------------------------------------------- publish */ +export async function publishProjects(data) { + const res = await fetch(API_URL, { + method: "PUT", + headers: { + "content-type": "application/json", + "x-admin-token": readToken(), + }, + cache: "no-store", + body: JSON.stringify(toPublishPayload(data)), + }); + const text = await res.text(); + let body = null; + try { + body = text ? JSON.parse(text) : null; + } catch { + body = null; + } + if (!res.ok) { + const message = body?.error || `HTTP ${res.status}`; + const error = new Error(message); + error.status = res.status; + throw error; + } + return body || { ok: true }; +} + +/** มี API ของเซิร์ฟเวอร์ให้เผยแพร่หรือไม่ (ใช้แสดงสถานะในหน้าจัดการ) */ +export async function probePublishApi() { + try { + const res = await fetch(API_URL, { method: "GET", cache: "no-store" }); + if (!res.ok) return { available: false, status: res.status, message: `HTTP ${res.status}` }; + const body = await res.json(); + return { available: true, writable: Boolean(body?.writable) }; + } catch (error) { + return { available: false, status: 0, message: "เชื่อมต่อเซิร์ฟเวอร์ไม่ได้" }; + } +} + +export function downloadJson(data) { + const payload = toPublishPayload(data); + const blob = new Blob([`${JSON.stringify(payload, null, 2)}\n`], { + type: "application/json;charset=utf-8", + }); + const url = URL.createObjectURL(blob); + const link = document.createElement("a"); + link.href = url; + link.download = "projects.json"; + document.body.appendChild(link); + link.click(); + link.remove(); + setTimeout(() => URL.revokeObjectURL(url), 2000); +} diff --git a/ui/pwa.js b/ui/pwa.js new file mode 100644 index 0000000..c96b681 --- /dev/null +++ b/ui/pwa.js @@ -0,0 +1,39 @@ +/* pwa.js — ลงทะเบียน service worker + เช็คอัปเดตอัตโนมัติ (ผู้ใช้ไม่ต้องล้างแคช) */ + +const SW_URL = "sw.js"; +let reloading = false; + +export async function registerServiceWorker() { + if (!("serviceWorker" in navigator)) return null; + if (location.protocol !== "https:" && location.hostname !== "localhost" && location.hostname !== "127.0.0.1") { + // PWA ต้องใช้ HTTPS หรือ localhost เท่านั้น + return null; + } + try { + const registration = await navigator.serviceWorker.register(SW_URL, { + scope: "./", + updateViaCache: "none", + }); + + // เช็คอัปเดตทันทีที่เปิดหน้า และซ้ำทุก 30 นาที (เบราว์เซอร์เช็คเองทุก 24 ชม. ซึ่งช้าเกินไป) + registration.update().catch(() => {}); + setInterval(() => registration.update().catch(() => {}), 30 * 60 * 1000); + + navigator.serviceWorker.addEventListener("controllerchange", () => { + if (reloading) return; + reloading = true; + location.reload(); + }); + + document.addEventListener("visibilitychange", () => { + if (document.visibilityState === "visible") registration.update().catch(() => {}); + }); + + return registration; + } catch (error) { + console.warn("ลงทะเบียน service worker ไม่สำเร็จ", error); + return null; + } +} + +registerServiceWorker(); diff --git a/ui/router.js b/ui/router.js new file mode 100644 index 0000000..ccddb17 --- /dev/null +++ b/ui/router.js @@ -0,0 +1,64 @@ +/* router.js — hash router จิ๋ว (ไม่มี build step, ใช้ได้กับ static hosting ทุกแบบ) */ + +const listeners = new Set(); +let routes = {}; +let fallback = null; +let currentPath = null; + +export function defineRoutes(map, fallbackRoute) { + routes = map; + fallback = fallbackRoute || Object.keys(map)[0]; +} + +export function currentRoute() { + return parseHash(); +} + +function parseHash() { + const raw = window.location.hash.replace(/^#/, ""); + const path = raw.split("?")[0] || "/"; + const query = new URLSearchParams(raw.split("?")[1] || ""); + return { path: path.startsWith("/") ? path : `/${path}`, query }; +} + +export function navigate(path) { + if (window.location.hash === `#${path}`) { + handleRoute(true); + return; + } + window.location.hash = `#${path}`; +} + +export function onRouteChange(callback) { + listeners.add(callback); + return () => listeners.delete(callback); +} + +function handleRoute(force = false) { + const route = parseHash(); + const key = route.path; + const resolved = routes[key] ? key : fallback; + if (!routes[resolved]) return; + if (!force && currentPath === resolved) return; + currentPath = resolved; + const view = routes[resolved]; + listeners.forEach((fn) => fn({ ...route, path: resolved, view })); +} + +export function startRouter() { + window.addEventListener("hashchange", () => handleRoute()); + if (!window.location.hash) { + window.location.replace("#/"); + } + handleRoute(true); +} + +export function markActiveNav(path) { + document.querySelectorAll("[data-nav]").forEach((link) => { + const target = link.getAttribute("data-nav"); + const isHome = path === "/" && (target === "home" || target === "home-link"); + const isAdmin = path === "/admin" && target.startsWith("admin"); + if (isHome || isAdmin) link.setAttribute("aria-current", "page"); + else link.removeAttribute("aria-current"); + }); +} diff --git a/ui/ui.js b/ui/ui.js new file mode 100644 index 0000000..e7c9b25 --- /dev/null +++ b/ui/ui.js @@ -0,0 +1,122 @@ +/* ui.js — ตัวช่วยกลาง: ไอคอน SVG, escaping, toast, ตรวจ URL */ + +const ICON_PATHS = { + search: '', + close: '', + settings: + '', + arrowRight: '', + arrowUp: '', + arrowDown: '', + plus: '', + trash: + '', + save: '', + download: '', + refresh: + '', + check: '', + alert: '', + shield: '', + external: + '', + folder: '', + film: '', + bus: '', + droplet: '', + cpu: '', + disc: '', + book: '', + wrench: '', + dashboard: '', + palette: '', + list: '', + spark: '', +}; + +export const ICON_NAMES = Object.keys(ICON_PATHS); + +/** คืนสตริง SVG (ใช้ innerHTML — ชื่อไอคอนมาจากลิสต์คงที่ ไม่ใช่ข้อมูลผู้ใช้) */ +export function icon(name, extraClass = "") { + const d = ICON_PATHS[name] || ICON_PATHS.folder; + return ``; +} + +/** แทนที่ทุกจุดที่ใส่ [data-icon="name"] ด้วย SVG จริง (สำหรับ markup ใน index.html) */ +export function hydrateIcons(root = document) { + root.querySelectorAll("[data-icon]").forEach((node) => { + const name = node.getAttribute("data-icon"); + if (!name || node.dataset.iconReady === "1") return; + node.innerHTML = icon(name); + node.dataset.iconReady = "1"; + }); +} + +export function escapeHtml(value) { + return String(value ?? "") + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} + +/** เติม https:// ถ้าไม่มี scheme และคืน null ถ้าไม่ใช่ http(s) */ +export function normalizeUrl(raw) { + const value = String(raw ?? "").trim(); + if (!value) return null; + const withScheme = /^https?:\/\//i.test(value) ? value : `https://${value.replace(/^\/+/, "")}`; + try { + const parsed = new URL(withScheme); + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null; + if (!parsed.hostname.includes(".")) return null; + return parsed.toString().replace(/\/$/, ""); + } catch { + return null; + } +} + +export function hostOf(url) { + const normalized = normalizeUrl(url); + if (!normalized) return ""; + try { + return new URL(normalized).hostname; + } catch { + return ""; + } +} + +export function isEmail(raw) { + return /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(raw ?? "").trim()); +} + +let toastTimer = null; +export function toast(message, kind = "info") { + const stack = document.getElementById("toast-stack"); + if (!stack) return; + stack.replaceChildren(); + const node = document.createElement("div"); + node.className = `toast${kind === "error" ? " toast--error" : ""}`; + node.textContent = message; + stack.appendChild(node); + clearTimeout(toastTimer); + toastTimer = setTimeout(() => stack.replaceChildren(), 3600); +} + +export function debounce(fn, wait = 120) { + let timer = null; + return (...args) => { + clearTimeout(timer); + timer = setTimeout(() => fn(...args), wait); + }; +} + +export function debounceImmediate(fn, wait = 400) { + let timer = null; + return (...args) => { + clearTimeout(timer); + timer = setTimeout(() => fn(...args), wait); + }; +} diff --git a/ui/views/admin.js b/ui/views/admin.js new file mode 100644 index 0000000..f6fc71e --- /dev/null +++ b/ui/views/admin.js @@ -0,0 +1,560 @@ +/* views/admin.js — หลังบ้าน: แก้ชื่อ/คำอธิบาย/ลิงก์ แล้วเผยแพร่หรือดาวน์โหลด JSON */ + +import { escapeHtml, icon, isEmail, normalizeUrl, toast, debounce } from "../ui.js"; +import { + clearDraft, + createProject, + downloadJson, + normalizeData, + probePublishApi, + publishProjects, + readDraft, + readToken, + writeDraft, + writeToken, +} from "../data.js"; + +const ICON_LABELS = { + folder: "โฟลเดอร์", + dashboard: "แดชบอร์ด", + film: "หนัง", + bus: "รถประจำทาง", + droplet: "สปริงเกลอร์", + cpu: "คอมพิวเตอร์", + disc: "แผ่นดิสก์", + book: "หนังสือ", + wrench: "เครื่องมือช่าง", + palette: "ออกแบบ", + list: "รายการ", + spark: "ประกาย", + shield: "ความปลอดภัย", + settings: "ตั้งค่า", +}; + +function serialize(data) { + const { projects, site, owner_name: owner } = data; + return JSON.stringify({ owner, site, projects }); +} + +export function adminView(ctx) { + let root = null; + let draft = null; + let published = null; + let listEl = null; + let dirtyBar = null; + let statusEl = null; + let apiState = { available: false }; + + const saveDraft = debounce(() => { + if (!draft) return; + if (serialize(draft) === serialize(published)) clearDraft(); + else writeDraft(draft); + }, 250); + + function isDirty() { + return draft && serialize(draft) !== serialize(published); + } + + /* ------------------------------------------------------------- render */ + function mount(container) { + root = container; + published = normalizeData(ctx.data); + const stored = readDraft(); + draft = stored && serialize(stored) !== serialize(published) ? stored : normalizeData(published); + const restored = Boolean(stored) && serialize(draft) !== serialize(published); + + root.innerHTML = ` +
+
+
+

จัดการข้อมูลโปรเจค

+

+ แก้ชื่อโปรเจค คำอธิบายใต้ชื่อ และลิงก์ของแต่ละโปรเจค จากนั้นกด “เผยแพร่” + เพื่อบันทึกลงไฟล์ข้อมูลของเว็บ +

+
+
+ + ${icon("arrowRight")}ดูหน้าเว็บ + +
+
+ +
+ + กำลังตรวจสอบช่องทางเผยแพร่… + +
+ +
+
+

ข้อความบนหน้าเว็บ

+
+
+
+ + +

ข้อความนี้แสดงเป็นหัวเรื่องใหญ่บนหน้าแรก

+
+
+
+ + +
+
+ + +

+
+
+
+
+ +
+
+

+ รายชื่อโปรเจค (${draft.projects.length}) +

+ +
+
+
+
+
+ +
+
+

ช่องทางบันทึก

+
+
+

+ กำลังตรวจสอบ… +

+
+ ตั้งรหัสเผยแพร่ (เมื่อเว็บอยู่บนเซิร์ฟเวอร์) +
+ + +

เก็บไว้ในเบราว์เซอร์เครื่องนี้เท่านั้น ไม่ถูกส่งไปที่อื่น

+
+
+
+
+ + +
`; + + listEl = root.querySelector("[data-list]"); + dirtyBar = root.querySelector("[data-dirty-bar]"); + statusEl = root.querySelector("[data-status]"); + + bindSiteFields(); + bindActions(root.querySelector(".wrap")); + renderList(); + + if (restored) { + toast("กู้คืนฉบับร่างที่แก้ค้างไว้ แล้ว"); + } + refreshDirty(); + checkApi(); + } + + function bindSiteFields() { + root.querySelectorAll("[data-site]").forEach((field) => { + field.addEventListener("input", () => { + const key = field.getAttribute("data-site"); + draft.site[key] = field.value; + if (key === "contact_email") { + const errorEl = root.querySelector('[data-error="site-email"]'); + const valid = !field.value.trim() || isEmail(field.value); + errorEl.textContent = valid ? "" : "รูปแบบอีเมลไม่ถูกต้อง"; + field.closest(".field").classList.toggle("field--error", !valid); + } + saveDraft(); + refreshDirty(); + }); + }); + } + + function bindActions(shell) { + shell.addEventListener("click", (event) => { + const trigger = event.target.closest("[data-act]"); + if (!trigger) return; + const act = trigger.getAttribute("data-act"); + if (act === "add") { + draft.projects.push(createProject(draft.projects.length)); + renderList(); + markDirty(); + const items = listEl.querySelectorAll(".admin-item"); + const last = items[items.length - 1]; + if (last) { + last.scrollIntoView({ block: "center", behavior: "smooth" }); + last.querySelector('input[data-field="project_name"]')?.focus(); + } + return; + } + if (act === "reload") { + reloadFromServer(); + return; + } + if (act === "download") { + downloadJson(draft); + toast("ดาวน์โหลด projects.json แล้ว — เอาไปวางในโฟลเดอร์ data/"); + return; + } + if (act === "discard") { + askDiscard(); + return; + } + if (act === "publish") { + doPublish(trigger); + } + }); + + root.querySelector("#publish-token")?.addEventListener("input", (event) => { + writeToken(event.target.value.trim()); + }); + + listEl.addEventListener("click", (event) => { + const btn = event.target.closest("[data-item-act]"); + if (!btn) return; + const item = btn.closest(".admin-item"); + const index = Number(item.dataset.index); + const act = btn.getAttribute("data-item-act"); + if (act === "up" && index > 0) { + [draft.projects[index - 1], draft.projects[index]] = [ + draft.projects[index], + draft.projects[index - 1], + ]; + renderList(); + markDirty(); + listEl.querySelectorAll(".admin-item")[index - 1]?.scrollIntoView({ block: "nearest" }); + } + if (act === "down" && index < draft.projects.length - 1) { + [draft.projects[index + 1], draft.projects[index]] = [ + draft.projects[index], + draft.projects[index + 1], + ]; + renderList(); + markDirty(); + listEl.querySelectorAll(".admin-item")[index + 1]?.scrollIntoView({ block: "nearest" }); + } + if (act === "remove") askRemove(index); + }); + + listEl.addEventListener("input", (event) => { + const field = event.target.closest("[data-field]"); + if (!field) return; + const item = field.closest(".admin-item"); + const index = Number(item.dataset.index); + const key = field.getAttribute("data-field"); + draft.projects[index][key] = field.value; + validateField(item, key); + if (key === "project_name") { + item.querySelector(".admin-item__label").textContent = field.value || "ไม่มีชื่อโปรเจค"; + } + markDirty(); + saveDraft(); + }); + + listEl.addEventListener("change", (event) => { + const field = event.target.closest("[data-field]"); + if (!field || event.target.tagName !== "SELECT") return; + const item = field.closest(".admin-item"); + draft.projects[Number(item.dataset.index)][field.getAttribute("data-field")] = field.value; + markDirty(); + }); + } + + function validateField(item, key) { + const input = item.querySelector(`[data-field="${key}"]`); + if (!input) return true; + const errorEl = item.querySelector(`[data-error="${key}"]`); + const value = input.value.trim(); + let message = ""; + if (key === "project_name" && !value) message = "ต้องใส่ชื่อโปรเจค"; + if (key === "project_url") { + if (!value) message = "ต้องใส่ลิงก์ของโปรเจค"; + else if (!normalizeUrl(value)) message = "ลิงก์ไม่ถูกต้อง (ต้องเริ่มด้วย http:// หรือ https://)"; + } + if (key === "contact_email" && value && !isEmail(value)) message = "รูปแบบอีเมลไม่ถูกต้อง"; + if (errorEl) errorEl.textContent = message; + input.closest(".field")?.classList.toggle("field--error", Boolean(message)); + return !message; + } + + function validateAll() { + let ok = true; + listEl.querySelectorAll(".admin-item").forEach((item) => { + ["project_name", "project_url", "contact_email"].forEach((key) => { + if (!validateField(item, key)) ok = false; + }); + }); + return ok; + } + + /* --------------------------------------------------------------- list */ + function renderList() { + if (!listEl) return; + root.querySelector("[data-project-count]").textContent = draft.projects.length; + if (draft.projects.length === 0) { + listEl.innerHTML = ` +
+ +

ยังไม่มีโปรเจค

+

กด “เพิ่มโปรเจค” เพื่อเริ่มใส่รายการแรก

+
`; + return; + } + listEl.innerHTML = draft.projects + .map((project, index) => itemHtml(project, index, draft.projects.length)) + .join(""); + } + + function itemHtml(project, index, total) { + const iconOptions = Object.entries(ICON_LABELS) + .map( + ([value, label]) => + ``, + ) + .join(""); + return ` +
+
+ ${index + 1} + ${escapeHtml(project.project_name || "ไม่มีชื่อโปรเจค")} +
+ + + +
+
+ +
+
+ + +

+
+
+ + +

+
+
+ +
+ + +
+ +
+
+ + +

+
+
+ + +
+
+
`; + } + + /* -------------------------------------------------------------- state */ + function markDirty() { + saveDraft(); + refreshDirty(); + } + + function refreshDirty() { + if (!dirtyBar) return; + dirtyBar.hidden = !isDirty(); + const publishBtn = dirtyBar.querySelector('[data-act="publish"]'); + if (publishBtn) publishBtn.disabled = !apiState.available; + } + + async function checkApi() { + apiState = await probePublishApi(); + if (!statusEl) return; + const textEl = statusEl.querySelector("[data-status-text]"); + const extraEl = statusEl.querySelector("[data-status-extra]"); + const hintEl = root.querySelector("[data-publish-hint]"); + if (apiState.available) { + statusEl.dataset.state = "ok"; + textEl.textContent = "พร้อมเผยแพร่ผ่านเซิร์ฟเวอร์"; + extraEl.textContent = apiState.writable + ? "บันทึกลง data/projects.json ได้ทันที" + : "อ่านได้ แต่เขียนไม่ได้ (ตรวจรหัสเผยแพร่)"; + hintEl.innerHTML = + "กด “เผยแพร่” แล้วไฟล์ data/projects.json จะถูกเขียนทับและ commit ขึ้น Git ให้อัตโนมัติ"; + } else if (ctx.source === "cache") { + statusEl.dataset.state = "warn"; + textEl.textContent = "เปิดแบบออฟไลน์ — เห็นข้อมูลที่แคชไว้"; + extraEl.textContent = ""; + hintEl.innerHTML = + "ตอนนี้อ่านข้อมูลจากแคชในเบราว์เซอร์ ถ้าต้องการแก้จริงให้เปิดผ่านเซิร์ฟเวอร์ หรือดาวน์โหลด JSON ไปวางใน data/ เอง"; + } else { + statusEl.dataset.state = "warn"; + textEl.textContent = "เปิดแบบไฟล์นิ่ง — เผยแพร่ตรงไม่ได้"; + extraEl.textContent = "ใช้ปุ่มดาวน์โหลด JSON แทน"; + hintEl.innerHTML = + "หน้านี้เปิดแบบไม่มีเซิร์ฟเวอร์หลังบ้าน จึงเขียนไฟล์เองไม่ได้: กด “ดาวน์โหลด JSON” แล้วเอาไฟล์ไปวางที่ data/projects.json ในโปรเจค"; + } + refreshDirty(); + } + + async function reloadFromServer() { + const result = await ctx.reload(); + published = normalizeData(result.data); + draft = normalizeData(published); + clearDraft(); + root.querySelector('[data-site="welcome_message"]').value = draft.site.welcome_message; + root.querySelector('[data-site="site_title"]').value = draft.site.site_title; + root.querySelector('[data-site="contact_email"]').value = draft.site.contact_email; + renderList(); + refreshDirty(); + toast("ดึงข้อมูลล่าสุดแล้ว"); + } + + function askDiscard() { + const dialog = document.createElement("dialog"); + dialog.className = "dialog"; + dialog.innerHTML = ` +

ทิ้งการแก้ไขทั้งหมด?

+

รายการที่แก้ไว้แต่ยังไม่เผยแพร่จะหายไป การกระทำนี้ย้อนกลับไม่ได้

+
+ + +
`; + document.body.appendChild(dialog); + dialog.addEventListener("click", (event) => { + if (event.target.closest("[data-close]")) dialog.close(); + if (event.target.closest("[data-confirm]")) { + clearDraft(); + draft = normalizeData(published); + mount(root); + toast("ทิ้งการแก้ไขแล้ว"); + dialog.close(); + } + }); + dialog.addEventListener("close", () => dialog.remove()); + dialog.showModal(); + } + + function askRemove(index) { + const project = draft.projects[index]; + const dialog = document.createElement("dialog"); + dialog.className = "dialog"; + dialog.innerHTML = ` +

ลบโปรเจคนี้?

+

“${escapeHtml( + project.project_name || "ไม่มีชื่อโปรเจค", + )}” จะถูกเอาออกจากรายการ (ยังไม่ถึงเว็บจนกว่าจะเผยแพร่)

+
+ + +
`; + document.body.appendChild(dialog); + dialog.addEventListener("click", (event) => { + if (event.target.closest("[data-close]")) dialog.close(); + if (event.target.closest("[data-confirm]")) { + draft.projects.splice(index, 1); + renderList(); + markDirty(); + toast("ลบโปรเจคออกจากรายการแล้ว"); + dialog.close(); + } + }); + dialog.addEventListener("close", () => dialog.remove()); + dialog.showModal(); + } + + async function doPublish(trigger) { + if (!validateAll()) { + toast("ยังมีช่องที่ต้องแก้ก่อนเผยแพร่", "error"); + const firstError = listEl.querySelector(".field--error input, .field--error textarea"); + firstError?.focus(); + return; + } + const emailValid = !draft.site.contact_email.trim() || isEmail(draft.site.contact_email); + if (!emailValid) { + toast("อีเมลติดต่อของเว็บไม่ถูกต้อง", "error"); + root.querySelector("#site-email")?.focus(); + return; + } + const label = trigger.querySelector("span"); + const original = label ? label.textContent : ""; + if (label) label.textContent = "กำลังเผยแพร่…"; + trigger.disabled = true; + try { + const result = await publishProjects(draft); + clearDraft(); + published = normalizeData({ ...draft, updated_at: result.updated_at || "" }); + draft = normalizeData(published); + ctx.setData(published); + refreshDirty(); + toast("เผยแพร่แล้ว — หน้าเว็บอัปเดตเรียบร้อย"); + } catch (error) { + toast(`เผยแพร่ไม่สำเร็จ: ${error.message}`, "error"); + } finally { + trigger.disabled = false; + if (label) label.textContent = original; + refreshDirty(); + } + } + + return { + mount, + destroy() { + root = null; + listEl = null; + dirtyBar = null; + statusEl = null; + draft = null; + published = null; + }, + }; +} diff --git a/ui/views/home.js b/ui/views/home.js new file mode 100644 index 0000000..cdfb33c --- /dev/null +++ b/ui/views/home.js @@ -0,0 +1,170 @@ +/* views/home.js — หน้าแรก: ข้อความต้อนรับ + ค้นหา + การ์ดโปรเจค */ + +import { escapeHtml, hostOf, icon, normalizeUrl } from "../ui.js"; + +export function homeView(ctx) { + let root = null; + let query = ""; + let inputEl = null; + let gridEl = null; + let countEl = null; + + function filtered() { + const items = ctx.data.projects; + const q = query.trim().toLowerCase(); + if (!q) return items; + return items.filter((p) => { + const haystack = [p.project_name, p.project_description, hostOf(p.project_url), p.project_url] + .join(" ") + .toLowerCase(); + return haystack.includes(q); + }); + } + + function cardHtml(project) { + const url = normalizeUrl(project.project_url); + const host = hostOf(project.project_url); + const name = escapeHtml(project.project_name || "ไม่มีชื่อโปรเจค"); + const desc = escapeHtml(project.project_description || "ยังไม่มีคำอธิบาย"); + const nameHtml = url + ? `${name}` + : `${name}`; + return ` +
+
+ +
+

${nameHtml}

+

${desc}

+
+
+
+ ${escapeHtml(host || "ยังไม่ใส่ลิงก์")} + เปิดเว็บไซต์ ${icon("arrowRight")} +
+
`; + } + + function renderGrid() { + if (!gridEl) return; + const items = filtered(); + if (countEl) { + countEl.textContent = + query.trim().length > 0 + ? `พบ ${items.length} จาก ${ctx.data.projects.length} โปรเจค` + : `${ctx.data.projects.length} โปรเจค`; + } + if (items.length === 0) { + const isSearch = query.trim().length > 0; + gridEl.className = ""; + gridEl.innerHTML = ` +
+ +

${isSearch ? "ไม่พบโปรเจคที่ค้นหา" : "ยังไม่มีโปรเจคในรายการ"}

+

${ + isSearch + ? "ลองพิมพ์คำอื่น หรือล้างคำค้นหาเพื่อดูทั้งหมด" + : "เข้าไปเพิ่มโปรเจคได้ที่หน้า “จัดการข้อมูล”" + }

+
`; + return; + } + gridEl.className = "project-grid"; + gridEl.innerHTML = items.map(cardHtml).join(""); + } + + return { + mount(container) { + root = container; + const site = ctx.data.site; + const total = ctx.data.projects.length; + const withEmail = ctx.data.projects.filter((p) => p.contact_email).length; + + root.innerHTML = ` +
+
+
+

${icon("spark")}${escapeHtml( + site.site_title, + )}

+

${escapeHtml( + site.welcome_message, + )}

+

รวมเว็บที่ทำเองไว้ในที่เดียว เลือกดูได้ตามใจ ไม่มีโฆษณา ไม่มีล็อกอิน

+ +
+ ${icon("folder")}${total} โปรเจค + ${icon("shield")}${escapeHtml(site.ssl_note)} + ${ + withEmail + ? `${icon("list")}${withEmail} โปรเจคมีอีเมลติดต่อ` + : "" + } +
+
+ +
+ +
+
+

รายชื่อโปรเจค

+

กดที่การ์ดเพื่อเปิดเว็บนั้นในแท็บใหม่

+
+

+
+ +
+
`; + + gridEl = root.querySelector("[data-grid]"); + countEl = root.querySelector("[data-count]"); + inputEl = root.querySelector("#project-search"); + const clearBtn = root.querySelector(".searchbar__clear"); + const form = root.querySelector(".searchbar"); + + form.addEventListener("submit", (event) => { + event.preventDefault(); + inputEl.blur(); + }); + inputEl.addEventListener("input", () => { + query = inputEl.value; + clearBtn.hidden = query.length === 0; + renderGrid(); + }); + clearBtn.addEventListener("click", () => { + inputEl.value = ""; + query = ""; + clearBtn.hidden = true; + inputEl.focus(); + renderGrid(); + }); + + renderGrid(); + }, + destroy() { + root = null; + inputEl = null; + gridEl = null; + countEl = null; + }, + }; +}