Apply new code format standard (#217)

This commit is contained in:
Chenlei Hu
2024-07-25 10:10:18 -04:00
committed by GitHub
parent 19c70d95d3
commit e179f75387
121 changed files with 11898 additions and 11983 deletions

View File

@@ -1,8 +1,8 @@
import { $el, ComfyDialog } from "./ui";
import { api } from "./api";
import type { ComfyApp } from "./app";
import { $el, ComfyDialog } from './ui'
import { api } from './api'
import type { ComfyApp } from './app'
$el("style", {
$el('style', {
textContent: `
.comfy-logging-logs {
display: grid;
@@ -23,17 +23,17 @@ $el("style", {
padding: 5px;
}
`,
parent: document.body,
});
parent: document.body
})
// Stringify function supporting max depth and removal of circular references
// https://stackoverflow.com/a/57193345
function stringify(val, depth, replacer, space, onGetObjID?) {
depth = isNaN(+depth) ? 1 : depth;
var recursMap = new WeakMap();
depth = isNaN(+depth) ? 1 : depth
var recursMap = new WeakMap()
function _build(val, depth, o?, a?, r?) {
// (JSON.stringify() has it's own rules, which we respect here by using it for property iteration)
return !val || typeof val != "object"
return !val || typeof val != 'object'
? val
: ((r = recursMap.has(val)),
recursMap.set(val, true),
@@ -42,201 +42,201 @@ function stringify(val, depth, replacer, space, onGetObjID?) {
? (o = (onGetObjID && onGetObjID(val)) || null)
: JSON.stringify(val, function (k, v) {
if (a || depth > 0) {
if (replacer) v = replacer(k, v);
if (!k) return (a = Array.isArray(v)), (val = v);
!o && (o = a ? [] : {});
o[k] = _build(v, a ? depth : depth - 1);
if (replacer) v = replacer(k, v)
if (!k) return (a = Array.isArray(v)), (val = v)
!o && (o = a ? [] : {})
o[k] = _build(v, a ? depth : depth - 1)
}
}),
o === void 0 ? (a ? [] : {}) : o);
o === void 0 ? (a ? [] : {}) : o)
}
return JSON.stringify(_build(val, depth), null, space);
return JSON.stringify(_build(val, depth), null, space)
}
const jsonReplacer = (k, v, ui) => {
if (v instanceof Array && v.length === 1) {
v = v[0];
v = v[0]
}
if (v instanceof Date) {
v = v.toISOString();
v = v.toISOString()
if (ui) {
v = v.split("T")[1];
v = v.split('T')[1]
}
}
if (v instanceof Error) {
let err = "";
if (v.name) err += v.name + "\n";
if (v.message) err += v.message + "\n";
if (v.stack) err += v.stack + "\n";
let err = ''
if (v.name) err += v.name + '\n'
if (v.message) err += v.message + '\n'
if (v.stack) err += v.stack + '\n'
if (!err) {
err = v.toString();
err = v.toString()
}
v = err;
v = err
}
return v;
};
return v
}
const fileInput: HTMLInputElement = $el("input", {
type: "file",
accept: ".json",
style: { display: "none" },
parent: document.body,
}) as HTMLInputElement;
const fileInput: HTMLInputElement = $el('input', {
type: 'file',
accept: '.json',
style: { display: 'none' },
parent: document.body
}) as HTMLInputElement
class ComfyLoggingDialog extends ComfyDialog {
logging: any;
logging: any
constructor(logging) {
super();
this.logging = logging;
super()
this.logging = logging
}
clear() {
this.logging.clear();
this.show();
this.logging.clear()
this.show()
}
export() {
const blob = new Blob(
[stringify([...this.logging.entries], 20, jsonReplacer, "\t")],
[stringify([...this.logging.entries], 20, jsonReplacer, '\t')],
{
type: "application/json",
type: 'application/json'
}
);
const url = URL.createObjectURL(blob);
const a = $el("a", {
)
const url = URL.createObjectURL(blob)
const a = $el('a', {
href: url,
download: `comfyui-logs-${Date.now()}.json`,
style: { display: "none" },
parent: document.body,
});
a.click();
style: { display: 'none' },
parent: document.body
})
a.click()
setTimeout(function () {
a.remove();
window.URL.revokeObjectURL(url);
}, 0);
a.remove()
window.URL.revokeObjectURL(url)
}, 0)
}
import() {
fileInput.onchange = () => {
const reader = new FileReader();
const reader = new FileReader()
reader.onload = () => {
fileInput.remove();
fileInput.remove()
try {
const obj = JSON.parse(reader.result as string);
const obj = JSON.parse(reader.result as string)
if (obj instanceof Array) {
this.show(obj);
this.show(obj)
} else {
throw new Error("Invalid file selected.");
throw new Error('Invalid file selected.')
}
} catch (error) {
alert("Unable to load logs: " + error.message);
alert('Unable to load logs: ' + error.message)
}
};
reader.readAsText(fileInput.files[0]);
};
fileInput.click();
}
reader.readAsText(fileInput.files[0])
}
fileInput.click()
}
createButtons() {
return [
$el("button", {
type: "button",
textContent: "Clear",
onclick: () => this.clear(),
$el('button', {
type: 'button',
textContent: 'Clear',
onclick: () => this.clear()
}),
$el("button", {
type: "button",
textContent: "Export logs...",
onclick: () => this.export(),
$el('button', {
type: 'button',
textContent: 'Export logs...',
onclick: () => this.export()
}),
$el("button", {
type: "button",
textContent: "View exported logs...",
onclick: () => this.import(),
$el('button', {
type: 'button',
textContent: 'View exported logs...',
onclick: () => this.import()
}),
...super.createButtons(),
];
...super.createButtons()
]
}
getTypeColor(type) {
switch (type) {
case "error":
return "red";
case "warn":
return "orange";
case "debug":
return "dodgerblue";
case 'error':
return 'red'
case 'warn':
return 'orange'
case 'debug':
return 'dodgerblue'
}
}
show(entries?: any[]) {
if (!entries) entries = this.logging.entries;
this.element.style.width = "100%";
if (!entries) entries = this.logging.entries
this.element.style.width = '100%'
const cols = {
source: "Source",
type: "Type",
timestamp: "Timestamp",
message: "Message",
};
const keys = Object.keys(cols);
source: 'Source',
type: 'Type',
timestamp: 'Timestamp',
message: 'Message'
}
const keys = Object.keys(cols)
const headers = Object.values(cols).map((title) =>
$el("div.comfy-logging-title", {
textContent: title,
$el('div.comfy-logging-title', {
textContent: title
})
);
)
const rows = entries.map((entry, i) => {
return $el(
"div.comfy-logging-log",
'div.comfy-logging-log',
{
$: (el) =>
el.style.setProperty(
"--row-bg",
`var(--tr-${i % 2 ? "even" : "odd"}-bg-color)`
),
'--row-bg',
`var(--tr-${i % 2 ? 'even' : 'odd'}-bg-color)`
)
},
keys.map((key) => {
let v = entry[key];
let color;
if (key === "type") {
color = this.getTypeColor(v);
let v = entry[key]
let color
if (key === 'type') {
color = this.getTypeColor(v)
} else {
v = jsonReplacer(key, v, true);
v = jsonReplacer(key, v, true)
if (typeof v === "object") {
v = stringify(v, 5, jsonReplacer, " ");
if (typeof v === 'object') {
v = stringify(v, 5, jsonReplacer, ' ')
}
}
return $el("div", {
return $el('div', {
style: {
color,
color
},
textContent: v,
});
textContent: v
})
})
);
});
)
})
const grid = $el(
"div.comfy-logging-logs",
'div.comfy-logging-logs',
{
style: {
gridTemplateColumns: `repeat(${headers.length}, 1fr)`,
},
gridTemplateColumns: `repeat(${headers.length}, 1fr)`
}
},
[...headers, ...rows]
);
const els = [grid];
)
const els = [grid]
if (!this.logging.enabled) {
els.unshift(
$el("h3", {
style: { textAlign: "center" },
textContent: "Logging is disabled",
$el('h3', {
style: { textAlign: 'center' },
textContent: 'Logging is disabled'
})
);
)
}
super.show($el("div", els));
super.show($el('div', els))
}
}
@@ -244,118 +244,118 @@ export class ComfyLogging {
/**
* @type Array<{ source: string, type: string, timestamp: Date, message: any }>
*/
entries = [];
entries = []
#enabled;
#console = {};
#enabled
#console = {}
app: ComfyApp;
dialog: ComfyLoggingDialog;
app: ComfyApp
dialog: ComfyLoggingDialog
get enabled() {
return this.#enabled;
return this.#enabled
}
set enabled(value) {
if (value === this.#enabled) return;
if (value === this.#enabled) return
if (value) {
this.patchConsole();
this.patchConsole()
} else {
this.unpatchConsole();
this.unpatchConsole()
}
this.#enabled = value;
this.#enabled = value
}
constructor(app) {
this.app = app;
this.app = app
this.dialog = new ComfyLoggingDialog(this);
this.addSetting();
this.catchUnhandled();
this.addInitData();
this.dialog = new ComfyLoggingDialog(this)
this.addSetting()
this.catchUnhandled()
this.addInitData()
}
addSetting() {
const settingId: string = "Comfy.Logging.Enabled";
const htmlSettingId = settingId.replaceAll(".", "-");
const settingId: string = 'Comfy.Logging.Enabled'
const htmlSettingId = settingId.replaceAll('.', '-')
const setting = this.app.ui.settings.addSetting({
id: settingId,
name: settingId,
defaultValue: true,
onChange: (value) => {
this.enabled = value;
this.enabled = value
},
type: (name, setter, value) => {
return $el("tr", [
$el("td", [
$el("label", {
textContent: "Logging",
for: htmlSettingId,
}),
return $el('tr', [
$el('td', [
$el('label', {
textContent: 'Logging',
for: htmlSettingId
})
]),
$el("td", [
$el("input", {
$el('td', [
$el('input', {
id: htmlSettingId,
type: "checkbox",
type: 'checkbox',
checked: value,
onchange: (event) => {
setter(event.target.checked);
},
setter(event.target.checked)
}
}),
$el("button", {
textContent: "View Logs",
$el('button', {
textContent: 'View Logs',
onclick: () => {
this.app.ui.settings.element.close();
this.dialog.show();
this.app.ui.settings.element.close()
this.dialog.show()
},
style: {
fontSize: "14px",
display: "block",
marginTop: "5px",
},
}),
]),
]);
},
});
this.enabled = setting.value;
fontSize: '14px',
display: 'block',
marginTop: '5px'
}
})
])
])
}
})
this.enabled = setting.value
}
patchConsole() {
// Capture common console outputs
const self = this;
for (const type of ["log", "warn", "error", "debug"]) {
const orig = console[type];
this.#console[type] = orig;
const self = this
for (const type of ['log', 'warn', 'error', 'debug']) {
const orig = console[type]
this.#console[type] = orig
console[type] = function () {
orig.apply(console, arguments);
self.addEntry("console", type, ...arguments);
};
orig.apply(console, arguments)
self.addEntry('console', type, ...arguments)
}
}
}
unpatchConsole() {
// Restore original console functions
for (const type of Object.keys(this.#console)) {
console[type] = this.#console[type];
console[type] = this.#console[type]
}
this.#console = {};
this.#console = {}
}
catchUnhandled() {
// Capture uncaught errors
window.addEventListener("error", (e) => {
this.addEntry("window", "error", e.error ?? "Unknown error");
return false;
});
window.addEventListener('error', (e) => {
this.addEntry('window', 'error', e.error ?? 'Unknown error')
return false
})
window.addEventListener("unhandledrejection", (e) => {
this.addEntry("unhandledrejection", "error", e.reason ?? "Unknown error");
});
window.addEventListener('unhandledrejection', (e) => {
this.addEntry('unhandledrejection', 'error', e.reason ?? 'Unknown error')
})
}
clear() {
this.entries = [];
this.entries = []
}
addEntry(source, type, ...args) {
@@ -364,20 +364,20 @@ export class ComfyLogging {
source,
type,
timestamp: new Date(),
message: args,
});
message: args
})
}
}
log(source, ...args) {
this.addEntry(source, "log", ...args);
this.addEntry(source, 'log', ...args)
}
async addInitData() {
if (!this.enabled) return;
const source = "ComfyUI.Logging";
this.addEntry(source, "debug", { UserAgent: navigator.userAgent });
const systemStats = await api.getSystemStats();
this.addEntry(source, "debug", systemStats);
if (!this.enabled) return
const source = 'ComfyUI.Logging'
this.addEntry(source, 'debug', { UserAgent: navigator.userAgent })
const systemStats = await api.getSystemStats()
this.addEntry(source, 'debug', systemStats)
}
}