steveyehtw commited on
Commit
dcab2e7
·
1 Parent(s): 2484080

Improve classroom lesson guidance and submission flow

Browse files
README.md CHANGED
@@ -27,6 +27,9 @@ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-
27
  - 班級與學生名單會寫回 Space repository 長期保存;尚未發布的草稿仍保存在 Space 執行期間。
28
  - 內容管理後台的「管理教室」可新增、改名或刪除班級,管理學生名單,並查看或刪除已提交內容。
29
  - 下課前可在「管理教室」按「備份 Lesson 提交」,將目前 Lesson 的正式版寫回 Space repository,避免重新建置後遺失。
 
 
 
30
  - 學生端 Python 會逐段顯示輸出;程式執行到 `input()` 時,Console 才出現輸入列並等待送出。
31
  - 內容管理後台可修改 Lesson 路線與各 Lesson 套版,也可新增、改名、編輯或刪除公開 Demo 專題。所有儲存都會寫回此 Space。
32
 
 
27
  - 班級與學生名單會寫回 Space repository 長期保存;尚未發布的草稿仍保存在 Space 執行期間。
28
  - 內容管理後台的「管理教室」可新增、改名或刪除班級,管理學生名單,並查看或刪除已提交內容。
29
  - 下課前可在「管理教室」按「備份 Lesson 提交」,將目前 Lesson 的正式版寫回 Space repository,避免重新建置後遺失。
30
+ - 學生端的保存分三層:「自動同步」更新師生即時可見的工作草稿,但不增加歷史版本;「暫存版本」建立可從舊進度載回的檢查點;「正式提交」凍結一份供老師檢查、整班下載或另行發布的版本。發布只採用正式提交,不會包含暫存。
31
+ - 教師個別學生畫面可切換查看目前草稿與最近的正式提交;學生繼續編輯後,草稿會變動,已提交版本保持不變。
32
+ - 學生成功呼叫老師後有 5 分鐘冷卻,伺服器會檢查;取消求助或老師標記已回應都不會重置計時。冷卻按同一班級與學生計算,跨 Lesson 共用。
33
  - 學生端 Python 會逐段顯示輸出;程式執行到 `input()` 時,Console 才出現輸入列並等待送出。
34
  - 內容管理後台可修改 Lesson 路線與各 Lesson 套版,也可新增、改名、編輯或刪除公開 Demo 專題。所有儲存都會寫回此 Space。
35
 
