add dynamic theme load

feature/existing-files-listing
Alexander Sokol 2023-06-01 19:46:28 +03:00
parent 6712673842
commit 6bb1dbc267
9 changed files with 81 additions and 140 deletions

View File

@ -3,18 +3,18 @@ const script = document.createElement('script');
script.src = 'file=extensions/sd-model-organizer/javascript/tinymce/tinymce.min.js';
document.head.appendChild(script);
let isHomeInitialStateInvoked = false
function findElem(elementId) {
return document.getElementById(elementId)
// return gradioApp().getElementById(elementId)
}
function log(text) {
console.log(text)
console.log(text)
}
function handleDescriptionPreviewContentChange(content, theme) {
log('handleDescriptionPreviewContentChange')
function setupDescriptionPreview(content, theme) {
if (tinymce.get('mo-description-preview') == null) {
tinymce.init({
selector: '#mo-description-preview',
@ -36,14 +36,21 @@ function handleDescriptionPreviewContentChange(content, theme) {
if (inst.initialized) {
inst.setContent(content)
}
}
function handleDescriptionPreviewContentChange(content) {
log('handleDescriptionPreviewContentChange')
getTheme()
.then(theme => {
setupDescriptionPreview(content, theme)
})
return []
}
function handleDescriptionEditorContentChange(content, theme) {
log('handleDescriptionEditorContentChange')
function setupDescriptionEdit(content, theme) {
let contentData = content.replace(/<\[\[token=".*?"]]>/, '');
if (tinymce.get('mo-description-editor') == null) {
@ -64,6 +71,15 @@ function handleDescriptionEditorContentChange(content, theme) {
if (inst.initialized) {
inst.setContent(contentData)
}
}
function handleDescriptionEditorContentChange(content) {
log('handleDescriptionEditorContentChange')
getTheme()
.then(theme => {
setupDescriptionEdit(content, theme)
})
return []
}
@ -142,7 +158,6 @@ function updateDownloadCardState(id, state) {
updateDownloadBlockVisibility(id, 'info-bar', isDownloadProgressVisible, 'flex')
updateDownloadBlockVisibility(id, 'progress', isDownloadProgressVisible, 'flex')
updateDownloadBlockVisibility(id, 'result-box', isResultBoxVisible, 'block')
}
function updateResultText(id, title, text) {
@ -325,26 +340,26 @@ function navigateAdd() {
return []
}
function navigateImportExport(){
log('Navigate import_export screen')
const navObj = {
screen: "import_export",
token: generateUUID(),
backstack: populateBackstack()
};
deliverNavObject(navObj)
return []
function navigateImportExport() {
log('Navigate import_export screen')
const navObj = {
screen: "import_export",
token: generateUUID(),
backstack: populateBackstack()
};
deliverNavObject(navObj)
return []
}
function navigateDebug(){
log('Navigate debug screen')
const navObj = {
screen: "debug",
token: generateUUID(),
backstack: populateBackstack()
};
deliverNavObject(navObj)
return []
function navigateDebug() {
log('Navigate debug screen')
const navObj = {
screen: "debug",
token: generateUUID(),
backstack: populateBackstack()
};
deliverNavObject(navObj)
return []
}
function navigateEdit(id) {
@ -429,11 +444,9 @@ function deliverNavObject(navObj) {
console.log('JSON Nav dispatched: ' + navJson)
}
isHomeInitialStateInvoked = false
function invokeHomeInitialStateLoad(){
function invokeHomeInitialStateLoad() {
log('invokeHomeInitialStateLoad')
if(!isHomeInitialStateInvoked){
if (!isHomeInitialStateInvoked) {
const initialStateTextArea = findElem('mo-initial-state-box').querySelector('textarea')
const stateTextArea = findElem('mo-home-state-box').querySelector('textarea')
stateTextArea.value = initialStateTextArea.value
@ -445,92 +458,61 @@ function invokeHomeInitialStateLoad(){
return []
}
function testGET(){
log('testGET')
const origin = window.location.origin;
fetch(origin + '/gg/model?id_=6')
.then(response => response.json())
.then(data => {
// Handle the parsed JSON data here
log(data);
})
.catch(error => {
// Handle any errors that occurred during the request
log(error);
});
}
function handleDarkMode(){
log('handleDarkMode')
var parsedUrl = new URL(window.location.href);
var theme = parsedUrl.searchParams.get('__theme');
log('theme=' + theme)
}
function handleLightMode(){
log('handleDarkMode')
var parsedUrl = new URL(window.location.href);
var theme = parsedUrl.searchParams.get('__theme');
log('theme=' + theme)
}
function getTheme(){
return new Promise((resolve, reject) => {
var parsedUrl = new URL(window.location.href)
var theme = parsedUrl.searchParams.get('__theme')
if (theme != null){
function getTheme() {
return new Promise((resolve, _) => {
const parsedUrl = new URL(window.location.href)
const theme = parsedUrl.searchParams.get('__theme')
if (theme != null) {
log('theme resolved: ' + theme)
resolve(theme)
} else{
fetch(origin + '/mo/display-options')
.then(response => response.json())
.then(data => {
log('card width: ' + data.card_width)
log('card height: ' + data.card_height)
log('theme: ' + data.theme)
resolve(data.theme)
})
.catch(error => {
reject(error)
});
} else {
fetch(origin + '/mo/display-options')
.then(response => response.json())
.then(data => {
log('display options received:')
log(data)
resolve(data.theme)
})
.catch(_ => {
resolve('light')
});
}
});
}
function installStyles(theme){
var linkElementColors = document.createElement('link');
function installStyles(theme) {
const linkElementColors = document.createElement('link');
linkElementColors.rel = 'stylesheet';
if (theme === 'dark'){
linkElementColors.href = 'file=extensions/sd-model-organizer/colors-dark.css';
log("theme:" + theme)
const timestamp = '?v=' + new Date().getTime();
if (theme === 'dark') {
log('installing dark theme')
linkElementColors.href = 'file=extensions/sd-model-organizer/styles/colors-dark.css' + timestamp;
} else {
linkElementColors.href = 'file=extensions/sd-model-organizer/colors-light.css';
log('installing light theme')
linkElementColors.href = 'file=extensions/sd-model-organizer/styles/colors-light.css' + timestamp;
}
document.head.appendChild(linkElementColors);
var linkElementStyles = document.createElement('link');
const linkElementStyles = document.createElement('link');
linkElementStyles.rel = 'stylesheet';
linkElementStyles.href = 'file=extensions/sd-model-organizer/styles.css';
linkElementStyles.href = 'file=extensions/sd-model-organizer/styles/styles.css';
document.head.appendChild(linkElementStyles);
}
onUiLoaded(function () {
log("UI loaded")
homeTab = findElem('mo_home_tab')
intersectionObserver = new IntersectionObserver((entries) => {
const homeTab = findElem('mo_home_tab')
const intersectionObserver = new IntersectionObserver((entries) => {
if (entries[0].intersectionRatio > 0) invokeHomeInitialStateLoad();
});
intersectionObserver.observe(homeTab);
getTheme()
.then(data => {
resolve(data.theme)
})
.catch(error => {
print(error)
});
.then(data => {
installStyles(data)
})
})

View File

@ -1,34 +1,9 @@
import time
from fastapi import FastAPI
from scripts.mo.data.storage import map_record_to_dict
from scripts.mo.environment import logger, env
def init_extension_api(app: FastAPI):
@app.get(f"/gg/hello")
async def greeting():
logger.debug('Greetings api called')
return {
'message': 'Hello',
'date': time.time()
}
@app.get(f"/gg/models")
async def get_models():
records = env.storage.get_all_records()
records_dict = list(map(lambda r: map_record_to_dict(r), records))
return records_dict
@app.get(f"/gg/model")
async def get_model(id_):
record = env.storage.get_record_by_id(id_)
if record is None:
return {'message': f'Model with {id_} not found.'}
else:
return map_record_to_dict(record)
@app.get('/mo/display-options')
async def get_display_options():
return {
@ -37,4 +12,4 @@ def init_extension_api(app: FastAPI):
'theme': env.theme()
}
logger.debug('MO API initialized')
logger.debug('Model Organizer API initialized')

View File

@ -36,8 +36,6 @@ def on_id_changed(record_id):
def details_ui_block():
with gr.Blocks():
details_id_box = gr.Textbox(label='details_id_box', elem_classes='mo-alert-warning', visible=False)
theme_box = gr.Textbox(label='theme_box', elem_classes='mo-alert-warning', visible=False, value=env.theme())
with gr.Row():
back_button = gr.Button("Back")
remove_button = gr.Button("Remove")
@ -57,7 +55,7 @@ def details_ui_block():
outputs=[content_widget, description_html_widget, description_input_widget, edit_button,
download_button])
description_input_widget.change(fn=None, inputs=[description_input_widget, theme_box],
description_input_widget.change(fn=None, inputs=description_input_widget,
_js='handleDescriptionPreviewContentChange')
back_button.click(fn=None, _js='navigateBack')

View File

@ -301,10 +301,6 @@ def edit_ui_block():
elem_classes='mo-alert-warning',
interactive=False,
visible=False)
theme_box = gr.Textbox(label='theme_box',
elem_classes='mo-alert-warning',
visible=False,
value=env.theme())
sha256_preload_state = gr.State()
@ -402,7 +398,7 @@ def edit_ui_block():
interactive=False,
visible=False)
description_input_widget.change(fn=None, inputs=[description_input_widget, theme_box],
description_input_widget.change(fn=None, inputs=description_input_widget,
_js='handleDescriptionEditorContentChange')
description_output_widget.change(_on_description_output_changed,

View File

@ -68,8 +68,7 @@ def on_json_box_change(json_state, home_refresh_token):
def main_ui_block():
css_styles = _load_mo_css()
with gr.Blocks(css=css_styles, elem_id='model_organizer_tab') as main_block:
gr.HTML(f'<style>{css_styles}</style>')
with gr.Blocks(elem_id='model_organizer_tab') as main_block:
if env.is_storage_has_errors():
gr.HTML(styled.alert_danger(env.storage_error))
return main_block

View File

@ -296,10 +296,6 @@ def _details_top(record: Record) -> str:
def record_details(record: Record) -> str:
content = '<div class="mo-details-container">'
content += _details_top(record)
content += '<button type="button" class="mo-btn mo-btn-success" ' \
f'onclick="handleDarkMode()">Dark</button><br>'
content += '<button type="button" class="mo-btn mo-btn-success" ' \
f'onclick="handleLightMode()">Light</button><br>'
content += '</div>'
return content
@ -354,9 +350,6 @@ def records_cards(records: List[Record]) -> str:
content += '<button type="button" class="mo-btn mo-btn-danger" ' \
f'onclick="navigateRemove(\'{record.id_}\')">Remove</button><br>'
content += '<button type="button" class="mo-btn mo-btn-danger" ' \
f'onclick="testGET()">TEST</button><br>'
content += '</div>'
content += '</div>'

View File

@ -1,6 +1,4 @@
/* needed only for IDE. Gradio ignores it*/
@import "colors-dark.css";
:root {
--mo-card-width: 250px;
--mo-card-height: 350px;