Skip to content

Commit

Permalink
Updates
Browse files Browse the repository at this point in the history
  • Loading branch information
blurymind committed Sep 5, 2024
1 parent bb67c42 commit b9a01ca
Show file tree
Hide file tree
Showing 9 changed files with 132 additions and 67 deletions.
4 changes: 2 additions & 2 deletions index.html

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion js/main.06152b0e08b70fd763db.js

This file was deleted.

1 change: 1 addition & 0 deletions js/main.43480244c0cadf3ee66a.js

Large diffs are not rendered by default.

File renamed without changes.
File renamed without changes.
135 changes: 94 additions & 41 deletions public/plugins/resources-editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,24 @@ export var ResourcesEditor = function({
getGistFileUrl,
getSelectedResourceUrl,
updateUrlParams,

}) {
const self = this;
this.name = 'ResourcesEditor';
this.selectedResourcesJson = 'resources.json';
this.resourcesFileUrl = '';
this.resourcesFileContent = '';
this.initResourcesFile = () => {
const dbStorage = app.data.db;
this.getVloatileResource = () => dbStorage.getDbValue(`volatileResources-${this.selectedResourcesJson}`);
this.setVolatileResource = value => dbStorage.save(`volatileResources-${this.selectedResourcesJson}`, value);

this.hasLocalChanges = () => this.getVloatileResource().then(volatile => {
if(volatile && volatile.raw_url) return false;
return true;
})
this.getFromGist = () => {
return new Promise(resolve => {
// todo copypasta
app.data.storage.getGistFiles(app.ui.openSettingsDialog).then(({ filesInGist }) => {
const fileFound = Object.values(filesInGist).find(
item => item.filename === 'resources.json'
Expand All @@ -28,58 +39,83 @@ export var ResourcesEditor = function({
time: 3000,
});
this.resourcesFileUrl = file.raw_url;
this.setVolatileResource(file);
resolve(file);
});
} else {
this.resourcesFileUrl = fileFound.raw_url;
return app.data.storage
.getContentOrRaw(fileFound.content, fileFound.raw_url)
.then(content => {
resolve({ ...fileFound, content })
const fileWithContent = { ...fileFound, content };
this.setVolatileResource(fileWithContent);
resolve(fileWithContent)
});
}
});
})
}
// resource in local or at gist
this.initResourcesFile = () => {
return new Promise(resolve => {
this.getVloatileResource().then(volatile => {
const volatileData = {};
console.log('------------', {volatile, volatileData})

if(volatile && volatile.content) {
ToastWc.show({
type: 'success',
content: `LOADED resources.json file`,
time: 2000,
});
console.log({volatile})
resolve(volatile);
return
} else {
app.data.storage.getGistFiles(app.ui.openSettingsDialog).then(({ filesInGist }) => {
const fileFound = Object.values(filesInGist).find(
item => item.filename === 'resources.json'
);
if (!fileFound) {
app.data.storage.editGistFile('resources.json', '{}').then(({file})=>{
console.log({result})
ToastWc.show({
type: 'success',
content: `Created a resources.json file`,
time: 3000,
});
this.resourcesFileUrl = file.raw_url;
this.setVolatileResource(file);
resolve(file);
});
} else {
this.resourcesFileUrl = fileFound.raw_url;
return app.data.storage
.getContentOrRaw(fileFound.content, fileFound.raw_url)
.then(content => {
const fileWithContent = { ...fileFound, content };
this.setVolatileResource(fileWithContent);
resolve(fileWithContent)
});
}
});
}
})
});
};

