Skip to content

Commit

Permalink
Merge pull request #2 from Quasso/develop
Browse files Browse the repository at this point in the history
Develop v1.0.0
  • Loading branch information
Quasso authored May 26, 2022
2 parents c0348d9 + 9f84b76 commit 5c7e72c
Show file tree
Hide file tree
Showing 8 changed files with 225 additions and 62 deletions.
Binary file added assets/compiled/icon-128.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "bionic-reader-extension",
"version": "0.0.1",
"version": "1.0.0",
"description": "A new concept called Bionic Reading aims to increase readability of text for humans. This extension converts text on-the-fly into Bionic Text.",
"main": "index.js",
"author": "Quasso <https://github.com/Quasso>",
Expand Down
110 changes: 97 additions & 13 deletions src/background.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,61 @@
const DEBUG = true;
const VERBOSE = false;
const DEFAULT_LOG_PREFIX = "[BRE: background]";
const STORAGE_PREFIX = 'breStatus-';

enum ITypesBG {
log,
action,
notify,
store
store,
store_create,
store_read
}

const storageSet = (key: string, value: string) => {
const STORAGE_OBJ = { key: value };
enum StorageKind {
is_active = "isActive"
}

declare interface StorageObject {
isActive?: boolean;
exists?: boolean;
}

const storageSet = (value: boolean | string, kind: StorageKind) => {
let STORAGE_OBJ: StorageObject;

switch (kind) {
case StorageKind.is_active:
STORAGE_OBJ = {
isActive: value as boolean
}
break;
}
chrome.storage.local.set(STORAGE_OBJ, () => {
smartLog(`Setting key '${key}' and value '${value}'`);
// smartLog(`Set key '${key}' and value '${value}'`);
smartLog(`Set storage object: ${STORAGE_OBJ}`);
});
}

const storageGet = (key: string): Promise<StorageObject> => {
return new Promise((resolve, reject) => {
chrome.storage.local.get([`${key}`], (value: StorageObject) => {
smartLog('Val is:');
console.log(value);
if (Object.entries(value).length > 0) {
smartLog(`Got key '${key}' with value '${value}'`);
smartLog('Val is (sanity check #2):');
console.log(value);
resolve(value);
} else {
smartLog(`No matching value for the key ${key}`);
resolve({ isActive: false, exists: false });
}
});
});
}


/**
*
* Smart Log
Expand Down Expand Up @@ -46,7 +86,7 @@ const sendNotification = (message: string) => {
type: "basic",
title: "Bionic Reader Extension",
message,
iconUrl: chrome.runtime.getURL("assets/compiled/bio-128.png")
iconUrl: chrome.runtime.getURL("assets/compiled/icon-128.png")
};

chrome.notifications.create(NOTIFICATION_OPTIONS);
Expand All @@ -58,7 +98,9 @@ const sendNotification = (message: string) => {
*
*/
chrome.runtime.onInstalled.addListener(() => {
smartLog('Initialised successfully.');
chrome.storage.local.clear().then(() => {
smartLog('Initialised successfully.');
});
});

/**
Expand All @@ -77,6 +119,40 @@ chrome.action.onClicked.addListener((tab) => {
}
});

const formatKey = (url: string): string => {
const cleanUrl = url.replace(/[^a-zA-Z0-9-]/g, '');
return STORAGE_PREFIX + cleanUrl;
}


const handleAction = (action: string): Promise<StorageObject> => {
return new Promise((resolve, reject) => {
switch (action) {
case 'checkPageInit':
const key = StorageKind.is_active;
storageGet(key)
.then((value) => {
if (value) {
console.log('Sending response with val...');
console.log('Confirm value immediately before send:');
console.log(value);
resolve(value);
} else {
resolve({ isActive: false });
}
}, (err) => {
console.log('Get storage failed:', err);
reject(err);
});
break;
default:
reject(false);
break;
}
});
}


/**
*
* onMessage handler
Expand All @@ -99,16 +175,24 @@ chrome.runtime.onMessage.addListener(
case ITypesBG.notify:
sendNotification(request.message);
break;
case ITypesBG.store:
if (request.details.isInit) {
if (request.details.key == 'GET_SENDER_TAB' && sender.tab) {
storageSet(sender.tab.url as string, request.details.value);
} else {
storageSet(request.details.key, request.details.value);
case ITypesBG.store_create:
if (request.details.value) {
if (request.details.action == 'setPageInit') {
storageSet(request.details.value, StorageKind.is_active);
}
smartLog('Initialised. Storage set.');
}
break;
case ITypesBG.store_read:
smartLog('Reading from the local store for the extension. Details:');
console.log(request.details);
smartLog('Action:');
console.log(request.details.action);
handleAction(request.details.action).then((value: StorageObject) => {
console.log(value);
console.log(sendResponse);
sendResponse(value);
});
break;
}
}
);
9 changes: 7 additions & 2 deletions src/bre.css
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
b {
.bre-initialised b {
font-weight: 600 !important;
}

.bre-override {

.bre-initialised .bre-override {
font-family: Helvetica !important;
letter-spacing: 0.6px !important;
line-height: 1.55em !important;
font-weight: 400 !important;
font-size: 1.1em !important;
}

.bre-inactive * b {
font-weight: 400 !important;
}
118 changes: 86 additions & 32 deletions src/content-script.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,6 @@
let CS_LOG_PREFIX = "[BRE: c-s via background]";

declare interface BionicReaderStatuses {
active: boolean;
init: boolean;
}

let STATUS: BionicReaderStatuses = {
active: false,
init: false
};
const CS_LOG_PREFIX = "[BRE: c-s via background]";
const CLASS_INIT = 'bre-initialised';
const CLASS_INACTIVE = 'bre-inactive';

export const DELIMITERS = {
HYPHEN: "-",
Expand All @@ -26,24 +18,54 @@ enum ITypesCS {
log,
action,
notify,
store
store,
store_create,
store_read
};

/**
*
* Send Message
*
* @description helper const to = communicate with background.js primarily. Send a message to another part of the extensio=>n
* @description helper const to = communicate with background.js primarily. Send a message to another part of the extension
* @param message [string] the message to log (if any)
* @param type [ITypesCS] the type of event we're sending
* @param details [object] no specific typings exist for this yet but it's an object with keys
*/
const sendMessage = (message: string, type?: ITypesCS, details?: any) => {
const sendMessage = (message: string, type?: ITypesCS, details?: any): void => {
!type ? type = ITypesCS.log : console.log('Nothing to see here');
chrome.runtime.sendMessage({ message, prefix: CS_LOG_PREFIX, type, details });
}

chrome.runtime.sendMessage({ message, prefix: CS_LOG_PREFIX, type, details }, (response) => {
if (response) {
console.log(response);
}
/**
*
* Send Message and Await Response
*
* @description helper const to = communicate with background.js primarily. Send a message to another part of the extension
* and also wait to hear back from it. (Note: performance of response erratic & not clear why)
* @param message [string] the message to log (if any)
* @param type [ITypesCS] the type of event we're sending
* @param details [object] no specific typings exist for this yet but it's an object with keys
*/
const sendMessageAndAwaitResponse = (message: string, type?: ITypesCS, details?: any): Promise<boolean | undefined> => {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage({ message, prefix: CS_LOG_PREFIX, type, details }, function (response) {
const exists: boolean = response.exists;
sendMessage(`Response block triggered! With resp: ${response}`); //recursive baby!
sendMessage(`Response was: ${response}`);
if (response == undefined) {
sendMessage("Response was undefined, need to sort this out...");
reject(undefined);
} else if (!exists) {
sendMessage("Response was false, meaning the key did not have a value.");
sendMessage(`Response was ${response}`);
resolve(exists);
} else if (exists) {
console.log(response);
sendMessage(`Response was ${response}`);
resolve(exists);
}
});
});
}

Expand Down Expand Up @@ -157,13 +179,45 @@ const parseBionic = (paragraph: Element) => {
bionicParagraphValues.push(paragraphBionic as string);

paragraph.innerHTML = paragraphBionic;
sendMessage(`Completed parsing paragraph ${wordIndex} DOM updated successfully.`);
sendMessage(`Completed parsing paragraph ${paragraphIndex} DOM updated successfully.`);
}
paragraphIndex++;
}

const toggleBionic = () => {
sendMessage(`Toggling bionic state from '${STATUS.active}'...`, ITypesCS.notify);
const toggleActiveClass = (isActive: boolean) => {
sendMessage(`Toggling bionic state from '${isActive}' to '${!isActive}'...`, ITypesCS.notify);
switch (isActive) {
case true:
document.querySelector('body')?.classList.remove(CLASS_INIT);
document.querySelector('body')?.classList.add(CLASS_INACTIVE);
break;
case false:
document.querySelector('body')?.classList.add(CLASS_INIT);
document.querySelector('body')?.classList.remove(CLASS_INACTIVE);
break;
}

}

const toggleBionic = (isActive: boolean) => {
// const isActive = document.querySelector('body')?.classList.contains(CLASS_INIT);

toggleActiveClass(isActive as boolean);
}

const initialised = () => {
// This works fine for actually setting a value, however return comms
// for some reason are missing the populated obj they should return
// so I have removed the reliance on receiving a response for now in
// favour of the class-based approach
sendMessage('Parsed all content on this page', ITypesCS.store_create,
{
value: true,
action: 'setPageInit',
});
sendMessage(`Automatically processed ${paragraphIndex} paragraphs and ${wordIndex} words!`, ITypesCS.notify);
sendMessage(`Appending the class`);
toggleActiveClass(false);
}

/**
Expand All @@ -180,13 +234,11 @@ const convertPageText = (paragraphs: NodeListOf<Element>) => {
sendMessage('Handling paragraph...');
parseBionic(paragraph);
});
sendMessage(`Automatically processed ${paragraphIndex} paragraphs and ${wordIndex} words!`, ITypesCS.notify);
STATUS.init = true;
sendMessage('Parsed all content on this page', ITypesCS.store,
{
key: 'GET_SENDER_TAB',
value: true
});
initialised();
}

const checkInit = (): boolean => {
return document.querySelector('body')?.classList.contains(CLASS_INIT) || false;
}

/**
Expand All @@ -199,12 +251,14 @@ const convertPageText = (paragraphs: NodeListOf<Element>) => {
*/
const autoGrabParagraphs = () => {
const paragraphs: NodeListOf<Element> = document.querySelectorAll('body p');
sendMessage(`There are ${paragraphs.length} paragraphs to parse.`);
sendMessage(`Is init? ${STATUS.init}`);
if (!STATUS.init) {
sendMessage(`Auto-grab <p> elements running. There are ${paragraphs.length} paragraphs to parse.`);
const isInit = checkInit();
sendMessage(`Is loaded? ${isInit}`);

if (!isInit) {
convertPageText(paragraphs);
} else {
toggleBionic();
toggleBionic(isInit);
}
}

Expand Down
Loading

0 comments on commit 5c7e72c

Please sign in to comment.