commit 350aae797fe280f2ecbad52a790fdfb74ab22404 Author: Codex Bot Date: Fri Sep 18 21:50:25 2026 +0800 feat: launch PK testing application diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..ebb546a --- /dev/null +++ b/.dockerignore @@ -0,0 +1,11 @@ +.git +.gitea +pages +utils +scripts +app.js +app.json +app.css +project.config.json +README.md + diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml new file mode 100644 index 0000000..53f586d --- /dev/null +++ b/.gitea/workflows/deploy.yml @@ -0,0 +1,49 @@ +name: Verify mini program and deploy preview +on: + push: + branches: [main] + pull_request: +concurrency: + group: pk-lab-xhs-production + cancel-in-progress: false +jobs: + verify-deploy: + runs-on: ubuntu-latest + container: { image: docker:27-cli } + timeout-minutes: 20 + env: + SOURCE_SERVER: ${{ gitea.server_url }} + SOURCE_REPOSITORY: ${{ gitea.repository }} + SOURCE_REVISION: ${{ gitea.sha }} + DEPLOY_PORT: ${{ vars.DEPLOY_PORT || '3001' }} + API_BASE_URL: ${{ vars.API_BASE_URL || 'http://47.76.92.159:18082' }} + steps: + - name: Fetch exact revision + env: { SOURCE_TOKEN: "${{ secrets.GITEA_TOKEN }}" } + run: | + set -eu + apk add --no-cache python3 nodejs curl + python3 - <<'PY' + import io,os,shutil,tarfile,tempfile,urllib.request + from pathlib import Path + url=f"{os.environ['SOURCE_SERVER'].rstrip('/')}/api/v1/repos/{os.environ['SOURCE_REPOSITORY']}/archive/{os.environ['SOURCE_REVISION']}.tar.gz" + req=urllib.request.Request(url,headers={'Authorization':'token '+os.environ['SOURCE_TOKEN']}) + with urllib.request.urlopen(req,timeout=60) as r:data=r.read() + with tempfile.TemporaryDirectory() as d: + with tarfile.open(fileobj=io.BytesIO(data),mode='r:gz') as a:a.extractall(d,filter='data') + roots=list(Path(d).iterdir());shutil.copytree(roots[0],Path.cwd(),dirs_exist_ok=True) + PY + - name: Check source and preview + run: npm run check + - name: Build preview image + run: docker build -t "pk-lab-xhs:$SOURCE_REVISION" . + - name: Update permanent preview container + if: gitea.event_name == 'push' && gitea.ref == 'refs/heads/main' + run: | + set -eu + docker rm -f pk-lab-xhs-preview 2>/dev/null || true + docker run -d --name pk-lab-xhs-preview --restart unless-stopped --read-only --tmpfs /var/cache/nginx --tmpfs /var/run -e API_BASE_URL="$API_BASE_URL" -p "$DEPLOY_PORT:8080" "pk-lab-xhs:$SOURCE_REVISION" + for i in 1 2 3 4 5 6; do curl -fsS "http://127.0.0.1:$DEPLOY_PORT/health" && exit 0; sleep 2; done + docker logs pk-lab-xhs-preview + exit 1 + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..096a8b1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.DS_Store +node_modules/ +project.private.config.json + diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..62e0033 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,6 @@ +FROM nginx:1.27-alpine +COPY web /usr/share/nginx/html +RUN printf 'server { listen 8080; server_name _; root /usr/share/nginx/html; location = /runtime-env.js { alias /tmp/runtime-env.js; } location / { try_files $uri $uri/ /index.html; } location = /health { access_log off; return 200 "ok\\n"; add_header Content-Type text/plain; } }' > /etc/nginx/conf.d/default.conf +EXPOSE 8080 +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=5 CMD wget -q -O- http://127.0.0.1:8080/health || exit 1 +CMD ["/bin/sh", "-c", "envsubst '$API_BASE_URL' < /usr/share/nginx/html/runtime-env.js > /tmp/runtime-env.js && exec nginx -g 'daemon off;'"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..3438c48 --- /dev/null +++ b/README.md @@ -0,0 +1,13 @@ +# PK 研究所(综合版) + +原生小红书小程序源码,同时提供由 Nginx 常驻托管的公网功能预览。综合版包含瀑布流测试广场、二选一淘汰赛、我的历史、跨小程序绑定码与三种可保存的分享图模板。 + +## 接入 + +1. 在 `app.js` 将 `apiBase` 改成生产 HTTPS API。 +2. 在小红书开放平台将该域名加入 request 合法域名。 +3. 用小红书开发者工具打开仓库根目录,绑定综合版 App ID。 +4. 后端配置同一 App ID/Secret 后重新部署。 + +CI 默认把公网预览持续部署到宿主机 `3001` 端口;配置变量 `DEPLOY_PORT` 可覆盖,`API_BASE_URL` 指向后端。预览使用后端显式开启的 `TEST_AUTH_ENABLED` 测试身份,正式小程序使用 `xhs.login()`。 + diff --git a/app.css b/app.css new file mode 100644 index 0000000..aadb431 --- /dev/null +++ b/app.css @@ -0,0 +1,8 @@ +page { background: #fff8f2; color: #201d1b; font-family: system-ui, -apple-system, sans-serif; } +.page { min-height: 100vh; padding: 28rpx; box-sizing: border-box; } +.muted { color: #867d76; } +.pill { display: inline-flex; padding: 10rpx 20rpx; border-radius: 999rpx; background: #fff0e4; color: #b65224; font-size: 24rpx; } +.primary { background: #25211f; color: #fff; border-radius: 999rpx; font-weight: 700; } +.secondary { background: #fff; color: #25211f; border: 2rpx solid #e8ded7; border-radius: 999rpx; } +.empty { padding: 100rpx 28rpx; text-align: center; color: #867d76; } + diff --git a/app.js b/app.js new file mode 100644 index 0000000..36f681d --- /dev/null +++ b/app.js @@ -0,0 +1,11 @@ +App({ + globalData: { + apiBase: 'https://api.example.com', + appKey: 'hub' + }, + onLaunch: function () { + var token = xhs.getStorageSync('pk_token'); + if (token) this.globalData.token = token; + } +}); + diff --git a/app.json b/app.json new file mode 100644 index 0000000..7a1b568 --- /dev/null +++ b/app.json @@ -0,0 +1,18 @@ +{ + "pages": [ + "pages/index/index", + "pages/test/test", + "pages/result/result", + "pages/me/me" + ], + "window": { + "navigationBarBackgroundColor": "#fff8f2", + "navigationBarTextStyle": "black", + "navigationBarTitleText": "PK 研究所", + "backgroundColor": "#fff8f2" + }, + "networkTimeout": { + "request": 10000 + } +} + diff --git a/package.json b/package.json new file mode 100644 index 0000000..9a165b1 --- /dev/null +++ b/package.json @@ -0,0 +1,7 @@ +{ + "name": "pk-lab-xhs", + "version": "0.1.0", + "private": true, + "scripts": { "check": "node scripts/check.mjs" } +} + diff --git a/pages/index/index.css b/pages/index/index.css new file mode 100644 index 0000000..c0be834 --- /dev/null +++ b/pages/index/index.css @@ -0,0 +1,23 @@ +.home { padding-bottom: 70rpx; } +.hero { position: relative; overflow: hidden; background: #ff6b35; color: #fff; border-radius: 36rpx; padding: 40rpx 34rpx 34rpx; box-shadow: 0 18rpx 50rpx rgba(168, 65, 25, .18); } +.hero-row { display: flex; justify-content: space-between; align-items: flex-start; } +.eyebrow { font-size: 21rpx; letter-spacing: 4rpx; opacity: .8; } +.title { width: 480rpx; margin-top: 18rpx; font-size: 58rpx; line-height: 1.05; font-weight: 900; } +.hero-copy { margin-top: 42rpx; width: 480rpx; font-size: 27rpx; line-height: 1.6; opacity: .92; } +.me-button { margin: 0; padding: 0 24rpx; min-width: 0; height: 64rpx; line-height: 64rpx; font-size: 25rpx; border-radius: 999rpx; background: rgba(255,255,255,.2); color: #fff; } +.hero-stickers { margin-top: 30rpx; display: flex; justify-content: space-between; font-size: 30rpx; font-weight: 800; } +.section-head { display: flex; justify-content: space-between; margin: 48rpx 6rpx 24rpx; font-size: 30rpx; font-weight: 800; } +.section-head .muted { font-size: 24rpx; font-weight: 500; } +.waterfall { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); grid-gap: 22rpx; align-items: start; } +.test-card { overflow: hidden; background: #fff; border-radius: 28rpx; box-shadow: 0 9rpx 30rpx rgba(62, 42, 30, .08); } +.test-card:active { transform: scale(.98); } +.card-art { position: relative; height: 250rpx; overflow: hidden; } +.card-1 .card-art { height: 310rpx; } +.card-number { position: absolute; left: 20rpx; top: 18rpx; color: rgba(255,255,255,.8); font-size: 22rpx; font-weight: 800; } +.card-emoji { position: absolute; left: 50%; top: 52%; transform: translate(-50%, -50%) rotate(-8deg); font-size: 112rpx; } +.card-body { padding: 24rpx; } +.card-title { font-size: 30rpx; font-weight: 900; } +.card-copy { margin-top: 12rpx; color: #746a63; font-size: 23rpx; line-height: 1.45; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; overflow: hidden; } +.card-meta { margin-top: 22rpx; display: flex; justify-content: space-between; color: #9a8e86; font-size: 20rpx; } +.retry { margin-top: 24rpx; width: 240rpx; font-size: 24rpx; } + diff --git a/pages/index/index.js b/pages/index/index.js new file mode 100644 index 0000000..eb68a35 --- /dev/null +++ b/pages/index/index.js @@ -0,0 +1,23 @@ +var api = require('../../utils/api'); + +Page({ + data: { tests: [], loading: true, error: '' }, + onLoad: function () { this.loadTests(); }, + onPullDownRefresh: function () { this.loadTests(true); }, + loadTests: function (refreshing) { + var self = this; + api.request('/api/v1/tests').then(function (tests) { + self.setData({ tests: tests, loading: false, error: '' }); + }).catch(function (error) { + self.setData({ loading: false, error: error.message || '加载失败' }); + }).then(function () { + if (refreshing) xhs.stopPullDownRefresh(); + }, function () { + if (refreshing) xhs.stopPullDownRefresh(); + }); + }, + openTest: function (event) { + xhs.navigateTo({ url: '/pages/test/test?slug=' + event.currentTarget.dataset.slug }); + }, + openMe: function () { xhs.navigateTo({ url: '/pages/me/me' }); } +}); diff --git a/pages/index/index.json b/pages/index/index.json new file mode 100644 index 0000000..9d61ab8 --- /dev/null +++ b/pages/index/index.json @@ -0,0 +1,2 @@ +{ "navigationBarTitleText": "PK 研究所" } + diff --git a/pages/index/index.xhsml b/pages/index/index.xhsml new file mode 100644 index 0000000..6e0170c --- /dev/null +++ b/pages/index/index.xhsml @@ -0,0 +1,29 @@ + + + + + TASTE LAB · 01 + 今天,认真选一个。 + + + + 没有“都可以”。每轮只选一个,让你的偏爱一路赢到底。 + ✦二选一↗ + + 全部测试{{tests.length}} 个题库 + 正在摆好擂台… + {{error}} + + + + 0{{index + 1}}{{item.emoji}} + + + {{item.title}} + {{item.subtitle}} + {{item.candidate_count}} 强{{item.run_count}} 人完成 → + + + + + diff --git a/pages/me/me.css b/pages/me/me.css new file mode 100644 index 0000000..6f3b658 --- /dev/null +++ b/pages/me/me.css @@ -0,0 +1,16 @@ +.profile-head { display: flex; align-items: center; margin: 12rpx 0 38rpx; } +.avatar { width: 104rpx; height: 104rpx; margin-right: 24rpx; line-height: 104rpx; text-align: center; border-radius: 50%; background: #25211f; color: #fff; font-weight: 900; } +.profile-title { font-size: 40rpx; font-weight: 900; } +.link-card { padding: 30rpx; border-radius: 30rpx; background: #f7e9ff; } +.link-title { margin-bottom: 10rpx; font-size: 29rpx; font-weight: 800; } +.link-card .muted { font-size: 23rpx; line-height: 1.5; } +.link-button { margin: 24rpx 0 0; font-size: 23rpx; } +.link-code { margin-top: 22rpx; text-align: center; font-size: 52rpx; letter-spacing: 12rpx; font-weight: 900; } +.section-title { margin: 48rpx 4rpx 22rpx; font-size: 29rpx; font-weight: 900; } +.result-row { display: flex; align-items: center; margin-bottom: 18rpx; padding: 28rpx; border-radius: 28rpx; background: #fff; box-shadow: 0 8rpx 26rpx rgba(50,35,25,.07); } +.medal { width: 74rpx; height: 74rpx; margin-right: 24rpx; line-height: 74rpx; text-align: center; border-radius: 20rpx; background: #ff6b35; color: #fff; font-weight: 900; } +.result-main { flex: 1; min-width: 0; } +.result-test { color: #887c74; font-size: 22rpx; } +.result-champion { margin-top: 6rpx; font-size: 34rpx; font-weight: 900; } +.arrow { font-size: 34rpx; } + diff --git a/pages/me/me.js b/pages/me/me.js new file mode 100644 index 0000000..e51156c --- /dev/null +++ b/pages/me/me.js @@ -0,0 +1,24 @@ +var api = require('../../utils/api'); + +Page({ + data: { loading: true, results: [], error: '', linkCode: '' }, + onShow: function () { this.load(); }, + load: function () { + var self = this; + api.ensureLogin().then(function () { return api.request('/api/v1/me/results'); }).then(function (results) { + self.setData({ results: results, loading: false, error: '' }); + }).catch(function (error) { self.setData({ loading: false, error: error.message || '加载失败' }); }); + }, + openResult: function (event) { + var result = this.data.results[event.currentTarget.dataset.index]; + xhs.setStorageSync('pk_last_result', result); + xhs.navigateTo({ url: '/pages/result/result?id=' + result.id }); + }, + makeLinkCode: function () { + var self = this; + api.request('/api/v1/me/link-code', { method: 'POST' }).then(function (data) { + self.setData({ linkCode: data.code }); + }).catch(function (error) { xhs.showToast({ title: error.message || '生成失败', icon: 'none' }); }); + } +}); + diff --git a/pages/me/me.json b/pages/me/me.json new file mode 100644 index 0000000..d813173 --- /dev/null +++ b/pages/me/me.json @@ -0,0 +1,2 @@ +{ "navigationBarTitleText": "我的 PK 档案" } + diff --git a/pages/me/me.xhsml b/pages/me/me.xhsml new file mode 100644 index 0000000..25dc87c --- /dev/null +++ b/pages/me/me.xhsml @@ -0,0 +1,19 @@ + + 我我的偏爱档案每次纠结,都算数。 + + 连接独立饭类版 + 两个小程序的身份标识不同,用一次性码确认后即可合并历史。 + + {{linkCode}} + + 做过的测试 · {{results.length}} + 正在翻档案… + {{error}} + 还没有结果,去选出第一个冠军吧。 + + + #1{{item.test_title}}{{item.champion_name}}→ + + + + diff --git a/pages/result/result.css b/pages/result/result.css new file mode 100644 index 0000000..d6a1664 --- /dev/null +++ b/pages/result/result.css @@ -0,0 +1,16 @@ +.result-kicker { text-align: center; color: #ff6b35; font-size: 22rpx; letter-spacing: 6rpx; font-weight: 800; } +.result-title { margin: 14rpx 0 28rpx; text-align: center; font-size: 46rpx; font-weight: 900; } +.champion { position: relative; overflow: hidden; padding: 54rpx 36rpx; text-align: center; border-radius: 36rpx; background: #25211f; color: #fff; } +.crown { position: absolute; right: 24rpx; top: 2rpx; color: #ffe568; font-size: 100rpx; transform: rotate(13deg); } +.test-name { opacity: .62; font-size: 24rpx; } +.champion-name { margin-top: 18rpx; font-size: 70rpx; line-height: 1.15; font-weight: 900; } +.runner { margin-top: 22rpx; color: #e5dcd6; font-size: 23rpx; } +.poster-head { display: flex; justify-content: space-between; margin: 46rpx 4rpx 20rpx; font-size: 30rpx; font-weight: 900; } +.poster-head .muted { font-size: 23rpx; font-weight: 500; } +.poster { width: 100%; height: 925rpx; border-radius: 30rpx; box-shadow: 0 16rpx 40rpx rgba(50,30,20,.12); } +.theme-scroll { margin-top: 26rpx; white-space: nowrap; } +.theme-row { display: flex; } +.theme-chip { flex: none; margin: 0 14rpx 0 0; padding: 0 28rpx; height: 68rpx; line-height: 68rpx; border-radius: 99rpx; background: #fff; color: #6d625b; font-size: 23rpx; } +.theme-chip.active { background: #25211f; color: #fff; } +.sticker-row { display: flex; justify-content: space-between; margin-top: 26rpx; padding: 26rpx; border-radius: 24rpx; background: #fff; font-size: 25rpx; } +.save, .again { margin-top: 22rpx; font-size: 28rpx; } diff --git a/pages/result/result.js b/pages/result/result.js new file mode 100644 index 0000000..cd78654 --- /dev/null +++ b/pages/result/result.js @@ -0,0 +1,90 @@ +var api = require('../../utils/api'); + +var THEMES = { + celebration: { bg: '#ff6b35', ink: '#fffaf4', card: '#25211f', accent: '#ffe568', label: '庆祝派对' }, + editorial: { bg: '#f3eadf', ink: '#201d1b', card: '#ffffff', accent: '#285ee8', label: '杂志封面' }, + sticker: { bg: '#c9f06b', ink: '#1e2810', card: '#ff72a7', accent: '#ffffff', label: '贴纸手账' } +}; + +Page({ + data: { + result: null, + template: 'celebration', + themeList: [ + { name: 'celebration', label: '庆祝派对' }, + { name: 'editorial', label: '杂志封面' }, + { name: 'sticker', label: '贴纸手账' } + ], + sticker: true, + saving: false + }, + onLoad: function (options) { + var cached = xhs.getStorageSync('pk_last_result'); + this.runId = options.id; + if (cached && cached.id === options.id) this.setData({ result: cached }); + else this.load(); + }, + onReady: function () { if (this.data.result) this.drawPoster(); }, + load: function () { + var self = this; + api.ensureLogin().then(function () { return api.request('/api/v1/me/results/' + self.runId); }).then(function (result) { + self.setData({ result: result }); self.drawPoster(); + }).catch(function (error) { xhs.showModal({ title: '读取失败', content: error.message || '请稍后重试', showCancel: false }); }); + }, + pickTemplate: function (event) { + this.setData({ template: event.currentTarget.dataset.name }); + this.drawPoster(); + }, + toggleSticker: function () { this.setData({ sticker: !this.data.sticker }); this.drawPoster(); }, + drawPoster: function () { + var result = this.data.result; + if (!result) return; + var theme = THEMES[this.data.template]; + var isCelebration = this.data.template === 'celebration'; + var showSticker = this.data.sticker; + xhs.createSelectorQuery().select('.poster').boundingClientRect(function (rect) { + var ctx = xhs.createCanvasContext('poster'); + if (rect) ctx.scale(rect.width / 750, rect.height / 1000); + ctx.setFillStyle(theme.bg); ctx.fillRect(0, 0, 750, 1000); + ctx.setFillStyle(theme.ink); ctx.setFontSize(24); ctx.fillText('PK 研究所 / MY PICK', 54, 72); + ctx.setFontSize(58); ctx.fillText('我的冠军是', 54, 156); + ctx.setFillStyle(theme.card); ctx.fillRect(46, 205, 658, 440); + ctx.setFillStyle(isCelebration ? '#fffaf4' : theme.ink); + ctx.setFontSize(26); ctx.fillText(result.test_title, 84, 270); + ctx.setFontSize(result.champion_name.length > 7 ? 62 : 82); + ctx.fillText(result.champion_name, 84, 405); + ctx.setFillStyle(theme.accent); ctx.fillRect(84, 440, Math.min(500, result.champion_name.length * 80), 18); + ctx.setFillStyle(isCelebration ? '#fffaf4' : theme.ink); + ctx.setFontSize(24); ctx.fillText('一路二选一,它赢到了最后。', 84, 525); + var ranking = result.ranking_names || []; + ctx.setFillStyle(theme.ink); ctx.setFontSize(25); ctx.fillText('我的 TOP 4', 54, 720); + for (var i = 0; i < Math.min(4, ranking.length); i += 1) { + ctx.setFontSize(26); ctx.fillText((i + 1) + '. ' + ranking[i], 64, 774 + i * 48); + } + if (showSticker) { + ctx.setFillStyle(theme.accent); ctx.beginPath(); ctx.arc(645, 125, 58, 0, Math.PI * 2); ctx.fill(); + ctx.setFillStyle(theme.card); ctx.setFontSize(28); ctx.fillText('WIN!', 607, 134); + ctx.setFontSize(52); ctx.fillText('✦', 640, 700); ctx.fillText('♡', 550, 900); + } + ctx.setFillStyle(theme.ink); ctx.setFontSize(20); ctx.fillText('长按保存,把答案分享给同频的人', 54, 956); + ctx.draw(); + }).exec(); + }, + savePoster: function () { + var self = this; + this.setData({ saving: true }); + xhs.canvasToTempFilePath({ + canvasId: 'poster', destWidth: 750, destHeight: 1000, + success: function (file) { + xhs.saveImageToPhotosAlbum({ + filePath: file.tempFilePath, + success: function () { xhs.showToast({ title: '已保存到相册' }); }, + fail: function () { xhs.showToast({ title: '保存失败,请检查相册权限', icon: 'none' }); }, + complete: function () { self.setData({ saving: false }); } + }); + }, + fail: function () { self.setData({ saving: false }); xhs.showToast({ title: '海报生成失败', icon: 'none' }); } + }); + }, + replay: function () { xhs.redirectTo({ url: '/pages/test/test?slug=' + this.data.result.test_slug }); } +}); diff --git a/pages/result/result.json b/pages/result/result.json new file mode 100644 index 0000000..56b8ff5 --- /dev/null +++ b/pages/result/result.json @@ -0,0 +1,2 @@ +{ "navigationBarTitleText": "你的冠军" } + diff --git a/pages/result/result.xhsml b/pages/result/result.xhsml new file mode 100644 index 0000000..19ab2e0 --- /dev/null +++ b/pages/result/result.xhsml @@ -0,0 +1,15 @@ + + FINAL ANSWER + 你的冠军诞生了! + ♛{{result.test_title}}{{result.champion_name}}决赛击败 {{result.runner_up_name}} + 分享卡片3 款模板任选 + + + + + + + 添加手绘贴纸{{sticker ? '已开启 ✓' : '关闭'}} + + + diff --git a/pages/test/test.css b/pages/test/test.css new file mode 100644 index 0000000..cc5808f --- /dev/null +++ b/pages/test/test.css @@ -0,0 +1,19 @@ +.arena { min-height: 100vh; background: #fff8f2; } +.topline { display: flex; align-items: center; justify-content: space-between; } +.progress { margin-top: 20rpx; height: 10rpx; overflow: hidden; border-radius: 99rpx; background: #eee4dd; } +.progress-in { height: 100%; border-radius: inherit; background: #ff6b35; transition: width .25s; } +.question { margin: 54rpx 8rpx 34rpx; font-size: 52rpx; line-height: 1.18; font-weight: 900; } +.pair { position: relative; } +.choice { position: relative; min-height: 360rpx; padding: 34rpx; box-sizing: border-box; border-radius: 38rpx; color: #fff; box-shadow: 0 20rpx 50rpx rgba(80, 35, 18, .14); } +.choice + .choice { margin-top: 24rpx; } +.choice-a { background: #ff6b35; transform: rotate(-1deg); } +.choice-b { background: #2766df; transform: rotate(1deg); } +.choice:active { transform: scale(.975); } +.choice-index { width: 54rpx; height: 54rpx; line-height: 54rpx; text-align: center; border: 2rpx solid rgba(255,255,255,.6); border-radius: 50%; font-size: 24rpx; font-weight: 800; } +.food-mark { position: absolute; right: 34rpx; top: 24rpx; font-size: 92rpx; opacity: .8; transform: rotate(12deg); } +.choice-name { margin-top: 72rpx; font-size: 60rpx; line-height: 1.12; font-weight: 900; } +.tap-hint { margin-top: 54rpx; font-size: 24rpx; opacity: .75; } +.versus { position: absolute; z-index: 3; left: 50%; top: 50%; transform: translate(-50%, -50%) rotate(-8deg); width: 84rpx; height: 84rpx; line-height: 84rpx; text-align: center; color: #201d1b; background: #fff; border: 5rpx solid #201d1b; border-radius: 50%; font-size: 26rpx; font-weight: 900; } +.round-note { margin: 38rpx 0; text-align: center; color: #8f827a; font-size: 24rpx; } +.saving { position: fixed; left: 50%; bottom: 70rpx; transform: translateX(-50%); padding: 22rpx 34rpx; border-radius: 99rpx; background: #201d1b; color: #fff; font-size: 25rpx; } + diff --git a/pages/test/test.js b/pages/test/test.js new file mode 100644 index 0000000..d68998b --- /dev/null +++ b/pages/test/test.js @@ -0,0 +1,68 @@ +var api = require('../../utils/api'); +var bracket = require('../../utils/bracket'); + +Page({ + data: { loading: true, error: '', test: null, left: null, right: null, round: 1, progress: 0, completed: 0, totalDecisions: 0 }, + onLoad: function (options) { + this.slug = options.slug; + this.load(); + }, + load: function () { + var self = this; + api.request('/api/v1/tests/' + this.slug).then(function (test) { + self.test = test; + self.state = bracket.create(test.candidates); + self.totalDecisions = test.candidates.length - 1; + self.refreshPair(); + self.setData({ loading: false, test: test, totalDecisions: self.totalDecisions }); + }).catch(function (error) { self.setData({ loading: false, error: error.message || '加载失败' }); }); + }, + refreshPair: function () { + var pair = bracket.current(this.state); + this.setData({ + left: pair && pair[0], + right: pair && pair[1], + round: this.state.round, + completed: this.state.decisions.length, + progress: Math.round(this.state.decisions.length / this.totalDecisions * 100) + }); + }, + choose: function (event) { + if (this.choosing) return; + this.choosing = true; + var side = event.currentTarget.dataset.side; + var winner = side === 'left' ? this.data.left : this.data.right; + var finished = bracket.choose(this.state, winner); + if (finished) this.complete(); + else { + this.refreshPair(); + this.choosing = false; + } + }, + complete: function () { + var self = this; + var champion = this.state.pool[0]; + var finalDecision = this.state.decisions[this.state.decisions.length - 1]; + var runnerUpId = finalDecision.left_id === champion.id ? finalDecision.right_id : finalDecision.left_id; + this.setData({ progress: 100, submitting: true }); + api.ensureLogin().then(function () { + return api.request('/api/v1/tests/' + self.slug + '/runs', { + method: 'POST', + data: { + app_key: 'hub', + champion_id: champion.id, + runner_up_id: runnerUpId, + ranking_ids: bracket.ranking(self.state), + decisions: self.state.decisions + } + }); + }).then(function (result) { + xhs.setStorageSync('pk_last_result', result); + xhs.redirectTo({ url: '/pages/result/result?id=' + result.id }); + }).catch(function (error) { + self.choosing = false; + self.setData({ submitting: false }); + xhs.showModal({ title: '结果保存失败', content: error.message || '请检查网络后重试', showCancel: false }); + }); + } +}); diff --git a/pages/test/test.json b/pages/test/test.json new file mode 100644 index 0000000..b157a79 --- /dev/null +++ b/pages/test/test.json @@ -0,0 +1,2 @@ +{ "navigationBarTitleText": "开始 PK" } + diff --git a/pages/test/test.xhsml b/pages/test/test.xhsml new file mode 100644 index 0000000..138dfd5 --- /dev/null +++ b/pages/test/test.xhsml @@ -0,0 +1,20 @@ + + 正在抽签… + {{error}} + + 第 {{round}} 轮{{progress}}% + + 此刻只能留一个,你会选谁? + + + A{{test.emoji}}{{left.name}}点它晋级 ↗ + + VS + + B{{test.emoji}}{{right.name}}点它晋级 ↗ + + + 已完成 {{completed}} / {{totalDecisions}} 次选择 + 正在保存你的冠军… + + diff --git a/project.config.json b/project.config.json new file mode 100644 index 0000000..10a8d66 --- /dev/null +++ b/project.config.json @@ -0,0 +1,9 @@ +{ + "description": "PK 研究所 - 小红书原生小程序", + "miniprogramRoot": "./", + "setting": { + "es6": true, + "minified": true + } +} + diff --git a/scripts/check.mjs b/scripts/check.mjs new file mode 100644 index 0000000..e9a9661 --- /dev/null +++ b/scripts/check.mjs @@ -0,0 +1,8 @@ +import { readFileSync, existsSync } from 'node:fs'; +const required = ['app.js','app.json','pages/index/index.xhsml','pages/test/test.js','pages/result/result.js','web/index.html','web/app.js']; +for (const file of required) if (!existsSync(file)) throw new Error(`Missing ${file}`); +JSON.parse(readFileSync('app.json','utf8')); +const web = readFileSync('web/index.html','utf8'); +if (!web.includes('./app.js') || !web.includes('./style.css')) throw new Error('Preview assets are not linked'); +console.log(`Static checks passed (${required.length} required files).`); + diff --git a/utils/api.js b/utils/api.js new file mode 100644 index 0000000..b67f837 --- /dev/null +++ b/utils/api.js @@ -0,0 +1,41 @@ +function request(path, options) { + var app = getApp(); + var token = app.globalData.token || xhs.getStorageSync('pk_token'); + options = options || {}; + return new Promise(function (resolve, reject) { + xhs.request({ + url: app.globalData.apiBase + path, + method: options.method || 'GET', + data: options.data, + header: token ? { 'content-type': 'application/json', Authorization: 'Bearer ' + token } : { 'content-type': 'application/json' }, + success: function (res) { + if (res.statusCode >= 200 && res.statusCode < 300) return resolve(res.data); + reject(new Error((res.data && res.data.detail) || '请求失败(' + res.statusCode + ')')); + }, + fail: reject + }); + }); +} + +function ensureLogin() { + var app = getApp(); + if (app.globalData.token || xhs.getStorageSync('pk_token')) return Promise.resolve(); + return new Promise(function (resolve, reject) { + xhs.login({ + success: function (loginResult) { + request('/api/v1/auth/xhs', { + method: 'POST', + data: { app_key: app.globalData.appKey, code: loginResult.code } + }).then(function (data) { + app.globalData.token = data.token; + xhs.setStorageSync('pk_token', data.token); + resolve(data); + }).catch(reject); + }, + fail: reject + }); + }); +} + +module.exports = { request: request, ensureLogin: ensureLogin }; + diff --git a/utils/bracket.js b/utils/bracket.js new file mode 100644 index 0000000..68be2fa --- /dev/null +++ b/utils/bracket.js @@ -0,0 +1,44 @@ +function create(candidates) { + return { + round: 1, + pool: candidates.slice(), + pairIndex: 0, + winners: [], + eliminated: [], + decisions: [] + }; +} + +function current(state) { + if (state.pool.length === 1) return null; + return [state.pool[state.pairIndex], state.pool[state.pairIndex + 1] || null]; +} + +function choose(state, winner) { + var pair = current(state); + if (!pair || !pair[1]) throw new Error('invalid bracket pair'); + var loser = pair[0].id === winner.id ? pair[1] : pair[0]; + state.winners.push(winner); + state.eliminated.unshift(loser); + state.decisions.push({ round: state.round, left_id: pair[0].id, right_id: pair[1].id, winner_id: winner.id }); + state.pairIndex += 2; + if (state.pairIndex < state.pool.length) { + if (!state.pool[state.pairIndex + 1]) { + state.winners.push(state.pool[state.pairIndex]); + state.pairIndex += 1; + } + if (state.pairIndex < state.pool.length) return false; + } + state.pool = state.winners; + state.winners = []; + state.pairIndex = 0; + state.round += 1; + return state.pool.length === 1; +} + +function ranking(state) { + return state.pool.concat(state.eliminated).map(function (item) { return item.id; }); +} + +module.exports = { create: create, current: current, choose: choose, ranking: ranking }; + diff --git a/web/app.js b/web/app.js new file mode 100644 index 0000000..b79d71b --- /dev/null +++ b/web/app.js @@ -0,0 +1,67 @@ +(function () { + 'use strict'; + var root = document.getElementById('app'); + var apiBase = (window.PK_CONFIG.apiBase || '').replace(/\/$/, ''); + var state = { tests: [], test: null, bracket: null, result: null, template: 'celebration', sticker: true }; + + function toast(message) { var el = document.getElementById('toast'); el.textContent = message; el.classList.add('show'); setTimeout(function () { el.classList.remove('show'); }, 2200); } + function escapeHtml(value) { return String(value).replace(/[&<>"']/g, function (char) { return ({'&':'&','<':'<','>':'>','"':'"',"'":'''})[char]; }); } + function request(path, options) { + options = options || {}; var token = localStorage.getItem('pk_token'); + var headers = {'Content-Type':'application/json'}; if (token) headers.Authorization = 'Bearer ' + token; + return fetch(apiBase + path, {method:options.method || 'GET',headers:headers,body:options.data ? JSON.stringify(options.data) : undefined}).then(function (response) { + return response.json().catch(function () { return {}; }).then(function (data) { if (!response.ok) throw new Error(data.detail || '请求失败'); return data; }); + }); + } + function ensureLogin() { + if (localStorage.getItem('pk_token')) return Promise.resolve(); + var id = localStorage.getItem('pk_preview_id') || (Date.now().toString(36) + Math.random().toString(36).slice(2)); localStorage.setItem('pk_preview_id', id); + return request('/api/v1/auth/xhs', {method:'POST',data:{app_key:'hub',code:'dev:web-' + id}}).then(function (data) { localStorage.setItem('pk_token', data.token); }); + } + function loadHome() { + root.innerHTML = '
正在摆好擂台…
'; + request('/api/v1/tests').then(function (tests) { state.tests = tests; renderHome(); }).catch(renderError); + } + function renderHome() { + root.innerHTML = '
TASTE LAB · PUBLIC PREVIEW

