Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Popup Toast and Cleanup #9

Merged
merged 1 commit into from
Dec 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"description": "SMWC.world Web Extension and Browser Addon to Easily Patch and Play SMW ROMs.",
"homepage_url": "https://smwc.world",
"author": "Shane",
"version": "0.0.5",
"version": "0.0.6",
"manifest_version": 3,
"commands": {
"_execute_action": {
Expand All @@ -13,7 +13,7 @@
"description": "Show Main Popup Action"
}
},
"permissions": ["contextMenus", "notifications", "storage"],
"permissions": ["contextMenus", "downloads", "notifications", "storage"],
"background": {
"type": "module"
},
Expand Down
34 changes: 0 additions & 34 deletions src/html/options.html
Original file line number Diff line number Diff line change
Expand Up @@ -55,40 +55,6 @@ <h1>SMWC Web Extension</h1>
</div>
</form>

<!-- <div class="accordion" id="accordionExample">-->
<!-- <div class="accordion-item">-->
<!-- <h2 class="accordion-header">-->
<!-- <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="false" aria-controls="collapseOne">-->
<!-- Advanced Settings-->
<!-- </button>-->
<!-- </h2>-->
<!-- <div id="collapseOne" class="accordion-collapse collapse" data-bs-parent="#accordionExample">-->
<!-- <div class="accordion-body">-->
<!-- <div class="alert alert-warning text-center" role="alert"><strong>DO NOT</strong> Change This Setting!</div>-->

<!-- <form id="advanced" class="">-->
<!-- <label for="url" class="form-label">SMWC.world URL</label>-->
<!-- <a id="reset-default" class="float-end align-bottom small" role="button">Reset to Default</a>-->
<!-- <input type="text" id="url" class="options" aria-describedby="urlHelp">-->
<!-- <div id="urlInvalid" class="invalid-feedback">Invalid Hostname.</div>-->
<!-- <div id="urlHelp" class="form-text mb-3">-->
<!-- URL to SMWC.world Instance. Only used for testing!-->
<!-- </div>-->
<!-- <div class="">-->
<!-- <button type="submit" class="btn btn-outline-warning w-100">-->
<!-- Save Advanced Settings-->
<!-- <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" fill="currentColor" class="bi bi-floppy2 ms-1" viewBox="0 0 16 16">-->
<!-- <path d="M1.5 0h11.586a1.5 1.5 0 0 1 1.06.44l1.415 1.414A1.5 1.5 0 0 1 16 2.914V14.5a1.5 1.5 0 0 1-1.5 1.5h-13A1.5 1.5 0 0 1 0 14.5v-13A1.5 1.5 0 0 1 1.5 0ZM1 1.5v13a.5.5 0 0 0 .5.5H2v-4.5A1.5 1.5 0 0 1 3.5 9h9a1.5 1.5 0 0 1 1.5 1.5V15h.5a.5.5 0 0 0 .5-.5V2.914a.5.5 0 0 0-.146-.353l-1.415-1.415A.5.5 0 0 0 13.086 1H13v3.5A1.5 1.5 0 0 1 11.5 6h-7A1.5 1.5 0 0 1 3 4.5V1H1.5a.5.5 0 0 0-.5.5Zm9.5-.5a.5.5 0 0 0-.5.5v3a.5.5 0 0 0 .5.5h1a.5.5 0 0 0 .5-.5v-3a.5.5 0 0 0-.5-.5h-1Z"/>-->
<!-- </svg>-->
<!-- </button>-->
<!-- </div>-->
<!-- </form>-->

<!-- </div>-->
<!-- </div>-->
<!-- </div>-->
<!-- </div>-->

<hr>
<div class="text-center">
<a class="link-body-emphasis text-decoration-none d-inline-block" target="_blank" rel="noopener"
Expand Down
14 changes: 13 additions & 1 deletion src/html/popup.html
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,22 @@
<div class="justify-content-center align-items-center d-flex text-center small">
<img src="../images/logo16.png" class="me-1" alt="SMWC Web Extension" title="SMWC Web Extension">
<a class="link-offset-2 link-underline link-underline-opacity-0 link-underline-opacity-75-hover mx-2" type="button" rel="noopener"
id="homepage_url" href="">SMWC Web Extension</a> v<span id="version"></span>
href="homepage_url">SMWC Web Extension</a> v<span id="version"></span>
</div>
</div>

<div aria-live="polite" aria-atomic="true" class="">
<div id="toast-container" class="toast-container bottom-0 end-0 p-3"></div>
</div>

<div class="d-none">
<div class="toast align-items-center border-0" role="alert" aria-live="assertive" aria-atomic="true" data-bs-delay="5000">
<div class="d-flex">
<div class="toast-body text-break small"></div>
</div>
</div>
</div> <!-- d-none -->

