Skip to content

Commit

Permalink
change javascript to esm
Browse files Browse the repository at this point in the history
  • Loading branch information
ddPn08 committed May 28, 2023
1 parent 2227662 commit 039019e
Show file tree
Hide file tree
Showing 7 changed files with 129 additions and 67 deletions.
20 changes: 20 additions & 0 deletions javascripts/gallery.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { addEventListener } from './radiata'
import { gradioApp, setObserver } from './utils'

addEventListener('ready', () => {
gradioApp()
.querySelectorAll('.info-gallery')
.forEach((gallery) => {
const click = () => {
let textarea = gallery.parentElement.querySelector('.image-generation-selected textarea')
let selected = [...gallery.querySelectorAll('.thumbnail-item.thumbnail-small')].find((e) => e.classList.contains('selected'))
let src = selected?.getElementsByTagName('img')[0].getAttribute('src')
textarea.value = src == null ? '' : new URL(src).pathname.slice(6)
textarea.dispatchEvent(new Event('input'))
}
setObserver(gallery, (node) => {
node.querySelector(':scope>button[aria-label=Clear]')?.addEventListener('click', click)
})
gallery.addEventListener('click', click)
})
})
48 changes: 48 additions & 0 deletions javascripts/radiata.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { gradioApp } from './utils'

window['__RADIATA_CONTEXT'] = {
executedOnLoaded: false,
eventListeners: {},
}

/**
* @param {string} type
* @param {*} listener
* @param {*} options
*/
export const addEventListener = (type, listener, options) => {
if (!window['__RADIATA_CONTEXT']['eventListeners'][type]) window['__RADIATA_CONTEXT']['eventListeners'][type] = []
window['__RADIATA_CONTEXT']['eventListeners'][type].push({ listener, options })
}

/**
* @param {string} type
* @param {...any} args
* @returns
*/
export const callEventListeners = (type, ...args) => {
if (!window['__RADIATA_CONTEXT']['eventListeners'][type]) return
window['__RADIATA_CONTEXT']['eventListeners'][type].forEach((listener) => listener.listener(...args))
}

export const initialize = () => {
addEventListener('ready', () => {
const button = gradioApp().getElementById('inference-mode-reload-button')
button.click()
})

document.addEventListener('DOMContentLoaded', function () {
var mutationObserver = new MutationObserver((m) => {
if (window['__RADIATA_CONTEXT'].executedOnLoaded) return
window['__RADIATA_CONTEXT'].executedOnLoaded = true
const interval = setInterval(() => {
const root = gradioApp().getElementById('radiata-root')
if (root) {
clearInterval(interval)
callEventListeners('ready')
}
}, 500)
})
mutationObserver.observe(gradioApp(), { childList: true, subtree: true })
})
}
25 changes: 25 additions & 0 deletions javascripts/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* Get the gradio-app element
* @returns {ShadowRoot | Document}
*/
export const gradioApp = () => {
const elems = document.getElementsByTagName('gradio-app')
const elem = elems.length == 0 ? document : elems[0]

if (elem !== document) elem.getElementById = (id) => document.getElementById(id)
return elem.shadowRoot ? elem.shadowRoot : elem
}

/**
* Set a MutationObserver on a target
* @param {Element} target
* @param {*} fn
* @returns {MutationObserver}
*/
export const setObserver = (target, fn) => {
let observer = new MutationObserver((records) => {
for (const record of records) for (const nodeList of record.addedNodes) if (nodeList instanceof HTMLElement) fn(nodeList)
})
observer.observe(target, { childList: true, subtree: true })
return observer
}
11 changes: 11 additions & 0 deletions jsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"module": "ESNext",
"target": "ESNext",
"paths": {
"/javascripts/*": [
"./javascripts/*"
]
}
},
}
14 changes: 14 additions & 0 deletions modules/javascripts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import os
from fastapi import FastAPI
from fastapi.responses import FileResponse


