Open result breadcrumb in the sidebar directory
Browse filesFiles changed (6)
545 unmodified lines5465475485495505515525535545555565571331 unmodified lines188918901891189218931894438 unmodified lines233323342335233623372338545 unmodified linesSTATE.folderSelections = folderPath ? [folderPath] : [];syncRoute();const routeId = ++routeRenderId;sidebarCurrentPath = "";await renderSidebar(routeId);if (routeId !== routeRenderId) return;await renderFolderTree(false, routeId);if (routeId !== routeRenderId) return;refreshFolderTreeSelectionState();syncUrl();doSearch();}1331 unmodified linesasync function renderSidebar(routeId = routeRenderId) {if (routeId !== routeRenderId) return;activateSidebarScrollKey(sidebarScrollKeyFor(STATE.source, ""));const requestSequence = ++sidebarRequestSequence;sidebarCurrentPath = "";438 unmodified linesrefreshFolderTreeSelectionState();syncUrl();doSearch();}});DOM.resultsList.addEventListener("keydown", (event) => {545 unmodified lines5465475485495505515525535545555561331 unmodified lines18881889189018911892189318941895189618971898438 unmodified lines23372338233923402341234223432344545 unmodified linesSTATE.folderSelections = folderPath ? [folderPath] : [];syncRoute();const routeId = ++routeRenderId;// Open the clicked result path directly; avoid a slow root request racing// the desired directory. Filtering must not wait for either sidebar fetch.if (folderPath) openFolder(folderPath, routeId);else renderSidebar(routeId);renderFolderTree(false, routeId);syncUrl();doSearch();}1331 unmodified linesasync function renderSidebar(routeId = routeRenderId) {if (routeId !== routeRenderId) return;// A result breadcrumb stores the filter in the URL. On a fresh load there// is no previous sidebar position, so restore a single selected directory.// Existing in-page navigation remains independent of filter changes.if (!initComplete && STATE.source && STATE.folderSelections.length === 1)return openFolder(STATE.folderSelections[0], routeId);activateSidebarScrollKey(sidebarScrollKeyFor(STATE.source, ""));const requestSequence = ++sidebarRequestSequence;sidebarCurrentPath = "";438 unmodified linesrefreshFolderTreeSelectionState();syncUrl();doSearch();if (path) openFolder(path, routeRenderId);else renderSidebar(routeRenderId);}});DOM.resultsList.addEventListener("keydown", (event) => {
158 unmodified lines159160161162163164158 unmodified lines<script>if ("serviceWorker" in navigator) { navigator.serviceWorker.register("/sw.js", { scope: "/" }); }</script><script src="/static/tts-client.js?v=clips-11"></script><script src="/static/app.js?v=phrases-4"></script></body></html>158 unmodified lines159160161162163164158 unmodified lines<script>if ("serviceWorker" in navigator) { navigator.serviceWorker.register("/sw.js", { scope: "/" }); }</script><script src="/static/tts-client.js?v=clips-11"></script><script src="/static/app.js?v=result-path-1"></script></body></html>
123456789101112131415161718192021222324252627282930"""Small isolated metadata fixture for real-backend path navigation tests.
Uses checked-out base metadata only; does not activate OCR or read any sourcetext. The original payload remains untouched and production startup is unchanged."""from contextlib import asynccontextmanagerfrom pathlib import Pathimport app
@asynccontextmanagerasync def fixture_lifespan(_application): payload = app.load_json_gz(app.DATA_PATH) app.records = [record for record in payload['records'] if record['source'] == 'CCRD'][:5000] app.sources = [{'slug':'CCRD','name':'CCRD','count':len(app.records)}] app.source_counts = {'CCRD':len(app.records)} app.source_physical_map = {'CCRD':'CCRD'} app.physical_source_counts = {'CCRD':len(app.records)} app.record_map = {row['doc_id']:row for row in app.records} app.record_map_index = {row['doc_id']:i for i,row in enumerate(app.records)} app.folder_tree_data = {'CCRD':app.load_json_gz(app.FOLDER_TREE_PATH)['CCRD']} app.folder_browser_data = {'CCRD':app.load_json_gz(app.FOLDER_BROWSER_PATH)['CCRD']} app.active_ocr_release = None app.fulltext_databases = None app.build_indexes() yield
app.app.router.lifespan_context = fixture_lifespanapplication = app.app307 unmodified lines308309310311312313314315316317318319320321322323324325326327328329330331307 unmodified linesfinally:context.close()def test_old_folder_navigation_does_not_restart_search_after_going_home(self):context, page, errors = self.page()try:result = page.evaluate("""async () => {let release;renderSidebar = () => STATE.source? new Promise(resolve => { release = resolve; }) : Promise.resolve();const searches = [];const trees = [];renderFolderTree = async () => trees.push(STATE.source);doSearch = () => searches.push(STATE.source);const oldNavigation = navigateToSourceFolder('CCRD', 'old');navigateHome();release();await oldNavigation;return {searches, trees, source: STATE.source};}""")self.assertEqual(result, {"searches": [None], "trees": [None], "source": None})self.assertEqual(errors, [])finally:context.close()307 unmodified lines308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431307 unmodified linesfinally:context.close()def test_result_folder_search_does_not_wait_for_sidebar_or_restart_after_going_home(self):context, page, errors = self.page()try:result = page.evaluate("""async () => {let release;renderSidebar = () => STATE.source? new Promise(resolve => { release = resolve; }) : Promise.resolve();openFolder = () => new Promise(resolve => { release = resolve; });const searches = [];const trees = [];renderFolderTree = async () => trees.push(STATE.source);doSearch = () => searches.push(STATE.source);const oldNavigation = navigateToSourceFolder('CCRD', 'old');const beforeGoingHome = searches.slice();navigateHome();release();await oldNavigation;return {beforeGoingHome, searches, trees, source: STATE.source};}""")self.assertEqual(result, {"beforeGoingHome": ['CCRD'], "searches": ['CCRD', None],"trees": ['CCRD', None], "source": None})self.assertEqual(errors, [])finally:context.close()def test_result_path_filters_subtree_and_opens_the_same_sidebar_directory(self):context, page, errors = self.page()try:page.evaluate("""() => {const node=(name,path,children=[])=>({name,path,count:1,children});const tree=[node('docs','docs',[node('子','docs/子')]),node('docs2','docs2')];API.getFolders=async()=>tree;API.getContents=async (_source,path)=>({folders:[],files:[{doc_id:'local',name:path||'ROOT'}]});loadSidebarInitial=async()=>null;window.__pathSearches=[];doSearch=()=>{window.__pathSearches.push({source:STATE.source,folders:STATE.folderSelections.slice()});};window.__resultPath=(source,folder)=>{const link=document.createElement('span');link.className='path-folder';link.dataset.source=source;link.dataset.folder=folder;DOM.resultsList.append(link);link.click();};}""")page.evaluate("__resultPath('CCRD','docs')")page.wait_for_function("""() => STATE.source==='CCRD' && sidebarCurrentPath==='docs' &&STATE.folderSelections.join()==='docs' &&document.querySelector('.sidebar-breadcrumb [data-folder-nav="docs"]') &&window.__pathSearches.length===1""")page.wait_for_function("document.querySelector('#filter-folder-tree input[data-folder-path=\"docs\"]')?.checked")self.assertTrue(page.locator('#filter-folder-tree input[data-folder-path="docs/子"]').is_checked())self.assertEqual(page.evaluate('__pathSearches[0]'), {'source':'CCRD','folders':['docs']})page.evaluate("__resultPath('CCRD','docs/子')")page.wait_for_function("""() => sidebarCurrentPath==='docs/子' &&STATE.folderSelections.join()==='docs/子' &&document.querySelector('.sidebar-breadcrumb [data-folder-nav="docs/子"]')""")self.assertEqual(page.evaluate('__pathSearches.at(-1)'), {'source':'CCRD','folders':['docs/子']})page.evaluate("__resultPath('CCRD','')")page.wait_for_function("""() => sidebarCurrentPath==='' && !STATE.folderSelections.length &&DOM.sidebarContent.textContent.includes('ROOT.txt')""")self.assertEqual(page.evaluate('__pathSearches.at(-1)'), {'source':'CCRD','folders':[]})self.assertEqual(errors, [])finally:context.close()def test_result_path_keyboard_activation_preserves_subtree_and_sidebar(self):context, page, errors = self.page()try:page.evaluate("""() => {history.replaceState(null,'','/CCRD');syncRoute();API.getContents=async (_source,path)=>({folders:[],files:[{doc_id:'id',name:path}]});doSearch=()=>{};refreshFolderTreeSelectionState=()=>{};DOM.resultsList.innerHTML='<span role="button" tabindex="0" class="path-folder" data-source="CCRD" data-folder="docs/子">子</span>';}""")link = page.locator('.path-folder[role="button"]')link.focus()page.keyboard.press('Enter')page.wait_for_function("sidebarCurrentPath==='docs/子' && STATE.folderSelections.join()==='docs/子'")self.assertEqual(page.locator('.sidebar-breadcrumb [data-folder-nav="docs/子"]').count(), 1)self.assertEqual(errors, [])finally:context.close()def test_rapid_result_paths_keep_latest_sidebar_and_filter(self):context, page, errors = self.page()try:result = page.evaluate("""async () => {history.replaceState(null,'','/CCRD');syncRoute();STATE.folderSelections=[];routeRenderId++;const pending={};API.getContents=(_source,path)=>new Promise(resolve=>{pending[path]=resolve;});doSearch=()=>{};refreshFolderTreeSelectionState=()=>{};const click=path=>{const link=document.createElement('span');link.className='path-folder';link.dataset.source='CCRD';link.dataset.folder=path;DOM.resultsList.append(link);link.click();};click('old');click('new');pending.new({folders:[],files:[{doc_id:'new',name:'NEW'}]});await new Promise(resolve=>setTimeout(resolve,0));pending.old({folders:[],files:[{doc_id:'old',name:'OLD'}]});await new Promise(resolve=>setTimeout(resolve,0));return {path:sidebarCurrentPath, selection:STATE.folderSelections.slice(),visible:DOM.sidebarContent.textContent.includes('NEW.txt'),stale:DOM.sidebarContent.textContent.includes('OLD.txt')};}""")self.assertEqual(result, {'path':'new','selection':['new'],'visible':True,'stale':False})self.assertEqual(errors, [])finally:context.close()def test_sidebar_root_render_does_not_automatically_follow_manual_filter_change(self):context, page, errors = self.page()try:result = page.evaluate("""async () => {STATE.source='CCRD';STATE.folderSelections=['manual-filter'];initComplete=true;loadSidebarInitial=async()=>null;API.getContents=async (_source,path)=>({folders:[],files:[{doc_id:'x',name:path||'ROOT'}]});await openFolder('manual-location',routeRenderId);await renderSidebar(routeRenderId);return {filter:STATE.folderSelections.slice(),path:sidebarCurrentPath,rootVisible:DOM.sidebarContent.textContent.includes('ROOT.txt')};}""")self.assertEqual(result, {'filter':['manual-filter'],'path':'','rootVisible':True})self.assertEqual(errors, [])finally:context.close()
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071"""Result breadcrumbs against a real, small CCRD metadata search backend."""from __future__ import annotationsimport jsonimport socketimport subprocessimport sysimport timeimport unittestfrom pathlib import Pathfrom urllib.request import urlopen
from playwright.sync_api import sync_playwright
ROOT=Path(__file__).resolve().parents[1]
class ResultPathNavigationTests(unittest.TestCase): @classmethod def setUpClass(cls): with socket.socket() as sock: sock.bind(('127.0.0.1',0));port=sock.getsockname()[1] cls.origin=f'http://127.0.0.1:{port}' cls.server=subprocess.Popen([sys.executable,'-m','uvicorn','tests.path_navigation_fixture:application', '--host','127.0.0.1','--port',str(port),'--log-level','warning'],cwd=ROOT, stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) for _ in range(180): if cls.server.poll() is not None:raise RuntimeError('fixture backend exited') try: with urlopen(cls.origin+'/api/sources',timeout=1) as response: if response.status==200:break except Exception:time.sleep(.25) else:raise RuntimeError('fixture backend not ready') cls.playwright=sync_playwright().start() cls.browser=cls.playwright.chromium.launch(headless=True,args=['--no-sandbox'])
@classmethod def tearDownClass(cls): cls.browser.close();cls.playwright.stop();cls.server.terminate();cls.server.wait(timeout=10)
def test_parent_and_child_result_paths_filter_real_records_and_open_sidebar(self): context=self.browser.new_context(viewport={'width':1280,'height':800},service_workers='block') page=context.new_page();errors=[];page.on('pageerror',lambda error:errors.append(str(error))) try: page.goto(self.origin+'/?fulltext=0',wait_until='domcontentloaded') parent=page.locator('#results-list .result-item').first.locator('.path-folder').nth(2) parent.wait_for(timeout=30000) path=parent.get_attribute('data-folder') parent.click() page.wait_for_function('''path=>STATE.source==='CCRD' && sidebarCurrentPath===path && STATE.folderSelections.length===1 && STATE.folderSelections[0]===path && !STATE.isLoading && STATE.results.length>0 && [...document.querySelectorAll('.sidebar-breadcrumb [data-folder-nav]')].some(x=>x.dataset.folderNav===path)''', arg=path,timeout=30000) records=page.evaluate('STATE.results.map(x=>x.Folder.join("/"))') self.assertTrue(records and all(p==path or p.startswith(path+'/') for p in records)) self.assertTrue(any(p.startswith(path+'/') for p in records),'parent must include descendants') self.assertEqual(page.evaluate('STATE.total'),1958) child=page.locator('#results-list .result-item').first.locator('.path-folder').nth(3) child_path=child.get_attribute('data-folder');child.click() page.wait_for_function('''path=>sidebarCurrentPath===path && STATE.folderSelections[0]===path && !STATE.isLoading && [...document.querySelectorAll('.sidebar-breadcrumb [data-folder-nav]')] .some(x=>x.dataset.folderNav===path)''',arg=child_path,timeout=30000) self.assertTrue(all(p==child_path or p.startswith(child_path+'/') for p in page.evaluate('STATE.results.map(x=>x.Folder.join("/"))'))) page.reload(wait_until='domcontentloaded') page.wait_for_function('''path=>STATE.source==='CCRD' && STATE.folderSelections[0]===path && sidebarCurrentPath===path && !STATE.isLoading && [...document.querySelectorAll('.sidebar-breadcrumb [data-folder-nav]')] .some(x=>x.dataset.folderNav===path)''',arg=child_path,timeout=30000) self.assertEqual(errors,[]) finally:context.close()1120 unmodified lines1121112211231124112511261120 unmodified linesclass FrontendContractTests(unittest.TestCase):def test_every_static_control_exists_is_cached_and_has_behavior(self):html = (Path(app.BASE_DIR) / "static" / "index.html").read_text(encoding="utf-8")source = (Path(app.BASE_DIR) / "static" / "app.js").read_text(encoding="utf-8")1120 unmodified lines11211122112311241125112611271128112911301131113211331134113511361137113811391120 unmodified linesclass FrontendContractTests(unittest.TestCase):def test_result_path_navigation_keeps_filter_and_sidebar_in_sync(self):source = (Path(__file__).resolve().parents[1] / 'static/app.js').read_text(encoding='utf-8')handler = source.split('const folder = event.target.closest(".path-folder[data-folder]");', 1)[1].split('DOM.resultsList.addEventListener("keydown"', 1)[0]self.assertIn('STATE.folderSelections = path ? [path] : []', handler)self.assertIn('if (path) openFolder(path, routeRenderId)', handler)self.assertIn('else renderSidebar(routeRenderId)', handler)source_navigation = source.split('async function navigateToSourceFolder(', 1)[1].split('function navigateHome()', 1)[0]self.assertIn('if (folderPath) openFolder(folderPath, routeId)', source_navigation)self.assertIn('renderFolderTree(false, routeId)', source_navigation)self.assertIn('doSearch()', source_navigation)def test_every_static_control_exists_is_cached_and_has_behavior(self):html = (Path(app.BASE_DIR) / "static" / "index.html").read_text(encoding="utf-8")source = (Path(app.BASE_DIR) / "static" / "app.js").read_text(encoding="utf-8")
static/app.js+12-6
static/index.html+1-1
tests/path_navigation_fixture.pyAdded+30
tests/test_browser.py+103-3
tests/test_path_navigation_browser.pyAdded+71
tests/test_search.py+13