<script type="text/javascript" src="../dist/jquery/jquery.min.js"></script>
<script type="text/javascript" src="../dist/bootstrap/bootstrap.bundle.min.js"></script>
<script type="module" src="../js/popup.js"></script>
Expand Down
38 changes: 31 additions & 7 deletions src/js/exports.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,19 @@
* @param {Function} callback
*/
export function patchRom(url, key, callback) {
const smwcWorld = 'https://smwc.world/patcher/'
console.debug(`patchRom: ${key}: ${url}`)
const patcherUrl = 'https://smwc.world/patcher/'
const sourceRom =
'https://github.com/videofindersTV/super-mario-world/raw/master/Super.Mario.World.1.smc'
const formdata = new FormData()
formdata.append('patch_url', url)
formdata.append('source_url', sourceRom)

const requestOptions = {
method: 'POST',
body: formdata,
redirect: 'follow',
}

fetch(smwcWorld, requestOptions)
fetch(patcherUrl, requestOptions)
.then((response) => response.json())
.then((result) => callback(result, key))
.catch((error) => console.warn('error', error))
Expand All @@ -33,18 +32,20 @@ export function patchRom(url, key, callback) {
* @param {InputEvent} event
*/
export async function saveOptions(event) {
console.log('saveOptions:', event)
console.debug('saveOptions:', event)
const { options } = await chrome.storage.sync.get(['options'])
let value
if (event.target.type === 'checkbox') {
value = event.target.checked
} else if (event.target.type === 'text') {
} else {
value = event.target.value
}
if (value !== undefined) {
options[event.target.id] = value
console.log(`Set: ${event.target.id}:`, value)
console.info(`Set: ${event.target.id}:`, value)
await chrome.storage.sync.set({ options })
} else {
console.warn(`Unknown Options ID: ${event.target.id}`)
}
}

Expand All @@ -66,3 +67,26 @@ export function updateOptions(options) {
}
}
}

/**
* Show Bootstrap Toast
* @function showToast
* @param {String} message
* @param {String} type
*/
export function showToast(message, type = 'success') {
console.debug(`showToast: ${type}: ${message}`)
const clone = document.querySelector('.d-none .toast')
const container = document.getElementById('toast-container')
if (clone && container) {
const element = clone.cloneNode(true)
element.querySelector('.toast-body').innerHTML = message
element.classList.add(`text-bg-${type}`)
container.appendChild(element)
const toast = new bootstrap.Toast(element)
element.addEventListener('mousemove', () => toast.hide())
toast.show()
} else {
console.info('Missing clone or container:', clone, container)
}
}
30 changes: 5 additions & 25 deletions src/js/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,21 @@

import { saveOptions, updateOptions } from './exports.js'

document.addEventListener('DOMContentLoaded', initOptions)

chrome.storage.onChanged.addListener(onChanged)

document.addEventListener('DOMContentLoaded', initOptions)
document
.querySelectorAll('#options-form input')
.forEach((el) => el.addEventListener('change', saveOptions))
document
.querySelectorAll('[data-bs-toggle="tooltip"]')
.forEach((el) => new bootstrap.Tooltip(el))

// document.getElementById('advanced').addEventListener('submit', saveAdvanced)