def apply_javascript_api(app: FastAPI):
def get(file_path: str):
dirname = os.path.dirname(file_path)
basename = os.path.basename(file_path)
if "." not in basename:
basename = f"{basename}.js"
return FileResponse(path=os.path.join("javascripts", dirname, basename))

app.get("/javascripts/{file_path:path}")(get)
65 changes: 3 additions & 62 deletions script.js
Original file line number Diff line number Diff line change
@@ -1,63 +1,4 @@
window['__RADIATA_CONTEXT'] = {
executedOnLoaded: false
}
import { initialize } from '/javascripts/radiata'
import '/javascripts/gallery'

/**
* @returns {ShadowRoot | Document}
*/
function gradioApp() {
const elems = document.getElementsByTagName('gradio-app')
const elem = elems.length == 0 ? document : elems[0]

if (elem !== document) elem.getElementById = (id) => document.getElementById(id)
return elem.shadowRoot ? elem.shadowRoot : elem
}

function setObserver(target, fn) {
let observer = new MutationObserver((records) => {
for (const record of records)
for (const nodeList of record.addedNodes)
if (nodeList instanceof HTMLElement) fn(nodeList)
});
observer.observe(target, { childList: true, subtree: true })
return observer
}

document.addEventListener("DOMContentLoaded", function () {
var mutationObserver = new MutationObserver((m) => {
if (window['__RADIATA_CONTEXT'].executedOnLoaded) return
window['__RADIATA_CONTEXT'].executedOnLoaded = true
const interval = setInterval(() => {
const root = gradioApp().getElementById("radiata-root")
if (root) {
clearInterval(interval)
inferenceReloadListeners()
attachGalleryListeners()
}
}, 500)
})
mutationObserver.observe(gradioApp(), { childList: true, subtree: true })
})

function inferenceReloadListeners() {
const button = gradioApp().getElementById("inference-mode-reload-button")
button.click()
}

/* Gallery */

function attachGalleryListeners() {
gradioApp().querySelectorAll('.info-gallery').forEach((gallery) => {
setObserver(gallery, (node) => {
node.querySelector(":scope>button[aria-label=Clear]")?.addEventListener('click', click);
});
function click() {
let textarea = gallery.parentElement.querySelector(".image-generation-selected textarea");
let selected = [...gallery.querySelectorAll('.thumbnail-item.thumbnail-small')].find((e) => e.classList.contains("selected"));
let src = selected?.getElementsByTagName("img")[0].getAttribute("src")
textarea.value = src == null ? "" : new URL(src).pathname.slice(6);
textarea.dispatchEvent(new Event('input'));
}
gallery.addEventListener('click', click);
});
}
initialize()
13 changes: 8 additions & 5 deletions webui.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import os
import time

from fastapi import FastAPI

if "--tensorrt" in os.environ.get("COMMANDLINE_ARGS", ""):
import tensorrt as trt

Expand All @@ -15,7 +17,7 @@
PreAppLaunchEvent,
PreUICreateEvent,
)
from modules import config, model_manager, plugin_loader, ui
from modules import config, model_manager, plugin_loader, ui, javascripts
from modules.diffusion import embeddings, networks


Expand All @@ -28,8 +30,9 @@ def pre_load():
model_manager.init()


def post_load():
PostAppLaunchEvent.call_event()
def post_load(app: FastAPI):
javascripts.apply_javascript_api(app)
PostAppLaunchEvent.call_event(app)


def wait_on_server():
Expand All @@ -41,15 +44,15 @@ def webui():
pre_load()
PreUICreateEvent.call_event()
app = ui.create_ui()
PostUICreateEvent.call_event(PostUICreateEvent(app=app))
PostUICreateEvent.call_event(app)
app.queue(64)
app, local_url, share_url = app.launch(
server_name=config.get("host"),
server_port=config.get("port"),
share=config.get("share"),
prevent_thread_lock=True,
)
post_load()
post_load(app)
wait_on_server()


Expand Down

0 comments on commit 039019e

Please sign in to comment.