Skip to content

Commit

Permalink
Merge pull request #321 from tableflip/remove-bg-page-api
Browse files Browse the repository at this point in the history
Refactor ipfs-companion so it no longer sets properties on the window
  • Loading branch information
lidel committed Dec 1, 2017
2 parents 287b357 + f4d2b98 commit e3a593e
Show file tree
Hide file tree
Showing 9 changed files with 636 additions and 569 deletions.
6 changes: 4 additions & 2 deletions add-on/src/background/background.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
'use strict'
/* eslint-env browser, webextensions */

const init = require('../lib/ipfs-companion')
const createIpfsCompanion = require('../lib/ipfs-companion')

// init add-on after all libs are loaded
document.addEventListener('DOMContentLoaded', init)
document.addEventListener('DOMContentLoaded', async () => {
window.ipfsCompanion = await createIpfsCompanion()
})
88 changes: 88 additions & 0 deletions add-on/src/lib/context-menus.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
'use strict'

const browser = require('webextension-polyfill')

async function findUrlForContext (context) {
if (context) {
if (context.linkUrl) {
// present when clicked on a link
return context.linkUrl
}
if (context.srcUrl) {
// present when clicked on page element such as image or video
return context.srcUrl
}
if (context.pageUrl) {
// pageUrl is the root frame
return context.pageUrl
}
}
// falback to the url of current tab
const currentTab = await browser.tabs.query({active: true, currentWindow: true}).then(tabs => tabs[0])
return currentTab.url
}

module.exports.findUrlForContext = findUrlForContext

const contextMenuUploadToIpfs = 'contextMenu_UploadToIpfs'
const contextMenuCopyCanonicalAddress = 'panelCopy_currentIpfsAddress'
const contextMenuCopyAddressAtPublicGw = 'panel_copyCurrentPublicGwUrl'

function createContextMenus (getState, ipfsPathValidator, { onUploadToIpfs, onCopyCanonicalAddress, onCopyAddressAtPublicGw }) {
try {
browser.contextMenus.create({
id: contextMenuUploadToIpfs,
title: browser.i18n.getMessage(contextMenuUploadToIpfs),
contexts: ['image', 'video', 'audio'],
documentUrlPatterns: ['<all_urls>'],
enabled: false,
onclick: onUploadToIpfs
})

browser.contextMenus.create({
id: contextMenuCopyCanonicalAddress,
title: browser.i18n.getMessage(contextMenuCopyCanonicalAddress),
contexts: ['page', 'image', 'video', 'audio', 'link'],
documentUrlPatterns: ['*://*/ipfs/*', '*://*/ipns/*'],
onclick: onCopyCanonicalAddress
})

browser.contextMenus.create({
id: contextMenuCopyAddressAtPublicGw,
title: browser.i18n.getMessage(contextMenuCopyAddressAtPublicGw),
contexts: ['page', 'image', 'video', 'audio', 'link'],
documentUrlPatterns: ['*://*/ipfs/*', '*://*/ipns/*'],
onclick: onCopyAddressAtPublicGw
})
} catch (err) {
// documentUrlPatterns is not supported in brave
if (err.message.indexOf('createProperties.documentUrlPatterns of contextMenus.create is not supported yet') > -1) {
console.warn('[ipfs-companion] Context menus disabled - createProperties.documentUrlPatterns of contextMenus.create is not supported yet')
return { update: () => Promise.resolve() }
}
throw err
}

return {
async update (changedTabId) {
try {
await browser.contextMenus.update(contextMenuUploadToIpfs, {enabled: getState().peerCount > 0})
if (changedTabId) {
// recalculate tab-dependant menu items
const currentTab = await browser.tabs.query({active: true, currentWindow: true}).then(tabs => tabs[0])
if (currentTab && currentTab.id === changedTabId) {
const ipfsContext = ipfsPathValidator.isIpfsPageActionsContext(currentTab.url)
browser.contextMenus.update(contextMenuCopyCanonicalAddress, {enabled: ipfsContext})
browser.contextMenus.update(contextMenuCopyAddressAtPublicGw, {enabled: ipfsContext})
}
}
} catch (err) {
console.log('[ipfs-companion] Error updating context menus', err)
}
}

// TODO: destroy?
}
}

module.exports.createContextMenus = createContextMenus
56 changes: 56 additions & 0 deletions add-on/src/lib/copier.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
'use strict'

const browser = require('webextension-polyfill')
const { safeIpfsPath } = require('./ipfs-path')
const { findUrlForContext } = require('./context-menus')

async function copyTextToClipboard (copyText) {
const currentTab = await browser.tabs.query({active: true, currentWindow: true}).then(tabs => tabs[0])
const tabId = currentTab.id
// Lets take a moment and ponder on the state of copying a string in 2017:
const copyToClipboardIn2017 = `function copyToClipboardIn2017(text) {
function oncopy(event) {
document.removeEventListener('copy', oncopy, true);
event.stopImmediatePropagation();
event.preventDefault();
event.clipboardData.setData('text/plain', text);
}
document.addEventListener('copy', oncopy, true);
document.execCommand('copy');
}`

// In Firefox you can't select text or focus an input field in background pages,
// so you can't write to the clipboard from a background page.
// We work around this limitation by injecting content scropt into a tab and copying there.
// Yes, this is 2017.
try {
const copyHelperPresent = (await browser.tabs.executeScript(tabId, { runAt: 'document_start', code: "typeof copyToClipboardIn2017 === 'function';" }))[0]
if (!copyHelperPresent) {
await browser.tabs.executeScript(tabId, { runAt: 'document_start', code: copyToClipboardIn2017 })
}
await browser.tabs.executeScript(tabId, { runAt: 'document_start', code: 'copyToClipboardIn2017(' + JSON.stringify(copyText) + ');' })
} catch (error) {
console.error('Failed to copy text: ' + error)
}
}

function createCopier (getState, notify) {
return {
async copyCanonicalAddress (context) {
const url = await findUrlForContext(context)
const rawIpfsAddress = safeIpfsPath(url)
copyTextToClipboard(rawIpfsAddress)
notify('notify_copiedCanonicalAddressTitle', rawIpfsAddress)
},

async copyAddressAtPublicGw (context) {
const url = await findUrlForContext(context)
const state = getState()
const urlAtPubGw = url.replace(state.gwURLString, state.pubGwURLString)
copyTextToClipboard(urlAtPubGw)
notify('notify_copiedPublicURLTitle', urlAtPubGw)
}
}
}

module.exports = createCopier
Loading

0 comments on commit e3a593e

Please sign in to comment.