feat(desktop): add DOM tree navigation helpers

This commit is contained in:
程序员阿江(Relakkes) 2026-05-29 13:24:36 +08:00
parent 19116cb4d9
commit 5083adc9f9
2 changed files with 25 additions and 0 deletions

View File

@ -0,0 +1,17 @@
import { describe, expect, it, beforeEach } from 'vitest'
import { climb, descend } from './treeNav'
beforeEach(() => { document.body.innerHTML = `<main><section><h1>A</h1></section></main>` })
describe('tree navigation', () => {
it('climb returns parent element, not past body', () => {
const h1 = document.querySelector('h1')!
expect(climb(h1)?.tagName.toLowerCase()).toBe('section')
expect(climb(document.querySelector('main')!)).toBeNull() // body 为界
})
it('descend returns first element child', () => {
const section = document.querySelector('section')!
expect(descend(section)?.tagName.toLowerCase()).toBe('h1')
expect(descend(document.querySelector('h1')!)).toBeNull()
})
})

View File

@ -0,0 +1,8 @@
export function climb(el: Element): Element | null {
const p = el.parentElement
if (!p || p.tagName.toLowerCase() === 'body' || p.tagName.toLowerCase() === 'html') return null
return p
}
export function descend(el: Element): Element | null {
return el.firstElementChild
}