Skip to content

Commit

Permalink
Merge pull request #72 from kabir-afk/master
Browse files Browse the repository at this point in the history
Refactor `SignItCoreContent` for browser compatibility & modal init fix
  • Loading branch information
hugolpz authored May 30, 2024
2 parents b17a69f + 22cef05 commit f370d96
Show file tree
Hide file tree
Showing 5 changed files with 59 additions and 65 deletions.
21 changes: 2 additions & 19 deletions SignItCoreContent.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,6 @@
// const { default: backgroundPage } = require("./background-script"); // to try

var banana,resArr;
(async()=>{
resArr = await chrome.runtime.sendMessage({ command: "getBanana" });
console.log(resArr);
const sourceMap = new Map(resArr[0]);
var SignItCoreContent = function (locale,map) {
const sourceMap = new Map(map);
banana = { i18n: (msg,locale) => sourceMap.get(locale)[msg] };
})();

var SignItCoreContent = function (locale) {
// in case of firefox
if ((locale.messageStore.sourceMap) instanceof Map) {
const sourceMap = new Map(locale.messageStore.sourceMap);
locale = locale.locale;
banana = { i18n: (msg,locale) => sourceMap.get(locale)[msg] };
}
else{ // in case of chrome
locale = resArr[1];
}
console.log("Passed trough ! :", locale);
console.log("SignItCoreContent.js",banana );
this.$container = $(`
Expand Down
27 changes: 18 additions & 9 deletions background-script.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ async function loadI18nLocalization( uiLanguageQid ) {
// Declare localisation
banana.setLocale(locale); // Change to new locale
storeParam('bananaInStore',banana)
storeParam("sourceMap", Array.from(banana.messageStore.sourceMap));

state = 'ready';

Expand Down Expand Up @@ -272,7 +273,15 @@ function normalize( selection ) { // this could do more

// Check a string with multiple words and return the word whose record is available
function getAvailableWord( word ) {
const wordArray = word.split(" ");

// while this makes for an ungly regex , I couldn't think of anything else.
// Using metacharcters like /W or /w meant removing accented letters as well, which would have broken
// many french words . . .so I retorted to this;

const regex = /[!"#$%&()*+,-./:;<=>?@[\\\]^_{|}~]/;
const stringWithoutSpecialChars = word.replace(regex,"");
const wordArray = stringWithoutSpecialChars.split(" ");
console.log(wordArray);
for ( let newWord of wordArray ) {
if( records.hasOwnProperty(newWord.toLowerCase()) ){
return newWord;
Expand Down Expand Up @@ -389,13 +398,17 @@ browser.runtime.onMessage.addListener( async function ( message ) {
// inside both chrome and firefox

if (message.command === "checkActiveTabInjections") {
await checkActiveTabInjections(message.currentTabId);
await checkActiveTabInjections(message.argument);
return;
} else if (message.command === "normalizeWordAndReturnFiles") {
const w = normalize(message.text);
const f = wordToFiles(w);
return [w, f];
const word = normalize(message.argument);
const files = wordToFiles(word);
return [word, files];
}
else if (message.command === "changeUiLanguage") {
await changeUiLanguage(message.argument);
return;
}
message = normalizeMessage(message);

// When message 'signit.getfiles' is heard, returns relevant extract of records[]
Expand All @@ -420,10 +433,6 @@ browser.runtime.onMessage.addListener( async function ( message ) {
storeParam([...message.arguments]);
return;
}
// else if (message.command === "changeUiLanguage") {
// await changeUiLanguage(message.newLanguage);
// return;
// }
});

/* *************************************************************** */
Expand Down
9 changes: 6 additions & 3 deletions content_scripts/signit.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,9 +153,10 @@
// Banana test, search `bananaInStore` in files for more
console.log("before")
var BetterBanana = await browser.storage.local.get( 'bananaInStore' );
console.log("after: BetterBanana = ", BetterBanana.bananaInStore)
var messageStore = await browser.storage.local.get( 'sourceMap' );
console.log("after: BetterBanana = ", BetterBanana.bananaInStore.locale,messageStore.sourceMap)

content = new SignItCoreContent(BetterBanana.bananaInStore);
content = new SignItCoreContent(BetterBanana.bananaInStore.locale,messageStore.sourceMap);

// Setup an absolute-positionned $anchorModal we can programatically move
// to be able to point exactly some coords with our popup later
Expand Down Expand Up @@ -217,7 +218,9 @@

// Modal generation or refresh
if ( message.command === 'signit.sign' || message.command === 'signit.hinticon') {
if ( popup === undefined ) { initModalUI(); }
// initialising modal everytime not only when popup is undefined ,
// by this we won't have to reload the web page everytime
initModalUI();
var coords = getSelectionCoords();
repositionElement($anchorModal,coords);
resizeElement($anchorModal,coords);
Expand Down
54 changes: 26 additions & 28 deletions popup/popup.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@ var browser = (browserType === 'firefox') ? browser : (browserType === 'chrome')
this.switchPanel( 'loaded' );
};

async function sendMsgAndExecFn(msg,argument){
const response = await browser.runtime.sendMessage({command:msg,argument});
if (response !== undefined) return response;
}

/* *********************************************************** */
// Browse tab
UI.prototype.initView = async function () {
Expand All @@ -96,7 +101,8 @@ var browser = (browserType === 'firefox') ? browser : (browserType === 'chrome')
// Add the CoreContent view
// similar to what we did in signit.js since here banana is defined solely as per i18n functionality
var BetterBanana = await browser.storage.local.get( 'bananaInStore' );
this.coreContent = new SignItCoreContent(BetterBanana.bananaInStore);
var messageStore = await browser.storage.local.get( 'sourceMap' );
this.coreContent = new SignItCoreContent(BetterBanana.bananaInStore.locale,messageStore.sourceMap);
this.coreContent.getContainer().hide();

// Put all that in the tab
Expand All @@ -107,12 +113,10 @@ var browser = (browserType === 'firefox') ? browser : (browserType === 'chrome')
// if the current window has a selected text, initialise the view with it
var tabs = await browser.tabs.query({active: true, currentWindow: true});

// since we cant send functions through sendMessages, nor can we store them
// in local storage and having a shared common functions file returns
// "checkActiveTabInjections is not defined" error , I am passing message to execute the
// function it directly in sw.js...can't think of anoy other soln as of now
// optimizing message passing for the functions that are present in
// sw.js as well background-script.js

await browser.runtime.sendMessage({command:"checkActiveTabInjections",currentTabId:tabs[0].id });
await sendMsgAndExecFn("checkActiveTabInjections",tabs[0].id);
var selection = await browser.tabs.sendMessage( tabs[ 0 ].id, {
command: "signit.getSelection",
} );
Expand All @@ -131,10 +135,7 @@ var browser = (browserType === 'firefox') ? browser : (browserType === 'chrome')
}
// runs normalize function and wordToFiles in a single go and retruns an array of _word and _files

const [_word, _files] = await browser.runtime.sendMessage({
command: "normalizeWordAndReturnFiles",
text: text,
});
const [_word,_files] = await sendMsgAndExecFn("normalizeWordAndReturnFiles",text);
this.coreContent.refresh(_word, _files);
// this.searchWidget.setValue( _word );
this.coreContent.getContainer().show();
Expand Down Expand Up @@ -188,7 +189,7 @@ var browser = (browserType === 'firefox') ? browser : (browserType === 'chrome')
}

if ( store !== false ) {
await browser.runtime.sendMessage({command:"storeParam",arguments:['history', this.history ]})
await sendMsgAndExecFn("storeParam",['history', this.history ]);
}
}

Expand Down Expand Up @@ -338,17 +339,17 @@ var browser = (browserType === 'firefox') ? browser : (browserType === 'chrome')
// _backgroundPage.storeParam( 'uiLanguage', _backgroundPage.params.uiLanguage ); // uiLanguage in localStorage before first usage-change
historyWidget.on( 'change', function( val ) {
val = parseInt( val ) >=0 ? parseInt( val ) : 0;
_backgroundPage.storeParam( 'historylimit', val );
sendMsgAndExecFn("storeParam",['historylimit', val])
this.cleanHistory();
}.bind( this ) );
wpintegrationWidget.on( 'change', () => _backgroundPage.storeParam('wpintegration',!_backgroundPage.params.wpintegration) );
twospeedWidget.on( 'change', () => _backgroundPage.storeParam('twospeed',!_backgroundPage.params.twospeed) );
// _backgroundPage.storeParam( 'twospeed', _backgroundPage.params.twospeed ); // twospeed in localStorage before first usage-change
hinticonWidget.on('change', () => _backgroundPage.storeParam('hinticon',!_backgroundPage.params.hinticon));
coloredwordsWidget.on('change', () => _backgroundPage.storeParam('coloredwords',!_backgroundPage.params.coloredwords));
wpintegrationWidget.on( 'change', () => sendMsgAndExecFn("storeParam",['wpintegration',!_backgroundPage.params.wpintegration]) );
twospeedWidget.on( 'change', () => sendMsgAndExecFn("storeParam",['twospeed',!_backgroundPage.params.twospeed] ));
// sendMsgAndExecFn("storeParam"( 'twospeed', _backgroundPage.params.twospeed ); // twospeed in localStorage before first usage-change
hinticonWidget.on('change', () => sendMsgAndExecFn("storeParam",['hinticon',!_backgroundPage.params.hinticon]));
coloredwordsWidget.on('change', () => sendMsgAndExecFn("storeParam",['coloredwords',!_backgroundPage.params.coloredwords]));
// Listen for item selection events
choosepanelsWidget.on('choose', (d)=>{
_backgroundPage.storeParam('choosepanels', d.getData());
sendMsgAndExecFn("storeParam",['choosepanels', d.getData()]);
});

// Build Settings UI
Expand Down Expand Up @@ -393,16 +394,13 @@ var browser = (browserType === 'firefox') ? browser : (browserType === 'chrome')
ui.switchPanel( 'loading' );
//banana = _backgroundPage.banana;

// temporary workaround . . . neeeds to be fixed later
// in case of chrome, whole page has to be reloaded and in case of firefox, the UI language changes
// but needs a page reload in order for those changes to reflect in modal

if (browserType === 'firefox') {
await _backgroundPage.changeUiLanguage( newLanguage ); // save in localStorage
}
else{
await browser.runtime.sendMessage({command:"changeUiLanguage",newLanguage});
}
// now in case of the chrome,both popup and modal update,
// but in case of popup you have to off->on again in order to see changes
// and in FF popup UI updates first
// in both browsers for the changes to reflect in modal you have to
// send another signit.hinticon command in order to see changes

await sendMsgAndExecFn("changeUiLanguage",newLanguage);
ui = new UI();
ui.switchPanel( 'loaded' );
}
Expand Down
13 changes: 7 additions & 6 deletions sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,7 @@ async function setState(value) {
// Declare localisation
banana.setLocale(locale); // Change to new locale
storeParam("bananaInStore", banana);
storeParam("sourceMap", Array.from(banana.messageStore.sourceMap));

// state = "ready";
state = await setState("ready");
Expand Down Expand Up @@ -742,9 +743,9 @@ async function setState(value) {
// the message which renders the test undefined

if (message.command === "normalizeWordAndReturnFiles") {
const w = normalize(message.text);
const f = wordToFiles(w);
sendResponse([w,f]);
const word = normalize(message.argument);
const files = wordToFiles(word);
sendResponse([word,files]);
}
message = normalizeMessage(message);

Expand Down Expand Up @@ -773,13 +774,13 @@ async function setState(value) {
callModal(message);
}
else if (message.command === "checkActiveTabInjections") {
checkActiveTabInjections(message.currentTabId);
checkActiveTabInjections(message.argument);
}
else if (message.command === "storeParam") {
storeParam([...message.arguments]);
storeParam([...message.argument]);
}
else if (message.command === "changeUiLanguage") {
await changeUiLanguage(message.newLanguage);
await changeUiLanguage(message.argument);
}
});

Expand Down

0 comments on commit f370d96

Please sign in to comment.