Created
August 19, 2024 21:27
-
-
Save cxmeel/646f450bd4db10ba3f056f420606efa9 to your computer and use it in GitHub Desktop.
Generates a React component from an existing Instance. Alternatively, set `clone = false` to "inverse portal."
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local React = require("@pkgs/React") | |
local useEffect = React.useEffect | |
local e = React.createElement | |
local function applyProps(target: Instance, props, applyRef) | |
for propName, propValue in props do | |
if propName == "children" or propName == "Parent" then | |
continue | |
end | |
if propName == "ref" then | |
if not applyRef then | |
continue | |
end | |
if typeof(propValue) == "function" then | |
propValue(target) | |
elseif typeof(propValue) == "table" then | |
propValue.current = target | |
end | |
continue | |
end | |
if propName:find("%.") then | |
local parts = propName:split(".") | |
local current = target | |
for i = 1, #parts - 1 do | |
current = (current :: any)[parts[i]] | |
end | |
(current :: any)[parts[#parts]] = propValue | |
continue | |
end | |
(target :: any)[propName] = propValue | |
end | |
end | |
local function fromInstance(target: Instance, clone: boolean?) | |
local instance = clone ~= false and target:Clone() or target | |
return function(props: { [string]: any }) | |
useEffect(function() | |
return function() | |
instance:Destroy() | |
end | |
end, {}) | |
useEffect(function() | |
applyProps(instance, props, false) | |
end, { props }) | |
if instance.Parent then | |
return | |
end | |
return e("Folder", { | |
ref = function(rbx: Folder) | |
if instance.Parent then | |
return | |
end | |
applyProps(instance, props, true) | |
instance.Parent = rbx.Parent | |
rbx:Destroy() | |
end, | |
}) | |
end | |
end | |
return fromInstance |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment