Striven
2 days ago c538c151c7462ad0395ff2c15c5e11e89e362aa8
quartz/util/fileTrie.ts
@@ -4,6 +4,7 @@
interface FileTrieData {
  slug: string
  title: string
  filePath: string
}
export class FileTrieNode<T extends FileTrieData = ContentDetails> {
@@ -11,6 +12,11 @@
  children: Array<FileTrieNode<T>>
  private slugSegments: string[]
  // prefer showing the file path segment over the slug segment
  // so that folders that dont have index files can be shown as is
  // without dashes in the slug
  private fileSegmentHint?: string
  private displayNameOverride?: string
  data: T | null
  constructor(segments: string[], data?: T) {
@@ -18,10 +24,18 @@
    this.slugSegments = segments
    this.data = data ?? null
    this.isFolder = false
    this.displayNameOverride = undefined
  }
  get displayName(): string {
    return this.data?.title ?? this.slugSegment ?? ""
    const nonIndexTitle = this.data?.title === "index" ? undefined : this.data?.title
    return (
      this.displayNameOverride ?? nonIndexTitle ?? this.fileSegmentHint ?? this.slugSegment ?? ""
    )
  }
  set displayName(name: string) {
    this.displayNameOverride = name
  }
  get slug(): FullSlug {
@@ -63,6 +77,9 @@
      // recursive case, we are not at the end of the path
      const child =
        this.children.find((c) => c.slugSegment === segment) ?? this.makeChild(path, undefined)
      const fileParts = file.filePath.split("/")
      child.fileSegmentHint = fileParts.at(-path.length)
      child.insert(path.slice(1), file)
    }
  }
@@ -72,6 +89,32 @@
    this.insert(file.slug.split("/"), file)
  }
  findNode(path: string[]): FileTrieNode<T> | undefined {
    if (path.length === 0 || (path.length === 1 && path[0] === "index")) {
      return this
    }
    return this.children.find((c) => c.slugSegment === path[0])?.findNode(path.slice(1))
  }
  ancestryChain(path: string[]): Array<FileTrieNode<T>> | undefined {
    if (path.length === 0 || (path.length === 1 && path[0] === "index")) {
      return [this]
    }
    const child = this.children.find((c) => c.slugSegment === path[0])
    if (!child) {
      return undefined
    }
    const childPath = child.ancestryChain(path.slice(1))
    if (!childPath) {
      return undefined
    }
    return [this, ...childPath]
  }
  /**
   * Filter trie nodes. Behaves similar to `Array.prototype.filter()`, but modifies tree in place
   */