group_tree.rb 1.72 KB
Newer Older
1 2
# frozen_string_literal: true

3
module GroupTree
4
  # rubocop:disable Gitlab/ModuleWithInstanceVariables
5
  # rubocop: disable CodeReuse/ActiveRecord
6
  def render_group_tree(groups)
7
    groups = groups.sort_by_attribute(@sort = params[:sort])
8

9 10 11 12 13 14 15 16
    groups = if params[:filter].present?
               filtered_groups_with_ancestors(groups)
             else
               # If `params[:parent_id]` is `nil`, we will only show root-groups
               groups.where(parent_id: params[:parent_id]).page(params[:page])
             end

    @groups = groups.with_selects_for_list(archived: params[:archived])
17 18 19 20 21 22

    respond_to do |format|
      format.html
      format.json do
        serializer = GroupChildSerializer.new(current_user: current_user)
                       .with_pagination(request, response)
23
        serializer.expand_hierarchy if params[:filter].present?
24 25 26
        render json: serializer.represent(@groups)
      end
    end
27
    # rubocop:enable Gitlab/ModuleWithInstanceVariables
28
  end
29
  # rubocop: enable CodeReuse/ActiveRecord
30

31
  # rubocop: disable CodeReuse/ActiveRecord
32 33 34
  def filtered_groups_with_ancestors(groups)
    filtered_groups = groups.search(params[:filter]).page(params[:page])

35
    if Group.supports_nested_objects?
36 37 38 39 40 41
      # We find the ancestors by ID of the search results here.
      # Otherwise the ancestors would also have filters applied,
      # which would cause them not to be preloaded.
      #
      # Pagination needs to be applied before loading the ancestors to
      # make sure ancestors are not cut off by pagination.
42
      Gitlab::ObjectHierarchy.new(Group.where(id: filtered_groups.select(:id)))
43 44 45 46 47
        .base_and_ancestors
    else
      filtered_groups
    end
  end
48
  # rubocop: enable CodeReuse/ActiveRecord
49
end