Skip to content
This repository has been archived by the owner on Nov 7, 2022. It is now read-only.

Commit

Permalink
feat: add project from share url, logging
Browse files Browse the repository at this point in the history
  • Loading branch information
rofe committed Oct 19, 2021
1 parent 78030ea commit e673bf7
Show file tree
Hide file tree
Showing 7 changed files with 161 additions and 120 deletions.
6 changes: 6 additions & 0 deletions src/extension/_locales/de/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@
"config_shareurl_copied": {
"message": "Teilen-URL für $1 in die Zwischenablage kopiert"
},
"config_shareurl_add_confirm": {
"message": "Möchtest du dieses Projekt zu deinem Helix Sidekick hinzufügen?"
},
"config_shareurl_added": {
"message": "Projekt zu Helix Sidekick hinzugefügt"
},
"config_manual_title": {
"message": "Manuell hinzufügen"
},
Expand Down
6 changes: 6 additions & 0 deletions src/extension/_locales/en/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@
"config_shareurl_copied": {
"message": "Sharing URL for $1 copied to clipboard"
},
"config_shareurl_add_confirm": {
"message": "Would you like to add this project to your Helix Sidekick?"
},
"config_shareurl_added": {
"message": "Project added to Helix Sidekick"
},
"config_manual_title": {
"message": "Add manually"
},
Expand Down
51 changes: 31 additions & 20 deletions src/extension/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,39 @@
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
/* eslint-disable no-console */

'use strict';

import {
log,
i18n,
getState,
getConfigMatches,
toggleDisplay,
notify,
addConfig,
getShareSettings,
isValidShareURL,
} from './utils.js';

/**
* Checks if the URL is a share URL and asks the user
* to add the config.
* @param {string} url The URL to check
*/
async function checkShareUrl(url) {
if (isValidShareURL(url)) {
log.info('share URL detected', url);
if (confirm(i18n('config_shareurl_add_confirm'))) {
await addConfig(getShareSettings(url), (added) => {
if (added) {
notify(i18n('config_shareurl_added'));
}
});
}
}
}

/**
* Checks a tab and enables/disables the extension.
* @param {number} id The ID of the tab
Expand All @@ -27,10 +50,10 @@ function checkTab(id) {
getState(({ configs }) => {
browser.tabs
.get(id)
.then((tab = {}) => {
.then(async (tab = {}) => {
if (!tab.url) return;
const matches = getConfigMatches(configs, tab.url);
// console.log('checking', id, tab.url, matches);
log.debug('checking', id, tab.url, matches);
const allowed = matches.length > 0;
if (allowed) {
// enable extension for this tab
Expand All @@ -41,9 +64,11 @@ function checkTab(id) {
} else {
// disable extension for this tab
browser.pageAction.hide(id);
// check if share URL and ask to add config
checkShareUrl(tab.url);
}
})
.catch((e) => console.error('error checking tab', id, e));
.catch((e) => log.error('error checking tab', id, e));
});
}

Expand Down Expand Up @@ -83,7 +108,7 @@ function toggle(id) {
browser.storage.onChanged.addListener(({ hlxSidekickDisplay = null }, area) => {
if (area === 'local' && hlxSidekickDisplay) {
const display = hlxSidekickDisplay.newValue;
console.log(`sidekick now ${display ? 'shown' : 'hidden'}`);
log.info(`sidekick now ${display ? 'shown' : 'hidden'}`);
browser.tabs
.query({
currentWindow: true,
Expand All @@ -96,21 +121,7 @@ function toggle(id) {
}
});
})
.catch((e) => console.error('error propagating display state', e));
.catch((e) => log.error('error propagating display state', e));
}
});

// fetch script and execute in sandbox
browser.runtime.onConnect.addListener((port) => {
console.assert(port.name === browser.runtime.id);
port.onMessage.addListener(({ scriptUrl, cb }) => {
if (scriptUrl) {
fetch(scriptUrl)
.then((response) => response.text())
.then((code) => browser.tabs.executeScript(port.sender.tab.id, { code }))
.then(() => (typeof cb === 'function' ? cb() : null))
.catch((e) => console.error('unable to load script', scriptUrl, e));
}
});
});
})();
13 changes: 6 additions & 7 deletions src/extension/content.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
/* eslint-disable no-console */

