Download index.html from hung9066/QuickVocabCapture: direct link, hf CLI and curl.
- Browser
- Download file 98.9 kB
-
https://huggingface.co/datasets/hung9066/QuickVocabCapture/resolve/main/index.html
- Command line
-
hf download hf://datasets/hung9066/QuickVocabCapture/index.html
-
curl -L -o index.html https://huggingface.co/datasets/hung9066/QuickVocabCapture/resolve/main/index.html
98.9 kB
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>MochiVocab - Học từ vựng Anki</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Nunito:wght@500;600;700;800;900&family=Quicksand:wght@500;600;700;800&display=swap" rel="stylesheet">
<style>
:root {
--bg-gray: #EBEBEB;
--lv1: #EB5757;
--lv2: #FFCB08;
--lv3: #56CCF2;
--lv4: #2F80ED;
--lv5: #1B3A70;
--green-sheet: #22C55E;
--red-sheet: #EF4444;
--mochi-yellow: #FFCB08;
--mochi-orange: #F59E0B;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: 'Nunito', 'Quicksand', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
-webkit-tap-highlight-color: transparent;
}
body {
background-color: var(--bg-gray);
color: #1F2937;
min-height: 100vh;
display: flex;
flex-direction: column;
overflow-x: hidden;
position: relative;
}
/* Background Decorative White Clouds & Copyright */
.cloud-bg {
position: fixed;
inset: 60px 0 0 0;
pointer-events: none;
z-index: 0;
overflow: hidden;
}
.cloud-left-top {
position: absolute;
left: -60px;
top: 55px;
width: 310px;
height: 185px;
background: #F7F7F7;
border-radius: 120px;
}
.cloud-left-top::before {
content: '';
position: absolute;
top: -55px;
left: 50px;
width: 160px;
height: 160px;
background: #F7F7F7;
border-radius: 50%;
}
.cloud-left-bottom {
position: absolute;
left: 110px;
bottom: -40px;
width: 260px;
height: 160px;
background: #F7F7F7;
border-radius: 100px;
}
.cloud-right-bottom {
position: absolute;
right: -50px;
bottom: 30px;
width: 280px;
height: 220px;
background: #F7F7F7;
border-radius: 130px;
}
.cloud-right-bottom::before {
content: '';
position: absolute;
top: 50px;
left: -65px;
width: 140px;
height: 140px;
background: #F7F7F7;
border-radius: 50%;
}
.copyright-tag {
position: fixed;
left: 16px;
bottom: 18px;
font-size: 15px;
font-weight: 800;
color: #FF9F1C;
z-index: 1;
pointer-events: none;
}
.copyright-tag span {
font-size: 12px;
font-weight: 700;
}
/* Top Header Navigation (MochiVocab style) */
.top-navbar {
background: #FFFFFF;
height: 60px;
padding: 0 28px;
display: flex;
align-items: center;
justify-content: space-between;
border-bottom: 1px solid #E2E2E2;
position: sticky;
top: 0;
z-index: 100;
}
.brand-logo {
display: flex;
align-items: center;
cursor: pointer;
}
.brand-logo img {
height: 36px;
width: auto;
display: block;
}
.nav-tabs {
display: flex;
align-items: stretch;
height: 100%;
}
.nav-tab {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 3px;
width: 120px;
height: 100%;
cursor: pointer;
color: #222;
font-weight: 700;
font-size: 13px;
border: none;
background: transparent;
transition: background 0.15s;
}
.nav-tab:hover {
background: #F5F5F5;
}
.nav-tab.active {
background: #ECECEC;
}
.nav-tab img {
height: 24px;
width: auto;
object-fit: contain;
}
.nav-right {
display: flex;
align-items: center;
gap: 10px;
}
.deck-select-pill {
padding: 6px 12px;
border-radius: 99px;
border: 1.5px solid #E5E5E5;
font-size: 13px;
font-weight: 700;
color: #444;
background: #FAFAFA;
max-width: 195px;
outline: none;
cursor: pointer;
}
.sync-btn-pill {
padding: 6px 12px;
border-radius: 99px;
border: 1.5px solid #22C55E;
background: #EAFBF1;
color: #16A34A;
font-size: 12.5px;
font-weight: 800;
cursor: pointer;
white-space: nowrap;
}
.user-greeting {
font-size: 20px;
font-weight: 800;
color: #FFCB08;
}
/* Center White Column */
.center-column {
position: relative;
z-index: 2;
width: 100%;
max-width: 780px;
min-height: calc(100vh - 60px);
margin: 0 auto;
background: #FFFFFF;
box-shadow: 0 0 18px rgba(0, 0, 0, 0.04);
display: flex;
flex-direction: column;
}
.view-section {
display: none;
flex: 1;
flex-direction: column;
width: 100%;
}
.view-section.active {
display: flex;
}
/* ============================================================
VIEW 1: ÔN TẬP DASHBOARD (5-BAR VERTICAL CHART)
============================================================ */
.dashboard-wrap {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 36px 24px 48px;
}
.chart-stage {
width: 100%;
max-width: 580px;
padding-top: 20px;
}
.bars-row {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 24px;
align-items: end;
height: 280px;
padding: 0 14px;
}
.bar-col {
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-end;
height: 100%;
}
.bar-count-label {
font-size: 16px;
font-weight: 600;
color: #222;
margin-bottom: 8px;
white-space: nowrap;
}
.bar-count-label b {
font-weight: 800;
}
.bar-pillar {
width: 100%;
max-width: 86px;
min-height: 6px;
border-radius: 22px 22px 0 0;
transition: height 0.45s cubic-bezier(0.22, 1, 0.36, 1);
box-shadow: 2px -1px 8px rgba(0,0,0,0.06);
}
.bar-lv1 { background: var(--lv1); }
.bar-lv2 { background: var(--lv2); }
.bar-lv3 { background: var(--lv3); }
.bar-lv4 { background: var(--lv4); }
.bar-lv5 { background: var(--lv5); }
.chart-baseline {
width: 100%;
height: 9px;
background: #BDBDBD;
border-radius: 99px;
}
.chart-numbers {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 24px;
padding: 12px 14px 0;
text-align: center;
}
.chart-numbers span {
font-size: 24px;
font-weight: 800;
color: #111;
}
.due-text {
margin-top: 32px;
font-size: 19px;
font-weight: 700;
color: #111;
text-align: center;
}
.due-text b {
color: #FF9F1C;
font-weight: 800;
}
.btn-ontap-ngay {
margin-top: 24px;
width: 250px;
height: 54px;
border-radius: 999px;
border: none;
background: linear-gradient(90deg, #58CC02 0%, #1CA83B 100%);
color: #FFFFFF;
font-size: 18px;
font-weight: 800;
cursor: pointer;
box-shadow: 0 5px 0 #15822D;
transition: transform 0.1s, box-shadow 0.1s;
}
.btn-ontap-ngay:active {
transform: translateY(3px);
box-shadow: 0 2px 0 #15822D;
}
/* ============================================================
VIEW 2: TRANG HỌC / QUIZ (CHUẨN PRESET ANKI + GIAO DIỆN MOCHI)
============================================================ */
.quiz-wrap {
flex: 1;
display: flex;
flex-direction: column;
position: relative;
padding: 20px 36px 260px;
max-width: 640px;
width: 100%;
margin: 0 auto;
}
.quiz-top-bar {
display: flex;
align-items: center;
gap: 18px;
margin-bottom: 14px;
}
.quiz-close-btn {
background: none;
border: none;
font-size: 24px;
font-weight: 800;
color: #9CA3AF;
cursor: pointer;
line-height: 1;
padding: 4px 6px;
}
.quiz-close-btn:hover {
color: #333;
}
.quiz-progress-track {
flex: 1;
height: 13px;
background: #F1F5F9;
border-radius: 999px;
position: relative;
}
.quiz-progress-fill {
height: 100%;
background: linear-gradient(90deg, #F59E0B, #FBBF24);
border-radius: 999px;
width: 12%;
transition: width 0.3s ease;
}
.quiz-progress-mascot {
position: absolute;
top: 50%;
left: 12%;
transform: translate(-50%, -56%);
width: 44px;
height: auto;
transition: left 0.3s ease;
pointer-events: none;
z-index: 3;
}
/* 5 Anki Mode Switcher Pills */
.anki-mode-pills {
display: flex;
justify-content: center;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 16px;
}
.anki-mode-pill {
padding: 5px 11px;
border-radius: 99px;
border: 1.5px solid #E5E7EB;
background: #F8FAFC;
color: #64748B;
font-size: 12px;
font-weight: 700;
cursor: pointer;
transition: all 0.15s;
}
.anki-mode-pill.active {
background: #FFFBEB;
border-color: #F59E0B;
color: #B45309;
}
.mochi-question-title {
font-size: 16px;
font-weight: 700;
color: #8E8E93;
margin-bottom: 20px;
text-align: center;
}
/* Audio Speaker + Snail Row */
.mochi-audio-group {
display: flex;
align-items: center;
justify-content: center;
gap: 16px;
margin-bottom: 24px;
}
.circle-audio-btn {
width: 88px;
height: 88px;
border-radius: 50%;
background: #FFFFFF;
border: 2.5px solid #E2E8F0;
box-shadow: 0 5px 0 #E2E8F0;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: transform 0.12s, border-color 0.15s;
}
.circle-audio-btn:hover {
border-color: #F59E0B;
}
.circle-audio-btn:active {
transform: translateY(3px);
}
.circle-audio-btn svg {
width: 44px;
height: 44px;
fill: #FFCB08;
}
.circle-snail-btn {
width: 56px;
height: 56px;
border-radius: 50%;
background: #FFFFFF;
border: 2px solid #E2E8F0;
box-shadow: 0 4px 0 #E2E8F0;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: transform 0.12s, border-color 0.15s;
}
.circle-snail-btn:hover {
border-color: #F59E0B;
}
.circle-snail-btn:active {
transform: translateY(2px);
}
.circle-snail-btn img {
width: 32px;
height: 32px;
object-fit: contain;
}
/* Prompt Text & Sentence Card (Exact CSS from Admin Phuc Anki Preset) */
.mochi-prompt-text {
font-size: 23px;
font-weight: 800;
color: #1E293B;
text-align: center;
margin-bottom: 22px;
line-height: 1.35;
}
.mochi-sentence-card {
width: 100%;
background: #FFFFFF;
border: 2px solid #E2E8F0;
border-radius: 20px;
padding: 22px 20px;
margin-bottom: 22px;
font-size: 19px;
font-weight: 600;
line-height: 1.5;
color: #1E293B;
text-align: center;
box-shadow: 0 2px 10px rgba(0,0,0,0.03);
}
u.mochi-target-highlight {
text-decoration: underline;
text-decoration-color: #F59E0B;
text-decoration-thickness: 3px;
text-underline-offset: 4px;
color: #B45309;
font-weight: 800;
}
.mochi-sentence-blank {
display: inline-block;
min-width: 90px;
height: 28px;
border-bottom: 3px solid #F59E0B;
margin: 0 4px;
vertical-align: middle;
}
/* SPELLING LETTER SLOTS (Exact match with Anki 1_typing_word) */
.mochi-spelling-card {
width: 100%;
min-height: 90px;
background: #FFFFFF;
border: 2px solid #E2E8F0;
border-radius: 20px;
padding: 20px 14px 24px;
margin-bottom: 16px;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
gap: 8px 10px;
cursor: text;
}
.mochi-slot-wrap {
display: inline-flex;
flex-direction: column;
align-items: center;
position: relative;
min-width: 24px;
}
.mochi-slot-char {
font-size: 24px;
font-weight: 800;
color: #1E293B;
height: 32px;
line-height: 32px;
text-align: center;
}
.mochi-slot-char.hint {
color: #CBD5E1 !important;
}
.mochi-slot-line {
width: 100%;
height: 3px;
background: #CBD5E1;
border-radius: 2px;
transition: all 0.15s;
}
.mochi-slot-wrap.active .mochi-slot-line {
background: #F59E0B;
}
.mochi-slot-pointer {
position: absolute;
bottom: -16px;
color: #F59E0B;
font-size: 13px;
display: none;
}
.mochi-slot-wrap.active .mochi-slot-pointer {
display: block;
}
.mochi-slot-wrap.slot-good .mochi-slot-char {
color: #22C55E !important;
}
.mochi-slot-wrap.slot-good .mochi-slot-line {
background: #22C55E !important;
}
.mochi-slot-wrap.slot-bad .mochi-slot-char {
color: #EF4444 !important;
}
.mochi-slot-wrap.slot-bad .mochi-slot-line {
background: #EF4444 !important;
}
/* ANKI #typeans INPUT & DIFF DISPLAY */
#typeans {
width: 100%;
font-size: 19px;
font-weight: 700;
text-align: center;
padding: 14px 18px;
border: 2px solid #28C76F;
border-radius: 16px;
outline: none;
background: #FFFFFF;
color: #1E293B;
margin-bottom: 12px;
transition: border-color 0.2s, box-shadow 0.2s;
}
#typeans:focus {
border-color: #28C76F;
box-shadow: 0 0 0 3px rgba(40, 199, 111, 0.14);
}
#typeans.hidden-for-slots {
position: absolute;
opacity: 0;
width: 1px;
height: 1px;
padding: 0;
margin: 0;
border: none;
pointer-events: none;
box-shadow: none;
}
.typeans-diff-box {
width: 100%;
padding: 14px 18px;
border: 2px solid #E2E8F0;
border-radius: 16px;
background: #F8FAFC;
text-align: center;
font-size: 20px;
font-weight: 800;
margin-bottom: 14px;
display: none;
letter-spacing: 0.5px;
}
.typeGood { color: #22C55E; font-weight: 800; }
.typeBad { color: #EF4444; text-decoration: line-through; font-weight: 800; }
.typeMissed { color: #F59E0B; font-weight: 800; }
/* MULTIPLE CHOICE OPTIONS LIST (Exact match with Anki 2, 3, 4) */
.mochi-options-list {
width: 100%;
display: flex;
flex-direction: column;
gap: 12px;
margin-bottom: 22px;
}
.mochi-option-btn {
background: #FFFFFF;
border: 2px solid #E5E7EB;
border-radius: 18px;
padding: 15px 20px;
display: flex;
align-items: center;
gap: 16px;
cursor: pointer;
box-shadow: 0 2px 6px rgba(0,0,0,0.02);
transition: all 0.15s;
width: 100%;
text-align: left;
}
.mochi-option-btn:hover {
border-color: #CBD5E1;
}
.mochi-option-btn.selected {
border-color: #F59E0B !important;
box-shadow: 0 0 0 1px #F59E0B !important;
background: #FFFFFF !important;
}
.mochi-option-btn.selected .mochi-opt-num {
border-color: #F59E0B !important;
color: #F59E0B !important;
}
.mochi-option-btn.correct-choice {
background: #22C55E !important;
border-color: #22C55E !important;
color: #FFFFFF !important;
}
.mochi-option-btn.correct-choice .mochi-opt-num {
border-color: #FFFFFF !important;
color: #FFFFFF !important;
}
.mochi-option-btn.correct-choice .mochi-opt-text {
color: #FFFFFF !important;
}
.mochi-option-btn.wrong-choice {
background: #EF4444 !important;
border-color: #EF4444 !important;
color: #FFFFFF !important;
}
.mochi-option-btn.wrong-choice .mochi-opt-num {
border-color: #FFFFFF !important;
color: #FFFFFF !important;
}
.mochi-option-btn.wrong-choice .mochi-opt-text {
color: #FFFFFF !important;
}
.mochi-opt-num {
width: 32px;
height: 32px;
border-radius: 50%;
border: 1.5px solid #CBD5E1;
display: flex;
align-items: center;
justify-content: center;
font-size: 15px;
font-weight: 700;
color: #64748B;
flex-shrink: 0;
transition: all 0.15s;
}
.mochi-opt-text {
font-size: 17px;
font-weight: 700;
color: #334155;
line-height: 1.4;
flex: 1;
}
/* French Accent Bar */
.accent-pills {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 6px;
margin-bottom: 18px;
}
.accent-pill {
padding: 5px 11px;
border-radius: 99px;
border: 1px solid #E2E8F0;
background: #F8FAFC;
font-size: 14px;
font-weight: 700;
color: #334155;
cursor: pointer;
}
.accent-pill:hover {
background: #FFFBEB;
border-color: #F59E0B;
}
/* Bottom Quiz Actions */
.mochi-actions {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
margin-top: 6px;
}
.mochi-btn-check {
width: 100%;
max-width: 230px;
padding: 14px 28px;
border-radius: 9999px;
border: none;
font-size: 16.5px;
font-weight: 800;
cursor: pointer;
background: #E2E8F0;
color: #94A3B8;
transition: all 0.15s;
}
.mochi-btn-check.ready {
background: #22C55E !important;
color: #FFFFFF !important;
box-shadow: 0 4px 0 #15822D !important;
}
.mochi-link-skip {
background: none;
border: none;
font-size: 14.5px;
font-weight: 700;
color: #64748B;
text-decoration: underline;
cursor: pointer;
padding: 4px;
}
/* ============================================================
MOCHI RESULT BOTTOM DRAWER (0MS INSTANT + MASCOT + EASE 1..4)
============================================================ */
.result-sheet-wrapper {
position: fixed;
left: 50%;
transform: translateX(-50%);
bottom: 0;
width: 100%;
max-width: 680px;
z-index: 200;
display: none;
flex-direction: column;
}
.result-sheet-wrapper.show {
display: flex;
}
.sheet-mascot {
width: 118px;
height: auto;
margin-left: 24px;
margin-bottom: -10px;
position: relative;
z-index: 202;
pointer-events: none;
}
.result-sheet-box {
border-radius: 26px 26px 0 0;
padding: 24px 28px 24px;
color: #FFFFFF;
position: relative;
box-shadow: 0 -6px 24px rgba(0,0,0,0.16);
display: flex;
flex-direction: column;
}
.result-sheet-box.correct {
background: var(--green-sheet);
}
.result-sheet-box.wrong {
background: var(--red-sheet);
}
.sheet-top-FloatBtns {
position: absolute;
top: -20px;
right: 24px;
display: flex;
gap: 10px;
z-index: 203;
}
.sheet-float-circle {
width: 42px;
height: 42px;
border-radius: 50%;
border: 2px solid rgba(255, 255, 255, 0.8);
display: flex;
align-items: center;
justify-content: center;
color: #FFFFFF;
cursor: pointer;
font-size: 16px;
}
.result-sheet-box.correct .sheet-float-circle { background: var(--green-sheet); }
.result-sheet-box.wrong .sheet-float-circle { background: var(--red-sheet); }
.sheet-main-row {
display: flex;
align-items: flex-start;
gap: 18px;
}
.sheet-speaker-btn {
width: 52px;
height: 52px;
border-radius: 50%;
background: #FFFFFF;
border: none;
box-shadow: 0 3px 8px rgba(0, 0, 0, 0.14);
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
flex-shrink: 0;
}
.sheet-speaker-btn svg {
width: 28px;
height: 28px;
fill: #F59E0B;
}
.sheet-word-details {
flex: 1;
}
.sheet-word-title {
font-size: 22px;
font-weight: 800;
margin-bottom: 4px;
line-height: 1.25;
}
.sheet-ipa {
font-size: 15.5px;
font-weight: 600;
opacity: 0.95;
margin-bottom: 6px;
}
.sheet-meaning {
font-size: 16.5px;
font-weight: 700;
margin-bottom: 10px;
}
.sheet-example-box {
background: rgba(255, 255, 255, 0.14);
padding: 11px 14px;
border-radius: 14px;
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 6px;
}
.sheet-example-speaker {
width: 38px;
height: 38px;
border-radius: 50%;
background: #FFFFFF;
border: none;
color: #F59E0B;
font-size: 18px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
flex-shrink: 0;
box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}
.sheet-example-trans {
font-size: 13.5px;
font-style: italic;
opacity: 0.92;
margin-top: 3px;
}
.sheet-extra-meta {
font-size: 13px;
opacity: 0.92;
margin-top: 4px;
}
.sheet-bottom-controls {
margin-top: 14px;
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
}
.btn-tiep-tuc {
width: 240px;
height: 48px;
border-radius: 999px;
background: #FFFFFF;
color: #16A34A;
border: none;
font-size: 16.5px;
font-weight: 800;
cursor: pointer;
box-shadow: 0 4px 10px rgba(0,0,0,0.12);
}
.result-sheet-box.wrong .btn-tiep-tuc {
color: #DC2626;
}
.anki-ease-shortcuts {
display: flex;
gap: 8px;
flex-wrap: wrap;
justify-content: center;
}
.anki-ease-btn {
background: rgba(255, 255, 255, 0.18);
border: 1px solid rgba(255, 255, 255, 0.45);
color: #FFFFFF;
padding: 4px 10px;
border-radius: 99px;
font-size: 12px;
font-weight: 700;
cursor: pointer;
}
.anki-ease-btn:hover {
background: rgba(255, 255, 255, 0.32);
}
/* ============================================================
VIEW 3: SỔ TAY (NOTEBOOK SCREEN)
============================================================ */
.notebook-wrap {
padding: 22px 32px 40px;
display: flex;
flex-direction: column;
flex: 1;
}
.nb-levels-header {
display: grid;
grid-template-columns: repeat(5, 1fr);
text-align: center;
align-items: end;
margin-bottom: 6px;
}
.nb-level-tab {
cursor: pointer;
padding: 6px 4px;
user-select: none;
}
.nb-level-title {
font-size: 15px;
font-weight: 800;
color: #BDBDBD;
}
.nb-level-tab.active .nb-level-title {
color: #757575;
}
.nb-level-stars {
font-size: 12px;
letter-spacing: 1px;
color: #757575;
height: 16px;
margin-top: 2px;
visibility: hidden;
}
.nb-level-tab.active .nb-level-stars {
visibility: visible;
}
.nb-level-stars .filled-star {
color: #FFCB08;
}
.nb-color-bar {
display: grid;
grid-template-columns: repeat(5, 1fr);
align-items: center;
margin-bottom: 28px;
}
.nb-bar-seg {
height: 5px;
cursor: pointer;
transition: height 0.15s;
}
.nb-bar-seg.active {
height: 11px;
border-radius: 99px;
}
.nb-bar-seg.seg-1 { background: var(--lv1); }
.nb-bar-seg.seg-2 { background: var(--lv2); }
.nb-bar-seg.seg-3 { background: var(--lv3); }
.nb-bar-seg.seg-4 { background: var(--lv4); }
.nb-bar-seg.seg-5 { background: var(--lv5); }
.nb-search-row {
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
margin-bottom: 28px;
}
.nb-search-pill {
display: flex;
align-items: center;
background: #EEEEEE;
border-radius: 999px;
padding: 5px 6px 5px 22px;
width: 100%;
max-width: 450px;
}
.nb-search-pill input {
flex: 1;
border: none;
background: transparent;
font-size: 14px;
font-weight: 700;
color: #333;
outline: none;
}
.nb-search-btn {
background: #219653;
color: #FFFFFF;
border: none;
border-radius: 999px;
padding: 8px 18px;
font-size: 13.5px;
font-weight: 800;
cursor: pointer;
}
.nb-save-btn {
background: #F2F2F2;
color: #888888;
border: none;
border-radius: 999px;
padding: 11px 22px;
font-size: 13.5px;
font-weight: 800;
}
.nb-word-list {
display: flex;
flex-direction: column;
gap: 14px;
padding: 0 12px;
}
.nb-word-row {
display: grid;
grid-template-columns: 34px 1.2fr 0.7fr 1.4fr;
align-items: center;
gap: 12px;
padding: 10px 4px;
border-bottom: 1px solid #F3F3F3;
cursor: pointer;
}
.nb-word-row:hover {
background: #FAFAFA;
}
.nb-check-icon {
width: 22px;
height: 22px;
border-radius: 50%;
border: 2px solid #27AE60;
color: #27AE60;
display: flex;
align-items: center;
justify-content: center;
font-size: 12px;
font-weight: 900;
}
.nb-word-text { font-size: 16.5px; font-weight: 800; color: #111; }
.nb-word-ipa { font-size: 13.5px; font-weight: 600; color: #27AE60; }
.nb-col-pos { font-size: 14px; font-weight: 800; color: #111; }
.nb-col-meaning { font-size: 14px; font-weight: 600; color: #222; line-height: 1.35; }
@media (max-width: 680px) {
.top-navbar { padding: 0 10px; }
.nav-tab { width: 64px; font-size: 11px; }
.quiz-wrap { padding: 16px 14px 260px; }
.nb-word-row { grid-template-columns: 28px 1.1fr 0.5fr 1.1fr; }
}
</style>
</head>
<body>
<div class="cloud-bg">
<div class="cloud-left-top"></div>
<div class="cloud-left-bottom"></div>
<div class="cloud-right-bottom"></div>
</div>
<div class="copyright-tag">© MochiVocab <span>ver5.0.1</span></div>
<!-- Top Navigation Header -->
<header class="top-navbar">
<div class="brand-logo" onclick="switchTab('ontap')">
<img src="/mochi_logo.png" alt="MOCHIVOCAB" />
</div>
<nav class="nav-tabs">
<button class="nav-tab active" id="tabBtn-ontap" onclick="switchTab('ontap')">
<img src="/assets/nav_ontap.png" alt="Ôn tập" />
<span>Ôn tập</span>
</button>
<button class="nav-tab" id="tabBtn-new" onclick="startQuizSession('new')">
<img src="/assets/nav_new.png" alt="Học từ mới" />
<span>Học từ mới</span>
</button>
<button class="nav-tab" id="tabBtn-notebook" onclick="switchTab('notebook')">
<img src="/assets/nav_notebook.png" alt="Sổ tay" />
<span>Sổ tay</span>
</button>
<button class="nav-tab" id="tabBtn-rank" onclick="switchTab('notebook')">
<img src="/assets/nav_rank.png" alt="Rank" />
<span>Rank</span>
</button>
<button class="nav-tab" id="tabBtn-hub" onclick="switchTab('ontap')">
<img src="/assets/nav_hub.png" alt="MochiHub" />
<span>MochiHub</span>
</button>
</nav>
<div class="nav-right">
<select id="deckFilter" class="deck-select-pill" onchange="onDeckChange()">
<option value="french2">french2</option>
<option value="">Tất cả bộ thẻ Anki</option>
</select>
<button id="btnSyncAnki" class="sync-btn-pill" onclick="syncWithAnki()" title="Đồng bộ dữ liệu 2 chiều với Anki">
🔄 Đồng bộ Anki
</button>
<span class="user-greeting">hi</span>
</div>
</header>
<main class="center-column">
<!-- ============================================================
SECTION 1: ÔN TẬP (BIỂU ĐỒ 5 CỘT TỪ DỮ LIỆU ANKI)
============================================================ -->
<section id="view-ontap" class="view-section active">
<div class="dashboard-wrap">
<div class="chart-stage">
<div class="bars-row">
<div class="bar-col">
<div class="bar-count-label"><b id="lvCount1">0</b> từ</div>
<div class="bar-pillar bar-lv1" id="lvBar1" style="height: 24px;"></div>
</div>
<div class="bar-col">
<div class="bar-count-label"><b id="lvCount2">0</b> từ</div>
<div class="bar-pillar bar-lv2" id="lvBar2" style="height: 8px;"></div>
</div>
<div class="bar-col">
<div class="bar-count-label"><b id="lvCount3">0</b> từ</div>
<div class="bar-pillar bar-lv3" id="lvBar3" style="height: 8px;"></div>
</div>
<div class="bar-col">
<div class="bar-count-label"><b id="lvCount4">0</b> từ</div>
<div class="bar-pillar bar-lv4" id="lvBar4" style="height: 8px;"></div>
</div>
<div class="bar-col">
<div class="bar-count-label"><b id="lvCount5">0</b> từ</div>
<div class="bar-pillar bar-lv5" id="lvBar5" style="height: 8px;"></div>
</div>
</div>
<div class="chart-baseline"></div>
<div class="chart-numbers">
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
</div>
</div>
<div class="due-text">
Đến giờ ôn tập: <b id="dueTotalCount">0</b> từ
<div id="newTotalInfo" style="font-size:14px; color:#757575; font-weight:700; margin-top:6px;"></div>
</div>
<button class="btn-ontap-ngay" onclick="startQuizSession('due')">
Ôn tập ngay
</button>
</div>
</section>
<!-- ============================================================
SECTION 2: QUIZ SESSION (ĐỒNG BỘ 100% LOGIC 5 THẺ ANKI)
============================================================ -->
<section id="view-quiz" class="view-section">
<div class="quiz-wrap" id="quizWorkspace">
<!-- Progress Bar -->
<div class="quiz-top-bar">
<button class="quiz-close-btn" onclick="switchTab('ontap')" title="Thoát">✕</button>
<div class="quiz-progress-track">
<div class="quiz-progress-fill" id="quizProgressFill"></div>
<img src="/assets/mochi_head.png" class="quiz-progress-mascot" id="quizProgressMascot" alt="Mochi" />
</div>
<span id="quizCounterBadge" style="font-size:14px; font-weight:800; color:#F59E0B; white-space:nowrap;">1 / 200</span>
</div>
<!-- 5 Anki Card Template Switcher Pills -->
<div class="anki-mode-pills">
<button type="button" class="anki-mode-pill" id="pillMode-1_typing_word" onclick="setQuizSubMode('1_typing_word')">1. Điền từ</button>
<button type="button" class="anki-mode-pill" id="pillMode-2_review_word" onclick="setQuizSubMode('2_review_word')">2. Nghe chọn nghĩa</button>
<button type="button" class="anki-mode-pill" id="pillMode-3_reading_example" onclick="setQuizSubMode('3_reading_example')">3. Đọc câu chọn nghĩa</button>
<button type="button" class="anki-mode-pill" id="pillMode-4_listening_example" onclick="setQuizSubMode('4_listening_example')">4. Nghe chọn âm / Điền câu</button>
<button type="button" class="anki-mode-pill" id="pillMode-5_dictation" onclick="setQuizSubMode('5_dictation')">5. Nghe và viết lại</button>
</div>
<div class="mochi-question-title" id="quizModeTitle">Điền từ</div>
<!-- Audio Group (Speaker + Snail, used in 2_review_word & 5_dictation) -->
<div class="mochi-audio-group" id="sharedAudioControls" style="display: none;">
<button type="button" class="circle-audio-btn" onclick="playWordAudio(1.0)" title="Nghe phát âm chuẩn">
<svg viewBox="0 0 24 24">
<path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"/>
</svg>
</button>
<button type="button" class="circle-snail-btn" onclick="playWordAudio(0.7)" title="Phát chậm 0.7x (Ốc sên)">
<img src="/assets/snail.png" alt="Slow" />
</button>
</div>
<!-- Prompt Meaning for 1_typing_word -->
<div class="mochi-prompt-text" id="typingPromptText" style="display: none;"></div>
<!-- Spelling Letter Slots Card for 1_typing_word (Exact Anki logic) -->
<div class="mochi-spelling-card" id="spellingSlotsCard" onclick="focusAnkiInput()" style="display: none;"></div>
<!-- Real Anki #typeans Input Box (shared by 1_typing_word & 5_dictation for 100% smooth IME/French typing) -->
<div id="typeansWrap" style="width: 100%; display: none;">
<input type="text" id="typeans" placeholder="Gõ từ vựng tiếng Pháp..." autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />
<div class="typeans-diff-box" id="typeansDiffBox"></div>
</div>
<!-- Quick French Accents Bar (for 1_typing_word & 5_dictation) -->
<div class="accent-pills" id="frenchAccentsBar" style="display: none;">
<button type="button" class="accent-pill" onclick="insertFrenchChar('é')">é</button>
<button type="button" class="accent-pill" onclick="insertFrenchChar('è')">è</button>
<button type="button" class="accent-pill" onclick="insertFrenchChar('ê')">ê</button>
<button type="button" class="accent-pill" onclick="insertFrenchChar('ë')">ë</button>
<button type="button" class="accent-pill" onclick="insertFrenchChar('à')">à</button>
<button type="button" class="accent-pill" onclick="insertFrenchChar('â')">â</button>
<button type="button" class="accent-pill" onclick="insertFrenchChar('ù')">ù</button>
<button type="button" class="accent-pill" onclick="insertFrenchChar('û')">û</button>
<button type="button" class="accent-pill" onclick="insertFrenchChar('î')">î</button>
<button type="button" class="accent-pill" onclick="insertFrenchChar('ï')">ï</button>
<button type="button" class="accent-pill" onclick="insertFrenchChar('ô')">ô</button>
<button type="button" class="accent-pill" onclick="insertFrenchChar('ç')">ç</button>
<button type="button" class="accent-pill" onclick="insertFrenchChar('œ')">œ</button>
<button type="button" class="accent-pill" onclick="insertFrenchChar('\'')">'</button>
</div>
<!-- Sentence Card & Multiple Choice Options (for 2_review_word, 3_reading_example, 4_listening_example) -->
<div id="mcQuizArea" style="width: 100%; display: none;">
<div class="mochi-sentence-card" id="mcSentenceCard" style="display: none;"></div>
<div class="mochi-options-list" id="mcOptionsList"></div>
</div>
<!-- Bottom Action Buttons -->
<div class="mochi-actions">
<button type="button" class="mochi-btn-check" id="btnCheckQuiz" onclick="submitCurrentAnswer()">Kiểm tra</button>
<button type="button" class="mochi-link-skip" onclick="giveUpCurrentCard()">Mình không nhớ từ này</button>
<button type="button" class="mochi-link-skip" id="btnSkipAudioLink" style="display:none;" onclick="setQuizSubMode('1_typing_word')">Tạm thời không nghe được</button>
</div>
<!-- Result Bottom Drawer (Exact Anki Back Side + Mochi Mascot) -->
<div class="result-sheet-wrapper" id="resultSheetWrapper">
<img src="/assets/mochi_happy.png" class="sheet-mascot" id="sheetMascotImg" alt="Mochi" />
<div class="result-sheet-box correct" id="resultSheetBox">
<div class="sheet-top-FloatBtns">
<button type="button" class="sheet-float-circle" title="Đổi dạng câu hỏi" onclick="cycleAnkiMode()">🔖</button>
<button type="button" class="sheet-float-circle" title="Thu nhỏ / Đóng" onclick="toggleDrawer()">⌵</button>
</div>
<div class="sheet-main-row">
<button type="button" class="sheet-speaker-btn" onclick="playWordAudio(1.0)" title="Nghe từ vựng">
<svg viewBox="0 0 24 24">
<path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"/>
</svg>
</button>
<div class="sheet-word-details">
<div class="sheet-word-title" id="sheetWordTitle"></div>
<div class="sheet-ipa" id="sheetIpa"></div>
<div class="sheet-meaning" id="sheetMeaning"></div>
<div class="sheet-example-box" id="sheetExampleRow">
<button type="button" class="sheet-example-speaker" id="sheetExAudioBtn" onclick="playExampleAudio()" title="Nghe câu ví dụ">🔊</button>
<div style="flex: 1;">
<div id="sheetExampleText"></div>
<div class="sheet-example-trans" id="sheetExampleTrans"></div>
</div>
</div>
<div class="sheet-extra-meta" id="sheetExtraMeta"></div>
</div>
</div>
<div class="sheet-bottom-controls">
<button type="button" class="btn-tiep-tuc" id="btnTiepTuc" onclick="onContinueClick()">Tiếp tục (Enter)</button>
<div class="anki-ease-shortcuts">
<button type="button" class="anki-ease-btn" onclick="answerEase(1)">[1] Học lại</button>
<button type="button" class="anki-ease-btn" onclick="answerEase(2)">[2] Khó</button>
<button type="button" class="anki-ease-btn" onclick="answerEase(3)">[3] Nhớ tốt</button>
<button type="button" class="anki-ease-btn" onclick="answerEase(4)">[4] Rất dễ</button>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- ============================================================
SECTION 3: SỔ TAY (DANH SÁCH TỪ VỰNG TRONG ANKI THEO 5 CẤP ĐỘ)
============================================================ -->
<section id="view-notebook" class="view-section">
<div class="notebook-wrap">
<div class="nb-levels-header">
<div class="nb-level-tab active" id="nbTab1" onclick="selectNotebookLevel(1)">
<div class="nb-level-title">Cấp độ 1</div>
<div class="nb-level-stars"><span class="filled-star">★</span>☆☆☆☆</div>
</div>
<div class="nb-level-tab" id="nbTab2" onclick="selectNotebookLevel(2)">
<div class="nb-level-title">Cấp độ 2</div>
<div class="nb-level-stars"><span class="filled-star">★★</span>☆☆☆</div>
</div>
<div class="nb-level-tab" id="nbTab3" onclick="selectNotebookLevel(3)">
<div class="nb-level-title">Cấp độ 3</div>
<div class="nb-level-stars"><span class="filled-star">★★★</span>☆☆</div>
</div>
<div class="nb-level-tab" id="nbTab4" onclick="selectNotebookLevel(4)">
<div class="nb-level-title">Cấp độ 4</div>
<div class="nb-level-stars"><span class="filled-star">★★★★</span>☆</div>
</div>
<div class="nb-level-tab" id="nbTab5" onclick="selectNotebookLevel(5)">
<div class="nb-level-title">Cấp độ 5</div>
<div class="nb-level-stars"><span class="filled-star">★★★★★</span></div>
</div>
</div>
<div class="nb-color-bar">
<div class="nb-bar-seg seg-1 active" id="nbSeg1" onclick="selectNotebookLevel(1)"></div>
<div class="nb-bar-seg seg-2" id="nbSeg2" onclick="selectNotebookLevel(2)"></div>
<div class="nb-bar-seg seg-3" id="nbSeg3" onclick="selectNotebookLevel(3)"></div>
<div class="nb-bar-seg seg-4" id="nbSeg4" onclick="selectNotebookLevel(4)"></div>
<div class="nb-bar-seg seg-5" id="nbSeg5" onclick="selectNotebookLevel(5)"></div>
</div>
<div class="nb-search-row">
<div class="nb-search-pill">
<input type="text" id="nbSearchInput" placeholder="Gõ vào đây từ bạn muốn tìm" oninput="renderNotebookList()" />
<button class="nb-search-btn" onclick="renderNotebookList()">Search</button>
</div>
<button class="nb-save-btn">Save</button>
</div>
<div class="nb-word-list" id="nbWordList"></div>
</div>
</section>
</main>
<audio id="audioPlayer"></audio>
<script>
let allCards = [];
let filteredCards = [];
let studyQueue = [];
let currentIndex = 0;
let currentCard = null;
const ANKI_MODES = [
'1_typing_word',
'2_review_word',
'3_reading_example',
'4_listening_example',
'5_dictation'
];
let quizSubMode = '1_typing_word';
let isSheetOpen = false;
let isUserCorrect = false;
let currentNotebookLevel = 1;
// State for 1_typing_word slots (exact port from Admin Phuc Anki template)
let typingTargetChars = [];
let typingTotalLetters = 0;
let typingHintIdx1 = -1;
let typingHintIdx2 = -1;
// State for Multiple Choice modes (2_review_word, 3_reading_example, 4_listening_example)
let currentMcOptions = []; // [{ text, audio, isCorrect }]
let chosenMcNumber = null; // 1..4
const IS_CLOUD_SPACE = window.location.hostname.endsWith('.hf.space') || window.location.hostname.includes('huggingface.co');
const IS_ENGLISH_SPACE = window.location.hostname.includes('english') || window.location.search.includes('lang=en');
const HF_DATASET_REPO = IS_ENGLISH_SPACE ? 'hung9066/mochi-english-anki-data' : 'hung9066/mochi-french-anki-data';
const HF_DATASET_BASE = `https://huggingface.co/datasets/${HF_DATASET_REPO}/resolve/main`;
const DEFAULT_DECK_NAME = IS_ENGLISH_SPACE ? 'hoc_lom' : 'french2';
function getMediaUrl(filename) {
if (!filename) return '';
if (IS_CLOUD_SPACE) {
return `${HF_DATASET_BASE}/media/${encodeURIComponent(filename)}`;
}
return '/media/' + encodeURIComponent(filename);
}
function applyCloudLocalStorageOverrides(cardsList) {
try {
const raw = localStorage.getItem('mochi_cloud_srs_map');
if (!raw) return;
const map = JSON.parse(raw);
cardsList.forEach(c => {
if (map[c.nid]) {
c.level = map[c.nid].level;
c.next_review = map[c.nid].next_review;
c.ivl = map[c.nid].ivl;
c.ease = map[c.nid].ease;
c.reps = map[c.nid].reps;
c.lapses = map[c.nid].lapses;
}
});
} catch (e) {}
}
async function initApp(forceFresh = false) {
try {
let data = null;
if (!IS_CLOUD_SPACE) {
try {
const res = await fetch('/api/cards');
if (res.ok) data = await res.json();
} catch (e) {}
}
if (!data && !forceFresh) {
try {
const res = await fetch('/cards_data.json');
if (res.ok) data = await res.json();
} catch (e) {}
}
if (!data) {
try {
const res = await fetch(`${HF_DATASET_BASE}/cards_data.json` + (forceFresh ? `?t=${Date.now()}` : ''));
if (res.ok) data = await res.json();
} catch (e) {}
}
allCards = data.cards || [];
window.ankiDeckStats = data.deck_stats || {};
if (IS_CLOUD_SPACE) {
applyCloudLocalStorageOverrides(allCards);
}
const nowInit = Date.now() / 1000;
let totalDueAll = 0;
let totalNewAll = 0;
for (let i = 0; i < allCards.length; i++) {
const c = allCards[i];
const lv = c.level || 0;
if (lv > 0 && (!c.next_review || c.next_review <= nowInit)) totalDueAll++;
else if (!lv || c.has_anki_new) totalNewAll++;
}
const deckSel = document.getElementById('deckFilter');
const prevVal = deckSel.getAttribute('data-user-selected') ? deckSel.value : (deckSel.value || DEFAULT_DECK_NAME);
const allBadge = totalDueAll > 0 ? `${totalDueAll} cần ôn` : `${Math.min(200, totalNewAll)} học tiếp`;
deckSel.innerHTML = `<option value="">Tất cả bộ thẻ Anki (${allBadge})</option>`;
(data.decks || []).forEach(d => {
const prefix = d + '::';
let dDue = 0;
let dNew = 0;
for (let i = 0; i < allCards.length; i++) {
const c = allCards[i];
if (c.deck === d || (c.deck && c.deck.startsWith(prefix))) {
const lv = c.level || 0;
if (lv > 0 && (!c.next_review || c.next_review <= nowInit)) dDue++;
else if (!lv || c.has_anki_new) dNew++;
}
}
const dStat = (window.ankiDeckStats && window.ankiDeckStats[d]) || null;
let badgeText = '';
if (dDue > 0) {
badgeText = `${dDue} cần ôn`;
} else if (dStat && (dStat.new_count + dStat.learn_count + dStat.review_count) > 0) {
badgeText = `${dStat.new_count + dStat.learn_count + dStat.review_count} học tiếp`;
} else if (dNew > 0) {
badgeText = `${Math.min(200, dNew)} học tiếp`;
} else {
badgeText = '0 cần ôn';
}
const opt = document.createElement('option');
opt.value = d;
opt.textContent = `${d.replace(/::/g, ' ▸ ')} (${badgeText})`;
deckSel.appendChild(opt);
});
if (prevVal === '' || (data.decks || []).includes(prevVal)) {
deckSel.value = prevVal;
} else if ((data.decks || []).includes(DEFAULT_DECK_NAME)) {
deckSel.value = DEFAULT_DECK_NAME;
}
applyDeckFilter();
} catch (e) {
console.error('Failed to load Anki cards:', e);
}
}
async function pushCloudReviewsToHF(interactivePrompt = false) {
try {
const savedRaw = localStorage.getItem('mochi_cloud_srs_v1');
if (!savedRaw || savedRaw === '{}') return true;
let token = localStorage.getItem('mochi_hf_token') || '';
if (!token && interactivePrompt) {
const inp = window.prompt('Nhập Hugging Face Token (hf_...) một lần duy nhất để đồng bộ kết quả ôn tập từ Web Cloud về Anki máy tính:');
if (inp && inp.trim().startsWith('hf_')) {
token = inp.trim();
localStorage.setItem('mochi_hf_token', token);
}
}
if (!token) return false;
// Merge with existing cloud_reviews.json on HF if present
let remoteReviews = {};
try {
const r = await fetch(`${HF_DATASET_BASE}/cloud_reviews.json?t=${Date.now()}`);
if (r.ok) remoteReviews = await r.json();
} catch (e) {}
const localReviews = JSON.parse(savedRaw || '{}');
const merged = Object.assign({}, remoteReviews, localReviews);
const jsonBytes = new TextEncoder().encode(JSON.stringify(merged));
let binary = '';
for (let i = 0; i < jsonBytes.length; i++) binary += String.fromCharCode(jsonBytes[i]);
const b64 = btoa(binary);
const body = JSON.stringify({ key: 'header', value: { summary: 'Sync web reviews to Anki' } }) + '\n' +
JSON.stringify({ key: 'file', value: { content: b64, path: 'cloud_reviews.json', encoding: 'base64' } }) + '\n';
const commitRes = await fetch(`https://huggingface.co/api/datasets/${HF_DATASET_REPO}/commit/main`, {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/x-ndjson'
},
body: body
});
return commitRes.ok;
} catch (e) {
console.error('Cloud review push error:', e);
return false;
}
}
async function syncWithAnki() {
const btn = document.getElementById('btnSyncAnki');
btn.textContent = '⏳ Đang đồng bộ...';
try {
if (!IS_CLOUD_SPACE) {
await fetch('/api/sync', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ force: false })
});
} else {
await pushCloudReviewsToHF(true);
}
await initApp();
btn.textContent = '✓ Đã đồng bộ Anki';
setTimeout(() => { btn.textContent = '🔄 Đồng bộ Anki'; }, 2000);
} catch (e) {
btn.textContent = '🔄 Đồng bộ Anki';
}
}
function onDeckChange() {
const deckSel = document.getElementById('deckFilter');
if (deckSel) deckSel.setAttribute('data-user-selected', '1');
applyDeckFilter();
if (document.getElementById('view-notebook').classList.contains('active')) {
renderNotebookList();
} else if (document.getElementById('view-quiz').classList.contains('active')) {
switchTab('ontap');
}
}
function applyDeckFilter() {
const deck = document.getElementById('deckFilter').value;
filteredCards = deck ? allCards.filter(c => c.deck === deck || c.deck.startsWith(deck + '::')) : [...allCards];
updateDashboardChart();
}
function updateDashboardChart() {
const counts = { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 };
let dueCount = 0;
let studyableNewCount = 0;
const now = Date.now() / 1000;
filteredCards.forEach(c => {
const lv = c.level || 0;
if (lv >= 0 && lv <= 5) counts[lv]++;
if (lv > 0 && (!c.next_review || c.next_review <= now)) {
dueCount++;
} else if (lv === 0 || c.has_anki_new) {
studyableNewCount++;
}
});
const maxVal = Math.max(10, counts[1], counts[2], counts[3], counts[4], counts[5]);
for (let i = 1; i <= 5; i++) {
document.getElementById('lvCount' + i).textContent = counts[i];
const h = counts[i] === 0 ? 6 : Math.max(24, Math.round((counts[i] / maxVal) * 230));
document.getElementById('lvBar' + i).style.height = h + 'px';
}
const selectedDeck = document.getElementById('deckFilter').value;
const dStat = (selectedDeck && window.ankiDeckStats && window.ankiDeckStats[selectedDeck]) || null;
const ankiRemainingToday = dStat ? (dStat.new_count + dStat.learn_count + dStat.review_count) : 0;
const dueEl = document.getElementById('dueTotalCount');
const newInfo = document.getElementById('newTotalInfo');
const btnOntap = document.querySelector('.btn-ontap-ngay');
if (dueCount > 0) {
if (dueEl) dueEl.textContent = dueCount;
const sessionSize = Math.min(200, dueCount);
if (newInfo) {
newInfo.innerHTML = `<span style="color:#E67E22;">📌 Phiên ôn tập tiếp theo: tách ${sessionSize} / ${dueCount} thẻ cần ôn từ Anki</span>` +
(counts[0] > 0 ? `<br><span style="color:#757575;">(Từ mới chưa học: ${counts[0]} từ)</span>` : '');
}
if (btnOntap) {
btnOntap.textContent = dueCount > 200 ? `Ôn tập ngay (${sessionSize} thẻ)` : `Ôn tập ngay (${dueCount} thẻ)`;
btnOntap.style.background = '';
btnOntap.style.boxShadow = '';
}
} else if (studyableNewCount > 0) {
const nextBatch = ankiRemainingToday > 0 ? Math.min(200, ankiRemainingToday, studyableNewCount) : Math.min(200, studyableNewCount);
if (dueEl) dueEl.textContent = nextBatch;
if (newInfo) {
newInfo.innerHTML = `<span style="color:#27AE60;">✅ Đã xong thẻ ôn cũ! Anki còn <b>${ankiRemainingToday || nextBatch}</b> thẻ có thể học tiếp hôm nay</span>` +
`<br><span style="color:#757575;">(Tổng từ mới / thẻ chưa học hết trong bộ: ${studyableNewCount} từ)</span>`;
}
if (btnOntap) {
btnOntap.textContent = `Học tiếp ngay (${nextBatch} thẻ)`;
btnOntap.style.background = '';
btnOntap.style.boxShadow = '';
}
} else {
if (dueEl) dueEl.textContent = 0;
if (newInfo) {
newInfo.innerHTML = `<span style="color:#27AE60;">✅ Anki thông báo bộ thẻ này đã hoàn thành toàn bộ thẻ!</span>`;
}
if (btnOntap) {
btnOntap.textContent = '🎉 Đã hết thẻ ôn tập';
btnOntap.style.background = '#BDBDBD';
btnOntap.style.boxShadow = '0 5px 0 #9E9E9E';
}
}
}
function switchTab(tabName) {
document.querySelectorAll('.nav-tab').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.view-section').forEach(s => s.classList.remove('active'));
if (tabName === 'ontap') {
document.getElementById('tabBtn-ontap').classList.add('active');
document.getElementById('view-ontap').classList.add('active');
updateDashboardChart();
} else if (tabName === 'notebook') {
document.getElementById('tabBtn-notebook').classList.add('active');
document.getElementById('view-notebook').classList.add('active');
renderNotebookList();
} else if (tabName === 'quiz') {
document.getElementById('view-quiz').classList.add('active');
}
}
function getNewStudyPool() {
const pureNew = filteredCards.filter(c => !c.level || c.level === 0);
const siblingNew = filteredCards.filter(c => (c.level || 0) > 0 && c.has_anki_new);
return [...pureNew, ...siblingNew];
}
function startQuizSession(type) {
const now = Date.now() / 1000;
let pool = [];
let activeTabType = type;
if (type === 'new') {
pool = getNewStudyPool();
if (pool.length === 0) {
alert('🎉 Bộ thẻ này trên Anki không còn thẻ từ mới nào chưa học!');
switchTab('ontap');
return;
}
} else {
pool = filteredCards.filter(c => c.level > 0 && (!c.next_review || c.next_review <= now));
if (pool.length === 0) {
pool = getNewStudyPool();
if (pool.length > 0) {
activeTabType = 'new';
} else {
alert('🎉 Anki thông báo bộ thẻ này đã hết thẻ cần ôn tập hôm nay! Bạn đã hoàn thành xong bài học.');
switchTab('ontap');
return;
}
}
}
document.querySelectorAll('.nav-tab').forEach(b => b.classList.remove('active'));
if (activeTabType === 'new') {
document.getElementById('tabBtn-new').classList.add('active');
} else {
document.getElementById('tabBtn-ontap').classList.add('active');
}
studyQueue = [...pool].sort(() => Math.random() - 0.5).slice(0, 200);
currentIndex = 0;
document.querySelectorAll('.view-section').forEach(s => s.classList.remove('active'));
document.getElementById('view-quiz').classList.add('active');
loadQuizCard();
}
function getCleanTargetWord(rawWord) {
return (rawWord || '')
.replace(/<[^>]*>/g, '')
.replace(/'|'|'/g, "'")
.replace(/\s*\([mf]\.?\)/i, '')
.trim();
}
async function loadQuizCard() {
if (!studyQueue.length) return;
if (currentIndex >= studyQueue.length) {
if (IS_CLOUD_SPACE) {
pushCloudReviewsToHF(false);
} else {
await initApp();
}
switchTab('ontap');
return;
}
currentCard = studyQueue[currentIndex];
isSheetOpen = false;
chosenMcNumber = null;
document.getElementById('resultSheetWrapper').classList.remove('show');
const pct = Math.max(4, Math.min(98, Math.round(((currentIndex + 1) / studyQueue.length) * 100)));
document.getElementById('quizProgressFill').style.width = pct + '%';
document.getElementById('quizProgressMascot').style.left = pct + '%';
const counterEl = document.getElementById('quizCounterBadge');
if (counterEl) {
counterEl.textContent = `${currentIndex + 1} / ${studyQueue.length}`;
}
// Cycle across the 5 Anki templates just like your Anki preset
const hasAudio = !!(currentCard.word_audio || currentCard.example_audio);
const hasEx = !!currentCard.example;
const rot = currentIndex % 5;
if (rot === 0) {
setQuizSubMode('1_typing_word');
} else if (rot === 1 && hasAudio) {
setQuizSubMode('2_review_word');
} else if (rot === 2 && hasEx) {
setQuizSubMode('3_reading_example');
} else if (rot === 3 && (hasEx || hasAudio)) {
setQuizSubMode('4_listening_example');
} else if (hasAudio) {
setQuizSubMode('5_dictation');
} else {
setQuizSubMode('1_typing_word');
}
setTimeout(() => preloadUpcomingAudio(currentIndex, 3), 250);
}
function cycleAnkiMode() {
const idx = ANKI_MODES.indexOf(quizSubMode);
const nextM = ANKI_MODES[(idx + 1) % ANKI_MODES.length];
setQuizSubMode(nextM);
}
// ============================================================
// EXACT FRENCH CONJUGATION / STEM MATCHER FROM ANKI PRESET
// ============================================================
function stripAccents(str) {
return (str || '').normalize('NFD').replace(/[\u0300-\u036f]/g, '');
}
function escapeRegExp(s) {
return (s || '').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
const IRREGULAR_FRENCH = {
'etre': ['suis', 'es', 'est', 'sommes', 'etes', 'sont', 'ete', 'etais', 'etait', 'etions', 'etiez', 'etaient', 'serai', 'seras', 'sera', 'serons', 'serez', 'seront', 'serais', 'serait', 'serions', 'seriez', 'seraient', 'sois', 'soit', 'soyons', 'soyez', 'soient', 'fut'],
'avoir': ['ai', 'as', 'a', 'avons', 'avez', 'ont', 'eu', 'avais', 'avait', 'avions', 'aviez', 'avaient', 'aurai', 'auras', 'aura', 'aurons', 'aurez', 'auront', 'aurais', 'aurait', 'aurions', 'auriez', 'auraient', 'aie', 'ait'],
'aller': ['vais', 'vas', 'va', 'allons', 'allez', 'vont', 'alle', 'allee', 'alles', 'allais', 'allait', 'irai', 'iras', 'ira', 'irons', 'irez', 'iront', 'irais', 'irait', 'aille', 'ailles', 'aillent'],
'pouvoir': ['peux', 'peut', 'pouvons', 'pouvez', 'peuvent', 'pu', 'pouvais', 'pouvait', 'pourrai', 'pourra', 'pourraient', 'pourrait', 'puisse', 'puissent'],
'devoir': ['dois', 'doit', 'devons', 'devez', 'doivent', 'du', 'devais', 'devait', 'devra', 'devrait', 'devraient', 'doive'],
'vouloir': ['veux', 'veut', 'voulons', 'voulez', 'veulent', 'voulu', 'voulais', 'voulait', 'voudrai', 'voudra', 'voudrait', 'voudraient', 'veuille'],
'faire': ['fais', 'fait', 'faisons', 'faites', 'font', 'faisais', 'faisait', 'ferai', 'fera', 'ferait', 'feraient', 'fasse', 'fassent'],
'savoir': ['sais', 'sait', 'savons', 'savez', 'savent', 'su', 'savais', 'savait', 'saura', 'saurait', 'sache'],
'venir': ['viens', 'vient', 'venons', 'venez', 'viennent', 'venu', 'venais', 'viendra', 'viendrait'],
'tenir': ['tiens', 'tient', 'tenons', 'tenez', 'tiennent', 'tenu', 'tenais', 'tiendra', 'tiendrait'],
'prendre': ['prends', 'prend', 'prenons', 'prenez', 'prennent', 'pris', 'prenait', 'prendra', 'prenne'],
'dire': ['dis', 'dit', 'disons', 'dites', 'disent', 'disait', 'dira', 'dirait'],
'mettre': ['mets', 'met', 'mettons', 'mettez', 'mettent', 'mis', 'mettait', 'mettra', 'mettrait'],
'voir': ['vois', 'voit', 'voyons', 'voyez', 'voient', 'vu', 'voyait', 'verra', 'verrait'],
'croire': ['crois', 'croit', 'croyons', 'croyez', 'croient', 'cru', 'croyait'],
'connaitre': ['connais', 'connait', 'connaissons', 'connaissez', 'connaissent', 'connu'],
'partir': ['pars', 'part', 'partons', 'partez', 'partent', 'parti', 'partait', 'partira'],
'dormir': ['dors', 'dort', 'dormons', 'dormez', 'dorment', 'dormi', 'dormait', 'dormira'],
'ecrire': ['ecris', 'ecrit', 'ecrivons', 'ecrivez', 'ecrivent', 'ecrit', 'ecrivait', 'ecrira'],
'boire': ['bois', 'boit', 'buvons', 'buvez', 'boivent', 'bu', 'buvait', 'boira'],
'vivre': ['vis', 'vit', 'vivons', 'vivez', 'vivent', 'vecu', 'vivait', 'vivra'],
'ouvrir': ['ouvre', 'ouvres', 'ouvrons', 'ouvrez', 'ouvrent', 'ouvert', 'ouvrait', 'ouvrira']
};
function findFrenchSpanInSentence(rawSentence, rawWord) {
const cleanSentence = (rawSentence || '').replace(/[’‘`]/g, "'").replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
const cleanWord = getCleanTargetWord(rawWord).replace(/[’‘`]/g, "'").replace(/\(.*?\)/g, '').replace(/\/.*$/, '').trim();
if (!cleanSentence || !cleanWord) return { cleanSentence, cleanWord, foundSpan: null };
let candidates = [cleanWord];
const noArt = cleanWord.replace(/^(?:to|a|an|the|le|la|les|un|une|des|du|de la|de l'|d'|l'|se|s'|ne pas|ne|n')\s+/i, '').trim();
if (noArt && noArt !== cleanWord) candidates.push(noArt);
if (noArt.endsWith('al')) candidates.push(noArt.slice(0, -2) + 'aux');
if (noArt.endsWith('aux')) candidates.push(noArt.slice(0, -3) + 'al');
if (noArt.endsWith('y') && noArt.length > 3) {
candidates.push(noArt.slice(0, -1) + 'ies', noArt.slice(0, -1) + 'ied');
}
if (noArt.endsWith('e') && noArt.length > 3) {
candidates.push(noArt + 'd', noArt.slice(0, -1) + 'ing');
} else if (noArt.length > 3) {
candidates.push(noArt + 'ed', noArt + 'ing', noArt + 'es');
}
if (noArt.endsWith('s') && noArt.length > 3) candidates.push(noArt.slice(0, -1));
else candidates.push(noArt + 's');
const parts = noArt.split(' ');
if (parts.length > 1) {
if (parts[0].endsWith('s')) candidates.push(parts[0].slice(0, -1) + ' ' + parts.slice(1).join(' '));
else candidates.push(parts[0] + 's ' + parts.slice(1).join(' '));
}
if (noArt.endsWith(' à')) {
candidates.push(noArt.slice(0, -2) + ' aux', noArt.slice(0, -2) + ' au');
} else if (noArt.endsWith(' de')) {
candidates.push(noArt.slice(0, -3) + ' du', noArt.slice(0, -3) + ' des');
}
const normBase = stripAccents(noArt.toLowerCase());
if (IRREGULAR_FRENCH[normBase]) {
candidates = candidates.concat(IRREGULAR_FRENCH[normBase]);
if (cleanWord.toLowerCase().indexOf('ne pas') === 0) {
const forms = IRREGULAR_FRENCH[normBase];
for (let nf = 0; nf < forms.length; nf++) {
candidates.push('ne ' + forms[nf] + ' pas', "n'" + forms[nf] + ' pas', forms[nf] + ' pas', "n'" + forms[nf]);
}
}
} else {
const prefixes = ['de', 're', 'per', 'ob', 'main', 'sou', 'con', 'ap', 'com', 'ad', 'inter', 'pre', 'pro', 'sur'];
for (let p = 0; p < prefixes.length; p++) {
const pfx = prefixes[p];
if (normBase.indexOf(pfx) === 0) {
const root = normBase.slice(pfx.length);
if (IRREGULAR_FRENCH[root]) {
for (let f = 0; f < IRREGULAR_FRENCH[root].length; f++) {
candidates.push(pfx + IRREGULAR_FRENCH[root][f]);
}
}
}
}
if (normBase.endsWith('eindre')) {
const stm = noArt.slice(0, -6);
candidates.push(stm + 'eint', stm + 'eign');
} else if (normBase.endsWith('aitre')) {
const stm2 = noArt.slice(0, -5);
candidates.push(stm2 + 'ait', stm2 + 'aiss', stm2 + 'u');
} else if (normBase.length >= 4) {
if (normBase.endsWith('er')) {
const stemEr = noArt.slice(0, -2);
candidates.push(stemEr);
if (stemEr.endsWith('y')) candidates.push(stemEr.slice(0, -1) + 'i');
} else if (normBase.endsWith('ir') || normBase.endsWith('re')) {
candidates.push(noArt.slice(0, -2));
}
}
}
const validCands = [];
const seen = {};
for (let i = 0; i < candidates.length; i++) {
const c = candidates[i].trim();
if (c.length >= 2 && !seen[c.toLowerCase()]) {
seen[c.toLowerCase()] = true;
validCands.push(c);
}
}
if (cleanWord.length === 1 && !seen[cleanWord.toLowerCase()]) {
validCands.push(cleanWord);
}
validCands.sort((a, b) => b.length - a.length);
let foundSpan = null;
// Pass 1: Exact whole word / phrase match
for (let j = 0; j < validCands.length; j++) {
const cand = validCands[j];
const pat = new RegExp("(?:\\b|\\b\\w+')" + escapeRegExp(cand) + "(?:\\b|')", 'i');
const match = pat.exec(cleanSentence);
if (match) {
const mText = match[0].replace(/^\w+'/, '');
const startIdx = cleanSentence.indexOf(mText, match.index);
if (startIdx !== -1) {
foundSpan = { start: startIdx, end: startIdx + mText.length, text: mText };
break;
}
}
}
// Pass 2: Stem / token match
if (!foundSpan) {
const words = cleanSentence.split(/([\s,.;:!?()«»"]+)/);
let charOffset = 0;
for (let w = 0; w < words.length; w++) {
const wordTok = words[w];
const normTok = stripAccents(wordTok.toLowerCase().replace(/^\w+'/, ''));
if (normTok.length >= 3) {
for (let k = 0; k < validCands.length; k++) {
const candNorm = stripAccents(validCands[k].toLowerCase());
if (candNorm.length >= 3 && (normTok.indexOf(candNorm) === 0 || candNorm.indexOf(normTok) === 0)) {
const coreWord = wordTok.replace(/^\w+'/, '');
const tokStart = charOffset + (wordTok.length - coreWord.length);
foundSpan = { start: tokStart, end: tokStart + coreWord.length, text: coreWord };
break;
}
}
if (foundSpan) break;
}
charOffset += wordTok.length;
}
}
// Pass 3: Substring search
if (!foundSpan) {
const sNorm = stripAccents(cleanSentence.toLowerCase());
for (let m = 0; m < validCands.length; m++) {
const cNorm = stripAccents(validCands[m].toLowerCase());
if (cNorm.length >= 3 && sNorm.indexOf(cNorm) !== -1) {
const pos = sNorm.indexOf(cNorm);
foundSpan = { start: pos, end: pos + validCands[m].length, text: cleanSentence.substr(pos, validCands[m].length) };
break;
}
}
}
return { cleanSentence, cleanWord, foundSpan };
}
// ============================================================
// SETUP EACH OF THE 5 ANKI MODES
// ============================================================
function setQuizSubMode(mode) {
quizSubMode = mode;
isSheetOpen = false;
chosenMcNumber = null;
document.getElementById('resultSheetWrapper').classList.remove('show');
ANKI_MODES.forEach(m => {
const pill = document.getElementById('pillMode-' + m);
if (pill) pill.classList.toggle('active', m === mode);
});
const sharedAudio = document.getElementById('sharedAudioControls');
const typingPrompt = document.getElementById('typingPromptText');
const slotsCard = document.getElementById('spellingSlotsCard');
const typeansWrap = document.getElementById('typeansWrap');
const typeansInp = document.getElementById('typeans');
const diffBox = document.getElementById('typeansDiffBox');
const accentsBar = document.getElementById('frenchAccentsBar');
const mcArea = document.getElementById('mcQuizArea');
const mcSent = document.getElementById('mcSentenceCard');
const titleEl = document.getElementById('quizModeTitle');
const btnCheck = document.getElementById('btnCheckQuiz');
const btnSkipAudio = document.getElementById('btnSkipAudioLink');
sharedAudio.style.display = 'none';
typingPrompt.style.display = 'none';
slotsCard.style.display = 'none';
typeansWrap.style.display = 'none';
diffBox.style.display = 'none';
typeansInp.style.display = 'block';
typeansInp.classList.remove('hidden-for-slots');
typeansInp.disabled = false;
typeansInp.value = '';
accentsBar.style.display = 'none';
mcArea.style.display = 'none';
mcSent.style.display = 'none';
btnSkipAudio.style.display = 'none';
btnCheck.classList.remove('ready');
if (mode === '1_typing_word') {
titleEl.textContent = 'Điền từ';
typingPrompt.style.display = 'block';
slotsCard.style.display = 'flex';
typeansWrap.style.display = 'block';
typeansInp.classList.add('hidden-for-slots');
accentsBar.style.display = 'flex';
btnCheck.classList.add('ready');
const posStr = currentCard.pos ? ` (${currentCard.pos})` : '';
typingPrompt.textContent = `${currentCard.meaning || currentCard.word}${posStr}`;
buildAnkiTypingSlots(getCleanTargetWord(currentCard.word));
setTimeout(() => focusAnkiInput(), 40);
} else if (mode === '2_review_word') {
titleEl.textContent = 'Nghe và chọn đáp án đúng';
sharedAudio.style.display = 'flex';
mcArea.style.display = 'block';
btnSkipAudio.style.display = 'inline-block';
currentMcOptions = buildMeaningOptions(currentCard);
renderMcOptionsList(false);
playWordAudio(1.0);
} else if (mode === '3_reading_example') {
titleEl.textContent = 'Chọn nghĩa của từ được gạch chân';
mcArea.style.display = 'block';
mcSent.style.display = 'block';
const { cleanSentence, cleanWord, foundSpan } = findFrenchSpanInSentence(currentCard.example || currentCard.word, currentCard.word);
if (foundSpan) {
const before = cleanSentence.slice(0, foundSpan.start);
const target = cleanSentence.slice(foundSpan.start, foundSpan.end);
const after = cleanSentence.slice(foundSpan.end);
mcSent.innerHTML = `${before}<u class="mochi-target-highlight"><strong>${target}</strong></u>${after}`;
} else {
mcSent.innerHTML = `${cleanSentence}<br><small style="color:#B45309; font-size:15px; margin-top:8px; display:inline-block; font-weight:700;">(Từ cần xác định nghĩa: <u class="mochi-target-highlight"><strong>${cleanWord}</strong></u>)</small>`;
}
currentMcOptions = buildMeaningOptions(currentCard);
renderMcOptionsList(false);
} else if (mode === '4_listening_example') {
mcArea.style.display = 'block';
mcSent.style.display = 'block';
const { cleanSentence, cleanWord, foundSpan } = findFrenchSpanInSentence(currentCard.example || '', currentCard.word);
const answerWord = foundSpan ? foundSpan.text : cleanWord;
const blankHtml = `<span class="mochi-sentence-blank" id="listeningBlankSpan" data-answer="${answerWord.replace(/"/g, '"')}"> </span>`;
if (foundSpan) {
mcSent.innerHTML = cleanSentence.slice(0, foundSpan.start) + blankHtml + cleanSentence.slice(foundSpan.end);
} else if (cleanSentence) {
mcSent.innerHTML = cleanSentence + ' ' + blankHtml;
} else {
mcSent.innerHTML = blankHtml;
}
const cmeta = currentCard.choices || {};
const hasAudioChoices = cmeta.audio_choices && cmeta.audio_choices.length >= 2;
if (hasAudioChoices) {
titleEl.textContent = 'Nghe các lựa chọn và chọn đáp án đúng';
const corrIdx = (cmeta.correct_choice_audio || 1) - 1;
currentMcOptions = cmeta.audio_choices.map((aud, idx) => ({
text: `Lựa chọn ${idx + 1}`,
audio: aud,
isCorrect: idx === corrIdx
}));
renderMcOptionsList(true);
} else {
titleEl.textContent = 'Chọn từ thích hợp điền vào chỗ trống';
currentMcOptions = buildWordOptions(currentCard);
renderMcOptionsList(false);
}
} else if (mode === '5_dictation') {
titleEl.textContent = 'Nghe và viết lại';
sharedAudio.style.display = 'flex';
typeansWrap.style.display = 'block';
accentsBar.style.display = 'flex';
btnSkipAudio.style.display = 'inline-block';
btnCheck.classList.add('ready');
setTimeout(() => focusAnkiInput(), 40);
playWordAudio(1.0);
}
}
// ============================================================
// EXACT ANKI 1_typing_word SLOTS ENGINE
// ============================================================
function buildAnkiTypingSlots(targetWord) {
const container = document.getElementById('spellingSlotsCard');
typingTargetChars = Array.from(targetWord);
typingTotalLetters = typingTargetChars.length;
typingHintIdx1 = (typingTotalLetters >= 8) ? Math.floor(typingTotalLetters * 0.35) : ((typingTotalLetters >= 5) ? 1 : -1);
typingHintIdx2 = (typingTotalLetters >= 8) ? Math.floor(typingTotalLetters * 0.8) : -1;
let html = '';
for (let i = 0; i < typingTotalLetters; i++) {
const ch = typingTargetChars[i];
if (ch === ' ') {
html += '<div class="mochi-slot-wrap" style="min-width: 14px;"><div class="mochi-slot-char"> </div><div class="mochi-slot-line" style="background:transparent;"></div></div>';
} else {
const isHint = (i === typingHintIdx1 || i === typingHintIdx2);
html += `<div class="mochi-slot-wrap${i === 0 ? ' active' : ''}" id="slotWrap_${i}">`;
html += ` <div class="mochi-slot-char${isHint ? ' hint' : ''}" id="slotChar_${i}">${isHint ? ch : ''}</div>`;
html += ` <div class="mochi-slot-line"></div>`;
html += ` <div class="mochi-slot-pointer">▲</div>`;
html += `</div>`;
}
}
container.innerHTML = html;
}
function updateAnkiTypingSlots() {
if (quizSubMode !== '1_typing_word') return;
const inp = document.getElementById('typeans');
const currentVal = Array.from(inp.value);
for (let j = 0; j < typingTotalLetters; j++) {
const charEl = document.getElementById('slotChar_' + j);
const wrapEl = document.getElementById('slotWrap_' + j);
if (wrapEl) wrapEl.classList.remove('active');
if (charEl) {
if (j < currentVal.length) {
charEl.innerText = currentVal[j];
charEl.classList.remove('hint');
} else if (j === typingHintIdx1 || j === typingHintIdx2) {
charEl.innerText = typingTargetChars[j];
charEl.classList.add('hint');
} else {
charEl.innerText = '';
}
}
}
if (typingTotalLetters > 0) {
const activeWrap = document.getElementById('slotWrap_' + Math.min(currentVal.length, typingTotalLetters - 1));
if (activeWrap) activeWrap.classList.add('active');
}
}
function focusAnkiInput() {
if (isSheetOpen) return;
const inp = document.getElementById('typeans');
if (inp && inp.style.display !== 'none') {
try {
inp.focus();
inp.selectionStart = inp.selectionEnd = inp.value.length;
} catch (e) {}
}
}
function insertFrenchChar(ch) {
if (isSheetOpen) return;
const inp = document.getElementById('typeans');
if (!inp) return;
const start = inp.selectionStart ?? inp.value.length;
const end = inp.selectionEnd ?? inp.value.length;
inp.value = inp.value.slice(0, start) + ch + inp.value.slice(end);
inp.focus();
try {
inp.selectionStart = inp.selectionEnd = start + ch.length;
} catch (e) {}
updateAnkiTypingSlots();
}
// Hook up #typeans input & compositionend exactly like Anki template
const typeansEl = document.getElementById('typeans');
typeansEl.addEventListener('input', function(e) {
if (!e || !e.isComposing) {
const clean = typeansEl.value.replace(/[\u2018\u2019`]/g, "'");
if (typeansEl.value !== clean) {
const pos = typeansEl.selectionStart;
typeansEl.value = clean;
try { typeansEl.selectionStart = typeansEl.selectionEnd = pos; } catch (err) {}
}
}
updateAnkiTypingSlots();
});
typeansEl.addEventListener('compositionend', updateAnkiTypingSlots);
// Click anywhere in workspace to keep focus on #typeans during typing modes
document.getElementById('quizWorkspace').addEventListener('click', function(e) {
if (isSheetOpen) return;
if (quizSubMode === '1_typing_word' || quizSubMode === '5_dictation') {
if (e.target !== typeansEl && !e.target.closest('button') && !e.target.closest('select')) {
focusAnkiInput();
}
}
});
// ============================================================
// MULTIPLE CHOICE OPTIONS BUILDER & NUMBER KEYS 1..4
// ============================================================
function buildMeaningOptions(card) {
const cmeta = card.choices || {};
if (cmeta.meaning_choices && cmeta.meaning_choices.length >= 2) {
const corrIdx = (cmeta.correct_choice || 1) - 1;
return cmeta.meaning_choices.map((txt, idx) => ({
text: (idx === corrIdx && card.explain && !txt.includes(card.explain)) ? `${txt} — ${card.explain}` : txt,
isCorrect: idx === corrIdx
}));
}
const others = filteredCards.filter(c => c.nid !== card.nid && c.meaning).sort(() => Math.random() - 0.5).slice(0, 3);
const opts = [{ text: card.meaning, isCorrect: true }, ...others.map(o => ({ text: o.meaning, isCorrect: false }))];
return opts.sort(() => Math.random() - 0.5);
}
function buildWordOptions(card) {
const cmeta = card.choices || {};
if (cmeta.word_choices && cmeta.word_choices.length >= 2) {
const corrIdx = (cmeta.correct_choice_word || 1) - 1;
return cmeta.word_choices.map((txt, idx) => ({
text: txt,
isCorrect: idx === corrIdx
}));
}
const others = filteredCards.filter(c => c.nid !== card.nid && c.word).sort(() => Math.random() - 0.5).slice(0, 3);
const opts = [{ text: getCleanTargetWord(card.word), isCorrect: true }, ...others.map(o => ({ text: getCleanTargetWord(o.word), isCorrect: false }))];
return opts.sort(() => Math.random() - 0.5);
}
function renderMcOptionsList(isAudioChoices) {
const list = document.getElementById('mcOptionsList');
list.innerHTML = '';
currentMcOptions.forEach((opt, idx) => {
const num = idx + 1;
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'mochi-option-btn';
btn.id = 'mochi-opt-' + num;
btn.innerHTML = `
<span class="mochi-opt-num">${num}</span>
${isAudioChoices ? '<span style="font-size:18px;">🔊</span>' : ''}
<span class="mochi-opt-text">${opt.text}</span>
`;
btn.onclick = () => chooseMcOption(num);
list.appendChild(btn);
});
}
function chooseMcOption(num) {
if (isSheetOpen) return;
if (num < 1 || num > currentMcOptions.length) return;
chosenMcNumber = num;
for (let i = 1; i <= 4; i++) {
const el = document.getElementById('mochi-opt-' + i);
if (el) el.classList.remove('selected');
}
const chosenEl = document.getElementById('mochi-opt-' + num);
if (chosenEl) chosenEl.classList.add('selected');
const optObj = currentMcOptions[num - 1];
if (optObj && optObj.audio) {
playAudioFileInstant(optObj.audio, 1.0, '');
}
document.getElementById('btnCheckQuiz').classList.add('ready');
}
// ============================================================
// SUBMIT & BACK-SIDE RESULT DRAWER (WITH ANKI DIFF & EASE 1..4)
// ============================================================
function normalizeCompare(s) {
return (s || '')
.toLowerCase()
.replace(/[\u2018\u2019`]/g, "'")
.replace(/\s+/g, ' ')
.trim();
}
function renderAnkiTypeDiff(typedStr, targetStr) {
const tChars = Array.from(targetStr);
const uChars = Array.from(typedStr);
if (quizSubMode === '1_typing_word') {
for (let i = 0; i < typingTotalLetters; i++) {
const wrapEl = document.getElementById('slotWrap_' + i);
const charEl = document.getElementById('slotChar_' + i);
if (!wrapEl || !charEl) continue;
wrapEl.classList.remove('active');
charEl.classList.remove('hint');
const u = uChars[i];
const t = tChars[i];
if (u !== undefined && t !== undefined && u.toLowerCase() === t.toLowerCase()) {
charEl.innerText = t;
wrapEl.classList.add('slot-good');
} else {
charEl.innerText = t;
wrapEl.classList.add('slot-bad');
}
}
return;
}
const diffBox = document.getElementById('typeansDiffBox');
const inp = document.getElementById('typeans');
inp.style.display = 'none';
diffBox.style.display = 'block';
let html = '';
const maxLen = Math.max(tChars.length, uChars.length);
for (let i = 0; i < maxLen; i++) {
const u = uChars[i];
const t = tChars[i];
if (u !== undefined && t !== undefined && u.toLowerCase() === t.toLowerCase()) {
html += `<span class="typeGood">${t}</span>`;
} else if (u !== undefined && t === undefined) {
html += `<span class="typeBad">${u}</span>`;
} else if (u === undefined && t !== undefined) {
html += `<span class="typeMissed">${t}</span>`;
} else {
html += `<span class="typeBad">${u}</span><span class="typeMissed">${t}</span>`;
}
}
diffBox.innerHTML = html;
}
function revealListeningBlank() {
const blankEl = document.getElementById('listeningBlankSpan');
if (blankEl) {
const ans = blankEl.getAttribute('data-answer') || getCleanTargetWord(currentCard.word);
blankEl.outerHTML = `<u class="mochi-target-highlight"><strong>${ans}</strong></u>`;
}
}
function giveUpCurrentCard() {
if (isSheetOpen) return;
chosenMcNumber = null;
if (quizSubMode === '1_typing_word' || quizSubMode === '5_dictation') {
renderAnkiTypeDiff('', getCleanTargetWord(currentCard.word));
} else if (quizSubMode === '4_listening_example') {
revealListeningBlank();
}
showResultSheet(false);
}
function submitCurrentAnswer() {
if (isSheetOpen) {
onContinueClick();
return;
}
if (quizSubMode === '1_typing_word' || quizSubMode === '5_dictation') {
const typedRaw = document.getElementById('typeans').value.trim();
const targetRaw = getCleanTargetWord(currentCard.word);
const right = normalizeCompare(typedRaw) === normalizeCompare(targetRaw);
renderAnkiTypeDiff(typedRaw, targetRaw);
showResultSheet(right);
} else {
if (quizSubMode === '4_listening_example') {
revealListeningBlank();
}
const opt = chosenMcNumber ? currentMcOptions[chosenMcNumber - 1] : null;
const right = Boolean(opt && opt.isCorrect);
// Highlight green correct-choice and red wrong-choice on the option buttons just like Anki!
currentMcOptions.forEach((o, idx) => {
const btn = document.getElementById('mochi-opt-' + (idx + 1));
if (!btn) return;
btn.classList.remove('selected');
if (o.isCorrect) {
btn.classList.add('correct-choice');
} else if (chosenMcNumber === idx + 1 && !right) {
btn.classList.add('wrong-choice');
}
});
showResultSheet(right);
}
}
function showResultSheet(isCorrect) {
isSheetOpen = true;
isUserCorrect = isCorrect;
try {
if (document.activeElement && document.activeElement.blur) {
document.activeElement.blur();
}
} catch (e) {}
const wrapper = document.getElementById('resultSheetWrapper');
const box = document.getElementById('resultSheetBox');
const mascot = document.getElementById('sheetMascotImg');
box.className = 'result-sheet-box ' + (isCorrect ? 'correct' : 'wrong');
mascot.src = isCorrect ? '/assets/mochi_happy.png' : '/assets/mochi_sad.png';
const posStr = currentCard.pos ? ` (${currentCard.pos})` : '';
document.getElementById('sheetWordTitle').textContent = `${getCleanTargetWord(currentCard.word)}${posStr}`;
document.getElementById('sheetIpa').textContent = currentCard.ipa || '';
document.getElementById('sheetMeaning').textContent = currentCard.meaning || '';
const exRow = document.getElementById('sheetExampleRow');
const exText = document.getElementById('sheetExampleText');
const exAudioBtn = document.getElementById('sheetExAudioBtn');
const transDiv = document.getElementById('sheetExampleTrans');
const extraMeta = document.getElementById('sheetExtraMeta');
if (currentCard.example) {
exRow.style.display = 'flex';
const cleanWord = getCleanTargetWord(currentCard.word);
const escaped = escapeRegExp(cleanWord);
exText.innerHTML = currentCard.example.replace(new RegExp(`(${escaped})`, 'gi'), '<b>$1</b>');
exAudioBtn.style.display = currentCard.example_audio ? 'flex' : 'none';
transDiv.textContent = currentCard.example_trans || '';
} else {
exRow.style.display = 'none';
}
const extras = [];
if (currentCard.collocation && currentCard.collocation !== 'N/A') extras.push(`📌 Cụm từ: ${currentCard.collocation}`);
if (currentCard.synonym && currentCard.synonym !== 'N/A') extras.push(`🔄 Đồng nghĩa: ${currentCard.synonym}`);
if (currentCard.antonym && currentCard.antonym !== 'N/A') extras.push(`⚡ Trái nghĩa: ${currentCard.antonym}`);
extraMeta.innerHTML = extras.join(' | ');
wrapper.classList.add('show');
playWordAudio(1.0);
}
function toggleDrawer() {
const wrapper = document.getElementById('resultSheetWrapper');
wrapper.classList.toggle('show');
}
function answerEase(easeNum) {
if (!currentCard) return;
const reviewedCard = currentCard;
const isRight = easeNum >= 2;
const curLv = reviewedCard.level || 0;
let newLv = 1;
let nextSec = 3600;
if (easeNum === 1) {
newLv = 1;
nextSec = 600;
} else if (easeNum === 2) {
newLv = Math.max(1, curLv);
nextSec = 43200;
} else if (easeNum === 3) {
newLv = Math.min(5, curLv + 1);
const intervals = { 1: 86400, 2: 259200, 3: 604800, 4: 1209600, 5: 2592000 };
nextSec = intervals[newLv] || 86400;
} else if (easeNum === 4) {
newLv = Math.min(5, curLv + 2);
nextSec = 604800 * newLv;
}
reviewedCard.level = newLv;
reviewedCard.next_review = Math.floor(Date.now() / 1000) + nextSec;
reviewedCard.has_anki_new = false;
if (!IS_CLOUD_SPACE) {
fetch('/api/review', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
nid: reviewedCard.nid,
correct: isRight,
ease: easeNum
})
}).then(r => r.json()).then(data => {
if (data && data.level !== undefined) {
reviewedCard.level = data.level;
reviewedCard.next_review = data.next_review;
}
}).catch(() => {});
} else {
try {
const saved = JSON.parse(localStorage.getItem('mochi_cloud_srs_v1') || '{}');
saved[String(reviewedCard.nid)] = {
level: reviewedCard.level,
next_review: reviewedCard.next_review,
correct: isRight,
ease: easeNum,
ts: Math.floor(Date.now() / 1000)
};
localStorage.setItem('mochi_cloud_srs_v1', JSON.stringify(saved));
} catch (e) {}
}
currentIndex++;
loadQuizCard();
}
function onContinueClick() {
answerEase(isUserCorrect ? 3 : 1);
}
// ============================================================
// GLOBAL KEYBOARD HANDLER (EXACT MATCH WITH ANKI PRESET)
// - Front side MC modes: 1, 2, 3, 4 selects option; Enter submits
// - Front side Typing modes: Enter submits
// - Back side (Result sheet open): Enter -> Continue; 1..4 -> Ease 1..4
// ============================================================
window.addEventListener('keydown', function(e) {
if (!document.getElementById('view-quiz').classList.contains('active')) return;
if (e.isComposing) return;
const k = e.key;
const code = e.code || '';
const kc = e.keyCode || e.which || 0;
// 1. When Result Drawer is open (Back side)
if (isSheetOpen) {
if (k === 'Enter' || code === 'Enter' || code === 'NumpadEnter' || kc === 13) {
e.preventDefault();
e.stopPropagation();
onContinueClick();
return;
}
if (k === '1' || code === 'Digit1' || code === 'Numpad1' || kc === 49 || kc === 97) {
e.preventDefault();
e.stopPropagation();
answerEase(1);
return;
}
if (k === '2' || code === 'Digit2' || code === 'Numpad2' || kc === 50 || kc === 98) {
e.preventDefault();
e.stopPropagation();
answerEase(2);
return;
}
if (k === '3' || code === 'Digit3' || code === 'Numpad3' || kc === 51 || kc === 99) {
e.preventDefault();
e.stopPropagation();
answerEase(3);
return;
}
if (k === '4' || code === 'Digit4' || code === 'Numpad4' || kc === 52 || kc === 100) {
e.preventDefault();
e.stopPropagation();
answerEase(4);
return;
}
return;
}
// 2. When on Front side
const isMcMode = (quizSubMode === '2_review_word' || quizSubMode === '3_reading_example' || quizSubMode === '4_listening_example');
if (isMcMode) {
let selectedNum = null;
if (k === '1' || code === 'Digit1' || code === 'Numpad1') selectedNum = 1;
else if (k === '2' || code === 'Digit2' || code === 'Numpad2') selectedNum = 2;
else if (k === '3' || code === 'Digit3' || code === 'Numpad3') selectedNum = 3;
else if (k === '4' || code === 'Digit4' || code === 'Numpad4') selectedNum = 4;
if (selectedNum !== null) {
e.preventDefault();
e.stopPropagation();
chooseMcOption(selectedNum);
return;
}
}
if (k === 'Enter' || code === 'Enter' || code === 'NumpadEnter' || kc === 13) {
e.preventDefault();
e.stopPropagation();
submitCurrentAnswer();
}
}, true);
// ============================================================
// ZERO-LATENCY AUDIO PRELOADER & FAST PLAYBACK ENGINE
// ============================================================
const audioPreloadMap = new Map();
let activeAudioElement = null;
let cachedVoiceFR = null;
let cachedVoiceEN = null;
function initSpeechVoices() {
if (!('speechSynthesis' in window)) return;
const voices = window.speechSynthesis.getVoices() || [];
if (!voices.length) return;
cachedVoiceFR = voices.find(v => v.lang && v.lang.toLowerCase().startsWith('fr') && v.localService) ||
voices.find(v => v.lang && v.lang.toLowerCase().startsWith('fr')) || null;
cachedVoiceEN = voices.find(v => v.lang && v.lang.toLowerCase().startsWith('en-us') && v.localService) ||
voices.find(v => v.lang && v.lang.toLowerCase().startsWith('en') && v.localService) ||
voices.find(v => v.lang && v.lang.toLowerCase().startsWith('en')) || null;
}
if ('speechSynthesis' in window) {
initSpeechVoices();
window.speechSynthesis.onvoiceschanged = initSpeechVoices;
}
function preloadSingleAudio(filename) {
if (!filename || audioPreloadMap.has(filename)) return;
if (audioPreloadMap.size > 80) {
const oldestKey = audioPreloadMap.keys().next().value;
audioPreloadMap.delete(oldestKey);
}
const a = new Audio();
a.preload = 'auto';
a.src = getMediaUrl(filename);
a.load();
audioPreloadMap.set(filename, a);
}
function preloadUpcomingAudio(startIdx, count = 6) {
if (!studyQueue || !studyQueue.length) return;
const endIdx = Math.min(studyQueue.length, startIdx + count);
for (let i = startIdx; i < endIdx; i++) {
const c = studyQueue[i];
if (!c) continue;
if (c.word_audio) preloadSingleAudio(c.word_audio);
if (c.example_audio) preloadSingleAudio(c.example_audio);
const ac = (c.choices && c.choices.audio_choices) || [];
for (let j = 0; j < ac.length; j++) {
if (ac[j]) preloadSingleAudio(ac[j]);
}
}
}
function playAudioFileInstant(filename, rate = 1.0, fallbackText = '') {
if (activeAudioElement) {
try { activeAudioElement.pause(); } catch (e) {}
}
if ('speechSynthesis' in window) {
try { window.speechSynthesis.cancel(); } catch (e) {}
}
if (!filename) {
if (fallbackText) speakFrenchFallback(fallbackText, rate);
return;
}
let audioEl = audioPreloadMap.get(filename);
if (!audioEl) {
audioEl = new Audio(getMediaUrl(filename));
audioEl.preload = 'auto';
audioPreloadMap.set(filename, audioEl);
}
activeAudioElement = audioEl;
try { audioEl.currentTime = 0; } catch (e) {}
audioEl.playbackRate = rate;
audioEl.play().catch(() => {
if (fallbackText) speakFrenchFallback(fallbackText, rate);
});
}
function speakFrenchFallback(text, rate = 1.0) {
if ('speechSynthesis' in window && text) {
try { window.speechSynthesis.cancel(); } catch (e) {}
const utter = new SpeechSynthesisUtterance(text);
const isEnglishCard = IS_ENGLISH_SPACE || (currentCard && String(currentCard.deck || '').toLowerCase().startsWith('hoc_lom'));
utter.lang = isEnglishCard ? 'en-US' : 'fr-FR';
if (isEnglishCard && cachedVoiceEN) utter.voice = cachedVoiceEN;
else if (!isEnglishCard && cachedVoiceFR) utter.voice = cachedVoiceFR;
utter.rate = rate;
window.speechSynthesis.speak(utter);
}
}
function playWordAudio(rate = 1.0) {
if (!currentCard) return;
const cleanW = getCleanTargetWord(currentCard.word);
const file = currentCard.word_audio || (!currentCard.example ? currentCard.example_audio : '');
playAudioFileInstant(file, rate, cleanW);
}
function playExampleAudio() {
if (!currentCard) return;
playAudioFileInstant(currentCard.example_audio, 1.0, currentCard.example || '');
}
// ============================================================
// SỔ TAY (NOTEBOOK) VIEW LOGIC
// ============================================================
function selectNotebookLevel(lv) {
currentNotebookLevel = lv;
for (let i = 1; i <= 5; i++) {
document.getElementById('nbTab' + i).classList.toggle('active', i === lv);
document.getElementById('nbSeg' + i).classList.toggle('active', i === lv);
}
renderNotebookList();
}
function renderNotebookList() {
const query = (document.getElementById('nbSearchInput').value || '').toLowerCase().trim();
const container = document.getElementById('nbWordList');
container.innerHTML = '';
let items = filteredCards.filter(c => (c.level || 0) === currentNotebookLevel);
if (query) {
items = filteredCards.filter(c =>
(c.word || '').toLowerCase().includes(query) ||
(c.meaning || '').toLowerCase().includes(query)
);
}
items.slice(0, 150).forEach(card => {
const row = document.createElement('div');
row.className = 'nb-word-row';
row.onclick = () => {
currentCard = card;
playWordAudio(1.0);
};
const posText = card.pos ? `(${card.pos.replace(/^\(|\)$/g, '')})` : '';
row.innerHTML = `
<div class="nb-check-icon">✓</div>
<div class="nb-col-word">
<div class="nb-word-text">${getCleanTargetWord(card.word)}</div>
<div class="nb-word-ipa">${card.ipa || ''}</div>
</div>
<div class="nb-col-pos">${posText}</div>
<div class="nb-col-meaning">${card.meaning || ''}</div>
`;
container.appendChild(row);
});
}
initApp();
</script>
</body>
</html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>MochiVocab - Học từ vựng Anki</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Nunito:wght@500;600;700;800;900&family=Quicksand:wght@500;600;700;800&display=swap" rel="stylesheet">
<style>
:root {
--bg-gray: #EBEBEB;
--lv1: #EB5757;
--lv2: #FFCB08;
--lv3: #56CCF2;
--lv4: #2F80ED;
--lv5: #1B3A70;
--green-sheet: #22C55E;
--red-sheet: #EF4444;
--mochi-yellow: #FFCB08;
--mochi-orange: #F59E0B;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: 'Nunito', 'Quicksand', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
-webkit-tap-highlight-color: transparent;
}
body {
background-color: var(--bg-gray);
color: #1F2937;
min-height: 100vh;
display: flex;
flex-direction: column;
overflow-x: hidden;
position: relative;
}
/* Background Decorative White Clouds & Copyright */
.cloud-bg {
position: fixed;
inset: 60px 0 0 0;
pointer-events: none;
z-index: 0;
overflow: hidden;
}
.cloud-left-top {
position: absolute;
left: -60px;
top: 55px;
width: 310px;
height: 185px;
background: #F7F7F7;
border-radius: 120px;
}
.cloud-left-top::before {
content: '';
position: absolute;
top: -55px;
left: 50px;
width: 160px;
height: 160px;
background: #F7F7F7;
border-radius: 50%;
}
.cloud-left-bottom {
position: absolute;
left: 110px;
bottom: -40px;
width: 260px;
height: 160px;
background: #F7F7F7;
border-radius: 100px;
}
.cloud-right-bottom {
position: absolute;
right: -50px;
bottom: 30px;
width: 280px;
height: 220px;
background: #F7F7F7;
border-radius: 130px;
}
.cloud-right-bottom::before {
content: '';
position: absolute;
top: 50px;
left: -65px;
width: 140px;
height: 140px;
background: #F7F7F7;
border-radius: 50%;
}
.copyright-tag {
position: fixed;
left: 16px;
bottom: 18px;