mirror of
https://github.com/willmiao/ComfyUI-Lora-Manager.git
synced 2026-09-21 03:01:27 -03:00
Compare commits
5 Commits
1fd7cc0123
...
34ca14d7fc
| Author | SHA1 | Date | |
|---|---|---|---|
| 34ca14d7fc | |||
| f7b247f9e8 | |||
| 3005d2877e | |||
| ed2a17970f | |||
| 9584fa85c9 |
@@ -868,6 +868,21 @@
|
||||
"previousWithShortcut": "Vorheriges Rezept (←)",
|
||||
"nextWithShortcut": "Nächstes Rezept (→)"
|
||||
},
|
||||
"modal": {
|
||||
"metadata": {
|
||||
"id": "ID"
|
||||
},
|
||||
"actions": {
|
||||
"openFileLocation": "Dateispeicherort öffnen",
|
||||
"copyId": "Rezept-ID kopieren"
|
||||
},
|
||||
"openFileLocation": {
|
||||
"success": "Dateispeicherort erfolgreich geöffnet",
|
||||
"failed": "Fehler beim Öffnen des Dateispeicherorts",
|
||||
"copied": "Pfad in die Zwischenablage kopiert: {{path}}",
|
||||
"clipboardFallback": "Pfad: {{path}}"
|
||||
}
|
||||
},
|
||||
"workflow": {
|
||||
"sendWorkflow": "Workflow an ComfyUI senden",
|
||||
"sent": "Workflow an ComfyUI gesendet",
|
||||
|
||||
@@ -868,6 +868,21 @@
|
||||
"previousWithShortcut": "Previous recipe (←)",
|
||||
"nextWithShortcut": "Next recipe (→)"
|
||||
},
|
||||
"modal": {
|
||||
"metadata": {
|
||||
"id": "ID"
|
||||
},
|
||||
"actions": {
|
||||
"openFileLocation": "Open File Location",
|
||||
"copyId": "Copy recipe ID"
|
||||
},
|
||||
"openFileLocation": {
|
||||
"success": "File location opened successfully",
|
||||
"failed": "Failed to open file location",
|
||||
"copied": "Path copied to clipboard: {{path}}",
|
||||
"clipboardFallback": "Path: {{path}}"
|
||||
}
|
||||
},
|
||||
"workflow": {
|
||||
"sendWorkflow": "Send Workflow to ComfyUI",
|
||||
"sent": "Workflow sent to ComfyUI",
|
||||
|
||||
@@ -868,6 +868,21 @@
|
||||
"previousWithShortcut": "Receta anterior (←)",
|
||||
"nextWithShortcut": "Siguiente receta (→)"
|
||||
},
|
||||
"modal": {
|
||||
"metadata": {
|
||||
"id": "ID"
|
||||
},
|
||||
"actions": {
|
||||
"openFileLocation": "Abrir ubicación del archivo",
|
||||
"copyId": "Copiar ID de la receta"
|
||||
},
|
||||
"openFileLocation": {
|
||||
"success": "Ubicación del archivo abierta exitosamente",
|
||||
"failed": "Error al abrir la ubicación del archivo",
|
||||
"copied": "Ruta copiada al portapapeles: {{path}}",
|
||||
"clipboardFallback": "Ruta: {{path}}"
|
||||
}
|
||||
},
|
||||
"workflow": {
|
||||
"sendWorkflow": "Enviar workflow a ComfyUI",
|
||||
"sent": "Workflow enviado a ComfyUI",
|
||||
|
||||
@@ -868,6 +868,21 @@
|
||||
"previousWithShortcut": "Recette précédente (←)",
|
||||
"nextWithShortcut": "Recette suivante (→)"
|
||||
},
|
||||
"modal": {
|
||||
"metadata": {
|
||||
"id": "ID"
|
||||
},
|
||||
"actions": {
|
||||
"openFileLocation": "Ouvrir l’emplacement du fichier",
|
||||
"copyId": "Copier l’ID de la Recipe"
|
||||
},
|
||||
"openFileLocation": {
|
||||
"success": "Emplacement du fichier ouvert avec succès",
|
||||
"failed": "Échec de l’ouverture de l’emplacement du fichier",
|
||||
"copied": "Chemin copié dans le presse-papiers: {{path}}",
|
||||
"clipboardFallback": "Chemin: {{path}}"
|
||||
}
|
||||
},
|
||||
"workflow": {
|
||||
"sendWorkflow": "Envoyer le workflow vers ComfyUI",
|
||||
"sent": "Workflow envoyé vers ComfyUI",
|
||||
|
||||
@@ -868,6 +868,21 @@
|
||||
"previousWithShortcut": "המתכון הקודם (←)",
|
||||
"nextWithShortcut": "המתכון הבא (→)"
|
||||
},
|
||||
"modal": {
|
||||
"metadata": {
|
||||
"id": "ID"
|
||||
},
|
||||
"actions": {
|
||||
"openFileLocation": "פתח מיקום קובץ",
|
||||
"copyId": "העתק מזהה מתכון"
|
||||
},
|
||||
"openFileLocation": {
|
||||
"success": "מיקום הקובץ נפתח בהצלחה",
|
||||
"failed": "פתיחת מיקום הקובץ נכשלה",
|
||||
"copied": "הנתיב הועתק ללוח העריכה: {{path}}",
|
||||
"clipboardFallback": "נתיב: {{path}}"
|
||||
}
|
||||
},
|
||||
"workflow": {
|
||||
"sendWorkflow": "שלח workflow ל-ComfyUI",
|
||||
"sent": "ה-workflow נשלח ל-ComfyUI",
|
||||
|
||||
@@ -868,6 +868,21 @@
|
||||
"previousWithShortcut": "前のレシピ(←)",
|
||||
"nextWithShortcut": "次のレシピ(→)"
|
||||
},
|
||||
"modal": {
|
||||
"metadata": {
|
||||
"id": "ID"
|
||||
},
|
||||
"actions": {
|
||||
"openFileLocation": "ファイルの場所を開く",
|
||||
"copyId": "レシピIDをコピー"
|
||||
},
|
||||
"openFileLocation": {
|
||||
"success": "ファイルの場所を正常に開きました",
|
||||
"failed": "ファイルの場所を開くのに失敗しました",
|
||||
"copied": "パスをクリップボードにコピーしました: {{path}}",
|
||||
"clipboardFallback": "パス: {{path}}"
|
||||
}
|
||||
},
|
||||
"workflow": {
|
||||
"sendWorkflow": "ワークフローをComfyUIへ送信",
|
||||
"sent": "ワークフローをComfyUIへ送信しました",
|
||||
|
||||
@@ -868,6 +868,21 @@
|
||||
"previousWithShortcut": "이전 레시피(←)",
|
||||
"nextWithShortcut": "다음 레시피(→)"
|
||||
},
|
||||
"modal": {
|
||||
"metadata": {
|
||||
"id": "ID"
|
||||
},
|
||||
"actions": {
|
||||
"openFileLocation": "파일 위치 열기",
|
||||
"copyId": "레시피 ID 복사"
|
||||
},
|
||||
"openFileLocation": {
|
||||
"success": "파일 위치가 성공적으로 열렸습니다",
|
||||
"failed": "파일 위치 열기에 실패했습니다",
|
||||
"copied": "경로가 클립보드에 복사되었습니다: {{path}}",
|
||||
"clipboardFallback": "경로: {{path}}"
|
||||
}
|
||||
},
|
||||
"workflow": {
|
||||
"sendWorkflow": "워크플로를 ComfyUI로 보내기",
|
||||
"sent": "워크플로를 ComfyUI로 보냈습니다",
|
||||
|
||||
@@ -868,6 +868,21 @@
|
||||
"previousWithShortcut": "Предыдущий рецепт (←)",
|
||||
"nextWithShortcut": "Следующий рецепт (→)"
|
||||
},
|
||||
"modal": {
|
||||
"metadata": {
|
||||
"id": "ID"
|
||||
},
|
||||
"actions": {
|
||||
"openFileLocation": "Открыть расположение файла",
|
||||
"copyId": "Копировать ID рецепта"
|
||||
},
|
||||
"openFileLocation": {
|
||||
"success": "Расположение файла успешно открыто",
|
||||
"failed": "Не удалось открыть расположение файла",
|
||||
"copied": "Путь скопирован в буфер обмена: {{path}}",
|
||||
"clipboardFallback": "Путь: {{path}}"
|
||||
}
|
||||
},
|
||||
"workflow": {
|
||||
"sendWorkflow": "Отправить workflow в ComfyUI",
|
||||
"sent": "Workflow отправлен в ComfyUI",
|
||||
|
||||
@@ -868,6 +868,21 @@
|
||||
"previousWithShortcut": "上一个配方(←)",
|
||||
"nextWithShortcut": "下一个配方(→)"
|
||||
},
|
||||
"modal": {
|
||||
"metadata": {
|
||||
"id": "ID"
|
||||
},
|
||||
"actions": {
|
||||
"openFileLocation": "打开文件位置",
|
||||
"copyId": "复制配方 ID"
|
||||
},
|
||||
"openFileLocation": {
|
||||
"success": "文件位置已成功打开",
|
||||
"failed": "打开文件位置失败",
|
||||
"copied": "路径已复制到剪贴板:{{path}}",
|
||||
"clipboardFallback": "路径:{{path}}"
|
||||
}
|
||||
},
|
||||
"workflow": {
|
||||
"sendWorkflow": "发送工作流到 ComfyUI",
|
||||
"sent": "工作流已发送到 ComfyUI",
|
||||
|
||||
@@ -868,6 +868,21 @@
|
||||
"previousWithShortcut": "上一個配方(←)",
|
||||
"nextWithShortcut": "下一個配方(→)"
|
||||
},
|
||||
"modal": {
|
||||
"metadata": {
|
||||
"id": "ID"
|
||||
},
|
||||
"actions": {
|
||||
"openFileLocation": "開啟檔案位置",
|
||||
"copyId": "複製配方 ID"
|
||||
},
|
||||
"openFileLocation": {
|
||||
"success": "檔案位置已成功開啟",
|
||||
"failed": "開啟檔案位置失敗",
|
||||
"copied": "路徑已複製到剪貼簿:{{path}}",
|
||||
"clipboardFallback": "路徑:{{path}}"
|
||||
}
|
||||
},
|
||||
"workflow": {
|
||||
"sendWorkflow": "傳送工作流到 ComfyUI",
|
||||
"sent": "工作流已傳送到 ComfyUI",
|
||||
|
||||
@@ -353,6 +353,17 @@ class RecipeListingHandler:
|
||||
|
||||
if not recipe:
|
||||
return web.json_response({"error": "Recipe not found"}, status=404)
|
||||
|
||||
# Expose the on-disk recipe JSON path so the modal can offer
|
||||
# "open file location" without guessing the storage layout.
|
||||
recipe = dict(recipe)
|
||||
try:
|
||||
json_path = await recipe_scanner.get_recipe_json_path(recipe_id)
|
||||
except Exception: # pragma: no cover - details must still load
|
||||
json_path = None
|
||||
if json_path:
|
||||
recipe["recipe_json_path"] = json_path
|
||||
|
||||
return web.json_response(recipe)
|
||||
except Exception as exc:
|
||||
self._logger.error(
|
||||
|
||||
@@ -1547,3 +1547,93 @@
|
||||
width: 20px;
|
||||
height: calc(1em * 1.3);
|
||||
}
|
||||
|
||||
/* Meta footer: de-emphasized location + recipe ID line below the modal body,
|
||||
mirroring the hash footnote in the shared model modal. Location sits left
|
||||
(tail of the path survives truncation), ID + copy button sit right. */
|
||||
.recipe-meta-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding-top: 6px;
|
||||
margin-top: 8px;
|
||||
border-top: 1px solid var(--border-color);
|
||||
font-size: 0.75em;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.recipe-meta-footer[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.recipe-meta-location {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.recipe-meta-location i {
|
||||
flex-shrink: 0;
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.recipe-meta-location-path {
|
||||
font-family: var(--font-mono, monospace);
|
||||
opacity: 0.7;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.recipe-meta-location:hover .recipe-meta-location-path,
|
||||
.recipe-meta-location:focus-visible .recipe-meta-location-path {
|
||||
opacity: 1;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.recipe-meta-location:focus-visible {
|
||||
outline: 1px solid var(--lora-accent);
|
||||
outline-offset: 2px;
|
||||
border-radius: var(--border-radius-xs);
|
||||
}
|
||||
|
||||
.recipe-meta-id {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.recipe-meta-id-label {
|
||||
font-size: 0.9em;
|
||||
opacity: 0.5;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.03em;
|
||||
}
|
||||
|
||||
.recipe-meta-id-value {
|
||||
font-family: var(--font-mono, monospace);
|
||||
opacity: 0.7;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.recipe-meta-copy-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0 2px;
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--text-muted);
|
||||
opacity: 0.35;
|
||||
font-size: 0.95em;
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.recipe-meta-copy-btn:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import { downloadManager } from '../managers/DownloadManager.js';
|
||||
import { MODEL_TYPES } from '../api/apiConfig.js';
|
||||
import { openMediaViewer } from './shared/MediaViewer.js';
|
||||
import { showRecipeDeleteConfirmation } from './RecipeCard.js';
|
||||
import { renderCompactTags, setupTagTooltip } from './shared/utils.js';
|
||||
import { renderCompactTags, setupTagTooltip, escapeAttribute } from './shared/utils.js';
|
||||
import { setupTagEditMode } from './shared/ModelTags.js';
|
||||
import { Combobox } from './Combobox.js';
|
||||
|
||||
@@ -66,6 +66,39 @@ function escapeHtml(value) {
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
/**
|
||||
* Call backend to open the recipe's file location and select the file.
|
||||
* Mirrors the model modal's openFileLocation, including the Docker
|
||||
* clipboard fallback.
|
||||
* @param {string} filePath
|
||||
*/
|
||||
async function openRecipeFileLocation(filePath) {
|
||||
try {
|
||||
const resp = await fetch('/api/lm/open-file-location', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ 'file_path': filePath })
|
||||
});
|
||||
if (!resp.ok) throw new Error('Failed to open file location');
|
||||
|
||||
const data = await resp.json();
|
||||
|
||||
if (data.mode === 'clipboard' && data.path) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(data.path);
|
||||
showToast('recipes.modal.openFileLocation.copied', { path: data.path }, 'success');
|
||||
} catch (clipboardErr) {
|
||||
console.warn('Clipboard API not available:', clipboardErr);
|
||||
showToast('recipes.modal.openFileLocation.clipboardFallback', { path: data.path }, 'info');
|
||||
}
|
||||
} else {
|
||||
showToast('recipes.modal.openFileLocation.success', {}, 'success');
|
||||
}
|
||||
} catch (err) {
|
||||
showToast('recipes.modal.openFileLocation.failed', {}, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback English strings for the collapsed "Why no LoRAs?" panel.
|
||||
// Translations live in locales/*.json under recipes.resources.
|
||||
const NO_LORAS_REASON_FALLBACKS = {
|
||||
@@ -421,6 +454,7 @@ class RecipeModal {
|
||||
this.syncGenerationParams(hydratedRecipe.gen_params);
|
||||
this.syncResourcesSection(hydratedRecipe);
|
||||
this.syncHeaderActions();
|
||||
this.syncMetaFooter();
|
||||
|
||||
// Show the modal
|
||||
modalManager.showModal('recipeModal', null, null, () => this.cleanupNavigationShortcuts());
|
||||
@@ -446,6 +480,79 @@ class RecipeModal {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the meta footer: clickable file location (opens the recipe JSON
|
||||
* in the OS file manager) plus the truncated recipe ID with copy button.
|
||||
* De-emphasized by design, mirroring the model modal's hash footnote.
|
||||
*/
|
||||
syncMetaFooter() {
|
||||
const footer = document.getElementById('recipeMetaFooter');
|
||||
if (!footer) {
|
||||
return;
|
||||
}
|
||||
|
||||
const recipeId = this.currentRecipe?.id || '';
|
||||
const filePath = this.currentRecipe?.file_path || '';
|
||||
const openTarget = this.currentRecipe?.recipe_json_path || filePath;
|
||||
const folderPath = filePath.replace(/[^/\\]+$/, '');
|
||||
|
||||
if (!recipeId && !folderPath) {
|
||||
footer.hidden = true;
|
||||
footer.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
|
||||
const truncatedId = recipeId.length > 14
|
||||
? `${recipeId.slice(0, 8)}…${recipeId.slice(-4)}`
|
||||
: recipeId;
|
||||
const openLocationLabel = translate('recipes.modal.actions.openFileLocation', {}, 'Open File Location');
|
||||
const copyIdLabel = translate('recipes.modal.actions.copyId', {}, 'Copy recipe ID');
|
||||
|
||||
const locationMarkup = folderPath ? `
|
||||
<span class="recipe-meta-location" role="button" tabindex="0"
|
||||
title="${escapeAttribute(folderPath)}"
|
||||
aria-label="${escapeAttribute(openLocationLabel)}"
|
||||
data-filepath="${escapeAttribute(openTarget)}">
|
||||
<i class="fas fa-folder-open" aria-hidden="true"></i>
|
||||
<span class="recipe-meta-location-path">${escapeHtml(folderPath)}</span>
|
||||
</span>` : '';
|
||||
|
||||
const idMarkup = recipeId ? `
|
||||
<span class="recipe-meta-id">
|
||||
<span class="recipe-meta-id-label">${translate('recipes.modal.metadata.id', {}, 'ID')}</span>
|
||||
<span class="recipe-meta-id-value" title="${escapeAttribute(recipeId)}">${escapeHtml(truncatedId)}</span>
|
||||
<button class="recipe-meta-copy-btn" title="${escapeAttribute(copyIdLabel)}" aria-label="${escapeAttribute(copyIdLabel)}">
|
||||
<i class="fas fa-copy" aria-hidden="true"></i>
|
||||
</button>
|
||||
</span>` : '';
|
||||
|
||||
footer.innerHTML = locationMarkup + idMarkup;
|
||||
footer.hidden = false;
|
||||
|
||||
const locationEl = footer.querySelector('.recipe-meta-location');
|
||||
if (locationEl) {
|
||||
const openLocation = () => {
|
||||
if (locationEl.dataset.filepath) {
|
||||
openRecipeFileLocation(locationEl.dataset.filepath);
|
||||
}
|
||||
};
|
||||
locationEl.addEventListener('click', openLocation);
|
||||
locationEl.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault();
|
||||
openLocation();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const copyBtn = footer.querySelector('.recipe-meta-copy-btn');
|
||||
if (copyBtn && recipeId) {
|
||||
copyBtn.addEventListener('click', () => {
|
||||
copyToClipboard(recipeId);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async hydrateRecipeDetails(recipeId, requestId, requestEditVersions = {}) {
|
||||
try {
|
||||
const fullRecipe = await fetchRecipeDetails(recipeId);
|
||||
@@ -471,6 +578,9 @@ class RecipeModal {
|
||||
if (fullRecipe.file_path !== undefined) {
|
||||
nextRecipe.file_path = fullRecipe.file_path;
|
||||
}
|
||||
if (fullRecipe.recipe_json_path !== undefined) {
|
||||
nextRecipe.recipe_json_path = fullRecipe.recipe_json_path;
|
||||
}
|
||||
if (fullRecipe.file_url !== undefined) {
|
||||
nextRecipe.file_url = fullRecipe.file_url;
|
||||
}
|
||||
@@ -568,6 +678,7 @@ class RecipeModal {
|
||||
this.updateSourceUrlDisplay(this.currentRecipe.source_path || '');
|
||||
}
|
||||
this.syncHeaderActions();
|
||||
this.syncMetaFooter();
|
||||
}
|
||||
|
||||
getPreviewMediaUrl(recipe = {}) {
|
||||
|
||||
@@ -76,6 +76,7 @@ export function generateImageWrapper(media, shouldBlur, nsfwText, metadataPanel,
|
||||
alt="Preview"
|
||||
width="${media.width}"
|
||||
height="${media.height}"
|
||||
fetchpriority="high"
|
||||
class="lazy ${shouldBlur ? 'blurred' : ''}">
|
||||
${shouldBlur ? `
|
||||
<div class="nsfw-overlay">
|
||||
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
} from './MediaUtils.js';
|
||||
import { generateMetadataPanel } from './MetadataPanel.js';
|
||||
import { generateImageWrapper, generateVideoWrapper } from './MediaRenderers.js';
|
||||
import { getShowcaseUrl, getThumbnailUrl } from '../../../utils/civitaiUtils.js';
|
||||
import { getShowcaseUrl, getDisplayUrl, getGalleryThumbnailUrl } from '../../../utils/civitaiUtils.js';
|
||||
import { openMediaViewer } from '../MediaViewer.js';
|
||||
import { escapeAttribute } from '../utils.js';
|
||||
|
||||
@@ -54,6 +54,13 @@ export async function loadExampleImages(images, modelHash, previewUrl = '') {
|
||||
const showcaseTab = document.getElementById('showcase-tab');
|
||||
if (!showcaseTab) return;
|
||||
|
||||
// Fresh load of a model's examples: reset the gallery position so a
|
||||
// previously viewed model's active index / expansion state never leaks
|
||||
// into this one (the modal is a singleton, state is module-level)
|
||||
galleryState.activeIndex = 0;
|
||||
galleryState.expanded = false;
|
||||
lastNavDirection = 1;
|
||||
|
||||
// First fetch local example files
|
||||
let localFiles = [];
|
||||
|
||||
@@ -275,7 +282,7 @@ function renderThumbnail(img, index, exampleFiles) {
|
||||
originalRemoteUrl.endsWith('.mp4') || originalRemoteUrl.endsWith('.webm');
|
||||
const mediaType = isVideo ? 'video' : 'image';
|
||||
|
||||
const thumbUrl = localFile ? localFile.path : getThumbnailUrl(originalRemoteUrl, mediaType);
|
||||
const thumbUrl = localFile ? localFile.path : getGalleryThumbnailUrl(originalRemoteUrl, mediaType);
|
||||
|
||||
const nsfwLevel = img.nsfwLevel !== undefined ? img.nsfwLevel : 0;
|
||||
const matureBlurThreshold = getMatureBlurThreshold(state.settings);
|
||||
@@ -284,9 +291,9 @@ function renderThumbnail(img, index, exampleFiles) {
|
||||
const activeClass = index === galleryState.activeIndex ? ' active' : '';
|
||||
const blurClass = shouldBlur ? ' blurred' : '';
|
||||
const mediaHtml = isVideo ?
|
||||
`<video class="thumb-media${blurClass}" src="${escapeAttribute(thumbUrl)}" muted playsinline preload="metadata"></video>
|
||||
`<video class="thumb-media${blurClass}" src="${escapeAttribute(thumbUrl)}" muted playsinline preload="none" data-lazy-video></video>
|
||||
<i class="fas fa-play thumb-video-badge"></i>` :
|
||||
`<img class="thumb-media${blurClass}" src="${escapeAttribute(thumbUrl)}" loading="lazy" alt="">`;
|
||||
`<img class="thumb-media${blurClass}" src="${escapeAttribute(thumbUrl)}" loading="lazy" fetchpriority="low" alt="">`;
|
||||
const nsfwBadge = shouldBlur ? '<i class="fas fa-eye-slash thumb-nsfw-badge"></i>' : '';
|
||||
|
||||
return `<button class="gallery-thumb${activeClass}" data-index="${index}">${mediaHtml}${nsfwBadge}</button>`;
|
||||
@@ -311,8 +318,9 @@ function renderMediaItem(img, index, exampleFiles) {
|
||||
originalRemoteUrl.endsWith('.mp4') || originalRemoteUrl.endsWith('.webm');
|
||||
const mediaType = isVideo ? 'video' : 'image';
|
||||
|
||||
// Optimize CivitAI URLs for showcase display (full quality)
|
||||
const remoteUrl = getShowcaseUrl(originalRemoteUrl, mediaType);
|
||||
// Optimize CivitAI URLs for in-modal display (images capped at width=2400;
|
||||
// the full-size media viewer uses getShowcaseUrl separately)
|
||||
const remoteUrl = getDisplayUrl(originalRemoteUrl, mediaType);
|
||||
|
||||
const localUrl = localFile ? localFile.path : '';
|
||||
|
||||
@@ -438,6 +446,48 @@ function findLocalFile(img, index, exampleFiles) {
|
||||
return localFile;
|
||||
}
|
||||
|
||||
// URLs already warmed in the HTTP cache, so repeat navigations and re-renders
|
||||
// never issue duplicate prefetch requests
|
||||
const prefetchedUrls = new Set();
|
||||
|
||||
// Direction of the last main-viewer navigation (+1 next / -1 prev); users
|
||||
// tend to keep clicking the same arrow, so prefetch reaches one further
|
||||
// ahead along it. Defaults to forward (Next is the most common navigation)
|
||||
let lastNavDirection = 1;
|
||||
|
||||
/**
|
||||
* Warm the HTTP cache for the examples most likely to be shown next: both
|
||||
* indices adjacent to the active one, plus one extra ahead along the last
|
||||
* navigation direction, so prev/next navigation feels instant. Images only:
|
||||
* video payloads are too heavy for speculative prefetch, and locally stored
|
||||
* examples need no network fetch at all.
|
||||
*/
|
||||
function prefetchAdjacentMedia() {
|
||||
const { images, exampleFiles, activeIndex, expanded } = galleryState;
|
||||
if (!expanded || images.length < 2) return;
|
||||
|
||||
[1, -1, lastNavDirection * 2].forEach(offset => {
|
||||
const index = ((activeIndex + offset) % images.length + images.length) % images.length;
|
||||
const img = images[index];
|
||||
if (!img?.url || findLocalFile(img, index, exampleFiles)) return;
|
||||
|
||||
const isVideo = img.url.endsWith('.mp4') || img.url.endsWith('.webm');
|
||||
if (isVideo) return;
|
||||
|
||||
// Must match the main viewer's URL (display mode) or the warmed
|
||||
// cache entry is never used
|
||||
const url = getDisplayUrl(img.url, 'image');
|
||||
if (prefetchedUrls.has(url)) return;
|
||||
prefetchedUrls.add(url);
|
||||
|
||||
// Off-DOM image: fills the HTTP/memory cache without affecting layout.
|
||||
// Low priority keeps it from competing with the active media's load.
|
||||
const preloader = new Image();
|
||||
preloader.fetchPriority = 'low';
|
||||
preloader.src = url;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch the main viewer to another example (wraps around)
|
||||
* @param {number} index - Target index in galleryState.images
|
||||
@@ -446,6 +496,11 @@ export function updateMainDisplay(index) {
|
||||
const count = galleryState.images.length;
|
||||
if (!count || !galleryState.expanded) return;
|
||||
|
||||
// Remember the navigation direction for direction-aware prefetching
|
||||
// (a raw index of -1 / count means wrap-around prev / next)
|
||||
const delta = index - galleryState.activeIndex;
|
||||
if (delta !== 0) lastNavDirection = delta > 0 ? 1 : -1;
|
||||
|
||||
galleryState.activeIndex = ((index % count) + count) % count;
|
||||
|
||||
const container = document.getElementById('mainMediaContainer');
|
||||
@@ -470,6 +525,7 @@ export function updateMainDisplay(index) {
|
||||
});
|
||||
|
||||
initMainMediaInteractions(container);
|
||||
prefetchAdjacentMedia();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -624,6 +680,40 @@ function setupScrollToExpand(gallery) {
|
||||
}, { passive: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Defer metadata fetches for video thumbnails until they scroll into view:
|
||||
* with preload="metadata" on every strip video, expanding the gallery would
|
||||
* otherwise hit the network for all of them at once
|
||||
* @param {HTMLElement} gallery - The .showcase-gallery element
|
||||
*/
|
||||
function initStripVideoLazyLoading(gallery) {
|
||||
const videos = gallery.querySelectorAll('.gallery-strip video[data-lazy-video]');
|
||||
if (!videos.length) return;
|
||||
|
||||
const enable = (video) => {
|
||||
video.preload = 'metadata';
|
||||
video.load();
|
||||
video.removeAttribute('data-lazy-video');
|
||||
};
|
||||
|
||||
if (typeof IntersectionObserver === 'undefined') {
|
||||
videos.forEach(enable);
|
||||
return;
|
||||
}
|
||||
|
||||
// No explicit root: intersection accounts for the strip's overflow
|
||||
// clipping, so off-screen thumbnails stay at preload="none"
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
entries.forEach(entry => {
|
||||
if (entry.isIntersecting) {
|
||||
enable(entry.target);
|
||||
observer.unobserve(entry.target);
|
||||
}
|
||||
});
|
||||
});
|
||||
videos.forEach(video => observer.observe(video));
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize all gallery interactions
|
||||
* @param {HTMLElement} gallery - The .showcase-gallery element
|
||||
@@ -683,6 +773,11 @@ export function initShowcaseContent(gallery) {
|
||||
const container = gallery.querySelector('.main-media-container');
|
||||
if (container && galleryState.expanded) {
|
||||
initMainMediaInteractions(container);
|
||||
// Gallery just (re)rendered expanded: warm the cache for the
|
||||
// examples adjacent to the active one
|
||||
prefetchAdjacentMedia();
|
||||
// Video thumbnails start at preload="none"; enable them on visibility
|
||||
initStripVideoLazyLoading(gallery);
|
||||
}
|
||||
|
||||
// Reposition controls on window resize
|
||||
|
||||
@@ -9,8 +9,13 @@
|
||||
export const OptimizationMode = {
|
||||
/** Full quality for showcase/display - uses /optimized=true only */
|
||||
SHOWCASE: 'showcase',
|
||||
/** In-modal display - caps image width at 2400 (covers the ~1200 CSS px
|
||||
* main viewer at DPR 2); videos stay full quality */
|
||||
DISPLAY: 'display',
|
||||
/** Thumbnail size for cards - uses /width=450,optimized=true */
|
||||
THUMBNAIL: 'thumbnail',
|
||||
/** Small thumbnails for the showcase gallery strip (72px display) - uses /width=160,optimized=true */
|
||||
GALLERY_THUMBNAIL: 'gallery-thumbnail',
|
||||
};
|
||||
|
||||
export const DEFAULT_CIVITAI_PAGE_HOST = 'civitai.com';
|
||||
@@ -95,15 +100,21 @@ export function rewriteCivitaiUrl(sourceUrl, mediaType = null, mode = Optimizati
|
||||
}
|
||||
|
||||
// Determine replacement based on mode and media type
|
||||
const isVideo = Boolean(mediaType && mediaType.toLowerCase() === 'video');
|
||||
let replacement;
|
||||
if (mode === OptimizationMode.SHOWCASE) {
|
||||
// Full quality for showcase - no width restriction
|
||||
replacement = '/optimized=true';
|
||||
} else if (mode === OptimizationMode.DISPLAY) {
|
||||
// Display mode caps image width for in-modal viewing; videos stay
|
||||
// full quality (CDN transcoding costs more than it saves here)
|
||||
replacement = isVideo ? '/optimized=true' : '/width=2400,optimized=true';
|
||||
} else {
|
||||
// Thumbnail mode with width restriction
|
||||
replacement = '/width=450,optimized=true';
|
||||
if (mediaType && mediaType.toLowerCase() === 'video') {
|
||||
replacement = '/transcode=true,width=450,optimized=true';
|
||||
// Thumbnail modes with width restriction
|
||||
const width = mode === OptimizationMode.GALLERY_THUMBNAIL ? 160 : 450;
|
||||
replacement = `/width=${width},optimized=true`;
|
||||
if (isVideo) {
|
||||
replacement = `/transcode=true,width=${width},optimized=true`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,6 +161,19 @@ export function getShowcaseUrl(url, type = 'image') {
|
||||
return getOptimizedUrl(url, type, OptimizationMode.SHOWCASE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get display-optimized URL for the in-modal main viewer (images capped at
|
||||
* width=2400; videos full quality). Use getShowcaseUrl for full-size viewing
|
||||
* (e.g. the media viewer overlay)
|
||||
*
|
||||
* @param {string} url - Original URL
|
||||
* @param {string} type - Media type ("image" or "video")
|
||||
* @returns {string} - Optimized URL for in-modal display
|
||||
*/
|
||||
export function getDisplayUrl(url, type = 'image') {
|
||||
return getOptimizedUrl(url, type, OptimizationMode.DISPLAY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get thumbnail-optimized URL (width=450)
|
||||
*
|
||||
@@ -161,6 +185,17 @@ export function getThumbnailUrl(url, type = 'image') {
|
||||
return getOptimizedUrl(url, type, OptimizationMode.THUMBNAIL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get gallery-strip-thumbnail-optimized URL (width=160, for the 72px strip)
|
||||
*
|
||||
* @param {string} url - Original URL
|
||||
* @param {string} type - Media type ("image" or "video")
|
||||
* @returns {string} - Optimized URL for gallery strip thumbnail display
|
||||
*/
|
||||
export function getGalleryThumbnailUrl(url, type = 'image') {
|
||||
return getOptimizedUrl(url, type, OptimizationMode.GALLERY_THUMBNAIL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a URL is from CivitAI
|
||||
*
|
||||
|
||||
@@ -144,5 +144,8 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Meta footer: file location + recipe ID, populated by RecipeModal.syncMetaFooter() -->
|
||||
<footer class="recipe-meta-footer" id="recipeMetaFooter" hidden></footer>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
import { describe, it, beforeEach, afterEach, expect, vi } from 'vitest';
|
||||
|
||||
const showToastMock = vi.fn();
|
||||
const copyToClipboardMock = vi.fn();
|
||||
const translateMock = vi.fn((key, params, fallback) => (typeof fallback === 'string' ? fallback : key));
|
||||
|
||||
const loadingManagerStub = {
|
||||
showSimpleLoading: vi.fn(),
|
||||
hide: vi.fn(),
|
||||
show: vi.fn(),
|
||||
restoreProgressBar: vi.fn(),
|
||||
};
|
||||
|
||||
const recipeItem = {
|
||||
id: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
|
||||
file_path: '/recipes/a1b2c3d4-e5f6-7890-abcd-ef1234567890.png',
|
||||
title: 'Demo Recipe',
|
||||
tags: [],
|
||||
loras: [],
|
||||
};
|
||||
|
||||
const virtualScrollerStub = {
|
||||
updateSingleItem: vi.fn(),
|
||||
getNavigationState: vi.fn(() => ({
|
||||
index: 0,
|
||||
hasPrev: false,
|
||||
hasNext: false,
|
||||
loadedItems: 1,
|
||||
totalItems: 1,
|
||||
})),
|
||||
getAdjacentItemByFilePath: vi.fn(async () => null),
|
||||
};
|
||||
|
||||
const stateStub = {
|
||||
global: { settings: {}, loadingManager: loadingManagerStub },
|
||||
loadingManager: loadingManagerStub,
|
||||
virtualScroller: virtualScrollerStub,
|
||||
};
|
||||
|
||||
const modalManagerMock = {
|
||||
showModal: vi.fn(),
|
||||
closeModal: vi.fn(),
|
||||
};
|
||||
|
||||
const fetchRecipeDetailsMock = vi.fn(async () => ({}));
|
||||
const updateRecipeMetadataMock = vi.fn(() => Promise.resolve({ success: true }));
|
||||
|
||||
vi.mock('../../../static/js/utils/uiHelpers.js', () => ({
|
||||
showToast: showToastMock,
|
||||
copyToClipboard: copyToClipboardMock,
|
||||
sendLoraToWorkflow: vi.fn(),
|
||||
sendModelPathToWorkflow: vi.fn(),
|
||||
openCivitaiByMetadata: vi.fn(),
|
||||
stripLoraTags: vi.fn((text) => text),
|
||||
sendPromptToWorkflow: vi.fn(),
|
||||
sendGenParamsToWorkflow: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/utils/i18nHelpers.js', () => ({
|
||||
translate: translateMock,
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/state/index.js', () => ({
|
||||
state: stateStub,
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/utils/storageHelpers.js', () => ({
|
||||
setSessionItem: vi.fn(),
|
||||
removeSessionItem: vi.fn(),
|
||||
getStorageItem: vi.fn(() => null),
|
||||
setStorageItem: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/api/recipeApi.js', () => ({
|
||||
fetchRecipeDetails: fetchRecipeDetailsMock,
|
||||
updateRecipeMetadata: updateRecipeMetadataMock,
|
||||
sendRecipeWorkflow: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/api/apiConfig.js', () => ({
|
||||
MODEL_TYPES: {
|
||||
LORA: 'loras',
|
||||
CHECKPOINT: 'checkpoints',
|
||||
EMBEDDING: 'embeddings',
|
||||
},
|
||||
}));
|
||||
|
||||
function recipeModalFixture() {
|
||||
return `
|
||||
<div id="recipeModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<header class="recipe-modal-header">
|
||||
<div class="recipe-modal-header-row">
|
||||
<h2 id="recipeModalTitle">Recipe Details</h2>
|
||||
<div class="modal-nav-controls">
|
||||
<button class="modal-nav-btn" id="recipeNavPrevBtn" disabled></button>
|
||||
<button class="modal-nav-btn" id="recipeNavNextBtn" disabled></button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="recipe-header-actions" id="recipeHeaderActions">
|
||||
<button class="modal-send-btn" id="sendRecipeBtn"><i class="fas fa-paper-plane"></i></button>
|
||||
<button class="modal-copy-btn" id="copyRecipeSyntaxBtn"><i class="fas fa-copy"></i></button>
|
||||
</div>
|
||||
<div id="recipeTagsContainer"></div>
|
||||
</header>
|
||||
<div class="modal-body">
|
||||
<div class="recipe-media-column">
|
||||
<div class="recipe-preview-container" id="recipePreviewContainer">
|
||||
<img id="recipeModalImage" src="" alt="Recipe Preview" class="recipe-preview-media">
|
||||
</div>
|
||||
</div>
|
||||
<div class="info-section recipe-gen-params">
|
||||
<div class="gen-params-container">
|
||||
<div class="param-group info-item">
|
||||
<div class="param-content" id="recipePrompt"></div>
|
||||
<div class="param-editor" id="recipePromptEditor">
|
||||
<textarea class="param-textarea" id="recipePromptInput"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<div class="param-group info-item">
|
||||
<div class="param-content" id="recipeNegativePrompt"></div>
|
||||
<div class="param-editor" id="recipeNegativePromptEditor">
|
||||
<textarea class="param-textarea" id="recipeNegativePromptInput"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<div class="other-params" id="recipeOtherParams"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="info-section recipe-bottom-section">
|
||||
<div class="recipe-section-actions">
|
||||
<span id="recipeLorasCount"></span>
|
||||
<button class="action-btn view-loras-btn" id="viewRecipeLorasBtn"></button>
|
||||
</div>
|
||||
<div class="recipe-loras-list" id="recipeLorasList"></div>
|
||||
</div>
|
||||
</div>
|
||||
<footer class="recipe-meta-footer" id="recipeMetaFooter" hidden></footer>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
async function flushAsyncTasks() {
|
||||
await Promise.resolve();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
const createdModals = [];
|
||||
|
||||
async function createRecipeModal() {
|
||||
const { RecipeModal } = await import('../../../static/js/components/RecipeModal.js');
|
||||
const recipeModal = new RecipeModal();
|
||||
createdModals.push(recipeModal);
|
||||
return recipeModal;
|
||||
}
|
||||
|
||||
function openLocationFetchCalls() {
|
||||
return global.fetch.mock.calls.filter(([url]) => url === '/api/lm/open-file-location');
|
||||
}
|
||||
|
||||
describe('RecipeModal meta footer', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
document.body.innerHTML = recipeModalFixture();
|
||||
global.modalManager = modalManagerMock;
|
||||
global.fetch = vi.fn(async () => ({
|
||||
ok: true,
|
||||
json: async () => ({}),
|
||||
}));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
createdModals.forEach(recipeModal => recipeModal.cleanupNavigationShortcuts());
|
||||
createdModals.length = 0;
|
||||
document.body.innerHTML = '';
|
||||
delete global.modalManager;
|
||||
delete global.fetch;
|
||||
});
|
||||
|
||||
it('shows the folder path and a middle-truncated recipe ID', async () => {
|
||||
const recipeModal = await createRecipeModal();
|
||||
recipeModal.showRecipeDetails(recipeItem);
|
||||
|
||||
const footer = document.getElementById('recipeMetaFooter');
|
||||
expect(footer.hidden).toBe(false);
|
||||
|
||||
const location = footer.querySelector('.recipe-meta-location');
|
||||
expect(location.querySelector('.recipe-meta-location-path').textContent).toBe('/recipes/');
|
||||
expect(location.dataset.filepath).toBe(recipeItem.file_path);
|
||||
|
||||
const idValue = footer.querySelector('.recipe-meta-id-value');
|
||||
expect(idValue.textContent).toBe('a1b2c3d4…7890');
|
||||
expect(idValue.getAttribute('title')).toBe(recipeItem.id);
|
||||
});
|
||||
|
||||
it('copies the full recipe ID when the copy button is clicked', async () => {
|
||||
const recipeModal = await createRecipeModal();
|
||||
recipeModal.showRecipeDetails(recipeItem);
|
||||
|
||||
document.querySelector('.recipe-meta-copy-btn').click();
|
||||
|
||||
expect(copyToClipboardMock).toHaveBeenCalledWith(recipeItem.id);
|
||||
});
|
||||
|
||||
it('opens the recipe file location when the path is clicked', async () => {
|
||||
const recipeModal = await createRecipeModal();
|
||||
recipeModal.showRecipeDetails(recipeItem);
|
||||
|
||||
document.querySelector('.recipe-meta-location').click();
|
||||
await flushAsyncTasks();
|
||||
|
||||
const calls = openLocationFetchCalls();
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(JSON.parse(calls[0][1].body)).toEqual({ file_path: recipeItem.file_path });
|
||||
expect(showToastMock).toHaveBeenCalledWith('recipes.modal.openFileLocation.success', {}, 'success');
|
||||
});
|
||||
|
||||
it('opens the recipe JSON path once hydration provides it', async () => {
|
||||
const jsonPath = '/recipes/a1b2c3d4-e5f6-7890-abcd-ef1234567890.recipe.json';
|
||||
fetchRecipeDetailsMock.mockResolvedValueOnce({
|
||||
id: recipeItem.id,
|
||||
file_path: recipeItem.file_path,
|
||||
recipe_json_path: jsonPath,
|
||||
});
|
||||
|
||||
const recipeModal = await createRecipeModal();
|
||||
recipeModal.showRecipeDetails(recipeItem);
|
||||
await flushAsyncTasks();
|
||||
|
||||
const location = document.querySelector('.recipe-meta-location');
|
||||
expect(location.dataset.filepath).toBe(jsonPath);
|
||||
});
|
||||
|
||||
it('copies the path to clipboard when the backend reports clipboard mode', async () => {
|
||||
const writeTextMock = vi.fn(async () => {});
|
||||
Object.defineProperty(window.navigator, 'clipboard', {
|
||||
value: { writeText: writeTextMock },
|
||||
configurable: true,
|
||||
});
|
||||
|
||||
global.fetch = vi.fn(async (url) => ({
|
||||
ok: true,
|
||||
json: async () => (url === '/api/lm/open-file-location'
|
||||
? { mode: 'clipboard', path: '/recipes' }
|
||||
: {}),
|
||||
}));
|
||||
|
||||
const recipeModal = await createRecipeModal();
|
||||
recipeModal.showRecipeDetails(recipeItem);
|
||||
|
||||
document.querySelector('.recipe-meta-location').click();
|
||||
await flushAsyncTasks();
|
||||
|
||||
expect(writeTextMock).toHaveBeenCalledWith('/recipes');
|
||||
expect(showToastMock).toHaveBeenCalledWith(
|
||||
'recipes.modal.openFileLocation.copied',
|
||||
{ path: '/recipes' },
|
||||
'success',
|
||||
);
|
||||
});
|
||||
|
||||
it('hides the footer when neither ID nor file path is available', async () => {
|
||||
const recipeModal = await createRecipeModal();
|
||||
recipeModal.showRecipeDetails({ title: 'Orphan', tags: [], loras: [] });
|
||||
|
||||
const footer = document.getElementById('recipeMetaFooter');
|
||||
expect(footer.hidden).toBe(true);
|
||||
expect(footer.innerHTML).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -197,4 +197,147 @@ describe('Showcase gallery', () => {
|
||||
expect(document.querySelector('.gallery-indicator-bar')).toBeTruthy();
|
||||
expect(document.querySelectorAll('.gallery-thumb')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('prefetches adjacent example images (skipping videos) while expanded', async () => {
|
||||
const { renderShowcaseContent, initShowcaseContent, updateMainDisplay } = await import(SHOWCASE_MODULE);
|
||||
|
||||
const prefetched = [];
|
||||
class MockImage {
|
||||
set src(value) { prefetched.push(value); }
|
||||
set fetchPriority(_value) { /* jsdom lacks fetchPriority */ }
|
||||
}
|
||||
vi.stubGlobal('Image', MockImage);
|
||||
|
||||
// Unique URLs: the module-level prefetch dedup set persists across tests
|
||||
const images = [
|
||||
{ url: 'https://image.civitai.com/pf/aaa.jpeg', width: 100, height: 100, nsfwLevel: 0 },
|
||||
{ url: 'https://image.civitai.com/pf/bbb.jpeg', width: 100, height: 100, nsfwLevel: 0 },
|
||||
{ url: 'https://image.civitai.com/pf/ccc.mp4', width: 100, height: 100, nsfwLevel: 0 },
|
||||
];
|
||||
document.body.innerHTML = `<div id="showcase-tab">${renderShowcaseContent(images, [], PREVIEW_URL, true)}</div>`;
|
||||
initShowcaseContent(document.querySelector('.showcase-gallery'));
|
||||
|
||||
// galleryState.activeIndex persists across tests → pin it to 0
|
||||
updateMainDisplay(0);
|
||||
|
||||
// Active index 0 → prefetches index 1; index 2 is a video and is skipped
|
||||
expect(prefetched).toContain('https://image.civitai.com/pf/bbb.jpeg');
|
||||
expect(prefetched).not.toContain('https://image.civitai.com/pf/ccc.mp4');
|
||||
|
||||
// Navigating to 1 prefetches the new neighbor (index 0)
|
||||
updateMainDisplay(1);
|
||||
expect(prefetched).toContain('https://image.civitai.com/pf/aaa.jpeg');
|
||||
|
||||
// Navigating back does not duplicate prefetch requests
|
||||
const count = prefetched.length;
|
||||
updateMainDisplay(0);
|
||||
expect(prefetched).toHaveLength(count);
|
||||
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('does not prefetch while collapsed', async () => {
|
||||
const { renderShowcaseContent, initShowcaseContent } = await import(SHOWCASE_MODULE);
|
||||
|
||||
const prefetched = [];
|
||||
class MockImage {
|
||||
set src(value) { prefetched.push(value); }
|
||||
set fetchPriority(_value) { /* jsdom lacks fetchPriority */ }
|
||||
}
|
||||
vi.stubGlobal('Image', MockImage);
|
||||
|
||||
const images = [
|
||||
{ url: 'https://image.civitai.com/pc/ddd.jpeg', width: 100, height: 100, nsfwLevel: 0 },
|
||||
{ url: 'https://image.civitai.com/pc/eee.jpeg', width: 100, height: 100, nsfwLevel: 0 },
|
||||
];
|
||||
document.body.innerHTML = `<div id="showcase-tab">${renderShowcaseContent(images, [], PREVIEW_URL)}</div>`;
|
||||
initShowcaseContent(document.querySelector('.showcase-gallery'));
|
||||
|
||||
expect(prefetched).toHaveLength(0);
|
||||
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('prefetches one extra example ahead along the navigation direction', async () => {
|
||||
const { renderShowcaseContent, initShowcaseContent, updateMainDisplay } = await import(SHOWCASE_MODULE);
|
||||
|
||||
const prefetched = [];
|
||||
class MockImage {
|
||||
set src(value) { prefetched.push(value); }
|
||||
set fetchPriority(_value) { /* jsdom lacks fetchPriority */ }
|
||||
}
|
||||
vi.stubGlobal('Image', MockImage);
|
||||
|
||||
// Unique URLs: the module-level prefetch dedup set persists across tests
|
||||
const images = [0, 1, 2, 3, 4].map(i => ({
|
||||
url: `https://image.civitai.com/pd/${i}.jpeg`, width: 100, height: 100, nsfwLevel: 0,
|
||||
}));
|
||||
document.body.innerHTML = `<div id="showcase-tab">${renderShowcaseContent(images, [], PREVIEW_URL, true)}</div>`;
|
||||
initShowcaseContent(document.querySelector('.showcase-gallery'));
|
||||
|
||||
// Pin position, then step forward: prefetch reaches +2 ahead (index 3)
|
||||
updateMainDisplay(0);
|
||||
updateMainDisplay(1);
|
||||
expect(prefetched).toContain('https://image.civitai.com/pd/2.jpeg');
|
||||
expect(prefetched).toContain('https://image.civitai.com/pd/3.jpeg');
|
||||
|
||||
// Step backward: prefetch reaches -2 ahead (index 4 wrapping around)
|
||||
updateMainDisplay(0);
|
||||
expect(prefetched).toContain('https://image.civitai.com/pd/4.jpeg');
|
||||
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('resets the gallery position when a new model is loaded', async () => {
|
||||
const { renderShowcaseContent, loadExampleImages, updateMainDisplay } = await import(SHOWCASE_MODULE);
|
||||
|
||||
// Model A: expand and navigate to the third example
|
||||
document.body.innerHTML = `<div id="showcase-tab">${renderShowcaseContent(IMAGES, [], PREVIEW_URL, true)}</div>`;
|
||||
updateMainDisplay(2);
|
||||
expect(document.querySelector('.gallery-thumb.active')?.dataset.index).toBe('2');
|
||||
|
||||
// Model B opens: loadExampleImages is the per-model entry point
|
||||
const modelBImages = [0, 1, 2, 3].map(i => ({
|
||||
url: `https://image.civitai.com/reset/${i}.jpeg`, width: 100, height: 100, nsfwLevel: 0,
|
||||
}));
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
json: () => Promise.resolve({ success: true, files: [] }),
|
||||
}));
|
||||
await loadExampleImages(modelBImages, 'model-b-hash', '');
|
||||
vi.unstubAllGlobals();
|
||||
|
||||
// The leaked index (2) must not carry over: model B starts at example 1
|
||||
const gallery = document.querySelector('.showcase-gallery');
|
||||
expect(gallery).toBeTruthy();
|
||||
expect(document.querySelector('.gallery-indicator-bar')).toBeTruthy();
|
||||
// Expand model B's gallery: it renders from index 0, not the leaked 2
|
||||
// (loadExampleImages already bound the controls via initShowcaseContent)
|
||||
document.querySelector('#galleryShowBtn').click();
|
||||
expect(document.querySelector('.gallery-thumb.active')?.dataset.index).toBe('0');
|
||||
expect(document.querySelector('#galleryPosition')?.textContent).toBe('1 / 4');
|
||||
});
|
||||
|
||||
it('defers video thumbnail metadata fetches until the strip shows them', async () => {
|
||||
const { renderShowcaseContent, initShowcaseContent } = await import(SHOWCASE_MODULE);
|
||||
|
||||
const images = [
|
||||
{ url: 'https://image.civitai.com/lv/fff.jpeg', width: 100, height: 100, nsfwLevel: 0 },
|
||||
{ url: 'https://image.civitai.com/lv/ggg.mp4', width: 100, height: 100, nsfwLevel: 0 },
|
||||
];
|
||||
document.body.innerHTML = `<div id="showcase-tab">${renderShowcaseContent(images, [], PREVIEW_URL, true)}</div>`;
|
||||
|
||||
const video = document.querySelector('.gallery-strip video');
|
||||
expect(video?.getAttribute('preload')).toBe('none');
|
||||
expect(video?.hasAttribute('data-lazy-video')).toBe(true);
|
||||
|
||||
// jsdom's HTMLMediaElement.load() is a not-implemented stub that logs
|
||||
const loadSpy = vi.spyOn(HTMLMediaElement.prototype, 'load').mockImplementation(() => {});
|
||||
|
||||
// jsdom has no IntersectionObserver → fallback enables everything at once
|
||||
initShowcaseContent(document.querySelector('.showcase-gallery'));
|
||||
expect(video.preload).toBe('metadata');
|
||||
expect(video.hasAttribute('data-lazy-video')).toBe(false);
|
||||
expect(loadSpy).toHaveBeenCalled();
|
||||
loadSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,7 +8,9 @@ import {
|
||||
rewriteCivitaiUrl,
|
||||
getOptimizedUrl,
|
||||
getShowcaseUrl,
|
||||
getDisplayUrl,
|
||||
getThumbnailUrl,
|
||||
getGalleryThumbnailUrl,
|
||||
extractCivitaiImageId,
|
||||
extractCivitaiModelUrlParts,
|
||||
classifyModelRelinkUrl,
|
||||
@@ -21,7 +23,9 @@ describe('civitaiUtils', () => {
|
||||
describe('OptimizationMode', () => {
|
||||
it('should have correct mode values', () => {
|
||||
expect(OptimizationMode.SHOWCASE).toBe('showcase');
|
||||
expect(OptimizationMode.DISPLAY).toBe('display');
|
||||
expect(OptimizationMode.THUMBNAIL).toBe('thumbnail');
|
||||
expect(OptimizationMode.GALLERY_THUMBNAIL).toBe('gallery-thumbnail');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -107,6 +111,38 @@ describe('civitaiUtils', () => {
|
||||
expect(rewritten).toBe('https://image.civitai.com/xG1nkqKTMzGDvpLrqFT7WA/abc123/width=450,optimized=true/12345.jpeg');
|
||||
});
|
||||
|
||||
it('should rewrite image URLs with /original=true for gallery-thumbnail mode (width=160)', () => {
|
||||
const originalUrl = 'https://image.civitai.com/xG1nkqKTMzGDvpLrqFT7WA/abc123/original=true/12345.jpeg';
|
||||
const [rewritten, wasRewritten] = rewriteCivitaiUrl(originalUrl, 'image', OptimizationMode.GALLERY_THUMBNAIL);
|
||||
|
||||
expect(wasRewritten).toBe(true);
|
||||
expect(rewritten).toBe('https://image.civitai.com/xG1nkqKTMzGDvpLrqFT7WA/abc123/width=160,optimized=true/12345.jpeg');
|
||||
});
|
||||
|
||||
it('should rewrite video URLs with /original=true for gallery-thumbnail mode', () => {
|
||||
const originalUrl = 'https://image.civitai.com/xG1nkqKTMzGDvpLrqFT7WA/abc123/original=true/12345.mp4';
|
||||
const [rewritten, wasRewritten] = rewriteCivitaiUrl(originalUrl, 'video', OptimizationMode.GALLERY_THUMBNAIL);
|
||||
|
||||
expect(wasRewritten).toBe(true);
|
||||
expect(rewritten).toBe('https://image.civitai.com/xG1nkqKTMzGDvpLrqFT7WA/abc123/transcode=true,width=160,optimized=true/12345.mp4');
|
||||
});
|
||||
|
||||
it('should rewrite image URLs with /original=true for display mode (width=2400)', () => {
|
||||
const originalUrl = 'https://image.civitai.com/xG1nkqKTMzGDvpLrqFT7WA/abc123/original=true/12345.jpeg';
|
||||
const [rewritten, wasRewritten] = rewriteCivitaiUrl(originalUrl, 'image', OptimizationMode.DISPLAY);
|
||||
|
||||
expect(wasRewritten).toBe(true);
|
||||
expect(rewritten).toBe('https://image.civitai.com/xG1nkqKTMzGDvpLrqFT7WA/abc123/width=2400,optimized=true/12345.jpeg');
|
||||
});
|
||||
|
||||
it('should keep videos full quality in display mode (no transcode/width)', () => {
|
||||
const originalUrl = 'https://image.civitai.com/xG1nkqKTMzGDvpLrqFT7WA/abc123/original=true/12345.mp4';
|
||||
const [rewritten, wasRewritten] = rewriteCivitaiUrl(originalUrl, 'video', OptimizationMode.DISPLAY);
|
||||
|
||||
expect(wasRewritten).toBe(true);
|
||||
expect(rewritten).toBe('https://image.civitai.com/xG1nkqKTMzGDvpLrqFT7WA/abc123/optimized=true/12345.mp4');
|
||||
});
|
||||
|
||||
it('should not rewrite URLs without /original=true', () => {
|
||||
const originalUrl = 'https://image.civitai.com/xG1nkqKTMzGDvpLrqFT7WA/abc123/width=450/12345.jpeg';
|
||||
const [rewritten, wasRewritten] = rewriteCivitaiUrl(originalUrl, 'image', OptimizationMode.THUMBNAIL);
|
||||
@@ -232,6 +268,38 @@ describe('civitaiUtils', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('getDisplayUrl', () => {
|
||||
it('should return display-optimized URL (width=2400) for images', () => {
|
||||
const originalUrl = 'https://image.civitai.com/xG1nkqKTMzGDvpLrqFT7WA/abc123/original=true/12345.jpeg';
|
||||
const displayUrl = getDisplayUrl(originalUrl, 'image');
|
||||
|
||||
expect(displayUrl).toBe('https://image.civitai.com/xG1nkqKTMzGDvpLrqFT7WA/abc123/width=2400,optimized=true/12345.jpeg');
|
||||
});
|
||||
|
||||
it('should keep videos full quality', () => {
|
||||
const originalUrl = 'https://image.civitai.com/xG1nkqKTMzGDvpLrqFT7WA/abc123/original=true/12345.mp4';
|
||||
const displayUrl = getDisplayUrl(originalUrl, 'video');
|
||||
|
||||
expect(displayUrl).toBe('https://image.civitai.com/xG1nkqKTMzGDvpLrqFT7WA/abc123/optimized=true/12345.mp4');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getGalleryThumbnailUrl', () => {
|
||||
it('should return gallery-thumbnail-optimized URL (width=160)', () => {
|
||||
const originalUrl = 'https://image.civitai.com/xG1nkqKTMzGDvpLrqFT7WA/abc123/original=true/12345.jpeg';
|
||||
const thumbnailUrl = getGalleryThumbnailUrl(originalUrl, 'image');
|
||||
|
||||
expect(thumbnailUrl).toBe('https://image.civitai.com/xG1nkqKTMzGDvpLrqFT7WA/abc123/width=160,optimized=true/12345.jpeg');
|
||||
});
|
||||
|
||||
it('should handle videos for gallery thumbnails', () => {
|
||||
const originalUrl = 'https://image.civitai.com/xG1nkqKTMzGDvpLrqFT7WA/abc123/original=true/12345.mp4';
|
||||
const thumbnailUrl = getGalleryThumbnailUrl(originalUrl, 'video');
|
||||
|
||||
expect(thumbnailUrl).toBe('https://image.civitai.com/xG1nkqKTMzGDvpLrqFT7WA/abc123/transcode=true,width=160,optimized=true/12345.mp4');
|
||||
});
|
||||
});
|
||||
|
||||
describe('isCivitaiUrl', () => {
|
||||
it('should return true for CivitAI URLs', () => {
|
||||
expect(isCivitaiUrl('https://image.civitai.com/something')).toBe(true);
|
||||
|
||||
@@ -2246,3 +2246,31 @@ async def test_reimport_without_any_source_returns_400(
|
||||
assert payload["success"] is False
|
||||
assert harness.analysis.local_calls == []
|
||||
assert harness.persistence.delete_calls == []
|
||||
|
||||
|
||||
async def test_get_recipe_detail_includes_recipe_json_path(
|
||||
monkeypatch, tmp_path: Path
|
||||
) -> None:
|
||||
"""The detail response exposes the recipe JSON path for open-location UI."""
|
||||
async with recipe_harness(monkeypatch, tmp_path) as harness:
|
||||
recipes_dir = Path(harness.scanner.recipes_dir)
|
||||
recipes_dir.mkdir(parents=True, exist_ok=True)
|
||||
harness.scanner.recipes["recipe-1"] = {
|
||||
"id": "recipe-1",
|
||||
"title": "Demo",
|
||||
"file_path": str(recipes_dir / "recipe-1.png"),
|
||||
}
|
||||
json_file = recipes_dir / "recipe-1.recipe.json"
|
||||
json_file.write_text("{}", encoding="utf-8")
|
||||
|
||||
response = await harness.client.get("/api/lm/recipe/recipe-1")
|
||||
assert response.status == 200
|
||||
payload = await response.json()
|
||||
assert payload["recipe_json_path"] == str(json_file)
|
||||
|
||||
# Without the JSON file on disk the key is omitted entirely.
|
||||
json_file.unlink()
|
||||
response = await harness.client.get("/api/lm/recipe/recipe-1")
|
||||
assert response.status == 200
|
||||
payload = await response.json()
|
||||
assert "recipe_json_path" not in payload
|
||||
|
||||
Reference in New Issue
Block a user