'use strict';

Expand All @@ -18,18 +17,18 @@
window.hlx = window.hlx || {};

const {
log,
getState,
getConfigMatches,
} = await import('./utils.js');

const inject = (config = window.hlx.selectedSidekickConfig) => {
getState(({ configs, display }) => {
// console.log('[content.js] ', configs, display);
let matches = [];
if (!config) {
// find config matches
matches = getConfigMatches(configs, window.location.href);
// console.log('[content.js] found matches', matches.length);
log.debug('content.js: found matches', matches.length);
if (matches.length === 0) {
// no config matches, do nothing
return;
Expand All @@ -40,18 +39,18 @@
}
}
if (config) {
// console.log('[content.js] single config found, inject sidekick', config);
log.info('content.js: single config found, inject sidekick', config);
// user selected config or single match, remember and show sidekick
window.hlx.selectedSidekickConfig = config;
import('./sidekick.js')
.then((mod) => mod.default(config, display))
.catch((e) => console.error('failed to load sidekick', e));
.catch((e) => log.error('failed to load sidekick', e));
} else if (matches.length > 0) {
// console.log('[content.js] multiple configs found, inject picker', matches);
log.info('content.js: multiple configs found, inject config picker', matches);
// multiple matches, show config picker
import('./configpicker.js')
.then((mod) => mod.default(matches, display, inject))
.catch((e) => console.error('failed to load config picker', e));
.catch((e) => log.error('failed to load config picker', e));
}
});
};
Expand Down
101 changes: 14 additions & 87 deletions src/extension/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,69 +9,24 @@
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
/* eslint-disable no-console, no-use-before-define */
/* eslint-disable no-use-before-define */

'use strict';

import {
log,
getState,
getMountpoints,
getGitHubSettings,
isValidShareURL,
getShareSettings,
i18n,
notify,
addConfig,
} from './utils.js';

import {} from './lib/js-yaml.min.js';

async function getMountpoints(owner, repo, ref) {
const fstab = `https://raw.githubusercontent.com/${owner}/${repo}/${ref}/fstab.yaml`;
const res = await fetch(fstab);
if (res.ok) {
const { mountpoints = {} } = jsyaml.load(await res.text());
return Object.values(mountpoints);
}
return [];
}

function getSidekickSettings(sidekickurl) {
try {
const params = new URL(sidekickurl).searchParams;
const giturl = params.get('giturl');
const hlx3 = params.get('hlx3') !== 'false';
// check gh url
if (Object.keys(getGitHubSettings(giturl)).length !== 3) {
throw new Error();
}
return {
giturl,
project: params.get('project'),
hlx3,
};
} catch (e) {
console.error('error getting sidekick settings from share url', e);
return {};
}
}

async function getProjectConfig(owner, repo, ref) {
const configJS = `https://raw.githubusercontent.com/${owner}/${repo}/${ref}/tools/sidekick/config.js`;
const cfg = {};
const res = await fetch(configJS);
if (res.ok) {
const js = await res.text();
const [, host] = /host: '(.*)',/.exec(js) || [];
if (host) {
cfg.host = host;
}
}
return cfg;
}

function getInnerHost(owner, repo, ref) {
return `${ref}--${repo}--${owner}.hlx3.page`;
}

