Something went wrong. Try again.
Fork of github.com/ccmdi/propsec
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414import { ItemView, WorkspaceLeaf, TFile, setIcon, ViewStateResult } from "obsidian";import { Violation, ViolationFilter, isWarningViolation } from "../types";import { ViolationStore } from "../validation/store";import { debug } from "../debug";import { getViolationIcon } from "../utils/violation";
export const VIOLATIONS_VIEW_TYPE = "propsec-violations";
// Incremental loading settingsconst INITIAL_RENDER_COUNT = 20; // Files to render initiallyconst LOAD_MORE_COUNT = 20; // Files to load when scrolling near bottom
/** * Sidebar view displaying frontmatter violations with incremental loading */export class ViolationsView extends ItemView { private store: ViolationStore; private changeListener: () => void; private searchQuery: string = ""; private filter: ViolationFilter = "errors"; private listContainer: HTMLElement | null = null; private summaryEl: HTMLElement | null = null; private filterContainer: HTMLElement | null = null;
// Incremental loading state private allFileEntries: Array<[string, Violation[]]> = []; private renderedCount: number = 0; private loadMoreSentinel: HTMLElement | null = null; private intersectionObserver: IntersectionObserver | null = null;
constructor(leaf: WorkspaceLeaf, store: ViolationStore) { super(leaf); this.store = store; this.changeListener = () => this.renderList(); }
getViewType(): string { return VIOLATIONS_VIEW_TYPE; }
getDisplayText(): string { return "Schema violations"; }
getIcon(): string { return "alert-triangle"; }
getState(): { filter: ViolationFilter; searchQuery: string } { return { filter: this.filter, searchQuery: this.searchQuery, }; }
async setState(state: { filter?: ViolationFilter; searchQuery?: string }, result: ViewStateResult): Promise<void> { if (state.filter) { this.filter = state.filter; } if (state.searchQuery !== undefined) { this.searchQuery = state.searchQuery; } // Re-render if we're already open if (this.listContainer) { this.renderFilterButtons(); this.renderList(); } return super.setState(state, result); }
async onOpen(): Promise<void> { this.store.onChange(this.changeListener); this.render(); }
async onClose(): Promise<void> { this.store.offChange(this.changeListener); // Clean up intersection observer if (this.intersectionObserver) { this.intersectionObserver.disconnect(); this.intersectionObserver = null; } }
private render(): void { const container = this.containerEl.children[1] as HTMLElement; container.empty(); container.addClass("propsec-violations-view");
// Nav header with filter buttons and search (sibling to view-content, not inside) let navHeader = this.containerEl.querySelector(".nav-header") as HTMLElement; if (!navHeader) { navHeader = createDiv({ cls: "nav-header" }); this.containerEl.insertBefore(navHeader, container); } navHeader.empty();
// Filter buttons this.filterContainer = navHeader.createDiv({ cls: "nav-buttons-container" }); this.renderFilterButtons();
// Search bar in header (using native Obsidian search-input-container style) const searchContainer = navHeader.createDiv({ cls: "search-input-container" }); const searchInput = searchContainer.createEl("input", { type: "search", attr: { enterkeyhint: "search", spellcheck: "false" }, placeholder: "Search...", }); searchInput.value = this.searchQuery; searchInput.addEventListener("input", (e) => { this.searchQuery = (e.target as HTMLInputElement).value.toLowerCase(); this.renderList(); this.app.workspace.requestSaveLayout(); });
// Summary this.summaryEl = container.createDiv({ cls: "propsec-view-summary", });
// Violations list container this.listContainer = container.createDiv({ cls: "propsec-view-list", });
// Set up intersection observer for infinite scroll this.setupIntersectionObserver();
this.renderList(); } /** * Set up intersection observer for "load more" functionality */ private setupIntersectionObserver(): void { if (this.intersectionObserver) { this.intersectionObserver.disconnect(); } this.intersectionObserver = new IntersectionObserver( (entries) => { for (const entry of entries) { if (entry.isIntersecting && this.renderedCount < this.allFileEntries.length) { this.loadMoreFiles(); } } }, { rootMargin: "100px" } ); }
private renderFilterButtons(): void { if (!this.filterContainer) return; this.filterContainer.empty();
const filters: Array<{ value: ViolationFilter; icon: string; tooltip: string }> = [ { value: "all", icon: "list", tooltip: "All" }, { value: "errors", icon: "alert-circle", tooltip: "Errors" }, { value: "warnings", icon: "alert-triangle", tooltip: "Warnings" }, ];
for (const filterDef of filters) { const btn = this.filterContainer.createDiv({ cls: `clickable-icon nav-action-button${this.filter === filterDef.value ? " is-active" : ""}`, attr: { "aria-label": filterDef.tooltip }, }); setIcon(btn, filterDef.icon); btn.addEventListener("click", () => { this.filter = filterDef.value; this.renderFilterButtons(); this.renderList(); this.app.workspace.requestSaveLayout(); }); } }
/** * Render the list with incremental loading */ private renderList(): void { const startTime = performance.now(); if (!this.listContainer || !this.summaryEl) return; this.listContainer.empty();
const violations = this.store.getFilteredViolations(this.filter);
// Build filtered file entries this.allFileEntries = []; for (const [filePath, fileViolations] of violations) { const filtered = this.filterViolations(filePath, fileViolations); if (filtered.length > 0) { this.allFileEntries.push([filePath, filtered]); } }
// Handle empty state if (this.allFileEntries.length === 0) { this.summaryEl.empty(); const emptyState = this.listContainer.createDiv({ cls: "propsec-view-empty", }); const emptyTitle = this.filter === "all" ? "No violations" : this.filter === "errors" ? "No errors" : "No warnings"; const emptyDesc = this.filter === "all" ? "All notes match their schemas" : this.filter === "errors" ? "No errors found" : "No warnings found"; if (!this.searchQuery) { emptyState.createEl("div", { text: emptyTitle, cls: "propsec-view-empty-title", }); emptyState.createEl("div", { text: emptyDesc, cls: "propsec-view-empty-desc", }); } else { emptyState.createEl("p", { text: "No violations match your search.", cls: "propsec-view-no-results", }); } return; }
// Update summary let summaryText: string; if (this.filter === "all") { const errorCount = this.store.getErrorCount(); const warningCount = this.store.getWarningCount(); summaryText = `${errorCount} error${errorCount !== 1 ? "s" : ""}, ${warningCount} warning${warningCount !== 1 ? "s" : ""}`; } else { let count = 0; for (const fileViolations of violations.values()) { count += fileViolations.length; } const label = this.filter === "errors" ? "error" : "warning"; summaryText = `${count} ${label}${count !== 1 ? "s" : ""}`; } this.summaryEl.setText(summaryText);
// Render initial batch this.renderedCount = 0; this.renderMoreFiles(INITIAL_RENDER_COUNT); debug(`renderList() completed in ${(performance.now() - startTime).toFixed(1)}ms, ${this.allFileEntries.length} files`); }
/** * Render more file sections */ private renderMoreFiles(count: number): void { if (!this.listContainer) return;
// Remove old sentinel if exists if (this.loadMoreSentinel) { this.loadMoreSentinel.remove(); this.loadMoreSentinel = null; }
const endIndex = Math.min(this.renderedCount + count, this.allFileEntries.length); for (let i = this.renderedCount; i < endIndex; i++) { const [filePath, fileViolations] = this.allFileEntries[i]; this.renderFileSection(this.listContainer, filePath, fileViolations); }
this.renderedCount = endIndex;
// Add sentinel for loading more if there are more items if (this.renderedCount < this.allFileEntries.length) { this.loadMoreSentinel = this.listContainer.createDiv({ cls: "propsec-load-sentinel", }); if (this.intersectionObserver) { this.intersectionObserver.observe(this.loadMoreSentinel); } } }
/** * Load more files when scrolling near bottom */ private loadMoreFiles(): void { this.renderMoreFiles(LOAD_MORE_COUNT); }
/** * Render a file section with its violations, grouped by schema */ private renderFileSection(container: HTMLElement, filePath: string, violations: Violation[]): void { const section = container.createDiv({ cls: "propsec-view-file", });
// Render file header (just the file name, no schema badge) this.renderFileHeader(section, filePath); // Group violations by schema const bySchema = new Map<string, Violation[]>(); for (const v of violations) { const schemaId = v.schemaMapping.id; if (!bySchema.has(schemaId)) { bySchema.set(schemaId, []); } bySchema.get(schemaId)!.push(v); }
// Render each schema's violations for (const [, schemaViolations] of bySchema) { const schemaName = schemaViolations[0].schemaMapping.name; const schemaGroup = section.createDiv({ cls: "propsec-view-schema-group", }); schemaGroup.createEl("span", { text: schemaName, cls: "propsec-view-schema", }); const violationsList = schemaGroup.createDiv({ cls: "propsec-view-violations", });
for (const violation of schemaViolations) { this.renderViolationItem(violationsList, violation); } } }
private filterViolations(filePath: string, violations: Violation[]): Violation[] { if (!this.searchQuery) return violations;
const query = this.searchQuery; if (filePath.toLowerCase().includes(query)) { return violations; } return violations.filter(v => v.field.toLowerCase().includes(query) || v.message.toLowerCase().includes(query) || v.schemaMapping.name.toLowerCase().includes(query) ); }
/** * Render a file header row (just the file link, no schema badge) */ private renderFileHeader(container: HTMLElement, filePath: string): void { const header = container.createDiv({ cls: "propsec-view-file-header", });
const fileLink = header.createEl("a", { cls: "propsec-view-file-link", });
// Show just the filename, with full path on hover const fileName = filePath.split("/").pop() || filePath; fileLink.setText(fileName.replace(/\.md$/, "")); fileLink.setAttr("title", filePath);
const openFile = async (e: MouseEvent, newTab: boolean) => { e.preventDefault(); const file = this.app.vault.getAbstractFileByPath(filePath); if (file instanceof TFile) { const leaf = newTab ? this.app.workspace.getLeaf('tab') : this.app.workspace.getLeaf(false); await leaf.openFile(file); } };
// Prevent middle-click auto-scroll fileLink.addEventListener("mousedown", (e) => { if (e.button === 1) e.preventDefault(); }); //eslint-disable-next-line @typescript-eslint/no-misused-promises fileLink.addEventListener("click", async (e) => await openFile(e, false)); //eslint-disable-next-line @typescript-eslint/no-misused-promises fileLink.addEventListener("auxclick", async (e) => { if (e.button === 1) { await openFile(e, true); } }); }
/** * Render a single violation item */ private renderViolationItem(container: HTMLElement, violation: Violation): void { const isWarning = isWarningViolation(violation); const item = container.createDiv({ cls: `propsec-view-item propsec-view-${violation.type} ${isWarning ? "propsec-warning" : "propsec-error-item"}`, });
const icon = getViolationIcon(violation.type); item.createEl("span", { text: icon, cls: "propsec-view-icon", });
item.createEl("span", { text: violation.message, cls: "propsec-view-message", }); }}