File size: 7,027 Bytes
2b0bc5f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
// ECMAScript 2020+
// Разбор расширений и подготовка для табов
class TabsExtensionParser {
/** Клонируем label с чекбоксом и возвращаем именно label (или null)
* @param {boolean} enabled
* @returns {HTMLLabelElement|null}
*/
static #cloneCheckbox(enabled) {
const base = document.getElementById("TABSEX_CHECKBOX");
if (!base) return null;
const label = base.querySelector('label')?.cloneNode(true);
if (!label) return null;
label.style.margin = "1em 0em";
label.checkbox = label.querySelector("input");
if (label.checkbox) label.checkbox.checked = !!enabled;
return label;
}
/**
* Убираем версию из имени (если есть). Пустые строки -> null.
* @param {string} name
* @returns {string|null}
*/
static #sanitizeExtensionName(name) {
if (typeof name !== 'string' || name.trim().length === 0) return null;
const version_pattern = /([Vv](?:er)?[\.\s]*\d)/;
return name.split(version_pattern)[0].trim();
}
/**
* Разбор одного узла из контейнера расширений
* @param {HTMLDivElement} node
* @param {string[]} keep
* @returns {[string|null, HTMLDivElement|null]}
*/
static #parseObject(node, keep) {
if (!node) return [null, null];
// Спец-случай: форма со списком скриптов
if (node.classList.contains("form")) {
const scripts = node.querySelector(".gradio-dropdown");
if (!scripts) return [null, null];
const script_block = document.createElement("div");
script_block.style.display = 'none';
scripts.style.margin = '10px 0px';
script_block.appendChild(scripts);
script_block.setAttribute("ext-label", "Scripts");
// прячем исходный form-узел, чтобы не было дубля; решение о дубликате принимает parse()
node.style.display = "none";
return ["Scripts", script_block];
}
const styler = node.querySelector(".styler");
if (!styler) return [null, null];
const accordion = node.querySelector(".gradio-accordion");
if (!accordion) return [null, null];
const isInput = accordion.classList.contains("input-accordion");
const displayName = accordion.querySelector(".label-wrap>span")?.textContent;
if (!displayName) return [null, null];
const extensionName = this.#sanitizeExtensionName(displayName);
if (!extensionName || keep.includes(extensionName)) return [null, null];
const contents = [...accordion.children].filter(
(div) => !div.classList.contains("hide")
&& !div.classList.contains("label-wrap")
&& div.children.length > 0
);
if (contents.length === 0) return [null, null];
const content = contents[0];
if (isInput) {
const checkbox = accordion.querySelector(".input-accordion-checkbox");
const dummy = this.#cloneCheckbox(checkbox?.checked ?? false);
// Ставим обработчики только если всё есть
if (dummy && dummy.checkbox && checkbox) {
dummy.checkbox.onchange = () => {
if (checkbox.checked !== dummy.checkbox.checked) checkbox.click();
};
checkbox.onchange = () => {
if (checkbox.checked !== dummy.checkbox.checked) dummy.checkbox.click();
};
content.insertBefore(dummy, content.firstElementChild);
}
}
// Прячем исходный блок с аккордеоном
node.style.display = "none";
// Переносим якорь на новый content (и переименовываем старый id безопасно)
if (accordion.id && !accordion.id.startsWith("component-")) {
content.id = accordion.id;
accordion.id = `moved-${accordion.id}`;
if (isInput) {
// Предотвращаем ошибки в консоли в сетапе webui
content.visibleCheckbox = { checked: null };
content.onVisibleCheckboxChange = () => {};
}
}
content.setAttribute("ext-label", displayName);
return [extensionName, content];
}
/**
* Доп. блок "Extra Options"
* @param {'txt'|'img'} mode
* @returns {[string|null, HTMLDivElement|null]}
*/
static #extra_options(mode) {
const extra_options = document.getElementById(`extra_options_${mode}2img`);
if (!extra_options || !extra_options.classList.contains("gradio-accordion"))
return [null, null];
const styler = extra_options.parentElement;
if (styler) styler.style.display = "none";
const contents = [...extra_options.children].filter(
(div) => !div.classList.contains("hide")
&& !div.classList.contains("label-wrap")
&& div.children.length > 0
);
if (contents.length === 0) return [null, null];
const content = contents[0];
content.setAttribute("ext-label", "Extra Options");
return ["Extra Options", content];
}
/**
* Разбор всех расширений
* @param {'txt'|'img'} mode
* @param {string[]} keep
* @returns {Object.<string, HTMLDivElement>}
*/
static parse(mode, keep) {
const validExtensions = {};
const container = document.getElementById(`${mode}2img_script_container`);
const styler = container?.querySelector(".styler");
if (!container || !styler) return validExtensions;
const children = Array.from(styler.children);
let foundScripts = false; // флаг "Scripts уже встретился" в ЭТОМ контейнере
// Важно: НИЧЕГО больше не «скидываем» в Scripts — разбираем каждый узел отдельно.
for (const node of children) {
// не допускаем второй Scripts в пределах текущего контейнера
if (foundScripts && node.classList.contains("form")) {
node.style.display = "none";
continue;
}
const [name, content] = this.#parseObject(node, keep);
if (name && content) validExtensions[name] = content;
if (name === "Scripts") foundScripts = true;
}
const [extra, options] = this.#extra_options(mode);
if (extra && options) validExtensions[extra] = options;
return validExtensions;
}
}
|