classroom_service.py CHANGED
@@ -18,6 +18,7 @@ SUBMISSIONS_PER_HOUR=max(1, int(os.getenv("CLASSROOM_SUBMISSIONS_PER_HOUR", "20"
18
  # Bundled syntax repairs target work saved before 2026-10-04 00:00 Asia/Taipei.
19
  LEGACY_REPAIR_CUTOFF_MS=1791043200000
20
  VERSION_WRITE_COOLDOWN_MS=max(0, int(os.getenv("CLASSROOM_VERSION_COOLDOWN_MS", "1500")))
 
21
  STUDENT_WS_CONNECTIONS_PER_MINUTE=max(10, int(os.getenv("CLASSROOM_WS_CONNECTIONS_PER_MINUTE", "300")))
22
  STUDENT_WS_MESSAGES_PER_MINUTE=max(60, int(os.getenv("CLASSROOM_WS_MESSAGES_PER_MINUTE", "300")))
23
  ALLOWED={".py",".json",".txt",".csv",".md",".toml",".yaml",".yml"}; ID_RE=re.compile(r"[^0-9A-Za-z_\-一-鿿]")
@@ -85,11 +86,13 @@ def init_db():
85
  columns={row[1] for row in c.execute("PRAGMA table_info(classroom_projects)")}
86
  if "checkpoint_files" not in columns:c.execute("ALTER TABLE classroom_projects ADD COLUMN checkpoint_files TEXT")
87
  if "checkpoint_at" not in columns:c.execute("ALTER TABLE classroom_projects ADD COLUMN checkpoint_at INTEGER")
 
88
  c.execute("""CREATE TABLE IF NOT EXISTS classroom_courses(class_code TEXT PRIMARY KEY,course_name TEXT,created_at INTEGER)""")
89
  c.execute("""CREATE TABLE IF NOT EXISTS classroom_members(class_code TEXT,student_id TEXT,display_name TEXT,created_at INTEGER,PRIMARY KEY(class_code,student_id))""")
90
  c.execute("""CREATE TABLE IF NOT EXISTS classroom_versions(class_code TEXT,student_id TEXT,display_name TEXT,week_id TEXT,version_id TEXT,kind TEXT,project_name TEXT,files TEXT,created_at INTEGER,PRIMARY KEY(class_code,student_id,week_id,version_id))""")
91
  c.execute("""CREATE TABLE IF NOT EXISTS classroom_migrations(migration_id TEXT PRIMARY KEY,applied_at INTEGER)""")
92
  c.execute("""CREATE TABLE IF NOT EXISTS classroom_write_windows(class_code TEXT,student_id TEXT,week_id TEXT,kind TEXT,window_started INTEGER,write_count INTEGER,last_write INTEGER,PRIMARY KEY(class_code,student_id,week_id,kind))""")
 
93
  for item in json.loads((DATA/"classes.json").read_text(encoding="utf-8")):
94
  code=clean(item.get("code"),"L6A")
95
  c.execute("""INSERT INTO classroom_courses VALUES(?,?,?) ON CONFLICT(class_code) DO UPDATE SET course_name=excluded.course_name""",(code,clean_label(item.get("name"),code),now()))
@@ -173,18 +176,34 @@ def init_db():
173
  WHERE classroom_members.class_code=classroom_versions.class_code
174
  AND classroom_members.student_id=classroom_versions.student_id
175
  )""")
176
- def empty(c,s,n,w): return {"class_code":c,"student_id":s,"display_name":n,"week_id":w,"project_name":"","files":{"main.py":"# 在這裡寫 Python\n"},"final_files":None,"checkpoint_files":None,"active_file":"main.py","output":"","status":"idle","needs_help":False,"updated_at":now(),"submitted_at":None,"checkpoint_at":None,"connected":True}
177
- def from_row(r,connected=False): return {"class_code":r[0],"student_id":r[1],"display_name":r[2],"week_id":r[3],"project_name":r[4],"files":json.loads(r[5]),"final_files":json.loads(r[6]) if r[6] else None,"active_file":r[7],"output":r[8],"status":r[9],"needs_help":bool(r[10]),"updated_at":r[11],"submitted_at":r[12],"checkpoint_files":json.loads(r[13]) if r[13] else None,"checkpoint_at":r[14],"connected":connected}
178
- SELECT="SELECT class_code,student_id,display_name,week_id,project_name,draft_files,final_files,active_file,output,status,needs_help,updated_at,submitted_at,checkpoint_files,checkpoint_at FROM classroom_projects"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  def load(c,s,n,w):
180
  with lock,sqlite3.connect(DB) as db:r=db.execute(SELECT+" WHERE class_code=? AND student_id=? AND week_id=?",(c,s,w)).fetchone()
181
- state=from_row(r,True) if r else empty(c,s,n,w); state["display_name"]=n; return state
182
  def save(x):
183
- values=(x["class_code"],x["student_id"],x["display_name"],x["week_id"],x["project_name"],json.dumps(x["files"],ensure_ascii=False),json.dumps(x["final_files"],ensure_ascii=False) if x["final_files"] else None,x["active_file"],x["output"][-40000:],x["status"],int(x["needs_help"]),x["updated_at"],x["submitted_at"],json.dumps(x["checkpoint_files"],ensure_ascii=False) if x.get("checkpoint_files") else None,x.get("checkpoint_at"))
184
  with lock,sqlite3.connect(DB) as db:
185
  db.execute("INSERT OR IGNORE INTO classroom_courses VALUES(?,?,?)",(x["class_code"],x["class_code"],now()))
186
  db.execute("""INSERT INTO classroom_members VALUES(?,?,?,?) ON CONFLICT(class_code,student_id) DO UPDATE SET display_name=excluded.display_name""",(x["class_code"],x["student_id"],x["display_name"],now()))
187
- db.execute("""INSERT INTO classroom_projects(class_code,student_id,display_name,week_id,project_name,draft_files,final_files,active_file,output,status,needs_help,updated_at,submitted_at,checkpoint_files,checkpoint_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(class_code,student_id,week_id) DO UPDATE SET display_name=excluded.display_name,project_name=excluded.project_name,draft_files=excluded.draft_files,final_files=excluded.final_files,active_file=excluded.active_file,output=excluded.output,status=excluded.status,needs_help=excluded.needs_help,updated_at=excluded.updated_at,submitted_at=excluded.submitted_at,checkpoint_files=excluded.checkpoint_files,checkpoint_at=excluded.checkpoint_at""",values)
188
  def catalog():
189
  with lock,sqlite3.connect(DB) as db:
190
  courses=db.execute("SELECT class_code,course_name FROM classroom_courses ORDER BY course_name,class_code").fetchall()
@@ -395,7 +414,7 @@ async def delete_class(req:CourseDelete):
395
  check_password(req.password);code=clean(req.class_code,"");deletions=archived_paths(code)
396
  with lock,sqlite3.connect(DB) as db:
397
  if not db.execute("SELECT 1 FROM classroom_courses WHERE class_code=?",(code,)).fetchone():raise HTTPException(404,"找不到這個班級")
398
- db.execute("DELETE FROM classroom_versions WHERE class_code=?",(code,));db.execute("DELETE FROM classroom_projects WHERE class_code=?",(code,));db.execute("DELETE FROM classroom_members WHERE class_code=?",(code,));db.execute("DELETE FROM classroom_courses WHERE class_code=?",(code,))
399
  for key,ws in list(students.items()):
400
  if key[0]==code:
401
  students.pop(key,None);live.pop(key,None)
@@ -456,6 +475,7 @@ async def delete_student(req:StudentDelete):
456
  db.execute("DELETE FROM classroom_versions WHERE class_code=? AND student_id=?",(code,student_id))
457
  db.execute("DELETE FROM classroom_projects WHERE class_code=? AND student_id=?",(code,student_id))
458
  db.execute("DELETE FROM classroom_members WHERE class_code=? AND student_id=?",(code,student_id))
 
459
  warning=persist_catalog(f"Remove classroom student {student_id} from {code}",deletions)
460
  for class_code,week_id in list(teachers):
461
  if class_code==code:await broadcast(code,week_id)
@@ -513,24 +533,35 @@ async def student_ws(ws:WebSocket):
513
  state["files"]=norm_files(m.get("files"));state["project_name"]=clean_label(m.get("project_name"),"");active=safe_path(m.get("active_file","main.py"));state["active_file"]=active if active in state["files"] else "main.py";state["updated_at"]=now()
514
  elif kind=="output":state["output"]=str(m.get("output",""))[-40000:]
515
  elif kind=="status":state["status"]=m.get("status") if m.get("status") in {"idle","running","success","error"} else "idle"
516
- elif kind=="help":state["needs_help"]=bool(m.get("needs_help"))
 
 
 
 
 
 
 
 
 
 
 
517
  elif kind=="checkpoint":
518
  try:
519
  consume_version_write(c,s,w,"checkpoint")
520
  state["files"]=norm_files(m.get("files",state["files"]));state["project_name"]=clean_label(m.get("project_name",state["project_name"]),"");state["checkpoint_files"]=dict(state["files"]);state["checkpoint_at"]=now();state["updated_at"]=state["checkpoint_at"];version=record_version(state,"checkpoint")
521
  except VersionLimitError as exc:
522
- await ws.send_json({"type":"write_rejected","message":str(exc)});continue
523
  elif kind=="submit":
524
  try:
525
  consume_version_write(c,s,w,"submit")
526
  state["files"]=norm_files(m.get("files",state["files"]));state["project_name"]=clean_label(m.get("project_name",state["project_name"]),"");state["final_files"]=dict(state["files"]);state["submitted_at"]=now();state["updated_at"]=state["submitted_at"];version=record_version(state,"submit")
527
  except VersionLimitError as exc:
528
- await ws.send_json({"type":"write_rejected","message":str(exc)});continue
529
- elif kind=="ping":await ws.send_json({"type":"pong","needs_help":state["needs_help"],"submitted_at":state["submitted_at"],"checkpoint_at":state.get("checkpoint_at")});continue
530
  else:continue
531
  save(state)
532
  warning=await asyncio.to_thread(persist_version,version) if version else ""
533
- await ws.send_json({"type":"ack","needs_help":state["needs_help"],"submitted_at":state["submitted_at"],"checkpoint_at":state.get("checkpoint_at"),"version_kind":version["kind"] if version else None,"version_at":version["created_at"] if version else None,"version_warning":warning});await broadcast(c,w)
534
  except (WebSocketDisconnect,json.JSONDecodeError):pass
535
  finally:
536
  if students.get(key) is ws:students.pop(key,None);state["connected"]=False;state["status"]="idle";save(state);await broadcast(c,w)
@@ -546,11 +577,11 @@ async def teacher_ws(ws:WebSocket):
546
  while True:
547
  m=await ws.receive_json()
548
  if m.get("type")=="ack_help":
549
- s=clean(m.get("student_id"),"student");state=live.get((c,s,w))
550
  if state:
551
- state["needs_help"]=False;save(state);target=students.get((c,s,w))
552
  if target:
553
- try:await target.send_json({"type":"help_ack"})
554
  except Exception:pass
555
  await broadcast(c,w)
556
  elif m.get("type")=="ping":await ws.send_json({"type":"pong"})
 
18
  # Bundled syntax repairs target work saved before 2026-10-04 00:00 Asia/Taipei.
19
  LEGACY_REPAIR_CUTOFF_MS=1791043200000
20
  VERSION_WRITE_COOLDOWN_MS=max(0, int(os.getenv("CLASSROOM_VERSION_COOLDOWN_MS", "1500")))
21
+ HELP_REQUEST_COOLDOWN_MS=max(0, int(os.getenv("CLASSROOM_HELP_COOLDOWN_MS", "300000")))
22
  STUDENT_WS_CONNECTIONS_PER_MINUTE=max(10, int(os.getenv("CLASSROOM_WS_CONNECTIONS_PER_MINUTE", "300")))
23
  STUDENT_WS_MESSAGES_PER_MINUTE=max(60, int(os.getenv("CLASSROOM_WS_MESSAGES_PER_MINUTE", "300")))
24
  ALLOWED={".py",".json",".txt",".csv",".md",".toml",".yaml",".yml"}; ID_RE=re.compile(r"[^0-9A-Za-z_\-一-鿿]")
 
86
  columns={row[1] for row in c.execute("PRAGMA table_info(classroom_projects)")}
87
  if "checkpoint_files" not in columns:c.execute("ALTER TABLE classroom_projects ADD COLUMN checkpoint_files TEXT")
88
  if "checkpoint_at" not in columns:c.execute("ALTER TABLE classroom_projects ADD COLUMN checkpoint_at INTEGER")
89
+ if "help_requested_at" not in columns:c.execute("ALTER TABLE classroom_projects ADD COLUMN help_requested_at INTEGER")
90
  c.execute("""CREATE TABLE IF NOT EXISTS classroom_courses(class_code TEXT PRIMARY KEY,course_name TEXT,created_at INTEGER)""")
91
  c.execute("""CREATE TABLE IF NOT EXISTS classroom_members(class_code TEXT,student_id TEXT,display_name TEXT,created_at INTEGER,PRIMARY KEY(class_code,student_id))""")
92
  c.execute("""CREATE TABLE IF NOT EXISTS classroom_versions(class_code TEXT,student_id TEXT,display_name TEXT,week_id TEXT,version_id TEXT,kind TEXT,project_name TEXT,files TEXT,created_at INTEGER,PRIMARY KEY(class_code,student_id,week_id,version_id))""")
93
  c.execute("""CREATE TABLE IF NOT EXISTS classroom_migrations(migration_id TEXT PRIMARY KEY,applied_at INTEGER)""")
94
  c.execute("""CREATE TABLE IF NOT EXISTS classroom_write_windows(class_code TEXT,student_id TEXT,week_id TEXT,kind TEXT,window_started INTEGER,write_count INTEGER,last_write INTEGER,PRIMARY KEY(class_code,student_id,week_id,kind))""")
95
+ c.execute("""CREATE TABLE IF NOT EXISTS classroom_help_cooldowns(class_code TEXT,student_id TEXT,last_requested_at INTEGER,cooldown_until INTEGER,PRIMARY KEY(class_code,student_id))""")
96
  for item in json.loads((DATA/"classes.json").read_text(encoding="utf-8")):
97
  code=clean(item.get("code"),"L6A")
98
  c.execute("""INSERT INTO classroom_courses VALUES(?,?,?) ON CONFLICT(class_code) DO UPDATE SET course_name=excluded.course_name""",(code,clean_label(item.get("name"),code),now()))
 
176
  WHERE classroom_members.class_code=classroom_versions.class_code
177
  AND classroom_members.student_id=classroom_versions.student_id
178
  )""")
179
+ def help_cooldown_until(class_code,student_id):
180
+ if HELP_REQUEST_COOLDOWN_MS<=0:return None
181
+ with lock,sqlite3.connect(DB) as db:row=db.execute("SELECT cooldown_until FROM classroom_help_cooldowns WHERE class_code=? AND student_id=?",(class_code,student_id)).fetchone()
182
+ until=int(row[0]) if row and row[0] else None
183
+ return until if until and until>now() else None
184
+ def start_help_cooldown(class_code,student_id):
185
+ current=now()
186
+ if HELP_REQUEST_COOLDOWN_MS<=0:return current,None
187
+ with lock,sqlite3.connect(DB) as db:
188
+ db.execute("BEGIN IMMEDIATE")
189
+ row=db.execute("SELECT cooldown_until FROM classroom_help_cooldowns WHERE class_code=? AND student_id=?",(class_code,student_id)).fetchone()
190
+ until=int(row[0]) if row and row[0] else 0
191
+ if until>current:return None,until
192
+ cooldown_until=current+HELP_REQUEST_COOLDOWN_MS
193
+ db.execute("INSERT INTO classroom_help_cooldowns VALUES(?,?,?,?) ON CONFLICT(class_code,student_id) DO UPDATE SET last_requested_at=excluded.last_requested_at,cooldown_until=excluded.cooldown_until",(class_code,student_id,current,cooldown_until))
194
+ return current,cooldown_until
195
+ def empty(c,s,n,w): return {"class_code":c,"student_id":s,"display_name":n,"week_id":w,"project_name":"","files":{"main.py":"# 在這裡寫 Python\n"},"final_files":None,"checkpoint_files":None,"active_file":"main.py","output":"","status":"idle","needs_help":False,"updated_at":now(),"submitted_at":None,"checkpoint_at":None,"help_requested_at":None,"help_cooldown_until":help_cooldown_until(c,s),"help_cooldown_ms":HELP_REQUEST_COOLDOWN_MS,"connected":True}
196
+ def from_row(r,connected=False): return {"class_code":r[0],"student_id":r[1],"display_name":r[2],"week_id":r[3],"project_name":r[4],"files":json.loads(r[5]),"final_files":json.loads(r[6]) if r[6] else None,"active_file":r[7],"output":r[8],"status":r[9],"needs_help":bool(r[10]),"updated_at":r[11],"submitted_at":r[12],"checkpoint_files":json.loads(r[13]) if r[13] else None,"checkpoint_at":r[14],"help_requested_at":r[15],"help_cooldown_ms":HELP_REQUEST_COOLDOWN_MS,"connected":connected}
197
+ SELECT="SELECT class_code,student_id,display_name,week_id,project_name,draft_files,final_files,active_file,output,status,needs_help,updated_at,submitted_at,checkpoint_files,checkpoint_at,help_requested_at FROM classroom_projects"
198
  def load(c,s,n,w):
199
  with lock,sqlite3.connect(DB) as db:r=db.execute(SELECT+" WHERE class_code=? AND student_id=? AND week_id=?",(c,s,w)).fetchone()
200
+ state=from_row(r,True) if r else empty(c,s,n,w); state["display_name"]=n; state["help_cooldown_until"]=help_cooldown_until(c,s); state["help_cooldown_ms"]=HELP_REQUEST_COOLDOWN_MS; return state
201
  def save(x):
202
+ values=(x["class_code"],x["student_id"],x["display_name"],x["week_id"],x["project_name"],json.dumps(x["files"],ensure_ascii=False),json.dumps(x["final_files"],ensure_ascii=False) if x["final_files"] else None,x["active_file"],x["output"][-40000:],x["status"],int(x["needs_help"]),x["updated_at"],x["submitted_at"],json.dumps(x["checkpoint_files"],ensure_ascii=False) if x.get("checkpoint_files") else None,x.get("checkpoint_at"),x.get("help_requested_at"))
203
  with lock,sqlite3.connect(DB) as db:
204
  db.execute("INSERT OR IGNORE INTO classroom_courses VALUES(?,?,?)",(x["class_code"],x["class_code"],now()))
205
  db.execute("""INSERT INTO classroom_members VALUES(?,?,?,?) ON CONFLICT(class_code,student_id) DO UPDATE SET display_name=excluded.display_name""",(x["class_code"],x["student_id"],x["display_name"],now()))
206
+ db.execute("""INSERT INTO classroom_projects(class_code,student_id,display_name,week_id,project_name,draft_files,final_files,active_file,output,status,needs_help,updated_at,submitted_at,checkpoint_files,checkpoint_at,help_requested_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(class_code,student_id,week_id) DO UPDATE SET display_name=excluded.display_name,project_name=excluded.project_name,draft_files=excluded.draft_files,final_files=excluded.final_files,active_file=excluded.active_file,output=excluded.output,status=excluded.status,needs_help=excluded.needs_help,updated_at=excluded.updated_at,submitted_at=excluded.submitted_at,checkpoint_files=excluded.checkpoint_files,checkpoint_at=excluded.checkpoint_at,help_requested_at=excluded.help_requested_at""",values)
207
  def catalog():
208
  with lock,sqlite3.connect(DB) as db:
209
  courses=db.execute("SELECT class_code,course_name FROM classroom_courses ORDER BY course_name,class_code").fetchall()
 
414
  check_password(req.password);code=clean(req.class_code,"");deletions=archived_paths(code)
415
  with lock,sqlite3.connect(DB) as db:
416
  if not db.execute("SELECT 1 FROM classroom_courses WHERE class_code=?",(code,)).fetchone():raise HTTPException(404,"找不到這個班級")
417
+ db.execute("DELETE FROM classroom_versions WHERE class_code=?",(code,));db.execute("DELETE FROM classroom_projects WHERE class_code=?",(code,));db.execute("DELETE FROM classroom_members WHERE class_code=?",(code,));db.execute("DELETE FROM classroom_help_cooldowns WHERE class_code=?",(code,));db.execute("DELETE FROM classroom_courses WHERE class_code=?",(code,))
418
  for key,ws in list(students.items()):
419
  if key[0]==code:
420
  students.pop(key,None);live.pop(key,None)
 
475
  db.execute("DELETE FROM classroom_versions WHERE class_code=? AND student_id=?",(code,student_id))
476
  db.execute("DELETE FROM classroom_projects WHERE class_code=? AND student_id=?",(code,student_id))
477
  db.execute("DELETE FROM classroom_members WHERE class_code=? AND student_id=?",(code,student_id))
478
+ db.execute("DELETE FROM classroom_help_cooldowns WHERE class_code=? AND student_id=?",(code,student_id))
479
  warning=persist_catalog(f"Remove classroom student {student_id} from {code}",deletions)
480
  for class_code,week_id in list(teachers):
481
  if class_code==code:await broadcast(code,week_id)
 
533
  state["files"]=norm_files(m.get("files"));state["project_name"]=clean_label(m.get("project_name"),"");active=safe_path(m.get("active_file","main.py"));state["active_file"]=active if active in state["files"] else "main.py";state["updated_at"]=now()
534
  elif kind=="output":state["output"]=str(m.get("output",""))[-40000:]
535
  elif kind=="status":state["status"]=m.get("status") if m.get("status") in {"idle","running","success","error"} else "idle"
536
+ elif kind=="help":
537
+ requested=bool(m.get("needs_help"))
538
+ if requested and not state["needs_help"]:
539
+ requested_at,cooldown_until=start_help_cooldown(c,s)
540
+ if requested_at is None:
541
+ state["help_cooldown_until"]=cooldown_until
542
+ remaining=max(1,(cooldown_until-now()+999)//1000)
543
+ await ws.send_json({"type":"help_rejected","needs_help":state["needs_help"],"help_cooldown_until":cooldown_until,"help_cooldown_ms":HELP_REQUEST_COOLDOWN_MS,"message":f"還要等 {remaining} 秒才能再次呼叫老師。"})
544
+ continue
545
+ state["needs_help"]=True;state["help_requested_at"]=requested_at;state["help_cooldown_until"]=cooldown_until
546
+ elif not requested:
547
+ state["needs_help"]=False;state["help_requested_at"]=None;state["help_cooldown_until"]=help_cooldown_until(c,s)
548
  elif kind=="checkpoint":
549
  try:
550
  consume_version_write(c,s,w,"checkpoint")
551
  state["files"]=norm_files(m.get("files",state["files"]));state["project_name"]=clean_label(m.get("project_name",state["project_name"]),"");state["checkpoint_files"]=dict(state["files"]);state["checkpoint_at"]=now();state["updated_at"]=state["checkpoint_at"];version=record_version(state,"checkpoint")
552
  except VersionLimitError as exc:
553
+ await ws.send_json({"type":"write_rejected","kind":"checkpoint","message":str(exc)});continue
554
  elif kind=="submit":
555
  try:
556
  consume_version_write(c,s,w,"submit")
557
  state["files"]=norm_files(m.get("files",state["files"]));state["project_name"]=clean_label(m.get("project_name",state["project_name"]),"");state["final_files"]=dict(state["files"]);state["submitted_at"]=now();state["updated_at"]=state["submitted_at"];version=record_version(state,"submit")
558
  except VersionLimitError as exc:
559
+ await ws.send_json({"type":"write_rejected","kind":"submit","message":str(exc)});continue
560
+ elif kind=="ping":state["help_cooldown_until"]=help_cooldown_until(c,s);await ws.send_json({"type":"pong","needs_help":state["needs_help"],"help_cooldown_until":state["help_cooldown_until"],"help_cooldown_ms":HELP_REQUEST_COOLDOWN_MS,"submitted_at":state["submitted_at"],"checkpoint_at":state.get("checkpoint_at")});continue
561
  else:continue
562
  save(state)
563
  warning=await asyncio.to_thread(persist_version,version) if version else ""
564
+ await ws.send_json({"type":"ack","needs_help":state["needs_help"],"help_cooldown_until":state.get("help_cooldown_until"),"help_cooldown_ms":HELP_REQUEST_COOLDOWN_MS,"submitted_at":state["submitted_at"],"checkpoint_at":state.get("checkpoint_at"),"version_kind":version["kind"] if version else None,"version_at":version["created_at"] if version else None,"version_warning":warning});await broadcast(c,w)
565
  except (WebSocketDisconnect,json.JSONDecodeError):pass
566
  finally:
567
  if students.get(key) is ws:students.pop(key,None);state["connected"]=False;state["status"]="idle";save(state);await broadcast(c,w)
 
577
  while True:
578
  m=await ws.receive_json()
579
  if m.get("type")=="ack_help":
580
+ s=clean(m.get("student_id"),"student");state=live.get((c,s,w)) or next((item for item in snapshot(c,w) if item["student_id"]==s),None)
581
  if state:
582
+ state["needs_help"]=False;state["help_requested_at"]=None;state["help_cooldown_until"]=help_cooldown_until(c,s);save(state);target=students.get((c,s,w))
583
  if target:
584
+ try:await target.send_json({"type":"help_ack","help_cooldown_until":state["help_cooldown_until"],"help_cooldown_ms":HELP_REQUEST_COOLDOWN_MS})
585
  except Exception:pass
586
  await broadcast(c,w)
587
  elif m.get("type")=="ping":await ws.send_json({"type":"pong"})
classroom_static/classroom.css CHANGED
@@ -186,10 +186,25 @@ body.panel-resizing { cursor:col-resize;user-select:none; }
186
  .panel-heading h2 { margin: 0; font-size: 1.1875rem; }
187
  .panel-heading.dark { min-width:0;padding-block:6px;flex-wrap:wrap;border-color:var(--editor-line);background:var(--editor-raised);color:var(--editor-ink); }
188
  .side-tabs { height:44px;display:flex;border-bottom:1px solid var(--line); }
189
- .side-tab { flex:1;border:0;background:var(--surface);color:var(--muted);font-size:.8rem;font-weight:800; }
190
  .side-tab.active { color:var(--navy);box-shadow:inset 0 -3px 0 var(--action); }
191
  #filesView { min-height:0;display:grid;grid-template-rows:52px minmax(0,1fr) auto; }
192
  #syntaxView { min-height:0;display:grid;grid-template-rows:52px auto minmax(0,1fr); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
  .file-list { min-height:0;overflow:auto;padding:var(--space-sm); }
194
  .file-row { display:flex;align-items:center;border-radius:var(--radius-sm); }
195
  .file-row:hover { background:var(--surface-subtle); }.file-row.selected{background:var(--action-soft);color:var(--navy)}
@@ -341,12 +356,18 @@ dialog::backdrop { background: oklch(0.16 0.04 255 / .72); }
341
 
342
  .detail-empty { height:100%;display:grid;place-items:center;padding:var(--space-2xl);color:var(--muted);text-align:center; }
343
  .detail-view { height:100%;display:grid;grid-template-rows:auto minmax(0,1fr); }
344
- .detail-header { min-height: 76px; display: flex; align-items: center; justify-content: space-between; gap: var(--space-lg); padding: var(--space-lg) var(--space-xl); background: var(--surface); border-bottom: 1px solid var(--line); }
345
- .detail-header h1 { margin: 0; font-size: 1.2rem; }
 
346
  .detail-meta { margin-top: 4px; color: var(--muted); font-size: .8rem; }
347
- .detail-actions { display: flex; gap: var(--space-sm); }
 
348
  .detail-split { min-height: 0; display: grid; grid-template-rows: minmax(240px, 1.15fr) minmax(180px, .85fr); }
349
- .teacher-project { min-height:0;display:grid;grid-template-rows:42px minmax(0,1fr); }
 
 
 
 
350
  .teacher-file-tabs { display:flex;gap:2px;padding:var(--space-xs) var(--space-md);overflow-x:auto;background:var(--editor-raised);border-bottom:1px solid var(--editor-line); }
351
  .teacher-file-tab { flex:none;min-height:32px;padding:0 var(--space-md);border:0;border-radius:var(--radius-sm);background:transparent;color:oklch(.72 .02 255);font:650 .78rem/1 "SFMono-Regular",Consolas,monospace; }
352
  .teacher-file-tab:hover,.teacher-file-tab.active { background:var(--editor-line);color:white; }
 
186
  .panel-heading h2 { margin: 0; font-size: 1.1875rem; }
187
  .panel-heading.dark { min-width:0;padding-block:6px;flex-wrap:wrap;border-color:var(--editor-line);background:var(--editor-raised);color:var(--editor-ink); }
188
  .side-tabs { height:44px;display:flex;border-bottom:1px solid var(--line); }
189
+ .side-tab { min-width:0;flex:1;padding-inline:var(--space-xs);border:0;background:var(--surface);color:var(--muted);font-size:.76rem;font-weight:800; }
190
  .side-tab.active { color:var(--navy);box-shadow:inset 0 -3px 0 var(--action); }
191
  #filesView { min-height:0;display:grid;grid-template-rows:52px minmax(0,1fr) auto; }
192
  #syntaxView { min-height:0;display:grid;grid-template-rows:52px auto minmax(0,1fr); }
193
+ #lessonView { min-height:0;display:grid;grid-template-rows:auto minmax(0,1fr); }
194
+ .lesson-guide-content { min-height:0;overflow:auto;padding:var(--space-lg); }
195
+ .lesson-guide-block { padding:0 0 var(--space-lg);margin:0 0 var(--space-lg);border-bottom:1px solid var(--line); }
196
+ .lesson-guide-block h2,.lesson-help-note h2 { margin:0 0 var(--space-sm);font-size:.9375rem;line-height:1.35; }
197
+ .lesson-guide-block p,.lesson-help-note p { margin:0;color:var(--muted);font-size:.875rem;line-height:1.55; }
198
+ .lesson-guide-block ul,.lesson-guide-block ol,.lesson-details ul { display:grid;gap:.45rem;margin:0;padding-inline-start:1.25rem;color:var(--ink);font-size:.83rem;line-height:1.5; }
199
+ .lesson-timeline { gap:.65rem!important; }
200
+ .lesson-timeline strong { color:var(--navy); }
201
+ .lesson-guide-block li::marker,.lesson-details li::marker { color:var(--action);font-weight:800; }
202
+ .lesson-target { padding:var(--space-md);border:0;border-radius:var(--radius-md);background:var(--action-soft); }
203
+ .lesson-ai-note { padding:var(--space-md);border:0;border-radius:var(--radius-md);background:var(--help-soft); }
204
+ .lesson-details { margin:0 0 var(--space-lg);border-bottom:1px solid var(--line); }
205
+ .lesson-details summary { min-height:44px;display:flex;align-items:center;color:var(--navy);font-size:.84rem;font-weight:800;cursor:pointer; }
206
+ .lesson-details ul { padding:0 0 var(--space-lg) 1.25rem; }
207
+ .lesson-help-note { padding:var(--space-md) 0 0; }
208
  .file-list { min-height:0;overflow:auto;padding:var(--space-sm); }
209
  .file-row { display:flex;align-items:center;border-radius:var(--radius-sm); }
210
  .file-row:hover { background:var(--surface-subtle); }.file-row.selected{background:var(--action-soft);color:var(--navy)}
 
356
 
357
  .detail-empty { height:100%;display:grid;place-items:center;padding:var(--space-2xl);color:var(--muted);text-align:center; }
358
  .detail-view { height:100%;display:grid;grid-template-rows:auto minmax(0,1fr); }
359
+ .detail-header { min-height: 76px; display: flex; flex-wrap:wrap;align-items: center; justify-content: space-between; gap: var(--space-lg); padding: var(--space-lg) var(--space-xl); background: var(--surface); border-bottom: 1px solid var(--line); }
360
+ .detail-header>div:first-child { min-width:0;flex:1 1 380px; }
361
+ .detail-header h1 { margin: 0; font-size: 1.3rem; }
362
  .detail-meta { margin-top: 4px; color: var(--muted); font-size: .8rem; }
363
+ .detail-actions { display: flex;flex:0 1 auto;flex-wrap:wrap;gap: var(--space-sm); }
364
+ .detail-actions .copy-button { white-space:nowrap; }
365
  .detail-split { min-height: 0; display: grid; grid-template-rows: minmax(240px, 1.15fr) minmax(180px, .85fr); }
366
+ .teacher-project { min-height:0;display:grid;grid-template-rows:38px 42px minmax(0,1fr); }
367
+ .teacher-version-tabs { display:flex;align-items:center;gap:var(--space-sm);padding:0 var(--space-lg);border-bottom:1px solid var(--line);background:var(--surface);color:var(--muted);font-size:.78rem; }
368
+ .teacher-version-tabs button { margin-left:auto;white-space:nowrap; }
369
+ .teacher-version-tabs strong { color:var(--navy); }
370
+ .detail-actions [aria-pressed="true"] { border-color:var(--action);background:var(--action-soft);color:var(--navy); }
371
  .teacher-file-tabs { display:flex;gap:2px;padding:var(--space-xs) var(--space-md);overflow-x:auto;background:var(--editor-raised);border-bottom:1px solid var(--editor-line); }
372
  .teacher-file-tab { flex:none;min-height:32px;padding:0 var(--space-md);border:0;border-radius:var(--radius-sm);background:transparent;color:oklch(.72 .02 255);font:650 .78rem/1 "SFMono-Regular",Consolas,monospace; }
373
  .teacher-file-tab:hover,.teacher-file-tab.active { background:var(--editor-line);color:white; }
classroom_static/student.html CHANGED
@@ -7,7 +7,7 @@
7
  <title>Python 專案教室|學生工作區</title>
8
  <link rel="stylesheet" href="/classroom-assets/vendor/codemirror/codemirror.css">
9
  <link rel="stylesheet" href="/classroom-assets/vendor/codemirror/material-darker.css">
10
- <link rel="stylesheet" href="/classroom-assets/classroom.css?v=2026fall-16">
11
  </head>
12
  <body>
13
  <header class="app-header">
@@ -20,10 +20,11 @@
20
  </div>
21
  <div class="header-actions">
22
  <div class="connection-state"><i class="status-dot" id="connectionDot"></i><span id="connectionText">未連線</span></div>
23
- <button class="btn help compact" id="helpButton">請老師協助</button>
24
  <button class="btn secondary compact" id="identityButton">更換身分</button>
25
  </div>
26
  </header>
 
27
 
28
  <section class="project-bar">
29
  <div class="project-context">
@@ -35,14 +36,14 @@
35
  <button class="copy-button" id="progressButton">選擇舊進度</button>
36
  <button class="copy-button" id="importButton">匯入 .py / ZIP</button>
37
  <button class="copy-button" id="exportButton">匯出專案</button>
38
- <button class="copy-button checkpoint-action" id="checkpointButton">暫存本週進度</button>
39
- <button class="btn compact" id="submitButton">提交正式版本</button>
40
  <input id="fileImport" type="file" accept=".py,.zip" hidden>
41
  </div>
42
  </section>
43
 
44
  <nav class="mobile-tabs" role="tablist">
45
- <button class="mobile-tab" data-panel="referencePanel">專案/語法</button>
46
  <button class="mobile-tab" data-panel="editorPanel" aria-selected="true">程式</button>
47
  <button class="mobile-tab" data-panel="consolePanel">執行結果</button>
48
  </nav>
@@ -52,6 +53,7 @@
52
  <div class="side-tabs">
53
  <button class="side-tab active" data-side="filesView">專案檔案</button>
54
  <button class="side-tab" data-side="syntaxView">語法查詢</button>
 
55
  </div>
56
  <section class="side-view" id="filesView">
57
  <div class="panel-heading"><h1>檔案夾</h1><button class="copy-button" id="newFileButton">+新增</button></div>
@@ -67,6 +69,10 @@
67
  </div>
68
  <div class="snippet-list" id="snippetList"></div>
69
  </section>
 
 
 
 
70
  </aside>
71
 
72
  <div class="panel-resizer reference-resizer" id="referenceResizer" role="separator" aria-label="調整專案側欄寬度" aria-orientation="vertical" tabindex="0" title="拖曳調整寬度;雙擊恢復預設"></div>
@@ -126,7 +132,7 @@
126
  <dialog id="progressDialog">
127
  <div class="dialog-content">
128
  <h2>選擇已儲存版本</h2>
129
- <p>每次暫存與正式提交都會保留;載入只會建立工作副本,不會刪除其他版本。</p>
130
  <div class="progress-list" id="progressList"></div>
131
  <button class="btn secondary dialog-close">關閉</button>
132
  </div>
@@ -137,6 +143,6 @@
137
  <script src="/classroom-assets/vendor/codemirror/python.js"></script>
138
  <script src="/classroom-assets/vendor/jszip/jszip.min.js"></script>
139
  <script src="/classroom-assets/pygame-support.js?v=2026fall-1"></script>
140
- <script src="/classroom-assets/student.js?v=2026fall-14"></script>
141
  </body>
142
  </html>
 
7
  <title>Python 專案教室|學生工作區</title>
8
  <link rel="stylesheet" href="/classroom-assets/vendor/codemirror/codemirror.css">
9
  <link rel="stylesheet" href="/classroom-assets/vendor/codemirror/material-darker.css">
10
+ <link rel="stylesheet" href="/classroom-assets/classroom.css?v=2026fall-20">
11
  </head>
12
  <body>
13
  <header class="app-header">
 
20
  </div>
21
  <div class="header-actions">
22
  <div class="connection-state"><i class="status-dot" id="connectionDot"></i><span id="connectionText">未連線</span></div>
23
+ <button class="btn help compact" id="helpButton" aria-describedby="helpStatus">請老師協助</button>
24
  <button class="btn secondary compact" id="identityButton">更換身分</button>
25
  </div>
26
  </header>
27
+ <span class="sr-only" id="helpStatus" aria-live="polite"></span>
28
 
29
  <section class="project-bar">
30
  <div class="project-context">
 
36
  <button class="copy-button" id="progressButton">選擇舊進度</button>
37
  <button class="copy-button" id="importButton">匯入 .py / ZIP</button>
38
  <button class="copy-button" id="exportButton">匯出專案</button>
39
+ <button class="copy-button checkpoint-action" id="checkpointButton" title="建立一個可以從進度載回的版本,不會交給老師或發布">暫存版本</button>
40
+ <button class="btn compact" id="submitButton" title="正式提交目前版本給老師檢查;老師另行發布後才會公開">正式提交</button>
41
  <input id="fileImport" type="file" accept=".py,.zip" hidden>
42
  </div>
43
  </section>
44
 
45
  <nav class="mobile-tabs" role="tablist">
46
+ <button class="mobile-tab" data-panel="referencePanel">專案/任務</button>
47
  <button class="mobile-tab" data-panel="editorPanel" aria-selected="true">程式</button>
48
  <button class="mobile-tab" data-panel="consolePanel">執行結果</button>
49
  </nav>
 
53
  <div class="side-tabs">
54
  <button class="side-tab active" data-side="filesView">專案檔案</button>
55
  <button class="side-tab" data-side="syntaxView">語法查詢</button>
56
+ <button class="side-tab" data-side="lessonView" id="lessonTab">本堂任務</button>
57
  </div>
58
  <section class="side-view" id="filesView">
59
  <div class="panel-heading"><h1>檔案夾</h1><button class="copy-button" id="newFileButton">+新增</button></div>
 
69
  </div>
70
  <div class="snippet-list" id="snippetList"></div>
71
  </section>
72
+ <section class="side-view" id="lessonView" hidden>
73
+ <div class="panel-heading"><h1 id="lessonHeading">本堂任務</h1><span id="lessonLabel"></span></div>
74
+ <div class="lesson-guide-content" id="lessonGuideContent"></div>
75
+ </section>
76
  </aside>
77
 
78
  <div class="panel-resizer reference-resizer" id="referenceResizer" role="separator" aria-label="調整專案側欄寬度" aria-orientation="vertical" tabindex="0" title="拖曳調整寬度;雙擊恢復預設"></div>
 
132
  <dialog id="progressDialog">
133
  <div class="dialog-content">
134
  <h2>選擇已儲存版本</h2>
135
+ <p>自動同步更新老師可查看的目前草稿,不會建立歷史版本;「暫存版本」建立可載回的工作版本;「正式提交」凍結一份交給老師檢查,老師另行發布後才會公開。載入舊版本只建立工作副本,不會刪除歷史紀錄。</p>
136
  <div class="progress-list" id="progressList"></div>
137
  <button class="btn secondary dialog-close">關閉</button>
138
  </div>
 
143
  <script src="/classroom-assets/vendor/codemirror/python.js"></script>
144
  <script src="/classroom-assets/vendor/jszip/jszip.min.js"></script>
145
  <script src="/classroom-assets/pygame-support.js?v=2026fall-1"></script>
146
+ <script src="/classroom-assets/student.js?v=2026fall-18"></script>
147
  </body>
148
  </html>
classroom_static/student.js CHANGED
@@ -1,8 +1,9 @@
1
  const SNIPPETS=[["基礎","輸入與輸出",'name = input("名字:")\nprint("你好", name)'],["判斷","if / elif / else",'if score >= 90:\n print("A")\nelse:\n print("繼續加油")'],["迴圈","for 與 range",'for number in range(1, 6):\n print(number)'],["迴圈","while",'while True:\n choice = input("選擇:")\n if choice == "q":\n break'],["資料","list",'items = []\nitems.append("線索")\nfor item in items:\n print(item)'],["資料","dict",'student = {"name": "Alex"}\nprint(student.get("team", "未分組"))'],["函式","def / return",'def add(a, b):\n return a + b'],["檔案","引入自己的模組",'from clues import find_clue'],["檔案","讀取 JSON",'import json\nwith open("data.json", encoding="utf-8") as file:\n data = json.load(file)'],["錯誤","try / except",'try:\n age = int(input("年齡:"))\nexcept ValueError:\n print("請輸入整數")'],["Pygame","瀏覽器版 Pygame 入門",'import asyncio\nimport pygame\n\nasync def main():\n pygame.init()\n screen = pygame.display.set_mode((640, 480))\n pygame.display.set_caption("我的第一個遊戲")\n clock = pygame.time.Clock()\n x = 300\n running = True\n\n while running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n\n keys = pygame.key.get_pressed()\n if keys[pygame.K_LEFT]:\n x -= 4\n if keys[pygame.K_RIGHT]:\n x += 4\n\n screen.fill((24, 34, 52))\n pygame.draw.circle(screen, (255, 190, 80), (x, 240), 28)\n pygame.display.flip()\n await asyncio.sleep(1 / 60)\n\n pygame.quit()\n\n# 瀏覽器版會自動呼叫 async main(),不用另外加 asyncio.run(main())']].map(([category,title,code])=>({category,title,code}));
2
- const $=id=>document.getElementById(id),E={};["identityDialog","identityForm","identityError","classCode","displayName","studentIdentity","identityButton","connectionDot","connectionText","helpButton","weekSelect","projectName","templateButton","progressButton","importButton","exportButton","checkpointButton","submitButton","fileImport","fileList","newFileButton","activeFileLabel","syntaxSearch","categoryFilters","snippetList","snippetCount","runButton","stopButton","toggleReferenceButton","toggleConsoleButton","studentLayout","editorPanel","referencePanel","consolePanel","referenceResizer","consoleResizer","consoleInputForm","consoleInput","consoleOutput","consoleTabs","consoleOutputTab","pygameOutputTab","consoleStream","pygameFrame","consoleHint","clearOutputButton","runStatusDot","runStatusText","saveStatus","submitStatus","toast","progressDialog","progressList"].forEach(id=>E[id]=$(id));
3
  const editor=CodeMirror.fromTextArea($("codeEditor"),{mode:"python",theme:"material-darker",lineNumbers:true,indentUnit:4,tabSize:4,extraKeys:{Tab:cm=>cm.replaceSelection(" ")}});
4
  let studentId=localStorage.getItem("classroom_student_id")||"",allowLegacyDraft=!!studentId,catalog={courses:[]};
5
- let course,files={"main.py":"# 在這裡寫 Python\n"},activeFile="main.py",socket,worker,workerReady=false,running=false,pygameRunning=false,needsHelp=false,checkpointAt=null,submittedAt=null,output="",suppress=false,timer,reconnect,category="全部",inputBuffer,inputControl,inputBytes,stdoutDecoder=new TextDecoder(),stderrDecoder=new TextDecoder();
 
6
  const clean=v=>String(v||"").trim().replace(/[^0-9A-Za-z_\-一-鿿]/g,"").slice(0,48),lesson=()=>E.weekSelect.value||"week02",lessonInfo=()=>course?.weeks.find(item=>item.id===lesson()),workspace=()=>lessonInfo()?.workspace_id||lesson(),key=()=>`classroom_project_${localStorage.getItem("classroom_code")}_${studentId}_${workspace()}`,legacyKey=()=>`classroom_project_${localStorage.getItem("classroom_code")}_${workspace()}`;
7
  function toast(t){E.toast.textContent=t;E.toast.classList.add("visible");setTimeout(()=>E.toast.classList.remove("visible"),1900)}
8
  function send(m){if(socket?.readyState!==WebSocket.OPEN)return false;socket.send(JSON.stringify(m));return true}
@@ -30,20 +31,23 @@ function connect(){
30
  const local=readLocal(),s=m.state;
31
  const server={files:s.files,activeFile:s.active_file,projectName:s.project_name,output:s.output};
32
  const src=local&&Number(local.savedAt||0)>Number(s.updated_at||0)?local:server;
33
- output=src.output||"";E.consoleOutput.textContent=output||"尚無執行結果。";checkpointAt=s.checkpoint_at;submittedAt=s.submitted_at;needsHelp=!!s.needs_help;renderState();setProject(src.files,src.projectName,src.activeFile);send({type:"output",output});
34
  }
35
  if(m.type==="identity"&&typeof m.display_name==="string"){
36
  localStorage.setItem("classroom_name",m.display_name);
37
  E.studentIdentity.textContent=`${clean(localStorage.getItem("classroom_code"))} · ${m.display_name}`;
38
  toast("老師已更新你的名單姓名");
39
  }
40
- if(m.type==="help_ack"){needsHelp=false;renderState();toast("老師已看到你的協助請求")}
41
- if(m.type==="write_rejected"){E.saveStatus.textContent="未儲存";toast(m.message||"儲存受到限制,請稍後再試");send({type:"ping"})}
42
- if(["ack","pong"].includes(m.type)){if(typeof m.needs_help==="boolean"){const seen=needsHelp&&!m.needs_help;needsHelp=m.needs_help;if(seen)toast("老師已看到你的協助請求")}if(Object.prototype.hasOwnProperty.call(m,"checkpoint_at"))checkpointAt=m.checkpoint_at;if(Object.prototype.hasOwnProperty.call(m,"submitted_at"))submittedAt=m.submitted_at;renderState();if(m.type==="ack")E.saveStatus.textContent="已同步";if(m.version_warning)toast(m.version_warning)}
 
43
  };
44
- current.onclose=async e=>{if(socket!==current)return;E.connectionDot.className="status-dot error";E.connectionText.textContent="已離線";E.saveStatus.textContent="保存在此裝置";if(e.code===4004||e.code===4404){localStorage.removeItem("classroom_student_id");localStorage.removeItem("classroom_name");studentId="";await loadCatalog();E.identityError.textContent=e.code===4004?"老師已將你從名單移除。":"姓名與班級名單不符,請重新輸入。";E.identityDialog.showModal();return}reconnect=setTimeout(connect,2500)};
45
  }
46
- function renderState(){E.helpButton.classList.toggle("active",needsHelp);E.helpButton.textContent=needsHelp?"取消請求協助":"請老師協助";const time=value=>new Date(value).toLocaleTimeString("zh-TW",{hour:"2-digit",minute:"2-digit"}),labels=[];if(checkpointAt)labels.push(`本週暫存 ${time(checkpointAt)}`);if(submittedAt)labels.push(`正式提交 ${time(submittedAt)}`);E.submitStatus.textContent=labels.join(" · ")||"尚未暫存或提交"}
 
 
47
  let editorRefreshFrame;
48
  function refreshEditorLayout(){cancelAnimationFrame(editorRefreshFrame);editorRefreshFrame=requestAnimationFrame(()=>{editor.refresh();editorRefreshFrame=requestAnimationFrame(()=>editor.refresh())})}
49
  const panelDefaults={reference:280,console:360},panelMinimums={reference:220,console:260},panelMaximums={reference:480,console:600};
@@ -79,7 +83,26 @@ function initResizablePanels(){
79
  setupResizer("reference");setupResizer("console");new ResizeObserver(refreshEditorLayout).observe(E.editorPanel);window.addEventListener("resize",()=>syncPanelWidths(false));
80
  }
81
  function setLayout(referenceHidden,consoleHidden){E.studentLayout.classList.toggle("reference-hidden",referenceHidden);E.studentLayout.classList.toggle("console-hidden",consoleHidden);E.toggleReferenceButton.setAttribute("aria-pressed",String(referenceHidden));E.toggleConsoleButton.setAttribute("aria-pressed",String(consoleHidden));E.toggleReferenceButton.textContent=referenceHidden?"顯示側欄":"隱藏側欄";E.toggleConsoleButton.textContent=consoleHidden?"顯示 Console":"隱藏 Console";localStorage.setItem("classroom_hide_reference",String(referenceHidden));localStorage.setItem("classroom_hide_console",String(consoleHidden));requestAnimationFrame(()=>{syncPanelWidths(false);refreshEditorLayout()})}
82
- function renderLesson(){const item=lessonInfo(),shared=item?.workspace_id&&item.workspace_id!==item.id;E.templateButton.disabled=!item?.template;E.templateButton.textContent=item?.template?"匯入專案起始套版":shared?"沿用目前專案":"尚未提供套版"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  function setConsoleView(view){E.consoleStream.dataset.view=view;E.consoleOutputTab.classList.toggle("active",view==="console");E.pygameOutputTab.classList.toggle("active",view==="pygame");E.consoleOutputTab.setAttribute("aria-selected",String(view==="console"));E.pygameOutputTab.setAttribute("aria-selected",String(view==="pygame"))}
84
  ClassroomPygame.attach(E.pygameFrame,message=>{if(message.type==="output"&&message.text)append(message.text);if(message.type==="status"&&message.label)E.runStatusText.textContent=message.label;if(message.type==="done"){pygameRunning=false;runState("success","遊戲已結束")}if(message.type==="error"||message.type==="load_error"){pygameRunning=false;if(message.text)append(`${message.text}\n`);runState("error","Pygame 執行錯誤");setConsoleView("console")}});
85
  function initWorker(){worker?.terminate();workerReady=false;running=false;E.consoleInputForm.hidden=true;E.runButton.disabled=true;E.runButton.textContent="載入 Python…";if(!crossOriginIsolated||typeof SharedArrayBuffer==="undefined"){append("瀏覽器未啟用互動式 Python。請重新整理,並使用最新版 Chrome、Edge 或 Safari。\n");runState("error","環境不支援");return}inputBuffer=new SharedArrayBuffer(16392);inputControl=new Int32Array(inputBuffer,0,2);inputBytes=new Uint8Array(inputBuffer,8);worker=new Worker("/classroom-assets/py-worker.js?v=2026fall-4");worker.onmessage=e=>{const m=e.data;if(m.type==="ready"){workerReady=true;E.runButton.disabled=false;E.runButton.textContent="執行";runState("online","準備完成")}else if(m.type==="stream"){const decoder=m.channel==="stderr"?stderrDecoder:stdoutDecoder;append(decoder.decode(m.bytes,{stream:true}))}else if(m.type==="input_request"){E.consoleInputForm.hidden=false;E.consoleInput.value="";E.runStatusText.textContent="等待輸入";E.consoleInput.focus()}else if(m.type==="done"){E.consoleInputForm.hidden=true;runState("success","執行成功")}else if(m.type==="python_error"){E.consoleInputForm.hidden=true;if(m.text)append(`${m.text}\n`);runState("error","程式錯誤")}else if(m.type==="load_error"){append(`Python 載入失敗:${m.text}\n`);runState("error","載入失敗")}};worker.onerror=e=>{append(`Python 執行器錯誤:${e.message}\n`);runState("error","執行器錯誤")}}
@@ -90,11 +113,12 @@ async function loadCatalog(){catalog=await(await fetch("/api/classroom/classes")
90
  E.identityForm.onsubmit=async e=>{e.preventDefault();const c=clean(E.classCode.value),n=E.displayName.value.trim(),button=E.identityForm.querySelector("button[type=submit]");if(!c||!n){E.identityError.textContent="請選擇課程並輸入姓名";return}button.disabled=true;button.textContent="驗證名單中…";E.identityError.textContent="";try{const response=await fetch("/api/classroom/student-login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({class_code:c,display_name:n})});const data=await response.json();if(!response.ok)throw Error(data.detail||"無法驗證名單");allowLegacyDraft=studentId===data.student_id;studentId=data.student_id;localStorage.setItem("classroom_student_id",studentId);localStorage.setItem("classroom_code",c);localStorage.setItem("classroom_name",data.display_name);E.identityDialog.close();connect()}catch(error){E.identityError.textContent=error.message}finally{button.disabled=false;button.textContent="進入教室"}};E.identityButton.onclick=async()=>{await loadCatalog();E.identityDialog.showModal()};E.weekSelect.onchange=()=>{localStorage.setItem("classroom_week",lesson());renderLesson();connect()};E.projectName.oninput=sync;
91
  E.newFileButton.onclick=()=>{const p=(prompt("新檔名(例如 clues.py):")||"").trim();if(!/^[\w\-\u4e00-\u9fff/]+\.(py|json|txt|csv|md)$/.test(p)||p.includes(".."))return toast("檔名不合規格");if(p in files)return toast("檔案已存在");files[p]=p.endsWith(".py")?"# 新的 Python 模組\n":"";openFile(p);sync()};
92
  E.templateButton.onclick=async()=>{const item=lessonInfo();if(!item?.template)return;if(!confirm("匯入起始套版會取代目前專案內容,繼續?"))return;const r=await fetch(`/api/classroom/template/${item.id}`);if(!r.ok)return toast("這個專案尚未發布套版");const d=await r.json();setProject(d.files,item.project);toast("已匯入專案起始套版")};
93
- E.progressButton.onclick=async()=>{const q=new URLSearchParams({class_code:localStorage.getItem("classroom_code")||"",student_id:studentId,display_name:localStorage.getItem("classroom_name")||""}),r=await fetch(`/api/classroom/progress?${q}`),d=await r.json(),source={published:"已發布",submit:"正式提交",checkpoint:"進度暫存"};E.progressList.innerHTML=d.progress.length?d.progress.map((p,i)=>{const item=course.weeks.find(w=>w.id===p.week_id),label=item?`Lesson ${item.lesson??item.week}`:p.week_id;return `<button class="progress-item" data-i="${i}"><strong>${esc(label)}|${esc(p.project_name)}</strong><span>${source[p.source]||"已儲存"} · ${new Date(p.submitted_at).toLocaleString("zh-TW")}</span></button>`}).join(""):'<p>還沒有已儲存的版本。</p>';E.progressList.querySelectorAll("[data-i]").forEach(b=>b.onclick=()=>{const p=d.progress[+b.dataset.i];setProject(p.files,p.project_name);E.progressDialog.close();toast("已載入這個版本的工作副本")});E.progressDialog.showModal()};document.querySelectorAll(".dialog-close").forEach(b=>b.onclick=()=>b.closest("dialog").close());
94
  E.importButton.onclick=()=>E.fileImport.click();E.fileImport.onchange=async()=>{const f=E.fileImport.files[0];if(!f)return;if(f.name.endsWith(".py"))setProject({"main.py":await f.text()},f.name.replace(/\.py$/,"").trim());else{const z=await JSZip.loadAsync(f),next={};for(const [p,item] of Object.entries(z.files))if(!item.dir&&/\.(py|json|txt|csv|md)$/i.test(p)&&!p.includes(".."))next[p]=await item.async("string");setProject(next,f.name.replace(/\.zip$/i,""))}E.fileImport.value="";toast("已匯入專案")};
95
  E.exportButton.onclick=async()=>{files[activeFile]=editor.getValue();const z=new JSZip();Object.entries(files).forEach(([p,t])=>z.file(p,t));const blob=await z.generateAsync({type:"blob"}),a=document.createElement("a");a.href=URL.createObjectURL(blob);a.download=`${clean(E.projectName.value)||"project"}.zip`;a.click();URL.revokeObjectURL(a.href)};
96
- E.checkpointButton.onclick=()=>{files[activeFile]=editor.getValue();if(!files["main.py"].trim())return toast("main.py 不能為空");saveLocal();if(!send({type:"checkpoint",files,project_name:E.projectName.value}))return toast("目前離線,請連線後再暫存");checkpointAt=Date.now();renderState();toast("已新增一個暫存版本,不會發布到 Demo")};
97
- E.submitButton.onclick=()=>{files[activeFile]=editor.getValue();if(!files["main.py"].trim())return toast("main.py 不能為空");if(!confirm("新增一個正式提交版本?之前的暫存與提交都會保留。"))return;saveLocal();if(!send({type:"submit",files,project_name:E.projectName.value}))return toast("目前離線,請連線後再提交");submittedAt=Date.now();renderState();toast("已新增一個正式提交版本")};E.helpButton.onclick=()=>{needsHelp=!needsHelp;renderState();send({type:"help",needs_help:needsHelp})};
 
98
  E.runButton.onclick=async()=>{if(!workerReady||running)return;files[activeFile]=editor.getValue();output="";E.consoleOutput.textContent="";E.consoleInputForm.hidden=true;stdoutDecoder=new TextDecoder();stderrDecoder=new TextDecoder();if(ClassroomPygame.isPygame(files)){pygameRunning=true;E.consoleTabs.hidden=false;E.pygameFrame.hidden=false;setConsoleView("pygame");runState("running","準備瀏覽器版 Pygame");try{await ClassroomPygame.run(files)}catch(error){if(!running)return;pygameRunning=false;append(`Pygame 載入失敗:${error.message}\n`);runState("error","Pygame 載入失敗");setConsoleView("console")}return}ClassroomPygame.stop();pygameRunning=false;E.consoleTabs.hidden=true;E.pygameFrame.hidden=true;setConsoleView("console");Atomics.store(inputControl,0,0);runState("running","執行中");worker.postMessage({type:"run",files,entry:"main.py",inputBuffer})};E.consoleInputForm.onsubmit=e=>{e.preventDefault();if(!running||E.consoleInputForm.hidden)return;const encoded=new TextEncoder().encode(E.consoleInput.value);if(encoded.length>inputBytes.length)return toast("單次輸入內容太長");inputBytes.fill(0);inputBytes.set(encoded);Atomics.store(inputControl,1,encoded.length);append(`${E.consoleInput.value}\n`);E.consoleInputForm.hidden=true;E.runStatusText.textContent="執行中";Atomics.store(inputControl,0,1);Atomics.notify(inputControl,0,1)};E.stopButton.onclick=()=>{append("\n[已停止]\n");if(pygameRunning){ClassroomPygame.stop();pygameRunning=false;setConsoleView("console");runState("idle","已停止");return}runState("idle","已停止");initWorker()};E.consoleOutputTab.onclick=()=>setConsoleView("console");E.pygameOutputTab.onclick=()=>setConsoleView("pygame");E.clearOutputButton.onclick=()=>{output="";E.consoleOutput.textContent="尚無執行結果。";send({type:"output",output:""})};E.syntaxSearch.oninput=renderSyntax;editor.on("change",()=>{if(!suppress){files[activeFile]=editor.getValue();sync()}});
99
- E.toggleReferenceButton.onclick=()=>setLayout(!E.studentLayout.classList.contains("reference-hidden"),E.studentLayout.classList.contains("console-hidden"));E.toggleConsoleButton.onclick=()=>setLayout(E.studentLayout.classList.contains("reference-hidden"),!E.studentLayout.classList.contains("console-hidden"));document.querySelectorAll(".side-tab").forEach(b=>b.onclick=()=>{document.querySelectorAll(".side-tab").forEach(x=>x.classList.toggle("active",x===b));document.querySelectorAll(".side-view").forEach(v=>v.hidden=v.id!==b.dataset.side)});document.querySelectorAll(".mobile-tab").forEach(b=>b.onclick=()=>{document.querySelectorAll(".mobile-tab").forEach(x=>x.setAttribute("aria-selected",String(x===b)));document.querySelectorAll(".student-layout>.panel").forEach(p=>p.classList.toggle("mobile-active",p.id===b.dataset.panel));if(b.dataset.panel==="editorPanel")refreshEditorLayout()});setInterval(()=>send({type:"ping"}),4000);
100
  (async()=>{[course]=await Promise.all([(await fetch("/api/classroom/course")).json(),loadCatalog()]);E.weekSelect.innerHTML=course.weeks.map(w=>`<option value="${w.id}">Lesson ${w.lesson??w.week}|${esc(w.title)}${w.workspace_id&&w.workspace_id!==w.id?"(同一專案)":""}</option>`).join("");const saved=localStorage.getItem("classroom_week");E.weekSelect.value=course.weeks.some(w=>w.id===saved)?saved:"week02";renderLesson();renderFiles();renderSyntax();initResizablePanels();setLayout(localStorage.getItem("classroom_hide_reference")==="true",localStorage.getItem("classroom_hide_console")==="true");initWorker();connect()})();
 
1
  const SNIPPETS=[["基礎","輸入與輸出",'name = input("名字:")\nprint("你好", name)'],["判斷","if / elif / else",'if score >= 90:\n print("A")\nelse:\n print("繼續加油")'],["迴圈","for 與 range",'for number in range(1, 6):\n print(number)'],["迴圈","while",'while True:\n choice = input("選擇:")\n if choice == "q":\n break'],["資料","list",'items = []\nitems.append("線索")\nfor item in items:\n print(item)'],["資料","dict",'student = {"name": "Alex"}\nprint(student.get("team", "未分組"))'],["函式","def / return",'def add(a, b):\n return a + b'],["檔案","引入自己的模組",'from clues import find_clue'],["檔案","讀取 JSON",'import json\nwith open("data.json", encoding="utf-8") as file:\n data = json.load(file)'],["錯誤","try / except",'try:\n age = int(input("年齡:"))\nexcept ValueError:\n print("請輸入整數")'],["Pygame","瀏覽器版 Pygame 入門",'import asyncio\nimport pygame\n\nasync def main():\n pygame.init()\n screen = pygame.display.set_mode((640, 480))\n pygame.display.set_caption("我的第一個遊戲")\n clock = pygame.time.Clock()\n x = 300\n running = True\n\n while running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n\n keys = pygame.key.get_pressed()\n if keys[pygame.K_LEFT]:\n x -= 4\n if keys[pygame.K_RIGHT]:\n x += 4\n\n screen.fill((24, 34, 52))\n pygame.draw.circle(screen, (255, 190, 80), (x, 240), 28)\n pygame.display.flip()\n await asyncio.sleep(1 / 60)\n\n pygame.quit()\n\n# 瀏覽器版會自動呼叫 async main(),不用另外加 asyncio.run(main())']].map(([category,title,code])=>({category,title,code}));
2
+ const $=id=>document.getElementById(id),E={};["identityDialog","identityForm","identityError","classCode","displayName","studentIdentity","identityButton","connectionDot","connectionText","helpButton","helpStatus","weekSelect","projectName","templateButton","progressButton","importButton","exportButton","checkpointButton","submitButton","fileImport","fileList","newFileButton","activeFileLabel","lessonHeading","lessonLabel","lessonGuideContent","syntaxSearch","categoryFilters","snippetList","snippetCount","runButton","stopButton","toggleReferenceButton","toggleConsoleButton","studentLayout","editorPanel","referencePanel","consolePanel","referenceResizer","consoleResizer","consoleInputForm","consoleInput","consoleOutput","consoleTabs","consoleOutputTab","pygameOutputTab","consoleStream","pygameFrame","consoleHint","clearOutputButton","runStatusDot","runStatusText","saveStatus","submitStatus","toast","progressDialog","progressList"].forEach(id=>E[id]=$(id));
3
  const editor=CodeMirror.fromTextArea($("codeEditor"),{mode:"python",theme:"material-darker",lineNumbers:true,indentUnit:4,tabSize:4,extraKeys:{Tab:cm=>cm.replaceSelection(" ")}});
4
  let studentId=localStorage.getItem("classroom_student_id")||"",allowLegacyDraft=!!studentId,catalog={courses:[]};
5
+ const HELP_COOLDOWN_MS=300000;
6
+ let course,files={"main.py":"# 在這裡寫 Python\n"},activeFile="main.py",socket,worker,workerReady=false,running=false,pygameRunning=false,needsHelp=false,helpCooldownUntil=null,helpCooldownMs=HELP_COOLDOWN_MS,checkpointAt=null,submittedAt=null,output="",suppress=false,timer,reconnect,category="全部",inputBuffer,inputControl,inputBytes,stdoutDecoder=new TextDecoder(),stderrDecoder=new TextDecoder();
7
  const clean=v=>String(v||"").trim().replace(/[^0-9A-Za-z_\-一-鿿]/g,"").slice(0,48),lesson=()=>E.weekSelect.value||"week02",lessonInfo=()=>course?.weeks.find(item=>item.id===lesson()),workspace=()=>lessonInfo()?.workspace_id||lesson(),key=()=>`classroom_project_${localStorage.getItem("classroom_code")}_${studentId}_${workspace()}`,legacyKey=()=>`classroom_project_${localStorage.getItem("classroom_code")}_${workspace()}`;
8
  function toast(t){E.toast.textContent=t;E.toast.classList.add("visible");setTimeout(()=>E.toast.classList.remove("visible"),1900)}
9
  function send(m){if(socket?.readyState!==WebSocket.OPEN)return false;socket.send(JSON.stringify(m));return true}
 
31
  const local=readLocal(),s=m.state;
32
  const server={files:s.files,activeFile:s.active_file,projectName:s.project_name,output:s.output};
33
  const src=local&&Number(local.savedAt||0)>Number(s.updated_at||0)?local:server;
34
+ output=src.output||"";E.consoleOutput.textContent=output||"尚無執行結果。";checkpointAt=s.checkpoint_at;submittedAt=s.submitted_at;needsHelp=!!s.needs_help;helpCooldownUntil=s.help_cooldown_until;helpCooldownMs=Number(s.help_cooldown_ms??helpCooldownMs);renderLesson();renderState();setProject(src.files,src.projectName,src.activeFile);send({type:"output",output});
35
  }
36
  if(m.type==="identity"&&typeof m.display_name==="string"){
37
  localStorage.setItem("classroom_name",m.display_name);
38
  E.studentIdentity.textContent=`${clean(localStorage.getItem("classroom_code"))} · ${m.display_name}`;
39
  toast("老師已更新你的名單姓名");
40
  }
41
+ if(m.type==="help_ack"){needsHelp=false;helpCooldownUntil=m.help_cooldown_until??helpCooldownUntil;const duration=Number(m.help_cooldown_ms??helpCooldownMs);if(duration!==helpCooldownMs){helpCooldownMs=duration;renderLesson()}E.helpStatus.textContent="老師已回應你的求助;冷卻結束後可以再次呼叫。";renderState();toast("老師已回應你的求助")}
42
+ if(m.type==="help_rejected"){needsHelp=!!m.needs_help;helpCooldownUntil=m.help_cooldown_until??helpCooldownUntil;const duration=Number(m.help_cooldown_ms??helpCooldownMs);if(duration!==helpCooldownMs){helpCooldownMs=duration;renderLesson()}E.helpStatus.textContent=m.message||"請稍後再呼叫老師。";renderState();toast(m.message||"請稍後再呼叫老師")}
43
+ if(m.type==="write_rejected"){E.saveStatus.textContent="未儲存";if(m.kind==="checkpoint"){E.checkpointButton.disabled=false;E.checkpointButton.textContent="暫存版本"}if(m.kind==="submit"){E.submitButton.disabled=false;E.submitButton.textContent="正式提交"}toast(m.message||"儲存受到限制,請稍後再試");send({type:"ping"})}
44
+ if(["ack","pong"].includes(m.type)){if(typeof m.needs_help==="boolean"){const seen=needsHelp&&!m.needs_help;needsHelp=m.needs_help;if(seen){E.helpStatus.textContent="老師已回應你的求助。";toast("老師已回應你的求助")}}if(Object.prototype.hasOwnProperty.call(m,"help_cooldown_until"))helpCooldownUntil=m.help_cooldown_until;if(Object.prototype.hasOwnProperty.call(m,"help_cooldown_ms")){const duration=Number(m.help_cooldown_ms);if(duration!==helpCooldownMs){helpCooldownMs=duration;renderLesson()}}if(Object.prototype.hasOwnProperty.call(m,"checkpoint_at"))checkpointAt=m.checkpoint_at;if(Object.prototype.hasOwnProperty.call(m,"submitted_at"))submittedAt=m.submitted_at;renderState();if(m.type==="ack"){E.saveStatus.textContent="已同步";if(m.version_kind==="checkpoint"){E.checkpointButton.disabled=false;E.checkpointButton.textContent="暫存版本";toast("暫存版本已建立,可以從進度載回")}if(m.version_kind==="submit"){E.submitButton.disabled=false;E.submitButton.textContent="正式提交";toast("正式提交已完成;尚未發布 Demo")}}if(m.version_warning)toast(m.version_warning)}
45
  };
46
+ current.onclose=async e=>{if(socket!==current)return;E.connectionDot.className="status-dot error";E.connectionText.textContent="已離線";E.saveStatus.textContent="保存在此裝置";E.checkpointButton.disabled=false;E.checkpointButton.textContent="暫存版本";E.submitButton.disabled=false;E.submitButton.textContent="正式提交";if(e.code===4004||e.code===4404){localStorage.removeItem("classroom_student_id");localStorage.removeItem("classroom_name");studentId="";await loadCatalog();E.identityError.textContent=e.code===4004?"老師已將你從名單移除。":"姓名與班級名單不符,請重新輸入。";E.identityDialog.showModal();return}reconnect=setTimeout(connect,2500)};
47
  }
48
+ function helpCooldownLabel(){return helpCooldownMs>=60000?`${Math.ceil(helpCooldownMs/60000)} 分鐘`:helpCooldownMs>0?`${Math.ceil(helpCooldownMs/1000)} 秒`:"沒有冷卻"}
49
+ function renderHelpButton(){const remaining=Math.max(0,Number(helpCooldownUntil||0)-Date.now()),seconds=Math.ceil(remaining/1000),label=needsHelp?"取消求助請求":remaining?`再次呼叫 ${Math.floor(seconds/60)}:${String(seconds%60).padStart(2,"0")}`:"請老師協助";E.helpButton.disabled=!needsHelp&&remaining>0;E.helpButton.classList.toggle("active",needsHelp);E.helpButton.textContent=label;E.helpButton.title=needsHelp?`老師已收到求助;取消後仍會保留 ${helpCooldownLabel()} 冷卻時間。`:`成功呼叫後有 ${helpCooldownLabel()} 冷卻。`}
50
+ function renderState(){renderHelpButton();const time=value=>new Date(value).toLocaleTimeString("zh-TW",{hour:"2-digit",minute:"2-digit"}),labels=[];if(checkpointAt)labels.push(`最近暫存 ${time(checkpointAt)}`);if(submittedAt)labels.push(`最近正式提交 ${time(submittedAt)}`);E.submitStatus.textContent=labels.join(" · ")||"尚無暫存或正式提交"}
51
  let editorRefreshFrame;
52
  function refreshEditorLayout(){cancelAnimationFrame(editorRefreshFrame);editorRefreshFrame=requestAnimationFrame(()=>{editor.refresh();editorRefreshFrame=requestAnimationFrame(()=>editor.refresh())})}
53
  const panelDefaults={reference:280,console:360},panelMinimums={reference:220,console:260},panelMaximums={reference:480,console:600};
 
83
  setupResizer("reference");setupResizer("console");new ResizeObserver(refreshEditorLayout).observe(E.editorPanel);window.addEventListener("resize",()=>syncPanelWidths(false));
84
  }
85
  function setLayout(referenceHidden,consoleHidden){E.studentLayout.classList.toggle("reference-hidden",referenceHidden);E.studentLayout.classList.toggle("console-hidden",consoleHidden);E.toggleReferenceButton.setAttribute("aria-pressed",String(referenceHidden));E.toggleConsoleButton.setAttribute("aria-pressed",String(consoleHidden));E.toggleReferenceButton.textContent=referenceHidden?"顯示側欄":"隱藏側欄";E.toggleConsoleButton.textContent=consoleHidden?"顯示 Console":"隱藏 Console";localStorage.setItem("classroom_hide_reference",String(referenceHidden));localStorage.setItem("classroom_hide_console",String(consoleHidden));requestAnimationFrame(()=>{syncPanelWidths(false);refreshEditorLayout()})}
86
+ function renderLesson(){
87
+ const item=lessonInfo(),shared=item?.workspace_id&&item.workspace_id!==item.id,isClosure=item?.id==="week05";
88
+ E.templateButton.disabled=!item?.template;
89
+ E.templateButton.textContent=item?.template?"匯入專案起始套版":shared?"沿用目前專案":"尚未提供套版";
90
+ E.lessonHeading.textContent=item?`Lesson ${item.lesson??item.week}|${item.title}`:"本堂任務";
91
+ E.lessonLabel.textContent=item?.project||"";
92
+ E.lessonGuideContent.innerHTML=isClosure?`
93
+ <section class="lesson-guide-block lesson-target"><h2>今天完成一條可玩的案件路線</h2><p>新玩家可以自己開始調查、收集線索、完成推理並看到結局。</p></section>
94
+ <section class="lesson-guide-block"><h2>收尾檢查</h2><ul><li>至少三個地點、三項不同線索</li><li>能查看證物,重複調查不會重複加入</li><li>必要線索能解鎖推理和合理結局</li><li>空白或錯誤輸入不會讓程式中止</li></ul></section>
95
+ <section class="lesson-guide-block"><h2>課堂流程|120 分鐘</h2><ol class="lesson-timeline"><li><strong>0–8 分|確認目標:</strong>說明今天的完成條件和 AI 使用規則。</li><li><strong>8–18 分|重現現況:</strong>載入自己的舊進度、執行一次,記下第一個問題。</li><li><strong>18–28 分|定義問題:</strong>寫下目前結果、預期結果和一個可重現的測試;示範如何請 AI 給提示。</li><li><strong>28–53 分|修第一個阻礙:</strong>一次改一件事,每次修改後都執行確認。</li><li><strong>53–73 分|同儕黑箱測試:</strong>同學只看操作說明試玩,記錄卡點和輸入。</li><li><strong>73–88 分|修復並重測:</strong>挑一個最重要的問題修好,請原測試者重跑。</li><li><strong>88–106 分|個人說明:</strong>每人 1–2 分鐘,說明一段程式、預測新測試,再實際展示。</li><li><strong>106–116 分|保存進度:</strong>達成條件且能執行就正式提交;還有問題就暫存並寫下下一步。</li><li><strong>116–120 分|離堂回顧:</strong>記下今天學會的事、AI 幫助和仍卡住的地方。</li></ol></section>
96
+ <section class="lesson-guide-block lesson-ai-note"><h2>AI 使用方式</h2><p>先自己指出問題,再請 AI 解釋錯誤、給小提示或設計測試。把 AI 建議的程式放進專案執行,留下「我問了什麼/我採用或修改什麼/測試結果」。老師會請你說明程式並現場預測測試結果;不需要隱瞞有使用 AI。</p></section>
97
+ <details class="lesson-details"><summary>自動同步、暫存和正式提交的差別</summary><ul><li><strong>自動同步:</strong>更新目前工作草稿,老師端可即時查看;不會新增一筆歷史版本。</li><li><strong>暫存版本:</strong>建立可從「選擇舊進度」載回的版本;不算交作業,也不會發布。</li><li><strong>正式提交:</strong>凍結一份交給老師檢查的版本。你仍能繼續編輯及再次提交;老師另外發布後才會公開。</li></ul></details>
98
+ <section class="lesson-help-note"><h2>需要老師幫忙?</h2><p>按一次「請老師協助」就會通知老師。成功呼叫後冷卻 ${helpCooldownLabel()};取消或老師回應都不會重置冷卻。等待時先寫下卡住的步驟和試過的方法。</p></section>`:`
99
+ <section class="lesson-guide-block lesson-target"><h2>${esc(item?.output||"本堂作品任務")}</h2><p>先確認目前版本,再完成一項可以執行和說明的功能。</p></section>
100
+ <section class="lesson-guide-block"><h2>完成後記得</h2><ul><li>執行程式並確認結果</li><li>建立暫存版本,保留可回復的進度</li><li>需要交給老師檢查時,再按正式提交</li></ul></section>
101
+ <details class="lesson-details"><summary>暫存和正式提交的差別</summary><ul><li><strong>自動同步:</strong>老師可查看目前草稿,不會建立歷史版本。</li><li><strong>暫存版本:</strong>可載回的工作進度,不會交給老師或公開。</li><li><strong>正式提交:</strong>凍結一份交給老師檢查;老師另行發布後才會公開。</li></ul></details>
102
+ <section class="lesson-help-note"><h2>需要老師幫忙?</h2><p>按一次就會通知老師。成功呼叫後冷卻 ${helpCooldownLabel()};取消或老師回應都不會重置。</p></section>`;
103
+ if(isClosure)setSideView("lessonView");
104
+ }
105
+ function setSideView(name){document.querySelectorAll(".side-tab").forEach(button=>button.classList.toggle("active",button.dataset.side===name));document.querySelectorAll(".side-view").forEach(view=>view.hidden=view.id!==name);if(lessonInfo()?.id==="week05"){document.querySelectorAll(".mobile-tab").forEach(button=>button.setAttribute("aria-selected",String(button.dataset.panel==="referencePanel")));document.querySelectorAll(".student-layout>.panel").forEach(panel=>panel.classList.toggle("mobile-active",panel.id==="referencePanel"))}}
106
  function setConsoleView(view){E.consoleStream.dataset.view=view;E.consoleOutputTab.classList.toggle("active",view==="console");E.pygameOutputTab.classList.toggle("active",view==="pygame");E.consoleOutputTab.setAttribute("aria-selected",String(view==="console"));E.pygameOutputTab.setAttribute("aria-selected",String(view==="pygame"))}
107
  ClassroomPygame.attach(E.pygameFrame,message=>{if(message.type==="output"&&message.text)append(message.text);if(message.type==="status"&&message.label)E.runStatusText.textContent=message.label;if(message.type==="done"){pygameRunning=false;runState("success","遊戲已結束")}if(message.type==="error"||message.type==="load_error"){pygameRunning=false;if(message.text)append(`${message.text}\n`);runState("error","Pygame 執行錯誤");setConsoleView("console")}});
108
  function initWorker(){worker?.terminate();workerReady=false;running=false;E.consoleInputForm.hidden=true;E.runButton.disabled=true;E.runButton.textContent="載入 Python…";if(!crossOriginIsolated||typeof SharedArrayBuffer==="undefined"){append("瀏覽器未啟用互動式 Python。請重新整理,並使用最新版 Chrome、Edge 或 Safari。\n");runState("error","環境不支援");return}inputBuffer=new SharedArrayBuffer(16392);inputControl=new Int32Array(inputBuffer,0,2);inputBytes=new Uint8Array(inputBuffer,8);worker=new Worker("/classroom-assets/py-worker.js?v=2026fall-4");worker.onmessage=e=>{const m=e.data;if(m.type==="ready"){workerReady=true;E.runButton.disabled=false;E.runButton.textContent="執行";runState("online","準備完成")}else if(m.type==="stream"){const decoder=m.channel==="stderr"?stderrDecoder:stdoutDecoder;append(decoder.decode(m.bytes,{stream:true}))}else if(m.type==="input_request"){E.consoleInputForm.hidden=false;E.consoleInput.value="";E.runStatusText.textContent="等待輸入";E.consoleInput.focus()}else if(m.type==="done"){E.consoleInputForm.hidden=true;runState("success","執行成功")}else if(m.type==="python_error"){E.consoleInputForm.hidden=true;if(m.text)append(`${m.text}\n`);runState("error","程式錯誤")}else if(m.type==="load_error"){append(`Python 載入失敗:${m.text}\n`);runState("error","載入失敗")}};worker.onerror=e=>{append(`Python 執行器錯誤:${e.message}\n`);runState("error","執行器錯誤")}}
 
113
  E.identityForm.onsubmit=async e=>{e.preventDefault();const c=clean(E.classCode.value),n=E.displayName.value.trim(),button=E.identityForm.querySelector("button[type=submit]");if(!c||!n){E.identityError.textContent="請選擇課程並輸入姓名";return}button.disabled=true;button.textContent="驗證名單中…";E.identityError.textContent="";try{const response=await fetch("/api/classroom/student-login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({class_code:c,display_name:n})});const data=await response.json();if(!response.ok)throw Error(data.detail||"無法驗證名單");allowLegacyDraft=studentId===data.student_id;studentId=data.student_id;localStorage.setItem("classroom_student_id",studentId);localStorage.setItem("classroom_code",c);localStorage.setItem("classroom_name",data.display_name);E.identityDialog.close();connect()}catch(error){E.identityError.textContent=error.message}finally{button.disabled=false;button.textContent="進入教室"}};E.identityButton.onclick=async()=>{await loadCatalog();E.identityDialog.showModal()};E.weekSelect.onchange=()=>{localStorage.setItem("classroom_week",lesson());renderLesson();connect()};E.projectName.oninput=sync;
114
  E.newFileButton.onclick=()=>{const p=(prompt("新檔名(例如 clues.py):")||"").trim();if(!/^[\w\-\u4e00-\u9fff/]+\.(py|json|txt|csv|md)$/.test(p)||p.includes(".."))return toast("檔名不合規格");if(p in files)return toast("檔案已存在");files[p]=p.endsWith(".py")?"# 新的 Python 模組\n":"";openFile(p);sync()};
115
  E.templateButton.onclick=async()=>{const item=lessonInfo();if(!item?.template)return;if(!confirm("匯入起始套版會取代目前專案內容,繼續?"))return;const r=await fetch(`/api/classroom/template/${item.id}`);if(!r.ok)return toast("這個專案尚未發布套版");const d=await r.json();setProject(d.files,item.project);toast("已匯入專案起始套版")};
116
+ E.progressButton.onclick=async()=>{const q=new URLSearchParams({class_code:localStorage.getItem("classroom_code")||"",student_id:studentId,display_name:localStorage.getItem("classroom_name")||""}),r=await fetch(`/api/classroom/progress?${q}`),d=await r.json(),source={published:"已發布",submit:"正式提交",checkpoint:"進度暫存"};E.progressList.innerHTML=d.progress.length?d.progress.map((p,i)=>{const item=course.weeks.find(w=>w.id===p.week_id),shared=course.weeks.filter(w=>(w.workspace_id||w.id)===p.week_id),lessons=shared.map(w=>w.lesson??w.week),label=shared.length>1?`Lesson ${lessons[0]}–${lessons[lessons.length-1]} 共用專案`:item?`Lesson ${item.lesson??item.week}`:p.week_id;return `<button class="progress-item" data-i="${i}"><strong>${esc(label)}|${esc(p.project_name)}</strong><span>${source[p.source]||"已儲存"} · ${new Date(p.submitted_at).toLocaleString("zh-TW")}</span></button>`}).join(""):'<p>還沒有已儲存的版本。</p>';E.progressList.querySelectorAll("[data-i]").forEach(b=>b.onclick=()=>{const p=d.progress[+b.dataset.i];setProject(p.files,p.project_name);E.progressDialog.close();toast("已載入這個版本的工作副本")});E.progressDialog.showModal()};document.querySelectorAll(".dialog-close").forEach(b=>b.onclick=()=>b.closest("dialog").close());
117
  E.importButton.onclick=()=>E.fileImport.click();E.fileImport.onchange=async()=>{const f=E.fileImport.files[0];if(!f)return;if(f.name.endsWith(".py"))setProject({"main.py":await f.text()},f.name.replace(/\.py$/,"").trim());else{const z=await JSZip.loadAsync(f),next={};for(const [p,item] of Object.entries(z.files))if(!item.dir&&/\.(py|json|txt|csv|md)$/i.test(p)&&!p.includes(".."))next[p]=await item.async("string");setProject(next,f.name.replace(/\.zip$/i,""))}E.fileImport.value="";toast("已匯入專案")};
118
  E.exportButton.onclick=async()=>{files[activeFile]=editor.getValue();const z=new JSZip();Object.entries(files).forEach(([p,t])=>z.file(p,t));const blob=await z.generateAsync({type:"blob"}),a=document.createElement("a");a.href=URL.createObjectURL(blob);a.download=`${clean(E.projectName.value)||"project"}.zip`;a.click();URL.revokeObjectURL(a.href)};
119
+ E.checkpointButton.onclick=()=>{files[activeFile]=editor.getValue();if(!files["main.py"].trim())return toast("main.py 不能為空");saveLocal();if(!send({type:"checkpoint",files,project_name:E.projectName.value}))return toast("目前離線,請連線後再暫存");E.checkpointButton.disabled=true;E.checkpointButton.textContent="正在暫存…"};
120
+ E.submitButton.onclick=()=>{files[activeFile]=editor.getValue();if(!files["main.py"].trim())return toast("main.py 不能為空");if(!confirm("正式提交目前版本給老師檢查?你之後仍可繼續修改並再次提交。"))return;saveLocal();if(!send({type:"submit",files,project_name:E.projectName.value}))return toast("目前離線,請連線後再提交");E.submitButton.disabled=true;E.submitButton.textContent="正在提交…"};
121
+ E.helpButton.onclick=()=>{if(!socket||socket.readyState!==WebSocket.OPEN)return toast("目前離線,連線後才能呼叫老師");if(needsHelp){needsHelp=false;E.helpStatus.textContent=`已取消求助;${helpCooldownLabel()} 冷卻仍會繼續。`;send({type:"help",needs_help:false});renderState();return}if(Date.now()<Number(helpCooldownUntil||0))return;needsHelp=true;helpCooldownUntil=Date.now()+helpCooldownMs;E.helpStatus.textContent="已通知老師。等待時請記下目前卡住的步驟和試過的方法。";send({type:"help",needs_help:true});renderState()};
122
  E.runButton.onclick=async()=>{if(!workerReady||running)return;files[activeFile]=editor.getValue();output="";E.consoleOutput.textContent="";E.consoleInputForm.hidden=true;stdoutDecoder=new TextDecoder();stderrDecoder=new TextDecoder();if(ClassroomPygame.isPygame(files)){pygameRunning=true;E.consoleTabs.hidden=false;E.pygameFrame.hidden=false;setConsoleView("pygame");runState("running","準備瀏覽器版 Pygame");try{await ClassroomPygame.run(files)}catch(error){if(!running)return;pygameRunning=false;append(`Pygame 載入失敗:${error.message}\n`);runState("error","Pygame 載入失敗");setConsoleView("console")}return}ClassroomPygame.stop();pygameRunning=false;E.consoleTabs.hidden=true;E.pygameFrame.hidden=true;setConsoleView("console");Atomics.store(inputControl,0,0);runState("running","執行中");worker.postMessage({type:"run",files,entry:"main.py",inputBuffer})};E.consoleInputForm.onsubmit=e=>{e.preventDefault();if(!running||E.consoleInputForm.hidden)return;const encoded=new TextEncoder().encode(E.consoleInput.value);if(encoded.length>inputBytes.length)return toast("單次輸入內容太長");inputBytes.fill(0);inputBytes.set(encoded);Atomics.store(inputControl,1,encoded.length);append(`${E.consoleInput.value}\n`);E.consoleInputForm.hidden=true;E.runStatusText.textContent="執行中";Atomics.store(inputControl,0,1);Atomics.notify(inputControl,0,1)};E.stopButton.onclick=()=>{append("\n[已停止]\n");if(pygameRunning){ClassroomPygame.stop();pygameRunning=false;setConsoleView("console");runState("idle","已停止");return}runState("idle","已停止");initWorker()};E.consoleOutputTab.onclick=()=>setConsoleView("console");E.pygameOutputTab.onclick=()=>setConsoleView("pygame");E.clearOutputButton.onclick=()=>{output="";E.consoleOutput.textContent="尚無執行結果。";send({type:"output",output:""})};E.syntaxSearch.oninput=renderSyntax;editor.on("change",()=>{if(!suppress){files[activeFile]=editor.getValue();sync()}});
123
+ E.toggleReferenceButton.onclick=()=>setLayout(!E.studentLayout.classList.contains("reference-hidden"),E.studentLayout.classList.contains("console-hidden"));E.toggleConsoleButton.onclick=()=>setLayout(E.studentLayout.classList.contains("reference-hidden"),!E.studentLayout.classList.contains("console-hidden"));document.querySelectorAll(".side-tab").forEach(b=>b.onclick=()=>setSideView(b.dataset.side));document.querySelectorAll(".mobile-tab").forEach(b=>b.onclick=()=>{document.querySelectorAll(".mobile-tab").forEach(x=>x.setAttribute("aria-selected",String(x===b)));document.querySelectorAll(".student-layout>.panel").forEach(p=>p.classList.toggle("mobile-active",p.id===b.dataset.panel));if(b.dataset.panel==="editorPanel")refreshEditorLayout()});let helpWasCooling=false;setInterval(()=>{const cooling=Date.now()<Number(helpCooldownUntil||0);if(helpWasCooling&&!cooling)E.helpStatus.textContent="冷卻時間已結束,現在可以再次呼叫老師。";helpWasCooling=cooling;renderHelpButton()},1000);setInterval(()=>send({type:"ping"}),4000);
124
  (async()=>{[course]=await Promise.all([(await fetch("/api/classroom/course")).json(),loadCatalog()]);E.weekSelect.innerHTML=course.weeks.map(w=>`<option value="${w.id}">Lesson ${w.lesson??w.week}|${esc(w.title)}${w.workspace_id&&w.workspace_id!==w.id?"(同一專案)":""}</option>`).join("");const saved=localStorage.getItem("classroom_week");E.weekSelect.value=course.weeks.some(w=>w.id===saved)?saved:"week02";renderLesson();renderFiles();renderSyntax();initResizablePanels();setLayout(localStorage.getItem("classroom_hide_reference")==="true",localStorage.getItem("classroom_hide_console")==="true");initWorker();connect()})();
classroom_static/teacher.html CHANGED
@@ -1,9 +1,9 @@
1
  <!doctype html>
2
  <html lang="zh-Hant">
3
- <head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Python 專案教室|教師控制台</title><link rel="stylesheet" href="/classroom-assets/classroom.css?v=2026fall-8"></head>
4
  <body>
5
  <header class="app-header"><div class="brand"><div class="brand-mark">Py</div><div class="brand-copy"><strong>全班專案控制台</strong><span id="classLabel">尚未進入班級</span></div></div><div class="header-actions"><div class="connection-state"><i id="connectionDot" class="status-dot"></i><span id="connectionText">未連線</span></div><a class="btn secondary compact header-link" href="/admin">內容管理</a><button class="btn secondary compact" id="loginButton">切換班級</button></div></header>
6
- <section class="project-bar"><div class="project-context"><label for="teacherWeek">Lesson</label><select id="teacherWeek"></select><span id="submissionSummary" class="submission-summary">等待學生</span></div><div class="project-actions"><button class="copy-button" id="downloadButton">下載全班 ZIP</button><button class="btn compact" id="publishButton">結算並發布 Demo</button></div></section>
7
  <main class="teacher-layout">
8
  <section class="roster-panel">
9
  <div class="panel-heading"><h1>學生狀態</h1><span id="studentTotal">0 人</span></div>
@@ -11,9 +11,9 @@
11
  <div class="filter-bar" id="teacherFilters"><button class="chip" data-filter="all" aria-pressed="true">全部</button><button class="chip" data-filter="checkpointed">已暫存</button><button class="chip" data-filter="submitted">已提交</button><button class="chip" data-filter="help">需要協助</button><button class="chip" data-filter="error">錯誤</button></div>
12
  <div class="roster-header"><span>學生</span><span>狀態</span><span>最新儲存</span><span>版本</span></div><div class="roster-list" id="rosterList"></div>
13
  </section>
14
- <section class="teacher-detail" id="teacherDetail"><div class="detail-empty" id="detailEmpty">選擇一位學生查看多檔案專案。</div><div class="detail-view" id="detailView" hidden><header class="detail-header"><div><h1 id="selectedStudentName"></h1><p class="detail-meta" id="selectedStudentMeta"></p></div><div class="detail-actions"><button class="copy-button" id="ackHelpButton" hidden>標記已查看</button><button class="copy-button" id="copyCodeButton">複製檔案</button><button class="copy-button danger-action" id="deleteStudentButton">刪除學生</button></div></header><div class="teacher-project"><nav class="teacher-file-tabs" id="teacherFiles"></nav><div class="detail-split"><section class="read-only-pane"><div class="pane-label"><span id="teacherActiveFile">main.py</span><span id="lineCount">0 行</span></div><pre class="code-readonly" id="studentCode"></pre></section><section class="read-only-pane"><div class="pane-label"><span>Console</span><span id="outputState"></span></div><pre class="output-readonly" id="studentOutput"></pre></section></div></div></div></section>
15
  </main>
16
  <dialog id="loginDialog"><form class="dialog-content form-stack" id="loginForm"><div><h1>進入教師控制台</h1><p>選取現有課程,或建立新的課程代碼。</p></div><div><label class="field-label" for="classCode">課程</label><select class="text-field" id="classCode" required></select></div><div id="newClassFields" hidden><label class="field-label" for="newClassCode">新課程代碼</label><input class="text-field" id="newClassCode"><label class="field-label secondary-label" for="newClassName">課程名稱</label><input class="text-field" id="newClassName"></div><div><label class="field-label" for="teacherPassword">教師密碼</label><input class="text-field" id="teacherPassword" type="password" required></div><p class="form-error" id="loginError"></p><button class="btn" type="submit">開始監看</button></form></dialog>
17
- <dialog id="publishDialog"><div class="dialog-content"><h2>結算並發布</h2><p id="publishMessage"></p><div class="publish-actions"><button class="btn secondary" id="cancelPublish">取消</button><button class="btn" id="confirmPublish">確認發布</button></div></div></dialog><div class="toast" id="toast"></div><script src="/classroom-assets/teacher.js?v=2026fall-11"></script>
18
  </body>
19
  </html>
 
1
  <!doctype html>
2
  <html lang="zh-Hant">
3
+ <head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Python 專案教室|教師控制台</title><link rel="stylesheet" href="/classroom-assets/classroom.css?v=2026fall-20"></head>
4
  <body>
5
  <header class="app-header"><div class="brand"><div class="brand-mark">Py</div><div class="brand-copy"><strong>全班專案控制台</strong><span id="classLabel">尚未進入班級</span></div></div><div class="header-actions"><div class="connection-state"><i id="connectionDot" class="status-dot"></i><span id="connectionText">未連線</span></div><a class="btn secondary compact header-link" href="/admin">內容管理</a><button class="btn secondary compact" id="loginButton">切換班級</button></div></header>
6
+ <section class="project-bar"><div class="project-context"><label for="teacherWeek">Lesson</label><select id="teacherWeek"></select><span id="submissionSummary" class="submission-summary">等待學生</span></div><div class="project-actions"><button class="copy-button" id="downloadButton">下載全班 ZIP</button><button class="btn compact" id="publishButton">結算並發布 Demo</button></div></section>
7
  <main class="teacher-layout">
8
  <section class="roster-panel">
9
  <div class="panel-heading"><h1>學生狀態</h1><span id="studentTotal">0 人</span></div>
 
11
  <div class="filter-bar" id="teacherFilters"><button class="chip" data-filter="all" aria-pressed="true">全部</button><button class="chip" data-filter="checkpointed">已暫存</button><button class="chip" data-filter="submitted">已提交</button><button class="chip" data-filter="help">需要協助</button><button class="chip" data-filter="error">錯誤</button></div>
12
  <div class="roster-header"><span>學生</span><span>狀態</span><span>最新儲存</span><span>版本</span></div><div class="roster-list" id="rosterList"></div>
13
  </section>
14
+ <section class="teacher-detail" id="teacherDetail"><div class="detail-empty" id="detailEmpty">選擇一位學生查看多檔案專案。</div><div class="detail-view" id="detailView" hidden><header class="detail-header"><div><h1 id="selectedStudentName"></h1><p class="detail-meta" id="selectedStudentMeta"></p></div><div class="detail-actions"><button class="copy-button" id="ackHelpButton" hidden>標記已回應</button><button class="copy-button" id="copyCodeButton">複製檔案</button><button class="copy-button danger-action" id="deleteStudentButton">刪除學生</button></div></header><div class="teacher-project"><nav class="teacher-version-tabs" aria-label="學生版本"><span>檢視版本</span><strong id="teacherVersionLabel">目前草稿</strong><button class="copy-button" id="versionViewButton" hidden>看正式提交</button></nav><nav class="teacher-file-tabs" id="teacherFiles"></nav><div class="detail-split"><section class="read-only-pane"><div class="pane-label"><span id="teacherActiveFile">main.py</span><span id="lineCount">0 行</span></div><pre class="code-readonly" id="studentCode"></pre></section><section class="read-only-pane"><div class="pane-label"><span>目前執行結果</span><span id="outputState"></span></div><pre class="output-readonly" id="studentOutput"></pre></section></div></div></div></section>
15
  </main>
16
  <dialog id="loginDialog"><form class="dialog-content form-stack" id="loginForm"><div><h1>進入教師控制台</h1><p>選取現有課程,或建立新的課程代碼。</p></div><div><label class="field-label" for="classCode">課程</label><select class="text-field" id="classCode" required></select></div><div id="newClassFields" hidden><label class="field-label" for="newClassCode">新課程代碼</label><input class="text-field" id="newClassCode"><label class="field-label secondary-label" for="newClassName">課程名稱</label><input class="text-field" id="newClassName"></div><div><label class="field-label" for="teacherPassword">教師密碼</label><input class="text-field" id="teacherPassword" type="password" required></div><p class="form-error" id="loginError"></p><button class="btn" type="submit">開始監看</button></form></dialog>
17
+ <dialog id="publishDialog"><div class="dialog-content"><h2>結算並發布</h2><p id="publishMessage"></p><div class="publish-actions"><button class="btn secondary" id="cancelPublish">取消</button><button class="btn" id="confirmPublish">確認發布</button></div></div></dialog><div class="toast" id="toast"></div><script src="/classroom-assets/teacher.js?v=2026fall-13"></script>
18
  </body>
19
  </html>
classroom_static/teacher.js CHANGED
@@ -4,7 +4,7 @@ const E = {};
4
  "classLabel", "connectionDot", "connectionText", "loginButton", "teacherWeek",
5
  "submissionSummary", "downloadButton", "publishButton", "studentTotal",
6
  "teacherFilters", "rosterList", "detailEmpty", "detailView", "selectedStudentName",
7
- "selectedStudentMeta", "teacherFiles", "teacherActiveFile", "lineCount", "studentCode",
8
  "studentOutput", "outputState", "ackHelpButton", "copyCodeButton", "deleteStudentButton",
9
  "rosterAddForm", "studentNames", "addStudentsButton",
10
  "loginDialog", "loginForm", "classCode", "newClassFields", "newClassCode", "newClassName",
@@ -16,6 +16,7 @@ let socket;
16
  let students = [];
17
  let selected = null;
18
  let file = "main.py";
 
19
  let filter = "all";
20
  let credentials;
21
  let reconnect;
@@ -34,8 +35,8 @@ function toast(text) {
34
  }
35
 
36
  function status(student) {
 
37
  if (!student.connected) return ["error", "離線"];
38
- if (student.needs_help) return ["help", "求助"];
39
  if (student.status === "running") return ["running", "執行中"];
40
  if (student.status === "error") return ["error", "錯誤"];
41
  return ["online", "在線"];
@@ -44,8 +45,11 @@ function status(student) {
44
  function show() {
45
  const submitted = students.filter(student => student.submitted_at).length;
46
  const checkpointed = students.filter(student => student.checkpoint_at).length;
 
47
  E.studentTotal.textContent = `${students.length} 人`;
48
- E.submissionSummary.textContent = `${checkpointed}/${students.length} 已暫存 · ${submitted}/${students.length} 已提交`;
 
 
49
  const list = students.filter(student => filter === "all" || (
50
  filter === "submitted" ? student.submitted_at :
51
  filter === "checkpointed" ? student.checkpoint_at :
@@ -53,7 +57,7 @@ function show() {
53
  ));
54
  E.rosterList.innerHTML = list.length ? list.map(student => {
55
  const [dot, label] = status(student);
56
- const latest = Math.max(student.submitted_at || 0, student.checkpoint_at || 0);
57
  const counts = student.version_counts || { checkpoint: 0, submit: 0 };
58
  const progressLabel = counts.checkpoint || counts.submit ? `暫 ${counts.checkpoint} · 交 ${counts.submit}` : "—";
59
  return `<button class="student-row ${student.student_id === selected ? "selected" : ""}" data-id="${student.student_id}"><span class="student-name">${esc(student.display_name)}</span><span class="status-label"><i class="status-dot ${dot}"></i>${label}</span><span class="time-label">${savedTime(latest)}</span><span class="help-label">${progressLabel}</span></button>`;
@@ -61,6 +65,7 @@ function show() {
61
  E.rosterList.querySelectorAll("[data-id]").forEach(button => button.onclick = () => {
62
  selected = button.dataset.id;
63
  file = "main.py";
 
64
  show();
65
  });
66
  detail();
@@ -76,25 +81,34 @@ function detail() {
76
  E.detailEmpty.hidden = true;
77
  E.detailView.hidden = false;
78
  const [, label] = status(student);
79
- const paths = Object.keys(student.files || {}).sort((a, b) => a === "main.py" ? -1 : b === "main.py" ? 1 : a.localeCompare(b));
80
- if (!(file in student.files)) file = paths[0];
 
 
81
  E.selectedStudentName.textContent = `${student.display_name} · ${student.project_name}`;
82
  const counts=student.version_counts||{checkpoint:0,submit:0},progress=[];
83
- if(student.checkpoint_at)progress.push(`暫存 ${counts.checkpoint} 版,最新 ${savedTime(student.checkpoint_at)}(不發布)`);
84
- if(student.submitted_at)progress.push(`提交 ${counts.submit} 版,最新 ${savedTime(student.submitted_at)}`);
85
- E.selectedStudentMeta.textContent = `${label} · ${progress.join(" · ") || "尚未暫存或提交"}`;
 
 
 
86
  E.ackHelpButton.hidden = !student.needs_help;
 
 
 
 
87
  E.teacherFiles.innerHTML = paths.map(path => `<button class="teacher-file-tab ${path === file ? "active" : ""}" data-file="${esc(path)}">${esc(path)}</button>`).join("");
88
  E.teacherFiles.querySelectorAll("[data-file]").forEach(button => button.onclick = () => {
89
  file = button.dataset.file;
90
  detail();
91
  });
92
- const code = student.files[file] || "";
93
  E.teacherActiveFile.textContent = file;
94
  E.lineCount.textContent = `${Math.max(1, code.split("\n").length)} 行`;
95
  E.studentCode.textContent = code || "# 空檔案";
96
  E.studentOutput.textContent = student.output || "尚無執行結果。";
97
- E.outputState.textContent = label;
98
  }
99
 
100
  function connect() {
@@ -209,6 +223,7 @@ E.teacherFilters.querySelectorAll("[data-filter]").forEach(button => button.oncl
209
  show();
210
  });
211
  E.ackHelpButton.onclick = () => { if (selected) socket.send(JSON.stringify({ type: "ack_help", student_id: selected })); };
 
212
  E.rosterAddForm.onsubmit = async event => {
213
  event.preventDefault();
214
  const names = E.studentNames.value.split(/[,,\n]+/).map(name => name.trim()).filter(Boolean);
@@ -224,7 +239,7 @@ E.rosterAddForm.onsubmit = async event => {
224
  };
225
  E.copyCodeButton.onclick = async () => {
226
  const student = students.find(item => item.student_id === selected);
227
- if (student) { await navigator.clipboard.writeText(student.files[file] || ""); toast("已複製檔案"); }
228
  };
229
  E.deleteStudentButton.onclick = async () => {
230
  const student = students.find(item => item.student_id === selected);
@@ -251,7 +266,7 @@ E.downloadButton.onclick = async () => {
251
  };
252
  E.publishButton.onclick = () => {
253
  const count = students.filter(student => student.submitted_at).length;
254
- E.publishMessage.textContent = `將 ${count} 份目前專案的最後版本發布到 Project_Demo。Space 會重新建置。`;
255
  E.publishDialog.showModal();
256
  };
257
  E.cancelPublish.onclick = () => E.publishDialog.close();
 
4
  "classLabel", "connectionDot", "connectionText", "loginButton", "teacherWeek",
5
  "submissionSummary", "downloadButton", "publishButton", "studentTotal",
6
  "teacherFilters", "rosterList", "detailEmpty", "detailView", "selectedStudentName",
7
+ "selectedStudentMeta", "teacherFiles", "teacherActiveFile", "teacherVersionLabel", "versionViewButton", "lineCount", "studentCode",
8
  "studentOutput", "outputState", "ackHelpButton", "copyCodeButton", "deleteStudentButton",
9
  "rosterAddForm", "studentNames", "addStudentsButton",
10
  "loginDialog", "loginForm", "classCode", "newClassFields", "newClassCode", "newClassName",
 
16
  let students = [];
17
  let selected = null;
18
  let file = "main.py";
19
+ let versionView = "draft";
20
  let filter = "all";
21
  let credentials;
22
  let reconnect;
 
35
  }
36
 
37
  function status(student) {
38
+ if (student.needs_help) return ["help", student.connected ? "求助" : "求助·離線"];
39
  if (!student.connected) return ["error", "離線"];
 
40
  if (student.status === "running") return ["running", "執行中"];
41
  if (student.status === "error") return ["error", "錯誤"];
42
  return ["online", "在線"];
 
45
  function show() {
46
  const submitted = students.filter(student => student.submitted_at).length;
47
  const checkpointed = students.filter(student => student.checkpoint_at).length;
48
+ const helpCount = students.filter(student => student.needs_help).length;
49
  E.studentTotal.textContent = `${students.length} 人`;
50
+ E.submissionSummary.textContent = `${checkpointed}/${students.length} 暫存 · ${submitted}/${students.length} 正式提交 · ${helpCount} 人求助`;
51
+ const helpFilter=E.teacherFilters.querySelector('[data-filter="help"]');
52
+ helpFilter.textContent=helpCount?`需要協助 ${helpCount}`:"需要協助";
53
  const list = students.filter(student => filter === "all" || (
54
  filter === "submitted" ? student.submitted_at :
55
  filter === "checkpointed" ? student.checkpoint_at :
 
57
  ));
58
  E.rosterList.innerHTML = list.length ? list.map(student => {
59
  const [dot, label] = status(student);
60
+ const latest = Math.max(student.updated_at || 0, student.submitted_at || 0, student.checkpoint_at || 0);
61
  const counts = student.version_counts || { checkpoint: 0, submit: 0 };
62
  const progressLabel = counts.checkpoint || counts.submit ? `暫 ${counts.checkpoint} · 交 ${counts.submit}` : "—";
63
  return `<button class="student-row ${student.student_id === selected ? "selected" : ""}" data-id="${student.student_id}"><span class="student-name">${esc(student.display_name)}</span><span class="status-label"><i class="status-dot ${dot}"></i>${label}</span><span class="time-label">${savedTime(latest)}</span><span class="help-label">${progressLabel}</span></button>`;
 
65
  E.rosterList.querySelectorAll("[data-id]").forEach(button => button.onclick = () => {
66
  selected = button.dataset.id;
67
  file = "main.py";
68
+ versionView = "draft";
69
  show();
70
  });
71
  detail();
 
81
  E.detailEmpty.hidden = true;
82
  E.detailView.hidden = false;
83
  const [, label] = status(student);
84
+ if(versionView==="submit"&&!student.final_files)versionView="draft";
85
+ const files=versionView==="submit"?student.final_files:(student.files||{});
86
+ const paths = Object.keys(files).sort((a, b) => a === "main.py" ? -1 : b === "main.py" ? 1 : a.localeCompare(b));
87
+ if (!(file in files)) file = paths[0];
88
  E.selectedStudentName.textContent = `${student.display_name} · ${student.project_name}`;
89
  const counts=student.version_counts||{checkpoint:0,submit:0},progress=[];
90
+ if(student.needs_help&&student.help_requested_at)progress.push(`求助於 ${savedTime(student.help_requested_at)}`);
91
+ progress.push(versionView==="submit"?`檢視正式提交版本 · ${savedTime(student.submitted_at)}`:"目前顯示自動同步草稿");
92
+ if(student.updated_at)progress.push(`草稿更新 ${savedTime(student.updated_at)}`);
93
+ if(student.checkpoint_at)progress.push(`可回復暫存 ${counts.checkpoint} 版,最近 ${savedTime(student.checkpoint_at)}`);
94
+ if(student.submitted_at)progress.push(`正式提交 ${counts.submit} 版,最近 ${savedTime(student.submitted_at)}`);
95
+ E.selectedStudentMeta.textContent = `${label} · ${progress.join(" · ")}`;
96
  E.ackHelpButton.hidden = !student.needs_help;
97
+ E.versionViewButton.hidden = !student.final_files;
98
+ E.versionViewButton.textContent=versionView==="submit"?"看目前草稿":"看正式提交";
99
+ E.versionViewButton.setAttribute("aria-pressed",String(versionView==="submit"));
100
+ E.teacherVersionLabel.textContent=versionView==="submit"?"正式提交版本":"目前草稿";
101
  E.teacherFiles.innerHTML = paths.map(path => `<button class="teacher-file-tab ${path === file ? "active" : ""}" data-file="${esc(path)}">${esc(path)}</button>`).join("");
102
  E.teacherFiles.querySelectorAll("[data-file]").forEach(button => button.onclick = () => {
103
  file = button.dataset.file;
104
  detail();
105
  });
106
+ const code = files[file] || "";
107
  E.teacherActiveFile.textContent = file;
108
  E.lineCount.textContent = `${Math.max(1, code.split("\n").length)} 行`;
109
  E.studentCode.textContent = code || "# 空檔案";
110
  E.studentOutput.textContent = student.output || "尚無執行結果。";
111
+ E.outputState.textContent = `${label} · 草稿執行結果`;
112
  }
113
 
114
  function connect() {
 
223
  show();
224
  });
225
  E.ackHelpButton.onclick = () => { if (selected) socket.send(JSON.stringify({ type: "ack_help", student_id: selected })); };
226
+ E.versionViewButton.onclick=()=>{versionView=versionView==="submit"?"draft":"submit";detail()};
227
  E.rosterAddForm.onsubmit = async event => {
228
  event.preventDefault();
229
  const names = E.studentNames.value.split(/[,,\n]+/).map(name => name.trim()).filter(Boolean);
 
239
  };
240
  E.copyCodeButton.onclick = async () => {
241
  const student = students.find(item => item.student_id === selected);
242
+ if (student) { const files=versionView==="submit"?student.final_files:student.files;await navigator.clipboard.writeText(files?.[file] || ""); toast("已複製檔案"); }
243
  };
244
  E.deleteStudentButton.onclick = async () => {
245
  const student = students.find(item => item.student_id === selected);
 
266
  };
267
  E.publishButton.onclick = () => {
268
  const count = students.filter(student => student.submitted_at).length;
269
+ E.publishMessage.textContent = `將 ${count} 份正式提交的最新版本公開到 Project Demo;進度暫存不會發布。Space 會重新建置。`;
270
  E.publishDialog.showModal();
271
  };
272
  E.cancelPublish.onclick = () => E.publishDialog.close();