今天,认真选一个。

没有“都可以”。每轮只选一个,让你的偏爱一路赢到底。

全部测试

' + state.tests.length + ' 个题库
' + state.tests.map(function (test, index) { + return ''; + }).join('') + '
'; + root.querySelectorAll('.test-card').forEach(function (el) { el.addEventListener('click', function () { loadTest(el.dataset.slug); }); }); + } + function loadTest(slug) { root.innerHTML = '
正在抽签…
'; request('/api/v1/tests/' + slug).then(function (test) { state.test = test; state.bracket = {round:1,pool:test.candidates.slice(),index:0,winners:[],eliminated:[],decisions:[]}; renderPair(); }).catch(renderError); } + function pair() { return [state.bracket.pool[state.bracket.index], state.bracket.pool[state.bracket.index + 1] || null]; } + function renderPair() { + var items = pair(), done = state.bracket.decisions.length, total = state.test.candidates.length - 1; + root.innerHTML = '
第 ' + state.bracket.round + ' 轮' + done + ' / ' + total + '

此刻只能留一个,
你会选谁?

VS
'; + root.querySelectorAll('.choice').forEach(function (el) { el.addEventListener('click', function () { choose(items[Number(el.dataset.side)]); }); }); + } + function choose(winner) { + var b = state.bracket, items = pair(), loser = items[0].id === winner.id ? items[1] : items[0]; + b.winners.push(winner); b.eliminated.unshift(loser); b.decisions.push({round:b.round,left_id:items[0].id,right_id:items[1].id,winner_id:winner.id}); b.index += 2; + if (b.index < b.pool.length && !b.pool[b.index + 1]) { b.winners.push(b.pool[b.index]); b.index += 1; } + if (b.index >= b.pool.length) { b.pool = b.winners; b.winners = []; b.index = 0; b.round += 1; } + if (b.pool.length === 1) complete(); else renderPair(); + } + function complete() { + var b = state.bracket, champion = b.pool[0], final = b.decisions[b.decisions.length - 1], runner = final.left_id === champion.id ? final.right_id : final.left_id; + root.innerHTML = '
正在保存你的冠军…
'; + ensureLogin().then(function () { return request('/api/v1/tests/' + state.test.slug + '/runs',{method:'POST',data:{app_key:'hub',champion_id:champion.id,runner_up_id:runner,ranking_ids:b.pool.concat(b.eliminated).map(function(i){return i.id;}),decisions:b.decisions}}); }).then(function (result) { state.result = result; renderResult(); }).catch(renderError); + } + function renderResult() { + var r = state.result; + root.innerHTML = '
FINAL ANSWER · ' + escapeHtml(r.test_title) + '

