feat: hobby project landing page (PWA + SPA) with admin backoffice

- landing page: welcome hero, live search, project card grid (10 projects from owner list)
- warm brown/white theme (fastwork-inspired layout), embedded K2D Thai font
- PWA: manifest, PIL-generated icons, versioned service worker with auto-update
- backoffice at #/admin: edit name/description/url, reorder, delete, publish
- server/publish.mjs: zero-dependency static server + PUT api/projects with
  validation, JSON write, git commit and push; loopback-only unless ADMIN_TOKEN
- docs: README, DESIGN.md (color/type contract), AGENTS.md
This commit is contained in:
Bkk1234 committed 2026-11-19 01:03:13 +07:00
1 parent e55b193644
commit c00bc62272
35 files changed
+3432 -2

No files matched your search

+10
View File
@@ -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
+7
View File
@@ -0,0 +1,7 @@
# ไฟล์/โฟลเดอร์ที่ไม่ขึ้น Git
node_modules/
.DS_Store
Thumbs.db
*.log
.env
.env.*
+79
View File
@@ -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` และ `<meta name="app-version">` ใน `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 แทน
+75
View File
@@ -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 ด้านล่าง, `<dialog>` ยืนยันการลบ/ทิ้งการแก้ไข
## 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` และ `<meta name="app-version">` พร้อมกัน
+74 -2
View File
@@ -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 (ไม่มีอิโมจิในหน้าเว็บ)
+312
View File
@@ -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);
}
}
+470
View File
@@ -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;
}
}
+503
View File
@@ -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;
}
}
+93
View File
@@ -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": "[email protected]",
"icon": "film"
},
{
"project_id": "atroute",
"project_name": "รวบรวมรถประจำทาง",
"project_description": "รวมสายรถประจำทาง ตารางเวลา และจุดจอดที่ใช้จริง",
"project_url": "https://atroute.hobbypj.com",
"contact_email": "[email protected]",
"icon": "bus"
},
{
"project_id": "irrcal",
"project_name": "ออกแบบสปริงเกลอร์",
"project_description": "คำนวณและออกแบบระบบสปริงเกลอร์สำหรับแปลงเกษตร",
"project_url": "https://irrcal.hobbypj.com",
"contact_email": "[email protected]",
"icon": "droplet"
},
{
"project_id": "kth",
"project_name": "ขายเคสคอมปรับแต่ง",
"project_description": "รวมเคสคอมพิวเตอร์พร้อมข้อมูลสเปกสำหรับคนชอบประกอบเอง",
"project_url": "https://kth.hobbypj.com",
"contact_email": "[email protected]",
"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": "[email protected]",
"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"
}
]
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 344 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

