local F=require(script.Parent.Type)local G=require(script.Parent.ElementKind)local h=require(script.Parent.ElementUtils)local l=require(script.Parent.PropMarkers.Children)local d=require(script.Parent.Symbol)local o=require(script.Parent.internalAssert)local O=(require(script.Parent.GlobalConfig)).get()local y=d.named("\073\110\116\101\114\110\097\108\068\097\116\097")local function M(d)local M local e local t local L local function n(F,G)local h=F.hostParent local l=F.hostKey local d=F.depth local o=F.parentContext L(F)local O=e(G,h,l,o)if O~=nil then O.depth=d end return O end local function s(G,l,d)if O.internalTypeChecks then o(F.of(G)==F.VirtualNode,"\069\120\112\101\099\116\101\100 \097\114\103 \035\049 \116\111 \098\101 \111\102 \116\121\112\101 \086\105\114\116\117\097\108\078\111\100\101")end local y={}for F,l in pairs(G.children)do local o=h.getElementByKey(d,F)local O=t(l,o)if O~=nil then G.children[F]=O else y[F]=true end end for F in pairs(y)do G.children[F]=nil end for F,d in h.iterateElements(d)do local o=F if F==h.UseParentKey then o=G.hostKey end if G.children[F]==nil then local h=e(d,l,o,G.context)if h~=nil then h.depth=G.depth+1 G.children[F]=h end end end end local function S(F,G,h)s(F,G,h)end local function X(G,h,l)if F.of(l)==F.Element or l==nil or typeof(l)=="\098\111\111\108\101\097\110"then s(G,h,l)else error(("\037\115\n\037\115"):format("\067\111\109\112\111\110\101\110\116 \114\101\116\117\114\110\101\100 \105\110\118\097\108\105\100 \099\104\105\108\100\114\101\110\058",G.currentElement.source or"\060\101\110\097\098\108\101 \101\108\101\109\101\110\116 \116\114\097\099\101\098\097\099\107\115\062"),0)end end function L(h)if O.internalTypeChecks then o(F.of(h)==F.VirtualNode,"\069\120\112\101\099\116\101\100 \097\114\103 \035\049 \116\111 \098\101 \111\102 \116\121\112\101 \086\105\114\116\117\097\108\078\111\100\101")end local l=G.of(h.currentElement)if l==G.Host then d.unmountHostNode(M,h)elseif l==G.Function then for F,G in pairs(h.children)do L(G)end elseif l==G.Stateful then h.instance:__unmount()elseif l==G.Portal then for F,G in pairs(h.children)do L(G)end elseif l==G.Fragment then for F,G in pairs(h.children)do L(G)end else error(("\085\110\107\110\111\119\110 \069\108\101\109\101\110\116\075\105\110\100 \037\113"):format(tostring(l),2))end end local function f(F,G)local h=G.component(G.props)X(F,F.hostParent,h)return F end local function u(F,G)local h=F.currentElement local o=h.props.target local O=G.props.target assert(d.isHostObject(O),"\069\120\112\101\099\116\101\100 \116\097\114\103\101\116 \116\111 \098\101 \104\111\115\116 \111\098\106\101\099\116")if O~=o then return n(F,G)end local y=G.props[l]S(F,O,y)return F end local function E(F,G)S(F,F.hostParent,G.elements)return F end function t(h,l,y)if O.internalTypeChecks then o(F.of(h)==F.VirtualNode,"\069\120\112\101\099\116\101\100 \097\114\103 \035\049 \116\111 \098\101 \111\102 \116\121\112\101 \086\105\114\116\117\097\108\078\111\100\101")end if O.typeChecks then assert(F.of(l)==F.Element or typeof(l)=="\098\111\111\108\101\097\110"or l==nil,"\069\120\112\101\099\116\101\100 \097\114\103 \035\050 \116\111 \098\101 \111\102 \116\121\112\101 \069\108\101\109\101\110\116\044 \098\111\111\108\101\097\110\044 \111\114 \110\105\108")end if h.currentElement==l and y==nil then return h end if typeof(l)=="\098\111\111\108\101\097\110"or l==nil then L(h)return nil end if h.currentElement.component~=l.component then return n(h,l)end local e=G.of(l)local t=true if e==G.Host then h=d.updateHostNode(M,h,l)elseif e==G.Function then h=f(h,l)elseif e==G.Stateful then t=h.instance:__update(l,y)elseif e==G.Portal then h=u(h,l)elseif e==G.Fragment then h=E(h,l)else error(("\085\110\107\110\111\119\110 \069\108\101\109\101\110\116\075\105\110\100 \037\113"):format(tostring(e),2))end if not t then return h end h.currentElement=l return h end local function j(G,h,l,y)if O.internalTypeChecks then o(d.isHostObject(h)or h==nil,"\069\120\112\101\099\116\101\100 \097\114\103 \035\050 \116\111 \098\101 \097 \104\111\115\116 \111\098\106\101\099\116")o(typeof(y)=="\116\097\098\108\101"or y==nil,"\069\120\112\101\099\116\101\100 \097\114\103 \035\052 \116\111 \098\101 \111\102 \116\121\112\101 \116\097\098\108\101 \111\114 \110\105\108")end if O.typeChecks then assert(l~=nil,"\069\120\112\101\099\116\101\100 \097\114\103 \035\051 \116\111 \098\101 \110\111\110-\110\105\108")assert(F.of(G)==F.Element or typeof(G)=="\098\111\111\108\101\097\110","\069\120\112\101\099\116\101\100 \097\114\103 \035\049 \116\111 \098\101 \111\102 \116\121\112\101 \069\108\101\109\101\110\116 \111\114 \098\111\111\108\101\097\110")end return{[F]=F.VirtualNode;currentElement=G;depth=1;children={};hostParent=h,hostKey=l;context=y,parentContext=y}end local function V(F)local G=F.currentElement local h=G.component(G.props)X(F,F.hostParent,h)end local function K(F)local G=F.currentElement local h=G.props.target local o=G.props[l]assert(d.isHostObject(h),"\069\120\112\101\099\116\101\100 \116\097\114\103\101\116 \116\111 \098\101 \104\111\115\116 \111\098\106\101\099\116")S(F,h,o)end local function R(F)local G=F.currentElement local h=G.elements S(F,F.hostParent,h)end function e(h,l,y,e)if O.internalTypeChecks then o(d.isHostObject(l)or l==nil,"\069\120\112\101\099\116\101\100 \097\114\103 \035\050 \116\111 \098\101 \097 \104\111\115\116 \111\098\106\101\099\116")o(typeof(e)=="\116\097\098\108\101"or e==nil,"\069\120\112\101\099\116\101\100 \097\114\103 \035\052 \116\111 \098\101 \111\102 \116\121\112\101 \116\097\098\108\101 \111\114 \110\105\108")end if O.typeChecks then assert(y~=nil,"\069\120\112\101\099\116\101\100 \097\114\103 \035\051 \116\111 \098\101 \110\111\110-\110\105\108")assert(F.of(h)==F.Element or typeof(h)=="\098\111\111\108\101\097\110","\069\120\112\101\099\116\101\100 \097\114\103 \035\049 \116\111 \098\101 \111\102 \116\121\112\101 \069\108\101\109\101\110\116 \111\114 \098\111\111\108\101\097\110")end if typeof(h)=="\098\111\111\108\101\097\110"then return nil end local t=G.of(h)local L=j(h,l,y,e)if t==G.Host then d.mountHostNode(M,L)elseif t==G.Function then V(L)elseif t==G.Stateful then h.component:__mount(M,L)elseif t==G.Portal then K(L)elseif t==G.Fragment then R(L)else error(("\085\110\107\110\111\119\110 \069\108\101\109\101\110\116\075\105\110\100 \037\113"):format(tostring(t),2))end return L end local function a(G,h,l)if O.typeChecks then assert(F.of(G)==F.Element,"\069\120\112\101\099\116\101\100 \097\114\103 \035\049 \116\111 \098\101 \111\102 \116\121\112\101 \069\108\101\109\101\110\116")assert(d.isHostObject(h)or h==nil,"\069\120\112\101\099\116\101\100 \097\114\103 \035\050 \116\111 \098\101 \097 \104\111\115\116 \111\098\106\101\099\116")end if l==nil then l="\082\111\097\099\116\084\114\101\101"end local o={[F]=F.VirtualTree;[y]={rootNode=nil;mounted=true}}o[y].rootNode=e(G,h,l)return o end local function m(G)local h=G[y]if O.typeChecks then assert(F.of(G)==F.VirtualTree,"\069\120\112\101\099\116\101\100 \097\114\103 \035\049 \116\111 \098\101 \097 \082\111\097\099\116 \104\097\110\100\108\101")assert(h.mounted,"\067\097\110\110\111\116 \117\110\109\111\117\110\116\101\100 \097 \082\111\097\099\116 \116\114\101\101 \116\104\097\116 \104\097\115 \097\108\114\101\097\100\121 \098\101\101\110 \117\110\109\111\117\110\116\101\100")end h.mounted=false if h.rootNode~=nil then L(h.rootNode)end end local function I(G,h)local l=G[y]if O.typeChecks then assert(F.of(G)==F.VirtualTree,"\069\120\112\101\099\116\101\100 \097\114\103 \035\049 \116\111 \098\101 \097 \082\111\097\099\116 \104\097\110\100\108\101")assert(F.of(h)==F.Element,"\069\120\112\101\099\116\101\100 \097\114\103 \035\050 \116\111 \098\101 \097 \082\111\097\099\116 \069\108\101\109\101\110\116")end l.rootNode=t(l.rootNode,h)return G end M={mountVirtualTree=a;unmountVirtualTree=m;updateVirtualTree=I;createVirtualNode=j,mountVirtualNode=e;unmountVirtualNode=L;updateVirtualNode=t,updateVirtualNodeWithChildren=S;updateVirtualNodeWithRenderResult=X}return M end return M
local Type = require(script.Parent.Type)
local ElementKind = require(script.Parent.ElementKind)
local ElementUtils = require(script.Parent.ElementUtils)
local Children = require(script.Parent.PropMarkers.Children)
local Symbol = require(script.Parent.Symbol)
local internalAssert = require(script.Parent.internalAssert)