this.onCommitResourceFiles = newContent => {
this.isBusy('Uploading changes to gist...');
app.data.storage.editGistFile('resources.json', newContent).then(response => {
app.data.storage.editGistFile('resources.json', newContent).then(() => {
ToastWc.show({
type: 'info',
content: 'Saved resources on gist',
time: 1000,
});
this.isBusy('Updating list...');
this.updateResourcesList(newContent);
document.querySelector('resources-component').setIsNew(false)
this.isBusy('')
});
};
this.updateResourcesList = fileContents => {
const resourcesData = JSON.parse(fileContents);
const objectKeys = Object.keys(JSON.parse(fileContents));
// const showThumbnails = true;//objectKeys.length < 600;
//todo use a for loop here
const options = objectKeys.map(fileKey => {
const fileData = resourcesData[fileKey];
const isCommitted = 'committed' in fileData; //add this field when saving
return `<option value="${
fileData.src
}" id="${fileKey}" title="${fileKey}" style="${!isCommitted &&
'border-left:3px solid'}content-visibility:auto;background-size: 25px;background-repeat: no-repeat;background-position-x: right;background-clip: padding-box;">
${fileKey}
</option>`;
});
document.getElementById(
'resource-list-label'
).innerHTML = `${objectKeys.length} files`;
document.getElementById('resources-editor-select').innerHTML = options.join(
''
);
this.onSelectScroll({
target: document.getElementById('resources-editor-select'),
});
this.isBusy('');
};
this.onOpenResourcesEditor = async () => {
const domPath = `app.plugins.${self.name}`;
const { value: formValues } = await Swal.fire({
Expand Down Expand Up @@ -110,18 +146,30 @@ export var ResourcesEditor = function({
document.querySelector('resources-component').addEventListener('isBusy', event => {
this.isBusy(event.detail.message)
});
document.querySelector('resources-component').addEventListener('commitNewContent', event => {
document.querySelector('resources-component').addEventListener('commitNewContent', event => {//raw
const newContent = event.detail;
app.data.storage.editGistFile('resources.json', newContent).then(response => {
ToastWc.show({
type: 'info',
content: 'Saved resources on gist',
time: 1000,
});
this.isBusy('Updating list...');
document.querySelector('resources-component').updateResourcesList(newContent);
this.setVolatileResource({
filename:'resources.json',
content: newContent, // todo not having raw_url can be used to detect if new file
});
});
document.querySelector('resources-component').addEventListener('headerButtonClicked', ({detail: action}) => {
if(action === 'pull') {
this.isBusy('Downloading changes to gist...');
this.getFromGist().then(resolve => {
document.querySelector('resources-component').updateResourcesList(resolve.content);
ToastWc.show({
type: 'success',
content: `Re-Downloaded resources.json file`,
time: 3000,
});
this.isBusy('');
})
}
if(action === 'push'){
this.getVloatileResource().then(result=> this.onCommitResourceFiles(result.content))
}
});
this.initResourcesFile().then((file) => {
ToastWc.show({
type: 'success',
Expand All @@ -130,7 +178,12 @@ export var ResourcesEditor = function({
onClick: ()=> window.open(file.raw_url, "_blank")
});
updateUrlParams('selectedResource', 'none');
document.querySelector('resources-component').init({file, darkMode: app.settings.theme() === 'dracula'})
document.querySelector('resources-component').init({
file,
gistId: this.gistId ,
darkMode: app.settings.theme() === 'dracula',
headerButtons: [{title: 'Load from gist', action: 'pull'}, {title: 'Save to gist', action: 'push'}]
})
});
},
preConfirm: () => {
Expand Down
2 changes: 1 addition & 1 deletion public/version.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"version": "0.4.346"
"version": "0.4.347"
}
54 changes: 33 additions & 21 deletions public/web-components.js
Original file line number Diff line number Diff line change
Expand Up @@ -241,11 +241,13 @@ class ResourcesComponent extends HTMLElement {
}
</style>
<div id="resources-editor" style="display:flex;flex-direction:column;width: 100%;height:100%; overflow: hidden;">
<div class="flex-wrap" style="gap: 10px;">
<div class="flex-wrap" style="gap: 10px;padding-bottom:2px;">
<slot name="header-area"></slot>
<a id="resourcesFileLink" href="${this.resourcesFileUrl}" target="_blank" rel="noopener noreferrer">resources.json</a>
<label for="resources-editor-select" id="resource-list-label">...</label>
from <a href="${this.gistId}" target="_blank" rel="noopener noreferrer">Gist</a>
from <a href="${this.gistId}" id="gistIdFileLink" target="_blank" rel="noopener noreferrer">Gist</a>
<div id="header-buttons" class="flex-wrap" style="flex:1;gap: 10px;"></div>
<div id="isNewFile"></div>
</div>
Expand Down Expand Up @@ -292,10 +294,10 @@ class ResourcesComponent extends HTMLElement {
this.resourcesFileContent = '';
this.gistId = '';
this.onSelectResource = evt => {
const selectedItem = evt.target.value;
this.selectedResources = Object.values(evt.target.selectedOptions).map(
item => item.id
(item, index) => ({id:item.id, index, src: item.dataset.src})
);
const selectedItem = this.selectedResources[this.selectedResources.length - 1].src;
if (selectedItem.startsWith('data:image')) {
shadowRoot.getElementById('selected-resource-preview').innerHTML = `
<img src="${selectedItem}" style="pointer-events:none;max-width:60vw;object-fit: contain; border: 0;"></img>
Expand All @@ -305,13 +307,15 @@ class ResourcesComponent extends HTMLElement {
}
};
this.onRemoveResource = () => {
this.isBusy('Removing files...');
const fileData = JSON.parse(this.resourcesFileContent);
this.selectedResources.forEach(selectedResource => {
if (selectedResource in fileData) delete fileData[selectedResource];
if (selectedResource.id in fileData) delete fileData[selectedResource.id];
});

const newContent = JSON.stringify(fileData, null, 2);
this.onCommitResourceFiles(newContent);
this.isBusy('');
};
const toBase64 = file => {
return new Promise((resolve, reject) => {
Expand All @@ -327,13 +331,15 @@ class ResourcesComponent extends HTMLElement {
newResFiles.forEach(file => {
filePathsPromises.push(toBase64(file));
});
this.isBusy('Updating file list with files...');
Promise.all(filePathsPromises).then(filePaths => {
const fileData = JSON.parse(this.resourcesFileContent);
filePaths.forEach(file => {
fileData[file.name] = { src: file.src, added: new Date() };
});
this.isBusy('');
const newContent = JSON.stringify(fileData, null, 2);
this.onCommitResourceFiles(newContent);
this.onCommitResourceFiles(newContent);
});
};
this.onSelectScroll = () => {
Expand All @@ -346,41 +352,38 @@ class ResourcesComponent extends HTMLElement {
const item = target[i];
const itemPos = item.offsetTop;
if (itemPos > startPos && itemPos < endPos) {
item.style['background-image'] = `url(${item.value})`;
item.style['background-image'] = `url(${item.dataset.src})`;
} else {
item.style['background-image'] = '';
}
}
};
this.onCommitResourceFiles = newContent => {
this.isBusy('Uploading changes to gist...');
this.resourcesFileContent = newContent;
this.notifyParent('commitNewContent', newContent)
this.updateResourcesList(newContent, true);
};
this.updateResourcesList = fileContents => {
this.updateResourcesList = (fileContents, isNew = false) => {
const resourcesData = JSON.parse(fileContents);
const objectKeys = Object.keys(JSON.parse(fileContents));
const options = objectKeys.map(fileKey => {
const fileData = resourcesData[fileKey];
const isCommitted = 'committed' in fileData; //add this field when saving
return `<option value="${
fileData.src
}" id="${fileKey}" title="${fileKey}" style="${!isCommitted &&
return `<option value="${fileKey}" id="${fileKey}" data-src="${fileData.src}" title="${fileKey}" style="${!isCommitted &&
'border-left:3px solid'}content-visibility:auto;background-size: 25px;background-repeat: no-repeat;background-position-x: right;background-clip: padding-box;">
${fileKey}
</option>`;
});
shadowRoot.getElementById(
'resource-list-label'
).innerHTML = `${objectKeys.length} files`;
shadowRoot.getElementById('resources-editor-select').innerHTML = options.join(
''
);
shadowRoot.getElementById('resource-list-label').innerHTML = `${objectKeys.length} files`;
shadowRoot.getElementById('resources-editor-select').innerHTML = options.join('');
this.onSelectScroll({
target: shadowRoot.getElementById('resources-editor-select'),
});
console.log(" DOONE ")
this.isBusy(false);
this.setIsNew(isNew);
// shadowRoot.getElementById('resources-editor-select').value = this.selectedResources[0];
};
this.setIsNew = isNew => shadowRoot.getElementById('isNewFile').innerText = isNew ? '*' : '';
////methods end
shadowRoot
.getElementById('file-input-res')
Expand All @@ -399,12 +402,21 @@ class ResourcesComponent extends HTMLElement {
.getElementById('onRemoveButton')
.addEventListener('click', this.onRemoveResource);
}
init({ file, darkMode }) {//todo you cannot pass functions to web components, but can use events?
init({ file, darkMode, headerButtons, gistId }) {//todo you cannot pass functions to web components, but can use events?
this.resourcesFileContent = file.content || '{}';
const shadowRoot = document.querySelector('resources-component').shadowRoot;
shadowRoot.getElementById('resourcesFileLink').href = file.raw_url;
shadowRoot.getElementById('gistIdFileLink').href = gistId || '';
if (darkMode) shadowRoot.getElementById('resources-editor').setAttribute("data-theme", "dark");
this.updateResourcesList(this.resourcesFileContent);
this.updateResourcesList(this.resourcesFileContent, !file.raw_url);
if(headerButtons) {
headerButtons.forEach(button => {
const el = document.createElement('button', {id: button.action});
el.innerText = button.title;
el.addEventListener('click', () => this.notifyParent('headerButtonClicked', button.action));
shadowRoot.getElementById('header-buttons').appendChild(el);
})
};
}
notifyParent(eventKey, detail) {
this.dispatchEvent(new CustomEvent(eventKey, { detail, composed: true }));
Expand Down
2 changes: 1 addition & 1 deletion sw.js

Large diffs are not rendered by default.

0 comments on commit b9a01ca

Please sign in to comment.