Selection.ItemsAdded=Signal.new()Selection.ItemsRemoved=Signal.new()Selection.PartsAdded=Signal.new()Selection.PartsRemoved=Signal.new()Selection.FocusChanged=Signal.new()Selection.Cleared=Signal.new()Selection.Changed=Signal.new()function Selection.IsSelected(b)return Selection.ItemIndex[b]end local function b(b,S)if b:IsA("\066\097\115\101\080\097\114\116")then S[#S+1]=b else local G=b:GetDescendants()for b,G in ipairs(G)do if G:IsA("\066\097\115\101\080\097\114\116")then S[#S+1]=G end end end end function Selection.Add(S,G)local g=GetCore()local f={}for b,S in pairs(S)do if S.Parent and not Selection.ItemIndex[S]then table.insert(f,S)end end local r=Selection.Items local d={}for S,G in pairs(f)do Selection.ItemIndex[G]=true CreateSelectionBoxes(G)local g=Maid.new()Selection.Maid[G]=g g.RemovalListener=G.AncestryChanged:Connect(function(b,S)if S==nil then Selection.Remove({G})end end)b(G,d)local f=not G:IsA("\066\097\115\101\080\097\114\116")or nil g.NewParts=f and G.DescendantAdded:Connect(function(b)if b:IsA("\066\097\115\101\080\097\114\116")then local S=(Selection.PartIndex[b]or 0)+1 Selection.PartIndex[b]=S Selection.Parts=Support.Keys(Selection.PartIndex)if S==1 then Selection.PartsAdded:Fire({b})end end end)g.RemovingParts=f and G.DescendantRemoving:Connect(function(b)if Selection.PartIndex[b]then local S=(Selection.PartIndex[b]or 0)-1 Selection.PartIndex[b]=S>0 and S or nil if S==0 then Selection.Parts=Support.Keys(Selection.PartIndex)Selection.PartsRemoved:Fire({b})end end end)end Selection.Items=Support.Keys(Selection.ItemIndex)if G and#f>0 then TrackSelectionChange(r)end local a={}for b,S in pairs(d)do local G=(Selection.PartIndex[S]or 0)+1 Selection.PartIndex[S]=G if G==1 then a[#a+1]=S end end if#a>0 then Selection.Parts=Support.Keys(Selection.PartIndex)Selection.PartsAdded:Fire(a)end if#f>0 then Selection.ItemsAdded:Fire(f)Selection.Changed:Fire()end end function Selection.Remove(S,G)local g={}for b,S in pairs(S)do if Selection.IsSelected(S)then table.insert(g,S)end end local f=Selection.Items local r={}for S,G in pairs(g)do Selection.ItemIndex[G]=nil RemoveSelectionBoxes(G)Selection.Maid[G]=nil b(G,r)end Selection.Items=Support.Keys(Selection.ItemIndex)if G and#g>0 then TrackSelectionChange(f)end local d={}for b,S in pairs(r)do local G=(Selection.PartIndex[S]or 0)-1 Selection.PartIndex[S]=G>0 and G or nil if G==0 then d[#d+1]=S end end if#d>0 then Selection.Parts=Support.Keys(Selection.PartIndex)Selection.PartsRemoved:Fire(d)end if#g>0 then Selection.ItemsRemoved:Fire(g)Selection.Changed:Fire()end end function Selection.Clear(b)Selection.Remove(Selection.Items,b)Selection.Cleared:Fire()end function Selection.Replace(b,S)local G=Selection.Items local g={}for b,S in ipairs(b)do if not Selection.ItemIndex[S]then table.insert(g,S)end end local f={}local r=Support.FlipTable(b)for b,S in ipairs(Selection.Items)do if not r[S]then table.insert(f,S)end end if#f>0 then Selection.Remove(f,false)end if#g>0 then Selection.Add(g,false)end if S then TrackSelectionChange(G)end end local function S(b)return b:IsA("\077\111\100\101\108")or b:IsA("\066\097\115\101\080\097\114\116")end local function G(b)if not b then return nil end if S(b)then return b elseif b then return b:FindFirstChildWhichIsA("\066\097\115\101\080\097\114\116")or b:FindFirstChildWhichIsA("\077\111\100\101\108")or b:FindFirstChildWhichIsA("\066\097\115\101\080\097\114\116",true)or b:FindFirstChildWhichIsA("\077\111\100\101\108",true)end end function Selection.SetFocus(b)local S=G(b)if Selection.Focus==S then return end Selection.Focus=S Selection.FocusChanged:Fire(S)end function FocusOnLastSelectedPart()if#Selection.Items==0 then Selection.SetFocus(nil)else Selection.SetFocus(Selection.Items[#Selection.Items])end end

Selection.ItemsAdded = Signal.new()
Selection.ItemsRemoved = Signal.new()
Selection.PartsAdded = Signal.new()
Selection.PartsRemoved = Signal.new()
Selection.FocusChanged = Signal.new()
Selection.Cleared = Signal.new()
Selection.Changed = Signal.new()

function Selection.IsSelected(Item)
	-- Returns whether `Item` is selected or not

	-- Check and return item presence in index
	return Selection.ItemIndex[Item];

end;

local function CollectParts(Item, Table)
	-- Adds parts found in `Item` to `Table`

	-- Collect parts
	if Item:IsA 'BasePart' then
		Table[#Table + 1] = Item

	-- Collect parts inside of groups
	else
		local Items = Item:GetDescendants()
		for _, Item in ipairs(Items) do
			if Item:IsA 'BasePart' then
				Table[#Table + 1] = Item
			end
		end
	end
end

function Selection.Add(Items, RegisterHistory)
	-- Adds the given items to the selection

	-- Get core API
	local Core = GetCore();

	-- Go through and validate each given item
	local SelectableItems = {};
	for _, Item in pairs(Items) do

		-- Make sure each item is valid and not already selected
		if Item.Parent and (not Selection.ItemIndex[Item]) then
			table.insert(SelectableItems, Item);
		end;

	end;

	local OldSelection = Selection.Items;

	-- Track parts in new selection
	local Parts = {}

	-- Go through the valid new selection items
	for _, Item in pairs(SelectableItems) do

		-- Add each valid item to the selection
		Selection.ItemIndex[Item] = true;
		CreateSelectionBoxes(Item)

		-- Create maid for cleaning up item listeners
		local ItemMaid = Maid.new()
		Selection.Maid[Item] = ItemMaid

		-- Deselect items that are destroyed
		ItemMaid.RemovalListener = Item.AncestryChanged:Connect(function (Object, Parent)
			if Parent == nil then
				Selection.Remove({ Item })
			end
		end)

		-- Collect parts within item
		CollectParts(Item, Parts)

		-- Listen for new parts in groups
		local IsGroup = not Item:IsA 'BasePart' or nil
		ItemMaid.NewParts = IsGroup and Item.DescendantAdded:Connect(function (Descendant)
			if Descendant:IsA 'BasePart' then
				local NewRefCount = (Selection.PartIndex[Descendant] or 0) + 1
				Selection.PartIndex[Descendant] = NewRefCount
				Selection.Parts = Support.Keys(Selection.PartIndex)
				if NewRefCount == 1 then
					Selection.PartsAdded:Fire { Descendant }
				end
			end
		end)
		ItemMaid.RemovingParts = IsGroup and Item.DescendantRemoving:Connect(function (Descendant)
			if Selection.PartIndex[Descendant] then
				local NewRefCount = (Selection.PartIndex[Descendant] or 0) - 1
				Selection.PartIndex[Descendant] = (NewRefCount > 0) and NewRefCount or nil
				if NewRefCount == 0 then
					Selection.Parts = Support.Keys(Selection.PartIndex)
					Selection.PartsRemoved:Fire { Descendant }
				end
			end
		end)

	end

	-- Update selected item list
	Selection.Items = Support.Keys(Selection.ItemIndex);

	-- Create a history record for this selection change, if requested
	if RegisterHistory and #SelectableItems > 0 then
		TrackSelectionChange(OldSelection);
	end;

	-- Register references to new parts
	local NewParts = {}
	for _, Part in pairs(Parts) do
		local NewRefCount = (Selection.PartIndex[Part] or 0) + 1
		Selection.PartIndex[Part] = NewRefCount
		if NewRefCount == 1 then
			NewParts[#NewParts + 1] = Part
		end
	end

	-- Update parts list
	if #NewParts > 0 then
		Selection.Parts = Support.Keys(Selection.PartIndex)
		Selection.PartsAdded:Fire(NewParts)
	end

	-- Fire relevant events
	if #SelectableItems > 0 then
		Selection.ItemsAdded:Fire(SelectableItems)
		Selection.Changed:Fire()
	end

end;

function Selection.Remove(Items, RegisterHistory)
	-- Removes the given items from the selection

	-- Go through and validate each given item
	local DeselectableItems = {};
	for _, Item in pairs(Items) do

		-- Make sure each item is actually selected
		if Selection.IsSelected(Item) then
			table.insert(DeselectableItems, Item);
		end;

	end;

	local OldSelection = Selection.Items;

	-- Track parts in removing selection
	local Parts = {}

	-- Go through the valid deselectable items
	for _, Item in pairs(DeselectableItems) do

		-- Remove item from selection
		Selection.ItemIndex[Item] = nil;
		RemoveSelectionBoxes(Item)

		-- Stop tracking item's parts
		Selection.Maid[Item] = nil

		-- Get parts associated with item
		CollectParts(Item, Parts)

	end;

	-- Update selected item list
	Selection.Items = Support.Keys(Selection.ItemIndex);

	-- Create a history record for this selection change, if requested
	if RegisterHistory and #DeselectableItems > 0 then
		TrackSelectionChange(OldSelection);
	end;

	-- Clear references to removing parts
	local RemovingParts = {}
	for _, Part in pairs(Parts) do
		local NewRefCount = (Selection.PartIndex[Part] or 0) - 1
		Selection.PartIndex[Part] = (NewRefCount > 0) and NewRefCount or nil
		if NewRefCount == 0 then
			RemovingParts[#RemovingParts + 1] = Part
		end
	end

	-- Update parts list
	if #RemovingParts > 0 then
		Selection.Parts = Support.Keys(Selection.PartIndex)
		Selection.PartsRemoved:Fire(RemovingParts)
	end

	-- Fire relevant events
	if #DeselectableItems > 0 then
		Selection.ItemsRemoved:Fire(DeselectableItems)
		Selection.Changed:Fire()
	end

end;

function Selection.Clear(RegisterHistory)
	-- Clears all items from selection

	-- Remove all selected items
	Selection.Remove(Selection.Items, RegisterHistory);

	-- Fire relevant events
	Selection.Cleared:Fire();

end;

function Selection.Replace(Items, RegisterHistory)
	-- Replaces the current selection with the given new items

	-- Save old selection reference for history
	local OldSelection = Selection.Items;

	-- Find new items
	local NewItems = {}
	for _, Item in ipairs(Items) do
		if not Selection.ItemIndex[Item] then
			table.insert(NewItems, Item)
		end
	end

	-- Find removing items
	local RemovingItems = {}
	local NewItemIndex = Support.FlipTable(Items)
	for _, Item in ipairs(Selection.Items) do
		if not NewItemIndex[Item] then
			table.insert(RemovingItems, Item)
		end
	end

	-- Update selection
	if #RemovingItems > 0 then
		Selection.Remove(RemovingItems, false)
	end
	if #NewItems > 0 then
		Selection.Add(NewItems, false)
	end

	-- Create a history record for this selection change, if requested
	if RegisterHistory then
		TrackSelectionChange(OldSelection);
	end;

end;

local function IsVisible(Item)
	return Item:IsA 'Model' or Item:IsA 'BasePart'
end

local function GetVisibleFocus(Item)
	-- Returns a visible focus representing the item

	-- Return nil if no focus
	if not Item then
		return nil
	end

	-- Return focus if it's visible
	if IsVisible(Item) then
		return Item

	-- Return first visible item within focus if not visible itself
	elseif Item then
		return Item:FindFirstChildWhichIsA('BasePart') or
			Item:FindFirstChildWhichIsA('Model') or
			Item:FindFirstChildWhichIsA('BasePart', true) or
			Item:FindFirstChildWhichIsA('Model', true)
	end
end

function Selection.SetFocus(Item)
	-- Selects `Item` as the focused selection item

	-- Ensure focus has changed
	local Focus = GetVisibleFocus(Item)
	if Selection.Focus == Focus then
		return
	end

	-- Set new focus item
	Selection.Focus = Focus

	-- Fire relevant events
	Selection.FocusChanged:Fire(Focus)

end

function FocusOnLastSelectedPart()
	-- Sets the last part of the selection as the focus

	-- If selection is empty, clear the focus
	if #Selection.Items == 0 then
		Selection.SetFocus(nil);

	-- Otherwise, focus on the last part in the selection
	else
		Selection.SetFocus(Selection.Items[#Selection.Items]);
	end;

end;