function isValidShareURL(shareurl) {
return Object.keys(getSidekickSettings(shareurl)).length === 3;
function getInnerHost(owner, repo, ref, hlx3) {
return `${ref}--${repo}--${owner}.hlx${hlx3 ? '3' : ''}.page`;
}

function isValidGitHubURL(giturl) {
Expand All @@ -93,9 +48,9 @@ function drawConfigs() {
const container = document.getElementById('configs');
container.innerHTML = '';
configs.forEach(({
owner, repo, ref, mountpoints, project, host,
owner, repo, ref, mountpoints, project, host, hlx3,
}, i) => {
const innerHost = getInnerHost(owner, repo, ref);
const innerHost = getInnerHost(owner, repo, ref, hlx3);
const section = document.createElement('section');
section.id = `config-${i}`;
section.className = 'config';
Expand Down Expand Up @@ -132,34 +87,6 @@ function drawConfigs() {
});
}

async function addConfig({ giturl, project, hlx3 }, cb) {
const { owner, repo, ref } = getGitHubSettings(giturl);
const projectConfig = await getProjectConfig(owner, repo, ref);
const mountpoints = await getMountpoints(owner, repo, ref);
getState(({ configs }) => {
if (!configs.find((cfg) => owner === cfg.owner && repo === cfg.repo && ref === cfg.ref)) {
configs.push({
id: `${owner}/${repo}/${ref}`,
giturl,
owner,
repo,
ref,
mountpoints,
project,
hlx3,
...projectConfig,
});
browser.storage.sync
.set({ hlxSidekickConfigs: configs })
.then(() => (typeof cb === 'function' ? cb(true) : null))
.catch((e) => console.error('error adding config', e));
} else {
notify(i18n('config_project_exists'));
if (typeof cb === 'function') cb(false);
}
});
}

function shareConfig(i, evt) {
browser.storage.sync
.get('hlxSidekickConfigs')
Expand All @@ -186,7 +113,7 @@ function shareConfig(i, evt) {
}, 3000);
}
})
.catch((e) => console.error('error sharing config', e));
.catch((e) => log.error('error sharing config', e));
}

function editConfig(i) {
Expand Down Expand Up @@ -276,7 +203,7 @@ function deleteConfig(i) {
})
.then((hlxSidekickConfigs) => browser.storage.sync.set({ hlxSidekickConfigs }))
.then(() => drawConfigs())
.catch((e) => console.error('error deleting config', e));
.catch((e) => log.error('error deleting config', e));
}
}

Expand All @@ -299,15 +226,15 @@ window.addEventListener('DOMContentLoaded', () => {
.clear()
.then(() => browser.storage.local.clear())
.then(() => drawConfigs())
.catch((e) => console.error('error deleting all configs', e));
.catch((e) => log.error('error deleting all configs', e));
}
});

document.getElementById('addShareConfigButton').addEventListener('click', async () => {
const shareurl = document.getElementById('shareurl').value;
// check share url
if (isValidShareURL(shareurl)) {
await addConfig(getSidekickSettings(shareurl), (added) => {
await addConfig(getShareSettings(shareurl), (added) => {
if (added) {
drawConfigs();
clearForms();
Expand Down
10 changes: 5 additions & 5 deletions src/extension/sidekick.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,23 @@

'use strict';

import { setDisplay } from './utils.js';
import { log, setDisplay } from './utils.js';

export default async function injectSidekick(config, display) {
if (typeof config !== 'object') {
console.warn('[sidekick.js] no valid config', config);
log.warn('sidekick.js: invalid config', config);
return;
}
if (window.hlx && window.hlx.sidekick) {
// sidekick exists, toggle
window.hlx.sidekick[display ? 'show' : 'hide']();
} else if (display) {
// create sidekick
// console.log('[sidekick.js] create sidekick');
log.debug('sidekick.js: no sidekick yet, create it');
// reduce config to only include properties relevant for sidekick
window.hlx.sidekickConfig = Object.fromEntries(Object.entries(config)
.filter(([k]) => ['owner', 'repo', 'ref', 'hlx3', 'devMode'].includes(k)));
// console.log('[sidekick.js] curated config', JSON.stringify(window.hlx.sidekickConfig));
log.debug('sidekick.js: curated config', JSON.stringify(window.hlx.sidekickConfig));
// inject sidekick
await import('https://www.hlx.live/tools/sidekick/module.js');

Expand All @@ -47,7 +47,7 @@ export default async function injectSidekick(config, display) {
await import(`${configOrigin}/tools/sidekick/config.js`);
} catch (e) {
// init sidekick without extended config
console.info('no extended sidekick config found');
log.info('no extended sidekick config found');
window.hlx.initSidekick();
}

Expand Down
Loading

0 comments on commit e673bf7

Please sign in to comment.