Skip to content

Commit

Permalink
Merge pull request #208 from facets-io/auth-css-fix
Browse files Browse the repository at this point in the history
Preview Feature via cookie management + Auth css fix
  • Loading branch information
mkotsollaris authored Feb 1, 2021
2 parents c60ae6e + 0a92883 commit 472d1de
Show file tree
Hide file tree
Showing 16 changed files with 399 additions and 224 deletions.
9 changes: 6 additions & 3 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,12 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token
with:
tag_name: 0.3.5
release_name: 0.3.5
tag_name: 0.4.0
release_name: 0.4.0
body: |
Added ability to Preview facets
- Enhanced Preview feature
- Added cookie management
- Added css for disabled buttons
- Added better UX for transition-management of the popup
draft: false
prerelease: false
11 changes: 10 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,13 @@ For trying out the plugin, you can try logging in with this account:
```
username: layani.kamora@primaryale.com
password: layani.kamora@primaryale.com
```
```

## Cookie Structure

```
FACET_EXTENSION_PREVIEW_TAB_ID: The TabID of Preview tab; updated onClick and on tab close consequently
FACET_EXTENSION_DISABLE_MO: Disables/enables the MO
FACET_EXTENSION_ALREADY_INTEGRATED: Domain is already integrated with facet.run
FACET_EXTENSION_INJECTING_SCRIPT_TAG: script tag that ought to be injected
```
58 changes: 38 additions & 20 deletions public/background.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
chrome.runtime.onMessage.addListener(
async function (request) {
async function (request, sender, sendResponse) {
// need to grab from shared
if (request.data === 'OPEN_WELCOME_PAGE') {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
Expand All @@ -8,31 +8,49 @@ chrome.runtime.onMessage.addListener(
});
return;
} else if (request.data === 'OPEN_PREVIEW_PAGE') {
await chrome.tabs.create({ url: request.config.url }, function (tab) {
console.log('[FACET][Background] SETTING COOKIES FOR ', request.config.url);
chrome.cookies.set({
url: request.config.url,
name: `FACET_EXTENSION_DISABLE_MO`,
value: "false"
});

chrome.tabs.create({ url: request.config.href }, function (tab) {
chrome.tabs.executeScript(tab.id, {
code: `
console.log('[Facet][Initiating Preview]');
window.IN_PREVIEW = true;
window.JSURL = "${request.config.jsUrl}";
document.getElementById('facetizer') && document.getElementById('facetizer').remove();
var node = document.getElementsByTagName('html').item(0);
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', "${request.config.jsUrl}");
script.setAttribute('facet-extension-loaded', false);
script.setAttribute('is-preview', true);
node.appendChild(script);
chrome.cookies.set({
url: request.config.url,
name: `FACET_EXTENSION_PREVIEW_TAB_ID`,
value: tab.id.toString()
});

chrome.cookies.set({
url: request.config.url,
name: `FACET_EXTENSION_ALREADY_INTEGRATED`,
value: request.config.alreadyIntegrated.toString()
});

node.style.visibility = "hidden";
chrome.cookies.set({
url: request.config.url,
name: `FACET_EXTENSION_INJECTING_SCRIPT_TAG`,
value: request.config.injectingScriptTag
});

