Skip to content

Commit

Permalink
Convert functions to arrow functions and use jQuery new API
Browse files Browse the repository at this point in the history
- Use arrow functions for better readability and consistency
- Use jQuery new API for event handlers to avoid deprecated methods
- Add return types for methods to improve type safety
- Rename StorageHelper to StorageService to follow naming convention
  • Loading branch information
Amir Naderi authored and VahidNaderi committed Oct 2, 2023
1 parent 0d4c673 commit c000de8
Show file tree
Hide file tree
Showing 10 changed files with 140 additions and 130 deletions.
5 changes: 1 addition & 4 deletions src/background.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
(request, sender, sendResponse) => {
if (request.sitesWithRanksCount)
chrome.action.setBadgeText({ text: request.sitesWithRanksCount.toString(), tabId: sender.tab?.id });
}
Expand Down
46 changes: 21 additions & 25 deletions src/content/content.ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,41 @@
import "./content.scss";
import { StorageHelper } from "../helpers/storage-helper";
import { StorageService } from "../shared/services/storage-service";

window.onload = () => {
StorageHelper.getSites().then((sites: any) => {
console.log(sites);
const storageService = new StorageService();

if (sites) {
const linksInPage = document.getElementsByTagName('cite');
let sitesWithRanksCount = 0;
for (const site of sites) {
for (let index = 0; index < linksInPage.length; index++) {
const link = linksInPage[index];
window.onload = async () => {
const sites = await storageService.getSites();
if (sites) {
const linksInPage = document.getElementsByTagName('cite');
let sitesWithRanksCount = 0;
for (const site of sites) {
for (let index = 0; index < linksInPage.length; index++) {
const link = linksInPage[index];

if (link.innerText.indexOf(site.hostname) > -1) {
const element = link.closest('.g');
if (element != null) {
highlightLink(element);
const pagePlacement = getPlacement(index + 1);
element.setAttribute('data-rank', pagePlacement.toString());
console.log('placement is :', pagePlacement);
sitesWithRanksCount++;
}
if (link.innerText.indexOf(site.hostname) > -1) {
const element = link.closest('.g');
if (element != null) {
highlightLink(element);
const pagePlacement = getPlacement(index + 1);
element.setAttribute('data-rank', pagePlacement.toString());
sitesWithRanksCount++;
}
}
}
chrome.runtime.sendMessage({ sitesWithRanksCount }, function (response) {
console.log(response);
});
}
})
chrome.runtime.sendMessage({ sitesWithRanksCount }, (response) => { });
}
}

function highlightLink(element: Element) {
const highlightLink = (element: Element): void => {
chrome.storage.sync.get('highlighting-enabled', data => {
if (data['highlighting-enabled'] === true || data['highlighting-enabled'] === undefined) {
element.classList.add('serptrends-item');
}
})
}

function getPlacement(itemIndexInPage: number) {
const getPlacement = (itemIndexInPage: number): number => {
const loc = new URLSearchParams(document.location.search);
const skip = Number(loc.get('start')) ?? 0;
return skip + itemIndexInPage;
Expand Down
49 changes: 25 additions & 24 deletions src/options/options.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import "./options.scss";
import { StorageHelper } from "../helpers/storage-helper";
import { CommonHelper } from "../helpers/common-helper";
import { StorageService } from "../shared/services/storage-service";
import { CommonHelper } from "../shared/helpers/common-helper";

chrome.storage.sync.get('mysites', function (data) {
const storageService = new StorageService();

chrome.storage.sync.get('mysites', (data) => {
if (data.mysites && data.mysites.length > 0) {

for (var i = 0; i < data.mysites.length; i++) {
Expand All @@ -18,33 +20,32 @@ chrome.storage.sync.get('highlighting-enabled', data => {
$('#enable-highlighting').prop('checked', data['highlighting-enabled']);
})

$('#enable-highlighting').change(() => {
const addSite = async (): Promise<void> => {
var sitename = $('#txtSite').val();
if (typeof sitename == 'string' && sitename && sitename.length > 0) {
const response = await storageService.addSite(sitename);
if (response) {
$('#mysites').append(CommonHelper.createSiteElement(response.item, true));
$('#txtSite').val('');
}
}
}

$('#enable-highlighting').on('change', () => {
chrome.storage.sync.set({ 'highlighting-enabled': $('#enable-highlighting').prop('checked') });
})

$('#txtSite').keypress(function (event) {
if (event.which == 13) addSite();
$('#txtSite').on('keypress', async (event) => {
if (event.which == 13) await addSite();
})

$('#btnAddSite').click(addSite);

function addSite() {
var sitename = $('#txtSite').val();
if (typeof sitename == 'string' && sitename && sitename.length > 0) {
var urlModel = CommonHelper.createUrlObject(sitename);
StorageHelper.addSite(sitename).then((res: any) => {
if (res) {
$('#mysites').append(CommonHelper.createSiteElement(urlModel, true));
$('#txtSite').val('');
}
})
}
}
$('#btnAddSite').on('click', addSite);

$('#mysites').on('click', '.btn-delete', function () {
var hostname = $(this).data('hostname');
$('#mysites').on('click', '.btn-delete', (event) => {
var $this = $(event.currentTarget);
var hostname = $this.data('hostname');
if (confirm('Remove ' + hostname + ' from this list?')) {
StorageHelper.removeSite(hostname);
$(this).parents('li').remove();
storageService.removeSite(hostname);
$this.parents('li').remove();
}
})
88 changes: 44 additions & 44 deletions src/popup/popup.ts
Original file line number Diff line number Diff line change
@@ -1,67 +1,67 @@
import "./popup.scss";
import { StorageHelper } from "../helpers/storage-helper"
import { CommonHelper } from "../helpers/common-helper";
import { SearchHelper } from "../helpers/search-helper";
import { StorageService } from "../shared/services/storage-service"
import { CommonHelper } from "../shared/helpers/common-helper";
import { SearchHelper } from "../shared/helpers/search-helper";
import { SiteStorageModel } from "../shared/models/site-storage";

var _searchCache: { [key: string]: any } = {};
const storageService = new StorageService();

$('#addsite').click(() => {
console.log('addsite');
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
$('#addsite').on('click', () => {
chrome.tabs.query({ active: true, currentWindow: true }, async (tabs) => {
if (tabs[0].url) {
StorageHelper.addSite(tabs[0].url).then((res: any) => {
if (res && res.added)
$('#site-ranks').append(CommonHelper.createSiteElement(res.item));
});

const response = await storageService.addSite(tabs[0].url);
if (response && response.added)
$('#site-ranks').append(CommonHelper.createSiteElement(response.item));
}
});
})

$('#refreshbtn').click(SearchHelper.refresh);
$('#refreshbtn').on('click', SearchHelper.refresh);

$('#btnOptions').click(() => {
$('#btnOptions').on('click', () => {
chrome.runtime.openOptionsPage();
})

sitesRefresh();

function sitesRefresh() {
chrome.storage.sync.get('mysites', (data) => {
const sitesRefresh = (): void => {
chrome.storage.sync.get('mysites', async (data) => {
if (data.mysites && data.mysites.length > 0) {
CommonHelper.isGooglePage().then(val => {
if (val) {
$('#addsite').hide();

chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
///////// CHECK /////////
let googleurl = new URL(tabs[0].url!);
let keyword = SearchHelper.getKeywordFromUrl(googleurl);
if (keyword) {
if (_searchCache[keyword] !== undefined)
showSites(keyword, tabs[0].id!);
else
getRank(googleurl, function () {
showSites(keyword as string, tabs[0].id!);
});
}
});
} else {
$('#addsite').show();
for (var i = 0; i < data.mysites.length; i++) {
let sitename = data.mysites[i];
const isGoolePage = await CommonHelper.isGooglePage();
if (isGoolePage) {
$('#addsite').hide();

$('#site-ranks').append(CommonHelper.createSiteElement(sitename));
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
let googleurl = new URL(tabs[0].url!);
let keyword = SearchHelper.getKeywordFromUrl(googleurl);
if (keyword) {
if (_searchCache[keyword] !== undefined)
showSites(keyword, tabs[0].id!);
else
getRank(googleurl, () => {
showSites(keyword as string, tabs[0].id!);
});
}
});
} else {
$('#addsite').show();
for (var i = 0; i < data.mysites.length; i++) {
let sitename = data.mysites[i];

$('#site-ranks').append(CommonHelper.createSiteElement(sitename));
}
})
}

}
});
}

function showSites(query: string, tabId: number) {
sitesRefresh();

const showSites = (query: string, tabId: number): void => {
if (query && query.length > 0) {
if (_searchCache[query] != undefined) {
chrome.storage.sync.get('mysites', function (data) {
chrome.storage.sync.get('mysites', (data) => {
if (data.mysites && data.mysites.length > 0) {
let rankCounter = 0;
for (var i = 0; i < data.mysites.length; i++) {
Expand All @@ -85,7 +85,7 @@ function showSites(query: string, tabId: number) {
}
}

function getRank(googleurl: URL, callback: any) {
const getRank = (googleurl: URL, callback: any): void => {
let keyword = SearchHelper.getKeywordFromUrl(googleurl);
// Throw an error if the keyword is null or undefined
if (!keyword) throw new Error('Keyword not found');
Expand All @@ -109,9 +109,9 @@ function getRank(googleurl: URL, callback: any) {
}
}

function httpGetAsync(theUrl: string, callback: any) {
const httpGetAsync = (theUrl: string, callback: any): void => {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
xmlHttp.onreadystatechange = () => {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
import { SiteStorageModel } from "../models/site-storage";

export class CommonHelper {
public static async isGooglePage() {
public static async isGooglePage(): Promise<boolean | null> {
let url = await this.getCurrentUrl();
console.log('url is ', url);
// Return true if url exists and contains 'google.com/search'
return url && url.href.toLowerCase().includes('google.com/search');
}

public static async getCurrentTab() {
public static async getCurrentTab(): Promise<chrome.tabs.Tab> {
let queryOptions = { active: true, currentWindow: true };
let tabs = await chrome.tabs.query(queryOptions);
return tabs[0];
}

public static async getCurrentUrl() {
public static async getCurrentUrl(): Promise<URL | null> {
let queryOptions = { active: true, currentWindow: true };
let tabs = await chrome.tabs.query(queryOptions);
console.log('The curent tab is:', tabs);
// Return null if tabs is empty or tabs[0].url is falsy
if (!tabs.length || !tabs[0].url) return null;
return new URL(tabs[0].url);
}
public static createUrlObject(url: string) {

public static createUrlObject(url: string): URL {
let u = null;
try {
u = new URL(url);
Expand All @@ -36,11 +36,11 @@ export class CommonHelper {
// var domain = u.hostname;
// if (domain.indexOf('www.') === 0)
// domain = domain.replace('www.', '');

return u;
}
public static getDomainNameFromUrl(url: string) {

public static getDomainNameFromUrl(url: string): string {
let u = null;
try {
u = new URL(url);
Expand All @@ -55,11 +55,11 @@ export class CommonHelper {
var domain = u.hostname;
if (domain.indexOf('www.') === 0)
domain = domain.replace('www.', '');

return domain;
}
public static createSiteElement(urlModel: URL, addDeleteButton?: boolean, rank?: number) {

public static createSiteElement(urlModel: SiteStorageModel, addDeleteButton?: boolean, rank?: number): JQuery<HTMLElement> {
var $element = $('<li><img src="' +
urlModel.origin +
'/favicon.ico" class="favicon"/><span class="site-name">' +
Expand All @@ -74,8 +74,8 @@ export class CommonHelper {
if (rank) {
$element.append('<span class="rank-badge">' + rank + '</span>');
}

return $element;
}

}
Loading

0 comments on commit c000de8

Please sign in to comment.