/**
* Initialize Options
* @function initOptions
*/
async function initOptions() {
console.log('initOptions')
console.debug('initOptions')
document.getElementById('version').textContent =
chrome.runtime.getManifest().version

Expand All @@ -29,7 +25,7 @@ async function initOptions() {
commands.find((x) => x.name === '_execute_action').shortcut || 'Not Set'

const { options } = await chrome.storage.sync.get(['options'])
console.log('options:', options)
console.debug('options:', options)
updateOptions(options)
}

Expand All @@ -40,27 +36,11 @@ async function initOptions() {
* @param {String} namespace
*/
function onChanged(changes, namespace) {
console.log('onChanged:', changes, namespace)
console.debug('onChanged:', changes, namespace)
for (let [key, { newValue }] of Object.entries(changes)) {
if (key === 'options') {
console.log(newValue)
console.debug(newValue)
updateOptions(newValue)
}
}
}

// /**
// * Save Options Click
// * @function saveAdvanced
// * @param {SubmitEvent} event
// */
// async function saveAdvanced(event) {
// console.log('saveOptions:', event)
// event.preventDefault()
// // const { url } = await chrome.storage.local.get(['url'])
// const input = document.getElementById('url')
// const url = input.value.replace(/\/$/, '')
// input.value = url
// console.log(`url: ${url}`)
// await chrome.storage.local.set({ url })
// }
55 changes: 22 additions & 33 deletions src/js/popup.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// JS for popup.html

import { patchRom, saveOptions, updateOptions } from './exports.js'
import { patchRom, saveOptions, showToast, updateOptions } from './exports.js'

document.addEventListener('DOMContentLoaded', initPopup)

document.getElementById('patch-form').addEventListener('submit', patchForm)
document
.querySelectorAll('a[href]')
.forEach((el) => el.addEventListener('click', popupLinks))
Expand All @@ -17,27 +17,23 @@ document
.querySelectorAll('[data-bs-toggle="tooltip"]')
.forEach((el) => new bootstrap.Tooltip(el))

document.getElementById('patch-form').addEventListener('submit', patchForm)

const patchRomBtn = document.getElementById('patch-rom')

/**
* Initialize Popup
* @function initPopup
*/
async function initPopup() {
console.log('initPopup')
console.debug('initPopup')
document.getElementById('patch-input').focus()

const manifest = chrome.runtime.getManifest()
document.getElementById('version').textContent = manifest.version
document.getElementById('homepage_url').href = manifest.homepage_url
document.querySelector('[href="homepage_url"]').href = manifest.homepage_url

const { options, popup } = await chrome.storage.sync.get([
'options',
'popup',
])
console.log('options, popup:', options, popup)
console.debug('options, popup:', options, popup)
document.getElementById(popup.searchType).checked = true
updateOptions(options)
}
Expand All @@ -49,10 +45,10 @@ async function initPopup() {
* @param {MouseEvent} event
*/
async function popupLinks(event) {
console.log('popupLinks:', event)
console.debug('popupLinks:', event)
event.preventDefault()
const anchor = event.target.closest('a')
console.log(`anchor.href: ${anchor.href}`)
console.info(`anchor.href: ${anchor.href}`)
if (anchor.href.endsWith('html/options.html')) {
chrome.runtime.openOptionsPage()
} else {
Expand All @@ -67,12 +63,12 @@ async function popupLinks(event) {
* @param {SubmitEvent} event
*/
async function updateSearchType(event) {
console.log('updateSearchType:', event)
console.debug('updateSearchType:', event)
const { popup } = await chrome.storage.sync.get(['popup'])
popup.searchType = event.target.id
await chrome.storage.sync.set({ popup })
const value = document.getElementById('patch-input').value
console.log('value:', value)
console.info('value:', value)
if (value) {
await patchForm(event)
}
Expand All @@ -84,41 +80,34 @@ async function updateSearchType(event) {
* @param {SubmitEvent} event
*/
async function patchForm(event) {
console.log('linksForm:', event)
console.debug('linksForm:', event)
event.preventDefault()
const patchRomBtn = document.getElementById('patch-rom')
if (patchRomBtn.classList.contains('disabled')) {
return console.log('Duplicate Click Detected!')
return console.info('Duplicate Click Detected!')
}
patchRomBtn.classList.add('disabled')
const value = document.getElementById('patch-input').value
console.log('value:', value)
console.info('value:', value)
const key = document.querySelector('input[name="searchType"]:checked').value
console.log('key:', key)
console.debug('key:', key)
const callback = (result, key) => {
console.log('popup callback:', result)
console.debug('popup callback:', result)
patchRomBtn.classList.remove('disabled')
if (result[key]) {
chrome.tabs.create({ active: true, url: result[key] }).then()
if (key === 'download') {
chrome.downloads.download({ url: result[key] })
} else {
chrome.tabs.create({ active: true, url: result[key] }).then()
}
window.close()
} else if (result.error?.__all__) {
console.warn(result.error.__all__[0])
showAlert(result.error.__all__[0])
showToast(`Error: ${result.error.__all__[0]}`, 'danger')
} else {
console.warn('Unknown Result:', result)
showAlert('Unknown Error. Check Logs...')
showToast('Error Patching! Inspect Popup for Details.', 'danger')
}
}
patchRom(value, key, callback)
}

function showAlert(message) {
console.log('showAlert:', message)
const alert = document.getElementById('popup-alert')
alert.textContent = message
alert.classList.remove('d-none')
$('#popup-alert')
.fadeTo(5000, 500)
.slideUp(500, function () {
$('#popup-alert').slideUp(500)
})
}
23 changes: 1 addition & 22 deletions src/js/service-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import { patchRom } from './exports.js'
chrome.runtime.onInstalled.addListener(onInstalled)
chrome.contextMenus.onClicked.addListener(contextMenusClicked)
chrome.notifications.onClicked.addListener(notificationsClicked)
// chrome.commands.onCommand.addListener(onCommand)
// chrome.runtime.onMessage.addListener(onMessage)
chrome.storage.onChanged.addListener(onChanged)

/**
Expand Down Expand Up @@ -78,25 +76,6 @@ function notificationsClicked(notificationId) {
chrome.notifications.clear(notificationId)
}

// /**
// * On Command Callback
// * @function onCommand
// * @param {String} command
// */
// async function onCommand(command) {
// console.log(`onCommand: ${command}`)
// }
//
// /**
// * On Message Callback
// * @function onMessage
// * @param {Object} message
// * @param {MessageSender} sender
// */
// async function onMessage(message, sender) {
// console.log('onMessage:', message, sender)
// }

/**
* On Changed Callback
* @function onChanged
Expand Down Expand Up @@ -125,7 +104,7 @@ function onChanged(changes, namespace) {
* @function createContextMenus
*/
function createContextMenus() {
console.log('createContextMenus')
console.debug('createContextMenus')
chrome.contextMenus.removeAll()
const ctx = ['link']
const contexts = [
Expand Down