file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
src/web_templates/__init__.py
Python
"""Static assets for web export packaging."""
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
src/web_templates/assets/css/app.css
CSS
* { box-sizing: border-box; } html, body { margin: 0; padding: 0; font-family: "Noto Sans", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif; background: #f6f6f6; color: #222; } .page { min-height: 100vh; } .topbar { position: fixed; top: 0; left: 0; right: 0; height: 56px; display: flex; align-items: center; justify-content: space-between; padding: 0 1.5rem; background: linear-gradient(135deg, #2f3b52 0%, #1f2937 100%); color: #f8fafc; box-shadow: 0 2px 12px rgba(15, 23, 42, 0.2); z-index: 100; } .topbar .controls { display: flex; gap: 1rem; align-items: center; } .topbar input[type="range"] { vertical-align: middle; } .sidebar { position: fixed; top: 56px; bottom: 0; width: 280px; background: #fff; border-right: 1px solid #e1e1e1; overflow-y: auto; padding: 1.5rem 1rem; } .sidebar nav ul { list-style: none; padding: 0; margin: 0; } .sidebar nav li { margin: 0.25rem 0; } .sidebar nav a { color: #1f2933; text-decoration: none; display: block; padding: 0.2rem 0.4rem; border-radius: 4px; } .sidebar nav a.active, .sidebar nav a:hover { background: #e3f2fd; } .content { margin-left: 280px; padding: 2rem; padding-top: 56px; height: calc(100vh - 56px); overflow-y: auto; background: #fefefe; line-height: 1.75; font-size: 18px; } .content .chapter { max-width: 720px; margin: 0 auto; } .content h1, .content h2, .content h3 { margin-top: 1.5em; margin-bottom: 0.75em; } .content p { margin: 0.75em 0; } .content [data-lang="original"] { color: #2f4858; } .content [data-lang="translation"] { color: #222; } body.hide-original [data-lang="original"] { display: none; } body.hide-translation [data-lang="translation"] { display: none; } .tepub-img { max-width: 100%; height: auto; } .search-highlight { background: #ffe0b2; } .content img, .content svg { display: block; margin: 1.5rem auto; max-width: 85%; height: auto; } .content h1, .content h2 { text-align: center; } .chapter-nav { position: fixed; top: 50%; transform: translateY(-50%); border: none; background: none; color: #334155; /* 根据顶栏颜色再选 */ font-size: 3.5rem; line-height: 1; padding: 0; cursor: pointer; } .chapter-nav:hover { color: #1d2755; transform: translateY(-50%) scale(1.05); } .chapter-nav:disabled { opacity: 0.3; cursor: default; transform: translateY(-50%); } .chapter-nav.prev { left: calc(280px + 16px); } .chapter-nav.next { right: 24px; } @media (max-width: 1024px) { .chapter-nav.prev { left: 16px; } .chapter-nav.next { right: 16px; } .sidebar { width: 220px; } .content { margin-left: 220px; padding: calc(2rem + 56px) 1.75rem 2rem; } }
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
src/web_templates/assets/js/app.js
JavaScript
(function () { const data = window.BOOK_DATA || { spine: [], toc: [] }; const contentRoot = "content/"; const contentEl = document.getElementById("content"); const tocEl = document.getElementById("toc"); const titleEl = document.getElementById("book-title"); const toggleOriginal = document.getElementById("toggle-original"); const toggleTranslation = document.getElementById("toggle-translation"); const prevBtn = document.getElementById("prev-chapter"); const nextBtn = document.getElementById("next-chapter"); const chapters = data.spine || []; const tocEntries = data.toc || chapters; const documents = data.documents || {}; let currentIndex = 0; titleEl.textContent = data.title || document.title; function normaliseHref(href) { if (!href) return ""; return href.replace(/^\.\//, "").replace(/^\//, ""); } function updateNavButtons() { if (!prevBtn || !nextBtn) return; prevBtn.disabled = currentIndex <= 0; nextBtn.disabled = currentIndex >= chapters.length - 1; } function renderToc() { const ul = document.createElement("ul"); tocEntries.forEach((entry, index) => { const li = document.createElement("li"); li.style.marginLeft = `${(entry.level || 0) * 12}px`; const link = document.createElement("a"); const rawHref = entry.href || chapters[index]?.href || ""; const targetHref = normaliseHref(rawHref); link.href = targetHref ? contentRoot + targetHref : "#"; link.dataset.href = targetHref; link.textContent = entry.title || entry.href || targetHref || "(untitled)"; link.addEventListener("click", (event) => { event.preventDefault(); if (!targetHref) return; openChapter(targetHref); }); li.appendChild(link); ul.appendChild(li); }); tocEl.innerHTML = ""; tocEl.appendChild(ul); } function setActiveLink(activeLink) { tocEl.querySelectorAll("a").forEach((link) => link.classList.remove("active")); if (activeLink) { activeLink.classList.add("active"); } } function renderChapter(htmlString, anchor) { const parser = new DOMParser(); const doc = parser.parseFromString(htmlString, "text/html"); const body = doc.querySelector("body"); const wrapper = document.createElement("article"); wrapper.className = "chapter"; wrapper.innerHTML = body ? body.innerHTML : htmlString; contentEl.innerHTML = ""; contentEl.appendChild(wrapper); applyVisibility(); if (anchor) { const node = contentEl.querySelector(`#${CSS.escape(anchor)}`); if (node) { node.scrollIntoView({ block: "start" }); } } } async function loadChapter(target, anchor) { if (!target) return; const inline = documents[target]; if (inline) { renderChapter(inline, anchor); return; } try { const response = await fetch(contentRoot + target); const text = await response.text(); renderChapter(text, anchor); } catch (error) { console.error("Failed to load chapter", target, error); } } async function openChapter(targetHref) { const target = normaliseHref(targetHref); if (!target) return; const [file, hash] = target.split("#"); await loadChapter(file, hash); const idx = chapters.findIndex((ch) => normaliseHref(ch.href).split("#")[0] === file); if (idx >= 0) { currentIndex = idx; } updateNavButtons(); const tocLink = tocEl.querySelector(`a[data-href="${CSS.escape(target)}"]`) || tocEl.querySelector(`a[data-href="${CSS.escape(file)}"]`); if (tocLink) { setActiveLink(tocLink); tocLink.scrollIntoView({ block: "nearest" }); } } function applyVisibility() { document.body.classList.toggle("hide-original", !toggleOriginal.checked); document.body.classList.toggle("hide-translation", !toggleTranslation.checked); } toggleOriginal.addEventListener("change", applyVisibility); toggleTranslation.addEventListener("change", applyVisibility); contentEl.addEventListener("click", (event) => { const anchor = event.target.closest("a"); if (!anchor) return; const href = anchor.getAttribute("href"); if (!href) return; if (href.startsWith(contentRoot)) { event.preventDefault(); const target = href.slice(contentRoot.length); openChapter(target); } }); if (prevBtn && nextBtn) { prevBtn.addEventListener("click", () => { const nextIdx = currentIndex - 1; if (nextIdx >= 0) { openChapter(chapters[nextIdx].href); } }); nextBtn.addEventListener("click", () => { const nextIdx = currentIndex + 1; if (nextIdx < chapters.length) { openChapter(chapters[nextIdx].href); } }); } renderToc(); applyVisibility(); updateNavButtons(); if (chapters.length) { openChapter(chapters[0].href); } })();
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
src/web_templates/index.html
HTML
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>TEPUB Web Export</title> <link rel="stylesheet" href="assets/css/app.css" /> <script defer src="assets/js/app.js"></script> </head> <body> <div class="page"> <header class="topbar"> <div class="title" id="book-title">TEPUB Export</div> <div class="controls"> <label> <input type="checkbox" id="toggle-original" checked /> 原文 </label> <label> <input type="checkbox" id="toggle-translation" checked /> 译文 </label> </div> </header> <aside class="sidebar"> <nav id="toc"></nav> </aside> <button id="prev-chapter" class="chapter-nav prev" aria-label="Previous chapter">&#8249;</button> <main class="content" id="content"></main> <button id="next-chapter" class="chapter-nav next" aria-label="Next chapter">&#8250;</button> </div> <script> window.BOOK_DATA = {{BOOK_DATA}}; </script> </body> </html>
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
src/webbuilder/__init__.py
Python
"""Utilities for exporting web-friendly versions of the translated EPUB.""" from __future__ import annotations from .exporter import export_web __all__ = ["export_web"]
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
src/webbuilder/assets.py
Python
from __future__ import annotations import json import shutil from dataclasses import dataclass from importlib import resources from pathlib import Path TEMPLATE_PACKAGE = "web_templates" @dataclass class BookData: title: str spine: list[dict] toc: list[dict] documents: dict[str, str] | None = None def _read_template(name: str) -> str: template_path = resources.files(TEMPLATE_PACKAGE) / name return template_path.read_text(encoding="utf-8") def _copy_directory(source: Path, destination: Path) -> None: if destination.exists(): shutil.rmtree(destination) shutil.copytree(source, destination) def copy_static_assets(output_root: Path) -> None: package_root = resources.files(TEMPLATE_PACKAGE) assets_source = package_root / "assets" with resources.as_file(assets_source) as src_path: _copy_directory(src_path, output_root / "assets") def render_index(output_root: Path, data: BookData) -> None: index_template = _read_template("index.html") book_data_json = json.dumps( { "title": data.title, "spine": data.spine, "toc": data.toc, "documents": data.documents or {}, }, ensure_ascii=False, ) contents = index_template.replace("{{BOOK_DATA}}", book_data_json) (output_root / "index.html").write_text(contents, encoding="utf-8")
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
src/webbuilder/dom.py
Python
from __future__ import annotations from collections.abc import Sequence from pathlib import Path from posixpath import normpath from lxml import html MEDIA_ATTRS: list[tuple[str, Sequence[str]]] = [ ("img", ("src", "srcset")), ("source", ("src", "srcset")), ("video", ("src", "poster")), ("audio", ("src",)), ("track", ("src",)), ("object", ("data",)), ("embed", ("src",)), ("image", ("{http://www.w3.org/1999/xlink}href", "xlink:href", "href")), ("use", ("{http://www.w3.org/1999/xlink}href", "xlink:href", "href")), ] def _is_external_url(value: str) -> bool: return value.startswith(("data:", "http:", "https:", "//", "#")) def _prefix_content_path(relative_to: Path, url: str) -> str: if not url or _is_external_url(url): return url if url.startswith("content/"): return url base = relative_to.parent.as_posix() combined = f"{base}/{url}" if base else url normalised = normpath(combined) return f"content/{normalised}" def _rewrite_links(doc: html.HtmlElement, relative_path: Path) -> None: for el in doc.xpath(".//a[@href]"): href = el.get("href") if not href or href.startswith(("mailto:", "javascript:")): continue if href.startswith("#"): continue fragment = "" path_part = href if "#" in href: path_part, fragment = href.split("#", 1) if not path_part: continue resolved = _prefix_content_path(relative_path, path_part) if resolved == path_part: continue if fragment: el.set("href", f"{resolved}#{fragment}") else: el.set("href", resolved) def _rewrite_media_urls(doc: html.HtmlElement, relative_path: Path) -> None: for tag, attrs in MEDIA_ATTRS: for el in doc.xpath(f".//{tag}"): for attr in attrs: value = el.get(attr) if value is None and attr.startswith("{"): _, local = attr.rsplit("}", 1) value = el.get(local) if value is None and ":" in attr: _, local = attr.rsplit(":", 1) value = el.get(local) if value is None: value = el.attrib.get(attr) if not value: continue if attr == "srcset": parts: list[str] = [] for candidate in value.split(","): candidate = candidate.strip() if not candidate: continue if " " in candidate: url_part, descriptor = candidate.split(" ", 1) parts.append( f"{_prefix_content_path(relative_path, url_part)} {descriptor.strip()}" ) else: parts.append(_prefix_content_path(relative_path, candidate)) if parts: el.set(attr, ", ".join(parts)) else: el.set(attr, _prefix_content_path(relative_path, value)) REMOVABLE_TAGS = {"font", "center"} REMOVABLE_ATTRS = {"style", "class", "lang", "xml:lang"} def _remove_tags(doc: html.HtmlElement) -> None: for tag in REMOVABLE_TAGS: for el in doc.xpath(f".//{tag}"): el.drop_tag() def _strip_attributes(doc: html.HtmlElement) -> None: for attr in REMOVABLE_ATTRS: for el in doc.xpath(f".//*[@{attr}]"): if attr in ("class", "style") and el.get("data-lang"): # Preserve class/style on translation/original nodes if present if attr in el.attrib: del el.attrib[attr] continue el.attrib.pop(attr, None) def _normalise_images(doc: html.HtmlElement) -> None: for img in doc.xpath(".//img"): if "loading" not in img.attrib: img.attrib["loading"] = "lazy" if "decoding" not in img.attrib: img.attrib["decoding"] = "async" # Ensure images don't overflow classes = [cls for cls in img.attrib.get("class", "").split() if cls] if "tepub-img" not in classes: classes.append("tepub-img") if classes: img.attrib["class"] = " ".join(classes) else: img.attrib.pop("class", None) def clean_html(content: bytes | str, *, relative_path: Path | None = None) -> str: parser = html.HTMLParser(encoding="utf-8") doc = html.fromstring(content, parser=parser) _remove_tags(doc) _strip_attributes(doc) _normalise_images(doc) if relative_path is not None: _rewrite_media_urls(doc, relative_path) _rewrite_links(doc, relative_path) return html.tostring(doc, encoding="unicode", method="html") def ensure_parseable(content: str) -> None: # Raises if not well-formed html.fromstring(content)
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
src/webbuilder/exporter.py
Python
from __future__ import annotations import shutil from pathlib import Path from ebooklib import ITEM_DOCUMENT, epub from lxml import html as lxml_html from config import AppSettings from epub_io.reader import EpubReader from epub_io.resources import iter_spine_items from injection.engine import apply_translations from .assets import BookData, copy_static_assets, render_index from .dom import clean_html, ensure_parseable def _default_output_dir(epub_path: Path, work_dir: Path) -> Path: # Export to workspace directory, not alongside EPUB return work_dir / f"{epub_path.stem}_web" def _book_title(reader: EpubReader) -> str: metadata = reader.book.get_metadata("DC", "title") if metadata: return metadata[0][0] return reader.epub_path.stem def _document_title(tree) -> str: candidates = tree.xpath("//h1") if candidates: text = candidates[0].text_content().strip() if text: return text titles = tree.xpath("//title") if titles: text = titles[0].text_content().strip() if text: return text return "" def _build_spine(reader: EpubReader, doc_titles: dict[Path, str]) -> list[dict]: spine: list[dict] = [] for item in iter_spine_items(reader.book): title = doc_titles.get(item.href, item.href.stem) spine.append( { "href": item.href.as_posix(), "title": title or item.href.stem, } ) return spine def _parse_toc(entries) -> list[dict]: toc_list: list[dict] = [] def recurse(items, level=0): for item in items: if isinstance(item, epub.Link): toc_list.append( { "title": item.title, "href": item.href, "level": level, } ) elif isinstance(item, (list, tuple)) and item: head = item[0] children = item[1] if len(item) > 1 else [] if isinstance(head, epub.Link): toc_list.append( { "title": head.title, "href": head.href, "level": level, } ) recurse(children, level + 1) recurse(entries) return toc_list def _copy_static_resources(reader: EpubReader, content_dir: Path) -> None: for item in reader.book.get_items(): # Skip HTML documents; they are handled separately if item.get_type() == ITEM_DOCUMENT: continue dest = content_dir / Path(item.file_name) dest.parent.mkdir(parents=True, exist_ok=True) dest.write_bytes(item.get_content()) def export_web( settings: AppSettings, input_epub: Path, *, output_dir: Path | None = None, output_mode: str | None = None, ) -> Path: output_root = ( Path(output_dir) if output_dir else _default_output_dir(input_epub, settings.work_dir) ) if output_root.exists(): shutil.rmtree(output_root) output_root.mkdir(parents=True, exist_ok=True) copy_static_assets(output_root) reader = EpubReader(input_epub, settings) updated_html, title_updates = apply_translations(settings, input_epub) doc_titles: dict[Path, str] = {} documents: dict[str, str] = {} mode_value = output_mode or getattr(settings, "output_mode", "bilingual") mode = mode_value.replace("-", "_").lower() if isinstance(mode_value, str) else "bilingual" if mode not in {"bilingual", "translated_only"}: mode = "bilingual" content_dir = output_root / "content" for document in reader.iter_documents(): path = document.path if path in updated_html: content = clean_html(updated_html[path], relative_path=path) else: content = clean_html(document.raw_html, relative_path=path) ensure_parseable(content) if mode == "translated_only": doc_titles[path] = ( _document_title(lxml_html.fromstring(content)) or path.stem if "lxml_html" in globals() else _document_title(document.tree) or path.stem ) else: doc_titles[path] = _document_title(document.tree) or path.stem documents[path.as_posix()] = content dest = content_dir / path dest.parent.mkdir(parents=True, exist_ok=True) dest.write_text(content, encoding="utf-8") _copy_static_resources(reader, content_dir) spine = _build_spine(reader, doc_titles) toc = _parse_toc(reader.book.toc) if reader.book.toc else [] if not toc: toc = [{"title": entry["title"], "href": entry["href"], "level": 0} for entry in spine] render_index( output_root, BookData( title=_book_title(reader), spine=spine, toc=toc, documents=documents, ), ) return output_root
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/audiobook/test_cover.py
Python
from pathlib import Path from PIL import Image from epub_io.path_utils import normalize_epub_href from audiobook.assembly import _prepare_cover def test_normalize_relative_image_path(): doc = Path("Text/chapter1.xhtml") assert normalize_epub_href(doc, "images/cover.jpg") == "Text/images/cover.jpg" def test_normalize_parent_directory(): doc = Path("Text/chapter1.xhtml") assert normalize_epub_href(doc, "../Images/cover.jpg") == "Images/cover.jpg" def test_normalize_rooted_path(): doc = Path("Text/chapter1.xhtml") assert normalize_epub_href(doc, "/Images/cover.jpg") == "Images/cover.jpg" def test_normalize_rejects_data_uri(): doc = Path("Text/chapter1.xhtml") assert normalize_epub_href(doc, "data:image/png;base64,abc") is None def test_normalize_rejects_remote_url(): doc = Path("Text/chapter1.xhtml") assert normalize_epub_href(doc, "https://example.com/cover.jpg") is None def test_prepare_cover_keeps_dimensions(tmp_path): src = tmp_path / "source.png" Image.new("RGB", (320, 180), color="navy").save(src, format="PNG") output_root = tmp_path / "output" result = _prepare_cover(output_root, reader=None, explicit_cover=src) assert result is not None saved = Image.open(result) assert saved.size == (320, 180)
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/audiobook/test_footnote_filtering.py
Python
"""Tests for footnote filtering during audiobook generation.""" from pathlib import Path from unittest.mock import Mock from lxml import html as lxml_html from audiobook.preprocess import _reextract_filtered, segment_to_text from state.models import ExtractMode, Segment, SegmentMetadata def test_reextract_filtered_removes_sup_footnotes(): """Test that <a><sup> footnote references are removed.""" html_content = """ <p>This is a sentence with a footnote<a href="#fn1"><sup>1</sup></a> reference.</p> """ # Mock segment segment = Segment( segment_id="test-001", file_path=Path("chapter.xhtml"), xpath="//p", extract_mode=ExtractMode.HTML, source_content=html_content, metadata=SegmentMetadata( element_type="p", spine_index=0, order_in_file=0 ) ) # Mock reader mock_doc = Mock() element = lxml_html.fromstring(html_content) mock_doc.tree.xpath.return_value = [element] mock_reader = Mock() mock_reader.read_document_by_path.return_value = mock_doc # Execute result = _reextract_filtered(segment, mock_reader) # Verify footnote reference removed assert result == "This is a sentence with a footnote reference." assert "<sup>" not in result assert "1" not in result def test_reextract_filtered_removes_sub_footnotes(): """Test that <a><sub> footnote references are removed.""" html_content = """ <p>This is text<a href="#note2"><sub>2</sub></a> with subscript note.</p> """ segment = Segment( segment_id="test-002", file_path=Path("chapter.xhtml"), xpath="//p", extract_mode=ExtractMode.HTML, source_content=html_content, metadata=SegmentMetadata( element_type="p", spine_index=0, order_in_file=0 ) ) mock_doc = Mock() element = lxml_html.fromstring(html_content) mock_doc.tree.xpath.return_value = [element] mock_reader = Mock() mock_reader.read_document_by_path.return_value = mock_doc result = _reextract_filtered(segment, mock_reader) assert result == "This is text with subscript note." assert "<sub>" not in result assert "2" not in result def test_reextract_filtered_preserves_regular_links(): """Test that regular links (without sup/sub) are preserved.""" html_content = """ <p>Visit <a href="https://example.com">our website</a> for more.</p> """ segment = Segment( segment_id="test-003", file_path=Path("chapter.xhtml"), xpath="//p", extract_mode=ExtractMode.HTML, source_content=html_content, metadata=SegmentMetadata( element_type="p", spine_index=0, order_in_file=0 ) ) mock_doc = Mock() element = lxml_html.fromstring(html_content) mock_doc.tree.xpath.return_value = [element] mock_reader = Mock() mock_reader.read_document_by_path.return_value = mock_doc result = _reextract_filtered(segment, mock_reader) # Link text should be preserved assert "our website" in result def test_reextract_filtered_multiple_footnotes(): """Test removing multiple footnote references.""" html_content = """ <p>First<a><sup>1</sup></a> and second<a><sup>2</sup></a> footnotes.</p> """ segment = Segment( segment_id="test-004", file_path=Path("chapter.xhtml"), xpath="//p", extract_mode=ExtractMode.HTML, source_content=html_content, metadata=SegmentMetadata( element_type="p", spine_index=0, order_in_file=0 ) ) mock_doc = Mock() element = lxml_html.fromstring(html_content) mock_doc.tree.xpath.return_value = [element] mock_reader = Mock() mock_reader.read_document_by_path.return_value = mock_doc result = _reextract_filtered(segment, mock_reader) assert result == "First and second footnotes." assert "1" not in result assert "2" not in result def test_segment_to_text_uses_reader_when_provided(): """Test that segment_to_text uses reader for re-extraction when provided.""" segment = Segment( segment_id="test-005", file_path=Path("chapter.xhtml"), xpath="//p", extract_mode=ExtractMode.HTML, source_content="<p>Text with<a><sup>1</sup></a> footnote.</p>", metadata=SegmentMetadata( element_type="p", spine_index=0, order_in_file=0 ) ) # Mock reader setup mock_doc = Mock() element = lxml_html.fromstring(segment.source_content) mock_doc.tree.xpath.return_value = [element] mock_reader = Mock() mock_reader.read_document_by_path.return_value = mock_doc # With reader - should filter result_with_reader = segment_to_text(segment, reader=mock_reader) assert result_with_reader == "Text with footnote." # Without reader - should keep HTML as-is (footnote number appears) result_without_reader = segment_to_text(segment, reader=None) assert "1" in result_without_reader def test_segment_to_text_fallback_on_reextraction_failure(): """Test fallback to stored content if re-extraction fails.""" segment = Segment( segment_id="test-006", file_path=Path("chapter.xhtml"), xpath="//p", extract_mode=ExtractMode.HTML, source_content="<p>Fallback text content</p>", metadata=SegmentMetadata( element_type="p", spine_index=0, order_in_file=0 ) ) # Mock reader that raises error mock_reader = Mock() mock_reader.read_document_by_path.side_effect = Exception("EPUB read failed") # Should fallback to stored content result = segment_to_text(segment, reader=mock_reader) assert result == "Fallback text content" def test_segment_to_text_skips_table_and_figure(): """Test that table and figure elements are skipped regardless of reader.""" table_segment = Segment( segment_id="test-007", file_path=Path("chapter.xhtml"), xpath="//table", extract_mode=ExtractMode.HTML, source_content="<table><tr><td>Data</td></tr></table>", metadata=SegmentMetadata( element_type="table", spine_index=0, order_in_file=0 ) ) figure_segment = Segment( segment_id="test-008", file_path=Path("chapter.xhtml"), xpath="//figure", extract_mode=ExtractMode.HTML, source_content="<figure><img src='pic.jpg'/></figure>", metadata=SegmentMetadata( element_type="figure", spine_index=0, order_in_file=0 ) ) mock_reader = Mock() assert segment_to_text(table_segment, reader=mock_reader) is None assert segment_to_text(figure_segment, reader=mock_reader) is None
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/audiobook/test_footnote_integration.py
Python
"""Integration test for footnote filtering with real EPUB structure.""" from pathlib import Path from unittest.mock import Mock from lxml import html as lxml_html from audiobook.preprocess import segment_to_text from state.models import ExtractMode, Segment, SegmentMetadata def test_dynasty_epub_footnote_patterns(): """Test with actual patterns from Dynasty EPUB file.""" # Pattern 1: Inline endnote reference with asterisk segment1 = Segment( segment_id="p1", file_path=Path("OEBPS/chapter01.xhtml"), xpath="//p[@id='p1']", extract_mode=ExtractMode.HTML, source_content='<p id="p1">Mars, the Spiller of Blood, had planted his seed in a mortal womb.<a href="#ftn3" id="ftn3a"><sup>*1</sup></a></p>', metadata=SegmentMetadata( element_type="p", spine_index=1, order_in_file=0 ) ) # Pattern 2: Multiple endnote references with numbers segment2 = Segment( segment_id="p3", file_path=Path("OEBPS/chapter01.xhtml"), xpath="//p[@id='p3']", extract_mode=ExtractMode.HTML, source_content='<p id="p3">The Roman character.<a href="content/OEBPS/notes.xhtml#n1" id="n1a"><sup>1</sup></a> Even more text.<a href="content/OEBPS/notes.xhtml#n2" id="n2a"><sup>2</sup></a> Final sentence.</p>', metadata=SegmentMetadata( element_type="p", spine_index=1, order_in_file=1 ) ) # Pattern 3: Footnote with subscript reference segment3 = Segment( segment_id="p10", file_path=Path("OEBPS/chapter01.xhtml"), xpath="//p[@id='p10']", extract_mode=ExtractMode.HTML, source_content='<p id="p10">Chemical formula H<a href="#fn1"><sub>2</sub></a>O is not actually a footnote, but our filter removes it anyway.</p>', metadata=SegmentMetadata( element_type="p", spine_index=1, order_in_file=2 ) ) # Test with reader (filtered) # Segment 1 mock_reader1 = Mock() mock_doc1 = Mock() element1 = lxml_html.fromstring(segment1.source_content) mock_doc1.tree.xpath.return_value = [element1] mock_reader1.read_document_by_path.return_value = mock_doc1 result1 = segment_to_text(segment1, reader=mock_reader1) assert result1 == "Mars, the Spiller of Blood, had planted his seed in a mortal womb." assert "*1" not in result1 # Segment 2 mock_reader2 = Mock() mock_doc2 = Mock() element2 = lxml_html.fromstring(segment2.source_content) mock_doc2.tree.xpath.return_value = [element2] mock_reader2.read_document_by_path.return_value = mock_doc2 result2 = segment_to_text(segment2, reader=mock_reader2) assert result2 == "The Roman character. Even more text. Final sentence." assert "1" not in result2.replace("Roman character.", "") # Avoid false positive from "1" in different context assert "2" not in result2 # Segment 3 mock_reader3 = Mock() mock_doc3 = Mock() element3 = lxml_html.fromstring(segment3.source_content) mock_doc3.tree.xpath.return_value = [element3] mock_reader3.read_document_by_path.return_value = mock_doc3 result3 = segment_to_text(segment3, reader=mock_reader3) # Note: This removes <sub>2</sub> which might be a chemical formula, not a footnote # This is a known limitation - users should review their content assert "2" not in result3 def test_footnote_file_exclusion(): """Test that footnote files can be excluded via audiobook_files config.""" # Main chapter segment chapter_segment = Segment( segment_id="ch1-p1", file_path=Path("OEBPS/chapter01.xhtml"), xpath="//p[1]", extract_mode=ExtractMode.HTML, source_content="<p>Main text<a><sup>1</sup></a> continues.</p>", metadata=SegmentMetadata( element_type="p", spine_index=1, order_in_file=0 ) ) # Footnote definition segment (in separate file) footnote_segment = Segment( segment_id="notes-fn1", file_path=Path("OEBPS/notes.xhtml"), # Different file xpath="//p[@id='fn1']", extract_mode=ExtractMode.HTML, source_content='<p id="fn1"><a href="#fn1a">1</a> This is the footnote text that explains something.</p>', metadata=SegmentMetadata( element_type="p", spine_index=99, # Footnotes usually at end order_in_file=0 ) ) # Simulate audiobook_files inclusion list filtering audiobook_files = { "OEBPS/chapter01.xhtml", # "OEBPS/notes.xhtml" is excluded } # Chapter file is included assert chapter_segment.file_path.as_posix() in audiobook_files # Footnote file is excluded assert footnote_segment.file_path.as_posix() not in audiobook_files # This filtering happens in controller.py before segment_to_text is called # So the footnote segment never gets processed for TTS def test_skips_footnote_definition_sections(): """Test that footnote definition sections are skipped based on segment ID.""" # Footnote definition segment (from Dynasty EPUB) footnote_def = Segment( segment_id="ftn3", file_path=Path("chapter.xhtml"), xpath="//div[@id='div3']/p[@id='ftn3']", extract_mode=ExtractMode.HTML, source_content='<p id="ftn3"><a href="#ftn3a">*1</a> Two historians, Marcus Octavius and Licinius Macer, claimed that the rapist was the girl\'s uncle.</p>', metadata=SegmentMetadata( element_type="p", spine_index=1, order_in_file=100 # Late in file ) ) # Endnote with different ID pattern endnote_def = Segment( segment_id="note-42", file_path=Path("chapter.xhtml"), xpath="//div[@id='endnotes']/p[@id='note-42']", extract_mode=ExtractMode.HTML, source_content="<p>This is the endnote text.</p>", metadata=SegmentMetadata( element_type="p", spine_index=1, order_in_file=101 ) ) # Footnote in div with class footnote_in_div = Segment( segment_id="p150", file_path=Path("chapter.xhtml"), xpath="//div[@class='footnotes']/p[@id='p150']", extract_mode=ExtractMode.HTML, source_content="<p>Footnote content here.</p>", metadata=SegmentMetadata( element_type="p", spine_index=1, order_in_file=150 ) ) # All should be skipped (return None) assert segment_to_text(footnote_def, reader=None) is None assert segment_to_text(endnote_def, reader=None) is None assert segment_to_text(footnote_in_div, reader=None) is None def test_preserves_regular_links_in_text(): """Ensure regular hyperlinks without sup/sub are preserved.""" segment = Segment( segment_id="p5", file_path=Path("chapter.xhtml"), xpath="//p[@id='p5']", extract_mode=ExtractMode.HTML, source_content='<p id="p5">Visit <a href="https://example.com">our website</a> for more information.</p>', metadata=SegmentMetadata( element_type="p", spine_index=1, order_in_file=0 ) ) mock_doc = Mock() element = lxml_html.fromstring(segment.source_content) mock_doc.tree.xpath.return_value = [element] mock_reader = Mock() mock_reader.read_document_by_path.return_value = mock_doc result = segment_to_text(segment, reader=mock_reader) # Link text is preserved assert "our website" in result assert "Visit" in result assert "for more information" in result
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/audiobook/test_mp4chapters.py
Python
from pathlib import Path import pytest from mutagen.mp4 import MP4 from pydub import AudioSegment from pydub.exceptions import CouldntEncodeError from audiobook.mp4chapters import _build_chpl_payload, write_chapter_markers def test_build_chpl_payload_structure(): payload = _build_chpl_payload([(0.0, "Intro"), (1.25, "Chapter 1")], 1000) assert payload[:8] == b"\x01\x00\x00\x00\x00\x00\x00\x00" count = payload[8] assert count == 2 offset = 9 starts = [] for _ in range(count): start_raw = int.from_bytes(payload[offset:offset + 8], "big") offset += 8 title_len = payload[offset] offset += 1 title = payload[offset:offset + title_len].decode("utf-8") offset += title_len starts.append((start_raw, title)) assert starts[0] == (0, "Intro") assert starts[1][0] == int(1.25 * 1000 * 10000) assert starts[1][1] == "Chapter 1" def test_write_chapter_markers_roundtrip(tmp_path): audio = AudioSegment.silent(duration=1000) output = Path(tmp_path / "sample.m4a") try: audio.export(output, format="mp4") except CouldntEncodeError: pytest.skip("ffmpeg not available for mp4 export") write_chapter_markers(output, [(0, "Intro"), (500, "Middle")]) mp4 = MP4(output) assert mp4.chapters, "Chapters not present after injection" assert mp4.chapters[0].title == "Intro" assert mp4.chapters[1].title == "Middle" assert mp4.chapters[0].start == pytest.approx(0.0, abs=0.01) assert mp4.chapters[1].start == pytest.approx(0.5, abs=0.01)
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/audiobook/test_roman_numerals.py
Python
"""Tests for Roman numeral conversion in audiobook titles.""" from pathlib import Path from audiobook.preprocess import segment_to_text from state.models import ExtractMode, Segment, SegmentMetadata def test_standalone_roman_I_in_h1_heading(): """Test that standalone 'I' in h1 heading converts to 'One'.""" segment = Segment( segment_id="part-1", file_path=Path("part01.xhtml"), xpath="/html/body/div/h1[1]", extract_mode=ExtractMode.TEXT, source_content="I", metadata=SegmentMetadata( element_type="h1", spine_index=12, order_in_file=1 ) ) result = segment_to_text(segment, reader=None) assert result == "One" def test_standalone_roman_II_in_h1_heading(): """Test that standalone 'II' in h1 heading converts to 'Two'.""" segment = Segment( segment_id="part-2", file_path=Path("part02.xhtml"), xpath="/html/body/div/h1[1]", extract_mode=ExtractMode.TEXT, source_content="II", metadata=SegmentMetadata( element_type="h1", spine_index=16, order_in_file=1 ) ) result = segment_to_text(segment, reader=None) assert result == "Two" def test_roman_numeral_III_to_X(): """Test Roman numerals III through X.""" test_cases = [ ("III", "Three"), ("IV", "Four"), ("V", "Five"), ("VI", "Six"), ("VII", "Seven"), ("VIII", "Eight"), ("IX", "Nine"), ("X", "Ten"), ] for roman, expected in test_cases: segment = Segment( segment_id=f"chapter-{roman}", file_path=Path("chapter.xhtml"), xpath="/html/body/div/h1", extract_mode=ExtractMode.TEXT, source_content=roman, metadata=SegmentMetadata( element_type="h1", spine_index=1, order_in_file=1 ) ) result = segment_to_text(segment, reader=None) assert result == expected, f"Expected '{roman}' to convert to '{expected}', got '{result}'" def test_larger_roman_numerals(): """Test larger Roman numerals XI through XX and beyond.""" test_cases = [ ("XI", "Eleven"), ("XII", "Twelve"), ("XIII", "Thirteen"), ("XIV", "Fourteen"), ("XV", "Fifteen"), ("XVI", "Sixteen"), ("XVII", "Seventeen"), ("XVIII", "Eighteen"), ("XIX", "Nineteen"), ("XX", "Twenty"), ("XXI", "Twenty-one"), ("XXX", "Thirty"), ("XL", "Forty"), ("L", "Fifty"), ("C", "One hundred"), ] for roman, expected in test_cases: segment = Segment( segment_id=f"chapter-{roman}", file_path=Path("chapter.xhtml"), xpath="/html/body/div/h2", extract_mode=ExtractMode.TEXT, source_content=roman, metadata=SegmentMetadata( element_type="h2", spine_index=1, order_in_file=1 ) ) result = segment_to_text(segment, reader=None) assert result == expected, f"Expected '{roman}' to convert to '{expected}', got '{result}'" def test_pronoun_I_in_sentence_unchanged(): """Test that 'I' as pronoun in sentence is NOT converted.""" segment = Segment( segment_id="p1", file_path=Path("chapter.xhtml"), xpath="/html/body/div/p", extract_mode=ExtractMode.TEXT, source_content="I am a sentence with the pronoun I in it.", metadata=SegmentMetadata( element_type="p", spine_index=1, order_in_file=5 # Not first ) ) result = segment_to_text(segment, reader=None) # Should NOT convert - it's a pronoun, not a title assert result == "I am a sentence with the pronoun I in it." def test_roman_numeral_with_period(): """Test Roman numeral with trailing period.""" segment = Segment( segment_id="ch1", file_path=Path("chapter.xhtml"), xpath="/html/body/div/h1", extract_mode=ExtractMode.TEXT, source_content="I.", metadata=SegmentMetadata( element_type="h1", spine_index=1, order_in_file=1 ) ) result = segment_to_text(segment, reader=None) assert result == "One." def test_roman_numeral_with_colon(): """Test Roman numeral with trailing colon.""" segment = Segment( segment_id="ch1", file_path=Path("chapter.xhtml"), xpath="/html/body/div/h1", extract_mode=ExtractMode.TEXT, source_content="V:", metadata=SegmentMetadata( element_type="h1", spine_index=1, order_in_file=1 ) ) result = segment_to_text(segment, reader=None) assert result == "Five:" def test_chapter_prefix_with_roman_numeral(): """Test 'Chapter I' format.""" segment = Segment( segment_id="ch1", file_path=Path("chapter.xhtml"), xpath="/html/body/div/h1", extract_mode=ExtractMode.TEXT, source_content="Chapter I", metadata=SegmentMetadata( element_type="h1", spine_index=1, order_in_file=1 ) ) result = segment_to_text(segment, reader=None) assert result == "Chapter One" def test_part_prefix_with_roman_numeral(): """Test 'Part II' format.""" segment = Segment( segment_id="part2", file_path=Path("part.xhtml"), xpath="/html/body/div/h1", extract_mode=ExtractMode.TEXT, source_content="Part II", metadata=SegmentMetadata( element_type="h1", spine_index=1, order_in_file=1 ) ) result = segment_to_text(segment, reader=None) assert result == "Part Two" def test_book_prefix_with_roman_numeral(): """Test 'Book III' format.""" segment = Segment( segment_id="book3", file_path=Path("book.xhtml"), xpath="/html/body/div/h1", extract_mode=ExtractMode.TEXT, source_content="Book III", metadata=SegmentMetadata( element_type="h1", spine_index=1, order_in_file=1 ) ) result = segment_to_text(segment, reader=None) assert result == "Book Three" def test_first_segment_in_file_converts(): """Test that first segment (order_in_file=1) with Roman numeral converts even if not heading.""" segment = Segment( segment_id="first", file_path=Path("chapter.xhtml"), xpath="/html/body/div/p[1]", extract_mode=ExtractMode.TEXT, source_content="IV", metadata=SegmentMetadata( element_type="p", # Not a heading spine_index=1, order_in_file=1 # But first in file ) ) result = segment_to_text(segment, reader=None) assert result == "Four" def test_non_first_segment_paragraph_not_converted(): """Test that non-first paragraph with 'I' is NOT converted.""" segment = Segment( segment_id="p5", file_path=Path("chapter.xhtml"), xpath="/html/body/div/p[5]", extract_mode=ExtractMode.TEXT, source_content="I", metadata=SegmentMetadata( element_type="p", spine_index=1, order_in_file=5 # Not first ) ) result = segment_to_text(segment, reader=None) # Should NOT convert - not a heading and not first in file assert result == "I" def test_lowercase_roman_numeral_in_heading(): """Test lowercase 'i' in heading converts to 'One'.""" segment = Segment( segment_id="ch1", file_path=Path("chapter.xhtml"), xpath="/html/body/div/h2", extract_mode=ExtractMode.TEXT, source_content="i", metadata=SegmentMetadata( element_type="h2", spine_index=1, order_in_file=1 ) ) result = segment_to_text(segment, reader=None) assert result == "One" def test_mixed_case_roman_numeral(): """Test mixed case 'Iv' normalizes and converts.""" segment = Segment( segment_id="ch4", file_path=Path("chapter.xhtml"), xpath="/html/body/div/h1", extract_mode=ExtractMode.TEXT, source_content="Iv", metadata=SegmentMetadata( element_type="h1", spine_index=1, order_in_file=1 ) ) result = segment_to_text(segment, reader=None) assert result == "Four" def test_invalid_roman_numeral_unchanged(): """Test invalid Roman numeral pattern is unchanged.""" segment = Segment( segment_id="invalid", file_path=Path("chapter.xhtml"), xpath="/html/body/div/h1", extract_mode=ExtractMode.TEXT, source_content="IIII", # Invalid - should be IV metadata=SegmentMetadata( element_type="h1", spine_index=1, order_in_file=1 ) ) result = segment_to_text(segment, reader=None) # Invalid Roman numeral should stay as-is assert result == "IIII"
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/cli/test_debug_analyze_skips.py
Python
from __future__ import annotations from pathlib import Path from click.testing import CliRunner from importlib import import_module def _load_app(): return import_module("cli.main").app def test_debug_analyze_skips_invokes_analysis(monkeypatch, tmp_path) -> None: called = {} def _fake_analyze(settings, library, limit, top_n, report_path): called["library"] = library called["limit"] = limit called["top_n"] = top_n called["report"] = report_path monkeypatch.setattr("debug_tools.analysis.analyze_library", _fake_analyze) runner = CliRunner() result = runner.invoke( _load_app(), [ "debug", "analyze-skips", "--library", str(tmp_path), "--limit", "5", "--top-n", "3", ], ) assert result.exit_code == 0 assert called["library"] == tmp_path assert called["limit"] == 5 assert called["top_n"] == 3
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/cli/test_debug_purge_refusals.py
Python
from pathlib import Path from click.testing import CliRunner from cli.main import app from config import AppSettings from state.models import ( Segment, SegmentMetadata, ExtractMode, SegmentsDocument, StateDocument, TranslationRecord, SegmentStatus, ) from state.store import save_segments, save_state, load_state def _build_segment(segment_id: str, content: str) -> Segment: return Segment( segment_id=segment_id, file_path=Path("chapter.xhtml"), xpath="/html/body/p[1]", extract_mode=ExtractMode.TEXT, source_content=content, metadata=SegmentMetadata(element_type="p", spine_index=0, order_in_file=0), ) def test_purge_refusals_resets_segments(monkeypatch, tmp_path): workspace = tmp_path / "workspace" settings = AppSettings(work_root=workspace, work_dir=workspace, cache_dir=workspace / "cache") settings.ensure_directories() segments = [ _build_segment("seg-1", "1"), _build_segment("seg-2", "正常内容"), ] save_segments( SegmentsDocument( epub_path=tmp_path / "book.epub", generated_at="2025-09-27T00:00:00Z", segments=segments, ), settings.segments_file, ) save_state( StateDocument( segments={ "seg-1": TranslationRecord( segment_id="seg-1", translation="I'm sorry, I can't help with that.", status=SegmentStatus.COMPLETED, provider_name="openai", model_name="gpt-4o", ), "seg-2": TranslationRecord( segment_id="seg-2", translation="正常翻译", status=SegmentStatus.COMPLETED, ), } ), settings.state_file, ) monkeypatch.setattr("cli.core.load_settings_from_cli", lambda path=None: settings) runner = CliRunner() result = runner.invoke(app, ["debug", "purge-refusals"]) assert result.exit_code == 0 state = load_state(settings.state_file) assert state.segments["seg-1"].status == SegmentStatus.PENDING assert state.segments["seg-1"].translation is None assert state.segments["seg-2"].status == SegmentStatus.COMPLETED def test_purge_refusals_dry_run(monkeypatch, tmp_path): workspace = tmp_path / "workspace" settings = AppSettings(work_root=workspace, work_dir=workspace, cache_dir=workspace / "cache") settings.ensure_directories() segments = [_build_segment("seg-1", "1")] save_segments( SegmentsDocument( epub_path=tmp_path / "book.epub", generated_at="2025-09-27T00:00:00Z", segments=segments, ), settings.segments_file, ) save_state( StateDocument( segments={ "seg-1": TranslationRecord( segment_id="seg-1", translation="抱歉,我无法协助处理该内容。", status=SegmentStatus.COMPLETED, ), } ), settings.state_file, ) monkeypatch.setattr("cli.core.load_settings_from_cli", lambda path=None: settings) runner = CliRunner() result = runner.invoke(app, ["debug", "purge-refusals", "--dry-run"]) assert result.exit_code == 0 state = load_state(settings.state_file) assert state.segments["seg-1"].status == SegmentStatus.COMPLETED
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/cli/test_debug_workspace.py
Python
from __future__ import annotations from click.testing import CliRunner from importlib import import_module from config import build_workspace_name from config import models as config_models def _load_app(): return import_module("cli.main").app def test_debug_workspace_command(monkeypatch, tmp_path) -> None: original_root = config_models.DEFAULT_ROOT_DIR config_models.DEFAULT_ROOT_DIR = tmp_path / ".tepub" monkeypatch.setenv("TEPUB_WORK_ROOT", str(tmp_path / ".tepub")) epub_path = tmp_path / "Sample Book.epub" epub_path.touch() try: runner = CliRunner() result = runner.invoke(_load_app(), ["debug", "workspace", str(epub_path)]) # with_book_workspace() derives workspace from EPUB filename (stem) # Expected: "Sample Book" (not slugified "sample-55c5211f") expected_workspace = epub_path.stem # "Sample Book" assert result.exit_code == 0 assert expected_workspace in result.output assert f"{expected_workspace}/segments.json" in result.output finally: config_models.DEFAULT_ROOT_DIR = original_root def test_debug_workspace_respects_cli_override(monkeypatch, tmp_path) -> None: epub_path = tmp_path / "Another.epub" epub_path.touch() override_root = tmp_path / "custom_root" monkeypatch.setenv("TEPUB_WORK_ROOT", str(override_root)) runner = CliRunner() result = runner.invoke(_load_app(), ["--work-dir", str(override_root), "debug", "workspace", str(epub_path)]) # When --work-dir is provided, with_book_workspace() is not used # Instead, the workspace is derived from EPUB filename in parent directory expected_workspace = epub_path.stem # "Another" assert result.exit_code == 0 assert expected_workspace in result.output
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/cli/test_format_command.py
Python
from pathlib import Path from click.testing import CliRunner from cli.main import app from config import AppSettings from state.models import SegmentStatus, StateDocument, TranslationRecord from state.store import save_state def test_format_command_polishes_translations(tmp_path, monkeypatch): settings = AppSettings().model_copy(update={"work_dir": tmp_path, "target_language": "Simplified Chinese"}) settings.ensure_directories() state_path = settings.state_file state = StateDocument( segments={ "seg-1": TranslationRecord( segment_id="seg-1", translation="这是2024年的报告", status=SegmentStatus.COMPLETED, ) }, source_language="auto", target_language="Simplified Chinese", ) save_state(state, state_path) runner = CliRunner() result = runner.invoke(app, ["--work-dir", str(tmp_path), "format"]) assert result.exit_code == 0 assert "Formatted translations saved" in result.output from state.store import load_state new_state = load_state(state_path) assert new_state.segments["seg-1"].translation == "这是 2024 年的报告"
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/config/test_settings.py
Python
from __future__ import annotations from pathlib import Path import pytest from config.loader import load_settings from config.models import AppSettings from exceptions import StateFileNotFoundError, WorkspaceNotFoundError def test_load_settings_reads_config_yaml(monkeypatch, tmp_path) -> None: monkeypatch.chdir(tmp_path) (tmp_path / "config.yaml").write_text( """ work_dir: ./workspace source_language: en target_language: Traditional Chinese """.strip(), encoding="utf-8", ) settings = load_settings() assert settings.work_dir == tmp_path / "workspace" assert settings.source_language == "en" assert settings.target_language == "Traditional Chinese" def test_cli_config_file_overrides_env(monkeypatch, tmp_path, tmp_path_factory) -> None: env_dir = tmp_path / "env" env_dir.mkdir() (env_dir / ".env").write_text("target_language=Spanish\n", encoding="utf-8") yaml_path = tmp_path / "settings.yaml" yaml_path.write_text("target_language: Simplified Chinese\n", encoding="utf-8") monkeypatch.chdir(env_dir) settings = load_settings(config_path=yaml_path) assert settings.target_language == "Simplified Chinese" class TestAppSettingsValidation: """Tests for AppSettings validation methods.""" def test_validate_for_export_succeeds_when_all_files_exist(self, tmp_path): """Test validation passes when all required files exist.""" import json epub_path = tmp_path / "book.epub" epub_path.write_text("fake epub") work_dir = tmp_path / "workspace" work_dir.mkdir() # Create valid segments file segments_data = { "epub_path": str(epub_path), "generated_at": "2024-01-01T00:00:00", "segments": [] } (work_dir / "segments.json").write_text(json.dumps(segments_data)) # Create valid state file state_data = { "provider_name": "test", "model_name": "test-model", "source_language": "en", "target_language": "zh", "segments": {} } (work_dir / "state.json").write_text(json.dumps(state_data)) settings = AppSettings( work_dir=work_dir, segments_file=work_dir / "segments.json", state_file=work_dir / "state.json", ) # Should not raise any exception settings.validate_for_export(epub_path) def test_validate_for_export_raises_when_workspace_missing(self, tmp_path): """Test validation fails when workspace doesn't exist.""" epub_path = tmp_path / "book.epub" epub_path.write_text("fake epub") work_dir = tmp_path / "nonexistent" settings = AppSettings( work_dir=work_dir, segments_file=work_dir / "segments.json", state_file=work_dir / "state.json", ) with pytest.raises(WorkspaceNotFoundError) as exc_info: settings.validate_for_export(epub_path) assert exc_info.value.epub_path == epub_path assert exc_info.value.work_dir == work_dir def test_validate_for_export_raises_when_segments_missing(self, tmp_path): """Test validation fails when segments file missing.""" epub_path = tmp_path / "book.epub" epub_path.write_text("fake epub") work_dir = tmp_path / "workspace" work_dir.mkdir() (work_dir / "state.json").write_text("{}") settings = AppSettings( work_dir=work_dir, segments_file=work_dir / "segments.json", state_file=work_dir / "state.json", ) with pytest.raises(StateFileNotFoundError) as exc_info: settings.validate_for_export(epub_path) assert exc_info.value.state_type == "segments" assert exc_info.value.epub_path == epub_path def test_validate_for_export_raises_when_state_missing(self, tmp_path): """Test validation fails when state file missing.""" epub_path = tmp_path / "book.epub" epub_path.write_text("fake epub") work_dir = tmp_path / "workspace" work_dir.mkdir() (work_dir / "segments.json").write_text("{}") settings = AppSettings( work_dir=work_dir, segments_file=work_dir / "segments.json", state_file=work_dir / "state.json", ) with pytest.raises(StateFileNotFoundError) as exc_info: settings.validate_for_export(epub_path) assert exc_info.value.state_type == "translation" assert exc_info.value.epub_path == epub_path def test_validate_for_translation_succeeds_when_segments_exist(self, tmp_path): """Test translation validation passes when segments file exists.""" import json epub_path = tmp_path / "book.epub" epub_path.write_text("fake epub") work_dir = tmp_path / "workspace" work_dir.mkdir() # Create valid segments file segments_data = { "epub_path": str(epub_path), "generated_at": "2024-01-01T00:00:00", "segments": [] } (work_dir / "segments.json").write_text(json.dumps(segments_data)) settings = AppSettings( work_dir=work_dir, segments_file=work_dir / "segments.json", ) # Should not raise any exception settings.validate_for_translation(epub_path) def test_validate_for_translation_raises_when_workspace_missing(self, tmp_path): """Test translation validation fails when workspace doesn't exist.""" epub_path = tmp_path / "book.epub" epub_path.write_text("fake epub") work_dir = tmp_path / "nonexistent" settings = AppSettings( work_dir=work_dir, segments_file=work_dir / "segments.json", ) with pytest.raises(WorkspaceNotFoundError) as exc_info: settings.validate_for_translation(epub_path) assert exc_info.value.epub_path == epub_path assert exc_info.value.work_dir == work_dir def test_validate_for_translation_raises_when_segments_missing(self, tmp_path): """Test translation validation fails when segments file missing.""" epub_path = tmp_path / "book.epub" epub_path.write_text("fake epub") work_dir = tmp_path / "workspace" work_dir.mkdir() settings = AppSettings( work_dir=work_dir, segments_file=work_dir / "segments.json", ) with pytest.raises(StateFileNotFoundError) as exc_info: settings.validate_for_translation(epub_path) assert exc_info.value.state_type == "segments" assert exc_info.value.epub_path == epub_path
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/config/test_workspace.py
Python
from __future__ import annotations import hashlib from pathlib import Path from config.models import AppSettings from config.workspace import build_workspace_name def test_build_workspace_name_uses_first_word_and_hash() -> None: epub_path = Path("/library/The-Great Book.epub") expected_hash = hashlib.sha1( str(epub_path.expanduser().resolve(strict=False)).encode("utf-8") ).hexdigest()[:8] workspace_name = build_workspace_name(epub_path) assert workspace_name == f"the-{expected_hash}" def test_build_workspace_name_handles_non_ascii() -> None: epub_path = Path("/library/你好.epub") expected_hash = hashlib.sha1( str(epub_path.expanduser().resolve(strict=False)).encode("utf-8") ).hexdigest()[:8] workspace_name = build_workspace_name(epub_path) assert workspace_name == f"book-{expected_hash}" def test_with_book_workspace_derives_directory(tmp_path: Path) -> None: settings = AppSettings(work_root=tmp_path, work_dir=tmp_path) epub_path = tmp_path / "Great Expectations.epub" derived = settings.with_book_workspace(epub_path) expected_dir = tmp_path / "Great Expectations" assert derived.work_dir == expected_dir assert derived.work_root == tmp_path assert derived.segments_file.parent == expected_dir assert derived.state_file.parent == expected_dir def test_with_override_root_creates_hashed_child(tmp_path: Path) -> None: settings = AppSettings(work_root=tmp_path, work_dir=tmp_path) epub_path = tmp_path / "The Book.epub" base_root = tmp_path / "custom" derived = settings.with_override_root(base_root, epub_path) expected_dir = base_root / build_workspace_name(epub_path) assert derived.work_root == base_root assert derived.work_dir == expected_dir def test_with_override_root_detects_existing_workspace(tmp_path: Path) -> None: settings = AppSettings(work_root=tmp_path, work_dir=tmp_path) epub_path = tmp_path / "The Book.epub" existing_workspace = tmp_path / build_workspace_name(epub_path) existing_workspace.mkdir() (existing_workspace / "segments.json").touch() derived = settings.with_override_root(existing_workspace, epub_path) assert derived.work_dir == existing_workspace assert derived.work_root == existing_workspace.parent def test_with_override_root_accepts_matching_name_without_files(tmp_path: Path) -> None: settings = AppSettings(work_root=tmp_path, work_dir=tmp_path) epub_path = tmp_path / "The Book.epub" workspace = tmp_path / build_workspace_name(epub_path) derived = settings.with_override_root(workspace, epub_path) # Since workspace doesn't have segments.json or state.json, it creates a hash-based subdir expected_dir = workspace / build_workspace_name(epub_path) assert derived.work_dir == expected_dir assert derived.work_root == workspace
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/conftest.py
Python
import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT))
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/debug_tools/test_analysis.py
Python
from __future__ import annotations from pathlib import Path from rich.console import Console from config import AppSettings from debug_tools import analysis from epub_io.selector import SkipAnalysis, SkipCandidate def test_analyze_library_summarises_results(monkeypatch, tmp_path) -> None: library = tmp_path / "library" library.mkdir() (library / "book1.epub").touch() (library / "book2.epub").touch() responses = [ SkipAnalysis( candidates=[ SkipCandidate( file_path=Path("Text/cover.xhtml"), spine_index=0, reason="cover", source="toc", ) ], toc_unmatched_titles=["foreword"], ), SkipAnalysis(candidates=[], toc_unmatched_titles=["preface"]), ] iterator = iter(responses) def _fake_analysis(_path, _settings): try: return next(iterator) except StopIteration: return responses[-1] monkeypatch.setattr(analysis, "analyze_skip_candidates", _fake_analysis) class DummyProgress: def __enter__(self): return self def __exit__(self, exc_type, exc, tb): # pragma: no cover - structural return False def add_task(self, *_args, **_kwargs): return 0 def advance(self, *_args, **_kwargs): return None monkeypatch.setattr(analysis, "Progress", DummyProgress) settings = AppSettings(work_root=tmp_path, work_dir=tmp_path) test_console = Console(record=True) monkeypatch.setattr(analysis, "console", test_console) analysis.analyze_library(settings, library, limit=None, top_n=5, report_path=None) output = test_console.export_text() assert "Skip Reasons" in output assert "cover" in output assert "Potential New" in output
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/debug_tools/test_extraction_summary.py
Python
from __future__ import annotations from pathlib import Path from rich.console import Console from config import AppSettings from debug_tools.extraction_summary import print_extraction_summary from state.models import Segment, SegmentMetadata, SegmentsDocument, SkippedDocument, StateDocument, TranslationRecord, SegmentStatus from state.store import save_segments, save_state def _make_segment(idx: int) -> Segment: return Segment( segment_id=f"seg-{idx}", file_path=Path(f"Text/chap{idx}.xhtml"), xpath="/html/body/p[1]", extract_mode="text", # type: ignore[arg-type] source_content=f"Paragraph {idx}", metadata=SegmentMetadata(element_type="p", spine_index=idx, order_in_file=1), ) def test_print_extraction_summary_outputs_tables(monkeypatch, tmp_path): settings = AppSettings(work_root=tmp_path, work_dir=tmp_path) segments = [_make_segment(i) for i in range(3)] document = SegmentsDocument( epub_path=tmp_path / "book.epub", generated_at="2025-09-26T00:00:00Z", segments=segments, skipped_documents=[ SkippedDocument( file_path=Path("Text/front.xhtml"), reason="cover", source="toc", ) ], ) save_segments(document, settings.segments_file) state = StateDocument( segments={ segment.segment_id: TranslationRecord( segment_id=segment.segment_id, status=SegmentStatus.PENDING, ) for segment in segments } ) save_state(state, settings.state_file) test_console = Console(record=True) monkeypatch.setattr("debug_tools.extraction_summary.console", test_console) print_extraction_summary(settings, show_samples=2) output = test_console.export_text() assert "Extraction Summary" in output assert "Text/front.xhtml" in output assert "Pending segments" in output
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/debug_tools/test_skip_lists.py
Python
from __future__ import annotations from pathlib import Path from rich.console import Console from config import AppSettings from debug_tools import skip_lists from state.models import SegmentsDocument, SkippedDocument, StateDocument def test_show_skip_list_displays_auto_skips(monkeypatch, tmp_path) -> None: settings = AppSettings(work_root=tmp_path, work_dir=tmp_path) doc = SegmentsDocument( epub_path=Path("book.epub"), generated_at="2025-01-01T00:00:00Z", segments=[], skipped_documents=[ SkippedDocument( file_path=Path("Text/front.xhtml"), reason="cover", source="toc", ) ], ) state = StateDocument(segments={}) test_console = Console(record=True) monkeypatch.setattr(skip_lists, "console", test_console) monkeypatch.setattr(skip_lists, "load_all_segments", lambda _settings: doc) monkeypatch.setattr(skip_lists, "load_translation_state", lambda _settings: state) skip_lists.show_skip_list(settings) output = test_console.export_text() assert "Automatically Skipped" in output assert "Text/front.xhtml" in output assert "toc" in output
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/epub_io/test_path_utils.py
Python
"""Tests for epub_io.path_utils module.""" from __future__ import annotations from pathlib import Path import pytest from epub_io.path_utils import normalize_epub_href def test_normalize_empty_href(): """Test that empty href returns None.""" result = normalize_epub_href(Path("text/chapter1.xhtml"), "") assert result is None def test_normalize_whitespace_only(): """Test that whitespace-only href returns None.""" result = normalize_epub_href(Path("text/chapter1.xhtml"), " ") assert result is None def test_normalize_none_href(): """Test that None href returns None.""" result = normalize_epub_href(Path("text/chapter1.xhtml"), None) assert result is None def test_normalize_data_uri(): """Test that data URIs are rejected.""" result = normalize_epub_href( Path("text/chapter1.xhtml"), "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA" ) assert result is None def test_normalize_http_url(): """Test that HTTP URLs are rejected.""" result = normalize_epub_href(Path("text/chapter1.xhtml"), "http://example.com/image.jpg") assert result is None def test_normalize_https_url(): """Test that HTTPS URLs are rejected.""" result = normalize_epub_href(Path("text/chapter1.xhtml"), "https://example.com/image.jpg") assert result is None def test_normalize_same_directory(): """Test normalizing href in same directory.""" result = normalize_epub_href(Path("text/chapter1.xhtml"), "image.jpg") assert result == "text/image.jpg" def test_normalize_subdirectory(): """Test normalizing href in subdirectory.""" result = normalize_epub_href(Path("text/chapter1.xhtml"), "images/cover.jpg") assert result == "text/images/cover.jpg" def test_normalize_parent_directory(): """Test normalizing href in parent directory.""" result = normalize_epub_href(Path("text/chapter1.xhtml"), "../images/cover.jpg") assert result == "images/cover.jpg" def test_normalize_root_relative(): """Test normalizing absolute path (relative to EPUB root).""" result = normalize_epub_href(Path("text/chapter1.xhtml"), "/images/cover.jpg") assert result == "images/cover.jpg" def test_normalize_complex_relative(): """Test normalizing complex relative path.""" result = normalize_epub_href( Path("text/part1/chapter1.xhtml"), "../../images/diagrams/fig1.png" ) assert result == "images/diagrams/fig1.png" def test_normalize_dot_segments(): """Test that . segments are normalized.""" result = normalize_epub_href(Path("text/chapter1.xhtml"), "./images/./cover.jpg") assert result == "text/images/cover.jpg" def test_normalize_traversal_outside_root(): """Test that paths traversing outside EPUB root are rejected.""" result = normalize_epub_href(Path("text/chapter1.xhtml"), "../../etc/passwd") assert result is None def test_normalize_traversal_outside_root_complex(): """Test rejection of complex traversal attempts.""" result = normalize_epub_href( Path("text/chapter1.xhtml"), "../../../sensitive/data.txt" ) assert result is None def test_normalize_multiple_slashes(): """Test that multiple slashes are normalized.""" result = normalize_epub_href(Path("text/chapter1.xhtml"), "images//cover.jpg") assert result == "text/images/cover.jpg" def test_normalize_trailing_slash(): """Test href with trailing slash.""" result = normalize_epub_href(Path("text/chapter1.xhtml"), "images/") assert result == "text/images" def test_normalize_from_root_document(): """Test normalizing from document at EPUB root.""" result = normalize_epub_href(Path("index.xhtml"), "images/cover.jpg") assert result == "images/cover.jpg" def test_normalize_deeply_nested_document(): """Test normalizing from deeply nested document.""" result = normalize_epub_href( Path("text/part1/section2/chapter3.xhtml"), "../../../images/cover.jpg" ) assert result == "images/cover.jpg" def test_normalize_preserves_extension(): """Test that file extensions are preserved.""" result = normalize_epub_href(Path("text/chapter1.xhtml"), "diagram.svg") assert result == "text/diagram.svg" def test_normalize_special_characters(): """Test handling of special characters in filenames.""" result = normalize_epub_href(Path("text/chapter1.xhtml"), "image (1).jpg") assert result == "text/image (1).jpg" def test_normalize_unicode_filename(): """Test handling of Unicode characters in filenames.""" result = normalize_epub_href(Path("text/chapter1.xhtml"), "图片.jpg") assert result == "text/图片.jpg" def test_normalize_windows_path_separator(): """Test that backslashes are handled (though uncommon in EPUB).""" # Note: This may vary based on how PurePosixPath handles backslashes result = normalize_epub_href(Path("text/chapter1.xhtml"), r"images\cover.jpg") # Should still work as POSIX path assert result is not None def test_normalize_leading_trailing_whitespace(): """Test that leading/trailing whitespace is stripped.""" result = normalize_epub_href(Path("text/chapter1.xhtml"), " image.jpg ") assert result == "text/image.jpg" def test_normalize_query_string(): """Test href with query string (uncommon but possible).""" result = normalize_epub_href(Path("text/chapter1.xhtml"), "image.jpg?version=2") # Query strings should be preserved in normalized path assert "image.jpg?version=2" in result def test_normalize_anchor_fragment(): """Test that anchor fragments are preserved.""" result = normalize_epub_href(Path("text/chapter1.xhtml"), "chapter2.xhtml#section1") # Fragments should be preserved assert "chapter2.xhtml#section1" in result
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/epub_io/test_reader.py
Python
from __future__ import annotations from pathlib import Path import pytest from config import AppSettings from epub_io.reader import EpubReader, MAX_EPUB_SIZE def test_epub_reader_rejects_missing_file(tmp_path): """Test that EpubReader raises FileNotFoundError for missing files.""" settings = AppSettings(work_dir=tmp_path) missing_epub = tmp_path / "missing.epub" with pytest.raises(FileNotFoundError, match="EPUB file not found"): EpubReader(missing_epub, settings) def test_epub_reader_rejects_oversized_file(tmp_path): """Test that EpubReader raises ValueError for files exceeding MAX_EPUB_SIZE.""" settings = AppSettings(work_dir=tmp_path) large_epub = tmp_path / "large.epub" # Create a file larger than MAX_EPUB_SIZE with open(large_epub, "wb") as f: f.seek(MAX_EPUB_SIZE + 1024) # 500MB + 1KB f.write(b"\0") with pytest.raises(ValueError, match="EPUB file too large"): EpubReader(large_epub, settings) def test_epub_reader_accepts_reasonable_size(tmp_path): """Test that EpubReader accepts files within size limit.""" settings = AppSettings(work_dir=tmp_path) small_epub = tmp_path / "small.epub" # Create a minimal valid ZIP file (EPUB is a ZIP) # This will fail to load as an EPUB, but should pass size validation with open(small_epub, "wb") as f: # Minimal ZIP file structure f.write(b"PK\x03\x04") # Local file header signature f.write(b"\x00" * 26) # Rest of header (26 bytes) # Central directory f.write(b"PK\x01\x02") # Central directory header f.write(b"\x00" * 42) # Rest of CD header # End of central directory f.write(b"PK\x05\x06") # EOCD signature f.write(b"\x00" * 18) # Rest of EOCD # This will fail loading the book, but size validation should pass # We're only testing size validation here try: EpubReader(small_epub, settings) except Exception as e: # Expected: will fail to load as valid EPUB # But should not be a "file too large" error assert "too large" not in str(e).lower()
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/epub_io/test_selector.py
Python
from __future__ import annotations from pathlib import Path from types import SimpleNamespace import pytest from lxml import html from config import AppSettings from epub_io import selector class FakeNav: def __init__(self, title: str, href: str, subitems: list | None = None) -> None: self.title = title self.href = href self.subitems = subitems or [] class FakeItem: def __init__(self, id_: str, file_name: str) -> None: self.id = id_ self.file_name = file_name self.media_type = "application/xhtml+xml" class FakeBook: def __init__(self) -> None: self._items = [ FakeItem("cover", "Text/cover.xhtml"), FakeItem("opening", "Text/opening.xhtml"), FakeItem("preface", "Text/preface.xhtml"), FakeItem("chapter1", "Text/chapter1.xhtml"), ] self.spine = [ ("cover", "yes"), ("opening", "yes"), ("preface", "yes"), ("chapter1", "yes"), ] self.toc = [ FakeNav("Cover", "Text/cover.xhtml"), FakeNav("Opening Remarks", "Text/opening.xhtml"), FakeNav("Preface", "Text/preface.xhtml"), FakeNav("Chapter 1", "Text/chapter1.xhtml"), ] def get_items(self): return self._items class FakeReader: def __init__(self, *_args, **_kwargs): self.book = FakeBook() self._docs = [ SimpleNamespace( path=Path("Text/cover.xhtml"), spine_item=SimpleNamespace(index=0, href=Path("Text/cover.xhtml"), linear=True), tree=html.fromstring("<html><body>Cover Page</body></html>"), ), SimpleNamespace( path=Path("Text/opening.xhtml"), spine_item=SimpleNamespace(index=1, href=Path("Text/opening.xhtml"), linear=True), tree=html.fromstring("<html><body>Opening remarks from the editor.</body></html>"), ), SimpleNamespace( path=Path("Text/preface.xhtml"), spine_item=SimpleNamespace(index=2, href=Path("Text/preface.xhtml"), linear=True), tree=html.fromstring("<html><body>This is the preface of the book.</body></html>"), ), SimpleNamespace( path=Path("Text/chapter1.xhtml"), spine_item=SimpleNamespace(index=3, href=Path("Text/chapter1.xhtml"), linear=True), tree=html.fromstring("<html><body>Acknowledgments and foreword</body></html>"), ), ] def iter_documents(self): for doc in self._docs: yield doc @pytest.fixture def settings(tmp_path): cfg = AppSettings() return cfg.model_copy(update={"work_dir": tmp_path}) def test_collect_skip_candidates_uses_toc_only(monkeypatch, settings): """Test that skip detection only uses TOC titles, not filename/content.""" monkeypatch.setattr(selector, "EpubReader", FakeReader) candidates = selector.collect_skip_candidates(Path("dummy.epub"), settings) # Cover should be detected from TOC title assert any(c.file_path.name == "cover.xhtml" and c.source == "toc" for c in candidates) # chapter1.xhtml has "Acknowledgments" in content but NOT in TOC title # With TOC-only detection, it should NOT be flagged assert not any(c.file_path.name == "chapter1.xhtml" for c in candidates) def test_analyze_skip_candidates_reports_unmatched_titles(monkeypatch, settings): monkeypatch.setattr(selector, "EpubReader", FakeReader) analysis = selector.analyze_skip_candidates(Path("dummy.epub"), settings) assert "opening remarks" in analysis.toc_unmatched_titles def test_skip_after_logic_triggers_cascade(monkeypatch, settings): """Test that cascade skipping activates after back-matter triggers.""" monkeypatch.setattr(selector, "EpubReader", FakeReader) # Enable cascade skipping settings = settings.model_copy(update={"skip_after_back_matter": True}) candidates = selector.collect_skip_candidates(Path("dummy.epub"), settings) # Should have "cover" from TOC (index 0) # Should NOT have cascade skips since our fake book doesn't have back-matter triggers assert any(c.source == "toc" for c in candidates) assert not any(c.source == "cascade" for c in candidates) def test_skip_after_logic_can_be_disabled(monkeypatch, settings): """Test that cascade skipping can be disabled via configuration.""" monkeypatch.setattr(selector, "EpubReader", FakeReader) # Disable cascade skipping settings = settings.model_copy(update={"skip_after_back_matter": False}) candidates = selector.collect_skip_candidates(Path("dummy.epub"), settings) # Should only have TOC-based skips, no cascade assert all(c.source != "cascade" for c in candidates)
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/epub_io/test_toc_utils.py
Python
"""Tests for epub_io.toc_utils module.""" from __future__ import annotations from unittest.mock import Mock import pytest from epub_io.toc_utils import parse_toc_to_dict class MockLink: """Mock EPUB Link object.""" def __init__(self, href: str, title: str): self.href = href self.title = title def test_parse_toc_empty(): """Test parsing empty TOC returns empty dict.""" reader = Mock() reader.book.toc = [] result = parse_toc_to_dict(reader) assert result == {} def test_parse_toc_none(): """Test parsing None TOC returns empty dict.""" reader = Mock() reader.book.toc = None result = parse_toc_to_dict(reader) assert result == {} def test_parse_toc_single_link(): """Test parsing single TOC link.""" reader = Mock() reader.book.toc = [MockLink("chapter1.xhtml", "Chapter 1")] result = parse_toc_to_dict(reader) assert result == {"chapter1.xhtml": "Chapter 1"} def test_parse_toc_multiple_links(): """Test parsing multiple TOC links.""" reader = Mock() reader.book.toc = [ MockLink("intro.xhtml", "Introduction"), MockLink("chapter1.xhtml", "Chapter 1"), MockLink("chapter2.xhtml", "Chapter 2"), ] result = parse_toc_to_dict(reader) assert result == { "intro.xhtml": "Introduction", "chapter1.xhtml": "Chapter 1", "chapter2.xhtml": "Chapter 2", } def test_parse_toc_fragment_removal(): """Test that fragments are removed from hrefs.""" reader = Mock() reader.book.toc = [ MockLink("chapter1.xhtml#section1", "Section 1"), MockLink("chapter1.xhtml#section2", "Section 2"), MockLink("chapter2.xhtml#intro", "Chapter 2 Intro"), ] result = parse_toc_to_dict(reader) # Multiple fragments for same file should keep last title assert "chapter1.xhtml" in result assert result["chapter2.xhtml"] == "Chapter 2 Intro" def test_parse_toc_nested_tuple(): """Test parsing nested tuple structure (older EpubPy format).""" reader = Mock() reader.book.toc = [ (MockLink("part1.xhtml", "Part 1"), [ MockLink("chapter1.xhtml", "Chapter 1"), MockLink("chapter2.xhtml", "Chapter 2"), ]), ] result = parse_toc_to_dict(reader) assert result == { "part1.xhtml": "Part 1", "chapter1.xhtml": "Chapter 1", "chapter2.xhtml": "Chapter 2", } def test_parse_toc_deeply_nested(): """Test parsing deeply nested TOC.""" reader = Mock() reader.book.toc = [ (MockLink("part1.xhtml", "Part 1"), [ (MockLink("chapter1.xhtml", "Chapter 1"), [ MockLink("section1.xhtml", "Section 1.1"), MockLink("section2.xhtml", "Section 1.2"), ]), ]), ] result = parse_toc_to_dict(reader) assert result == { "part1.xhtml": "Part 1", "chapter1.xhtml": "Chapter 1", "section1.xhtml": "Section 1.1", "section2.xhtml": "Section 1.2", } def test_parse_toc_empty_title(): """Test handling of empty titles.""" reader = Mock() reader.book.toc = [ MockLink("chapter1.xhtml", ""), MockLink("chapter2.xhtml", "Chapter 2"), ] result = parse_toc_to_dict(reader) assert result == { "chapter1.xhtml": "", "chapter2.xhtml": "Chapter 2", } def test_parse_toc_none_title(): """Test handling of None titles.""" link = Mock() link.href = "chapter1.xhtml" link.title = None reader = Mock() reader.book.toc = [link] result = parse_toc_to_dict(reader) # None titles should be preserved as empty string assert "chapter1.xhtml" in result def test_parse_toc_missing_attributes(): """Test handling of items without href or title attributes.""" invalid_item = Mock(spec=[]) # No href or title attributes reader = Mock() reader.book.toc = [ MockLink("chapter1.xhtml", "Chapter 1"), invalid_item, MockLink("chapter2.xhtml", "Chapter 2"), ] result = parse_toc_to_dict(reader) # Should skip invalid item and process valid ones assert result == { "chapter1.xhtml": "Chapter 1", "chapter2.xhtml": "Chapter 2", } def test_parse_toc_mixed_formats(): """Test handling of mixed link and tuple formats.""" reader = Mock() reader.book.toc = [ MockLink("intro.xhtml", "Introduction"), (MockLink("part1.xhtml", "Part 1"), [ MockLink("chapter1.xhtml", "Chapter 1"), ]), MockLink("epilogue.xhtml", "Epilogue"), ] result = parse_toc_to_dict(reader) assert result == { "intro.xhtml": "Introduction", "part1.xhtml": "Part 1", "chapter1.xhtml": "Chapter 1", "epilogue.xhtml": "Epilogue", }
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/epub_io/test_writer.py
Python
from pathlib import Path, PurePosixPath from ebooklib import epub from epub_io import writer def test_write_updated_epub_updates_toc(monkeypatch, tmp_path): book = epub.EpubBook() html_item = epub.EpubHtml(uid="ch1", file_name="Text/ch1.xhtml", content="<h1 id='t'>Original</h1>") book.add_item(html_item) book.spine = [html_item] book.toc = [epub.Link("Text/ch1.xhtml#t", "Original", "ch1")] monkeypatch.setattr(writer, "load_book", lambda path: book) monkeypatch.setattr( writer, "get_item_by_href", lambda b, href: html_item, ) updated_html = {Path("Text/ch1.xhtml"): "<h1 id='t'>Título</h1>".encode("utf-8")} toc_updates = {PurePosixPath("Text/ch1.xhtml"): {"t": "Título", None: "Título"}} output_path = tmp_path / "out.epub" writer.write_updated_epub( tmp_path / "in.epub", output_path, updated_html, toc_updates=toc_updates, css_mode="translated_only", ) assert book.toc[0].title == "Título" def test_write_updated_epub_injects_translated_only_css(monkeypatch, tmp_path): book = epub.EpubBook() html_item = epub.EpubHtml(uid="ch1", file_name="Text/ch1.xhtml", content="<p data-lang='original'>Hi</p>") css_item = epub.EpubItem( uid="style", file_name="Styles/style.css", media_type="text/css", content="body { font-family: serif; }".encode("utf-8"), ) book.add_item(html_item) book.add_item(css_item) book.spine = [html_item] book.toc = [epub.Link("Text/ch1.xhtml", "Original", "ch1")] monkeypatch.setattr(writer, "load_book", lambda path: book) monkeypatch.setattr( writer, "get_item_by_href", lambda b, href: html_item, ) updated_html = {Path("Text/ch1.xhtml"): "<p data-lang='translation'>你好</p>".encode("utf-8")} output_path = tmp_path / "out.epub" writer.write_updated_epub( tmp_path / "in.epub", output_path, updated_html, css_mode="translated_only", ) css_content = css_item.get_content().decode("utf-8") assert "[data-lang=\"original\"]" in css_content
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/extraction/test_epub_export.py
Python
"""Tests for EPUB structure extraction.""" from __future__ import annotations import zipfile from pathlib import Path import pytest from extraction.epub_export import extract_epub_structure, get_epub_metadata_files def create_test_epub(epub_path: Path) -> None: """Create a minimal valid EPUB for testing.""" with zipfile.ZipFile(epub_path, 'w', zipfile.ZIP_DEFLATED) as epub: # mimetype must be first and uncompressed epub.writestr('mimetype', 'application/epub+zip', compress_type=zipfile.ZIP_STORED) # META-INF/container.xml container_xml = '''<?xml version="1.0"?> <container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container"> <rootfiles> <rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/> </rootfiles> </container>''' epub.writestr('META-INF/container.xml', container_xml) # OEBPS/content.opf content_opf = '''<?xml version="1.0"?> <package xmlns="http://www.idpf.org/2007/opf" version="2.0" unique-identifier="bookid"> <metadata xmlns:dc="http://purl.org/dc/elements/1.1/"> <dc:title>Test Book</dc:title> <dc:identifier id="bookid">test-123</dc:identifier> <dc:language>en</dc:language> </metadata> <manifest> <item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml"/> <item id="text1" href="text00000.html" media-type="application/xhtml+xml"/> </manifest> <spine toc="ncx"> <itemref idref="text1"/> </spine> </package>''' epub.writestr('OEBPS/content.opf', content_opf) # OEBPS/toc.ncx toc_ncx = '''<?xml version="1.0"?> <ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1"> <head> <meta name="dtb:uid" content="test-123"/> </head> <docTitle><text>Test Book</text></docTitle> <navMap> <navPoint id="navpoint-1" playOrder="1"> <navLabel><text>Chapter 1</text></navLabel> <content src="text00000.html"/> </navPoint> </navMap> </ncx>''' epub.writestr('OEBPS/toc.ncx', toc_ncx) # OEBPS/text00000.html html_content = '''<?xml version="1.0"?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head><title>Chapter 1</title></head> <body><h1>Chapter 1</h1><p>Test content.</p></body> </html>''' epub.writestr('OEBPS/text00000.html', html_content) # Add a style file css_content = 'body { font-family: serif; }' epub.writestr('OEBPS/styles.css', css_content) class TestExtractEpubStructure: """Tests for extract_epub_structure function.""" def test_extracts_all_files(self, tmp_path): """Test that all files from EPUB are extracted.""" epub_path = tmp_path / "test.epub" create_test_epub(epub_path) output_dir = tmp_path / "extracted" mapping = extract_epub_structure(epub_path, output_dir) # Check that all expected files are in mapping expected_files = { 'mimetype', 'META-INF/container.xml', 'OEBPS/content.opf', 'OEBPS/toc.ncx', 'OEBPS/text00000.html', 'OEBPS/styles.css', } assert set(mapping.keys()) == expected_files def test_preserves_directory_structure(self, tmp_path): """Test that directory structure is preserved.""" epub_path = tmp_path / "test.epub" create_test_epub(epub_path) output_dir = tmp_path / "extracted" mapping = extract_epub_structure(epub_path, output_dir, preserve_structure=True) # Check that files are in correct directories assert mapping['mimetype'] == output_dir / 'mimetype' assert mapping['META-INF/container.xml'] == output_dir / 'META-INF' / 'container.xml' assert mapping['OEBPS/content.opf'] == output_dir / 'OEBPS' / 'content.opf' # Verify files actually exist assert (output_dir / 'mimetype').exists() assert (output_dir / 'META-INF' / 'container.xml').exists() assert (output_dir / 'OEBPS' / 'content.opf').exists() def test_file_contents_are_correct(self, tmp_path): """Test that extracted files have correct contents.""" epub_path = tmp_path / "test.epub" create_test_epub(epub_path) output_dir = tmp_path / "extracted" mapping = extract_epub_structure(epub_path, output_dir) # Check mimetype content mimetype_content = mapping['mimetype'].read_text() assert mimetype_content == 'application/epub+zip' # Check that HTML file contains expected text html_content = mapping['OEBPS/text00000.html'].read_text() assert 'Chapter 1' in html_content assert 'Test content' in html_content # Check CSS content css_content = mapping['OEBPS/styles.css'].read_text() assert 'font-family: serif' in css_content def test_creates_output_directory_if_missing(self, tmp_path): """Test that output directory is created if it doesn't exist.""" epub_path = tmp_path / "test.epub" create_test_epub(epub_path) output_dir = tmp_path / "deep" / "nested" / "extracted" assert not output_dir.exists() extract_epub_structure(epub_path, output_dir) assert output_dir.exists() assert (output_dir / 'mimetype').exists() def test_raises_error_for_missing_epub(self, tmp_path): """Test that FileNotFoundError is raised for missing EPUB.""" epub_path = tmp_path / "nonexistent.epub" output_dir = tmp_path / "extracted" with pytest.raises(FileNotFoundError): extract_epub_structure(epub_path, output_dir) def test_raises_error_for_invalid_epub(self, tmp_path): """Test that BadZipFile is raised for invalid EPUB.""" epub_path = tmp_path / "invalid.epub" epub_path.write_text("This is not a valid EPUB file") output_dir = tmp_path / "extracted" with pytest.raises(zipfile.BadZipFile): extract_epub_structure(epub_path, output_dir) def test_flattened_extraction(self, tmp_path): """Test extraction without preserving directory structure.""" epub_path = tmp_path / "test.epub" create_test_epub(epub_path) output_dir = tmp_path / "extracted" mapping = extract_epub_structure(epub_path, output_dir, preserve_structure=False) # All files should be in the root output directory assert mapping['mimetype'] == output_dir / 'mimetype' assert mapping['META-INF/container.xml'] == output_dir / 'container.xml' assert mapping['OEBPS/content.opf'] == output_dir / 'content.opf' assert mapping['OEBPS/text00000.html'] == output_dir / 'text00000.html' # Verify no subdirectories were created subdirs = [d for d in output_dir.iterdir() if d.is_dir()] assert len(subdirs) == 0 class TestGetEpubMetadataFiles: """Tests for get_epub_metadata_files function.""" def test_identifies_key_metadata_files(self, tmp_path): """Test that key metadata files are correctly identified.""" epub_path = tmp_path / "test.epub" create_test_epub(epub_path) output_dir = tmp_path / "extracted" mapping = extract_epub_structure(epub_path, output_dir) metadata = get_epub_metadata_files(mapping) # Check that all key files are identified assert 'mimetype' in metadata assert 'container' in metadata assert 'opf' in metadata assert 'ncx' in metadata # Verify paths are correct assert metadata['mimetype'] == output_dir / 'mimetype' assert metadata['container'] == output_dir / 'META-INF' / 'container.xml' assert metadata['opf'] == output_dir / 'OEBPS' / 'content.opf' assert metadata['ncx'] == output_dir / 'OEBPS' / 'toc.ncx' def test_handles_missing_files_gracefully(self, tmp_path): """Test that missing metadata files don't cause errors.""" # Create mapping with only some files mapping = { 'mimetype': tmp_path / 'mimetype', 'OEBPS/text.html': tmp_path / 'OEBPS' / 'text.html', } metadata = get_epub_metadata_files(mapping) # Should have mimetype but not others assert 'mimetype' in metadata assert 'container' not in metadata assert 'opf' not in metadata assert 'ncx' not in metadata def test_case_insensitive_matching(self, tmp_path): """Test that file matching is case-insensitive for container.xml.""" mapping = { 'META-INF/Container.XML': tmp_path / 'META-INF' / 'Container.XML', 'OEBPS/Content.OPF': tmp_path / 'OEBPS' / 'Content.OPF', } metadata = get_epub_metadata_files(mapping) assert 'container' in metadata assert 'opf' in metadata
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/extraction/test_image_export.py
Python
from pathlib import Path from types import SimpleNamespace from extraction.image_export import ( _is_image_item, _is_potential_cover, extract_images, get_image_mapping, ) def test_is_image_item(): # Mock item with media_type item_image = SimpleNamespace(media_type="image/jpeg", file_name="test.jpg") assert _is_image_item(item_image) is True item_text = SimpleNamespace(media_type="text/html", file_name="test.html") assert _is_image_item(item_text) is False # Mock item with only filename item_png = SimpleNamespace(file_name="image.png") assert _is_image_item(item_png) is True item_txt = SimpleNamespace(file_name="readme.txt") assert _is_image_item(item_txt) is False def test_is_potential_cover(): assert _is_potential_cover(Path("images/cover.jpg"), False) is True assert _is_potential_cover(Path("images/title.png"), False) is True assert _is_potential_cover(Path("images/first.jpg"), True) is True assert _is_potential_cover(Path("images/diagram.jpg"), False) is False def test_extract_images(tmp_path): """Test image extraction with mock EPUB.""" # Create mock items mock_items = [ SimpleNamespace( media_type="image/jpeg", file_name="images/cover.jpg", get_content=lambda: b"fake-jpg-data", ), SimpleNamespace( media_type="image/png", file_name="images/fig1.png", get_content=lambda: b"fake-png-data", ), SimpleNamespace( media_type="text/html", file_name="chapter.html", get_content=lambda: b"<html></html>", ), ] # Mock book mock_book = SimpleNamespace(get_items=lambda: mock_items) # Mock reader mock_reader = SimpleNamespace(book=mock_book) # Mock settings settings = SimpleNamespace() # Patch EpubReader to return mock from extraction import image_export original_reader = image_export.EpubReader def mock_epub_reader(epub_path, settings): return mock_reader image_export.EpubReader = mock_epub_reader try: # Extract images output_dir = tmp_path / "images" epub_path = tmp_path / "test.epub" extracted = extract_images(settings, epub_path, output_dir) # Verify results assert len(extracted) == 2 assert (output_dir / "cover.jpg").exists() assert (output_dir / "fig1.png").exists() # Verify cover candidate detection cover_candidates = [img for img in extracted if img.is_cover_candidate] assert len(cover_candidates) >= 1 assert any("cover" in img.epub_path.name for img in cover_candidates) finally: image_export.EpubReader = original_reader def test_get_image_mapping(): from extraction.image_export import ImageInfo images = [ ImageInfo( epub_path=Path("images/cover.jpg"), extracted_path=Path("/tmp/cover.jpg"), is_cover_candidate=True, ), ImageInfo( epub_path=Path("images/fig1.png"), extracted_path=Path("/tmp/fig1.png"), is_cover_candidate=False, ), ] mapping = get_image_mapping(images) assert mapping["images/cover.jpg"] == "cover.jpg" assert mapping["images/fig1.png"] == "fig1.png"
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/extraction/test_markdown_export.py
Python
from pathlib import Path from types import SimpleNamespace import pytest from ebooklib import epub from extraction.markdown_export import ( _sanitize_filename, _html_to_markdown, export_to_markdown, export_combined_markdown, ) from epub_io.reader import EpubReader from epub_io.toc_utils import parse_toc_to_dict from epub_io.path_utils import normalize_epub_href from state.models import ExtractMode, Segment, SegmentMetadata, SegmentsDocument from state.store import save_segments def test_sanitize_filename(): assert _sanitize_filename("Chapter 1: Introduction") == "chapter-1-introduction" assert _sanitize_filename("File/Path\\Test") == "filepathtest" assert _sanitize_filename(" Spaces ") == "spaces" assert _sanitize_filename("A" * 100) == "a" * 50 assert _sanitize_filename("") == "untitled" assert _sanitize_filename("!!!") == "untitled" def test_normalize_image_href(): assert normalize_epub_href(Path("Text/ch1.xhtml"), "../images/fig1.png") == "images/fig1.png" assert normalize_epub_href(Path("Text/ch1.xhtml"), "images/fig1.png") == "Text/images/fig1.png" assert normalize_epub_href(Path("Text/ch1.xhtml"), "/images/fig1.png") == "images/fig1.png" assert normalize_epub_href(Path("Text/ch1.xhtml"), "data:image/png;base64,abc") is None assert normalize_epub_href(Path("Text/ch1.xhtml"), "http://example.com/img.jpg") is None def test_html_to_markdown_with_images(): html = '<p>Text before <img src="../images/fig1.png" alt="Figure 1"/> text after</p>' image_mapping = {"images/fig1.png": "fig1.png"} result = _html_to_markdown(html, Path("Text/ch1.xhtml"), image_mapping) assert "![Figure 1](images/fig1.png)" in result assert "Text before" in result assert "text after" in result def test_html_to_markdown_without_images(): html = "<p>Hello <b>world</b></p>" result = _html_to_markdown(html, Path("Text/ch1.xhtml"), {}) assert "Hello" in result assert "world" in result def test_parse_toc_with_mock_reader(tmp_path, monkeypatch): """Test TOC parsing with a mock epub book.""" # Create mock TOC structure link1 = epub.Link("Text/ch1.xhtml", "Chapter 1", "ch1") link2 = epub.Link("Text/ch2.xhtml#section", "Chapter 2", "ch2") nested = epub.Link("Text/ch3.xhtml", "Chapter 3", "ch3") mock_book = SimpleNamespace(toc=[link1, link2, (nested, [])]) # Create mock reader mock_reader = SimpleNamespace(book=mock_book) toc_map = parse_toc_to_dict(mock_reader) assert toc_map["Text/ch1.xhtml"] == "Chapter 1" assert toc_map["Text/ch2.xhtml"] == "Chapter 2" assert toc_map["Text/ch3.xhtml"] == "Chapter 3" def test_export_to_markdown(tmp_path, monkeypatch): """Test full markdown export with segments.""" # Create test segments segments = [ Segment( segment_id="seg-1", file_path=Path("Text/ch1.xhtml"), xpath="/html/body/p[1]", extract_mode=ExtractMode.TEXT, source_content="First paragraph in chapter 1.", metadata=SegmentMetadata(element_type="p", spine_index=0, order_in_file=1), ), Segment( segment_id="seg-2", file_path=Path("Text/ch1.xhtml"), xpath="/html/body/p[2]", extract_mode=ExtractMode.TEXT, source_content="Second paragraph in chapter 1.", metadata=SegmentMetadata(element_type="p", spine_index=0, order_in_file=2), ), Segment( segment_id="seg-3", file_path=Path("Text/ch2.xhtml"), xpath="/html/body/p[1]", extract_mode=ExtractMode.TEXT, source_content="First paragraph in chapter 2.", metadata=SegmentMetadata(element_type="p", spine_index=1, order_in_file=1), ), ] # Save segments work_dir = tmp_path / ".tepub" work_dir.mkdir() segments_file = work_dir / "segments.json" segments_doc = SegmentsDocument( epub_path=tmp_path / "test.epub", generated_at="2024-01-01T00:00:00", segments=segments, ) save_segments(segments_doc, segments_file) # Create mock settings settings = SimpleNamespace(segments_file=segments_file) # Mock TOC link1 = epub.Link("Text/ch1.xhtml", "Introduction", "ch1") link2 = epub.Link("Text/ch2.xhtml", "Chapter Two", "ch2") # Mock spine items mock_item1 = SimpleNamespace(id="ch1", file_name="Text/ch1.xhtml", media_type="application/xhtml+xml") mock_item2 = SimpleNamespace(id="ch2", file_name="Text/ch2.xhtml", media_type="application/xhtml+xml") mock_spine = [("ch1", "yes"), ("ch2", "yes")] mock_book = SimpleNamespace( toc=[link1, link2], spine=mock_spine ) def mock_get_items(): return [mock_item1, mock_item2] mock_book.get_items = mock_get_items # Mock EpubReader to return our mock book def mock_reader_init(self, epub_path, settings): self.epub_path = epub_path self.settings = settings self.book = mock_book monkeypatch.setattr(EpubReader, "__init__", mock_reader_init) # Export markdown mock_epub = tmp_path / "test.epub" output_dir = tmp_path / "markdown" created_files = export_to_markdown(settings, mock_epub, output_dir) # Verify output assert len(created_files) == 2 assert created_files[0].name == "001_introduction.md" assert created_files[1].name == "002_chapter-two.md" # Check content content1 = created_files[0].read_text() assert "# Introduction" in content1 assert "First paragraph in chapter 1." in content1 assert "Second paragraph in chapter 1." in content1 content2 = created_files[1].read_text() assert "# Chapter Two" in content2 assert "First paragraph in chapter 2." in content2 def test_export_combined_markdown(tmp_path, monkeypatch): """Test combined markdown export.""" # Create test segments segments = [ Segment( segment_id="seg-1", file_path=Path("Text/ch1.xhtml"), xpath="/html/body/p[1]", extract_mode=ExtractMode.TEXT, source_content="First paragraph in chapter 1.", metadata=SegmentMetadata(element_type="p", spine_index=0, order_in_file=1), ), Segment( segment_id="seg-2", file_path=Path("Text/ch2.xhtml"), xpath="/html/body/p[1]", extract_mode=ExtractMode.TEXT, source_content="First paragraph in chapter 2.", metadata=SegmentMetadata(element_type="p", spine_index=1, order_in_file=1), ), ] # Save segments work_dir = tmp_path / ".tepub" work_dir.mkdir() segments_file = work_dir / "segments.json" segments_doc = SegmentsDocument( epub_path=tmp_path / "test-book.epub", generated_at="2024-01-01T00:00:00", segments=segments, ) save_segments(segments_doc, segments_file) # Create mock settings settings = SimpleNamespace(segments_file=segments_file) # Mock TOC link1 = epub.Link("Text/ch1.xhtml", "Introduction", "ch1") link2 = epub.Link("Text/ch2.xhtml", "Chapter Two", "ch2") # Mock spine items mock_item1 = SimpleNamespace(id="ch1", file_name="Text/ch1.xhtml", media_type="application/xhtml+xml") mock_item2 = SimpleNamespace(id="ch2", file_name="Text/ch2.xhtml", media_type="application/xhtml+xml") mock_spine = [("ch1", "yes"), ("ch2", "yes")] mock_book = SimpleNamespace( toc=[link1, link2], spine=mock_spine ) def mock_get_items(): return [mock_item1, mock_item2] mock_book.get_items = mock_get_items # Mock EpubReader def mock_reader_init(self, epub_path, settings): self.epub_path = epub_path self.settings = settings self.book = mock_book monkeypatch.setattr(EpubReader, "__init__", mock_reader_init) # Export combined markdown mock_epub = tmp_path / "test-book.epub" output_dir = tmp_path / "markdown" combined_file = export_combined_markdown(settings, mock_epub, output_dir) # Verify combined file assert combined_file.name == "test-book.md" assert combined_file.exists() # Check content content = combined_file.read_text() assert "# " in content # Book title assert "## Introduction" in content assert "## Chapter Two" in content assert "First paragraph in chapter 1." in content assert "First paragraph in chapter 2." in content assert "---" in content # Chapter separator
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/extraction/test_segments.py
Python
import re from pathlib import Path from lxml import html from extraction.segments import iter_segments from state.models import ExtractMode def test_iter_segments_classifies_simple_and_atomic(): markup = """ <html><body> <h1>Chapter One</h1> <p>Paragraph text.</p> <div>Inline <em>emphasis</em>.</div> <ul><li>Item <span>One</span></li><li>Item Two</li></ul> </body></html> """ tree = html.fromstring(markup) segments = list(iter_segments(tree, Path("chapter1.xhtml"), spine_index=0)) assert len(segments) == 4 heading = segments[0] assert heading.extract_mode == ExtractMode.TEXT assert heading.source_content == "Chapter One" list_segment = segments[-1] assert list_segment.extract_mode == ExtractMode.HTML assert "<span" not in list_segment.source_content assert "Item One" in list_segment.source_content def test_iter_segments_handles_drop_cap(): """Test that drop cap pattern (decorative first letter) extracts correctly.""" markup = """ <html><body> <p><span class="drop"><span class="big">T</span></span>he fantasy always runs like this.</p> <p>Normal paragraph without drop cap.</p> <p><span><span>A</span></span>nother drop cap example.</p> </body></html> """ tree = html.fromstring(markup) segments = list(iter_segments(tree, Path("test.xhtml"), spine_index=0)) assert len(segments) == 3 # First paragraph with drop cap should extract as "The fantasy..." not "T he fantasy..." assert segments[0].source_content == "The fantasy always runs like this." # Normal paragraph assert segments[1].source_content == "Normal paragraph without drop cap." # Another drop cap assert segments[2].source_content == "Another drop cap example." def test_iter_segments_normalizes_ellipsis(): """Test that spaced ellipsis patterns are normalized to standard ellipsis.""" markup = """ <html><body> <p>Text before . . . and after.</p> <p>Multiple . . . . dots here.</p> <p>Already correct... format.</p> <p>Mix of . . . and ... patterns.</p> </body></html> """ tree = html.fromstring(markup) segments = list(iter_segments(tree, Path("test.xhtml"), spine_index=0)) assert len(segments) == 4 # Spaced ellipsis should be normalized to ... assert segments[0].source_content == "Text before ... and after." assert segments[1].source_content == "Multiple ... dots here." assert segments[2].source_content == "Already correct... format." assert segments[3].source_content == "Mix of ... and ... patterns." def test_iter_segments_nested_blockquote_only_innermost_has_text(): """Extract only innermost when outer levels are empty wrappers.""" markup = """ <html><body> <blockquote><blockquote><blockquote> Centuries to Millennia Before </blockquote></blockquote></blockquote> </body></html> """ tree = html.fromstring(markup) segments = list(iter_segments(tree, Path("test.xhtml"), spine_index=0)) # Only innermost blockquote has text, outer levels are wrappers assert len(segments) == 1 assert segments[0].source_content == "Centuries to Millennia Before" assert segments[0].metadata.element_type == "blockquote" def test_iter_segments_nested_blockquote_multiple_levels_have_text(): """Extract all levels that have their own text content.""" markup = """ <html><body> <blockquote> Outer level text <blockquote>Inner level text</blockquote> </blockquote> </body></html> """ tree = html.fromstring(markup) segments = list(iter_segments(tree, Path("test.xhtml"), spine_index=0)) # Both levels have text assert len(segments) == 2 contents = [s.source_content for s in segments] assert "Outer level text Inner level text" in contents # Outer (includes inner) assert "Inner level text" in contents # Inner def test_iter_segments_nested_blockquote_mixed(): """Extract only levels with text, skip empty wrappers.""" markup = """ <html><body> <blockquote> <blockquote> Middle level text <blockquote>Innermost text</blockquote> </blockquote> </blockquote> </body></html> """ tree = html.fromstring(markup) segments = list(iter_segments(tree, Path("test.xhtml"), spine_index=0)) # Outer has no own text (skip), middle and innermost have text (extract) assert len(segments) == 2 contents = [s.source_content for s in segments] # Middle level includes innermost assert any("Middle level text" in c and "Innermost text" in c for c in contents) # Innermost only assert "Innermost text" in contents def test_iter_segments_nested_div_smart_extraction(): """Test smart extraction works for nested divs too.""" markup = """ <html><body> <div> <div>Actual content</div> </div> </body></html> """ tree = html.fromstring(markup) segments = list(iter_segments(tree, Path("test.xhtml"), spine_index=0)) # Only inner div has text assert len(segments) == 1 assert segments[0].source_content == "Actual content" assert segments[0].metadata.element_type == "div" def _normalize_html(value: str) -> str: return re.sub(r"\s+", "", value) def test_iter_segments_handles_complex_markup(): markup = """ <html xmlns='http://www.w3.org/1999/xhtml' xmlns:epub='http://www.idpf.org/2007/ops'> <body> <section epub:type='frontmatter' id='fm'> <h2 class='heading'>Preface &amp; Overview</h2> <p id='p1' class='lead'>This <span>preface</span> has <a href='#'>links</a> &amp; inline elements.</p> <div id='blurb' style='color:red;'>Solo text block.</div> <div class='skip'><p>Nested paragraph should not produce div segment.</p></div> <table id='stats' class='table table-striped' style='width:100%'> <thead> <tr><th scope='col'>Year</th><th>Sales</th></tr> </thead> <tbody> <tr class='row'> <td data-label='Year'><span>2024</span></td> <td><span>10k</span></td> </tr> <tr> <td>2025</td> <td><span>12k</span></td> </tr> </tbody> </table> <ul class='bullet-list' id='points'> <li><span>First</span> point</li> <li>Second <strong>point</strong> <ul> <li>Nested should be ignored</li> </ul> </li> </ul> <epub:switch> <epub:case><p>Namespaced case paragraph.</p></epub:case> </epub:switch> </section> </body> </html> """ tree = html.fromstring(markup) segments = list(iter_segments(tree, Path("complex.xhtml"), spine_index=2)) assert len(segments) == 7 assert [segment.metadata.element_type for segment in segments] == [ "h2", "p", "div", "p", "table", "ul", "p", ] for index, segment in enumerate(segments, start=1): assert segment.metadata.order_in_file == index assert segment.metadata.spine_index == 2 heading, first_para, blurb_div, nested_para, table_seg, list_seg, namespaced_para = segments assert heading.extract_mode == ExtractMode.TEXT assert heading.source_content == "Preface & Overview" assert first_para.extract_mode == ExtractMode.TEXT assert first_para.source_content == "This preface has links & inline elements." assert blurb_div.extract_mode == ExtractMode.TEXT assert blurb_div.source_content == "Solo text block." assert nested_para.extract_mode == ExtractMode.TEXT assert nested_para.source_content == "Nested paragraph should not produce div segment." assert table_seg.extract_mode == ExtractMode.HTML expected_table = ( "<thead><tr><th>Year</th><th>Sales</th></tr></thead>" "<tbody><tr><td>2024</td><td>10k</td></tr><tr><td>2025</td><td>12k</td></tr></tbody>" ) assert _normalize_html(table_seg.source_content) == _normalize_html(expected_table) assert "span" not in table_seg.source_content assert "class=" not in table_seg.source_content assert list_seg.extract_mode == ExtractMode.HTML expected_list = ( "<li>First point</li>" "<li>Second <strong>point</strong><ul><li>Nested should be ignored</li></ul></li>" ) assert _normalize_html(list_seg.source_content) == _normalize_html(expected_list) assert "span" not in list_seg.source_content assert "class=" not in list_seg.source_content assert namespaced_para.extract_mode == ExtractMode.TEXT assert namespaced_para.source_content == "Namespaced case paragraph."
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/injection/test_engine.py
Python
from collections import defaultdict from pathlib import Path, PurePosixPath from types import SimpleNamespace from lxml import html from injection.engine import _apply_translations_to_document, _group_translated_segments from state.models import ExtractMode, Segment, SegmentMetadata, SegmentStatus, TranslationRecord def test_apply_translations_inserts_translation_node(): markup = "<html><body><p>Original text</p></body></html>" tree = html.fromstring(markup) document = SimpleNamespace(tree=tree, spine_item=SimpleNamespace(index=0)) segment = Segment( segment_id="chapter-1", file_path=Path("Text/ch1.xhtml"), xpath="/html/body/p", extract_mode=ExtractMode.TEXT, source_content="Original text", metadata=SegmentMetadata(element_type="p", spine_index=0, order_in_file=1), ) title_map = defaultdict(dict) updated, failures = _apply_translations_to_document( document, [(segment, "Translated")], "bilingual", title_map ) assert updated is True assert failures == [] paragraphs = tree.xpath("/html/body/p") assert len(paragraphs) == 2 assert paragraphs[0].get("data-lang") == "original" assert paragraphs[1].get("data-lang") == "translation" assert paragraphs[1].text == "Translated" assert title_map == {} def test_apply_translations_replaces_in_translated_only_mode(): markup = "<html><body><h1 id='t'>Original heading</h1></body></html>" tree = html.fromstring(markup) document = SimpleNamespace(tree=tree, spine_item=SimpleNamespace(index=0)) segment = Segment( segment_id="chapter-title", file_path=Path("Text/ch1.xhtml"), xpath="/html/body/h1", extract_mode=ExtractMode.TEXT, source_content="Original heading", metadata=SegmentMetadata(element_type="h1", spine_index=0, order_in_file=1), ) title_map = defaultdict(dict) updated, failures = _apply_translations_to_document( document, [(segment, "Título traducido")], "translated_only", title_map ) assert updated is True assert failures == [] headings = tree.xpath("/html/body/h1") assert len(headings) == 1 assert headings[0].text == "Título traducido" mapped = title_map[PurePosixPath("Text/ch1.xhtml")] assert mapped["t"] == "Título traducido" assert mapped[None] == "Título traducido" def test_group_translated_segments_excludes_auto_copied(tmp_path, monkeypatch): """Test that segments with provider_name=None (auto-copied) are excluded from injection.""" from state.store import save_segments, save_state from state.models import SegmentsDocument, StateDocument # Create test segments segments = [ Segment( segment_id="seg-1", file_path=Path("Text/ch1.xhtml"), xpath="/html/body/p[1]", extract_mode=ExtractMode.TEXT, source_content="Hello world", metadata=SegmentMetadata(element_type="p", spine_index=0, order_in_file=1), ), Segment( segment_id="seg-2", file_path=Path("Text/ch1.xhtml"), xpath="/html/body/p[2]", extract_mode=ExtractMode.TEXT, source_content="…", metadata=SegmentMetadata(element_type="p", spine_index=0, order_in_file=2), ), ] # Create state with one AI-translated and one auto-copied segment state = StateDocument( segments={ "seg-1": TranslationRecord( segment_id="seg-1", status=SegmentStatus.COMPLETED, translation="Translated text", provider_name="anthropic", model_name="claude-3-5-sonnet", ), "seg-2": TranslationRecord( segment_id="seg-2", status=SegmentStatus.COMPLETED, translation="…", provider_name=None, # Auto-copied segment model_name=None, ), }, current_provider="anthropic", current_model="claude-3-5-sonnet", ) # Save test data work_root = tmp_path / ".tepub" work_root.mkdir() segments_file = work_root / "segments.json" state_file = work_root / "state.json" segments_doc = SegmentsDocument( epub_path=tmp_path / "test.epub", generated_at="2024-01-01T00:00:00", segments=segments, ) save_segments(segments_doc, segments_file) save_state(state, state_file) # Create settings mock settings = SimpleNamespace( segments_file=segments_file, state_file=state_file, ) # Test the grouping function grouped = _group_translated_segments(settings) # Should only include the AI-translated segment, not the auto-copied one assert Path("Text/ch1.xhtml") in grouped segments_list = grouped[Path("Text/ch1.xhtml")] assert len(segments_list) == 1 assert segments_list[0][0].segment_id == "seg-1" assert segments_list[0][1] == "Translated text" def test_apply_translations_nested_blockquote_smart(): """Test injection with smart-extracted nested blockquotes.""" # Outer wrapper (no text), innermost has text markup = """<html><body> <blockquote><blockquote><blockquote> Centuries to Millennia Before </blockquote></blockquote></blockquote> </body></html>""" tree = html.fromstring(markup) document = SimpleNamespace(tree=tree, spine_item=SimpleNamespace(index=0)) # Only innermost extracted (from smart extraction) segment = Segment( segment_id="bq-inner", file_path=Path("Text/ch1.xhtml"), xpath="/html/body/blockquote/blockquote/blockquote", extract_mode=ExtractMode.TEXT, source_content="Centuries to Millennia Before", metadata=SegmentMetadata(element_type="blockquote", spine_index=0, order_in_file=1), ) title_map = defaultdict(dict) updated, failures = _apply_translations_to_document( document, [(segment, "几个世纪到几千年之前")], "bilingual", title_map ) assert updated is True assert failures == [] # Innermost level should have 2 blockquotes (original + translation) innermost_bqs = tree.xpath("/html/body/blockquote/blockquote/blockquote") assert len(innermost_bqs) == 2 assert innermost_bqs[0].get("data-lang") == "original" assert innermost_bqs[1].get("data-lang") == "translation" # Outer blockquotes should have NO data-lang (not extracted) outer_bqs = tree.xpath("/html/body/blockquote") for bq in outer_bqs[:1]: # First outer blockquote assert bq.get("data-lang") is None def test_apply_translations_ul_no_wrapper(): """Verify UL translation has no wrapper artifact.""" markup = """<html><body><ul><li>Item 1</li></ul></body></html>""" tree = html.fromstring(markup) document = SimpleNamespace(tree=tree, spine_item=SimpleNamespace(index=0)) segment = Segment( segment_id="list-1", file_path=Path("Text/ch1.xhtml"), xpath="/html/body/ul", extract_mode=ExtractMode.HTML, source_content="<li>Item 1</li>", metadata=SegmentMetadata(element_type="ul", spine_index=0, order_in_file=1), ) title_map = defaultdict(dict) updated, failures = _apply_translations_to_document( document, [(segment, "<li>项目 1</li>")], "bilingual", title_map ) uls = tree.xpath("/html/body/ul") translation_ul = uls[1] result = html.tostring(translation_ul, encoding="unicode") assert "<wrapper>" not in result assert "<li>项目 1</li>" in result
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/injection/test_html_ops.py
Python
from lxml import html from injection.html_ops import _set_html_content def test_set_html_content_removes_wrapper(): """Test that wrapper parsing artifact doesn't leak into output.""" element = html.fromstring("<ul></ul>") markup = "<li>Item 1</li><li>Item 2</li>" _set_html_content(element, markup) result = html.tostring(element, encoding="unicode") assert "<wrapper>" not in result assert "</wrapper>" not in result assert "<li>Item 1</li>" in result assert "<li>Item 2</li>" in result assert len(element) == 2 def test_set_html_content_with_table(): """Test wrapper removal with table HTML.""" element = html.fromstring("<table></table>") markup = "<thead><tr><th>Header</th></tr></thead><tbody><tr><td>Data</td></tr></tbody>" _set_html_content(element, markup) result = html.tostring(element, encoding="unicode") assert "<wrapper>" not in result assert "<thead>" in result assert "<tbody>" in result def test_set_html_content_empty_markup(): """Test empty markup clears element.""" element = html.fromstring("<div>Old content</div>") _set_html_content(element, "") assert element.text is None assert len(element) == 0
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/state/test_base.py
Python
"""Tests for generic state management base module.""" from __future__ import annotations import json from pathlib import Path import pytest from pydantic import BaseModel from state.base import ( atomic_write, load_generic_state, save_generic_state, update_state_item, ) # Test models class SimpleState(BaseModel): """Simple test state model.""" counter: int = 0 name: str = "test" class ComplexState(BaseModel): """Complex test state model with nested data.""" items: dict[str, int] = {} metadata: dict[str, str] = {} class TestAtomicWrite: """Tests for atomic_write function.""" def test_atomic_write_creates_file(self, tmp_path: Path): """Test that atomic_write creates the target file.""" target = tmp_path / "test.json" payload = {"key": "value"} atomic_write(target, payload) assert target.exists() assert json.loads(target.read_text()) == payload def test_atomic_write_uses_tmp_file(self, tmp_path: Path): """Test that atomic_write uses temporary file for atomicity.""" target = tmp_path / "test.json" payload = {"key": "value"} # The .tmp file should not exist after successful write atomic_write(target, payload) tmp_file = target.with_suffix(target.suffix + ".tmp") assert not tmp_file.exists() assert target.exists() def test_atomic_write_overwrites_existing(self, tmp_path: Path): """Test that atomic_write overwrites existing files.""" target = tmp_path / "test.json" # Write initial content atomic_write(target, {"version": 1}) assert json.loads(target.read_text())["version"] == 1 # Overwrite with new content atomic_write(target, {"version": 2}) assert json.loads(target.read_text())["version"] == 2 def test_atomic_write_preserves_unicode(self, tmp_path: Path): """Test that atomic_write preserves non-ASCII characters.""" target = tmp_path / "test.json" payload = {"chinese": "中文", "emoji": "🚀"} atomic_write(target, payload) loaded = json.loads(target.read_text()) assert loaded["chinese"] == "中文" assert loaded["emoji"] == "🚀" def test_atomic_write_formats_json(self, tmp_path: Path): """Test that atomic_write formats JSON with indentation.""" target = tmp_path / "test.json" payload = {"nested": {"key": "value"}} atomic_write(target, payload) content = target.read_text() # Should have indentation (multiple lines) assert "\n" in content assert " " in content # 2-space indent class TestLoadGenericState: """Tests for load_generic_state function.""" def test_load_simple_state(self, tmp_path: Path): """Test loading a simple state document.""" state_file = tmp_path / "state.json" state_file.write_text(json.dumps({"counter": 42, "name": "loaded"})) state = load_generic_state(state_file, SimpleState) assert isinstance(state, SimpleState) assert state.counter == 42 assert state.name == "loaded" def test_load_complex_state(self, tmp_path: Path): """Test loading a complex state document.""" state_file = tmp_path / "state.json" data = { "items": {"a": 1, "b": 2}, "metadata": {"version": "1.0"} } state_file.write_text(json.dumps(data)) state = load_generic_state(state_file, ComplexState) assert isinstance(state, ComplexState) assert state.items == {"a": 1, "b": 2} assert state.metadata == {"version": "1.0"} def test_load_missing_file_raises(self, tmp_path: Path): """Test that loading non-existent file raises FileNotFoundError.""" missing_file = tmp_path / "missing.json" with pytest.raises(FileNotFoundError): load_generic_state(missing_file, SimpleState) def test_load_invalid_json_raises(self, tmp_path: Path): """Test that loading invalid JSON raises JSONDecodeError.""" invalid_file = tmp_path / "invalid.json" invalid_file.write_text("not valid json{") with pytest.raises(json.JSONDecodeError): load_generic_state(invalid_file, SimpleState) def test_load_validation_error(self, tmp_path: Path): """Test that loading data with wrong schema raises ValidationError.""" state_file = tmp_path / "state.json" # Invalid type for counter field (string instead of int) state_file.write_text(json.dumps({"counter": "not_a_number", "name": "test"})) from pydantic import ValidationError with pytest.raises(ValidationError): load_generic_state(state_file, SimpleState) class TestSaveGenericState: """Tests for save_generic_state function.""" def test_save_simple_state(self, tmp_path: Path): """Test saving a simple state document.""" state_file = tmp_path / "state.json" state = SimpleState(counter=99, name="saved") save_generic_state(state, state_file) assert state_file.exists() loaded_data = json.loads(state_file.read_text()) assert loaded_data["counter"] == 99 assert loaded_data["name"] == "saved" def test_save_complex_state(self, tmp_path: Path): """Test saving a complex state document.""" state_file = tmp_path / "state.json" state = ComplexState( items={"x": 10, "y": 20}, metadata={"author": "test"} ) save_generic_state(state, state_file) loaded_data = json.loads(state_file.read_text()) assert loaded_data["items"] == {"x": 10, "y": 20} assert loaded_data["metadata"] == {"author": "test"} def test_save_uses_atomic_write(self, tmp_path: Path): """Test that save_generic_state uses atomic write.""" state_file = tmp_path / "state.json" state = SimpleState(counter=1) save_generic_state(state, state_file) # Temporary file should not exist after save tmp_file = state_file.with_suffix(state_file.suffix + ".tmp") assert not tmp_file.exists() assert state_file.exists() def test_save_overwrites_existing(self, tmp_path: Path): """Test that saving overwrites existing state file.""" state_file = tmp_path / "state.json" # Save initial state state1 = SimpleState(counter=1, name="first") save_generic_state(state1, state_file) # Save new state state2 = SimpleState(counter=2, name="second") save_generic_state(state2, state_file) # Verify only second state persists loaded_data = json.loads(state_file.read_text()) assert loaded_data["counter"] == 2 assert loaded_data["name"] == "second" class TestUpdateStateItem: """Tests for update_state_item function.""" def test_update_modifies_state(self, tmp_path: Path): """Test that update_state_item correctly modifies state.""" state_file = tmp_path / "state.json" initial_state = SimpleState(counter=0, name="initial") save_generic_state(initial_state, state_file) def increment_counter(state: SimpleState) -> SimpleState: state.counter += 1 return state updated = update_state_item(state_file, SimpleState, increment_counter) assert updated.counter == 1 assert updated.name == "initial" def test_update_persists_changes(self, tmp_path: Path): """Test that update_state_item persists changes to disk.""" state_file = tmp_path / "state.json" initial_state = SimpleState(counter=5, name="test") save_generic_state(initial_state, state_file) def double_counter(state: SimpleState) -> SimpleState: state.counter *= 2 return state update_state_item(state_file, SimpleState, double_counter) # Reload from disk to verify persistence reloaded = load_generic_state(state_file, SimpleState) assert reloaded.counter == 10 def test_update_complex_state(self, tmp_path: Path): """Test updating complex state with nested structures.""" state_file = tmp_path / "state.json" initial_state = ComplexState(items={"a": 1}, metadata={}) save_generic_state(initial_state, state_file) def add_item(state: ComplexState) -> ComplexState: state.items["b"] = 2 state.metadata["updated"] = "true" return state updated = update_state_item(state_file, ComplexState, add_item) assert updated.items == {"a": 1, "b": 2} assert updated.metadata == {"updated": "true"} def test_update_returns_updated_state(self, tmp_path: Path): """Test that update_state_item returns the updated state.""" state_file = tmp_path / "state.json" initial_state = SimpleState(counter=0) save_generic_state(initial_state, state_file) def modify(state: SimpleState) -> SimpleState: state.name = "modified" return state result = update_state_item(state_file, SimpleState, modify) assert result.name == "modified" assert isinstance(result, SimpleState) def test_update_multiple_times(self, tmp_path: Path): """Test multiple sequential updates.""" state_file = tmp_path / "state.json" initial_state = SimpleState(counter=0) save_generic_state(initial_state, state_file) def increment(state: SimpleState) -> SimpleState: state.counter += 1 return state # Apply update 3 times for _ in range(3): update_state_item(state_file, SimpleState, increment) final_state = load_generic_state(state_file, SimpleState) assert final_state.counter == 3 class TestIntegration: """Integration tests combining multiple functions.""" def test_full_lifecycle(self, tmp_path: Path): """Test complete lifecycle: create, save, load, update.""" state_file = tmp_path / "lifecycle.json" # 1. Create and save state = SimpleState(counter=1, name="lifecycle") save_generic_state(state, state_file) # 2. Load loaded = load_generic_state(state_file, SimpleState) assert loaded.counter == 1 # 3. Update def increment(s: SimpleState) -> SimpleState: s.counter += 1 return s updated = update_state_item(state_file, SimpleState, increment) assert updated.counter == 2 # 4. Reload to verify final = load_generic_state(state_file, SimpleState) assert final.counter == 2 def test_concurrent_updates_use_atomic_write(self, tmp_path: Path): """Test that concurrent updates don't leave tmp files.""" state_file = tmp_path / "concurrent.json" state = SimpleState(counter=0) save_generic_state(state, state_file) def increment(s: SimpleState) -> SimpleState: s.counter += 1 return s # Multiple updates for _ in range(5): update_state_item(state_file, SimpleState, increment) # No tmp files should remain tmp_file = state_file.with_suffix(state_file.suffix + ".tmp") assert not tmp_file.exists() assert state_file.exists() # Final state should be correct final = load_generic_state(state_file, SimpleState) assert final.counter == 5
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/state/test_safe_load.py
Python
"""Tests for safe_load_state function.""" from __future__ import annotations import json from pathlib import Path import pytest from pydantic import BaseModel from exceptions import CorruptedStateError from state.base import safe_load_state class SimpleModel(BaseModel): """Simple test model.""" name: str count: int class TestSafeLoadState: """Tests for safe_load_state function.""" def test_loads_valid_file_successfully(self, tmp_path): """Test loading a valid state file.""" state_file = tmp_path / "state.json" state_file.write_text(json.dumps({"name": "test", "count": 42})) result = safe_load_state(state_file, SimpleModel, "test") assert isinstance(result, SimpleModel) assert result.name == "test" assert result.count == 42 def test_raises_file_not_found_for_missing_file(self, tmp_path): """Test that missing file raises FileNotFoundError.""" missing_file = tmp_path / "missing.json" with pytest.raises(FileNotFoundError): safe_load_state(missing_file, SimpleModel, "test") def test_raises_corrupted_error_for_invalid_json(self, tmp_path): """Test that invalid JSON raises CorruptedStateError.""" state_file = tmp_path / "state.json" state_file.write_text("not valid json{") with pytest.raises(CorruptedStateError) as exc_info: safe_load_state(state_file, SimpleModel, "test") error = exc_info.value assert error.file_path == state_file assert error.state_type == "test" assert "Invalid JSON format" in error.reason assert "line" in error.reason def test_raises_corrupted_error_for_schema_mismatch(self, tmp_path): """Test that schema validation failure raises CorruptedStateError.""" state_file = tmp_path / "state.json" # Wrong type for 'count' field state_file.write_text(json.dumps({"name": "test", "count": "not_a_number"})) with pytest.raises(CorruptedStateError) as exc_info: safe_load_state(state_file, SimpleModel, "test") error = exc_info.value assert error.file_path == state_file assert error.state_type == "test" assert "Schema validation failed" in error.reason assert "count" in error.reason def test_raises_corrupted_error_for_missing_required_field(self, tmp_path): """Test that missing required field raises CorruptedStateError.""" state_file = tmp_path / "state.json" # Missing 'count' field state_file.write_text(json.dumps({"name": "test"})) with pytest.raises(CorruptedStateError) as exc_info: safe_load_state(state_file, SimpleModel, "test") error = exc_info.value assert "Schema validation failed" in error.reason assert "count" in error.reason def test_error_message_includes_helpful_suggestion(self, tmp_path): """Test that error message suggests re-running extract.""" state_file = tmp_path / "state.json" state_file.write_text("{invalid") with pytest.raises(CorruptedStateError) as exc_info: safe_load_state(state_file, SimpleModel, "segments") error_msg = str(exc_info.value) assert "tepub extract" in error_msg assert "corrupted" in error_msg.lower() def test_preserves_file_path_in_error(self, tmp_path): """Test that file path is preserved in error for debugging.""" state_file = tmp_path / "deeply" / "nested" / "state.json" state_file.parent.mkdir(parents=True) state_file.write_text("bad json") with pytest.raises(CorruptedStateError) as exc_info: safe_load_state(state_file, SimpleModel, "test") assert exc_info.value.file_path == state_file assert str(state_file) not in str(exc_info.value) # Shows only filename assert "state.json" in str(exc_info.value)
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/test_exceptions.py
Python
"""Tests for custom exceptions.""" from __future__ import annotations from pathlib import Path import pytest from exceptions import CorruptedStateError, StateFileNotFoundError, TepubError, WorkspaceNotFoundError class TestTepubError: """Tests for base TepubError exception.""" def test_is_exception(self): """TepubError should be an Exception subclass.""" assert issubclass(TepubError, Exception) def test_can_raise(self): """TepubError can be raised and caught.""" with pytest.raises(TepubError) as exc_info: raise TepubError("test error") assert str(exc_info.value) == "test error" class TestStateFileNotFoundError: """Tests for StateFileNotFoundError.""" def test_is_tepub_error(self): """StateFileNotFoundError should be a TepubError subclass.""" assert issubclass(StateFileNotFoundError, TepubError) def test_segments_error_message(self): """Test error message for missing segments file.""" epub_path = Path("/path/to/book.epub") error = StateFileNotFoundError("segments", epub_path) expected = ( "No extraction state found for 'book.epub'.\n" "Please run: tepub extract '/path/to/book.epub'" ) assert str(error) == expected assert error.state_type == "segments" assert error.epub_path == epub_path def test_translation_error_message(self): """Test error message for missing translation state file.""" epub_path = Path("/downloads/novel.epub") error = StateFileNotFoundError("translation", epub_path) expected = ( "No translation state found for 'novel.epub'.\n" "Please run the following commands first:\n" " 1. tepub extract '/downloads/novel.epub'\n" " 2. tepub translate '/downloads/novel.epub'" ) assert str(error) == expected assert error.state_type == "translation" assert error.epub_path == epub_path def test_unknown_state_type_message(self): """Test fallback error message for unknown state type.""" epub_path = Path("/test/book.epub") error = StateFileNotFoundError("unknown", epub_path) expected = "State file 'unknown' not found." assert str(error) == expected def test_can_be_caught_as_tepub_error(self): """StateFileNotFoundError can be caught as TepubError.""" epub_path = Path("/test.epub") with pytest.raises(TepubError): raise StateFileNotFoundError("segments", epub_path) def test_preserves_path_type(self): """Test that Path objects are preserved correctly.""" epub_path = Path("/some/path/to/book.epub") error = StateFileNotFoundError("segments", epub_path) assert isinstance(error.epub_path, Path) assert error.epub_path == epub_path class TestWorkspaceNotFoundError: """Tests for WorkspaceNotFoundError.""" def test_is_tepub_error(self): """WorkspaceNotFoundError should be a TepubError subclass.""" assert issubclass(WorkspaceNotFoundError, TepubError) def test_error_message(self): """Test error message for missing workspace.""" epub_path = Path("/books/mybook.epub") work_dir = Path("/workspace/mybook") error = WorkspaceNotFoundError(epub_path, work_dir) expected = ( "No workspace found for 'mybook.epub'.\n" "Expected workspace at: /workspace/mybook\n" "Please run: tepub extract '/books/mybook.epub'" ) assert str(error) == expected assert error.epub_path == epub_path assert error.work_dir == work_dir def test_can_be_caught_as_tepub_error(self): """WorkspaceNotFoundError can be caught as TepubError.""" epub_path = Path("/test.epub") work_dir = Path("/workspace") with pytest.raises(TepubError): raise WorkspaceNotFoundError(epub_path, work_dir) def test_preserves_path_types(self): """Test that Path objects are preserved correctly.""" epub_path = Path("/path/to/book.epub") work_dir = Path("/path/to/workspace") error = WorkspaceNotFoundError(epub_path, work_dir) assert isinstance(error.epub_path, Path) assert isinstance(error.work_dir, Path) assert error.epub_path == epub_path assert error.work_dir == work_dir class TestCorruptedStateError: """Tests for CorruptedStateError.""" def test_is_tepub_error(self): """CorruptedStateError should be a TepubError subclass.""" assert issubclass(CorruptedStateError, TepubError) def test_error_message_structure(self): """Test error message for corrupted state file.""" file_path = Path("/workspace/state.json") error = CorruptedStateError(file_path, "translation", "Invalid JSON format (line 1, column 5)") assert "state.json" in str(error) assert "Invalid JSON format" in str(error) assert "tepub extract" in str(error) assert error.file_path == file_path assert error.state_type == "translation" assert error.reason == "Invalid JSON format (line 1, column 5)" def test_can_be_caught_as_tepub_error(self): """CorruptedStateError can be caught as TepubError.""" file_path = Path("/test.json") with pytest.raises(TepubError): raise CorruptedStateError(file_path, "segments", "test reason") def test_preserves_path_type(self): """Test that Path objects are preserved correctly.""" file_path = Path("/some/path/state.json") error = CorruptedStateError(file_path, "state", "test") assert isinstance(error.file_path, Path) assert error.file_path == file_path
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/translation/test_controller.py
Python
from pathlib import Path from types import SimpleNamespace import pytest from rich.console import Console from config import AppSettings, ProviderConfig from state.models import ExtractMode, Segment, SegmentMetadata, SegmentStatus, SegmentsDocument from state.store import load_state, save_segments from translation.controller import run_translation from translation.providers.base import ProviderFatalError class DummyProvider: name = "dummy" model = "dummy-model" def translate(self, segment: Segment, source_language: str, target_language: str) -> str: return "<p>Hola mundo</p>" @pytest.fixture def settings(tmp_path): cfg = AppSettings().model_copy(update={"work_dir": tmp_path}) cfg.ensure_directories() return cfg def _write_segments(settings: AppSettings, input_epub: Path) -> Segment: segment = Segment( segment_id="chapter1-001", file_path=Path("Text/chapter1.xhtml"), xpath="/html/body/p[1]", extract_mode=ExtractMode.TEXT, source_content="Hello world", metadata=SegmentMetadata(element_type="p", spine_index=0, order_in_file=1), ) document = SegmentsDocument( epub_path=input_epub, generated_at="2024-01-01T00:00:00Z", segments=[segment], skipped_documents=[], ) save_segments(document, settings.segments_file) return segment def test_run_translation_updates_state(monkeypatch, settings, tmp_path): input_epub = tmp_path / "book.epub" input_epub.write_text("stub", encoding="utf-8") segment = _write_segments(settings, input_epub) monkeypatch.setattr("translation.controller.create_provider", lambda _config: DummyProvider()) test_console = Console(record=True) monkeypatch.setattr("translation.controller.console", test_console) run_translation( settings, input_epub, source_language="en", target_language="zh-CN", ) state = load_state(settings.state_file) record = state.segments[segment.segment_id] assert record.status == SegmentStatus.COMPLETED assert record.translation == "<p>Hola mundo</p>" assert record.provider_name == "dummy" assert record.model_name == "dummy-model" output = test_console.export_text() assert "Dashboard" in output assert "files" in output assert "Hola mundo" in output class FailingProvider: name = "dummy" model = "dummy-model" def translate(self, segment: Segment, source_language: str, target_language: str) -> str: raise ProviderFatalError("network unavailable") def test_run_translation_handles_fatal_error(monkeypatch, settings, tmp_path): input_epub = tmp_path / "fatal.epub" input_epub.write_text("stub", encoding="utf-8") segment = _write_segments(settings, input_epub) monkeypatch.setattr("translation.controller.create_provider", lambda _config: FailingProvider()) test_console = Console(record=True) monkeypatch.setattr("translation.controller.console", test_console) run_translation( settings, input_epub, source_language="en", target_language="zh-CN", ) state = load_state(settings.state_file) record = state.segments[segment.segment_id] assert record.status == SegmentStatus.ERROR # Error should be logged output = test_console.export_text() assert "network unavailable" in output.lower() class SpyProvider: name = "spy" model = "spy-model" def __init__(self): self.calls = [] def translate(self, segment: Segment, source_language: str, target_language: str) -> str: self.calls.append(segment.source_content) return "TRANSLATED" def test_run_translation_auto_copies_punctuation(monkeypatch, settings, tmp_path): input_epub = tmp_path / "auto-copy.epub" input_epub.write_text("stub", encoding="utf-8") ellipsis_segment = Segment( segment_id="seg-ellipsis", file_path=Path("Text/chapter1.xhtml"), xpath="/html/body/p[1]", extract_mode=ExtractMode.TEXT, source_content="…", metadata=SegmentMetadata(element_type="p", spine_index=0, order_in_file=1), ) content_segment = Segment( segment_id="seg-content", file_path=Path("Text/chapter1.xhtml"), xpath="/html/body/p[2]", extract_mode=ExtractMode.TEXT, source_content="Hello world", metadata=SegmentMetadata(element_type="p", spine_index=0, order_in_file=2), ) document = SegmentsDocument( epub_path=input_epub, generated_at="2024-01-01T00:00:00Z", segments=[ellipsis_segment, content_segment], skipped_documents=[], ) save_segments(document, settings.segments_file) spy = SpyProvider() monkeypatch.setattr("translation.controller.create_provider", lambda _config: spy) run_translation( settings, input_epub, source_language="en", target_language="zh-CN", ) state = load_state(settings.state_file) ellipsis_record = state.segments[ellipsis_segment.segment_id] assert ellipsis_record.status == SegmentStatus.COMPLETED assert ellipsis_record.translation == "…" assert ellipsis_record.provider_name is None # Auto-copied segments have no provider assert ellipsis_record.model_name is None content_record = state.segments[content_segment.segment_id] assert content_record.provider_name == "spy" # AI-translated segments have provider info assert content_record.model_name == "spy-model" assert spy.calls == ["Hello world"]
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/translation/test_languages.py
Python
from translation.languages import normalize_language, describe_language def test_normalize_language_accepts_codes_and_names() -> None: assert normalize_language("en") == ("en", "English") assert normalize_language("English") == ("en", "English") assert normalize_language("zh-CN") == ("zh-CN", "Simplified Chinese") assert normalize_language("Simplified Chinese") == ("zh-CN", "Simplified Chinese") assert normalize_language("auto") == ("auto", "Auto") def test_describe_language_falls_back_to_code() -> None: assert describe_language("en") == "English" assert describe_language("xx") == "xx"
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/translation/test_parallel.py
Python
"""Tests for parallel translation processing.""" from pathlib import Path import pytest from rich.console import Console from config import AppSettings from state.models import ExtractMode, Segment, SegmentMetadata, SegmentsDocument, SegmentStatus from state.store import load_state, save_segments from translation.controller import run_translation class DummyParallelProvider: """Provider that simulates parallel translation.""" name = "dummy" model = "dummy-model" def __init__(self): self.call_count = 0 def translate(self, segment: Segment, source_language: str, target_language: str) -> str: """Simulate translation with a counter.""" self.call_count += 1 return f"<p>Translation {self.call_count}</p>" @pytest.fixture def settings(tmp_path): cfg = AppSettings().model_copy(update={"work_dir": tmp_path}) cfg.ensure_directories() return cfg def _write_segments(settings: AppSettings, input_epub: Path, count: int = 5) -> list[Segment]: """Create test segments.""" segments = [] for i in range(count): segment = Segment( segment_id=f"seg-{i:03d}", file_path=Path("Text/chapter1.xhtml"), xpath=f"/html/body/p[{i+1}]", extract_mode=ExtractMode.TEXT, source_content=f"Text segment {i}", metadata=SegmentMetadata(element_type="p", spine_index=0, order_in_file=i + 1), ) segments.append(segment) document = SegmentsDocument( epub_path=input_epub, generated_at="2024-01-01T00:00:00Z", segments=segments, skipped_documents=[], ) save_segments(document, settings.segments_file) return segments def test_parallel_translation_processes_all_segments(monkeypatch, settings, tmp_path): """Test that parallel translation processes all segments.""" input_epub = tmp_path / "book.epub" input_epub.write_text("stub", encoding="utf-8") segments = _write_segments(settings, input_epub, count=10) provider = DummyParallelProvider() monkeypatch.setattr("translation.controller.create_provider", lambda _config: provider) test_console = Console(record=True) monkeypatch.setattr("translation.controller.console", test_console) # Set workers to 3 to test parallel execution settings.translation_workers = 3 run_translation( settings, input_epub, source_language="en", target_language="zh-CN", ) # Verify all segments were translated state = load_state(settings.state_file) assert len(state.segments) == 10 for i, segment in enumerate(segments): record = state.segments[segment.segment_id] assert record.status == SegmentStatus.COMPLETED assert record.translation is not None assert "Translation" in record.translation # Verify provider was called for each segment assert provider.call_count == 10 def test_parallel_with_single_worker_is_sequential(monkeypatch, settings, tmp_path): """Test that workers=1 still works (sequential mode).""" input_epub = tmp_path / "book.epub" input_epub.write_text("stub", encoding="utf-8") segments = _write_segments(settings, input_epub, count=5) provider = DummyParallelProvider() monkeypatch.setattr("translation.controller.create_provider", lambda _config: provider) test_console = Console(record=True) monkeypatch.setattr("translation.controller.console", test_console) # Set workers to 1 for sequential execution settings.translation_workers = 1 run_translation( settings, input_epub, source_language="en", target_language="zh-CN", ) # Verify all segments were translated state = load_state(settings.state_file) assert len(state.segments) == 5 for segment in segments: record = state.segments[segment.segment_id] assert record.status == SegmentStatus.COMPLETED assert record.translation is not None assert provider.call_count == 5
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/translation/test_polish.py
Python
from translation.polish import polish_translation, target_is_chinese def test_polish_inserts_spaces_between_chinese_and_numbers(): assert polish_translation("第3章") == "第 3 章" def test_polish_handles_english_phrase(): assert polish_translation("学习machine learning方法") == "学习 machine learning 方法" def test_polish_formats_quotes(): assert polish_translation("中文“引用”中文") == "中文 “引用” 中文" def test_polish_formats_dashes(): assert polish_translation("中文--英文") == "中文 —— 英文" # No space after ) assert polish_translation("(注释)--英文") == "(注释)—— 英文" # No space before ( assert polish_translation("中文--(注释)") == "中文 ——(注释)" # Both rules apply with Chinese context assert polish_translation("中文)--(中文") == "中文)——(中文" # Inside parentheses gets normal spacing assert polish_translation("(括号--内容)") == "(括号 —— 内容)" def test_polish_fixes_existing_emdash_spacing(): """Test fixing spacing around existing —— characters.""" # Add spaces where missing assert polish_translation("中文——英文") == "中文 —— 英文" # Remove extra spaces and normalize assert polish_translation("中文 —— 英文") == "中文 —— 英文" # No space after ) assert polish_translation("(注释)——英文") == "(注释)—— 英文" # No space before ( assert polish_translation("中文——(注释)") == "中文 ——(注释)" # Both rules with existing em-dash assert polish_translation("中文)——(中文") == "中文)——(中文" # Real example from translation assert polish_translation("优素福·阿萨尔·亚萨尔——阿拉伯最后一位统治的犹太国王") == "优素福·阿萨尔·亚萨尔 —— 阿拉伯最后一位统治的犹太国王" def test_target_is_chinese(): assert target_is_chinese("Simplified Chinese") assert target_is_chinese("中文") assert not target_is_chinese("English") def test_polish_normalizes_ellipsis_in_chinese(): """Test ellipsis normalization in Chinese text.""" # cjk-text-formatter removes leading space before ellipsis for cleaner output assert polish_translation("文字 . . . 更多文字") == "文字... 更多文字" assert polish_translation("开始 . . . . 结束") == "开始... 结束" assert polish_translation("已经正确...的格式") == "已经正确... 的格式" def test_polish_normalizes_ellipsis_in_english(): """Test ellipsis normalization in non-Chinese text.""" # cjk-text-formatter removes leading space before ellipsis for cleaner output assert polish_translation("Text before . . . and after.") == "Text before... and after." assert polish_translation("Multiple . . . . dots here.") == "Multiple... dots here." assert polish_translation("Already correct... format.") == "Already correct... format." def test_polish_handles_percentage_spacing(): """Test spacing with percentage symbols.""" assert polish_translation("占人口比例的5%甚至更多") == "占人口比例的 5% 甚至更多" assert polish_translation("增长20%左右") == "增长 20% 左右" assert polish_translation("的15%是") == "的 15% 是" def test_polish_handles_temperature_spacing(): """Test spacing with temperature units.""" # Unicode temperature symbols assert polish_translation("温度25℃很热") == "温度 25℃ 很热" assert polish_translation("约25℉左右") == "约 25℉ 左右" # Degree + letter combinations assert polish_translation("是25°C今天") == "是 25°C 今天" assert polish_translation("约25°c左右") == "约 25°c 左右" assert polish_translation("温度25°F较低") == "温度 25°F 较低" assert polish_translation("大约25°f吧") == "大约 25°f 吧" def test_polish_handles_degree_spacing(): """Test spacing with degree symbols.""" assert polish_translation("角度45°比较") == "角度 45° 比较" assert polish_translation("转90°然后") == "转 90° 然后" def test_polish_handles_permille_spacing(): """Test spacing with per mille symbols.""" assert polish_translation("浓度3‰的溶液") == "浓度 3‰ 的溶液" def test_polish_handles_mixed_ellipsis_and_chinese_rules(): """Test that ellipsis normalization works with other Chinese polishing rules.""" # Ellipsis + spacing between Chinese and English # cjk-text-formatter removes leading space before ellipsis for cleaner output assert polish_translation("学习 . . . machine learning") == "学习... machine learning" # Ellipsis + dash formatting assert polish_translation("文字 . . . 中文--英文") == "文字... 中文 —— 英文"
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/translation/test_prefilter.py
Python
from state.models import Segment, SegmentMetadata, ExtractMode from translation.prefilter import should_auto_copy def _segment(text: str) -> Segment: return Segment( segment_id="seg", file_path="chapter.xhtml", xpath="/", extract_mode=ExtractMode.TEXT, source_content=text, metadata=SegmentMetadata(element_type="p", spine_index=0, order_in_file=0), ) def test_auto_copy_for_ellipsis(): assert should_auto_copy(_segment("…")) def test_auto_copy_for_numbers(): assert should_auto_copy(_segment("123-125")) def test_auto_copy_for_page_marker(): assert should_auto_copy(_segment("p. 42")) def test_auto_copy_rejects_short_word(): assert not should_auto_copy(_segment("Fig.")) def test_auto_copy_rejects_normal_sentence(): assert not should_auto_copy(_segment("Hello world"))
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/translation/test_prompt_builder.py
Python
from pathlib import Path from translation.prompt_builder import build_prompt, configure_prompt from state.models import Segment, SegmentMetadata, ExtractMode def _make_segment(text: str, mode: ExtractMode = ExtractMode.TEXT) -> Segment: return Segment( segment_id="seg-1", file_path=Path("Text/chapter1.xhtml"), xpath="/html/body/p[1]", extract_mode=mode, source_content=text, metadata=SegmentMetadata(element_type="p", spine_index=0, order_in_file=1), ) def test_build_prompt_includes_language_instructions() -> None: configure_prompt(None) # Use DEFAULT_SYSTEM_PROMPT segment = _make_segment("Hello world") prompt = build_prompt(segment, source_language="en", target_language="zh-CN") assert "Translate from English" in prompt assert "Simplified Chinese" in prompt assert "SOURCE:\nHello world" in prompt def test_build_prompt_handles_auto_detection() -> None: configure_prompt(None) # Use DEFAULT_SYSTEM_PROMPT segment = _make_segment("<p>Hello</p>", ExtractMode.HTML) prompt = build_prompt(segment, source_language="auto", target_language="fr") assert "Detect the source language automatically" in prompt assert "Preserve HTML structure" in prompt
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/translation/test_refusal_filter.py
Python
from translation.refusal_filter import looks_like_refusal def test_detects_english_refusal(): assert looks_like_refusal("I'm sorry, I can't help with that.") def test_detects_chinese_refusal(): assert looks_like_refusal("抱歉,我无法协助处理该内容。") def test_ignores_legit_text(): assert not looks_like_refusal("Sorry means something different in this context.") def test_ignores_mid_sentence_apology(): assert not looks_like_refusal("Well, I'm sorry but this part was already translated.") def test_long_refusal_still_detected(): long_text = "I'm sorry" + " very" * 500 assert looks_like_refusal(long_text)
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
tests/webbuilder/test_dom.py
Python
from pathlib import Path from webbuilder.dom import clean_html def test_clean_html_removes_font_and_styles(): html = "<html><body><font color='red'><span style='color:blue'>文本</span></font></body></html>" cleaned = clean_html(html) assert "font" not in cleaned assert "style" not in cleaned assert "文本" in cleaned def test_clean_html_adds_image_attrs(): html_doc = "<html><body><img src='a.jpg' class='cover' /><img src='b.jpg' /></body></html>" cleaned = clean_html(html_doc) assert 'loading="lazy"' in cleaned assert 'decoding="async"' in cleaned assert cleaned.count('class="tepub-img"') == 2 assert 'class="tepub-img"' in cleaned def test_clean_html_rewrites_media_urls(tmp_path): html_doc = """ <html><body> <img src="images/a.jpg" srcset="images/a@2x.jpg 2x" /> <audio src="audio/sample.mp3"></audio> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><image xlink:href="images/cover.jpg" href="images/cover.jpg" /></svg> <p><a href="../chapter2.xhtml#section">Next chapter</a></p> </body></html> """ rel = Path("chapters/ch1.xhtml") cleaned = clean_html(html_doc, relative_path=rel) assert 'src="content/chapters/images/a.jpg"' in cleaned assert 'srcset="content/chapters/images/a@2x.jpg 2x"' in cleaned assert 'src="content/chapters/audio/sample.mp3"' in cleaned assert ('xlink:href="content/chapters/images/cover.jpg"' in cleaned) or ( 'ns0:href="content/chapters/images/cover.jpg"' in cleaned ) assert 'href="content/chapters/images/cover.jpg"' in cleaned assert 'href="content/chapter2.xhtml#section"' in cleaned
xiaolai/tepub
37
TEPUB - Tools for EPUB: Translate books, create audiobooks, and export to various formats
Python
xiaolai
xiaolai
inblockchain
.prettierrc.js
JavaScript
module.exports = { bracketSpacing: true, singleQuote: false, arrowParens: "avoid", trailingComma: "none" }
xiaoxian521/responsive-storage
36
Responsive local storage, supports vue2 and vue3
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/vue2/public/index.html
HTML
<!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <link rel="icon" href="<%= BASE_URL %>favicon.ico"> <title>vue2 responsive-storage test</title> </head> <body> <noscript> <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"></div> <!-- built files will be auto injected --> </body> </html>
xiaoxian521/responsive-storage
36
Responsive local storage, supports vue2 and vue3
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/vue2/src/App.vue
Vue
<template> <div class="content"> <el-tooltip content="Vue2版本" placement="top" effect="light"> <p>Vue2 Version</p> </el-tooltip> <el-tooltip content="请打开本地浏览器的LocalStorage查看rs-starValue对应值的变化并观察页面中star的变化" placement="top" effect="light" > <p> Please open the Local Storage of your local browser to check the change of the corresponding value of rs-starValue and observe the change of star in the page </p> </el-tooltip> <el-rate v-model="$storage.starValue" disabled show-score score-template="{value} Star" /> <br /> <StarButton /> </div> </template> <script> import StarButton from "./components/button"; export default { name: "App", components: { StarButton } }; </script> <style scoped> .content { width: 300px; height: 300px; margin: 70px auto; text-align: center; } </style>
xiaoxian521/responsive-storage
36
Responsive local storage, supports vue2 and vue3
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/vue2/src/assets/reset.css
CSS
html, body, #app { margin: 0; padding: 0; width: 100%; height: 100%; }
xiaoxian521/responsive-storage
36
Responsive local storage, supports vue2 and vue3
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/vue2/src/components/button.vue
Vue
<template> <div> <el-tooltip content="减" placement="bottom" effect="light"> <el-button size="small" @click="decrease"> - Decrease </el-button> </el-tooltip> <el-tooltip content="加" placement="bottom" effect="light"> <el-button size="small" @click="increase"> + Increase </el-button> </el-tooltip> </div> </template> <script> export default { name: "StarButton", methods: { decrease() { if (this.$storage.starValue <= 0) return; this.$storage.starValue--; }, increase() { if (this.$storage.starValue >= 5) return; this.$storage.starValue++; } } }; </script>
xiaoxian521/responsive-storage
36
Responsive local storage, supports vue2 and vue3
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/vue2/src/main.js
JavaScript
import Vue from 'vue' import App from './App.vue' import "./assets/reset.css" import 'element-ui/lib/theme-chalk/index.css' import ElementUI from 'element-ui' Vue.use(ElementUI) import Storage from "../../../dist" // import Storage from "responsive-storage" Vue.use(Storage, { version: 2, // nameSpace: "test_", memory: { // starValue: Storage.getData("starValue", "test_") ?? 1 starValue: Storage.getData("starValue") ?? 1 } }) Vue.config.productionTip = false new Vue({ render: h => h(App), }).$mount('#app')
xiaoxian521/responsive-storage
36
Responsive local storage, supports vue2 and vue3
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/vue2/vue.config.js
JavaScript
const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ transpileDependencies: true })
xiaoxian521/responsive-storage
36
Responsive local storage, supports vue2 and vue3
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/vue3/index.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" href="/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>vue3 responsive-storage test</title> </head> <body> <div id="app"></div> <script type="module" src="/src/main.ts"></script> </body> </html>
xiaoxian521/responsive-storage
36
Responsive local storage, supports vue2 and vue3
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/vue3/src/App.vue
Vue
<template> <div class="content"> <el-tooltip content="Vue3版本" placement="top" effect="light"> <p>Vue3 Version</p> </el-tooltip> <el-tooltip content="请打开本地浏览器的LocalStorage查看rs-starValue对应值的变化并观察页面中star的变化" placement="top" effect="light" > <p> Please open the Local Storage of your local browser to check the change of the corresponding value of rs-starValue and observe the change of star in the page </p> </el-tooltip> <el-rate v-model="starValue" disabled show-score score-template="{value} Star" /> <br /> <StarButton /> </div> </template> <script setup lang="ts"> import StarButton from "./components/button.vue"; import { computed, getCurrentInstance } from "vue"; let starValue = computed(() => { return getCurrentInstance()!.appContext.app.config.globalProperties.$storage .starValue; }); </script> <style scoped> .content { width: 300px; height: 300px; margin: 70px auto; text-align: center; } </style>
xiaoxian521/responsive-storage
36
Responsive local storage, supports vue2 and vue3
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/vue3/src/assets/reset.css
CSS
html, body, #app { margin: 0; padding: 0; width: 100%; height: 100%; }
xiaoxian521/responsive-storage
36
Responsive local storage, supports vue2 and vue3
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/vue3/src/components/button.vue
Vue
<script setup lang="ts"> import { getCurrentInstance, onBeforeMount } from "vue"; let _storage: any = null; function decrease() { if (_storage.starValue <= 0) return; _storage.starValue--; } function increase() { if (_storage.starValue >= 5) return; _storage.starValue++; } onBeforeMount(() => { _storage = getCurrentInstance()!.appContext.app.config.globalProperties.$storage; }); </script> <template> <el-tooltip content="减" placement="bottom" effect="light"> <el-button @click="decrease"> - Decrease </el-button> </el-tooltip> <el-tooltip content="加" placement="bottom" effect="light"> <el-button @click="increase"> + Increase </el-button> </el-tooltip> </template>
xiaoxian521/responsive-storage
36
Responsive local storage, supports vue2 and vue3
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/vue3/src/env.d.ts
TypeScript
/// <reference types="vite/client" /> declare module '*.vue' { import type { DefineComponent } from 'vue' // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types const component: DefineComponent<{}, {}, any> export default component }
xiaoxian521/responsive-storage
36
Responsive local storage, supports vue2 and vue3
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/vue3/src/main.ts
TypeScript
import { createApp } from "vue"; import App from "./App.vue"; import "./assets/reset.css"; import "element-plus/dist/index.css"; import Storage from "../../../dist"; // import Storage from "responsive-storage"; import ElementPlus from "element-plus"; const app = createApp(App); app.use(Storage, { // nameSpace: "test_", memory: { // starValue: Storage.getData("starValue", "test_") ?? 1 starValue: Storage.getData("starValue") ?? 1 } }); app.use(ElementPlus).mount("#app");
xiaoxian521/responsive-storage
36
Responsive local storage, supports vue2 and vue3
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/vue3/vite.config.ts
TypeScript
import { defineConfig } from "vite"; import vue from "@vitejs/plugin-vue"; // https://vitejs.dev/config/ export default defineConfig({ plugins: [vue()] });
xiaoxian521/responsive-storage
36
Responsive local storage, supports vue2 and vue3
TypeScript
xiaoxian521
xiaoming
pure-admin
src/convert.ts
TypeScript
import * as Vue from "vue"; export * from "vue"; export { Vue };
xiaoxian521/responsive-storage
36
Responsive local storage, supports vue2 and vue3
TypeScript
xiaoxian521
xiaoming
pure-admin
src/index.ts
TypeScript
import { reactive } from "./convert"; import { StorageOpts } from "./types"; export default class Storage { static _nameSpace = "rs-"; static _getStaticKey = (nameSpace: string, key: string) => `${nameSpace ?? this._nameSpace}${key}`; static install(app: any, options: StorageOpts) { const { nameSpace = this._nameSpace, memory } = options; memory && this.clearAll(nameSpace, memory); return new Storage(app, options); } static clearAll(nameSpace: string, memory: object) { Object.keys(memory).forEach(key => { const alias: string = nameSpace + key; if (Object.prototype.hasOwnProperty.call(window.localStorage, alias)) { window.localStorage.removeItem(alias); } }); } static get(key: string) { return JSON.parse(window.localStorage.getItem(key) as string); } static set(key: string, val: string) { val = typeof val === "object" ? JSON.stringify(val) : val; window.localStorage.setItem(key, val); } static getData(key: string, nameSpace?: string) { if ( Object.prototype.hasOwnProperty.call( window.localStorage, this._getStaticKey(nameSpace!, key) ) ) return JSON.parse( window.localStorage.getItem( this._getStaticKey(nameSpace!, key) ) as string ); } public constructor(app: any, options: StorageOpts) { const that = Storage; const { version = 3, nameSpace = that._nameSpace, memory } = options; const _getKey = (key: string): string => nameSpace + key; /** * Vue2 uses defineReactive to create responsive storage * Vue3 uses reactive to create responsive storage */ let _storage: any = version === 3 ? reactive(memory) : memory; if (Object.keys(_storage).length === 0) console.warn("key cannot be empty"); Object.keys(_storage).forEach(key => { const val = _storage[key]; that.set(_getKey(key), val); Reflect.defineProperty(_storage, key, { get: () => that.get(_getKey(key)), set: val => that.set(_getKey(key), val), configurable: true }); if (version === 2) app.util.defineReactive(_storage, key, _storage[key]); }); let _target = version === 3 ? app.config.globalProperties : app.prototype; Reflect.defineProperty(_target, "$storage", { get: () => _storage }); } }
xiaoxian521/responsive-storage
36
Responsive local storage, supports vue2 and vue3
TypeScript
xiaoxian521
xiaoming
pure-admin
src/types.ts
TypeScript
export type Version = 2 | 3; export interface StorageOpts { /** vue版本 可选2、3 默认3 */ version?: Version; /** 命名空间 默认 `rs-` */ nameSpace?: string; /** 需要存储的响应式对象 */ memory: object; }
xiaoxian521/responsive-storage
36
Responsive local storage, supports vue2 and vue3
TypeScript
xiaoxian521
xiaoming
pure-admin
tsup.config.ts
TypeScript
import { defineConfig } from "tsup"; const config = { dts: true, clean: true, minify: true, outDir: "dist", sourcemap: false, external: ["vue"] }; export default defineConfig([ { entry: ["src/index.ts"], format: ["esm"], ...config } ]);
xiaoxian521/responsive-storage
36
Responsive local storage, supports vue2 and vue3
TypeScript
xiaoxian521
xiaoming
pure-admin
.eslintrc.js
JavaScript
// eslint-disable-next-line @typescript-eslint/no-var-requires module.exports = require("./.eslintrc.ts").default
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
.eslintrc.ts
TypeScript
exports.default = { extends: [ "plugin:import/typescript", "plugin:@typescript-eslint/recommended" ], settings: { "import/resolver": { node: { extensions: [".js", ".jsx", ".mjs", ".ts", ".tsx", ".d.ts"] } } }, rules: { "import/named": "off", // TS "@typescript-eslint/type-annotation-spacing": ["error", {}], "@typescript-eslint/consistent-type-imports": [ "error", { prefer: "type-imports", disallowTypeAnnotations: false } ], "@typescript-eslint/consistent-type-definitions": ["error", "interface"], "@typescript-eslint/consistent-indexed-object-style": ["error", "record"], // Override JS "no-useless-constructor": "off", indent: "off", "@typescript-eslint/indent": [ "error", 2, { SwitchCase: 1, VariableDeclarator: 1, outerIIFEBody: 1, MemberExpression: 1, FunctionDeclaration: { parameters: 1, body: 1 }, FunctionExpression: { parameters: 1, body: 1 }, CallExpression: { arguments: 1 }, ArrayExpression: 1, ObjectExpression: 1, ImportDeclaration: 1, flatTernaryExpressions: false, ignoreComments: false, ignoredNodes: [ "TemplateLiteral *", "JSXElement", "JSXElement > *", "JSXAttribute", "JSXIdentifier", "JSXNamespacedName", "JSXMemberExpression", "JSXSpreadAttribute", "JSXExpressionContainer", "JSXOpeningElement", "JSXClosingElement", "JSXFragment", "JSXOpeningFragment", "JSXClosingFragment", "JSXText", "JSXEmptyExpression", "JSXSpreadChild", "TSTypeParameterInstantiation" ], offsetTernaryExpressions: true } ], "no-unused-vars": "off", "@typescript-eslint/no-unused-vars": [ "error", { argsIgnorePattern: "^_" } ], "no-redeclare": "off", "@typescript-eslint/no-redeclare": "error", "no-use-before-define": "off", "@typescript-eslint/no-use-before-define": [ "error", { functions: false, classes: false, variables: true } ], "brace-style": "off", "comma-dangle": "off", "object-curly-spacing": "off", "@typescript-eslint/object-curly-spacing": ["error", "always"], semi: "off", "@typescript-eslint/quotes": ["error"], "space-before-blocks": "off", "@typescript-eslint/space-before-blocks": ["error", "always"], "space-before-function-paren": "off", "@typescript-eslint/space-before-function-paren": [ "error", { anonymous: "always", named: "never", asyncArrow: "always" } ], "space-infix-ops": "off", "@typescript-eslint/space-infix-ops": "error", "keyword-spacing": "off", "@typescript-eslint/keyword-spacing": [ "error", { before: true, after: true } ], "comma-spacing": "off", "@typescript-eslint/comma-spacing": [ "error", { before: false, after: true } ], "no-extra-parens": "off", "@typescript-eslint/no-extra-parens": ["error", "functions"], "no-dupe-class-members": "off", "@typescript-eslint/no-dupe-class-members": "error", "no-loss-of-precision": "off", "@typescript-eslint/no-loss-of-precision": "error", "lines-between-class-members": "off", "@typescript-eslint/lines-between-class-members": [ "error", "always", { exceptAfterSingleLine: true } ], "@typescript-eslint/naming-convention": "off", "@typescript-eslint/explicit-function-return-type": "off", "@typescript-eslint/explicit-member-accessibility": "off", "@typescript-eslint/no-explicit-any": "off", "@typescript-eslint/parameter-properties": "off", "@typescript-eslint/no-empty-interface": "off", "@typescript-eslint/ban-ts-ignore": "off", "@typescript-eslint/no-empty-function": "off", "@typescript-eslint/no-non-null-assertion": "off", "@typescript-eslint/explicit-module-boundary-types": "off", "@typescript-eslint/ban-types": "off", "@typescript-eslint/no-namespace": "off", "@typescript-eslint/triple-slash-reference": "off", "@typescript-eslint/prefer-ts-expect-error": "off", "@typescript-eslint/ban-ts-comment": "off", "@typescript-eslint/semi": "off" } };
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
.prettierrc.js
JavaScript
module.exports = { bracketSpacing: true, singleQuote: false, arrowParens: "avoid", trailingComma: "none" }
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
jest.config.js
JavaScript
module.exports = { preset: "ts-jest", testEnvironment: "node" }
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/angular.ts
TypeScript
// @ts-nocheck import { Component } from '@angular/core' @Component({ selector: 'app-list-item', template: ` <article class="flex items-start space-x-6 p-6"> <img [src]="movie.image" alt="" width="60" height="88" class="flex-none rounded-md bg-slate-100" /> <div class="relative min-w-0 flex-auto"> <h2 class="truncate pr-20 font-semibold text-slate-900"> {{ movie.title }} </h2> <dl class="mt-2 flex flex-wrap text-sm font-medium leading-6"> <div class="absolute top-0 right-0 flex items-center space-x-1"> <dt class="text-sky-500"> <span class="sr-only">Star rating</span> <svg width="16" height="20" fill="currentColor"> <path d="M7.05 3.691c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.372 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.539 1.118l-2.8-2.034a1 1 0 00-1.176 0l-2.8 2.034c-.783.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.363-1.118L.98 9.483c-.784-.57-.381-1.81.587-1.81H5.03a1 1 0 00.95-.69L7.05 3.69z" /> </svg> </dt> <dd>{{ movie.starRating }}</dd> </div> <div> <dt class="sr-only">Rating</dt> <dd class="rounded px-1.5 ring-1 ring-slate-200"> {{ movie.rating }} </dd> </div> <div class="ml-2"> <dt class="sr-only">Year</dt> <dd>{{ movie.year }}</dd> </div> <div> <dt class="sr-only">Genre</dt> <dd class="flex items-center"> <svg width="2" height="2" fill="currentColor" class="mx-2 text-slate-300" aria-hidden="true" > <circle cx="1" cy="1" r="1" /> </svg> {{ movie.genre }} </dd> </div> <div> <dt class="sr-only">Runtime</dt> <dd class="flex items-center"> <svg width="2" height="2" fill="currentColor" class="mx-2 text-slate-300" aria-hidden="true" > <circle cx="1" cy="1" r="1" /> </svg> {{ movie.runtime }} </dd> </div> <div class="mt-2 w-full flex-none font-normal"> <dt class="sr-only">Cast</dt> <dd class="text-slate-400">{{ movie.cast }}</dd> </div> </dl> </div> </article> ` }) export class ListItemComponent { @Input() movie!: { image: string title: string starRating: string rating: string year: string genre: string runtime: string cast: string } }
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/react.js
JavaScript
export default function ListItem({ movie }) { return ( <article className="flex items-start space-x-6 p-6"> <img src={movie.image} alt="" width="60" height="88" className="flex-none rounded-md bg-slate-100" /> <div className="relative min-w-0 flex-auto"> <h2 className="truncate pr-20 font-semibold text-slate-900"> {movie.title} </h2> <dl className="mt-2 flex flex-wrap text-sm font-medium leading-6"> <div className="absolute top-0 right-0 flex items-center space-x-1"> <dt className="text-sky-500"> <span className="sr-only">Star rating</span> <svg width="16" height="20" fill="currentColor"> <path d="M7.05 3.691c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.372 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.539 1.118l-2.8-2.034a1 1 0 00-1.176 0l-2.8 2.034c-.783.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.363-1.118L.98 9.483c-.784-.57-.381-1.81.587-1.81H5.03a1 1 0 00.95-.69L7.05 3.69z" /> </svg> </dt> <dd>{movie.starRating}</dd> </div> <div> <dt className="sr-only">Rating</dt> <dd className="rounded px-1.5 ring-1 ring-slate-200"> {movie.rating} </dd> </div> <div className="ml-2"> <dt className="sr-only">Year</dt> <dd>{movie.year}</dd> </div> <div> <dt className="sr-only">Genre</dt> <dd className="flex items-center"> <svg width="2" height="2" fill="currentColor" className="mx-2 text-slate-300" aria-hidden="true"> <circle cx="1" cy="1" r="1" /> </svg> {movie.genre} </dd> </div> <div> <dt className="sr-only">Runtime</dt> <dd className="flex items-center"> <svg width="2" height="2" fill="currentColor" className="mx-2 text-slate-300" aria-hidden="true"> <circle cx="1" cy="1" r="1" /> </svg> {movie.runtime} </dd> </div> <div className="mt-2 w-full flex-none font-normal"> <dt className="sr-only">Cast</dt> <dd className="text-slate-400">{movie.cast}</dd> </div> </dl> </div> </article> ) }
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/sample.blade.php
PHP
<article class="flex items-start space-x-6 p-6"> <img src="{{ $movie->image }}" alt="" width="60" height="88" class="flex-none rounded-md bg-slate-100" /> <div class="min-w-0 relative flex-auto"> <h2 class="font-semibold text-slate-900 truncate pr-20">{{ $movie->title }}</h2> <dl class="mt-2 flex flex-wrap text-sm leading-6 font-medium"> <div class="absolute top-0 right-0 flex items-center space-x-1"> <dt class="text-sky-500"> <span class="sr-only">Star rating</span> <svg width="16" height="20" fill="currentColor"> <path d="M7.05 3.691c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.372 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.539 1.118l-2.8-2.034a1 1 0 00-1.176 0l-2.8 2.034c-.783.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.363-1.118L.98 9.483c-.784-.57-.381-1.81.587-1.81H5.03a1 1 0 00.95-.69L7.05 3.69z" /> </svg> </dt> <dd>{{ $movie->starRating }}</dd> </div> <div> <dt class="sr-only">Rating</dt> <dd class="px-1.5 ring-1 ring-slate-200 rounded">{{ $movie->rating }}</dd> </div> <div class="ml-2"> <dt class="sr-only">Year</dt> <dd>{{ $movie->year }}</dd> </div> <div> <dt class="sr-only">Genre</dt> <dd class="flex items-center"> <svg width="2" height="2" fill="currentColor" class="mx-2 text-slate-300" aria-hidden="true"> <circle cx="1" cy="1" r="1" /> </svg> {{ $movie->genre }} </dd> </div> <div> <dt class="sr-only">Runtime</dt> <dd class="flex items-center"> <svg width="2" height="2" fill="currentColor" class="mx-2 text-slate-300" aria-hidden="true"> <circle cx="1" cy="1" r="1" /> </svg> {{ $movie->runtime }} </dd> </div> <div class="flex-none w-full mt-2 font-normal"> <dt class="sr-only">Cast</dt> <dd class="text-slate-400">{{ $movie->cast }}</dd> </div> </dl> </div> </article>
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/sample.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <div class="grid grid-cols-1 sm:grid-cols-2 sm:gap-x-8 sm:px-8 sm:py-12 md:py-16" transform=""> <div class="relative z-10 col-start-1 row-start-1 bg-gradient-to-t from-black px-4 pt-40 pb-3 sm:bg-none"> <p class="text-sm font-medium text-white sm:mb-1 sm:text-gray-500"> Entire house </p> <h2 class="text-xl font-semibold text-white sm:text-2xl sm:leading-7 sm:text-black md:text-3xl"> Beach House in Collingwood </h2> </div> <div class="col-start-1 row-start-2 px-4 sm:pb-16"> <div class="my-5 flex items-center text-sm font-medium sm:mt-2 sm:mb-4"> <svg width="20" height="20" fill="currentColor" class="text-violet-600"> <path d="M9.05 3.691c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.372 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.539 1.118l-2.8-2.034a1 1 0 00-1.176 0l-2.8 2.034c-.783.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.363-1.118l-2.8-2.034c-.784-.57-.381-1.81.587-1.81H7.03a1 1 0 00.95-.69L9.05 3.69z" /> </svg> <div class="ml-1"> <span class="text-xl text-black">4.94</span> <span class="sm:hidden md:inline">(128)</span> </div> <div class="mx-2 text-base font-normal">·</div> <div>Collingwood, Ontario</div> </div> <hr class="hidden w-16 border-gray-300 sm:block" /> </div> <div class="col-start-1 row-start-3 space-y-3 px-4"> <p class="flex items-center text-sm font-medium text-black"> <img src="/kevin-francis.jpg" alt="" class="mr-2 h-6 w-6 rounded-full bg-gray-100" /> Hosted by Kevin Francis </p> <button type="button" class="rounded-lg bg-violet-100 px-6 py-2 text-base font-semibold text-violet-700"> Check availability </button> </div> <div class="col-start-1 row-start-1 flex sm:col-start-2 sm:row-span-3"> <div class="grid w-full grid-cols-3 grid-rows-2 gap-2"> <div class="relative col-span-3 row-span-2 md:col-span-2"> <img src="/beach-house.jpg" alt="" class="absolute inset-0 h-full w-full bg-gray-100 object-cover sm:rounded-lg" /> </div> <div class="relative hidden md:block"> <img src="/beach-house-interior.jpg" alt="" class="absolute inset-0 h-full w-full rounded-lg bg-gray-100 object-cover" /> </div> <div class="relative hidden md:block"> <img src="/beach-house-view.jpg" alt="" class="absolute inset-0 h-full w-full rounded-lg bg-gray-100 object-cover" /> </div> </div> </div> </div> </body> </html>
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/sample.svelte
Svelte
<div class="grid grid-cols-1 sm:grid-cols-2 sm:gap-x-8 sm:px-8 sm:py-12 md:py-16" transform=""> <div class="relative z-10 col-start-1 row-start-1 bg-gradient-to-t from-black px-4 pt-40 pb-3 sm:bg-none"> <p class="text-sm font-medium text-white sm:mb-1 sm:text-gray-500"> Entire house </p> <h2 class="text-xl font-semibold text-white sm:text-2xl sm:leading-7 sm:text-black md:text-3xl"> Beach House in Collingwood </h2> </div> <div class="col-start-1 row-start-2 px-4 sm:pb-16"> <div class="my-5 flex items-center text-sm font-medium sm:mt-2 sm:mb-4"> <svg width="20" height="20" fill="currentColor" class="text-violet-600"> <path d="M9.05 3.691c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.372 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.539 1.118l-2.8-2.034a1 1 0 00-1.176 0l-2.8 2.034c-.783.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.363-1.118l-2.8-2.034c-.784-.57-.381-1.81.587-1.81H7.03a1 1 0 00.95-.69L9.05 3.69z" /> </svg> <div class="ml-1"> <span class="text-xl text-black">4.94</span> <span class="sm:hidden md:inline">(128)</span> </div> <div class="mx-2 text-base font-normal">·</div> <div>Collingwood, Ontario</div> </div> <hr class="hidden w-16 border-gray-300 sm:block" /> </div> <div class="col-start-1 row-start-3 space-y-3 px-4"> <p class="flex items-center text-sm font-medium text-black"> <img src="/kevin-francis.jpg" alt="" class="mr-2 h-6 w-6 rounded-full bg-gray-100" /> Hosted by Kevin Francis </p> <button type="button" class="rounded-lg bg-violet-100 px-6 py-2 text-base font-semibold text-violet-700"> Check availability </button> </div> <div class="col-start-1 row-start-1 flex sm:col-start-2 sm:row-span-3"> <div class="grid w-full grid-cols-3 grid-rows-2 gap-2"> <div class="relative col-span-3 row-span-2 md:col-span-2"> <img src="/beach-house.jpg" alt="" class="absolute inset-0 h-full w-full bg-gray-100 object-cover sm:rounded-lg" /> </div> <div class="relative hidden md:block"> <img src="/beach-house-interior.jpg" alt="" class="absolute inset-0 h-full w-full rounded-lg bg-gray-100 object-cover" /> </div> <div class="relative hidden md:block"> <img src="/beach-house-view.jpg" alt="" class="absolute inset-0 h-full w-full rounded-lg bg-gray-100 object-cover" /> </div> </div> </div> </div> <style global lang="postcss"> @tailwind base; @tailwind components; @tailwind utilities; </style>
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/sample.tsx
TypeScript (TSX)
// @ts-nocheck import type { FC } from 'react' import { ButtonProps } from './Button.types' import clsx from 'clsx' export const Button: FC<ButtonProps> = (props) => { const btn = clsx('bg-blue-100') const { disabled } = props return ( <> <button {...props} className={clsx( 'rounded-full border border-gray-400 bg-sky-200 py-1 px-3 lg:py-2 lg:px-4 text-sm lg:text-base font-medium text-gray-800 hover:bg-sky-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-sky-500 disabled:opacity-50 disabled:cursor-not-allowed', disabled && 'bg-sky-200/70 opacity-70' )} style={{ transform: 'translate3d(0, 0, 0)' }}> {props.children} </button> <div class="grid grid-cols-1 sm:grid-cols-2 sm:gap-x-8 sm:px-8 sm:py-12 md:py-16" transform=""> <div class="relative z-10 col-start-1 row-start-1 bg-gradient-to-t from-black px-4 pt-40 pb-3 sm:bg-none"> <p class="p-[calc(100%*2.5)] text-sm font-medium text-white sm:mb-1 sm:text-gray-500"> Entire house </p> <h2 class="text-xl font-semibold text-white sm:text-2xl sm:leading-7 sm:text-black md:text-3xl"> Beach House in Collingwood </h2> </div> <div class="col-start-1 row-start-2 px-4 sm:pb-16"> <div class="my-5 flex items-center text-sm font-medium sm:mt-2 sm:mb-4"> <svg width="20" height="20" fill="currentColor" class="text-violet-600"> <path d="M9.05 3.691c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.372 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.539 1.118l-2.8-2.034a1 1 0 00-1.176 0l-2.8 2.034c-.783.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.363-1.118l-2.8-2.034c-.784-.57-.381-1.81.587-1.81H7.03a1 1 0 00.95-.69L9.05 3.69z" /> </svg> <div class="ml-1 hover:bg-sky-300 focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed"> <span class="text-xl text-black">4.94</span> <span class="sm:hidden md:inline">(128)</span> </div> <div class="mx-2 text-base font-normal">·</div> </div> <hr class="hidden w-16 border-gray-300 sm:block" /> </div> <div class="col-start-1 row-start-3 space-y-3 px-4"> <p class="flex items-center text-sm font-medium text-black"> <img src="/kevin-francis.jpg" alt="" class="mr-2 h-6 w-6 rounded-full bg-gray-100" /> Hosted by Kevin Francis </p> <button type="button" class="rounded-lg bg-violet-100 px-6 py-2 text-base font-semibold text-violet-700"> Check availability </button> </div> <div class="col-start-1 row-start-1 flex sm:col-start-2 sm:row-span-3"> <div class="grid w-full grid-cols-3 grid-rows-2 gap-2"> <div class="relative col-span-3 row-span-2 md:col-span-2"> <img src="/beach-house.jpg" alt="" class="absolute inset-0 h-full w-full bg-gray-100 object-cover sm:rounded-lg" /> </div> <div class="relative hidden md:block"> <img src="/beach-house-interior.jpg" alt="" class="absolute inset-0 h-full w-full rounded-lg bg-gray-100 object-cover" /> </div> <div class="relative hidden md:block"> <img src="/beach-house-view.jpg" alt="" class="absolute inset-0 h-full w-full rounded-lg bg-gray-100 object-cover" /> </div> </div> </div> </div> </> ) }
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/sample.vue
Vue
<template> <article class="flex items-start space-x-6 p-6"> <img :src="movie.image" alt="" width="60" height="88" class="flex-none rounded-md bg-slate-100" /> <div class="relative min-w-0 flex-auto"> <h2 class="truncate pr-20 font-semibold text-slate-900"> {{ movie.title }} </h2> <dl class="mt-2 flex flex-wrap text-sm font-medium leading-6"> <div class="absolute top-0 right-0 flex items-center space-x-1"> <dt class="text-sky-500"> <span class="sr-only">Star rating</span> <svg width="16" height="20" fill="currentColor"> <path d="M7.05 3.691c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.372 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.539 1.118l-2.8-2.034a1 1 0 00-1.176 0l-2.8 2.034c-.783.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.363-1.118L.98 9.483c-.784-.57-.381-1.81.587-1.81H5.03a1 1 0 00.95-.69L7.05 3.69z" /> </svg> </dt> <dd>{{ movie.starRating }}</dd> </div> <div> <dt class="sr-only">Rating</dt> <dd class="rounded px-1.5 ring-1 ring-slate-200"> {{ movie.rating }} </dd> </div> <div class="ml-2"> <dt class="sr-only">Year</dt> <dd>{{ movie.year }}</dd> </div> <div> <dt class="sr-only">Genre</dt> <dd class="flex items-center"> <svg width="2" height="2" fill="currentColor" class="mx-2 text-slate-300" aria-hidden="true"> <circle cx="1" cy="1" r="1" /> </svg> {{ movie.genre }} </dd> </div> <div> <dt class="sr-only">Runtime</dt> <dd class="flex items-center"> <svg width="2" height="2" fill="currentColor" class="mx-2 text-slate-300" aria-hidden="true"> <circle cx="1" cy="1" r="1" /> </svg> {{ movie.runtime }} </dd> </div> <div class="mt-2 w-full flex-none font-normal"> <dt class="sr-only">Cast</dt> <dd class="text-slate-400">{{ movie.cast }}</dd> </div> </dl> </div> </article> </template> <script> export default { props: ['movie'] } </script>
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/tailwind.config.js
JavaScript
module.exports = { mode: 'jit', theme: {}, variants: { extend: {} } }
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/tailwindcss/1 Layout/index.html
HTML
<!-- Layout --> <!-- https://tailwindcss.com/docs/aspect-ratio --> <div class="aspect-auto"></div> <div class="aspect-square"></div> <div class="aspect-video"></div> <div class="aspect-[4/3]"></div> <!-- https://tailwindcss.com/docs/container --> <div class="container"></div> <!-- https://tailwindcss.com/docs/columns --> <div class="columns-1"></div> <div class="columns-12"></div> <div class="columns-auto"></div> <div class="columns-3xs"></div> <div class="columns-xs"></div> <div class="columns-7xl"></div> <div class="columns-[10rem]"></div> <!-- https://tailwindcss.com/docs/break-after --> <div class="break-after-auto"></div> <div class="break-after-avoid-page"></div> <div class="break-after-column"></div> <!-- https://tailwindcss.com/docs/break-before --> <div class="break-before-auto"></div> <div class="break-before-avoid-page"></div> <div class="break-before-column"></div> <!-- https://tailwindcss.com/docs/break-inside --> <div class="break-inside-auto"></div> <div class="break-inside-avoid-page"></div> <!-- https://tailwindcss.com/docs/box-decoration-break --> <div class="box-decoration-clone"></div> <div class="box-decoration-slice"></div> <!-- https://tailwindcss.com/docs/box-sizing --> <div class="box-border"></div> <div class="box-content"></div> <!-- https://tailwindcss.com/docs/display --> <div class="block"></div> <div class="inline-block"></div> <div class="inline"></div> <div class="flex"></div> <div class="inline-flex"></div> <div class="table"></div> <div class="inline-table"></div> <div class="table-caption"></div> <div class="table-column-group"></div> <div class="flow-root"></div> <div class="grid"></div> <div class="inline-grid"></div> <div class="contents"></div> <div class="list-item"></div> <div class="hidden"></div> <!-- https://tailwindcss.com/docs/float --> <div class="float-right"></div> <div class="float-left"></div> <div class="float-none"></div> <!-- https://tailwindcss.com/docs/clear --> <div class="clear-left"></div> <!-- https://tailwindcss.com/docs/isolation --> <div class="isolate"></div> <div class="isolation-auto"></div> <!-- https://tailwindcss.com/docs/object-position --> <div class="object-bottom"></div> <div class="object-right-bottom"></div> <!-- https://tailwindcss.com/docs/overflow --> <div class="overflow-auto"></div> <div class="overflow-x-clip"></div> <!-- https://tailwindcss.com/docs/overscroll-behavior --> <div class="overscroll-auto"></div> <div class="overscroll-y-contain"></div> <!-- https://tailwindcss.com/docs/position --> <div class="static"></div> <div class="fixed"></div> <div class="absolute"></div> <div class="relative"></div> <div class="sticky"></div> <!-- https://tailwindcss.com/docs/top-right-bottom-left --> <div class="inset-0"></div> <div class="inset-x-0"></div> <div class="top-0"></div> <div class="right-0"></div> <div class="bottom-0"></div> <div class="left-0"></div> <div class="inset-px"></div> <div class="inset-x-px"></div> <div class="top-px"></div> <!-- https://tailwindcss.com/docs/visibility --> <div class="visible"></div> <div class="invisible"></div> <div class="collapse"></div> <!-- https://tailwindcss.com/docs/z-index --> <div class="z-0"></div> <div class="z-auto"></div> <div class="z-[100]"></div>
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/tailwindcss/10 Tables/index.html
HTML
<!-- Tables --> <!-- https://tailwindcss.com/docs/border-collapse --> <div class="border-collapse"></div> <div class="border-separate"></div> <!-- https://tailwindcss.com/docs/border-spacing --> <div class="border-spacing-0"></div> <div class="border-spacing-y-96"></div> <div class="border-spacing-[7px]"></div> <!-- https://tailwindcss.com/docs/table-layout --> <div class="table-auto"></div> <div class="table-fixed"></div>
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/tailwindcss/11 Transitions & Animation/index.html
HTML
<!-- Transitions & Animation --> <!-- https://tailwindcss.com/docs/transition-property --> <div class="transition-none"></div> <div class="transition-all"></div> <div class="transition"></div> <div class="transition-colors"></div> <div class="transition-opacity"></div> <div class="transition-shadow"></div> <div class="transition-transform"></div> <div class="transition-[height]"></div> <!-- https://tailwindcss.com/docs/transition-duration --> <div class="duration-75"></div> <div class="duration-[2000ms]"></div> <!-- https://tailwindcss.com/docs/transition-timing-function --> <div class="ease-linear"></div> <div class="ease-in-out"></div> <div class="ease-[cubic-bezier(0.95,0.05,0.795,0.035)]"></div> <!-- https://tailwindcss.com/docs/transition-delay --> <div class="delay-75"></div> <div class="delay-[2000ms]"></div> <!-- https://tailwindcss.com/docs/animation --> <div class="animate-none"></div> <div class="animate-spin"></div> <div class="animate-ping"></div> <div class="animate-[wiggle_1s_ease-in-out_infinite]"></div>
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/tailwindcss/12 Transforms/index.html
HTML
<!-- Transforms --> <!-- https://tailwindcss.com/docs/scale --> <div class="scale-0"></div> <div class="scale-y-75"></div> <div class="scale-[1.7]"></div> <!-- https://tailwindcss.com/docs/rotate --> <div class="rotate-0"></div> <div class="rotate-[17deg]"></div> <!-- https://tailwindcss.com/docs/translate --> <div class="translate-x-0"></div> <div class="translate-y-full"></div> <div class="translate-y-[17rem]"></div> <!-- https://tailwindcss.com/docs/skew --> <div class="skew-x-0"></div> <div class="skew-y-[17deg]"></div> <!-- https://tailwindcss.com/docs/transform-origin --> <div class="origin-center"></div> <div class="origin-bottom-left"></div> <div class="origin-[33%_75%]"></div>
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/tailwindcss/13 Interactivity/index.html
HTML
<!-- Interactivity --> <!-- https://tailwindcss.com/docs/accent-color --> <div class="accent-inherit"></div> <div class="accent-stone-600"></div> <div class="accent-[#50d71e]"></div> <!-- https://tailwindcss.com/docs/appearance --> <div class="appearance-none"></div> <!-- https://tailwindcss.com/docs/cursor --> <div class="cursor-auto"></div> <div class="cursor-not-allowed"></div> <div class="cursor-[url(hand.cur),_pointer]"></div> <!-- https://tailwindcss.com/docs/caret-color --> <div class="caret-inherit"></div> <div class="caret-rose-600"></div> <div class="caret-[#50d71e]"></div> <!-- https://tailwindcss.com/docs/pointer-events --> <div class="pointer-events-none"></div> <div class="pointer-events-auto"></div> <!-- https://tailwindcss.com/docs/resize --> <div class="resize-none"></div> <div class="resize"></div> <!-- https://tailwindcss.com/docs/scroll-behavior --> <div class="scroll-auto"></div> <div class="scroll-smooth"></div> <!-- https://tailwindcss.com/docs/scroll-margin --> <div class="scroll-m-0"></div> <div class="scroll-m-[24rem]"></div> <!-- https://tailwindcss.com/docs/scroll-padding --> <div class="scroll-p-0"></div> <div class="scroll-p-[24rem]"></div> <!-- https://tailwindcss.com/docs/scroll-snap-align --> <div class="snap-start"></div> <div class="snap-align-none"></div> <!-- https://tailwindcss.com/docs/scroll-snap-stop --> <div class="snap-normal"></div> <div class="snap-always"></div> <!-- https://tailwindcss.com/docs/scroll-snap-type --> <div class="snap-none"></div> <!-- https://tailwindcss.com/docs/touch-action --> <div class="touch-auto"></div> <div class="touch-manipulation"></div> <!-- https://tailwindcss.com/docs/user-select --> <div class="select-none"></div> <div class="select-text"></div> <div class="select-all"></div> <div class="select-auto"></div> <!-- https://tailwindcss.com/docs/will-change --> <div class="will-change-auto"></div> <div class="will-change-[top,left]"></div>
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/tailwindcss/14 SVG/index.html
HTML
<!-- SVG --> <!-- https://tailwindcss.com/docs/fill --> <div class="fill-none"></div> <div class="fill-neutral-800"></div> <div class="fill-[#243c5a]"></div> <!-- https://tailwindcss.com/docs/stroke --> <div class="stroke-none"></div> <div class="stroke-gray-500"></div> <div class="stroke-[#243c5a]"></div> <!-- https://tailwindcss.com/docs/stroke-width --> <div class="stroke-0"></div> <div class="stroke-[2px]"></div>
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/tailwindcss/15 Accessibility/index.html
HTML
<!-- Accessibility --> <!-- https://tailwindcss.com/docs/screen-readers --> <div class="sr-only"></div> <div class="not-sr-only"></div>
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/tailwindcss/2 Flexbox & Grid/index.html
HTML
<!-- Flexbox & Grid --> <!-- https://tailwindcss.com/docs/flex-basis --> <div class="basis-0"></div> <div class="basis-auto"></div> <div class="basis-px"></div> <div class="basis-0.5"></div> <div class="basis-1/5"></div> <div class="basis-full"></div> <div class="basis-[14.2857143%]"></div> <!-- https://tailwindcss.com/docs/flex-direction --> <div class="flex-row"></div> <div class="flex-row-reverse"></div> <div class="flex-col"></div> <div class="flex-col-reverse"></div> <!-- https://tailwindcss.com/docs/flex-wrap --> <div class="flex-wrap"></div> <div class="flex-wrap-reverse"></div> <div class="flex-nowrap"></div> <!-- https://tailwindcss.com/docs/flex --> <div class="flex-1"></div> <div class="flex-auto"></div> <div class="flex-initial"></div> <div class="flex-none"></div> <div class="flex-[2_2_0%]"></div> <!-- https://tailwindcss.com/docs/flex-grow --> <div class="grow"></div> <div class="grow-0"></div> <div class="grow-[2]"></div> <!-- https://tailwindcss.com/docs/flex-shrink --> <div class="shrink"></div> <div class="shrink-0"></div> <div class="shrink-[2]"></div> <!-- https://tailwindcss.com/docs/order --> <div class="order-1"></div> <div class="order-first"></div> <div class="order-last"></div> <div class="order-none"></div> <!-- https://tailwindcss.com/docs/grid-template-columns --> <div class="grid-cols-1"></div> <div class="grid-cols-none"></div> <!-- https://tailwindcss.com/docs/grid-column --> <div class="col-auto"></div> <div class="col-span-1"></div> <div class="col-span-full"></div> <div class="col-start-1"></div> <div class="col-end-auto"></div> <!-- https://tailwindcss.com/docs/grid-template-rows --> <div class="grid-rows-1"></div> <div class="grid-rows-none"></div> <!-- https://tailwindcss.com/docs/grid-row --> <div class="row-auto"></div> <div class="row-span-1"></div> <div class="row-start-auto"></div> <div class="row-end-auto"></div> <!-- https://tailwindcss.com/docs/grid-auto-flow --> <div class="grid-flow-row"></div> <div class="grid-flow-col-dense"></div> <!-- https://tailwindcss.com/docs/grid-auto-columns --> <div class="auto-cols-auto"></div> <div class="auto-cols-fr"></div> <!-- https://tailwindcss.com/docs/grid-auto-rows --> <div class="auto-rows-auto"></div> <div class="auto-rows-fr"></div> <!-- https://tailwindcss.com/docs/gap --> <div class="gap-0"></div> <div class="gap-x-0"></div> <div class="gap-px"></div> <div class="gap-y-0.5"></div> <!-- https://tailwindcss.com/docs/justify-content --> <div class="justify-start"></div> <div class="justify-end"></div> <div class="justify-center"></div> <div class="justify-between"></div> <div class="justify-around"></div> <div class="justify-evenly"></div> <!-- https://tailwindcss.com/docs/justify-items --> <div class="justify-items-start"></div> <div class="justify-items-end"></div> <div class="justify-items-center"></div> <div class="justify-items-stretch"></div> <!-- https://tailwindcss.com/docs/justify-self --> <div class="justify-self-auto"></div> <div class="justify-self-start"></div> <div class="justify-self-end"></div> <div class="justify-self-center"></div> <div class="justify-self-stretch"></div> <!-- https://tailwindcss.com/docs/align-content --> <div class="content-center"></div> <div class="content-start"></div> <div class="content-end"></div> <div class="content-between"></div> <div class="content-around"></div> <div class="content-evenly"></div> <div class="content-baseline"></div> <!-- https://tailwindcss.com/docs/align-items --> <div class="items-start"></div> <div class="items-end"></div> <div class="items-center"></div> <div class="items-baseline"></div> <div class="items-stretch"></div> <!-- https://tailwindcss.com/docs/align-self --> <div class="self-auto"></div> <div class="self-start"></div> <div class="self-end"></div> <div class="self-center"></div> <div class="self-stretch"></div> <div class="self-baseline"></div> <!-- https://tailwindcss.com/docs/place-content --> <div class="place-content-center"></div> <div class="place-content-start"></div> <div class="place-content-end"></div> <div class="place-content-between"></div> <div class="place-content-around"></div> <div class="place-content-evenly"></div> <div class="place-content-baseline"></div> <div class="place-content-stretch"></div> <!-- https://tailwindcss.com/docs/place-items --> <div class="place-items-start"></div> <div class="place-items-end"></div> <div class="place-items-center"></div> <div class="place-items-baseline"></div> <div class="place-items-stretch"></div> <!-- https://tailwindcss.com/docs/place-self --> <div class="place-self-auto"></div> <div class="place-self-start"></div> <div class="place-self-end"></div> <div class="place-self-center"></div> <div class="place-self-stretch"></div>
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/tailwindcss/3 Spacing/index.html
HTML
<!-- Spacing --> <!-- https://tailwindcss.com/docs/padding --> <div class="p-0"></div> <div class="px-0"></div> <div class="py-0"></div> <div class="pt-0"></div> <div class="pr-0"></div> <div class="pb-0"></div> <div class="pl-12"></div> <!-- https://tailwindcss.com/docs/margin --> <div class="m-0"></div> <div class="mx-0"></div> <div class="my-0"></div> <div class="mt-0"></div> <div class="mr-0"></div> <div class="mb-0"></div> <div class="ml-0"></div> <div class="m-px"></div> <div class="mx-px"></div> <div class="ml-1.5"></div> <div class="mt-auto"></div> <div class="ml-auto"></div> <!-- https://tailwindcss.com/docs/space --> <div class="space-x-0"></div> <div class="space-y-0.5"></div> <div class="space-y-reverse"></div> <div class="space-x-reverse"></div>
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/tailwindcss/4 Sizing/index.html
HTML
<!-- Sizing --> <!-- https://tailwindcss.com/docs/width --> <div class="w-0"></div> <div class="w-px"></div> <div class="w-0.5"></div> <div class="w-1/4"></div> <div class="w-screen"></div> <div class="w-fit"></div> <div class="w-[32rem]"></div> <!-- https://tailwindcss.com/docs/min-width --> <div class="min-w-0"></div> <div class="min-w-full"></div> <div class="min-w-min"></div> <div class="min-w-max"></div> <div class="min-w-fit"></div> <!-- https://tailwindcss.com/docs/max-width --> <div class="max-w-0"></div> <div class="max-w-none"></div> <div class="max-w-xs"></div> <div class="max-w-screen-md"></div> <div class="max-w-screen-2xl"></div> <!-- https://tailwindcss.com/docs/height --> <div class="h-0"></div> <div class="h-px"></div> <div class="h-0.5"></div> <div class="h-fit"></div> <!-- https://tailwindcss.com/docs/padding --> <div class="min-h-0"></div> <div class="min-h-screen"></div> <!-- https://tailwindcss.com/docs/max-height --> <div class="max-h-0"></div> <div class="max-h-screen"></div>
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/tailwindcss/5 Typography/index.html
HTML
<!-- Typography --> <!-- https://tailwindcss.com/docs/font-family --> <div class="font-sans"></div> <div class="font-serif"></div> <div class="font-mono"></div> <!-- https://tailwindcss.com/docs/font-size --> <div class="text-xs"></div> <div class="text-9xl"></div> <!-- https://tailwindcss.com/docs/font-smoothing --> <div class="antialiased"></div> <div class="subpixel-antialiased"></div> <!-- https://tailwindcss.com/docs/font-style --> <div class="italic"></div> <div class="not-italic"></div> <!-- hhttps://tailwindcss.com/docs/font-weight --> <div class="font-thin"></div> <div class="font-extralight"></div> <div class="font-light"></div> <div class="font-normal"></div> <div class="font-medium"></div> <div class="font-semibold"></div> <div class="font-bold"></div> <div class="font-extrabold"></div> <div class="font-black"></div> <!-- https://tailwindcss.com/docs/font-variant-numeric --> <div class="normal-nums"></div> <div class="ordinal"></div> <div class="slashed-zero"></div> <div class="lining-nums"></div> <div class="oldstyle-nums"></div> <div class="proportional-nums"></div> <div class="tabular-nums"></div> <div class="diagonal-fractions"></div> <div class="stacked-fractions"></div> <!-- https://tailwindcss.com/docs/letter-spacing --> <div class="tracking-tighter"></div> <div class="tracking-tight"></div> <div class="tracking-normal"></div> <div class="tracking-wide"></div> <div class="tracking-wider"></div> <div class="tracking-widest"></div> <!-- https://tailwindcss.com/docs/line-height --> <div class="leading-3"></div> <div class="leading-none"></div> <div class="leading-loose"></div> <!-- https://tailwindcss.com/docs/list-style-type --> <div class="list-none"></div> <div class="list-disc"></div> <div class="list-decimal"></div> <!-- https://tailwindcss.com/docs/list-style-position --> <div class="list-inside"></div> <div class="list-outside"></div> <!-- https://tailwindcss.com/docs/text-align --> <div class="text-left"></div> <div class="text-center"></div> <div class="text-right"></div> <div class="text-justify"></div> <div class="text-start"></div> <div class="text-end"></div> <!-- https://tailwindcss.com/docs/text-color --> <div class="text-inherit"></div> <div class="text-current"></div> <div class="text-zinc-900"></div> <div class="text-[#50d71e]"></div> <!-- https://tailwindcss.com/docs/text-decoration --> <div class="underline"></div> <div class="overline"></div> <div class="line-through"></div> <div class="no-underline"></div> <!-- https://tailwindcss.com/docs/text-decoration-color --> <div class="decoration-inherit"></div> <div class="decoration-red-200"></div> <div class="decoration-[#50d71e]"></div> <!-- https://tailwindcss.com/docs/text-decoration-style --> <div class="decoration-solid"></div> <div class="decoration-double"></div> <div class="decoration-dotted"></div> <div class="decoration-dashed"></div> <div class="decoration-wavy"></div> <!-- https://tailwindcss.com/docs/text-decoration-thickness --> <div class="decoration-auto"></div> <div class="decoration-from-font"></div> <div class="decoration-8"></div> <div class="decoration-[3px]"></div> <!-- https://tailwindcss.com/docs/text-underline-offset --> <div class="underline-offset-auto"></div> <div class="underline-offset-0"></div> <div class="underline-offset-[3px]"></div> <!-- https://tailwindcss.com/docs/text-transform --> <div class="uppercase"></div> <div class="lowercase"></div> <div class="capitalize"></div> <div class="normal-case"></div> <!-- https://tailwindcss.com/docs/text-overflow --> <div class="truncate"></div> <div class="text-ellipsis"></div> <div class="text-clip"></div> <!-- https://tailwindcss.com/docs/text-indent --> <div class="indent-0"></div> <div class="indent-[50%]"></div> <!-- https://tailwindcss.com/docs/vertical-align --> <div class="align-baseline"></div> <div class="align-top"></div> <div class="align-middle"></div> <div class="align-super"></div> <div class="align-bottom"></div> <div class="align-text-top"></div> <div class="align-text-bottom"></div> <div class="align-sub"></div> <div class="align-super"></div> <!-- https://tailwindcss.com/docs/whitespace --> <div class="whitespace-normal"></div> <div class="whitespace-nowrap"></div> <div class="whitespace-pre"></div> <div class="whitespace-pre-line"></div> <div class="whitespace-pre-wrap"></div> <!-- https://tailwindcss.com/docs/word-break --> <div class="break-normal"></div> <div class="break-words"></div> <div class="break-all"></div> <div class="break-keep"></div> <!-- https://tailwindcss.com/docs/content --> <div class="content-none"></div>
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/tailwindcss/6 Backgrounds/index.html
HTML
<!-- Backgrounds --> <!-- https://tailwindcss.com/docs/background-attachment --> <div class="bg-fixed"></div> <div class="bg-local"></div> <div class="bg-scroll"></div> <!-- https://tailwindcss.com/docs/background-clip --> <div class="bg-clip-border"></div> <div class="bg-clip-padding"></div> <div class="bg-clip-content"></div> <div class="bg-clip-text"></div> <!-- https://tailwindcss.com/docs/background-color --> <div class="bg-inherit"></div> <div class="bg-slate-50"></div> <div class="bg-fuchsia-400"></div> <div class="bg-[#50d71e]"></div> <!-- https://tailwindcss.com/docs/background-origin --> <div class="bg-origin-border"></div> <div class="bg-origin-padding"></div> <div class="bg-origin-content"></div> <!-- https://tailwindcss.com/docs/background-position --> <div class="bg-bottom"></div> <div class="bg-right-bottom"></div> <!-- https://tailwindcss.com/docs/background-repeat --> <div class="bg-repeat"></div> <div class="bg-repeat-y"></div> <!-- https://tailwindcss.com/docs/background-size --> <div class="bg-auto"></div> <div class="bg-cover"></div> <div class="bg-contain"></div> <!-- https://tailwindcss.com/docs/background-image --> <div class="bg-none"></div> <div class="bg-gradient-to-r"></div> <!-- https://tailwindcss.com/docs/gradient-color-stops --> <div class="from-inherit"></div> <div class="from-current"></div> <div class="from-gray-200"></div> <div class="to-rose-900"></div> <div class="from-[#243c5a]"></div>
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/tailwindcss/7 Borders/index.html
HTML
<!-- Borders --> <!-- https://tailwindcss.com/docs/border-radius --> <div class="rounded-none"></div> <div class="rounded"></div> <div class="rounded-r-lg"></div> <div class="rounded-bl-full"></div> <div class="rounded-[12px]"></div> <!-- https://tailwindcss.com/docs/border-width --> <div class="border-0"></div> <div class="border-x-4"></div> <div class="border-l"></div> <div class="border-t-[3px]"></div> <!-- https://tailwindcss.com/docs/border-color --> <div class="border-inherit"></div> <div class="border-transparent"></div> <div class="border-orange-400"></div> <div class="border-[#243c5a]"></div> <!-- https://tailwindcss.com/docs/border-style --> <div class="border-solid"></div> <div class="border-dashed"></div> <div class="border-dotted"></div> <div class="border-double"></div> <div class="border-hidden"></div> <div class="border-none"></div> <!-- https://tailwindcss.com/docs/divide-width --> <div class="divide-x-0"></div> <div class="divide-y-reverse"></div> <div class="divide-x-[3px]"></div> <!-- https://tailwindcss.com/docs/divide-color --> <div class="divide-inherit"></div> <div class="divide-transparent"></div> <div class="divide-amber-100"></div> <div class="divide-[#243c5a]"></div> <!-- https://tailwindcss.com/docs/divide-style --> <div class="divide-solid"></div> <div class="divide-none"></div> <!-- https://tailwindcss.com/docs/outline-width --> <div class="outline-0"></div> <div class="outline-[5px]"></div> <!-- https://tailwindcss.com/docs/outline-color --> <div class="outline-inherit"></div> <div class="outline-[#243c5a]"></div> <!-- https://tailwindcss.com/docs/outline-style --> <div class="outline-none"></div> <div class="outline"></div> <!-- https://tailwindcss.com/docs/outline-offset --> <div class="outline-offset-0"></div> <div class="outline-offset-[3px]"></div> <!-- https://tailwindcss.com/docs/ring-width --> <div class="ring-0"></div> <div class="ring"></div> <div class="ring-inset"></div> <div class="ring-[10px]"></div> <!-- https://tailwindcss.com/docs/ring-color --> <div class="ring-inherit"></div> <div class="ring-orange-200"></div> <div class="ring-[#50d71e]"></div> <!-- https://tailwindcss.com/docs/ring-offset-width --> <div class="ring-offset-0 "></div> <div class="ring-offset-[3px]"></div> <!-- https://tailwindcss.com/docs/ring-offset-color --> <div class="ring-offset-inherit"></div> <div class="ring-offset-orange-200"></div> <div class="ring-offset-[#50d71e]"></div>
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/tailwindcss/8 Effects/index.html
HTML
<!-- Effects --> <!-- https://tailwindcss.com/docs/box-shadow --> <div class="shadow-sm"></div> <div class="shadow"></div> <div class="shadow-none"></div> <div class="shadow-[0_35px_60px_-15px_rgba(0,0,0,0.3)]"></div> <!-- https://tailwindcss.com/docs/box-shadow-color --> <div class="shadow-inherit"></div> <div class="shadow-orange-100"></div> <div class="shadow-[#50d71e]"></div> <!-- https://tailwindcss.com/docs/opacity --> <div class="opacity-0"></div> <div class="opacity-[.67]"></div> <!-- https://tailwindcss.com/docs/mix-blend-mode --> <div class="mix-blend-normal"></div> <div class="mix-blend-saturation"></div> <!-- https://tailwindcss.com/docs/background-blend-mode --> <div class="bg-blend-normal"></div>
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/tailwindcss/9 Filters/index.html
HTML
<!-- Filters --> <!-- https://tailwindcss.com/docs/blur --> <div class="blur-none"></div> <div class="blur"></div> <div class="blur-3xl"></div> <div class="blur-[2px]"></div> <!-- https://tailwindcss.com/docs/brightness --> <div class="brightness-0"></div> <div class="brightness-[1.75]"></div> <!-- https://tailwindcss.com/docs/contrast --> <div class="contrast-0"></div> <div class="contrast-[.25]"></div> <!-- https://tailwindcss.com/docs/drop-shadow --> <div class="drop-shadow-sm"></div> <div class="drop-shadow-[0_35px_35px_rgba(0,0,0,0.25)]"></div> <!-- https://tailwindcss.com/docs/grayscale --> <div class="grayscale-0"></div> <div class="grayscale-[50%]"></div> <!-- https://tailwindcss.com/docs/hue-rotate --> <div class="hue-rotate-0"></div> <div class="hue-rotate-[270deg]"></div> <!-- https://tailwindcss.com/docs/invert --> <div class="invert-0"></div> <div class="invert-[.25]"></div> <!-- https://tailwindcss.com/docs/saturate --> <div class="saturate-0"></div> <div class="saturate-[.25]"></div> <!-- https://tailwindcss.com/docs/sepia --> <div class="sepia-0"></div> <div class="sepia-[.25]"></div> <!-- https://tailwindcss.com/docs/backdrop-blur --> <div class="backdrop-blur-none"></div> <div class="backdrop-blur-[2px]"></div> <!-- https://tailwindcss.com/docs/backdrop-brightness --> <div class="backdrop-brightness-0"></div> <div class="backdrop-brightness-[1.75]"></div> <!-- https://tailwindcss.com/docs/backdrop-contrast --> <div class="backdrop-contrast-0"></div> <div class="backdrop-contrast-[.25]"></div> <!-- https://tailwindcss.com/docs/backdrop-grayscale --> <div class="backdrop-grayscale-0"></div> <div class="backdrop-grayscale-[.5]"></div> <!-- https://tailwindcss.com/docs/backdrop-hue-rotate --> <div class="backdrop-hue-rotate-0"></div> <div class="backdrop-hue-rotate-[270deg]"></div> <!-- https://tailwindcss.com/docs/backdrop-invert --> <div class="backdrop-invert-0"></div> <div class="backdrop-invert-[.25]"></div> <!-- https://tailwindcss.com/docs/backdrop-opacity --> <div class="backdrop-opacity-0"></div> <div class="backdrop-opacity-[.15]"></div> <!-- https://tailwindcss.com/docs/backdrop-saturate --> <div class="backdrop-saturate-0"></div> <div class="backdrop-saturate-[.25]"></div> <!-- https://tailwindcss.com/docs/backdrop-sepia --> <div class="backdrop-sepia-0"></div> <div class="backdrop-sepia-[.25]"></div>
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
src/index.ts
TypeScript
import type { ExtensionContext } from "vscode"; import { window, workspace } from "vscode"; import { Configuration } from "./utils/configuration"; import { Decoration } from "./utils/decoration"; export async function activate(context: ExtensionContext): Promise<void> { const configuration = new Configuration(); const decoration = new Decoration(configuration); decoration.update(); window.onDidChangeActiveTextEditor( () => { decoration.update(); }, null, context.subscriptions ); workspace.onDidChangeTextDocument( () => { decoration.update(); }, null, context.subscriptions ); workspace.onDidChangeConfiguration( () => { const configuration = new Configuration(); decoration.update(configuration); }, null, context.subscriptions ); } export async function deactivate(): Promise<void> { const configuration = new Configuration(); const decoration = new Decoration(configuration); decoration.dispose(); }
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
src/utils/configuration.ts
TypeScript
import type { DecorationRenderOptions, WorkspaceConfiguration } from "vscode"; import { workspace } from "vscode"; type Configs = Record< string, { enable: boolean; options: DecorationRenderOptions; regex: string; } >; type VariantsConfig = Record< string, { enable: boolean; variants: string[]; color: string; } >; export interface MyConfiguration { configs: Configs; languages: string[]; } export class Configuration { configuration: WorkspaceConfiguration; constructor() { this.configuration = workspace.getConfiguration("tailwindcss-highlight"); } get languages(): MyConfiguration["languages"] { return this.configuration.get("languages") ?? []; } get configs(): MyConfiguration["configs"] { const variants = this.configuration.get<VariantsConfig>("variants") ?? {}; const configs = this.configuration.get<Configs>("configs") ?? {}; return { ...configs, ...Object.entries(variants).reduce((acc, [key, value]) => { acc[`variants:${key}`] = { enable: value.enable ?? true, options: { color: value.color }, regex: `(?<=[:\`\'\"\\s])(${value.variants.join("|")}):` }; return acc; }, {} as Configs) }; } }
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
src/utils/decoration.ts
TypeScript
import type { DecorationOptions, TextEditor, TextEditorDecorationType } from "vscode"; import { Range, window } from "vscode"; import type { MyConfiguration } from "./configuration"; import { getClassNames, getUtility } from "./utils"; export class Decoration { timer: NodeJS.Timer | undefined; configuration: MyConfiguration; decorators: Array<{ decorator: TextEditorDecorationType; regex: string }>; private options = { backgroundColor: "", borderStyle: "dashed", borderWidth: "0 0 1px 0" }; private enable = true; constructor(configuration: MyConfiguration) { this.timer = undefined; this.configuration = configuration; this.decorators = Object.entries(configuration.configs) .filter(config => config[1].enable ?? this.enable) .sort(a => { if ( a[0].startsWith("variants:") && !["variants:other", "variants:responsive"].includes(a[0]) ) { return -1; } return 0; }) .map(config => { return { regex: config[1].regex, decorator: window.createTextEditorDecorationType( config[1].options ?? this.options ) }; }); } private decorate(editor: TextEditor): void { if (editor == null) return; const document = editor.document; const text = document.getText(); const classNames = getClassNames(text); this.decorators.forEach(decorator => { const regex = new RegExp(decorator.regex, "g"); const chars: DecorationOptions[] = []; classNames.forEach(className => { const utilities = getUtility(className.value, regex); utilities.forEach(utility => { const start = document.positionAt(className.start + utility.start); const end = document.positionAt(className.start + utility.end); const range = new Range(start, end); chars.push({ range }); }); editor.setDecorations(decorator.decorator, chars); }); }); } update(configuration?: MyConfiguration): void { if (configuration != null) { this.configuration = configuration; this.decorators = Object.entries(configuration.configs) .filter(config => config[1].enable ?? this.enable) .map(config => { return { regex: config[1].regex, decorator: window.createTextEditorDecorationType( config[1].options ?? this.options ) }; }); } const editor = window.activeTextEditor; if (editor == null) return; const languageId = editor.document.languageId; if (!this.configuration.languages.includes(languageId)) return; if (this.timer != null) { clearTimeout(this.timer); this.timer = undefined; } this.timer = setTimeout(() => { this.decorate(editor); }, 20); } dispose(): void { this.decorators.forEach(decorator => { decorator.decorator.dispose(); }); } }
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
src/utils/utils.ts
TypeScript
export function getClassNames( targetText: string ): Array<{ start: number; value: string }> { const arr = []; const regexes = [ /(?:\b(?:class(?:Name)?|tw)\s*=\s*(?:(?:{([^>}]+)})|(["'`][^"'`]+["'`])))/, /(?:(clsx|classnames)\()([^)]+)\)/ ]; const regex = new RegExp(regexes.map(r => r.source).join("|"), "gm"); const classNameMatches = targetText.matchAll(regex); for (const classNameMatch of classNameMatches) { const stringMatches = classNameMatch[0].matchAll( /(?:["'`]([\s\S.:/${}()[\]"']+)["'`])/g ); for (const stringMatch of stringMatches) { if (classNameMatch.index != null && stringMatch.index != null) { arr.push({ start: classNameMatch.index + stringMatch.index, value: stringMatch[0] }); } } } return arr; } export function getUtility( targetText: string, regex: RegExp ): Array<{ end: number; start: number; value: string; }> { const arr = []; const matches = targetText.matchAll(regex); for (const match of matches) { if (match.index != null) { arr.push({ start: match.index, end: match.index + match[0].length, value: match[0] }); } } return arr; }
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
tests/filetext.ts
TypeScript
export const filetext = ` import React from 'react' export const Component = () => { const btn = classnames("p-20 pt-20 pb-20 pl-20 pr-20 px-20 py-20", true ? "-p-20 ": "p-[20px]") return ( <div role="pt-1 mb-1 border-red-100"></div> <div className={clsx('p-10 pt-10 pb-10 pl-10 pr-10 px-10 py-10 -p-10 p-[10px]', { 'm-10 mt-10 mb-10 ml-10 mr-10 mx-10 my-10 -m-10': true })}> <div className={classnames("space-x-10 space-y-10", true ? "-space-x-10" : "-space-y-10" )}></div> <div className="border border-t-10 border-t border-none border-gray-100 border-opacity-0 border-solid"></div> <div className="rounded rounded-md rounded-l-10"></div> <div className="divide-x-10 divide-y-10 divide-x divide-y divide-gray-100"></div> <div className="ring ring-0 ring-gray-100 ring-offset-gray-100"></div> <div className="w w- w-0 w-10 w-2.5 w-1/2 w-full min-w-100 max-w-100 max-w-screen-sm"></div> <div className="h h- h-0 h-10 h-2.5 h-1/2 h-full min-h-100 max-h-100"></div> <div className="flex flex-1 flex-auto flex-grow-0 flex-shrink-0 inline-flex"></div> <div className="grid grid-flow-row grid-flow-row-dense"></div> <div className="order-10 order-none -order-1"></div> <div className="col-auto col-span-10 col-start-10 col-end-10"></div> <div className="row-auto row-span-10 row-start-10 row-end-10"></div> <div className="auto-cols-auto auto-cols-fr"></div> <div className="auto-rows-auto auto-rows-fr"></div> <div className="gap-10 gap-x-10 gap-y-10 gap-0.5 gap-x-0.5 gap-px"></div> <div className="justify-start justify-end justify-center justify-between justify-around justify-evenly"></div> <div className="justify-items-start justify-items-end justify-items-center justify-items-stretch"></div> <div className="justify-self-auto justify-self-start justify-self-end justify-self-center justify-self-stretch"></div> <div className="content-center content-start content-end content-between content-around content-evenly"></div> <div className="items-start items-end items-center items-baseline items-stretch"></div> <div className="self-auto self-start self-end self-center self-stretch"></div> <div className="place-content-center place-content-start place-content-end place-content-between place-content-around place-content-evenly place-content-stretch"></div> <div className="place-items-start place-items-end place-items-center place-items-stretch"></div> <div className="place-self-auto place-self-start place-self-end place-self-center place-self-stretch"></div> <div className="table table-auto table-fixed border-collapse border-separate"></div> <div className="transition transition-all duration-10 delay-10 ease-linear ease-in-out"></div> <div className="animate-spin"></div> <div className="transform transform-gpu transform-none"></div> <div className="origin-center origin-top-right"></div> <div className="scale-10 scale-x-10 scale-y-10"></div> <div className="rotate-10 -rotate-10"></div> <div className="translate-x-10 translate-x-0.5 translate-y-10 translate-y-1/2 -translate-x-full"></div> <div className="skew-x-10 skew-y-10 -skew-x-10"></div> <div className="text-center text-gray-100 text-opacity-10"></div> <div className="underline line-through no-underline"></div> <div className="uppercase lowercase capitalize normal-case"></div> <div className="truncate overflow-ellipsis overflow-clip"></div> <div className="align-baseline align-text-bottom"></div> <div className="whitespace-normal whitespace-pre-wrap whitespace-pre-line whitespace-pre"></div> <div className="break-normal break-words break-all"></div> <div className="font-sans font-bold italic not-italic"></div> <div className="leading-10 leading-normal tracking-normal"></div> <div className="bg-fixed bg-clip-text bg-gray-100 bg-opacity-10 bg-left-bottom bg-no-repeat bg-contain bg-gradient-to-t"></div> <div className="from-transparent from-gray-100 via-gray-100 to-gray-100"></div> <div className="static fixed absolute relative sticky"></div> <div className="top-10 -left-10 inset-10 -inset-y-1 right-3.5 bottom-1/2 bottom-[calc(100%+0.6rem)]"></div> <div style={ { transform: 'translateX(10px)', } } className=""></div> <div className=""></div> <div className=""></div> </div> ) } `;
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
tests/utils.test.ts
TypeScript
import pJson from "../package.json"; import { getClassNames, getUtility } from "../src/utils/utils"; import { filetext } from "./filetext"; const config = pJson.contributes.configuration.properties["tailwindcss-highlight.configs"] .default; const testUtility = (regex: string): string[] => { const classNames = getClassNames(filetext); return classNames.flatMap(className => { return getUtility(className.value, new RegExp(regex, "g")).map( i => i.value ); }); }; describe("getClassNames", () => { test("className", () => { const classNames = getClassNames(` <div class="flex items-center p-10" transform=""></div> <div className="flex items-center p-10"></div> `); expect(classNames).toEqual([ { start: 18, value: "\"flex items-center p-10\"" }, { start: 84, value: "\"flex items-center p-10\"" } ]); }); test("clsx", () => { const classNames = getClassNames(` const btn = clsx('flex', 'items-center', 'p-10', x === 100 ? 'bg-blue-500' : 'bg-red-500') <div className={clsx("flex items-center p-10")}></div> <div className="flex items-center p-10"></div> <div className={x === 100 ? "flex" : clsx("flex items-center p-10")} style={{ transform: "" }}></div> `); expect(classNames).toEqual([ { start: 24, value: "'flex', 'items-center', 'p-10', x === 100 ? 'bg-blue-500' : 'bg-red-500'" }, { start: 125, value: "\"flex items-center p-10\"" }, { start: 180, value: "\"flex items-center p-10\"" }, { start: 246, value: "\"flex\" : clsx(\"flex items-center p-10\"" } ]); }); test("classnames", () => { const classNames = getClassNames(` const btn = classnames('flex', 'items-center', 'p-10', true ? 'bg-blue-500' : 'bg-red-500') <div className={classnames("flex items-center p-10")}></div> `); expect(classNames).toEqual([ { start: 30, value: "'flex', 'items-center', 'p-10', true ? 'bg-blue-500' : 'bg-red-500'" }, { start: 132, value: "\"flex items-center p-10\"" } ]); }); test("no matching", () => { const classNames = getClassNames(` <div style="transform"></div> <div style={{ transform: 'translateX(100px)' }}></div> `); expect(classNames).toEqual([]); }); }); describe("getUtility", () => { test("padding", () => { const expected = [ "p-20", "pt-20", "pb-20", "pl-20", "pr-20", "px-20", "py-20", "-p-20", "p-[20px]", "p-10", "pt-10", "pb-10", "pl-10", "pr-10", "px-10", "py-10", "-p-10", "p-[10px]" ]; const regex = config.padding.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("margin", () => { const expected = [ "m-10", "mt-10", "mb-10", "ml-10", "mr-10", "mx-10", "my-10", "-m-10" ]; const regex = config.margin.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("space", () => { const expected = ["space-x-10", "space-y-10", "-space-x-10", "-space-y-10"]; const regex = config.space.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("border", () => { const expected = [ "border", "border-t-10", "border-t", "border-none", "border-gray-100", "border-opacity-0", "border-solid" ]; const regex = config.border.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("rounded", () => { const expected = ["rounded", "rounded-md", "rounded-l-10"]; const regex = config.rounded.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("divide", () => { const expected = [ "divide-x-10", "divide-y-10", "divide-x", "divide-y", "divide-gray-100" ]; const regex = config.divide.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("ring", () => { const expected = [ "ring", "ring-0", "ring-gray-100", "ring-offset-gray-100" ]; const regex = config.ring.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("width", () => { const expected = [ "w-0", "w-10", "w-2.5", "w-1/2", "w-full", "min-w-100", "max-w-100", "max-w-screen-sm" ]; const regex = config.width.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("height", () => { const expected = [ "h-0", "h-10", "h-2.5", "h-1/2", "h-full", "min-h-100", "max-h-100" ]; const regex = config.height.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("flex", () => { const expected = [ "flex", "flex-1", "flex-auto", "flex-grow-0", "flex-shrink-0" ]; const regex = config.flex.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("grid", () => { const expected = ["grid", "grid-flow-row", "grid-flow-row-dense"]; const regex = config.grid.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("order", () => { const expected = ["order-10", "order-none", "-order-1"]; const regex = config.order.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("gridColumn", () => { const expected = ["col-auto", "col-span-10", "col-start-10", "col-end-10"]; const regex = config.gridColumn.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("gridRow", () => { const expected = ["row-auto", "row-span-10", "row-start-10", "row-end-10"]; const regex = config.gridRow.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("gridRow", () => { const expected = ["row-auto", "row-span-10", "row-start-10", "row-end-10"]; const regex = config.gridRow.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("gridAutoColumns", () => { const expected = ["auto-cols-auto", "auto-cols-fr"]; const regex = config.gridAutoColumns.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("gridAutoRows", () => { const expected = ["auto-rows-auto", "auto-rows-fr"]; const regex = config.gridAutoRows.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("gap", () => { const expected = [ "gap-10", "gap-x-10", "gap-y-10", "gap-0.5", "gap-x-0.5", "gap-px" ]; const regex = config.gap.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("justifyContent", () => { const expected = [ "justify-start", "justify-end", "justify-center", "justify-between", "justify-around", "justify-evenly" ]; const regex = config.justifyContent.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("justifyItems", () => { const expected = [ "justify-items-start", "justify-items-end", "justify-items-center", "justify-items-stretch" ]; const regex = config.justifyItems.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("justifySelf", () => { const expected = [ "justify-self-auto", "justify-self-start", "justify-self-end", "justify-self-center", "justify-self-stretch" ]; const regex = config.justifySelf.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("alignContent", () => { const expected = [ "content-center", "content-start", "content-end", "content-between", "content-around", "content-evenly" ]; const regex = config.alignContent.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("alignItems", () => { const expected = [ "items-start", "items-end", "items-center", "items-baseline", "items-stretch" ]; const regex = config.alignItems.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("alignSelf", () => { const expected = [ "self-auto", "self-start", "self-end", "self-center", "self-stretch" ]; const regex = config.alignSelf.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("placeContent", () => { const expected = [ "place-content-center", "place-content-start", "place-content-end", "place-content-between", "place-content-around", "place-content-evenly", "place-content-stretch" ]; const regex = config.placeContent.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("placeItems", () => { const expected = [ "place-items-start", "place-items-end", "place-items-center", "place-items-stretch" ]; const regex = config.placeItems.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("placeSelf", () => { const expected = [ "place-self-auto", "place-self-start", "place-self-end", "place-self-center", "place-self-stretch" ]; const regex = config.placeSelf.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("table", () => { const expected = ["table", "table-auto", "table-fixed"]; const regex = config.table.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("borderCollapse", () => { const expected = ["border-collapse", "border-separate"]; const regex = config.borderCollapse.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("transition", () => { const expected = ["transition", "transition-all"]; const regex = config.transition.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("transitionDuration", () => { const expected = ["duration-10"]; const regex = config.transitionDuration.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("transitionTimingFunction", () => { const expected = ["ease-linear", "ease-in-out"]; const regex = config.transitionTimingFunction.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("transitionDelay", () => { const expected = ["delay-10"]; const regex = config.transitionDelay.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("animation", () => { const expected = ["animate-spin"]; const regex = config.animation.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("tranform", () => { const expected = ["transform", "transform-gpu", "transform-none"]; const regex = config.transform.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("transformOrigin", () => { const expected = ["origin-center", "origin-top-right"]; const regex = config.transformOrigin.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("scale", () => { const expected = ["scale-10", "scale-x-10", "scale-y-10"]; const regex = config.scale.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("rotate", () => { const expected = ["rotate-10", "-rotate-10"]; const regex = config.rotate.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("translate", () => { const expected = [ "translate-x-10", "translate-x-0.5", "translate-y-10", "translate-y-1/2", "-translate-x-full" ]; const regex = config.translate.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("skew", () => { const expected = ["skew-x-10", "skew-y-10", "-skew-x-10"]; const regex = config.skew.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("text", () => { const expected = ["text-center", "text-gray-100", "text-opacity-10"]; const regex = config.text.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("textDecoration", () => { const expected = ["underline", "line-through", "no-underline"]; const regex = config.textDecoration.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("textTransform", () => { const expected = ["uppercase", "lowercase", "capitalize", "normal-case"]; const regex = config.textTransform.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("textOverflow", () => { const expected = ["truncate", "overflow-ellipsis", "overflow-clip"]; const regex = config.textOverflow.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("verticalAlign", () => { const expected = ["align-baseline", "align-text-bottom"]; const regex = config.verticalAlign.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("whitespace", () => { const expected = [ "whitespace-normal", "whitespace-pre-wrap", "whitespace-pre-line", "whitespace-pre" ]; const regex = config.whitespace.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("wordBreak", () => { const expected = ["break-normal", "break-words", "break-all"]; const regex = config.wordBreak.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("font", () => { const expected = ["font-sans", "font-bold"]; const regex = config.font.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("fontStyle", () => { const expected = ["italic", "not-italic"]; const regex = config.fontStyle.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("leading", () => { const expected = ["leading-10", "leading-normal"]; const regex = config.leading.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("tracking", () => { const expected = ["tracking-normal"]; const regex = config.tracking.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("background", () => { const expected = [ "bg-fixed", "bg-clip-text", "bg-gray-100", "bg-opacity-10", "bg-left-bottom", "bg-no-repeat", "bg-contain", "bg-gradient-to-t" ]; const regex = config.background.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("gradientColorStops", () => { const expected = [ "from-transparent", "from-gray-100", "via-gray-100", "to-gray-100" ]; const regex = config.gradientColorStops.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("position", () => { const expected = ["static", "fixed", "absolute", "relative", "sticky"]; const regex = config.position.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); test("inset", () => { const expected = [ "top-10", "-left-10", "inset-10", "-inset-y-1", "right-3.5", "bottom-1/2", "bottom-[calc(100%+0.6rem)]" ]; const regex = config.inset.regex; const utility = testUtility(regex); expect(utility).toEqual(expect.arrayContaining(expected)); }); });
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
tsup.config.ts
TypeScript
import { defineConfig } from "tsup"; export default defineConfig({ entry: ["src/index.ts"], external: ["vscode"], format: ["cjs"], shims: false, clean: true });
xiaoxian521/tailwindcss-highlight-intellisense
6
About Intelligent Tailwind CSS Highlight tooling for Visual Studio Code
TypeScript
xiaoxian521
xiaoming
pure-admin
.prettierrc.mjs
JavaScript
// @ts-check /** @type {import("prettier").Config} */ export default { bracketSpacing: true, singleQuote: false, arrowParens: "avoid", trailingComma: "none" };
xiaoxian521/vite-plugin-remove-console
187
Vite plugin that remove all the specified console types in the production environment
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/nuxt3/app.vue
Vue
<template> <div> <NuxtWelcome /> </div> </template> <script> console.log( "%cConsole Log Test===>>>: ", "color: MidnightBlue; background: Aquamarine; font-size: 20px;", "Console Log Test" ) </script>
xiaoxian521/vite-plugin-remove-console
187
Vite plugin that remove all the specified console types in the production environment
TypeScript
xiaoxian521
xiaoming
pure-admin
playgrounds/nuxt3/nuxt.config.ts
TypeScript
import { defineNuxtConfig } from "nuxt/config"; import removeConsole from "vite-plugin-remove-console"; // https://nuxt.com/docs/api/configuration/nuxt-config export default defineNuxtConfig({ vite: { plugins: [removeConsole()] } });
xiaoxian521/vite-plugin-remove-console
187
Vite plugin that remove all the specified console types in the production environment
TypeScript
xiaoxian521
xiaoming
pure-admin