Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions scripts/runtime-files.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const groups = {
"app.mjs",
"core.mjs",
"data.mjs",
"feedback-prediction-ui.mjs",
"feedback-story-ui.mjs",
"feedback-story.css",
"feedback-story.mjs",
Expand Down
45 changes: 29 additions & 16 deletions src/experiments/recommendation/app.mjs
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
import {POSTS,TOPICS,PRESETS,INITIAL_PROFILE} from './data.mjs?v=cat-feedback-v1';
import {rankPosts,metrics,feedback,challenge,experiment} from './core.mjs?v=cat-feedback-v1';
import {captureFeedback} from './feedback-story.mjs?v=cat-feedback-v1';
import {mountFeedbackStory} from './feedback-story-ui.mjs?v=cat-feedback-v1';
import {mountSeatLesson} from './seat-lesson-ui.mjs?v=cat-feedback-v1';
import {renderRecommendationCard} from './recommendation-cards.mjs?v=cat-feedback-v1';
import {POSTS,TOPICS,PRESETS,INITIAL_PROFILE} from './data.mjs?v=feedback-prediction-v1';
import {rankPosts,metrics,feedback,challenge,experiment} from './core.mjs?v=feedback-prediction-v1';
import {captureFeedback} from './feedback-story.mjs?v=feedback-prediction-v1';
import {mountFeedbackStory} from './feedback-story-ui.mjs?v=feedback-prediction-v1';
import {mountSeatLesson} from './seat-lesson-ui.mjs?v=feedback-prediction-v1';
import {renderRecommendationCard} from './recommendation-cards.mjs?v=feedback-prediction-v1';
import {mountFeedbackPrediction} from './feedback-prediction-ui.mjs?v=feedback-prediction-v1';

const $=id=>document.getElementById(id);
const feedbackStory=mountFeedbackStory({document});
let weights={...PRESETS.click.weights},baseline={...PRESETS.click.weights},profile={...INITIAL_PROFILE};
const seatLesson=mountSeatLesson({document,getInputs:()=>({posts:POSTS,weights,profile})});
let completed=null,runCount=0,toastTimer;
const feedbackPrediction=mountFeedbackPrediction({document,getInputs:()=>({posts:POSTS,weights,profile}),
applyFeedback:evidence=>applyPostFeedback(evidence.action.post.id,evidence.action.direction,{evidence,guided:true}),
returnToCard:({postId,direction})=>focusFeedback(postId,direction),
reducedMotion:()=>matchMedia('(prefers-reduced-motion:reduce)').matches});
const keyOrder=['click','diversity','newcomer'];
const same=(a,b)=>keyOrder.every(k=>a[k]===b[k]);
const strategy=w=>Object.values(PRESETS).find(p=>same(p.weights,w))?.name||'你的自定义规则';
Expand All @@ -36,7 +41,7 @@ function render(){
$('challenge-checks').innerHTML=[[goal.click,'预测点击率 ≥ 40%'],[goal.diversity,'至少 4 种主题'],[goal.newcomer,'至少 2 个新人席位']].map(([ok,label])=>`<li class="${ok?'done':''}"><span class="check-icon" aria-hidden="true">${ok?'✓':''}</span>${label}<span class="sr-only">${ok?',已达成':',未达成'}</span></li>`).join('');
$('challenge-status').textContent=goal.won?'挑战达成!再跑一轮,看看代价。':'还差一点,试着调调看。';$('challenge-status').classList.toggle('won',goal.won);
$('taste-bars').innerHTML=Object.entries(TOPICS).map(([key,topic])=>`<div class="taste-item" title="${topic.short}兴趣 ${Math.round(profile[key]*100)}"><div class="taste-track"><div class="taste-fill" style="width:${profile[key]*100}%"></div></div><span>${topic.short} ${Math.round(profile[key]*100)}</span></div>`).join('');
$('baseline-caption').textContent=`对照组:${strategy(baseline)}`;renderComparison();feedbackStory.sync(weights,profile);seatLesson.sync();return m;
$('baseline-caption').textContent=`对照组:${strategy(baseline)}`;renderComparison();feedbackStory.sync(weights,profile);seatLesson.sync();feedbackPrediction.sync();return m;
}

function renderComparison(){
Expand All @@ -55,18 +60,25 @@ function renderComparison(){
function changeWeights(next){weights={...next};const m=render();announce(`首页已更新:${m.topics} 种主题,${m.newcomers} 个新人席位,预测点击率 ${pct(m.ctr)}%。`);}
document.querySelectorAll('[data-preset]').forEach(button=>button.addEventListener('click',()=>changeWeights(PRESETS[button.dataset.preset].weights)));
for(const key of keyOrder) $(key).addEventListener('input',event=>changeWeights({...weights,[key]:Number(event.target.value)}));
$('feed').addEventListener('click',event=>{
const button=event.target.closest('[data-feedback]');if(!button)return;
const post=POSTS.find(p=>p.id===button.dataset.post),direction=Number(button.dataset.feedback);
const evidence=feedbackStory.shouldRecord()?captureFeedback(POSTS,weights,profile,post.id,direction):null;
function focusFeedback(postId,direction,slot=0){
const retained=[...$('feed').querySelectorAll('[data-feedback]')].find(b=>b.dataset.post===postId&&Number(b.dataset.feedback)===direction);
(retained||$('feed').children[Math.max(0,slot)]?.querySelector(`[data-feedback="${direction}"]`))?.focus({preventScroll:true});
}
function applyPostFeedback(postId,direction,{evidence=null,guided=false}={}){
const post=POSTS.find(p=>p.id===postId),recording=feedbackStory.shouldRecord();
evidence=evidence||(recording?captureFeedback(POSTS,weights,profile,post.id,direction):null);
const slot=[...$('feed').children].findIndex(card=>card.dataset.id===post.id);
const before=profile[post.topic];profile=feedback(profile,post.topic,direction);
const note=before===profile[post.topic]?`${TOPICS[post.topic].short}兴趣已${direction>0?'达到上限':'降到下限'}。`:`${direction>0?'多看一点':'少看一点'}${TOPICS[post.topic].short},首页已重新排序。`;
const slot=[...$('feed').children].indexOf(button.closest('.post-card'));
if(evidence)feedbackStory.record(evidence);
render();$('feedback-note').textContent=note;announce(note+(evidence?' 已保留反馈前后对照,可通过首页上方链接查看。':''));toast(note);
if(recording&&evidence)feedbackStory.record(evidence);
render();$('feedback-note').textContent=note;announce(note+(recording&&evidence?' 已保留反馈前后对照,可通过首页上方链接查看。':''));toast(note);
// Reranking replaces cards; keep keyboard focus on the same action when possible.
const retained=[...$('feed').querySelectorAll('[data-feedback]')].find(b=>b.dataset.post===post.id&&Number(b.dataset.feedback)===direction);
(retained||$('feed').children[Math.max(0,slot)]?.querySelector(`[data-feedback="${direction}"]`))?.focus({preventScroll:true});
if(!guided)focusFeedback(post.id,direction,slot);
}
$('feed').addEventListener('click',event=>{
const button=event.target.closest('[data-feedback]');if(!button)return;
const postId=button.dataset.post,direction=Number(button.dataset.feedback);
if(!feedbackPrediction.request(postId,direction))applyPostFeedback(postId,direction);
});
$('run').addEventListener('click',()=>{
completed={result:experiment(POSTS,weights,baseline,profile),number:++runCount};
Expand All @@ -80,6 +92,7 @@ const emptyComparison=$('comparison-result').innerHTML;
$('reset').addEventListener('click',()=>{
weights={...PRESETS.click.weights};baseline={...PRESETS.click.weights};profile={...INITIAL_PROFILE};completed=null;runCount=0;
feedbackStory.reset();
feedbackPrediction.reset();
seatLesson.reset();
$('comparison-result').innerHTML=emptyComparison;$('run-number').textContent='未运行';$('feedback-note').textContent='试试卡片上的「喜欢」和「少一点」。';
$('feed').innerHTML='';render();toast('已回到实验起点');announce('全部规则、口味和实验记录已重置。');
Expand Down
98 changes: 98 additions & 0 deletions src/experiments/recommendation/feedback-prediction-ui.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import {TOPICS} from './data.mjs?v=feedback-prediction-v1';
import {captureFeedback,recordMatches} from './feedback-story.mjs?v=feedback-prediction-v1';
import {escapeCardText as escape,recommendationTitle as title,recommendationArt as art,recommendationCharacter as character} from './recommendation-cards.mjs?v=feedback-prediction-v1';

const percent=value=>Math.round(value*100);
const position=rank=>rank===null?'六席外':`第 ${rank} 位`;
const answer=choice=>choice==='stays'?'仍在首页六席':'离开首页六席';

// This optional layer defers an existing feedback action. It does not change the
// scorer, profile persistence, or the separate, user-pinned feedback story.
export function mountFeedbackPrediction({document,getInputs,applyFeedback,returnToCard=()=>{},reducedMotion=()=>false}){
const $=name=>document.getElementById(`feedback-prediction-${name}`);
let enabled=false,pending=null,choice=null,completed=null;
const status=text=>{$('status').textContent=text;};
function moveTo(name){
$(name).focus({preventScroll:true});
$('panel').scrollIntoView({behavior:reducedMotion()?'instant':'smooth',block:'nearest'});
}
function hideChoices(){
$('choices').hidden=true;$('apply').disabled=true;
for(const key of ['stays','leaves'])$(key).setAttribute('aria-pressed','false');
}
function cancel(message,{restoreFocus=false}={}){
const action=pending?.action;pending=null;choice=null;hideChoices();
$('panel').hidden=true;status(message);
if(action&&restoreFocus)returnToCard({postId:action.post.id,direction:action.direction});
}
function pendingMatches(){
if(!pending)return false;
const {weights,profile}=getInputs();
return recordMatches({...pending,after:pending.before},weights,profile);
}
function sync(){
if(pending&&!pendingMatches())cancel('规则或口味变了,这次猜测已取消,未发送反馈。请重新选一张卡。');
if(completed){
const {weights,profile}=getInputs();
$('result-state').textContent=recordMatches(completed,weights,profile)
?'本次反馈结果 · 规则未改'
:'保留上次反馈结果 · 当前口味或规则已改变';
}
}
function request(postId,direction){
if(!enabled)return false;
const {posts,weights,profile}=getInputs();
pending=captureFeedback(posts,weights,profile,postId,direction);choice=null;completed=null;
const {post,beforeRank}=pending.action,topic=TOPICS[post.topic],name=character(post);
$('card').innerHTML=`<span class="feedback-prediction-art" style="--topic:${topic.color}" aria-hidden="true">${art(post)||topic.glyph}</span><div><strong>${escape(title(post))}</strong><span>${name?`出镜:${escape(name)} · `:''}${escape(topic.short)} · 反馈前${position(beforeRank)}</span></div>`;
$('title').textContent=`点「${direction>0?'喜欢':'少一点'}」后,这张卡还会在首页吗?`;
$('panel').hidden=false;$('result').hidden=true;hideChoices();$('choices').hidden=false;
status('先猜去留,再检验;这次反馈还没发送,首页和口味都没变。');
moveTo('title');return true;
}
function choose(value){
if(!pending)return;
if(!pendingMatches()){sync();return;}
choice=value;
for(const key of ['stays','leaves'])$(key).setAttribute('aria-pressed',String(key===choice));
$('apply').disabled=false;status(`你猜「${answer(choice)}」。还没发送反馈,点「检验这次反馈」看实际结果。`);
}
function reveal(){
if(!pending||!choice)return;
if(!pendingMatches()){sync();return;}
const evidence=pending,guess=choice;
// Consume before rendering/applying: repeated clicks cannot send it twice.
pending=null;choice=null;hideChoices();
applyFeedback(evidence);completed=evidence;
const {action:a,before,after,effect}=evidence,topic=TOPICS[a.post.topic].short;
$('result').hidden=false;
$('verdict').textContent=`你猜:${answer(guess)}。实际:${a.afterRank===null?'离开首页六席':`仍在首页,第 ${a.afterRank} 位`}。`;
$('position').textContent=`${position(a.beforeRank)} → ${position(a.afterRank)}`;
$('interest-label').textContent=`${topic}兴趣`;
$('interest').textContent=`${percent(before.profile[a.post.topic])} → ${percent(after.profile[a.post.topic])}`;
const cause=effect==='limit'
?`${topic}兴趣已到${a.direction>0?'上限':'下限'},这次没有变化,首页也没变。`
:effect==='unweighted'
?'兴趣变了,但「点击优先」是 0,口味不参与排序,所以首页没变。'
:`反馈调整的是「${topic}」主题兴趣,不是屏蔽某张卡;兴趣变了,也不保证它离开首页。`;
$('reason').textContent=`${cause}三项规则没变。${a.afterRank===null?'这张卡仍在候选池里,没有被屏蔽。':''}`;
$('title').textContent='这张卡,真的离开了吗?';
sync();status('已发送一次反馈。你的猜测和真实结果就在下方;可继续选别的卡。');moveTo('result-state');
}
$('mode').addEventListener('click',()=>{
enabled=!enabled;$('mode').setAttribute('aria-pressed',String(enabled));
$('mode').textContent=enabled?'退出猜测模式':'先猜再反馈';
if(!enabled&&pending)cancel('已退出猜测模式;刚才的反馈没有发送。现在点卡片可直接反馈。',{restoreFocus:true});
else status(enabled?'已开启:选一张卡,点「喜欢」或「少一点」,先猜它的去留。':'已恢复直接反馈;点卡片就会更新首页。');
});
$('stays').addEventListener('click',()=>choose('stays'));
$('leaves').addEventListener('click',()=>choose('leaves'));
$('apply').addEventListener('click',reveal);
$('cancel').addEventListener('click',()=>cancel('已取消,这次没有发送反馈;首页和口味没变。',{restoreFocus:true}));
function reset(){
enabled=false;pending=null;choice=null;completed=null;hideChoices();
$('panel').hidden=true;$('result').hidden=true;$('mode').setAttribute('aria-pressed','false');$('mode').textContent='先猜再反馈';
status('可选小挑战:先开启,再点一张卡的反馈。不开启也能照常玩。');
}
reset();return {request,sync,reset};
}
6 changes: 3 additions & 3 deletions src/experiments/recommendation/feedback-story-ui.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {TOPICS} from './data.mjs?v=cat-feedback-v1';
import {recordMatches} from './feedback-story.mjs?v=cat-feedback-v1';
import {escapeCardText as escape,recommendationTitle as title,recommendationArt as art,recommendationCharacter as character} from './recommendation-cards.mjs?v=cat-feedback-v1';
import {TOPICS} from './data.mjs?v=feedback-prediction-v1';
import {recordMatches} from './feedback-story.mjs?v=feedback-prediction-v1';
import {escapeCardText as escape,recommendationTitle as title,recommendationArt as art,recommendationCharacter as character} from './recommendation-cards.mjs?v=feedback-prediction-v1';

const interest=value=>Math.round(value*100);
const cast=post=>{const name=character(post);return name?`<span class="feedback-cast">出镜:${escape(name)}</span>`:'';};
Expand Down
23 changes: 23 additions & 0 deletions src/experiments/recommendation/feedback-story.css

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/experiments/recommendation/feedback-story.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {feedback,rankPosts,scorePost,probability,metrics} from './core.mjs?v=cat-feedback-v1';
import {feedback,rankPosts,scorePost,probability,metrics} from './core.mjs?v=feedback-prediction-v1';

function freeze(value){
if(value&&typeof value==='object'){
Expand Down
4 changes: 2 additions & 2 deletions src/experiments/recommendation/recommendation-cards.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {TOPICS} from './data.mjs?v=cat-feedback-v1';
import {probability} from './core.mjs?v=cat-feedback-v1';
import {TOPICS} from './data.mjs?v=feedback-prediction-v1';
import {probability} from './core.mjs?v=feedback-prediction-v1';

// Display-only remapping. The same post IDs and original data still go to the scorer.
const studioPosts={
Expand Down
Loading
Loading