Skip to content

Commit

Permalink
fix(fix related to popup and translate): changes made to fix issues 4…
Browse files Browse the repository at this point in the history
…6,47 and 51 (#52)

fix/46_47_51

Co-authored-by: Sathya Shanmugha <[email protected]>
  • Loading branch information
sathyan13 and Sathya Shanmugha authored Feb 22, 2023
1 parent aaf3741 commit ca8510a
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 17 deletions.
6 changes: 6 additions & 0 deletions src/_contracts/translate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ export interface TranslateData {

export type Documents = string[];

export type TranslatedDocuments = {
translatedText: Documents;
sourceLanguage: string;
};

export type SourceLanguauge = string;
export interface NodeMap {
[key: string]: Node;
}
Expand Down
3 changes: 1 addition & 2 deletions src/background/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ browser.contextMenus.onClicked.addListener((info): void => {

void sendMessage(
'translate-selection',
{ translatedText: escape(translatedDocs[0]) },
{ translatedText: escape(translatedDocs.translatedText[0]) },
{
context: 'content-script',
tabId,
Expand All @@ -179,4 +179,3 @@ browser.contextMenus.onClicked.addListener((info): void => {
}
})();
});
// }
10 changes: 7 additions & 3 deletions src/contentScripts/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
PageMap,
CacheLangs,
CacheTextMap,
TranslatedDocuments,
} from '../_contracts';
import { IGNORED_NODES, DOC_BOUNDARY, PAGE_SPLIT_PATTERN } from '../constants';

Expand Down Expand Up @@ -114,25 +115,28 @@ export async function translateMany(
SourceLanguageCode: string,
TargetLanguageCode: string,
docs: Documents
): Promise<Documents> {
): Promise<TranslatedDocuments> {
const client = new TranslateClient(creds);
const responses = await sendDocumentsToTranslate(
client,
SourceLanguageCode,
TargetLanguageCode,
docs
);

if (responses.some(res => res.status === 'rejected')) {
throw new Error('One or more parts of the document failed to translate.');
}

return responses.reduce((docs, response) => {
let sourceLanguageResponse = '';

const translateTextResponse = responses.reduce((docs, response) => {
if (response.status === 'fulfilled') {
sourceLanguageResponse = response.value.SourceLanguageCode ?? '';
return docs.concat([response.value.TranslatedText ?? '']);
}
return docs;
}, [] as Documents);
return { translatedText: translateTextResponse, sourceLanguage: sourceLanguageResponse };
}

/**
Expand Down
14 changes: 9 additions & 5 deletions src/contentScripts/translate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,22 +84,26 @@ async function translateFromApi(
const tDocs = await translateMany(creds, langs.source, langs.target, docs);

// Break the translated documents back into pages
const tPagesRaw = breakDocuments(tDocs);

const tPagesRaw = breakDocuments(tDocs.translatedText);
// Sanitize the pages returned from Amazon Translate
const tPagesSanitized = tPagesRaw.map(page => sanitizePage(page));

// Break the pages into tuples of the node ID and the translated text
const translatedPageMap = createPageMap(tPagesSanitized);

// Make a cache text map for the selected language pair
const textMap = makeCacheTextMap(pageMap, translatedPageMap);

// Cache the translated text map
cacheTranslation(window.location.href, langs.source, langs.target, textMap);
cacheTranslation(window.location.href, tDocs.sourceLanguage, langs.target, textMap);

// Apply the translated documents to the DOM
tPagesSanitized.forEach(page =>
pageIsValid(page) ? swapText(nodeMap, ...splitPage(page)) : undefined
);

/**
* Caching the text map on the reverse order to avoid an extra api call.
* If the initial request is from English -> German it will cached along with German -> English
*/
const textMapReverse = makeCacheTextMap(translatedPageMap, pageMap);
cacheTranslation(window.location.href, langs.target, tDocs.sourceLanguage, textMapReverse);
}
22 changes: 15 additions & 7 deletions src/popup/Popup.vue
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
targetLang: 'en',
},
languages,
prevtargetLang:'',
};
},
mounted() {
Expand All @@ -33,7 +34,8 @@
this.form.sourceLang = lockr.get(ExtensionOptions.DEFAULT_SOURCE_LANG, 'auto');
this.form.targetLang = lockr.get(ExtensionOptions.DEFAULT_TARGET_LANG, 'en');
this.cachingEnabled = lockr.get(ExtensionOptions.CACHING_ENABLED, false);

this.prevtargetLang = lockr.get(ExtensionOptions.DEFAULT_SOURCE_LANG, 'auto');

onMessage('status', async ({ data: _data }) => {
const data = _data as unknown;
const { status, message } = data as TranslateStatusData;
Expand All @@ -47,15 +49,20 @@
* the Amazon Translate API. After the credentials are decrypted it sends them via a message
* to the content-script along with the selected source and target language codes.
*/

async translatePage(e: Event) {
try {
e.preventDefault();
this.status = '';
this.message = '';

this.message = '';
if ([this.region, this.accessKeyId, this.secretAccessKey].includes('')) {
throw new Error('Your credentials are invalid.');
}
if (this.prevtargetLang === this.form.targetLang) {
this.status = 'complete';
this.message = `Translation already in target language`;
return
}

const credentials = {
accessKeyId: this.accessKeyId,
Expand All @@ -71,13 +78,16 @@
const message = {
creds: config,
langs: {
source: this.form.sourceLang,
source: this.form.sourceLang === lockr.get(ExtensionOptions.DEFAULT_SOURCE_LANG, 'auto')?
this.prevtargetLang : this.form.sourceLang,
target: this.form.targetLang,
},
tabId,
cachingEnabled: this.cachingEnabled,
};


this.prevtargetLang = this.form.targetLang;

sendMessage('translate', message, {
context: 'content-script',
tabId,
Expand Down Expand Up @@ -135,7 +145,6 @@
</option>
</select>
</div>

<div>
<select v-model="form.targetLang" class="aws-field">
<option
Expand All @@ -147,7 +156,6 @@
</option>
</select>
</div>

<div>
<aws-button
class="submit-button"
Expand Down

0 comments on commit ca8510a

Please sign in to comment.