Skip to content

Commit

Permalink
fix: translate task lang settings update
Browse files Browse the repository at this point in the history
  • Loading branch information
windingwind committed Dec 10, 2024
1 parent ae203ed commit e132380
Showing 1 changed file with 31 additions and 1 deletion.
32 changes: 31 additions & 1 deletion src/utils/task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ export interface TranslateTask {
* Generated at task runtime.
*/
langto?: string;
/**
* Whether the from language is inferred.
*/
langfromInferred?: boolean;
/**
* Service secret.
*
Expand Down Expand Up @@ -82,6 +86,10 @@ export interface TranslateTask {
* If not provided, the call will fail.
*/
callerID?: string;
/**
* If the task is once processed.
*/
processed?: boolean;
}

export type TranslateTaskProcessor = (
Expand All @@ -99,11 +107,19 @@ export class TranslateTaskRunner {
const ztoolkit = addon.data.ztoolkit;
if (!data.langfrom || !data.langto) {
ztoolkit.log("try auto detect language");
const { fromLanguage, toLanguage } = autoDetectLanguage(
const { fromLanguage, toLanguage, isInferred } = autoDetectLanguage(
Zotero.Items.get(data.itemId || -1),
);
data.langfrom = data.langfrom || fromLanguage;
data.langto = data.langto || toLanguage;
if (isInferred) {
data.langfromInferred = true;
}
}

// If the task is not new, update language settings
if (data.processed) {
updateTranslateTaskLang(data);
}

data.callerID = data.callerID || config.addonID;
Expand All @@ -118,6 +134,7 @@ export class TranslateTaskRunner {
data.result = this.makeErrorInfo(data.service, String(e));
data.status = "fail";
}
data.processed = true;
}

protected makeErrorInfo(serviceId: string, detail: string) {
Expand Down Expand Up @@ -325,6 +342,16 @@ export function getLastTranslateTask<
return undefined;
}

/**
* Update the task with the latest language settings.
*/
export function updateTranslateTaskLang(task: TranslateTask) {
if (!task.langfromInferred) {
task.langfrom = getPref("sourceLanguage") as string;
}
task.langto = getPref("targetLanguage") as string;
}

export function putTranslateTaskAtHead(taskId: string) {
const queue = (Zotero[config.addonInstance] as Addon).data.translate.queue;
const idx = queue.findIndex((task) => task.id === taskId);
Expand Down Expand Up @@ -358,6 +385,7 @@ export function autoDetectLanguage(item: Zotero.Item | null) {
toLanguage,
};
}
let isInferred = false;
if (getPref("enableAutoDetectLanguage")) {
if (topItem) {
let itemLanguage: string =
Expand All @@ -384,11 +412,13 @@ export function autoDetectLanguage(item: Zotero.Item | null) {
ztoolkit.log("use autoDetect", itemLanguage);
// If the item language is not the same as the target/source language, use it
detectedFromLanguage = itemLanguage;
isInferred = true;
}
}
}
return {
fromLanguage: detectedFromLanguage,
toLanguage,
isInferred,
};
}

0 comments on commit e132380

Please sign in to comment.