Speed up explorer scrolling and add Favorites view
Browse filesFiles changed (3)
- app.py+126-62
- explorer.css+7-2
- explorer.js+201-83
20 unmodified lines21222324252685 unmodified lines1121131141151161172300 unmodified lines241824192420242124222423242424252426242724282429243032 unmodified lines24632464246524662467246824697 unmodified lines24772478247924802481248259 unmodified lines25422543254425452546254725488 unmodified lines25572558255925602561256225632564256525662567256825692570257125721333 unmodified lines39063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239332 unmodified lines393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396971 unmodified lines404140424043404440454046404740484049405020 unmodified linesfrom datetime import datetimefrom functools import lru_cachefrom io import BytesIOfrom pathlib import Pathfrom urllib.parse import quote, unquote, urlparsefrom zoneinfo import ZoneInfo85 unmodified linesPREVIEW_CACHE_SIZE = 256PREVIEW_QUALITY = 70PREVIEW_SIZE = 320IMAGE_KEY_CACHE_SIZE = 512DUPLICATE_HASH_SIZE = 16DUPLICATE_HASH_DISTANCE = 242300 unmodified linesdef encrypted_image_bytes(image):salt = os.urandom(SALT_SIZE)nonce = os.urandom(NONCE_SIZE)encrypted = AESGCM(image_key(salt)).encrypt(nonce,image_png_bytes(image),FILE_MAGIC,)return FILE_MAGIC + salt + nonce + encrypted32 unmodified linesdef star_database():STAR_DB.parent.mkdir(parents=True, exist_ok=True)database = sqlite3.connect(STAR_DB)database.execute("CREATE TABLE IF NOT EXISTS stars (path TEXT PRIMARY KEY)")7 unmodified linesartists TEXT NOT NULL)""")return database59 unmodified linesdef stored_bytes(path):data = path.read_bytes()if not data.startswith(FILE_MAGIC):raise HTTPException(500, "invalid encrypted image")salt_start = len(FILE_MAGIC)8 unmodified lines@lru_cache(maxsize=PREVIEW_CACHE_SIZE)def stored_preview(path, modified, size):with Image.open(BytesIO(stored_bytes(path))) as image:image.thumbnail((PREVIEW_SIZE, PREVIEW_SIZE))data = BytesIO()image.save(data,format="WEBP",quality=PREVIEW_QUALITY,method=0,)return data.getvalue()def reserve_matrix_grid(folder):1333 unmodified lines)def explorer_images(folder, starred):path = (IMAGE_DIR / folder).resolve()if path.parent != IMAGE_DIR.resolve() or not path.is_dir():raise HTTPException(404, "folder not found")database = star_database()images = []try:with os.scandir(path) as entries:files = [itemfor item in sorted(entries, key=natural_key, reverse=True)if Path(item.name).suffix.casefold() in IMAGE_SUFFIXESand item.is_file()]for item in files:relative = (Path(folder) / item.name).as_posix()prompt, second_prompt, artists = stored_prompt(Path(item.path), relative, database)images.append({"name": Path(item.name).with_suffix(".png").name,"path": relative,"starred": relative in starred,"prompt": prompt,"second_prompt": second_prompt,2 unmodified linesdatabase.commit()finally:database.close()return images@api.get("/api/images", dependencies=[Depends(require_pass)])def image_list(folder: str = Query(None), infinite: bool = Query(False)):root = IMAGE_DIRif not root.is_dir():return {"groups": []} if infinite else ({"folders": []} if folder is None else {"images": []})with os.scandir(root) as entries:folders = [item.namefor item in sorted(entries, key=natural_key, reverse=True)if item.is_dir(follow_symlinks=False)and explorer_folder_has_images(item.path)]if folder is None and not infinite:return {"folders": [{"name": name} for name in folders]}starred = starred_paths()if infinite:return {"groups": [{"name": name, "images": explorer_images(name, starred)}for name in folders]}return {"images": explorer_images(folder, starred)}@api.post("/api/images/star", dependencies=[Depends(require_pass)])71 unmodified linespath.unlink()database = star_database()try:database.executemany("DELETE FROM image_prompts WHERE path = ?",((relative,) for relative in relatives),)database.commit()finally:database.close()20 unmodified lines2122232425262785 unmodified lines1131141151161171181191201212300 unmodified lines242224232424242524262427242824292430243124322433243432 unmodified lines246724682469247024712472247324747 unmodified lines2482248324842485248624872488248924902491249224932494249559 unmodified lines25552556255725582559256025612562256325648 unmodified lines2573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726081333 unmodified lines3942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240132 unmodified lines4016401740184019402040214022402340244025402640274028402940304031403271 unmodified lines4104410541064107410841094110411141124113411420 unmodified linesfrom datetime import datetimefrom functools import lru_cachefrom io import BytesIOfrom itertools import islicefrom pathlib import Pathfrom urllib.parse import quote, unquote, urlparsefrom zoneinfo import ZoneInfo85 unmodified linesPREVIEW_CACHE_SIZE = 256PREVIEW_QUALITY = 70PREVIEW_SIZE = 320EXPLORER_PAGE_SIZE = 80EXPLORER_MAX_PAGE_SIZE = 200EXPLORER_DB_TIMEOUT = 30IMAGE_KEY_CACHE_SIZE = 512DUPLICATE_HASH_SIZE = 16DUPLICATE_HASH_DISTANCE = 242300 unmodified linesdef encrypted_image_bytes(image):return encrypt_image_data(image_png_bytes(image))def encrypt_image_data(data, salt=None):salt = salt if salt is not None else os.urandom(SALT_SIZE)nonce = os.urandom(NONCE_SIZE)encrypted = AESGCM(image_key(salt)).encrypt(nonce, data, FILE_MAGIC)return FILE_MAGIC + salt + nonce + encrypted32 unmodified linesdef star_database():STAR_DB.parent.mkdir(parents=True, exist_ok=True)database = sqlite3.connect(STAR_DB, timeout=EXPLORER_DB_TIMEOUT)database.execute("PRAGMA journal_mode=WAL")database.execute("CREATE TABLE IF NOT EXISTS stars (path TEXT PRIMARY KEY)")7 unmodified linesartists TEXT NOT NULL)""")database.execute("""CREATE TABLE IF NOT EXISTS image_previews (path TEXT PRIMARY KEY,modified INTEGER NOT NULL,size INTEGER NOT NULL,data BLOB NOT NULL)""")return database59 unmodified linesdef stored_bytes(path):return decrypt_image_data(path.read_bytes())def decrypt_image_data(data):if not data.startswith(FILE_MAGIC):raise HTTPException(500, "invalid encrypted image")salt_start = len(FILE_MAGIC)8 unmodified lines@lru_cache(maxsize=PREVIEW_CACHE_SIZE)def stored_preview(path, modified, size):relative = path.relative_to(IMAGE_DIR.resolve()).as_posix()database = star_database()try:cached = database.execute("""SELECT data FROM image_previewsWHERE path = ? AND modified = ? AND size = ?""",(relative, modified, size),).fetchone()if cached is not None:return decrypt_image_data(cached[0])source = path.read_bytes()with Image.open(BytesIO(decrypt_image_data(source))) as image:image.thumbnail((PREVIEW_SIZE, PREVIEW_SIZE))data = BytesIO()image.save(data,format="WEBP",quality=PREVIEW_QUALITY,method=0,)preview = data.getvalue()salt = source[len(FILE_MAGIC):len(FILE_MAGIC) + SALT_SIZE]database.execute("INSERT OR REPLACE INTO image_previews VALUES (?, ?, ?, ?)",(relative, modified, size, encrypt_image_data(preview, salt)),)database.commit()return previewfinally:database.close()def reserve_matrix_grid(folder):1333 unmodified lines)def explorer_files(folder):path = (IMAGE_DIR / folder).resolve()if path.parent != IMAGE_DIR.resolve() or not path.is_dir():raise HTTPException(404, "folder not found")with os.scandir(path) as entries:return [(Path(folder) / item.name).as_posix()for item in sorted(entries, key=natural_key, reverse=True)if Path(item.name).suffix.casefold() in IMAGE_SUFFIXESand item.is_file()]@api.get("/api/images", dependencies=[Depends(require_pass)])def image_list(folder: str = Query(None),infinite: bool = Query(False),favorites: bool = Query(False),search: str = Query(""),offset: int = Query(0, ge=0),limit: int = Query(EXPLORER_PAGE_SIZE, ge=1, le=EXPLORER_MAX_PAGE_SIZE),):grouped = infinite or (favorites and folder is None)root = IMAGE_DIRif not root.is_dir():key = "groups" if grouped else "folders" if folder is None else "images"return {key: [], "next_offset": None}if grouped or folder is None:with os.scandir(root) as entries:folders = [item.namefor item in sorted(entries, key=natural_key, reverse=True)if item.is_dir(follow_symlinks=False)and (grouped or explorer_folder_has_images(item.path))]if not grouped:return {"folders": [{"name": name} for name in folders]}else:folders = [folder]starred = starred_paths()if favorites:favorite_folders = {relative.split("/", 1)[0] for relative in starred}folders = [name for name in folders if name in favorite_folders]files = (relative for name in folders for relative in explorer_files(name)if not favorites or relative in starred)database = star_database()try:query = search.strip().casefold()if query:files = (relative for relative in files if (query in Path(relative).with_suffix(".png").name.casefold()or any(query in prompt.casefold() for prompt in stored_prompt(root / relative, relative, database)[:2])))page = list(islice(files, offset, offset + limit + 1))images = []for relative in page[:limit]:prompt, second_prompt, artists = stored_prompt(root / relative, relative, database)stat = (root / relative).stat()images.append({"name": Path(relative).with_suffix(".png").name,"path": relative,"version": f"{stat.st_mtime_ns}-{stat.st_size}","starred": relative in starred,"prompt": prompt,"second_prompt": second_prompt,2 unmodified linesdatabase.commit()finally:database.close()result = {"next_offset": offset + limit if len(page) > limit else None}if grouped:groups = {}for image in images:name = image["path"].split("/", 1)[0]groups.setdefault(name, []).append(image)result["groups"] = [{"name": name, "images": items}for name, items in groups.items()]else:result["images"] = imagesreturn result@api.post("/api/images/star", dependencies=[Depends(require_pass)])71 unmodified linespath.unlink()database = star_database()try:for table in ("image_prompts", "image_previews"):database.executemany(f"DELETE FROM {table} WHERE path = ?",((relative,) for relative in relatives),)database.commit()finally:database.close()
123415 unmodified lines20212223242526143 unmodified lines170171172173174175@import url('https://fonts.googleapis.com/css2?family=Inter:wght@450;600&display=swap');:root {--bg: #111;15 unmodified linesbody {background: var(--bg);color: var(--text);font-family: Inter, sans-serif;font-weight: 450;margin: 0;}143 unmodified linesmargin-top: 2rem;}.preview {background: var(--bg);border: 0;123415 unmodified lines20212223242526143 unmodified lines170171172173174175176177178179180@import url('https://fonts.googleapis.com/css2?family=Spline+Sans:wght@450;600&display=swap');:root {--bg: #111;15 unmodified linesbody {background: var(--bg);color: var(--text);font-family: 'Spline Sans', sans-serif;font-weight: 450;margin: 0;}143 unmodified linesmargin-top: 2rem;}.load-more {display: block;margin: var(--gap) auto;}.preview {background: var(--bg);border: 0;
3 unmodified lines45678910111213141533 unmodified lines4950515253549 unmodified lines64656667686970717273747576777879808182838485868788899091929394959697989910010110210310410523 unmodified lines12913013113213313413513613713813914014114214314414514614714814915015115212 unmodified lines16516616716816917017117217317417517617717817918018118218318418518618718818919019120 unmodified lines21221321421521621721825 unmodified lines2442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912923 unmodified lines29629729829930030130230330430530630730830931031131231331431531639 unmodified lines35635735835936036136261 unmodified lines4244254264274284294302 unmodified lines4334344354364374384394404414423 unmodified linesconst $$ = (selector, root = document) => [...root.querySelectorAll(selector)]const p = new URLSearchParams(location.search).get("p")const api = (path, query = {}) => `${path}?${new URLSearchParams({ p, ...query })}`const preview = path => api("/api/images/preview", { path })const original = path => api("/api/images/original", { path })const MIN_ZOOM = 1const MAX_ZOOM = 8const ZOOM_STEP = 1.2const INFINITE = "*"class ImageExplorer extends HTMLElement {connectedCallback() {33 unmodified lines</dialog>`this.cache = new Map()this.setupPreviews()this.load()$(".back", this).addEventListener("click", () => this.load())$(".date-prev", this).addEventListener("click", () => this.navigateDate(1))9 unmodified linesthis.setupLightbox()}async load(folder) {$(".status", this).textContent = "Loading"this.previewObserver.disconnect()$(".content", this).replaceChildren()let data = this.cache.get(folder)if (!data) {const query = folder === INFINITE? { infinite: true }: folder ? { folder } : {}const response = await fetch(api("/api/images", query))if (!response.ok) {$(".status", this).textContent = "Unable to load images"return}data = await response.json()this.cache.set(folder, data)}this.folder = folderif (!folder) this.folders = data.folders.map(item => item.name)$("h1", this).textContent = folder === INFINITE? "Infinite": folder || "Image folders"$(".back", this).hidden = !folderconst favorites = $(".favorites", this)favorites.hidden = !folderfavorites.setAttribute("aria-pressed", "false")this.favoritesOnly = falsethis.updateDateNav()const search = $("input[type=search]", this)search.value = ""search.placeholder = folder ? "Search positive prompts" : "Filter folders"search.setAttribute("aria-label", search.placeholder)if (folder === INFINITE) this.addGroups(data.groups)else if (folder) this.addImages(data.images)else this.addFolders(data.folders)this.update()}updateDateNav() {23 unmodified linesdelete image.dataset.srcthis.previewObserver.unobserve(image)}}, { rootMargin: "320px" })}addFolders(folders) {const grid = document.createElement("div")grid.className = "grid folders"const infinite = document.createElement("div")infinite.className = "folder entry"infinite.dataset.name = "infinite"const infiniteOpen = document.createElement("button")infiniteOpen.className = "folder-open"infiniteOpen.type = "button"infiniteOpen.addEventListener("click", () => this.load(INFINITE))const infiniteName = document.createElement("strong")infiniteName.textContent = "∞ Infinite"infiniteOpen.append(infiniteName)infinite.append(infiniteOpen)grid.append(infinite)for (const folder of folders) {const card = document.createElement("div")card.className = "folder entry"12 unmodified lines$(".content", this).append(grid)}addImages(images) {this.images = imagesconst grid = document.createElement("div")grid.className = "grid"for (const image of images) grid.append(this.card(image))$(".content", this).append(grid)}addGroups(groups) {this.images = groups.flatMap(group => group.images)const content = $(".content", this)for (const group of groups) {const section = document.createElement("section")section.className = "date-group"const heading = document.createElement("h2")heading.textContent = group.nameconst grid = document.createElement("div")grid.className = "grid"for (const image of group.images) grid.append(this.card(image))section.append(heading, grid)content.append(section)}}20 unmodified linesopen.addEventListener("click", () => this.openImage(image))const picture = document.createElement("img")picture.alt = image.namepicture.dataset.src = preview(image.path)this.previewObserver.observe(picture)open.append(picture)const star = this.starButton(image, "card-star")25 unmodified lines}setStar(path, starred) {for (const data of this.cache.values()) {const images = data.images || data.groups?.flatMap(group => group.images) || []for (const image of images) {if (image.path === path) image.starred = starred}}for (const button of $$(".star", this)) {if (button.dataset.path === path) this.renderStar(button, starred)}for (const card of $$(".image", this)) {if (card.dataset.path === path) card.classList.toggle("favorite", starred)}this.filter($("input[type=search]", this).value)}async toggleStar(image) {this.pendingStars ||= new Set()if (this.pendingStars.has(image.path)) returnthis.pendingStars.add(image.path)const buttons = $$(".star", this).filter(button => (button.dataset.path === image.path))for (const button of buttons) button.disabled = trueconst starred = !image.starredthis.setStar(image.path, starred)try {const response = await fetch(api("/api/images/star"), {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ path: image.path, starred }),})if (!response.ok) throw new Error("Unable to update star")} catch (error) {this.setStar(image.path, !starred)$(".status", this).textContent = error.message} finally {this.pendingStars.delete(image.path)for (const button of buttons) button.disabled = false}}select(checked) {for (const input of $$(".item", this)) input.checked = checkedthis.update()}3 unmodified lines}toggleFavorites() {this.favoritesOnly = !this.favoritesOnly$(".favorites", this).setAttribute("aria-pressed", this.favoritesOnly)this.filter($("input[type=search]", this).value)}filter(value) {const query = value.trim().toLowerCase()for (const entry of $$(".entry", this)) {const nameMatch = !query || entry.dataset.name.includes(query)|| entry.dataset.prompt?.includes(query)const favoriteMatch = !this.favoritesOnly || entry.classList.contains("favorite")entry.hidden = !nameMatch || !favoriteMatch}for (const group of $$(".date-group", this)) {group.hidden = !$(".entry:not([hidden])", group)}}39 unmodified lines})if (!response.ok) throw new Error("Delete failed")this.cache.clear()await this.load(this.folder)} catch (error) {$(".status", this).textContent = error.message} finally {61 unmodified linesshowImage(image) {const dialog = $(".lightbox", this)$("img", dialog).src = original(image.path)$("img", dialog).alt = image.name$(".prompt", dialog).textContent = this.formatPrompt(image)$(".upscale-status", dialog).textContent = ""2 unmodified linesthis.renderStar(star, image.starred)}moveImage(step) {const count = this.images.lengththis.imageIndex = (this.imageIndex + step + count) % countthis.showImage(this.images[this.imageIndex])}formatPrompt(image) {3 unmodified lines4567891011121314151617181933 unmodified lines5354555657585960619 unmodified lines717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817923 unmodified lines20320420520620720820921021121221321421521621721821922022122222322422522622722812 unmodified lines24124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328420 unmodified lines30530630730830931031131225 unmodified lines3383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994003 unmodified lines40440540640740840941041141241341441541641741841942042142242339 unmodified lines46346446546646746846961 unmodified lines5315325335345355365372 unmodified lines5405415425435445455465475485495505515525535545555565575585595603 unmodified linesconst $$ = (selector, root = document) => [...root.querySelectorAll(selector)]const p = new URLSearchParams(location.search).get("p")const api = (path, query = {}) => `${path}?${new URLSearchParams({ p, ...query })}`const preview = image => api("/api/images/preview", { path: image.path, v: image.version })const original = image => api("/api/images/original", { path: image.path, v: image.version })const MIN_ZOOM = 1const MAX_ZOOM = 8const ZOOM_STEP = 1.2const INFINITE = "*"const FAVORITES = "favorites"const SEARCH_DELAY = 250const LOAD_MARGIN = "640px"const PREVIEW_MARGIN = "320px"class ImageExplorer extends HTMLElement {connectedCallback() {33 unmodified lines</dialog>`this.cache = new Map()this.setupPreviews()this.pageObserver = new IntersectionObserver(entries => {if (entries.some(entry => entry.isIntersecting)) this.loadMore()}, { rootMargin: LOAD_MARGIN })this.load()$(".back", this).addEventListener("click", () => this.load())$(".date-prev", this).addEventListener("click", () => this.navigateDate(1))9 unmodified linesthis.setupLightbox()}async load(folder, favoritesOnly = false, query = "") {clearTimeout(this.searchTimer)this.controller?.abort()const controller = new AbortController()this.controller = controllerthis.folder = folder$(".lightbox", this).close()this.favoritesOnly = folder === FAVORITES || favoritesOnlythis.searchQuery = querythis.images = []this.imagePaths = new Set()this.groupGrids = new Map()this.nextOffset = folder ? 0 : nullthis.loadingPage = falsethis.more = null$(".status", this).textContent = "Loading"this.previewObserver.disconnect()this.pageObserver.disconnect()$(".content", this).replaceChildren()$("h1", this).textContent = folder === FAVORITES ? "Favorites": folder === INFINITE ? "Infinite" : folder || "Image folders"$(".back", this).hidden = !folder$(".all", this).textContent = folder ? "Select loaded" : "Select all"const favorites = $(".favorites", this)favorites.hidden = !folder || folder === FAVORITESfavorites.setAttribute("aria-pressed", this.favoritesOnly)this.updateDateNav()const search = $("input[type=search]", this)search.value = querysearch.placeholder = folder ? "Search positive prompts" : "Filter folders"search.setAttribute("aria-label", search.placeholder)if (folder) {if (folder !== INFINITE && folder !== FAVORITES) this.addImages([])this.more = document.createElement("button")this.more.className = "load-more"this.more.type = "button"this.more.textContent = "Load more"this.more.addEventListener("click", () => this.loadMore())$(".content", this).append(this.more)this.pageObserver.observe(this.more)await this.loadMore()return}try {let data = this.cache.get(folder)if (!data) {const response = await fetch(api("/api/images"), { signal: controller.signal })if (!response.ok) throw new Error("Unable to load folders")data = await response.json()}if (controller !== this.controller) returnthis.cache.set(folder, data)this.folders = [FAVORITES, INFINITE, ...data.folders.map(item => item.name)]this.addFolders(data.folders)this.update()} catch (error) {if (controller === this.controller) $(".status", this).textContent = error.message}}loadMore() {if (this.loadingPage) return this.pageTaskif (this.nextOffset === null || !this.folder || this.pendingStars?.size) returnthis.pageTask = this.loadPage()return this.pageTask}async loadPage() {const controller = this.controllerconst grouped = this.folder === INFINITE || this.folder === FAVORITESconst query = {offset: this.nextOffset,favorites: this.favoritesOnly,search: this.searchQuery,...(grouped ? { infinite: true } : { folder: this.folder }),}this.loadingPage = truethis.more.disabled = truethis.more.textContent = "Loading"try {const response = await fetch(api("/api/images", query), { signal: controller.signal })if (!response.ok) throw new Error("Unable to load images")const data = await response.json()if (controller !== this.controller) returnif (grouped) this.addGroups(data.groups)else this.addImages(data.images)this.nextOffset = data.next_offsetthis.more.hidden = this.nextOffset === nullthis.more.textContent = "Load more"this.update()this.pageObserver.unobserve(this.more)if (this.nextOffset !== null) this.pageObserver.observe(this.more)} catch (error) {if (controller !== this.controller) returnthis.pageObserver.unobserve(this.more)this.more.textContent = "Retry loading images"$(".status", this).textContent = error.message} finally {if (controller === this.controller) {this.loadingPage = falsethis.more.disabled = false}}}updateDateNav() {23 unmodified linesdelete image.dataset.srcthis.previewObserver.unobserve(image)}}, { rootMargin: PREVIEW_MARGIN })}addFolders(folders) {const grid = document.createElement("div")grid.className = "grid folders"for (const [folder, label] of [[FAVORITES, "Favorites"], [INFINITE, "Infinite"]]) {const card = document.createElement("div")card.className = "folder entry"card.dataset.name = label.toLowerCase()const open = document.createElement("button")open.className = "folder-open"open.type = "button"open.addEventListener("click", () => this.load(folder))const name = document.createElement("strong")name.textContent = labelopen.append(name)card.append(open)grid.append(card)}for (const folder of folders) {const card = document.createElement("div")card.className = "folder entry"12 unmodified lines$(".content", this).append(grid)}appendImages(grid, images) {const cards = document.createDocumentFragment()for (const image of images) {if (this.imagePaths.has(image.path)) continuethis.imagePaths.add(image.path)this.images.push(image)cards.append(this.card(image))}grid.append(cards)}addImages(images) {let grid = $(".content > .grid", this)if (!grid) {grid = document.createElement("div")grid.className = "grid"$(".content", this).append(grid)}this.appendImages(grid, images)}addGroups(groups) {const content = $(".content", this)for (const group of groups) {let grid = this.groupGrids.get(group.name)if (!grid) {const section = document.createElement("section")section.className = "date-group"const heading = document.createElement("h2")heading.textContent = group.namegrid = document.createElement("div")grid.className = "grid"section.append(heading, grid)content.insertBefore(section, this.more)this.groupGrids.set(group.name, grid)}this.appendImages(grid, group.images)grid.parentElement.hidden = !$(".entry:not([hidden])", grid)}}20 unmodified linesopen.addEventListener("click", () => this.openImage(image))const picture = document.createElement("img")picture.alt = image.namepicture.decoding = "async"picture.dataset.src = preview(image)this.previewObserver.observe(picture)open.append(picture)const star = this.starButton(image, "card-star")25 unmodified lines}setStar(path, starred) {for (const image of this.images) {if (image.path === path) image.starred = starred}for (const button of $$(".star", this)) {if (button.dataset.path === path) this.renderStar(button, starred)}for (const card of $$(".image", this)) {if (card.dataset.path !== path) continuecard.classList.toggle("favorite", starred)card.hidden = this.favoritesOnly && !starredif (card.hidden) $(".item", card).checked = false}for (const group of $$(".date-group", this)) {group.hidden = !$(".entry:not([hidden])", group)}this.update()}async toggleStar(image) {this.pendingStars ||= new Set()if (this.pendingStars.has(image.path)) returnthis.pendingStars.add(image.path)const controller = this.controllerconst buttons = $$(".star", this).filter(button => (button.dataset.path === image.path))for (const button of buttons) button.disabled = trueconst starred = !image.starredtry {await this.pageTaskif (controller !== this.controller) returnthis.setStar(image.path, starred)const response = await fetch(api("/api/images/star"), {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ path: image.path, starred }),})if (!response.ok) throw new Error("Unable to update star")if (controller === this.controller && this.favoritesOnly && !starred&& this.nextOffset !== null) {this.nextOffset = Math.max(0, this.nextOffset - 1)}} catch (error) {this.setStar(image.path, !starred)$(".status", this).textContent = error.message} finally {this.pendingStars.delete(image.path)for (const button of buttons) button.disabled = falseif (this.more && this.nextOffset !== null) {this.pageObserver.unobserve(this.more)this.pageObserver.observe(this.more)}}}select(checked) {for (const input of $$(".entry:not([hidden]) .item", this)) input.checked = checkedthis.update()}3 unmodified lines}toggleFavorites() {this.load(this.folder, !this.favoritesOnly, $("input[type=search]", this).value)}filter(value) {clearTimeout(this.searchTimer)if (this.folder) {this.searchTimer = setTimeout(() => {this.load(this.folder, this.favoritesOnly, value)}, SEARCH_DELAY)return}const query = value.trim().toLowerCase()for (const entry of $$(".entry", this)) {entry.hidden = !entry.dataset.name.includes(query)}}39 unmodified lines})if (!response.ok) throw new Error("Delete failed")this.cache.clear()await this.load(this.folder, this.favoritesOnly, $("input[type=search]", this).value)} catch (error) {$(".status", this).textContent = error.message} finally {61 unmodified linesshowImage(image) {const dialog = $(".lightbox", this)$("img", dialog).src = original(image)$("img", dialog).alt = image.name$(".prompt", dialog).textContent = this.formatPrompt(image)$(".upscale-status", dialog).textContent = ""2 unmodified linesthis.renderStar(star, image.starred)}async moveImage(step) {const controller = this.controllerconst current = this.images[this.imageIndex]if (step > 0 && this.imageIndex === this.images.length - 1&& this.nextOffset !== null) await this.loadMore()if (controller !== this.controller) returnconst images = this.images.filter(image => !this.favoritesOnly || image.starred)if (!images.length) {$(".lightbox", this).close()return}const index = images.indexOf(current)const image = images[(index + step + images.length) % images.length]this.imageIndex = this.images.indexOf(image)this.showImage(image)}formatPrompt(image) {
app.py+126-62
explorer.css+7-2
explorer.js+201-83