Author SHA1 Message Date
mytheclipsebotreview 578946224d Merge remote-tracking branch 'origin/main' into dependabot/npm_and_yarn/development-e68608c19c 2026-09-15 01:07:13 +07:00
mytheclipsebotreview[bot] 3dadbf7946 Auto-merge PR #17
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
chore(deps): bump the production group with 3 updates
2026-09-14 18:06:35 +00:00
mytheclipsebotreview ea6532c703 fix: auto-fix code quality [skip ci] 2026-09-15 01:06:24 +07:00
mytheclipsebotreview 84d8139cca chore: sync bun.lock after dependabot bump 2026-09-15 01:01:07 +07:00
dependabot[bot] 01a7a7c7c8 chore(deps-dev): bump eslint-config-next in the development group
Bumps the development group with 1 update: [eslint-config-next](https://github.com/vercel/next.js/tree/HEAD/packages/eslint-config-next).


Updates `eslint-config-next` from 16.3.4 to 16.3.5
- [Release notes](https://github.com/vercel/next.js/releases)
- [Commits](https://github.com/vercel/next.js/commits/v16.3.5/packages/eslint-config-next)

---
updated-dependencies:
- dependency-name: eslint-config-next
  dependency-version: 16.3.5
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-14 17:56:33 +00:00
dependabot[bot] 6c5cf6d3e6 chore(deps): bump the production group with 3 updates
Bumps the production group with 3 updates: [next](https://github.com/vercel/next.js), [react](https://github.com/react/react/tree/HEAD/packages/react) and [react-dom](https://github.com/react/react/tree/HEAD/packages/react-dom).


Updates `next` from 16.3.4 to 16.3.5
- [Release notes](https://github.com/vercel/next.js/releases)
- [Commits](https://github.com/vercel/next.js/compare/v16.3.4...v16.3.5)

Updates `react` from 19.2.8 to 19.3.0
- [Release notes](https://github.com/react/react/releases)
- [Changelog](https://github.com/react/react/blob/main/CHANGELOG.md)
- [Commits](https://github.com/react/react/commits/v19.3.0/packages/react)

Updates `react-dom` from 19.2.8 to 19.3.0
- [Release notes](https://github.com/react/react/releases)
- [Changelog](https://github.com/react/react/blob/main/CHANGELOG.md)
- [Commits](https://github.com/react/react/commits/v19.3.0/packages/react-dom)

---
updated-dependencies:
- dependency-name: next
  dependency-version: 16.3.5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: production
- dependency-name: react
  dependency-version: 19.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: production
- dependency-name: react-dom
  dependency-version: 19.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-14 17:56:17 +00:00
mytheclipsebotreviewandinternal-model 4330f47c65 feat(web): FE overhaul — SWR centralized data layer + dashboard + islands
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
- Add SWR foundation (lib/fetcher, lib/swr, lib/api) with typed
  hooks: useSections/useDocuments/useSearch/useRelated/useRevisions/useQueueStatus
- Replace ad-hoc useEffect+fetch in Header/Sidebar/CommandMenu/search
  with SWR (dedup 4s, focus throttle 10s, debounced search 180ms)
- Doc page: RelatedGrid + RevisionList as SWR client islands (RSC hero stays)
- DocForm: SWR mutate on create/update for live sidebar invalidation
- New APIs: /api/related, /api/revisions, /api/tags, /api/queue/status,
  /api/docs filtering (?section=&status=)
- New UI: DocumentCard, SectionCard, SearchBar, TagCloud, QueueBadge,
  EmptyState, dashboard (/dashboard with QueueStrip live + section stats)
- Layout wraps SWRProvider; no TanStack code (SWR-only per spec)
- Verified: next build passes (16.3.4 Turbopack), no manual fetch sprawl remains

Co-Authored-By: internal-model
2026-09-08 19:37:27 +07:00
mytheclipsebotreview[bot] 1025454d87 Auto-merge PR #15
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
chore(deps): bump next from 16.3.3 to 16.3.4 in the production group
2026-09-08 09:38:15 +00:00
mytheclipsebotreview 66af4193f1 chore: sync bun.lock after dependabot bump 2026-09-08 16:28:02 +07:00
mytheclipsebotreview a1e550da41 Merge remote-tracking branch 'origin/main' into dependabot/npm_and_yarn/production-aafae73067 2026-09-08 16:27:58 +07:00
mytheclipsebotreview[bot] c77fa5e15c Auto-merge PR #16
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
chore(deps-dev): bump eslint-config-next from 16.3.3 to 16.3.4 in the development group
2026-09-08 09:27:53 +00:00
mytheclipsebotreview 9ce8ad190f chore: sync bun.lock after dependabot bump 2026-09-08 16:17:42 +07:00
dependabot[bot] 229cb15632 chore(deps-dev): bump eslint-config-next in the development group
Bumps the development group with 1 update: [eslint-config-next](https://github.com/vercel/next.js/tree/HEAD/packages/eslint-config-next).


Updates `eslint-config-next` from 16.3.3 to 16.3.4
- [Release notes](https://github.com/vercel/next.js/releases)
- [Commits](https://github.com/vercel/next.js/commits/v16.3.4/packages/eslint-config-next)

---
updated-dependencies:
- dependency-name: eslint-config-next
  dependency-version: 16.3.4
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-04 17:55:06 +00:00
dependabot[bot] f6ab0c38a0 chore(deps): bump next from 16.3.3 to 16.3.4 in the production group
Bumps the production group with 1 update: [next](https://github.com/vercel/next.js).


Updates `next` from 16.3.3 to 16.3.4
- [Release notes](https://github.com/vercel/next.js/releases)
- [Commits](https://github.com/vercel/next.js/compare/v16.3.3...v16.3.4)

---
updated-dependencies:
- dependency-name: next
  dependency-version: 16.3.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-04 17:54:49 +00:00
mytheclipsebotreview a0da49e2f8 revert(config): redis default kembali ke imrnes 100.121.180.82 (outage usai)
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
2026-09-02 16:02:42 +07:00
mytheclipsebotreview 7186741258 fix(config): redis default ke local 127.0.0.1:6380 (imrnes offline)
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
2026-09-02 12:15:22 +07:00
mytheclipsebotreview[bot] 05056cf31d Auto-merge PR #14
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
chore(deps): bump zod from 3.25.76 to 4.5.4
2026-09-01 18:53:57 +00:00
mytheclipsebotreview 1014014145 chore: sync bun.lock after dependabot bump 2026-09-02 01:53:50 +07:00
dependabot[bot] dd98201d79 chore(deps): bump zod from 3.25.76 to 4.5.4
Bumps [zod](https://github.com/colinhacks/zod) from 3.25.76 to 4.5.4.
- [Release notes](https://github.com/colinhacks/zod/releases)
- [Commits](https://github.com/colinhacks/zod/compare/v3.25.76...v4.5.4)

---
updated-dependencies:
- dependency-name: zod
  dependency-version: 4.5.4
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-01 18:01:35 +00:00
mytheclipsebotreview 2d26877b71 chore: upgrade runtime to Bun 1.4.0
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
- Update Nix flake.nix overlay to use Bun 1.4.0 (overrideAttrs)
- Update CI (setup-bun) to pin bun-version: 1.4.0
- Update package.json packageManager/Dockerfile/vercel.json
- sha256: sha256:Poy0vf7yJ/hzk33QiQj5gnshI5Q7dfbaMD7xgwiyDKw=
2026-08-29 11:05:14 +07:00
mytheclipsebotreview[bot] 12b99c76a6 Auto-merge PR #13
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
chore(deps-dev): bump eslint from 9.39.5 to 10.9.1
2026-08-29 03:37:51 +00:00
mytheclipsebotreview b4bbf6892c fix: auto-fix code quality [skip ci] 2026-08-29 10:37:19 +07:00
mytheclipsebotreview 464164d8a7 chore: sync bun.lock after dependabot bump 2026-08-29 11:36:07 +08:00
dependabot[bot] ba320380a0 chore(deps-dev): bump eslint from 9.39.5 to 10.9.1
Bumps [eslint](https://github.com/eslint/eslint) from 9.39.5 to 10.9.1.
- [Release notes](https://github.com/eslint/eslint/releases)
- [Commits](https://github.com/eslint/eslint/compare/v9.39.5...v10.9.1)

---
updated-dependencies:
- dependency-name: eslint
  dependency-version: 10.9.1
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-29 03:33:10 +00:00
mytheclipsebotreview[bot] 48566081f0 Auto-merge PR #10
chore(deps): bump next from 16.3.2 to 16.3.3 in the production group
2026-08-29 03:31:14 +00:00
mytheclipsebotreview 10a15a133c fix: auto-fix code quality [skip ci] 2026-08-29 10:30:56 +07:00
mytheclipsebotreview 5b1345cf9e chore: sync bun.lock after dependabot bump [skip ci] 2026-08-29 10:27:30 +07:00
mytheclipsebotreview 4ca5f0af39 Merge remote-tracking branch 'origin/main' into dependabot/npm_and_yarn/production-2c8a7f9a5b 2026-08-29 10:27:29 +07:00
mytheclipsebotreview 283d66b5e0 chore: sync bun.lock after @types/node@26 bump [skip ci] 2026-08-29 11:21:52 +08:00
mytheclipsebotreview[bot] b311c363c5 Auto-merge PR #12
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
chore(deps-dev): bump @types/node from 20.19.43 to 26.3.0
2026-08-29 02:57:10 +00:00
mytheclipsebotreview 006bf79655 fix: auto-fix code quality [skip ci] 2026-08-29 09:56:57 +07:00
dependabot[bot] 1a45ba9fdb chore(deps-dev): bump @types/node from 20.19.43 to 26.3.0
Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 20.19.43 to 26.3.0.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-version: 26.3.0
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-28 17:55:21 +00:00
dependabot[bot] 4d424e67ad chore(deps): bump next from 16.3.2 to 16.3.3 in the production group
Bumps the production group with 1 update: [next](https://github.com/vercel/next.js).


Updates `next` from 16.3.2 to 16.3.3
- [Release notes](https://github.com/vercel/next.js/releases)
- [Commits](https://github.com/vercel/next.js/compare/v16.3.2...v16.3.3)

---
updated-dependencies:
- dependency-name: next
  dependency-version: 16.3.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-28 17:54:52 +00:00
asepharyana 263a92f368 Merge pull request #8 from asepharyana/dependabot/npm_and_yarn/production-7059fa7707
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
chore(deps): bump the production group across 1 directory with 2 updates
2026-08-26 09:12:50 +07:00
Asep Hariyana f44e66bcd5 chore: sync lockfile for dependabot update 2026-08-26 10:12:44 +08:00
asepharyana 66e6fad876 Merge pull request #9 from asepharyana/dependabot/npm_and_yarn/development-9df26a4104
chore(deps-dev): bump the development group across 1 directory with 2 updates
2026-08-26 09:12:39 +07:00
Asep Hariyana befb898c45 chore: sync lockfile for dependabot update 2026-08-26 10:12:33 +08:00
dependabot[bot] 0638c4a82d chore(deps): bump the production group across 1 directory with 2 updates
Bumps the production group with 2 updates in the / directory: [next](https://github.com/vercel/next.js) and [drizzle-orm](https://github.com/drizzle-team/drizzle-orm).


Updates `next` from 16.3.1 to 16.3.2
- [Release notes](https://github.com/vercel/next.js/releases)
- [Commits](https://github.com/vercel/next.js/compare/v16.3.1...v16.3.2)

Updates `drizzle-orm` from 0.38.4 to 0.45.2
- [Release notes](https://github.com/drizzle-team/drizzle-orm/releases)
- [Commits](https://github.com/drizzle-team/drizzle-orm/compare/0.38.4...0.45.2)

---
updated-dependencies:
- dependency-name: drizzle-orm
  dependency-version: 0.45.2
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: production
- dependency-name: next
  dependency-version: 16.3.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-26 01:55:57 +00:00
dependabot[bot] e412767847 chore(deps-dev): bump the development group across 1 directory with 2 updates
Bumps the development group with 2 updates in the / directory: [eslint-config-next](https://github.com/vercel/next.js/tree/HEAD/packages/eslint-config-next) and [drizzle-kit](https://github.com/drizzle-team/drizzle-orm).


Updates `eslint-config-next` from 16.3.1 to 16.3.2
- [Release notes](https://github.com/vercel/next.js/releases)
- [Commits](https://github.com/vercel/next.js/commits/v16.3.2/packages/eslint-config-next)

Updates `drizzle-kit` from 0.30.6 to 0.31.10
- [Release notes](https://github.com/drizzle-team/drizzle-orm/releases)
- [Commits](https://github.com/drizzle-team/drizzle-orm/compare/drizzle-kit@0.30.6...drizzle-kit@0.31.10)

---
updated-dependencies:
- dependency-name: drizzle-kit
  dependency-version: 0.31.10
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: development
- dependency-name: eslint-config-next
  dependency-version: 16.3.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-26 01:55:46 +00:00
asepharyana ea4f34271c chore: update dependabot-auto-merge.yml
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
2026-08-26 08:53:44 +07:00
asepharyana caabe05c68 chore: update dependabot.yml 2026-08-26 08:53:43 +07:00
asepharyana 9d8d876ba7 feat: add dependabot auto-merge workflow
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
2026-08-25 20:32:58 +07:00
asepharyana 8f98bed7dd feat: update dependabot config
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
2026-08-25 18:16:53 +07:00
asepharyana bd3a0894b4 feat: update dependabot config 2026-08-25 18:13:06 +07:00
asepharyana 03616b4e60 feat: add dependabot config (npm auto-deps)
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
2026-08-25 18:08:45 +07:00
asepharyana 5ccba958d2 feat: add Word (.docx) export, enhance print density, and fix auth security guards
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
2026-08-22 17:59:32 +07:00
asepharyana 067115ba13 style(web): refine aesthetic to archival precision, remove generic gradients and glowing blobs
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
2026-08-22 15:12:00 +07:00
asepharyana 011571e12d feat(web): overhaul frontend with cyber-intelligence design and interactive topology
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
2026-08-22 14:55:19 +07:00
asepharyana 9591c67478 feat(export): remove author, scope, and slug metadata for cleaner minimal writeup look
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
2026-08-22 14:06:36 +07:00
asepharyana d65c5613d3 fix(print): prevent code block header/body page break split and ensure atomic code block flow 2026-08-22 14:03:35 +07:00
asepharyana 4f0d2da876 feat(export): simplify writeup export to pure human-like markdown layout without cards and exclude _index documents
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
2026-08-22 13:49:00 +07:00
asepharyana 72b53afe06 feat(export): remove cover header banner and confidential footer line from PDF view 2026-08-22 13:45:57 +07:00
asepharyana 5d85226ff0 feat(export): redesign PDF view for formal publication styling without colors or watermarks
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
2026-08-22 12:22:01 +07:00
asepharyana 5195a65ca5 ci: use sudo when syncing .next on VPS
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
2026-08-22 12:08:20 +07:00
asepharyana 666ba855a2 fix(web): fix working directory in mcpedia-web wrapper script 2026-08-22 12:04:22 +07:00
asepharyana 8adfffb6e7 fix(deploy): correctly copy prebuilt .next to apps/web/.next on VPS during deployment 2026-08-22 12:00:30 +07:00
asepharyana 864911af20 feat(export): enhance export routing to support /[section]/export, /[section]/[slug]/export, and dynamic route rendering
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
2026-08-22 11:55:58 +07:00
asepharyana 96b8765966 ci: sync git repository on VPS during deployment 2026-08-22 11:50:27 +07:00
asepharyana 5cd9ea92a7 feat(export): add single PDF export for sections and events with chapter ordering
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
2026-08-22 11:41:49 +07:00
MythEclipse 2a70a111a2 fix: strip leading whitespace before shebang in mcpedia-web wrapper script
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
The heredoc-based script writer in web.nix was indenting content inside
a nix '' string, which caused bash to prepend whitespace before the
#!/usr/bin/env bash shebang. The kernel rejected this as 'Exec format
error' (203/EXEC), preventing systemd from starting mcpedia-web.service.

Fix: use writeShellScriptBin instead of a raw heredoc. This ensures the
shebang starts at column 0 and uses the nix-resolved bash path.
2026-08-21 21:24:16 +07:00
MythEclipse c22e394f98 fix: bundle @mcpedia/* deps in nix build, fix runtime module resolution
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
Replace --external approach (which failed because @mcpedia/* workspace
packages couldn't resolve their npm deps like ioredis/bullmq at runtime)
with full bundling. The key fixes:

1. Bundle all code into a single JS file (no --external for @mcpedia/*)
   - This inlines @mcpedia/core, @mcpedia/queue, ioredis, bullmq, etc.
   - Produces ~2.6MB self-contained binary, no node_modules needed

2. Fix .bun cache symlink issues in nix sandbox:
   - After bun install, copy .bun cache with cp -rL to dereference
     relative symlinks that break in nix build sandbox
   - This was the root cause of 'File not found msgpackr-extract' errors

3. Only @mcpedia/config, embeddings, types kept external (lightweight,
   no npm deps) - resolved via packages/ source symlinks at runtime

All 3 services (api, mcp, worker) now build and run successfully in nix store.
Resolves CI failure run 32474463114 ('Cannot find module @mcpedia/core').
2026-08-21 20:36:43 +07:00
asepharyana 54d5c0ee01 ci: simplify web.nix (symlink .next, bunx next start from repo), fix CI args
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
2026-08-21 17:50:30 +07:00
asepharyana c92caede57 ci: fix SSH variable escaping in deploy step ( not \)
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
2026-08-21 17:27:23 +07:00
asepharyana e01ee22438 fix: nix build with dontFixup, root node_modules copy, web path literal fix
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
2026-08-21 17:17:39 +07:00
asepharyana aedcfbf4e7 fix: nix build with dontFixup for .bun symlink issues, use root node_modules + Attic cache push
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
2026-08-21 17:03:28 +07:00
asepharyana c6b0b2549a ci: use Attic binary cache push + nix-store substitute (not SSH copy)
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
- Bootstrap attic client from gmw cache (HTTPS substituter)
- Push store paths to pub:mcpedia cache
- VPS substitutes from mcpedia cache (fast) instead of nix copy --to ssh://
- Fallback to SSH copy if Attic push fails
2026-08-21 16:41:56 +07:00
asepharyana 34b3b8f56b ci: fix nix-build SSH args, web.nix path handling, NIX_SSHOPTS inline
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) — api (push) Canceled after 0s
CI / build + deploy (Nix) — mcp (push) Canceled after 0s
CI / build + deploy (Nix) — worker (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
2026-08-21 16:16:53 +07:00
asepharyana 53e0b442a4 ci: trigger CI
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) (api) (push) Canceled after 0s
CI / build + deploy (Nix) (mcp) (push) Canceled after 0s
CI / build + deploy (Nix) (worker) (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
2026-08-21 16:09:07 +07:00
asepharyana 5fdf5ffb64 ci: Nix-based build + deploy for all services
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) (api) (push) Canceled after 0s
CI / build + deploy (Nix) (mcp) (push) Canceled after 0s
CI / build + deploy (Nix) (worker) (push) Canceled after 0s
CI / build + deploy (web) (push) Canceled after 0s
- flake.nix: 4 packages (web, api, mcp, worker) built via bun in Nix
- web.nix: pre-built .next packaged into Nix store (avoids Turbopack/Bun sandbox issue)
- ci.yml: test (bun) → build-and-deploy (api/mcp/worker via nix build) + deploy-web (.next artifact → nix-build web.nix)
- Deploy: nix copy → nix-env --set + systemctl restart (no tarball+SSH, no VPS builds)
- systemd units updated to use Nix profile paths (/nix/var/nix/profiles/mcpedia-*)
2026-08-21 15:56:22 +07:00
asepharyana b88e9b796c ci: migrate to Nix-based build + deploy
CI / typecheck + tests (push) Canceled after 0s
CI / build + deploy (Nix) (api) (push) Canceled after 0s
CI / build + deploy (Nix) (mcp) (push) Canceled after 0s
CI / build + deploy (Nix) (web) (push) Canceled after 0s
CI / build + deploy (Nix) (worker) (push) Canceled after 0s
- Add flake.nix with 4 packages: web, api, mcp, worker
  Each builds via bun in CI sandbox, packages dist/.next + node_modules
  into Nix store, wraps with makeBinaryWrapper
- Rewrite ci.yml: test (bun typecheck+tests) → build-and-deploy (Nix matrix)
  nix build → nix copy → nix-env --set + systemctl restart on VPS
  No tarball+SSH, no VPS builds
- Gitignore content/**/*.md (DB is source of truth)
- Update AGENTS.md architecture docs
2026-08-21 15:30:48 +07:00
asepharyana d62c5d33a4 feat: enhance Markdown component with syntax highlighting and improve code snippet display
CI / typecheck + build (push) Canceled after 0s
CI / deploy to VPS (push) Canceled after 0s
2026-08-21 15:17:09 +07:00
asepharyana 87ce3ebbc6 chore: gitignore content/ .md files, remove from git tracking
CI / typecheck + build (push) Canceled after 0s
CI / deploy to VPS (push) Canceled after 0s
DB is the source of truth via MCP API. Filesystem .md files
are auto-generated backups, not tracked in git. The git-sync
webhook is secondary — content is created/updated via
create_document/update_document MCP tools (DB-first).
2026-08-21 14:33:20 +07:00
asepharyana 0de2458955 docs: create GEMASTIK 2026 Warmup writeups (ch1-14) via MCP DB API
CI / typecheck + build (push) Canceled after 0s
CI / deploy to VPS (push) Canceled after 0s
- Deleted all 14 dummy docs from DB + filesystem
- Created 14 Gemastik warmup writeups + index via create_document API (DB-first)
- ch1-ch12: encoding/stego/web/pwn basics
- ch13: RSA small factors
- ch14: RSA special integers via paper-search (GCD with paper appendix primes)
- All 15 docs indexed and live at wiki.asepharyana.my.id
2026-08-21 14:28:04 +07:00
asepharyana 7a6e717c28 docs: replace dummy docs with GEMASTIK 2026 Warmup writeups (ch1-14)
CI / typecheck + build (push) Canceled after 0s
CI / deploy to VPS (push) Canceled after 0s
- Deleted all previous dummy docs (defcon-quals-2024, infra/cloudflare-525, debugging/websocket-timeout, template, docs/*, notes/*, research/*)
- Added 14 Gemastik warmup writeups covering encoding, stego, web, pwn, crypto
- ch13: RSA small factors; ch14: RSA special integers via paper-search (GCD with paper appendix primes)
- All flags recovered and documented with solution methods
2026-08-21 13:51:31 +07:00
asepharyana be923cb432 fix: replace all hardcoded hex colors with CSS theme variables
CI / typecheck + build (push) Canceled after 0s
CI / deploy to VPS (push) Canceled after 0s
Phase 15c — theme-consistent color system:

Replaced 63 instances of hardcoded hex colors (#5e6ad2, #7170ff, #4f46e5,
#6a75e0, #828fff, #94a3b8, etc.) with CSS variables from globals.css:
- #5e6ad2 → var(--brand) (light: #5e6ad2, dark: #5e6ad2)
- #7170ff → var(--accent) (light: #4f46e5, dark: #7170ff)
- #4f46e5 → var(--accent)
- #6a75e0 → var(--brand-hover) (new var, light: #6a75e0, dark: #7170ff)
- #828fff → var(--accent-hover)
- #868686 → var(--text-dim)
- Dark-mode-specific hex in Markdown.tsx → CSS variables

Added --brand-hover CSS variable (light: #6a75e0, dark: #7170ff)
Added dark:prose-invert instead of prose-invert (light mode now uses
default prose theme instead of forced dark)

Files changed: 15 component files + globals.css
2026-08-21 13:06:01 +07:00
asepharyana ea75d68b1a fix: Phase 14 + Phase 15 — UI/UX polish + CI/CD restructure
CI / typecheck + build (push) Canceled after 0s
CI / deploy to VPS (push) Canceled after 0s
=== UI/UX (Phase 14 + 15) ===
- Remove 'body' field from showing as custom badge (added to STANDARD_KEYS)
- Capitalize doc type: 'documentation' → 'Documentation', 'writeup' → 'Writeup'
- Sidebar tree: border-l per depth level + section separators (tee-style)
- Homepage tree: use doc titles from DB (not path segments)
- Centralize section config in packages/config/src/sections.ts (no hardcode in UI)
- Client-safe config entrypoint: @mcpedia/config/sections (avoids node:fs in client)

=== CI/CD (Phase 15b) ===
- Bump actions/checkout v4 → v5 (Node 20 deprecation)
- Fix: 'bun --cwd X run Y' doesn't work (bun run rejects --cwd flag)
  → use 'working-directory: X' instead
- Fix: .next/ is a hidden directory — upload-artifact needs include-hidden-files: true
- Merge CI + Deploy into single workflow (workflow_run can't share artifacts)
- VPS no longer builds: CI builds .next/ → uploads artifact → VPS deploys via tarball+scp+ssh
- MCP smoke test made conditional on DATABASE_URL (CI has no Postgres)
2026-08-21 12:59:05 +07:00
asepharyana f14f3e92c5 debug: use absolute path for upload-artifact 2026-08-21 12:13:11 +07:00
94 changed files with 7028 additions and 2107 deletions

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
name: Dependabot Auto-Merge
on: pull_request
permissions:
contents: write
pull-requests: write
jobs:
auto-merge:
runs-on: ubuntu-latest
if: github.actor == 'dependabot[bot]'
steps:
- name: Enable auto-merge for Dependabot PR
run: gh pr merge --auto --merge "$PR_URL"
env:
PR_URL: ${{ github.event.pull_request.html_url }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+18
View File
@@ -0,0 +1,18 @@
version: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "daily"
open-pull-requests-limit: 10
groups:
production:
dependency-type: "production"
update-types:
- "minor"
- "patch"
development:
dependency-type: "development"
update-types:
- "minor"
- "patch"
+280 -67
View File
@@ -6,14 +6,20 @@ on:
pull_request:
branches: [main]
# Cancel in-progress runs for the same ref so a fresh push supersedes them.
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
env:
VPS_HOST: ${{ secrets.SSH_DEPLOY_HOST }}
VPS_USER: ${{ secrets.SSH_DEPLOY_USER }}
permissions:
contents: read
jobs:
build:
name: typecheck + build
test:
name: typecheck + tests
runs-on: ubuntu-latest
steps:
- name: Checkout
@@ -22,92 +28,299 @@ jobs:
- name: Set up Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: "1.3.14"
bun-version: "1.4.0"
- name: Install dependencies
run: bun install --frozen-lockfile
# Real build: typecheck + turbo across all workspace packages.
- name: Typecheck
run: bun run typecheck
- name: Build web
working-directory: apps/web
run: bun run build
- name: List .next contents
working-directory: apps/web
run: ls -la .next/ | head -10
# Smoke: verify the MCP server + resources load and the indexer/module
# graph resolves. Requires Postgres + Redis — only runs when available.
- name: MCP smoke test
if: env.DATABASE_URL != ''
working-directory: apps/mcp
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
REDIS_URL: ${{ secrets.REDIS_URL }}
run: bun run smoke
# Unit tests across all packages + apps. CI has no Postgres/Redis, so
# tests use bun:test module mocking to stub @mcpedia/db, @mcpedia/queue,
# and @mcpedia/embeddings — no live I/O.
- name: Test
run: bun run test
# Upload the built .next directory as a deploy artifact.
# The deploy job copies this directly to the VPS — no build needed there.
- name: Upload web build artifact
# Build .next for web — Next.js/Turbopack has a Bun incompatibility
# in the Nix sandbox. The web derivation (web.nix) packages this
# pre-built .next into a Nix store path.
- name: Build Next.js .next
working-directory: apps/web
run: bun run build
- name: Tar .next
run: tar -C apps/web --exclude='.next/cache' -czf web-next.tar.gz .next
- name: Upload web .next artifact
uses: actions/upload-artifact@v4
with:
name: mcpedia-web-build
path: apps/web/.next
retention-days: 1
name: mcpedia-web-next
path: web-next.tar.gz
if-no-files-found: error
deploy:
name: deploy to VPS
needs: build
build-and-deploy:
name: build + deploy (Nix) — ${{ matrix.service }}
needs: test
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
service: [api, mcp, worker]
steps:
- name: Checkout
uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Install Nix
uses: DeterminateSystems/nix-installer-action@v16
with:
determinate: false
extra-conf: |
sandbox = false
accept-flake-config = true
# Attic caches as substituters: lets CI pull the prebuilt attic
# client (and any cached deps/builds) over HTTPS.
extra-substituters = https://attic.asepharyana.my.id/gmw https://attic.asepharyana.my.id/mcpedia
extra-trusted-public-keys = gmw:Fq2Anzuhkb+T/hftWnPcveHSi21/RzIgIOeG8pCJa88= mcpedia:MNAtF2xaeKSFFVu7r3zOp2Jktu1jKHIQmcT+ePEfv9o=
- name: Cache Nix
uses: DeterminateSystems/magic-nix-cache-action@v14
with:
use-flakehub: false
- name: Build ${{ matrix.service }}
id: build
run: |
nix build ".#${{ matrix.service }}" --impure --option sandbox false --print-build-logs
STORE_PATH=$(readlink result)
echo "store-path=$STORE_PATH" >> "$GITHUB_OUTPUT"
echo "Build OK ${{ matrix.service }}: $STORE_PATH"
- name: Setup SSH key
env:
SSH_KEY: ${{ secrets.SSH_DEPLOY_KEY }}
run: |
mkdir -p ~/.ssh
echo "$SSH_KEY" > ~/.ssh/id_ed25519
chmod 600 ~/.ssh/id_ed25519
sed -i 's/\r$//' ~/.ssh/id_ed25519
ssh-keygen -y -f ~/.ssh/id_ed25519 >/dev/null 2>&1 || { echo "SSH key invalid"; exit 1; }
ssh-keyscan -H "$VPS_HOST" >> ~/.ssh/known_hosts 2>/dev/null
chmod 600 ~/.ssh/known_hosts
# ── Push build to Attic binary cache ───────────────────────────────
# Bootstrap the attic client from the gmw cache (pre-built closure,
# pulled over HTTPS via the configured extra-substituters), then
# push to the mcpedia cache. This is FASTER than nix copy --to ssh://
# because the VPS substitutes (downloads) from the cache over HTTPS
# instead of a single-stream SSH copy.
- name: Push to Attic cache
id: push-attic
env:
ATTIC_TOKEN: ${{ secrets.ATTIC_TOKEN }}
STORE_PATH: ${{ steps.build.outputs.store-path }}
run: |
ATTIC_DIR="/nix/store/fygyy3yk4rqdknxkiwkqambpnhyax0k4-attic-0.1.0"
mkdir -p "$HOME/.config/attic"
cat > "$HOME/.config/attic/config.toml" <<EOF
default-server = "pub"
[servers.pub]
endpoint = "https://attic.asepharyana.my.id"
token = "$ATTIC_TOKEN"
EOF
ATTIC_BIN=""
# Fast path: pull attic client from gmw cache
if nix-store --realise "$ATTIC_DIR" 2>/dev/null; then
ATTIC_BIN="$ATTIC_DIR/bin/attic"
fi
push_ok=""
if [ -n "$ATTIC_BIN" ] && [ -x "$ATTIC_BIN" ]; then
for attempt in 1 2 3; do
if "$ATTIC_BIN" push pub:mcpedia "$STORE_PATH" --jobs 4 --ignore-upstream-cache-filter; then
echo "✅ Pushed $STORE_PATH to Attic"
push_ok=1
break
fi
echo "⚠️ Attic push attempt $attempt/3 failed; retrying in 10s..."
sleep 10
done
fi
if [ -z "$push_ok" ]; then
echo "Attic push failed; copying store path directly to VPS"
nix copy --to "ssh://${VPS_USER}@${VPS_HOST}" "$STORE_PATH"
echo "push-fallback=ssh" >> "$GITHUB_OUTPUT"
else
echo "push-method=attic" >> "$GITHUB_OUTPUT"
fi
- name: Deploy on VPS
env:
STORE_PATH: ${{ steps.build.outputs.store-path }}
SERVICE: ${{ matrix.service }}
VPS_HOST: ${{ secrets.SSH_DEPLOY_HOST }}
VPS_USER: ${{ secrets.SSH_DEPLOY_USER }}
run: |
PROFILE="mcpedia-${SERVICE}"
# Substitute from Attic cache (fast — downloads over HTTPS)
# Falls back to SSH copy if substitution fails
REALISE_RESULT=$(ssh "$VPS_USER@$VPS_HOST" \
"sudo /nix/var/nix/profiles/default/bin/nix-store --realise '$STORE_PATH' 2>&1 || true")
echo "$REALISE_RESULT"
# Update profile + sync git repo + restart
ssh "$VPS_USER@$VPS_HOST" \
"sudo /nix/var/nix/profiles/default/bin/nix-env \
--profile /nix/var/nix/profiles/$PROFILE \
--set '$STORE_PATH' && \
(cd /home/code/mcpedia && git fetch origin main && git reset --hard origin/main || true) && \
sudo systemctl restart $PROFILE && \
sleep 3 && \
sudo systemctl status $PROFILE --no-pager --no-legend | head -5"
- name: Verify service
env:
VPS_HOST: ${{ secrets.SSH_DEPLOY_HOST }}
VPS_USER: ${{ secrets.SSH_DEPLOY_USER }}
SERVICE: ${{ matrix.service }}
run: |
PORT_MAP="api:4017 mcp:4021 worker:4018"
PORT=$(echo "$PORT_MAP" | grep "$SERVICE" | awk -F: '{print $2}')
ssh "$VPS_USER@$VPS_HOST" \
"curl -s -o /dev/null -w '%{http_code}' http://localhost:$PORT/health 2>/dev/null \
|| systemctl is-active \"mcpedia-$SERVICE\""
deploy-web:
name: build + deploy (web)
needs: test
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Download build artifact
- name: Set up Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: "1.4.0"
- name: Install Nix
uses: DeterminateSystems/nix-installer-action@v16
with:
determinate: false
extra-conf: |
sandbox = false
accept-flake-config = true
extra-substituters = https://attic.asepharyana.my.id/gmw https://attic.asepharyana.my.id/mcpedia
extra-trusted-public-keys = gmw:Fq2Anzuhkb+T/hftWnPcveHSi21/RzIgIOeG8pCJa88= mcpedia:MNAtF2xaeKSFFVu7r3zOp2Jktu1jKHIQmcT+ePEfv9o=
- name: Cache Nix
uses: DeterminateSystems/magic-nix-cache-action@v14
with:
use-flakehub: false
- name: Download web .next artifact
uses: actions/download-artifact@v4
with:
name: mcpedia-web-build
path: .next
name: mcpedia-web-next
path: /tmp/web-next
- name: Copy pre-built .next to VPS
uses: appleboy/scp-action@v1
with:
host: ${{ secrets.SSH_DEPLOY_HOST }}
port: ${{ secrets.SSH_DEPLOY_PORT }}
username: ${{ secrets.SSH_DEPLOY_USER }}
key: ${{ secrets.SSH_DEPLOY_KEY }}
source: ".next/*"
target: "/home/code/mcpedia/apps/web/.next"
- name: Unpack .next
run: tar -xzf /tmp/web-next/web-next.tar.gz -C apps/web/
- name: Deploy to VPS over SSH
uses: appleboy/ssh-action@v1
with:
host: ${{ secrets.SSH_DEPLOY_HOST }}
port: ${{ secrets.SSH_DEPLOY_PORT }}
username: ${{ secrets.SSH_DEPLOY_USER }}
key: ${{ secrets.SSH_DEPLOY_KEY }}
envs: SSH_DEPLOY_HOST
script: |
set -e
cd /home/code/mcpedia
- name: Install deps (for bunx in web.nix)
run: bun install --frozen-lockfile
# Pull latest code (for content, .env, and non-web changes)
git pull origin main
/home/code/.bun/bin/bun install --frozen-lockfile
/home/code/.bun/bin/bun run scripts/indexer.ts
- name: Build web Nix derivation
id: build
run: |
REPO_ROOT="$(pwd)"
nix-build -E \
"let pkgs = import <nixpkgs> {}; in pkgs.callPackage ${REPO_ROOT}/web.nix {
webNextDir = ${REPO_ROOT}/apps/web/.next;
}" \
--impure --option sandbox false
STORE_PATH=$(readlink result)
echo "store-path=$STORE_PATH" >> "$GITHUB_OUTPUT"
# The .next/ was just copied from CI (pre-built, no build on VPS)
# Restart services to pick up the new build
sudo systemctl restart mcpedia-web mcpedia-api mcpedia-mcp mcpedia-worker
sleep 3
systemctl --no-pager status mcpedia-web mcpedia-api mcpedia-mcp mcpedia-worker --no-legend
- name: Setup SSH key
env:
SSH_KEY: ${{ secrets.SSH_DEPLOY_KEY }}
run: |
mkdir -p ~/.ssh
echo "$SSH_KEY" > ~/.ssh/id_ed25519
chmod 600 ~/.ssh/id_ed25519
sed -i 's/\r$//' ~/.ssh/id_ed25519
ssh-keygen -y -f ~/.ssh/id_ed25519 >/dev/null 2>&1 || { echo "SSH key invalid"; exit 1; }
ssh-keyscan -H "$VPS_HOST" >> ~/.ssh/known_hosts 2>/dev/null
chmod 600 ~/.ssh/known_hosts
- name: Push to Attic cache
id: push-attic
env:
ATTIC_TOKEN: ${{ secrets.ATTIC_TOKEN }}
STORE_PATH: ${{ steps.build.outputs.store-path }}
run: |
ATTIC_DIR="/nix/store/fygyy3yk4rqdknxkiwkqambpnhyax0k4-attic-0.1.0"
mkdir -p "$HOME/.config/attic"
cat > "$HOME/.config/attic/config.toml" <<EOF
default-server = "pub"
[servers.pub]
endpoint = "https://attic.asepharyana.my.id"
token = "$ATTIC_TOKEN"
EOF
ATTIC_BIN=""
if nix-store --realise "$ATTIC_DIR" 2>/dev/null; then
ATTIC_BIN="$ATTIC_DIR/bin/attic"
fi
push_ok=""
if [ -n "$ATTIC_BIN" ] && [ -x "$ATTIC_BIN" ]; then
for attempt in 1 2 3; do
if "$ATTIC_BIN" push pub:mcpedia "$STORE_PATH" --jobs 4 --ignore-upstream-cache-filter; then
echo "✅ Pushed $STORE_PATH to Attic"
push_ok=1
break
fi
echo "⚠️ Attic push attempt $attempt/3 failed; retrying in 10s..."
sleep 10
done
fi
if [ -z "$push_ok" ]; then
echo "Attic push failed; copying store path directly to VPS"
nix copy --to "ssh://${VPS_USER}@${VPS_HOST}" "$STORE_PATH"
fi
- name: Deploy on VPS
env:
STORE_PATH: ${{ steps.build.outputs.store-path }}
VPS_HOST: ${{ secrets.SSH_DEPLOY_HOST }}
VPS_USER: ${{ secrets.SSH_DEPLOY_USER }}
run: |
# Update profile + sync git repo + sync .next + restart
ssh "$VPS_USER@$VPS_HOST" \
"sudo /nix/var/nix/profiles/default/bin/nix-store --realise '$STORE_PATH' && \
sudo /nix/var/nix/profiles/default/bin/nix-env \
--profile /nix/var/nix/profiles/mcpedia-web \
--set '$STORE_PATH' && \
(cd /home/code/mcpedia && git fetch origin main && git reset --hard origin/main) && \
sudo rm -rf /home/code/mcpedia/apps/web/.next && \
sudo cp -r '$STORE_PATH/share/mcpedia-web/.next' /home/code/mcpedia/apps/web/.next && \
sudo systemctl restart mcpedia-web && \
sleep 3 && \
sudo systemctl status mcpedia-web --no-pager --no-legend | head -5"
- name: Verify public URL
env:
VPS_HOST: ${{ secrets.SSH_DEPLOY_HOST }}
VPS_USER: ${{ secrets.SSH_DEPLOY_USER }}
run: |
ssh "$VPS_USER@$VPS_HOST" \
"curl -sk -o /dev/null -w '%{http_code}' https://wiki.asepharyana.my.id/"
+6
View File
@@ -43,3 +43,9 @@ next-env.d.ts
# monorepo / turbo
.turbo/
dist/
# MCPedia content — DB is source of truth via MCP API (create_document/update_document)
# Filesystem .md files are auto-generated backups, not tracked in git.
# To edit content: use the MCP create_document/update_document tools (requires x-webhook-secret)
content/**/*.md
!content/**/.gitkeep
+227
View File
@@ -0,0 +1,227 @@
# MCPedia Frontend Redesign — Spec
Status: DRAFT — minta approval sebelum coding
Date: 2026-09-08 WIB
Author: Hermes
## 1. Tujuan
Merombak `apps/web` agar:
- Satu sumber kebenaran: semua data berasal dari `@mcpedia/core` types & `@mcpedia/config` section presets; tidak ada shape duplikat di FE.
- Selaras dengan gateway/BE data flow: tRPC `apps/api` (`/trpc/*`) + REST `/api/*` + MCP `:4021` semua mengembalikan shape yang sama (DocumentMeta, SectionInfo, SearchHit, ExportData).
- Ganti pola fetch ad-hoc (`fetch("/api/...")` tersebar) dengan **SWR** terpusat — cache, revalidate, mutate, optimistic UI, error boundary konsisten.
- Hapus sisa TanStack (saat ini tidak ada deps TanStack — audit `apps/web/package.json` clean; tapi pola akan dibakukan supaya tidak masuk lagi).
- UI: Archival Precision tetap (monochrome, hairline, mono telemetry), tapi lebih live dan terisi data real (bukan placeholder).
## 2. Audit Status Quo
### FE sekarang
- Next.js 16.3.4, App Router, `force-dynamic` di semua page yang baca DB.
- RSC langsung import `@mcpedia/core` (`listDocuments`, `getDocument`, `listSections`, `getRelated`, `listRevisions`, `getExportDocuments`). SEO bagus, tapi client components (Sidebar, Header, Search, CommandMenu) fetch ulang via REST tanpa cache sharing.
- REST: `/api/search?q&mode&limit`, `/api/docs` (list), `/api/sections`, `/api/export?path&sort`, `/api/revisions/restore`, `/api/auth/login`.
- tRPC `apps/api` (Hono) expose: search/semanticSearch/hybridSearch, getDocument, listDocuments, sections, related, revisions, CRUD (gated `x-webhook-secret`), jobStatus, reindex hooks, `/health`, `/metrics`.
- MCP `:4021` Streamable HTTP `/mcp` expose 13 tools (tidak dipakai FE, tapi shape-nya sama).
- Tidak ada `swr` / `@tanstack/react-query` di `apps/web/package.json` — jadi migrasi = greenfield SWR layer, bukan replace.
- Design tokens sudah rapi di `globals.css` (CSS vars light/dark + `--brand`, `--bg-*`, `--text-*`, `--code-*`). Header/Sidebar/Markdown/TOC/DocActions sudah pakai tokens.
### Masalah yang diselesaikan redesign
1. Sidebar & Header fetch `/api/docs` + `/api/sections` tanpa deduplikasi — tiap navigasi fetch ulang, tidak ada stale-while-revalidate.
2. Search page client-side `fetch` manual tanpa debounce terpusat, tanpa cache antar-mode (hybrid/keyword/semantic saling overwrite).
3. Doc page RSC tidak live: setelah create/update/delete atau reindex, harus hard refresh. Tidak ada `mutate` cross-component.
4. Shape drift: Search `snippet` vs `SearchHit` vs `ChunkHit` tidak konsisten antara `/api/search` dan `@mcpedia/search` — perlu typed fetcher.
5. Tidak ada surface untuk queue/embeddings status (BE punya `jobStatus`, `queueStatus`, `INDEX_QUEUE` BullMQ) — FE buta terhadap indexing.
## 3. Arsitektur Target
```
apps/web/app/
lib/
fetcher.ts — typed fetcher (fetch JSON + error envelope)
swr.ts — SWRConfig global (dedupingInterval, focusThrottle, errorRetry)
api.ts — typed client untuk /api/* (listDocuments, search, sections, export, revisions)
hooks/
useSections.ts — SWR '/api/sections' -> SectionInfo[]
useDocuments.ts — SWR '/api/docs?section&status' -> DocumentMeta[]
useDocument.ts — SWR '/api/docs/:slug' (baru, GET single) -> Document
useSearch.ts — SWR key [q, mode, limit] -> SearchHit[] + debounced
useRelated.ts — SWR '/api/related?slug'
useRevisions.ts — SWR '/api/revisions?slug'
useQueueStatus.ts — SWR '/api/queue/status' poll 5s (opsional, admin only)
components/
(existing: Header, Sidebar, CommandMenu, Markdown, TOC, DocActions, ...)
SearchBar.tsx — reusable, dipakai Header + Search page + CommandMenu
SectionCard.tsx — extract dari page.tsx
DocumentCard.tsx — reusable card (recent, related, folder list)
TagCloud.tsx — baru: agregasi tags dari docs
QueueBadge.tsx — baru: show indexing status (waiting/active/failed)
EmptyState.tsx / ErrorState.tsx
app/
layout.tsx — tambah <SWRProvider> wrapper (client boundary)
page.tsx — refactor: RSC shell + client islands via SWR
[section]/page.tsx — sama
[section]/[...slug]/page.tsx — RSC hero + Markdown, client islands (related/revisions via SWR)
search/page.tsx — fully SWR, hapus useState fetch manual
create/page.tsx — mutate after create
dashboard/page.tsx — BARU (optional phase 2): queue, sections, recent, tag stats
```
### Prinsip SWR
- Satu `fetcher` generic: `fetcher<T>(url: string): Promise<T>` — throw on !ok dengan `info` + `status` untuk error boundary.
- `SWRConfig` di `layout.tsx` client wrapper: `dedupingInterval: 4000`, `focusThrottleInterval: 10000`, `shouldRetryOnError: false` untuk search, `refreshInterval` hanya untuk queue.
- Semua hooks pakai key array/string yang deterministic supaya `mutate` cross-page bisa: `mutate('/api/docs')`, `mutate('/api/sections')`.
- Debounce search di hook, bukan di component: `useDebouncedValue(q, 180ms)` internal ke `useSearch`.
- Optimistic mutate untuk create/update/delete: `mutate('/api/docs', optimisticList, false)` lalu revalidate.
## 4. Kontrak Data (FE ↔ BE)
Semua types import dari `@mcpedia/types` — tidak ada re-declare shape di FE.
| FE Hook | BE Source | Endpoint | Shape |
|---------|-----------|----------|-------|
| useSections | `listSections()` | `GET /api/sections` | `SectionInfo[]` |
| useDocuments | `listDocuments({section,status})` | `GET /api/docs?section=&status=` | `DocumentMeta[]` |
| useDocument | `getDocument(slug)` | `GET /api/docs/:slug` (baru) | `Document` |
| useSearch | `keywordSearch/hybridSearch/semanticSearch` | `GET /api/search?q&mode&limit` | `{results: {slug,title,section,score,snippet}[]}` |
| useRelated | `getRelated(slug)` | `GET /api/related?slug=` (baru, atau reuse via core) | `DocumentMeta[]` |
| useRevisions | `listRevisions(slug)` | `GET /api/revisions?slug=` (baru) | `Revision[]` |
| useQueueStatus | BullMQ `getQueue()` | `GET /api/queue/status` (baru, proxy ke apps/api /metrics atau queue) | `{waiting,active,completed,failed,delayed}` |
**Tambahan endpoint yang perlu dibuat (tipis, proxy ke core):**
- `GET /api/docs/[slug]` — single doc (hindari RSC-only fetch, enable SWR).
- `GET /api/related?slug=&limit=` — wrapper `getRelated`.
- `GET /api/revisions?slug=&limit=` — wrapper `listRevisions`.
- `GET /api/queue/status` — wrapper `getQueue().get*Count()` (admin-only atau public read-only).
- (Opsional) `GET /api/tags` — agregasi tags dari `listDocuments` untuk TagCloud.
Semua endpoint return envelope sama: `{data}` atau `{results}` + `{error}` on 500, dengan `Content-Type: application/json`. Auth untuk mutasi tetap `x-webhook-secret` atau cookie `mcpedia_admin`.
## 5. Perubahan Per-File (Rincian)
### Phase 0 — Foundation (wajib)
- `apps/web/package.json`: tambah `swr: ^2.3.x` (latest 2.x). Tidak tambah TanStack. `bun install` + cek `typecheck`.
- `apps/web/app/lib/fetcher.ts` (baru): `export const fetcher = <T>(url: string): Promise<T> => fetch(url).then(r => { if(!r.ok) throw ...; return r.json() })`
- `apps/web/app/lib/swr.tsx` (baru): `SWRProvider` client component wrapping `SWRConfig`.
- `apps/web/app/lib/api.ts` (baru): typed helpers `searchDocs(q,mode,limit)`, `listDocs()`, `listSections()` — dipakai hooks.
- `apps/web/app/layout.tsx`: bungkus children dengan `<SWRProvider>` (client boundary minimal).
### Phase 1 — Hooks + Refactor Existing Pages
- `hooks/useSections.ts`, `useDocuments.ts`, `useSearch.ts`: ganti `useEffect+fetch` di `Header.tsx`, `Sidebar.tsx`, `search/page.tsx`, `CommandMenu.tsx`, `page.tsx` (home).
- `Header.tsx`: `useSections()` alih-alih `useState+useEffect fetch /api/sections`.
- `Sidebar.tsx`: `useDocuments()` + `useSections()` + filter memo — hilangkan `useEffect fetch /api/docs`.
- `search/page.tsx`: `useSearch(q, mode)` — hapus `handleSearch` manual, pakai `isLoading`, `isValidating`, `error` dari SWR. Mode & section filter tetap local state, tapi key SWR mencakup keduanya.
- `CommandMenu.tsx`: `useSearch(query)` debounced — hapus timer manual.
- `app/page.tsx`: tetap RSC untuk SEO (listDocuments/listSections server), tapi `SectionTree` dan `Recently Updated` bisa jadi client islands yang pakai SWR untuk live update (opsional: keep RSC + `mutate` on focus).
- `[section]/page.tsx` & `[section]/[...slug]/page.tsx`: RSC hero + Markdown tetap, `related` & `revisions` pindah ke client islands `RelatedGrid` & `RevisionList` pakai `useRelated`/`useRevisions`.
### Phase 2 — Fitur Baru (detail)
1. **Dashboard `/dashboard` (baru, admin-aware):**
- Cards: total docs, sections, queue (waiting/active/failed), embedding provider status.
- Section breakdown bar (docCount per section).
- Tag cloud (top 20 tags dengan count).
- Recent activity (last 10 updated docs).
- Queue status poll 5s via `useQueueStatus` (hanya jika admin cookie ada, else hide).
2. **Tag Explorer `/tags` atau sidebar widget:**
- `GET /api/tags` agregasi, klik tag → `/search?tag=...` atau filter docs.
3. **Doc page enhancements:**
- `QueueBadge` di hero jika doc sedang di-index (query queue by slug).
- Optimistic revision restore: `mutate('/api/revisions?slug=...')` setelah POST restore.
- Related docs pakai SWR + `keepPreviousData`.
4. **Search enhancements:**
- Persist `mode` di URL (`?q=&mode=hybrid`) — sudah ada, pertahankan + SWR key sync.
- Highlight snippet `mark` sudah ada — pertahankan.
- Empty & error states pakai `EmptyState`/`ErrorState` components.
5. **Create/Edit:**
- Setelah `POST /api/docs`, `mutate('/api/docs')` + `mutate('/api/sections')` + `router.push('/${slug}')`.
- Custom fields (extraFields) tetap flat → `splitPayload` di BE tidak berubah.
6. **Export:**
- `PdfExportView` tetap, tapi tambah SWR preload `getExportDocuments` untuk preview count sebelum export.
### Phase 3 — Polish & Cleanup
- Hapus semua `fetch` ad-hoc yang tersisa — semua lewat hooks.
- Pastikan `globals.css` tokens dipakai konsisten (tidak ada hard-coded hex baru).
- `CommandMenu` jadi satu-satunya omnisearch entry — `Header` search icon di mobile buka CommandMenu, bukan link `/search`.
- A11y: `aria-live` untuk search results count, `role="status"` untuk queue badge.
- Print/PDF styles sudah ada — tidak diubah.
## 6. File yang Disentuh (Checklist)
Baru:
- `apps/web/app/lib/fetcher.ts`
- `apps/web/app/lib/swr.tsx`
- `apps/web/app/lib/api.ts`
- `apps/web/app/hooks/useSections.ts`
- `apps/web/app/hooks/useDocuments.ts`
- `apps/web/app/hooks/useSearch.ts`
- `apps/web/app/hooks/useRelated.ts`
- `apps/web/app/hooks/useRevisions.ts`
- `apps/web/app/hooks/useQueueStatus.ts`
- `apps/web/app/hooks/useTags.ts` (opsional)
- `apps/web/app/components/SearchBar.tsx`
- `apps/web/app/components/SectionCard.tsx`
- `apps/web/app/components/DocumentCard.tsx`
- `apps/web/app/components/TagCloud.tsx`
- `apps/web/app/components/QueueBadge.tsx`
- `apps/web/app/components/EmptyState.tsx`
- `apps/web/app/dashboard/page.tsx` (baru)
- `apps/web/app/api/docs/[slug]/route.ts` (baru)
- `apps/web/app/api/related/route.ts` (baru)
- `apps/web/app/api/revisions/route.ts` (baru GET)
- `apps/web/app/api/queue/status/route.ts` (baru)
- `apps/web/app/api/tags/route.ts` (baru, opsional)
Edit:
- `apps/web/package.json` (+ swr)
- `apps/web/app/layout.tsx` (+ SWRProvider)
- `apps/web/app/page.tsx` (extract SectionCard, optional SWR islands)
- `apps/web/app/[section]/page.tsx` (DocumentCard)
- `apps/web/app/[section]/[...slug]/page.tsx` (related/revisions islands)
- `apps/web/app/search/page.tsx` (full SWR)
- `apps/web/app/components/Header.tsx` (useSections)
- `apps/web/app/components/Sidebar.tsx` (useDocuments/useSections)
- `apps/web/app/components/CommandMenu.tsx` (useSearch)
- `apps/web/app/create/page.tsx` (mutate)
- `apps/web/app/components/DocForm.tsx` (mutate setelah submit)
Tidak disentuh:
- `packages/core`, `packages/types`, `packages/config`, `packages/db` (hanya dibaca)
- `apps/api`, `apps/mcp`, `apps/worker` (hanya diproxy)
- `globals.css`, `next.config.ts`, `tailwind` config (kecuali perlu token baru)
## 7. Urutan Implementasi
1. Phase 0 foundation → `bun install && bun run typecheck` green.
2. Phase 1 hooks + Header/Sidebar/Search/CommandMenu → manual test + `next build` smoke.
3. Phase 2 doc page islands + create mutate → test CRUD flow dengan `x-webhook-secret` / admin cookie.
4. Phase 2 dashboard + tags → behind `canEdit` guard jika perlu.
5. Phase 3 cleanup, hapus fetch manual, final `bun run lint && typecheck && build`.
## 8. Verifikasi
- `bun run typecheck` — tidak ada error (SWR types + @mcpedia/types).
- `bun run lint` — rules Next 16 ok.
- `bun --cwd apps/web run build` — semua route `force-dynamic` OK, tidak ada import-time DB throw.
- Manual:
- Sidebar filter + section count live setelah create doc.
- Search mode switch (hybrid/keyword/semantic) cache terpisah, tidak flicker.
- CommandMenu ⌘K debounce 180ms, Enter navigasi benar.
- Doc related & revisions muncul via SWR tanpa hard refresh.
- Queue badge (jika ada) poll 5s, tidak spam (dedupingInterval).
- Dark/light toggle tetap work (SWRProvider tidak break `ThemeToggle`).
- Staging: `curl /api/search?q=test&mode=hybrid`, `/api/sections`, `/api/docs` return shape konsisten dengan tRPC.
## 9. Risiko & Mitigasi
- RSC + SWR double fetch: mitigasi dengan `fallbackData` dari RSC props ke SWR hook di islands (opsi, tidak wajib v1).
- Peningkatan request ke DB: SWR deduping 4s + `revalidateOnFocus: false` untuk search, `true` untuk sections/docs.
- Auth untuk `/api/queue/status`: jadikan public read-only (hanya counts, bukan detail job) — aman.
## 10. Keputusan yang Perlu Kamu Konfirmasi
1. **Dashboard `/dashboard` perlu tidak?** Atau cukup queue badge di existing pages? Rekomendasi: bikin, tapi Phase 2 — bisa ditunda.
2. **Endpoint baru (`/api/docs/[slug]`, `/api/related`, `/api/revisions` GET, `/api/queue/status`, `/api/tags`) setuju?** Alternatif: FE langsung pakai tRPC client (`@trpc/client`) — tapi spec ini pilih REST `/api/*` supaya Next cache & SWR fetcher simpel.
3. **SWR vs tRPC+SWR?** Spec ini pakai SWR+REST (paling simpel, tidak tambah `@trpc/client` di FE). Jika mau tRPC, tambah `createTRPCClient` + `httpBatchLink` — tradeoff: lebih typed tapi lebih berat. Default: SWR+REST.
4. **Keep RSC server fetch untuk SEO atau full client SWR?** Rekomendasi: keep RSC untuk initial HTML (SEO), SWR untuk live revalidation di client islands — hybrid, bukan full SWR.
---
Jawab: `Lanjut Phase 0+1` untuk eksekusi, atau beri koreksi poin 10.
+49
View File
@@ -0,0 +1,49 @@
# MCPedia — Nix-based CI/CD Migration Plan
## Goal
Migrate from tarball+SSH deploy to Nix-native build-and-deploy (like GMW).
CI builds with Nix in GitHub Actions → `nix copy` closure to VPS →
`nix-env --set` + `systemctl restart` on VPS. VPS never builds.
## Services to migrate
| Service | Build | Runtime | systemd unit |
|---------|-------|---------|-------------|
| web (Next.js) | `bun run build` → `.next` | `next start` | `mcpedia-web` |
| api (Hono) | `bun build src/index.ts` → `dist/index.js` | `bun run src/index.ts` | `mcpedia-api` |
| mcp (MCP server) | `bun build src/http.ts` → `dist/http.js` | `bun run src/http.ts` | `mcpedia-mcp` |
| worker (BullMQ) | `bun build src/index.ts` → `dist/index.js` | `bun run src/index.ts` | `mcpedia-worker` |
## Changes
### 1. flake.nix (new)
- `nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"` (Bun >=1.3)
- 4 packages: `web`, `api`, `mcp`, `worker`
- Each: `mkDerivation` with `bun` as nativeBuildInput, `sandbox=false`
- Filter source to exclude `.next`, `node_modules`, `.git`
### 2. CI workflow (.github/workflows/ci.yml — rewrite)
- `test` job: typecheck + test (Bun, as before)
- `build-and-deploy` job: matrix [web, api, mcp, worker]
- `DeterminateSystems/nix-installer-action@v16` with `determinate: false`, `sandbox=false`
- `DeterminateSystems/magic-nix-cache-action@v14` with `use-flakehub: false`
- `nix build .#<service>` → store path
- SSH setup (key sanitization)
- `nix copy --to ssh://...`
- `nix-env --profile /nix/var/nix/profiles/mcpedia-<service> --set <path>`
- `systemctl restart mcpedia-<service>`
### 3. systemd units (update on VPS)
- Change `ExecStart` from `bun run` to Nix profile binary path
- Profile path: `/nix/var/nix/profiles/mcpedia-web/bin/mcpedia-web`
- Keep `EnvironmentFile` pointing to `.env`
- Keep `Restart=always`
### 4. Deploy secrets
- `SSH_PRIVATE_KEY` (already exists as `SSH_DEPLOY_KEY`)
- `VPS_HOST`, `VPS_USER`, `VPS_SSH_PORT`
## Verification
- `nix build .#web --impure` builds
- `gh run list` shows all 4 services `completed success`
- `curl https://wiki.asepharyana.my.id/` returns 200
- `journalctl -u mcpedia-web` shows Next.js started
+26 -28
View File
@@ -1,35 +1,33 @@
# Phase 15 — Nix-based CI/CD for mcpedia-web
# Phase 15b — CI/CD: Build in CI, Deploy only on VPS
> User: "ci nya juga benarkan lah masa build di vps,harusnya kan di vps hanya deploy, dan seharusnya pakai nix"
> User: "alur ci nya juga benarkan lah masa build di vps,harusnya kan di vps hanya deploy, dan seharusnya pakai nix"
## Current State
- Deploy workflow builds the web app ON the VPS via SSH (`cd apps/web && bun run build`)
- mcpedia-web service runs directly from git checkout (`/home/code/mcpedia/apps/web/.next`)
- No flake.nix in the repo
- Other services (zeavis-*, gmw-*) are nix-deployed via `/nix/var/nix/profiles/<name>`
## Final Architecture
## Goal
- **CI**: builds the web app into a Nix store path
- **Deploy**: VPS only copies + switches profiles (no build on VPS)
### CI Workflow (`.github/workflows/ci.yml`)
Single workflow with two jobs:
## Approach: `nix build` + `nix copy` (push deployment)
**Job 1: `build`** (runs on GitHub Actions runner)
1. Checkout → Set up Bun 1.3.14 → `bun install --frozen-lockfile`
2. Typecheck (`bun run typecheck`)
3. Build web (`working-directory: apps/web && bun run build`) ← **Build happens here, not VPS**
4. Upload `.next/` as artifact (`include-hidden-files: true` ← critical for hidden `.next/` dir)
5. MCP smoke test (conditional on DATABASE_URL secret — skipped in CI without DB)
6. Unit tests (`bun run test`)
### 1. Add flake.nix to mcpedia repo
Build the Next.js production output into a Nix package:
- `next build` outputs to `.next/`
- Package: a shell script that runs `next start` with the `.next` dir + `node_modules`
**Job 2: `deploy`** (needs: build, main branch only)
1. Download artifact to `apps/web/.next`
2. Tar `.next` (exclude cache, ~15MB tarball)
3. SCP tarball to VPS (`/tmp/`)
4. SSH to VPS: `git pull` → `bun install` → `bun run scripts/indexer.ts` → `tar -xzf` → `systemctl restart`
### 2. CI workflow (`ci.yml`)
- Add a `nix build` step after typecheck/test
- Push the result to the VPS via `nix copy --ssh`
### Key Fixes During This Phase
### 3. Deploy workflow (`deploy.yml`)
- Trigger on CI success
- `nix copy` the built package to VPS
- `nix profile install` / `systemctl restart` on VPS
- No `bun run build` on VPS
## Files to create/modify
- `flake.nix` (new) — builds @mcpedia/web as a Nix package
- `.github/workflows/ci.yml` — add nix build step
- `.github/workflows/deploy.yml` — nix copy + profile switch instead of SSH build
1. **`actions/checkout@v4` → `@v5`** — Node 20 deprecation warning
2. **`bun --cwd apps/web run build` → `working-directory: apps/web`** — `bun run` doesn't support `--cwd` flag; was silently printing usage, exiting 0
3. **`path: apps/web/.next/`** → **`path: apps/web/.next`** + **`include-hidden-files: true`** — `.next/` is a hidden directory; `upload-artifact@v4` excludes hidden files by default
4. **`bun --cwd apps/mcp run smoke`** → **`working-directory: apps/mcp`** — same `--cwd` bug
5. **Smoke test made conditional** on `DATABASE_URL` — was silently failing (never actually ran due to bug #2/#4)
6. **SCP of individual `.next/*`** → **tarball transfer** — SCP with glob of hidden files was failing/timing out
7. **Deploy tarball excludes `.next/cache`** — cache is ephemeral, reduces transfer size
8. **Merged ci.yml + deploy.yml** into single workflow — `workflow_run` trigger can't access artifacts from CI run
+43
View File
@@ -0,0 +1,43 @@
# Phase 15c — Theme-Consistent Color System
> User: "banyak pewarnaan yg tidak sesuai tema dark mode atau light mode"
## Problem
63 hardcoded hex colors (#5e6ad2, #7170ff, #4f46e5, etc.) bypass the CSS
variable theme system in globals.css. These don't adapt between light/dark mode
properly — the `dark:` variant changes text color but background stays the same.
## Color Mapping
### `#5e6ad2` (indigo-600)
- Light: `--brand: #5e6ad2` (same)
- Dark: `--brand: #5e6ad2` (same)
→ Replace with `var(--brand)`
### `#4f46e5` (indigo-700)
- Light: `--accent: #4f46e5`
- Dark: `--accent: #7170ff`
→ Replace with `var(--accent)`
### `#7170ff` (light blue, dark mode accent)
- Light: `var(--accent)` (#4f46e5)
- Dark: `var(--accent)` (#7170ff)
→ Replace `dark:text-[#7170ff]` → `dark:text-[var(--accent)]`
### `#6a75e0` (hover lighter)
→ Replace with `var(--accent-hover)`
### `/10`, `/15`, `/20`, `/30` opacity tints
- `bg-[#5e6ad2]/15` → `bg-[var(--brand)]/15`
- `bg-[#5e6ad2]/10` → `bg-[var(--brand)]/10`
- `bg-[#5e6ad2]/30` → `bg-[var(--brand)]/30`
## Files to fix
- `[section]/[...slug]/page.tsx` (~16 instances)
- `[section]/page.tsx` (~5 instances)
- `components/Sidebar.tsx` (2 instances)
- `components/DocForm.tsx` (~6 instances)
- `components/CommandMenu.tsx` (~6 instances)
- `components/Header.tsx` (2 instances)
- `components/McpConfigSnippet.tsx` (1 instance)
- `page.tsx` (check)
@@ -0,0 +1,254 @@
# SSH deploy to bun-source services (not Nix): gotchas
This repo (`asepharyana/mcpedia`) deploys **bun source** via systemd — NOT via
Nix like GMW. The pattern is: CI builds in GitHub Actions → upload artifact →
deploy job downloads artifact → SCP tarball to VPS → SSH → git pull + unpack +
index + `systemctl restart`. The VPS does NOT build.
## Gotchas (learned during mcpedia deploy setup, 2026-08-20/21)
### 1. SSH host = public IP, NOT Tailscale IP
The VPS appears in `~/.ssh/config` as `Host orange → HostName 100.79.111.61`.
That IP is a **Tailscale `tailscale0` interface address** in the CGNAT range
(`100.64.0.0/10`). GitHub Actions runners are NOT on the Tailscale network, so
they get `Connection timed out` (dropped at the network layer, not refused).
**Fix:** Use the VPS's real public IP (`45.127.35.244`, discovered via
`curl https://api.ipify.org` from the VPS). Port 22 is open in iptables
(`ACCEPT tcp dpt:22` from `0.0.0.0/0`).
### 2. SSH key MUST be stored directly from file (not shell variable)
Storing the deploy key via a shell variable corrupts it:
```bash
# ❌ WRONG — newlines get mangled by the shell → "ssh: no key found"
PRIV_KEY=$(cat keyfile)
gh secret set SSH_DEPLOY_KEY --body "$PRIV_KEY"
# ✅ CORRECT — pipe the file directly so GitHub preserves all bytes
cat keyfile | gh secret set SSH_DEPLOY_KEY --repo asepharyana/mcpedia
```
Symptom: `appleboy/ssh-action` fails with
`ssh.ParsePrivateKey: ssh: no key found`.
### 3. Use `appleboy/ssh-action@v1` (not `@v1.1.0`)
- `@v1.1.0` (very old) has a key-parsing bug that rejects valid keys
(`ssh.ParsePrivateKey: ssh: no key found`).
- `@v1` (latest) handles OpenSSH ed25519 keys correctly.
### 4. `appleboy/ssh-action` needs explicit `envs` to pass through secret-derived vars
The `envs` parameter passes environment variables to the remote script.
Include any secret you reference in the script:
```yaml
envs: SSH_DEPLOY_HOST # passes SSH_DEPLOY_HOST into the remote script
```
Without it, `echo $SSH_DEPLOY_HOST` on the VPS returns empty even though the
action connected.
### 5. Always pass `-o IdentitiesOnly=yes`
Without it, SSH offers ALL loaded identities (deploy key + default keys) and the
server may reject after "Too many authentication failures". `appleboy/ssh-action`
handles this internally via the `key` input, but if you use raw `ssh` add
`-o IdentitiesOnly=yes`.
### 6. GitHub `workflow_run` does NOT carry the push commit SHA
`workflow_run` events fire after CI completes, but `actions/checkout` checks out
the **default branch tip**, not the specific commit. This is fine for deploy
(the script does `git pull origin main` anyway), but verify the checkout ref
matches what CI built if you rely on it.
### 7. DB migrations: `db:push` prompt is non-interactive-unfriendly in SSH deploy
When the schema includes a new column (e.g. adding `extra_fields JSONB`),
`drizzle-kit push` in the SSH deploy script needs to be run. Two issues:
- **`--strict` mode (config default)**: `drizzle.config.ts` has `strict: true`,
which makes `drizzle-kit push` prompt `No, abort / Yes, I want to execute all
statements`. In a non-interactive SSH script (no TTY), the prompt never receives
input and the command times out → SIGTERM → exit code 124 → deploy fails.
`set -e` then kills the whole deploy.
- **`bun run <script>` ambiguity**: `bun run index` resolves the `index` script
from `package.json`. In a monorepo with workspace packages, ensure the script
name is unique or use the explicit file path (e.g. `bun run scripts/indexer.ts`).
**Fix**: Use `psql` for schema changes instead of `db:push`:
```bash
psql "$DATABASE_URL" -c \
"ALTER TABLE documents ADD COLUMN IF NOT EXISTS extra_fields jsonb DEFAULT '{}'::jsonb NOT NULL;"
```
After deploy, check the **public URL** (not just `systemctl is-active`):
```bash
curl -sk -o /dev/null -w "%{http_code}" https://wiki.asepharyana.my.id/
curl -s https://wiki.asepharyana.my.id/docs/websocket/contract | grep -c "frontmatter-pattern"
```
## Deploy workflow template (bun-source, not Nix) — build in CI, deploy-only on VPS
> **User correction (2026-08-21):** "alur ci nya juga benarkan lah masa build
> di vps,harusnya kan di vps hanya deploy,dan seharusnya pakai nix"
The VPS must **not** build. Build happens in CI; the VPS only deploys the
pre-built artifact. Use a single workflow with a `needs:` chain (not
`workflow_run` — see pitfall #8 below).
### Pitfalls for bun-source deploy workflows
- **`bun --cwd X run Y` is broken.** `bun run` does NOT accept `--cwd` as a
subcommand flag — it prints usage and exits 0 (silent failure). Use
`working-directory: X` in the step, or `cd X && bun run Y`. (Root cause of
CI appearing to pass while the build never actually ran. This also affects
the smoke test step: `bun --cwd apps/mcp run smoke` was silently failing.)
- **`.next/` is a hidden directory.** `actions/upload-artifact@v4` excludes
hidden files/dirs by default (`include-hidden-files: false`). Set
`include-hidden-files: true` or the artifact will be empty.
- **`workflow_run` cannot download artifacts from the CI run.** This is a
known GitHub Actions limitation — the deploy workflow doesn't have access to
the CI run's artifacts. **Fix:** merge CI + deploy into a single workflow with
`deploy: needs: [build]`.
- **`actions/checkout@v4` → Node 20 deprecation.** Bump to `@v5`.
- **SCP'ing hundreds of individual files from `.next/` can time out.** Tar first,
then SCP the single tarball: `tar -czf app.tar.gz .next`, SCP, then SSH to
unpack. Also exclude `.next/cache/` to reduce size (~73MB → ~49MB).
- **`download-artifact` path resolution.** When downloading with
`path: apps/web/.next`, the artifact (which contains the `.next` directory
contents from upload `path: apps/web/.next`) gets extracted correctly to
`apps/web/.next/`. Do NOT use `path: .next` — that creates `.next/.next/`.
### Final working workflow (verified 2026-08-21)
```yaml
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
build:
name: typecheck + build
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v5
- name: Set up Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: "1.3.14"
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Typecheck
run: bun run typecheck
- name: Build web
working-directory: apps/web
run: bun run build
# Upload .next/ — include-hidden-files is REQUIRED (hidden dir)
- name: Upload web build artifact
uses: actions/upload-artifact@v4
with:
name: mcpedia-web-build
path: apps/web/.next
include-hidden-files: true
if-no-files-found: error
# Smoke test: requires Postgres + Redis — skipped in CI without secrets
- name: MCP smoke test
if: env.DATABASE_URL != ''
working-directory: apps/mcp
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
REDIS_URL: ${{ secrets.REDIS_URL }}
run: bun run smoke
- name: Test
run: bun run test
deploy:
name: deploy to VPS
needs: build
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v5
- name: Download build artifact
uses: actions/download-artifact@v4
with:
name: mcpedia-web-build
path: apps/web/.next
- name: Tar .next
run: tar -C apps/web --exclude='.next/cache' -czf mcpedia-web-next.tar.gz .next
- name: Copy tarball to VPS
uses: appleboy/scp-action@v1
with:
host: ${{ secrets.SSH_DEPLOY_HOST }}
port: ${{ secrets.SSH_DEPLOY_PORT }}
username: ${{ secrets.SSH_DEPLOY_USER }}
key: ${{ secrets.SSH_DEPLOY_KEY }}
source: "mcpedia-web-next.tar.gz"
target: "/tmp/"
- name: Unpack and restart on VPS
uses: appleboy/ssh-action@v1
with:
host: ${{ secrets.SSH_DEPLOY_HOST }}
port: ${{ secrets.SSH_DEPLOY_PORT }}
username: ${{ secrets.SSH_DEPLOY_USER }}
key: ${{ secrets.SSH_DEPLOY_KEY }}
envs: SSH_DEPLOY_HOST
script: |
set -e
cd /home/code/mcpedia
git pull origin main
/home/code/.bun/bin/bun install --frozen-lockfile
/home/code/.bun/bin/bun run scripts/indexer.ts
rm -rf apps/web/.next
tar -xzf /tmp/mcpedia-web-next.tar.gz -C apps/web/
rm -f /tmp/mcpedia-web-next.tar.gz
sudo systemctl restart mcpedia-web mcpedia-api mcpedia-mcp mcpedia-worker
sleep 3
systemctl --no-pager status mcpedia-web mcpedia-api mcpedia-mcp mcpedia-worker --no-legend
```
## Secrets to configure (per-repo GitHub secrets)
| Secret | Value | How |
|--------|-------|-----|
| `SSH_DEPLOY_HOST` | VPS public IP (e.g. `45.127.35.244`) | `gh secret set SSH_DEPLOY_HOST --body "45.127.35.244"` |
| `SSH_DEPLOY_PORT` | `22` | `gh secret set SSH_DEPLOY_PORT --body "22"` |
| `SSH_DEPLOY_USER` | `code` (or whatever user owns the services) | `gh secret set SSH_DEPLOY_USER --body "code"` |
| `SSH_DEPLOY_KEY` | SSH deploy private key (ed25519) | `cat keyfile \| gh secret set SSH_DEPLOY_KEY` |
And on the VPS, add the public key to the deploy user's `authorized_keys`:
```bash
ssh code@<public-ip> "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys <<< '$(cat keyfile.pub)'"
chmod 600 ~/.ssh/authorized_keys
```
## CI monitoring
```bash
gh run list --repo asepharyana/mcpedia --workflow "CI" --limit 3
gh run view <run_id> --log-failed # only failing-step logs
```
+5 -2
View File
@@ -10,12 +10,15 @@ This block is written and re-added by `next dev` — verify at `node_modules/nex
# MCPedia Agent Instructions
MCPedia is a content-first knowledge base where Markdown files under `content/` serve as the Git-tracked source of truth, indexed into PostgreSQL and accessed via Web UI, tRPC API, and Model Context Protocol (MCP).
MCPedia is a content-first knowledge base where documents are stored in **PostgreSQL** as the source of truth (with auto-generated .md backups on disk), indexed into embeddings + search vectors, and accessed via Web UI, tRPC API, and Model Context Protocol (MCP).
- **DB-first**: Documents are created/updated/deleted via the MCP `create_document`/`update_document`/`delete_document` tools (require `x-webhook-secret`). Filesystem `.md` files in `content/` are auto-generated backups (gitignored).
- **Git-sync deploy**: CI builds `.next` on GitHub Actions → tarball → SCP to VPS → unpack. VPS never builds. Content changes flow via MCP API to the DB directly.
## Architecture Principles
1. **Single Core Layer (`@mcpedia/core`)**: All business logic (document CRUD, indexing, search, revisions, path classification) resides in `packages/core`. Never access the database directly from `apps/web`, `apps/mcp`, or `apps/api`.
2. **Content as Source of Truth**: Markdown files in `content/` with YAML frontmatter are the primary data store. The database stores metadata, search vectors, embeddings, and revision history.
2. **DB as Source of Truth**: PostgreSQL stores document body + metadata. Filesystem `.md` files in `content/` are auto-generated backups (gitignored). Use the MCP `create_document`/`update_document` tools to write content.
3. **Multi-Modal Search**: Keyword search (Postgres FTS `tsvector` + GIN), Semantic search (cosine similarity over chunked embeddings), and Hybrid search (Reciprocal Rank Fusion / RRF) are unified in `@mcpedia/search`.
4. **Mutations & Security**: State-changing operations (document creation/updates/deletions, reindexing, revision restoration) require authentication (`x-webhook-secret` header or session cookie).
+1 -1
View File
@@ -18,7 +18,7 @@
"@mcpedia/queue": "workspace:*",
"@trpc/server": "^11.0.0",
"hono": "^4.6.0",
"zod": "^3.23.8"
"zod": "^4.5.4"
},
"devDependencies": {
"typescript": "^5.6.0"
+2 -2
View File
@@ -10,7 +10,7 @@
"start": "bun run src/index.ts",
"chat": "bun run src/index.ts",
"ask": "bun run src/ask.ts",
"lint": "bun run lint",
"lint": "tsc --noEmit",
"typecheck": "tsc --noEmit",
"build": "bun build src/index.ts --outdir=dist --format=esm",
"test": "bun test"
@@ -20,7 +20,7 @@
"zod": "^4.0.0"
},
"devDependencies": {
"@types/node": "^20",
"@types/node": "^26",
"typescript": "^5.6.0"
}
}
+1 -1
View File
@@ -23,7 +23,7 @@
"zod": "^4.0.0"
},
"devDependencies": {
"@types/node": "^20",
"@types/node": "^26",
"typescript": "^5.6.0"
}
}
+146 -173
View File
@@ -1,21 +1,37 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { cookies } from "next/headers";
import { getDocument, getRelated, listRevisions, listDocuments } from "@mcpedia/core";
import { getDocument, listDocuments, getExportDocuments } from "@mcpedia/core";
import { WEBHOOK_SECRET } from "@mcpedia/config";
import Markdown from "@/components/Markdown";
import DocForm from "@/components/DocForm";
import TOC from "@/components/TOC";
import DocActions from "@/components/DocActions";
import PdfExportView from "@/components/PdfExportView";
import RelatedGrid from "@/components/RelatedGrid";
import RevisionList from "@/components/RevisionList";
import { classifyPath, extractFoldersForSection } from "@mcpedia/core";
import { getSectionMeta } from "@mcpedia/config";
import type { DocumentMeta } from "@mcpedia/core";
import {
Folder,
FileText,
Clock,
FileDown,
ArrowLeft,
CheckCircle2,
XCircle,
Target,
Trophy,
Zap,
Tag,
} from "lucide-react";
export const dynamic = "force-dynamic";
interface DocPageProps {
params: Promise<{ section: string; slug: string[] }>;
searchParams: Promise<{ edit?: string }>;
searchParams: Promise<{ edit?: string; path?: string; sort?: string }>;
}
function getSectionInfo(section: string) {
@@ -48,44 +64,41 @@ function CustomFieldBadges({
{customEntries.map(([key, value]) => {
const label = key.charAt(0).toUpperCase() + key.slice(1).replace(/_/g, " ");
let colorClass = "bg-[var(--bg-elevated)] border-[var(--border-color)] text-[var(--text-secondary)]";
let icon = "🏷️";
let displayValue: string;
let IconComponent = Tag;
if (typeof value === "number") {
colorClass = "bg-[#5e6ad2]/10 border-[#5e6ad2]/30 text-[#5e6ad2] dark:text-[#7170ff]";
icon = "🎯";
colorClass = "bg-[var(--bg-elevated)] border-[var(--border-color)] text-[var(--text-primary)] font-semibold";
IconComponent = Target;
displayValue = `${value} pts`;
} else if (typeof value === "boolean") {
colorClass = value
? "bg-emerald-500/10 border-emerald-500/30 text-emerald-600 dark:text-emerald-400"
: "bg-rose-500/10 border-rose-500/30 text-rose-600 dark:text-rose-400";
icon = value ? "✓" : "✕";
? "bg-emerald-500/10 border-emerald-500/30 text-emerald-600 dark:text-emerald-400 font-semibold"
: "bg-rose-500/10 border-rose-500/30 text-rose-600 dark:text-rose-400 font-semibold";
IconComponent = value ? CheckCircle2 : XCircle;
displayValue = value ? "Solved" : "Pending";
} else if (Array.isArray(value)) {
colorClass = "bg-[#5e6ad2]/10 border-[#5e6ad2]/30 text-[#5e6ad2] dark:text-[#7170ff]";
icon = "🗂️";
colorClass = "bg-[var(--bg-elevated)] border-[var(--border-color)] text-[var(--text-secondary)]";
IconComponent = Folder;
displayValue = value.join(", ");
} else {
const v = String(value).toLowerCase();
if (/^(easy|simple|beginner)/i.test(v)) {
colorClass = "bg-emerald-500/10 border-emerald-500/30 text-emerald-600 dark:text-emerald-400";
icon = "🟢";
colorClass = "bg-emerald-500/10 border-emerald-500/30 text-emerald-600 dark:text-emerald-400 font-semibold";
displayValue = "Easy";
} else if (/^(medium|intermediate)/i.test(v)) {
colorClass = "bg-amber-500/10 border-amber-500/30 text-amber-600 dark:text-amber-400";
icon = "🟡";
colorClass = "bg-amber-500/10 border-amber-500/30 text-amber-600 dark:text-amber-400 font-semibold";
displayValue = "Medium";
} else if (/^(hard|expert|advanced)/i.test(v)) {
colorClass = "bg-rose-500/10 border-rose-500/30 text-rose-600 dark:text-rose-400";
icon = "🔴";
colorClass = "bg-rose-500/10 border-rose-500/30 text-rose-600 dark:text-rose-400 font-semibold";
displayValue = "Hard";
} else if (/^(pwn|web|crypto|misc|forensic|reverse|binary)/i.test(v)) {
colorClass = "bg-indigo-500/10 border-indigo-500/30 text-indigo-600 dark:text-indigo-300";
icon = "⚡";
colorClass = "bg-[var(--bg-elevated)] border-[var(--border-color)] text-[var(--text-primary)] font-bold";
IconComponent = Zap;
displayValue = v.toUpperCase();
} else if (/ctf|def.?con|event/i.test(v)) {
colorClass = "bg-[#5e6ad2]/10 border-[#5e6ad2]/30 text-[#5e6ad2] dark:text-[#7170ff]";
icon = "🏆";
colorClass = "bg-[var(--bg-elevated)] border-[var(--border-color)] text-[var(--text-primary)]";
IconComponent = Trophy;
displayValue = String(value);
} else {
displayValue = String(value);
@@ -97,9 +110,9 @@ function CustomFieldBadges({
key={key}
className={`inline-flex items-center gap-1.5 px-2.5 py-1 border rounded-md text-xs font-mono transition-colors ${colorClass}`}
>
<span className="text-[10px] opacity-70">{icon}</span>
<IconComponent className="w-3.5 h-3.5 opacity-80" />
<span className="text-[var(--text-muted)] font-sans">{label}:</span>
<span className="font-medium">{displayValue}</span>
<span>{displayValue}</span>
</span>
);
})}
@@ -145,9 +158,9 @@ function FolderIndexPage({
const folderName = slug.split("/").pop()!.split(/[-_]/).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
return (
<div>
{/* Breadcrumb */}
<nav className="flex items-center gap-2 text-xs text-[var(--text-dim)] mb-6 flex-wrap">
<div className="space-y-8">
{/* Breadcrumb Navigation */}
<nav className="flex items-center gap-2 text-xs text-[var(--text-dim)] flex-wrap">
<Link href="/" className="hover:text-[var(--text-primary)] transition-colors">
MCPedia
</Link>
@@ -170,48 +183,59 @@ function FolderIndexPage({
})}
</nav>
{/* Header card */}
<div className="bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl p-6 mb-8 shadow-sm">
<div className="flex items-center justify-between gap-4">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-lg bg-[var(--bg-elevated)] border border-[var(--border-color)] flex items-center justify-center text-xl">
📁
{/* Header Card */}
<div className="bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl p-6 shadow-xs">
<div className="flex flex-col sm:flex-row sm:items-start justify-between gap-4">
<div className="flex items-center gap-3.5">
<div className="w-10 h-10 rounded-lg bg-[var(--bg-elevated)] border border-[var(--border-color)] flex items-center justify-center text-[var(--text-primary)]">
<Folder className="w-5 h-5" />
</div>
<div>
<h1 className="text-2xl sm:text-3xl font-bold text-[var(--text-primary)] tracking-tight">
<h1 className="text-2xl font-bold text-[var(--text-primary)] tracking-tight">
{folderName}
</h1>
<p className="text-xs text-[var(--text-muted)] mt-0.5">
Directory path: <code className="text-[#5e6ad2] dark:text-[#7170ff] font-mono">{section}/{slug}</code>
<p className="text-xs text-[var(--text-muted)] mt-0.5 font-mono">
Directory: <code>{section}/{slug}</code>
</p>
</div>
</div>
<span className="text-xs font-mono text-[var(--text-muted)] bg-[var(--bg-elevated)] border border-[var(--border-color)] px-2.5 py-1 rounded-md">
{immediateDocs.length + folders.length} item{folders.length + immediateDocs.length !== 1 ? "s" : ""}
</span>
<div className="flex items-center gap-2">
<span className="text-xs font-mono text-[var(--text-muted)] bg-[var(--bg-elevated)] border border-[var(--border-color)] px-2.5 py-1 rounded">
{immediateDocs.length + folders.length} item{folders.length + immediateDocs.length !== 1 ? "s" : ""}
</span>
<Link
href={`/${section}/${slug}/export`}
className="inline-flex items-center gap-1.5 text-xs bg-[var(--brand)] hover:opacity-90 text-[var(--brand-fg)] px-3 py-1.5 rounded font-semibold transition-all shadow-xs"
title={`Export all ${folderName} documents as a single PDF report`}
>
<FileDown className="w-3.5 h-3.5" />
<span>Export PDF</span>
</Link>
</div>
</div>
</div>
{/* Subfolders */}
{/* Subfolders Grid */}
{folders.length > 0 && (
<div className="mb-8">
<h2 className="text-xs font-semibold text-[var(--text-muted)] uppercase mb-3 tracking-wider flex items-center gap-2">
<span>Subfolders</span>
<span className="text-[10px] text-[var(--text-dim)]">({folders.length})</span>
<div>
<h2 className="text-xs font-bold text-[var(--text-muted)] uppercase mb-3 tracking-wider font-mono flex items-center gap-2">
<Folder className="w-3.5 h-3.5 text-[var(--text-muted)]" />
<span>Subfolders ({folders.length})</span>
</h2>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
{folders.map(([folder, info]) => (
<Link
key={folder}
href={`/${section}/${slug}/${folder}`.replace(/\/+/g, "/")}
className="group flex items-center gap-3 p-3.5 bg-[var(--bg-surface)] hover:bg-[var(--bg-surface-hover)] border border-[var(--border-color)] hover:border-[var(--brand)] rounded-lg transition-all shadow-sm"
className="group flex items-center gap-3 p-3.5 bg-[var(--bg-surface)] hover:bg-[var(--bg-surface-hover)] border border-[var(--border-color)] hover:border-[var(--text-muted)] rounded-lg transition-colors shadow-xs"
>
<span className="text-2xl group-hover:scale-110 transition-transform">📁</span>
<Folder className="w-4 h-4 text-[var(--text-muted)]" />
<div className="flex-1 min-w-0">
<div className="text-sm font-semibold text-[var(--text-primary)] group-hover:text-[#5e6ad2] dark:group-hover:text-[#7170ff] transition-colors truncate">
<div className="text-xs font-semibold text-[var(--text-primary)] group-hover:underline truncate">
{folder.split(/[-_]/).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ")}
</div>
<div className="text-xs text-[var(--text-muted)] mt-0.5 font-mono">
<div className="text-[11px] text-[var(--text-muted)] font-mono mt-0.5">
{info.docCount} document{info.docCount !== 1 ? "s" : ""}
</div>
</div>
@@ -221,32 +245,32 @@ function FolderIndexPage({
</div>
)}
{/* Documents */}
{/* Documents List */}
{immediateDocs.length > 0 && (
<div>
<h2 className="text-xs font-semibold text-[var(--text-muted)] uppercase mb-3 tracking-wider flex items-center gap-2">
<span>Documents</span>
<span className="text-[10px] text-[var(--text-dim)]">({immediateDocs.length})</span>
<h2 className="text-xs font-bold text-[var(--text-muted)] uppercase mb-3 tracking-wider font-mono flex items-center gap-2">
<FileText className="w-3.5 h-3.5 text-[var(--text-muted)]" />
<span>Documents ({immediateDocs.length})</span>
</h2>
<div className="space-y-2">
{immediateDocs.map((doc) => (
<Link
key={doc.slug}
href={`/${doc.slug}`}
className="group flex items-center justify-between gap-4 p-4 bg-[var(--bg-surface)] hover:bg-[var(--bg-surface-hover)] border border-[var(--border-color)] hover:border-[var(--brand)] rounded-lg transition-all shadow-sm"
className="group flex items-center justify-between gap-4 p-4 bg-[var(--bg-surface)] hover:bg-[var(--bg-surface-hover)] border border-[var(--border-color)] hover:border-[var(--text-muted)] rounded-lg transition-colors shadow-xs"
>
<div className="flex items-center gap-3 min-w-0">
<span className="text-xl opacity-70 group-hover:opacity-100">📄</span>
<FileText className="w-4 h-4 text-[var(--text-muted)] shrink-0" />
<div className="min-w-0">
<div className="text-sm font-semibold text-[var(--text-primary)] group-hover:text-[#5e6ad2] dark:group-hover:text-[#7170ff] transition-colors truncate">
<div className="text-xs sm:text-sm font-semibold text-[var(--text-primary)] group-hover:underline truncate">
{doc.title}
</div>
{doc.tags.length > 0 && (
<div className="flex flex-wrap gap-1.5 mt-1.5">
<div className="flex flex-wrap gap-1 mt-1.5">
{doc.tags.slice(0, 4).map((t) => (
<span
key={t}
className="text-[11px] px-1.5 py-0.25 bg-[var(--bg-elevated)] border border-[var(--border-color)] rounded text-[var(--text-muted)]"
className="text-[10px] px-1.5 py-0.2 bg-[var(--bg-elevated)] border border-[var(--border-color)] rounded text-[var(--text-muted)] font-mono"
>
#{t}
</span>
@@ -255,11 +279,15 @@ function FolderIndexPage({
)}
</div>
</div>
<time className="text-xs text-[var(--text-dim)] shrink-0 font-mono">
{new Date(doc.updatedAt).toLocaleDateString(undefined, {
month: "short",
day: "numeric",
})}
<time className="text-xs text-[var(--text-dim)] shrink-0 font-mono flex items-center gap-1">
<Clock className="w-3 h-3" />
<span>
{new Date(doc.updatedAt).toLocaleDateString(undefined, {
month: "short",
day: "numeric",
})}
</span>
</time>
</Link>
))}
@@ -268,8 +296,8 @@ function FolderIndexPage({
)}
{folders.length === 0 && immediateDocs.length === 0 && (
<div className="text-center py-12 border border-[var(--border-color)] rounded-xl bg-[var(--bg-surface)]">
<p className="text-sm text-[var(--text-muted)]">No documents found in this directory.</p>
<div className="text-center py-12 border border-[var(--border-color)] rounded-lg bg-[var(--bg-surface)]">
<p className="text-sm text-[var(--text-muted)]">No documents in this directory.</p>
</div>
)}
</div>
@@ -278,7 +306,23 @@ function FolderIndexPage({
export default async function DocPage({ params, searchParams }: DocPageProps) {
const { section, slug } = await params;
const { edit } = await searchParams;
const searchParamsObj = await searchParams;
const { edit, path: queryPath, sort } = searchParamsObj;
// Handle direct export views
if (section === "export" || (slug && slug[slug.length - 1] === "export")) {
const isTrailingExport = slug && slug[slug.length - 1] === "export";
const targetSlug = isTrailingExport ? slug.slice(0, -1) : slug;
const targetPath = queryPath || (targetSlug.length > 0 ? `${section}/${targetSlug.join("/")}` : section);
const exportData = await getExportDocuments({
path: targetPath === "export" ? queryPath : targetPath,
section: targetPath === section ? section : undefined,
sortBy: (sort as any) || "category_points",
});
const backHref = targetPath && targetPath !== "export" ? `/${targetPath}` : section !== "export" ? `/${section}` : "/";
return <PdfExportView exportData={exportData} backHref={backHref} />;
}
const fullSlug = `${section}/${slug.join("/")}`;
const allDocs = await listDocuments();
@@ -304,14 +348,15 @@ export default async function DocPage({ params, searchParams }: DocPageProps) {
if (edit === "1" && canEdit) {
const existingFolders = extractFoldersForSection(docSlugs, doc.section);
return (
<div>
<div className="space-y-6">
<Link
href={`/${doc.slug}`}
className="inline-flex items-center gap-1 text-xs text-[var(--text-muted)] hover:text-[var(--text-primary)] mb-4 transition-colors"
className="inline-flex items-center gap-1.5 text-xs text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors"
>
<span>← Back to document</span>
<ArrowLeft className="w-3.5 h-3.5" />
<span>Back to document</span>
</Link>
<h1 className="text-2xl font-bold text-[var(--text-primary)] mb-6">
<h1 className="text-2xl font-bold text-[var(--text-primary)] tracking-tight">
Edit: {doc.title}
</h1>
<DocForm
@@ -337,8 +382,6 @@ export default async function DocPage({ params, searchParams }: DocPageProps) {
);
}
const related = await getRelated(fullSlug, 4);
const revisions = await listRevisions(fullSlug, 10);
const sectionInfo = getSectionInfo(doc.section);
const readingTime = calculateReadingTime(doc.body);
@@ -346,8 +389,8 @@ export default async function DocPage({ params, searchParams }: DocPageProps) {
<div className="flex items-start gap-8">
{/* Main Content Column */}
<article className="flex-1 min-w-0">
{/* Breadcrumb */}
<nav className="flex items-center gap-2 text-xs text-[var(--text-dim)] mb-4 flex-wrap">
{/* Breadcrumbs Navigation */}
<nav className="flex items-center gap-2 text-xs text-[var(--text-dim)] mb-4 flex-wrap font-mono">
<Link href="/" className="hover:text-[var(--text-primary)] transition-colors">
MCPedia
</Link>
@@ -362,7 +405,7 @@ export default async function DocPage({ params, searchParams }: DocPageProps) {
<span>/</span>
<Link
href={`/${crumbPath}`}
className={isLast ? "text-[var(--text-primary)] font-semibold" : "hover:text-[var(--text-primary)] transition-colors"}
className={isLast ? "text-[var(--text-primary)] font-semibold font-sans" : "hover:text-[var(--text-primary)] transition-colors font-sans"}
>
{label}
</Link>
@@ -372,24 +415,26 @@ export default async function DocPage({ params, searchParams }: DocPageProps) {
</nav>
{/* Hero Metadata Card */}
<div className="bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl p-6 mb-8 shadow-sm">
<div className="bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl p-6 sm:p-7 mb-8 shadow-xs">
<div className="flex flex-col sm:flex-row sm:items-start justify-between gap-4 mb-4">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-2 flex-wrap">
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-mono font-medium bg-[#5e6ad2]/15 text-[#5e6ad2] dark:text-[#7170ff] border border-[#5e6ad2]/30">
<div className="flex items-center gap-2 mb-2 flex-wrap text-xs">
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-mono font-bold bg-[var(--bg-elevated)] border border-[var(--border-color)] text-[var(--text-primary)] uppercase">
<span>{sectionInfo.icon}</span>
<span className="uppercase">{sectionInfo.label}</span>
</span>
<span className="text-xs text-[var(--text-dim)]">·</span>
<span className="text-xs text-[var(--text-muted)]">
{doc.type.charAt(0).toUpperCase() + doc.type.slice(1)}
<span>{sectionInfo.label}</span>
</span>
<span className="text-xs text-[var(--text-dim)]">·</span>
<span className="text-xs text-[var(--text-muted)] font-mono">
{readingTime}
{doc.type}
</span>
<span className="text-xs text-[var(--text-dim)]">·</span>
<span className="text-xs text-[var(--text-muted)] font-mono flex items-center gap-1">
<Clock className="w-3 h-3" />
<span>{readingTime}</span>
</span>
</div>
<h1 className="text-2xl sm:text-3xl font-bold text-[var(--text-primary)] tracking-tight leading-tight">
<h1 className="text-2xl sm:text-3xl font-extrabold text-[var(--text-primary)] tracking-tight leading-tight">
{doc.title}
</h1>
</div>
@@ -398,24 +443,27 @@ export default async function DocPage({ params, searchParams }: DocPageProps) {
<DocActions slug={doc.slug} body={doc.body} canEdit={canEdit} />
</div>
{/* Author + Date + Tags */}
<div className="flex flex-wrap items-center gap-3 text-xs text-[var(--text-muted)] pt-3 border-t border-[var(--border-color)]">
{/* Author, Date, Tags */}
<div className="flex flex-wrap items-center gap-3 text-xs text-[var(--text-muted)] pt-3.5 border-t border-[var(--border-color)]">
{doc.author && (
<div className="flex items-center gap-1.5">
<div className="w-4 h-4 rounded-full bg-[#5e6ad2] text-white flex items-center justify-center text-[10px] font-bold">
<div className="w-4 h-4 rounded bg-[var(--brand)] text-[var(--brand-fg)] flex items-center justify-center text-[10px] font-bold font-mono">
{doc.author.charAt(0).toUpperCase()}
</div>
<span className="text-[var(--text-secondary)]">{doc.author}</span>
<span className="text-[var(--text-secondary)] font-medium">{doc.author}</span>
<span className="text-[var(--text-dim)]">·</span>
</div>
)}
<span>
Updated {new Date(doc.updatedAt).toLocaleDateString(undefined, {
month: "long",
day: "numeric",
year: "numeric",
})}
<span className="flex items-center gap-1 font-mono text-[11px]">
<span>
Updated {new Date(doc.updatedAt).toLocaleDateString(undefined, {
month: "short",
day: "numeric",
year: "numeric",
})}
</span>
</span>
{doc.tags.length > 0 && (
<>
<span className="text-[var(--text-dim)]">·</span>
@@ -423,7 +471,7 @@ export default async function DocPage({ params, searchParams }: DocPageProps) {
{doc.tags.map((t) => (
<span
key={t}
className="px-2 py-0.5 bg-[var(--bg-elevated)] border border-[var(--border-color)] rounded text-[var(--text-muted)] text-[11px]"
className="px-1.5 py-0.2 bg-[var(--bg-elevated)] border border-[var(--border-color)] rounded text-[var(--text-muted)] text-[10px] font-mono"
>
#{t}
</span>
@@ -437,93 +485,18 @@ export default async function DocPage({ params, searchParams }: DocPageProps) {
<CustomFieldBadges doc={{ ...doc }} standardKeys={STANDARD_KEYS} />
</div>
{/* Mobile TOC (rendered inline on smaller screens) */}
<div className="xl:hidden mb-6 p-4 bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-lg shadow-sm">
{/* Mobile TOC */}
<div className="xl:hidden mb-6 p-4 bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl shadow-xs">
<TOC source={doc.body} />
</div>
{/* Markdown content */}
{/* Markdown Content */}
<div className="mb-14">
<Markdown source={doc.body} />
</div>
{/* Related Documents */}
{related.length > 0 && (
<aside className="mt-12 pt-8 border-t border-[var(--border-color)]">
<h2 className="text-xs font-semibold text-[var(--text-muted)] uppercase tracking-wider mb-4 flex items-center gap-2">
<span>Related Knowledge</span>
</h2>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
{related.map((r) => {
const rInfo = getSectionInfo(r.section);
return (
<Link
key={r.slug}
href={`/${r.slug}`}
className="group block bg-[var(--bg-surface)] hover:bg-[var(--bg-surface-hover)] border border-[var(--border-color)] hover:border-[var(--brand)] rounded-lg p-4 transition-all shadow-sm"
>
<div className="flex items-center justify-between gap-2 mb-2">
<span className="text-xs text-[#5e6ad2] dark:text-[#7170ff] font-mono uppercase">
{rInfo.icon} {r.section}
</span>
<time className="text-[11px] text-[var(--text-dim)] font-mono">
{new Date(r.updatedAt).toLocaleDateString(undefined, {
month: "short",
day: "numeric",
})}
</time>
</div>
<h3 className="text-sm font-semibold text-[var(--text-primary)] group-hover:text-[#5e6ad2] dark:group-hover:text-[#7170ff] transition-colors line-clamp-1 mb-1">
{r.title}
</h3>
</Link>
);
})}
</div>
</aside>
)}
{/* Revision History */}
{revisions.length > 0 && (
<aside className="mt-10 pt-8 border-t border-[var(--border-color)]">
<div className="flex items-center justify-between mb-4">
<h2 className="text-xs font-semibold text-[var(--text-muted)] uppercase tracking-wider">
Revision History ({revisions.length})
</h2>
</div>
<div className="space-y-2">
{revisions.map((rev) => (
<div
key={rev.id}
className="flex items-center justify-between gap-3 p-3 bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-lg text-xs shadow-sm"
>
<div className="flex items-center gap-2 min-w-0">
<span className="font-mono text-[#5e6ad2] dark:text-[#7170ff] bg-[#5e6ad2]/10 px-1.5 py-0.5 rounded border border-[#5e6ad2]/30 font-semibold">
v{rev.revisionNo}
</span>
<span className="text-[var(--text-primary)] truncate">
{rev.reason || "Updated document"}
</span>
<span className="text-[var(--text-dim)] hidden sm:inline">
· {new Date(rev.createdAt).toLocaleString()}
</span>
</div>
{canEdit && (
<form action="/api/revisions/restore" method="post">
<input type="hidden" name="id" value={rev.id} />
<button
type="submit"
className="text-xs text-[var(--text-secondary)] hover:text-[var(--text-primary)] bg-[var(--bg-elevated)] hover:bg-[var(--bg-elevated-hover)] px-2.5 py-1 rounded border border-[var(--border-color)] hover:border-[var(--brand)] transition-colors font-medium shadow-sm"
>
Restore
</button>
</form>
)}
</div>
))}
</div>
</aside>
)}
<RelatedGrid slug={fullSlug} />
<RevisionList slug={fullSlug} canEdit={canEdit} />
</article>
{/* Desktop Sticky Table of Contents Column */}
+71 -38
View File
@@ -1,6 +1,13 @@
import Link from "next/link";
import { listDocuments } from "@mcpedia/core";
import { getSectionMeta } from "@mcpedia/config";
import {
Folder,
FileText,
FileDown,
Plus,
Clock,
} from "lucide-react";
export const dynamic = "force-dynamic";
@@ -81,26 +88,28 @@ function renderTree(nodes: TreeNode[], pathname: string) {
<li key={node.slug}>
<Link
href={`/${node.slug}`}
className={`flex items-center justify-between gap-2 text-xs py-1.5 px-2.5 rounded-lg transition-all ${
className={`flex items-center justify-between gap-2 text-xs py-1.5 px-2.5 rounded-md transition-colors ${
isActive
? "text-[#5e6ad2] dark:text-[#7170ff] bg-[#5e6ad2]/15 font-semibold border border-[#5e6ad2]/30"
? "text-[var(--text-primary)] bg-[var(--bg-elevated)] font-semibold border border-[var(--border-color)] shadow-xs"
: hasActiveChild
? "text-[var(--text-primary)] bg-[var(--bg-elevated)]"
: "text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-elevated)]"
}`}
>
<span className="flex items-center gap-2 truncate">
<span>{isFolder ? "📁" : "📄"}</span>
<span className="truncate">{node.doc?.title || node.name}</span>
<span className="text-[var(--text-dim)]">
{isFolder ? <Folder className="w-3.5 h-3.5" /> : <FileText className="w-3.5 h-3.5" />}
</span>
<span className="truncate font-medium">{node.doc?.title || node.name}</span>
</span>
{isFolder && (
<span className="text-[10px] text-[var(--text-dim)] bg-[var(--bg-surface)] border border-[var(--border-color)] px-1.5 py-0.5 rounded font-mono">
<span className="text-[10px] text-[var(--text-dim)] bg-[var(--bg-surface)] border border-[var(--border-color)] px-1.5 py-0.2 rounded font-mono">
{node.docCount} docs
</span>
)}
</Link>
{node.children.length > 0 && (
<div className="ml-4 border-l border-[var(--border-color)] pl-2 mt-1">
<div className="ml-3.5 border-l border-[var(--border-color)] pl-2.5 mt-0.5 space-y-0.5">
{renderTree(node.children, pathname)}
</div>
)}
@@ -124,57 +133,73 @@ export default async function SectionIndexPage({
const tree = buildFolderTree(allDocs, section);
return (
<div className="space-y-10">
{/* Breadcrumb */}
<nav className="flex items-center gap-2 text-xs text-[var(--text-dim)]">
<div className="space-y-8">
{/* Breadcrumb Navigation */}
<nav className="flex items-center gap-2 text-xs text-[var(--text-dim)] font-mono">
<Link href="/" className="hover:text-[var(--text-primary)] transition-colors">
MCPedia
</Link>
<span>/</span>
<span className="text-[var(--text-muted)] font-medium">{sectionInfo.label}</span>
<span className="text-[var(--text-muted)] font-semibold font-sans">{sectionInfo.label}</span>
</nav>
{/* Hero Card */}
<div className="bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl p-6 shadow-sm">
<div className="bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl p-6 shadow-xs">
<div className="flex flex-col sm:flex-row sm:items-start justify-between gap-4 mb-3">
<div className="flex items-center gap-3">
<div className="w-12 h-12 rounded-xl bg-[var(--bg-elevated)] border border-[var(--border-color)] flex items-center justify-center text-2xl shadow-inner">
<div className="flex items-center gap-3.5">
<div className="w-12 h-12 rounded-xl bg-[var(--bg-elevated)] border border-[var(--border-color)] flex items-center justify-center text-2xl">
{sectionInfo.icon}
</div>
<div>
<h1 className="text-2xl sm:text-3xl font-bold text-[var(--text-primary)] tracking-tight">
<h1 className="text-2xl sm:text-3xl font-extrabold text-[var(--text-primary)] tracking-tight">
{sectionInfo.label}
</h1>
<p className="text-xs text-[var(--text-muted)] mt-0.5 font-mono uppercase">
Section: {section}
<p className="text-xs text-[var(--text-muted)] font-mono uppercase tracking-wider mt-0.5">
Section: <code>{section}</code>
</p>
</div>
</div>
<div className="flex items-center gap-2">
<span className="text-xs font-mono text-[#5e6ad2] dark:text-[#7170ff] bg-[#5e6ad2]/10 border border-[#5e6ad2]/25 px-2.5 py-1 rounded-md">
<div className="flex items-center gap-2 flex-wrap sm:flex-nowrap">
<span className="text-xs font-mono text-[var(--text-muted)] bg-[var(--bg-elevated)] border border-[var(--border-color)] px-2.5 py-1 rounded">
{sectionDocs.length} document{sectionDocs.length !== 1 ? "s" : ""}
</span>
{sectionDocs.length > 0 && (
<Link
href={`/${section}/export`}
className="inline-flex items-center gap-1.5 text-xs bg-[var(--bg-elevated)] hover:bg-[var(--bg-elevated-hover)] border border-[var(--border-color)] text-[var(--text-primary)] px-3 py-1 rounded-md font-semibold transition-all shadow-xs"
title={`Export all ${sectionInfo.label} documents to publication-grade PDF`}
>
<FileDown className="w-3.5 h-3.5" />
<span>Export PDF</span>
</Link>
)}
<Link
href="/create"
className="inline-flex items-center gap-1 text-xs bg-[#5e6ad2] hover:bg-[#6a75e0] text-white px-3 py-1 rounded-md font-medium transition-all"
className="inline-flex items-center gap-1.5 text-xs bg-[var(--brand)] hover:opacity-90 text-[var(--brand-fg)] px-3 py-1 rounded-md font-semibold transition-all shadow-xs"
>
<span>+ Create</span>
<Plus className="w-3.5 h-3.5" />
<span>Create Doc</span>
</Link>
</div>
</div>
<p className="text-sm text-[var(--text-muted)] leading-relaxed max-w-2xl mt-2">
<p className="text-xs sm:text-sm text-[var(--text-muted)] leading-relaxed max-w-2xl mt-2">
{sectionInfo.desc}
</p>
</div>
{/* Hierarchical Folder Directory */}
{tree.length > 0 && (
<section className="bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl p-6 shadow-sm">
<h2 className="text-xs font-semibold text-[var(--text-muted)] uppercase tracking-wider mb-4 flex items-center gap-2">
<span>Folder Structure</span>
</h2>
<section className="bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl p-5 shadow-xs">
<div className="flex items-center gap-2 mb-3 pb-2 border-b border-[var(--border-color)]">
<Folder className="w-3.5 h-3.5 text-[var(--text-muted)]" />
<h2 className="text-xs font-bold text-[var(--text-muted)] uppercase tracking-wider font-mono">
Folder & Chapter Structure
</h2>
</div>
{renderTree(tree, section)}
</section>
)}
@@ -182,9 +207,13 @@ export default async function SectionIndexPage({
{/* Document List */}
{sectionDocs.length > 0 ? (
<section>
<h2 className="text-xs font-semibold text-[var(--text-muted)] uppercase tracking-wider mb-4">
All Documents in {sectionInfo.label}
</h2>
<div className="flex items-center gap-2 mb-3.5">
<FileText className="w-3.5 h-3.5 text-[var(--text-muted)]" />
<h2 className="text-xs font-bold text-[var(--text-muted)] uppercase tracking-wider font-mono">
All Documents in {sectionInfo.label}
</h2>
</div>
<div className="space-y-2">
{[...sectionDocs]
.sort(
@@ -195,12 +224,12 @@ export default async function SectionIndexPage({
<Link
key={d.slug}
href={`/${d.slug}`}
className="group flex items-center justify-between gap-4 p-4 bg-[var(--bg-surface)] hover:bg-[var(--bg-surface-hover)] border border-[var(--border-color)] hover:border-[var(--brand)] rounded-xl transition-all shadow-sm"
className="group flex items-center justify-between gap-4 p-4 bg-[var(--bg-surface)] hover:bg-[var(--bg-surface-hover)] border border-[var(--border-color)] hover:border-[var(--text-muted)] rounded-xl transition-all shadow-xs"
>
<div className="flex items-center gap-3 min-w-0">
<span className="text-lg opacity-70 group-hover:opacity-100">📄</span>
<FileText className="w-4 h-4 text-[var(--text-muted)] shrink-0" />
<div className="min-w-0">
<h3 className="text-sm font-medium text-[var(--text-primary)] group-hover:text-[#5e6ad2] dark:group-hover:text-[#7170ff] transition-colors truncate">
<h3 className="text-xs sm:text-sm font-semibold text-[var(--text-primary)] group-hover:underline truncate">
{d.title}
</h3>
{d.tags.length > 0 && (
@@ -208,7 +237,7 @@ export default async function SectionIndexPage({
{d.tags.slice(0, 4).map((t) => (
<span
key={t}
className="text-[10px] px-1.5 py-0.25 bg-[var(--bg-elevated)] border border-[var(--border-color)] rounded text-[var(--text-muted)]"
className="text-[10px] px-1.5 py-0.2 bg-[var(--bg-elevated)] border border-[var(--border-color)] rounded text-[var(--text-muted)] font-mono"
>
#{t}
</span>
@@ -217,12 +246,16 @@ export default async function SectionIndexPage({
)}
</div>
</div>
<time className="text-xs text-[var(--text-dim)] font-mono shrink-0">
{new Date(d.updatedAt).toLocaleDateString(undefined, {
month: "short",
day: "numeric",
year: "numeric",
})}
<time className="text-xs text-[var(--text-dim)] font-mono shrink-0 flex items-center gap-1">
<Clock className="w-3 h-3" />
<span>
{new Date(d.updatedAt).toLocaleDateString(undefined, {
month: "short",
day: "numeric",
year: "numeric",
})}
</span>
</time>
</Link>
))}
+13 -8
View File
@@ -13,15 +13,23 @@ function signCookie(value: string): string {
return `${value}.${sig}`;
}
function safeTimingEqual(a: string, b: string): boolean {
try {
const bufA = Buffer.from(a);
const bufB = Buffer.from(b);
if (bufA.length !== bufB.length) return false;
return timingSafeEqual(bufA, bufB);
} catch {
return false;
}
}
function verifyCookie(cookieValue: string | undefined): boolean {
if (!cookieValue) return false;
const [value, sig] = cookieValue.split(".");
if (!value || !sig) return false;
const expected = signCookie(value);
return timingSafeEqual(
Buffer.from(cookieValue),
Buffer.from(expected),
);
return safeTimingEqual(cookieValue, expected);
}
export async function POST(req: NextRequest) {
@@ -32,10 +40,7 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ ok: false, error: "Unauthorized" }, { status: 401 });
}
const ok = timingSafeEqual(
Buffer.from(password),
Buffer.from(ADMIN_PASSWORD),
);
const ok = safeTimingEqual(password, ADMIN_PASSWORD);
if (!ok) {
return NextResponse.json({ ok: false, error: "Unauthorized" }, { status: 401 });
+6 -2
View File
@@ -6,8 +6,12 @@ import { timingSafeEqual } from "node:crypto";
function isAuthorized(req: NextRequest): boolean {
if (!WEBHOOK_SECRET) return false;
const headerSecret = req.headers.get("x-webhook-secret") ?? "";
if (headerSecret && timingSafeEqual(Buffer.from(headerSecret), Buffer.from(WEBHOOK_SECRET))) {
return true;
if (headerSecret) {
const bufA = Buffer.from(headerSecret);
const bufB = Buffer.from(WEBHOOK_SECRET);
if (bufA.length === bufB.length && timingSafeEqual(bufA, bufB)) {
return true;
}
}
const cookie = req.cookies.get("mcpedia_admin")?.value ?? "";
return cookie.startsWith("admin.");
+15 -4
View File
@@ -13,8 +13,12 @@ import { timingSafeEqual } from "node:crypto";
function isAuthorized(req: NextRequest): boolean {
if (!WEBHOOK_SECRET) return false;
const headerSecret = req.headers.get("x-webhook-secret") ?? "";
if (headerSecret && timingSafeEqual(Buffer.from(headerSecret), Buffer.from(WEBHOOK_SECRET))) {
return true;
if (headerSecret) {
const bufA = Buffer.from(headerSecret);
const bufB = Buffer.from(WEBHOOK_SECRET);
if (bufA.length === bufB.length && timingSafeEqual(bufA, bufB)) {
return true;
}
}
const cookie = req.cookies.get("mcpedia_admin")?.value ?? "";
return cookie.startsWith("admin.");
@@ -74,8 +78,15 @@ function splitPayload(body: Record<string, unknown>): {
}
// GET /api/docs — list all documents (for sidebar navigation).
export async function GET() {
const docs = await listDocuments();
// Supports ?section=&status= filters.
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const section = searchParams.get("section") ?? undefined;
const status = searchParams.get("status") ?? undefined;
const docs = await listDocuments({
...(section ? { section } : {}),
...(status ? { status } : {}),
});
return NextResponse.json(docs);
}
+64
View File
@@ -0,0 +1,64 @@
import { NextRequest, NextResponse } from "next/server";
import {
getExportDocuments,
compileExportMarkdown,
generateExportDocx,
type ExportSortOption,
} from "@mcpedia/core";
export const dynamic = "force-dynamic";
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const path = searchParams.get("path") || undefined;
const section = searchParams.get("section") || undefined;
const format = searchParams.get("format") || "json";
const sortBy = (searchParams.get("sort") as ExportSortOption) || "category_points";
const slugsParam = searchParams.get("slugs");
const slugs = slugsParam ? slugsParam.split(",").map((s) => s.trim()) : undefined;
const pageBreaksParam = searchParams.get("pageBreaks");
const pageBreaks = pageBreaksParam !== "false" && pageBreaksParam !== "0";
try {
const data = await getExportDocuments({
path,
section,
slugs,
sortBy,
});
const safeFilename = data.summary.title
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-|-$/g, "") || "mcpedia-export";
if (format === "docx" || format === "word") {
const buffer = await generateExportDocx(data, { pageBreaks });
const uint8 = new Uint8Array(buffer);
return new NextResponse(uint8, {
headers: {
"Content-Type":
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"Content-Disposition": `attachment; filename="${safeFilename}.docx"`,
},
});
}
if (format === "markdown" || format === "md") {
const md = compileExportMarkdown(data);
return new NextResponse(md, {
headers: {
"Content-Type": "text/markdown; charset=utf-8",
"Content-Disposition": `attachment; filename="${safeFilename}.md"`,
},
});
}
return NextResponse.json(data);
} catch (err) {
return NextResponse.json(
{ error: err instanceof Error ? err.message : "Export failed" },
{ status: 500 },
);
}
}
+27
View File
@@ -0,0 +1,27 @@
import { NextResponse } from "next/server";
export const dynamic = "force-dynamic";
// GET /api/queue/status — BullMQ queue counts (read-only, public)
// Falls back gracefully when Redis is unavailable so the UI never breaks.
export async function GET() {
try {
const { getQueue } = await import("@mcpedia/queue");
const q = getQueue();
const [waiting, active, completed, failed, delayed] = await Promise.all([
q.getWaitingCount(),
q.getActiveCount(),
q.getCompletedCount(),
q.getFailedCount(),
q.getDelayedCount(),
]);
return NextResponse.json({ waiting, active, completed, failed, delayed });
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
// Return zeroed status so the FE can render gracefully
return NextResponse.json(
{ waiting: 0, active: 0, completed: 0, failed: 0, delayed: 0, error: msg },
{ status: 200 },
);
}
}
+20
View File
@@ -0,0 +1,20 @@
import { NextRequest, NextResponse } from "next/server";
import { getRelated } from "@mcpedia/core";
export const dynamic = "force-dynamic";
// GET /api/related?slug=...&limit=5
export async function GET(req: NextRequest) {
const slug = new URL(req.url).searchParams.get("slug") ?? "";
const limit = Math.min(Math.max(Number(new URL(req.url).searchParams.get("limit") ?? 5), 1), 20);
if (!slug.trim()) {
return NextResponse.json({ results: [] });
}
try {
const results = await getRelated(slug, limit);
return NextResponse.json({ results });
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
return NextResponse.json({ results: [], error: msg }, { status: 500 });
}
}
@@ -1,12 +1,32 @@
import { NextRequest, NextResponse } from "next/server";
import { restoreRevision, getRevision } from "@mcpedia/core";
import { WEBHOOK_SECRET } from "@mcpedia/config";
import { timingSafeEqual } from "node:crypto";
import { revalidatePath } from "next/cache";
function isAuthorized(req: NextRequest): boolean {
if (!WEBHOOK_SECRET) return false;
const headerSecret = req.headers.get("x-webhook-secret") ?? "";
if (headerSecret) {
const bufA = Buffer.from(headerSecret);
const bufB = Buffer.from(WEBHOOK_SECRET);
if (bufA.length === bufB.length && timingSafeEqual(bufA, bufB)) {
return true;
}
}
const cookie = req.cookies.get("mcpedia_admin")?.value ?? "";
return cookie.startsWith("admin.");
}
// POST /api/revisions/restore — restore a document to a past revision.
// Body (form-urlencoded): id=<revision uuid>
// After restoring, we rebuild semantic chunks (handled inside restoreRevision)
// and revalidate the doc page so the Web UI reflects the restored body.
export async function POST(req: NextRequest) {
if (!isAuthorized(req)) {
return NextResponse.json({ ok: false, error: "Unauthorized" }, { status: 401 });
}
const form = await req.formData().catch(() => null);
const id = form?.get("id");
if (typeof id !== "string" || id.length === 0) {
+21
View File
@@ -0,0 +1,21 @@
import { NextRequest, NextResponse } from "next/server";
import { listRevisions } from "@mcpedia/core";
export const dynamic = "force-dynamic";
// GET /api/revisions?slug=...&limit=10
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const slug = searchParams.get("slug") ?? "";
const limit = Math.min(Math.max(Number(searchParams.get("limit") ?? 10), 1), 50);
if (!slug.trim()) {
return NextResponse.json({ revisions: [] });
}
try {
const revisions = await listRevisions(slug, limit);
return NextResponse.json({ revisions });
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
return NextResponse.json({ revisions: [], error: msg }, { status: 500 });
}
}
+28
View File
@@ -0,0 +1,28 @@
import { NextResponse } from "next/server";
import { listDocuments } from "@mcpedia/core";
export const dynamic = "force-dynamic";
// GET /api/tags?limit=30 — aggregated tag counts
export async function GET(req: Request) {
const limit = Math.min(Math.max(Number(new URL(req.url).searchParams.get("limit") ?? 30), 1), 100);
try {
const docs = await listDocuments();
const counts = new Map<string, number>();
for (const d of docs) {
for (const t of d.tags ?? []) {
const tag = String(t).trim();
if (!tag) continue;
counts.set(tag, (counts.get(tag) ?? 0) + 1);
}
}
const tags = [...counts.entries()]
.map(([tag, count]) => ({ tag, count }))
.sort((a, b) => b.count - a.count || a.tag.localeCompare(b.tag))
.slice(0, limit);
return NextResponse.json({ tags });
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
return NextResponse.json({ tags: [], error: msg }, { status: 500 });
}
}
+92 -104
View File
@@ -3,28 +3,46 @@
import { useState, useEffect, useRef } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useSearch } from "@/hooks/useSearch";
import {
Search,
Plus,
ArrowRight,
BookOpen,
Flag,
Sparkles,
} from "lucide-react";
interface Hit {
slug: string;
interface QuickAction {
id: string;
title: string;
section: string;
snippet?: string;
score: number;
subtitle: string;
icon: React.ComponentType<{ className?: string }>;
href?: string;
}
export default function CommandMenu() {
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const [results, setResults] = useState<Hit[]>([]);
const [loading, setLoading] = useState(false);
const [selectedIndex, setSelectedIndex] = useState(0);
const router = useRouter();
const inputRef = useRef<HTMLInputElement>(null);
// Global shortcut ⌘K or /
const { hits, isSearching, isValidating } = useSearch(query, "hybrid", 10);
const results = query.trim() ? hits : [];
const loading = isSearching || isValidating;
const quickActions: QuickAction[] = [
{ id: "create-doc", title: "Create New Document", subtitle: "Write technical doc, writeup, or note", icon: Plus, href: "/create" },
{ id: "hybrid-search", title: "Multi-Modal Hybrid Search", subtitle: "Full-text + Semantic vector search console", icon: Search, href: "/search" },
{ id: "browse-docs", title: "Documentation Hub", subtitle: "System setup, API references, protocol specs", icon: BookOpen, href: "/docs" },
{ id: "browse-writeups", title: "CTF & Writeups Directory", subtitle: "Pwn, Reverse, Web, Crypto writeups and solutions", icon: Flag, href: "/writeups" },
{ id: "browse-research", title: "Research & Benchmarks", subtitle: "Architecture notes, benchmarks, experiments", icon: Sparkles, href: "/research" },
];
useEffect(() => {
function handleKeyDown(e: KeyboardEvent) {
if ((e.metaKey || e.ctrlKey) && e.key === "k") {
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
e.preventDefault();
setOpen((prev) => !prev);
} else if (e.key === "/" && !["INPUT", "TEXTAREA"].includes((e.target as HTMLElement)?.tagName)) {
@@ -42,48 +60,35 @@ export default function CommandMenu() {
if (open) {
setTimeout(() => inputRef.current?.focus(), 50);
setQuery("");
setResults([]);
setSelectedIndex(0);
}
}, [open]);
// Debounced search
useEffect(() => {
if (!query.trim()) {
setResults([]);
return;
}
const timer = setTimeout(async () => {
setLoading(true);
try {
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}&limit=8`);
const data = await res.json();
setResults(data.results || []);
setSelectedIndex(0);
} catch {
setResults([]);
} finally {
setLoading(false);
}
}, 150);
return () => clearTimeout(timer);
setSelectedIndex(0);
}, [query]);
function handleNavigate(slug: string) {
function handleNavigate(href: string) {
setOpen(false);
router.push(`/${slug}`);
router.push(href);
}
const totalItems = query.trim() ? results.length : quickActions.length;
function handleKeyNavigation(e: React.KeyboardEvent) {
if (e.key === "ArrowDown") {
e.preventDefault();
setSelectedIndex((prev) => (results.length > 0 ? (prev + 1) % results.length : 0));
setSelectedIndex((prev) => (totalItems > 0 ? (prev + 1) % totalItems : 0));
} else if (e.key === "ArrowUp") {
e.preventDefault();
setSelectedIndex((prev) => (results.length > 0 ? (prev - 1 + results.length) % results.length : 0));
} else if (e.key === "Enter" && results[selectedIndex]) {
setSelectedIndex((prev) => (totalItems > 0 ? (prev - 1 + totalItems) % totalItems : 0));
} else if (e.key === "Enter") {
e.preventDefault();
handleNavigate(results[selectedIndex].slug);
if (query.trim() && results[selectedIndex]) {
handleNavigate(`/${results[selectedIndex].slug}`);
} else if (!query.trim() && quickActions[selectedIndex]?.href) {
handleNavigate(quickActions[selectedIndex].href!);
}
}
}
@@ -91,102 +96,92 @@ export default function CommandMenu() {
return (
<button
onClick={() => setOpen(true)}
className="hidden md:flex items-center gap-2 px-3 py-1.5 bg-[var(--bg-surface)] hover:bg-[var(--bg-elevated)] border border-[var(--border-color)] hover:border-[var(--brand)] text-xs text-[var(--text-muted)] hover:text-[var(--text-primary)] rounded-lg transition-all shadow-sm"
type="button"
className="hidden md:flex items-center gap-2.5 px-3 py-1.5 bg-[var(--bg-elevated)] hover:bg-[var(--bg-elevated-hover)] border border-[var(--border-color)] hover:border-[var(--text-muted)] text-xs text-[var(--text-muted)] hover:text-[var(--text-primary)] rounded-md transition-all shadow-xs cursor-pointer group"
>
<svg className="w-3.5 h-3.5 text-[var(--text-dim)]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
<span>Search docs...</span>
<kbd className="ml-2 font-mono bg-[var(--bg-elevated)] px-1.5 py-0.5 rounded border border-[var(--border-color)] text-[10px] text-[var(--text-dim)]">
⌘K
</kbd>
<Search className="w-3.5 h-3.5 text-[var(--text-dim)] group-hover:text-[var(--text-primary)] transition-colors" />
<span className="font-sans">Search...</span>
<kbd className="ml-2 font-mono bg-[var(--bg-surface)] px-1.5 py-0.2 rounded border border-[var(--border-color)] text-[10px] text-[var(--text-muted)]">⌘K</kbd>
</button>
);
}
return (
<div className="fixed inset-0 z-50 flex items-start justify-center pt-20 px-4">
{/* Backdrop */}
<div
className="fixed inset-0 bg-black/60 dark:bg-black/80 backdrop-blur-sm transition-opacity"
onClick={() => setOpen(false)}
/>
{/* Modal */}
<div className="fixed inset-0 z-50 flex items-start justify-center pt-16 sm:pt-24 px-4">
<div className="fixed inset-0 bg-black/60 backdrop-blur-xs transition-opacity" onClick={() => setOpen(false)} />
<div className="relative w-full max-w-2xl bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl shadow-2xl overflow-hidden animate-fade-in">
{/* Search input bar */}
<div className="flex items-center gap-3 px-4 py-3.5 border-b border-[var(--border-color)] bg-[var(--bg-elevated)]">
<svg className="w-5 h-5 text-[#5e6ad2] dark:text-[#7170ff] shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
<div className="flex items-center gap-3 px-4 sm:px-5 py-3.5 border-b border-[var(--border-color)] bg-[var(--bg-elevated)]">
<Search className="w-4 h-4 text-[var(--text-muted)] shrink-0" />
<input
ref={inputRef}
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={handleKeyNavigation}
placeholder="Type to search (titles, keywords, concepts)..."
placeholder="Search documents, writeups, concepts, or tools..."
className="w-full bg-transparent text-[var(--text-primary)] placeholder-[var(--text-dim)] text-sm focus:outline-none"
/>
{loading && (
<div className="w-4 h-4 border-2 border-[#5e6ad2] border-t-transparent rounded-full animate-spin shrink-0" />
)}
<button
onClick={() => setOpen(false)}
className="text-xs text-[var(--text-muted)] hover:text-[var(--text-primary)] bg-[var(--bg-surface)] px-1.5 py-0.5 rounded border border-[var(--border-color)]"
>
ESC
</button>
{loading && <div className="w-4 h-4 border-2 border-[var(--text-muted)] border-t-transparent rounded-full animate-spin shrink-0" />}
<button onClick={() => setOpen(false)} type="button" className="text-[10px] font-mono text-[var(--text-dim)] hover:text-[var(--text-primary)] bg-[var(--bg-surface)] px-1.5 py-0.5 rounded border border-[var(--border-color)]">ESC</button>
</div>
{/* Results / Suggestions */}
<div className="max-h-96 overflow-y-auto p-2">
<div className="max-h-[22rem] overflow-y-auto p-2">
{query.trim() === "" ? (
<div className="px-3 py-6 text-center">
<p className="text-xs text-[var(--text-muted)]">Search full-text, semantic embeddings, and CTF writeups.</p>
<div className="flex justify-center gap-2 mt-3 text-[11px] text-[var(--text-dim)]">
<span>Navigation: <kbd className="bg-[var(--bg-elevated)] px-1 py-0.5 rounded border border-[var(--border-color)]">↑</kbd> <kbd className="bg-[var(--bg-elevated)] px-1 py-0.5 rounded border border-[var(--border-color)]">↓</kbd></span>
<span>Select: <kbd className="bg-[var(--bg-elevated)] px-1 py-0.5 rounded border border-[var(--border-color)]">↵</kbd></span>
</div>
<div className="p-1 space-y-0.5">
<div className="px-2.5 py-1 text-[10px] font-mono uppercase tracking-wider text-[var(--text-muted)]">Quick Shortcuts</div>
{quickActions.map((action, idx) => {
const Icon = action.icon;
const isSelected = idx === selectedIndex;
return (
<div
key={action.id}
onClick={() => action.href && handleNavigate(action.href)}
onMouseEnter={() => setSelectedIndex(idx)}
className={`flex items-center justify-between gap-3 px-3 py-2 rounded-lg cursor-pointer transition-colors ${isSelected ? "bg-[var(--bg-elevated)] text-[var(--text-primary)]" : "hover:bg-[var(--bg-elevated)] text-[var(--text-secondary)]"}`}
>
<div className="flex items-center gap-2.5">
<div className={`p-1.5 rounded ${isSelected ? "bg-[var(--brand)] text-[var(--brand-fg)]" : "bg-[var(--bg-elevated)] text-[var(--text-muted)]"}`}>
<Icon className="w-3.5 h-3.5" />
</div>
<div>
<div className="text-xs font-semibold text-[var(--text-primary)]">{action.title}</div>
<div className="text-[11px] text-[var(--text-muted)]">{action.subtitle}</div>
</div>
</div>
<ArrowRight className={`w-3.5 h-3.5 text-[var(--text-dim)] ${isSelected ? "text-[var(--text-primary)]" : ""}`} />
</div>
);
})}
</div>
) : results.length === 0 && !loading ? (
<div className="px-4 py-8 text-center text-xs text-[var(--text-muted)]">
No documents matching &quot;{query}&quot;
<div className="px-4 py-10 text-center text-xs text-[var(--text-muted)] space-y-1">
<p>No knowledge base items matched &quot;{query}&quot;</p>
</div>
) : (
<ul className="space-y-1">
<ul className="space-y-1 p-1">
{results.map((hit, index) => {
const isSelected = index === selectedIndex;
return (
<li
key={hit.slug}
onClick={() => handleNavigate(hit.slug)}
onClick={() => handleNavigate(`/${hit.slug}`)}
onMouseEnter={() => setSelectedIndex(index)}
className={`flex items-start justify-between gap-3 px-3 py-2.5 rounded-lg cursor-pointer transition-all ${
isSelected
? "bg-[#5e6ad2]/15 border border-[#5e6ad2]/40 text-[var(--text-primary)]"
: "hover:bg-[var(--bg-elevated)] text-[var(--text-secondary)] border border-transparent"
}`}
className={`flex items-start justify-between gap-3 px-3 py-2.5 rounded-lg cursor-pointer transition-colors ${isSelected ? "bg-[var(--bg-elevated)] text-[var(--text-primary)] border border-[var(--border-color)]" : "hover:bg-[var(--bg-elevated)] text-[var(--text-secondary)] border border-transparent"}`}
>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="text-xs px-1.5 py-0.25 bg-[var(--bg-elevated)] border border-[var(--border-color)] rounded text-[#5e6ad2] dark:text-[#7170ff] font-mono">
{hit.section}
</span>
<span className={`text-sm font-medium ${isSelected ? "text-[#5e6ad2] dark:text-[#7170ff]" : "text-[var(--text-primary)]"} truncate`}>
{hit.title}
</span>
<div className="flex items-center gap-2 mb-0.5">
<span className="text-[10px] font-mono px-1.5 py-0.2 bg-[var(--bg-elevated)] border border-[var(--border-color)] rounded text-[var(--text-muted)] uppercase font-semibold">{hit.section}</span>
<span className="text-xs sm:text-sm font-semibold text-[var(--text-primary)] truncate">{hit.title}</span>
</div>
{hit.snippet && (
<p
className="text-xs text-[var(--text-muted)] mt-1 line-clamp-1 [&>mark]:bg-[#5e6ad2]/30 [&>mark]:text-[var(--text-primary)] [&>mark]:rounded [&>mark]:px-0.5"
className="text-xs text-[var(--text-muted)] line-clamp-1 mt-1 [&>mark]:bg-[var(--bg-elevated-hover)] [&>mark]:text-[var(--text-primary)] [&>mark]:font-semibold"
// snippet is server-sanitized ts_headline output
dangerouslySetInnerHTML={{ __html: hit.snippet }}
/>
)}
</div>
<span className="text-[11px] text-[var(--text-dim)] shrink-0 self-center">
{hit.slug}
</span>
<span className="text-[10px] font-mono text-[var(--text-dim)] shrink-0 self-center">/{hit.slug}</span>
</li>
);
})}
@@ -194,16 +189,9 @@ export default function CommandMenu() {
)}
</div>
{/* Footer */}
<div className="flex items-center justify-between px-4 py-2.5 border-t border-[var(--border-color)] bg-[var(--bg-elevated)] text-[11px] text-[var(--text-dim)]">
<span>Tip: Press <kbd className="bg-[var(--bg-surface)] px-1 py-0.5 rounded border border-[var(--border-color)]">Hybrid</kbd> search is enabled</span>
<Link
href={`/search?q=${encodeURIComponent(query)}`}
onClick={() => setOpen(false)}
className="hover:text-[#5e6ad2] dark:hover:text-[#7170ff] transition-colors"
>
Open full search page →
</Link>
<div className="flex items-center justify-between px-4 py-2 border-t border-[var(--border-color)] bg-[var(--bg-elevated)] text-[10px] text-[var(--text-muted)] font-mono">
<div className="flex items-center gap-2"><span>[ ↑↓ NAVIGATE ]</span><span>[ ↵ SELECT ]</span></div>
<Link href={`/search?q=${encodeURIComponent(query)}`} onClick={() => setOpen(false)} className="hover:text-[var(--text-primary)] font-medium flex items-center gap-1"><span>Full Search Console</span><ArrowRight className="w-3 h-3" /></Link>
</div>
</div>
</div>
+40 -22
View File
@@ -2,6 +2,14 @@
import { useState } from "react";
import Link from "next/link";
import {
Copy,
Check,
Share2,
FileDown,
FileText,
Edit3,
} from "lucide-react";
interface DocActionsProps {
slug: string;
@@ -27,62 +35,72 @@ export default function DocActions({ slug, body, canEdit }: DocActionsProps) {
return (
<div className="flex items-center gap-1.5 shrink-0 flex-wrap">
{/* Copy Markdown */}
{/* Copy Raw Markdown */}
<button
onClick={handleCopyMarkdown}
type="button"
title="Copy raw markdown content"
className="inline-flex items-center gap-1 px-2.5 py-1 text-xs bg-[var(--bg-surface)] hover:bg-[var(--bg-elevated)] border border-[var(--border-color)] hover:border-[var(--brand)] text-[var(--text-muted)] hover:text-[var(--text-primary)] rounded-md transition-all shadow-sm"
className="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs bg-[var(--bg-surface)] hover:bg-[var(--bg-elevated)] border border-[var(--border-color)] text-[var(--text-muted)] hover:text-[var(--text-primary)] rounded-md transition-colors shadow-xs cursor-pointer"
>
{copiedMd ? (
<>
<svg className="w-3.5 h-3.5 text-emerald-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
<span className="text-emerald-500 font-medium">Copied MD</span>
<Check className="w-3.5 h-3.5 text-emerald-500" />
<span className="text-emerald-500 font-medium">Copied</span>
</>
) : (
<>
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7v8a2 2 0 002 2h6M8 7V5a2 2 0 012-2h4.586a1 1 0 01.707.293l4.414 4.414a1 1 0 01.293.707V15a2 2 0 01-2 2h-2M8 7H6a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2v-2" />
</svg>
<Copy className="w-3.5 h-3.5" />
<span>Raw MD</span>
</>
)}
</button>
{/* Copy Link */}
{/* Copy Share Link */}
<button
onClick={handleCopyLink}
type="button"
title="Copy link to document"
className="inline-flex items-center gap-1 px-2.5 py-1 text-xs bg-[var(--bg-surface)] hover:bg-[var(--bg-elevated)] border border-[var(--border-color)] hover:border-[var(--brand)] text-[var(--text-muted)] hover:text-[var(--text-primary)] rounded-md transition-all shadow-sm"
className="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs bg-[var(--bg-surface)] hover:bg-[var(--bg-elevated)] border border-[var(--border-color)] text-[var(--text-muted)] hover:text-[var(--text-primary)] rounded-md transition-colors shadow-xs cursor-pointer"
>
{copiedLink ? (
<>
<svg className="w-3.5 h-3.5 text-emerald-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
<span className="text-emerald-500 font-medium">Copied Link</span>
<Check className="w-3.5 h-3.5 text-emerald-500" />
<span className="text-emerald-500 font-medium">Copied</span>
</>
) : (
<>
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
</svg>
<Share2 className="w-3.5 h-3.5" />
<span>Share</span>
</>
)}
</button>
{/* Export PDF */}
<Link
href={`/${slug}/export`}
title="Export document to publication-grade PDF"
className="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs bg-[var(--bg-surface)] hover:bg-[var(--bg-elevated)] border border-[var(--border-color)] text-[var(--text-muted)] hover:text-[var(--text-primary)] rounded-md transition-colors shadow-xs"
>
<FileDown className="w-3.5 h-3.5" />
<span>PDF</span>
</Link>
{/* Export Word (.docx) */}
<a
href={`/api/export?path=${encodeURIComponent(slug)}&format=docx`}
title="Download editable Microsoft Word (.docx) file"
className="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs bg-[var(--bg-surface)] hover:bg-[var(--bg-elevated)] border border-[var(--border-color)] text-[var(--text-muted)] hover:text-[var(--text-primary)] rounded-md transition-colors shadow-xs cursor-pointer"
>
<FileText className="w-3.5 h-3.5" />
<span>Word (.docx)</span>
</a>
{/* Edit Link */}
<Link
href={canEdit ? `/${slug}?edit=1` : `/login?redirect=/${slug}`}
className="inline-flex items-center gap-1 px-2.5 py-1 text-xs bg-[#5e6ad2]/10 hover:bg-[#5e6ad2]/20 border border-[#5e6ad2]/30 hover:border-[#5e6ad2]/60 text-[#5e6ad2] dark:text-[#7170ff] rounded-md transition-all font-medium"
className="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs bg-[var(--bg-elevated)] hover:bg-[var(--bg-elevated-hover)] border border-[var(--border-color)] text-[var(--text-primary)] rounded-md transition-colors font-medium shadow-xs"
>
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
<Edit3 className="w-3.5 h-3.5" />
<span>Edit</span>
</Link>
</div>
+150 -109
View File
@@ -2,7 +2,21 @@
import { useState, useRef } from "react";
import { useRouter } from "next/navigation";
import { mutate } from "swr";
import Markdown from "./Markdown";
import {
Bold,
Italic,
Heading2,
Heading3,
Code,
Link as LinkIcon,
Plus,
Trash2,
Eye,
Edit3,
Sliders,
} from "lucide-react";
interface DocFormProps {
mode: "create" | "edit";
@@ -22,8 +36,26 @@ interface DocFormProps {
};
}
const DEFAULT_SECTION_LIST = ["docs", "writeups", "research", "notes", "guides", "tutorials", "ctf", "api", "projects"];
const DEFAULT_TYPE_LIST = ["documentation", "writeup", "research", "note", "guide", "tutorial", "spec"];
const DEFAULT_SECTION_LIST = [
"docs",
"writeups",
"research",
"notes",
"guides",
"tutorials",
"ctf",
"api",
"projects",
];
const DEFAULT_TYPE_LIST = [
"documentation",
"writeup",
"research",
"note",
"guide",
"tutorial",
"spec",
];
const PRESET_FIELDS = [
{ key: "difficulty", value: "medium" },
@@ -88,7 +120,7 @@ export default function DocForm({
const availableFolders = existingFolders?.[section] ?? [];
const baseInputCls =
"w-full px-3.5 py-2 bg-[var(--bg-surface)] border border-[var(--border-color)] hover:border-[var(--brand)] rounded-lg text-sm text-[var(--text-primary)] placeholder-[var(--text-dim)] focus:outline-none focus:border-[var(--brand)] focus:ring-1 focus:ring-[#5e6ad2] transition-colors";
"w-full px-3.5 py-2 bg-[var(--bg-surface)] border border-[var(--border-color)] hover:border-[var(--text-muted)] rounded-lg text-sm text-[var(--text-primary)] placeholder-[var(--text-dim)] focus:outline-none focus:border-[var(--text-primary)] transition-colors";
function addCustomField(key = "", value = "") {
setCustomFields([...customFields, { key, value }]);
@@ -128,7 +160,7 @@ export default function DocForm({
setError(null);
if (!effectiveSlug || !title || !body) {
setError("Slug, title, and body are required.");
setError("Slug, title, and markdown body are required.");
setLoading(false);
return;
}
@@ -175,11 +207,16 @@ export default function DocForm({
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data.error ?? "Save failed");
throw new Error(data.error ?? "Failed to save document. Verify ADMIN_PASSWORD or secret.");
}
const result = await res.json();
// Invalidate SWR caches so Sidebar/Header/search reflect the change immediately
mutate("/api/docs");
mutate("/api/sections");
mutate((key) => typeof key === "string" && key.startsWith("/api/tags"));
router.push(result.doc?.slug ? `/${result.doc.slug}` : "/");
router.refresh();
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
@@ -190,75 +227,73 @@ export default function DocForm({
return (
<form onSubmit={handleSubmit} className="space-y-6 max-w-4xl">
{error && (
<div className="p-3.5 rounded-lg border border-rose-500/30 bg-rose-500/10 text-rose-500 dark:text-rose-400 text-sm">
<div className="p-3.5 rounded-lg border border-rose-500/30 bg-rose-500/10 text-rose-500 dark:text-rose-400 text-xs font-medium animate-fade-in">
{error}
</div>
)}
{/* Title */}
{/* Document Title */}
<div>
<label className="block text-xs font-semibold uppercase tracking-wider text-[var(--text-muted)] mb-1.5">
<label className="block text-xs font-semibold uppercase tracking-wider text-[var(--text-muted)] mb-1.5 font-mono">
Document Title *
</label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="e.g. Database Architecture Overview"
className={`${baseInputCls} text-base`}
placeholder="e.g. Exploiting Stack Alignment Issues in x86_64"
className={`${baseInputCls} text-base font-semibold`}
required
/>
</div>
{/* Section + Type + Status */}
{/* Section, Type, Status */}
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<div>
<label className="block text-xs font-semibold uppercase tracking-wider text-[var(--text-muted)] mb-1.5">
<label className="block text-xs font-semibold uppercase tracking-wider text-[var(--text-muted)] mb-1.5 font-mono">
Section
</label>
<div className="relative">
<input
type="text"
list="section-list"
value={section}
onChange={(e) => setSection(e.target.value)}
placeholder="e.g. docs, writeups, ctf, guides"
className={baseInputCls}
required
/>
<datalist id="section-list">
{sectionOptions.map((s) => (
<option key={s} value={s}>
{s.toUpperCase()}
</option>
))}
</datalist>
</div>
<input
type="text"
list="section-list"
value={section}
onChange={(e) => setSection(e.target.value)}
placeholder="e.g. docs, writeups, research"
className={baseInputCls}
required
/>
<datalist id="section-list">
{sectionOptions.map((s) => (
<option key={s} value={s}>
{s.toUpperCase()}
</option>
))}
</datalist>
</div>
<div>
<label className="block text-xs font-semibold uppercase tracking-wider text-[var(--text-muted)] mb-1.5">
Type
<label className="block text-xs font-semibold uppercase tracking-wider text-[var(--text-muted)] mb-1.5 font-mono">
Document Type
</label>
<div className="relative">
<input
type="text"
list="type-list"
value={type}
onChange={(e) => setType(e.target.value)}
placeholder="e.g. documentation, writeup, note"
className={baseInputCls}
/>
<datalist id="type-list">
{DEFAULT_TYPE_LIST.map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</datalist>
</div>
<input
type="text"
list="type-list"
value={type}
onChange={(e) => setType(e.target.value)}
placeholder="e.g. writeup, documentation, note"
className={baseInputCls}
/>
<datalist id="type-list">
{DEFAULT_TYPE_LIST.map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</datalist>
</div>
<div>
<label className="block text-xs font-semibold uppercase tracking-wider text-[var(--text-muted)] mb-1.5">
<label className="block text-xs font-semibold uppercase tracking-wider text-[var(--text-muted)] mb-1.5 font-mono">
Status
</label>
<select
@@ -267,7 +302,7 @@ export default function DocForm({
className={baseInputCls}
>
<option value="published">Published</option>
<option value="draft">Draft</option>
<option value="draft">Draft (Unindexed)</option>
</select>
</div>
</div>
@@ -275,8 +310,8 @@ export default function DocForm({
{/* Folder + Slug */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-xs font-semibold uppercase tracking-wider text-[var(--text-muted)] mb-1.5">
Parent Folder
<label className="block text-xs font-semibold uppercase tracking-wider text-[var(--text-muted)] mb-1.5 font-mono">
Parent Folder / Chapter
</label>
<select
value={parentFolder}
@@ -292,9 +327,10 @@ export default function DocForm({
))}
</select>
</div>
<div>
<label className="block text-xs font-semibold uppercase tracking-wider text-[var(--text-muted)] mb-1.5">
{isEdit ? "Full Slug" : "Slug (File name) *"}
<label className="block text-xs font-semibold uppercase tracking-wider text-[var(--text-muted)] mb-1.5 font-mono">
{isEdit ? "Document Path" : "Slug (File name) *"}
</label>
{isEdit ? (
<input
@@ -309,12 +345,12 @@ export default function DocForm({
value={slugInput}
onChange={(e) => setSlugInput(e.target.value)}
className={`${baseInputCls} font-mono`}
placeholder="my-new-post"
placeholder="ret2win-guide"
required
/>
)}
<p className="text-[11px] text-[var(--text-dim)] mt-1 font-mono">
Path: <span className="text-[#5e6ad2] dark:text-[#7170ff]">{effectiveSlug || section}</span>
<p className="text-[11px] text-[var(--text-dim)] mt-1.5 font-mono">
Full Slug: <span className="text-[var(--text-primary)] font-semibold">{effectiveSlug || section}</span>
</p>
</div>
</div>
@@ -322,7 +358,7 @@ export default function DocForm({
{/* Tags + Author */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-xs font-semibold uppercase tracking-wider text-[var(--text-muted)] mb-1.5">
<label className="block text-xs font-semibold uppercase tracking-wider text-[var(--text-muted)] mb-1.5 font-mono">
Tags (comma separated)
</label>
<input
@@ -330,11 +366,11 @@ export default function DocForm({
value={tags}
onChange={(e) => setTags(e.target.value)}
className={baseInputCls}
placeholder="ctf, pwn, reverse, tutorial"
placeholder="pwn, x86_64, rop, ctf"
/>
</div>
<div>
<label className="block text-xs font-semibold uppercase tracking-wider text-[var(--text-muted)] mb-1.5">
<label className="block text-xs font-semibold uppercase tracking-wider text-[var(--text-muted)] mb-1.5 font-mono">
Author
</label>
<input
@@ -342,31 +378,32 @@ export default function DocForm({
value={author}
onChange={(e) => setAuthor(e.target.value)}
className={baseInputCls}
placeholder="asep"
placeholder="e.g. asepharyana"
/>
</div>
</div>
{/* Custom Metadata Fields */}
<div className="p-4 bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl space-y-3 shadow-sm">
<div className="flex items-center justify-between">
<div className="p-4 bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl space-y-3.5 shadow-xs">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
<div>
<h3 className="text-xs font-semibold uppercase tracking-wider text-[var(--text-muted)]">
Dynamic Custom Metadata
<h3 className="text-xs font-semibold uppercase tracking-wider text-[var(--text-muted)] font-mono flex items-center gap-1.5">
<Sliders className="w-3.5 h-3.5 text-[var(--text-muted)]" />
<span>Technical Metadata</span>
</h3>
<p className="text-[11px] text-[var(--text-dim)] mt-0.5">
Add custom key-values (event, difficulty, points, etc.) rendered as styled badges.
Custom fields (points, difficulty, event, solved) will render as styled badges in the document hero.
</p>
</div>
<div className="flex items-center gap-1.5 flex-wrap">
<span className="text-[11px] text-[var(--text-dim)]">Presets:</span>
<div className="flex items-center gap-1 flex-wrap">
<span className="text-[10px] font-mono text-[var(--text-dim)] uppercase">Presets:</span>
{PRESET_FIELDS.map((preset) => (
<button
key={preset.key}
type="button"
onClick={() => addCustomField(preset.key, preset.value)}
className="px-2 py-0.5 text-[11px] bg-[var(--bg-elevated)] hover:bg-[var(--bg-elevated-hover)] border border-[var(--border-color)] text-[var(--text-muted)] hover:text-[var(--text-primary)] rounded transition-colors"
className="px-2 py-0.5 text-[10px] bg-[var(--bg-elevated)] hover:bg-[var(--bg-elevated-hover)] border border-[var(--border-color)] text-[var(--text-muted)] hover:text-[var(--text-primary)] rounded transition-colors font-mono cursor-pointer"
>
+{preset.key}
</button>
@@ -393,10 +430,10 @@ export default function DocForm({
<button
type="button"
onClick={() => removeCustomField(i)}
className="p-2 text-rose-500 hover:text-rose-600 rounded hover:bg-[var(--bg-elevated)] transition-colors"
className="p-2 text-rose-500 hover:text-rose-600 rounded hover:bg-[var(--bg-elevated)] transition-colors cursor-pointer"
title="Remove field"
>
✕
<Trash2 className="w-4 h-4" />
</button>
</div>
))}
@@ -404,14 +441,15 @@ export default function DocForm({
<button
type="button"
onClick={() => addCustomField()}
className="text-xs text-[#5e6ad2] dark:text-[#7170ff] hover:underline px-3 py-1.5 rounded-lg border border-[#5e6ad2]/30 hover:border-[#5e6ad2]/60 bg-[#5e6ad2]/5 transition-colors font-medium"
className="inline-flex items-center gap-1.5 text-xs text-[var(--text-primary)] hover:underline px-3 py-1 rounded-md border border-[var(--border-color)] bg-[var(--bg-elevated)] hover:bg-[var(--bg-elevated-hover)] transition-colors font-medium cursor-pointer"
>
+ Add Custom Field
<Plus className="w-3.5 h-3.5" />
<span>Add Custom Field</span>
</button>
</div>
{/* Body with Write / Preview Tabs */}
<div className="border border-[var(--border-color)] rounded-xl overflow-hidden bg-[var(--bg-surface)] shadow-sm">
{/* Markdown Body Editor */}
<div className="border border-[var(--border-color)] rounded-xl overflow-hidden bg-[var(--bg-surface)] shadow-xs">
{/* Editor Toolbar */}
<div className="flex items-center justify-between px-3 py-2 bg-[var(--bg-elevated)] border-b border-[var(--border-color)] flex-wrap gap-2">
{/* Tabs */}
@@ -419,90 +457,92 @@ export default function DocForm({
<button
type="button"
onClick={() => setActiveTab("write")}
className={`px-3 py-1 text-xs rounded-md font-medium transition-all ${
className={`flex items-center gap-1.5 px-3 py-1 text-xs rounded font-semibold transition-all cursor-pointer ${
activeTab === "write"
? "bg-[#5e6ad2] text-white shadow-sm"
? "bg-[var(--brand)] text-[var(--brand-fg)] shadow-xs"
: "text-[var(--text-muted)] hover:text-[var(--text-primary)]"
}`}
>
Write
<Edit3 className="w-3.5 h-3.5" />
<span>Write</span>
</button>
<button
type="button"
onClick={() => setActiveTab("preview")}
className={`px-3 py-1 text-xs rounded-md font-medium transition-all ${
className={`flex items-center gap-1.5 px-3 py-1 text-xs rounded font-semibold transition-all cursor-pointer ${
activeTab === "preview"
? "bg-[#5e6ad2] text-white shadow-sm"
? "bg-[var(--brand)] text-[var(--brand-fg)] shadow-xs"
: "text-[var(--text-muted)] hover:text-[var(--text-primary)]"
}`}
>
Live Preview
<Eye className="w-3.5 h-3.5" />
<span>Preview</span>
</button>
</div>
{/* Markdown Action Shortcuts */}
{/* Quick Markdown Formatter Shortcuts */}
{activeTab === "write" && (
<div className="flex items-center gap-1 text-xs text-[var(--text-muted)]">
<button
type="button"
onClick={() => insertMarkdown("**", "**")}
className="px-2 py-0.5 hover:bg-[var(--bg-surface)] rounded text-[var(--text-secondary)] hover:text-[var(--text-primary)]"
className="p-1 hover:bg-[var(--bg-surface)] rounded hover:text-[var(--text-primary)]"
title="Bold"
>
<b>B</b>
<Bold className="w-3.5 h-3.5" />
</button>
<button
type="button"
onClick={() => insertMarkdown("*", "*")}
className="px-2 py-0.5 hover:bg-[var(--bg-surface)] rounded text-[var(--text-secondary)] hover:text-[var(--text-primary)]"
className="p-1 hover:bg-[var(--bg-surface)] rounded hover:text-[var(--text-primary)]"
title="Italic"
>
<i>I</i>
<Italic className="w-3.5 h-3.5" />
</button>
<button
type="button"
onClick={() => insertMarkdown("## ")}
className="px-2 py-0.5 hover:bg-[var(--bg-surface)] rounded text-[var(--text-secondary)] hover:text-[var(--text-primary)]"
className="p-1 hover:bg-[var(--bg-surface)] rounded hover:text-[var(--text-primary)]"
title="Heading 2"
>
H2
<Heading2 className="w-3.5 h-3.5" />
</button>
<button
type="button"
onClick={() => insertMarkdown("### ")}
className="p-1 hover:bg-[var(--bg-surface)] rounded hover:text-[var(--text-primary)]"
title="Heading 3"
>
<Heading3 className="w-3.5 h-3.5" />
</button>
<button
type="button"
onClick={() => insertMarkdown("```\n", "\n```")}
className="px-2 py-0.5 hover:bg-[var(--bg-surface)] rounded text-[var(--text-secondary)] hover:text-[var(--text-primary)] font-mono"
className="p-1 hover:bg-[var(--bg-surface)] rounded hover:text-[var(--text-primary)]"
title="Code Block"
>
{"</>"}
<Code className="w-3.5 h-3.5" />
</button>
<button
type="button"
onClick={() => insertMarkdown("[", "](https://)")}
className="px-2 py-0.5 hover:bg-[var(--bg-surface)] rounded text-[var(--text-secondary)] hover:text-[var(--text-primary)]"
className="p-1 hover:bg-[var(--bg-surface)] rounded hover:text-[var(--text-primary)]"
title="Link"
>
Link
</button>
<button
type="button"
onClick={() => insertMarkdown("> [!NOTE]\n> ")}
className="px-2 py-0.5 hover:bg-[var(--bg-surface)] rounded text-[var(--text-secondary)] hover:text-[var(--text-primary)]"
title="Note Callout"
>
Note
<LinkIcon className="w-3.5 h-3.5" />
</button>
</div>
)}
</div>
{/* Tab content */}
{/* Tab Content */}
{activeTab === "write" ? (
<textarea
ref={textareaRef}
value={body}
onChange={(e) => setBody(e.target.value)}
className="w-full h-96 p-4 bg-transparent text-[var(--text-primary)] placeholder-[var(--text-dim)] font-mono text-sm focus:outline-none resize-y leading-relaxed"
placeholder="# Write your markdown document here..."
placeholder="# Write your technical documentation or writeup here in Markdown..."
required
/>
) : (
@@ -510,28 +550,29 @@ export default function DocForm({
{body.trim() ? (
<Markdown source={body} />
) : (
<p className="text-xs text-[var(--text-dim)] italic">Nothing to preview yet.</p>
<p className="text-xs text-[var(--text-dim)] italic font-mono">No content to preview yet.</p>
)}
</div>
)}
</div>
{/* Actions */}
{/* Submit Action Buttons */}
<div className="flex items-center gap-3">
<button
type="submit"
disabled={loading}
className="px-6 py-2.5 bg-[#5e6ad2] hover:bg-[#6a75e0] text-white rounded-lg font-medium text-sm transition-all shadow-md shadow-[#5e6ad2]/20 disabled:opacity-50 flex items-center gap-2"
className="px-6 py-2.5 bg-[var(--brand)] hover:opacity-90 text-[var(--brand-fg)] rounded-lg font-semibold text-xs transition-all shadow-xs disabled:opacity-50 flex items-center gap-2 cursor-pointer font-mono uppercase tracking-wider"
>
{loading && (
<div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
<div className="w-3.5 h-3.5 border-2 border-current border-t-transparent rounded-full animate-spin" />
)}
<span>{loading ? "Saving document..." : mode === "create" ? "Create Document" : "Save Changes"}</span>
<span>{loading ? "PERSISTING..." : mode === "create" ? "PUBLISH_DOCUMENT" : "SAVE_CHANGES"}</span>
</button>
<button
type="button"
onClick={() => router.back()}
className="px-4 py-2.5 border border-[var(--border-color)] hover:border-[var(--brand)] text-[var(--text-muted)] hover:text-[var(--text-primary)] bg-[var(--bg-surface)] rounded-lg text-sm transition-colors shadow-sm"
className="px-4 py-2.5 border border-[var(--border-color)] hover:border-[var(--text-muted)] text-[var(--text-muted)] hover:text-[var(--text-primary)] bg-[var(--bg-surface)] rounded-lg text-xs transition-colors shadow-xs cursor-pointer font-mono"
>
Cancel
</button>
+88
View File
@@ -0,0 +1,88 @@
import Link from "next/link";
import { Clock, FileText } from "lucide-react";
import type { DocumentMeta } from "@mcpedia/types";
import { getSectionMeta } from "@mcpedia/config/sections";
export function DocumentCard({
doc,
showSection = false,
score,
}: {
doc: DocumentMeta;
showSection?: boolean;
score?: number;
}) {
const sInfo = getSectionMeta(doc.section);
return (
<Link
href={`/${doc.slug}`}
className="group flex items-center justify-between gap-4 p-4 bg-[var(--bg-surface)] hover:bg-[var(--bg-surface-hover)] border border-[var(--border-color)] hover:border-[var(--text-muted)] rounded-xl transition-all shadow-xs"
>
<div className="flex items-center gap-3 min-w-0">
<FileText className="w-4 h-4 text-[var(--text-muted)] shrink-0" />
<div className="min-w-0">
<h3 className="text-xs sm:text-sm font-semibold text-[var(--text-primary)] group-hover:underline truncate">
{doc.title}
</h3>
<div className="flex flex-wrap items-center gap-1.5 mt-1.5">
{showSection && (
<span className="text-[10px] font-mono px-1.5 py-0.2 bg-[var(--bg-elevated)] border border-[var(--border-color)] rounded text-[var(--text-muted)] uppercase font-semibold">
{sInfo.icon} {doc.section}
</span>
)}
{doc.tags.slice(0, 4).map((t: string) => (
<span
key={t}
className="text-[10px] px-1.5 py-0.2 bg-[var(--bg-elevated)] border border-[var(--border-color)] rounded text-[var(--text-muted)] font-mono"
>
#{t}
</span>
))}
{typeof score === "number" && (
<span className="text-[10px] font-mono text-[var(--text-dim)] bg-[var(--bg-elevated)] px-1.5 py-0.2 rounded">
{score.toFixed(3)}
</span>
)}
</div>
</div>
</div>
<time className="text-xs text-[var(--text-dim)] font-mono shrink-0 flex items-center gap-1">
<Clock className="w-3 h-3" />
<span>
{new Date(doc.updatedAt).toLocaleDateString(undefined, { month: "short", day: "numeric" })}
</span>
</time>
</Link>
);
}
export function CompactDocCard({ doc, snippet, score }: { doc: DocumentMeta; snippet?: string; score?: number }) {
const sInfo = getSectionMeta(doc.section);
return (
<Link
href={`/${doc.slug}`}
className="group block bg-[var(--bg-surface)] hover:bg-[var(--bg-surface-hover)] border border-[var(--border-color)] hover:border-[var(--text-muted)] rounded-xl p-4.5 transition-all shadow-xs"
>
<div className="flex items-center justify-between gap-3 mb-2">
<div className="flex items-center gap-2">
<span className="text-[10px] font-mono px-1.5 py-0.2 rounded bg-[var(--bg-elevated)] border border-[var(--border-color)] text-[var(--text-muted)] uppercase font-semibold">
{sInfo.icon} {doc.section}
</span>
<span className="text-xs text-[var(--text-dim)] font-mono truncate">/{doc.slug}</span>
</div>
{typeof score === "number" && (
<span className="text-xs font-mono text-[var(--text-dim)] bg-[var(--bg-elevated)] px-2 py-0.5 rounded">
{score.toFixed(3)}
</span>
)}
</div>
<h2 className="text-sm font-semibold text-[var(--text-primary)] group-hover:underline mb-1.5">{doc.title}</h2>
{snippet && (
<p
className="text-xs text-[var(--text-muted)] leading-relaxed line-clamp-2 [&>mark]:bg-[var(--bg-elevated-hover)] [&>mark]:text-[var(--text-primary)] [&>mark]:font-semibold"
dangerouslySetInnerHTML={{ __html: snippet }}
/>
)}
</Link>
);
}
+53
View File
@@ -0,0 +1,53 @@
import { FileQuestion, SearchX, AlertCircle, Inbox } from "lucide-react";
import Link from "next/link";
export function EmptyState({
title = "No results",
description,
icon: Icon = Inbox,
action,
}: {
title?: string;
description?: string;
icon?: typeof Inbox;
action?: { label: string; href: string };
}) {
return (
<div className="text-center py-12 bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl shadow-xs space-y-3">
<div className="w-10 h-10 rounded-xl bg-[var(--bg-elevated)] border border-[var(--border-color)] flex items-center justify-center mx-auto text-[var(--text-muted)]">
<Icon className="w-5 h-5" />
</div>
<h3 className="text-sm font-bold text-[var(--text-primary)]">{title}</h3>
{description && <p className="text-xs text-[var(--text-muted)] max-w-sm mx-auto leading-relaxed">{description}</p>}
{action && (
<Link
href={action.href}
className="inline-flex items-center gap-1.5 text-xs bg-[var(--brand)] text-[var(--brand-fg)] px-3 py-1.5 rounded-md font-semibold mt-2"
>
{action.label}
</Link>
)}
</div>
);
}
export function ErrorState({ message, onRetry }: { message?: string; onRetry?: () => void }) {
return (
<div className="p-4 rounded-xl border border-amber-500/30 bg-amber-500/10 text-amber-900 dark:text-amber-200 text-xs flex items-start gap-2.5">
<AlertCircle className="w-4 h-4 shrink-0 mt-0.5" />
<div className="flex-1 min-w-0">
<div className="font-semibold">Something went wrong</div>
{message && <div className="text-[11px] opacity-80 mt-1 break-words">{message}</div>}
</div>
{onRetry && (
<button
onClick={onRetry}
type="button"
className="shrink-0 px-2.5 py-1 rounded bg-[var(--bg-surface)] border border-[var(--border-color)] text-[var(--text-primary)] font-semibold hover:bg-[var(--bg-elevated)]"
>
Retry
</button>
)}
</div>
);
}
+77 -68
View File
@@ -1,47 +1,47 @@
"use client";
import { useState, useEffect } from "react";
import { useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { DEFAULT_SECTIONS, type SectionConfig } from "@mcpedia/config/sections";
import { DEFAULT_SECTIONS } from "@mcpedia/config/sections";
import { useSections } from "@/hooks/useSections";
import ThemeToggle from "@/components/ThemeToggle";
import CommandMenu from "@/components/CommandMenu";
import {
Plus,
Search,
Menu,
X,
Lock,
} from "lucide-react";
export default function Header() {
const pathname = usePathname();
const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
const [sections, setSections] = useState<SectionConfig[]>(DEFAULT_SECTIONS);
useEffect(() => {
fetch("/api/sections")
.then((r) => r.json())
.then((data) => {
if (Array.isArray(data) && data.length > 0) {
setSections(data);
}
})
.catch(() => {});
}, []);
const { data: liveSections } = useSections();
const sections = liveSections && liveSections.length > 0 ? liveSections : DEFAULT_SECTIONS;
return (
<header className="sticky top-0 z-30 border-b border-[var(--border-color)] glass-nav">
<div className="mx-auto max-w-7xl px-4 sm:px-6 h-14 flex items-center justify-between gap-4">
<header className="site-header no-print sticky top-0 z-40 border-b border-[var(--border-color)] glass-nav transition-all">
<div className="mx-auto max-w-7xl px-4 sm:px-6 h-14 flex items-center justify-between gap-3 sm:gap-4">
{/* Brand */}
<div className="flex items-center gap-3">
<Link href="/" className="flex items-center gap-2 group">
<div className="w-7 h-7 rounded-lg bg-gradient-to-br from-[#5e6ad2] to-[#7170ff] flex items-center justify-center text-white font-bold text-xs shadow-md shadow-[#5e6ad2]/20 group-hover:scale-105 transition-transform">
<Link href="/" className="flex items-center gap-2.5 group">
<div className="flex items-center justify-center w-7 h-7 rounded-md bg-[var(--brand)] text-[var(--brand-fg)] font-mono font-bold text-xs shadow-xs group-hover:opacity-90 transition-opacity">
M
</div>
<span className="font-semibold text-[var(--text-primary)] text-base tracking-tight transition-colors">
MCPedia
</span>
<div className="flex items-center gap-2">
<span className="font-bold text-[var(--text-primary)] text-sm tracking-tight leading-none">
MCPedia
</span>
<span className="text-[10px] font-mono px-1.5 py-0.2 rounded bg-[var(--bg-elevated)] border border-[var(--border-color)] text-[var(--text-muted)] hidden sm:inline-block">
CORE::DB
</span>
</div>
</Link>
<span className="hidden sm:inline-block text-[10px] uppercase font-mono px-1.5 py-0.5 rounded bg-[var(--bg-elevated)] border border-[var(--border-color)] text-[var(--text-muted)]">
v0.1.0
</span>
</div>
{/* Desktop Nav */}
{/* Center: Desktop Sections Nav */}
<nav className="hidden md:flex items-center gap-1">
{sections.map((s) => {
const isActive = pathname === `/${s.id}` || pathname.startsWith(`/${s.id}/`);
@@ -49,101 +49,110 @@ export default function Header() {
<Link
key={s.id}
href={`/${s.id}`}
className={`px-3 py-1.5 rounded-md text-xs font-medium transition-all ${
className={`px-3 py-1 rounded-md text-xs font-medium transition-colors flex items-center gap-1.5 ${
isActive
? "text-[var(--text-primary)] bg-[var(--bg-elevated)] border border-[var(--border-color)]"
: "text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-surface-hover)]"
? "text-[var(--text-primary)] bg-[var(--bg-elevated)] border border-[var(--border-color)] font-semibold"
: "text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-elevated)]"
}`}
>
<span className="mr-1.5 opacity-80">{s.icon}</span>
{s.label}
<span>{s.icon}</span>
<span>{s.label}</span>
</Link>
);
})}
</nav>
{/* Right tools */}
<div className="flex items-center gap-2.5">
{/* Right Tools & Navigation Deck */}
<div className="flex items-center gap-2">
<CommandMenu />
<Link
href="/search"
className="md:hidden p-1.5 text-[var(--text-muted)] hover:text-[var(--text-primary)] rounded-lg hover:bg-[var(--bg-elevated)] transition-colors"
title="Search"
className="md:hidden p-1.5 text-[var(--text-muted)] hover:text-[var(--text-primary)] rounded-md bg-[var(--bg-surface)] border border-[var(--border-color)] transition-colors"
title="Search knowledge base"
>
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
<Search className="w-4 h-4" />
</Link>
<Link
href="/create"
className="hidden sm:inline-flex items-center gap-1.5 px-3 py-1 bg-[#5e6ad2] hover:bg-[#7170ff] text-white text-xs font-medium rounded-lg transition-all shadow-sm"
className="hidden sm:inline-flex items-center gap-1.5 px-3 py-1.5 bg-[var(--brand)] hover:opacity-90 text-[var(--brand-fg)] text-xs font-semibold rounded-md shadow-xs transition-all cursor-pointer"
>
<span>+</span>
<Plus className="w-3.5 h-3.5" />
<span>New Doc</span>
</Link>
<Link
href="/login"
className={`px-2.5 py-1 text-xs rounded-lg transition-colors ${
className={`p-1.5 sm:px-2.5 sm:py-1.5 text-xs rounded-md transition-colors flex items-center gap-1.5 ${
pathname === "/login"
? "text-[var(--text-primary)] bg-[var(--bg-elevated)] font-medium"
? "text-[var(--text-primary)] bg-[var(--bg-elevated)] font-semibold border border-[var(--border-color)]"
: "text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-elevated)]"
}`}
title="Admin Login"
>
Login
<Lock className="w-3.5 h-3.5" />
<span className="hidden sm:inline">Admin</span>
</Link>
<div className="border-l border-[var(--border-color)] pl-2.5 flex items-center">
<div className="border-l border-[var(--border-color)] pl-2 flex items-center">
<ThemeToggle />
</div>
{/* Mobile menu toggle */}
<button
onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
className="md:hidden p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)]"
className="md:hidden p-1.5 text-[var(--text-muted)] hover:text-[var(--text-primary)] rounded-md hover:bg-[var(--bg-elevated)] transition-colors"
aria-label="Toggle navigation"
>
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
{mobileMenuOpen ? (
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
) : (
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
)}
</svg>
{mobileMenuOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
</button>
</div>
</div>
{/* Mobile Drawer */}
{mobileMenuOpen && (
<div className="md:hidden border-t border-[var(--border-color)] bg-[var(--bg-surface)] px-4 py-3 space-y-1 animate-fade-in shadow-lg">
{sections.map((s) => (
<Link
key={s.id}
href={`/${s.id}`}
onClick={() => setMobileMenuOpen(false)}
className="flex items-center gap-2 px-3 py-2 rounded-lg text-sm text-[var(--text-secondary)] hover:bg-[var(--bg-elevated)] hover:text-[var(--text-primary)]"
>
<span>{s.icon}</span>
<span>{s.label}</span>
</Link>
))}
<div className="pt-2 border-t border-[var(--border-color)] flex gap-2">
<div className="md:hidden border-t border-[var(--border-color)] bg-[var(--bg-surface)] px-4 py-4 space-y-2 animate-fade-in shadow-lg">
<div className="text-[10px] font-mono uppercase tracking-wider text-[var(--text-muted)] px-1 mb-1">
Knowledge Sections
</div>
<div className="grid grid-cols-2 gap-1.5">
{sections.map((s) => {
const isActive = pathname === `/${s.id}` || pathname.startsWith(`/${s.id}/`);
return (
<Link
key={s.id}
href={`/${s.id}`}
onClick={() => setMobileMenuOpen(false)}
className={`flex items-center gap-2 px-3 py-2 rounded-md text-xs font-medium transition-colors ${
isActive
? "bg-[var(--bg-elevated)] text-[var(--text-primary)] border border-[var(--border-color)] font-semibold"
: "text-[var(--text-secondary)] hover:bg-[var(--bg-elevated)] hover:text-[var(--text-primary)]"
}`}
>
<span>{s.icon}</span>
<span className="truncate">{s.label}</span>
</Link>
);
})}
</div>
<div className="pt-3 border-t border-[var(--border-color)] flex gap-2">
<Link
href="/search"
onClick={() => setMobileMenuOpen(false)}
className="flex-1 text-center py-2 text-xs bg-[var(--bg-elevated)] text-[var(--text-secondary)] rounded-lg font-medium border border-[var(--border-color)]"
className="flex-1 flex items-center justify-center gap-1.5 py-2 text-xs bg-[var(--bg-elevated)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] rounded-md font-medium border border-[var(--border-color)]"
>
Search
<Search className="w-3.5 h-3.5" />
<span>Search</span>
</Link>
<Link
href="/create"
onClick={() => setMobileMenuOpen(false)}
className="flex-1 text-center py-2 text-xs bg-[#5e6ad2] text-white rounded-lg font-medium"
className="flex-1 flex items-center justify-center gap-1.5 py-2 text-xs bg-[var(--brand)] text-[var(--brand-fg)] rounded-md font-semibold shadow-xs"
>
+ Create
<Plus className="w-3.5 h-3.5" />
<span>Create Doc</span>
</Link>
</div>
</div>
@@ -0,0 +1,376 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import {
Cpu,
Database,
Layers,
Sparkles,
Search,
Globe,
Server,
ArrowRight,
CheckCircle2,
} from "lucide-react";
interface NodeDetail {
id: string;
title: string;
badge: string;
type: "client" | "protocol" | "core" | "storage";
icon: any;
desc: string;
metrics: { label: string; value: string }[];
features: string[];
docLink?: string;
}
const NODES: NodeDetail[] = [
{
id: "ai-agents",
title: "AI Coding Agents",
badge: "MCP::CLIENT",
type: "client",
icon: Sparkles,
desc: "Claude Desktop, Cursor, Antigravity, and Zed connect via Model Context Protocol to read and write technical knowledge directly.",
metrics: [
{ label: "Transport", value: "Stdio / HTTP SSE" },
{ label: "Tools Exposed", value: "13 Native Tools" },
{ label: "Authentication", value: "x-webhook-secret" },
],
features: [
"Semantic similarity search over chunks",
"Direct document CRUD into Postgres",
"Context retrieval for debugging & CTF writeups",
],
docLink: "/docs",
},
{
id: "web-ui",
title: "Human Web Interface",
badge: "UI::NEXTJS",
type: "client",
icon: Globe,
desc: "Fast, accessible developer web interface with dark/light themes, keyboard shortcuts, and instant search.",
metrics: [
{ label: "Framework", value: "Next.js 16.3" },
{ label: "Styling", value: "Tailwind CSS v4" },
{ label: "Command Menu", value: "⌘K Omnisearch" },
],
features: [
"Hierarchical folder directory tree",
"Publication-grade PDF export generator",
"Live markdown editor with revision rollback",
],
docLink: "/docs",
},
{
id: "mcp-server",
title: "MCP Server Gateway",
badge: "PORT::4021",
type: "protocol",
icon: Server,
desc: "Streamable Model Context Protocol server exposing tool endpoints and resource URIs.",
metrics: [
{ label: "Port", value: ":4021" },
{ label: "Protocol", value: "MCP 2024-11-05" },
{ label: "Runtime", value: "Bun Engine" },
],
features: [
"get_document / create_document tools",
"search_hybrid / search_semantic tools",
"list_sections & list_revisions resources",
],
docLink: "/api",
},
{
id: "core-engine",
title: "@mcpedia/core",
badge: "CORE::PACKAGE",
type: "core",
icon: Layers,
desc: "Unified business logic layer shared across Web, MCP Server, REST API, and Background Workers.",
metrics: [
{ label: "Architecture", value: "Monorepo Package" },
{ label: "Validation", value: "Strict Type Safety" },
{ label: "Ranking", value: "RRF Hybrid Fusion" },
],
features: [
"Path classification & folder hierarchy",
"Markdown document chunking & tokenization",
"Drizzle ORM transactional schema mapping",
],
docLink: "/research",
},
{
id: "search-engine",
title: "Multi-Modal Search Engine",
badge: "SEARCH::RRF",
type: "core",
icon: Search,
desc: "Reciprocal Rank Fusion uniting Postgres Full-Text Search tsvectors with vector embeddings.",
metrics: [
{ label: "FTS Algorithm", value: "tsvector + GIN" },
{ label: "Vector Search", value: "Cosine Similarity" },
{ label: "Fusion Constant", value: "k = 60" },
],
features: [
"Sub-millisecond keyword retrieval",
"Conceptual similarity matching",
"Instant snippet generation with highlight markers",
],
docLink: "/search",
},
{
id: "postgres-db",
title: "PostgreSQL 16 + pgvector",
badge: "DB::POSTGRES",
type: "storage",
icon: Database,
desc: "ACID-compliant relational database storing document bodies, revision trees, vector embeddings, and full-text indexes.",
metrics: [
{ label: "Extension", value: "vector (1536 dim)" },
{ label: "Backups", value: "Auto .md to disk" },
{ label: "Isolation", value: "Transactional" },
],
features: [
"HNSW vector index for embeddings",
"Complete revision history preservation",
"Instant document schema migrations",
],
docLink: "/docs",
},
];
export default function InteractiveTopology() {
const [activeNodeId, setActiveNodeId] = useState<string>("core-engine");
const activeNode = NODES.find((n) => n.id === activeNodeId) || NODES[0];
const ActiveIcon = activeNode.icon;
return (
<div className="bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl overflow-hidden shadow-xs">
{/* Header Bar */}
<div className="p-4 sm:p-5 border-b border-[var(--border-color)] bg-[var(--bg-elevated)] flex flex-col sm:flex-row sm:items-center justify-between gap-3">
<div>
<div className="flex items-center gap-2 mb-1">
<span className="w-1.5 h-1.5 rounded-full bg-emerald-500" />
<span className="text-[10px] font-mono uppercase tracking-wider text-[var(--text-muted)]">
Architecture Schematic
</span>
</div>
<h3 className="text-base sm:text-lg font-bold text-[var(--text-primary)] tracking-tight">
System Topology: Single Core Architecture
</h3>
</div>
<div className="flex items-center gap-2">
<span className="text-[11px] font-mono text-[var(--text-muted)] bg-[var(--bg-surface)] border border-[var(--border-color)] px-2 py-1 rounded">
Click nodes to inspect
</span>
</div>
</div>
{/* Grid Layout */}
<div className="grid grid-cols-1 lg:grid-cols-12">
{/* Visual Map Column (Left) */}
<div className="lg:col-span-7 p-5 border-b lg:border-b-0 lg:border-r border-[var(--border-color)] bg-[var(--bg-app)] flex flex-col justify-between space-y-5">
{/* Layer 1: Clients */}
<div>
<span className="text-[10px] font-mono uppercase tracking-widest text-[var(--text-muted)] mb-2 block">
1. Ingestion & Access Layer
</span>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
{NODES.filter((n) => n.type === "client").map((node) => {
const Icon = node.icon;
const isSelected = activeNodeId === node.id;
return (
<button
key={node.id}
onClick={() => setActiveNodeId(node.id)}
type="button"
className={`p-3 rounded-lg border text-left transition-all cursor-pointer ${
isSelected
? "bg-[var(--bg-surface)] border-[var(--text-primary)] shadow-xs ring-1 ring-[var(--text-primary)]"
: "bg-[var(--bg-surface)] border-[var(--border-color)] hover:border-[var(--text-muted)]"
}`}
>
<div className="flex items-center justify-between mb-2">
<div className={`p-1.5 rounded ${isSelected ? "bg-[var(--brand)] text-[var(--brand-fg)]" : "bg-[var(--bg-elevated)] text-[var(--text-muted)]"}`}>
<Icon className="w-3.5 h-3.5" />
</div>
<span className="text-[10px] font-mono px-1.5 py-0.2 rounded bg-[var(--bg-elevated)] text-[var(--text-muted)] border border-[var(--border-color)]">
{node.badge}
</span>
</div>
<div className="font-semibold text-xs text-[var(--text-primary)]">{node.title}</div>
</button>
);
})}
</div>
</div>
{/* Flow Connector Arrow */}
<div className="flex justify-center text-[var(--text-dim)]">
<span className="text-[10px] font-mono px-2.5 py-0.5 rounded bg-[var(--bg-surface)] border border-[var(--border-color)]">
↓ Protocol Gateway
</span>
</div>
{/* Layer 2: Protocol & Core Services */}
<div>
<span className="text-[10px] font-mono uppercase tracking-widest text-[var(--text-muted)] mb-2 block">
2. Core Engine & Protocol Layer
</span>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-2.5">
{NODES.filter((n) => n.type === "protocol" || n.type === "core").map((node) => {
const Icon = node.icon;
const isSelected = activeNodeId === node.id;
return (
<button
key={node.id}
onClick={() => setActiveNodeId(node.id)}
type="button"
className={`p-3 rounded-lg border text-left transition-all cursor-pointer ${
isSelected
? "bg-[var(--bg-surface)] border-[var(--text-primary)] shadow-xs ring-1 ring-[var(--text-primary)]"
: "bg-[var(--bg-surface)] border-[var(--border-color)] hover:border-[var(--text-muted)]"
}`}
>
<div className="flex items-center justify-between mb-2">
<div className={`p-1.5 rounded ${isSelected ? "bg-[var(--brand)] text-[var(--brand-fg)]" : "bg-[var(--bg-elevated)] text-[var(--text-muted)]"}`}>
<Icon className="w-3.5 h-3.5" />
</div>
</div>
<div className="font-semibold text-xs text-[var(--text-primary)] leading-tight mb-0.5 truncate">
{node.title}
</div>
<div className="text-[10px] text-[var(--text-muted)] font-mono truncate">
{node.badge}
</div>
</button>
);
})}
</div>
</div>
{/* Flow Connector Arrow */}
<div className="flex justify-center text-[var(--text-dim)]">
<span className="text-[10px] font-mono px-2.5 py-0.5 rounded bg-[var(--bg-surface)] border border-[var(--border-color)]">
↓ Persistent Storage Layer
</span>
</div>
{/* Layer 3: Storage */}
<div>
<span className="text-[10px] font-mono uppercase tracking-widest text-[var(--text-muted)] mb-2 block">
3. Database (Source of Truth)
</span>
{NODES.filter((n) => n.type === "storage").map((node) => {
const Icon = node.icon;
const isSelected = activeNodeId === node.id;
return (
<button
key={node.id}
onClick={() => setActiveNodeId(node.id)}
type="button"
className={`w-full p-3 rounded-lg border text-left transition-all cursor-pointer ${
isSelected
? "bg-[var(--bg-surface)] border-[var(--text-primary)] shadow-xs ring-1 ring-[var(--text-primary)]"
: "bg-[var(--bg-surface)] border-[var(--border-color)] hover:border-[var(--text-muted)]"
}`}
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className={`p-1.5 rounded ${isSelected ? "bg-[var(--brand)] text-[var(--brand-fg)]" : "bg-[var(--bg-elevated)] text-[var(--text-muted)]"}`}>
<Icon className="w-4 h-4" />
</div>
<div>
<div className="font-semibold text-xs text-[var(--text-primary)]">{node.title}</div>
<div className="text-[11px] text-[var(--text-muted)]">Source of truth for all content & embeddings</div>
</div>
</div>
<span className="text-[10px] font-mono px-1.5 py-0.2 rounded bg-[var(--bg-elevated)] text-[var(--text-muted)] border border-[var(--border-color)]">
{node.badge}
</span>
</div>
</button>
);
})}
</div>
</div>
{/* Node Inspector Details Column (Right) */}
<div className="lg:col-span-5 p-5 bg-[var(--bg-surface)] flex flex-col justify-between space-y-5 animate-fade-in">
<div>
{/* Inspector Header */}
<div className="flex items-start justify-between gap-3 mb-3">
<div className="flex items-center gap-2.5">
<div className="w-9 h-9 rounded-lg bg-[var(--bg-elevated)] border border-[var(--border-color)] text-[var(--text-primary)] flex items-center justify-center">
<ActiveIcon className="w-4 h-4" />
</div>
<div>
<h4 className="text-sm font-bold text-[var(--text-primary)]">{activeNode.title}</h4>
<span className="text-[10px] font-mono text-[var(--text-muted)]">
{activeNode.badge}
</span>
</div>
</div>
</div>
<p className="text-xs text-[var(--text-secondary)] leading-relaxed mb-5">
{activeNode.desc}
</p>
{/* Telemetry Metrics */}
<div className="mb-5">
<span className="text-[10px] font-semibold uppercase tracking-wider text-[var(--text-muted)] font-mono mb-2 block">
Specifications
</span>
<div className="space-y-1.5">
{activeNode.metrics.map((m) => (
<div
key={m.label}
className="flex items-center justify-between p-2 bg-[var(--bg-elevated)] border border-[var(--border-color)] rounded text-xs"
>
<span className="text-[var(--text-muted)] text-[11px]">{m.label}</span>
<span className="font-mono font-medium text-[var(--text-primary)] text-[11px]">{m.value}</span>
</div>
))}
</div>
</div>
{/* Key Capabilities */}
<div>
<span className="text-[10px] font-semibold uppercase tracking-wider text-[var(--text-muted)] font-mono mb-2 block">
Capabilities
</span>
<ul className="space-y-1.5">
{activeNode.features.map((feat, idx) => (
<li key={idx} className="flex items-start gap-2 text-xs text-[var(--text-secondary)]">
<span className="text-emerald-500 shrink-0 font-mono text-[11px]">✓</span>
<span>{feat}</span>
</li>
))}
</ul>
</div>
</div>
{/* Link to Documentation */}
{activeNode.docLink && (
<div className="pt-3 border-t border-[var(--border-color)]">
<Link
href={activeNode.docLink}
className="inline-flex items-center justify-center gap-1.5 w-full py-2 bg-[var(--bg-elevated)] hover:bg-[var(--bg-elevated-hover)] border border-[var(--border-color)] text-xs font-semibold text-[var(--text-primary)] rounded-lg transition-colors group"
>
<span>Read documentation</span>
<ArrowRight className="w-3.5 h-3.5 group-hover:translate-x-0.5 transition-transform" />
</Link>
</div>
)}
</div>
</div>
</div>
);
}
+128 -43
View File
@@ -4,20 +4,44 @@ import React, { useState } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import rehypeSlug from "rehype-slug";
import rehypeHighlight from "rehype-highlight";
import {
Copy,
Check,
Info,
Lightbulb,
AlertTriangle,
Flame,
ShieldAlert,
} from "lucide-react";
function CodeBlock({ children, className, ...props }: React.HTMLAttributes<HTMLElement>) {
function extractText(node: React.ReactNode): string {
if (node === null || node === undefined || typeof node === "boolean") {
return "";
}
if (typeof node === "string" || typeof node === "number") {
return String(node);
}
if (Array.isArray(node)) {
return node.map(extractText).join("");
}
if (React.isValidElement(node)) {
return extractText((node.props as { children?: React.ReactNode })?.children);
}
return "";
}
function PreBlock({ children, ...props }: React.HTMLAttributes<HTMLPreElement>) {
const [copied, setCopied] = useState(false);
const textContent = String(children).replace(/\n$/, "");
const match = /language-(\w+)/.exec(className || "");
const language = match ? match[1] : "";
const textContent = extractText(children).replace(/\n$/, "");
// If inline code
if (!className && typeof children === "string" && !children.includes("\n")) {
return (
<code className={className} {...props}>
{children}
</code>
);
let language = "text";
if (React.isValidElement(children)) {
const className = (children.props as { className?: string })?.className || "";
const match = /language-(\w+)/.exec(className);
if (match) {
language = match[1];
}
}
function handleCopy() {
@@ -27,37 +51,42 @@ function CodeBlock({ children, className, ...props }: React.HTMLAttributes<HTMLE
}
return (
<div className="relative group my-4 rounded-lg overflow-hidden border border-[#23252a] bg-[#0c0d0e]">
<div className="code-block-wrapper relative group my-6 print:my-2 rounded-xl print:rounded border border-[var(--border-code)] print:border-slate-300 bg-[var(--code-block-bg)] print:bg-slate-50 shadow-sm print:shadow-none">
{/* Code block header bar */}
<div className="flex items-center justify-between px-3.5 py-1.5 bg-[#141517] border-b border-[#1f2022] text-[11px] text-[#8a8f98] font-mono">
<span>{language || "text"}</span>
<div className="code-block-header flex items-center justify-between px-4 py-2.5 print:px-2.5 print:py-0.5 bg-[var(--code-header-bg)] print:bg-slate-100 border-b border-[var(--border-code)] print:border-slate-300 text-xs font-mono select-none">
<div className="flex items-center gap-2.5">
<div className="no-print flex items-center gap-1.5 opacity-75 group-hover:opacity-100 transition-opacity">
<span className="w-2.5 h-2.5 rounded-full bg-rose-500/80 inline-block" />
<span className="w-2.5 h-2.5 rounded-full bg-amber-500/80 inline-block" />
<span className="w-2.5 h-2.5 rounded-full bg-emerald-500/80 inline-block" />
</div>
<span className="text-[11px] print:text-[7pt] font-semibold uppercase tracking-wider text-[var(--text-muted)] print:text-slate-700 group-hover:text-[var(--text-primary)] transition-colors">
{language}
</span>
</div>
<button
onClick={handleCopy}
type="button"
className="flex items-center gap-1 text-[#8a8f98] hover:text-[#f7f8f8] bg-[#1a1b1d] hover:bg-[#23252a] px-2 py-0.5 rounded border border-[#27292d] transition-all"
aria-label="Copy code to clipboard"
className="no-print flex items-center gap-1.5 text-xs text-[var(--text-muted)] hover:text-[var(--text-primary)] bg-[var(--code-button-bg)] hover:bg-[var(--code-button-hover-bg)] px-2.5 py-1 rounded-md border border-[var(--border-code)] transition-all font-sans shadow-xs cursor-pointer"
>
{copied ? (
<>
<svg className="w-3 h-3 text-emerald-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
<span className="text-emerald-400 font-sans">Copied!</span>
<Check className="w-3.5 h-3.5 text-emerald-500" />
<span className="text-emerald-500 font-medium">Copied!</span>
</>
) : (
<>
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
<span className="font-sans">Copy</span>
<Copy className="w-3.5 h-3.5" />
<span>Copy</span>
</>
)}
</button>
</div>
<pre className="!m-0 !bg-transparent p-4 overflow-x-auto text-sm text-[#e2e4e7] font-mono leading-relaxed">
<code className={className} {...props}>
{children}
</code>
<pre className="!m-0 !bg-transparent p-4 sm:p-5 print:p-2 overflow-x-auto text-[13px] sm:text-[13.5px] print:text-[7.5pt] text-[var(--pre-text)] print:text-slate-900 font-mono leading-relaxed print:leading-snug" {...props}>
{children}
</pre>
</div>
);
@@ -66,32 +95,88 @@ function CodeBlock({ children, className, ...props }: React.HTMLAttributes<HTMLE
export default function Markdown({ source }: { source: string }) {
return (
<div
className="prose prose-invert max-w-none
prose-headings:text-[#f7f8f8] prose-headings:font-medium prose-headings:tracking-tight
prose-h1:text-2xl prose-h1:mb-6 prose-h1:mt-8 prose-h1:pb-2 prose-h1:border-b prose-h1:border-[#1f2022]
prose-h2:text-xl prose-h2:mb-4 prose-h2:mt-8
prose-h3:text-base prose-h3:mb-3 prose-h3:mt-6
prose-p:text-[#d0d6e0] prose-p:leading-relaxed prose-p:mb-4
prose-a:text-[#7170ff] prose-a:no-underline hover:prose-a:underline hover:prose-a:text-[#828fff]
prose-ul:text-[#d0d6e0] prose-ul:my-3 prose-li:my-1
prose-ol:text-[#d0d6e0] prose-ol:my-3
prose-strong:text-[#f7f8f8] prose-strong:font-semibold
prose-hr:border-[#1f2022] prose-hr:my-8"
className="prose max-w-none
prose-headings:text-[var(--text-primary)] prose-headings:font-bold prose-headings:tracking-tight
prose-h1:text-2xl sm:prose-h1:text-3xl prose-h1:mb-6 prose-h1:mt-8 prose-h1:pb-3 prose-h1:border-b prose-h1:border-[var(--border-color)] print:prose-h1:text-[13pt] print:prose-h1:mt-2 print:prose-h1:mb-1 print:prose-h1:pb-0.5
prose-h2:text-xl sm:prose-h2:text-2xl prose-h2:mb-4 prose-h2:mt-8 prose-h2:pb-2 prose-h2:border-b prose-h2:border-[var(--border-subtle)] print:prose-h2:text-[10.5pt] print:prose-h2:mt-2 print:prose-h2:mb-1 print:prose-h2:pb-0.5
prose-h3:text-lg prose-h3:mb-3 prose-h3:mt-6 print:prose-h3:text-[9.5pt] print:prose-h3:mt-1.5 print:prose-h3:mb-0.5
prose-p:text-[var(--text-secondary)] prose-p:leading-relaxed prose-p:mb-4 print:prose-p:text-[8.5pt] print:prose-p:leading-snug print:prose-p:mb-1.5
prose-a:text-[var(--accent)] prose-a:font-medium prose-a:no-underline hover:prose-a:underline hover:prose-a:text-[var(--accent-hover)]
prose-ul:text-[var(--text-secondary)] prose-ul:my-4 prose-li:my-1.5 print:prose-ul:my-1 print:prose-li:my-0.5
prose-ol:text-[var(--text-secondary)] prose-ol:my-4 print:prose-ol:my-1
prose-strong:text-[var(--text-primary)] prose-strong:font-semibold
prose-hr:border-[var(--border-color)] prose-hr:my-8 print:prose-hr:my-2"
>
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeSlug]}
rehypePlugins={[rehypeSlug, rehypeHighlight]}
components={{
code: CodeBlock as any,
pre: ({ children }) => <>{children}</>,
pre: PreBlock as any,
code: ({ children, className, ...props }: React.HTMLAttributes<HTMLElement>) => {
if (className?.includes("hljs") || className?.includes("language-")) {
return (
<code className={className} {...props}>
{children}
</code>
);
}
return (
<code
className="px-1.5 py-0.5 rounded-md print:rounded-none bg-[var(--code-inline-bg)] print:bg-slate-100 text-[var(--code-inline-text)] print:text-slate-900 border border-[var(--code-inline-border)] print:border-slate-200 font-mono text-[0.875em] print:text-[7.5pt] font-medium"
{...props}
>
{children}
</code>
);
},
table: ({ node, ...props }) => (
<div className="overflow-x-auto my-6 border border-[#1f2022] rounded-lg">
<div className="overflow-x-auto my-6 print:my-1.5 border border-[var(--border-color)] print:border-slate-300 rounded-xl print:rounded-none shadow-xs print:shadow-none">
<table className="w-full border-collapse" {...props} />
</div>
),
blockquote: ({ children }) => {
const rawText = extractText(children).trim();
const alertMatch = rawText.match(/^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]/i);
if (alertMatch) {
const alertType = alertMatch[1].toUpperCase();
let borderClass = "border-indigo-500 bg-indigo-500/10 text-indigo-900 dark:text-indigo-200 print:bg-indigo-50 print:text-indigo-950";
let Icon = Info;
let title = "Note";
if (alertType === "TIP") {
borderClass = "border-emerald-500 bg-emerald-500/10 text-emerald-900 dark:text-emerald-200 print:bg-emerald-50 print:text-emerald-950";
Icon = Lightbulb;
title = "Tip";
} else if (alertType === "IMPORTANT") {
borderClass = "border-violet-500 bg-violet-500/10 text-violet-900 dark:text-violet-200 print:bg-violet-50 print:text-violet-950";
Icon = Flame;
title = "Important";
} else if (alertType === "WARNING") {
borderClass = "border-amber-500 bg-amber-500/10 text-amber-900 dark:text-amber-200 print:bg-amber-50 print:text-amber-950";
Icon = AlertTriangle;
title = "Warning";
} else if (alertType === "CAUTION") {
borderClass = "border-rose-500 bg-rose-500/10 text-rose-900 dark:text-rose-200 print:bg-rose-50 print:text-rose-950";
Icon = ShieldAlert;
title = "Caution";
}
return (
<div className={`my-5 print:my-1.5 p-4 print:p-2 rounded-xl print:rounded border-l-4 ${borderClass} shadow-xs print:shadow-none`}>
<div className="flex items-center gap-2 font-bold text-xs print:text-[7.5pt] uppercase tracking-wider mb-1.5 print:mb-0.5">
<Icon className="w-4 h-4 print:w-3 print:h-3" />
<span>{title}</span>
</div>
<div className="text-xs sm:text-sm print:text-[8pt] text-[var(--text-secondary)] print:text-slate-900 [&>p]:mb-1 [&>p:last-child]:mb-0 print:[&>p]:mb-0.5">
{children}
</div>
</div>
);
}
return (
<blockquote className="border-l-4 border-[#5e6ad2] bg-[#141517]/60 pl-4 py-2 my-4 rounded-r text-[#a0a4a8] not-italic">
<blockquote className="border-l-4 border-[var(--brand)] print:border-slate-500 bg-[var(--brand)]/5 dark:bg-[var(--brand)]/10 print:bg-slate-50 pl-4 print:pl-2.5 py-2.5 print:py-1 my-5 print:my-1.5 rounded-r-xl print:rounded-none text-[var(--text-secondary)] print:text-slate-900 not-italic print:text-[8pt]">
{children}
</blockquote>
);
+91 -38
View File
@@ -1,11 +1,22 @@
"use client";
import { useState } from "react";
import Markdown from "@/components/Markdown";
import {
Sparkles,
Terminal,
Server,
Copy,
Check,
Laptop,
} from "lucide-react";
const CONFIGS = [
{
id: "claude",
label: "Claude Desktop",
icon: Sparkles,
lang: "json",
filename: "~/Library/Application Support/Claude/claude_desktop_config.json",
content: `{
"mcpServers": {
@@ -13,17 +24,37 @@ const CONFIGS = [
"command": "bun",
"args": ["run", "/path/to/mcpedia/apps/mcp/src/index.ts"],
"env": {
"DATABASE_URL": "postgresql://...",
"DATABASE_URL": "postgresql://postgres:password@localhost:5432/mcpedia",
"OPENROUTER_API_KEY": "sk-or-v1-..."
}
}
}
}`,
},
{
id: "cursor",
label: "Cursor AI",
icon: Laptop,
lang: "json",
filename: ".cursor/mcp.json",
content: `{
"mcpServers": {
"mcpedia": {
"command": "bun",
"args": ["run", "/path/to/mcpedia/apps/mcp/src/index.ts"],
"env": {
"DATABASE_URL": "postgresql://postgres:password@localhost:5432/mcpedia"
}
}
}
}`,
},
{
id: "http",
label: "Remote HTTP (SSE)",
filename: "Streamable HTTP Endpoint",
label: "Streamable HTTP (SSE)",
icon: Server,
lang: "json",
filename: "Streamable HTTP Client Config",
content: `{
"mcpServers": {
"mcpedia-remote": {
@@ -37,12 +68,14 @@ const CONFIGS = [
},
{
id: "cli",
label: "CLI Client",
filename: "Terminal One-Shot / REPL",
content: `# One-shot question
bun run apps/mcp-client/src/ask.ts "How does ret2win stack alignment work?"
label: "CLI & Scripts",
icon: Terminal,
lang: "bash",
filename: "Terminal Subprocess / REPL",
content: `# Semantic question answering via MCP client
bun run apps/mcp-client/src/ask.ts "How does ret2win stack alignment work in x86_64?"
# Interactive REPL
# Interactive REPL with tool discovery
bun run apps/mcp-client/src/index.ts`,
},
];
@@ -53,49 +86,55 @@ export default function McpConfigSnippet() {
const current = CONFIGS.find((c) => c.id === activeTab) || CONFIGS[0];
function handleCopy() {
const markdownSnippet = `\`\`\`${current.lang}
${current.content}
\`\`\``;
function handleCopyAll() {
navigator.clipboard.writeText(current.content);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}
return (
<div className="bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl overflow-hidden shadow-md">
<div className="bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl overflow-hidden shadow-xs">
{/* Header bar with tabs */}
<div className="flex items-center justify-between px-4 py-2.5 bg-[var(--bg-elevated)] border-b border-[var(--border-color)] flex-wrap gap-2">
<div className="flex items-center gap-1.5">
{CONFIGS.map((c) => (
<button
key={c.id}
onClick={() => setActiveTab(c.id)}
className={`px-3 py-1 text-xs rounded-md font-medium transition-all ${
activeTab === c.id
? "bg-[#5e6ad2] text-white shadow-sm"
: "text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-surface)]"
}`}
>
{c.label}
</button>
))}
<div className="flex items-center gap-1.5 flex-wrap">
{CONFIGS.map((c) => {
const Icon = c.icon;
const isSelected = activeTab === c.id;
return (
<button
key={c.id}
onClick={() => setActiveTab(c.id)}
type="button"
className={`flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-md font-medium transition-all cursor-pointer ${
isSelected
? "bg-[var(--brand)] text-[var(--brand-fg)] font-semibold shadow-xs"
: "text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-surface)]"
}`}
>
<Icon className="w-3.5 h-3.5" />
<span>{c.label}</span>
</button>
);
})}
</div>
<button
onClick={handleCopy}
onClick={handleCopyAll}
type="button"
className="flex items-center gap-1.5 text-xs text-[var(--text-muted)] hover:text-[var(--text-primary)] bg-[var(--bg-surface)] hover:bg-[var(--bg-elevated-hover)] px-2.5 py-1 rounded border border-[var(--border-color)] transition-all shadow-sm"
className="flex items-center gap-1.5 px-2.5 py-1 text-xs bg-[var(--bg-surface)] hover:bg-[var(--bg-elevated-hover)] border border-[var(--border-color)] text-[var(--text-primary)] rounded-md transition-colors shadow-xs cursor-pointer font-medium"
>
{copied ? (
<>
<svg className="w-3.5 h-3.5 text-emerald-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
<span className="text-emerald-500 font-medium">Copied!</span>
<Check className="w-3.5 h-3.5 text-emerald-500" />
<span className="text-emerald-500">Copied</span>
</>
) : (
<>
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
<Copy className="w-3.5 h-3.5" />
<span>Copy Config</span>
</>
)}
@@ -103,12 +142,26 @@ export default function McpConfigSnippet() {
</div>
{/* Code preview */}
<pre className="p-4 text-xs font-mono text-[var(--pre-text)] bg-[var(--code-block-bg)] overflow-x-auto leading-relaxed">
<code>{current.content}</code>
</pre>
<div className="p-4 sm:p-5 [&>.prose>.group]:my-0 [&>.prose]:max-w-none">
<Markdown source={markdownSnippet} />
</div>
<div className="px-4 py-2 bg-[var(--bg-elevated)] border-t border-[var(--border-color)] text-[11px] text-[var(--text-dim)]">
Config location: <span className="font-mono text-[var(--text-muted)]">{current.filename}</span>
{/* Footer Info */}
<div className="px-4 py-2.5 bg-[var(--bg-elevated)] border-t border-[var(--border-color)] text-xs text-[var(--text-dim)] flex flex-col sm:flex-row sm:items-center justify-between gap-2">
<div className="flex items-center gap-2">
<span className="font-mono uppercase text-[10px] text-[var(--text-muted)]">
Target File:
</span>
<span className="font-mono text-[var(--text-secondary)] text-[11px]">
{current.filename}
</span>
</div>
<div className="flex items-center gap-3 text-[11px] font-mono">
<span className="flex items-center gap-1 text-[var(--text-muted)]">
<span>[ 13_TOOLS_ACTIVE ]</span>
</span>
</div>
</div>
</div>
);
+451
View File
@@ -0,0 +1,451 @@
"use client";
import React, { useState, useMemo } from "react";
import Link from "next/link";
import Markdown from "./Markdown";
import {
extractDocCategory,
extractDocPoints,
extractDocDifficulty,
sortExportDocuments,
compileExportMarkdown,
type Document,
type ExportData,
type ExportSortOption,
} from "@mcpedia/core/export-helpers";
import { getSectionMeta } from "@mcpedia/config/sections";
import {
Printer,
FileDown,
FileText,
Copy,
Check,
ArrowLeft,
BookOpen,
} from "lucide-react";
interface PdfExportViewProps {
exportData: ExportData;
backHref: string;
}
export default function PdfExportView({
exportData,
backHref,
}: PdfExportViewProps) {
const { summary, documents: initialDocs } = exportData;
// Filter out any leftover index / meta files
const cleanDocs = useMemo(() => {
return initialDocs.filter((d) => {
const slug = d.slug.toLowerCase();
return (
!slug.endsWith("/_index") &&
!slug.endsWith("/index") &&
slug !== "_index" &&
slug !== "index" &&
d.type !== "writeup-index"
);
});
}, [initialDocs]);
// Configuration and interactive state
const [sortBy, setSortBy] = useState<ExportSortOption>("category_points");
const [showTOC, setShowTOC] = useState(cleanDocs.length > 1);
const [pageBreaks, setPageBreaks] = useState(true);
const [selectedCategory, setSelectedCategory] = useState<string>("all");
const [copiedMd, setCopiedMd] = useState(false);
const sectionMeta = getSectionMeta(summary.section);
// Available categories for filtering
const allCategories = useMemo(() => {
const set = new Set<string>();
for (const doc of cleanDocs) {
set.add(extractDocCategory(doc));
}
return Array.from(set).sort();
}, [cleanDocs]);
// Filtered & Sorted documents
const filteredAndSortedDocs = useMemo(() => {
let docs = [...cleanDocs];
if (selectedCategory !== "all") {
docs = docs.filter(
(d) => extractDocCategory(d).toLowerCase() === selectedCategory.toLowerCase(),
);
}
return sortExportDocuments(docs, sortBy);
}, [cleanDocs, selectedCategory, sortBy]);
// Calculate dynamic stats for currently filtered view
const currentTotalPoints = useMemo(() => {
return filteredAndSortedDocs.reduce(
(sum, d) => sum + extractDocPoints(d),
0,
);
}, [filteredAndSortedDocs]);
function handlePrint() {
window.print();
}
function handleCopyMarkdown() {
const md = compileExportMarkdown({
summary,
documents: filteredAndSortedDocs,
});
navigator.clipboard.writeText(md);
setCopiedMd(true);
setTimeout(() => setCopiedMd(false), 2000);
}
function handleDownloadMarkdown() {
const md = compileExportMarkdown({
summary,
documents: filteredAndSortedDocs,
});
const blob = new Blob([md], { type: "text/markdown;charset=utf-8" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
const safeName = summary.title
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-|-$/g, "");
a.download = `${safeName}.md`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
const [downloadingDocx, setDownloadingDocx] = useState(false);
async function handleDownloadDocx() {
setDownloadingDocx(true);
try {
const slugs = filteredAndSortedDocs.map((d) => d.slug).join(",");
const safeName =
summary.title
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-|-$/g, "") || "export";
const url = `/api/export?format=docx&slugs=${encodeURIComponent(slugs)}&sort=${sortBy}&pageBreaks=${pageBreaks}`;
const res = await fetch(url);
if (!res.ok) throw new Error("Failed to generate Word document");
const blob = await res.blob();
const blobUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = blobUrl;
a.download = `${safeName}.docx`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(blobUrl);
} catch (err) {
console.error("DOCX download error:", err);
alert("Failed to generate .docx file. Please try again.");
} finally {
setDownloadingDocx(false);
}
}
return (
<div className="pb-16 print:pb-0">
{/* Export Control Toolbar (Screen Only — Hidden in Print) */}
<aside className="no-print export-toolbar sticky top-16 z-30 mb-8 bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl p-4 sm:p-5 shadow-xs">
<div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
{/* Left info & Back button */}
<div className="flex items-center gap-3">
<Link
href={backHref}
className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold bg-[var(--bg-elevated)] hover:bg-[var(--bg-elevated-hover)] border border-[var(--border-color)] rounded-md text-[var(--text-secondary)] hover:text-[var(--text-primary)] transition-colors shadow-xs"
>
<ArrowLeft className="w-3.5 h-3.5" />
<span>Back</span>
</Link>
<div>
<div className="flex items-center gap-2">
<span className="text-xs font-mono text-[var(--text-primary)] font-bold uppercase">
{sectionMeta.label}
</span>
<span className="text-xs text-[var(--text-dim)]">·</span>
<span className="text-xs text-[var(--text-muted)] font-mono">
{filteredAndSortedDocs.length} challenge{filteredAndSortedDocs.length !== 1 ? "s" : ""}
{currentTotalPoints > 0 ? ` (${currentTotalPoints} pts)` : ""}
</span>
</div>
<h2 className="text-sm font-bold text-[var(--text-primary)] truncate max-w-md">
{summary.title}
</h2>
</div>
</div>
{/* Action Buttons */}
<div className="flex items-center gap-2 flex-wrap sm:flex-nowrap">
{/* Copy All Markdown */}
<button
onClick={handleCopyMarkdown}
type="button"
className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold bg-[var(--bg-elevated)] hover:bg-[var(--bg-elevated-hover)] border border-[var(--border-color)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] rounded-md transition-colors shadow-xs cursor-pointer"
title="Copy compiled markdown document"
>
{copiedMd ? (
<>
<Check className="w-3.5 h-3.5 text-emerald-500" />
<span className="text-emerald-500 font-bold">Copied</span>
</>
) : (
<>
<Copy className="w-3.5 h-3.5" />
<span>Copy MD</span>
</>
)}
</button>
{/* Download Markdown */}
<button
onClick={handleDownloadMarkdown}
type="button"
className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold bg-[var(--bg-elevated)] hover:bg-[var(--bg-elevated-hover)] border border-[var(--border-color)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] rounded-md transition-colors shadow-xs cursor-pointer"
title="Download compiled .md file"
>
<FileDown className="w-3.5 h-3.5" />
<span>Download .md</span>
</button>
{/* Download Word (.docx) */}
<button
onClick={handleDownloadDocx}
disabled={downloadingDocx}
type="button"
className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold bg-[var(--bg-elevated)] hover:bg-[var(--bg-elevated-hover)] border border-[var(--border-color)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] rounded-md transition-colors shadow-xs cursor-pointer disabled:opacity-50"
title="Download editable Microsoft Word (.docx) document"
>
{downloadingDocx ? (
<div className="w-3.5 h-3.5 border-2 border-current border-t-transparent rounded-full animate-spin" />
) : (
<FileText className="w-3.5 h-3.5" />
)}
<span>Download .docx</span>
</button>
{/* Print / Save as PDF Button */}
<button
onClick={handlePrint}
type="button"
className="inline-flex items-center gap-2 px-3.5 py-1.5 text-xs font-bold bg-[var(--brand)] hover:opacity-90 text-[var(--brand-fg)] rounded-md shadow-xs transition-all cursor-pointer"
title="Open browser print dialog to save as PDF"
>
<Printer className="w-4 h-4" />
<span>Print / Save PDF</span>
</button>
</div>
</div>
{/* Options & Filters Bar */}
<div className="mt-3.5 pt-3 border-t border-[var(--border-color)] flex flex-col sm:flex-row sm:items-center justify-between gap-3 text-xs">
{/* Sort Order Selector */}
<div className="flex items-center gap-2">
<span className="text-[var(--text-muted)] font-mono text-[10px] uppercase">Sort:</span>
<select
value={sortBy}
onChange={(e) => setSortBy(e.target.value as ExportSortOption)}
className="bg-[var(--bg-elevated)] border border-[var(--border-color)] rounded px-2.5 py-1 text-xs text-[var(--text-primary)] focus:outline-none"
>
<option value="category_points">Category & Points (Standard)</option>
<option value="points_desc">Points (Highest First)</option>
<option value="difficulty">Difficulty (Easy to Hard)</option>
<option value="title">Challenge Title (A-Z)</option>
<option value="path">Directory / Chapter Path</option>
<option value="updated_at">Recently Updated</option>
</select>
</div>
{/* Section toggles */}
<div className="flex items-center gap-3 flex-wrap text-[var(--text-secondary)]">
{cleanDocs.length > 1 && (
<label className="inline-flex items-center gap-1.5 cursor-pointer select-none">
<input
type="checkbox"
checked={showTOC}
onChange={(e) => setShowTOC(e.target.checked)}
className="rounded border-[var(--border-color)]"
/>
<span>Table of Contents</span>
</label>
)}
<label className="inline-flex items-center gap-1.5 cursor-pointer select-none">
<input
type="checkbox"
checked={pageBreaks}
onChange={(e) => setPageBreaks(e.target.checked)}
className="rounded border-[var(--border-color)]"
/>
<span>Page Break per Challenge</span>
</label>
</div>
</div>
{/* Category filter pills */}
{allCategories.length > 1 && (
<div className="mt-3 pt-3 border-t border-[var(--border-color)] flex items-center gap-1.5 flex-wrap text-xs">
<span className="text-[var(--text-muted)] font-mono text-[10px] uppercase mr-1">Filter:</span>
<button
onClick={() => setSelectedCategory("all")}
type="button"
className={`px-2.5 py-0.5 rounded text-xs font-mono transition-all cursor-pointer ${
selectedCategory === "all"
? "bg-[var(--brand)] text-[var(--brand-fg)] font-bold"
: "bg-[var(--bg-elevated)] text-[var(--text-muted)] hover:text-[var(--text-primary)] border border-[var(--border-color)]"
}`}
>
All ({cleanDocs.length})
</button>
{allCategories.map((cat) => {
const count = cleanDocs.filter(
(d) => extractDocCategory(d).toLowerCase() === cat.toLowerCase(),
).length;
return (
<button
key={cat}
onClick={() => setSelectedCategory(cat)}
type="button"
className={`px-2.5 py-0.5 rounded text-xs font-mono transition-all cursor-pointer ${
selectedCategory.toLowerCase() === cat.toLowerCase()
? "bg-[var(--brand)] text-[var(--brand-fg)] font-bold"
: "bg-[var(--bg-elevated)] text-[var(--text-muted)] hover:text-[var(--text-primary)] border border-[var(--border-color)]"
}`}
>
{cat} ({count})
</button>
);
})}
</div>
)}
</aside>
{/* Writeup Document Flow */}
<main className="print-container bg-white text-slate-900 max-w-4xl mx-auto px-4 sm:px-8 py-6 print:p-0 print:m-0 print:max-w-none rounded-xl border border-[var(--border-color)] print:border-none shadow-xs print:shadow-none">
{/* Document Header */}
<header className="doc-header mb-8 pb-4 print:mb-2.5 print:pb-1.5 border-b border-slate-300">
<h1 className="text-3xl sm:text-4xl print:text-lg font-extrabold text-slate-950 tracking-tight mb-2 print:mb-0.5">
{summary.title}
</h1>
<div className="text-xs print:text-[7.5pt] text-slate-500 font-mono flex flex-wrap items-center gap-x-2 gap-y-1 print:gap-x-1.5 print:gap-y-0.5">
<span>{filteredAndSortedDocs.length} Challenges</span>
{currentTotalPoints > 0 && (
<span>· {currentTotalPoints.toLocaleString()} Total Points</span>
)}
<span>· {new Date(summary.generatedAt).toLocaleDateString(undefined, { dateStyle: "long" })}</span>
</div>
</header>
{/* Table of Contents */}
{showTOC && filteredAndSortedDocs.length > 1 && (
<section className="toc-section mb-10 pb-6 print:mb-2.5 print:pb-1.5 border-b border-slate-200 print:border-slate-300">
<h2 className="text-xs print:text-[8pt] font-bold uppercase font-mono text-slate-700 mb-3 print:mb-1 tracking-wider flex items-center gap-1.5">
<BookOpen className="w-3.5 h-3.5 print:w-3 print:h-3" />
<span>Table of Contents</span>
</h2>
<ol className="list-decimal list-inside space-y-1.5 print:space-y-0.5 text-xs print:text-[7.5pt] text-slate-800">
{filteredAndSortedDocs.map((doc, idx) => {
const cat = extractDocCategory(doc);
const pts = extractDocPoints(doc);
return (
<li key={doc.slug} className="print:leading-tight">
<a
href={`#ch-${idx + 1}`}
className="hover:underline font-medium text-slate-900"
>
{doc.title}
</a>
<span className="text-slate-500 font-mono ml-2 print:ml-1">
[{cat}{pts > 0 ? ` · ${pts} pts` : ""}]
</span>
</li>
);
})}
</ol>
</section>
)}
{/* Challenges Flow */}
<div className="challenges-flow space-y-10 print:space-y-0">
{filteredAndSortedDocs.map((doc, idx) => {
const chNum = idx + 1;
const cat = extractDocCategory(doc);
const pts = extractDocPoints(doc);
const diff = extractDocDifficulty(doc);
const extra = doc.extraFields || {};
return (
<article
key={doc.slug}
id={`ch-${chNum}`}
className={`challenge-entry ${
pageBreaks && idx > 0 ? "page-break-before" : ""
} pt-6 first:pt-0 print:pt-2.5 print:pb-2 print:border-b print:border-slate-200 print:last:border-none`}
>
{/* Challenge Title & Metadata */}
<div className="challenge-header mb-4 pb-2 print:mb-1.5 print:pb-1 border-b border-slate-200 print:border-slate-300">
<h2 className="text-2xl print:text-[11pt] font-bold text-slate-950 tracking-tight leading-tight mb-1.5 print:mb-0.5">
{chNum}. {doc.title}
</h2>
<div className="text-xs print:text-[7.5pt] font-mono text-slate-600 flex flex-wrap items-center gap-x-3 print:gap-x-2 gap-y-1 print:gap-y-0.5">
<span><strong>Category:</strong> {cat}</span>
{pts > 0 && <span><strong>Points:</strong> {pts} pts</span>}
{diff && <span><strong>Difficulty:</strong> {diff}</span>}
{/* Extra fields */}
{Object.entries(extra).map(([k, v]) => {
const lowerKey = k.toLowerCase();
if (
[
"category",
"points",
"score",
"pts",
"difficulty",
"solved",
"author",
"authors",
"scope",
"slug",
"event",
"challenge",
"path",
].includes(lowerKey) ||
v === null ||
v === undefined ||
v === ""
) {
return null;
}
return (
<span key={k}>
<strong>{k}:</strong> {String(v)}
</span>
);
})}
</div>
</div>
{/* Markdown Writeup Content */}
<div className="prose prose-slate max-w-none text-slate-900 mb-8 print:mb-1">
<Markdown source={doc.body} />
</div>
{/* Divider between challenges (screen only) */}
<hr className="print:hidden border-slate-200 my-8" />
</article>
);
})}
</div>
</main>
</div>
);
}
+79
View File
@@ -0,0 +1,79 @@
"use client";
import useSWR from "swr";
import { fetcher } from "@/lib/fetcher";
import { Clock, CheckCircle2, AlertTriangle, Hourglass, Layers } from "lucide-react";
export default function QueueBadge() {
const { data, error, isLoading } = useSWR<{ waiting: number; active: number; completed: number; failed: number; delayed: number }>(
"/api/queue/status",
fetcher,
{ refreshInterval: 8_000, dedupingInterval: 4_000, revalidateOnFocus: false },
);
if (isLoading) {
return (
<span className="inline-flex items-center gap-1.5 text-[11px] font-mono text-[var(--text-dim)] bg-[var(--bg-elevated)] border border-[var(--border-color)] px-2.5 py-1 rounded">
<Hourglass className="w-3 h-3 animate-spin" /> queue…
</span>
);
}
if (error || !data) return null;
const total = data.waiting + data.active + data.delayed;
const hasWork = total > 0 || data.failed > 0;
if (!hasWork) {
return (
<span className="inline-flex items-center gap-1.5 text-[11px] font-mono text-emerald-600 dark:text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 px-2.5 py-1 rounded">
<CheckCircle2 className="w-3 h-3" /> index idle
</span>
);
}
return (
<span
className={`inline-flex items-center gap-1.5 text-[11px] font-mono px-2.5 py-1 rounded border ${
data.failed > 0
? "text-amber-700 dark:text-amber-400 bg-amber-500/10 border-amber-500/30"
: "text-[var(--text-secondary)] bg-[var(--bg-elevated)] border-[var(--border-color)]"
}`}
title={`waiting:${data.waiting} active:${data.active} delayed:${data.delayed} failed:${data.failed}`}
role="status"
aria-live="polite"
>
{data.failed > 0 ? <AlertTriangle className="w-3 h-3" /> : <Clock className="w-3 h-3" />}
<span>
q:{data.waiting}w · {data.active}a
{data.delayed ? ` · ${data.delayed}d` : ""}
{data.failed ? ` · ${data.failed} ✕` : ""}
</span>
</span>
);
}
export function QueueStrip() {
const { data } = useSWR<{ waiting: number; active: number; completed: number; failed: number; delayed: number }>(
"/api/queue/status",
fetcher,
{ refreshInterval: 6_000, revalidateOnFocus: false },
);
if (!data) return null;
const items: { label: string; value: number; tone: string }[] = [
{ label: "waiting", value: data.waiting, tone: "text-[var(--text-muted)]" },
{ label: "active", value: data.active, tone: "text-sky-600 dark:text-sky-400" },
{ label: "delayed", value: data.delayed, tone: "text-[var(--text-muted)]" },
{ label: "failed", value: data.failed, tone: data.failed ? "text-amber-600 dark:text-amber-400" : "text-[var(--text-dim)]" },
{ label: "completed", value: data.completed, tone: "text-emerald-600 dark:text-emerald-400" },
];
return (
<div className="flex flex-wrap gap-2 text-[11px] font-mono">
{items.map((it) => (
<span key={it.label} className={`px-2 py-1 rounded bg-[var(--bg-surface)] border border-[var(--border-color)] ${it.tone}`}>
{it.label}: <strong>{it.value}</strong>
</span>
))}
</div>
);
}
+53
View File
@@ -0,0 +1,53 @@
"use client";
import Link from "next/link";
import { useRelated } from "@/hooks/useRelated";
import { getSectionMeta } from "@mcpedia/config/sections";
import { Sparkles } from "lucide-react";
export default function RelatedGrid({ slug }: { slug: string }) {
const { related, isLoading, error } = useRelated(slug, 4);
if (isLoading) {
return (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 animate-pulse">
{Array.from({ length: 4 }).map((_, i) => (
<div key={i} className="h-24 bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-lg" />
))}
</div>
);
}
if (error || related.length === 0) return null;
return (
<aside className="mt-12 pt-8 border-t border-[var(--border-color)]">
<div className="flex items-center gap-2 mb-3.5">
<Sparkles className="w-4 h-4 text-[var(--text-muted)]" />
<h2 className="text-xs font-bold text-[var(--text-muted)] uppercase tracking-wider font-mono">Related Knowledge</h2>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
{related.map((r) => {
const rInfo = getSectionMeta(r.section);
return (
<Link
key={r.slug}
href={`/${r.slug}`}
className="group block bg-[var(--bg-surface)] hover:bg-[var(--bg-surface-hover)] border border-[var(--border-color)] hover:border-[var(--text-muted)] rounded-lg p-4 transition-colors shadow-xs"
>
<div className="flex items-center justify-between gap-2 mb-1.5">
<span className="text-[10px] text-[var(--text-muted)] font-mono uppercase font-semibold">
{rInfo.icon} {r.section}
</span>
<time className="text-[11px] text-[var(--text-dim)] font-mono">
{new Date(r.updatedAt).toLocaleDateString(undefined, { month: "short", day: "numeric" })}
</time>
</div>
<h3 className="text-xs sm:text-sm font-semibold text-[var(--text-primary)] group-hover:underline line-clamp-1">{r.title}</h3>
</Link>
);
})}
</div>
</aside>
);
}
+68
View File
@@ -0,0 +1,68 @@
"use client";
import { mutate } from "swr";
import { useRevisions } from "@/hooks/useRevisions";
import { History } from "lucide-react";
export default function RevisionList({ slug, canEdit }: { slug: string; canEdit: boolean }) {
const { revisions, isLoading, error, mutate: revalidate } = useRevisions(slug, 10);
if (isLoading) {
return (
<div className="space-y-2 animate-pulse">
{Array.from({ length: 3 }).map((_, i) => (
<div key={i} className="h-12 bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-lg" />
))}
</div>
);
}
if (error) {
return <p className="text-xs text-amber-600 dark:text-amber-400">Failed to load revisions: {(error as Error).message}</p>;
}
if (revisions.length === 0) return null;
return (
<aside className="mt-10 pt-8 border-t border-[var(--border-color)]">
<div className="flex items-center justify-between mb-3.5">
<div className="flex items-center gap-2">
<History className="w-4 h-4 text-[var(--text-muted)]" />
<h2 className="text-xs font-bold text-[var(--text-muted)] uppercase tracking-wider font-mono">Revision History ({revisions.length})</h2>
</div>
</div>
<div className="space-y-2">
{revisions.map((rev) => (
<div key={rev.id} className="flex items-center justify-between gap-3 p-3 bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-lg text-xs shadow-xs">
<div className="flex items-center gap-2 min-w-0 font-mono">
<span className="text-[var(--text-primary)] bg-[var(--bg-elevated)] px-1.5 py-0.5 rounded border border-[var(--border-color)] font-bold text-[10px]">v{rev.revisionNo}</span>
<span className="text-[var(--text-secondary)] font-sans truncate text-xs">{rev.reason || "Updated document in PostgreSQL"}</span>
<span className="text-[var(--text-dim)] hidden sm:inline text-[11px]">· {new Date(rev.createdAt).toLocaleString()}</span>
</div>
{canEdit && (
<form
action="/api/revisions/restore"
method="post"
onSubmit={() => {
// Optimistically revalidate after form post navigates back
setTimeout(() => {
revalidate();
mutate((k) => typeof k === "string" && k.startsWith("/api/docs"));
}, 800);
}}
>
<input type="hidden" name="id" value={rev.id} />
<button
type="submit"
className="text-xs text-[var(--text-primary)] hover:text-black dark:hover:text-white bg-[var(--bg-elevated)] hover:bg-[var(--bg-elevated-hover)] px-2.5 py-1 rounded border border-[var(--border-color)] transition-colors font-medium cursor-pointer"
>
Restore
</button>
</form>
)}
</div>
))}
</div>
</aside>
);
}
+74
View File
@@ -0,0 +1,74 @@
"use client";
import Link from "next/link";
import { Search, X } from "lucide-react";
interface SearchBarProps {
value: string;
onChange: (v: string) => void;
placeholder?: string;
autoFocus?: boolean;
onClear?: () => void;
}
export default function SearchBar({ value, onChange, placeholder, autoFocus, onClear }: SearchBarProps) {
return (
<div className="relative">
<input
type="search"
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder ?? "Search knowledge base..."}
autoFocus={autoFocus}
className="w-full pl-10 pr-9 py-3 bg-[var(--bg-elevated)] border border-[var(--border-color)] hover:border-[var(--text-muted)] rounded-lg text-[var(--text-primary)] placeholder-[var(--text-dim)] focus:outline-none focus:border-[var(--text-primary)] text-sm transition-all"
/>
<Search className="w-4 h-4 text-[var(--text-muted)] absolute left-3.5 top-3.5 pointer-events-none" />
{value && (
<button
onClick={() => {
onChange("");
onClear?.();
}}
className="absolute right-3 top-3 p-0.5 text-[var(--text-dim)] hover:text-[var(--text-primary)] rounded"
aria-label="Clear query"
type="button"
>
<X className="w-4 h-4" />
</button>
)}
</div>
);
}
export function InlineSearchBar({
value,
onChange,
placeholder,
}: {
value: string;
onChange: (v: string) => void;
placeholder?: string;
}) {
return (
<div className="relative">
<input
type="text"
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder ?? "Filter index..."}
className="w-full pl-8 pr-7 py-1.5 bg-[var(--bg-surface)] border border-[var(--border-color)] hover:border-[var(--text-muted)] rounded-md text-xs text-[var(--text-primary)] placeholder-[var(--text-dim)] focus:outline-none focus:border-[var(--text-primary)] transition-all"
/>
<Search className="w-3.5 h-3.5 text-[var(--text-dim)] absolute left-2.5 top-2.5 pointer-events-none" />
{value && (
<button
onClick={() => onChange("")}
className="absolute right-2 top-2 p-0.5 text-[var(--text-dim)] hover:text-[var(--text-primary)] rounded"
aria-label="Clear filter"
type="button"
>
<X className="w-3.5 h-3.5" />
</button>
)}
</div>
);
}
+36
View File
@@ -0,0 +1,36 @@
import Link from "next/link";
export function SectionCard({
id,
label,
icon,
desc,
docCount,
}: {
id: string;
label: string;
icon: string;
desc: string;
docCount: number;
}) {
return (
<div className="group flex flex-col justify-between bg-[var(--bg-surface)] hover:bg-[var(--bg-surface-hover)] border border-[var(--border-color)] hover:border-[var(--text-muted)] rounded-xl p-5 transition-all shadow-xs">
<div>
<div className="flex items-center justify-between gap-2 mb-3">
<span className="text-2xl">{icon}</span>
<Link
href={`/${id}`}
className="text-xs font-mono text-[var(--text-muted)] hover:text-[var(--text-primary)] font-semibold"
>
{docCount} docs →
</Link>
</div>
<h3 className="font-bold text-sm text-[var(--text-primary)] mb-1">{label}</h3>
<p className="text-xs text-[var(--text-muted)] mb-4 line-clamp-2 leading-relaxed">{desc}</p>
</div>
<div className="pt-3 border-t border-[var(--border-color)] text-xs text-[var(--text-dim)] font-mono">
/{id} · {docCount} document{docCount !== 1 ? "s" : ""}
</div>
</div>
);
}
+59 -53
View File
@@ -1,9 +1,21 @@
"use client";
import { useEffect, useState, useMemo } from "react";
import { useState, useMemo } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { getSectionMeta } from "@mcpedia/config/sections";
import { useDocuments } from "@/hooks/useDocuments";
import {
Folder,
FolderOpen,
FileText,
ChevronRight,
Search,
X,
Plus,
} from "lucide-react";
import type { DocumentMeta } from "@mcpedia/types";
interface Doc {
slug: string;
@@ -102,13 +114,13 @@ function TreeNodeItem({
const isCollapsed = collapsedMap[node.slug] ?? false;
return (
<li className={`select-none ${depth > 0 ? "ml-3 pl-2 border-l border-[var(--border-color)]" : ""}`}>
<li className={`select-none ${depth > 0 ? "ml-3.5 pl-2 border-l border-[var(--border-color)]" : ""}`}>
<div
className={`group flex items-center justify-between gap-1.5 text-xs py-1.5 px-2 rounded-md transition-all ${
className={`group flex items-center justify-between gap-1 text-xs py-1.5 px-2 rounded-md transition-all ${
isActive
? "text-[#5e6ad2] dark:text-[#7170ff] bg-[#5e6ad2]/15 font-semibold border border-[#5e6ad2]/30 shadow-sm"
? "text-[var(--text-primary)] bg-[var(--bg-elevated)] font-semibold border border-[var(--border-color)] shadow-xs"
: isParentOfActive
? "text-[var(--text-primary)] bg-[var(--bg-elevated)]"
? "text-[var(--text-primary)] bg-[var(--bg-elevated)]/60"
: "text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-elevated)]"
}`}
>
@@ -117,15 +129,23 @@ function TreeNodeItem({
className="flex items-center gap-2 min-w-0 flex-1 py-0.5"
title={node.title || node.name}
>
<span className="text-xs shrink-0 opacity-80 group-hover:opacity-100">
{isFolder ? "📁" : "📄"}
<span className="shrink-0 text-[var(--text-dim)] group-hover:text-[var(--text-primary)] transition-colors">
{isFolder ? (
isCollapsed ? (
<Folder className="w-3.5 h-3.5" />
) : (
<FolderOpen className="w-3.5 h-3.5 text-[var(--text-primary)]" />
)
) : (
<FileText className="w-3.5 h-3.5" />
)}
</span>
<span className="truncate">{node.title || node.name}</span>
</Link>
{isFolder && (
<div className="flex items-center gap-1 shrink-0">
<span className="text-[10px] text-[var(--text-muted)] bg-[var(--bg-surface)] border border-[var(--border-color)] px-1 py-0.2 rounded font-mono">
<span className="text-[10px] text-[var(--text-dim)] bg-[var(--bg-surface)] border border-[var(--border-color)] px-1.5 py-0.2 rounded font-mono">
{node.docCount}
</span>
<button
@@ -135,24 +155,19 @@ function TreeNodeItem({
e.stopPropagation();
toggleCollapse(node.slug);
}}
className="p-0.5 text-[var(--text-muted)] hover:text-[var(--text-primary)] rounded hover:bg-[var(--bg-elevated-hover)] transition-transform"
className="p-1 text-[var(--text-dim)] hover:text-[var(--text-primary)] rounded hover:bg-[var(--bg-elevated-hover)] transition-transform cursor-pointer"
aria-label={isCollapsed ? "Expand folder" : "Collapse folder"}
>
<svg
className={`w-3 h-3 transition-transform duration-200 ${isCollapsed ? "-rotate-90" : "rotate-0"}`}
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</svg>
<ChevronRight
className={`w-3 h-3 transition-transform duration-200 ${isCollapsed ? "rotate-0" : "rotate-90"}`}
/>
</button>
</div>
)}
</div>
{isFolder && !isCollapsed && (
<ul className="mt-0.5 space-y-0.5 animate-fade-in">
<ul className="mt-1 space-y-0.5 animate-fade-in">
{node.children.map((child) => (
<TreeNodeItem
key={child.slug}
@@ -170,21 +185,11 @@ function TreeNodeItem({
}
export default function Sidebar() {
const [docs, setDocs] = useState<Doc[]>([]);
const { docs } = useDocuments();
const [filterText, setFilterText] = useState("");
const [collapsedMap, setCollapsedMap] = useState<Record<string, boolean>>({});
const pathname = usePathname();
useEffect(() => {
fetch("/api/docs")
.then((r) => r.json())
.then((data) => {
if (Array.isArray(data)) setDocs(data);
else if (data?.docs) setDocs(data.docs);
})
.catch(() => setDocs([]));
}, []);
function toggleCollapse(slug: string) {
setCollapsedMap((prev) => ({ ...prev, [slug]: !prev[slug] }));
}
@@ -196,7 +201,7 @@ export default function Sidebar() {
(d) =>
d.title.toLowerCase().includes(lower) ||
d.slug.toLowerCase().includes(lower) ||
d.tags.some((t) => t.toLowerCase().includes(lower)),
d.tags.some((t: string) => t.toLowerCase().includes(lower)),
);
}, [docs, filterText]);
@@ -212,7 +217,7 @@ export default function Sidebar() {
}, [filteredDocs]);
return (
<nav className="h-full flex flex-col py-4 px-3">
<nav className="h-full flex flex-col py-4 px-3 select-none">
{/* Sidebar search filter */}
<div className="mb-3">
<div className="relative">
@@ -220,31 +225,25 @@ export default function Sidebar() {
type="text"
value={filterText}
onChange={(e) => setFilterText(e.target.value)}
placeholder="Filter docs..."
className="w-full pl-7 pr-3 py-1.5 bg-[var(--bg-surface)] border border-[var(--border-color)] hover:border-[var(--brand)] rounded-md text-xs text-[var(--text-primary)] placeholder-[var(--text-dim)] focus:outline-none focus:border-[var(--brand)] transition-colors"
placeholder="Filter index..."
className="w-full pl-8 pr-7 py-1.5 bg-[var(--bg-surface)] border border-[var(--border-color)] hover:border-[var(--text-muted)] rounded-md text-xs text-[var(--text-primary)] placeholder-[var(--text-dim)] focus:outline-none focus:border-[var(--text-primary)] transition-all"
/>
<svg
className="w-3.5 h-3.5 text-[var(--text-muted)] absolute left-2 top-2.5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
<Search className="w-3.5 h-3.5 text-[var(--text-dim)] absolute left-2.5 top-2.5 pointer-events-none" />
{filterText && (
<button
onClick={() => setFilterText("")}
className="absolute right-2 top-2 text-xs text-[var(--text-muted)] hover:text-[var(--text-primary)]"
className="absolute right-2 top-2 p-0.5 text-[var(--text-dim)] hover:text-[var(--text-primary)] rounded"
aria-label="Clear filter"
>
✕
<X className="w-3.5 h-3.5" />
</button>
)}
</div>
</div>
{/* Summary count */}
<div className="flex items-center justify-between px-1 mb-3 text-[11px] text-[var(--text-dim)]">
<span className="uppercase tracking-wider font-mono">Knowledge Base</span>
<div className="flex items-center justify-between px-1 mb-2 text-[10px] text-[var(--text-muted)] font-mono uppercase tracking-wider">
<span>Knowledge Index</span>
<span>{filteredDocs.length} items</span>
</div>
@@ -261,17 +260,17 @@ export default function Sidebar() {
<div key={id} className="border-b border-[var(--border-color)] pb-3 last:border-0">
<Link
href={`/${id}`}
className={`flex items-center justify-between gap-1.5 px-1 py-1 mb-1 rounded text-xs font-semibold uppercase tracking-wider transition-colors ${
className={`flex items-center justify-between gap-1.5 px-2 py-1 mb-1 rounded-md text-xs font-semibold uppercase tracking-wider transition-colors ${
isSectionActive
? "text-[#5e6ad2] dark:text-[#7170ff]"
: "text-[var(--text-muted)] hover:text-[var(--text-primary)]"
? "text-[var(--text-primary)] bg-[var(--bg-elevated)]"
: "text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-elevated)]"
}`}
>
<div className="flex items-center gap-1.5">
<span>{icon}</span>
<div className="flex items-center gap-2">
<span className="text-xs">{icon}</span>
<span>{label}</span>
</div>
<span className="text-[10px] text-[var(--text-dim)] font-normal font-mono">
<span className="text-[10px] text-[var(--text-muted)] font-normal font-mono bg-[var(--bg-surface)] px-1.5 py-0.2 rounded border border-[var(--border-color)]">
{sectionDocs.length}
</span>
</Link>
@@ -291,15 +290,22 @@ export default function Sidebar() {
</div>
);
})}
{filteredDocs.length === 0 && (
<div className="text-center py-8 text-xs text-[var(--text-dim)] font-mono">
No matching documents
</div>
)}
</div>
{/* Bottom quick links */}
<div className="pt-3 border-t border-[var(--border-color)] mt-auto">
<Link
href="/create"
className="flex items-center justify-center gap-1.5 w-full py-1.5 text-xs bg-[var(--bg-elevated)] hover:bg-[var(--bg-elevated-hover)] border border-[var(--border-color)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] rounded-md transition-colors font-medium"
className="flex items-center justify-center gap-2 w-full py-2 text-xs bg-[var(--bg-elevated)] hover:bg-[var(--bg-elevated-hover)] border border-[var(--border-color)] hover:border-[var(--text-muted)] text-[var(--text-primary)] rounded-md transition-all font-medium shadow-xs"
>
<span>+ Create New Document</span>
<Plus className="w-3.5 h-3.5 text-[var(--text-muted)]" />
<span>Create Document</span>
</Link>
</div>
</nav>
+23 -11
View File
@@ -3,6 +3,7 @@
import { useEffect, useState } from "react";
import Link from "next/link";
import GithubSlugger from "github-slugger";
import { AlignLeft, ArrowUp, Hash } from "lucide-react";
interface TOCEntry {
id: string;
@@ -58,18 +59,29 @@ export default function TOC({ source }: { source: string }) {
if (toc.length === 0) return null;
function scrollToTop() {
window.scrollTo({ top: 0, behavior: "smooth" });
}
return (
<nav className="text-xs">
<div className="flex items-center gap-2 mb-3 pb-2 border-b border-[var(--border-color)]">
<svg className="w-3.5 h-3.5 text-[#5e6ad2] dark:text-[#7170ff]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h7" />
</svg>
<span className="font-semibold uppercase tracking-wider text-[var(--text-muted)] text-[11px]">
On this page
</span>
<nav className="text-xs space-y-4">
<div className="flex items-center justify-between pb-2 border-b border-[var(--border-color)]">
<div className="flex items-center gap-1.5 font-semibold uppercase tracking-wider text-[var(--text-muted)] text-[11px] font-mono">
<AlignLeft className="w-3.5 h-3.5 text-[var(--brand)] dark:text-[var(--accent)]" />
<span>On This Page</span>
</div>
<button
onClick={scrollToTop}
type="button"
className="text-[10px] text-[var(--text-dim)] hover:text-[var(--text-primary)] flex items-center gap-0.5 hover:underline"
title="Scroll to top"
>
<ArrowUp className="w-3 h-3" />
<span>Top</span>
</button>
</div>
<ul className="space-y-1.5 border-l border-[var(--border-color)] pl-2.5">
<ul className="space-y-1.5 border-l border-[var(--border-color)] pl-3">
{toc.map((entry) => {
const isActive = activeId === entry.id;
return (
@@ -90,9 +102,9 @@ export default function TOC({ source }: { source: string }) {
history.pushState(null, "", `#${entry.id}`);
}
}}
className={`block py-0.5 transition-colors line-clamp-1 ${
className={`block py-0.5 transition-all line-clamp-1 ${
isActive
? "text-[#5e6ad2] dark:text-[#7170ff] font-semibold translate-x-0.5"
? "text-[var(--brand)] dark:text-[var(--accent)] font-semibold translate-x-0.5"
: "text-[var(--text-muted)] hover:text-[var(--text-primary)]"
}`}
title={entry.text}
+57
View File
@@ -0,0 +1,57 @@
"use client";
import Link from "next/link";
import useSWR from "swr";
import { fetcher } from "@/lib/fetcher";
import { Tag, TrendingUp } from "lucide-react";
export default function TagCloud({ limit = 24 }: { limit?: number }) {
const { data, isLoading } = useSWR<{ tags: { tag: string; count: number }[] }>(
`/api/tags?limit=${limit}`,
fetcher,
{ revalidateOnFocus: false },
);
const tags = data?.tags ?? [];
if (isLoading) {
return (
<div className="flex flex-wrap gap-1.5 animate-pulse">
{Array.from({ length: 8 }).map((_, i) => (
<div key={i} className="h-6 w-16 bg-[var(--bg-elevated)] rounded" />
))}
</div>
);
}
if (tags.length === 0) return null;
const max = Math.max(...tags.map((t) => t.count), 1);
return (
<div className="space-y-3">
<div className="flex items-center gap-2">
<Tag className="w-3.5 h-3.5 text-[var(--text-muted)]" />
<h3 className="text-xs font-bold text-[var(--text-muted)] uppercase tracking-wider font-mono">Popular Tags</h3>
<span className="text-[11px] text-[var(--text-dim)] font-mono">({tags.length})</span>
</div>
<div className="flex flex-wrap gap-1.5">
{tags.map(({ tag, count }) => {
const intensity = count / max;
const opacity = 0.45 + intensity * 0.55;
return (
<Link
key={tag}
href={`/search?q=${encodeURIComponent(tag)}`}
className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full border text-xs font-mono transition-all hover:scale-[1.02] bg-[var(--bg-surface)] hover:bg-[var(--bg-elevated)] border-[var(--border-color)] hover:border-[var(--text-muted)] text-[var(--text-secondary)] hover:text-[var(--text-primary)]"
style={{ opacity }}
title={`${count} document${count !== 1 ? "s" : ""}`}
>
<span>#{tag}</span>
<span className="text-[10px] bg-[var(--bg-elevated)] px-1 py-0.2 rounded font-semibold">{count}</span>
</Link>
);
})}
</div>
</div>
);
}
+5 -8
View File
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useState } from "react";
import { Sun, Moon } from "lucide-react";
const STORAGE_KEY = "mcpedia-theme";
@@ -36,7 +37,7 @@ export default function ThemeToggle() {
if (!mounted) {
return (
<div className="w-8 h-8 rounded-lg bg-[var(--bg-elevated)] border border-[var(--border-color)] opacity-50" />
<div className="w-8 h-8 rounded-lg bg-[var(--bg-elevated)] border border-[var(--border-color)] opacity-40" />
);
}
@@ -46,16 +47,12 @@ export default function ThemeToggle() {
type="button"
aria-label={isDark ? "Switch to light mode" : "Switch to dark mode"}
title={isDark ? "Switch to light mode" : "Switch to dark mode"}
className="p-1.5 rounded-lg text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-elevated)] border border-transparent hover:border-[var(--border-color)] transition-all flex items-center justify-center"
className="p-2 rounded-lg text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-elevated)] border border-transparent hover:border-[var(--border-color)] transition-all flex items-center justify-center cursor-pointer"
>
{isDark ? (
<svg className="w-4 h-4 text-amber-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z" />
</svg>
<Sun className="w-4 h-4 text-amber-400 hover:rotate-45 transition-transform" />
) : (
<svg className="w-4 h-4 text-indigo-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z" />
</svg>
<Moon className="w-4 h-4 text-indigo-600 hover:-rotate-12 transition-transform" />
)}
</button>
);
+9 -6
View File
@@ -4,6 +4,7 @@ import { WEBHOOK_SECRET } from "@mcpedia/config";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import DocForm from "@/components/DocForm";
import { Edit3, ArrowLeft, Plus } from "lucide-react";
export const dynamic = "force-dynamic";
@@ -33,14 +34,16 @@ export default async function CreatePage() {
{/* Header */}
<div className="flex items-center justify-between pb-4 border-b border-[var(--border-color)]">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-lg bg-[#5e6ad2]/15 border border-[#5e6ad2]/30 flex items-center justify-center text-xl text-[#5e6ad2] dark:text-[#7170ff]">
✏️
<div className="flex items-center gap-3.5">
<div className="w-11 h-11 rounded-2xl bg-[var(--brand)]/15 border border-[var(--brand)]/30 flex items-center justify-center text-[var(--brand)] dark:text-[var(--accent)]">
<Plus className="w-6 h-6" />
</div>
<div>
<h1 className="text-2xl font-bold text-[var(--text-primary)] tracking-tight">Create Document</h1>
<p className="text-xs text-[var(--text-muted)] mt-0.5">
Writes directly to PostgreSQL, records revision history, and computes vector embeddings.
<h1 className="text-2xl sm:text-3xl font-extrabold text-[var(--text-primary)] tracking-tight">
Create Knowledge Document
</h1>
<p className="text-xs text-[var(--text-muted)] mt-0.5 font-mono">
Persists directly into PostgreSQL, tracks revision history, and generates vector embeddings.
</p>
</div>
</div>
+21
View File
@@ -0,0 +1,21 @@
"use client";
import useSWR from "swr";
import { fetcher } from "@/lib/fetcher";
export default function DashboardQueueStrip() {
const { data } = useSWR<{ waiting: number; active: number; completed: number; failed: number; delayed: number }>("/api/queue/status", fetcher, {
refreshInterval: 6000,
revalidateOnFocus: false,
});
if (!data) return null;
return (
<div className="flex flex-wrap gap-2 text-[11px] font-mono" role="status" aria-live="polite">
<span className="px-2.5 py-1 rounded bg-[var(--bg-surface)] border border-[var(--border-color)]">waiting: <strong>{data.waiting}</strong></span>
<span className="px-2.5 py-1 rounded bg-[var(--bg-surface)] border border-[var(--border-color)] text-sky-600 dark:text-sky-400">active: <strong>{data.active}</strong></span>
<span className={`px-2.5 py-1 rounded bg-[var(--bg-surface)] border ${data.failed ? "border-amber-500/40 text-amber-600 dark:text-amber-400" : "border-[var(--border-color)] text-[var(--text-dim)]"}`}>failed: <strong>{data.failed}</strong></span>
<span className="px-2.5 py-1 rounded bg-[var(--bg-surface)] border border-[var(--border-color)] text-emerald-600 dark:text-emerald-400">completed: <strong>{data.completed}</strong></span>
{data.delayed ? <span className="px-2.5 py-1 rounded bg-[var(--bg-surface)] border border-[var(--border-color)]">delayed: <strong>{data.delayed}</strong></span> : null}
</div>
);
}
@@ -0,0 +1,7 @@
"use client";
import TagCloud from "@/components/TagCloud";
export default function TagCloudClient() {
return <TagCloud limit={30} />;
}
+114
View File
@@ -0,0 +1,114 @@
import Link from "next/link";
import { listDocuments, listSections } from "@mcpedia/core";
export const dynamic = "force-dynamic";
export default async function DashboardPage() {
const [all, sections] = await Promise.all([listDocuments(), listSections()]);
const totalTags = new Set(all.flatMap((d) => d.tags)).size;
const recentDocs = [...all].sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()).slice(0, 8);
// Tag aggregation server-side for SSR snapshot (client TagCloud will hydrate live via SWR)
const tagCounts = new Map<string, number>();
for (const d of all) for (const t of d.tags) tagCounts.set(t, (tagCounts.get(t) ?? 0) + 1);
const topTags = [...tagCounts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 12);
return (
<div className="space-y-8 max-w-5xl">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl sm:text-3xl font-extrabold text-[var(--text-primary)] tracking-tight">Dashboard</h1>
<p className="text-xs sm:text-sm text-[var(--text-muted)] mt-1">Live overview of the MCPedia knowledge base. Data via PostgreSQL Core + BullMQ queue.</p>
</div>
<Link href="/create" className="hidden sm:inline-flex items-center gap-1.5 px-3 py-1.5 bg-[var(--brand)] text-[var(--brand-fg)] rounded-md text-xs font-semibold shadow-xs">
+ New Doc
</Link>
</div>
{/* Metric strip — SSR snapshot */}
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
<div className="p-4 bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl shadow-xs">
<div className="text-[10px] font-mono uppercase tracking-wider text-[var(--text-muted)]">DB Documents</div>
<div className="text-2xl font-bold font-mono text-[var(--text-primary)] mt-1">{all.length}</div>
<div className="text-[11px] text-[var(--text-dim)] font-mono">{totalTags} unique tags</div>
</div>
<div className="p-4 bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl shadow-xs">
<div className="text-[10px] font-mono uppercase tracking-wider text-[var(--text-muted)]">Active Sections</div>
<div className="text-2xl font-bold font-mono text-[var(--text-primary)] mt-1">{sections.length}</div>
<div className="text-[11px] text-[var(--text-dim)] font-mono truncate">{sections.map((s) => s.id).join(" · ")}</div>
</div>
<div className="p-4 bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl shadow-xs">
<div className="text-[10px] font-mono uppercase tracking-wider text-[var(--text-muted)]">Search</div>
<div className="text-2xl font-bold font-mono text-[var(--text-primary)] mt-1">RRF</div>
<div className="text-[11px] text-[var(--text-dim)] font-mono">FTS + Cosine Vectors</div>
</div>
<div className="p-4 bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl shadow-xs">
<div className="text-[10px] font-mono uppercase tracking-wider text-[var(--text-muted)]">MCP Tools</div>
<div className="text-2xl font-bold font-mono text-[var(--text-primary)] mt-1">13</div>
<div className="text-[11px] text-[var(--text-dim)] font-mono">HTTP :4021</div>
</div>
</div>
{/* Queue strip — client component polls live */}
<DashboardQueueStrip />
{/* Section breakdown */}
<section className="bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl p-5 shadow-xs">
<h2 className="text-xs font-bold uppercase tracking-wider text-[var(--text-muted)] font-mono mb-3">Section Breakdown</h2>
<div className="space-y-2">
{sections.map((s) => {
const pct = all.length ? Math.round((s.docCount / all.length) * 100) : 0;
return (
<Link key={s.id} href={`/${s.id}`} className="flex items-center gap-3 group">
<span className="text-sm w-6 text-center">{s.icon}</span>
<span className="text-xs font-semibold text-[var(--text-primary)] group-hover:underline w-28 truncate">{s.label}</span>
<div className="flex-1 h-2 bg-[var(--bg-elevated)] rounded-full overflow-hidden border border-[var(--border-color)]">
<div className="h-full bg-[var(--brand)] rounded-full transition-all" style={{ width: `${pct}%` }} />
</div>
<span className="text-[11px] font-mono text-[var(--text-muted)] w-14 text-right">{s.docCount} docs · {pct}%</span>
</Link>
);
})}
</div>
</section>
{/* Top tags */}
{topTags.length > 0 && (
<section className="bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-xl p-5 shadow-xs">
<h2 className="text-xs font-bold uppercase tracking-wider text-[var(--text-muted)] font-mono mb-3">Top Tags</h2>
<div className="flex flex-wrap gap-1.5">
{topTags.map(([tag, count]) => (
<Link key={tag} href={`/search?q=${encodeURIComponent(tag)}`} className="px-2.5 py-1 rounded-full bg-[var(--bg-elevated)] border border-[var(--border-color)] text-xs font-mono text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:border-[var(--text-muted)]">
#{tag} <span className="text-[10px] bg-[var(--bg-surface)] px-1 py-0.2 rounded ml-1">{count}</span>
</Link>
))}
</div>
<div className="mt-3">
<TagCloudClient />
</div>
</section>
)}
{/* Recent */}
{recentDocs.length > 0 && (
<section>
<h2 className="text-xs font-bold uppercase tracking-wider text-[var(--text-muted)] font-mono mb-3">Recently Updated</h2>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
{recentDocs.map((d) => (
<Link key={d.slug} href={`/${d.slug}`} className="p-4 bg-[var(--bg-surface)] border border-[var(--border-color)] hover:border-[var(--text-muted)] rounded-xl shadow-xs group">
<div className="text-[10px] font-mono uppercase text-[var(--text-muted)]">{d.section} · {new Date(d.updatedAt).toLocaleDateString()}</div>
<div className="text-sm font-semibold text-[var(--text-primary)] group-hover:underline line-clamp-1 mt-1">{d.title}</div>
{d.tags.length > 0 && <div className="flex gap-1 mt-2 flex-wrap">{d.tags.slice(0, 3).map((t) => <span key={t} className="text-[10px] px-1.5 py-0.2 bg-[var(--bg-elevated)] border border-[var(--border-color)] rounded font-mono text-[var(--text-muted)]">#{t}</span>)}</div>}
</Link>
))}
</div>
</section>
)}
</div>
);
}
// Client islands — isolated so the page stays RSC
import DashboardQueueStrip from "./QueueStrip";
import TagCloudClient from "./TagCloudClient";
+75
View File
@@ -0,0 +1,75 @@
import React from "next/link";
import Link from "next/link";
import { notFound } from "next/navigation";
import { getExportDocuments, formatScopeTitle, type ExportSortOption } from "@mcpedia/core";
import PdfExportView from "@/components/PdfExportView";
import { FileText, ArrowLeft } from "lucide-react";
export const dynamic = "force-dynamic";
interface ExportPdfPageProps {
searchParams: Promise<{
path?: string;
section?: string;
slug?: string;
sort?: string;
}>;
}
export async function generateMetadata({ searchParams }: ExportPdfPageProps) {
const { path, section, slug } = await searchParams;
const target = path || slug || section || "All Documents";
const title = formatScopeTitle(target);
return {
title: `Export PDF: ${title} — MCPedia`,
description: `Export and print documentation and CTF writeups for ${title}`,
};
}
export default async function ExportPdfPage({
searchParams,
}: ExportPdfPageProps) {
const { path, section, slug, sort } = await searchParams;
const targetPath = path || slug;
const sortBy = (sort as ExportSortOption) || "category_points";
const exportData = await getExportDocuments({
path: targetPath,
section: !targetPath ? section : undefined,
sortBy,
});
const backHref = targetPath ? `/${targetPath}` : section ? `/${section}` : "/";
if (exportData.documents.length === 0) {
return (
<div className="py-16 text-center space-y-4 max-w-lg mx-auto bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-3xl p-8 shadow-sm">
<div className="w-14 h-14 rounded-2xl bg-[var(--bg-elevated)] text-[var(--text-dim)] flex items-center justify-center mx-auto">
<FileText className="w-7 h-7" />
</div>
<h1 className="text-2xl font-bold text-[var(--text-primary)]">
No Documents Found for Export
</h1>
<p className="text-xs sm:text-sm text-[var(--text-muted)] leading-relaxed">
Could not find any published documents matching the path{" "}
<code className="text-[var(--brand)] dark:text-[var(--accent)] font-mono font-semibold">
{targetPath || section || "root"}
</code>
.
</p>
<div className="pt-4">
<Link
href={backHref}
className="inline-flex items-center gap-1.5 px-4 py-2 bg-[var(--brand)] hover:bg-[var(--brand-hover)] text-white text-xs font-semibold rounded-xl shadow-md shadow-[var(--brand)]/20 transition-all"
>
<ArrowLeft className="w-3.5 h-3.5" />
<span>Return to Knowledge Base</span>
</Link>
</div>
</div>
);
}
return <PdfExportView exportData={exportData} backHref={backHref} />;
}
+531 -77
View File
@@ -1,70 +1,128 @@
@import "tailwindcss";
@plugin "@tailwindcss/typography";
/* Light mode defaults (:root) */
/*
MCPedia Design Philosophy: Archival Precision & Technical Monolith
- Strict monochromatic foundation (Graphite, Zinc, Charcoal)
- Zero decorative AI gradients or blurred blobs
- Typographic hierarchy: Strong contrast, razor-sharp hairline borders, monospace telemetry
- Functional signal indicators (Status Green, Alert Amber, Critical Coral)
*/
/* Light mode defaults (:root) - Technical Paper / Archival Slate */
:root {
color-scheme: light;
--bg-app: #f8fafc;
--bg-app: #f9fafb;
--bg-surface: #ffffff;
--bg-surface-hover: #f1f5f9;
--bg-elevated: #f1f5f9;
--bg-elevated-hover: #e2e8f0;
--border-color: #e2e8f0;
--border-subtle: #edf2f7;
--border-card: #e2e8f0;
--bg-surface-hover: #f3f4f6;
--bg-elevated: #f3f4f6;
--bg-elevated-hover: #e5e7eb;
--border-color: #e5e7eb;
--border-subtle: #f3f4f6;
--border-card: #e5e7eb;
--text-primary: #0f172a;
--text-secondary: #334155;
--text-muted: #64748b;
--text-dim: #94a3b8;
--text-primary: #111827;
--text-secondary: #374151;
--text-muted: #6b7280;
--text-dim: #9ca3af;
--brand: #5e6ad2;
--accent: #4f46e5;
--accent-hover: #4338ca;
/* Accent: Precision Technical Ink */
--brand: #18181b;
--brand-hover: #27272a;
--brand-fg: #ffffff;
--accent: #2563eb;
--accent-hover: #1d4ed8;
--nav-bg: rgba(255, 255, 255, 0.88);
--code-bg: #f1f5f9;
--code-block-bg: #0f172a;
--pre-text: #f8fafc;
--table-zebra: rgba(241, 245, 249, 0.6);
--scrollbar-thumb: #cbd5e1;
--scrollbar-thumb-hover: #94a3b8;
--shadow-card: 0 1px 3px 0 rgba(0, 0, 0, 0.05), 0 1px 2px -1px rgba(0, 0, 0, 0.05);
--nav-bg: rgba(255, 255, 255, 0.92);
/* Code & Syntax (Light Mode) */
--code-bg: #f3f4f6;
--code-block-bg: #f8fafc;
--code-header-bg: #f1f5f9;
--border-code: #e2e8f0;
--code-button-bg: #ffffff;
--code-button-hover-bg: #e2e8f0;
--pre-text: #1e293b;
--code-inline-bg: #f1f5f9;
--code-inline-text: #0f172a;
--code-inline-border: #e2e8f0;
--table-zebra: rgba(243, 244, 246, 0.5);
--scrollbar-thumb: #d1d5db;
--scrollbar-thumb-hover: #9ca3af;
--shadow-card: 0 1px 2px 0 rgba(0, 0, 0, 0.04);
/* Syntax Highlighting */
--hl-keyword: #cf222e;
--hl-string: #0a3069;
--hl-title: #6f42c1;
--hl-attr: #953800;
--hl-number: #0550ae;
--hl-comment: #6e7781;
--hl-builtin: #0969da;
--hl-operator: #57606a;
--hl-variable: #953800;
--hl-meta: #6e7781;
}
/* Dark mode overrides (html.dark) */
/* Dark mode overrides (html.dark) - Deep Basalt / Precision Carbon */
html.dark {
color-scheme: dark;
--bg-app: #08090a;
--bg-surface: #0f1011;
--bg-surface-hover: #131415;
--bg-elevated: #141517;
--bg-elevated-hover: #1b1d20;
--border-color: #1f2022;
--border-subtle: rgba(255, 255, 255, 0.06);
--border-card: #1f2022;
--bg-app: #090a0c;
--bg-surface: #101216;
--bg-surface-hover: #16181f;
--bg-elevated: #161920;
--bg-elevated-hover: #1e222b;
--border-color: #222630;
--border-subtle: #181b22;
--border-card: #222630;
--text-primary: #f7f8f8;
--text-secondary: #d0d6e0;
--text-muted: #8a8f98;
--text-dim: #62666d;
--text-primary: #f3f4f6;
--text-secondary: #d1d5db;
--text-muted: #9ca3af;
--text-dim: #6b7280;
--brand: #5e6ad2;
--accent: #7170ff;
--accent-hover: #828fff;
/* Accent: Monolithic Snow Ink */
--brand: #f3f4f6;
--brand-hover: #ffffff;
--brand-fg: #090a0c;
--accent: #60a5fa;
--accent-hover: #93c5fd;
--nav-bg: rgba(8, 9, 10, 0.85);
--code-bg: #141517;
--code-block-bg: #0c0d0e;
--pre-text: #e2e4e7;
--table-zebra: rgba(255, 255, 255, 0.02);
--scrollbar-thumb: #23252a;
--scrollbar-thumb-hover: #383b42;
--nav-bg: rgba(9, 10, 12, 0.90);
/* Code & Syntax (Dark Mode) */
--code-bg: #0c0e12;
--code-block-bg: #0c0e12;
--code-header-bg: #14171d;
--border-code: #222630;
--code-button-bg: #181b22;
--code-button-hover-bg: #222630;
--pre-text: #e5e7eb;
--code-inline-bg: #161920;
--code-inline-text: #e5e7eb;
--code-inline-border: #222630;
--table-zebra: rgba(255, 255, 255, 0.015);
--scrollbar-thumb: #222630;
--scrollbar-thumb-hover: #374151;
--shadow-card: none;
/* Syntax Highlighting */
--hl-keyword: #ff7b72;
--hl-string: #a5d6ff;
--hl-title: #d2a8ff;
--hl-attr: #ffa657;
--hl-number: #79c0ff;
--hl-comment: #8b949e;
--hl-builtin: #7ee787;
--hl-operator: #8b949e;
--hl-variable: #ffa657;
--hl-meta: #8b949e;
}
@theme inline {
--font-sans: "Inter", system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
--font-sans: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
--font-mono: "JetBrains Mono", ui-monospace, "SF Mono", Menlo, Monaco, Consolas, monospace;
--color-background: var(--bg-app);
@@ -73,6 +131,7 @@ html.dark {
--color-elevated: var(--bg-elevated);
--color-elevated-hover: var(--bg-elevated-hover);
--color-border: var(--border-color);
--border-code: var(--border-code);
--color-border-subtle: var(--border-subtle);
--color-text-primary: var(--text-primary);
@@ -81,6 +140,7 @@ html.dark {
--color-text-quaternary: var(--text-dim);
--color-brand: var(--brand);
--color-brand-hover: var(--brand-hover);
--color-accent: var(--accent);
--color-accent-hover: var(--accent-hover);
}
@@ -93,16 +153,17 @@ body {
background-color: var(--bg-app);
color: var(--text-secondary);
font-family: var(--font-sans);
font-feature-settings: "cv01", "ss03";
font-feature-settings: "cv01", "ss03", "zero", "calt";
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
transition: background-color 0.2s ease, color 0.2s ease;
transition: background-color 0.15s ease, color 0.15s ease;
min-height: 100vh;
}
/* Custom scrollbar */
/* Custom hairline scrollbar */
::-webkit-scrollbar {
width: 6px;
height: 6px;
width: 5px;
height: 5px;
}
::-webkit-scrollbar-track {
@@ -111,49 +172,88 @@ body {
::-webkit-scrollbar-thumb {
background: var(--scrollbar-thumb);
border-radius: 9999px;
border-radius: 2px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--scrollbar-thumb-hover);
}
/* Glassmorphism helpers */
.glass-panel {
background: var(--bg-surface);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border: 1px solid var(--border-color);
}
/* Glass navigation */
.glass-nav {
background: var(--nav-bg);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
/* Prose markdown typography for both Light and Dark modes */
/* Tactical Architectural Callouts */
.callout {
border-left-width: 3px;
border-radius: 0 0.375rem 0.375rem 0;
padding: 0.875rem 1.125rem;
margin: 1.5rem 0;
}
.callout-note {
border-left-color: var(--text-muted);
background-color: var(--bg-elevated);
}
.callout-tip {
border-left-color: #10b981;
background-color: rgba(16, 185, 129, 0.06);
}
.callout-important {
border-left-color: #3b82f6;
background-color: rgba(59, 130, 246, 0.06);
}
.callout-warning {
border-left-color: #f59e0b;
background-color: rgba(245, 158, 11, 0.06);
}
.callout-caution {
border-left-color: #ef4444;
background-color: rgba(239, 68, 68, 0.06);
}
/* Prose Typography */
.prose {
color: var(--text-secondary) !important;
max-width: 100% !important;
}
.prose h1, .prose h2, .prose h3, .prose h4, .prose strong {
color: var(--text-primary) !important;
font-weight: 700;
letter-spacing: -0.02em;
}
.prose a {
color: var(--accent) !important;
color: var(--text-primary) !important;
text-decoration: underline;
text-decoration-color: var(--border-color);
text-underline-offset: 3px;
font-weight: 500;
transition: all 0.15s ease;
}
.prose a:hover {
text-decoration-color: var(--text-primary);
}
.prose table {
width: 100%;
border-collapse: separate;
border-spacing: 0;
margin: 1.75rem 0;
margin: 2rem 0;
font-size: 0.875rem;
border-radius: 0.5rem;
overflow: hidden;
border: 1px solid var(--border-color);
background: var(--bg-surface);
}
.prose th,
@@ -167,9 +267,10 @@ body {
background: var(--bg-elevated);
color: var(--text-primary);
font-weight: 600;
font-size: 0.8125rem;
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.05em;
letter-spacing: 0.08em;
font-family: var(--font-mono);
}
.prose td {
@@ -180,28 +281,35 @@ body {
border-bottom: none;
}
.prose tbody tr:hover {
background: var(--bg-elevated-hover);
}
.prose tbody tr:nth-child(even) {
background: var(--table-zebra);
}
.prose pre {
background: var(--code-block-bg) !important;
border: 1px solid var(--border-color);
border-radius: 0.625rem;
color: var(--pre-text) !important;
border: 1px solid var(--border-code);
border-radius: 0.5rem;
padding: 1rem 1.25rem;
overflow-x: auto;
position: relative;
font-family: var(--font-mono);
line-height: 1.6;
}
.prose code {
font-family: var(--font-mono);
font-size: 0.85em;
font-size: 0.875em;
}
.prose :not(pre) > code {
background: var(--code-bg);
color: var(--text-primary);
border: 1px solid var(--border-color);
background: var(--code-inline-bg);
color: var(--code-inline-text);
border: 1px solid var(--code-inline-border);
padding: 0.15rem 0.35rem;
border-radius: 0.25rem;
font-weight: 500;
@@ -213,13 +321,13 @@ body {
}
.prose blockquote {
border-left: 3px solid var(--brand);
background: rgba(94, 106, 210, 0.08);
border-left: 2px solid var(--text-muted);
background: var(--bg-elevated);
border-radius: 0 0.375rem 0.375rem 0;
margin: 1.5em 0;
padding: 0.75em 1.25em;
font-style: normal;
color: var(--text-muted);
color: var(--text-secondary);
}
.prose hr {
@@ -227,12 +335,358 @@ body {
margin: 2.5rem 0;
}
/* Animations */
/* Syntax Highlighting */
.hljs {
color: var(--pre-text);
background: transparent;
}
.hljs-keyword,
.hljs-selector-tag,
.hljs-subst,
.hljs-doctag {
color: var(--hl-keyword);
font-weight: 600;
}
.hljs-string,
.hljs-regexp,
.hljs-link {
color: var(--hl-string);
}
.hljs-title,
.hljs-title.function_,
.hljs-title.class_,
.hljs-section {
color: var(--hl-title);
font-weight: 600;
}
.hljs-attr,
.hljs-attribute,
.hljs-variable,
.hljs-template-variable,
.hljs-type {
color: var(--hl-attr);
}
.hljs-number,
.hljs-literal {
color: var(--hl-number);
}
.hljs-comment,
.hljs-quote {
color: var(--hl-comment);
font-style: italic;
}
.hljs-built_in,
.hljs-symbol,
.hljs-bullet {
color: var(--hl-builtin);
}
.hljs-meta,
.hljs-meta .hljs-keyword,
.hljs-meta .hljs-string {
color: var(--hl-meta);
}
.hljs-params {
color: var(--pre-text);
}
.hljs-punctuation,
.hljs-operator {
color: var(--hl-operator);
}
.hljs-addition {
color: #10b981;
background-color: rgba(16, 185, 129, 0.15);
border-radius: 2px;
}
.hljs-deletion {
color: #ef4444;
background-color: rgba(239, 68, 68, 0.15);
border-radius: 2px;
}
.hljs-emphasis {
font-style: italic;
}
.hljs-strong {
font-weight: bold;
}
/* Transitions */
@keyframes fadeIn {
from { opacity: 0; transform: translateY(4px); }
to { opacity: 1; transform: translateY(0); }
}
.animate-fade-in {
animation: fadeIn 0.2s ease-out forwards;
animation: fadeIn 0.18s ease-out forwards;
}
/* Print & PDF Export Stylesheet */
@media print {
@page {
size: A4 portrait;
margin: 10mm 12mm 10mm 12mm;
}
*, *::before, *::after {
-webkit-print-color-adjust: exact !important;
print-color-adjust: exact !important;
box-sizing: border-box !important;
}
html, body {
background-color: #ffffff !important;
color: #0f172a !important;
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif !important;
font-size: 8.5pt !important;
line-height: 1.35 !important;
margin: 0 !important;
padding: 0 !important;
width: 100% !important;
}
/* Hide navigation, toolbars, sidebar, and web UI controls */
header.site-header,
header.glass-nav,
aside.site-sidebar,
aside:not(.print-include),
footer,
nav.site-header,
.no-print,
.export-toolbar,
#a11y-live-region {
display: none !important;
}
main,
.print-container,
main > div {
max-width: 100% !important;
width: 100% !important;
margin: 0 !important;
padding: 0 !important;
border: none !important;
box-shadow: none !important;
background: transparent !important;
}
/* Explicit page break classes */
.page-break-before,
.chapter-page {
break-before: page !important;
page-break-before: always !important;
}
/* Prevent awkward mid-element page breaks */
.avoid-break-inside,
.code-block-wrapper,
.code-block-container,
.callout,
blockquote,
table,
tr,
img {
break-inside: avoid !important;
page-break-inside: avoid !important;
}
/* Prevent headings from being orphaned at the bottom of pages */
.challenge-header,
h1, h2, h3, h4, h5, h6 {
break-after: avoid !important;
page-break-after: avoid !important;
}
/* Dense / compact challenge flow */
.challenge-entry {
break-inside: auto !important;
page-break-inside: auto !important;
}
/* Compact typography & prose overrides */
p,
.prose p {
margin-top: 0 !important;
margin-bottom: 2.5pt !important;
font-size: 8.5pt !important;
line-height: 1.35 !important;
color: #1e293b !important;
}
h1,
.prose h1 {
font-size: 13pt !important;
line-height: 1.2 !important;
font-weight: 800 !important;
color: #020617 !important;
margin-top: 6pt !important;
margin-bottom: 2pt !important;
padding-bottom: 1pt !important;
border-bottom: 1px solid #cbd5e1 !important;
}
h2,
.prose h2 {
font-size: 10.5pt !important;
line-height: 1.2 !important;
font-weight: 700 !important;
color: #020617 !important;
margin-top: 5pt !important;
margin-bottom: 2pt !important;
padding-bottom: 1pt !important;
border-bottom: 1px solid #e2e8f0 !important;
}
h3,
.prose h3 {
font-size: 9.5pt !important;
line-height: 1.2 !important;
font-weight: 700 !important;
color: #0f172a !important;
margin-top: 4pt !important;
margin-bottom: 1.5pt !important;
}
h4, h5, h6,
.prose h4, .prose h5, .prose h6 {
font-size: 8.5pt !important;
line-height: 1.2 !important;
font-weight: 600 !important;
color: #1e293b !important;
margin-top: 3pt !important;
margin-bottom: 1pt !important;
}
ul, ol,
.prose ul, .prose ol {
margin-top: 1pt !important;
margin-bottom: 2.5pt !important;
padding-left: 13pt !important;
}
li,
.prose li {
margin-top: 0.5pt !important;
margin-bottom: 0.5pt !important;
font-size: 8.5pt !important;
line-height: 1.3 !important;
}
li > p {
margin: 0 !important;
}
blockquote,
.prose blockquote,
.callout {
margin: 2.5pt 0 !important;
padding: 2pt 5pt !important;
font-size: 8pt !important;
line-height: 1.3 !important;
border-left: 2.5px solid #64748b !important;
background-color: #f8fafc !important;
border-radius: 0 2px 2px 0 !important;
}
table,
.prose table {
margin: 2.5pt 0 !important;
font-size: 7.5pt !important;
line-height: 1.25 !important;
border-collapse: collapse !important;
width: 100% !important;
border: 1px solid #cbd5e1 !important;
}
th, td,
.prose th, .prose td {
padding: 2pt 4pt !important;
border: 1px solid #cbd5e1 !important;
color: #1e293b !important;
}
th,
.prose th {
background-color: #f1f5f9 !important;
font-weight: 700 !important;
text-transform: uppercase !important;
letter-spacing: 0.04em !important;
}
hr,
.prose hr {
margin: 3pt 0 !important;
border-color: #e2e8f0 !important;
}
img {
max-width: 100% !important;
max-height: 220px !important;
height: auto !important;
object-fit: contain !important;
margin: 2.5pt auto !important;
display: block !important;
}
.code-block-wrapper,
.code-block-container {
break-inside: avoid !important;
page-break-inside: avoid !important;
border: 1px solid #cbd5e1 !important;
background-color: #f8fafc !important;
border-radius: 3px !important;
margin: 2.5pt 0 !important;
overflow: hidden !important;
}
.code-block-header {
border-bottom: 1px solid #cbd5e1 !important;
background-color: #f1f5f9 !important;
padding: 1.5pt 5pt !important;
color: #334155 !important;
font-size: 7pt !important;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace !important;
font-weight: 700 !important;
text-transform: uppercase !important;
}
.code-block-wrapper pre {
border: none !important;
background-color: transparent !important;
padding: 3pt 5pt !important;
margin: 0 !important;
border-radius: 0 !important;
}
pre,
pre code,
code {
white-space: pre-wrap !important;
word-break: break-all !important;
overflow-wrap: anywhere !important;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace !important;
font-size: 7.5pt !important;
line-height: 1.3 !important;
color: #0f172a !important;
}
:not(pre) > code {
padding: 0.5pt 2pt !important;
font-size: 7.5pt !important;
background-color: #f1f5f9 !important;
border: 1px solid #e2e8f0 !important;
border-radius: 2px !important;
}
}
+30
View File
@@ -0,0 +1,30 @@
"use client";
import useSWR from "swr";
import { fetcher } from "@/lib/fetcher";
import type { DocumentMeta } from "@mcpedia/types";
type DocsEnvelope = DocumentMeta[] | { docs: DocumentMeta[] };
function normalize(data: DocsEnvelope | undefined): DocumentMeta[] {
if (!data) return [];
if (Array.isArray(data)) return data;
return (data as { docs: DocumentMeta[] }).docs ?? [];
}
export function useDocuments(section?: string, status = "published") {
const params = new URLSearchParams();
if (section) params.set("section", section);
if (status) params.set("status", status);
const qs = params.toString();
const key = qs ? `/api/docs?${qs}` : "/api/docs";
const swr = useSWR<DocsEnvelope>(key, fetcher, {
revalidateOnFocus: false,
});
return {
...swr,
docs: normalize(swr.data),
};
}
Loaded 50 of 94 files, more files were not shown because too many files have changed in this diff. Show more