Source Code

/ src / repository / templatetags / file_tree.py

import re
from django import template
from django.db.models import Q
from repository.models import File

register = template.Library()

@register.inclusion_tag('repository/tree_node.html')
def render_tree_node(dir_path=None, expanded_dirs=None, current_file=None):
    """Render a tree node and its children recursively"""
    if dir_path is None or dir_path == "":
        files = File.objects.filter(~Q(path__contains="/"))
    else:
        prefix = f"{dir_path}/"
        files = File.objects.filter(
            Q(path__startswith=prefix) &
            ~Q(path__regex=rf'^{re.escape(prefix)}[^/]*/')
        )

    files = files.order_by('-is_directory', 'name')

    should_expand = False
    if expanded_dirs and dir_path:
        should_expand = dir_path in expanded_dirs

    return {
        'files': files,
        'dir_path': dir_path or "",
        'expanded_dirs': expanded_dirs or [],
        'current_file': current_file,
        'should_expand': should_expand,
    }