Skip to content

Commit

Permalink
fix(wx): merge pageAction into browserAction
Browse files Browse the repository at this point in the history
Only one of browser_action, page_action can be specified in Chrome

Part of #218 effort
  • Loading branch information
lidel committed May 11, 2017
1 parent d7ac1c6 commit 8c86572
Show file tree
Hide file tree
Showing 6 changed files with 225 additions and 238 deletions.
7 changes: 0 additions & 7 deletions add-on/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,6 @@
"default_popup": "src/popup/browser-action.html"
},

"page_action": {
"browser_style": true,
"default_title": "Show IPFS actions for this page",
"default_icon": "icons/ipfs-logo-on.svg",
"default_popup": "src/popup/page-action.html"
},

"options_ui": {
"page": "src/options/options.html"
},
Expand Down
14 changes: 7 additions & 7 deletions add-on/src/lib/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -325,17 +325,17 @@ function updateContextMenus () {
browser.contextMenus.update(contextMenuUploadToIpfs, {enabled: state.peerCount > 0})
}

// pageAction
// Page Actions
// -------------------------------------------------------------------

// used in browser-action popup
// eslint-disable-next-line no-unused-vars
function isIpfsPageActionsContext (url) {
return window.IsIpfs.url(url) && !url.startsWith(state.apiURLString)
}