+81
View File
@@ -0,0 +1,81 @@
<!doctype html>
<html lang="th">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>โปรเจคอดิเรกของเรา</title>
<meta
name="description"
content="รายชื่อโปรเจคอดิเรกของเรา เลือกโปรเจคที่อยากดูได้เลย ทุกเว็บใช้ SSL ฟรีต่ออายุอัตโนมัติ"
/>
<meta name="theme-color" content="#8A4722" />
<meta name="app-version" content="2026.11.19.1" />
<link rel="manifest" href="manifest.json" />
<link rel="icon" type="image/png" sizes="192x192" href="icons/icon-192.png" />
<link rel="icon" type="image/png" sizes="64x64" href="icons/favicon-64.png" />
<link rel="apple-touch-icon" href="icons/icon-180.png" />
<link rel="preload" href="fonts/k2d-400-thai.woff2" as="font" type="font/woff2" crossorigin />
<link rel="preload" href="fonts/k2d-700-thai.woff2" as="font" type="font/woff2" crossorigin />
<link rel="stylesheet" href="assets/css/theme.css" />
<link rel="stylesheet" href="assets/css/home.css" />
<link rel="stylesheet" href="assets/css/admin.css" />
<script type="module" src="ui/app.js"></script>
</head>
<body>
<a class="skip-link" href="#main">ข้ามไปที่เนื้อหาหลัก</a>
<header class="site-header">
<div class="wrap site-header__inner">
<a class="brand" href="#/" aria-label="กลับไปหน้ารายชื่อโปรเจค">
<span class="brand__mark" aria-hidden="true">
<svg viewBox="0 0 32 32" width="32" height="32" focusable="false">
<rect width="32" height="32" rx="9" fill="currentColor" />
<rect x="8" y="8" width="6.5" height="6.5" rx="1.8" fill="#FFFFFF" />
<rect x="17.5" y="8" width="6.5" height="6.5" rx="1.8" fill="#FFFFFF" opacity=".55" />
<rect x="8" y="17.5" width="6.5" height="6.5" rx="1.8" fill="#FFFFFF" opacity=".55" />
<rect x="17.5" y="17.5" width="6.5" height="6.5" rx="1.8" fill="#FFFFFF" />
</svg>
</span>
<span class="brand__text">
<strong>โปรเจคอดิเรก</strong>
<small>hobbypj.com</small>
</span>
</a>
<nav class="site-nav" aria-label="เมนูหลัก">
<a class="site-nav__link" href="#/" data-nav="home">หน้าแรก</a>
<a class="site-nav__link" href="#/admin" data-nav="admin">จัดการข้อมูล</a>
<a class="btn btn--primary btn--sm" href="#/admin" data-nav="admin-cta">
<span data-icon="settings"></span>
<span>แก้ไขรายการ</span>
</a>
</nav>
</div>
</header>
<main id="main" class="site-main" tabindex="-1"></main>
<footer class="site-footer">
<div class="wrap site-footer__inner">
<div class="site-footer__col">
<p class="site-footer__brand">โปรเจคอดิเรกของเรา</p>
<p class="site-footer__note">เว็บเล็ก ๆ ที่ทำเล่นเพราะอยากทำ ไม่ได้มีไว้ขาย</p>
</div>
<div class="site-footer__col">
<p class="site-footer__title">ความปลอดภัย</p>
<p class="site-footer__note" data-ssl-note>ทุกเว็บใช้ SSL ฟรี ต่ออายุอัตโนมัติ</p>
</div>
<div class="site-footer__col">
<p class="site-footer__title">ติดต่อ</p>
<p class="site-footer__note"><a data-contact-link href="#/admin">เพิ่มอีเมลติดต่อได้ในหน้าจัดการ</a></p>
</div>
</div>
</footer>
<div class="toast-stack" id="toast-stack" role="status" aria-live="polite"></div>
<noscript>
<div class="wrap noscript">หน้านี้ต้องเปิดใช้งาน JavaScript เพื่อแสดงรายชื่อโปรเจค</div>
</noscript>
</body>
</html>
+36
View File
@@ -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"
}
]
}
+11
View File
@@ -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"
}
}
+304
View File
@@ -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 || "[email protected]"),
"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(
`<!doctype html><meta charset="utf-8"><title>ไม่พบหน้านี้</title>
<div style="font-family:sans-serif;padding:40px">
<h1>ไม่พบหน้านี้</h1><p><a href="/">กลับไปหน้ารายชื่อโปรเจค</a></p>
</div>`,
);
}
}
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 ? "เปิด" : "ปิด"}`);
});
+110
View File
@@ -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();
}
}
+103
View File
@@ -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 = `
<div class="wrap">
<div class="hero" style="min-height:280px"></div>
<div class="loading" aria-hidden="true">
<div class="skeleton"></div><div class="skeleton"></div><div class="skeleton"></div>
</div>
<p class="visually-hidden" role="status">กำลังโหลดรายชื่อโปรเจค</p>
</div>`;
}
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();
+209
View File
@@ -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);
}
+39
View File
@@ -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();
+64
View File
@@ -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");
});
}
+122
View File
@@ -0,0 +1,122 @@
/* ui.js — ตัวช่วยกลาง: ไอคอน SVG, escaping, toast, ตรวจ URL */
const ICON_PATHS = {
search: '<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>',
close: '<path d="M18 6 6 18M6 6l12 12"/>',
settings:
'<path d="M4 7h10M18 7h2M4 17h2M10 17h10"/><circle cx="16" cy="7" r="2.5"/><circle cx="8" cy="17" r="2.5"/>',
arrowRight: '<path d="M5 12h14M13 5l7 7-7 7"/>',
arrowUp: '<path d="M12 19V5M5 12l7-7 7 7"/>',
arrowDown: '<path d="M12 5v14M19 12l-7 7-7-7"/>',
plus: '<path d="M12 5v14M5 12h14"/>',
trash:
'<path d="M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2M6 7l1 13h10l1-13"/><path d="M10 11v6M14 11v6"/>',
save: '<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2Z"/><path d="M17 21v-8H7v8M7 3v5h8"/>',
download: '<path d="M12 3v12M7 11l5 5 5-5M4 21h16"/>',
refresh:
'<path d="M20 11a8 8 0 1 0-2.3 5.7"/><path d="M20 4v7h-7"/>',
check: '<path d="m4 12 5 5L20 6"/>',
alert: '<path d="M12 3 2.5 20h19L12 3Z"/><path d="M12 9v5M12 17.5v.5"/>',
shield: '<path d="M12 3 5 6v6c0 4.4 3 7.6 7 9 4-1.4 7-4.6 7-9V6l-7-3Z"/><path d="m9 12 2 2 4-4"/>',
external:
'<path d="M14 4h6v6M20 4l-8.5 8.5"/><path d="M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5"/>',
folder: '<path d="M3 7a2 2 0 0 1 2-2h4l2 2h6a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Z"/>',
film: '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M7 4v16M17 4v16M3 9h4M3 15h4M17 9h4M17 15h4"/>',
bus: '<rect x="4" y="4" width="16" height="12" rx="2"/><path d="M4 10h16M7 20v-2M17 20v-2"/><circle cx="8" cy="13.5" r=".8"/><circle cx="16" cy="13.5" r=".8"/>',
droplet: '<path d="M12 3s6 6.2 6 10a6 6 0 0 1-12 0c0-3.8 6-10 6-10Z"/>',
cpu: '<rect x="7" y="7" width="10" height="10" rx="2"/><path d="M10 3v2M14 3v2M10 19v2M14 19v2M3 10h2M3 14h2M19 10h2M19 14h2"/>',
disc: '<circle cx="12" cy="12" r="8"/><circle cx="12" cy="12" r="2.4"/>',
book: '<path d="M5 4h9a3 3 0 0 1 3 3v13H8a3 3 0 0 1-3-3V4Z"/><path d="M8 20a3 3 0 0 1 0-6h9"/>',
wrench: '<path d="M14.5 4.5a4.5 4.5 0 0 0 5.7 5.7L11 19.5a3.5 3.5 0 1 1-5-5l9-9Z"/>',
dashboard: '<rect x="3" y="3" width="7" height="9" rx="1.6"/><rect x="14" y="3" width="7" height="5" rx="1.6"/><rect x="14" y="12" width="7" height="9" rx="1.6"/><rect x="3" y="16" width="7" height="5" rx="1.6"/>',
palette: '<circle cx="12" cy="12" r="9"/><circle cx="9" cy="9.5" r="1.2"/><circle cx="15" cy="9.5" r="1.2"/><circle cx="12" cy="15" r="1.2"/>',
list: '<path d="M8 6h13M8 12h13M8 18h13M3.5 6h.5M3.5 12h.5M3.5 18h.5"/>',
spark: '<path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8L12 3Z"/>',
};
export const ICON_NAMES = Object.keys(ICON_PATHS);
/** คืนสตริง SVG (ใช้ innerHTML — ชื่อไอคอนมาจากลิสต์คงที่ ไม่ใช่ข้อมูลผู้ใช้) */
export function icon(name, extraClass = "") {
const d = ICON_PATHS[name] || ICON_PATHS.folder;
return `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"
stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"
${extraClass ? `class="${extraClass}"` : ""}>${d}</svg>`;
}
/** แทนที่ทุกจุดที่ใส่ [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, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
}
/** เติม 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);
};
}
+560
View File
@@ -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 = `
<div class="wrap">
<div class="admin-head">
<div>
<h1 class="admin-head__title">จัดการข้อมูลโปรเจค</h1>
<p class="admin-head__sub">
แก้ชื่อโปรเจค คำอธิบายใต้ชื่อ และลิงก์ของแต่ละโปรเจค จากนั้นกด “เผยแพร่”
เพื่อบันทึกลงไฟล์ข้อมูลของเว็บ
</p>
</div>
<div class="admin-head__actions">
<button class="btn btn--ghost" type="button" data-act="reload">
${icon("refresh")}<span>ดึงข้อมูลล่าสุด</span>
</button>
<a class="btn btn--ghost" href="#/">${icon("arrowRight")}<span>ดูหน้าเว็บ</span></a>
<button class="btn btn--primary" type="button" data-act="add">
${icon("plus")}<span>เพิ่มโปรเจค</span>
</button>
</div>
</div>
<div class="publish-status" data-status data-state="warn">
<span class="publish-status__dot" aria-hidden="true"></span>
<span data-status-text>กำลังตรวจสอบช่องทางเผยแพร่…</span>
<span data-status-extra></span>
</div>
<section class="panel" aria-labelledby="site-panel-title">
<div class="panel__head">
<h2 class="panel__title" id="site-panel-title">ข้อความบนหน้าเว็บ</h2>
</div>
<div class="panel__body">
<div class="field">
<label class="field__label" for="site-welcome">ข้อความต้อนรับ</label>
<textarea id="site-welcome" data-site="welcome_message" rows="3">${escapeHtml(
draft.site.welcome_message,
)}</textarea>
<p class="field__hint">ข้อความนี้แสดงเป็นหัวเรื่องใหญ่บนหน้าแรก</p>
</div>
<div class="admin-grid-2">
<div class="field">
<label class="field__label" for="site-title">ชื่อเว็บ (ป้ายเล็กบนฮีโร่)</label>
<input id="site-title" type="text" data-site="site_title" value="${escapeHtml(
draft.site.site_title,
)}" />
</div>
<div class="field">
<label class="field__label" for="site-email">อีเมลติดต่อ (ส่วนท้ายเว็บ)</label>
<input id="site-email" type="email" data-site="contact_email" value="${escapeHtml(
draft.site.contact_email,
)}" placeholder="[email protected]" />
<p class="field__error" data-error="site-email"></p>
</div>
</div>
</div>
</section>
<section class="panel" aria-labelledby="projects-panel-title">
<div class="panel__head">
<h2 class="panel__title" id="projects-panel-title">
รายชื่อโปรเจค (<span data-project-count>${draft.projects.length}</span>)
</h2>
<button class="btn btn--quiet btn--sm" type="button" data-act="add">
${icon("plus")}<span>เพิ่มโปรเจค</span>
</button>
</div>
<div class="panel__body">
<div class="admin-list" data-list></div>
</div>
</section>
<section class="panel" aria-labelledby="publish-panel-title">
<div class="panel__head">
<h2 class="panel__title" id="publish-panel-title">ช่องทางบันทึก</h2>
</div>
<div class="panel__body">
<p class="admin-hint" data-publish-hint>
กำลังตรวจสอบ…
</p>
<details class="admin-hint">
<summary>ตั้งรหัสเผยแพร่ (เมื่อเว็บอยู่บนเซิร์ฟเวอร์)</summary>
<div class="field" style="margin-top:12px;max-width:420px">
<label class="field__label" for="publish-token">รหัสเผยแพร่</label>
<input id="publish-token" type="password" autocomplete="off" value="${escapeHtml(
readToken(),
)}" placeholder="ADMIN_TOKEN" />
<p class="field__hint">เก็บไว้ในเบราว์เซอร์เครื่องนี้เท่านั้น ไม่ถูกส่งไปที่อื่น</p>
</div>
</details>
</div>
</section>
<div class="dirty-bar" data-dirty-bar hidden>
<span class="dirty-bar__text">มีการแก้ไขที่ยังไม่ถูกบันทึก</span>
<div class="dirty-bar__actions">
<button class="btn btn--ghost btn--sm" type="button" data-act="download">
${icon("download")}<span>ดาวน์โหลด JSON</span>
</button>
<button class="btn btn--ghost btn--sm" type="button" data-act="discard">
<span>ทิ้งการแก้ไข</span>
</button>
<button class="btn btn--primary btn--sm" type="button" data-act="publish">
${icon("save")}<span>เผยแพร่</span>
</button>
</div>
</div>
</div>`;
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 = `
<div class="empty">
<span class="empty__icon" aria-hidden="true">${icon("folder")}</span>
<p class="empty__title">ยังไม่มีโปรเจค</p>
<p class="empty__text">กด “เพิ่มโปรเจค” เพื่อเริ่มใส่รายการแรก</p>
</div>`;
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]) =>
`<option value="${value}" ${project.icon === value ? "selected" : ""}>${label}</option>`,
)
.join("");
return `
<div class="admin-item" data-index="${index}">
<div class="admin-item__head">
<span class="admin-item__index">${index + 1}</span>
<span class="admin-item__label">${escapeHtml(project.project_name || "ไม่มีชื่อโปรเจค")}</span>
<div class="admin-item__tools">
<button class="btn btn--quiet" type="button" data-item-act="up" ${
index === 0 ? "disabled" : ""
} aria-label="เลื่อนขึ้น">${icon("arrowUp")}</button>
<button class="btn btn--quiet" type="button" data-item-act="down" ${
index === total - 1 ? "disabled" : ""
} aria-label="เลื่อนลง">${icon("arrowDown")}</button>
<button class="btn btn--danger" type="button" data-item-act="remove">${icon("trash")}
<span>ลบ</span></button>
</div>
</div>
<div class="admin-grid-2">
<div class="field">
<label class="field__label" for="name-${index}">ชื่อโปรเจค</label>
<input id="name-${index}" type="text" data-field="project_name" value="${escapeHtml(
project.project_name,
)}" placeholder="เช่น รวบรวมโรงหนัง" />
<p class="field__error" data-error="project_name"></p>
</div>
<div class="field">
<label class="field__label" for="url-${index}">ลิงก์เว็บไซต์</label>
<input id="url-${index}" type="url" data-field="project_url" value="${escapeHtml(
project.project_url,
)}" placeholder="https://example.hobbypj.com" inputmode="url" />
<p class="field__error" data-error="project_url"></p>
</div>
</div>
<div class="field">
<label class="field__label" for="desc-${index}">คำอธิบายใต้ชื่อ</label>
<textarea id="desc-${index}" rows="2" data-field="project_description"
placeholder="อธิบายสั้น ๆ ว่าโปรเจคนี้ทำอะไร">${escapeHtml(
project.project_description,
)}</textarea>
</div>
<div class="admin-grid-2">
<div class="field">
<label class="field__label" for="email-${index}">อีเมลติดต่อ (ไม่บังคับ)</label>
<input id="email-${index}" type="email" data-field="contact_email" value="${escapeHtml(
project.contact_email,
)}" placeholder="[email protected]" />
<p class="field__error" data-error="contact_email"></p>
</div>
<div class="field">
<label class="field__label" for="icon-${index}">ไอคอนการ์ด</label>
<select id="icon-${index}" data-field="icon">${iconOptions}</select>
</div>
</div>
</div>`;
}
/* -------------------------------------------------------------- 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 =
"กด “เผยแพร่” แล้วไฟล์ <code>data/projects.json</code> จะถูกเขียนทับและ commit ขึ้น Git ให้อัตโนมัติ";
} else if (ctx.source === "cache") {
statusEl.dataset.state = "warn";
textEl.textContent = "เปิดแบบออฟไลน์ — เห็นข้อมูลที่แคชไว้";
extraEl.textContent = "";
hintEl.innerHTML =
"ตอนนี้อ่านข้อมูลจากแคชในเบราว์เซอร์ ถ้าต้องการแก้จริงให้เปิดผ่านเซิร์ฟเวอร์ หรือดาวน์โหลด JSON ไปวางใน <code>data/</code> เอง";
} else {
statusEl.dataset.state = "warn";
textEl.textContent = "เปิดแบบไฟล์นิ่ง — เผยแพร่ตรงไม่ได้";
extraEl.textContent = "ใช้ปุ่มดาวน์โหลด JSON แทน";
hintEl.innerHTML =
"หน้านี้เปิดแบบไม่มีเซิร์ฟเวอร์หลังบ้าน จึงเขียนไฟล์เองไม่ได้: กด “ดาวน์โหลด JSON” แล้วเอาไฟล์ไปวางที่ <code>data/projects.json</code> ในโปรเจค";
}
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 = `
<div class="dialog__head"><h2 class="dialog__title">ทิ้งการแก้ไขทั้งหมด?</h2></div>
<div class="dialog__body"><p>รายการที่แก้ไว้แต่ยังไม่เผยแพร่จะหายไป การกระทำนี้ย้อนกลับไม่ได้</p></div>
<div class="dialog__foot">
<button class="btn btn--ghost" type="button" data-close>ยกเลิก</button>
<button class="btn btn--danger" type="button" data-confirm>ทิ้งการแก้ไข</button>
</div>`;
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 = `
<div class="dialog__head"><h2 class="dialog__title">ลบโปรเจคนี้?</h2></div>
<div class="dialog__body"><p>“${escapeHtml(
project.project_name || "ไม่มีชื่อโปรเจค",
)}” จะถูกเอาออกจากรายการ (ยังไม่ถึงเว็บจนกว่าจะเผยแพร่)</p></div>
<div class="dialog__foot">
<button class="btn btn--ghost" type="button" data-close>ยกเลิก</button>
<button class="btn btn--danger" type="button" data-confirm>ลบโปรเจค</button>
</div>`;
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;
},
};
}
+170
View File
@@ -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
? `<a href="${escapeHtml(url)}" target="_blank" rel="noopener noreferrer">${name}</a>`
: `<span>${name}</span>`;
return `
<article class="project-card">
<div class="project-card__top">
<span class="project-card__icon" aria-hidden="true">${icon(project.icon)}</span>
<div class="project-card__heading">
<h3 class="project-card__name">${nameHtml}</h3>
<p class="project-card__desc">${desc}</p>
</div>
</div>
<div class="project-card__foot">
<span class="project-card__host">${escapeHtml(host || "ยังไม่ใส่ลิงก์")}</span>
<span class="project-card__go">เปิดเว็บไซต์ ${icon("arrowRight")}</span>
</div>
</article>`;
}
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 = `
<div class="empty">
<span class="empty__icon" aria-hidden="true">${icon(isSearch ? "search" : "folder")}</span>
<p class="empty__title">${isSearch ? "ไม่พบโปรเจคที่ค้นหา" : "ยังไม่มีโปรเจคในรายการ"}</p>
<p class="empty__text">${
isSearch
? "ลองพิมพ์คำอื่น หรือล้างคำค้นหาเพื่อดูทั้งหมด"
: "เข้าไปเพิ่มโปรเจคได้ที่หน้า “จัดการข้อมูล”"
}</p>
</div>`;
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 = `
<div class="wrap">
<section class="hero" aria-labelledby="hero-title">
<div class="hero__inner">
<p class="hero__eyebrow">${icon("spark")}<span>${escapeHtml(
site.site_title,
)}</span></p>
<h1 class="hero__title" id="hero-title">${escapeHtml(
site.welcome_message,
)}</h1>
<p class="hero__lead">รวมเว็บที่ทำเองไว้ในที่เดียว เลือกดูได้ตามใจ ไม่มีโฆษณา ไม่มีล็อกอิน</p>
<form class="searchbar" role="search" autocomplete="off">
<span class="searchbar__icon" aria-hidden="true">${icon("search")}</span>
<label class="visually-hidden" for="project-search">ค้นหาโปรเจค</label>
<input id="project-search" type="search" name="q"
placeholder="ค้นหาชื่อโปรเจค หรือคำอธิบาย" enterkeyhint="search" />
<button class="searchbar__clear" type="button" aria-label="ล้างคำค้นหา" hidden>
${icon("close")}
</button>
</form>
<div class="hero__meta">
<span>${icon("folder")}${total} โปรเจค</span>
<span>${icon("shield")}${escapeHtml(site.ssl_note)}</span>
${
withEmail
? `<span>${icon("list")}${withEmail} โปรเจคมีอีเมลติดต่อ</span>`
: ""
}
</div>
</div>
<div class="hero__deco" aria-hidden="true">
${ctx.data.projects
.slice(0, 3)
.map(
(project, index) => `
<div class="hero__deco-card" style="--i:${index}">
<span class="hero__deco-icon">${icon(project.icon)}</span>
<span class="hero__deco-name">${escapeHtml(project.project_name)}</span>
</div>`,
)
.join("")}
</div>
</section>
<div class="section-head">
<div>
<h2 class="section-head__title" id="projects-title">รายชื่อโปรเจค</h2>
<p class="section-head__sub">กดที่การ์ดเพื่อเปิดเว็บนั้นในแท็บใหม่</p>
</div>
<p class="section-head__count" data-count></p>
</div>
<div data-grid aria-labelledby="projects-title"></div>
</div>`;
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;
},
};
}