local config = require(script.Parent.GlobalConfig).get()

local InternalData = Symbol.named("InternalData")

--[[
	The reconciler is the mechanism in Roact that constructs the virtual tree
	that later gets turned into concrete objects by the renderer.

	Roact's reconciler is constructed with the renderer as an argument, which
	enables switching to different renderers for different platforms or
	scenarios.

	When testing the reconciler itself, it's common to use `NoopRenderer` with
	spies replacing some methods. The default (and only) reconciler interface
	exposed by Roact right now uses `RobloxRenderer`.
]]
local function createReconciler(renderer)
	local reconciler
	local mountVirtualNode
	local updateVirtualNode
	local unmountVirtualNode

	--[[
		Unmount the given virtualNode, replacing it with a new node described by
		the given element.

		Preserves host properties, depth, and context from parent.
	]]
	local function replaceVirtualNode(virtualNode, newElement)
		local hostParent = virtualNode.hostParent
		local hostKey = virtualNode.hostKey
		local depth = virtualNode.depth
		local parentContext = virtualNode.parentContext

		unmountVirtualNode(virtualNode)
		local newNode = mountVirtualNode(newElement, hostParent, hostKey, parentContext)

		-- mountVirtualNode can return nil if the element is a boolean
		if newNode ~= nil then
			newNode.depth = depth
		end

		return newNode
	end

	--[[
		Utility to update the children of a virtual node based on zero or more
		updated children given as elements.
	]]
	local function updateChildren(virtualNode, hostParent, newChildElements)
		if config.internalTypeChecks then
			internalAssert(Type.of(virtualNode) == Type.VirtualNode, "Expected arg #1 to be of type VirtualNode")
		end

		local removeKeys = {}

		-- Changed or removed children
		for childKey, childNode in pairs(virtualNode.children) do
			local newElement = ElementUtils.getElementByKey(newChildElements, childKey)
			local newNode = updateVirtualNode(childNode, newElement)

			if newNode ~= nil then
				virtualNode.children[childKey] = newNode
			else
				removeKeys[childKey] = true
			end
		end

		for childKey in pairs(removeKeys) do
			virtualNode.children[childKey] = nil
		end

		-- Added children
		for childKey, newElement in ElementUtils.iterateElements(newChildElements) do
			local concreteKey = childKey
			if childKey == ElementUtils.UseParentKey then
				concreteKey = virtualNode.hostKey
			end

			if virtualNode.children[childKey] == nil then
				local childNode = mountVirtualNode(newElement, hostParent, concreteKey, virtualNode.context)

				-- mountVirtualNode can return nil if the element is a boolean
				if childNode ~= nil then
					childNode.depth = virtualNode.depth + 1
					virtualNode.children[childKey] = childNode
				end
			end
		end
	end

	local function updateVirtualNodeWithChildren(virtualNode, hostParent, newChildElements)
		updateChildren(virtualNode, hostParent, newChildElements)
	end

	local function updateVirtualNodeWithRenderResult(virtualNode, hostParent, renderResult)
		if Type.of(renderResult) == Type.Element
			or renderResult == nil
			or typeof(renderResult) == "boolean"
		then
			updateChildren(virtualNode, hostParent, renderResult)
		else
			error(("%s\n%s"):format(
				"Component returned invalid children:",
				virtualNode.currentElement.source or "<enable element tracebacks>"
			), 0)
		end
	end

	--[[
		Unmounts the given virtual node and releases any held resources.
	]]
	function unmountVirtualNode(virtualNode)
		if config.internalTypeChecks then
			internalAssert(Type.of(virtualNode) == Type.VirtualNode, "Expected arg #1 to be of type VirtualNode")
		end

		local kind = ElementKind.of(virtualNode.currentElement)

		if kind == ElementKind.Host then
			renderer.unmountHostNode(reconciler, virtualNode)
		elseif kind == ElementKind.Function then
			for _, childNode in pairs(virtualNode.children) do
				unmountVirtualNode(childNode)
			end
		elseif kind == ElementKind.Stateful then
			virtualNode.instance:__unmount()
		elseif kind == ElementKind.Portal then
			for _, childNode in pairs(virtualNode.children) do
				unmountVirtualNode(childNode)
			end
		elseif kind == ElementKind.Fragment then
			for _, childNode in pairs(virtualNode.children) do
				unmountVirtualNode(childNode)
			end
		else
			error(("Unknown ElementKind %q"):format(tostring(kind), 2))
		end
	end

	local function updateFunctionVirtualNode(virtualNode, newElement)
		local children = newElement.component(newElement.props)

		updateVirtualNodeWithRenderResult(virtualNode, virtualNode.hostParent, children)

		return virtualNode
	end

	local function updatePortalVirtualNode(virtualNode, newElement)
		local oldElement = virtualNode.currentElement
		local oldTargetHostParent = oldElement.props.target

		local targetHostParent = newElement.props.target

		assert(renderer.isHostObject(targetHostParent), "Expected target to be host object")

		if targetHostParent ~= oldTargetHostParent then
			return replaceVirtualNode(virtualNode, newElement)
		end

		local children = newElement.props[Children]

		updateVirtualNodeWithChildren(virtualNode, targetHostParent, children)

		return virtualNode
	end

	local function updateFragmentVirtualNode(virtualNode, newElement)
		updateVirtualNodeWithChildren(virtualNode, virtualNode.hostParent, newElement.elements)

		return virtualNode
	end

	--[[
		Update the given virtual node using a new element describing what it
		should transform into.

		`updateVirtualNode` will return a new virtual node that should replace
		the passed in virtual node. This is because a virtual node can be
		updated with an element referencing a different component!

		In that case, `updateVirtualNode` will unmount the input virtual node,
		mount a new virtual node, and return it in this case, while also issuing
		a warning to the user.
	]]
	function updateVirtualNode(virtualNode, newElement, newState)
		if config.internalTypeChecks then
			internalAssert(Type.of(virtualNode) == Type.VirtualNode, "Expected arg #1 to be of type VirtualNode")
		end
		if config.typeChecks then
			assert(
				Type.of(newElement) == Type.Element or typeof(newElement) == "boolean" or newElement == nil,
				"Expected arg #2 to be of type Element, boolean, or nil"
			)
		end

		-- If nothing changed, we can skip this update
		if virtualNode.currentElement == newElement and newState == nil then
			return virtualNode
		end

		if typeof(newElement) == "boolean" or newElement == nil then
			unmountVirtualNode(virtualNode)
			return nil
		end

		if virtualNode.currentElement.component ~= newElement.component then
			return replaceVirtualNode(virtualNode, newElement)
		end

		local kind = ElementKind.of(newElement)

		local shouldContinueUpdate = true

		if kind == ElementKind.Host then
			virtualNode = renderer.updateHostNode(reconciler, virtualNode, newElement)
		elseif kind == ElementKind.Function then
			virtualNode = updateFunctionVirtualNode(virtualNode, newElement)
		elseif kind == ElementKind.Stateful then
			shouldContinueUpdate = virtualNode.instance:__update(newElement, newState)
		elseif kind == ElementKind.Portal then
			virtualNode = updatePortalVirtualNode(virtualNode, newElement)
		elseif kind == ElementKind.Fragment then
			virtualNode = updateFragmentVirtualNode(virtualNode, newElement)
		else
			error(("Unknown ElementKind %q"):format(tostring(kind), 2))
		end

		-- Stateful components can abort updates via shouldUpdate. If that
		-- happens, we should stop doing stuff at this point.
		if not shouldContinueUpdate then
			return virtualNode
		end

		virtualNode.currentElement = newElement

		return virtualNode
	end

	--[[
		Constructs a new virtual node but not does mount it.
	]]
	local function createVirtualNode(element, hostParent, hostKey, context)
		if config.internalTypeChecks then
			internalAssert(renderer.isHostObject(hostParent) or hostParent == nil, "Expected arg #2 to be a host object")
			internalAssert(typeof(context) == "table" or context == nil, "Expected arg #4 to be of type table or nil")
		end
		if config.typeChecks then
			assert(hostKey ~= nil, "Expected arg #3 to be non-nil")
			assert(
				Type.of(element) == Type.Element or typeof(element) == "boolean",
				"Expected arg #1 to be of type Element or boolean"
			)
		end

		return {
			[Type] = Type.VirtualNode,
			currentElement = element,
			depth = 1,
			children = {},
			hostParent = hostParent,
			hostKey = hostKey,
			context = context,
			-- This copy of context is useful if the element gets replaced
			-- with an element of a different component type
			parentContext = context,
		}
	end

	local function mountFunctionVirtualNode(virtualNode)
		local element = virtualNode.currentElement

		local children = element.component(element.props)

		updateVirtualNodeWithRenderResult(virtualNode, virtualNode.hostParent, children)
	end

	local function mountPortalVirtualNode(virtualNode)
		local element = virtualNode.currentElement

		local targetHostParent = element.props.target
		local children = element.props[Children]

		assert(renderer.isHostObject(targetHostParent), "Expected target to be host object")

		updateVirtualNodeWithChildren(virtualNode, targetHostParent, children)
	end

	local function mountFragmentVirtualNode(virtualNode)
		local element = virtualNode.currentElement
		local children = element.elements

		updateVirtualNodeWithChildren(virtualNode, virtualNode.hostParent, children)
	end

	--[[
		Constructs a new virtual node and mounts it, but does not place it into
		the tree.
	]]
	function mountVirtualNode(element, hostParent, hostKey, context)
		if config.internalTypeChecks then
			internalAssert(renderer.isHostObject(hostParent) or hostParent == nil, "Expected arg #2 to be a host object")
			internalAssert(typeof(context) == "table" or context == nil, "Expected arg #4 to be of type table or nil")
		end
		if config.typeChecks then
			assert(hostKey ~= nil, "Expected arg #3 to be non-nil")
			assert(
				Type.of(element) == Type.Element or typeof(element) == "boolean",
				"Expected arg #1 to be of type Element or boolean"
			)
		end

		-- Boolean values render as nil to enable terse conditional rendering.
		if typeof(element) == "boolean" then
			return nil
		end

		local kind = ElementKind.of(element)

		local virtualNode = createVirtualNode(element, hostParent, hostKey, context)

		if kind == ElementKind.Host then
			renderer.mountHostNode(reconciler, virtualNode)
		elseif kind == ElementKind.Function then
			mountFunctionVirtualNode(virtualNode)
		elseif kind == ElementKind.Stateful then
			element.component:__mount(reconciler, virtualNode)
		elseif kind == ElementKind.Portal then
			mountPortalVirtualNode(virtualNode)
		elseif kind == ElementKind.Fragment then
			mountFragmentVirtualNode(virtualNode)
		else
			error(("Unknown ElementKind %q"):format(tostring(kind), 2))
		end

		return virtualNode
	end

	--[[
		Constructs a new Roact virtual tree, constructs a root node for
		it, and mounts it.
	]]
	local function mountVirtualTree(element, hostParent, hostKey)
		if config.typeChecks then
			assert(Type.of(element) == Type.Element, "Expected arg #1 to be of type Element")
			assert(renderer.isHostObject(hostParent) or hostParent == nil, "Expected arg #2 to be a host object")
		end

		if hostKey == nil then
			hostKey = "RoactTree"
		end

		local tree = {
			[Type] = Type.VirtualTree,
			[InternalData] = {
				-- The root node of the tree, which starts into the hierarchy of
				-- Roact component instances.
				rootNode = nil,
				mounted = true,
			},
		}

		tree[InternalData].rootNode = mountVirtualNode(element, hostParent, hostKey)

		return tree
	end

	--[[
		Unmounts the virtual tree, freeing all of its resources.

		No further operations should be done on the tree after it's been
		unmounted, as indicated by its the `mounted` field.
	]]
	local function unmountVirtualTree(tree)
		local internalData = tree[InternalData]
		if config.typeChecks then
			assert(Type.of(tree) == Type.VirtualTree, "Expected arg #1 to be a Roact handle")
			assert(internalData.mounted, "Cannot unmounted a Roact tree that has already been unmounted")
		end

		internalData.mounted = false

		if internalData.rootNode ~= nil then
			unmountVirtualNode(internalData.rootNode)
		end
	end

	--[[
		Utility method for updating the root node of a virtual tree given a new
		element.
	]]
	local function updateVirtualTree(tree, newElement)
		local internalData = tree[InternalData]
		if config.typeChecks then
			assert(Type.of(tree) == Type.VirtualTree, "Expected arg #1 to be a Roact handle")
			assert(Type.of(newElement) == Type.Element, "Expected arg #2 to be a Roact Element")
		end

		internalData.rootNode = updateVirtualNode(internalData.rootNode, newElement)

		return tree
	end

	reconciler = {
		mountVirtualTree = mountVirtualTree,
		unmountVirtualTree = unmountVirtualTree,
		updateVirtualTree = updateVirtualTree,

		createVirtualNode = createVirtualNode,
		mountVirtualNode = mountVirtualNode,
		unmountVirtualNode = unmountVirtualNode,
		updateVirtualNode = updateVirtualNode,
		updateVirtualNodeWithChildren = updateVirtualNodeWithChildren,
		updateVirtualNodeWithRenderResult = updateVirtualNodeWithRenderResult,
	}

	return reconciler
end

return createReconciler