var previewNode = document.createElement('div');
previewNode.setAttribute('id', 'facet-preview-loading-bar');
node.appendChild(previewNode);
`,
chrome.tabs.executeScript(tab.id, {
file: 'preview-click-content.js',
runAt: 'document_start',
});
});
} else if (request.data === 'GET_CURRENT_TAB') {
if (sender.tab && sender.tab.id) {
sendResponse({ tabId: sender.tab.id });
} else {
sendResponse({ tabId: undefined });
}
} else if (request.data === 'SET_COOKIE_VALUE') {
chrome.cookies.set({
url: request.config.url,
name: request.config.name,
value: request.config.value
});
}
},
);
47 changes: 27 additions & 20 deletions public/facet-extension-window-variable-content.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,34 @@
/**
* Injects @param {disableMutationObserverScript} into the current page.
* IIFE that injects @param {disableMutationObserverScript} into the current page.
* The value is determined by the boolean attribute `facet-extension-loaded` which is defined through `mutationObserverVariableInjection.js`.
*/
window.disableMutationObserverScript = false;
const scriptArr = document.querySelectorAll('script');
let found = false;
scriptArr.forEach(script => {
if (found) {
return;

(async function () {

const keysObj = {
FACET_EXTENSION_PREVIEW_TAB_ID: 'FACET_EXTENSION_PREVIEW_TAB_ID',
FACET_EXTENSION_DISABLE_MO: 'FACET_EXTENSION_DISABLE_MO',
FACET_EXTENSION_ALREADY_INTEGRATED: 'FACET_EXTENSION_ALREADY_INTEGRATED',
FACET_EXTENSION_INJECTING_SCRIPT_TAG: 'FACET_EXTENSION_INJECTING_SCRIPT_TAG'
};

function getFacetExtensionCookie(key) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${key}=`);
if (parts.length === 2) {
return parts.pop().split(';').shift();
}
}
if (script.attributes && script.attributes['is-preview']) {
window.disableMutationObserverScript = false;
window.IN_PREVIEW = true;
window.JSURL = script.attributes['src'];
found = true;

const alreadyIntegrated = (getFacetExtensionCookie(keysObj["FACET_EXTENSION_ALREADY_INTEGRATED"]) === 'true');
const scriptTagVal = getFacetExtensionCookie(keysObj['FACET_EXTENSION_INJECTING_SCRIPT_TAG']);
if (!alreadyIntegrated) {
var node = document.getElementsByTagName('html').item(0);
node.style.visibility = "hidden";
var previewNode = document.createElement('div');
previewNode.setAttribute('src', window.JSURL);
node.prepend(previewNode);
return;

var scriptTag = document.createElement('script');
scriptTag.setAttribute('type', 'text/javascript');
scriptTag.setAttribute('src', scriptTagVal);
node.prepend(scriptTag);
}
if (script.attributes && script.attributes['facet-extension-loaded']) {
window.disableMutationObserverScript = script.getAttribute("facet-extension-loaded") === "true" ? true : false;
}
})
})();
8 changes: 5 additions & 3 deletions public/manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"manifest_version": 2,
"name": "Facet",
"version": "0.3.5",
"version": "0.4.0",
"description": "Facet.ninja | Deploy - Learn - Adapt",
"icons": {
"512": "facet_logo_512x512.png"
Expand Down Expand Up @@ -38,12 +38,14 @@
}
],
"web_accessible_resources": [
"facet-extension-window-variable-content.js"
"facet-extension-window-variable-content.js",
"preview-click-content.js"
],
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxfhoAGlzfRw1Tdn5cbu9XozL65aZM+lNzvQIDCJBbXVV7sdireo6C9e0p4MmUl/VlJGeBRSQFVeh5cNIcYb0/zdoAmOlXI6vr1vaMZFWgA9dpmTUEiz2jqUV2jsTvhLUjNH8Xr0y0xs66Av2tP2Fj3+0dcSMF7op8MSyTOIimZipW5ct8ORwgXDvqhL5SaBm49rRDlwHmlmdLbdpQFbMFE5ZlM1ah9W/fHErATHsffZfXWQyVBZCOCKCYkPOHZj3wViIJbSaeVZv+XVUZl/uhPkL5Txzkb4qXricAzyyvmA3O/8XijiHjw+VpxzBIpAj7P4Bbgsal2r3VJeOC67OYwIDAQAB",
"permissions": [
"<all_urls>",
"storage",
"tabs"
"tabs",
"cookies"
]
}
61 changes: 48 additions & 13 deletions public/mutationObserverVariableInjection.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,57 @@