async function onUpdatedTab (tabId, changeInfo, tab) {
if (tab && tab.url) {
const ipfsContext = window.IsIpfs.url(tab.url) && !tab.url.startsWith(state.apiURLString)
if (ipfsContext) {
browser.pageAction.show(tab.id)
} else {
browser.pageAction.hide(tab.id)
}
if (state.linkify && changeInfo.status === 'complete') {
console.log(`Running linkfyDOM for ${tab.url}`)
try {
Expand Down
24 changes: 23 additions & 1 deletion add-on/src/popup/browser-action.html
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,35 @@
<body>
<!-- https://firefoxux.github.io/StyleGuide/#/navigation -->
<div class="panel">
<div class="panel-section panel-section-list" id="ipfs-resource-context-actions">
<div class="panel-list-item" id="copy-current-ipfs-address">
<div class="icon"></div>
<div class="text" data-i18n="panelCopy_currentIpfsAddress"></div>
<div class="text-shortcut"></div>
</div>
<div class="panel-list-item" id="copy-current-public-gw-url">
<div class="icon"></div>
<div class="text" data-i18n="panel_copyCurrentPublicGwUrl"></div>
<div class="text-shortcut"></div>
</div>
<div class="panel-list-item" id="pin-current-ipfs-address">
<div class="icon"></div>
<div class="text" data-i18n="panel_pinCurrentIpfsAddress"></div>
<div class="text-shortcut"></div>
</div>
<div class="panel-list-item" id="unpin-current-ipfs-address">
<div class="icon"></div>
<div class="text" data-i18n="panel_unpinCurrentIpfsAddress"></div>
<div class="text-shortcut"></div>
</div>
<div class="panel-section-separator"></div>
</div>
<div class="panel-section panel-section-list" id="operations">
<div class="panel-list-item" id="quick-upload">
<div class="icon"></div>
<div class="text" data-i18n="panel_quickUpload"></div>
<div class="text-shortcut"></div>
</div>
<div class="panel-section-separator"></div>
<div class="panel-list-item" id="open-webui">
<div class="icon"></div>
<div class="text" data-i18n="panel_openWebui"></div>
Expand Down
215 changes: 195 additions & 20 deletions add-on/src/popup/browser-action.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
'use strict'
/* eslint-env browser, webextensions */

const ipfsContextActions = document.getElementById('ipfs-resource-context-actions')
const pinResourceButton = document.getElementById('pin-current-ipfs-address')
const unpinResourceButton = document.getElementById('unpin-current-ipfs-address')
const copyIpfsAddressButton = document.getElementById('copy-current-ipfs-address')
const copyPublicGwAddressButton = document.getElementById('copy-current-public-gw-url')

const enableRedirect = document.getElementById('enable-gateway-redirect')
const disableRedirect = document.getElementById('disable-gateway-redirect')
const openWebUI = document.getElementById('open-webui')
Expand All @@ -12,26 +18,193 @@ const ipfsIconOn = '../../icons/ipfs-logo-on.svg'
const ipfsIconOff = '../../icons/ipfs-logo-off.svg'
const offline = 'offline'

function show (id) {
document.getElementById(id).classList.remove('hidden')
function resolv (element) {
// lookup DOM if element is just a string ID
if (Object.prototype.toString.call(element) === '[object String]') {
return document.getElementById(element)
}
// return as-is otherwise
return element
}

function hide (id) {
document.getElementById(id).classList.add('hidden')
function set (id, value) {
resolv(id).textContent = value
}

function set (id, value) {
document.getElementById(id).textContent = value
function show (element) {
element = resolv(element)
element.classList.remove('disabled')
element.classList.remove('hidden')
}

function disable (element) {
resolv(element).classList.add('disabled')
}

function hide (element) {
resolv(element).classList.add('hidden')
}

function getBackgroundPage () {
return browser.runtime.getBackgroundPage()
}

function getCurrentTab () {
return browser.tabs.query({active: true, currentWindow: true}).then(tabs => tabs[0])
}

// Ipfs Context Page Actions
// ===================================================================

async function copyCurrentPublicGwAddress () {
const bg = await getBackgroundPage()
const currentTab = await getCurrentTab()
const publicGwAddress = new URL(currentTab.url.replace(bg.state.gwURLString, 'https://ipfs.io/')).toString()
copyTextToClipboard(publicGwAddress)
bg.notify('notify_copiedPublicURLTitle', publicGwAddress)
window.close()
}

async function copyCurrentCanonicalAddress () {
const bg = await getBackgroundPage()
const currentTab = await getCurrentTab()
const rawIpfsAddress = currentTab.url.replace(/^.+(\/ip(f|n)s\/.+)/, '$1')
copyTextToClipboard(rawIpfsAddress)
bg.notify('notify_copiedCanonicalAddressTitle', rawIpfsAddress)
window.close()
}

function copyTextToClipboard (copyText) {
// lets take a moment and ponder on the state of copying a string in 2017
const copyFrom = document.createElement('textarea')
copyFrom.textContent = copyText
const body = document.getElementsByTagName('body')[0]
body.appendChild(copyFrom) // oh god why
copyFrom.select()
document.execCommand('copy') // srsly
body.removeChild(copyFrom)
}

async function pinCurrentResource () {
deactivatePinButton()
try {
const bg = await getBackgroundPage()
const currentTab = await getCurrentTab()
const currentPath = await resolveToIPFS(new URL(currentTab.url).pathname)
const pinResult = await bg.ipfs.pin.add(currentPath, { recursive: true })
console.log('ipfs.pin.add result', pinResult)
bg.notify('notify_pinnedIpfsResourceTitle', currentPath)
} catch (error) {
handlePinError('notify_pinErrorTitle', error)
}
window.close()
}

async function unpinCurrentResource () {
deactivatePinButton()
try {
const bg = await getBackgroundPage()
const currentTab = await getCurrentTab()
const currentPath = await resolveToIPFS(new URL(currentTab.url).pathname)
const result = await bg.ipfs.pin.rm(currentPath, {recursive: true})
console.log('ipfs.pin.rm result', result)
bg.notify('notify_unpinnedIpfsResourceTitle', currentPath)
} catch (error) {
handlePinError('notify_unpinErrorTitle', error)
}
window.close()
}

function activatePinning () {
pinResourceButton.onclick = pinCurrentResource
show(pinResourceButton)
unpinResourceButton.onclick = undefined
hide(unpinResourceButton)
}

function activateUnpinning () {
pinResourceButton.onclick = undefined
unpinResourceButton.onclick = unpinCurrentResource
hide(pinResourceButton)
show(unpinResourceButton)
}

function deactivatePinButton () {
pinResourceButton.onclick = undefined
unpinResourceButton.onclick = undefined
disable(pinResourceButton)
hide(unpinResourceButton)
}

async function handlePinError (errorMessageKey, error) {
console.error(browser.i18n.getMessage(errorMessageKey), error)
deactivatePinButton()
try {
const bg = await getBackgroundPage()
bg.notify(errorMessageKey, error.message)
} catch (error) {
console.error('unable to access background page', error)
}
}

async function resolveToIPFS (path) {
if (/^\/ipns/.test(path)) {
const bg = await getBackgroundPage()
const response = await bg.ipfs.name.resolve(path, {recursive: true, nocache: false})
return response.Path
}
return path
}

async function activatePinButton () {
try {
const bg = await getBackgroundPage()
const currentTab = await getCurrentTab()
const currentPath = await resolveToIPFS(new URL(currentTab.url).pathname)
const response = await bg.ipfs.pin.ls(currentPath, {quiet: true})
console.log(`positive ipfs.pin.ls for ${currentPath}: ${JSON.stringify(response)}`)
activateUnpinning()
} catch (error) {
if (/is not pinned/.test(error.message)) {
console.log(`negative ipfs.pin.ls: ${error} (${JSON.stringify(error)})`)
activatePinning()
} else {
console.error(`unexpected result of ipfs.pin.ls: ${error} (${JSON.stringify(error)})`)
deactivatePinButton()
}
}
}

async function updatePageActions () {
console.log('running updatePageActions()')
try {
const bg = await getBackgroundPage()
const currentTab = await getCurrentTab()
if (bg.isIpfsPageActionsContext(currentTab.url)) {
deactivatePinButton()
show(ipfsContextActions)
copyPublicGwAddressButton.onclick = copyCurrentPublicGwAddress
copyIpfsAddressButton.onclick = copyCurrentCanonicalAddress
activatePinButton()
} else {
hide(ipfsContextActions)
}
} catch (error) {
console.error(`Error while setting up pageAction: ${error}`)
}
}

// Global Actions
// ===================================================================

quickUpload.onclick = () => browser.tabs.create({ url: browser.extension.getURL('src/popup/quick-upload.html') })

enableRedirect.onclick = () => browser.storage.local.set({useCustomGateway: true})
.then(updatePopup)
.then(updateBrowserActionPopup)
.catch(error => { console.error(`Unable to update redirect state due to ${error}`) })

disableRedirect.onclick = () => browser.storage.local.set({useCustomGateway: false})
.then(updatePopup)
.then(updateBrowserActionPopup)
.catch(error => { console.error(`Unable to update redirect state due to ${error}`) })

openWebUI.onclick = async () => {
Expand All @@ -49,7 +222,7 @@ openPreferences.onclick = () => {
browser.runtime.openOptionsPage().then(() => window.close())
}

async function updatePopup () {
async function updateBrowserActionPopup () {
// update redirect status
const options = await browser.storage.local.get()
try {
Expand Down Expand Up @@ -77,16 +250,9 @@ async function updatePopup () {
try {
const background = await browser.runtime.getBackgroundPage()
if (background.ipfs) {
// update gateway version
try {
const v = await background.ipfs.version()
set('gateway-version-val', (v.commit ? v.version + '/' + v.commit : v.version))
} catch (error) {
set('gateway-version-val', offline)
}
// update swarm peer count
try {
const peerCount = await background.getSwarmPeerCount()
const peerCount = background.state.peerCount
set('swarm-peers-val', peerCount < 0 ? offline : peerCount)
ipfsIcon.src = peerCount > 0 ? ipfsIconOn : ipfsIconOff
if (peerCount > 0) { // API is online & there are peers
Expand All @@ -102,16 +268,25 @@ async function updatePopup () {
} catch (error) {
console.error(`Unable update peer count due to ${error}`)
}
// update gateway version
try {
const v = await background.ipfs.version()
set('gateway-version-val', (v.commit ? v.version + '/' + v.commit : v.version))
} catch (error) {
set('gateway-version-val', offline)
}
}
} catch (error) {
console.error(`Error while accessing background page: ${error}`)
}
}

// run on initial popup load
// hide things that cause ugly reflow if removed later
hide(ipfsContextActions)
hide('quick-upload')
hide('open-webui')
updatePopup()

// listen to any changes and update diagnostics
browser.alarms.onAlarm.addListener(updatePopup)
browser.alarms.onAlarm.addListener(updateBrowserActionPopup)
document.addEventListener('DOMContentLoaded', updatePageActions)
document.addEventListener('DOMContentLoaded', updateBrowserActionPopup)
42 changes: 0 additions & 42 deletions add-on/src/popup/page-action.html

This file was deleted.

Loading

0 comments on commit 8c86572

Please sign in to comment.