Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .config/dotnet-tools.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"isRoot": true,
"tools": {
"fable": {
"version": "5.23.0",
"version": "5.24.0",
"commands": [
"fable"
],
Expand Down
61 changes: 61 additions & 0 deletions src/Feliz.CompilerPlugins/AstUtils.fs
Original file line number Diff line number Diff line change
Expand Up @@ -214,3 +214,64 @@ let withTag tag =
| e -> e

let withJSXTag = withTag "jsx"

let isJsxOutput (compiler: PluginHelper) =
match compiler.Options.FileExtension with
| ".jsx"
| ".tsx" -> true
| _ -> false

let jsxProp (key: string) (value: Fable.Expr) =
Fable.Value(Fable.NewTuple([ makeStrConst key; value ], false), None)

let jsxSpread (props: Fable.Expr) =
Fable.Call(
nullValue,
{
makeCallInfo [ props ] with
Tags = [ "jsx-spread" ]
},
Fable.Any,
None
)

let isSeqType (fableType: Fable.Type) =
match fableType with
| Fable.Type.DeclaredType(entity, _) -> entity.FullName = "System.Collections.Generic.IEnumerable`1"
| _ -> false

/// Coerces the `children` prop to the declared F# collection type: the JSX transform sets it to `undefined`,
/// a single element or a JS array depending on how many children the call site nests.
let jsxChildrenAs (compiler: PluginHelper) (fableType: Fable.Type) (children: Fable.Expr) =
let fsharpList =
ImportFromFableLib.makeImportLib compiler Fable.Any "FSharpList" "List"

let ofArray = ImportFromFableLib.makeImportLib compiler Fable.Any "ofArray" "List"

match fableType with
| Fable.Type.List _ ->
emitJs "$1 instanceof $0 ? $1 : $2(Array.isArray($1) ? $1 : $1 == null ? [] : [$1])" [
fsharpList
children
ofArray
]
| Fable.Type.Array _ -> emitJs "Array.isArray($0) ? $0 : $0 == null ? [] : [$0]" [ children ]
| t when isSeqType t ->
emitJs "$1 instanceof $0 || Array.isArray($1) ? $1 : $1 == null ? [] : [$1]" [ fsharpList; children ]
| _ -> children

let jsxElement (compiler: PluginHelper) reactElementType (reactComponent: Fable.Expr) (props: Fable.Expr list) =
let callee = ImportFromFableLib.makeImportLib compiler Fable.Any "create" "JSX"

let props =
Fable.Value(Fable.NewArray(Fable.ArrayValues props, Fable.Any, Fable.ImmutableArray), None)

Fable.Call(
callee,
{
makeCallInfo [ reactComponent; props ] with
Tags = [ "jsx" ]
},
reactElementType,
None
)
76 changes: 54 additions & 22 deletions src/Feliz.CompilerPlugins/ReactComponent.fs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,25 @@ module internal ReactComponentHelpers =
_) as e -> Some e
| _ -> None

let private (|IsComponentCall|_|) =
function
| Call(IsCreateElement _, info, _, r) -> Some(info, r)
| Call(_, info, _, r) when List.contains "jsx" info.Tags -> Some(info, r)
| _ -> None

let private (|IsPropsExpression|_|) =
function
| ObjectExpr(properties, _, _) -> properties |> List.map (fun p -> p.Name, p.Body) |> Some
| Value(NewArray(ArrayValues props, _, _), _) ->
props
|> List.choose (
function
| Value(NewTuple([ Value(StringConstant name, _); value ], _), _) -> Some(name, value)
| _ -> None
)
|> Some
| _ -> None

let rec private (|InnerDeclaredTypeFullName|_|) (type': Type) =
match type' with
| LambdaType(_, InnerDeclaredTypeFullName returnType) -> Some(returnType)
Expand All @@ -92,11 +111,6 @@ module internal ReactComponentHelpers =
Some(selector, fullName)
| _ -> None

let private (|IsObjectExpression|_|) =
function
| ObjectExpr(properties, _, _) -> Some properties
| _ -> None

let rec private tryGetSourceArgName (arg: Expr) =
match arg with
| IdentExpr({ Name = name; Range = range }) -> Some(name, range)
Expand All @@ -107,10 +121,10 @@ module internal ReactComponentHelpers =
let verify (body: Expr) (lazyComponentName) (compilerInfo: PluginHelper) : unit =
let rec loopAst (body: Expr) : unit =
match body with
| Call(IsCreateElement _, info, _, _) ->
| IsComponentCall(info, _) ->

match info.Args with
| IsReactElementImport(sourceComponentName, returnTypeFullName) :: IsObjectExpression properties :: _ ->
| IsReactElementImport(sourceComponentName, returnTypeFullName) :: IsPropsExpression properties :: _ ->
if returnTypeFullName.EndsWith "ReactElement" |> not then
let errorMsg =
String.concat "" [
Expand All @@ -130,12 +144,12 @@ module internal ReactComponentHelpers =

let lazyArgList =
properties
|> List.choose (fun property ->
|> List.choose (fun (propertyName, propertyValue) ->

match tryGetSourceArgName property.Body with
match tryGetSourceArgName propertyValue with
| Some(argName, range) ->
// returns sourceName, lazyName and range of the argument.
Some(property.Name, argName, range)
Some(propertyName, argName, range)
| None -> None
)

Expand Down Expand Up @@ -183,7 +197,7 @@ module internal ReactComponentHelpers =

let rec loopAst (body: Expr) =
match body with
| Call(IsCreateElement _, info, _, r) ->
| IsComponentCall(info, r) ->

let relativeImport =
IdentExpr {
Expand All @@ -197,7 +211,7 @@ module internal ReactComponentHelpers =
}

let pathInfo = getPathInfo info.Args compilerInfo
let info = { info with Args = pathInfo }
let info = { info with Args = pathInfo; Tags = [] }

let t =
DeclaredType(
Expand Down Expand Up @@ -388,25 +402,31 @@ type ReactComponentAttribute
// F# Component { Value = 1 }
// JSX <Component Value={1} />
// JS createElement(Component, { Value: 1 })
if AstUtils.recordHasField "Key" compiler info.Args[0].Type then
// When the key property is upper-case (which is common in record fields)
// then we should rewrite it
let modifiedRecord =
let props =
if AstUtils.recordHasField "Key" compiler info.Args[0].Type then
// When the key property is upper-case (which is common in record fields)
// then we should rewrite it
AstUtils.emitJs "(($value) => { $value.key = $value.Key; return $value; })($0)" [ info.Args[0] ]
else
info.Args[0]

AstUtils.createElement reactElType [ reactComponent; modifiedRecord ]
if AstUtils.isJsxOutput compiler then
AstUtils.jsxElement compiler reactElType reactComponent [ AstUtils.jsxSpread props ]
else
AstUtils.createElement reactElType [ reactComponent; info.Args[0] ]
AstUtils.createElement reactElType [ reactComponent; props ]
elif info.Args.Length = 1 && info.Args[0].Type = Type.Unit then
// F# Component()
// JSX <Component />
// JS createElement(Component, null)
AstUtils.createElement reactElType [ reactComponent; AstUtils.nullValue ]
if AstUtils.isJsxOutput compiler then
AstUtils.jsxElement compiler reactElType reactComponent []
else
AstUtils.createElement reactElType [ reactComponent; AstUtils.nullValue ]
else
let mutable keyBinding = None
let mutable tupleArgBinding = 0

let propsObj =
let props =
List.zip (List.take info.Args.Length membArgs) info.Args
|> List.collect (fun (arg, expr) ->
match arg.Name, expr with
Expand All @@ -422,9 +442,14 @@ type ReactComponentAttribute
name, expr
]
) // if input is a single tupled argument, we don't have names
|> AstUtils.objExpr

let reactEl = AstUtils.createElement reactElType [ reactComponent; propsObj ]
let reactEl =
if AstUtils.isJsxOutput compiler then
props
|> List.map (fun (name, value) -> AstUtils.jsxProp name value)
|> AstUtils.jsxElement compiler reactElType reactComponent
else
AstUtils.createElement reactElType [ reactComponent; AstUtils.objExpr props ]

let expr =
match keyBinding with
Expand Down Expand Up @@ -620,6 +645,13 @@ type ReactComponentAttribute
let getterKey = if arg.DisplayName = "key" then "$key" else arg.DisplayName
let getterKind = ExprGet(AstUtils.makeStrConst getterKey)
let getter = Get(IdentExpr propsArg, getterKind, Any, None)

let getter =
if arg.DisplayName = "children" && AstUtils.isJsxOutput compiler then
AstUtils.jsxChildrenAs compiler arg.Type getter
else
getter

(arg, getter) :: bindings
)
|> List.rev
Expand Down
1 change: 1 addition & 0 deletions tests/Feliz/Feliz.Tests.fsproj
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
<Compile Include="EnsureJSX.test.fs" />
<Compile Include="Basic.fs" />
<Compile Include="Basic.test.fs" />
<Compile Include="ReactComponentChildren.test.fs" />
<Compile Include="ReactBindings/Context.test.fs" />
<Compile Include="ReactBindings/Fragment.test.fs" />
<Compile Include="ReactBindings/ReactLazyComponent/Fixtures/Models.fs" />
Expand Down
55 changes: 55 additions & 0 deletions tests/Feliz/ReactComponentChildren.test.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
module Tests.ReactComponentChildren

open Feliz
open Vitest

[<ReactComponent>]
let ListChildren (children: ReactElement list) =
Html.div [
prop.testId "count"
prop.text (sprintf "count=%d" (List.length children))
]

[<ReactComponent>]
let ArrayChildren (children: ReactElement[]) =
Html.div [
prop.testId "count"
prop.text (sprintf "count=%d" children.Length)
]

[<ReactComponent>]
let SeqChildren (children: seq<ReactElement>) =
Html.div [
prop.testId "count"
prop.text (sprintf "count=%d" (Seq.length children))
]

[<ReactComponent>]
let Greeting (name: string) = Html.span name

let private childrenTests name (render: ReactElement list -> ReactElement) =
describe name
<| fun _ ->
test "two children"
<| fun _ ->
let r = RTL.render (render [ Greeting "a"; Greeting "b" ])
expect(r.getByTestId "count").toHaveTextContent "count=2"

test "one child"
<| fun _ ->
let r = RTL.render (render [ Greeting "a" ])
expect(r.getByTestId "count").toHaveTextContent "count=1"

test "no children"
<| fun _ ->
let r = RTL.render (render [])
expect(r.getByTestId "count").toHaveTextContent "count=0"

test "children built at runtime"
<| fun _ ->
let r = RTL.render (render ([ "a"; "b"; "c" ] |> List.map Greeting))
expect(r.getByTestId "count").toHaveTextContent "count=3"

childrenTests "ReactComponent children typed as list" ListChildren
childrenTests "ReactComponent children typed as array" (fun xs -> ArrayChildren(Array.ofList xs))
childrenTests "ReactComponent children typed as seq" (fun xs -> SeqChildren(List.toSeq xs))
Loading