/**
* taken from https://gist.github.com/devjin0617/3e8d72d94c1b9e69690717a219644c7a
*
* injectScript - Inject internal script to available access to the `window`
* Injects facet-extension-window-variable-content.js
*
* @param {type} file_path Local path of the internal script.
* @param {type} tag The tag as string, where the script will be append (default: 'body').
* @see {@link http://stackoverflow.com/questions/20499994/access-window-variable-from-content-script}
*/
async function injectScript(file_path, tag) {
chrome.storage && chrome.storage.sync.get('facet-settings', function (obj) {
var node = document.getElementsByTagName('html')[0];
var script = document.createElement('script');
const val = Boolean(obj && obj['facet-settings'] && obj['facet-settings']['isPluginEnabled']);
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', file_path);
script.setAttribute('facet-extension-loaded', val);
node.appendChild(script);
(async function () {

async function injectScript(file_path, tag) {
chrome.storage && chrome.storage.sync.get('facet-settings', function (obj) {
var node = document.getElementsByTagName('html')[0];
var script = document.createElement('script');
const val = Boolean(obj && obj['facet-settings'] && obj['facet-settings']['isPluginEnabled']);
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', file_path);
script.setAttribute('facet-extension-loaded', val);
node.appendChild(script);
});
}

const keys = {
'FACET_EXTENSION_DISABLE_MO': 'FACET_EXTENSION_DISABLE_MO',
'FACET_EXTENSION_PREVIEW_TAB_ID': 'FACET_EXTENSION_PREVIEW_TAB_ID',
'FACET_EXTENSION_ALREADY_INTEGRATED': 'FACET_EXTENSION_ALREADY_INTEGRATED',
}

function getFacetExtensionCookie(key) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${key}=`);
if (parts.length === 2) {
return parts.pop().split(';').shift();
}
}

const previewId = getFacetExtensionCookie(keys["FACET_EXTENSION_PREVIEW_TAB_ID"]);

await chrome.runtime.sendMessage({
data: 'GET_CURRENT_TAB'
}, async (response) => {
// response.tabId
const val = response.tabId != previewId;
await chrome.runtime.sendMessage({
data: 'SET_COOKIE_VALUE',
config: {
url: window.location.origin,
name: 'FACET_EXTENSION_DISABLE_MO',
value: val.toString()
}
});
});
}
injectScript(chrome.extension.getURL('facet-extension-window-variable-content.js'), 'body');

console.log("[FACET][mutationObserverVariableInjection] INJECTING facet-extension-window-variable-content.js");
injectScript(chrome.extension.getURL('facet-extension-window-variable-content.js'), 'body');
})();
4 changes: 4 additions & 0 deletions public/preview-click-content.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
(function () {
var node = document.getElementsByTagName('html').item(0);
node.style.visibility = "hidden";
})();
6 changes: 3 additions & 3 deletions src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import isDevelopment from './utils/isDevelopment';

function App() {
const { enqueueSnackbar } = useSnackbar();
const { showSideBar, isPluginEnabled, setIsPluginEnabled,
isDomainWhitelisted, facetMap, setFacetMap, setLoadingSideBar, setNonRolledOutFacets } = useContext(AppContext);
const { showSideBar, isPluginEnabled, setIsPluginEnabled, isDomainWhitelisted, facetMap, setFacetMap, setLoadingSideBar, setNonRolledOutFacets } = useContext(AppContext);

// TODO potential need of refactor
chrome && chrome.runtime.onMessage && chrome.runtime.onMessage.addListener(
async function (message, sendResponse) {
Expand Down Expand Up @@ -42,7 +42,7 @@ function App() {
load();


}, [setIsPluginEnabled, isPluginEnabled, showSideBar]);
}, [setIsPluginEnabled, isDomainWhitelisted, isPluginEnabled, showSideBar]);

// removing width/height hack
if ((isPluginEnabled && isDomainWhitelisted) || isDevelopment()) {
Expand Down
2 changes: 1 addition & 1 deletion src/AppProvider.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const AppProvider = ({ children }) => {
const { enqueueSnackbar } = useSnackbar();

const [isPluginEnabled, setIsPluginEnabled] = isDevelopment() ? useState(true) : useState(false);
const [showSideBar, setShowSideBar] = isDevelopment() ? useState(true) : useState(false);
const [showSideBar, setShowSideBar] = useState(true);
const [loadingSideBar, setLoadingSideBar] = isDevelopment() ? useState(false) : useState(true);
const [isDomainWhitelisted, setIsDomainWhitelisted] = isDevelopment() ? useState(true) : useState(false);

Expand Down
29 changes: 15 additions & 14 deletions src/facetTreeSideBar/FacetTreeSideBar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import facetLogoIce from '../static/images/facet_ice_logo.svg';
import CodeSnippet from '../shared/CodeSnippet';
import FacetButton from '../shared/FacetButton';
import isDevelopment from '../utils/isDevelopment';
import { scriptHasAlreadyBeenInjected } from '../highlighter.js';

const useStyles = makeStyles((theme) => ({
root: {
Expand Down Expand Up @@ -100,7 +101,7 @@ export default function FacetTreeSideBar() {
const {
facetMap, setFacetMap, loadingSideBar, logout,
showSideBar, setShowSideBar, reset, onSaveClick, textToCopy, handleCloseMenuEl,
globalFacets, setGlobalFacets, jsUrl,
globalFacets, setGlobalFacets, jsUrl, url,
facetLabelMenu, expanded, setExpanded, onDeleteDOMElement, enqueueSnackbar,
setSelectedFacet, onGotoClick, nonRolledOutFacets, setNonRolledOutFacets, setLoadingSideBar } = useContext(AppContext);
const [renamingFacet, setRenamingFacet] = useState(false);
Expand Down Expand Up @@ -222,23 +223,19 @@ export default function FacetTreeSideBar() {
});
const activateDeactivateElement = showSideBar
? (
<CustomIconButtonContainer onClick={() => {
<FacetIconButton iconWidth="30" iconHeight="30" size="medium" title="Enable" key="edit" fill={color.ice} name="edit" onClick={() => {
if (!isDevelopment()) {
setLoadingSideBar(true);
}
sideBarHandler();
}} title="Disable" >
<FacetImage onMouseOver={(e) => { e.currentTarget.src = facetLogo }} onMouseOut={(e) => { e.currentTarget.src = facetLogoIce }} width="27" height="27" title="facet" src={facetLogoIce} />
</CustomIconButtonContainer>
}} />
) : (
<CustomIconButtonContainer onClick={() => {
<FacetIconButton iconWidth="30" iconHeight="30" size="medium" title="Disable" key="edit-outline" name="edit-outline" onClick={() => {
if (!isDevelopment()) {
setLoadingSideBar(true);
setLoadingSideBar(false);
}
sideBarHandler();
}} title="Enable">
<FacetImage onMouseOver={(e) => { e.currentTarget.src = facetLogoIce }} onMouseOut={(e) => { e.currentTarget.src = facetLogo }} width="27" height="27" title="facet" src={facetLogo} />
</CustomIconButtonContainer>
}} />
);

return (
Expand Down Expand Up @@ -278,21 +275,25 @@ export default function FacetTreeSideBar() {
</CopyToClipboard>
<Divider style={{ backgroundColor: color.lightGray }} />
<div className={classes.saveAndPreview}>

<FacetButton text="Save & Preview Page" onClick={async () => {
await onSaveClick();
const alreadyIntegrated = scriptHasAlreadyBeenInjected();
chrome.runtime.sendMessage({
data: ChromeRequestType.OPEN_PREVIEW_PAGE,
config: {
jsUrl,
href: window.location.href
url: window.location.origin,
injectingScriptTag: jsUrl,
href: window.location.href,
alreadyIntegrated
}
});
}} />
</div>
<div className={classes.drawerHeader}>
{activateDeactivateElement}
<FacetIconButton iconWidth="30" iconHeight="30" size="medium" name="trash-2-outline" onClick={() => { reset(); }} title="Delete All" aria-label="Delete All" />
<FacetIconButton iconWidth="30" iconHeight="30" size="medium" title="save" name="save-outline" onClick={() => { onSaveClick(); }} aria-label="add" />
<FacetIconButton key="trash-2-outline" iconWidth="30" iconHeight="30" size="medium" name="trash-2-outline" onClick={() => { reset(); }} title="Delete All" aria-label="Delete All" />
<FacetIconButton key="save" iconWidth="30" iconHeight="30" size="medium" title="save" name="save-outline" onClick={() => { onSaveClick(); }} aria-label="add" />
</div>
</div>
<Divider style={{ backgroundColor: color.lightGray }} />
Expand Down
Loading

0 comments on commit 472d1de

Please sign in to comment.