' + escapeHtml(r.champion_name) + '

' + (r.runner_up_name ? '决赛击败 ' + escapeHtml(r.runner_up_name) : '一路赢到最后') + '

'; + drawPoster(); root.querySelectorAll('[data-theme]').forEach(function (el) { el.addEventListener('click', function () { state.template = el.dataset.theme; root.querySelectorAll('[data-theme]').forEach(function(x){x.classList.remove('active');});el.classList.add('active');drawPoster(); }); }); + document.getElementById('stickerToggle').addEventListener('click',function(){state.sticker=!state.sticker;this.textContent='手绘贴纸:'+(state.sticker?'开启':'关闭');drawPoster();}); + document.getElementById('savePoster').addEventListener('click',function(){var a=document.createElement('a');a.download='我的PK冠军-'+r.champion_name+'.png';a.href=document.getElementById('poster').toDataURL('image/png');a.click();toast('分享图已保存');}); + document.getElementById('replay').addEventListener('click',function(){loadTest(r.test_slug);}); + } + function drawPoster() { + var canvas=document.getElementById('poster'),ctx=canvas.getContext('2d'),r=state.result,themes={celebration:['#ff6b35','#fffaf4','#25211f','#ffe568'],editorial:['#f3eadf','#201d1b','#fff','#285ee8'],sticker:['#c9f06b','#1e2810','#ff72a7','#fff']},t=themes[state.template]; + ctx.fillStyle=t[0];ctx.fillRect(0,0,750,1000);ctx.fillStyle=t[1];ctx.font='700 24px system-ui';ctx.fillText('PK 研究所 / MY PICK',54,72);ctx.font='900 58px system-ui';ctx.fillText('我的冠军是',54,156);ctx.fillStyle=t[2];ctx.fillRect(46,205,658,440);ctx.fillStyle=state.template==='celebration'?'#fffaf4':t[1];ctx.font='600 26px system-ui';ctx.fillText(r.test_title,84,270);ctx.font='900 '+(r.champion_name.length>7?62:82)+'px system-ui';ctx.fillText(r.champion_name,84,405);ctx.fillStyle=t[3];ctx.fillRect(84,440,Math.min(500,r.champion_name.length*80),18);ctx.fillStyle=state.template==='celebration'?'#fffaf4':t[1];ctx.font='24px system-ui';ctx.fillText('一路二选一,它赢到了最后。',84,525);ctx.fillStyle=t[1];ctx.font='700 25px system-ui';ctx.fillText('我的 TOP 4',54,720);(r.ranking_names||[]).slice(0,4).forEach(function(name,i){ctx.font='26px system-ui';ctx.fillText((i+1)+'. '+name,64,774+i*48);});if(state.sticker){ctx.fillStyle=t[3];ctx.beginPath();ctx.arc(645,125,58,0,Math.PI*2);ctx.fill();ctx.fillStyle=t[2];ctx.font='900 28px system-ui';ctx.fillText('WIN!',607,134);ctx.font='52px system-ui';ctx.fillText('✦',640,700);ctx.fillText('♡',550,900);}ctx.fillStyle=t[1];ctx.font='20px system-ui';ctx.fillText('保存这张图,把答案分享给同频的人',54,956); + } + function loadHistory() { root.innerHTML='
正在翻档案…
';ensureLogin().then(function(){return request('/api/v1/me/results');}).then(renderHistory).catch(renderError); } + function renderHistory(results) { root.innerHTML='
MY TASTE ARCHIVE

我的偏爱档案

每一次纠结,都算数。

做过的测试

'+results.length+' 条结果
'+(results.length?results.map(function(r,i){return '';}).join(''):'
还没有结果,去选第一个冠军吧。
')+'
';document.getElementById('linkCode').addEventListener('click',function(){request('/api/v1/me/link-code',{method:'POST'}).then(function(d){document.getElementById('code').textContent=d.code;}).catch(renderError);});root.querySelectorAll('.result-row').forEach(function(el){el.addEventListener('click',function(){state.result=results[Number(el.dataset.i)];renderResult();});}); } + function renderError(error) { root.innerHTML='

暂时没接上服务

'+escapeHtml(error.message||'未知错误')+'

';document.getElementById('retry').addEventListener('click',loadHome); } + document.getElementById('homeButton').addEventListener('click',loadHome); document.getElementById('meButton').addEventListener('click',loadHistory); loadHome(); +}()); + diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..ec3539e --- /dev/null +++ b/web/index.html @@ -0,0 +1,18 @@ + + + + + + + PK 研究所 · 公网预览 + + + + +
+
+ + + + + diff --git a/web/runtime-env.js b/web/runtime-env.js new file mode 100644 index 0000000..757f135 --- /dev/null +++ b/web/runtime-env.js @@ -0,0 +1,2 @@ +window.PK_CONFIG = { apiBase: '${API_BASE_URL}' }; + diff --git a/web/style.css b/web/style.css new file mode 100644 index 0000000..725f003 --- /dev/null +++ b/web/style.css @@ -0,0 +1,2 @@ +:root{--paper:#fff8f2;--ink:#201d1b;--orange:#ff6b35;--blue:#2766df;--muted:#887d75;--line:#e8ddd5}*{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--ink);font-family:Inter,ui-sans-serif,system-ui,-apple-system,"PingFang SC",sans-serif}.nav{position:sticky;top:0;z-index:20;display:flex;justify-content:space-between;align-items:center;padding:18px max(24px,calc((100vw - 1180px)/2));background:rgba(255,248,242,.92);border-bottom:1px solid rgba(50,30,20,.08);backdrop-filter:blur(15px)}button{font:inherit;border:0;cursor:pointer}.brand{padding:0;background:none;font-weight:950;letter-spacing:2px}.brand i{color:var(--orange)}.nav-pill,.button{padding:12px 20px;border-radius:99px;background:var(--ink);color:white;font-weight:800}.shell{width:min(1180px,calc(100% - 36px));margin:34px auto 80px}.hero{position:relative;overflow:hidden;min-height:330px;padding:54px;border-radius:38px;background:var(--orange);color:white;box-shadow:0 24px 70px rgba(162,61,23,.18)}.hero:after{content:"↗";position:absolute;right:40px;bottom:-54px;font-size:260px;font-weight:900;opacity:.12;transform:rotate(-12deg)}.eyebrow{font-size:12px;letter-spacing:5px;opacity:.75}.hero h1{max-width:700px;margin:22px 0 24px;font-size:clamp(46px,7vw,92px);line-height:.98;letter-spacing:-.06em}.hero p{max-width:550px;font-size:18px;line-height:1.65}.section-head{display:flex;justify-content:space-between;align-items:end;margin:55px 5px 20px}.section-head h2{margin:0;font-size:28px}.muted{color:var(--muted)}.grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:22px;align-items:start}.test-card{overflow:hidden;padding:0;text-align:left;border-radius:28px;background:white;box-shadow:0 12px 40px rgba(60,35,20,.08);transition:.2s}.test-card:hover{transform:translateY(-6px) rotate(-.5deg);box-shadow:0 20px 50px rgba(60,35,20,.14)}.test-card:nth-child(3n+2) .art{height:270px}.art{position:relative;height:220px;display:grid;place-items:center;color:white}.art .emoji{font-size:92px;filter:drop-shadow(0 8px 8px rgba(0,0,0,.12));transform:rotate(-8deg)}.art small{position:absolute;top:20px;left:22px;font-weight:900;opacity:.8}.card-body{padding:25px}.card-body h3{margin:0;font-size:24px}.card-body p{min-height:48px;color:#756a62;line-height:1.5}.meta{display:flex;justify-content:space-between;color:#958981;font-size:13px}.loading,.empty{padding:100px 20px;text-align:center;color:var(--muted)}.arena{max-width:900px}.arena-top{display:flex;justify-content:space-between}.progress{height:9px;margin:17px 0 48px;border-radius:99px;background:#e9ded6;overflow:hidden}.progress span{display:block;height:100%;background:var(--orange);transition:width .25s}.arena h1{font-size:clamp(40px,6vw,72px);line-height:1.08}.pair{position:relative;display:grid;grid-template-columns:1fr 1fr;gap:24px}.choice{position:relative;min-height:400px;padding:40px;text-align:left;border-radius:36px;color:white;box-shadow:0 20px 50px rgba(80,35,18,.13);transition:.15s}.choice:hover{transform:scale(1.015)}.choice:first-child{background:var(--orange)}.choice:last-child{background:var(--blue)}.choice-letter{display:grid;width:52px;height:52px;place-items:center;border:2px solid rgba(255,255,255,.6);border-radius:50%;font-weight:900}.choice-emoji{position:absolute;right:30px;top:20px;font-size:86px;opacity:.8}.choice-name{display:block;margin-top:85px;font-size:clamp(39px,5vw,66px);font-weight:950;line-height:1.06}.choice-hint{position:absolute;bottom:32px;left:40px;opacity:.72}.vs{position:absolute;z-index:2;left:50%;top:50%;display:grid;width:76px;height:76px;place-items:center;transform:translate(-50%,-50%) rotate(-9deg);border:5px solid var(--ink);border-radius:50%;background:white;font-weight:950}.result-shell{max-width:1040px}.champion-panel{padding:55px;text-align:center;border-radius:38px;background:var(--ink);color:white}.champion-panel small{opacity:.6}.champion-panel h1{margin:18px 0 8px;font-size:clamp(55px,9vw,105px);letter-spacing:-.06em}.result-layout{display:grid;grid-template-columns:minmax(0,1fr) 330px;gap:30px;margin-top:35px}.poster{width:100%;border-radius:28px;box-shadow:0 18px 55px rgba(50,30,20,.15)}.control{padding:28px;border-radius:28px;background:white}.control h2{margin-top:0}.theme{display:block;width:100%;margin:10px 0;padding:16px;text-align:left;border:2px solid var(--line);border-radius:18px;background:white;font-weight:800}.theme.active{border-color:var(--ink);background:var(--ink);color:white}.wide{width:100%;margin-top:16px}.outline{background:white;color:var(--ink);border:2px solid var(--line)}.history{max-width:850px}.link-box{padding:28px;border-radius:28px;background:#f7e9ff}.link-code{margin:20px 0 0;font-size:42px;letter-spacing:10px;font-weight:950}.result-row{display:flex;align-items:center;gap:18px;width:100%;margin:12px 0;padding:22px;text-align:left;border-radius:24px;background:white;box-shadow:0 8px 28px rgba(50,30,20,.07)}.medal{display:grid;width:60px;height:60px;place-items:center;border-radius:18px;background:var(--orange);color:white;font-weight:950}.result-row strong{display:block;font-size:24px}.result-row span:last-child{margin-left:auto}.toast{position:fixed;z-index:50;left:50%;bottom:30px;padding:14px 22px;transform:translate(-50%,30px);border-radius:99px;background:var(--ink);color:white;opacity:0;pointer-events:none;transition:.2s}.toast.show{opacity:1;transform:translate(-50%,0)}@media(max-width:800px){.grid{grid-template-columns:repeat(2,minmax(0,1fr))}.hero{padding:38px 30px}.pair,.result-layout{grid-template-columns:1fr}.choice{min-height:300px}.vs{top:50%}.result-layout{gap:20px}}@media(max-width:520px){.grid{gap:14px}.art{height:160px}.test-card:nth-child(3n+2) .art{height:200px}.art .emoji{font-size:66px}.card-body{padding:18px}.card-body h3{font-size:19px}.card-body p{font-size:14px}.meta{font-size:11px}.pair{gap:16px}.choice{padding:24px;min-height:250px}.choice-name{margin-top:52px}.choice-hint{left:24px;bottom:22px}.choice-emoji{font-size:60px}.vs{width:60px;height:60px}.champion-panel{padding:38px 25px}.result-shell{width:min(100% - 24px,1180px)}} +