Learning is the language you're studying. From is the language you'll see its translations in.
Warn before saving near-duplicate translations
Keyboard shortcut badges on game buttons
Give each flashcard a consistent pastel color
When you open Pretzel from your Home Screen, go straight to practice instead of the translator
Keep language and other preferences in step with your other devices. Turn off to let this device keep its own settings.
Spaced Learning settings
Control how far into the future your answers push each word's next review. Longer waits for words you know well, shorter ones for words you're still learning.
Choose the three options for sorting your cards
How far a right or wrong answer postpones the next review. The Write game lands in between, based on how close your answer was
Manage your vocabulary
Import new words in bulk, or scan your saved vocabulary for duplicates.
You can import vocabulary from another app, like Quizlet or your own spreadsheet with translations.
Paste a list of words or sentences, one per line. Add translations with a tab, dash, equals sign, semicolon or comma (e.g. Hund - dog). We will detect them, and automatically divide them. Lines without a translation get translated automatically.
Swap languages
Scan your saved vocabulary for repeated or very similar translations, and clean them up in one place.
Perfect matches — same word and translation, saved more than once:
Similar matches — closest first. Tap × to delete one, or remove them all in bulk (the one with less practice history goes):
Download a spreadsheet (CSV) with every word and translation you've saved, along with your practice history.
How do you want to sync your vocabulary?
Pick where your saved words live. You can switch later from this same screen.
Set up on our server
We create a private space for you in a few seconds — just pick a PIN. Faster and easier, but your words live on our server instead of one only you control.
Set up with Google Drive
A few more steps to connect your own spreadsheet. The most private option — nothing about your vocabulary touches our servers.
I already have an account
Set up your server space
Your private code (not your email) is what keeps this space yours and what you'll use to sync a second device. We only ask for your email so we can help you recover your code by hand if you ever lose it — we won't use it for anything else.
Back
Sync with your existing link
Paste what Pretzel gave you when you first set this up — your server code, or your Google Sheet's Web app link, either works. You'll find it in Pretzel settings on the other device, or wherever you saved it.
You've set up the spreadsheet and your vocabulary is synced! Copy your Web App URL below, and paste it into another device to sync your vocabulary there too.
Follow these steps to sync your spreadsheet with vocabulary
⚠︎ It's better that you complete the first set up from a computer.
1
Create a new, blank spreadsheet in Google Sheets (you can call it 'Vocabulary', and you can change this name later).
2
In the top bar of Google Sheets (File, Edit, View...), click on Extensions and select Apps Script.
3
Delete any existing code in the scripts editor window, and paste this script, and only this script on the editor:
4
Click on Deploy (top right), then select New deployment.
5
Click the gear icon next to "Select type", pick Web app. Configure:
Description: Vocab (for example)
Execute as: Me (your email)
Who has access: Anyone (the last option)
6
Click Deploy, and authorize the security permissions. These will ask you to let your script read and edit your spreadsheet. It won't give Pretzel access to your data. Click Authorize Access, log in, click Advanced (bottom left), Go to [your project's name] (unsafe), and Continue.
7
Copy the Web app link (the second link) and paste it below:
Expand instructions
·
Delete my account
·
Log out
Back
·
I already have a Web App URL
What is Pretzel?
Pretzel is a small web app to help learn languages, designed as a weekend project for my journey learning German. I use it to keep my vocabulary, and retrain the words and sentences I want to remember.
How to use The idea is that you save Pretzel to your phone's home screen and use it as your daily translator. The perk is that you can save everything you translate to learn it later. As often as you'd like, you can rehearse your saved translations through different exercises, like multiple choice or typing them out. The goal is to make it easy to regularly review your vocabulary using spaced repetition, which reinforces your learning over time. Right now, Pretzel supports a few languages, but reach out if you'd like another one added!
How's the data stored I have zero access to your data. Your saved vocabulary is stored directly on your personal Google Sheet. Pretzel simply stores the access key locally on your device to communicate with it. When you configure the Apps Script (using the setup steps above), you are essentially creating a secure, private bridge between this app and your spreadsheet, allowing them to talk directly to each other without a middleman. Nothing is saved on our servers. The only tracking metric used is GoatCounter—a privacy-friendly analytics tool that provides basic, non-identifiable usage statistics so I know the app is functioning properly.
How is the translator working The app relies on an open-source translation service to reliably pull definitions and translations for free.
Who's behind this That would be me, Hector Mangas. My background is in cognitive psychology, but with the help of Gemini, I can code a little! I was learning German this summer and found most flashcard apps very frustrating. I wanted to create a translator app that could seamlessly save and help me rehearse the things that actually interested me. If you'd like to get in touch, just send me an email! You can also check out more of my work on my site, hectormangas.com.
We're sorry to see you go
Deleting your account...
One last step
We have successfully removed all of your data from our servers. The spreadsheet you synced your vocabulary with, though, still has your data in it.
If you also want to delete your vocabulary, head over to your Google Drive, and manually remove your sheet there.
Pretzel is sorry to see you go, and we hope we get to meet again.
/**
* ULTRA-SCALABLE GOOGLE APPS SCRIPT BACKEND FOR FLASHCARD PRACTICE
* Supports infinite rows by performing heavy sorting, filtering,
* and distractor generation entirely on Google's servers.
*
* Column-independent: scans row 1 headers dynamically.
*
* The two word columns are labelled "Learning" / "From" on a new sheet -
* generic names, since Pretzel now supports many languages, not just German
* from English. "Deutsch"/"English" (and the older bare "de"/"en") are still
* recognized as aliases so existing sheets keep working untouched. If you'd
* like an existing sheet's headers relabelled too, open the Apps Script
* editor, select renameLanguageHeaders_ from the function dropdown and run it
* once - it only touches row 1's text, never any data.
*/
// Use the active sheet (the original, working behavior) whenever it actually
// has data. Only if the active tab is blank do we look for another tab that has
// a recognized word column (Learning/From, or the older Deutsch/English/de/en),
// so a stray empty "active" tab can't make the app load zero cards. This never
// overrides a real vocabulary tab that's already selected.
function getVocabSheet_() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var active = ss.getActiveSheet();
if (active && active.getLastColumn() > 0 && active.getLastRow() > 1) return active;
var sheets = ss.getSheets();
for (var s = 0; s < sheets.length; s++) {
var sh = sheets[s];
if (sh.getLastColumn() === 0 || sh.getLastRow() <= 1) continue;
var hdr = sh.getRange(1, 1, 1, sh.getLastColumn()).getValues()[0].map(function (h) {
return h.toString().toLowerCase().trim();
});
if (firstIndexOf_(hdr, ["learning", "deutsch", "de"]) !== -1 ||
firstIndexOf_(hdr, ["from", "english", "en"]) !== -1) {
return sh;
}
}
return active || sheets[0];
}
function doGet(e) {
try {
var sheet = getVocabSheet_();
var data = sheet.getDataRange().getValues();
if (data.length === 0) {
return makeJSONResponse({ error: "Empty sheet" });
}
var headers = data[0].map(function(h) { return h.toString().toLowerCase().trim(); });
// Resolve column indexes dynamically
var idIdx = headers.indexOf("id");
// "learning" is the current header label; "deutsch"/"de" are older aliases
// (this used to be a German-only app) kept for sheets created before the
// multi-language rename.
var deIdx = firstIndexOf_(headers, ["learning", "deutsch", "de"]);
var enIdx = firstIndexOf_(headers, ["from", "english", "en"]);
var dateAddedIdx = headers.indexOf("dateadded");
var practiceCountIdx = headers.indexOf("practicecount");
var lastPracticeIdx = headers.indexOf("lastpractice");
var nextPracticeIdx = headers.indexOf("nextpractice") !== -1 ? headers.indexOf("nextpractice") : headers.indexOf("nextpracticedate");
var correctCountIdx = headers.indexOf("correctcount");
var incorrectCountIdx = headers.indexOf("incorrectcount");
var statusIdx = headers.indexOf("status");
// Fallbacks
if (idIdx === -1) idIdx = 0;
if (deIdx === -1) deIdx = 1;
if (enIdx === -1) enIdx = 2;
if (dateAddedIdx === -1) dateAddedIdx = 3;
if (practiceCountIdx === -1) practiceCountIdx = 4;
if (lastPracticeIdx === -1) lastPracticeIdx = 5;
if (nextPracticeIdx === -1) nextPracticeIdx = 6;
if (correctCountIdx === -1) correctCountIdx = 7;
if (incorrectCountIdx === -1) incorrectCountIdx = 8;
if (statusIdx === -1) statusIdx = 9;
var action = e.parameter.action;
var now = Date.now();
// OPTIMIZATION 1: Fast metadata summary response (Instantly loads home screen)
if (action === 'getStats') {
var stats = {
graduated: 0,
rehearsed: 0,
pending: 0,
dueToday: 0,
mistakeCount: 0,
articleCount: 0,
readyToGrad: 0,
totalReps: 0
};
for (var i = 1; i < data.length; i++) {
var row = data[i];
if (!row[deIdx] && !row[enIdx]) continue;
var status = row[statusIdx] ? row[statusIdx].toString().trim() : "new";
var practiceCount = parseInt(row[practiceCountIdx]) || 0;
var incorrectCount = parseInt(row[incorrectCountIdx]) || 0;
var correctCount = parseInt(row[correctCountIdx]) || 0;
var nextPracticeVal = row[nextPracticeIdx];
var nextPracticeDate = 0;
if (nextPracticeVal) {
try { nextPracticeDate = new Date(nextPracticeVal).getTime(); } catch(err) { nextPracticeDate = 0; }
}
stats.totalReps += practiceCount;
// General categories
if (status === 'graduated' || status === 'retired') {
stats.graduated++;
} else if (practiceCount === 0 || status === 'new') {
stats.pending++;
} else if (practiceCount > 0) {
stats.rehearsed++;
}
// Game specific categories
if (nextPracticeDate <= now && status !== 'graduated' && status !== 'retired') {
stats.dueToday++;
}
if (incorrectCount > 0 && status !== 'graduated' && status !== 'retired') {
stats.mistakeCount++;
}
if (/^(der|die|das)\s+/i.test(row[deIdx]) && status !== 'graduated' && status !== 'retired') {
stats.articleCount++;
}
// Ready to graduate metrics
if (status !== 'graduated' && status !== 'retired' && practiceCount >= 10) {
var ratio = 0;
if (correctCount > 0) {
ratio = (incorrectCount === 0) ? correctCount : (correctCount / incorrectCount);
}
if (ratio >= 2) {
var dateVal = row[dateAddedIdx];
var parsedAdded = dateVal ? Date.parse(dateVal) : 0;
if (!isNaN(parsedAdded) && (now - parsedAdded > 30 * 24 * 60 * 60 * 1000)) {
stats.readyToGrad++;
}
}
}
}
return makeJSONResponse(stats);
}
// OPTIMIZATION 2: Server-side Sorting and Distractors generation for active 10 cards
if (action === 'getGameCards') {
var gameMode = e.parameter.gameMode;
var excludeRows = JSON.parse(e.parameter.excludeRows || "[]").map(Number);
var cardsPool = [];
for (var i = 1; i < data.length; i++) {
var row = data[i];
if (!row[deIdx] && !row[enIdx]) continue;
var status = row[statusIdx] ? row[statusIdx].toString().trim() : "new";
var practiceCount = parseInt(row[practiceCountIdx]) || 0;
var incorrectCount = parseInt(row[incorrectCountIdx]) || 0;
var correctCount = parseInt(row[correctCountIdx]) || 0;
var nextPracticeVal = row[nextPracticeIdx];
var nextPracticeDate = 0;
if (nextPracticeVal) {
try { nextPracticeDate = new Date(nextPracticeVal).getTime(); } catch(err) { nextPracticeDate = 0; }
}
var lastPracticeVal = row[lastPracticeIdx];
var lastPracticeDate = 0;
if (lastPracticeVal) {
try { lastPracticeDate = new Date(lastPracticeVal).getTime(); } catch(err) { lastPracticeDate = 0; }
}
cardsPool.push({
rowIndex: i + 1,
id: row[idIdx] ? row[idIdx].toString().trim() : "",
de: row[deIdx] ? row[deIdx].toString().trim() : "",
en: row[enIdx] ? row[enIdx].toString().trim() : "",
dateAdded: row[dateAddedIdx] ? row[dateAddedIdx].toString() : "",
lastPracticeDate: lastPracticeDate,
nextPracticeDate: nextPracticeDate,
status: status,
practiceCount: practiceCount,
correctCount: correctCount,
incorrectCount: incorrectCount
});
}
var filtered = [];
if (gameMode === 'dueToday') {
var due = cardsPool.filter(function(c) {
return c.nextPracticeDate <= now && c.status !== 'graduated' && c.status !== 'retired';
});
var available = due.filter(function(c) { return excludeRows.indexOf(c.rowIndex) === -1; });
if (available.length === 0 && due.length > 0) available = due;
if (available.length === 0) {
// Chronological Upcoming backfill
var upcoming = cardsPool.filter(function(c) {
return c.nextPracticeDate > now && c.status !== 'graduated' && c.status !== 'retired';
}).sort(function(a, b) { return a.nextPracticeDate - b.nextPracticeDate; });
filtered = upcoming.slice(0, 10);
} else {
filtered = available.sort(function() { return 0.5 - Math.random(); }).slice(0, 10);
}
}
else if (gameMode === 'newWords') {
var pending = cardsPool.filter(function(c) {
return (c.practiceCount === 0 || c.status === 'new') && c.status !== 'graduated' && c.status !== 'retired';
});
var available = pending.filter(function(c) { return excludeRows.indexOf(c.rowIndex) === -1; });
if (available.length === 0 && pending.length > 0) available = pending;
filtered = available.sort(function() { return 0.5 - Math.random(); }).slice(0, 10);
}
else if (gameMode === 'shuffle') {
var rehearsed = cardsPool.filter(function(c) {
return c.practiceCount > 0 && c.status !== 'graduated' && c.status !== 'retired';
});
filtered = rehearsed.sort(function() { return 0.5 - Math.random(); }).slice(0, 10);
}
else if (gameMode === 'mistaken') {
var activePool = cardsPool.filter(function(c) { return c.status !== 'graduated' && c.status !== 'retired'; });
activePool.sort(function(a, b) {
var ratioA = (a.correctCount + a.incorrectCount) > 0 ? (a.incorrectCount / (a.correctCount + a.incorrectCount)) : 0;
var ratioB = (b.correctCount + b.incorrectCount) > 0 ? (b.incorrectCount / (b.correctCount + b.incorrectCount)) : 0;
if (ratioB !== ratioA) return ratioB - ratioA;
if (a.practiceCount !== b.practiceCount) return a.practiceCount - b.practiceCount;
var lastA = a.lastPracticeDate ? a.lastPracticeDate : now;
var lastB = b.lastPracticeDate ? b.lastPracticeDate : now;
return lastA - lastB;
});
var available = activePool.filter(function(c) { return excludeRows.indexOf(c.rowIndex) === -1; });
if (available.length === 0 && activePool.length >= 10) available = activePool;
filtered = available.slice(0, 10);
}
else if (gameMode === 'article') {
var articlePool = cardsPool.filter(function(c) {
return /^(der|die|das)\s+/i.test(c.de) && c.status !== 'graduated' && c.status !== 'retired';
});
articlePool.sort(function(a, b) {
var ratioA = (a.correctCount + a.incorrectCount) > 0 ? (a.incorrectCount / (a.correctCount + a.incorrectCount)) : 0;
var ratioB = (b.correctCount + b.incorrectCount) > 0 ? (b.incorrectCount / (b.correctCount + b.incorrectCount)) : 0;
if (ratioB !== ratioA) return ratioB - ratioA;
if (a.practiceCount !== b.practiceCount) return a.practiceCount - b.practiceCount;
var lastA = a.lastPracticeDate ? a.lastPracticeDate : now;
var lastB = b.lastPracticeDate ? b.lastPracticeDate : now;
return lastA - lastB;
});
var available = articlePool.filter(function(c) { return excludeRows.indexOf(c.rowIndex) === -1; });
if (available.length === 0 && articlePool.length >= 10) available = articlePool;
filtered = available.slice(0, 10);
}
else if (gameMode === 'graduate') {
var eligible = cardsPool.filter(function(c) {
if (c.status === 'graduated' || c.status === 'retired') return false;
if (c.practiceCount < 10) return false;
var ratio = 0;
if (c.correctCount > 0) {
ratio = (c.incorrectCount === 0) ? c.correctCount : (c.correctCount / c.incorrectCount);
}
if (ratio < 2) return false;
if (!c.dateAdded) return false;
var parsedAdded = Date.parse(c.dateAdded);
return (!isNaN(parsedAdded) && (now - parsedAdded > 30 * 24 * 60 * 60 * 1000));
});
eligible.sort(function(a, b) { return b.practiceCount - a.practiceCount; });
var available = eligible.filter(function(c) { return excludeRows.indexOf(c.rowIndex) === -1; });
if (available.length === 0 && eligible.length > 0) available = eligible;
filtered = available.slice(0, 10);
}
// Inject smart distractors on the server side to save client processing power
filtered.forEach(function(card) {
var hasQ = card.en.indexOf('?') !== -1;
var hasS = card.en.indexOf('/') !== -1;
var hasC = card.en.indexOf(',') !== -1;
var pool = cardsPool.filter(function(c) { return c.en !== card.en; });
if (hasQ) pool = pool.filter(function(c) { return c.en.indexOf('?') !== -1; });
if (hasS) pool = pool.filter(function(c) { return c.en.indexOf('/') !== -1; });
if (hasC) pool = pool.filter(function(c) { return c.en.indexOf(',') !== -1; });
var options = pool.map(function(c) { return c.en; });
options.sort(function() { return 0.5 - Math.random(); });
var selectedDistractors = options.slice(0, 3);
// Pad out distractors if pool is too small
if (selectedDistractors.length < 3) {
var genPool = cardsPool.filter(function(c) { return c.en !== card.en && selectedDistractors.indexOf(c.en) === -1; }).map(function(c) { return c.en; });
genPool.sort(function() { return 0.5 - Math.random(); });
while (selectedDistractors.length < 3 && genPool.length > 0) {
var candidate = genPool.pop();
if (hasQ && candidate.indexOf('?') === -1) candidate += '?';
if (hasS && candidate.indexOf('/') === -1) candidate += ' / alternative';
if (hasC && candidate.indexOf(',') === -1) candidate += ', or similar';
selectedDistractors.push(candidate);
}
}
card.distractors = selectedDistractors;
});
return makeJSONResponse(filtered);
}
// OPTIMIZATION 3: Paged list retrieval for bookmarks modals
if (action === 'getList') {
var type = e.parameter.type;
var filteredList = [];
for (var i = 1; i < data.length; i++) {
var row = data[i];
if (!row[deIdx] && !row[enIdx]) continue;
var status = row[statusIdx] ? row[statusIdx].toString().trim() : "new";
var practiceCount = parseInt(row[practiceCountIdx]) || 0;
var nextPracticeVal = row[nextPracticeIdx];
var nextPracticeDate = 0;
if (nextPracticeVal) {
try { nextPracticeDate = new Date(nextPracticeVal).getTime(); } catch(err) { nextPracticeDate = 0; }
}
var match = false;
if (type === 'graduated' && (status === 'graduated' || status === 'retired')) match = true;
if (type === 'rehearsed' && practiceCount > 0 && status !== 'graduated' && status !== 'retired') match = true;
if (type === 'pending' && (practiceCount === 0 || status === 'new') && status !== 'graduated' && status !== 'retired') match = true;
if (match) {
filteredList.push({
rowIndex: i + 1,
de: row[deIdx] ? row[deIdx].toString().trim() : "",
en: row[enIdx] ? row[enIdx].toString().trim() : "",
dateAdded: row[dateAddedIdx] ? row[dateAddedIdx].toString() : "",
practiceCount: practiceCount,
correctCount: (correctCountIdx !== -1) ? parseInt(row[correctCountIdx]) || 0 : 0,
incorrectCount: (incorrectCountIdx !== -1) ? parseInt(row[incorrectCountIdx]) || 0 : 0,
status: status
});
}
}
return makeJSONResponse(filteredList);
}
// OPTIMIZATION 4: Single compressed payload for initial background sync
if (action === 'getAllBookmarksCompressed') {
var headers = ["rowIndex", "id", "de", "en", "dateAdded", "practiceCount", "lastPracticeDate", "nextPracticeDate", "correctCount", "incorrectCount", "status"];
var rows = [];
for (var i = 1; i < data.length; i++) {
var row = data[i];
if (!row[deIdx] && !row[enIdx]) continue;
var nextPracticeVal = row[nextPracticeIdx];
var nextPracticeDate = 0;
if (nextPracticeVal) {
try { nextPracticeDate = new Date(nextPracticeVal).getTime(); } catch(err) { nextPracticeDate = 0; }
}
var lastPracticeVal = row[lastPracticeIdx];
var lastPracticeDate = 0;
if (lastPracticeVal) {
try { lastPracticeDate = new Date(lastPracticeVal).getTime(); } catch(err) { lastPracticeDate = 0; }
}
rows.push([
i + 1,
row[idIdx] ? row[idIdx].toString().trim() : "",
row[deIdx] ? row[deIdx].toString().trim() : "",
row[enIdx] ? row[enIdx].toString().trim() : "",
row[dateAddedIdx] ? row[dateAddedIdx].toString() : "",
parseInt(row[practiceCountIdx]) || 0,
lastPracticeDate,
nextPracticeDate,
(correctCountIdx !== -1) ? parseInt(row[correctCountIdx]) || 0 : 0,
(incorrectCountIdx !== -1) ? parseInt(row[incorrectCountIdx]) || 0 : 0,
row[statusIdx] ? row[statusIdx].toString().trim() : "new"
]);
}
return makeJSONResponse({ headers: headers, rows: rows });
}
} catch(err) {
return makeJSONResponse({ error: err.toString() });
}
}
function doPost(e) {
try {
var payload = JSON.parse(e.postData.contents);
var sheet = getVocabSheet_();
var data = sheet.getDataRange().getValues();
var lastCol = sheet.getLastColumn();
var headers = [];
if (data.length > 0) {
headers = data[0].map(function(h) { return h.toString().toLowerCase().trim(); });
} else {
// Create column structure if the sheet is completely blank. Generic
// "Learning" / "From" labels, not "Deutsch"/"English" - Pretzel supports
// many languages now, not just German from English.
headers = ["id", "learning", "from", "dateadded", "practicecount", "lastpractice", "nextpractice", "correctcount", "incorrectcount", "status"];
sheet.appendRow(["ID", "Learning", "From", "dateAdded", "PracticeCount", "LastPractice", "NextPractice", "correctCount", "incorrectCount", "Status"]);
}
// Resolve Indices
var idIdx = headers.indexOf("id");
// "learning" is the current header label; "deutsch"/"de" are older aliases
// (this used to be a German-only app) kept for sheets created before the
// multi-language rename.
var deIdx = firstIndexOf_(headers, ["learning", "deutsch", "de"]);
var enIdx = firstIndexOf_(headers, ["from", "english", "en"]);
var dateAddedIdx = headers.indexOf("dateadded");
var practiceCountIdx = headers.indexOf("practicecount");
var lastPracticeIdx = headers.indexOf("lastpractice");
var nextPracticeIdx = headers.indexOf("nextpractice") !== -1 ? headers.indexOf("nextpractice") : headers.indexOf("nextpracticedate");
var correctCountIdx = headers.indexOf("correctcount");
var incorrectCountIdx = headers.indexOf("incorrectcount");
var statusIdx = headers.indexOf("status");
// Position Map Fallbacks
if (idIdx === -1) idIdx = 0;
if (deIdx === -1) deIdx = 1;
if (enIdx === -1) enIdx = 2;
if (dateAddedIdx === -1) dateAddedIdx = 3;
if (practiceCountIdx === -1) practiceCountIdx = 4;
if (lastPracticeIdx === -1) lastPracticeIdx = 5;
if (nextPracticeIdx === -1) nextPracticeIdx = 6;
if (correctCountIdx === -1) correctCountIdx = 7;
if (incorrectCountIdx === -1) incorrectCountIdx = 8;
if (statusIdx === -1) statusIdx = 9;
var action = payload.action;
// ACTION 1: ADD NEW TRANSLATION
if (action === 'add' || (!action && !payload.rowIndex)) {
var newRow = [];
for (var i = 0; i < Math.max(10, headers.length); i++) {
newRow.push("");
}
newRow[idIdx] = payload.id || "";
newRow[deIdx] = payload.de || "";
newRow[enIdx] = payload.en || "";
newRow[dateAddedIdx] = payload.dateAdded || new Date().toISOString();
newRow[practiceCountIdx] = payload.practiceCount !== undefined ? payload.practiceCount : 0;
newRow[lastPracticeIdx] = payload.lastPracticeDate || "";
newRow[nextPracticeIdx] = payload.nextPracticeDate || new Date().toISOString();
newRow[correctCountIdx] = payload.correctCount !== undefined ? payload.correctCount : 0;
newRow[incorrectCountIdx] = payload.incorrectCount !== undefined ? payload.incorrectCount : 0;
newRow[statusIdx] = payload.status || "new";
sheet.appendRow(newRow);
return makeJSONResponse({ status: "success", message: "Added successfully" });
}
// ACTION 2: DELETE TRANSLATION
if (action === 'delete') {
var deTarget = (payload.de || "").toLowerCase().trim();
var enTarget = (payload.en || "").toLowerCase().trim();
for (var r = 1; r < data.length; r++) {
var row = data[r];
var deVal = (row[deIdx] || "").toString().toLowerCase().trim();
var enVal = (row[enIdx] || "").toString().toLowerCase().trim();
if (deVal === deTarget && enVal === enTarget) {
sheet.deleteRow(r + 1);
return makeJSONResponse({ status: "success", message: "Deleted successfully" });
}
}
return makeJSONResponse({ status: "error", message: "Translation not found" });
}
// ACTION 3: UPDATE STATISTICS / DATES (CARDS SYSTEM)
if (action === 'updateStats') {
var rowIndex = parseInt(payload.rowIndex);
if (!rowIndex || rowIndex <= 1 || rowIndex > data.length) {
return makeJSONResponse({ status: "error", message: "Invalid rowIndex: " + rowIndex });
}
// When the review clock is paused, leave the existing next-review date untouched.
if (!payload.skipReviewDate) {
sheet.getRange(rowIndex, nextPracticeIdx + 1).setValue(payload.nextPracticeDate);
}
sheet.getRange(rowIndex, statusIdx + 1).setValue(payload.status);
sheet.getRange(rowIndex, lastPracticeIdx + 1).setValue(new Date().toISOString());
if (payload.incrementPractice) {
var practiceRange = sheet.getRange(rowIndex, practiceCountIdx + 1);
var count = parseInt(practiceRange.getValue()) || 0;
practiceRange.setValue(count + 1);
}
if (payload.isCorrect !== undefined && payload.isCorrect !== null) {
var isTrue = (payload.isCorrect === true || payload.isCorrect === "true");
var targetColIdx = isTrue ? correctCountIdx : incorrectCountIdx;
var cellRange = sheet.getRange(rowIndex, targetColIdx + 1);
var curHits = parseInt(cellRange.getValue()) || 0;
cellRange.setValue(curHits + 1);
}
return makeJSONResponse({ status: "success", message: "Stats updated successfully" });
}
return makeJSONResponse({ status: "error", message: "Invalid action" });
} catch(err) {
return makeJSONResponse({ status: "error", message: err.toString() });
}
}
function makeJSONResponse(obj) {
return ContentService.createTextOutput(JSON.stringify(obj))
.setMimeType(ContentService.MimeType.JSON);
}
// Return the index of the first header (case-insensitive, already lowercased
// by the caller) found among `names`, checked in priority order, or -1.
function firstIndexOf_(headers, names) {
for (var i = 0; i < names.length; i++) {
var idx = headers.indexOf(names[i]);
if (idx !== -1) return idx;
}
return -1;
}
/* ===== ONE-TIME MIGRATION (optional) ===== */
// Relabels row 1's word-column headers from the old German-only names
// ("Deutsch"/"English", or bare "de"/"en") to the generic "Learning"/"From" -
// text only, no data is touched, and columns stay in the same position. Safe
// to run any time; it's a no-op if the headers are already "Learning"/"From"
// or don't match a recognized old name (in which case it leaves them alone).
function renameLanguageHeaders_() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lastCol = sheet.getLastColumn();
if (lastCol === 0) { Logger.log('Sheet is empty - nothing to rename.'); return; }
var headerRange = sheet.getRange(1, 1, 1, lastCol);
var headers = headerRange.getValues()[0];
var lower = headers.map(function (h) { return h.toString().toLowerCase().trim(); });
var deIdx = firstIndexOf_(lower, ["deutsch", "de"]);
var enIdx = firstIndexOf_(lower, ["english", "en"]);
var changed = false;
if (deIdx !== -1 && lower[deIdx] !== "learning") { headers[deIdx] = "Learning"; changed = true; }
if (enIdx !== -1 && lower[enIdx] !== "from") { headers[enIdx] = "From"; changed = true; }
if (changed) {
headerRange.setValues([headers]);
Logger.log('Renamed header(s) to Learning/From.');
} else {
Logger.log('Nothing to rename - headers are already Learning/From, or no Deutsch/English/de/en column was found.');
}
}