diff --git a/CHANGELOG.md b/CHANGELOG.md index 07c39660b1..4e25a06b4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,7 @@ - Allow oneliner formatting when including module with single type alias. https://github.com/rescript-lang/rescript/pull/7502 - Improve error messages for JSX type mismatches, passing objects where record is expected, passing array literal where tuple is expected, and more. https://github.com/rescript-lang/rescript/pull/7500 - Show in error messages when coercion can be used to fix a type mismatch. https://github.com/rescript-lang/rescript/pull/7505 +- Remove deprecated pipe last (|>) syntax. https://github.com/rescript-lang/rescript/pull/7512 # 12.0.0-alpha.13 diff --git a/analysis/reanalyze/src/Exception.ml b/analysis/reanalyze/src/Exception.ml index 891b2d6d4e..d9a5c59dbd 100644 --- a/analysis/reanalyze/src/Exception.ml +++ b/analysis/reanalyze/src/Exception.ml @@ -304,17 +304,6 @@ let traverseAst () = let exceptions = [arg] |> raiseArgs in currentEvents := {Event.exceptions; loc; kind = Raises} :: !currentEvents; arg |> snd |> iterExprOpt self - | Texp_apply - { - funct = {exp_desc = Texp_ident (atat, _, _)}; - args = [arg; (_lbl1, Some {exp_desc = Texp_ident (callee, _, _)})]; - } - when (* Exn(...) |> raise *) - atat |> Path.name = "Pervasives.|>" && callee |> Path.name |> isRaise - -> - let exceptions = [arg] |> raiseArgs in - currentEvents := {Event.exceptions; loc; kind = Raises} :: !currentEvents; - arg |> snd |> iterExprOpt self | Texp_apply {funct = {exp_desc = Texp_ident (callee, _, _)} as e; args} -> let calleeName = Path.name callee in if calleeName |> isRaise then diff --git a/compiler/syntax/src/res_comments_table.ml b/compiler/syntax/src/res_comments_table.ml index 867a579d4e..62ce43b66c 100644 --- a/compiler/syntax/src/res_comments_table.ml +++ b/compiler/syntax/src/res_comments_table.ml @@ -1483,9 +1483,8 @@ and walk_expression expr t comments = txt = Longident.Lident ( ":=" | "||" | "&&" | "==" | "===" | "<" | ">" | "!=" - | "!==" | "<=" | ">=" | "|>" | "+" | "+." | "-" | "-." - | "++" | "^" | "*" | "*." | "/" | "/." | "**" | "->" - | "<>" ); + | "!==" | "<=" | ">=" | "+" | "+." | "-" | "-." | "++" + | "^" | "*" | "*." | "/" | "/." | "**" | "->" | "<>" ); }; }; args = [(Nolabel, operand1); (Nolabel, operand2)]; diff --git a/compiler/syntax/src/res_core.ml b/compiler/syntax/src/res_core.ml index 897d7f12f4..da7614ba8f 100644 --- a/compiler/syntax/src/res_core.ml +++ b/compiler/syntax/src/res_core.ml @@ -2186,25 +2186,9 @@ and parse_binary_expr ?(context = OrdinaryExpr) ?a p prec = let b = parse_binary_expr ~context p token_prec in let loc = mk_loc a.Parsetree.pexp_loc.loc_start b.pexp_loc.loc_end in let expr = - match (token, b.pexp_desc) with - | ( BarGreater, - Pexp_apply {funct = fun_expr; args; partial; transformed_jsx} ) -> - { - b with - pexp_desc = - Pexp_apply - { - funct = fun_expr; - args = args @ [(Nolabel, a)]; - partial; - transformed_jsx; - }; - } - | BarGreater, _ -> Ast_helper.Exp.apply ~loc b [(Nolabel, a)] - | _ -> - Ast_helper.Exp.apply ~loc - (make_infix_operator p token start_pos end_pos) - [(Nolabel, a); (Nolabel, b)] + Ast_helper.Exp.apply ~loc + (make_infix_operator p token start_pos end_pos) + [(Nolabel, a); (Nolabel, b)] in Parser.eat_breadcrumb p; loop expr) diff --git a/compiler/syntax/src/res_parsetree_viewer.ml b/compiler/syntax/src/res_parsetree_viewer.ml index 0a4d43bf2c..56e3c0895b 100644 --- a/compiler/syntax/src/res_parsetree_viewer.ml +++ b/compiler/syntax/src/res_parsetree_viewer.ml @@ -280,7 +280,7 @@ let operator_precedence operator = | "&&" -> 3 | "^" -> 4 | "&" -> 5 - | "==" | "===" | "<" | ">" | "!=" | "<>" | "!==" | "<=" | ">=" | "|>" -> 6 + | "==" | "===" | "<" | ">" | "!=" | "<>" | "!==" | "<=" | ">=" -> 6 | "<<" | ">>" | ">>>" -> 7 | "+" | "+." | "-" | "-." | "++" -> 8 | "*" | "*." | "/" | "/." | "%" -> 9 @@ -317,8 +317,8 @@ let is_unary_bitnot_expression expr = let is_binary_operator operator = match operator with | ":=" | "||" | "&&" | "==" | "===" | "<" | ">" | "!=" | "!==" | "<=" | ">=" - | "|>" | "+" | "+." | "-" | "-." | "++" | "*" | "*." | "/" | "/." | "**" - | "->" | "<>" | "%" | "&" | "^" | "<<" | ">>" | ">>>" -> + | "+" | "+." | "-" | "-." | "++" | "*" | "*." | "/" | "/." | "**" | "->" + | "<>" | "%" | "&" | "^" | "<<" | ">>" | ">>>" -> true | _ -> false @@ -715,7 +715,7 @@ let is_single_pipe_expr expr = match expr.pexp_desc with | Pexp_apply { - funct = {pexp_desc = Pexp_ident {txt = Longident.Lident ("->" | "|>")}}; + funct = {pexp_desc = Pexp_ident {txt = Longident.Lident "->"}}; args = [(Nolabel, _operand1); (Nolabel, _operand2)]; } -> true @@ -724,7 +724,7 @@ let is_single_pipe_expr expr = match expr.pexp_desc with | Pexp_apply { - funct = {pexp_desc = Pexp_ident {txt = Longident.Lident ("->" | "|>")}}; + funct = {pexp_desc = Pexp_ident {txt = Longident.Lident "->"}}; args = [(Nolabel, operand1); (Nolabel, _operand2)]; } when not (is_pipe_expr operand1) -> diff --git a/compiler/syntax/src/res_printer.ml b/compiler/syntax/src/res_printer.ml index 5690282e4b..3089dd2b77 100644 --- a/compiler/syntax/src/res_printer.ml +++ b/compiler/syntax/src/res_printer.ml @@ -3753,13 +3753,10 @@ and print_unary_expression ~state expr cmt_tbl = and print_binary_expression ~state (expr : Parsetree.expression) cmt_tbl = let print_binary_operator ~inline_rhs operator = let spacing_before_operator = - if operator = "->" then Doc.soft_line - else if operator = "|>" then Doc.line - else Doc.space + if operator = "->" then Doc.soft_line else Doc.space in let spacing_after_operator = if operator = "->" then Doc.nil - else if operator = "|>" then Doc.space else if inline_rhs then Doc.space else Doc.line in @@ -3930,10 +3927,7 @@ and print_binary_expression ~state (expr : Parsetree.expression) cmt_tbl = match expr.pexp_desc with | Pexp_apply { - funct = - { - pexp_desc = Pexp_ident {txt = Longident.Lident (("->" | "|>") as op)}; - }; + funct = {pexp_desc = Pexp_ident {txt = Longident.Lident ("->" as op)}}; args = [(Nolabel, lhs); (Nolabel, rhs)]; } when not @@ -3952,8 +3946,6 @@ and print_binary_expression ~state (expr : Parsetree.expression) cmt_tbl = (match (lhs_has_comment_below, op) with | true, "->" -> Doc.concat [Doc.soft_line; Doc.text "->"] | false, "->" -> Doc.text "->" - | true, "|>" -> Doc.concat [Doc.line; Doc.text "|> "] - | false, "|>" -> Doc.text " |> " | _ -> Doc.nil); rhs_doc; ]) diff --git a/compiler/syntax/src/res_scanner.ml b/compiler/syntax/src/res_scanner.ml index 6ce390a68d..a49ea8a5ee 100644 --- a/compiler/syntax/src/res_scanner.ml +++ b/compiler/syntax/src/res_scanner.ml @@ -820,9 +820,6 @@ let rec scan scanner = | '|' -> next2 scanner; Token.Lor - | '>' -> - next2 scanner; - Token.BarGreater | _ -> next scanner; Token.Bar) diff --git a/compiler/syntax/src/res_token.ml b/compiler/syntax/src/res_token.ml index 4a4c1e0fd7..312af0c423 100644 --- a/compiler/syntax/src/res_token.ml +++ b/compiler/syntax/src/res_token.ml @@ -94,7 +94,6 @@ type t = | TemplateTail of string * Lexing.position | TemplatePart of string * Lexing.position | Backtick - | BarGreater | Try | DocComment of Location.t * string | ModuleComment of Location.t * string @@ -109,7 +108,7 @@ let precedence = function | Caret -> 4 | Band -> 5 | Equal | EqualEqual | EqualEqualEqual | LessThan | GreaterThan | BangEqual - | BangEqualEqual | LessEqual | GreaterEqual | BarGreater -> + | BangEqualEqual | LessEqual | GreaterEqual -> 6 | LeftShift | RightShift | RightShiftUnsigned -> 7 | Plus | PlusDot | Minus | MinusDot | PlusPlus -> 8 @@ -213,7 +212,6 @@ let to_string = function | TemplatePart (text, _) -> text ^ "${" | TemplateTail (text, _) -> "TemplateTail(" ^ text ^ ")" | Backtick -> "`" - | BarGreater -> "|>" | Try -> "try" | DocComment (_loc, s) -> "DocComment " ^ s | ModuleComment (_loc, s) -> "ModuleComment " ^ s diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/expected/deadcode.txt b/tests/analysis_tests/tests-reanalyze/deadcode/expected/deadcode.txt index 121a796eb4..a0b06162e0 100644 --- a/tests/analysis_tests/tests-reanalyze/deadcode/expected/deadcode.txt +++ b/tests/analysis_tests/tests-reanalyze/deadcode/expected/deadcode.txt @@ -1216,7 +1216,7 @@ addValueReference OptArg.res:14:4 --> OptArg.res:14:21 addValueReference OptArg.res:14:4 --> OptArg.res:14:27 DeadOptionalArgs.addReferences twoArgs called with optional argNames: argNamesMaybe: OptArg.res:16:7 - addValueReference OptArg.res:16:12 --> OptArg.res:14:4 + addValueReference OptArg.res:16:10 --> OptArg.res:14:4 addValueReference OptArg.res:18:4 --> OptArg.res:18:17 addValueReference OptArg.res:18:4 --> OptArg.res:18:14 addValueReference OptArg.res:18:4 --> OptArg.res:18:24 @@ -2510,7 +2510,7 @@ File References Live Value +OptArg.+fourArgs: 1 references (OptArg.res:26:4) [0] Live Value +OptArg.+wrapOneArg: 1 references (OptArg.res:22:7) [0] Live Value +OptArg.+oneArg: 1 references (OptArg.res:20:4) [0] - Live Value +OptArg.+twoArgs: 1 references (OptArg.res:16:12) [0] + Live Value +OptArg.+twoArgs: 1 references (OptArg.res:16:10) [0] Live Value +OptArg.+threeArgs: 2 references (OptArg.res:11:7, OptArg.res:12:7) [0] Live Value +OptArg.+bar: 2 references (OptArg.res:7:7, OptArg.resi:2:0) [0] Live Value +OptArg.+foo: 1 references (OptArg.res:5:7) [0] diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/OptArg.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/OptArg.res index a556a52c0f..d72a06e155 100644 --- a/tests/analysis_tests/tests-reanalyze/deadcode/src/OptArg.res +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/OptArg.res @@ -13,7 +13,7 @@ Js.log(threeArgs(~a=4, 1)) let twoArgs = (~a=1, ~b=2, c) => a + b + c -Js.log(1 |> twoArgs) +Js.log(1->twoArgs) let oneArg = (~a=1, ~z, b) => a + b diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/Uncurried.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/Uncurried.res index cf85f9d9cd..6f45db2925 100644 --- a/tests/analysis_tests/tests-reanalyze/deadcode/src/Uncurried.res +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/Uncurried.res @@ -14,19 +14,19 @@ type u3 = (. int, string, int) => string let uncurried0 = (. ()) => "" @genType -let uncurried1 = (. x) => x |> string_of_int +let uncurried1 = (. x) => x -> string_of_int @genType -let uncurried2 = (. x, y) => (x |> string_of_int) ++ y +let uncurried2 = (. x, y) => (x -> string_of_int) ++ y @genType -let uncurried3 = (. x, y, z) => (x |> string_of_int) ++ (y ++ (z |> string_of_int)) +let uncurried3 = (. x, y, z) => (x -> string_of_int) ++ (y ++ (z -> string_of_int)) @genType -let curried3 = (x, y, z) => (x |> string_of_int) ++ (y ++ (z |> string_of_int)) +let curried3 = (x, y, z) => (x -> string_of_int) ++ (y ++ (z -> string_of_int)) @genType -let callback = cb => cb() |> string_of_int +let callback = cb => cb() -> string_of_int type auth = {login: unit => string} type authU = {loginU: (. unit) => string} diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/Unison.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/Unison.res index b56f30c871..154c25fa76 100644 --- a/tests/analysis_tests/tests-reanalyze/deadcode/src/Unison.res +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/Unison.res @@ -27,9 +27,9 @@ let rec toString = (~width, stack) => switch stack { | Cons({break, doc}, stack) => switch break { - | IfNeed => (fits(width, stack) ? "fits " : "no ") ++ (stack |> toString(~width=width - 1)) - | Never => "never " ++ (doc ++ (stack |> toString(~width=width - 1))) - | Always => "always " ++ (doc ++ (stack |> toString(~width=width - 1))) + | IfNeed => (fits(width, stack) ? "fits " : "no ") ++ (stack -> toString(~width=width - 1)) + | Never => "never " ++ (doc ++ (stack -> toString(~width=width - 1))) + | Always => "always " ++ (doc ++ (stack -> toString(~width=width - 1))) } | Empty => "" } diff --git a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/TestYojson.res b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/TestYojson.res index 4bb1e410a1..b98e4ff83f 100644 --- a/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/TestYojson.res +++ b/tests/analysis_tests/tests-reanalyze/deadcode/src/exception/TestYojson.res @@ -4,7 +4,7 @@ let foo = x => Yojson.Basic.from_string(x) let bar = (str, json) => switch { open Yojson.Basic.Util - json |> member(str) + member(str, json) } { | j => j | exception Yojson.Basic.Util.Type_error("a", d) when d == json => json diff --git a/tests/syntax_tests/data/conversion/reason/attributes.res b/tests/syntax_tests/data/conversion/reason/attributes.res index d7f62c9132..4549e63705 100644 --- a/tests/syntax_tests/data/conversion/reason/attributes.res +++ b/tests/syntax_tests/data/conversion/reason/attributes.res @@ -17,4 +17,4 @@ list{1, 2, 3}->map(a => a + 1)->filter(a => modulo(a, 2) == 0)->Js.log type t @new external make: unit => t = "DOMParser" -Js.log(make() |> parseHtmlFromString("sdsd")) +Js.log(make()->parseHtmlFromString("sdsd")) diff --git a/tests/syntax_tests/data/conversion/reason/expected/attributes.res.txt b/tests/syntax_tests/data/conversion/reason/expected/attributes.res.txt index 3adb465c6e..4549e63705 100644 --- a/tests/syntax_tests/data/conversion/reason/expected/attributes.res.txt +++ b/tests/syntax_tests/data/conversion/reason/expected/attributes.res.txt @@ -17,4 +17,4 @@ list{1, 2, 3}->map(a => a + 1)->filter(a => modulo(a, 2) == 0)->Js.log type t @new external make: unit => t = "DOMParser" -Js.log(parseHtmlFromString("sdsd", make())) +Js.log(make()->parseHtmlFromString("sdsd")) diff --git a/tests/syntax_tests/data/conversion/reason/expected/underscoreSugar.res.txt b/tests/syntax_tests/data/conversion/reason/expected/underscoreSugar.res.txt index a67f171f48..3d93c56b5f 100644 --- a/tests/syntax_tests/data/conversion/reason/expected/underscoreSugar.res.txt +++ b/tests/syntax_tests/data/conversion/reason/expected/underscoreSugar.res.txt @@ -1 +1 @@ -let photo = Array.get(_, 0)(filterNone(pricedRoom["room"]["photos"])) +let photo = pricedRoom["room"]["photos"]->filterNone->Array.get(_, 0) diff --git a/tests/syntax_tests/data/conversion/reason/underscoreSugar.res b/tests/syntax_tests/data/conversion/reason/underscoreSugar.res index 9330f5c835..3d93c56b5f 100644 --- a/tests/syntax_tests/data/conversion/reason/underscoreSugar.res +++ b/tests/syntax_tests/data/conversion/reason/underscoreSugar.res @@ -1 +1 @@ -let photo = pricedRoom["room"]["photos"] |> filterNone |> Array.get(_, 0) +let photo = pricedRoom["room"]["photos"]->filterNone->Array.get(_, 0) diff --git a/tests/syntax_tests/data/idempotency/bs-css/Css_Legacy_Core.res b/tests/syntax_tests/data/idempotency/bs-css/Css_Legacy_Core.res index ed928be91e..cd62df5885 100644 --- a/tests/syntax_tests/data/idempotency/bs-css/Css_Legacy_Core.res +++ b/tests/syntax_tests/data/idempotency/bs-css/Css_Legacy_Core.res @@ -1492,7 +1492,7 @@ let gridLengthToJs = x => } let string_of_dimensions = dimensions => - dimensions |> List.map(gridLengthToJs) |> String.concat(" ") + dimensions->List.map(gridLengthToJs)->String.concat(" ") let gridTemplateColumns = dimensions => D("gridTemplateColumns", string_of_dimensions(dimensions)) @@ -1699,13 +1699,13 @@ let fontFace = (~fontFamily, ~src, ~fontStyle=?, ~fontWeight=?, ~fontDisplay=?, let fontStyle = Js.Option.map((. value) => FontStyle.toString(value), fontStyle) let src = src - |> List.map(x => + ->List.map(x => switch x { | #localUrl(value) => `local("$(value)")` | #url(value) => `url("$(value)")` } ) - |> String.concat(", ") + ->String.concat(", ") let fontStyle = Belt.Option.mapWithDefault(fontStyle, "", s => "font-style: " ++ (s ++ ";")) let fontWeight = Belt.Option.mapWithDefault(fontWeight, "", w => diff --git a/tests/syntax_tests/data/idempotency/bs-css/Css_test.res b/tests/syntax_tests/data/idempotency/bs-css/Css_test.res index 900e1d168f..d0b3074109 100644 --- a/tests/syntax_tests/data/idempotency/bs-css/Css_test.res +++ b/tests/syntax_tests/data/idempotency/bs-css/Css_test.res @@ -21,7 +21,7 @@ let r = x => toJson(list{x}) /* simple rule for more readable tests */ describe("Var", () => { test("test usage (limited)", () => - expect((r(color(var("foo"))), r(marginTop(var("--bar"))))->Js.Json.stringifyAny) |> toBeJson(( + expect((r(color(var("foo"))), r(marginTop(var("--bar"))))->Js.Json.stringifyAny)->toBeJson(( {"color": "var(--foo)"}, {"marginTop": "var(--bar)"}, )) @@ -33,7 +33,7 @@ describe("Var", () => { r(textDecoration(varDefault("foo", "default"))), r(alignItems(varDefault("--bar", "default"))), )->Js.Json.stringifyAny, - ) |> toBeJson(({"textDecoration": "var(--foo,default)"}, {"alignItems": "var(--bar,default)"})) + )->toBeJson(({"textDecoration": "var(--foo,default)"}, {"alignItems": "var(--bar,default)"})) ) }) @@ -50,7 +50,7 @@ describe("Color style", () => r(color(hex("FFF"))), r(color(currentColor)), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"color": "rgb(1, 2, 3)"}, {"color": "rgba(4, 5, 6, 0.3)"}, {"color": "hsl(7deg, 8%, 9%)"}, @@ -64,10 +64,10 @@ describe("Color style", () => ) describe("Label", () => - test("test value", () => expect(r(label("a"))->Js.Json.stringifyAny) |> toBeJson({"label": "a"})) + test("test value", () => expect(r(label("a"))->Js.Json.stringifyAny)->toBeJson({"label": "a"})) ) // test("test classname", () => -// expect(style([label("theName")])) |> toContainString("theName") +// expect(style([label("theName")]))->toContainString("theName") // ); describe("Filter", () => @@ -85,7 +85,7 @@ describe("Filter", () => r(filter(list{#unset})), r(filter(list{#url("myurl")})), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"filter": "opacity(10%) invert(20%)"}, {"filter": "blur(20px) brightness(20%)"}, {"filter": "contrast(30%) drop-shadow(5px 6px 7px rgb(255, 0, 0))"}, @@ -109,7 +109,7 @@ describe("Angle", () => r(transform(rotate(grad(38.8)))), r(transform(rotate(turn(0.25)))), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"transform": "rotate(1deg)"}, {"transform": "rotate(6.28rad)"}, {"transform": "rotate(38.8grad)"}, @@ -129,7 +129,7 @@ describe("Direction", () => r(direction(unset)), r(direction(initial)), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"direction": "ltr"}, {"direction": "ltr"}, {"direction": "rtl"}, @@ -154,7 +154,7 @@ describe("Resize", () => r(resize(unset)), r(resize(initial)), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"resize": "none"}, {"resize": "both"}, {"resize": "horizontal"}, @@ -179,7 +179,7 @@ describe("Backdrop filter", () => r(backdropFilter(list{#invert(#num(30)), #opacity(#percent(10.0))})), r(backdropFilter(list{#saturate(#num(30)), #sepia(#percent(10.0))})), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"backdrop-filter": "none"}, {"backdrop-filter": "blur(10px), brightness(42%)"}, {"backdrop-filter": "contrast(10), drop-shadow(0.5%)"}, @@ -212,7 +212,7 @@ describe("Gradient background", () => ), ), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"background": "linear-gradient(45deg, #FF0000 0, #0000FF 100%)"}, { "background": "repeating-linear-gradient(45deg, #FF0000 0, #0000FF 10px)", @@ -234,7 +234,7 @@ describe("Position", () => { r(bottom(pct(20.))), r(left(vh(4.))), )->Js.Json.stringifyAny, - ) |> toBeJson(({"top": "10px"}, {"right": "1rem"}, {"bottom": "20%"}, {"left": "4vh"})) + )->toBeJson(({"top": "10px"}, {"right": "1rem"}, {"bottom": "20%"}, {"left": "4vh"})) ) test("should allow cascading", () => @@ -245,7 +245,7 @@ describe("Position", () => { r(bottom(unset)), r(left(initial)), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"top": "initial"}, {"right": "inherit"}, {"bottom": "unset"}, @@ -267,7 +267,7 @@ describe("object-fit", () => r(objectFit(#initial)), r(objectFit(#unset)), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"objectFit": "fill"}, {"objectFit": "contain"}, {"objectFit": "cover"}, @@ -287,7 +287,7 @@ describe("box-shadow", () => { r(boxShadow(Shadow.box(green))), r(boxShadows(list{Shadow.box(yellow), Shadow.box(red)})), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"boxShadow": "0 0 0 0 #008000"}, {"boxShadow": "0 0 0 0 #FFFF00, 0 0 0 0 #FF0000"}, )) @@ -299,7 +299,7 @@ describe("box-shadow", () => { r(boxShadow(Shadow.box(~x=px(1), ~y=px(2), red))), r(boxShadow(Shadow.box(~inset=true, red))), )->Js.Json.stringifyAny, - ) |> toBeJson(({"boxShadow": "1px 2px 0 0 #FF0000"}, {"boxShadow": "0 0 0 0 #FF0000 inset"})) + )->toBeJson(({"boxShadow": "1px 2px 0 0 #FF0000"}, {"boxShadow": "0 0 0 0 #FF0000 inset"})) ) test("should allow special values", () => @@ -311,7 +311,7 @@ describe("box-shadow", () => { r(boxShadow(unset)), r(important(boxShadow(none))), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"boxShadow": "none"}, {"boxShadow": "inherit"}, {"boxShadow": "initial"}, @@ -328,7 +328,7 @@ describe("text-shadow", () => { r(textShadow(Shadow.text(green))), r(textShadows(list{Shadow.text(yellow), Shadow.text(red)})), )->Js.Json.stringifyAny, - ) |> toBeJson(({"textShadow": "0 0 0 #008000"}, {"textShadow": "0 0 0 #FFFF00, 0 0 0 #FF0000"})) + )->toBeJson(({"textShadow": "0 0 0 #008000"}, {"textShadow": "0 0 0 #FFFF00, 0 0 0 #FF0000"})) ) test("should use options when present", () => @@ -337,7 +337,7 @@ describe("text-shadow", () => { r(textShadow(Shadow.text(~x=px(1), ~y=px(2), red))), r(textShadow(Shadow.text(~blur=vh(1.), red))), )->Js.Json.stringifyAny, - ) |> toBeJson(({"textShadow": "1px 2px 0 #FF0000"}, {"textShadow": "0 0 1vh #FF0000"})) + )->toBeJson(({"textShadow": "1px 2px 0 #FF0000"}, {"textShadow": "0 0 1vh #FF0000"})) ) test("should allow special values", () => @@ -349,7 +349,7 @@ describe("text-shadow", () => { r(textShadow(unset)), r(important(textShadow(none))), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"textShadow": "none"}, {"textShadow": "inherit"}, {"textShadow": "initial"}, @@ -366,7 +366,7 @@ describe("transitions", () => { r(transition("transform")), r(transitions(list{Transition.shorthand("height"), Transition.shorthand("top")})), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"transition": "0ms ease 0ms transform"}, {"transition": "0ms ease 0ms height, 0ms ease 0ms top"}, )) @@ -375,7 +375,7 @@ describe("transitions", () => { test("should use options when present", () => expect( r(transition(~duration=3, ~delay=4, ~timingFunction=easeOut, "top"))->Js.Json.stringifyAny, - ) |> toBeJson({"transition": "3ms ease-out 4ms top"}) + )->toBeJson({"transition": "3ms ease-out 4ms top"}) ) }) @@ -393,7 +393,7 @@ describe("animation", () => { }), ), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"animation": "a 0ms ease 0ms 1 normal none running"}, { "animation": "a1 0ms ease 0ms 1 normal none running, a2 0ms ease 0ms 1 normal none running", @@ -415,7 +415,7 @@ describe("animation", () => { toAnimationName("a"), ), )->Js.Json.stringifyAny, - ) |> toBeJson({ + )->toBeJson({ "animation": "a 300ms linear 400ms infinite reverse forwards running", }) ) @@ -430,7 +430,7 @@ describe("Word spacing", () => r(wordSpacing(pct(50.))), r(wordSpacing(inherit_)), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"wordSpacing": "normal"}, {"wordSpacing": "1vh"}, {"wordSpacing": "50%"}, @@ -449,7 +449,7 @@ describe("gridTemplateAreas", () => { r(gridTemplateAreas(#initial)), r(gridTemplateAreas(#unset)), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"gridTemplateAreas": "none"}, {"gridTemplateAreas": "'a'"}, {"gridTemplateAreas": "inherit"}, @@ -459,7 +459,7 @@ describe("gridTemplateAreas", () => { ) test("sucessfully combines list", () => - expect(r(gridTemplateAreas(#areas(list{"a a a", "b b b"})))->Js.Json.stringifyAny) |> toBeJson({ + expect(r(gridTemplateAreas(#areas(list{"a a a", "b b b"})))->Js.Json.stringifyAny)->toBeJson({ "gridTemplateAreas": "'a a a' 'b b b'", }) ) @@ -479,7 +479,7 @@ describe("GridArea", () => { r(gridArea(#initial)), r(gridArea(#unset)), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"gridArea": "auto"}, {"gridArea": "a"}, {"gridArea": "1"}, @@ -499,7 +499,7 @@ describe("GridArea", () => { r(gridArea3(#ident("a"), #numIdent(1, "a"), #auto)), r(gridArea4(#num(5), #span(#num(16)), #span(#ident("b")), #auto)), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"gridArea": "auto / 1"}, {"gridArea": "a / 1 a / auto"}, {"gridArea": "5 / span 16 / span b / auto"}, @@ -511,7 +511,7 @@ describe("gridTemplateCoumns", () => { test("concatenates list", () => expect( r(gridTemplateColumns(list{#fr(1.), #px(100), #auto}))->Js.Json.stringifyAny, - ) |> toBeJson({"gridTemplateColumns": "1fr 100px auto"}) + )->toBeJson({"gridTemplateColumns": "1fr 100px auto"}) ) test("unfolds repeats", () => @@ -524,7 +524,7 @@ describe("gridTemplateCoumns", () => { r(gridTemplateColumns(list{#repeat(#num(4), #minmax(#px(100), #fr(1.)))})), // r(gridTemplateColumns([`repeat(`num(4), `fitContent(`px(200)))])), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"gridTemplateColumns": "repeat(4, 1fr)"}, {"gridTemplateColumns": "repeat(4, auto)"}, {"gridTemplateColumns": "repeat(4, min-content)"}, @@ -549,7 +549,7 @@ describe("backgroundPosition", () => { r(backgroundPosition(inherit_)), r(backgroundPosition(unset)), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"backgroundPosition": "left"}, {"backgroundPosition": "right"}, {"backgroundPosition": "top"}, @@ -570,7 +570,7 @@ describe("backgroundPosition", () => { r(backgroundPosition(#hv(pct(50.), #top))), r(backgroundPosition(#hv(pct(50.), pct(50.)))), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"backgroundPosition": "left center"}, {"backgroundPosition": "right 50%"}, {"backgroundPosition": "50% top"}, @@ -581,7 +581,7 @@ describe("backgroundPosition", () => { test("test multiple positions", () => expect( r(backgroundPositions(list{#hv(px(0), px(0)), center}))->Js.Json.stringifyAny, - ) |> toBeJson({"backgroundPosition": "0px 0px, center"}) + )->toBeJson({"backgroundPosition": "0px 0px, center"}) ) test("test edge offsets values", () => @@ -589,7 +589,7 @@ describe("backgroundPosition", () => { r( backgroundPosition4(~y=#top, ~offsetY=px(10), ~x=#right, ~offsetX=px(50)), )->Js.Json.stringifyAny, - ) |> toBeJson({"backgroundPosition": "right 50px top 10px"}) + )->toBeJson({"backgroundPosition": "right 50px top 10px"}) ) }) @@ -605,7 +605,7 @@ describe("backgroundRepeat", () => { r(backgroundRepeat(noRepeat)), r(backgroundRepeat(inherit_)), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"backgroundRepeat": "repeat-x"}, {"backgroundRepeat": "repeat-y"}, {"backgroundRepeat": "repeat"}, @@ -624,7 +624,7 @@ describe("backgroundRepeat", () => { r(backgroundRepeat(#hv(round, space))), r(backgroundRepeat(#hv(noRepeat, round))), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"backgroundRepeat": "repeat space"}, {"backgroundRepeat": "repeat repeat"}, {"backgroundRepeat": "round space"}, @@ -644,7 +644,7 @@ describe("backgroundImage", () => r(backgroundImage(radialGradient(list{(pct(30.), yellow)}))), r(backgroundImage(repeatingRadialGradient(list{(pct(30.), yellow)}))), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"backgroundImage": "none"}, {"backgroundImage": "url(x)"}, {"backgroundImage": "linear-gradient(5deg, #FF0000 10%)"}, @@ -664,7 +664,7 @@ describe("background shorhand", () => r(background(linearGradient(deg(5.), list{(pct(10.), red)}))), r(background(none)), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"background": "rgb(1, 2, 3)"}, {"background": "url(x)"}, {"background": "linear-gradient(5deg, #FF0000 10%)"}, @@ -690,7 +690,7 @@ describe("clipPath", () => r(clipPath(initial)), r(clipPath(unset)), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"clipPath": "none"}, {"clipPath": "url(x)"}, {"clipPath": "margin-box"}, @@ -719,7 +719,7 @@ describe("columnGap", () => r(columnGap(initial)), r(columnGap(unset)), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"columnGap": "normal"}, {"columnGap": "3px"}, {"columnGap": "2.5em"}, @@ -772,7 +772,7 @@ describe("cursor", () => r(cursor(zoomIn)), r(cursor(zoomOut)), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"cursor": "context-menu"}, {"cursor": "help"}, {"cursor": "pointer"}, diff --git a/tests/syntax_tests/data/idempotency/bs-css/Selectors_test.res b/tests/syntax_tests/data/idempotency/bs-css/Selectors_test.res index 0c02b630b6..ba74f6fa0a 100644 --- a/tests/syntax_tests/data/idempotency/bs-css/Selectors_test.res +++ b/tests/syntax_tests/data/idempotency/bs-css/Selectors_test.res @@ -56,7 +56,7 @@ describe("Pseudo classes", () => { r(valid(list{ruleSelector})), r(visited(list{ruleSelector})), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {":active": ruleJson}, {":checked": ruleJson}, {":default": ruleJson}, @@ -97,11 +97,11 @@ describe("Pseudo classes", () => { r(host(list{ruleSelector})), r(host(~selector=".special-custom-element", list{ruleSelector})), )->Js.Json.stringifyAny, - ) |> toBeJson(({":host": ruleJson}, {":host(.special-custom-element)": ruleJson})) + )->toBeJson(({":host": ruleJson}, {":host(.special-custom-element)": ruleJson})) ) test("test not", () => - expect(r(not__("p", list{ruleSelector}))->Js.Json.stringifyAny) |> toBeJson({ + expect(r(not__("p", list{ruleSelector}))->Js.Json.stringifyAny)->toBeJson({ ":not(p)": ruleJson, }) ) @@ -114,7 +114,7 @@ describe("Pseudo classes", () => { r(nthChild(#n(2), list{ruleSelector})), r(nthChild(#add(3, 4), list{ruleSelector})), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {":nth-child(odd)": ruleJson}, {":nth-child(even)": ruleJson}, {":nth-child(2n)": ruleJson}, @@ -130,7 +130,7 @@ describe("Pseudo classes", () => { r(nthLastChild(#n(2), list{ruleSelector})), r(nthLastChild(#add(3, 4), list{ruleSelector})), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {":nth-last-child(odd)": ruleJson}, {":nth-last-child(even)": ruleJson}, {":nth-last-child(2n)": ruleJson}, @@ -146,7 +146,7 @@ describe("Pseudo classes", () => { r(nthLastOfType(#n(2), list{ruleSelector})), r(nthLastOfType(#add(3, 4), list{ruleSelector})), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {":nth-last-of-type(odd)": ruleJson}, {":nth-last-of-type(even)": ruleJson}, {":nth-last-of-type(2n)": ruleJson}, @@ -162,7 +162,7 @@ describe("Pseudo classes", () => { r(nthOfType(#n(2), list{ruleSelector})), r(nthOfType(#add(3, 4), list{ruleSelector})), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {":nth-of-type(odd)": ruleJson}, {":nth-of-type(even)": ruleJson}, {":nth-of-type(2n)": ruleJson}, @@ -182,7 +182,7 @@ describe("Pseudo classes", () => r(placeholder(list{ruleSelector})), r(selection(list{ruleSelector})), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"::after": ruleJson}, {"::before": ruleJson}, {"::first-letter": ruleJson}, @@ -202,6 +202,6 @@ describe("Combinators", () => r(siblings(list{ruleSelector})), r(directSibling(list{ruleSelector})), )->Js.Json.stringifyAny, - ) |> toBeJson(({" > li": ruleJson}, {" > *": ruleJson}, {" ~ ": ruleJson}, {" + ": ruleJson})) + )->toBeJson(({" > li": ruleJson}, {" > *": ruleJson}, {" ~ ": ruleJson}, {" + ": ruleJson})) ) ) diff --git a/tests/syntax_tests/data/idempotency/bs-css/Svg_test.res b/tests/syntax_tests/data/idempotency/bs-css/Svg_test.res index bf8288a62d..6a199948eb 100644 --- a/tests/syntax_tests/data/idempotency/bs-css/Svg_test.res +++ b/tests/syntax_tests/data/idempotency/bs-css/Svg_test.res @@ -28,7 +28,7 @@ describe("Fill", () => r(SVG.fill(#contextStroke)), r(SVG.fill(#none)), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"fill": "#FF0044"}, {"fill": "url(#mydef)"}, {"fill": "context-fill"}, @@ -48,7 +48,7 @@ describe("strokeDasharray", () => r(SVG.strokeDasharray(#dasharray(list{1.->pct, 2->px, 3.->pct, 4->px}))), r(SVG.strokeDasharray(#none)), )->Js.Json.stringifyAny, - ) |> toBeJson(( + )->toBeJson(( {"stroke-dasharray": "1px 2px 3px 4px"}, {"stroke-dasharray": "1% 2% 3% 4%"}, {"stroke-dasharray": "1px 2% 3px 4%"}, diff --git a/tests/syntax_tests/data/idempotency/bs-css/Test.res b/tests/syntax_tests/data/idempotency/bs-css/Test.res index e17dd2f241..327b33aa8c 100644 --- a/tests/syntax_tests/data/idempotency/bs-css/Test.res +++ b/tests/syntax_tests/data/idempotency/bs-css/Test.res @@ -66,7 +66,7 @@ let differentHeightLengths = { vmax(1.0), vmin(1.0), zero, - ] |> Array.map(x => { + ]->Array.map(x => { let className = style(\"@"(redBox, list{height(x)}))
}) @@ -2026,28 +2026,28 @@ let make = () => open Css style(redBox) }> - {"1" |> text} + {"1"->text}
- {"2" |> text} + {"2"->text}
- {"3" |> text} + {"3"->text}
- {"4" |> text} + {"4"->text}
@@ -2062,28 +2062,28 @@ let make = () => open Css style(redBox) }> - {"1" |> text} + {"1"->text}
- {"2" |> text} + {"2"->text}
- {"3" |> text} + {"3"->text}
- {"4" |> text} + {"4"->text}
@@ -2098,28 +2098,28 @@ let make = () => open Css style(redBox) }> - {"1" |> text} + {"1"->text}
- {"2" |> text} + {"2"->text}
- {"3" |> text} + {"3"->text}
- {"4" |> text} + {"4"->text}
diff --git a/tests/syntax_tests/data/idempotency/bs-fetch/reason_examples.res b/tests/syntax_tests/data/idempotency/bs-fetch/reason_examples.res index a69da21679..ebce2dfac6 100644 --- a/tests/syntax_tests/data/idempotency/bs-fetch/reason_examples.res +++ b/tests/syntax_tests/data/idempotency/bs-fetch/reason_examples.res @@ -1,26 +1,26 @@ let _ = { open Js.Promise Fetch.fetch("/api/hellos/1") - |> then_(Fetch.Response.text) - |> then_(text => print_endline(text) |> resolve) + ->then_(Fetch.Response.text) + ->then_(text => print_endline(text)->resolve) } let _ = { open Js.Promise Fetch.fetchWithInit("/api/hello", Fetch.RequestInit.make(~method_=Post, ())) - |> then_(Fetch.Response.text) - |> then_(text => print_endline(text) |> resolve) + ->then_(Fetch.Response.text) + ->then_(text => print_endline(text)->resolve) } let _ = { open Js.Promise Fetch.fetch("/api/fruit") /* assume server returns `["apple", "banana", "pear", ...]` */ - |> then_(Fetch.Response.json) - |> then_(json => Js.Json.decodeArray(json) |> resolve) - |> then_(opt => Belt.Option.getExn(opt) |> resolve) - |> then_(items => - items |> Js.Array.map(item => item |> Js.Json.decodeString |> Belt.Option.getExn) |> resolve + ->then_(Fetch.Response.json) + ->then_(json => Js.Json.decodeArray(json)->resolve) + ->then_(opt => Belt.Option.getExn(opt)->resolve) + ->then_(items => + items->Js.Array.map(item => item->Js.Json.decodeString->Belt.Option.getExn)->resolve ) } @@ -37,5 +37,5 @@ let _ = { ~headers=Fetch.HeadersInit.make({"Content-Type": "application/json"}), (), ), - ) |> then_(Fetch.Response.json) + )->then_(Fetch.Response.json) } diff --git a/tests/syntax_tests/data/idempotency/bs-webapi/src/Webapi/Webapi__Canvas/Webapi__Canvas__Canvas2d.res b/tests/syntax_tests/data/idempotency/bs-webapi/src/Webapi/Webapi__Canvas/Webapi__Canvas__Canvas2d.res index 305e03d06c..22f3fd3181 100644 --- a/tests/syntax_tests/data/idempotency/bs-webapi/src/Webapi/Webapi__Canvas/Webapi__Canvas__Canvas2d.res +++ b/tests/syntax_tests/data/idempotency/bs-webapi/src/Webapi/Webapi__Canvas/Webapi__Canvas__Canvas2d.res @@ -141,9 +141,9 @@ let reifyStyle = (type a, x: 'a): (style, a) => { @get external fillStyle: t => 'a = "" @get external strokeStyle: t => 'a = "" -let fillStyle = (ctx: t) => ctx |> fillStyle |> reifyStyle +let fillStyle = (ctx: t) => ctx->fillStyle->reifyStyle -let strokeStyle = (ctx: t) => ctx |> strokeStyle |> reifyStyle +let strokeStyle = (ctx: t) => ctx->strokeStyle->reifyStyle @set external shadowOffsetX: (t, float) => unit = "" @set external shadowOffsetY: (t, float) => unit = "" diff --git a/tests/syntax_tests/data/idempotency/bs-webapi/src/Webapi/Webapi__Dom/Webapi__Dom__HtmlInputElement.res b/tests/syntax_tests/data/idempotency/bs-webapi/src/Webapi/Webapi__Dom/Webapi__Dom__HtmlInputElement.res index 896fd20e99..62c73157be 100644 --- a/tests/syntax_tests/data/idempotency/bs-webapi/src/Webapi/Webapi__Dom/Webapi__Dom__HtmlInputElement.res +++ b/tests/syntax_tests/data/idempotency/bs-webapi/src/Webapi/Webapi__Dom/Webapi__Dom__HtmlInputElement.res @@ -127,10 +127,10 @@ module Impl = ( selectionDirection, element, ) => - element |> setSelectionRangeWithDirection_( + element->setSelectionRangeWithDirection_( selectionStart, selectionEnd, - selectionDirection |> SelectionDirection.toString, + selectionDirection->SelectionDirection.toString, ) module SelectionMode = { @@ -156,11 +156,11 @@ module Impl = ( selectionMode, element, ) => - element |> setRangeTextWithinIntervalWithSelectionMode_( + element->setRangeTextWithinIntervalWithSelectionMode_( text, selectionStart, selectionEnd, - selectionMode |> SelectionMode.toString, + selectionMode->SelectionMode.toString, ) } diff --git a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Canvas/Webapi__Canvas__Canvas2d__test.res b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Canvas/Webapi__Canvas__Canvas2d__test.res index 21b28b37c7..58fbaa2c14 100644 --- a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Canvas/Webapi__Canvas__Canvas2d__test.res +++ b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Canvas/Webapi__Canvas__Canvas2d__test.res @@ -5,13 +5,13 @@ open Webapi.Dom let canvasEl = Document.createElement("canvas", document) let ctx = CanvasElement.getContext2d(canvasEl) -ctx |> save -ctx |> restore +ctx->save +ctx->restore -ctx |> scale(~x=1., ~y=2.) -ctx |> rotate(2.) -ctx |> translate(~x=2., ~y=3.) -ctx |> transform(~m11=1., ~m12=2., ~m21=1., ~m22=1., ~dx=1., ~dy=1.) +ctx->scale(~x=1., ~y=2.) +ctx->rotate(2.) +ctx->translate(~x=2., ~y=3.) +ctx->transform(~m11=1., ~m12=2., ~m21=1., ~m22=1., ~dx=1., ~dy=1.) globalAlpha(ctx, 0.9) globalCompositeOperation(ctx, Composite.sourceOver) @@ -25,13 +25,13 @@ setStrokeStyle(ctx, String, "red") setFillStyle(ctx, String, "red") switch fillStyle(ctx) { -| (Gradient, g) => g |> addColorStop(0.0, "red") +| (Gradient, g) => g->addColorStop(0.0, "red") | (String, s) => Js.log(s) | _ => () } switch strokeStyle(ctx) { -| (Gradient, g) => g |> addColorStop(1.2, "blue") +| (Gradient, g) => g->addColorStop(1.2, "blue") | (String, s) => Js.log(s) | _ => () } @@ -41,33 +41,33 @@ shadowOffsetY(ctx, 1.) shadowBlur(ctx, 1.) shadowColor(ctx, "red") -ctx |> beginPath -ctx |> closePath -ctx |> fill -ctx |> stroke -ctx |> clip -ctx |> moveTo(~x=1., ~y=1.) -ctx |> lineTo(~x=1., ~y=2.) -ctx |> quadraticCurveTo(~cp1x=1., ~cp1y=1., ~x=1., ~y=1.) -ctx |> bezierCurveTo(~cp1x=1., ~cp1y=1., ~cp2x=2., ~cp2y=2., ~x=4., ~y=4.) -ctx |> arcTo(~x1=1., ~y1=1., ~x2=2., ~y2=2., ~r=4.) -ctx |> arc(~x=1., ~y=1., ~r=4., ~startAngle=1., ~endAngle=3., ~anticw=true) -ctx |> rect(~x=0., ~y=0., ~w=10., ~h=10.) -let _ = ctx |> isPointInPath(~x=0., ~y=0.) +ctx->beginPath +ctx->closePath +ctx->fill +ctx->stroke +ctx->clip +ctx->moveTo(~x=1., ~y=1.) +ctx->lineTo(~x=1., ~y=2.) +ctx->quadraticCurveTo(~cp1x=1., ~cp1y=1., ~x=1., ~y=1.) +ctx->bezierCurveTo(~cp1x=1., ~cp1y=1., ~cp2x=2., ~cp2y=2., ~x=4., ~y=4.) +ctx->arcTo(~x1=1., ~y1=1., ~x2=2., ~y2=2., ~r=4.) +ctx->arc(~x=1., ~y=1., ~r=4., ~startAngle=1., ~endAngle=3., ~anticw=true) +ctx->rect(~x=0., ~y=0., ~w=10., ~h=10.) +let _ = ctx->isPointInPath(~x=0., ~y=0.) -let linearGradient = ctx |> createLinearGradient(~x0=0.0, ~y0=0.0, ~x1=0.0, ~y1=0.0) +let linearGradient = ctx->createLinearGradient(~x0=0.0, ~y0=0.0, ~x1=0.0, ~y1=0.0) setStrokeStyle(ctx, Gradient, linearGradient) -let _ = ctx |> createRadialGradient(~x0=0.0, ~y0=0.0, ~x1=0.0, ~y1=0.0, ~r0=0.0, ~r1=0.0) -linearGradient |> addColorStop(0.0, "red") +let _ = ctx->createRadialGradient(~x0=0.0, ~y0=0.0, ~x1=0.0, ~y1=0.0, ~r0=0.0, ~r1=0.0) +linearGradient->addColorStop(0.0, "red") let _ = List.map( createPattern(ctx, Document.createElement("img", document)), list{#noRepeat, #repeat, #repeatX, #repeatY}, ) -let measureText = ctx |> measureText("foo") +let measureText = ctx->measureText("foo") let width = width(measureText) -ctx |> fillText("foo!", ~x=0.0, ~y=0.0, ~maxWidth=width) -ctx |> strokeText("foo!", ~x=0.0, ~y=0.0, ~maxWidth=width) +ctx->fillText("foo!", ~x=0.0, ~y=0.0, ~maxWidth=width) +ctx->strokeText("foo!", ~x=0.0, ~y=0.0, ~maxWidth=width) let imageData = createImageDataCoords(ctx, ~width=0.0, ~height=0.0) createImageDataFromImage(ctx, imageData) Image.width(imageData) @@ -90,9 +90,9 @@ let _: unit = putImageData( font(ctx, "10px Courier") textAlign(ctx, "left") textBaseline(ctx, "top") -ctx |> fillText("hi", ~x=1., ~y=0.) -ctx |> strokeText("hi", ~x=1., ~y=0.) +ctx->fillText("hi", ~x=1., ~y=0.) +ctx->strokeText("hi", ~x=1., ~y=0.) -ctx |> fillRect(~x=1., ~y=0., ~w=10., ~h=10.) -ctx |> strokeRect(~x=1., ~y=0., ~w=10., ~h=10.) -ctx |> clearRect(~x=1., ~y=0., ~w=10., ~h=10.) +ctx->fillRect(~x=1., ~y=0., ~w=10., ~h=10.) +ctx->strokeRect(~x=1., ~y=0., ~w=10., ~h=10.) +ctx->clearRect(~x=1., ~y=0., ~w=10., ~h=10.) diff --git a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Document__test.res b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Document__test.res index 4a734f9ef0..476e915600 100644 --- a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Document__test.res +++ b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Document__test.res @@ -1,7 +1,7 @@ open Webapi.Dom open Document -let el = document |> createElement("strong") +let el = document->createElement("strong") let _ = characterSet(document) let _ = compatMode(document) diff --git a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__DomStringMap__test.res b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__DomStringMap__test.res index 26218b26a9..aa2dd721b6 100644 --- a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__DomStringMap__test.res +++ b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__DomStringMap__test.res @@ -2,7 +2,7 @@ open Webapi.Dom open Webapi.Dom.DomStringMap let dataset = - document |> Document.createElement("div") |> Element.unsafeAsHtmlElement |> HtmlElement.dataset + document->Document.createElement("div")->Element.unsafeAsHtmlElement->HtmlElement.dataset let () = set("fooKey", "barValue", dataset) let _ = get("fooKey", dataset) diff --git a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__DomTokenList__test.res b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__DomTokenList__test.res index 18f98f1118..8ea5d7061b 100644 --- a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__DomTokenList__test.res +++ b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__DomTokenList__test.res @@ -1,7 +1,7 @@ open Webapi.Dom open DomTokenList -let tlist = document |> Document.createElement("div") |> Element.classList +let tlist = document->Document.createElement("div")->Element.classList let _ = length(tlist) let _ = item(3, tlist) diff --git a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Element__test.res b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Element__test.res index f800478184..05386e550b 100644 --- a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Element__test.res +++ b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Element__test.res @@ -1,8 +1,8 @@ open Webapi.Dom open Element -let el = document |> Document.createElement("strong") -let el2 = document |> Document.createElement("small") +let el = document->Document.createElement("strong") +let el2 = document->Document.createElement("small") let event = PointerEvent.make("my-event") let _ = assignedSlot(el) diff --git a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__EventTarget__test.res b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__EventTarget__test.res index 1ff84dcd8f..cb77e8dd83 100644 --- a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__EventTarget__test.res +++ b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__EventTarget__test.res @@ -1,7 +1,7 @@ open Webapi.Dom open EventTarget -let target = document |> Document.createElement("strong") |> Element.asEventTarget +let target = document->Document.createElement("strong")->Element.asEventTarget let event = Event.make("my-event") let handleClick = _ => print_endline("asd") diff --git a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__GlobalEventHandlers__test.res b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__GlobalEventHandlers__test.res index 7959ff264d..ecfe850ea5 100644 --- a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__GlobalEventHandlers__test.res +++ b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__GlobalEventHandlers__test.res @@ -2,7 +2,7 @@ open Webapi.Dom let handleSelection = _ => print_endline("change") -let elm = document |> Document.createElement("strong") +let elm = document->Document.createElement("strong") Element.addSelectionChangeEventListenerWithOptions( handleSelection, @@ -20,9 +20,9 @@ Element.removeSelectionChangeEventListenerUseCapture(handleSelection, elm) let htmlElm = document - |> Document.createElement("strong") - |> HtmlElement.ofElement - |> TestHelpers.unsafelyUnwrapOption + ->Document.createElement("strong") + ->HtmlElement.ofElement + ->TestHelpers.unsafelyUnwrapOption HtmlElement.addSelectionChangeEventListenerWithOptions( handleSelection, @@ -38,7 +38,7 @@ HtmlElement.removeSelectionChangeEventListenerWithOptions( ) HtmlElement.removeSelectionChangeEventListenerUseCapture(handleSelection, htmlElm) -let htmlDoc = document |> Document.asHtmlDocument |> TestHelpers.unsafelyUnwrapOption +let htmlDoc = document->Document.asHtmlDocument->TestHelpers.unsafelyUnwrapOption HtmlDocument.addSelectionChangeEventListenerWithOptions( handleSelection, diff --git a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__HtmlDocument__test.res b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__HtmlDocument__test.res index fafe584897..8a1ffb7897 100644 --- a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__HtmlDocument__test.res +++ b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__HtmlDocument__test.res @@ -1,8 +1,8 @@ open Webapi.Dom open! HtmlDocument -let el = document |> Document.createElement("strong") -let htmlDocument = document |> Document.asHtmlDocument |> TestHelpers.unsafelyUnwrapOption +let el = document->Document.createElement("strong") +let htmlDocument = document->Document.asHtmlDocument->TestHelpers.unsafelyUnwrapOption let _ = activeElement(htmlDocument) let _ = body(htmlDocument) diff --git a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__HtmlElement__test.res b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__HtmlElement__test.res index 711702813e..54ba2f5fa5 100644 --- a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__HtmlElement__test.res +++ b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__HtmlElement__test.res @@ -3,15 +3,15 @@ open HtmlElement let el = document - |> Document.createElement("strong") - |> Element.asHtmlElement - |> TestHelpers.unsafelyUnwrapOption + ->Document.createElement("strong") + ->Element.asHtmlElement + ->TestHelpers.unsafelyUnwrapOption let el2 = document - |> Document.createElement("small") - |> Element.asHtmlElement - |> TestHelpers.unsafelyUnwrapOption -let event = document |> Document.createEvent("my-event") + ->Document.createElement("small") + ->Element.asHtmlElement + ->TestHelpers.unsafelyUnwrapOption +let event = document->Document.createEvent("my-event") let _ = accessKey(el) let _ = setAccessKey(el, "") diff --git a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__NodeList__test.res b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__NodeList__test.res index d7768eeff5..a29c18369a 100644 --- a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__NodeList__test.res +++ b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__NodeList__test.res @@ -1,6 +1,6 @@ open Webapi.Dom open NodeList -let items = document |> Document.querySelectorAll(".item") +let items = document->Document.querySelectorAll(".item") forEach((item, _) => Js.log(item), items) diff --git a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Node__test.res b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Node__test.res index 77cc939d56..d2f13a0a57 100644 --- a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Node__test.res +++ b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Node__test.res @@ -1,9 +1,9 @@ open Webapi.Dom open Node -let node = document |> Document.createElement("strong") |> Element.rootNode -let node2 = document |> Document.createElement("small") |> Element.rootNode -let node3 = document |> Document.createElement("small") |> Element.rootNode +let node = document->Document.createElement("strong")->Element.rootNode +let node2 = document->Document.createElement("small")->Element.rootNode +let node3 = document->Document.createElement("small")->Element.rootNode let _ = childNodes(node) let _ = firstChild(node) diff --git a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Range__test.res b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Range__test.res index a5bffa7032..d75f2b4999 100644 --- a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Range__test.res +++ b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Range__test.res @@ -1,7 +1,7 @@ open Webapi.Dom open Range -let node = document |> Document.createElement("strong") +let node = document->Document.createElement("strong") let range = make() diff --git a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Selection__test.res b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Selection__test.res index 662205bd15..8d91607f17 100644 --- a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Selection__test.res +++ b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Selection__test.res @@ -1,12 +1,12 @@ open Webapi.Dom open Selection -let node = document |> Document.createElement("strong") +let node = document->Document.createElement("strong") let sel = document - |> Document.asHtmlDocument - |> TestHelpers.unsafelyUnwrapOption - |> HtmlDocument.getSelection + ->Document.asHtmlDocument + ->TestHelpers.unsafelyUnwrapOption + ->HtmlDocument.getSelection let range = Range.make() diff --git a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Text__test.res b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Text__test.res index 6d891633b9..1c92d2986f 100644 --- a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Text__test.res +++ b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Text__test.res @@ -1,5 +1,5 @@ open Webapi.Dom -let node = document |> Document.createTextNode("text") |> Text.asNode +let node = document->Document.createTextNode("text")->Text.asNode let text = Text.ofNode(node) diff --git a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Window__test.res b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Window__test.res index 7f793cb63c..313fc9475c 100644 --- a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Window__test.res +++ b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Dom/Webapi__Dom__Window__test.res @@ -1,7 +1,7 @@ open Webapi.Dom -let el = document |> Document.createElement("strong") -let event = document |> Document.createEvent("my-event") +let el = document->Document.createElement("strong") +let event = document->Document.createEvent("my-event") let handleClick = _ => print_endline("asd") let _ = Window.console(window) diff --git a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Performace__test.res b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Performace__test.res index b55d0f0964..102d690b34 100644 --- a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Performace__test.res +++ b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__Performace__test.res @@ -1 +1 @@ -let _ = Webapi.Dom.window |> Webapi.Dom.Window.performance |> Webapi.Performance.now +let _ = Webapi.Dom.window->Webapi.Dom.Window.performance->Webapi.Performance.now diff --git a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__ResizeObserver__test.res b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__ResizeObserver__test.res index 9e8af1ec16..6bc70e5c51 100644 --- a/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__ResizeObserver__test.res +++ b/tests/syntax_tests/data/idempotency/bs-webapi/tests/Webapi/Webapi__ResizeObserver__test.res @@ -1,4 +1,4 @@ -let el = Webapi.Dom.document |> Webapi.Dom.Document.createElement("strong") +let el = Webapi.Dom.document->Webapi.Dom.Document.createElement("strong") let handler = entries => { let entry = entries[0] diff --git a/tests/syntax_tests/data/idempotency/covid-19charts.com/data-processor/data_processor.res b/tests/syntax_tests/data/idempotency/covid-19charts.com/data-processor/data_processor.res index db3b34e709..61a53677a0 100644 --- a/tests/syntax_tests/data/idempotency/covid-19charts.com/data-processor/data_processor.res +++ b/tests/syntax_tests/data/idempotency/covid-19charts.com/data-processor/data_processor.res @@ -12,7 +12,7 @@ let createId = (country, provinceOrState) => module StringSet = Set.Make(String) -let locationRows = Csv.sub(~r=1, ~c=0, ~cols=2, ~rows=Csv.lines(csv) - 1, csv) |> Csv.to_array +let locationRows = Csv.sub(~r=1, ~c=0, ~cols=2, ~rows=Csv.lines(csv) - 1, csv)->Csv.to_array let duplicateCountries = Array.fold_left(((countries, duplicateCountries), x) => switch x { | [provinceOrState, country] => @@ -23,17 +23,17 @@ let duplicateCountries = Array.fold_left(((countries, duplicateCountries), x) => } | _ => invalid_arg("Unknown format") } -, (StringSet.empty, StringSet.empty), locationRows) |> snd +, (StringSet.empty, StringSet.empty), locationRows)->snd let locations = \"@"( duplicateCountries - |> StringSet.elements - |> List.map(country => { + ->StringSet.elements + ->List.map(country => { let id = country ++ " (All regions)" (id, #Assoc(list{("country", #String(country)), ("name", #String(id))})) }), locationRows - |> Array.map(x => + ->Array.map(x => switch x { | [provinceOrState, country] if String.length(provinceOrState) === 0 => let id = createId(country, provinceOrState) @@ -51,25 +51,25 @@ let locations = \"@"( | _ => invalid_arg("Unknown format") } ) - |> Array.to_list, + ->Array.to_list, ) Yojson.Basic.to_file(Sys.argv[3], #Assoc(locations)) let days = ( - Csv.sub(~r=0, ~c=4, ~cols=Csv.columns(csv) - 4, ~rows=1, csv) |> Csv.to_array - )[0] |> Array.map(x => #String(x)) + Csv.sub(~r=0, ~c=4, ~cols=Csv.columns(csv) - 4, ~rows=1, csv)->Csv.to_array + )[0]->Array.map(x => #String(x)) -Yojson.Basic.to_file(Sys.argv[4], #List(days |> Array.to_list)) +Yojson.Basic.to_file(Sys.argv[4], #List(days->Array.to_list)) module LocationMap = Map.Make(String) module DayMap = LocationMap -let casesListToMap = list => list |> List.fold_left((countryMap, row) => +let casesListToMap = list => list->List.fold_left((countryMap, row) => switch Csv.Row.to_assoc(row) { | list{("Province/State", provinceOrState), ("Country/Region", country), _lat, _lon, ...rest} => - let currentCountryMap = LocationMap.find_opt(country, countryMap) |> ( + let currentCountryMap = LocationMap.find_opt(country, countryMap)->( x => switch x { | Some(x) => x @@ -81,7 +81,7 @@ let casesListToMap = list => list |> List.fold_left((countryMap, row) => LocationMap.add( provinceOrState, List.fold_left( - (days, (key, value)) => DayMap.add(key, value |> int_of_string, days), + (days, (key, value)) => DayMap.add(key, value->int_of_string, days), DayMap.empty, rest, ), @@ -105,8 +105,8 @@ let getWithDefault = (default, x) => } let data = { - let confirmed = Csv.Rows.load(~has_header=true, pathToConfirmedDataCsv) |> casesListToMap - let deaths = Csv.Rows.load(~has_header=true, pathToDeathsDataCsv) |> casesListToMap + let confirmed = Csv.Rows.load(~has_header=true, pathToConfirmedDataCsv)->casesListToMap + let deaths = Csv.Rows.load(~has_header=true, pathToDeathsDataCsv)->casesListToMap let merged = LocationMap.merge((countryId, confirmed, deaths) => { let confirmed = getWithDefault(LocationMap.empty, confirmed) @@ -140,7 +140,7 @@ let data = { let id = countryId ++ " (All regions)" LocationMap.add(id, days, countries) - }, LocationMap.empty, duplicateCountries |> StringSet.elements) + }, LocationMap.empty, duplicateCountries->StringSet.elements) } LocationMap.fold( @@ -154,13 +154,13 @@ let data = { merged, allRegionsPerCountry, ) - |> LocationMap.bindings - |> List.map(((locationId, dayMap)) => ( + ->LocationMap.bindings + ->List.map(((locationId, dayMap)) => ( locationId, #Assoc( dayMap - |> DayMap.bindings - |> List.map(((day, {confirmed, deaths})) => ( + ->DayMap.bindings + ->List.map(((day, {confirmed, deaths})) => ( day, #Assoc(list{("confirmed", #Int(confirmed)), ("deaths", #Int(deaths))}), )), diff --git a/tests/syntax_tests/data/idempotency/covid-19charts.com/src/Chart.res b/tests/syntax_tests/data/idempotency/covid-19charts.com/src/Chart.res index cf4779aa0a..6220cbc48f 100644 --- a/tests/syntax_tests/data/idempotency/covid-19charts.com/src/Chart.res +++ b/tests/syntax_tests/data/idempotency/covid-19charts.com/src/Chart.res @@ -14,8 +14,8 @@ let calculateMaxValue = (dataType, locations, data) => Js.Array.reduce( (maxValue, location) => values(location.Location.id) - |> Js.Option.map((. value) => Js.Math.max_int(maxValue, Data.getValue(dataType, value))) - |> Js.Option.getWithDefault(maxValue), + ->Js.Option.map((. value) => Js.Math.max_int(maxValue, Data.getValue(dataType, value))) + ->Js.Option.getWithDefault(maxValue), maxValue, locations, ), @@ -40,8 +40,8 @@ let ordinalSuffix = i => { let renderTooltipValues = (~chartType, ~payload, ~separator) => payload - |> Js.Array.filter(payload => payload.R.Tooltip.name !== "daily-growth-indicator") - |> Js.Array.map(payload => { + ->Js.Array.filter(payload => payload.R.Tooltip.name !== "daily-growth-indicator") + ->Js.Array.map(payload => { let currentDataItem = (payload: R.Tooltip.payload).payload.Data.values(payload.R.Tooltip.name) @@ -52,32 +52,32 @@ let renderTooltipValues = (~chartType, ~payload, ~separator) => | Filters.Number(dataType) => let growthString = currentDataItem - |> Js.Option.map((. dataItem) => - " (+" ++ ((Data.getGrowth(dataType, dataItem) *. 100. |> Js.Float.toFixed) ++ "%)") + ->Js.Option.map((. dataItem) => + " (+" ++ ((Data.getGrowth(dataType, dataItem) *. 100.->Js.Float.toFixed) ++ "%)") ) - |> Js.Option.getWithDefault("") + ->Js.Option.getWithDefault("") (separator ++ Js.Int.toString(R.Line.toInt(payload.value)), growthString) | Filters.PercentageGrowthOfCases => let growthString = currentDataItem - |> Js.Option.map((. dataItem) => - " (+" ++ ((Data.getDailyNewCases(dataItem).confirmed |> Js.Int.toString) ++ ")") + ->Js.Option.map((. dataItem) => + " (+" ++ ((Data.getDailyNewCases(dataItem).confirmed->Js.Int.toString) ++ ")") ) - |> Js.Option.getWithDefault("") + ->Js.Option.getWithDefault("") ( separator ++ ("+" ++ - ((R.Line.toFloat(payload.value) *. 100. |> Js.Float.toFixed) ++ "%")), + ((R.Line.toFloat(payload.value) *. 100.->Js.Float.toFixed) ++ "%")), growthString, ) | Filters.TotalMortalityRate => let growthString = currentDataItem - |> Js.Option.map((. dataItem) => { + ->Js.Option.map((. dataItem) => { let {Data.confirmed: confirmed, deaths} = Data.getRecord(dataItem) " (" ++ (Js.Int.toString(deaths) ++ ("/" ++ Js.Int.toString(confirmed)) ++ ")") }) - |> Js.Option.getWithDefault("") + ->Js.Option.getWithDefault("") ( separator ++ (Js.Float.toFixedWithPrecision(R.Line.toFloat(payload.value) *. 100., ~digits=2) ++ @@ -92,7 +92,7 @@ let renderTooltipValues = (~chartType, ~payload, ~separator) => } }) - |> React.array + ->React.array @react.component let make = ( @@ -133,7 +133,7 @@ let make = ( let exponent = { let threshold = Js.Int.toFloat(threshold) let maxValue = calculateMaxValue(Data.Confirmed, locations, data) - log((maxValue |> Belt.Int.toFloat) /. threshold) /. log(dailyGrowth) |> Js.Math.ceil + log((maxValue->Belt.Int.toFloat) /. threshold) /. log(dailyGrowth)->Js.Math.ceil } Belt.Int.toFloat) - |> int_of_float - |> R.Line.int, + Js.Math.pow_float(~base=dailyGrowth, ~exp=item.Data.index->Belt.Int.toFloat) + ->int_of_float + ->R.Line.int, ) } else { Js.null @@ -162,7 +162,7 @@ let make = ( let divRef = React.useRef(Js.Nullable.null) let (dot, setDot) = React.useState(() => true) React.useEffect1(() => { - let opt = divRef |> React.Ref.current |> Js.Nullable.toOption + let opt = divRef->React.Ref.current->Js.Nullable.toOption switch opt { | Some(ref) => setDot(_ => clientHeight(ref) > 500.) | None => () @@ -223,7 +223,7 @@ let make = ( "stroke": primaryColor, })} /> - , locations) |> Js.Array.reverseInPlace |> React.array} + , locations)->Js.Array.reverseInPlace->React.array} switch Js.Null.toOption(payload) { @@ -267,13 +267,13 @@ let make = ( | (Filters.Number(_), Filters.Logarithmic) => #log | _ => #linear }} - domain=("dataMin" |> R.YAxis.string, "dataMax" |> R.YAxis.string) + domain=("dataMin"->R.YAxis.string, "dataMax"->R.YAxis.string) tickFormatter={x => switch chartType { | Filters.Number(_) => Js.Int.toString(R.Line.toInt(x)) | Filters.TotalMortalityRate | Filters.PercentageGrowthOfCases => - (R.Line.toFloat(x) *. 100. |> Js.Float.toFixed) ++ "%" + (R.Line.toFloat(x) *. 100.->Js.Float.toFixed) ++ "%" }} /> diff --git a/tests/syntax_tests/data/idempotency/covid-19charts.com/src/ColorStack.res b/tests/syntax_tests/data/idempotency/covid-19charts.com/src/ColorStack.res index cdc90321a9..fb0e78eb9e 100644 --- a/tests/syntax_tests/data/idempotency/covid-19charts.com/src/ColorStack.res +++ b/tests/syntax_tests/data/idempotency/covid-19charts.com/src/ColorStack.res @@ -52,7 +52,7 @@ let make = (~locations) => { let updateColors = (~locations, {colors, associations}) => { let colors = Stack.copy(colors) let locations = Set.fromArray(locations) - let prevLocations = Map.keysToArray(associations) |> Set.fromArray + let prevLocations = Map.keysToArray(associations)->Set.fromArray let removed = Set.diff(prevLocations, locations) Set.forEach(removed, location => diff --git a/tests/syntax_tests/data/idempotency/covid-19charts.com/src/Data.res b/tests/syntax_tests/data/idempotency/covid-19charts.com/src/Data.res index 1711269c2a..ef6de3e041 100644 --- a/tests/syntax_tests/data/idempotency/covid-19charts.com/src/Data.res +++ b/tests/syntax_tests/data/idempotency/covid-19charts.com/src/Data.res @@ -44,7 +44,7 @@ let countryIds = Map.keys(locations) let startDate = Js.Date.fromString(days[0]) let endDate = Js.Date.fromString(days[Js.Array.length(days) - 1]) -let dayToIndex = Js.Array.mapi((day, index) => (day, index), days) |> Map.fromArray +let dayToIndex = Js.Array.mapi((day, index) => (day, index), days)->Map.fromArray type xValue = | Date(Js.Date.t) @@ -56,7 +56,7 @@ type value = let dataWithGrowth = Map.entries(data) - |> Js.Array.map(((countryId, dataPoints)) => { + ->Js.Array.map(((countryId, dataPoints)) => { let data = Lazy.from_fun(() => { let countryDataWithGrowth = Map.empty() let _ = Js.Array.reduce((prevRecord, day) => { @@ -75,7 +75,7 @@ let dataWithGrowth = }) (countryId, data) }) - |> Belt.Map.String.fromArray + ->Belt.Map.String.fromArray type item = { x: xValue, @@ -92,7 +92,7 @@ let calendar: t = Js.Array.mapi((day, index) => { Belt.HashMap.String.set( values, Map.get(locations, countryId).name, - Lazy.from_fun(() => Map.get(Belt.Map.String.getExn(dataWithGrowth, countryId) |> Lazy.force, day)), + Lazy.from_fun(() => Map.get(Belt.Map.String.getExn(dataWithGrowth, countryId)->Lazy.force, day)), ), countryIds, ) @@ -100,7 +100,7 @@ let calendar: t = Js.Array.mapi((day, index) => { x: Date(Js.Date.fromString(day)), index: index, values: countryId => - Belt.HashMap.String.get(values, countryId) |> Js.Option.map((. x) => Lazy.force(x)), + Belt.HashMap.String.get(values, countryId)->Js.Option.map((. x) => Lazy.force(x)), } }, days) @@ -143,12 +143,12 @@ let alignToDay0 = (dataType, threshold) => { Lazy.from_fun(() => { let dataPoints = Lazy.force(dataPoints) Map.entries(dataPoints) - |> Js.Array.map(((date, value)) => (Map.get(dayToIndex, date), value)) - |> Js.Array.sortInPlaceWith((a, b) => compare(a |> fst, b |> fst)) - |> Js.Array.map(((_, value)) => value) - |> Js.Array.filter(value => getValue(dataType, value) >= threshold) - |> Js.Array.mapi((value, index) => (index, value)) - |> Belt.Map.Int.fromArray + ->Js.Array.map(((date, value)) => (Map.get(dayToIndex, date), value)) + ->Js.Array.sortInPlaceWith((a, b) => compare(a->fst, b->fst)) + ->Js.Array.map(((_, value)) => value) + ->Js.Array.filter(value => getValue(dataType, value) >= threshold) + ->Js.Array.mapi((value, index) => (index, value)) + ->Belt.Map.Int.fromArray }) ) @@ -156,7 +156,7 @@ let alignToDay0 = (dataType, threshold) => { x: Day(day), index: day, values: countryId => - Belt.Map.String.get(data, countryId) |> Js.Option.andThen((. countryData) => + Belt.Map.String.get(data, countryId)->Js.Option.andThen((. countryData) => Belt.Map.Int.get(Lazy.force(countryData), day) ), }) @@ -202,7 +202,7 @@ let getDailyMortailityRate = x => { /* * let allLocations = * Map.entries(locations) - * |> Js.Array.map(((locationId, value)) => + * ->Js.Array.map(((locationId, value)) => * {ReactSelect.label: value.name, value: locationId} * ); */ diff --git a/tests/syntax_tests/data/idempotency/covid-19charts.com/src/Filters.res b/tests/syntax_tests/data/idempotency/covid-19charts.com/src/Filters.res index 3810a0c96c..1e1d7dcb22 100644 --- a/tests/syntax_tests/data/idempotency/covid-19charts.com/src/Filters.res +++ b/tests/syntax_tests/data/idempotency/covid-19charts.com/src/Filters.res @@ -17,9 +17,9 @@ module Input = { onChange value={switch value { | Float(float) => - float |> Js.Option.map((. int) => Js.Float.toString(int)) |> Js.Option.getWithDefault("") + float->Js.Option.map((. int) => Js.Float.toString(int))->Js.Option.getWithDefault("") | Number(int) => - int |> Js.Option.map((. int) => Js.Int.toString(int)) |> Js.Option.getWithDefault("") + int->Js.Option.map((. int) => Js.Int.toString(int))->Js.Option.getWithDefault("") | Text(text) => text }} placeholder=label @@ -103,7 +103,7 @@ module Radio = { {React.string(text)} - }) |> React.array} + })->React.array} } @@ -167,7 +167,7 @@ module Locations = { onClick={removedId => setLocations(locations => Js.Array.filter(id => id != removedId, locations))} /> - ) |> React.array} + )->React.array}
{ @@ -226,7 +226,7 @@ module ThresholdInput = { value=Input.Number(threshold) onBlur=ignore onChange={ev => { - let value = ReactEvent.Form.target(ev)["value"] |> int_of_string_opt + let value = ReactEvent.Form.target(ev)["value"]->int_of_string_opt setThreshold(_ => value) }} label="1" @@ -248,7 +248,7 @@ module CalendarInput = { ref=?{Belt.Option.map(Js.Nullable.toOption(forwardedRef), ReactDOMRe.Ref.domRef)} className="bg-bggray text-base border-bggray border date-range-button" onClick> - {React.string(Js.Date.fromString(value) |> Js.Date.toLocaleDateString)} + {React.string(Js.Date.fromString(value)->Js.Date.toLocaleDateString)}
) diff --git a/tests/syntax_tests/data/idempotency/covid-19charts.com/src/Index.res b/tests/syntax_tests/data/idempotency/covid-19charts.com/src/Index.res index bbf7893f78..4a91f7e7b4 100644 --- a/tests/syntax_tests/data/idempotency/covid-19charts.com/src/Index.res +++ b/tests/syntax_tests/data/idempotency/covid-19charts.com/src/Index.res @@ -30,7 +30,7 @@ module App = { ~queryFragment, ~coder={ encode: x => SerializeQueryParam.string.encode(encode(x)), - decode: x => SerializeQueryParam.string.decode(x) |> Js.Option.andThen((. x) => decode(x)), + decode: x => SerializeQueryParam.string.decode(x)->Js.Option.andThen((. x) => decode(x)), }, ) @@ -101,8 +101,8 @@ module App = { () => Some(17), ~queryFragment="threshold", ~coder={ - encode: x => Belt.Option.getWithDefault(x, 1) |> SerializeQueryParam.int.encode, - decode: x => SerializeQueryParam.int.decode(x) |> Js.Option.map((. x) => Some(x)), + encode: x => Belt.Option.getWithDefault(x, 1)->SerializeQueryParam.int.encode, + decode: x => SerializeQueryParam.int.decode(x)->Js.Option.map((. x) => Some(x)), }, ) let startDate = UseQueryParam.hook( @@ -115,19 +115,19 @@ module App = { ~queryFragment="until", ~coder=SerializeQueryParam.date, ) - let resetDates = if Data.isInitialRange(startDate |> fst, endDate |> fst) { + let resetDates = if Data.isInitialRange(startDate->fst, endDate->fst) { None } else { Some( () => { - let setStart = startDate |> snd - let setEnd = endDate |> snd + let setStart = startDate->snd + let setEnd = endDate->snd setStart(_ => Data.startDate) setEnd(_ => Data.endDate) }, ) } - let thresholdOr1 = Belt.Option.getWithDefault(threshold |> fst, 1) + let thresholdOr1 = Belt.Option.getWithDefault(threshold->fst, 1)
fst} + chartType={chartType->fst} threshold=thresholdOr1 - timeline={timeline |> fst} + timeline={timeline->fst} locations - scale={scale |> fst} - startDate={startDate |> fst} - endDate={endDate |> fst} + scale={scale->fst} + startDate={startDate->fst} + endDate={endDate->fst} />
} diff --git a/tests/syntax_tests/data/idempotency/genType/src/Annotation.res b/tests/syntax_tests/data/idempotency/genType/src/Annotation.res index 6b195ac8e3..c2fb3987b8 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/Annotation.res +++ b/tests/syntax_tests/data/idempotency/genType/src/Annotation.res @@ -54,8 +54,8 @@ let rec getAttributePayload = (checkText, attributes: Typedtree.attributes) => { | {pexp_desc: Pexp_construct({txt: Lident(("true" | "false") as s)}, _), _} => Some(BoolPayload(s == "true")) | {pexp_desc: Pexp_tuple(exprs)} => - let payloads = exprs |> List.rev |> List.fold_left((payloads, expr) => - switch expr |> fromExpr { + let payloads = exprs->List.rev->List.fold_left((payloads, expr) => + switch expr->fromExpr { | Some(payload) => list{payload, ...payloads} | None => payloads } @@ -69,7 +69,7 @@ let rec getAttributePayload = (checkText, attributes: Typedtree.attributes) => { | list{({Asttypes.txt: txt}, payload), ..._tl} if checkText(txt) => switch payload { | PStr(list{}) => Some(UnrecognizedPayload) - | PStr(list{{pstr_desc: Pstr_eval(expr, _)}, ..._}) => expr |> fromExpr + | PStr(list{{pstr_desc: Pstr_eval(expr, _)}, ..._}) => expr->fromExpr | PStr(list{{pstr_desc: Pstr_extension(_)}, ..._}) => Some(UnrecognizedPayload) | PStr(list{{pstr_desc: Pstr_value(_)}, ..._}) => Some(UnrecognizedPayload) | PStr(list{{pstr_desc: Pstr_primitive(_)}, ..._}) => Some(UnrecognizedPayload) @@ -93,10 +93,10 @@ let rec getAttributePayload = (checkText, attributes: Typedtree.attributes) => { } let getGenTypeAsRenaming = attributes => - switch attributes |> getAttributePayload(tagIsGenTypeAs) { + switch attributes->getAttributePayload(tagIsGenTypeAs) { | Some(StringPayload(s)) => Some(s) | None => - switch attributes |> getAttributePayload(tagIsGenType) { + switch attributes->getAttributePayload(tagIsGenType) { | Some(StringPayload(s)) => Some(s) | _ => None } @@ -104,14 +104,14 @@ let getGenTypeAsRenaming = attributes => } let getAsRenaming = attributes => - switch attributes |> getAttributePayload(tagIsAs) { + switch attributes->getAttributePayload(tagIsAs) { | Some(StringPayload(s)) => Some(s) | _ => None } let getAttributeImportRenaming = attributes => { - let attributeImport = attributes |> getAttributePayload(tagIsGenTypeImport) - let genTypeAsRenaming = attributes |> getGenTypeAsRenaming + let attributeImport = attributes->getAttributePayload(tagIsGenTypeImport) + let genTypeAsRenaming = attributes->getGenTypeAsRenaming switch (attributeImport, genTypeAsRenaming) { | (Some(StringPayload(importString)), _) => (Some(importString), genTypeAsRenaming) | (Some(TuplePayload(list{StringPayload(importString), StringPayload(renameString)})), _) => ( @@ -123,7 +123,7 @@ let getAttributeImportRenaming = attributes => { } let getDocString = attributes => { - let docPayload = attributes |> getAttributePayload(tagIsOcamlDoc) + let docPayload = attributes->getAttributePayload(tagIsOcamlDoc) switch docPayload { | Some(StringPayload(docString)) => "/** " ++ (docString ++ " */\n") | _ => "" @@ -144,7 +144,7 @@ let fromAttributes = (attributes: Typedtree.attributes) => let rec moduleTypeCheckAnnotation = (~checkAnnotation, {mty_desc}: Typedtree.module_type) => switch mty_desc { - | Tmty_signature(signature) => signature |> signatureCheckAnnotation(~checkAnnotation) + | Tmty_signature(signature) => signature->signatureCheckAnnotation(~checkAnnotation) | Tmty_ident(_) | Tmty_functor(_) | Tmty_with(_) @@ -155,22 +155,22 @@ and moduleDeclarationCheckAnnotation = ( ~checkAnnotation, {md_attributes, md_type, md_loc: loc}: Typedtree.module_declaration, ) => - md_attributes |> checkAnnotation(~loc) || md_type |> moduleTypeCheckAnnotation(~checkAnnotation) + md_attributes->checkAnnotation(~loc) || md_type->moduleTypeCheckAnnotation(~checkAnnotation) and signatureItemCheckAnnotation = (~checkAnnotation, signatureItem: Typedtree.signature_item) => switch signatureItem { | {Typedtree.sig_desc: Typedtree.Tsig_type(_, typeDeclarations)} => - typeDeclarations |> List.exists(({typ_attributes, typ_loc: loc}: Typedtree.type_declaration) => - typ_attributes |> checkAnnotation(~loc) + typeDeclarations->List.exists(({typ_attributes, typ_loc: loc}: Typedtree.type_declaration) => + typ_attributes->checkAnnotation(~loc) ) | {sig_desc: Tsig_value({val_attributes, val_loc: loc})} => - val_attributes |> checkAnnotation(~loc) + val_attributes->checkAnnotation(~loc) | {sig_desc: Tsig_module(moduleDeclaration)} => - moduleDeclaration |> moduleDeclarationCheckAnnotation(~checkAnnotation) - | {sig_desc: Tsig_attribute(attribute), sig_loc: loc} => list{attribute} |> checkAnnotation(~loc) + moduleDeclaration->moduleDeclarationCheckAnnotation(~checkAnnotation) + | {sig_desc: Tsig_attribute(attribute), sig_loc: loc} => list{attribute}->checkAnnotation(~loc) | _ => false } and signatureCheckAnnotation = (~checkAnnotation, signature: Typedtree.signature) => - signature.sig_items |> List.exists(signatureItemCheckAnnotation(~checkAnnotation)) + signature.sig_items->List.exists(signatureItemCheckAnnotation(~checkAnnotation)) let rec structureItemCheckAnnotation = ( ~checkAnnotation, @@ -178,29 +178,29 @@ let rec structureItemCheckAnnotation = ( ) => switch structureItem { | {Typedtree.str_desc: Typedtree.Tstr_type(_, typeDeclarations)} => - typeDeclarations |> List.exists(({typ_attributes, typ_loc: loc}: Typedtree.type_declaration) => - typ_attributes |> checkAnnotation(~loc) + typeDeclarations->List.exists(({typ_attributes, typ_loc: loc}: Typedtree.type_declaration) => + typ_attributes->checkAnnotation(~loc) ) | {str_desc: Tstr_value(_loc, valueBindings)} => - valueBindings |> List.exists(({vb_attributes, vb_loc: loc}: Typedtree.value_binding) => - vb_attributes |> checkAnnotation(~loc) + valueBindings->List.exists(({vb_attributes, vb_loc: loc}: Typedtree.value_binding) => + vb_attributes->checkAnnotation(~loc) ) | {str_desc: Tstr_primitive({val_attributes, val_loc: loc})} => - val_attributes |> checkAnnotation(~loc) + val_attributes->checkAnnotation(~loc) | {str_desc: Tstr_module(moduleBinding)} => - moduleBinding |> moduleBindingCheckAnnotation(~checkAnnotation) + moduleBinding->moduleBindingCheckAnnotation(~checkAnnotation) | {str_desc: Tstr_recmodule(moduleBindings)} => - moduleBindings |> List.exists(moduleBindingCheckAnnotation(~checkAnnotation)) + moduleBindings->List.exists(moduleBindingCheckAnnotation(~checkAnnotation)) | {str_desc: Tstr_include({incl_attributes, incl_mod, incl_loc: loc})} => - incl_attributes |> checkAnnotation(~loc) || - incl_mod |> moduleExprCheckAnnotation(~checkAnnotation) + incl_attributes->checkAnnotation(~loc) || + incl_mod->moduleExprCheckAnnotation(~checkAnnotation) | _ => false } and moduleExprCheckAnnotation = (~checkAnnotation, moduleExpr: Typedtree.module_expr) => switch moduleExpr.mod_desc { | Tmod_structure(structure) | Tmod_constraint({mod_desc: Tmod_structure(structure)}, _, _, _) => - structure |> structureCheckAnnotation(~checkAnnotation) + structure->structureCheckAnnotation(~checkAnnotation) | Tmod_constraint(_) | Tmod_ident(_) | Tmod_functor(_) @@ -211,18 +211,18 @@ and moduleBindingCheckAnnotation = ( ~checkAnnotation, {mb_expr, mb_attributes, mb_loc: loc}: Typedtree.module_binding, ) => - mb_attributes |> checkAnnotation(~loc) || mb_expr |> moduleExprCheckAnnotation(~checkAnnotation) + mb_attributes->checkAnnotation(~loc) || mb_expr->moduleExprCheckAnnotation(~checkAnnotation) and structureCheckAnnotation = (~checkAnnotation, structure: Typedtree.structure) => - structure.str_items |> List.exists(structureItemCheckAnnotation(~checkAnnotation)) + structure.str_items->List.exists(structureItemCheckAnnotation(~checkAnnotation)) -let sanitizeVariableName = name => name |> Str.global_replace(Str.regexp("-"), "_") +let sanitizeVariableName = name => name->Str.global_replace(Str.regexp("-"), "_") let importFromString = (importString): \"import" => { let name = { - let base = importString |> Filename.basename - try base |> Filename.chop_extension catch { + let base = importString->Filename.basename + try base->Filename.chop_extension catch { | Invalid_argument(_) => base - } |> sanitizeVariableName + }->sanitizeVariableName } let importPath = ImportPath.fromStringUnsafe(importString) {name: name, importPath: importPath} diff --git a/tests/syntax_tests/data/idempotency/genType/src/Arnold.res b/tests/syntax_tests/data/idempotency/genType/src/Arnold.res index f7ed09949c..4a11f21c94 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/Arnold.res +++ b/tests/syntax_tests/data/idempotency/genType/src/Arnold.res @@ -3,7 +3,7 @@ let verbose = DeadCommon.verbose let printPos = (ppf, pos: Lexing.position) => { let file = pos.Lexing.pos_fname let line = pos.Lexing.pos_lnum - Format.fprintf(ppf, "@{%s@} @{%i@}", file |> Filename.basename, line) + Format.fprintf(ppf, "@{%s@} @{%i@}", file->Filename.basename, line) } module StringSet = Set.Make(String) @@ -29,10 +29,10 @@ module FunctionArgs = { let toString = functionArgs => functionArgs == list{} ? "" - : "<" ++ ((functionArgs |> List.map(argToString) |> String.concat(",")) ++ ">") + : "<" ++ ((functionArgs->List.map(argToString)->String.concat(",")) ++ ">") let find = (t: t, ~label) => - switch t |> List.find_opt(arg => arg.label == label) { + switch t->List.find_opt(arg => arg.label == label) { | Some({functionName}) => Some(functionName) | None => None } @@ -68,7 +68,7 @@ module FunctionCall = { } let substituteName = (~sub, name) => - switch sub |> FunctionArgs.find(~label=name) { + switch sub->FunctionArgs.find(~label=name) { | Some(functionName) => functionName | None => name } @@ -78,10 +78,10 @@ module FunctionCall = { t } else { { - functionName: t.functionName |> substituteName(~sub), - functionArgs: t.functionArgs |> List.map((arg: FunctionArgs.arg) => { + functionName: t.functionName->substituteName(~sub), + functionArgs: t.functionArgs->List.map((arg: FunctionArgs.arg) => { ...arg, - functionName: arg.functionName |> substituteName(~sub), + functionName: arg.functionName->substituteName(~sub), }), } } @@ -273,14 +273,14 @@ module Trace = { Path.name(progressFunction) ++ (":" ++ Progress.toString(progress)) | Tcall(FunctionCall(functionCall), progress) => FunctionCall.toString(functionCall) ++ (":" ++ Progress.toString(progress)) - | Tnondet(traces) => "[" ++ ((traces |> List.map(toString) |> String.concat(" || ")) ++ "]") - | Toption(retOption) => retOption |> retOptionToString + | Tnondet(traces) => "[" ++ ((traces->List.map(toString)->String.concat(" || ")) ++ "]") + | Toption(retOption) => retOption->retOptionToString | Tseq(traces) => - let tracesNotEmpty = traces |> List.filter(\"<>"(empty)) + let tracesNotEmpty = traces->List.filter(\"<>"(empty)) switch tracesNotEmpty { | list{} => "_" - | list{t} => t |> toString - | list{_, ..._} => tracesNotEmpty |> List.map(toString) |> String.concat("; ") + | list{t} => t->toString + | list{_, ..._} => tracesNotEmpty->List.map(toString)->String.concat("; ") } } } @@ -312,7 +312,7 @@ module Values: { | None => list{} | Some(p) => list{"none: " ++ Progress.toString(p)} }, - ) |> String.concat(", ") + )->String.concat(", ") let none = (~progress) => {none: Some(progress), some: None} let some = (~progress) => {none: None, some: Some(progress)} @@ -342,8 +342,8 @@ module State = { let toString = ({progress, trace, valuesOpt}) => { let progressStr = switch valuesOpt { - | None => progress |> Progress.toString - | Some(values) => "{" ++ ((values |> Values.toString) ++ "}") + | None => progress->Progress.toString + | Some(values) => "{" ++ ((values->Values.toString) ++ "}") } progressStr ++ (" with trace " ++ Trace.toString(trace)) } @@ -386,7 +386,7 @@ module State = { | list{s, ...nextStates} => List.fold_left(nd, s, nextStates) } - let unorderedSequence = states => {...states |> sequence, valuesOpt: None} + let unorderedSequence = states => {...states->sequence, valuesOpt: None} let none = (~progress) => init(~progress, ~trace=Trace.none, ~valuesOpt=Some(Values.none(~progress)), ()) @@ -411,17 +411,17 @@ module Command = { let rec toString = command => switch command { - | Call(call, _pos) => call |> Call.toString - | ConstrOption(r) => r |> Trace.retOptionToString - | Nondet(commands) => "[" ++ ((commands |> List.map(toString) |> String.concat(" || ")) ++ "]") + | Call(call, _pos) => call->Call.toString + | ConstrOption(r) => r->Trace.retOptionToString + | Nondet(commands) => "[" ++ ((commands->List.map(toString)->String.concat(" || ")) ++ "]") | Nothing => "_" - | Sequence(commands) => commands |> List.map(toString) |> String.concat("; ") + | Sequence(commands) => commands->List.map(toString)->String.concat("; ") | SwitchOption({functionCall, some: cSome, none: cNone}) => "switch " ++ (FunctionCall.toString(functionCall) ++ (" {some: " ++ (toString(cSome) ++ (", none: " ++ (toString(cNone) ++ "}"))))) | UnorderedSequence(commands) => - "{" ++ ((commands |> List.map(toString) |> String.concat(", ")) ++ "}") + "{" ++ ((commands->List.map(toString)->String.concat(", ")) ++ "}") } let nothing = Nothing @@ -454,7 +454,7 @@ module Command = { let \"+++" = (c1, c2) => sequence(list{c1, c2}) let unorderedSequence = commands => { - let relevantCommands = commands |> List.filter(x => x != nothing) + let relevantCommands = commands->List.filter(x => x != nothing) switch relevantCommands { | list{} => nothing | list{c} => c @@ -472,16 +472,16 @@ module Kind = { let empty: t = list{} - let hasLabel = (~label, k: t) => k |> List.exists(entry => entry.label == label) + let hasLabel = (~label, k: t) => k->List.exists(entry => entry.label == label) - let rec entryToString = ({label, k}) => k == list{} ? label : label ++ (":" ++ (k |> toString)) + let rec entryToString = ({label, k}) => k == list{} ? label : label ++ (":" ++ (k->toString)) and toString = (kind: t) => - kind == list{} ? "" : "<" ++ ((kind |> List.map(entryToString) |> String.concat(", ")) ++ ">") + kind == list{} ? "" : "<" ++ ((kind->List.map(entryToString)->String.concat(", ")) ++ ">") let addLabelWithEmptyKind = (~label, kind) => - if !(kind |> hasLabel(~label)) { - list{{label: label, k: empty}, ...kind} |> List.sort(compare) + if !(kind->hasLabel(~label)) { + list{{label: label, k: empty}, ...kind}->List.sort(compare) } else { kind } @@ -507,8 +507,8 @@ module FunctionTable = { }, tbl, list{}, - ) |> List.sort(((fn1, _, _), (fn2, _, _)) => String.compare(fn1, fn2)) - definitions |> List.iteri((i, (functionName, kind, body)) => + )->List.sort(((fn1, _, _), (fn2, _, _)) => String.compare(fn1, fn2)) + definitions->List.iteri((i, (functionName, kind, body)) => Format.fprintf( ppf, "@,@{%d@} @{%s%s@}: %s", @@ -543,18 +543,18 @@ module FunctionTable = { } let addLabelToKind = (~functionName, ~label, tbl: t) => { - let functionDefinition = tbl |> getFunctionDefinition(~functionName) - functionDefinition.kind = functionDefinition.kind |> Kind.addLabelWithEmptyKind(~label) + let functionDefinition = tbl->getFunctionDefinition(~functionName) + functionDefinition.kind = functionDefinition.kind->Kind.addLabelWithEmptyKind(~label) } let addBody = (~body, ~functionName, tbl: t) => { - let functionDefinition = tbl |> getFunctionDefinition(~functionName) + let functionDefinition = tbl->getFunctionDefinition(~functionName) functionDefinition.body = body } let functionGetKindOfLabel = (~functionName, ~label, tbl: t) => switch Hashtbl.find(tbl, functionName) { - | {kind} => kind |> Kind.hasLabel(~label) ? Some(Kind.empty) : None + | {kind} => kind->Kind.hasLabel(~label) ? Some(Kind.empty) : None | exception Not_found => None } } @@ -585,7 +585,7 @@ module FindFunctionsCalled = { let callees = ref(StringSet.empty) let traverseExpr = traverseExpr(~callees) if isFunction { - expression |> traverseExpr.expr(traverseExpr) |> ignore + expression->traverseExpr.expr(traverseExpr)->ignore } callees.contents } @@ -615,10 +615,10 @@ module ExtendFunctionTable = { let checkArg = ((argLabel: Asttypes.arg_label, _argOpt)) => switch (argLabel, kindOpt) { | (Labelled(l) | Optional(l), Some(kind)) => - kind |> List.for_all(({Kind.label: label}) => label != l) + kind->List.for_all(({Kind.label: label}) => label != l) | _ => true } - if args |> List.for_all(checkArg) { + if args->List.for_all(checkArg) { Some((path, loc)) } else { None @@ -638,8 +638,8 @@ module ExtendFunctionTable = { | Some((id_pos, _, callees)) => if !StringSet.is_empty(StringSet.inter(Lazy.force(callees), progressFunctions)) { let functionName = Path.name(callee) - if !(callee |> FunctionTable.isInFunctionInTable(~functionTable)) { - functionTable |> FunctionTable.addFunction(~functionName) + if !(callee->FunctionTable.isInFunctionInTable(~functionTable)) { + functionTable->FunctionTable.addFunction(~functionName) if verbose { Log_.info(~loc, ~name="Termination Analysis", (ppf, ()) => Format.fprintf( @@ -655,13 +655,13 @@ module ExtendFunctionTable = { } } | Texp_apply({exp_desc: Texp_ident(callee, _, _)}, args) - if callee |> FunctionTable.isInFunctionInTable(~functionTable) => + if callee->FunctionTable.isInFunctionInTable(~functionTable) => let functionName = Path.name(callee) - args |> List.iter(((argLabel: Asttypes.arg_label, argOpt)) => - switch (argLabel, argOpt |> extractLabelledArgument) { + args->List.iter(((argLabel: Asttypes.arg_label, argOpt)) => + switch (argLabel, argOpt->extractLabelledArgument) { | (Labelled(label), Some((path, loc))) - if path |> FunctionTable.isInFunctionInTable(~functionTable) => - functionTable |> FunctionTable.addLabelToKind(~functionName, ~label) + if path->FunctionTable.isInFunctionInTable(~functionTable) => + functionTable->FunctionTable.addLabelToKind(~functionName, ~label) if verbose { Log_.info(~loc, ~name="Termination Analysis", (ppf, ()) => Format.fprintf( @@ -693,7 +693,7 @@ module ExtendFunctionTable = { expression: Typedtree.expression, ) => { let traverseExpr = traverseExpr(~functionTable, ~progressFunctions, ~valueBindingsTable) - expression |> traverseExpr.expr(traverseExpr) |> ignore + expression->traverseExpr.expr(traverseExpr)->ignore } } @@ -702,7 +702,7 @@ module CheckExpressionWellFormed = { let super = Tast_mapper.default let checkIdent = (~path, ~loc) => - if path |> FunctionTable.isInFunctionInTable(~functionTable) { + if path->FunctionTable.isInFunctionInTable(~functionTable) { Stats.logHygieneOnlyCallDirectly(~path, ~loc) } @@ -713,24 +713,24 @@ module CheckExpressionWellFormed = { e | Texp_apply({exp_desc: Texp_ident(functionPath, _, _)}, args) => let functionName = Path.name(functionPath) - args |> List.iter(((argLabel: Asttypes.arg_label, argOpt)) => - switch argOpt |> ExtendFunctionTable.extractLabelledArgument { + args->List.iter(((argLabel: Asttypes.arg_label, argOpt)) => + switch argOpt->ExtendFunctionTable.extractLabelledArgument { | Some((path, loc)) => switch argLabel { | Labelled(label) => if ( - functionTable |> FunctionTable.functionGetKindOfLabel(~functionName, ~label) != None + functionTable->FunctionTable.functionGetKindOfLabel(~functionName, ~label) != None ) { () } else { switch Hashtbl.find_opt(valueBindingsTable, functionName) { | Some((_pos, body: Typedtree.expression, _)) - if path |> FunctionTable.isInFunctionInTable(~functionTable) => - let inTable = functionPath |> FunctionTable.isInFunctionInTable(~functionTable) + if path->FunctionTable.isInFunctionInTable(~functionTable) => + let inTable = functionPath->FunctionTable.isInFunctionInTable(~functionTable) if !inTable { - functionTable |> FunctionTable.addFunction(~functionName) + functionTable->FunctionTable.addFunction(~functionName) } - functionTable |> FunctionTable.addLabelToKind(~functionName, ~label) + functionTable->FunctionTable.addLabelToKind(~functionName, ~label) if verbose { Log_.info(~loc=body.exp_loc, ~name="Termination Analysis", (ppf, ()) => Format.fprintf( @@ -766,7 +766,7 @@ module CheckExpressionWellFormed = { let run = (~functionTable, ~valueBindingsTable, expression: Typedtree.expression) => { let traverseExpr = traverseExpr(~functionTable, ~valueBindingsTable) - expression |> traverseExpr.expr(traverseExpr) |> ignore + expression->traverseExpr.expr(traverseExpr)->ignore } } @@ -791,8 +791,8 @@ module Compile = { ) { | Some(innerFunctionName) => let innerFunctionDefinition = - functionTable |> FunctionTable.getFunctionDefinition(~functionName=innerFunctionName) - let argsFromKind = innerFunctionDefinition.kind |> List.map((entry: Kind.entry) => ( + functionTable->FunctionTable.getFunctionDefinition(~functionName=innerFunctionName) + let argsFromKind = innerFunctionDefinition.kind->List.map((entry: Kind.entry) => ( Asttypes.Labelled(entry.label), Some({ ...expr, @@ -802,12 +802,12 @@ module Compile = { (Path.Pident(Ident.create(innerFunctionName)), \"@"(argsFromKind, argsToExtend)) | None => (calleeToRename, argsToExtend) } - if callee |> FunctionTable.isInFunctionInTable(~functionTable) { + if callee->FunctionTable.isInFunctionInTable(~functionTable) { let functionName = Path.name(callee) - let functionDefinition = functionTable |> FunctionTable.getFunctionDefinition(~functionName) + let functionDefinition = functionTable->FunctionTable.getFunctionDefinition(~functionName) exception ArgError let getFunctionArg = ({Kind.label: label}) => { - let argOpt = args |> List.find_opt(arg => + let argOpt = args->List.find_opt(arg => switch arg { | (Asttypes.Labelled(s), Some(_)) => s == label | _ => false @@ -817,20 +817,20 @@ module Compile = { | Some((_, Some(e))) => Some(e) | _ => None } - let functionArg = switch argOpt |> ExtendFunctionTable.extractLabelledArgument( + let functionArg = switch argOpt->ExtendFunctionTable.extractLabelledArgument( ~kindOpt=Some(functionDefinition.kind), ) { | None => Stats.logHygieneMustHaveNamedArgument(~label, ~loc) raise(ArgError) - | Some((path, _pos)) if path |> FunctionTable.isInFunctionInTable(~functionTable) => + | Some((path, _pos)) if path->FunctionTable.isInFunctionInTable(~functionTable) => let functionName = Path.name(path) {FunctionArgs.label: label, functionName: functionName} | Some((path, _pos)) if functionTable - |> FunctionTable.functionGetKindOfLabel( + ->FunctionTable.functionGetKindOfLabel( ~functionName=currentFunctionName, ~label=Path.name(path), ) == @@ -844,7 +844,7 @@ module Compile = { } functionArg } - let functionArgsOpt = try Some(functionDefinition.kind |> List.map(getFunctionArg)) catch { + let functionArgsOpt = try Some(functionDefinition.kind->List.map(getFunctionArg)) catch { | ArgError => None } switch functionArgsOpt { @@ -853,17 +853,17 @@ module Compile = { Command.Call( FunctionCall({functionName: functionName, functionArgs: functionArgs}), loc, - ) |> evalArgs(~args, ~ctx) + )->evalArgs(~args, ~ctx) } - } else if callee |> isProgressFunction { - Command.Call(ProgressFunction(callee), loc) |> evalArgs(~args, ~ctx) + } else if callee->isProgressFunction { + Command.Call(ProgressFunction(callee), loc)->evalArgs(~args, ~ctx) } else { - switch functionTable |> FunctionTable.functionGetKindOfLabel( + switch functionTable->FunctionTable.functionGetKindOfLabel( ~functionName=currentFunctionName, ~label=Path.name(callee), ) { | Some(kind) if kind == Kind.empty => - Command.Call(FunctionCall(Path.name(callee) |> FunctionCall.noArgs), loc) |> evalArgs( + Command.Call(FunctionCall(Path.name(callee)->FunctionCall.noArgs), loc)->evalArgs( ~args, ~ctx, ) @@ -871,50 +871,50 @@ module Compile = { // TODO when kinds are extended in future: check that args matches with kind // and create a function call with the appropriate arguments assert(false) - | None => expr |> expression(~ctx) |> evalArgs(~args, ~ctx) + | None => expr->expression(~ctx)->evalArgs(~args, ~ctx) } } - | Texp_apply(expr, args) => expr |> expression(~ctx) |> evalArgs(~args, ~ctx) + | Texp_apply(expr, args) => expr->expression(~ctx)->evalArgs(~args, ~ctx) | Texp_let(Recursive, list{{vb_pat: {pat_desc: Tpat_var(id, _), pat_loc}, vb_expr}}, inExpr) => let oldFunctionName = Ident.name(id) let newFunctionName = currentFunctionName ++ ("$" ++ oldFunctionName) - functionTable |> FunctionTable.addFunction(~functionName=newFunctionName) + functionTable->FunctionTable.addFunction(~functionName=newFunctionName) let newFunctionDefinition = - functionTable |> FunctionTable.getFunctionDefinition(~functionName=newFunctionName) + functionTable->FunctionTable.getFunctionDefinition(~functionName=newFunctionName) let currentFunctionDefinition = - functionTable |> FunctionTable.getFunctionDefinition(~functionName=currentFunctionName) + functionTable->FunctionTable.getFunctionDefinition(~functionName=currentFunctionName) newFunctionDefinition.kind = currentFunctionDefinition.kind let newCtx = {...ctx, currentFunctionName: newFunctionName} Hashtbl.replace(ctx.innerRecursiveFunctions, oldFunctionName, newFunctionName) - newFunctionDefinition.body = Some(vb_expr |> expression(~ctx=newCtx)) + newFunctionDefinition.body = Some(vb_expr->expression(~ctx=newCtx)) if verbose { Log_.info(~loc=pat_loc, ~name="Termination Analysis", (ppf, ()) => Format.fprintf(ppf, "Adding recursive definition @{%s@}", newFunctionName) ) } - inExpr |> expression(~ctx) + inExpr->expression(~ctx) | Texp_let(recFlag, valueBindings, inExpr) => if recFlag == Recursive { Stats.logHygieneNoNestedLetRec(~loc) } let commands = \"@"( - valueBindings |> List.map((vb: Typedtree.value_binding) => vb.vb_expr |> expression(~ctx)), - list{inExpr |> expression(~ctx)}, + valueBindings->List.map((vb: Typedtree.value_binding) => vb.vb_expr->expression(~ctx)), + list{inExpr->expression(~ctx)}, ) Command.sequence(commands) | Texp_sequence(e1, e2) => open Command \"+++"(expression(~ctx, e1), expression(~ctx, e2)) | Texp_ifthenelse(e1, e2, eOpt) => - let c1 = e1 |> expression(~ctx) - let c2 = e2 |> expression(~ctx) - let c3 = eOpt |> expressionOpt(~ctx) + let c1 = e1->expression(~ctx) + let c2 = e2->expression(~ctx) + let c3 = eOpt->expressionOpt(~ctx) open Command \"+++"(c1, nondet(list{c2, c3})) | Texp_constant(_) => Command.nothing | Texp_construct({loc: {loc_ghost}}, {cstr_name}, expressions) => - let c = expressions |> List.map(e => e |> expression(~ctx)) |> Command.unorderedSequence + let c = expressions->List.map(e => e->expression(~ctx))->Command.unorderedSequence switch cstr_name { | "Some" if loc_ghost == false => open Command @@ -924,11 +924,11 @@ module Compile = { \"+++"(c, ConstrOption(Rnone)) | _ => c } - | Texp_function({cases}) => cases |> List.map(case(~ctx)) |> Command.nondet + | Texp_function({cases}) => cases->List.map(case(~ctx))->Command.nondet | Texp_match(e, cases, list{}, _) => - let cE = e |> expression(~ctx) - let cCases = cases |> List.map(case(~ctx)) + let cE = e->expression(~ctx) + let cCases = cases->List.map(case(~ctx)) switch (cE, cases) { | ( Call(FunctionCall(functionCall), loc), @@ -947,28 +947,28 @@ module Compile = { | Texp_match(_, _, list{_, ..._} as _casesExn, _) => assert(false) - | Texp_field(e, _lid, _desc) => e |> expression(~ctx) + | Texp_field(e, _lid, _desc) => e->expression(~ctx) | Texp_record({fields, extended_expression}) => list{ extended_expression, ...fields - |> Array.to_list - |> List.map(((_desc, recordLabelDefinition: Typedtree.record_label_definition)) => + ->Array.to_list + ->List.map(((_desc, recordLabelDefinition: Typedtree.record_label_definition)) => switch recordLabelDefinition { | Kept(_typeExpr) => None | Overridden(_loc, e) => Some(e) } ), } - |> List.map(expressionOpt(~ctx)) - |> Command.unorderedSequence + ->List.map(expressionOpt(~ctx)) + ->Command.unorderedSequence | Texp_setfield(e1, _loc, _desc, e2) => - list{e1, e2} |> List.map(expression(~ctx)) |> Command.unorderedSequence + list{e1, e2}->List.map(expression(~ctx))->Command.unorderedSequence | Texp_tuple(expressions) => - expressions |> List.map(expression(~ctx)) |> Command.unorderedSequence + expressions->List.map(expression(~ctx))->Command.unorderedSequence | Texp_assert(_) => Command.nothing @@ -994,17 +994,17 @@ module Compile = { and expressionOpt = (~ctx, eOpt) => switch eOpt { | None => Command.nothing - | Some(e) => e |> expression(~ctx) + | Some(e) => e->expression(~ctx) } and evalArgs = (~args, ~ctx, command) => { // Don't assume any evaluation order on the arguments - let commands = args |> List.map(((_, eOpt)) => eOpt |> expressionOpt(~ctx)) + let commands = args->List.map(((_, eOpt)) => eOpt->expressionOpt(~ctx)) open Command \"+++"(unorderedSequence(commands), command) } and case = (~ctx, {c_guard, c_rhs}: Typedtree.case) => switch c_guard { - | None => c_rhs |> expression(~ctx) + | None => c_rhs->expression(~ctx) | Some(e) => open Command \"+++"(expression(~ctx, e), expression(~ctx, c_rhs)) @@ -1049,8 +1049,8 @@ module CallStack = { }, t.tbl, list{}, - ) |> List.sort(((_, i1, _), (_, i2, _)) => i2 - i1) - frames |> List.iter(((functionCall: FunctionCall.t, i, pos)) => + )->List.sort(((_, i1, _), (_, i2, _)) => i2 - i1) + frames->List.iter(((functionCall: FunctionCall.t, i, pos)) => Format.fprintf( ppf, "@,@{%d@} %s (%a)", @@ -1074,14 +1074,14 @@ module Eval = { let lookupCache = (~functionCall, cache: cache) => Hashtbl.find_opt(cache, functionCall) let updateCache = (~functionCall, ~loc, ~state, cache: cache) => { - Stats.logResult(~functionCall, ~resString=state |> State.toString, ~loc) + Stats.logResult(~functionCall, ~resString=state->State.toString, ~loc) if !Hashtbl.mem(cache, functionCall) { Hashtbl.replace(cache, functionCall, state) } } let hasInfiniteLoop = (~callStack, ~functionCallToInstantiate, ~functionCall, ~loc, ~state) => - if callStack |> CallStack.hasFunctionCall(~functionCall) { + if callStack->CallStack.hasFunctionCall(~functionCall) { if state.State.progress == NoProgress { Log_.error(~loc, ~name="Error Termination", (ppf, ()) => { Format.fprintf(ppf, "Possible infinite loop when calling ") @@ -1089,13 +1089,13 @@ module Eval = { ? Format.fprintf( ppf, "@{%s@}", - functionCallToInstantiate |> FunctionCall.toString, + functionCallToInstantiate->FunctionCall.toString, ) : Format.fprintf( ppf, "@{%s@} which is @{%s@}", - functionCallToInstantiate |> FunctionCall.toString, - functionCall |> FunctionCall.toString, + functionCallToInstantiate->FunctionCall.toString, + functionCall->FunctionCall.toString, ) Format.fprintf(ppf, "@,%a", CallStack.print, callStack) }) @@ -1118,10 +1118,10 @@ module Eval = { ): State.t => { let pos = loc.Location.loc_start let functionCall = - functionCallToInstantiate |> FunctionCall.applySubstitution(~sub=functionArgs) + functionCallToInstantiate->FunctionCall.applySubstitution(~sub=functionArgs) let functionName = functionCall.functionName let call = Call.FunctionCall(functionCall) - let stateAfterCall = switch cache |> lookupCache(~functionCall) { + let stateAfterCall = switch cache->lookupCache(~functionCall) { | Some(stateAfterCall) => Stats.logCache(~functionCall, ~hit=true, ~loc) { @@ -1140,14 +1140,14 @@ module Eval = { } } else { Stats.logCache(~functionCall, ~hit=false, ~loc) - let functionDefinition = functionTable |> FunctionTable.getFunctionDefinition(~functionName) - callStack |> CallStack.addFunctionCall(~functionCall, ~pos) + let functionDefinition = functionTable->FunctionTable.getFunctionDefinition(~functionName) + callStack->CallStack.addFunctionCall(~functionCall, ~pos) let body = switch functionDefinition.body { | Some(body) => body | None => assert(false) } let stateAfterCall = - body |> run( + body->run( ~cache, ~callStack, ~functionArgs=functionCall.functionArgs, @@ -1155,9 +1155,9 @@ module Eval = { ~madeProgressOn, ~state=State.init(), ) - cache |> updateCache(~functionCall, ~loc, ~state=stateAfterCall) + cache->updateCache(~functionCall, ~loc, ~state=stateAfterCall) // Invariant: run should restore the callStack - callStack |> CallStack.removeFunctionCall(~functionCall) + callStack->CallStack.removeFunctionCall(~functionCall) let trace = Trace.Tcall(call, stateAfterCall.progress) {...stateAfterCall, trace: trace} } @@ -1175,7 +1175,7 @@ module Eval = { ): State.t => switch command { | Call(FunctionCall(functionCall), loc) => - functionCall |> runFunctionCall( + functionCall->runFunctionCall( ~cache, ~callStack, ~functionArgs, @@ -1204,11 +1204,11 @@ module Eval = { | list{} => state | list{c, ...nextCommands} => let state1 = - c |> run(~cache, ~callStack, ~functionArgs, ~functionTable, ~madeProgressOn, ~state) + c->run(~cache, ~callStack, ~functionArgs, ~functionTable, ~madeProgressOn, ~state) let (madeProgressOn, callStack) = switch state1.progress { | Progress => // look for infinite loops in the rest of the sequence, remembering what has made progress ( - FunctionCallSet.union(madeProgressOn, callStack |> CallStack.toSet), + FunctionCallSet.union(madeProgressOn, callStack->CallStack.toSet), CallStack.create(), ) | NoProgress => (madeProgressOn, callStack) @@ -1221,8 +1221,8 @@ module Eval = { let stateNoTrace = {...state, trace: Trace.empty} // the commands could be executed in any order: progess if any one does let states = - commands |> List.map(c => - c |> run( + commands->List.map(c => + c->run( ~cache, ~callStack, ~functionArgs, @@ -1231,14 +1231,14 @@ module Eval = { ~state=stateNoTrace, ) ) - State.seq(state, states |> State.unorderedSequence) + State.seq(state, states->State.unorderedSequence) | Nondet(commands) => let stateNoTrace = {...state, trace: Trace.empty} // the commands could be executed in any order: progess if any one does let states = - commands |> List.map(c => - c |> run( + commands->List.map(c => + c->run( ~cache, ~callStack, ~functionArgs, @@ -1247,11 +1247,11 @@ module Eval = { ~state=stateNoTrace, ) ) - State.seq(state, states |> State.nondet) + State.seq(state, states->State.nondet) | SwitchOption({functionCall, loc, some, none}) => let stateAfterCall = - functionCall |> runFunctionCall( + functionCall->runFunctionCall( ~cache, ~callStack, ~functionArgs, @@ -1262,7 +1262,7 @@ module Eval = { ) switch stateAfterCall.valuesOpt { | None => - Command.nondet(list{some, none}) |> run( + Command.nondet(list{some, none})->run( ~cache, ~callStack, ~functionArgs, @@ -1275,7 +1275,7 @@ module Eval = { switch progressOpt { | None => State.init(~progress=Progress, ()) | Some(progress) => - c |> run( + c->run( ~cache, ~callStack, ~functionArgs, @@ -1284,8 +1284,8 @@ module Eval = { ~state=State.init(~progress, ()), ) } - let stateNone = values |> Values.getNone |> runOpt(none) - let stateSome = values |> Values.getSome |> runOpt(some) + let stateNone = values->Values.getNone->runOpt(none) + let stateSome = values->Values.getSome->runOpt(some) State.seq(stateAfterCall, State.nondet(list{stateSome, stateNone})) } } @@ -1298,8 +1298,8 @@ module Eval = { let callStack = CallStack.create() let functionArgs = FunctionArgs.empty let functionCall = FunctionCall.noArgs(functionName) - callStack |> CallStack.addFunctionCall(~functionCall, ~pos) - let functionDefinition = functionTable |> FunctionTable.getFunctionDefinition(~functionName) + callStack->CallStack.addFunctionCall(~functionCall, ~pos) + let functionDefinition = functionTable->FunctionTable.getFunctionDefinition(~functionName) if functionDefinition.kind != Kind.empty { Stats.logHygieneParametric(~functionName, ~loc) } else { @@ -1308,7 +1308,7 @@ module Eval = { | None => assert(false) } let state = - body |> run( + body->run( ~cache, ~callStack, ~functionArgs, @@ -1316,28 +1316,28 @@ module Eval = { ~madeProgressOn=FunctionCallSet.empty, ~state=State.init(), ) - cache |> updateCache(~functionCall, ~loc, ~state) + cache->updateCache(~functionCall, ~loc, ~state) } } } let progressFunctionsFromAttributes = attributes => { - let lidToString = lid => lid |> Longident.flatten |> String.concat(".") + let lidToString = lid => lid->Longident.flatten->String.concat(".") let isProgress = \"="("progress") - if attributes |> Annotation.hasAttribute(isProgress) { + if attributes->Annotation.hasAttribute(isProgress) { Some( - switch attributes |> Annotation.getAttributePayload(isProgress) { + switch attributes->Annotation.getAttributePayload(isProgress) { | None => list{} | Some(IdentPayload(lid)) => list{lidToString(lid)} | Some(TuplePayload(l)) => l - |> List.filter(x => + ->List.filter(x => switch x { | Annotation.IdentPayload(_) => true | _ => false } ) - |> List.map(x => + ->List.map(x => switch x { | Annotation.IdentPayload(lid) => lidToString(lid) | _ => assert(false) @@ -1356,7 +1356,7 @@ let traverseAst = (~valueBindingsTable) => { let value_bindings = (self: Tast_mapper.mapper, (recFlag, valueBindings)) => { // Update the table of value bindings for variables - valueBindings |> List.iter((vb: Typedtree.value_binding) => + valueBindings->List.iter((vb: Typedtree.value_binding) => switch vb.vb_pat.pat_desc { | Tpat_var(id, {loc: {loc_start: pos}}) => let callees = Lazy.from_fun(() => FindFunctionsCalled.findCallees(vb.vb_expr)) @@ -1369,7 +1369,7 @@ let traverseAst = (~valueBindingsTable) => { (StringSet.empty, list{}) } else { let (progressFunctions0, functionsToAnalyze0) = - valueBindings |> List.fold_left( + valueBindings->List.fold_left( ((progressFunctions, functionsToAnalyze), valueBinding: Typedtree.value_binding) => switch progressFunctionsFromAttributes(valueBinding.vb_attributes) { | None => (progressFunctions, functionsToAnalyze) @@ -1386,7 +1386,7 @@ let traverseAst = (~valueBindingsTable) => { }, (StringSet.empty, list{}), ) - (progressFunctions0, functionsToAnalyze0 |> List.rev) + (progressFunctions0, functionsToAnalyze0->List.rev) } if functionsToAnalyze != list{} { @@ -1398,8 +1398,8 @@ let traverseAst = (~valueBindingsTable) => { | Tpat_var(id, _) => list{Ident.name(id), ...defs} | _ => defs } - , list{}, valueBindings) |> List.rev - let recursiveDefinitions = recursiveFunctions |> List.map(functionName => ( + , list{}, valueBindings)->List.rev + let recursiveDefinitions = recursiveFunctions->List.map(functionName => ( functionName, { let (_pos, e, _set) = Hashtbl.find(valueBindingsTable, functionName) @@ -1407,27 +1407,27 @@ let traverseAst = (~valueBindingsTable) => { }, )) - recursiveDefinitions |> List.iter(((functionName, _body)) => - functionTable |> FunctionTable.addFunction(~functionName) + recursiveDefinitions->List.iter(((functionName, _body)) => + functionTable->FunctionTable.addFunction(~functionName) ) - recursiveDefinitions |> List.iter(((_, body)) => - body |> ExtendFunctionTable.run(~functionTable, ~progressFunctions, ~valueBindingsTable) + recursiveDefinitions->List.iter(((_, body)) => + body->ExtendFunctionTable.run(~functionTable, ~progressFunctions, ~valueBindingsTable) ) - recursiveDefinitions |> List.iter(((_, body)) => - body |> CheckExpressionWellFormed.run(~functionTable, ~valueBindingsTable) + recursiveDefinitions->List.iter(((_, body)) => + body->CheckExpressionWellFormed.run(~functionTable, ~valueBindingsTable) ) - functionTable |> Hashtbl.iter(( + functionTable->Hashtbl.iter(( functionName, functionDefinition: FunctionTable.functionDefinition, ) => if functionDefinition.body == None { let (_pos, body, _) = Hashtbl.find(valueBindingsTable, functionName) - functionTable |> FunctionTable.addBody( + functionTable->FunctionTable.addBody( ~body=Some( - body |> Compile.expression( + body->Compile.expression( ~ctx={ currentFunctionName: functionName, functionTable: functionTable, @@ -1446,13 +1446,13 @@ let traverseAst = (~valueBindingsTable) => { } let cache = Eval.createCache() - functionsToAnalyze |> List.iter(((functionName, loc)) => - functionName |> Eval.analyzeFunction(~cache, ~functionTable, ~loc) + functionsToAnalyze->List.iter(((functionName, loc)) => + functionName->Eval.analyzeFunction(~cache, ~functionTable, ~loc) ) Stats.newRecursiveFunctions(~numFunctions=Hashtbl.length(functionTable)) } - valueBindings |> List.iter(valueBinding => super.value_binding(self, valueBinding) |> ignore) + valueBindings->List.iter(valueBinding => super.value_binding(self, valueBinding)->ignore) (recFlag, valueBindings) } @@ -1465,7 +1465,7 @@ let processStructure = (structure: Typedtree.structure) => { Stats.newFile() let valueBindingsTable = Hashtbl.create(1) let traverseAst = traverseAst(~valueBindingsTable) - structure |> traverseAst.structure(traverseAst) |> ignore + structure->traverseAst.structure(traverseAst)->ignore } let reportResults = () => diff --git a/tests/syntax_tests/data/idempotency/genType/src/Config_.res b/tests/syntax_tests/data/idempotency/genType/src/Config_.res index bb7887423a..ceb1ab42fe 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/Config_.res +++ b/tests/syntax_tests/data/idempotency/genType/src/Config_.res @@ -91,7 +91,7 @@ let getBsCurryPath = (~config) => let getBool = (s, json) => switch json { | Ext_json_types.Obj({map}) => - switch map |> String_map.find_opt(s) { + switch map->String_map.find_opt(s) { | Some(True(_)) => Some(true) | Some(False(_)) => Some(false) | _ => None @@ -102,7 +102,7 @@ let getBool = (s, json) => let getString = (s, json) => switch json { | Ext_json_types.Obj({map}) => - switch map |> String_map.find_opt(s) { + switch map->String_map.find_opt(s) { | Some(Str({str})) => str | _ => "" } @@ -112,7 +112,7 @@ let getString = (s, json) => let getStringOption = (s, json) => switch json { | Ext_json_types.Obj({map}) => - switch map |> String_map.find_opt(s) { + switch map->String_map.find_opt(s) { | Some(Str({str})) => Some(str) | _ => None } @@ -123,9 +123,9 @@ let getShims = json => { let shims = ref(list{}) switch json { | Ext_json_types.Obj({map}) => - switch map |> String_map.find_opt("shims") { + switch map->String_map.find_opt("shims") { | Some(Ext_json_types.Obj({map: shimsMap})) => - shimsMap |> String_map.iter((fromModule, toModule) => + shimsMap->String_map.iter((fromModule, toModule) => switch toModule { | Ext_json_types.Str({str}) => shims := list{(fromModule, str), ...shims.contents} | _ => () @@ -133,10 +133,10 @@ let getShims = json => { ) | Some(Arr({content})) => /* To be deprecated: array of strings */ - content |> Array.iter(x => + content->Array.iter(x => switch x { | Ext_json_types.Str({str}) => - let fromTo = Str.split(Str.regexp("="), str) |> Array.of_list + let fromTo = Str.split(Str.regexp("="), str)->Array.of_list assert (Array.length(fromTo) === 2) shims := list{(fromTo[0], fromTo[1]), ...shims.contents} | _ => () @@ -152,8 +152,8 @@ let getShims = json => { let getDebug = json => switch json { | Ext_json_types.Obj({map}) => - switch map |> String_map.find_opt("debug") { - | Some(Ext_json_types.Obj({map})) => map |> String_map.iter(Debug.setItem) + switch map->String_map.find_opt("debug") { + | Some(Ext_json_types.Obj({map})) => map->String_map.iter(Debug.setItem) | _ => () } | _ => () @@ -161,22 +161,22 @@ let getDebug = json => let readConfig = (~bsVersion, ~getConfigFile, ~getBsConfigFile, ~namespace) => { let fromJson = json => { - let languageString = json |> getString("language") - let moduleString = json |> getString("module") - let importPathString = json |> getString("importPath") - let reasonReactPathString = json |> getString("reasonReactPath") - let fileHeader = json |> getStringOption("fileHeader") - let bsBlockPathString = json |> getString("bsBlockPath") - let bsCurryPathString = json |> getString("bsCurryPath") - let exportInterfacesBool = json |> getBool("exportInterfaces") - let generatedFileExtensionStringOption = json |> getStringOption("generatedFileExtension") - let propTypesBool = json |> getBool("propTypes") - let shimsMap = json |> getShims |> List.fold_left((map, (fromModule, toModule)) => { - let moduleName: ModuleName.t = fromModule |> ModuleName.fromStringUnsafe - let shimModuleName = toModule |> ModuleName.fromStringUnsafe + let languageString = json->getString("language") + let moduleString = json->getString("module") + let importPathString = json->getString("importPath") + let reasonReactPathString = json->getString("reasonReactPath") + let fileHeader = json->getStringOption("fileHeader") + let bsBlockPathString = json->getString("bsBlockPath") + let bsCurryPathString = json->getString("bsCurryPath") + let exportInterfacesBool = json->getBool("exportInterfaces") + let generatedFileExtensionStringOption = json->getStringOption("generatedFileExtension") + let propTypesBool = json->getBool("propTypes") + let shimsMap = json->getShims->List.fold_left((map, (fromModule, toModule)) => { + let moduleName: ModuleName.t = fromModule->ModuleName.fromStringUnsafe + let shimModuleName = toModule->ModuleName.fromStringUnsafe ModuleNameMap.add(moduleName, shimModuleName, map) }, ModuleNameMap.empty) - json |> getDebug + json->getDebug let language = switch languageString { | "typescript" => TypeScript | "untyped" => Untyped @@ -217,11 +217,11 @@ let readConfig = (~bsVersion, ~getConfigFile, ~getBsConfigFile, ~namespace) => { let bsVersion = switch bsVersion { | None => (0, 0, 0) | Some(s) => - switch s |> Str.split(Str.regexp(Str.quote("."))) { + switch s->Str.split(Str.regexp(Str.quote("."))) { | list{x1, x2, x3, ..._} => let v1 = int_of_string(x1) let v2 = int_of_string(x2) - let v3 = switch x3 |> Str.split(Str.regexp("-")) { + let v3 = switch x3->Str.split(Str.regexp("-")) { | list{x3, ..._} => int_of_string(x3) | _ => 0 } @@ -254,7 +254,7 @@ let readConfig = (~bsVersion, ~getConfigFile, ~getBsConfigFile, ~namespace) => { languageString, moduleString, importPathString, - shimsMap |> ModuleNameMap.cardinal, + shimsMap->ModuleNameMap.cardinal, v1, v2, v3, @@ -291,18 +291,18 @@ let readConfig = (~bsVersion, ~getConfigFile, ~getBsConfigFile, ~namespace) => { let fromBsConfig = json => switch json { | Ext_json_types.Obj({map}) => - let config = switch map |> String_map.find_opt("gentypeconfig") { - | Some(jsonGenFlowConfig) => jsonGenFlowConfig |> fromJson + let config = switch map->String_map.find_opt("gentypeconfig") { + | Some(jsonGenFlowConfig) => jsonGenFlowConfig->fromJson | _ => default } - let config = switch map |> String_map.find_opt("namespace") { + let config = switch map->String_map.find_opt("namespace") { | Some(True(_)) => {...config, namespace: namespace} | _ => config } - let config = switch map |> String_map.find_opt("bs-dependencies") { + let config = switch map->String_map.find_opt("bs-dependencies") { | Some(Arr({content})) => let strings = ref(list{}) - content |> Array.iter(x => + content->Array.iter(x => switch x { | Ext_json_types.Str({str}) => strings := list{str, ...strings.contents} | _ => () @@ -311,7 +311,7 @@ let readConfig = (~bsVersion, ~getConfigFile, ~getBsConfigFile, ~namespace) => { {...config, bsDependencies: strings.contents} | _ => config } - let config = switch map |> String_map.find_opt("sources") { + let config = switch map->String_map.find_opt("sources") { | Some(sourceItem) => {...config, sources: Some(sourceItem)} | _ => config } @@ -320,13 +320,13 @@ let readConfig = (~bsVersion, ~getConfigFile, ~getBsConfigFile, ~namespace) => { } switch getConfigFile() { | Some(configFile) => - try configFile |> Ext_json_parse.parse_json_from_file |> fromJson catch { + try configFile->Ext_json_parse.parse_json_from_file->fromJson catch { | _ => default } | None => switch getBsConfigFile() { | Some(bsConfigFile) => - try bsConfigFile |> Ext_json_parse.parse_json_from_file |> fromBsConfig catch { + try bsConfigFile->Ext_json_parse.parse_json_from_file->fromBsConfig catch { | _ => default } | None => default diff --git a/tests/syntax_tests/data/idempotency/genType/src/Converter.res b/tests/syntax_tests/data/idempotency/genType/src/Converter.res index 7a452df283..e697563df3 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/Converter.res +++ b/tests/syntax_tests/data/idempotency/genType/src/Converter.res @@ -48,20 +48,20 @@ let rec toString = converter => ((uncurried ? "Uncurried" : "") ++ ("(" ++ ((argConverters - |> List.map(groupedArgConverter => + ->List.map(groupedArgConverter => switch groupedArgConverter { | ArgConverter(conv) => "(" ++ ("_" ++ (":" ++ (toString(conv) ++ ")"))) | GroupConverter(groupConverters) => "{|" ++ ((groupConverters - |> List.map(((s, optional, argConverter)) => + ->List.map(((s, optional, argConverter)) => s ++ ((optional == Optional ? "?" : "") ++ (":" ++ toString(argConverter))) ) - |> String.concat(", ")) ++ + ->String.concat(", ")) ++ "|}") } ) - |> String.concat(", ")) ++ + ->String.concat(", ")) ++ (" -> " ++ (toString(retConverter) ++ ")"))))) | IdentC => "id" @@ -77,28 +77,28 @@ let rec toString = converter => "{" ++ (dot ++ ((fieldsC - |> List.map(({lblJS, lblRE, c}) => + ->List.map(({lblJS, lblRE, c}) => (lblJS == lblRE ? lblJS : "(" ++ (lblJS ++ ("/" ++ (lblRE ++ ")")))) ++ (":" ++ - (c |> toString)) + (c->toString)) ) - |> String.concat(", ")) ++ "}")) + ->String.concat(", ")) ++ "}")) | OptionC(c) => "option(" ++ (toString(c) ++ ")") | PromiseC(c) => "promise(" ++ (toString(c) ++ ")") | TupleC(innerTypesC) => - "[" ++ ((innerTypesC |> List.map(toString) |> String.concat(", ")) ++ "]") + "[" ++ ((innerTypesC->List.map(toString)->String.concat(", ")) ++ "]") | VariantC({noPayloads, withPayload}) => "variant(" ++ ((\"@"( - noPayloads |> List.map(case => case.labelJS |> labelJSToString), - withPayload |> List.map(((case, numArgs, c)) => - (case.labelJS |> labelJSToString) ++ + noPayloads->List.map(case => case.labelJS->labelJSToString), + withPayload->List.map(((case, numArgs, c)) => + (case.labelJS->labelJSToString) ++ (":" ++ - (string_of_int(numArgs) ++ (":" ++ (c |> toString)))) + (string_of_int(numArgs) ++ (":" ++ (c->toString)))) ), - ) |> String.concat(", ")) ++ + )->String.concat(", ")) ++ ")") } @@ -107,7 +107,7 @@ let typeGetConverterNormalized = (~config, ~inline, ~lookupId, ~typeNameIsInterf let expandOneLevel = type_ => switch type_ { | Ident({builtin: false, name}) => - switch name |> lookupId { + switch name->lookupId { | (t: CodeItem.exportTypeItem) => t.type_ | exception Not_found => type_ } @@ -117,15 +117,15 @@ let typeGetConverterNormalized = (~config, ~inline, ~lookupId, ~typeNameIsInterf let normalized_ = type_ switch type_ { | Array(t, mutable_) => - let (tConverter, tNormalized) = t |> visit(~visited) + let (tConverter, tNormalized) = t->visit(~visited) (ArrayC(tConverter), Array(tNormalized, mutable_)) | Function({argTypes, componentName, retType, typeVars, uncurried} as function_) => - let argConverted = argTypes |> List.map(argTypeToGroupedArgConverter(~visited)) - let argConverters = argConverted |> List.map(fst) - let (retConverter, retNormalized) = retType |> visit(~visited) + let argConverted = argTypes->List.map(argTypeToGroupedArgConverter(~visited)) + let argConverters = argConverted->List.map(fst) + let (retConverter, retNormalized) = retType->visit(~visited) let isHook = switch argTypes { - | list{{aType: Object(_)}} => retType |> EmitType.isTypeReactElement(~config) + | list{{aType: Object(_)}} => retType->EmitType.isTypeReactElement(~config) | _ => false } ( @@ -139,7 +139,7 @@ let typeGetConverterNormalized = (~config, ~inline, ~lookupId, ~typeNameIsInterf }), Function({ ...function_, - argTypes: argConverted |> List.map(snd), + argTypes: argConverted->List.map(snd), retType: retNormalized, }), ) @@ -150,12 +150,12 @@ let typeGetConverterNormalized = (~config, ~inline, ~lookupId, ~typeNameIsInterf | Ident({builtin: true}) => (IdentC, normalized_) | Ident({builtin: false, name, typeArgs}) => - if visited |> StringSet.mem(name) { + if visited->StringSet.mem(name) { circular := name (IdentC, normalized_) } else { - let visited = visited |> StringSet.add(name) - switch name |> lookupId { + let visited = visited->StringSet.add(name) + switch name->lookupId { | {annotation: GenTypeOpaque} => (IdentC, normalized_) | {annotation: NoGenType} => (IdentC, normalized_) | {typeVars, type_} => @@ -164,15 +164,15 @@ let typeGetConverterNormalized = (~config, ~inline, ~lookupId, ~typeNameIsInterf } let f = typeVar => - switch pairs |> List.find(((typeVar1, _)) => typeVar == typeVar1) { + switch pairs->List.find(((typeVar1, _)) => typeVar == typeVar1) { | (_, typeArgument) => Some(typeArgument) | exception Not_found => None } - let (converter, inlined) = type_ |> TypeVars.substitute(~f) |> visit(~visited) + let (converter, inlined) = type_->TypeVars.substitute(~f)->visit(~visited) (converter, inline ? inlined : normalized_) | exception Not_found => if inline { - let typeArgs = typeArgs |> List.map(t => t |> visit(~visited) |> snd) + let typeArgs = typeArgs->List.map(t => t->visit(~visited)->snd) (IdentC, Ident({builtin: false, name: name, typeArgs: typeArgs})) } else { (IdentC, normalized_) @@ -181,23 +181,23 @@ let typeGetConverterNormalized = (~config, ~inline, ~lookupId, ~typeNameIsInterf } | Null(t) => - let (tConverter, tNormalized) = t |> visit(~visited) + let (tConverter, tNormalized) = t->visit(~visited) (NullableC(tConverter), Null(tNormalized)) | Nullable(t) => - let (tConverter, tNormalized) = t |> visit(~visited) + let (tConverter, tNormalized) = t->visit(~visited) (NullableC(tConverter), Nullable(tNormalized)) /* | Object(closedFlag, fields) => */ /* let fieldsConverted = */ /* fields */ - /* |> List.map(({type_} as field) => */ - /* (field, type_ |> visit(~visited)) */ + /*->List.map(({type_} as field) => */ + /* (field, type_->visit(~visited)) */ /* ); */ /* ( */ /* ObjectC( */ /* fieldsConverted */ - /* |> List.map((({nameJS, nameRE, optional}, (converter, _))) => */ + /*->List.map((({nameJS, nameRE, optional}, (converter, _))) => */ /* { */ /* lblJS: nameJS, */ /* lblRE: nameRE, */ @@ -208,27 +208,27 @@ let typeGetConverterNormalized = (~config, ~inline, ~lookupId, ~typeNameIsInterf /* Object( */ /* closedFlag, */ /* fieldsConverted */ - /* |> List.map(((field, (_, tNormalized))) => */ + /*->List.map(((field, (_, tNormalized))) => */ /* {...field, type_: tNormalized} */ /* ), */ /* ), */ /* ); */ | Option(t) => - let (tConverter, tNormalized) = t |> visit(~visited) + let (tConverter, tNormalized) = t->visit(~visited) (OptionC(tConverter), Option(tNormalized)) | Promise(t) => - let (tConverter, tNormalized) = t |> visit(~visited) + let (tConverter, tNormalized) = t->visit(~visited) (PromiseC(tConverter), Promise(tNormalized)) | Record(fields) => let fieldsConverted = - fields |> List.map(({type_} as field) => (field, type_ |> visit(~visited))) + fields->List.map(({type_} as field) => (field, type_->visit(~visited))) /* ( */ /* RecordC( */ /* fieldsConverted */ - /* |> List.map((({nameJS, nameRE, optional}, (converter, _))) => */ + /*->List.map((({nameJS, nameRE, optional}, (converter, _))) => */ /* { */ /* lblJS: nameJS, */ /* lblRE: nameRE, */ @@ -238,27 +238,27 @@ let typeGetConverterNormalized = (~config, ~inline, ~lookupId, ~typeNameIsInterf /* ), */ /* Record( */ /* fieldsConverted */ - /* |> List.map(((field, (_, tNormalized))) => */ + /*->List.map(((field, (_, tNormalized))) => */ /* {...field, type_: tNormalized} */ /* ), */ /* ), */ /* ); */ | Tuple(innerTypes) => - let (innerConversions, normalizedList) = innerTypes |> List.map(visit(~visited)) |> List.split + let (innerConversions, normalizedList) = innerTypes->List.map(visit(~visited))->List.split (TupleC(innerConversions), Tuple(normalizedList)) | TypeVar(_) => (IdentC, normalized_) | Variant(variant) => - let (withPayload, normalized, unboxed) = switch variant.payloads |> List.map((( + let (withPayload, normalized, unboxed) = switch variant.payloads->List.map((( case, numArgs, t, - )) => (case, numArgs, t |> visit(~visited))) { + )) => (case, numArgs, t->visit(~visited))) { | list{} => (list{}, normalized_, variant.unboxed) | list{(case, numArgs, (converter, tNormalized))} => - let unboxed = tNormalized |> expandOneLevel |> typeIsObject + let unboxed = tNormalized->expandOneLevel->typeIsObject let normalized = Variant({ ...variant, payloads: list{(case, numArgs, tNormalized)}, @@ -267,14 +267,14 @@ let typeGetConverterNormalized = (~config, ~inline, ~lookupId, ~typeNameIsInterf (list{(case, numArgs, converter)}, normalized, unboxed) | list{_, _, ..._} as withPayloadConverted => let withPayloadNormalized = - withPayloadConverted |> List.map(((case, numArgs, (_, tNormalized))) => ( + withPayloadConverted->List.map(((case, numArgs, (_, tNormalized))) => ( case, numArgs, tNormalized, )) let normalized = Variant({...variant, payloads: withPayloadNormalized}) ( - withPayloadConverted |> List.map(((case, numArgs, (converter, _))) => ( + withPayloadConverted->List.map(((case, numArgs, (converter, _))) => ( case, numArgs, converter, @@ -297,12 +297,12 @@ let typeGetConverterNormalized = (~config, ~inline, ~lookupId, ~typeNameIsInterf switch aType { | GroupOfLabeledArgs(fields) => let fieldsConverted = - fields |> List.map(({type_} as field) => (field, type_ |> visit(~visited))) + fields->List.map(({type_} as field) => (field, type_->visit(~visited))) let tNormalized = GroupOfLabeledArgs( - fieldsConverted |> List.map(((field, (_, t))) => {...field, type_: t}), + fieldsConverted->List.map(((field, (_, t))) => {...field, type_: t}), ) let converter = GroupConverter( - fieldsConverted |> List.map((({nameJS, optional}, (converter, _))) => ( + fieldsConverted->List.map((({nameJS, optional}, (converter, _))) => ( nameJS, optional, converter, @@ -310,18 +310,18 @@ let typeGetConverterNormalized = (~config, ~inline, ~lookupId, ~typeNameIsInterf ) (converter, {aName: aName, aType: tNormalized}) | _ => - let (converter, tNormalized) = aType |> visit(~visited) + let (converter, tNormalized) = aType->visit(~visited) let converter = ArgConverter(converter) (converter, {aName: aName, aType: tNormalized}) } - let (converter, normalized) = type0 |> visit(~visited=StringSet.empty) + let (converter, normalized) = type0->visit(~visited=StringSet.empty) let finalConverter = circular.contents != "" ? CircularC(circular.contents, converter) : converter if Debug.converter.contents { Log_.item( "Converter type0:%s converter:%s\n", - type0 |> EmitType.typeToString(~config, ~typeNameIsInterface), - finalConverter |> toString, + type0->EmitType.typeToString(~config, ~typeNameIsInterface), + finalConverter->toString, ) } (finalConverter, normalized) @@ -329,80 +329,80 @@ let typeGetConverterNormalized = (~config, ~inline, ~lookupId, ~typeNameIsInterf let typeGetConverter = (~config, ~lookupId, ~typeNameIsInterface, type_) => type_ - |> typeGetConverterNormalized(~config, ~inline=false, ~lookupId, ~typeNameIsInterface) - |> fst + ->typeGetConverterNormalized(~config, ~inline=false, ~lookupId, ~typeNameIsInterface) + ->fst let typeGetNormalized = (~config, ~inline, ~lookupId, ~typeNameIsInterface, type_) => - type_ |> typeGetConverterNormalized(~config, ~inline, ~lookupId, ~typeNameIsInterface) |> snd + type_->typeGetConverterNormalized(~config, ~inline, ~lookupId, ~typeNameIsInterface)->snd let rec converterIsIdentity = (~toJS, converter) => switch converter { - | ArrayC(c) => c |> converterIsIdentity(~toJS) + | ArrayC(c) => c->converterIsIdentity(~toJS) - | CircularC(_, c) => c |> converterIsIdentity(~toJS) + | CircularC(_, c) => c->converterIsIdentity(~toJS) | FunctionC({argConverters, retConverter, uncurried}) => - retConverter |> converterIsIdentity(~toJS) && - ((!toJS || (uncurried || argConverters |> List.length <= 1)) && - argConverters |> List.for_all(groupedArgConverter => + retConverter->converterIsIdentity(~toJS) && + ((!toJS || (uncurried || argConverters->List.length <= 1)) && + argConverters->List.for_all(groupedArgConverter => switch groupedArgConverter { - | ArgConverter(argConverter) => argConverter |> converterIsIdentity(~toJS=!toJS) + | ArgConverter(argConverter) => argConverter->converterIsIdentity(~toJS=!toJS) | GroupConverter(_) => false } )) | IdentC => true - | NullableC(c) => c |> converterIsIdentity(~toJS) + | NullableC(c) => c->converterIsIdentity(~toJS) | ObjectC(fieldsC) => - fieldsC |> List.for_all(({lblJS, lblRE, c}) => + fieldsC->List.for_all(({lblJS, lblRE, c}) => lblJS == lblRE && switch c { - | OptionC(c1) => c1 |> converterIsIdentity(~toJS) - | _ => c |> converterIsIdentity(~toJS) + | OptionC(c1) => c1->converterIsIdentity(~toJS) + | _ => c->converterIsIdentity(~toJS) } ) | OptionC(c) => if toJS { - c |> converterIsIdentity(~toJS) + c->converterIsIdentity(~toJS) } else { false } - | PromiseC(c) => c |> converterIsIdentity(~toJS) + | PromiseC(c) => c->converterIsIdentity(~toJS) | RecordC(_) => false - | TupleC(innerTypesC) => innerTypesC |> List.for_all(converterIsIdentity(~toJS)) + | TupleC(innerTypesC) => innerTypesC->List.for_all(converterIsIdentity(~toJS)) | VariantC(_) => false } let rec apply = (~config, ~converter, ~indent, ~nameGen, ~toJS, ~variantTables, value) => switch converter { - | _ if converter |> converterIsIdentity(~toJS) => value + | _ if converter->converterIsIdentity(~toJS) => value | ArrayC(c) => - let x = "ArrayItem" |> EmitText.name(~nameGen) + let x = "ArrayItem"->EmitText.name(~nameGen) value ++ (".map(function _element(" ++ - ((x |> EmitType.ofTypeAny(~config)) ++ + ((x->EmitType.ofTypeAny(~config)) ++ (") { return " ++ - ((x |> apply(~config, ~converter=c, ~indent, ~nameGen, ~toJS, ~variantTables)) ++ "})")))) + ((x->apply(~config, ~converter=c, ~indent, ~nameGen, ~toJS, ~variantTables)) ++ "})")))) | CircularC(s, c) => value - |> EmitText.addComment( + ->EmitText.addComment( ~comment="WARNING: circular type " ++ (s ++ ". Only shallow converter applied."), ) - |> apply(~config, ~converter=c, ~indent, ~nameGen, ~toJS, ~variantTables) + ->apply(~config, ~converter=c, ~indent, ~nameGen, ~toJS, ~variantTables) | FunctionC({argConverters, componentName, isHook, retConverter, typeVars, uncurried}) => let resultName = EmitText.resultName(~nameGen) - let indent1 = indent |> Indent.more - let indent2 = indent1 |> Indent.more + let indent1 = indent->Indent.more + let indent2 = indent1->Indent.more let mkReturn = x => "const " ++ @@ -412,7 +412,7 @@ let rec apply = (~config, ~converter, ~indent, ~nameGen, ~toJS, ~variantTables, (";" ++ (Indent.break(~indent=indent1) ++ ("return " ++ - (resultName |> apply( + (resultName->apply( ~config, ~converter=retConverter, ~indent=indent2, @@ -424,12 +424,12 @@ let rec apply = (~config, ~converter, ~indent, ~nameGen, ~toJS, ~variantTables, let convertArg = (i, groupedArgConverter) => switch groupedArgConverter { | ArgConverter(argConverter) => - let varName = i + 1 |> EmitText.argi(~nameGen) + let varName = i + 1->EmitText.argi(~nameGen) let notToJS = !toJS ( list{varName}, list{ - varName |> apply( + varName->apply( ~config, ~converter=argConverter, ~indent=indent2, @@ -442,15 +442,15 @@ let rec apply = (~config, ~converter, ~indent, ~nameGen, ~toJS, ~variantTables, | GroupConverter(groupConverters) => let notToJS = !toJS if toJS { - let varName = i + 1 |> EmitText.argi(~nameGen) + let varName = i + 1->EmitText.argi(~nameGen) ( list{varName}, - groupConverters |> List.map(((label, optional, argConverter)) => + groupConverters->List.map(((label, optional, argConverter)) => varName - |> EmitText.fieldAccess(~label) - |> apply( + ->EmitText.fieldAccess(~label) + ->apply( ~config, - ~converter=optional == Optional && !(argConverter |> converterIsIdentity(~toJS)) + ~converter=optional == Optional && !(argConverter->converterIsIdentity(~toJS)) ? OptionC(argConverter) : argConverter, ~indent=indent2, @@ -462,17 +462,17 @@ let rec apply = (~config, ~converter, ~indent, ~nameGen, ~toJS, ~variantTables, ) } else { let varNames = - groupConverters |> List.map(((s, _optional, _argConverter)) => - s |> EmitText.arg(~nameGen) + groupConverters->List.map(((s, _optional, _argConverter)) => + s->EmitText.arg(~nameGen) ) - let varNamesArr = varNames |> Array.of_list + let varNamesArr = varNames->Array.of_list let fieldValues = groupConverters - |> List.mapi((i, (s, _optional, argConverter)) => + ->List.mapi((i, (s, _optional, argConverter)) => s ++ (":" ++ - (varNamesArr[i] |> apply( + (varNamesArr[i]->apply( ~config, ~converter=argConverter, ~indent=indent2, @@ -481,7 +481,7 @@ let rec apply = (~config, ~converter, ~indent, ~nameGen, ~toJS, ~variantTables, ~variantTables, ))) ) - |> String.concat(", ") + ->String.concat(", ") (varNames, list{"{" ++ (fieldValues ++ "}")}) } } @@ -495,7 +495,7 @@ let rec apply = (~config, ~converter, ~indent, ~nameGen, ~toJS, ~variantTables, } let (declareProps, args) = switch bodyArgs { | list{props} if isHook => - let propsName = "$props" |> EmitText.name(~nameGen) + let propsName = "$props"->EmitText.name(~nameGen) ( Indent.break(~indent=indent1) ++ ("const " ++ (propsName ++ (" = " ++ (props ++ ";")))), list{value, propsName}, @@ -506,13 +506,13 @@ let rec apply = (~config, ~converter, ~indent, ~nameGen, ~toJS, ~variantTables, declareProps ++ (Indent.break(~indent=indent1) ++ - (functionName |> EmitText.funCall(~args, ~useCurry) |> mkReturn)) + (functionName->EmitText.funCall(~args, ~useCurry)->mkReturn)) } - let convertedArgs = argConverters |> List.mapi(convertArg) - let args = convertedArgs |> List.map(fst) |> List.concat - let funParams = args |> List.map(v => v |> EmitType.ofTypeAny(~config)) - let bodyArgs = convertedArgs |> List.map(snd) |> List.concat + let convertedArgs = argConverters->List.mapi(convertArg) + let args = convertedArgs->List.map(fst)->List.concat + let funParams = args->List.map(v => v->EmitType.ofTypeAny(~config)) + let bodyArgs = convertedArgs->List.map(snd)->List.concat EmitText.funDef( ~bodyArgs, ~functionName=componentName, @@ -534,32 +534,32 @@ let rec apply = (~config, ~converter, ~indent, ~nameGen, ~toJS, ~variantTables, (" == null ? " ++ (value ++ (" : " ++ - (value |> apply(~config, ~converter=c, ~indent, ~nameGen, ~toJS, ~variantTables))))), + (value->apply(~config, ~converter=c, ~indent, ~nameGen, ~toJS, ~variantTables))))), }) | ObjectC(fieldsC) => let simplifyFieldConverted = fieldConverter => switch fieldConverter { - | OptionC(converter1) if converter1 |> converterIsIdentity(~toJS) => IdentC + | OptionC(converter1) if converter1->converterIsIdentity(~toJS) => IdentC | _ => fieldConverter } let fieldValues = fieldsC - |> List.map(({lblJS, lblRE, c: fieldConverter}) => + ->List.map(({lblJS, lblRE, c: fieldConverter}) => (toJS ? lblJS : lblRE) ++ (":" ++ (value - |> EmitText.fieldAccess(~label=toJS ? lblRE : lblJS) - |> apply( + ->EmitText.fieldAccess(~label=toJS ? lblRE : lblJS) + ->apply( ~config, - ~converter=fieldConverter |> simplifyFieldConverted, + ~converter=fieldConverter->simplifyFieldConverted, ~indent, ~nameGen, ~toJS, ~variantTables, ))) ) - |> String.concat(", ") + ->String.concat(", ") "{" ++ (fieldValues ++ "}") | OptionC(c) => @@ -569,82 +569,82 @@ let rec apply = (~config, ~converter, ~indent, ~nameGen, ~toJS, ~variantTables, (" == null ? " ++ (value ++ (" : " ++ - (value |> apply(~config, ~converter=c, ~indent, ~nameGen, ~toJS, ~variantTables))))), + (value->apply(~config, ~converter=c, ~indent, ~nameGen, ~toJS, ~variantTables))))), }) } else { EmitText.parens(list{ value ++ (" == null ? undefined : " ++ - (value |> apply(~config, ~converter=c, ~indent, ~nameGen, ~toJS, ~variantTables))), + (value->apply(~config, ~converter=c, ~indent, ~nameGen, ~toJS, ~variantTables))), }) } | PromiseC(c) => - let x = "$promise" |> EmitText.name(~nameGen) + let x = "$promise"->EmitText.name(~nameGen) value ++ (".then(function _element(" ++ - ((x |> EmitType.ofTypeAny(~config)) ++ + ((x->EmitType.ofTypeAny(~config)) ++ (") { return " ++ - ((x |> apply(~config, ~converter=c, ~indent, ~nameGen, ~toJS, ~variantTables)) ++ "})")))) + ((x->apply(~config, ~converter=c, ~indent, ~nameGen, ~toJS, ~variantTables)) ++ "})")))) | RecordC(fieldsC) => let simplifyFieldConverted = fieldConverter => switch fieldConverter { - | OptionC(converter1) if converter1 |> converterIsIdentity(~toJS) => IdentC + | OptionC(converter1) if converter1->converterIsIdentity(~toJS) => IdentC | _ => fieldConverter } if toJS { let fieldValues = fieldsC - |> List.mapi((index, {lblJS, c: fieldConverter}) => + ->List.mapi((index, {lblJS, c: fieldConverter}) => lblJS ++ (":" ++ (value - |> EmitText.arrayAccess(~index) - |> apply( + ->EmitText.arrayAccess(~index) + ->apply( ~config, - ~converter=fieldConverter |> simplifyFieldConverted, + ~converter=fieldConverter->simplifyFieldConverted, ~indent, ~nameGen, ~toJS, ~variantTables, ))) ) - |> String.concat(", ") + ->String.concat(", ") fieldsC == list{} && config.language == Flow ? "Object.freeze({})" : "{" ++ (fieldValues ++ "}") } else { let fieldValues = fieldsC - |> List.map(({lblJS, c: fieldConverter}) => + ->List.map(({lblJS, c: fieldConverter}) => value - |> EmitText.fieldAccess(~label=lblJS) - |> apply( + ->EmitText.fieldAccess(~label=lblJS) + ->apply( ~config, - ~converter=fieldConverter |> simplifyFieldConverted, + ~converter=fieldConverter->simplifyFieldConverted, ~indent, ~nameGen, ~toJS, ~variantTables, ) ) - |> String.concat(", ") + ->String.concat(", ") "[" ++ (fieldValues ++ "]") } | TupleC(innerTypesC) => "[" ++ ((innerTypesC - |> List.mapi((index, c) => + ->List.mapi((index, c) => value - |> EmitText.arrayAccess(~index) - |> apply(~config, ~converter=c, ~indent, ~nameGen, ~toJS, ~variantTables) + ->EmitText.arrayAccess(~index) + ->apply(~config, ~converter=c, ~indent, ~nameGen, ~toJS, ~variantTables) ) - |> String.concat(", ")) ++ + ->String.concat(", ")) ++ "]") | VariantC({noPayloads: list{case}, withPayload: list{}, polymorphic}) => - toJS ? case.labelJS |> labelJSToString : case.label |> Runtime.emitVariantLabel(~polymorphic) + toJS ? case.labelJS->labelJSToString : case.label->Runtime.emitVariantLabel(~polymorphic) | VariantC(variantC) => if variantC.noPayloads != list{} { @@ -652,26 +652,26 @@ let rec apply = (~config, ~converter, ~indent, ~nameGen, ~toJS, ~variantTables, } let convertToString = !toJS && - variantC.noPayloads |> List.exists(({labelJS}) => + variantC.noPayloads->List.exists(({labelJS}) => labelJS == BoolLabel(true) || labelJS == BoolLabel(false) ) ? ".toString()" : "" - let table = variantC.hash |> variantTable(~toJS) + let table = variantC.hash->variantTable(~toJS) let accessTable = v => table ++ EmitText.array(list{v ++ convertToString}) switch variantC.withPayload { - | list{} => value |> accessTable + | list{} => value->accessTable | list{(case, numArgs, objConverter)} if variantC.unboxed => let casesWithPayload = (~indent) => if toJS { value - |> Runtime.emitVariantGetPayload(~numArgs, ~polymorphic=variantC.polymorphic) - |> apply(~config, ~converter=objConverter, ~indent, ~nameGen, ~toJS, ~variantTables) + ->Runtime.emitVariantGetPayload(~numArgs, ~polymorphic=variantC.polymorphic) + ->apply(~config, ~converter=objConverter, ~indent, ~nameGen, ~toJS, ~variantTables) } else { value - |> apply(~config, ~converter=objConverter, ~indent, ~nameGen, ~toJS, ~variantTables) - |> Runtime.emitVariantWithPayload( + ->apply(~config, ~converter=objConverter, ~indent, ~nameGen, ~toJS, ~variantTables) + ->Runtime.emitVariantWithPayload( ~config, ~label=case.label, ~numArgs, @@ -682,21 +682,21 @@ let rec apply = (~config, ~converter, ~indent, ~nameGen, ~toJS, ~variantTables, ? casesWithPayload(~indent) : EmitText.ifThenElse( ~indent, - (~indent as _) => value |> EmitText.typeOfObject, + (~indent as _) => value->EmitText.typeOfObject, casesWithPayload, - (~indent as _) => value |> accessTable, + (~indent as _) => value->accessTable, ) | list{_, ..._} => let convertCaseWithPayload = (~indent, ~numArgs, ~objConverter, case) => value - |> (toJS + ->(toJS ? Runtime.emitVariantGetPayload(~numArgs, ~polymorphic=variantC.polymorphic) : Runtime.emitJSVariantGetPayload) - |> apply(~config, ~converter=objConverter, ~indent, ~nameGen, ~toJS, ~variantTables) - |> ( + ->apply(~config, ~converter=objConverter, ~indent, ~nameGen, ~toJS, ~variantTables) + ->( toJS - ? Runtime.emitJSVariantWithPayload(~label=case.labelJS |> labelJSToString) + ? Runtime.emitJSVariantWithPayload(~label=case.labelJS->labelJSToString) : Runtime.emitVariantWithPayload( ~config, ~label=case.label, @@ -705,32 +705,32 @@ let rec apply = (~config, ~converter, ~indent, ~nameGen, ~toJS, ~variantTables, ) ) let switchCases = (~indent) => - variantC.withPayload |> List.map(((case, numArgs, objConverter)) => ( + variantC.withPayload->List.map(((case, numArgs, objConverter)) => ( toJS - ? case.label |> Runtime.emitVariantLabel(~polymorphic=variantC.polymorphic) - : case.labelJS |> labelJSToString, - case |> convertCaseWithPayload(~indent, ~numArgs, ~objConverter), + ? case.label->Runtime.emitVariantLabel(~polymorphic=variantC.polymorphic) + : case.labelJS->labelJSToString, + case->convertCaseWithPayload(~indent, ~numArgs, ~objConverter), )) let casesWithPayload = (~indent) => value - |> { + ->{ open Runtime toJS ? emitVariantGetLabel(~polymorphic=variantC.polymorphic) : emitJSVariantGetLabel } - |> EmitText.\"switch"(~indent, ~cases=switchCases(~indent)) + ->EmitText.\"switch"(~indent, ~cases=switchCases(~indent)) variantC.noPayloads == list{} ? casesWithPayload(~indent) : EmitText.ifThenElse( ~indent, - (~indent as _) => value |> EmitText.typeOfObject, + (~indent as _) => value->EmitText.typeOfObject, casesWithPayload, - (~indent as _) => value |> accessTable, + (~indent as _) => value->accessTable, ) } } let toJS = (~config, ~converter, ~indent, ~nameGen, ~variantTables, value) => - value |> apply(~config, ~converter, ~indent, ~nameGen, ~variantTables, ~toJS=true) + value->apply(~config, ~converter, ~indent, ~nameGen, ~variantTables, ~toJS=true) let toReason = (~config, ~converter, ~indent, ~nameGen, ~variantTables, value) => - value |> apply(~config, ~converter, ~indent, ~nameGen, ~toJS=false, ~variantTables) + value->apply(~config, ~converter, ~indent, ~nameGen, ~toJS=false, ~variantTables) diff --git a/tests/syntax_tests/data/idempotency/genType/src/DeadCode.res b/tests/syntax_tests/data/idempotency/genType/src/DeadCode.res index e75fbd640f..49fecfae95 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/DeadCode.res +++ b/tests/syntax_tests/data/idempotency/genType/src/DeadCode.res @@ -2,7 +2,7 @@ open DeadCommon let \"+++" = Filename.concat -let getModuleName = fn => fn |> Paths.getModuleName |> ModuleName.toString +let getModuleName = fn => fn->Paths.getModuleName->ModuleName.toString let rec getSignature = (~isfunc=false, moduleType: Types.module_type) => switch moduleType { @@ -28,7 +28,7 @@ let rec collectExportFromSignatureItem = (~path, si: Types.signature_item) => } | Sig_type(id, t, _) => if analyzeTypes.contents { - DeadType.addDeclaration(~path=list{id |> Ident.name, ...path}, t) + DeadType.addDeclaration(~path=list{id->Ident.name, ...path}, t) } | (Sig_module(id, {Types.md_type: moduleType}, _) | Sig_modtype(id, {Types.mtd_type: Some(moduleType)})) as s => @@ -37,8 +37,8 @@ let rec collectExportFromSignatureItem = (~path, si: Types.signature_item) => | _ => true } if collect { - getSignature(moduleType) |> List.iter( - collectExportFromSignatureItem(~path=list{id |> Ident.name, ...path}), + getSignature(moduleType)->List.iter( + collectExportFromSignatureItem(~path=list{id->Ident.name, ...path}), ) } | _ => () @@ -46,7 +46,7 @@ let rec collectExportFromSignatureItem = (~path, si: Types.signature_item) => let processSignature = (signature: Types.signature) => { let module_id = currentModuleName.contents - signature |> List.iter(sig_item => + signature->List.iter(sig_item => collectExportFromSignatureItem(~path=list{module_id}, sig_item) ) } @@ -84,7 +84,7 @@ let loadCmtFile = cmtFilePath => { ProcessDeadAnnotations.signature(signature) processSignature(signature.sig_type) | Implementation(structure) => - let cmtiExists = Sys.file_exists((cmtFilePath |> Filename.chop_extension) ++ ".cmti") + let cmtiExists = Sys.file_exists((cmtFilePath->Filename.chop_extension) ++ ".cmti") if !cmtiExists { ProcessDeadAnnotations.structure(structure) } @@ -116,9 +116,9 @@ let runAnalysis = (~cmtRoot) => { let absDir = dir == "" ? root : \"+++"(root, dir) if Sys.file_exists(absDir) { if Sys.is_directory(absDir) { - absDir |> Sys.readdir |> Array.iter(d => walkSubDirs(\"+++"(dir, d))) + absDir->Sys.readdir->Array.iter(d => walkSubDirs(\"+++"(dir, d))) } else if Filename.check_suffix(absDir, ".cmt") || Filename.check_suffix(absDir, ".cmti") { - absDir |> loadCmtFile + absDir->loadCmtFile } } } @@ -135,19 +135,19 @@ let runAnalysis = (~cmtRoot) => { let lib_bs = \"+++"(GenTypeCommon.projectRoot.contents, \"+++"("lib", "bs")) let sourceDirs = ModuleResolver.readSourceDirs(~configSources=None) - sourceDirs.dirs |> List.iter(sourceDir => { + sourceDirs.dirs->List.iter(sourceDir => { let libBsSourceDir = Filename.concat(lib_bs, sourceDir) - let files = switch Sys.readdir(libBsSourceDir) |> Array.to_list { + let files = switch Sys.readdir(libBsSourceDir)->Array.to_list { | files => files | exception Sys_error(_) => list{} } let cmtFiles = - files |> List.filter(x => + files->List.filter(x => Filename.check_suffix(x, ".cmt") || Filename.check_suffix(x, ".cmti") ) - cmtFiles |> List.iter(cmtFile => { + cmtFiles->List.iter(cmtFile => { let cmtFilePath = Filename.concat(libBsSourceDir, cmtFile) - cmtFilePath |> loadCmtFile + cmtFilePath->loadCmtFile }) }) diff --git a/tests/syntax_tests/data/idempotency/genType/src/DeadCommon.res b/tests/syntax_tests/data/idempotency/genType/src/DeadCommon.res index e351f2274d..69c904eff0 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/DeadCommon.res +++ b/tests/syntax_tests/data/idempotency/genType/src/DeadCommon.res @@ -21,7 +21,7 @@ let checkPrefix = prefix_ => { GenTypeCommon.projectRoot.contents == "" ? prefix_ : Filename.concat(GenTypeCommon.projectRoot.contents, prefix_) - let prefixLen = prefix |> String.length + let prefixLen = prefix->String.length sourceDir => String.length(sourceDir) >= prefixLen && String.sub(sourceDir, 0, prefixLen) == prefix } @@ -42,7 +42,7 @@ let whitelistSourceDir = lazy ( } ) -let posInWhitelist = (pos: Lexing.position) => pos.pos_fname |> Lazy.force(whitelistSourceDir) +let posInWhitelist = (pos: Lexing.position) => pos.pos_fname->Lazy.force(whitelistSourceDir) // Blacklist=prefix don't report on source dirs with the given prefix let blacklistSourceDir = lazy ( @@ -52,7 +52,7 @@ let blacklistSourceDir = lazy ( } ) -let posInBlacklist = (pos: Lexing.position) => pos.pos_fname |> Lazy.force(blacklistSourceDir) +let posInBlacklist = (pos: Lexing.position) => pos.pos_fname->Lazy.force(blacklistSourceDir) let write = Sys.getenv_opt("Write") != None @@ -64,7 +64,7 @@ let posToString = (~printCol=true, ~shortFile=true, pos: Lexing.position) => { let file = pos.Lexing.pos_fname let line = pos.Lexing.pos_lnum let col = pos.Lexing.pos_cnum - pos.Lexing.pos_bol - (shortFile ? file |> Filename.basename : file) ++ + (shortFile ? file->Filename.basename : file) ++ (":" ++ (string_of_int(line) ++ (printCol ? ":" ++ string_of_int(col) : ": "))) } @@ -175,7 +175,7 @@ let declGetLoc = decl => { let getPosOfValue = (~moduleName, ~valueName) => switch Hashtbl.find_opt(moduleDecls, moduleName) { | Some(posSet) => - posSet |> PosSet.find_first_opt(pos => + posSet->PosSet.find_first_opt(pos => switch PosHash.find_opt(decls, pos) { | Some({declKind: Value, path: list{name, ..._}}) if name == valueName => true | _ => false @@ -202,8 +202,8 @@ let addValueReference = (~addFileReference, ~locFrom: Location.t, ~locTo: Locati if verbose { Log_.item( "addValueReference %s --> %s@.", - locFrom.loc_start |> posToString, - locTo.loc_start |> posToString, + locFrom.loc_start->posToString, + locTo.loc_start->posToString, ) } PosHash.addSet(valueReferences, locTo.loc_start, locFrom.loc_start) @@ -269,30 +269,30 @@ let iterFilesFromRootsToLeaves = iterFun => { removeIncomingEdge(toFile) } - fileReferences |> FileHash.iter((fromFile, set) => { + fileReferences->FileHash.iter((fromFile, set) => { if getNum(fromFile) == 0 { Hashtbl.replace(referencesByNumber, 0, FileSet.add(fromFile, getSet(0))) } - set |> FileSet.iter(toFile => addEdge(fromFile, toFile)) + set->FileSet.iter(toFile => addEdge(fromFile, toFile)) }) while getSet(0) != FileSet.empty { let filesWithNoIncomingReferences = getSet(0) Hashtbl.remove(referencesByNumber, 0) - filesWithNoIncomingReferences |> FileSet.iter(fileName => { + filesWithNoIncomingReferences->FileSet.iter(fileName => { iterFun(fileName) let references = try FileHash.find(fileReferences, fileName) catch { | Not_found => FileSet.empty } - references |> FileSet.iter(toFile => removeEdge(fileName, toFile)) + references->FileSet.iter(toFile => removeEdge(fileName, toFile)) }) } // Process any remaining items in case of circular references - referencesByNumber |> Hashtbl.iter((_num, set) => + referencesByNumber->Hashtbl.iter((_num, set) => if FileSet.is_empty(set) { () } else { - set |> FileSet.iter(fileName => { + set->FileSet.iter(fileName => { let pos = {...Lexing.dummy_pos, pos_fname: fileName} let loc = {...Location.none, loc_start: pos, loc_end: pos} Log_.info(~loc, ~name="Warning Dead Analysis Cycle", (ppf, ()) => @@ -310,9 +310,9 @@ let iterFilesFromRootsToLeaves = iterFun => { /* ******* PROCESSING ******* */ -let pathToString = path => path |> List.rev |> String.concat(".") +let pathToString = path => path->List.rev->String.concat(".") -let pathWithoutHead = path => path |> List.rev |> List.tl |> String.concat(".") +let pathWithoutHead = path => path->List.rev->List.tl->String.concat(".") let annotateAtEnd = (~pos) => !posIsReason(pos) @@ -337,7 +337,7 @@ let addDeclaration_ = (~sideEffects=false, ~declKind, ~path, ~loc: Location.t, n "add%sDeclaration %s %s@.", declKind == Value ? "Value" : "Type", name, - pos |> posToString, + pos->posToString, ) } @@ -363,7 +363,7 @@ let addDeclaration_ = (~sideEffects=false, ~declKind, ~path, ~loc: Location.t, n let addTypeDeclaration = addDeclaration_ let addValueDeclaration = (~sideEffects, ~path, ~loc: Location.t, name) => - name |> addDeclaration_(~sideEffects, ~declKind=Value, ~path, ~loc) + name->addDeclaration_(~sideEffects, ~declKind=Value, ~path, ~loc) /* *** REPORTING *** */ @@ -401,14 +401,14 @@ module ProcessDeadAnnotations = { let processAttributes = (~pos, attributes) => { if ( attributes - |> Annotation.getAttributePayload(Annotation.tagIsOneOfTheGenTypeAnnotations) != None + ->Annotation.getAttributePayload(Annotation.tagIsOneOfTheGenTypeAnnotations) != None ) { - pos |> annotateGenType + pos->annotateGenType } - if attributes |> Annotation.getAttributePayload(\"="(deadAnnotation)) != None { - pos |> annotateDead - } else if attributes |> Annotation.getAttributePayload(\"="(liveAnnotation)) != None { - pos |> annotateLive + if attributes->Annotation.getAttributePayload(\"="(deadAnnotation)) != None { + pos->annotateDead + } else if attributes->Annotation.getAttributePayload(\"="(liveAnnotation)) != None { + pos->annotateLive } } @@ -419,7 +419,7 @@ module ProcessDeadAnnotations = { {vb_attributes, vb_pat} as value_binding: Typedtree.value_binding, ) => { switch vb_pat.pat_desc { - | Tpat_var(_id, pLoc) => vb_attributes |> processAttributes(~pos=pLoc.loc.loc_start) + | Tpat_var(_id, pLoc) => vb_attributes->processAttributes(~pos=pLoc.loc.loc_start) | _ => () } @@ -428,13 +428,13 @@ module ProcessDeadAnnotations = { let type_kind = (self, typeKind: Typedtree.type_kind) => { switch typeKind { | Ttype_record(labelDeclarations) => - labelDeclarations |> List.iter(({ld_attributes, ld_loc}: Typedtree.label_declaration) => - ld_attributes |> processAttributes(~pos=ld_loc.loc_start) + labelDeclarations->List.iter(({ld_attributes, ld_loc}: Typedtree.label_declaration) => + ld_attributes->processAttributes(~pos=ld_loc.loc_start) ) | Ttype_variant(constructorDeclarations) => - constructorDeclarations |> List.iter(( + constructorDeclarations->List.iter(( {cd_attributes, cd_loc}: Typedtree.constructor_declaration, - ) => cd_attributes |> processAttributes(~pos=cd_loc.loc_start)) + ) => cd_attributes->processAttributes(~pos=cd_loc.loc_start)) | _ => () } super.type_kind(self, typeKind) @@ -443,7 +443,7 @@ module ProcessDeadAnnotations = { self, {val_attributes, val_val} as value_description: Typedtree.value_description, ) => { - val_attributes |> processAttributes(~pos=val_val.val_loc.loc_start) + val_attributes->processAttributes(~pos=val_val.val_loc.loc_start) super.value_description(self, value_description) } { @@ -456,11 +456,11 @@ module ProcessDeadAnnotations = { let structure = structure => { let collectExportLocations = collectExportLocations() - structure |> collectExportLocations.structure(collectExportLocations) |> ignore + structure->collectExportLocations.structure(collectExportLocations)->ignore } let signature = signature => { let collectExportLocations = collectExportLocations() - signature |> collectExportLocations.signature(collectExportLocations) |> ignore + signature->collectExportLocations.signature(collectExportLocations)->ignore } } @@ -480,8 +480,8 @@ module WriteDeadAnnotations = { ("[" ++ ((isReason || declKind != Value ? "@" : "@@") ++ (deadAnnotation ++ - (" \"" ++ ((path |> pathWithoutHead) ++ "\"] "))))) - let posAnnotation = decl |> getPosAnnotation + (" \"" ++ ((path->pathWithoutHead) ++ "\"] "))))) + let posAnnotation = decl->getPosAnnotation let col = posAnnotation.pos_cnum - posAnnotation.pos_bol let originalLen = String.length(original) { @@ -495,12 +495,12 @@ module WriteDeadAnnotations = { original ++ annotationStr }, declarations: nextDeclarations, - } |> lineToString_ + }->lineToString_ } let lineToString = ({original, declarations}) => { let declarations = - declarations |> List.sort((decl1, decl2) => + declarations->List.sort((decl1, decl2) => getPosAnnotation(decl2).pos_cnum - getPosAnnotation(decl1).pos_cnum ) lineToString_({original: original, declarations: declarations}) @@ -520,7 +520,7 @@ module WriteDeadAnnotations = { try loop() catch { | End_of_file => close_in(channel) - lines.contents |> List.rev |> Array.of_list + lines.contents->List.rev->Array.of_list } } @@ -528,8 +528,8 @@ module WriteDeadAnnotations = { if fileName != "" && write { let channel = open_out(fileName) let lastLine = Array.length(lines) - lines |> Array.iteri((n, line) => { - output_string(channel, line |> lineToString) + lines->Array.iteri((n, line) => { + output_string(channel, line->lineToString) if n < lastLine - 1 { output_char(channel, '\n') } @@ -546,12 +546,12 @@ module WriteDeadAnnotations = { currentFileLines := readFile(fileName) } - let indexInLines = (decl |> getPosAnnotation).pos_lnum - 1 + let indexInLines = (decl->getPosAnnotation).pos_lnum - 1 if indexInLines < Array.length(currentFileLines.contents) { let line = currentFileLines.contents[indexInLines] line.declarations = list{decl, ...line.declarations} - Format.fprintf(ppf, " <-- line %d@. %s@.", decl.pos.pos_lnum, line |> lineToString) + Format.fprintf(ppf, " <-- line %d@. %s@.", decl.pos.pos_lnum, line->lineToString) } else { Format.fprintf(ppf, " <-- Can't find line %d@.", decl.pos.pos_lnum) } @@ -564,8 +564,8 @@ module WriteDeadAnnotations = { } let declIsDead = (~refs, decl) => { - let liveRefs = refs |> PosSet.filter(p => !ProcessDeadAnnotations.isAnnotatedDead(p)) - liveRefs |> PosSet.cardinal == 0 && !ProcessDeadAnnotations.isAnnotatedGenTypeOrLive(decl.pos) + let liveRefs = refs->PosSet.filter(p => !ProcessDeadAnnotations.isAnnotatedDead(p)) + liveRefs->PosSet.cardinal == 0 && !ProcessDeadAnnotations.isAnnotatedGenTypeOrLive(decl.pos) } let doReportDead = pos => @@ -586,41 +586,41 @@ let rec resolveRecursiveRefs = ( switch decl.pos { | _ if decl.resolved => if recursiveDebug { - Log_.item("recursiveDebug %s [%d] already resolved@.", decl.path |> pathToString, level) + Log_.item("recursiveDebug %s [%d] already resolved@.", decl.path->pathToString, level) } - decl.pos |> ProcessDeadAnnotations.isAnnotatedDead + decl.pos->ProcessDeadAnnotations.isAnnotatedDead | _ if PosSet.mem(decl.pos, refsBeingResolved.contents) => if recursiveDebug { Log_.item( "recursiveDebug %s [%d] is being resolved: assume dead@.", - decl.path |> pathToString, + decl.path->pathToString, level, ) } true | _ => if recursiveDebug { - Log_.item("recursiveDebug resolving %s [%d]@.", decl.path |> pathToString, level) + Log_.item("recursiveDebug resolving %s [%d]@.", decl.path->pathToString, level) } refsBeingResolved := PosSet.add(decl.pos, refsBeingResolved.contents) let allDepsResolved = ref(true) - let newRefs = refs |> PosSet.filter(x => + let newRefs = refs->PosSet.filter(x => if x == decl.pos { if recursiveDebug { - Log_.item("recursiveDebug %s ignoring reference to self@.", decl.path |> pathToString) + Log_.item("recursiveDebug %s ignoring reference to self@.", decl.path->pathToString) } false } else { switch PosHash.find_opt(decls, x) { | None => if recursiveDebug { - Log_.item("recursiveDebug can't find decl for %s@.", x |> posToString) + Log_.item("recursiveDebug can't find decl for %s@.", x->posToString) } true | Some(xDecl) => let xRefs = PosHash.findSet(xDecl.declKind == Value ? valueReferences : typeReferences, x) let xDeclIsDead = - xDecl |> resolveRecursiveRefs( + xDecl->resolveRecursiveRefs( ~deadDeclarations, ~level=level + 1, ~orderedFiles, @@ -635,29 +635,29 @@ let rec resolveRecursiveRefs = ( } ) - let isDead = decl |> declIsDead(~refs=newRefs) + let isDead = decl->declIsDead(~refs=newRefs) let isResolved = !isDead || (allDepsResolved.contents || level == 0) if isResolved { decl.resolved = true if isDead { - if decl.pos |> doReportDead { + if decl.pos->doReportDead { deadDeclarations := list{decl, ...deadDeclarations.contents} } - if decl |> checkSideEffects { - decl.pos |> ProcessDeadAnnotations.annotateDead + if decl->checkSideEffects { + decl.pos->ProcessDeadAnnotations.annotateDead } } if verbose { - let refsString = newRefs |> PosSet.elements |> List.map(posToString) |> String.concat(", ") + let refsString = newRefs->PosSet.elements->List.map(posToString)->String.concat(", ") Log_.item( "%s %s %s: %d references (%s) [%d]@.", isDead ? "Dead" : "Live", decl.declKind == Value ? "Value" : "Type", - decl.path |> pathToString, - newRefs |> PosSet.cardinal, + decl.path->pathToString, + newRefs->PosSet.cardinal, refsString, level, ) @@ -695,7 +695,7 @@ module Decl = { /* From the root of the file dependency DAG to the leaves. From the bottom of the file to the top. */ - let (position1, position2) = (fname1 |> findPosition, fname2 |> findPosition) + let (position1, position2) = (fname1->findPosition, fname2->findPosition) let (p1, p2) = pathIsImplementationOf(path1, path2) ? (1, 0) : pathIsImplementationOf(path2, path1) @@ -711,7 +711,7 @@ module Decl = { let emitWarning = (~message, ~loc, ~name, ~path) => Log_.info(~loc, ~name, (ppf, ()) => - Format.fprintf(ppf, "@{%s@} %s", path |> pathWithoutHead, message) + Format.fprintf(ppf, "@{%s@} %s", path->pathWithoutHead, message) ) let isInsideReportedValue = decl => { @@ -736,8 +736,8 @@ module Decl = { let report = (~ppf, decl) => { let noSideEffectsOrUnderscore = !decl.sideEffects || { - let name = decl.path |> List.hd - name |> String.length >= 2 && + let name = decl.path->List.hd + name->String.length >= 2 && (String.get(name, 0) == '_' || (String.get(name, 0) == '+' && String.get(name, 1) == '_')) } @@ -753,15 +753,15 @@ module Decl = { | VariantCase => ("Warning Dead Type", "is a variant case which is never constructed") } - let insideReportedValue = decl |> isInsideReportedValue + let insideReportedValue = decl->isInsideReportedValue let shouldEmitWarning = !insideReportedValue - let shouldWriteAnnotation = shouldEmitWarning && decl |> checkSideEffects + let shouldWriteAnnotation = shouldEmitWarning && decl->checkSideEffects if shouldEmitWarning { - emitWarning(~message, ~loc=decl |> declGetLoc, ~name, ~path=decl.path) + emitWarning(~message, ~loc=decl->declGetLoc, ~name, ~path=decl.path) } if shouldWriteAnnotation { - decl |> WriteDeadAnnotations.onDeadDecl(~ppf) + decl->WriteDeadAnnotations.onDeadDecl(~ppf) } } } @@ -769,7 +769,7 @@ module Decl = { let reportDead = () => { let iterDeclInOrder = (~orderedFiles, ~deadDeclarations, decl) => { let refs = - decl.pos |> PosHash.findSet(decl.declKind == Value ? valueReferences : typeReferences) + decl.pos->PosHash.findSet(decl.declKind == Value ? valueReferences : typeReferences) resolveRecursiveRefs( ~deadDeclarations, ~level=0, @@ -777,16 +777,16 @@ let reportDead = () => { ~refsBeingResolved=ref(PosSet.empty), ~refs, decl, - ) |> ignore + )->ignore } if verbose { Log_.item("@.File References@.@.") - fileReferences |> FileHash.iter((file, files) => + fileReferences->FileHash.iter((file, files) => Log_.item( "%s -->> %s@.", - file |> Filename.basename, - files |> FileSet.elements |> List.map(Filename.basename) |> String.concat(", "), + file->Filename.basename, + files->FileSet.elements->List.map(Filename.basename)->String.concat(", "), ) ) } @@ -807,14 +807,14 @@ let reportDead = () => { }) let orderedDeclarations = - declarations |> List.fast_sort( + declarations->List.fast_sort( Decl.compareUsingDependencies(~orderedFiles), ) /* analyze in reverse order */ let deadDeclarations = ref(list{}) - orderedDeclarations |> List.iter(iterDeclInOrder(~orderedFiles, ~deadDeclarations)) + orderedDeclarations->List.iter(iterDeclInOrder(~orderedFiles, ~deadDeclarations)) let ppf = Format.std_formatter - let sortedDeadDeclarations = deadDeclarations.contents |> List.fast_sort(Decl.compareForReporting) - sortedDeadDeclarations |> List.iter(Decl.report(~ppf)) + let sortedDeadDeclarations = deadDeclarations.contents->List.fast_sort(Decl.compareForReporting) + sortedDeadDeclarations->List.iter(Decl.report(~ppf)) } diff --git a/tests/syntax_tests/data/idempotency/genType/src/DeadType.res b/tests/syntax_tests/data/idempotency/genType/src/DeadType.res index be04809fe0..5e33e5fb58 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/DeadType.res +++ b/tests/syntax_tests/data/idempotency/genType/src/DeadType.res @@ -6,7 +6,7 @@ let typeDependencies = ref(list{}) let addTypeReference = (~posFrom, ~posTo) => { if verbose { - Log_.item("addTypeReference %s --> %s@.", posFrom |> posToString, posTo |> posToString) + Log_.item("addTypeReference %s --> %s@.", posFrom->posToString, posTo->posToString) } PosHash.addSet(typeReferences, posTo, posFrom) } @@ -15,7 +15,7 @@ let addDeclaration = (~path as path_, {type_kind, type_manifest}: Types.type_dec let save = (~declKind, ~loc: Location.t, ~name) => { let isInterfaceFile = Filename.check_suffix(loc.loc_start.pos_fname, "i") let name = isInterfaceFile ? name : "+" ++ name - let path = list{name, ...path_} |> pathToString + let path = list{name, ...path_}->pathToString if type_manifest == None { addTypeDeclaration(~declKind, ~path=path_, ~loc, name) } @@ -45,8 +45,8 @@ let processTypeDeclaration = (typeDeclaration: Typedtree.type_declaration) => { if verbose { Log_.item( "extendTypeDependencies %s --> %s@.", - loc1.loc_start |> posToString, - loc2.loc_start |> posToString, + loc1.loc_start->posToString, + loc2.loc_start->posToString, ) } @@ -61,7 +61,7 @@ let processTypeDeclaration = (typeDeclaration: Typedtree.type_declaration) => { typeDeclaration.typ_name.txt, ...currentModulePath.contents, }), - } |> String.concat(".") + }->String.concat(".") try switch typeDeclaration.typ_manifest { | Some({ctyp_desc: Ttyp_constr(_, {txt}, _)}) => @@ -69,7 +69,7 @@ let processTypeDeclaration = (typeDeclaration: Typedtree.type_declaration) => { \"@"( list{currentModuleName.contents, ...Longident.flatten(txt)}, list{name.Asttypes.txt}, - ) |> String.concat(".") + )->String.concat(".") let loc1 = Hashtbl.find(fields, path1) let loc2 = Hashtbl.find(fields, path2) extendTypeDependencies(loc, loc1) @@ -86,10 +86,10 @@ let processTypeDeclaration = (typeDeclaration: Typedtree.type_declaration) => { switch typeDeclaration.typ_kind { | Ttype_record(l) => - l |> List.iter(({Typedtree.ld_name: ld_name, ld_loc}) => updateDependencies(ld_name, ld_loc)) + l->List.iter(({Typedtree.ld_name: ld_name, ld_loc}) => updateDependencies(ld_name, ld_loc)) | Ttype_variant(l) => - l |> List.iter(({Typedtree.cd_name: cd_name, cd_loc}) => updateDependencies(cd_name, cd_loc)) + l->List.iter(({Typedtree.cd_name: cd_name, cd_loc}) => updateDependencies(cd_name, cd_loc)) | _ => () } diff --git a/tests/syntax_tests/data/idempotency/genType/src/DeadValue.res b/tests/syntax_tests/data/idempotency/genType/src/DeadValue.res index 54099c6217..2816497a16 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/DeadValue.res +++ b/tests/syntax_tests/data/idempotency/genType/src/DeadValue.res @@ -15,16 +15,16 @@ let whiteListSideEffects = list{ let whiteTableSideEffects = Lazy.from_fun(() => { let tbl = Hashtbl.create(11) - whiteListSideEffects |> List.iter(s => Hashtbl.add(tbl, s, ())) + whiteListSideEffects->List.iter(s => Hashtbl.add(tbl, s, ())) tbl }) let pathIsWhitelistedForSideEffects = path => - switch path |> Path.flatten { + switch path->Path.flatten { | #Ok(id, mods) => Hashtbl.mem( Lazy.force(whiteTableSideEffects), - list{Ident.name(id), ...mods} |> String.concat("."), + list{Ident.name(id), ...mods}->String.concat("."), ) | #Contains_apply => false } @@ -33,42 +33,42 @@ let rec exprNoSideEffects = (expr: Typedtree.expression) => switch expr.exp_desc { | Texp_ident(_) | Texp_constant(_) => true - | Texp_construct(_, _, el) => el |> List.for_all(exprNoSideEffects) + | Texp_construct(_, _, el) => el->List.for_all(exprNoSideEffects) | Texp_function(_) => true | Texp_apply({exp_desc: Texp_ident(path, _, _)}, args) - if path |> pathIsWhitelistedForSideEffects => - args |> List.for_all(((_, eo)) => eo |> exprOptNoSideEffects) + if path->pathIsWhitelistedForSideEffects => + args->List.for_all(((_, eo)) => eo->exprOptNoSideEffects) | Texp_apply(_) => false - | Texp_sequence(e1, e2) => e1 |> exprNoSideEffects && e2 |> exprNoSideEffects + | Texp_sequence(e1, e2) => e1->exprNoSideEffects && e2->exprNoSideEffects | Texp_let(_, vbs, e) => - vbs |> List.for_all((vb: Typedtree.value_binding) => vb.vb_expr |> exprNoSideEffects) && - e |> exprNoSideEffects + vbs->List.for_all((vb: Typedtree.value_binding) => vb.vb_expr->exprNoSideEffects) && + e->exprNoSideEffects | Texp_record({fields, extended_expression}) => - fields |> Array.for_all(fieldNoSideEffects) && extended_expression |> exprOptNoSideEffects + fields->Array.for_all(fieldNoSideEffects) && extended_expression->exprOptNoSideEffects | Texp_assert(_) => false | Texp_match(e, casesOK, casesExn, partial) => partial == Total && - (e |> exprNoSideEffects && - (casesOK |> List.for_all(caseNoSideEffects) && casesExn |> List.for_all(caseNoSideEffects))) + (e->exprNoSideEffects && + (casesOK->List.for_all(caseNoSideEffects) && casesExn->List.for_all(caseNoSideEffects))) | Texp_letmodule(_) => false - | Texp_lazy(e) => e |> exprNoSideEffects - | Texp_try(e, cases) => e |> exprNoSideEffects && cases |> List.for_all(caseNoSideEffects) - | Texp_tuple(el) => el |> List.for_all(exprNoSideEffects) - | Texp_variant(_lbl, eo) => eo |> exprOptNoSideEffects - | Texp_field(e, _lid, _ld) => e |> exprNoSideEffects + | Texp_lazy(e) => e->exprNoSideEffects + | Texp_try(e, cases) => e->exprNoSideEffects && cases->List.for_all(caseNoSideEffects) + | Texp_tuple(el) => el->List.for_all(exprNoSideEffects) + | Texp_variant(_lbl, eo) => eo->exprOptNoSideEffects + | Texp_field(e, _lid, _ld) => e->exprNoSideEffects | Texp_setfield(_) => false - | Texp_array(el) => el |> List.for_all(exprNoSideEffects) + | Texp_array(el) => el->List.for_all(exprNoSideEffects) | Texp_ifthenelse(e1, e2, eo) => - e1 |> exprNoSideEffects && (e2 |> exprNoSideEffects && eo |> exprOptNoSideEffects) - | Texp_while(e1, e2) => e1 |> exprNoSideEffects && e2 |> exprNoSideEffects + e1->exprNoSideEffects && (e2->exprNoSideEffects && eo->exprOptNoSideEffects) + | Texp_while(e1, e2) => e1->exprNoSideEffects && e2->exprNoSideEffects | Texp_for(_id, _pat, e1, e2, _dir, e3) => - e1 |> exprNoSideEffects && (e2 |> exprNoSideEffects && e3 |> exprNoSideEffects) + e1->exprNoSideEffects && (e2->exprNoSideEffects && e3->exprNoSideEffects) | Texp_send(_) => false | Texp_new(_) => true | Texp_instvar(_) => true | Texp_setinstvar(_) => false | Texp_override(_) => false - | Texp_letexception(_ec, e) => e |> exprNoSideEffects + | Texp_letexception(_ec, e) => e->exprNoSideEffects | Texp_object(_) => true | Texp_pack(_) => false | Texp_unreachable => false @@ -77,15 +77,15 @@ let rec exprNoSideEffects = (expr: Typedtree.expression) => and exprOptNoSideEffects = eo => switch eo { | None => true - | Some(e) => e |> exprNoSideEffects + | Some(e) => e->exprNoSideEffects } and fieldNoSideEffects = ((_ld, rld): (_, Typedtree.record_label_definition)) => switch rld { | Kept(_typeExpr) => true - | Overridden(_lid, e) => e |> exprNoSideEffects + | Overridden(_lid, e) => e->exprNoSideEffects } and caseNoSideEffects = ({c_guard, c_rhs}: Typedtree.case) => - c_guard |> exprOptNoSideEffects && c_rhs |> exprNoSideEffects + c_guard->exprOptNoSideEffects && c_rhs->exprNoSideEffects let checkAnyBindingWithNoSideEffects = ( {vb_pat: {pat_desc}, vb_expr: expr, vb_loc: loc}: Typedtree.value_binding, @@ -150,9 +150,9 @@ let collectExpr = (super, self, e: Typedtree.expression) => { // When the ppx uses a dummy location, find the original location. let moduleName = switch path { | Pident(_) => currentModuleName.contents - | _ => path |> Path.head |> Ident.name + | _ => path->Path.head->Ident.name } - let valueName = path |> Path.last + let valueName = path->Path.last switch getPosOfValue(~moduleName, ~valueName) { | Some(posName) => addValueReference( @@ -169,7 +169,7 @@ let collectExpr = (super, self, e: Typedtree.expression) => { | Texp_apply( {exp_desc: Texp_ident(path, _, {Types.val_loc: locTo, _})}, list{(_lbl, Some({exp_desc: Texp_constant(Const_string(s, _))}))}, - ) if path |> Path.name == "JSResource.jSResource" && Filename.check_suffix(s, ".bs") => + ) if path->Path.name == "JSResource.jSResource" && Filename.check_suffix(s, ".bs") => let moduleName = Filename.chop_extension(s) switch getPosOfValue(~moduleName, ~valueName="make") { | None => () @@ -177,10 +177,10 @@ let collectExpr = (super, self, e: Typedtree.expression) => { if verbose { Log_.item( "lazyLoad %s(%s) %s defined in %s@.", - path |> Path.name, + path->Path.name, moduleName, - locTo.loc_start |> posToString, - posMake |> posToString, + locTo.loc_start->posToString, + posMake->posToString, ) } let locMake = { @@ -198,7 +198,7 @@ let collectExpr = (super, self, e: Typedtree.expression) => { (_, Some({exp_desc: Texp_constant(Const_string(sFalse, _))})), }, ) - if path |> Path.name == "J.unsafe_expr" && + if path->Path.name == "J.unsafe_expr" && (Filename.check_suffix(sTrue, ".bs") && Filename.check_suffix(sFalse, ".bs")) => let moduleTrue = Filename.chop_extension(sTrue) @@ -213,11 +213,11 @@ let collectExpr = (super, self, e: Typedtree.expression) => { "requireCond true:%s false:%s allPositions:[%s]@.", moduleTrue, moduleFalse, - allPositions |> PosSet.elements |> List.map(posToString) |> String.concat(", "), + allPositions->PosSet.elements->List.map(posToString)->String.concat(", "), ) } - allPositions |> PosSet.iter(pos => { + allPositions->PosSet.iter(pos => { let posFrom = {...Lexing.dummy_pos, pos_fname: currentModuleName.contents} let locFrom = { Location.loc_start: posFrom, @@ -246,7 +246,7 @@ let collectPattern = (super, self, pat: Typedtree.pattern) => { let posFrom = pat.pat_loc.loc_start switch pat.pat_desc { | Tpat_record(cases, _clodsedFlag) => - cases |> List.iter(((_loc, {Types.lbl_loc: {loc_start: posTo}}, _pat)) => + cases->List.iter(((_loc, {Types.lbl_loc: {loc_start: posTo}}, _pat)) => if analyzeTypes.contents { DeadType.addTypeReference(~posFrom, ~posTo) } @@ -261,9 +261,9 @@ let collectValueReferences = { /* Tast_mapper */ let super = Tast_mapper.default - let expr = (self, e) => e |> collectExpr(super, self) - let pat = (self, p) => p |> collectPattern(super, self) - let value_binding = (self, vb) => vb |> collectValueBinding(super, self) + let expr = (self, e) => e->collectExpr(super, self) + let pat = (self, p) => p->collectPattern(super, self) + let value_binding = (self, vb) => vb->collectValueBinding(super, self) let type_declaration = (self, typeDeclaration: Typedtree.type_declaration) => { DeadType.processTypeDeclaration(typeDeclaration) super.type_declaration(self, typeDeclaration) @@ -284,7 +284,7 @@ let collectValueReferences = { ~path, ~loc=vd.val_loc, ~sideEffects=false, - "+" ++ (vd.val_id |> Ident.name), + "+" ++ (vd.val_id->Ident.name), ) } @@ -328,13 +328,13 @@ let processTypeDependency = (( } let processStructure = (~cmt_value_dependencies, structure: Typedtree.structure) => { - structure |> collectValueReferences.structure(collectValueReferences) |> ignore + structure->collectValueReferences.structure(collectValueReferences)->ignore - let valueDependencies = cmt_value_dependencies |> List.rev + let valueDependencies = cmt_value_dependencies->List.rev - valueDependencies |> List.iter(processValueDependency) + valueDependencies->List.iter(processValueDependency) - DeadType.typeDependencies.contents |> List.iter(processTypeDependency) + DeadType.typeDependencies.contents->List.iter(processTypeDependency) DeadType.typeDependencies := list{} } diff --git a/tests/syntax_tests/data/idempotency/genType/src/Dependencies.res b/tests/syntax_tests/data/idempotency/genType/src/Dependencies.res index 3203a73029..94a09bc3da 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/Dependencies.res +++ b/tests/syntax_tests/data/idempotency/genType/src/Dependencies.res @@ -5,60 +5,60 @@ let rec handleNamespace = (~name, dep) => | External(_) | Internal(_) => dep | Dot(External(s), moduleName) if s == name => External(moduleName) - | Dot(dep1, s) => Dot(dep1 |> handleNamespace(~name), s) + | Dot(dep1, s) => Dot(dep1->handleNamespace(~name), s) } let rec fromPath1 = (~config, ~typeEnv, path: Path.t) => switch path { | Pident(id) => - let name = id |> Ident.name - switch typeEnv |> TypeEnv.lookup(~name) { + let name = id->Ident.name + switch typeEnv->TypeEnv.lookup(~name) { | None => External(name) | Some(typeEnv1) => - switch typeEnv1 |> TypeEnv.expandAliasToExternalModule(~name) { + switch typeEnv1->TypeEnv.expandAliasToExternalModule(~name) { | Some(dep) => dep | None => - let resolvedName = name |> TypeEnv.addModulePath(~typeEnv=typeEnv1) + let resolvedName = name->TypeEnv.addModulePath(~typeEnv=typeEnv1) Internal(resolvedName) } } - | Pdot(Pident(id), s, _pos) if id |> ScopedPackage.isGeneratedModule(~config) => - External(s |> ScopedPackage.addGeneratedModule(~generatedModule=id)) + | Pdot(Pident(id), s, _pos) if id->ScopedPackage.isGeneratedModule(~config) => + External(s->ScopedPackage.addGeneratedModule(~generatedModule=id)) - | Pdot(p, s, _pos) => Dot(p |> fromPath1(~config, ~typeEnv), s) - | Papply(_) => Internal("__Papply_unsupported_genType__" |> ResolvedName.fromString) + | Pdot(p, s, _pos) => Dot(p->fromPath1(~config, ~typeEnv), s) + | Papply(_) => Internal("__Papply_unsupported_genType__"->ResolvedName.fromString) } let rec isInternal = dep => switch dep { | External(_) => false | Internal(_) => true - | Dot(d, _) => d |> isInternal + | Dot(d, _) => d->isInternal } let fromPath = (~config, ~typeEnv, path) => { - let dep = path |> fromPath1(~config, ~typeEnv) + let dep = path->fromPath1(~config, ~typeEnv) if Debug.typeResolution.contents { Log_.item( "fromPath path:%s typeEnv:%s %s resolved:%s\n", - path |> Path.name, - typeEnv |> TypeEnv.toString, - dep |> isInternal ? "Internal" : "External", - dep |> depToString, + path->Path.name, + typeEnv->TypeEnv.toString, + dep->isInternal ? "Internal" : "External", + dep->depToString, ) } switch config.namespace { | None => dep - | Some(name) => dep |> handleNamespace(~name) + | Some(name) => dep->handleNamespace(~name) } } let rec getOuterModuleName = dep => switch dep { - | External(name) => name |> ModuleName.fromStringUnsafe - | Internal(resolvedName) => resolvedName |> ResolvedName.toString |> ModuleName.fromStringUnsafe - | Dot(dep1, _) => dep1 |> getOuterModuleName + | External(name) => name->ModuleName.fromStringUnsafe + | Internal(resolvedName) => resolvedName->ResolvedName.toString->ModuleName.fromStringUnsafe + | Dot(dep1, _) => dep1->getOuterModuleName } let rec removeExternalOuterModule = dep => @@ -66,5 +66,5 @@ let rec removeExternalOuterModule = dep => | External(_) | Internal(_) => dep | Dot(External(_), s) => External(s) - | Dot(dep1, s) => Dot(dep1 |> removeExternalOuterModule, s) + | Dot(dep1, s) => Dot(dep1->removeExternalOuterModule, s) } diff --git a/tests/syntax_tests/data/idempotency/genType/src/EmitJs.res b/tests/syntax_tests/data/idempotency/genType/src/EmitJs.res index 95df8ee154..4c91c96f99 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/EmitJs.res +++ b/tests/syntax_tests/data/idempotency/genType/src/EmitJs.res @@ -12,7 +12,7 @@ type env = { let requireModule = (~\"import", ~env, ~importPath, ~strict=false, moduleName) => { let requires = \"import" ? env.requiresEarly : env.requires - let requiresNew = requires |> ModuleNameMap.add(moduleName, (importPath, strict)) + let requiresNew = requires->ModuleNameMap.add(moduleName, (importPath, strict)) \"import" ? {...env, requiresEarly: requiresNew} : {...env, requires: requiresNew} } @@ -32,24 +32,24 @@ let createExportTypeMap = ( if Debug.codeItems.contents { Log_.item( "Type Map: %s%s%s\n", - resolvedTypeName |> ResolvedName.toString, - typeVars == list{} ? "" : "(" ++ ((typeVars |> String.concat(",")) ++ ")"), + resolvedTypeName->ResolvedName.toString, + typeVars == list{} ? "" : "(" ++ ((typeVars->String.concat(",")) ++ ")"), " " ++ - ((annotation |> Annotation.toString |> EmitText.comment) ++ - (" = " ++ (type_ |> EmitType.typeToString(~config, ~typeNameIsInterface=_ => false)))), + ((annotation->Annotation.toString->EmitText.comment) ++ + (" = " ++ (type_->EmitType.typeToString(~config, ~typeNameIsInterface=_ => false)))), ) } - exportTypeMap |> StringMap.add( - resolvedTypeName |> ResolvedName.toString, + exportTypeMap->StringMap.add( + resolvedTypeName->ResolvedName.toString, {CodeItem.typeVars: typeVars, type_: type_, annotation: annotation}, ) } switch typeDeclaration.exportFromTypeDeclaration { - | {exportType, annotation} => exportType |> addExportType(~annotation) + | {exportType, annotation} => exportType->addExportType(~annotation) } } - typeDeclarations |> List.fold_left(updateExportTypeMap, StringMap.empty) + typeDeclarations->List.fold_left(updateExportTypeMap, StringMap.empty) } let codeItemToString = (~config, ~typeNameIsInterface, codeItem: CodeItem.t) => @@ -57,7 +57,7 @@ let codeItemToString = (~config, ~typeNameIsInterface, codeItem: CodeItem.t) => | ExportComponent({nestedModuleName}) => "ExportComponent nestedModuleName:" ++ switch nestedModuleName { - | Some(moduleName) => moduleName |> ModuleName.toString + | Some(moduleName) => moduleName->ModuleName.toString | None => "" } | ExportValue({resolvedName, type_}) => @@ -67,9 +67,9 @@ let codeItemToString = (~config, ~typeNameIsInterface, codeItem: CodeItem.t) => (" type:" ++ EmitType.typeToString(~config, ~typeNameIsInterface, type_)))) | ImportComponent({importAnnotation}) => - "ImportComponent " ++ (importAnnotation.importPath |> ImportPath.dump) + "ImportComponent " ++ (importAnnotation.importPath->ImportPath.dump) | ImportValue({importAnnotation}) => - "ImportValue " ++ (importAnnotation.importPath |> ImportPath.dump) + "ImportValue " ++ (importAnnotation.importPath->ImportPath.dump) } let emitExportType = ( @@ -83,12 +83,12 @@ let emitExportType = ( let (opaque, type_) = switch opaque { | Some(opaque) => (opaque, type_) | None => - let normalized = type_ |> typeGetNormalized + let normalized = type_->typeGetNormalized (false, normalized) } resolvedTypeName - |> ResolvedName.toString - |> EmitType.emitExportType( + ->ResolvedName.toString + ->EmitType.emitExportType( ~early?, ~config, ~emitters, @@ -111,11 +111,11 @@ let typeNameIsInterface = ( | Record(_) => true | _ => false } - switch exportTypeMap |> StringMap.find(typeName) { - | {type_} => type_ |> typeIsInterface + switch exportTypeMap->StringMap.find(typeName) { + | {type_} => type_->typeIsInterface | exception Not_found => - switch exportTypeMapFromOtherFiles |> StringMap.find(typeName) { - | {type_} => type_ |> typeIsInterface + switch exportTypeMapFromOtherFiles->StringMap.find(typeName) { + | {type_} => type_->typeIsInterface | exception Not_found => false } } @@ -130,7 +130,7 @@ let emitExportFromTypeDeclaration = ( exportFromTypeDeclaration: CodeItem.exportFromTypeDeclaration, ) => ( env, - exportFromTypeDeclaration.exportType |> emitExportType( + exportFromTypeDeclaration.exportType->emitExportType( ~emitters, ~config, ~typeGetNormalized, @@ -146,7 +146,7 @@ let emitExportFromTypeDeclarations = ( ~typeNameIsInterface, exportFromTypeDeclarations, ) => - exportFromTypeDeclarations |> List.fold_left( + exportFromTypeDeclarations->List.fold_left( ((env, emitters)) => emitExportFromTypeDeclaration( ~config, @@ -175,7 +175,7 @@ let rec emitCodeItem = ( ) => { let language = config.language if Debug.codeItems.contents { - Log_.item("Code Item: %s\n", codeItem |> codeItemToString(~config, ~typeNameIsInterface)) + Log_.item("Code Item: %s\n", codeItem->codeItemToString(~config, ~typeNameIsInterface)) } let indent = Some("") @@ -197,17 +197,17 @@ let rec emitCodeItem = ( | (Flow | Untyped, _) => false } - let (firstNameInPath, restOfPath, lastNameInPath) = switch asPath |> Str.split( + let (firstNameInPath, restOfPath, lastNameInPath) = switch asPath->Str.split( Str.regexp("\\."), ) { | list{x, ...y} => - let lastNameInPath = switch y |> List.rev { + let lastNameInPath = switch y->List.rev { | list{last, ..._} => last | list{} => x } es6 - ? (x, list{"", ...y} |> String.concat("."), lastNameInPath) - : (name, list{"", x, ...y} |> String.concat("."), lastNameInPath) + ? (x, list{"", ...y}->String.concat("."), lastNameInPath) + : (name, list{"", x, ...y}->String.concat("."), lastNameInPath) | _ => (name, "", name) } @@ -218,7 +218,7 @@ let rec emitCodeItem = ( let (emitters, env) = if es6 { /* emit an import {... as ...} immediately */ let emitters = - importPath |> EmitType.emitImportValueAsEarly( + importPath->EmitType.emitImportValueAsEarly( ~config, ~emitters, ~name=firstNameInPath, @@ -229,8 +229,8 @@ let rec emitCodeItem = ( /* add an early require(...) */ let env = firstNameInPath - |> ModuleName.fromStringUnsafe - |> requireModule(~\"import"=true, ~env, ~importPath, ~strict=true) + ->ModuleName.fromStringUnsafe + ->requireModule(~\"import"=true, ~env, ~importPath, ~strict=true) (emitters, env) } let componentNameTypeChecked = lastNameInPath ++ "TypeChecked" @@ -249,18 +249,18 @@ let rec emitCodeItem = ( config.language == Untyped ? emitters : ("(" ++ - (("props" |> EmitType.ofType( + (("props"->EmitType.ofType( ~config, ~typeNameIsInterface, ~type_=ident(propsTypeName), )) ++ ")") - |> EmitType.ofType( + ->EmitType.ofType( ~config, ~typeNameIsInterface, ~type_=EmitType.typeReactElement(~config), )) ++ (" {\n return <" ++ (componentPath ++ " {...props}/>;\n}")) - |> EmitType.emitExportFunction( + ->EmitType.emitExportFunction( ~early=true, ~emitters, ~name=componentNameTypeChecked, @@ -268,17 +268,17 @@ let rec emitCodeItem = ( ~comment="In case of type error, check the type of '" ++ ("make" ++ ("' in '" ++ - ((fileName |> ModuleName.toString) ++ + ((fileName->ModuleName.toString) ++ (".re'" ++ (" and the props of '" ++ - ((importPath |> ImportPath.emit(~config)) ++ "'.")))))), + ((importPath->ImportPath.emit(~config)) ++ "'.")))))), ) /* Wrap the component */ let emitters = "function " ++ (EmitText.parens( - \"@"(propsFields |> List.map(({nameJS}: field) => nameJS), list{"children"}) |> List.map( + \"@"(propsFields->List.map(({nameJS}: field) => nameJS), list{"children"})->List.map( EmitType.ofTypeAny(~config), ), ) ++ @@ -287,28 +287,28 @@ let rec emitCodeItem = ( componentPath, "{" ++ ((propsFields - |> List.map(({nameJS: propName, optional, type_: propTyp}) => + ->List.map(({nameJS: propName, optional, type_: propTyp}) => propName ++ (": " ++ - (propName |> Converter.toJS( + (propName->Converter.toJS( ~config, - ~converter=(optional == Mandatory ? propTyp : Option(propTyp)) |> typeGetConverter, + ~converter=(optional == Mandatory ? propTyp : Option(propTyp))->typeGetConverter, ~indent, ~nameGen, ~variantTables, ))) ) - |> String.concat(", ")) ++ + ->String.concat(", ")) ++ "}"), - "children" |> Converter.toJS( + "children"->Converter.toJS( ~config, - ~converter=childrenTyp |> typeGetConverter, + ~converter=childrenTyp->typeGetConverter, ~indent, ~nameGen, ~variantTables, ), }) ++ "; }"))) ++ ";" - |> EmitType.emitExportConstEarly( + ->EmitType.emitExportConstEarly( ~comment="Export '" ++ ("make" ++ "' early to allow circular import from the '.bs.js' file."), @@ -319,7 +319,7 @@ let rec emitCodeItem = ( ~typeNameIsInterface, ) let env = - ModuleName.reasonReact |> requireModule( + ModuleName.reasonReact->requireModule( ~\"import"=true, ~env, ~importPath=ImportPath.reasonReactPath(~config), @@ -334,8 +334,8 @@ let rec emitCodeItem = ( let (firstNameInPath, restOfPath) = valueName == asPath ? (valueName, "") - : switch asPath |> Str.split(Str.regexp("\\.")) { - | list{x, ...y} => (x, list{"", ...y} |> String.concat(".")) + : switch asPath->Str.split(Str.regexp("\\.")) { + | list{x, ...y} => (x, list{"", ...y}->String.concat(".")) | _ => (asPath, "") } let importFileVariable = "$$" ++ importFile @@ -345,7 +345,7 @@ let rec emitCodeItem = ( /* emit an import {... as ...} immediately */ let valueNameNotChecked = valueName ++ "NotChecked" let emitters = - importPath |> EmitType.emitImportValueAsEarly( + importPath->EmitType.emitImportValueAsEarly( ~config, ~emitters, ~name=firstNameInPath, @@ -360,14 +360,14 @@ let rec emitCodeItem = ( : importFileVariable ++ ("." ++ firstNameInPath) let env = importFileVariable - |> ModuleName.fromStringUnsafe - |> requireModule(~\"import"=true, ~env, ~importPath, ~strict=true) + ->ModuleName.fromStringUnsafe + ->requireModule(~\"import"=true, ~env, ~importPath, ~strict=true) (emitters, importedAsName, env) } let type_ = switch type_ { | Function({argTypes: list{{aType: Object(_)}}, retType} as function_) - if retType |> EmitType.isTypeReactElement(~config) => + if retType->EmitType.isTypeReactElement(~config) => let componentName = switch importFile { | "." | ".." => @@ -378,19 +378,19 @@ let rec emitCodeItem = ( | _ => type_ } - let converter = type_ |> typeGetConverter + let converter = type_->typeGetConverter let valueNameTypeChecked = valueName ++ "TypeChecked" let emitters = importedAsName ++ restOfPath ++ ";" - |> EmitType.emitExportConstEarly( + ->EmitType.emitExportConstEarly( ~config, ~comment="In case of type error, check the type of '" ++ (valueName ++ ("' in '" ++ - ((fileName |> ModuleName.toString) ++ - (".re'" ++ (" and '" ++ ((importPath |> ImportPath.emit(~config)) ++ "'.")))))), + ((fileName->ModuleName.toString) ++ + (".re'" ++ (" and '" ++ ((importPath->ImportPath.emit(~config)) ++ "'.")))))), ~emitters, ~name=valueNameTypeChecked, ~type_, @@ -399,9 +399,9 @@ let rec emitCodeItem = ( let valueNameNotDefault = valueName == "default" ? Runtime.default : valueName let emitters = (valueNameTypeChecked - |> Converter.toReason(~config, ~converter, ~indent, ~nameGen, ~variantTables) - |> EmitType.emitTypeCast(~config, ~type_, ~typeNameIsInterface)) ++ ";" - |> EmitType.emitExportConstEarly( + ->Converter.toReason(~config, ~converter, ~indent, ~nameGen, ~variantTables) + ->EmitType.emitTypeCast(~config, ~type_, ~typeNameIsInterface)) ++ ";" + ->EmitType.emitExportConstEarly( ~comment="Export '" ++ (valueNameNotDefault ++ "' early to allow circular import from the '.bs.js' file."), @@ -420,20 +420,20 @@ let rec emitCodeItem = ( | ExportComponent({componentAccessPath, exportType, moduleAccessPath, nestedModuleName, type_}) => let nameGen = EmitText.newNameGen() - let converter = type_ |> typeGetConverter + let converter = type_->typeGetConverter let importPath = - fileName |> ModuleResolver.resolveModule( + fileName->ModuleResolver.resolveModule( ~importExtension=".bs", ~outputFileRelative, ~resolver, ~useBsDependencies=false, ) - let moduleNameBs = fileName |> ModuleName.forBsFile + let moduleNameBs = fileName->ModuleName.forBsFile let moduleName = switch nestedModuleName { | Some(moduleName) => moduleName | None => fileName } - let propsTypeName = exportType.resolvedTypeName |> ResolvedName.toString + let propsTypeName = exportType.resolvedTypeName->ResolvedName.toString let componentType = EmitType.typeReactComponent(~config, ~propsType=ident(propsTypeName)) let name = EmitType.componentExportName(~config, ~fileName, ~moduleName) @@ -456,11 +456,11 @@ let rec emitCodeItem = ( } let args = \"@"( - propConverters |> List.map(((s, optional, argConverter)) => - jsPropsDot(s) |> Converter.toReason( + propConverters->List.map(((s, optional, argConverter)) => + jsPropsDot(s)->Converter.toReason( ~config, ~converter=optional == Optional && - !(argConverter |> Converter.converterIsIdentity(~toJS=false)) + !(argConverter->Converter.converterIsIdentity(~toJS=false)) ? OptionC(argConverter) : argConverter, ~indent, @@ -469,7 +469,7 @@ let rec emitCodeItem = ( ) ), list{ - jsPropsDot("children") |> Converter.toReason( + jsPropsDot("children")->Converter.toReason( ~config, ~converter=childrenConverter, ~indent, @@ -497,28 +497,28 @@ let rec emitCodeItem = ( "ReasonReact.wrapReasonForJs(", " " ++ (ModuleName.toString(moduleNameBs) ++ - ("." ++ ((componentAccessPath |> Runtime.emitModuleAccessPath(~config)) ++ ","))), + ("." ++ ((componentAccessPath->Runtime.emitModuleAccessPath(~config)) ++ ","))), " (function _(" ++ (EmitType.ofType(~config, ~typeNameIsInterface, ~type_=ident(propsTypeName), jsProps) ++ ") {"), " return " ++ ((ModuleName.toString(moduleNameBs) ++ ("." ++ - (moduleAccessPath |> Runtime.emitModuleAccessPath(~config))) - |> EmitText.curry(~args, ~numArgs=args |> List.length)) ++ + (moduleAccessPath->Runtime.emitModuleAccessPath(~config))) + ->EmitText.curry(~args, ~numArgs=args->List.length)) ++ ";"), " }));", - } |> String.concat("\n"), + }->String.concat("\n"), ) let emitters = switch exportType.type_ { | GroupOfLabeledArgs(fields) if config.language == Untyped && config.propTypes => fields - |> List.map((field: field) => { - let type_ = field.type_ |> typeGetInlined + ->List.map((field: field) => { + let type_ = field.type_->typeGetInlined {...field, type_: type_} }) - |> EmitType.emitPropTypes(~config, ~name, ~emitters, ~indent) + ->EmitType.emitPropTypes(~config, ~name, ~emitters, ~indent) | _ => emitters } @@ -526,33 +526,33 @@ let rec emitCodeItem = ( /* only export default for the top level component in the file */ fileName == moduleName ? EmitType.emitExportDefault(~emitters, ~config, name) : emitters - let env = moduleNameBs |> requireModule(~\"import"=false, ~env, ~importPath) + let env = moduleNameBs->requireModule(~\"import"=false, ~env, ~importPath) let env = - ModuleName.reasonReact |> requireModule( + ModuleName.reasonReact->requireModule( ~\"import"=false, ~env, ~importPath=ImportPath.reasonReactPath(~config), ) - let numArgs = args |> List.length + let numArgs = args->List.length let useCurry = numArgs >= 2 config.emitImportCurry = config.emitImportCurry || useCurry (env, emitters) | ExportValue({docString, moduleAccessPath, originalName, resolvedName, type_}) => - resolvedName |> ExportModule.extendExportModules(~moduleItemsEmitter, ~type_) + resolvedName->ExportModule.extendExportModules(~moduleItemsEmitter, ~type_) let resolvedName = ResolvedName.toString(resolvedName) let nameGen = EmitText.newNameGen() let importPath = - fileName |> ModuleResolver.resolveModule( + fileName->ModuleResolver.resolveModule( ~importExtension=".bs", ~outputFileRelative, ~resolver, ~useBsDependencies=false, ) - let fileNameBs = fileName |> ModuleName.forBsFile - let envWithRequires = fileNameBs |> requireModule(~\"import"=false, ~env, ~importPath) + let fileNameBs = fileName->ModuleName.forBsFile + let envWithRequires = fileNameBs->requireModule(~\"import"=false, ~env, ~importPath) let default = "default" let make = "make" @@ -571,11 +571,11 @@ let rec emitCodeItem = ( let (type_, hookType) = switch type_ { | Function( {argTypes: list{{aType: Object(closedFlags, fields)}}, retType, typeVars} as function_, - ) if retType |> EmitType.isTypeReactElement(~config) => + ) if retType->EmitType.isTypeReactElement(~config) => let propsType = { let fields = - fields |> List.map((field: field) => - field.nameJS == "children" && field.type_ |> EmitType.isTypeReactElement(~config) + fields->List.map((field: field) => + field.nameJS == "children" && field.type_->EmitType.isTypeReactElement(~config) ? {...field, type_: EmitType.typeReactChild(~config)} : field ) @@ -598,14 +598,14 @@ let rec emitCodeItem = ( } else { resolvedName } - let hookName = (fileName |> ModuleName.toString) ++ (suffix == "" ? suffix : "_" ++ suffix) + let hookName = (fileName->ModuleName.toString) ++ (suffix == "" ? suffix : "_" ++ suffix) let resolvedTypeName = if ( !config.emitTypePropDone && (originalName == default || originalName == make) ) { config.emitTypePropDone = true ResolvedName.fromString("Props") } else { - ResolvedName.fromString(name) |> ResolvedName.dot("Props") + ResolvedName.fromString(name)->ResolvedName.dot("Props") } ( @@ -623,7 +623,7 @@ let rec emitCodeItem = ( If type annotated direcly, they are not checked. But typeof() works. */ let flowFunctionTypeWorkaround = hookType != None && config.language == Flow - let converter = type_ |> typeGetConverter + let converter = type_->typeGetConverter let hookNameForTypeof = name ++ "$$forTypeof" let type_ = flowFunctionTypeWorkaround ? ident("typeof(" ++ (hookNameForTypeof ++ ")")) : type_ @@ -660,11 +660,11 @@ let rec emitCodeItem = ( } let emitters = - ((fileNameBs |> ModuleName.toString) ++ + ((fileNameBs->ModuleName.toString) ++ ("." ++ - (moduleAccessPath |> Runtime.emitModuleAccessPath(~config))) - |> Converter.toJS(~config, ~converter, ~indent, ~nameGen, ~variantTables)) ++ ";" - |> EmitType.emitExportConst( + (moduleAccessPath->Runtime.emitModuleAccessPath(~config))) + ->Converter.toJS(~config, ~converter, ~indent, ~nameGen, ~variantTables)) ++ ";" + ->EmitType.emitExportConst( ~config, ~docString, ~emitters, @@ -676,11 +676,11 @@ let rec emitCodeItem = ( let emitters = switch hookType { | Some({propsType: Object(_, fields)}) if config.language == Untyped && config.propTypes => fields - |> List.map((field: field) => { - let type_ = field.type_ |> typeGetInlined + ->List.map((field: field) => { + let type_ = field.type_->typeGetInlined {...field, type_: type_} }) - |> EmitType.emitPropTypes(~config, ~name, ~emitters, ~indent) + ->EmitType.emitPropTypes(~config, ~name, ~emitters, ~indent) | _ => emitters } @@ -707,7 +707,7 @@ and emitCodeItems = ( ~variantTables, codeItems, ) => - codeItems |> List.fold_left( + codeItems->List.fold_left( ((env, emitters)) => emitCodeItem( ~config, @@ -729,7 +729,7 @@ and emitCodeItems = ( let emitRequires = (~importedValueOrComponent, ~early, ~config, ~requires, emitters) => ModuleNameMap.fold( (moduleName, (importPath, strict), emitters) => - importPath |> EmitType.emitRequire( + importPath->EmitType.emitRequire( ~importedValueOrComponent, ~early, ~emitters, @@ -749,32 +749,32 @@ let emitVariantTables = (~config, ~emitters, variantTables) => { (typeAnnotation ++ (" = {" ++ ((variantC.noPayloads - |> List.map(case => { - let js = case.labelJS |> labelJSToString(~alwaysQuotes=!toJS) + ->List.map(case => { + let js = case.labelJS->labelJSToString(~alwaysQuotes=!toJS) let re = - case.label |> Runtime.emitVariantLabel(~comment=false, ~polymorphic=variantC.polymorphic) - toJS ? (re |> EmitText.quotes) ++ (": " ++ js) : js ++ (": " ++ re) + case.label->Runtime.emitVariantLabel(~comment=false, ~polymorphic=variantC.polymorphic) + toJS ? (re->EmitText.quotes) ++ (": " ++ js) : js ++ (": " ++ re) }) - |> String.concat(", ")) ++ "};")))) + ->String.concat(", ")) ++ "};")))) Hashtbl.fold(((_, toJS), variantC, l) => list{(variantC, toJS), ...l}, variantTables, list{}) - |> List.sort(((variantC1, toJS1), (variantC2, toJS2)) => { + ->List.sort(((variantC1, toJS1), (variantC2, toJS2)) => { let n = compare(variantC1.Converter.hash, variantC2.hash) n != 0 ? n : compare(toJS2, toJS1) }) - |> List.fold_left( + ->List.fold_left( (emitters, (variantC, toJS)) => variantC - |> emitTable(~table=variantC.Converter.hash |> variantTable(~toJS), ~toJS) - |> Emitters.requireEarly(~emitters), + ->emitTable(~table=variantC.Converter.hash->variantTable(~toJS), ~toJS) + ->Emitters.requireEarly(~emitters), emitters, ) } let typeGetInlined = (~config, ~exportTypeMap, type_) => - type_ |> Converter.typeGetNormalized( + type_->Converter.typeGetNormalized( ~config, ~inline=true, - ~lookupId=s => exportTypeMap |> StringMap.find(s), + ~lookupId=s => exportTypeMap->StringMap.find(s), ~typeNameIsInterface=_ => false, ) @@ -789,53 +789,53 @@ let rec readCmtFilesRecursively = ( {CodeItem.typeName: typeName, asTypeName, importPath}, ) => { let updateTypeMapFromOtherFiles = (~asType, ~exportTypeMapFromCmt, env) => - switch exportTypeMapFromCmt |> StringMap.find(typeName) { + switch exportTypeMapFromCmt->StringMap.find(typeName) { | (exportTypeItem: CodeItem.exportTypeItem) => let type_ = - exportTypeItem.type_ |> typeGetInlined(~config, ~exportTypeMap=exportTypeMapFromCmt) + exportTypeItem.type_->typeGetInlined(~config, ~exportTypeMap=exportTypeMapFromCmt) { ...env, - exportTypeMapFromOtherFiles: env.exportTypeMapFromOtherFiles |> StringMap.add( + exportTypeMapFromOtherFiles: env.exportTypeMapFromOtherFiles->StringMap.add( asType, {...exportTypeItem, type_: type_}, ), } | exception Not_found => env } - let cmtFile = importPath |> ImportPath.toCmt(~config, ~outputFileRelative) |> Paths.getCmtFile + let cmtFile = importPath->ImportPath.toCmt(~config, ~outputFileRelative)->Paths.getCmtFile switch asTypeName { | Some(asType) if cmtFile != "" => - switch env.cmtToExportTypeMap |> StringMap.find(cmtFile) { - | exportTypeMapFromCmt => env |> updateTypeMapFromOtherFiles(~asType, ~exportTypeMapFromCmt) + switch env.cmtToExportTypeMap->StringMap.find(cmtFile) { + | exportTypeMapFromCmt => env->updateTypeMapFromOtherFiles(~asType, ~exportTypeMapFromCmt) | exception Not_found => /* cmt file not read before: this ensures termination */ let typeDeclarations = Cmt_format.read_cmt(cmtFile) - |> inputCmtTranslateTypeDeclarations(~config, ~outputFileRelative, ~resolver) - |> ((x: CodeItem.translation) => x.typeDeclarations) + ->inputCmtTranslateTypeDeclarations(~config, ~outputFileRelative, ~resolver) + ->((x: CodeItem.translation) => x.typeDeclarations) let exportTypeMapFromCmt = - typeDeclarations |> createExportTypeMap( + typeDeclarations->createExportTypeMap( ~config, - ~file=cmtFile |> Filename.basename |> Filename.chop_extension, + ~file=cmtFile->Filename.basename->Filename.chop_extension, ) let cmtToExportTypeMap = - env.cmtToExportTypeMap |> StringMap.add(cmtFile, exportTypeMapFromCmt) + env.cmtToExportTypeMap->StringMap.add(cmtFile, exportTypeMapFromCmt) let env = - {...env, cmtToExportTypeMap: cmtToExportTypeMap} |> updateTypeMapFromOtherFiles( + {...env, cmtToExportTypeMap: cmtToExportTypeMap}->updateTypeMapFromOtherFiles( ~asType, ~exportTypeMapFromCmt, ) let newImportTypes = typeDeclarations - |> List.map((typeDeclaration: CodeItem.typeDeclaration) => typeDeclaration.importTypes) - |> List.concat + ->List.map((typeDeclaration: CodeItem.typeDeclaration) => typeDeclaration.importTypes) + ->List.concat - newImportTypes |> List.fold_left( + newImportTypes->List.fold_left( (env, newImportType) => - newImportType |> readCmtFilesRecursively( + newImportType->readCmtFilesRecursively( ~config, ~env, ~inputCmtTranslateTypeDeclarations, @@ -860,7 +860,7 @@ let emitImportType = ( {CodeItem.typeName: typeName, asTypeName, importPath} as importType, ) => { let env = - importType |> readCmtFilesRecursively( + importType->readCmtFilesRecursively( ~config, ~env, ~inputCmtTranslateTypeDeclarations, @@ -888,7 +888,7 @@ let emitImportTypes = ( ~typeNameIsInterface, importTypes, ) => - importTypes |> List.fold_left( + importTypes->List.fold_left( ((env, emitters)) => emitImportType( ~config, @@ -904,10 +904,10 @@ let emitImportTypes = ( let getAnnotatedTypedDeclarations = (~annotatedSet, typeDeclarations) => typeDeclarations - |> List.map(typeDeclaration => { + ->List.map(typeDeclaration => { let nameInAnnotatedSet = - annotatedSet |> StringSet.mem( - typeDeclaration.CodeItem.exportFromTypeDeclaration.exportType.resolvedTypeName |> ResolvedName.toString, + annotatedSet->StringSet.mem( + typeDeclaration.CodeItem.exportFromTypeDeclaration.exportType.resolvedTypeName->ResolvedName.toString, ) if nameInAnnotatedSet { { @@ -921,7 +921,7 @@ let getAnnotatedTypedDeclarations = (~annotatedSet, typeDeclarations) => typeDeclaration } }) - |> List.filter(({exportFromTypeDeclaration: {annotation}}: CodeItem.typeDeclaration) => + ->List.filter(({exportFromTypeDeclaration: {annotation}}: CodeItem.typeDeclaration) => annotation != NoGenType ) @@ -929,9 +929,9 @@ let propagateAnnotationToSubTypes = (~codeItems, typeMap: CodeItem.exportTypeMap let annotatedSet = ref(StringSet.empty) let initialAnnotatedTypes = typeMap - |> StringMap.bindings - |> List.filter(((_, {CodeItem.annotation: annotation})) => annotation == Annotation.GenType) - |> List.map(((_, {CodeItem.type_: type_})) => type_) + ->StringMap.bindings + ->List.filter(((_, {CodeItem.annotation: annotation})) => annotation == Annotation.GenType) + ->List.map(((_, {CodeItem.type_: type_})) => type_) let typesOfExportedValue = (codeItem: CodeItem.t) => switch codeItem { | ExportComponent({type_}) @@ -939,55 +939,55 @@ let propagateAnnotationToSubTypes = (~codeItems, typeMap: CodeItem.exportTypeMap | ImportValue({type_}) => list{type_} | _ => list{} } - let typesOfExportedValues = codeItems |> List.map(typesOfExportedValue) |> List.concat + let typesOfExportedValues = codeItems->List.map(typesOfExportedValue)->List.concat let visitTypAndUpdateMarked = type0 => { let visited = ref(StringSet.empty) let rec visit = type_ => switch type_ { | Ident({name: typeName, typeArgs}) => - if visited.contents |> StringSet.mem(typeName) { + if visited.contents->StringSet.mem(typeName) { () } else { - visited := visited.contents |> StringSet.add(typeName) - typeArgs |> List.iter(visit) - switch typeMap |> StringMap.find(typeName) { + visited := visited.contents->StringSet.add(typeName) + typeArgs->List.iter(visit) + switch typeMap->StringMap.find(typeName) { | {annotation: GenType | GenTypeOpaque} => () | {type_: type1, annotation: NoGenType} => if Debug.translation.contents { Log_.item("Marking Type As Annotated %s\n", typeName) } - annotatedSet := annotatedSet.contents |> StringSet.add(typeName) - type1 |> visit - | exception Not_found => annotatedSet := annotatedSet.contents |> StringSet.add(typeName) + annotatedSet := annotatedSet.contents->StringSet.add(typeName) + type1->visit + | exception Not_found => annotatedSet := annotatedSet.contents->StringSet.add(typeName) } } - | Array(t, _) => t |> visit + | Array(t, _) => t->visit | Function({argTypes, retType}) => - argTypes |> List.iter(({aType}) => visit(aType)) - retType |> visit + argTypes->List.iter(({aType}) => visit(aType)) + retType->visit | GroupOfLabeledArgs(fields) | Object(_, fields) | Record(fields) => - fields |> List.iter(({type_}) => type_ |> visit) + fields->List.iter(({type_}) => type_->visit) | Option(t) | Null(t) | Nullable(t) | Promise(t) => - t |> visit - | Tuple(innerTypes) => innerTypes |> List.iter(visit) + t->visit + | Tuple(innerTypes) => innerTypes->List.iter(visit) | TypeVar(_) => () - | Variant({payloads}) => payloads |> List.iter(((_, _, t)) => t |> visit) + | Variant({payloads}) => payloads->List.iter(((_, _, t)) => t->visit) } - type0 |> visit + type0->visit } - \"@"(initialAnnotatedTypes, typesOfExportedValues) |> List.iter(visitTypAndUpdateMarked) - let newTypeMap = typeMap |> StringMap.mapi(( + \"@"(initialAnnotatedTypes, typesOfExportedValues)->List.iter(visitTypAndUpdateMarked) + let newTypeMap = typeMap->StringMap.mapi(( typeName, exportTypeItem: CodeItem.exportTypeItem, ) => { ...exportTypeItem, - annotation: annotatedSet.contents |> StringSet.mem(typeName) + annotation: annotatedSet.contents->StringSet.mem(typeName) ? Annotation.GenType : exportTypeItem.annotation, }) @@ -1014,19 +1014,19 @@ let emitTranslationAsString = ( let (exportTypeMap, annotatedSet) = translation.typeDeclarations - |> createExportTypeMap(~config, ~file=fileName |> ModuleName.toString) - |> propagateAnnotationToSubTypes(~codeItems=translation.codeItems) + ->createExportTypeMap(~config, ~file=fileName->ModuleName.toString) + ->propagateAnnotationToSubTypes(~codeItems=translation.codeItems) let annotatedTypeDeclarations = - translation.typeDeclarations |> getAnnotatedTypedDeclarations(~annotatedSet) + translation.typeDeclarations->getAnnotatedTypedDeclarations(~annotatedSet) let importTypesFromTypeDeclarations = annotatedTypeDeclarations - |> List.map((typeDeclaration: CodeItem.typeDeclaration) => typeDeclaration.importTypes) - |> List.concat + ->List.map((typeDeclaration: CodeItem.typeDeclaration) => typeDeclaration.importTypes) + ->List.concat let exportFromTypeDeclarations = - annotatedTypeDeclarations |> List.map((typeDeclaration: CodeItem.typeDeclaration) => + annotatedTypeDeclarations->List.map((typeDeclaration: CodeItem.typeDeclaration) => typeDeclaration.exportFromTypeDeclaration ) @@ -1037,12 +1037,12 @@ let emitTranslationAsString = ( ) let lookupId_ = (~env, s) => - try exportTypeMap |> StringMap.find(s) catch { - | Not_found => env.exportTypeMapFromOtherFiles |> StringMap.find(s) + try exportTypeMap->StringMap.find(s) catch { + | Not_found => env.exportTypeMapFromOtherFiles->StringMap.find(s) } let typeGetNormalized_ = (~env, ~inline=false, type_) => - type_ |> Converter.typeGetNormalized( + type_->Converter.typeGetNormalized( ~config, ~inline, ~lookupId=lookupId_(~env), @@ -1050,7 +1050,7 @@ let emitTranslationAsString = ( ) let typeGetConverter_ = (~env, type_) => - type_ |> Converter.typeGetConverter( + type_->Converter.typeGetConverter( ~config, ~lookupId=lookupId_(~env), ~typeNameIsInterface=typeNameIsInterface(~env), @@ -1063,8 +1063,8 @@ let emitTranslationAsString = ( let (env, emitters) = /* imports from type declarations go first to build up type tables */ \"@"(importTypesFromTypeDeclarations, translation.importTypes) - |> List.sort_uniq(Translation.importTypeCompare) - |> emitImportTypes( + ->List.sort_uniq(Translation.importTypeCompare) + ->emitImportTypes( ~config, ~emitters, ~env, @@ -1075,7 +1075,7 @@ let emitTranslationAsString = ( ) let (env, emitters) = - exportFromTypeDeclarations |> emitExportFromTypeDeclarations( + exportFromTypeDeclarations->emitExportFromTypeDeclarations( ~config, ~emitters, ~typeGetNormalized=typeGetNormalized_(~env), @@ -1084,7 +1084,7 @@ let emitTranslationAsString = ( ) let (env, emitters) = - translation.codeItems |> emitCodeItems( + translation.codeItems->emitCodeItems( ~config, ~emitters, ~moduleItemsEmitter, @@ -1101,7 +1101,7 @@ let emitTranslationAsString = ( let emitters = config.emitImportReact ? EmitType.emitImportReact(~emitters, ~config) : emitters let env = config.emitImportCurry - ? ModuleName.curry |> requireModule( + ? ModuleName.curry->requireModule( ~\"import"=true, ~env, ~importPath=ImportPath.bsCurryPath(~config), @@ -1109,33 +1109,33 @@ let emitTranslationAsString = ( : env let env = config.emitImportPropTypes - ? ModuleName.propTypes |> requireModule(~\"import"=true, ~env, ~importPath=ImportPath.propTypes) + ? ModuleName.propTypes->requireModule(~\"import"=true, ~env, ~importPath=ImportPath.propTypes) : env let finalEnv = config.emitCreateBucklescriptBlock - ? ModuleName.createRescriptBlock |> requireModule( + ? ModuleName.createRescriptBlock->requireModule( ~\"import"=true, ~env, ~importPath=ImportPath.bsBlockPath(~config), ) : env - let emitters = variantTables |> emitVariantTables(~config, ~emitters) + let emitters = variantTables->emitVariantTables(~config, ~emitters) let emitters = - moduleItemsEmitter |> ExportModule.emitAllModuleItems(~config, ~emitters, ~fileName) + moduleItemsEmitter->ExportModule.emitAllModuleItems(~config, ~emitters, ~fileName) emitters - |> emitRequires( + ->emitRequires( ~importedValueOrComponent=false, ~early=true, ~config, ~requires=finalEnv.requiresEarly, ) - |> emitRequires( + ->emitRequires( ~importedValueOrComponent=finalEnv.importedValueOrComponent, ~early=false, ~config, ~requires=finalEnv.requires, ) - |> Emitters.toString(~separator="\n\n") + ->Emitters.toString(~separator="\n\n") } diff --git a/tests/syntax_tests/data/idempotency/genType/src/EmitText.res b/tests/syntax_tests/data/idempotency/genType/src/EmitText.res index af0fe2334c..4da990a0ff 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/EmitText.res +++ b/tests/syntax_tests/data/idempotency/genType/src/EmitText.res @@ -10,13 +10,13 @@ let name = (~nameGen, s) => s } -let parens = xs => "(" ++ ((xs |> String.concat(", ")) ++ ")") +let parens = xs => "(" ++ ((xs->String.concat(", ")) ++ ")") -let arg = (~nameGen, x) => "Arg" ++ x |> name(~nameGen) +let arg = (~nameGen, x) => "Arg" ++ x->name(~nameGen) -let argi = (~nameGen, i) => "Arg" ++ (i |> string_of_int) |> name(~nameGen) +let argi = (~nameGen, i) => "Arg" ++ (i->string_of_int)->name(~nameGen) -let array = xs => "[" ++ ((xs |> String.concat(", ")) ++ "]") +let array = xs => "[" ++ ((xs->String.concat(", ")) ++ "]") let comment = x => "/* " ++ (x ++ " */") @@ -26,12 +26,12 @@ let curry = (~args, ~numArgs, name) => | 1 => name ++ parens(args) | (2 | 3 | 4 | 5 | 6 | 7 | 8) as n => - "Curry._" ++ ((n |> string_of_int) ++ parens(\"@"(list{name}, args))) - | _ => "Curry.app" ++ parens(list{name, args |> array}) + "Curry._" ++ ((n->string_of_int) ++ parens(\"@"(list{name}, args))) + | _ => "Curry.app" ++ parens(list{name, args->array}) } let funCall = (~args, ~useCurry=false, name) => - useCurry ? name |> curry(~args, ~numArgs=args |> List.length) : name ++ parens(args) + useCurry ? name->curry(~args, ~numArgs=args->List.length) : name ++ parens(args) let genericsString = (~typeVars) => typeVars === list{} ? "" : "<" ++ (String.concat(",", typeVars) ++ ">") @@ -43,11 +43,11 @@ let funDef = (~bodyArgs, ~functionName, ~funParams, ~indent, ~mkBody, ~typeVars) | Some(name) => name } ++ (genericsString(~typeVars) ++ - ((funParams |> parens) ++ - (" {" ++ ((bodyArgs |> mkBody) ++ (Indent.break(~indent) ++ "}")))))) + ((funParams->parens) ++ + (" {" ++ ((bodyArgs->mkBody) ++ (Indent.break(~indent) ++ "}")))))) let ifThenElse = (~indent, if_, then_, else_) => { - let indent1 = indent |> Indent.more + let indent1 = indent->Indent.more if_(~indent=indent1) ++ (Indent.break(~indent) ++ ("? " ++ (then_(~indent=indent1) ++ (Indent.break(~indent) ++ (": " ++ else_(~indent=indent1)))))) @@ -57,13 +57,13 @@ let newNameGen = () => Hashtbl.create(1) let quotes = x => "\"" ++ (x ++ "\"") -let resultName = (~nameGen) => "result" |> name(~nameGen) +let resultName = (~nameGen) => "result"->name(~nameGen) let \"switch" = (~indent, ~cases, expr) => { - let lastCase = (cases |> List.length) - 1 + let lastCase = (cases->List.length) - 1 cases - |> List.mapi((i, (label, code)) => + ->List.mapi((i, (label, code)) => if i == lastCase { code } else { @@ -72,7 +72,7 @@ let \"switch" = (~indent, ~cases, expr) => { (label ++ (Indent.break(~indent) ++ ("? " ++ (code ++ (Indent.break(~indent) ++ ": ")))))) } ) - |> String.concat("") + ->String.concat("") } let typeOfObject = x => "typeof(" ++ (x ++ (")" ++ (" === " ++ "\'object\'"))) diff --git a/tests/syntax_tests/data/idempotency/genType/src/EmitType.res b/tests/syntax_tests/data/idempotency/genType/src/EmitType.res index ea04291541..7e562270ae 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/EmitType.res +++ b/tests/syntax_tests/data/idempotency/genType/src/EmitType.res @@ -13,7 +13,7 @@ let fileHeader = (~config, ~sourceFile) => { switch lines { | list{line} => "/* " ++ (line ++ " */\n") | _ => - "/** \n" ++ ((lines |> List.map(line => " * " ++ line) |> String.concat("\n")) ++ "\n */\n") + "/** \n" ++ ((lines->List.map(line => " * " ++ line)->String.concat("\n")) ++ "\n */\n") } } @@ -60,13 +60,13 @@ let shimExtension = (~config) => let interfaceName = (~config, name) => config.exportInterfaces ? "I" ++ name : name let typeReactComponent = (~config, ~propsType) => - (config.language == Flow ? "React$ComponentType" : "React.ComponentType") |> ident( + (config.language == Flow ? "React$ComponentType" : "React.ComponentType")->ident( ~builtin=true, ~typeArgs=list{propsType}, ) let typeReactContext = (~config, ~type_) => - (config.language == Flow ? "React$Context" : "React.Context") |> ident( + (config.language == Flow ? "React$Context" : "React.Context")->ident( ~builtin=true, ~typeArgs=list{type_}, ) @@ -86,7 +86,7 @@ let typeReactChild = (~config) => let isTypeReactElement = (~config, type_) => type_ === typeReactElement(~config) let typeReactDOMReDomRef = (~config) => - (config.language == Flow ? "React$Ref" : "React.Ref") |> ident( + (config.language == Flow ? "React$Ref" : "React.Ref")->ident( ~builtin=true, ~typeArgs=list{mixedOrUnknown(~config)}, ) @@ -106,8 +106,8 @@ let typeReactRef = (~type_) => Object( let componentExportName = (~config, ~fileName, ~moduleName) => switch config.language { - | Flow => fileName == moduleName ? "component" : moduleName |> ModuleName.toString - | _ => moduleName |> ModuleName.toString + | Flow => fileName == moduleName ? "component" : moduleName->ModuleName.toString + | _ => moduleName->ModuleName.toString } let typeAny = (~config) => @@ -131,7 +131,7 @@ let rec renderType = (~config, ~indent=None, ~typeNameIsInterface, ~inFunType, t } if config.language == TypeScript && (typeIsSimple && arrayKind == Mutable) { - (t |> renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType)) ++ "[]" + (t->renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType)) ++ "[]" } else { let arrayName = arrayKind == Mutable @@ -141,15 +141,15 @@ let rec renderType = (~config, ~indent=None, ~typeNameIsInterface, ~inFunType, t : "ReadonlyArray" arrayName ++ ("<" ++ - ((t |> renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType)) ++ ">")) + ((t->renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType)) ++ ">")) } | Function({argTypes: list{{aType: Object(closedFlag, fields)}}, retType, typeVars}) - if retType |> isTypeReactElement(~config) => - let fields = fields |> List.map(field => { + if retType->isTypeReactElement(~config) => + let fields = fields->List.map(field => { ...field, - type_: field.type_ |> TypeVars.substitute(~f=s => - if typeVars |> List.mem(s) { + type_: field.type_->TypeVars.substitute(~f=s => + if typeVars->List.mem(s) { Some(typeAny(~config)) } else { None @@ -157,7 +157,7 @@ let rec renderType = (~config, ~indent=None, ~typeNameIsInterface, ~inFunType, t ), }) let componentType = typeReactComponent(~config, ~propsType=Object(closedFlag, fields)) - componentType |> renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType) + componentType->renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType) | Function({argTypes, retType, typeVars}) => renderFunType(~config, ~indent, ~inFunType, ~typeNameIsInterface, ~typeVars, argTypes, retType) @@ -165,7 +165,7 @@ let rec renderType = (~config, ~indent=None, ~typeNameIsInterface, ~inFunType, t | GroupOfLabeledArgs(fields) | Object(_, fields) | Record(fields) => - let indent1 = fields |> Indent.heuristicFields(~indent) + let indent1 = fields->Indent.heuristicFields(~indent) let config = switch type0 { | GroupOfLabeledArgs(_) => {...config, exportInterfaces: false} | _ => config @@ -174,21 +174,21 @@ let rec renderType = (~config, ~indent=None, ~typeNameIsInterface, ~inFunType, t | Object(closedFlag, _) => closedFlag | _ => Closed } - fields |> renderFields(~closedFlag, ~config, ~indent=indent1, ~inFunType, ~typeNameIsInterface) + fields->renderFields(~closedFlag, ~config, ~indent=indent1, ~inFunType, ~typeNameIsInterface) | Ident({builtin, name, typeArgs}) => ( - !builtin && (config.exportInterfaces && name |> typeNameIsInterface) - ? name |> interfaceName(~config) + !builtin && (config.exportInterfaces && name->typeNameIsInterface) + ? name->interfaceName(~config) : name ) ++ EmitText.genericsString( - ~typeVars=typeArgs |> List.map( + ~typeVars=typeArgs->List.map( renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType), ), ) | Null(type_) => - "(null | " ++ ((type_ |> renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType)) ++ ")") + "(null | " ++ ((type_->renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType)) ++ ")") | Nullable(type_) | Option(type_) => switch config.language { @@ -200,28 +200,28 @@ let rec renderType = (~config, ~indent=None, ~typeNameIsInterface, ~inFunType, t } "?" ++ ((isComplex ? " (" : "") ++ - ((type_ |> renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType)) ++ ( + ((type_->renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType)) ++ ( isComplex ? ")" : "" ))) | TypeScript => "(null | undefined | " ++ - ((type_ |> renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType)) ++ + ((type_->renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType)) ++ ")") } | Promise(type_) => "Promise" ++ ("<" ++ - ((type_ |> renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType)) ++ ">")) + ((type_->renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType)) ++ ">")) | Tuple(innerTypes) => "[" ++ ((innerTypes - |> List.map(renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType)) - |> String.concat(", ")) ++ + ->List.map(renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType)) + ->String.concat(", ")) ++ "]") | TypeVar(s) => s | Variant({noPayloads, payloads, unboxed}) => - let noPayloadsRendered = noPayloads |> List.map(case => case.labelJS |> labelJSToString) + let noPayloadsRendered = noPayloads->List.map(case => case.labelJS->labelJSToString) let field = (~name, value) => { mutable_: Mutable, nameJS: name, @@ -230,20 +230,20 @@ let rec renderType = (~config, ~indent=None, ~typeNameIsInterface, ~inFunType, t type_: TypeVar(value), } let fields = fields => - fields |> renderFields(~closedFlag=Closed, ~config, ~indent, ~inFunType, ~typeNameIsInterface) - let payloadsRendered = payloads |> List.map(((case, _numArgs, type_)) => { - let typeRendered = type_ |> renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType) + fields->renderFields(~closedFlag=Closed, ~config, ~indent, ~inFunType, ~typeNameIsInterface) + let payloadsRendered = payloads->List.map(((case, _numArgs, type_)) => { + let typeRendered = type_->renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType) unboxed ? typeRendered : list{ - case.labelJS |> labelJSToString |> field(~name=Runtime.jsVariantTag), - typeRendered |> field(~name=Runtime.jsVariantValue), - } |> fields + case.labelJS->labelJSToString->field(~name=Runtime.jsVariantTag), + typeRendered->field(~name=Runtime.jsVariantValue), + }->fields }) let rendered = \"@"(noPayloadsRendered, payloadsRendered) - let indent1 = rendered |> Indent.heuristicVariants(~indent) + let indent1 = rendered->Indent.heuristicVariants(~indent) (indent1 == None ? "" : Indent.break(~indent=indent1) ++ " ") ++ - (rendered |> String.concat((indent1 == None ? " " : Indent.break(~indent=indent1)) ++ "| ")) + (rendered->String.concat((indent1 == None ? " " : Indent.break(~indent=indent1)) ++ "| ")) } and renderField = ( ~config, @@ -258,14 +258,14 @@ and renderField = ( (mutMarker ++ (lbl ++ (optMarker ++ - (": " ++ (type_ |> renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType)))))) + (": " ++ (type_->renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType)))))) } and renderFields = (~closedFlag, ~config, ~indent, ~inFunType, ~typeNameIsInterface, fields) => { - let indent1 = indent |> Indent.more + let indent1 = indent->Indent.more let exact = config.language == Flow && (!config.exportInterfaces && closedFlag == Closed) let space = indent == None && fields != list{} ? " " : "" let renderedFields = - fields |> List.map(renderField(~config, ~indent=indent1, ~typeNameIsInterface, ~inFunType)) + fields->List.map(renderField(~config, ~indent=indent1, ~typeNameIsInterface, ~inFunType)) let dotdotdot = config.language == Flow && !exact ? list{Indent.break(~indent=indent1) ++ "..."} : list{} (exact ? "{|" : "{") ++ @@ -291,18 +291,18 @@ and renderFunType = ( (aName == "" ? "_" ++ string_of_int(i + 1) : aName) ++ ":" } parameterName ++ - (aType |> renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType=true)) + (aType->renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType=true)) }, argTypes)) ++ (") => " ++ - ((retType |> renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType)) ++ + ((retType->renderType(~config, ~indent, ~typeNameIsInterface, ~inFunType)) ++ (inFunType ? ")" : "")))))) let typeToString = (~config, ~typeNameIsInterface, type_) => - type_ |> renderType(~config, ~typeNameIsInterface, ~inFunType=false) + type_->renderType(~config, ~typeNameIsInterface, ~inFunType=false) let ofType = (~config, ~typeNameIsInterface=_ => false, ~type_, s) => config.language == Untyped ? s - : s ++ (": " ++ (type_ |> typeToString(~config, ~typeNameIsInterface))) + : s ++ (": " ++ (type_->typeToString(~config, ~typeNameIsInterface))) let emitHookTypeAsFunction = ( ~config, @@ -321,11 +321,11 @@ let emitHookTypeAsFunction = ( (EmitText.genericsString(~typeVars) ++ ("(" ++ ("_: " ++ - (propsType |> renderType(~config, ~typeNameIsInterface, ~inFunType=true)) ++ + (propsType->renderType(~config, ~typeNameIsInterface, ~inFunType=true)) ++ (")" ++ - ((" " |> ofType(~config, ~typeNameIsInterface, ~type_=retType)) ++ + ((" "->ofType(~config, ~typeNameIsInterface, ~type_=retType)) ++ (" { return " ++ - (retValue ++ " };")))))))))) |> Emitters.\"export"(~emitters) + (retValue ++ " };"))))))))))->Emitters.\"export"(~emitters) let emitExportConst_ = ( ~early, @@ -343,12 +343,12 @@ let emitExportConst_ = ( switch (config.module_, config.language) { | (_, TypeScript) | (ES6, _) => - "export const " ++ ((name |> ofType(~config, ~typeNameIsInterface, ~type_)) ++ (" = " ++ line)) + "export const " ++ ((name->ofType(~config, ~typeNameIsInterface, ~type_)) ++ (" = " ++ line)) | (CommonJS, _) => "const " ++ - ((name |> ofType(~config, ~typeNameIsInterface, ~type_)) ++ + ((name->ofType(~config, ~typeNameIsInterface, ~type_)) ++ (" = " ++ (line ++ (";\nexports." ++ (name ++ (" = " ++ name)))))) - }) |> (early ? Emitters.exportEarly : Emitters.\"export")(~emitters) + })->(early ? Emitters.exportEarly : Emitters.\"export")(~emitters) let emitExportConst = emitExportConst_(~early=false) @@ -362,14 +362,14 @@ let emitExportFunction = (~early, ~comment, ~emitters, ~name, ~config, line) => | (ES6, _) => "export function " ++ (name ++ line) | (CommonJS, _) => "function " ++ (name ++ (line ++ (";\nexports." ++ (name ++ (" = " ++ name))))) - } |> (early ? Emitters.exportEarly : Emitters.\"export")(~emitters) + }->(early ? Emitters.exportEarly : Emitters.\"export")(~emitters) let emitExportDefault = (~emitters, ~config, name) => switch (config.module_, config.language) { | (_, TypeScript) | (ES6, _) => - "export default " ++ (name ++ ";") |> Emitters.\"export"(~emitters) - | (CommonJS, _) => "exports.default = " ++ (name ++ ";") |> Emitters.\"export"(~emitters) + "export default " ++ (name ++ ";")->Emitters.\"export"(~emitters) + | (CommonJS, _) => "exports.default = " ++ (name ++ ";")->Emitters.\"export"(~emitters) } let emitExportType = ( @@ -385,10 +385,10 @@ let emitExportType = ( ) => { let \"export" = early ? Emitters.exportEarly : Emitters.\"export" let typeParamsString = EmitText.genericsString(~typeVars) - let isInterface = resolvedTypeName |> typeNameIsInterface + let isInterface = resolvedTypeName->typeNameIsInterface let resolvedTypeName = config.exportInterfaces && isInterface - ? resolvedTypeName |> interfaceName(~config) + ? resolvedTypeName->interfaceName(~config) : resolvedTypeName let exportNameAs = switch nameAs { | None => "" @@ -405,10 +405,10 @@ let emitExportType = ( (resolvedTypeName ++ (typeParamsString ++ (" " ++ - (((opaque ? mixedOrUnknown(~config) : type_) |> typeToString( + (((opaque ? mixedOrUnknown(~config) : type_)->typeToString( ~config, ~typeNameIsInterface, - )) ++ (";" ++ exportNameAs))))) |> \"export"(~emitters) + )) ++ (";" ++ exportNameAs)))))->\"export"(~emitters) } else { "export" ++ ((opaque ? " opaque " : " ") ++ @@ -416,17 +416,17 @@ let emitExportType = ( (resolvedTypeName ++ (typeParamsString ++ (" = " ++ - (((opaque ? mixedOrUnknown(~config) : type_) |> typeToString( + (((opaque ? mixedOrUnknown(~config) : type_)->typeToString( ~config, ~typeNameIsInterface, - )) ++ (";" ++ exportNameAs))))))) |> \"export"(~emitters) + )) ++ (";" ++ exportNameAs)))))))->\"export"(~emitters) } | TypeScript => if opaque { /* Represent an opaque type as an absract class with a field called 'opaque'. Any type parameters must occur in the type of opaque, so that different instantiations are considered different types. */ - let typeOfOpaqueField = typeVars == list{} ? "any" : typeVars |> String.concat(" | ") + let typeOfOpaqueField = typeVars == list{} ? "any" : typeVars->String.concat(" | ") "// tslint:disable-next-line:max-classes-per-file \n" ++ (( String.capitalize_ascii(resolvedTypeName) != resolvedTypeName @@ -438,7 +438,7 @@ let emitExportType = ( (typeParamsString ++ (" { protected opaque!: " ++ (typeOfOpaqueField ++ (" }; /* simulate opaque types */" ++ exportNameAs))))))) - |> \"export"(~emitters) + ->\"export"(~emitters) } else { if isInterface && config.exportInterfaces { "export interface " ++ (resolvedTypeName ++ (typeParamsString ++ " ")) @@ -448,9 +448,9 @@ let emitExportType = ( (resolvedTypeName ++ (typeParamsString ++ " = "))) } ++ (switch type_ { - | _ => type_ |> typeToString(~config, ~typeNameIsInterface) + | _ => type_->typeToString(~config, ~typeNameIsInterface) } ++ - (";" ++ exportNameAs)) |> \"export"(~emitters) + (";" ++ exportNameAs))->\"export"(~emitters) } | Untyped => emitters } @@ -466,7 +466,7 @@ let emitImportValueAsEarly = (~config, ~emitters, ~name, ~nameAs, importPath) => | None => name } ++ (" from " ++ - ("'" ++ ((importPath |> ImportPath.emit(~config)) ++ "';"))))) |> Emitters.requireEarly(~emitters) + ("'" ++ ((importPath->ImportPath.emit(~config)) ++ "';")))))->Emitters.requireEarly(~emitters) } let emitRequire = ( @@ -489,15 +489,15 @@ let emitRequire = ( ("import * as " ++ (ModuleName.toString(moduleName) ++ (" from '" ++ - ((importPath |> ImportPath.emit(~config)) ++ "';")))) - |> (early ? Emitters.requireEarly : Emitters.require)(~emitters) + ((importPath->ImportPath.emit(~config)) ++ "';")))) + ->(early ? Emitters.requireEarly : Emitters.require)(~emitters) | _ => commentBeforeRequire ++ ("const " ++ (ModuleName.toString(moduleName) ++ (" = require('" ++ - ((importPath |> ImportPath.emit(~config)) ++ "');")))) - |> (early ? Emitters.requireEarly : Emitters.require)(~emitters) + ((importPath->ImportPath.emit(~config)) ++ "');")))) + ->(early ? Emitters.requireEarly : Emitters.require)(~emitters) } } @@ -516,28 +516,28 @@ let emitImportReact = (~emitters, ~config) => ~strict=false, ImportPath.react, ) - | TypeScript => "import * as React from 'react';" |> require(~early=true, ~emitters) + | TypeScript => "import * as React from 'react';"->require(~early=true, ~emitters) } let emitPropTypes = (~config, ~emitters, ~indent, ~name, fields) => { - let indent1 = indent |> Indent.more + let indent1 = indent->Indent.more let prefix = s => "PropTypes." ++ s let rec emitType = (~indent, type_: type_) => switch type_ { - | Array(t, _) => prefix("arrayOf") ++ ("(" ++ ((t |> emitType(~indent)) ++ ")")) - | Ident({name: ("bool" | "number" | "string") as id}) => id |> prefix - | Function(_) => "func" |> prefix + | Array(t, _) => prefix("arrayOf") ++ ("(" ++ ((t->emitType(~indent)) ++ ")")) + | Ident({name: ("bool" | "number" | "string") as id}) => id->prefix + | Function(_) => "func"->prefix | GroupOfLabeledArgs(fields) | Object(_, fields) | Record(fields) => - let indent1 = indent |> Indent.more + let indent1 = indent->Indent.more prefix("shape") ++ ("({" ++ (Indent.break(~indent=indent1) ++ ((fields - |> List.filter(({nameJS}: field) => nameJS != "children") - |> List.map(emitField(~indent=indent1)) - |> String.concat("," ++ Indent.break(~indent=indent1))) ++ + ->List.filter(({nameJS}: field) => nameJS != "children") + ->List.map(emitField(~indent=indent1)) + ->String.concat("," ++ Indent.break(~indent=indent1))) ++ (Indent.break(~indent) ++ "})")))) | Ident(_) @@ -548,12 +548,12 @@ let emitPropTypes = (~config, ~emitters, ~indent, ~name, fields) => { | Tuple(_) | TypeVar(_) | Variant(_) => - "any" |> prefix + "any"->prefix } and emitField = (~indent, {nameJS, optional, type_}: field) => nameJS ++ (" : " ++ - ((type_ |> emitType(~indent)) ++ (optional == Mandatory ? ".isRequired" : ""))) + ((type_->emitType(~indent)) ++ (optional == Mandatory ? ".isRequired" : ""))) config.emitImportPropTypes = true @@ -562,10 +562,10 @@ let emitPropTypes = (~config, ~emitters, ~indent, ~name, fields) => { ("{" ++ (Indent.break(~indent=indent1) ++ ((fields - |> List.filter(({nameJS}: field) => nameJS != "children") - |> List.map(emitField(~indent=indent1)) - |> String.concat("," ++ Indent.break(~indent=indent1))) ++ (Indent.break(~indent) ++ "};"))))) - |> Emitters.\"export"(~emitters) + ->List.filter(({nameJS}: field) => nameJS != "children") + ->List.map(emitField(~indent=indent1)) + ->String.concat("," ++ Indent.break(~indent=indent1))) ++ (Indent.break(~indent) ++ "};"))))) + ->Emitters.\"export"(~emitters) } let emitImportTypeAs = ( @@ -578,8 +578,8 @@ let emitImportTypeAs = ( ) => { let (typeName, asTypeName) = switch asTypeName { | Some(asName) => - asName |> typeNameIsInterface - ? (typeName |> interfaceName(~config), Some(asName |> interfaceName(~config))) + asName->typeNameIsInterface + ? (typeName->interfaceName(~config), Some(asName->interfaceName(~config))) : (typeName, asTypeName) | None => (typeName, asTypeName) } @@ -597,17 +597,17 @@ let emitImportTypeAs = ( | Some(asT) => " as " ++ asT | None => "" } ++ - ("} from '" ++ ((importPath |> ImportPath.emit(~config)) ++ "';"))))))) - |> Emitters.\"import"(~emitters) + ("} from '" ++ ((importPath->ImportPath.emit(~config)) ++ "';"))))))) + ->Emitters.\"import"(~emitters) | Untyped => emitters } } -let ofTypeAny = (~config, s) => s |> ofType(~config, ~type_=typeAny(~config)) +let ofTypeAny = (~config, s) => s->ofType(~config, ~type_=typeAny(~config)) let emitTypeCast = (~config, ~type_, ~typeNameIsInterface, s) => switch config.language { - | TypeScript => s ++ (" as " ++ (type_ |> typeToString(~config, ~typeNameIsInterface))) + | TypeScript => s ++ (" as " ++ (type_->typeToString(~config, ~typeNameIsInterface))) | Untyped | Flow => s } diff --git a/tests/syntax_tests/data/idempotency/genType/src/Emitters.res b/tests/syntax_tests/data/idempotency/genType/src/Emitters.res index 54da7d4c1c..986df43b5b 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/Emitters.res +++ b/tests/syntax_tests/data/idempotency/genType/src/Emitters.res @@ -18,35 +18,35 @@ let string = (~emitter, s) => list{s, ...emitter} let requireEarly = (~emitters, s) => { ...emitters, - requireEmitterEarly: s |> string(~emitter=emitters.requireEmitterEarly), + requireEmitterEarly: s->string(~emitter=emitters.requireEmitterEarly), } let exportEarly = (~emitters, s) => { ...emitters, - exportEmitterEarly: s |> string(~emitter=emitters.exportEmitterEarly), + exportEmitterEarly: s->string(~emitter=emitters.exportEmitterEarly), } let require = (~emitters, s) => { ...emitters, - requireEmitter: s |> string(~emitter=emitters.requireEmitter), + requireEmitter: s->string(~emitter=emitters.requireEmitter), } let \"import" = (~emitters, s) => { ...emitters, - importEmitter: s |> string(~emitter=emitters.importEmitter), + importEmitter: s->string(~emitter=emitters.importEmitter), } let \"export" = (~emitters, s) => { ...emitters, - exportEmitter: s |> string(~emitter=emitters.exportEmitter), + exportEmitter: s->string(~emitter=emitters.exportEmitter), } let toString = (~separator, emitters) => list{ - emitters.requireEmitterEarly |> List.rev, - emitters.exportEmitterEarly |> List.rev, - emitters.requireEmitter |> List.rev, - emitters.importEmitter |> List.rev, - emitters.exportEmitter |> List.rev, + emitters.requireEmitterEarly->List.rev, + emitters.exportEmitterEarly->List.rev, + emitters.requireEmitter->List.rev, + emitters.importEmitter->List.rev, + emitters.exportEmitter->List.rev, } - |> List.concat - |> String.concat(separator) + ->List.concat + ->String.concat(separator) diff --git a/tests/syntax_tests/data/idempotency/genType/src/ExportModule.res b/tests/syntax_tests/data/idempotency/genType/src/ExportModule.res index 44af002a43..7a9fba972b 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/ExportModule.res +++ b/tests/syntax_tests/data/idempotency/genType/src/ExportModule.res @@ -16,7 +16,7 @@ let rec exportModuleValueToType = exportModuleValue => switch exportModuleValue { | S(s, type_) => {typeForValue: ident(s), typeForType: type_} | M(exportModuleItem) => - let (fieldsForValue, fieldsForType) = exportModuleItem |> exportModuleItemToFields |> List.split + let (fieldsForValue, fieldsForType) = exportModuleItem->exportModuleItemToFields->List.split { typeForValue: Object(Open, fieldsForValue), typeForType: Object(Open, fieldsForType), @@ -24,7 +24,7 @@ let rec exportModuleValueToType = exportModuleValue => } and exportModuleItemToFields: exportModuleItem => list<(field, field)> = exportModuleItem => Hashtbl.fold((fieldName, exportModuleValue, fields) => { - let {typeForValue, typeForType} = exportModuleValue |> exportModuleValueToType + let {typeForValue, typeForType} = exportModuleValue->exportModuleValueToType let fieldForType = { mutable_: Mutable, nameJS: fieldName, @@ -49,7 +49,7 @@ let rec extendExportModuleItem = (x, ~exportModuleItem: exportModuleItem, ~type_ Hashtbl.replace(exportModuleItem, fieldName, M(innerExportModuleItem)) innerExportModuleItem } - rest |> extendExportModuleItem(~exportModuleItem=innerExportModuleItem, ~valueName, ~type_) + rest->extendExportModuleItem(~exportModuleItem=innerExportModuleItem, ~valueName, ~type_) } let extendExportModuleItems = (x, ~exportModuleItems: exportModuleItems, ~type_, ~valueName) => @@ -64,7 +64,7 @@ let extendExportModuleItems = (x, ~exportModuleItems: exportModuleItems, ~type_, Hashtbl.replace(exportModuleItems, moduleName, exportModuleItem) exportModuleItem } - rest |> extendExportModuleItem(~exportModuleItem, ~type_, ~valueName) + rest->extendExportModuleItem(~exportModuleItem, ~type_, ~valueName) } let createModuleItemsEmitter: unit => exportModuleItems = () => Hashtbl.create(1) @@ -75,16 +75,16 @@ let rev_fold = (f, tbl, base) => { } let emitAllModuleItems = (~config, ~emitters, ~fileName, exportModuleItems: exportModuleItems) => - emitters |> rev_fold((moduleName, exportModuleItem, emitters) => { - let {typeForValue, typeForType} = M(exportModuleItem) |> exportModuleValueToType + emitters->rev_fold((moduleName, exportModuleItem, emitters) => { + let {typeForValue, typeForType} = M(exportModuleItem)->exportModuleValueToType let emittedModuleItem = config.modulesAsObjects - ? ModuleName.forInnerModule(~fileName, ~innerModuleName=moduleName) |> ModuleName.toString - : typeForValue |> EmitType.typeToString( + ? ModuleName.forInnerModule(~fileName, ~innerModuleName=moduleName)->ModuleName.toString + : typeForValue->EmitType.typeToString( /* abuse type to print object */ ~config={...config, language: Flow}, ~typeNameIsInterface=_ => false, ) - emittedModuleItem |> EmitType.emitExportConst( + emittedModuleItem->EmitType.emitExportConst( ~config, ~emitters, ~name=moduleName, @@ -95,9 +95,9 @@ let emitAllModuleItems = (~config, ~emitters, ~fileName, exportModuleItems: expo let extendExportModules = (~moduleItemsEmitter: exportModuleItems, ~type_, resolvedName) => resolvedName - |> ResolvedName.toList - |> extendExportModuleItems( + ->ResolvedName.toList + ->extendExportModuleItems( ~exportModuleItems=moduleItemsEmitter, ~type_, - ~valueName=resolvedName |> ResolvedName.toString, + ~valueName=resolvedName->ResolvedName.toString, ) diff --git a/tests/syntax_tests/data/idempotency/genType/src/GenIdent.res b/tests/syntax_tests/data/idempotency/genType/src/GenIdent.res index 587218f003..a4e0f8bb88 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/GenIdent.res +++ b/tests/syntax_tests/data/idempotency/genType/src/GenIdent.res @@ -12,10 +12,10 @@ type typeVarsGen = { let createTypeVarsGen = () => {typeNameMap: IntMap.empty, typeNameCounter: 0} let jsTypeNameForAnonymousTypeID = (~typeVarsGen, id) => - try typeVarsGen.typeNameMap |> IntMap.find(id) catch { + try typeVarsGen.typeNameMap->IntMap.find(id) catch { | Not_found => typeVarsGen.typeNameCounter = typeVarsGen.typeNameCounter + 1 let name = "T" ++ string_of_int(typeVarsGen.typeNameCounter) - typeVarsGen.typeNameMap = typeVarsGen.typeNameMap |> IntMap.add(id, name) + typeVarsGen.typeNameMap = typeVarsGen.typeNameMap->IntMap.add(id, name) name } diff --git a/tests/syntax_tests/data/idempotency/genType/src/GenType.res b/tests/syntax_tests/data/idempotency/genType/src/GenType.res index ecf84275bf..6030a8875c 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/GenType.res +++ b/tests/syntax_tests/data/idempotency/genType/src/GenType.res @@ -35,11 +35,11 @@ let cli = () => { } cliCommand := command } - and setAdd = s => Add(s) |> setCliCommand - and setRm = s => Rm(s) |> setCliCommand - and setClean = () => Clean |> setCliCommand - and setDCE = cmtRoot => DCE(cmtRoot) |> setCliCommand - and setTermination = cmtRoot => Termination(cmtRoot) |> setCliCommand + and setAdd = s => Add(s)->setCliCommand + and setRm = s => Rm(s)->setCliCommand + and setClean = () => Clean->setCliCommand + and setDCE = cmtRoot => DCE(cmtRoot)->setCliCommand + and setTermination = cmtRoot => Termination(cmtRoot)->setCliCommand and speclist = list{ ("-bs-version", Arg.String(setBsVersion), "set the bucklescript version"), ("-clean", Arg.Unit(setClean), "clean all the generated files"), @@ -68,30 +68,30 @@ let cli = () => { let splitColon = Str.split(Str.regexp(":"), s) let (cmt, mlast) = switch splitColon { | list{cmt, ...rest} => - let mlast = rest |> String.concat("") + let mlast = rest->String.concat("") (cmt, mlast) | _ => assert(false) } - let config = Paths.readConfig(~bsVersion, ~namespace=cmt |> Paths.findNameSpace) + let config = Paths.readConfig(~bsVersion, ~namespace=cmt->Paths.findNameSpace) if Debug.basic.contents { Log_.item("Add %s %s\n", cmt, mlast) } - cmt |> GenTypeMain.processCmtFile(~signFile, ~config) + cmt->GenTypeMain.processCmtFile(~signFile, ~config) exit(0) | Clean => let config = Paths.readConfig(~bsVersion, ~namespace=None) let sourceDirs = ModuleResolver.readSourceDirs(~configSources=config.sources) if Debug.basic.contents { - Log_.item("Clean %d dirs\n", sourceDirs.dirs |> List.length) + Log_.item("Clean %d dirs\n", sourceDirs.dirs->List.length) } let count = ref(0) - sourceDirs.dirs |> List.iter(dir => { + sourceDirs.dirs->List.iter(dir => { let files = Sys.readdir(dir) - files |> Array.iter(file => + files->Array.iter(file => if Filename.check_suffix(file, ".re") { let extension = EmitType.outputFileSuffix(~config) - let generated = Filename.concat(dir, (file |> Filename.chop_extension) ++ extension) + let generated = Filename.concat(dir, (file->Filename.chop_extension) ++ extension) if Sys.file_exists(generated) { Unix.unlink(generated) incr(count) @@ -107,13 +107,13 @@ let cli = () => { | NoOp => printUsageAndExit() | Rm(s) => - let splitColon = Str.split(Str.regexp(":"), s) |> Array.of_list + let splitColon = Str.split(Str.regexp(":"), s)->Array.of_list assert (Array.length(splitColon) === 1) let cmtAbsolutePath: string = splitColon[0] /* somehow the CMT hook is passing an absolute path here */ - let cmt = cmtAbsolutePath |> Paths.relativePathFromBsLib - let config = Paths.readConfig(~bsVersion, ~namespace=cmt |> Paths.findNameSpace) - let outputFile = cmt |> Paths.getOutputFile(~config) + let cmt = cmtAbsolutePath->Paths.relativePathFromBsLib + let config = Paths.readConfig(~bsVersion, ~namespace=cmt->Paths.findNameSpace) + let outputFile = cmt->Paths.getOutputFile(~config) if Debug.basic.contents { Log_.item("Remove %s\n", cmt) } diff --git a/tests/syntax_tests/data/idempotency/genType/src/GenTypeCommon.res b/tests/syntax_tests/data/idempotency/genType/src/GenTypeCommon.res index 661606f342..217f2eb6d9 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/GenTypeCommon.res +++ b/tests/syntax_tests/data/idempotency/genType/src/GenTypeCommon.res @@ -28,12 +28,12 @@ type labelJS = | StringLabel(string) let labelJSToString = (~alwaysQuotes=false, labelJS) => { - let addQuotes = x => alwaysQuotes ? x |> EmitText.quotes : x + let addQuotes = x => alwaysQuotes ? x->EmitText.quotes : x switch labelJS { - | BoolLabel(b) => b |> string_of_bool |> addQuotes - | FloatLabel(s) => s |> addQuotes - | IntLabel(i) => i |> addQuotes - | StringLabel(s) => s |> EmitText.quotes + | BoolLabel(b) => b->string_of_bool->addQuotes + | FloatLabel(s) => s->addQuotes + | IntLabel(i) => i->addQuotes + | StringLabel(s) => s->EmitText.quotes } } @@ -158,14 +158,14 @@ module ScopedPackage = { // @demo/some-library -> DemoSomelibrary let packageNameToGeneratedModuleName = packageName => if String.contains(packageName, '/') { - Some(packageName |> namespace_of_package_name) + Some(packageName->namespace_of_package_name) } else { None } let isGeneratedModule = (id, ~config) => - config.bsDependencies |> List.exists(packageName => - packageName |> packageNameToGeneratedModuleName == Some(id |> Ident.name) + config.bsDependencies->List.exists(packageName => + packageName->packageNameToGeneratedModuleName == Some(id->Ident.name) ) // (Common, DemoSomelibrary) -> Common-DemoSomelibrary @@ -173,7 +173,7 @@ module ScopedPackage = { // Common-DemoSomelibrary -> Common let removeGeneratedModule = s => - switch s |> String.split_on_char('-') { + switch s->String.split_on_char('-') { | list{name, _scope} => name | _ => s } @@ -181,21 +181,21 @@ module ScopedPackage = { let rec depToString = dep => switch dep { - | External(name) => name |> ScopedPackage.removeGeneratedModule - | Internal(resolvedName) => resolvedName |> ResolvedName.toString + | External(name) => name->ScopedPackage.removeGeneratedModule + | Internal(resolvedName) => resolvedName->ResolvedName.toString | Dot(d, s) => depToString(d) ++ ("_" ++ s) } let rec depToResolvedName = (dep: dep) => switch dep { - | External(name) => name |> ResolvedName.fromString + | External(name) => name->ResolvedName.fromString | Internal(resolvedName) => resolvedName - | Dot(p, s) => ResolvedName.dot(s, p |> depToResolvedName) + | Dot(p, s) => ResolvedName.dot(s, p->depToResolvedName) } let createVariant = (~noPayloads, ~payloads, ~polymorphic) => { let hash = - noPayloads |> List.map(case => (case.label, case.labelJS)) |> Array.of_list |> Hashtbl.hash + noPayloads->List.map(case => (case.label, case.labelJS))->Array.of_list->Hashtbl.hash let unboxed = payloads == list{} Variant({ @@ -247,7 +247,7 @@ module NodeFilename = { let normalize = (path): t => switch Sys.os_type { - | "Win32" => path |> Str.split(Str.regexp("\\")) |> String.concat(dirSep) + | "Win32" => path->Str.split(Str.regexp("\\"))->String.concat(dirSep) | _ => path } @@ -270,6 +270,6 @@ module NodeFilename = { let concat = (dirname: string, filename) => { open Path - Path.concat(normalize(dirname), filename) |> toString + Path.concat(normalize(dirname), filename)->toString } } diff --git a/tests/syntax_tests/data/idempotency/genType/src/GenTypeMain.res b/tests/syntax_tests/data/idempotency/genType/src/GenTypeMain.res index 4c2c61ad24..ce429449bc 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/GenTypeMain.res +++ b/tests/syntax_tests/data/idempotency/genType/src/GenTypeMain.res @@ -6,8 +6,8 @@ module StringSet = Set.Make(String) let cmtCheckAnnotations = (~checkAnnotation, inputCMT) => switch inputCMT.Cmt_format.cmt_annots { - | Implementation(structure) => structure |> Annotation.structureCheckAnnotation(~checkAnnotation) - | Interface(signature) => signature |> Annotation.signatureCheckAnnotation(~checkAnnotation) + | Implementation(structure) => structure->Annotation.structureCheckAnnotation(~checkAnnotation) + | Interface(signature) => signature->Annotation.signatureCheckAnnotation(~checkAnnotation) | _ => false } @@ -45,22 +45,22 @@ let inputCmtTranslateTypeDeclarations = ( | Implementation(structure) => { ...structure, - str_items: structure.str_items |> List.filter(structureItemIsDeclaration), - } |> TranslateStructure.translateStructure(~config, ~outputFileRelative, ~resolver, ~typeEnv) + str_items: structure.str_items->List.filter(structureItemIsDeclaration), + }->TranslateStructure.translateStructure(~config, ~outputFileRelative, ~resolver, ~typeEnv) | Interface(signature) => { ...signature, - sig_items: signature.sig_items |> List.filter(signatureItemIsDeclaration), - } |> TranslateSignature.translateSignature(~config, ~outputFileRelative, ~resolver, ~typeEnv) + sig_items: signature.sig_items->List.filter(signatureItemIsDeclaration), + }->TranslateSignature.translateSignature(~config, ~outputFileRelative, ~resolver, ~typeEnv) | Packed(_) | Partial_implementation(_) | Partial_interface(_) => list{} } translations - |> Translation.combine - |> Translation.addTypeDeclarationsFromModuleEquations(~typeEnv) + ->Translation.combine + ->Translation.addTypeDeclarationsFromModuleEquations(~typeEnv) } let translateCMT = (~config, ~outputFileRelative, ~resolver, inputCMT): Translation.t => { @@ -68,14 +68,14 @@ let translateCMT = (~config, ~outputFileRelative, ~resolver, inputCMT): Translat let typeEnv = TypeEnv.root() let translations = switch cmt_annots { | Implementation(structure) => - structure |> TranslateStructure.translateStructure( + structure->TranslateStructure.translateStructure( ~config, ~outputFileRelative, ~resolver, ~typeEnv, ) | Interface(signature) => - signature |> TranslateSignature.translateSignature( + signature->TranslateSignature.translateSignature( ~config, ~outputFileRelative, ~resolver, @@ -84,8 +84,8 @@ let translateCMT = (~config, ~outputFileRelative, ~resolver, inputCMT): Translat | _ => list{} } translations - |> Translation.combine - |> Translation.addTypeDeclarationsFromModuleEquations(~typeEnv) + ->Translation.combine + ->Translation.addTypeDeclarationsFromModuleEquations(~typeEnv) } let emitTranslation = ( @@ -99,7 +99,7 @@ let emitTranslation = ( translation, ) => { let codeText = - translation |> EmitJs.emitTranslationAsString( + translation->EmitJs.emitTranslationAsString( ~config, ~fileName, ~outputFileRelative, @@ -109,7 +109,7 @@ let emitTranslation = ( let fileContents = signFile( EmitType.fileHeader( ~config, - ~sourceFile=(fileName |> ModuleName.toString) ++ (isInterface ? ".rei" : ".re"), + ~sourceFile=(fileName->ModuleName.toString) ++ (isInterface ? ".rei" : ".re"), ) ++ ("\n" ++ (codeText ++ "\n")), @@ -131,11 +131,11 @@ let readCmt = cmtFile => } let processCmtFile = (~signFile, ~config, cmt) => { - let cmtFile = cmt |> Paths.getCmtFile + let cmtFile = cmt->Paths.getCmtFile if cmtFile != "" { - let outputFile = cmt |> Paths.getOutputFile(~config) - let outputFileRelative = cmt |> Paths.getOutputFileRelative(~config) - let fileName = cmt |> Paths.getModuleName + let outputFile = cmt->Paths.getOutputFile(~config) + let outputFileRelative = cmt->Paths.getOutputFileRelative(~config) + let fileName = cmt->Paths.getModuleName let isInterface = Filename.check_suffix(cmtFile, ".cmti") let resolver = ModuleResolver.createLazyResolver( ~config, @@ -148,23 +148,23 @@ let processCmtFile = (~signFile, ~config, cmt) => { let checkAnnotation = (~loc as _, attributes) => { if ( attributes - |> Annotation.getAttributePayload(Annotation.tagIsGenTypeIgnoreInterface) != None + ->Annotation.getAttributePayload(Annotation.tagIsGenTypeIgnoreInterface) != None ) { ignoreInterface := true } attributes - |> Annotation.getAttributePayload(Annotation.tagIsOneOfTheGenTypeAnnotations) != None + ->Annotation.getAttributePayload(Annotation.tagIsOneOfTheGenTypeAnnotations) != None } - let hasGenTypeAnnotations = inputCMT |> cmtCheckAnnotations(~checkAnnotation) + let hasGenTypeAnnotations = inputCMT->cmtCheckAnnotations(~checkAnnotation) if isInterface { - let cmtFileImpl = (cmtFile |> Filename.chop_extension) ++ ".cmt" + let cmtFileImpl = (cmtFile->Filename.chop_extension) ++ ".cmt" let inputCMTImpl = readCmt(cmtFileImpl) - let hasGenTypeAnnotationsImpl = inputCMTImpl |> cmtCheckAnnotations(~checkAnnotation=( + let hasGenTypeAnnotationsImpl = inputCMTImpl->cmtCheckAnnotations(~checkAnnotation=( ~loc, attributes, ) => - if attributes |> checkAnnotation(~loc) { + if attributes->checkAnnotation(~loc) { if !ignoreInterface.contents { Log_.Color.setup() Log_.info(~loc, ~name="Warning genType", (ppf, ()) => @@ -186,8 +186,8 @@ let processCmtFile = (~signFile, ~config, cmt) => { } if hasGenTypeAnnotations { inputCMT - |> translateCMT(~config, ~outputFileRelative, ~resolver) - |> emitTranslation( + ->translateCMT(~config, ~outputFileRelative, ~resolver) + ->emitTranslation( ~config, ~fileName, ~isInterface, @@ -196,10 +196,10 @@ let processCmtFile = (~signFile, ~config, cmt) => { ~resolver, ~signFile, ) - } else if inputCMT |> cmtHasTypeErrors { - outputFile |> GeneratedFiles.logFileAction(TypeError) + } else if inputCMT->cmtHasTypeErrors { + outputFile->GeneratedFiles.logFileAction(TypeError) } else { - outputFile |> GeneratedFiles.logFileAction(NoMatch) + outputFile->GeneratedFiles.logFileAction(NoMatch) if Sys.file_exists(outputFile) { Unix.unlink(outputFile) } diff --git a/tests/syntax_tests/data/idempotency/genType/src/GeneratedFiles.res b/tests/syntax_tests/data/idempotency/genType/src/GeneratedFiles.res index da9df374cd..a18e7415ba 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/GeneratedFiles.res +++ b/tests/syntax_tests/data/idempotency/genType/src/GeneratedFiles.res @@ -31,7 +31,7 @@ let readLines = (file: string): list => { } catch { | End_of_file => close_in(chan) - lines.contents |> List.rev + lines.contents->List.rev } finished_lines } @@ -49,12 +49,12 @@ let writeFileIfRequired = (~outputFile, ~fileContents) => let oldContents = readFile(outputFile) let identical = oldContents == fileContents if identical { - outputFile |> logFileAction(Identical) + outputFile->logFileAction(Identical) } else { - outputFile |> logFileAction(Replace) + outputFile->logFileAction(Replace) writeFile(outputFile, fileContents) } } else { - outputFile |> logFileAction(Write) + outputFile->logFileAction(Write) writeFile(outputFile, fileContents) } diff --git a/tests/syntax_tests/data/idempotency/genType/src/ImportPath.res b/tests/syntax_tests/data/idempotency/genType/src/ImportPath.res index deb305ff8d..6ebd9e327d 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/ImportPath.res +++ b/tests/syntax_tests/data/idempotency/genType/src/ImportPath.res @@ -12,14 +12,14 @@ let bsCurryPath = (~config) => ("", Config_.getBsCurryPath(~config)) let fromModule = (~dir, ~importExtension, moduleName) => { let withNoPath = - (moduleName |> ModuleName.toString |> ScopedPackage.removeGeneratedModule) ++ importExtension + (moduleName->ModuleName.toString->ScopedPackage.removeGeneratedModule) ++ importExtension (dir, withNoPath) } let fromStringUnsafe = s => ("", s) let chopExtensionSafe = s => - try s |> Filename.chop_extension catch { + try s->Filename.chop_extension catch { | Invalid_argument(_) => s } @@ -28,8 +28,8 @@ let dump = ((dir, s)) => NodeFilename.concat(dir, s) let toCmt = (~config, ~outputFileRelative, (dir, s)) => { open Filename concat( - outputFileRelative |> dirname, - ((dir, s |> chopExtensionSafe) |> dump) ++ + outputFileRelative->dirname, + ((dir, s->chopExtensionSafe)->dump) ++ (switch config.namespace { | None => "" | Some(name) => "-" ++ name @@ -40,6 +40,6 @@ let toCmt = (~config, ~outputFileRelative, (dir, s)) => { let emit = (~config, (dir, s)) => switch config.importPath { - | Relative => (dir, s) |> dump + | Relative => (dir, s)->dump | Node => s } diff --git a/tests/syntax_tests/data/idempotency/genType/src/Indent.res b/tests/syntax_tests/data/idempotency/genType/src/Indent.res index 5c7f0319af..bd1a63a213 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/Indent.res +++ b/tests/syntax_tests/data/idempotency/genType/src/Indent.res @@ -14,11 +14,11 @@ let more = indent => let heuristicFields = (~indent, fields) => { let threshold = 2 - fields |> List.length > threshold && indent == None ? Some("") : indent + fields->List.length > threshold && indent == None ? Some("") : indent } let heuristicVariants = (~indent, rendered) => { let threshold = 40 - let break = rendered |> String.concat(" ") |> String.length > threshold + let break = rendered->String.concat(" ")->String.length > threshold break && indent == None ? Some(" ") : indent } diff --git a/tests/syntax_tests/data/idempotency/genType/src/ModuleName.res b/tests/syntax_tests/data/idempotency/genType/src/ModuleName.res index 5009724d09..61f05e4b3b 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/ModuleName.res +++ b/tests/syntax_tests/data/idempotency/genType/src/ModuleName.res @@ -14,7 +14,7 @@ let reasonReact = "ReasonReact" let forBsFile = s => s ++ "BS" let forInnerModule = (~fileName, ~innerModuleName) => - (fileName |> forBsFile) ++ ("." ++ innerModuleName) + (fileName->forBsFile) ++ ("." ++ innerModuleName) let fromStringUnsafe = s => s let toString = s => s let compare = (s1: string, s2) => compare(s1, s2) diff --git a/tests/syntax_tests/data/idempotency/genType/src/ModuleResolver.res b/tests/syntax_tests/data/idempotency/genType/src/ModuleResolver.res index 318466c5c1..3aec7769bf 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/ModuleResolver.res +++ b/tests/syntax_tests/data/idempotency/genType/src/ModuleResolver.res @@ -11,7 +11,7 @@ let readBsDependenciesDirs = (~root) => { let absDir = dir == "" ? root : \"+++"(root, dir) if Sys.file_exists(absDir) && Sys.is_directory(absDir) { dirs := list{dir, ...dirs.contents} - absDir |> Sys.readdir |> Array.iter(d => findSubDirs(\"+++"(dir, d))) + absDir->Sys.readdir->Array.iter(d => findSubDirs(\"+++"(dir, d))) } } findSubDirs("") @@ -33,23 +33,23 @@ let readDirsFromConfig = (~configSources) => { if Sys.file_exists(absDir) && Sys.is_directory(absDir) { dirs := list{dir, ...dirs.contents} if subdirs { - absDir |> Sys.readdir |> Array.iter(d => processDir(~subdirs, \"+++"(dir, d))) + absDir->Sys.readdir->Array.iter(d => processDir(~subdirs, \"+++"(dir, d))) } } } let rec processSourceItem = (sourceItem: Ext_json_types.t) => switch sourceItem { - | Str({str}) => str |> processDir(~subdirs=false) + | Str({str}) => str->processDir(~subdirs=false) | Obj({map}) => - switch map |> String_map.find_opt("dir") { + switch map->String_map.find_opt("dir") { | Some(Str({str})) => - let subdirs = switch map |> String_map.find_opt("subdirs") { + let subdirs = switch map->String_map.find_opt("subdirs") { | Some(True(_)) => true | Some(False(_)) => false | _ => false } - str |> processDir(~subdirs) + str->processDir(~subdirs) | _ => () } | Arr({content}) => Array.iter(processSourceItem, content) @@ -65,16 +65,16 @@ let readDirsFromConfig = (~configSources) => { let readSourceDirs = (~configSources) => { let sourceDirs = - list{"lib", "bs", ".sourcedirs.json"} |> List.fold_left(\"+++", bsbProjectRoot.contents) + list{"lib", "bs", ".sourcedirs.json"}->List.fold_left(\"+++", bsbProjectRoot.contents) let dirs = ref(list{}) let pkgs = Hashtbl.create(1) let readDirs = json => switch json { | Ext_json_types.Obj({map}) => - switch map |> String_map.find_opt("dirs") { + switch map->String_map.find_opt("dirs") { | Some(Arr({content})) => - content |> Array.iter(x => + content->Array.iter(x => switch x { | Ext_json_types.Str({str}) => dirs := list{str, ...dirs.contents} | _ => () @@ -89,9 +89,9 @@ let readSourceDirs = (~configSources) => { let readPkgs = json => switch json { | Ext_json_types.Obj({map}) => - switch map |> String_map.find_opt("pkgs") { + switch map->String_map.find_opt("pkgs") { | Some(Arr({content})) => - content |> Array.iter(x => + content->Array.iter(x => switch x { | Ext_json_types.Arr({content: [Str({str: name}), Str({str: path})]}) => Hashtbl.add(pkgs, name, path) @@ -104,9 +104,9 @@ let readSourceDirs = (~configSources) => { | _ => () } - if sourceDirs |> Sys.file_exists { + if sourceDirs->Sys.file_exists { try { - let json = sourceDirs |> Ext_json_parse.parse_json_from_file + let json = sourceDirs->Ext_json_parse.parse_json_from_file if bsbProjectRoot.contents != projectRoot.contents { dirs := readDirsFromConfig(~configSources) } else { @@ -129,8 +129,8 @@ let readSourceDirs = (~configSources) => { back to the directory where they belong. */ let sourcedirsJsonToMap = (~config, ~extensions, ~excludeFile) => { let rec chopExtensions = fname => - switch fname |> Filename.chop_extension { - | fnameChopped => fnameChopped |> chopExtensions + switch fname->Filename.chop_extension { + | fnameChopped => fnameChopped->chopExtensions | exception _ => fname } @@ -138,22 +138,22 @@ let sourcedirsJsonToMap = (~config, ~extensions, ~excludeFile) => { let bsDependenciesFileMap = ref(ModuleNameMap.empty) let filterGivenExtension = fileName => - extensions |> List.exists(ext => Filename.check_suffix(fileName, ext)) && !excludeFile(fileName) + extensions->List.exists(ext => Filename.check_suffix(fileName, ext)) && !excludeFile(fileName) let addDir = (~dirOnDisk, ~dirEmitted, ~filter, ~map) => dirOnDisk - |> Sys.readdir - |> Array.iter(fname => - if fname |> filter { + ->Sys.readdir + ->Array.iter(fname => + if fname->filter { map := - map.contents |> ModuleNameMap.add( - fname |> chopExtensions |> ModuleName.fromStringUnsafe, + map.contents->ModuleNameMap.add( + fname->chopExtensions->ModuleName.fromStringUnsafe, dirEmitted, ) } ) let {dirs, pkgs} = readSourceDirs(~configSources=config.sources) - dirs |> List.iter(dir => + dirs->List.iter(dir => addDir( ~dirEmitted=dir, ~dirOnDisk=\"+++"(projectRoot.contents, dir), @@ -162,13 +162,13 @@ let sourcedirsJsonToMap = (~config, ~extensions, ~excludeFile) => { ) ) - config.bsDependencies |> List.iter(packageName => + config.bsDependencies->List.iter(packageName => switch Hashtbl.find(pkgs, packageName) { | path => - let root = list{"lib", "bs"} |> List.fold_left(\"+++", path) + let root = list{"lib", "bs"}->List.fold_left(\"+++", path) let filter = fileName => - list{".cmt", ".cmti"} |> List.exists(ext => Filename.check_suffix(fileName, ext)) - readBsDependenciesDirs(~root) |> List.iter(dir => { + list{".cmt", ".cmti"}->List.exists(ext => Filename.check_suffix(fileName, ext)) + readBsDependenciesDirs(~root)->List.iter(dir => { let dirOnDisk = \"+++"(root, dir) let dirEmitted = \"+++"(packageName, dir) addDir(~dirEmitted, ~dirOnDisk, ~filter, ~map=bsDependenciesFileMap) @@ -196,25 +196,25 @@ let createLazyResolver = (~config, ~extensions, ~excludeFile) => { ~excludeFile, ) let find = (~bsDependencies, ~map, moduleName) => - switch map |> ModuleNameMap.find(moduleName) { + switch map->ModuleNameMap.find(moduleName) { | resolvedModuleDir => Some((resolvedModuleDir, Uppercase, bsDependencies)) | exception Not_found => - switch map |> ModuleNameMap.find(moduleName |> ModuleName.uncapitalize) { + switch map->ModuleNameMap.find(moduleName->ModuleName.uncapitalize) { | resolvedModuleDir => Some((resolvedModuleDir, Lowercase, bsDependencies)) | exception Not_found => None } } (~useBsDependencies, moduleName) => - switch moduleName |> find(~bsDependencies=false, ~map=moduleNameMap) { + switch moduleName->find(~bsDependencies=false, ~map=moduleNameMap) { | None if useBsDependencies => - moduleName |> find(~bsDependencies=true, ~map=bsDependenciesFileMap) + moduleName->find(~bsDependencies=true, ~map=bsDependenciesFileMap) | res => res } }), } let apply = (~resolver, ~useBsDependencies, moduleName) => - moduleName |> Lazy.force(resolver.lazyFind, ~useBsDependencies) + moduleName->Lazy.force(resolver.lazyFind, ~useBsDependencies) /* Resolve a reference to ModuleName, and produce a path suitable for require. E.g. require "../foo/bar/ModuleName.ext" where ext is ".re" or ".js". */ @@ -232,17 +232,17 @@ let resolveModule = ( So if e.g. project_root/src/ModuleName.re exists. */ \"+++"(outputFileAbsoluteDir, ModuleName.toString(moduleName) ++ ".re") let candidate = /* e.g. import "./Modulename.ext" */ - moduleName |> ImportPath.fromModule(~dir=Filename.current_dir_name, ~importExtension) + moduleName->ImportPath.fromModule(~dir=Filename.current_dir_name, ~importExtension) if Sys.file_exists(moduleNameReFile) { candidate } else { let rec pathToList = path => { - let isRoot = path |> Filename.basename == path + let isRoot = path->Filename.basename == path isRoot ? list{path} - : list{path |> Filename.basename, ...path |> Filename.dirname |> pathToList} + : list{path->Filename.basename, ...path->Filename.dirname->pathToList} } - switch moduleName |> apply(~resolver, ~useBsDependencies) { + switch moduleName->apply(~resolver, ~useBsDependencies) { | None => candidate | Some((resolvedModuleDir, case, bsDependencies)) => /* e.g. "dst" in case of dst/ModuleName.re */ @@ -250,13 +250,13 @@ let resolveModule = ( let walkUpOutputDir = /* e.g. ".." in case dst is a path of length 1 */ outputFileRelativeDir - |> pathToList - |> List.map(_ => Filename.parent_dir_name) - |> ( + ->pathToList + ->List.map(_ => Filename.parent_dir_name) + ->( l => switch l { | list{} => "" - | list{_, ...rest} => rest |> List.fold_left(\"+++", Filename.parent_dir_name) + | list{_, ...rest} => rest->List.fold_left(\"+++", Filename.parent_dir_name) } ) @@ -266,15 +266,15 @@ let resolveModule = ( /* e.g. import "../dst/ModuleName.ext" */ ( - case == Uppercase ? moduleName : moduleName |> ModuleName.uncapitalize - ) |> ImportPath.fromModule(~dir=fromOutputDirToModuleDir, ~importExtension) + case == Uppercase ? moduleName : moduleName->ModuleName.uncapitalize + )->ImportPath.fromModule(~dir=fromOutputDirToModuleDir, ~importExtension) } } } let resolveGeneratedModule = (~config, ~outputFileRelative, ~resolver, moduleName) => { if Debug.moduleResolution.contents { - Log_.item("Resolve Generated Module: %s\n", moduleName |> ModuleName.toString) + Log_.item("Resolve Generated Module: %s\n", moduleName->ModuleName.toString) } let importPath = resolveModule( ~importExtension=EmitType.generatedModuleExtension(~config), @@ -284,7 +284,7 @@ let resolveGeneratedModule = (~config, ~outputFileRelative, ~resolver, moduleNam moduleName, ) if Debug.moduleResolution.contents { - Log_.item("Import Path: %s\n", importPath |> ImportPath.dump) + Log_.item("Import Path: %s\n", importPath->ImportPath.dump) } importPath } @@ -294,12 +294,12 @@ let resolveGeneratedModule = (~config, ~outputFileRelative, ~resolver, moduleNam ") let importPathForReasonModuleName = (~config, ~outputFileRelative, ~resolver, moduleName) => { if Debug.moduleResolution.contents { - Log_.item("Resolve Reason Module: %s\n", moduleName |> ModuleName.toString) + Log_.item("Resolve Reason Module: %s\n", moduleName->ModuleName.toString) } - switch config.shimsMap |> ModuleNameMap.find(moduleName) { + switch config.shimsMap->ModuleNameMap.find(moduleName) { | shimModuleName => if Debug.moduleResolution.contents { - Log_.item("ShimModuleName: %s\n", shimModuleName |> ModuleName.toString) + Log_.item("ShimModuleName: %s\n", shimModuleName->ModuleName.toString) } let importPath = resolveModule( ~importExtension=".shim", @@ -309,10 +309,10 @@ let importPathForReasonModuleName = (~config, ~outputFileRelative, ~resolver, mo shimModuleName, ) if Debug.moduleResolution.contents { - Log_.item("Import Path: %s\n", importPath |> ImportPath.dump) + Log_.item("Import Path: %s\n", importPath->ImportPath.dump) } importPath | exception Not_found => - moduleName |> resolveGeneratedModule(~config, ~outputFileRelative, ~resolver) + moduleName->resolveGeneratedModule(~config, ~outputFileRelative, ~resolver) } } diff --git a/tests/syntax_tests/data/idempotency/genType/src/NamedArgs.res b/tests/syntax_tests/data/idempotency/genType/src/NamedArgs.res index afe84b7974..c21e7fbb0f 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/NamedArgs.res +++ b/tests/syntax_tests/data/idempotency/genType/src/NamedArgs.res @@ -71,4 +71,4 @@ let rec reverse = (~soFar=list{}, lst) => } let group = labeledTypes => - labeledTypes |> groupReversed(~revCurGroup=list{}, ~revResult=list{}) |> reverse + labeledTypes->groupReversed(~revCurGroup=list{}, ~revResult=list{})->reverse diff --git a/tests/syntax_tests/data/idempotency/genType/src/Paths.res b/tests/syntax_tests/data/idempotency/genType/src/Paths.res index 259cac501e..ee5b9f7f09 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/Paths.res +++ b/tests/syntax_tests/data/idempotency/genType/src/Paths.res @@ -6,7 +6,7 @@ let rec findProjectRoot = (~dir) => if Sys.file_exists(Filename.concat(dir, bsconfig)) { dir } else { - let parent = dir |> Filename.dirname + let parent = dir->Filename.dirname if parent == dir { prerr_endline("Error: cannot find project root containing " ++ (bsconfig ++ ".")) assert(false) @@ -38,10 +38,10 @@ let handleNamespace = cmt => { } let noDir = Filename.basename(cmt) == cmt if noDir { - cmt |> Filename.chop_extension |> cutAfterDash + cmt->Filename.chop_extension->cutAfterDash } else { - let dir = cmt |> Filename.dirname - let base = cmt |> Filename.basename |> Filename.chop_extension |> cutAfterDash + let dir = cmt->Filename.dirname + let base = cmt->Filename.basename->Filename.chop_extension->cutAfterDash Filename.concat(dir, base) } } @@ -52,28 +52,28 @@ let findNameSpace = cmt => { | n => Some(String.sub(s, n + 1, String.length(s) - n - 1)) | exception Not_found => None } - cmt |> Filename.basename |> Filename.chop_extension |> keepAfterDash + cmt->Filename.basename->Filename.chop_extension->keepAfterDash } /* Get the output file to be written, relative to the project root. */ let getOutputFileRelative = (~config, cmt) => - (cmt |> handleNamespace) ++ EmitType.outputFileSuffix(~config) + (cmt->handleNamespace) ++ EmitType.outputFileSuffix(~config) /* Get the output file to be written, as an absolute path. */ let getOutputFile = (~config, cmt) => Filename.concat(projectRoot.contents, getOutputFileRelative(~config, cmt)) let getModuleName = cmt => - cmt |> handleNamespace |> Filename.basename |> ModuleName.fromStringUnsafe + cmt->handleNamespace->Filename.basename->ModuleName.fromStringUnsafe let getCmtFile = cmt => { let pathCmt = Filename.concat(Sys.getcwd(), cmt) let cmtFile = if Filename.check_suffix(pathCmt, ".cmt") { let pathCmtLowerCase = { - let dirName = pathCmt |> Filename.dirname - let baseName = pathCmt |> Filename.basename - Filename.concat(dirName, baseName |> String.uncapitalize_ascii) + let dirName = pathCmt->Filename.dirname + let baseName = pathCmt->Filename.basename + Filename.concat(dirName, baseName->String.uncapitalize_ascii) } let pathCmti = Filename.chop_extension(pathCmt) ++ ".cmti" let pathCmtiLowerCase = Filename.chop_extension(pathCmtLowerCase) ++ ".cmti" @@ -96,11 +96,11 @@ let getCmtFile = cmt => { let getConfigFile = () => { let gentypeconfig = concat(projectRoot.contents, "gentypeconfig.json") - gentypeconfig |> Sys.file_exists ? Some(gentypeconfig) : None + gentypeconfig->Sys.file_exists ? Some(gentypeconfig) : None } let getBsConfigFile = () => { let bsconfig = concat(projectRoot.contents, "bsconfig.json") - bsconfig |> Sys.file_exists ? Some(bsconfig) : None + bsconfig->Sys.file_exists ? Some(bsconfig) : None } /* Find the relative path from /.../bs/lib @@ -110,10 +110,10 @@ let relativePathFromBsLib = fileName => fileName } else { let rec pathToList = path => { - let isRoot = path |> Filename.basename == path + let isRoot = path->Filename.basename == path isRoot ? list{path} - : list{path |> Filename.basename, ...path |> Filename.dirname |> pathToList} + : list{path->Filename.basename, ...path->Filename.dirname->pathToList} } let rec fromLibBs = (~acc, reversedList) => switch reversedList { @@ -122,13 +122,13 @@ let relativePathFromBsLib = fileName => | list{} => list{} /* not found */ } fileName - |> pathToList - |> fromLibBs(~acc=list{}) - |> ( + ->pathToList + ->fromLibBs(~acc=list{}) + ->( l => switch l { | list{} => fileName - | list{root, ...dirs} => dirs |> List.fold_left(concat, root) + | list{root, ...dirs} => dirs->List.fold_left(concat, root) } ) } diff --git a/tests/syntax_tests/data/idempotency/genType/src/ResolvedName.res b/tests/syntax_tests/data/idempotency/genType/src/ResolvedName.res index 701bc5c0bd..a352c1f356 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/ResolvedName.res +++ b/tests/syntax_tests/data/idempotency/genType/src/ResolvedName.res @@ -6,7 +6,7 @@ let fromString = x => list{x} let toList = x => x -let toString = x => x |> String.concat("_") +let toString = x => x->String.concat("_") type eq = (t, t) @@ -27,28 +27,28 @@ let rec applyEquation = (~el: t, eq: eq): list => switch (eq, el) { | ((list{}, rhs), _) => list{\"@"(rhs, el)} | ((list{s1, ...rest1}, rhs), list{s2, ...rest2}) => - s1 == s2 ? (rest1, rhs) |> applyEquation(~el=rest2) : list{} + s1 == s2 ? (rest1, rhs)->applyEquation(~el=rest2) : list{} | ((list{_, ..._}, _), list{}) => list{} } let rec applyEquationsToElements = (~eqs: list, ~seen, elements: list): list => { let applyEqs = el => { let freshElements = - eqs |> List.map(applyEquation(~el)) |> List.concat |> List.filter(y => !NameSet.mem(y, seen)) - freshElements |> List.map(elFresh => (elFresh, el)) + eqs->List.map(applyEquation(~el))->List.concat->List.filter(y => !NameSet.mem(y, seen)) + freshElements->List.map(elFresh => (elFresh, el)) } - let newEquations = elements |> List.map(applyEqs) |> List.concat - let newElements = newEquations |> List.map(fst) - let newSeen = NameSet.union(seen, newElements |> NameSet.of_list) + let newEquations = elements->List.map(applyEqs)->List.concat + let newElements = newEquations->List.map(fst) + let newSeen = NameSet.union(seen, newElements->NameSet.of_list) newEquations == list{} ? newEquations - : \"@"(newEquations, newElements |> applyEquationsToElements(~eqs, ~seen=newSeen)) + : \"@"(newEquations, newElements->applyEquationsToElements(~eqs, ~seen=newSeen)) } /* Apply equations of the form e.g. X.Y = A from the alias: module A = X.Y. Return a list of equations on types. E.g. if the element is X.Y.t, return equation A.t = X.Y.t */ let applyEquations = (~eqs: list, el: t): list => - list{el} |> applyEquationsToElements(~eqs, ~seen=NameSet.empty) + list{el}->applyEquationsToElements(~eqs, ~seen=NameSet.empty) diff --git a/tests/syntax_tests/data/idempotency/genType/src/Runtime.res b/tests/syntax_tests/data/idempotency/genType/src/Runtime.res index 5696bbdff5..239b8e4dd7 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/Runtime.res +++ b/tests/syntax_tests/data/idempotency/genType/src/Runtime.res @@ -20,7 +20,7 @@ type rec moduleAccessPath = | Root(string) | Dot(moduleAccessPath, moduleItem) -let recordValueToString = recordValue => recordValue |> string_of_int +let recordValueToString = recordValue => recordValue->string_of_int let recordGen = () => {unboxed: 0, boxed: 0} @@ -48,8 +48,8 @@ let rec emitModuleAccessPath = (~config, moduleAccessPath) => | Root(s) => s | Dot(p, moduleItem) => p - |> emitModuleAccessPath(~config) - |> ( + ->emitModuleAccessPath(~config) + ->( config.modulesAsObjects ? EmitText.fieldAccess(~label=moduleItem.name) : EmitText.arrayAccess(~index=moduleItem.index) @@ -58,46 +58,46 @@ let rec emitModuleAccessPath = (~config, moduleAccessPath) => let emitVariantLabel = (~comment=true, ~polymorphic, label) => if polymorphic { - (comment ? label |> EmitText.comment : "") ++ (label |> Btype.hash_variant |> string_of_int) + (comment ? label->EmitText.comment : "") ++ (label->Btype.hash_variant->string_of_int) } else { label } let emitVariantGetLabel = (~polymorphic, x) => if polymorphic { - x |> EmitText.arrayAccess(~index=0) + x->EmitText.arrayAccess(~index=0) } else { - x |> EmitText.fieldAccess(~label="tag") + x->EmitText.fieldAccess(~label="tag") } let emitVariantGetPayload = (~numArgs, ~polymorphic, x) => if polymorphic { - x |> EmitText.arrayAccess(~index=1) + x->EmitText.arrayAccess(~index=1) } else if numArgs == 1 { - x |> EmitText.arrayAccess(~index=0) + x->EmitText.arrayAccess(~index=0) } else if numArgs == 0 { /* inline record */ x } else { /* to convert a runtime block to a tuple, remove the tag */ - x |> EmitText.arraySlice + x->EmitText.arraySlice } let emitVariantWithPayload = (~config, ~label, ~numArgs, ~polymorphic, x) => if polymorphic { - EmitText.array(list{label |> emitVariantLabel(~polymorphic), x}) + EmitText.array(list{label->emitVariantLabel(~polymorphic), x}) } else { config.emitCreateBucklescriptBlock = true - let args = numArgs == 1 ? list{x} |> EmitText.array : x - createRescriptBlock |> EmitText.funCall(~args=list{label, args}) + let args = numArgs == 1 ? list{x}->EmitText.array : x + createRescriptBlock->EmitText.funCall(~args=list{label, args}) } let jsVariantTag = "tag" let jsVariantValue = "value" -let emitJSVariantGetLabel = x => x |> EmitText.fieldAccess(~label=jsVariantTag) +let emitJSVariantGetLabel = x => x->EmitText.fieldAccess(~label=jsVariantTag) -let emitJSVariantGetPayload = x => x |> EmitText.fieldAccess(~label=jsVariantValue) +let emitJSVariantGetPayload = x => x->EmitText.fieldAccess(~label=jsVariantValue) let emitJSVariantWithPayload = (~label, x) => "{" ++ (jsVariantTag ++ (":" ++ (label ++ (", " ++ (jsVariantValue ++ (":" ++ (x ++ "}"))))))) @@ -172,8 +172,8 @@ module Mangle = { "asr", ] - let table = Hashtbl.create(keywords |> Array.length) - keywords |> Array.iter(x => Hashtbl.add(table, "_" ++ x, x)) + let table = Hashtbl.create(keywords->Array.length) + keywords->Array.iter(x => Hashtbl.add(table, "_" ++ x, x)) /* Apply ReScript's mangling rules for object field names: @@ -181,7 +181,7 @@ module Mangle = { Otherwise remove leading "_" when followed by an uppercase letter, or keyword. */ let translate = x => { - let len = x |> String.length + let len = x->String.length if len > 2 && (String.get(x, len - 1) == '_' && String.get(x, len - 2) == '_') { /* "foo__" -> "foo" */ String.sub(x, 0, len - 2) diff --git a/tests/syntax_tests/data/idempotency/genType/src/TranslateCoreType.res b/tests/syntax_tests/data/idempotency/genType/src/TranslateCoreType.res index fa6c120ae3..3e12050e07 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/TranslateCoreType.res +++ b/tests/syntax_tests/data/idempotency/genType/src/TranslateCoreType.res @@ -26,26 +26,26 @@ let processVariant = rowFields => { Typedtree.Ttag({txt: label}, attributes, _, /* only variants with no payload */ list{}), ...otherFields, } => - otherFields |> loop( + otherFields->loop( ~noPayloads=list{(label, attributes), ...noPayloads}, ~payloads, ~unknowns, ) | list{Ttag({txt: label}, attributes, _, list{payload}), ...otherFields} => - otherFields |> loop( + otherFields->loop( ~noPayloads, ~payloads=list{(label, attributes, payload), ...payloads}, ~unknowns, ) | list{Ttag(_, _, _, list{_, _, ..._}) | Tinherit(_), ...otherFields} => - otherFields |> loop(~noPayloads, ~payloads, ~unknowns=list{"Tinherit", ...unknowns}) + otherFields->loop(~noPayloads, ~payloads, ~unknowns=list{"Tinherit", ...unknowns}) | list{} => { - noPayloads: noPayloads |> List.rev, - payloads: payloads |> List.rev, - unknowns: unknowns |> List.rev, + noPayloads: noPayloads->List.rev, + payloads: payloads->List.rev, + unknowns: unknowns->List.rev, } } - rowFields |> loop(~noPayloads=list{}, ~payloads=list{}, ~unknowns=list{}) + rowFields->loop(~noPayloads=list{}, ~payloads=list{}, ~unknowns=list{}) } let rec translateArrowType = ( @@ -59,9 +59,9 @@ let rec translateArrowType = ( ) => switch coreType.ctyp_desc { | Ttyp_arrow(Nolabel, coreType1, coreType2) => - let {dependencies, type_} = coreType1 |> translateCoreType_(~config, ~typeVarsGen, ~typeEnv, _) + let {dependencies, type_} = coreType1->translateCoreType_(~config, ~typeVarsGen, ~typeEnv, _) let nextRevDeps = List.rev_append(dependencies, revArgDeps) - coreType2 |> translateArrowType( + coreType2->translateArrowType( ~config, ~typeVarsGen, ~noFunctionReturnDependencies, @@ -70,48 +70,48 @@ let rec translateArrowType = ( ~revArgs=list{(Nolabel, type_), ...revArgs}, ) | Ttyp_arrow((Labelled(lbl) | Optional(lbl)) as label, coreType1, coreType2) => - let asLabel = switch coreType.ctyp_attributes |> Annotation.getGenTypeAsRenaming { + let asLabel = switch coreType.ctyp_attributes->Annotation.getGenTypeAsRenaming { | Some(s) => s | None => "" } - switch coreType1 |> removeOption(~label) { + switch coreType1->removeOption(~label) { | None => let {dependencies, type_: type1} = - coreType1 |> translateCoreType_(~config, ~typeVarsGen, ~typeEnv) + coreType1->translateCoreType_(~config, ~typeVarsGen, ~typeEnv) let nextRevDeps = List.rev_append(dependencies, revArgDeps) - coreType2 |> translateArrowType( + coreType2->translateArrowType( ~config, ~typeVarsGen, ~noFunctionReturnDependencies, ~typeEnv, ~revArgDeps=nextRevDeps, ~revArgs=list{ - (Label(asLabel == "" ? lbl |> Runtime.mangleObjectField : asLabel), type1), + (Label(asLabel == "" ? lbl->Runtime.mangleObjectField : asLabel), type1), ...revArgs, }, ) | Some((lbl, t1)) => - let {dependencies, type_: type1} = t1 |> translateCoreType_(~config, ~typeVarsGen, ~typeEnv) + let {dependencies, type_: type1} = t1->translateCoreType_(~config, ~typeVarsGen, ~typeEnv) let nextRevDeps = List.rev_append(dependencies, revArgDeps) - coreType2 |> translateArrowType( + coreType2->translateArrowType( ~config, ~typeVarsGen, ~noFunctionReturnDependencies, ~typeEnv, ~revArgDeps=nextRevDeps, ~revArgs=list{ - (OptLabel(asLabel == "" ? lbl |> Runtime.mangleObjectField : asLabel), type1), + (OptLabel(asLabel == "" ? lbl->Runtime.mangleObjectField : asLabel), type1), ...revArgs, }, ) } | _ => let {dependencies, type_: retType} = - coreType |> translateCoreType_(~config, ~typeVarsGen, ~typeEnv) + coreType->translateCoreType_(~config, ~typeVarsGen, ~typeEnv) let allDeps = List.rev_append(revArgDeps, noFunctionReturnDependencies ? list{} : dependencies) - let labeledConvertableTypes = revArgs |> List.rev - let argTypes = labeledConvertableTypes |> NamedArgs.group + let labeledConvertableTypes = revArgs->List.rev + let argTypes = labeledConvertableTypes->NamedArgs.group let functionType = Function({ argTypes: argTypes, @@ -132,7 +132,7 @@ and translateCoreType_ = ( ) => switch coreType.ctyp_desc { | Ttyp_alias(ct, _) => - ct |> translateCoreType_(~config, ~typeVarsGen, ~noFunctionReturnDependencies=false, ~typeEnv) + ct->translateCoreType_(~config, ~typeVarsGen, ~noFunctionReturnDependencies=false, ~typeEnv) | Ttyp_constr( Pdot(Pident({name: "Js"}), "t", _) as path, @@ -148,13 +148,13 @@ and translateCoreType_ = ( switch objectField { | Typedtree.OTtag({txt: name}, _, t) => ( name, - name |> Runtime.isMutableObjectField + name->Runtime.isMutableObjectField ? {dependencies: list{}, type_: ident("")} - : t |> translateCoreType_(~config, ~typeVarsGen, ~typeEnv), + : t->translateCoreType_(~config, ~typeVarsGen, ~typeEnv), ) - | OTinherit(t) => ("Inherit", t |> translateCoreType_(~config, ~typeVarsGen, ~typeEnv)) + | OTinherit(t) => ("Inherit", t->translateCoreType_(~config, ~typeVarsGen, ~typeEnv)) } - let fieldsTranslations = tObj |> List.map(getFieldType) + let fieldsTranslations = tObj->List.map(getFieldType) translateConstr( ~config, ~fieldsTranslations, @@ -165,7 +165,7 @@ and translateCoreType_ = ( ) | Ttyp_constr(path, _, typeParams) => - let paramsTranslation = typeParams |> translateCoreTypes_(~config, ~typeVarsGen, ~typeEnv) + let paramsTranslation = typeParams->translateCoreTypes_(~config, ~typeVarsGen, ~typeEnv) TranslateTypeExprFromTypes.translateConstr( ~config, ~fieldsTranslations=list{}, @@ -176,10 +176,10 @@ and translateCoreType_ = ( ) | Ttyp_poly(_, t) => - t |> translateCoreType_(~config, ~typeVarsGen, ~noFunctionReturnDependencies, ~typeEnv) + t->translateCoreType_(~config, ~typeVarsGen, ~noFunctionReturnDependencies, ~typeEnv) | Ttyp_arrow(_) => - coreType |> translateArrowType( + coreType->translateArrowType( ~config, ~typeVarsGen, ~noFunctionReturnDependencies, @@ -189,10 +189,10 @@ and translateCoreType_ = ( ) | Ttyp_tuple(listExp) => - let innerTypesTranslation = listExp |> translateCoreTypes_(~config, ~typeVarsGen, ~typeEnv) - let innerTypes = innerTypesTranslation |> List.map(({type_}) => type_) + let innerTypesTranslation = listExp->translateCoreTypes_(~config, ~typeVarsGen, ~typeEnv) + let innerTypes = innerTypesTranslation->List.map(({type_}) => type_) let innerTypesDeps = - innerTypesTranslation |> List.map(({dependencies}) => dependencies) |> List.concat + innerTypesTranslation->List.map(({dependencies}) => dependencies)->List.concat let tupleType = Tuple(innerTypes) @@ -201,45 +201,45 @@ and translateCoreType_ = ( | Ttyp_var(s) => {dependencies: list{}, type_: TypeVar(s)} | Ttyp_variant(rowFields, _, _) => - switch rowFields |> processVariant { + switch rowFields->processVariant { | {noPayloads, payloads, unknowns: list{}} => let noPayloads = - noPayloads |> List.map(((label, _attibutes)) => {label: label, labelJS: StringLabel(label)}) + noPayloads->List.map(((label, _attibutes)) => {label: label, labelJS: StringLabel(label)}) let payloadsTranslations = - payloads |> List.map(((label, attributes, payload)) => ( + payloads->List.map(((label, attributes, payload)) => ( label, attributes, - payload |> translateCoreType_(~config, ~typeVarsGen, ~typeEnv), + payload->translateCoreType_(~config, ~typeVarsGen, ~typeEnv), )) - let payloads = payloadsTranslations |> List.map(((label, _attributes, translation)) => { + let payloads = payloadsTranslations->List.map(((label, _attributes, translation)) => { let numArgs = 1 ({label: label, labelJS: StringLabel(label)}, numArgs, translation.type_) }) let type_ = createVariant(~noPayloads, ~payloads, ~polymorphic=true) let dependencies = - payloadsTranslations |> List.map(((_, _, {dependencies})) => dependencies) |> List.concat + payloadsTranslations->List.map(((_, _, {dependencies})) => dependencies)->List.concat {dependencies: dependencies, type_: type_} | _ => {dependencies: list{}, type_: mixedOrUnknown(~config)} } | Ttyp_package({pack_path, pack_fields}) => - switch typeEnv |> TypeEnv.lookupModuleTypeSignature(~path=pack_path) { + switch typeEnv->TypeEnv.lookupModuleTypeSignature(~path=pack_path) { | Some((signature, typeEnv)) => let typeEquationsTranslation = - pack_fields |> List.map(((x, t)) => ( + pack_fields->List.map(((x, t)) => ( x.Asttypes.txt, - t |> translateCoreType_(~config, ~typeVarsGen, ~typeEnv), + t->translateCoreType_(~config, ~typeVarsGen, ~typeEnv), )) let typeEquations = - typeEquationsTranslation |> List.map(((x, translation)) => (x, translation.type_)) + typeEquationsTranslation->List.map(((x, translation)) => (x, translation.type_)) let dependenciesFromTypeEquations = typeEquationsTranslation - |> List.map(((_, translation)) => translation.dependencies) - |> List.flatten - let typeEnv1 = typeEnv |> TypeEnv.addTypeEquations(~typeEquations) + ->List.map(((_, translation)) => translation.dependencies) + ->List.flatten + let typeEnv1 = typeEnv->TypeEnv.addTypeEquations(~typeEquations) let (dependenciesFromRecordType, type_) = - signature.sig_type |> signatureToModuleRuntimeRepresentation( + signature.sig_type->signatureToModuleRuntimeRepresentation( ~config, ~typeVarsGen, ~typeEnv=typeEnv1, @@ -256,15 +256,15 @@ and translateCoreType_ = ( | Ttyp_object(_) => {dependencies: list{}, type_: mixedOrUnknown(~config)} } and translateCoreTypes_ = (~config, ~typeVarsGen, ~typeEnv, typeExprs): list => - typeExprs |> List.map(translateCoreType_(~config, ~typeVarsGen, ~typeEnv)) + typeExprs->List.map(translateCoreType_(~config, ~typeVarsGen, ~typeEnv)) let translateCoreType = (~config, ~noFunctionReturnDependencies=?, ~typeEnv, coreType) => { let typeVarsGen = GenIdent.createTypeVarsGen() let translation = - coreType |> translateCoreType_(~config, ~typeVarsGen, ~noFunctionReturnDependencies?, ~typeEnv) + coreType->translateCoreType_(~config, ~typeVarsGen, ~noFunctionReturnDependencies?, ~typeEnv) if Debug.dependencies.contents { - translation.dependencies |> List.iter(dep => Log_.item("Dependency: %s\n", dep |> depToString)) + translation.dependencies->List.iter(dep => Log_.item("Dependency: %s\n", dep->depToString)) } translation } diff --git a/tests/syntax_tests/data/idempotency/genType/src/TranslateSignature.res b/tests/syntax_tests/data/idempotency/genType/src/TranslateSignature.res index af69083da2..fe51877278 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/TranslateSignature.res +++ b/tests/syntax_tests/data/idempotency/genType/src/TranslateSignature.res @@ -9,15 +9,15 @@ let translateSignatureValue = ( ): Translation.t => { let {Typedtree.val_id: val_id, val_desc, val_attributes} = valueDescription if Debug.translation.contents { - Log_.item("Translate Signature Value %s\n", val_id |> Ident.name) + Log_.item("Translate Signature Value %s\n", val_id->Ident.name) } let typeExpr = val_desc.ctyp_type let addAnnotationsToFunction = type_ => type_ switch (val_id, Annotation.fromAttributes(val_attributes)) { | (id, GenType) => id - |> Ident.name - |> { + ->Ident.name + ->{ open Translation Ident.name(id) == "make" ? translateComponent : translateValue }( @@ -41,25 +41,25 @@ let rec translateModuleDeclaration = ( ~typeEnv, {md_id, md_type}: Typedtree.module_declaration, ) => { - let name = md_id |> Ident.name + let name = md_id->Ident.name if Debug.translation.contents { Log_.item("Translate Module Declaration %s\n", name) } - let typeEnv = typeEnv |> TypeEnv.newModule(~name) + let typeEnv = typeEnv->TypeEnv.newModule(~name) switch md_type.mty_desc { | Tmty_signature(signature) => signature - |> translateSignature(~config, ~outputFileRelative, ~resolver, ~typeEnv) - |> Translation.combine + ->translateSignature(~config, ~outputFileRelative, ~resolver, ~typeEnv) + ->Translation.combine | Tmty_ident(path, _) => - switch typeEnv |> TypeEnv.lookupModuleTypeSignature(~path) { + switch typeEnv->TypeEnv.lookupModuleTypeSignature(~path) { | None => Translation.empty | Some((signature, _)) => signature - |> translateSignature(~config, ~outputFileRelative, ~resolver, ~typeEnv) - |> Translation.combine + ->translateSignature(~config, ~outputFileRelative, ~resolver, ~typeEnv) + ->Translation.combine } | Tmty_functor(_) => @@ -84,23 +84,23 @@ and translateModuleTypeDeclaration = ( moduleTypeDeclaration: Typedtree.module_type_declaration, ) => { if Debug.translation.contents { - Log_.item("Translate Module Type Declaration %s\n", moduleTypeDeclaration.mtd_id |> Ident.name) + Log_.item("Translate Module Type Declaration %s\n", moduleTypeDeclaration.mtd_id->Ident.name) } switch moduleTypeDeclaration { | {mtd_type: None} => Translation.empty | {mtd_id, mtd_type: Some(mtd_type)} => switch mtd_type.mty_desc { | Tmty_signature(signature) => - let name = mtd_id |> Ident.name + let name = mtd_id->Ident.name let translation = signature - |> translateSignature( + ->translateSignature( ~config, ~outputFileRelative, ~resolver, - ~typeEnv=typeEnv |> TypeEnv.newModuleType(~name, ~signature), + ~typeEnv=typeEnv->TypeEnv.newModuleType(~name, ~signature), ) - |> Translation.combine + ->Translation.combine translation | Tmty_ident(_) => @@ -133,7 +133,7 @@ and translateSignatureItem = ( | {Typedtree.sig_desc: Typedtree.Tsig_type(_, typeDeclarations)} => { importTypes: list{}, codeItems: list{}, - typeDeclarations: typeDeclarations |> TranslateTypeDeclarations.translateTypeDeclarations( + typeDeclarations: typeDeclarations->TranslateTypeDeclarations.translateTypeDeclarations( ~config, ~outputFileRelative, ~resolver, @@ -143,7 +143,7 @@ and translateSignatureItem = ( | {Typedtree.sig_desc: Tsig_value(valueDescription)} => if valueDescription.val_prim != list{} { - valueDescription |> Translation.translatePrimitive( + valueDescription->Translation.translatePrimitive( ~config, ~outputFileRelative, ~resolver, @@ -151,13 +151,13 @@ and translateSignatureItem = ( ) } else { let moduleItem = - moduleItemGen |> Runtime.newModuleItem(~name=valueDescription.val_id |> Ident.name) - typeEnv |> TypeEnv.updateModuleItem(~moduleItem) - valueDescription |> translateSignatureValue(~config, ~outputFileRelative, ~resolver, ~typeEnv) + moduleItemGen->Runtime.newModuleItem(~name=valueDescription.val_id->Ident.name) + typeEnv->TypeEnv.updateModuleItem(~moduleItem) + valueDescription->translateSignatureValue(~config, ~outputFileRelative, ~resolver, ~typeEnv) } | {Typedtree.sig_desc: Typedtree.Tsig_module(moduleDeclaration)} => - moduleDeclaration |> translateModuleDeclaration( + moduleDeclaration->translateModuleDeclaration( ~config, ~outputFileRelative, ~resolver, @@ -166,9 +166,9 @@ and translateSignatureItem = ( | {Typedtree.sig_desc: Typedtree.Tsig_modtype(moduleTypeDeclaration)} => let moduleItem = - moduleItemGen |> Runtime.newModuleItem(~name=moduleTypeDeclaration.mtd_id |> Ident.name) - typeEnv |> TypeEnv.updateModuleItem(~moduleItem) - moduleTypeDeclaration |> translateModuleTypeDeclaration( + moduleItemGen->Runtime.newModuleItem(~name=moduleTypeDeclaration.mtd_id->Ident.name) + typeEnv->TypeEnv.updateModuleItem(~moduleItem) + moduleTypeDeclaration->translateModuleTypeDeclaration( ~config, ~outputFileRelative, ~resolver, @@ -207,7 +207,7 @@ and translateSignature = (~config, ~outputFileRelative, ~resolver, ~typeEnv, sig Log_.item("Translate Signature\n") } let moduleItemGen = Runtime.moduleItemGen() - signature.Typedtree.sig_items |> List.map( + signature.Typedtree.sig_items->List.map( translateSignatureItem(~config, ~outputFileRelative, ~resolver, ~moduleItemGen, ~typeEnv), ) } diff --git a/tests/syntax_tests/data/idempotency/genType/src/TranslateSignatureFromTypes.res b/tests/syntax_tests/data/idempotency/genType/src/TranslateSignatureFromTypes.res index 5cf3613d2b..9193b6676e 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/TranslateSignatureFromTypes.res +++ b/tests/syntax_tests/data/idempotency/genType/src/TranslateSignatureFromTypes.res @@ -9,9 +9,9 @@ let translateTypeDeclarationFromTypes = ( ~id, {type_params, type_kind, type_attributes, type_manifest}: Types.type_declaration, ): list => { - typeEnv |> TypeEnv.newType(~name=id |> Ident.name) + typeEnv->TypeEnv.newType(~name=id->Ident.name) let typeName = Ident.name(id) - let typeVars = type_params |> TypeVars.extractFromTypeExpr + let typeVars = type_params->TypeVars.extractFromTypeExpr if Debug.translation.contents { Log_.item("Translate Types.type_declaration %s\n", typeName) } @@ -29,7 +29,7 @@ let translateTypeDeclarationFromTypes = ( | _ => NoDeclaration } - declarationKind |> TranslateTypeDeclarations.traslateDeclarationKind( + declarationKind->TranslateTypeDeclarations.traslateDeclarationKind( ~config, ~outputFileRelative, ~resolver, @@ -51,15 +51,15 @@ let rec translateModuleDeclarationFromTypes = ( ): Translation.t => switch moduleDeclaration.md_type { | Mty_signature(signature) => - let name = id |> Ident.name + let name = id->Ident.name signature - |> translateSignatureFromTypes( + ->translateSignatureFromTypes( ~config, ~outputFileRelative, ~resolver, - ~typeEnv=typeEnv |> TypeEnv.newModule(~name), + ~typeEnv=typeEnv->TypeEnv.newModule(~name), ) - |> Translation.combine + ->Translation.combine | Mty_ident(_) => logNotImplemented("Mty_ident " ++ __LOC__) @@ -84,7 +84,7 @@ and translateSignatureItemFromTypes = ( | Types.Sig_type(id, typeDeclaration, _) => { importTypes: list{}, codeItems: list{}, - typeDeclarations: typeDeclaration |> translateTypeDeclarationFromTypes( + typeDeclarations: typeDeclaration->translateTypeDeclarationFromTypes( ~config, ~outputFileRelative, ~resolver, @@ -94,9 +94,9 @@ and translateSignatureItemFromTypes = ( } | Types.Sig_module(id, moduleDeclaration, _) => - let moduleItem = moduleItemGen |> Runtime.newModuleItem(~name=id |> Ident.name) - typeEnv |> TypeEnv.updateModuleItem(~moduleItem) - moduleDeclaration |> translateModuleDeclarationFromTypes( + let moduleItem = moduleItemGen->Runtime.newModuleItem(~name=id->Ident.name) + typeEnv->TypeEnv.updateModuleItem(~moduleItem) + moduleDeclaration->translateModuleDeclarationFromTypes( ~config, ~outputFileRelative, ~resolver, @@ -132,7 +132,7 @@ and translateSignatureFromTypes = ( Log_.item("Translate Types.signature\n") } let moduleItemGen = Runtime.moduleItemGen() - signature |> List.map( + signature->List.map( translateSignatureItemFromTypes( ~config, ~outputFileRelative, diff --git a/tests/syntax_tests/data/idempotency/genType/src/TranslateStructure.res b/tests/syntax_tests/data/idempotency/genType/src/TranslateStructure.res index 420c093b76..9176b1efcd 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/TranslateStructure.res +++ b/tests/syntax_tests/data/idempotency/genType/src/TranslateStructure.res @@ -6,31 +6,31 @@ let rec addAnnotationsToTypes_ = (~config, ~expr: Typedtree.expression, argTypes let (fields1, nextTypes1) = addAnnotationsToFields(~config, expr, fields, nextTypes) list{{aName: aName, aType: GroupOfLabeledArgs(fields1)}, ...nextTypes1} | (Texp_function({param, cases: list{{c_rhs}}}), _, list{{aType}, ...nextTypes}) => - let nextTypes1 = nextTypes |> addAnnotationsToTypes_(~config, ~expr=c_rhs) + let nextTypes1 = nextTypes->addAnnotationsToTypes_(~config, ~expr=c_rhs) let aName = Ident.name(param) list{{aName: aName, aType: aType}, ...nextTypes1} | (Texp_record({fields: [({lbl_name: "I"}, Overridden(_, exprRecord))]}), Tconstr(path, _, _), _) - if switch path |> TranslateTypeExprFromTypes.pathToList |> List.rev { + if switch path->TranslateTypeExprFromTypes.pathToList->List.rev { | list{"Js", "Fn", _arity} => true | _ => false } => - // let uncurried1: Js.Fn.arity1(_) = {I: x => x |> string_of_int}; + // let uncurried1: Js.Fn.arity1(_) = {I: x => x->string_of_int}; addAnnotationsToTypes_(~config, ~expr=exprRecord, argTypes) | (Texp_apply({exp_desc: Texp_ident(path, _, _)}, list{(_, Some(expr1))}), _, _) => - switch path |> TranslateTypeExprFromTypes.pathToList |> List.rev { + switch path->TranslateTypeExprFromTypes.pathToList->List.rev { | list{"Js", "Internal", fn_mk} // Uncurried function definition uses Js.Internal.fn_mkX(...) if String.length(fn_mk) >= 5 && String.sub(fn_mk, 0, 5) == "fn_mk" => - argTypes |> addAnnotationsToTypes_(~config, ~expr=expr1) + argTypes->addAnnotationsToTypes_(~config, ~expr=expr1) | _ => argTypes } | _ => argTypes } and addAnnotationsToTypes = (~config, ~expr: Typedtree.expression, argTypes: list) => { let argTypes = addAnnotationsToTypes_(~config, ~expr, argTypes) - if argTypes |> List.filter(({aName}) => aName == "param") |> List.length > 1 { + if argTypes->List.filter(({aName}) => aName == "param")->List.length > 1 { // Underscore "_" appears as "param", can occur more than once - argTypes |> List.mapi((i, {aName, aType}) => { + argTypes->List.mapi((i, {aName, aType}) => { aName: aName ++ ("_" ++ string_of_int(i)), aType: aType, }) @@ -45,7 +45,7 @@ and addAnnotationsToFields = ( argTypes: list, ) => switch (expr.exp_desc, fields, argTypes) { - | (_, list{}, _) => (list{}, argTypes |> addAnnotationsToTypes(~config, ~expr)) + | (_, list{}, _) => (list{}, argTypes->addAnnotationsToTypes(~config, ~expr)) | (Texp_function({cases: list{{c_rhs}}}), list{field, ...nextFields}, _) => let (nextFields1, types1) = addAnnotationsToFields(~config, c_rhs, nextFields, argTypes) let (nameJS, nameRE) = TranslateTypeDeclarations.renameRecordField( @@ -62,7 +62,7 @@ and addAnnotationsToFields = ( let addAnnotationsToFunctionType = (~config, expr: Typedtree.expression, type_: type_) => switch type_ { | Function(function_) => - let argTypes = function_.argTypes |> addAnnotationsToTypes(~config, ~expr) + let argTypes = function_.argTypes->addAnnotationsToTypes(~config, ~expr) Function({...function_, argTypes: argTypes}) | _ => type_ } @@ -72,25 +72,25 @@ let removeValueBindingDuplicates = structureItems => { switch bindings { | list{{vb_pat: {pat_desc: Tpat_var(id, _)}} as binding, ...otherBindings} => let name = Ident.name(id) - if seen.contents |> StringSet.mem(name) { - otherBindings |> processBindings(~seen) + if seen.contents->StringSet.mem(name) { + otherBindings->processBindings(~seen) } else { - seen := seen.contents |> StringSet.add(name) - list{binding, ...otherBindings |> processBindings(~seen)} + seen := seen.contents->StringSet.add(name) + list{binding, ...otherBindings->processBindings(~seen)} } - | list{binding, ...otherBindings} => list{binding, ...otherBindings |> processBindings(~seen)} + | list{binding, ...otherBindings} => list{binding, ...otherBindings->processBindings(~seen)} | list{} => list{} } let rec processItems = (items: list, ~acc, ~seen) => switch items { | list{{Typedtree.str_desc: Tstr_value(loc, valueBindings)} as item, ...otherItems} => - let bindings = valueBindings |> processBindings(~seen) + let bindings = valueBindings->processBindings(~seen) let item = {...item, str_desc: Tstr_value(loc, bindings)} - otherItems |> processItems(~acc=list{item, ...acc}, ~seen) - | list{item, ...otherItems} => otherItems |> processItems(~acc=list{item, ...acc}, ~seen) + otherItems->processItems(~acc=list{item, ...acc}, ~seen) + | list{item, ...otherItems} => otherItems->processItems(~acc=list{item, ...acc}, ~seen) | list{} => acc } - structureItems |> List.rev |> processItems(~acc=list{}, ~seen=ref(StringSet.empty)) + structureItems->List.rev->processItems(~acc=list{}, ~seen=ref(StringSet.empty)) } let translateValueBinding = ( @@ -103,17 +103,17 @@ let translateValueBinding = ( ): Translation.t => switch vb_pat.pat_desc { | Tpat_var(id, _) => - let name = id |> Ident.name + let name = id->Ident.name if Debug.translation.contents { Log_.item("Translate Value Binding %s\n", name) } - let moduleItem = moduleItemGen |> Runtime.newModuleItem(~name) - typeEnv |> TypeEnv.updateModuleItem(~nameOpt=Some(name), ~moduleItem) + let moduleItem = moduleItemGen->Runtime.newModuleItem(~name) + typeEnv->TypeEnv.updateModuleItem(~nameOpt=Some(name), ~moduleItem) if Annotation.fromAttributes(vb_attributes) == GenType { id - |> Ident.name - |> { + ->Ident.name + ->{ open Translation Ident.name(id) == "make" ? translateComponent : translateValue }( @@ -136,17 +136,17 @@ let translateValueBinding = ( let rec removeDuplicateValueBindings = (structureItems: list) => switch structureItems { | list{{Typedtree.str_desc: Tstr_value(loc, valueBindings)} as structureItem, ...rest} => - let (boundInRest, filteredRest) = rest |> removeDuplicateValueBindings - let valueBindingsFiltered = valueBindings |> List.filter(valueBinding => + let (boundInRest, filteredRest) = rest->removeDuplicateValueBindings + let valueBindingsFiltered = valueBindings->List.filter(valueBinding => switch valueBinding { | {Typedtree.vb_pat: {pat_desc: Tpat_var(id, _)}} => - !(boundInRest |> StringSet.mem(id |> Ident.name)) + !(boundInRest->StringSet.mem(id->Ident.name)) | _ => true } ) - let bound = valueBindings |> List.fold_left((bound, valueBinding: Typedtree.value_binding) => + let bound = valueBindings->List.fold_left((bound, valueBinding: Typedtree.value_binding) => switch valueBinding { - | {vb_pat: {pat_desc: Tpat_var(id, _)}} => bound |> StringSet.add(id |> Ident.name) + | {vb_pat: {pat_desc: Tpat_var(id, _)}} => bound->StringSet.add(id->Ident.name) | _ => bound } , boundInRest) @@ -155,7 +155,7 @@ let rec removeDuplicateValueBindings = (structureItems: list - let (boundInRest, filteredRest) = rest |> removeDuplicateValueBindings + let (boundInRest, filteredRest) = rest->removeDuplicateValueBindings (boundInRest, list{structureItem, ...filteredRest}) | list{} => (StringSet.empty, list{}) @@ -169,36 +169,36 @@ let rec translateModuleBinding = ( ~moduleItemGen, {mb_id, mb_expr, mb_attributes}: Typedtree.module_binding, ): Translation.t => { - let name = mb_id |> Ident.name + let name = mb_id->Ident.name if Debug.translation.contents { Log_.item("Translate Module Binding %s\n", name) } - let moduleItem = moduleItemGen |> Runtime.newModuleItem(~name) - typeEnv |> TypeEnv.updateModuleItem(~moduleItem) - let typeEnv = typeEnv |> TypeEnv.newModule(~name) + let moduleItem = moduleItemGen->Runtime.newModuleItem(~name) + typeEnv->TypeEnv.updateModuleItem(~moduleItem) + let typeEnv = typeEnv->TypeEnv.newModule(~name) switch mb_expr.mod_desc { | Tmod_structure(structure) => - let isLetPrivate = mb_attributes |> Annotation.hasAttribute(Annotation.tagIsInternLocal) + let isLetPrivate = mb_attributes->Annotation.hasAttribute(Annotation.tagIsInternLocal) if isLetPrivate { Translation.empty } else { structure - |> translateStructure(~config, ~outputFileRelative, ~resolver, ~typeEnv) - |> Translation.combine + ->translateStructure(~config, ~outputFileRelative, ~resolver, ~typeEnv) + ->Translation.combine } | Tmod_apply(_) => /* Only look at the resulting type of the module */ switch mb_expr.mod_type { | Mty_signature(signature) => signature - |> TranslateSignatureFromTypes.translateSignatureFromTypes( + ->TranslateSignatureFromTypes.translateSignatureFromTypes( ~config, ~outputFileRelative, ~resolver, ~typeEnv, ) - |> Translation.combine + ->Translation.combine | Mty_ident(_) => logNotImplemented("Mty_ident " ++ __LOC__) @@ -215,21 +215,21 @@ let rec translateModuleBinding = ( switch moduleType { | Mty_signature(signature) => signature - |> TranslateSignatureFromTypes.translateSignatureFromTypes( + ->TranslateSignatureFromTypes.translateSignatureFromTypes( ~config, ~outputFileRelative, ~resolver, ~typeEnv, ) - |> Translation.combine + ->Translation.combine | Mty_ident(path) => - switch typeEnv |> TypeEnv.lookupModuleTypeSignature(~path) { + switch typeEnv->TypeEnv.lookupModuleTypeSignature(~path) { | None => Translation.empty | Some((signature, _)) => signature - |> TranslateSignature.translateSignature(~config, ~outputFileRelative, ~resolver, ~typeEnv) - |> Translation.combine + ->TranslateSignature.translateSignature(~config, ~outputFileRelative, ~resolver, ~typeEnv) + ->Translation.combine } | Mty_functor(_) => @@ -241,32 +241,32 @@ let rec translateModuleBinding = ( } | Tmod_ident(path, _) => - let dep = path |> Dependencies.fromPath(~config, ~typeEnv) - let internal = dep |> Dependencies.isInternal - typeEnv |> TypeEnv.addModuleEquation(~dep, ~internal) + let dep = path->Dependencies.fromPath(~config, ~typeEnv) + let internal = dep->Dependencies.isInternal + typeEnv->TypeEnv.addModuleEquation(~dep, ~internal) Translation.empty | Tmod_functor(_) => logNotImplemented("Tmod_functor " ++ __LOC__) Translation.empty | Tmod_constraint(_, Mty_ident(path), Tmodtype_explicit(_), Tcoerce_none) => - switch typeEnv |> TypeEnv.lookupModuleTypeSignature(~path) { + switch typeEnv->TypeEnv.lookupModuleTypeSignature(~path) { | None => Translation.empty | Some((signature, _)) => signature - |> TranslateSignature.translateSignature(~config, ~outputFileRelative, ~resolver, ~typeEnv) - |> Translation.combine + ->TranslateSignature.translateSignature(~config, ~outputFileRelative, ~resolver, ~typeEnv) + ->Translation.combine } | Tmod_constraint(_, Mty_signature(signature), Tmodtype_explicit(_), Tcoerce_none) => signature - |> TranslateSignatureFromTypes.translateSignatureFromTypes( + ->TranslateSignatureFromTypes.translateSignatureFromTypes( ~config, ~outputFileRelative, ~resolver, ~typeEnv, ) - |> Translation.combine + ->Translation.combine | Tmod_constraint( {mod_desc: Tmod_structure(structure)}, @@ -276,10 +276,10 @@ let rec translateModuleBinding = ( ) => { ...structure, - str_items: structure.str_items |> removeDuplicateValueBindings |> snd, + str_items: structure.str_items->removeDuplicateValueBindings->snd, } - |> translateStructure(~config, ~outputFileRelative, ~resolver, ~typeEnv) - |> Translation.combine + ->translateStructure(~config, ~outputFileRelative, ~resolver, ~typeEnv) + ->Translation.combine | Tmod_constraint(_) => logNotImplemented("Tmod_constraint " ++ __LOC__) @@ -298,7 +298,7 @@ and translateStructureItem = ( | {Typedtree.str_desc: Typedtree.Tstr_type(_, typeDeclarations)} => { importTypes: list{}, codeItems: list{}, - typeDeclarations: typeDeclarations |> TranslateTypeDeclarations.translateTypeDeclarations( + typeDeclarations: typeDeclarations->TranslateTypeDeclarations.translateTypeDeclarations( ~config, ~outputFileRelative, ~resolver, @@ -308,14 +308,14 @@ and translateStructureItem = ( | {Typedtree.str_desc: Tstr_value(_loc, valueBindings)} => valueBindings - |> List.map( + ->List.map( translateValueBinding(~config, ~outputFileRelative, ~resolver, ~moduleItemGen, ~typeEnv), ) - |> Translation.combine + ->Translation.combine | {Typedtree.str_desc: Tstr_primitive(valueDescription)} => /* external declaration */ - valueDescription |> Translation.translatePrimitive( + valueDescription->Translation.translatePrimitive( ~config, ~outputFileRelative, ~resolver, @@ -323,7 +323,7 @@ and translateStructureItem = ( ) | {Typedtree.str_desc: Tstr_module(moduleBinding)} => - moduleBinding |> translateModuleBinding( + moduleBinding->translateModuleBinding( ~config, ~outputFileRelative, ~resolver, @@ -332,7 +332,7 @@ and translateStructureItem = ( ) | {Typedtree.str_desc: Tstr_modtype(moduleTypeDeclaration)} => - moduleTypeDeclaration |> TranslateSignature.translateModuleTypeDeclaration( + moduleTypeDeclaration->TranslateSignature.translateModuleTypeDeclaration( ~config, ~outputFileRelative, ~resolver, @@ -341,10 +341,10 @@ and translateStructureItem = ( | {Typedtree.str_desc: Tstr_recmodule(moduleBindings)} => moduleBindings - |> List.map( + ->List.map( translateModuleBinding(~config, ~outputFileRelative, ~resolver, ~typeEnv, ~moduleItemGen), ) - |> Translation.combine + ->Translation.combine | { /* ReScript's encoding of @module: include with constraint. */ @@ -365,7 +365,7 @@ and translateStructureItem = ( }), _, } => - structItem1 |> translateStructureItem( + structItem1->translateStructureItem( ~config, ~outputFileRelative, ~resolver, @@ -375,13 +375,13 @@ and translateStructureItem = ( | {Typedtree.str_desc: Tstr_include({incl_type: signature})} => signature - |> TranslateSignatureFromTypes.translateSignatureFromTypes( + ->TranslateSignatureFromTypes.translateSignatureFromTypes( ~config, ~outputFileRelative, ~resolver, ~typeEnv, ) - |> Translation.combine + ->Translation.combine | {Typedtree.str_desc: Tstr_eval(_)} => logNotImplemented("Tstr_eval " ++ __LOC__) @@ -413,9 +413,9 @@ and translateStructure = (~config, ~outputFileRelative, ~resolver, ~typeEnv, str } let moduleItemGen = Runtime.moduleItemGen() structure.Typedtree.str_items - |> removeValueBindingDuplicates - |> List.map(structItem => - structItem |> translateStructureItem( + ->removeValueBindingDuplicates + ->List.map(structItem => + structItem->translateStructureItem( ~config, ~outputFileRelative, ~resolver, diff --git a/tests/syntax_tests/data/idempotency/genType/src/TranslateTypeDeclarations.res b/tests/syntax_tests/data/idempotency/genType/src/TranslateTypeDeclarations.res index ccba96cdd7..70538d42e0 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/TranslateTypeDeclarations.res +++ b/tests/syntax_tests/data/idempotency/genType/src/TranslateTypeDeclarations.res @@ -18,7 +18,7 @@ let createExportTypeFromTypeDeclaration = ( typeName, ~typeVars, ): CodeItem.exportFromTypeDeclaration => { - let resolvedTypeName = typeName |> TypeEnv.addModulePath(~typeEnv) + let resolvedTypeName = typeName->TypeEnv.addModulePath(~typeEnv) { exportType: { nameAs: nameAs, @@ -32,7 +32,7 @@ let createExportTypeFromTypeDeclaration = ( } let createCase = ((label, attributes)) => - switch attributes |> Annotation.getAttributePayload(Annotation.tagIsGenTypeAs) { + switch attributes->Annotation.getAttributePayload(Annotation.tagIsGenTypeAs) { | Some(BoolPayload(b)) => {label: label, labelJS: BoolLabel(b)} | Some(FloatPayload(s)) => {label: label, labelJS: FloatLabel(s)} | Some(IntPayload(i)) => {label: label, labelJS: IntLabel(i)} @@ -44,11 +44,11 @@ let createCase = ((label, attributes)) => // If @genType.as is used, perform renaming conversion. // If @as is used (with records-as-objects active), no conversion is required. let renameRecordField = (~config, ~attributes, ~nameRE) => - switch attributes |> Annotation.getGenTypeAsRenaming { + switch attributes->Annotation.getGenTypeAsRenaming { | Some(nameJS) => (nameJS, nameRE) | None => if config.recordsAsObjects { - switch attributes |> Annotation.getAsRenaming { + switch attributes->Annotation.getAsRenaming { | Some(name) => (name, name) | None => (nameRE, nameRE) } @@ -67,18 +67,18 @@ let traslateDeclarationKind = ( ~typeVars, declarationKind, ): list => { - let annotation = typeAttributes |> Annotation.fromAttributes + let annotation = typeAttributes->Annotation.fromAttributes let opaque = annotation == Annotation.GenTypeOpaque ? Some(true) : None /* None means don't know */ - let (importStringOpt, nameAs) = typeAttributes |> Annotation.getAttributeImportRenaming - let unboxedAnnotation = typeAttributes |> Annotation.hasAttribute(Annotation.tagIsUnboxed) + let (importStringOpt, nameAs) = typeAttributes->Annotation.getAttributeImportRenaming + let unboxedAnnotation = typeAttributes->Annotation.hasAttribute(Annotation.tagIsUnboxed) let returnTypeDeclaration = (typeDeclaration: CodeItem.typeDeclaration) => opaque == Some(true) ? list{{...typeDeclaration, importTypes: list{}}} : list{typeDeclaration} let handleGeneralDeclaration = (translation: TranslateTypeExprFromTypes.translation) => { let exportFromTypeDeclaration = - typeName |> createExportTypeFromTypeDeclaration( + typeName->createExportTypeFromTypeDeclaration( ~annotation, ~nameAs, ~opaque, @@ -87,7 +87,7 @@ let traslateDeclarationKind = ( ~typeVars, ) let importTypes = - translation.dependencies |> Translation.translateDependencies( + translation.dependencies->Translation.translateDependencies( ~config, ~outputFileRelative, ~resolver, @@ -96,7 +96,7 @@ let traslateDeclarationKind = ( } let translateLabelDeclarations = labelDeclarations => { - let fieldTranslations = labelDeclarations |> List.map(({ + let fieldTranslations = labelDeclarations->List.map(({ Types.ld_id: ld_id, ld_mutable, ld_type, @@ -105,25 +105,25 @@ let traslateDeclarationKind = ( let (nameJS, nameRE) = renameRecordField( ~attributes=ld_attributes, ~config, - ~nameRE=ld_id |> Ident.name, + ~nameRE=ld_id->Ident.name, ) let mutability = ld_mutable == Mutable ? Mutable : Immutable ( nameJS, nameRE, mutability, - ld_type |> TranslateTypeExprFromTypes.translateTypeExprFromTypes(~config, ~typeEnv), + ld_type->TranslateTypeExprFromTypes.translateTypeExprFromTypes(~config, ~typeEnv), ) }) let dependencies = fieldTranslations - |> List.map(((_, _, _, {TranslateTypeExprFromTypes.dependencies: dependencies})) => + ->List.map(((_, _, _, {TranslateTypeExprFromTypes.dependencies: dependencies})) => dependencies ) - |> List.concat + ->List.concat - let fields = fieldTranslations |> List.map((( + let fields = fieldTranslations->List.map((( nameJS, nameRE, mutable_, @@ -146,7 +146,7 @@ let traslateDeclarationKind = ( | (_, Some(importString)) => /* import type */ let typeName_ = typeName - let nameWithModulePath = typeName_ |> TypeEnv.addModulePath(~typeEnv) |> ResolvedName.toString + let nameWithModulePath = typeName_->TypeEnv.addModulePath(~typeEnv)->ResolvedName.toString let (typeName, asTypeName) = switch nameAs { | Some(asString) => (asString, "$$" ++ nameWithModulePath) | None => (nameWithModulePath, "$$" ++ nameWithModulePath) @@ -155,16 +155,16 @@ let traslateDeclarationKind = ( { CodeItem.typeName: typeName, asTypeName: Some(asTypeName), - importPath: importString |> ImportPath.fromStringUnsafe, + importPath: importString->ImportPath.fromStringUnsafe, }, } let exportFromTypeDeclaration = /* Make the imported type usable from other modules by exporting it too. */ - typeName_ |> createExportTypeFromTypeDeclaration( + typeName_->createExportTypeFromTypeDeclaration( ~annotation=GenType, ~nameAs=None, ~opaque=Some(false), - ~type_=asTypeName |> ident(~typeArgs=typeVars |> List.map(s => TypeVar(s))), + ~type_=asTypeName->ident(~typeArgs=typeVars->List.map(s => TypeVar(s))), ~typeEnv, ~typeVars, ) @@ -173,7 +173,7 @@ let traslateDeclarationKind = ( | (GeneralDeclarationFromTypes(None) | GeneralDeclaration(None), None) => { CodeItem.importTypes: list{}, - exportFromTypeDeclaration: typeName |> createExportTypeFromTypeDeclaration( + exportFromTypeDeclaration: typeName->createExportTypeFromTypeDeclaration( ~annotation, ~nameAs, ~opaque=Some(true), @@ -181,28 +181,28 @@ let traslateDeclarationKind = ( ~typeEnv, ~typeVars, ), - } |> returnTypeDeclaration + }->returnTypeDeclaration | (GeneralDeclarationFromTypes(Some(typeExpr)), None) => let translation = - typeExpr |> TranslateTypeExprFromTypes.translateTypeExprFromTypes(~config, ~typeEnv) - translation |> handleGeneralDeclaration |> returnTypeDeclaration + typeExpr->TranslateTypeExprFromTypes.translateTypeExprFromTypes(~config, ~typeEnv) + translation->handleGeneralDeclaration->returnTypeDeclaration | (GeneralDeclaration(Some(coreType)), None) => - let translation = coreType |> TranslateCoreType.translateCoreType(~config, ~typeEnv) + let translation = coreType->TranslateCoreType.translateCoreType(~config, ~typeEnv) let type_ = switch (coreType, translation.type_) { | ({ctyp_desc: Ttyp_variant(rowFields, _, _)}, Variant(variant)) => - let rowFieldsVariants = rowFields |> TranslateCoreType.processVariant - let noPayloads = rowFieldsVariants.noPayloads |> List.map(createCase) + let rowFieldsVariants = rowFields->TranslateCoreType.processVariant + let noPayloads = rowFieldsVariants.noPayloads->List.map(createCase) let payloads = if ( - variant.payloads |> List.length == (rowFieldsVariants.payloads |> List.length) + variant.payloads->List.length == (rowFieldsVariants.payloads->List.length) ) { - List.combine(variant.payloads, rowFieldsVariants.payloads) |> List.map((( + List.combine(variant.payloads, rowFieldsVariants.payloads)->List.map((( (_case, i, type_), (label, attributes, _), )) => { - let case = (label, attributes) |> createCase + let case = (label, attributes)->createCase (case, i, type_) }) } else { @@ -212,18 +212,18 @@ let traslateDeclarationKind = ( createVariant(~noPayloads, ~payloads, ~polymorphic=true) | _ => translation.type_ } - {...translation, type_: type_} |> handleGeneralDeclaration |> returnTypeDeclaration + {...translation, type_: type_}->handleGeneralDeclaration->returnTypeDeclaration | (RecordDeclarationFromTypes(labelDeclarations), None) => let {TranslateTypeExprFromTypes.dependencies: dependencies, type_} = - labelDeclarations |> translateLabelDeclarations + labelDeclarations->translateLabelDeclarations let importTypes = - dependencies |> Translation.translateDependencies(~config, ~outputFileRelative, ~resolver) + dependencies->Translation.translateDependencies(~config, ~outputFileRelative, ~resolver) { CodeItem.importTypes: importTypes, - exportFromTypeDeclaration: typeName |> createExportTypeFromTypeDeclaration( + exportFromTypeDeclaration: typeName->createExportTypeFromTypeDeclaration( ~annotation, ~nameAs, ~opaque, @@ -231,18 +231,18 @@ let traslateDeclarationKind = ( ~typeEnv, ~typeVars, ), - } |> returnTypeDeclaration + }->returnTypeDeclaration | (VariantDeclarationFromTypes(constructorDeclarations), None) => let recordGen = Runtime.recordGen() - let variants = constructorDeclarations |> List.map(constructorDeclaration => { + let variants = constructorDeclarations->List.map(constructorDeclaration => { let constructorArgs = constructorDeclaration.Types.cd_args - let name = constructorDeclaration.Types.cd_id |> Ident.name + let name = constructorDeclaration.Types.cd_id->Ident.name let attributes = constructorDeclaration.Types.cd_attributes let argsTranslation = switch constructorArgs { | Cstr_tuple(typeExprs) => - typeExprs |> TranslateTypeExprFromTypes.translateTypeExprsFromTypes(~config, ~typeEnv) - | Cstr_record(labelDeclarations) => list{labelDeclarations |> translateLabelDeclarations} + typeExprs->TranslateTypeExprFromTypes.translateTypeExprsFromTypes(~config, ~typeEnv) + | Cstr_record(labelDeclarations) => list{labelDeclarations->translateLabelDeclarations} } let inlineRecord = switch constructorArgs { | Cstr_tuple(_) => false @@ -250,37 +250,37 @@ let traslateDeclarationKind = ( } let argTypes = - argsTranslation |> List.map(({TranslateTypeExprFromTypes.type_: type_}) => type_) + argsTranslation->List.map(({TranslateTypeExprFromTypes.type_: type_}) => type_) let importTypes = argsTranslation - |> List.map(({TranslateTypeExprFromTypes.dependencies: dependencies}) => dependencies) - |> List.concat - |> Translation.translateDependencies(~config, ~outputFileRelative, ~resolver) + ->List.map(({TranslateTypeExprFromTypes.dependencies: dependencies}) => dependencies) + ->List.concat + ->Translation.translateDependencies(~config, ~outputFileRelative, ~resolver) let recordValue = - recordGen |> Runtime.newRecordValue(~unboxed=constructorArgs == Cstr_tuple(list{})) + recordGen->Runtime.newRecordValue(~unboxed=constructorArgs == Cstr_tuple(list{})) ( name, attributes, argTypes, importTypes, inlineRecord, - recordValue |> Runtime.recordValueToString, + recordValue->Runtime.recordValueToString, ) }) let (variantsNoPayload, variantsWithPayload) = - variants |> List.partition(((_, _, argTypes, _, _, _)) => argTypes == list{}) + variants->List.partition(((_, _, argTypes, _, _, _)) => argTypes == list{}) let noPayloads = - variantsNoPayload |> List.map((( + variantsNoPayload->List.map((( name, attributes, _argTypes, _importTypes, _inlineRecord, recordValue, - )) => {...(name, attributes) |> createCase, label: recordValue}) - let payloads = variantsWithPayload |> List.map((( + )) => {...(name, attributes)->createCase, label: recordValue}) + let payloads = variantsWithPayload->List.map((( name, attributes, argTypes, @@ -292,15 +292,15 @@ let traslateDeclarationKind = ( | list{type_} => type_ | _ => Tuple(argTypes) } - let numArgs = inlineRecord ? 0 : argTypes |> List.length - ({...(name, attributes) |> createCase, label: recordValue}, numArgs, type_) + let numArgs = inlineRecord ? 0 : argTypes->List.length + ({...(name, attributes)->createCase, label: recordValue}, numArgs, type_) }) let variantTyp = switch (noPayloads, payloads) { | (list{}, list{(_c, _, type_)}) if unboxedAnnotation && config.useUnboxedAnnotations => type_ | _ => createVariant(~noPayloads, ~payloads, ~polymorphic=false) } - let resolvedTypeName = typeName |> TypeEnv.addModulePath(~typeEnv) + let resolvedTypeName = typeName->TypeEnv.addModulePath(~typeEnv) let exportFromTypeDeclaration = { CodeItem.exportType: { @@ -313,12 +313,12 @@ let traslateDeclarationKind = ( annotation: annotation, } let importTypes = - variants |> List.map(((_, _, _, importTypes, _, _)) => importTypes) |> List.concat + variants->List.map(((_, _, _, importTypes, _, _)) => importTypes)->List.concat { CodeItem.exportFromTypeDeclaration: exportFromTypeDeclaration, importTypes: importTypes, - } |> returnTypeDeclaration + }->returnTypeDeclaration | (NoDeclaration, None) => list{} } @@ -335,13 +335,13 @@ let translateTypeDeclaration = ( {typ_attributes, typ_id, typ_manifest, typ_params, typ_type}: Typedtree.type_declaration, ): list => { if Debug.translation.contents { - Log_.item("Translate Type Declaration %s\n", typ_id |> Ident.name) + Log_.item("Translate Type Declaration %s\n", typ_id->Ident.name) } - typeEnv |> TypeEnv.newType(~name=typ_id |> Ident.name) + typeEnv->TypeEnv.newType(~name=typ_id->Ident.name) let typeName = Ident.name(typ_id) - let typeVars = typ_params |> List.map(((coreType, _)) => coreType) |> TypeVars.extractFromCoreType + let typeVars = typ_params->List.map(((coreType, _)) => coreType)->TypeVars.extractFromCoreType let declarationKind = switch typ_type.type_kind { | Type_record(labelDeclarations, _) => RecordDeclarationFromTypes(labelDeclarations) @@ -353,7 +353,7 @@ let translateTypeDeclaration = ( | _ => NoDeclaration } - declarationKind |> traslateDeclarationKind( + declarationKind->traslateDeclarationKind( ~config, ~outputFileRelative, ~resolver, @@ -372,5 +372,5 @@ let translateTypeDeclarations = ( typeDeclarations: list, ): list => typeDeclarations - |> List.map(translateTypeDeclaration(~config, ~outputFileRelative, ~resolver, ~typeEnv)) - |> List.concat + ->List.map(translateTypeDeclaration(~config, ~outputFileRelative, ~resolver, ~typeEnv)) + ->List.concat diff --git a/tests/syntax_tests/data/idempotency/genType/src/TranslateTypeExprFromTypes.res b/tests/syntax_tests/data/idempotency/genType/src/TranslateTypeExprFromTypes.res index 2c0774af27..6af723f097 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/TranslateTypeExprFromTypes.res +++ b/tests/syntax_tests/data/idempotency/genType/src/TranslateTypeExprFromTypes.res @@ -12,14 +12,14 @@ let rec removeOption = (~label: Asttypes.arg_label, typeExpr: Types.type_expr) = | (Tconstr(Pdot(Path.Pident(nameSpace), id, _), list{t}, _), Optional(lbl)) if Ident.name(nameSpace) == "FB" && id == "option" => Some((lbl, t)) - | (Tlink(t), _) => t |> removeOption(~label) + | (Tlink(t), _) => t->removeOption(~label) | _ => None } let rec pathToList = path => switch path { - | Path.Pident(id) => list{id |> Ident.name} - | Path.Pdot(p, s, _) => list{s, ...p |> pathToList} + | Path.Pident(id) => list{id->Ident.name} + | Path.Pdot(p, s, _) => list{s, ...p->pathToList} | Path.Papply(_) => list{} } @@ -32,21 +32,21 @@ let translateConstr = ( ~typeEnv, ) => { let defaultCase = () => { - let typeArgs = paramsTranslation |> List.map(({type_}: translation) => type_) + let typeArgs = paramsTranslation->List.map(({type_}: translation) => type_) let typeParamDeps = - paramsTranslation |> List.map(({dependencies}) => dependencies) |> List.concat + paramsTranslation->List.map(({dependencies}) => dependencies)->List.concat - switch typeEnv |> TypeEnv.applyTypeEquations(~config, ~path) { + switch typeEnv->TypeEnv.applyTypeEquations(~config, ~path) { | Some(type_) => {dependencies: typeParamDeps, type_: type_} | None => - let dep = path |> Dependencies.fromPath(~config, ~typeEnv) + let dep = path->Dependencies.fromPath(~config, ~typeEnv) { dependencies: list{dep, ...typeParamDeps}, - type_: Ident({builtin: false, name: dep |> depToString, typeArgs: typeArgs}), + type_: Ident({builtin: false, name: dep->depToString, typeArgs: typeArgs}), } } } - switch (path |> pathToList |> List.rev, paramsTranslation) { + switch (path->pathToList->List.rev, paramsTranslation) { | (list{"FB", "bool"} | list{"bool"}, list{}) => {dependencies: list{}, type_: booleanT} | (list{"FB", "int"} | list{"int"}, list{}) => {dependencies: list{}, type_: numberT} @@ -194,7 +194,7 @@ let translateConstr = ( ) => { dependencies: \"@"(argsDependencies, ret.dependencies), type_: Function({ - argTypes: ts |> List.map(type_ => {aName: "", aType: type_}), + argTypes: ts->List.map(type_ => {aName: "", aType: type_}), componentName: None, retType: ret.type_, typeVars: list{}, @@ -268,7 +268,7 @@ let translateConstr = ( | Variant({payloads: list{(_, _, Tuple(argTypes))}}) => argTypes | Variant({payloads: list{(_, _, type_)}}) => list{type_} | _ => list{singleT} - } |> List.map(type_ => {aName: "", aType: type_}) + }->List.map(type_ => {aName: "", aType: type_}) { dependencies: \"@"(argsDependencies, ret.dependencies), type_: Function({ @@ -307,7 +307,7 @@ let translateConstr = ( ) => { dependencies: \"@"(argsDependencies, ret.dependencies), type_: Function({ - argTypes: ts |> List.map(type_ => {aName: "", aType: type_}), + argTypes: ts->List.map(type_ => {aName: "", aType: type_}), componentName: None, retType: ret.type_, typeVars: list{}, @@ -316,26 +316,26 @@ let translateConstr = ( } | (list{"Js", "t"}, _) => let dependencies = - fieldsTranslations |> List.map(((_, {dependencies})) => dependencies) |> List.concat + fieldsTranslations->List.map(((_, {dependencies})) => dependencies)->List.concat let rec checkMutableField = (~acc=list{}, fields) => switch fields { | list{(previousName, {type_: _}), (name, {type_}), ...rest} if Runtime.checkMutableObjectField(~previousName, ~name) => /* The field was annotated "@set" */ - rest |> checkMutableField(~acc=list{(name, type_, Mutable), ...acc}) + rest->checkMutableField(~acc=list{(name, type_, Mutable), ...acc}) | list{(name, {type_}), ...rest} => - rest |> checkMutableField(~acc=list{(name, type_, Immutable), ...acc}) - | list{} => acc |> List.rev + rest->checkMutableField(~acc=list{(name, type_, Immutable), ...acc}) + | list{} => acc->List.rev } let fields = fieldsTranslations - |> checkMutableField - |> List.map(((name, t, mutable_)) => { + ->checkMutableField + ->List.map(((name, t, mutable_)) => { let (optional, type_) = switch t { | Option(t) => (Optional, t) | _ => (Mandatory, t) } - let name = name |> Runtime.mangleObjectField + let name = name->Runtime.mangleObjectField {mutable_: mutable_, nameJS: name, nameRE: name, optional: optional, type_: type_} }) let type_ = Object(closedFlag, fields) @@ -362,18 +362,18 @@ let processVariant = rowFields => { ), ...otherFields, } => - otherFields |> loop(~noPayloads=list{label, ...noPayloads}, ~payloads, ~unknowns) + otherFields->loop(~noPayloads=list{label, ...noPayloads}, ~payloads, ~unknowns) | list{(label, Rpresent(Some(payload))), ...otherFields} => - otherFields |> loop(~noPayloads, ~payloads=list{(label, payload), ...payloads}, ~unknowns) + otherFields->loop(~noPayloads, ~payloads=list{(label, payload), ...payloads}, ~unknowns) | list{(label, Rabsent | Reither(false, _, _, _)), ...otherFields} => - otherFields |> loop(~noPayloads, ~payloads, ~unknowns=list{label, ...unknowns}) + otherFields->loop(~noPayloads, ~payloads, ~unknowns=list{label, ...unknowns}) | list{} => { - noPayloads: noPayloads |> List.rev, - payloads: payloads |> List.rev, - unknowns: unknowns |> List.rev, + noPayloads: noPayloads->List.rev, + payloads: payloads->List.rev, + unknowns: unknowns->List.rev, } } - rowFields |> loop(~noPayloads=list{}, ~payloads=list{}, ~unknowns=list{}) + rowFields->loop(~noPayloads=list{}, ~payloads=list{}, ~unknowns=list{}) } let rec translateArrowType = ( @@ -398,9 +398,9 @@ let rec translateArrowType = ( ) | Tarrow(Nolabel, typeExpr1, typeExpr2, _) => let {dependencies, type_} = - typeExpr1 |> translateTypeExprFromTypes_(~config, ~typeVarsGen, ~typeEnv, _) + typeExpr1->translateTypeExprFromTypes_(~config, ~typeVarsGen, ~typeEnv, _) let nextRevDeps = List.rev_append(dependencies, revArgDeps) - typeExpr2 |> translateArrowType( + typeExpr2->translateArrowType( ~config, ~typeVarsGen, ~noFunctionReturnDependencies, @@ -409,39 +409,39 @@ let rec translateArrowType = ( ~revArgs=list{(Nolabel, type_), ...revArgs}, ) | Tarrow((Labelled(lbl) | Optional(lbl)) as label, typeExpr1, typeExpr2, _) => - switch typeExpr1 |> removeOption(~label) { + switch typeExpr1->removeOption(~label) { | None => let {dependencies, type_: type1} = - typeExpr1 |> translateTypeExprFromTypes_(~config, ~typeVarsGen, ~typeEnv) + typeExpr1->translateTypeExprFromTypes_(~config, ~typeVarsGen, ~typeEnv) let nextRevDeps = List.rev_append(dependencies, revArgDeps) - typeExpr2 |> translateArrowType( + typeExpr2->translateArrowType( ~config, ~typeVarsGen, ~noFunctionReturnDependencies, ~typeEnv, ~revArgDeps=nextRevDeps, - ~revArgs=list{(Label(lbl |> Runtime.mangleObjectField), type1), ...revArgs}, + ~revArgs=list{(Label(lbl->Runtime.mangleObjectField), type1), ...revArgs}, ) | Some((lbl, t1)) => let {dependencies, type_: type1} = - t1 |> translateTypeExprFromTypes_(~config, ~typeVarsGen, ~typeEnv) + t1->translateTypeExprFromTypes_(~config, ~typeVarsGen, ~typeEnv) let nextRevDeps = List.rev_append(dependencies, revArgDeps) - typeExpr2 |> translateArrowType( + typeExpr2->translateArrowType( ~config, ~typeVarsGen, ~noFunctionReturnDependencies, ~typeEnv, ~revArgDeps=nextRevDeps, - ~revArgs=list{(OptLabel(lbl |> Runtime.mangleObjectField), type1), ...revArgs}, + ~revArgs=list{(OptLabel(lbl->Runtime.mangleObjectField), type1), ...revArgs}, ) } | _ => let {dependencies, type_: retType} = - typeExpr |> translateTypeExprFromTypes_(~config, ~typeVarsGen, ~typeEnv) + typeExpr->translateTypeExprFromTypes_(~config, ~typeVarsGen, ~typeEnv) let allDeps = List.rev_append(revArgDeps, noFunctionReturnDependencies ? list{} : dependencies) - let labeledConvertableTypes = revArgs |> List.rev - let argTypes = labeledConvertableTypes |> NamedArgs.group + let labeledConvertableTypes = revArgs->List.rev + let argTypes = labeledConvertableTypes->NamedArgs.group let functionType = Function({ argTypes: argTypes, @@ -471,24 +471,24 @@ and translateTypeExprFromTypes_ = ( let rec getFieldTypes = (texp: Types.type_expr) => switch texp.desc { | Tfield(name, _, t1, t2) => - let (closedFlafg, fields) = t2 |> getFieldTypes + let (closedFlafg, fields) = t2->getFieldTypes ( closedFlafg, list{ ( name, - name |> Runtime.isMutableObjectField + name->Runtime.isMutableObjectField ? {dependencies: list{}, type_: ident("")} - : t1 |> translateTypeExprFromTypes_(~config, ~typeVarsGen, ~typeEnv), + : t1->translateTypeExprFromTypes_(~config, ~typeVarsGen, ~typeEnv), ), ...fields, }, ) - | Tlink(te) => te |> getFieldTypes + | Tlink(te) => te->getFieldTypes | Tvar(None) => (Open, list{}) | _ => (Closed, list{}) } - let (closedFlag, fieldsTranslations) = tObj |> getFieldTypes + let (closedFlag, fieldsTranslations) = tObj->getFieldTypes translateConstr( ~config, ~fieldsTranslations, @@ -499,7 +499,7 @@ and translateTypeExprFromTypes_ = ( ) | Tconstr(path, list{{desc: Tlink(te)}}, r) => - {...typeExpr, desc: Types.Tconstr(path, list{te}, r)} |> translateTypeExprFromTypes_( + {...typeExpr, desc: Types.Tconstr(path, list{te}, r)}->translateTypeExprFromTypes_( ~config, ~typeVarsGen, ~noFunctionReturnDependencies=false, @@ -508,7 +508,7 @@ and translateTypeExprFromTypes_ = ( | Tconstr(path, typeParams, _) => let paramsTranslation = - typeParams |> translateTypeExprsFromTypes_(~config, ~typeVarsGen, ~typeEnv) + typeParams->translateTypeExprsFromTypes_(~config, ~typeVarsGen, ~typeEnv) translateConstr( ~config, ~fieldsTranslations=list{}, @@ -519,10 +519,10 @@ and translateTypeExprFromTypes_ = ( ) | Tpoly(t, list{}) => - t |> translateTypeExprFromTypes_(~config, ~typeVarsGen, ~noFunctionReturnDependencies, ~typeEnv) + t->translateTypeExprFromTypes_(~config, ~typeVarsGen, ~noFunctionReturnDependencies, ~typeEnv) | Tarrow(_) => - typeExpr |> translateArrowType( + typeExpr->translateArrowType( ~config, ~typeVarsGen, ~noFunctionReturnDependencies, @@ -532,29 +532,29 @@ and translateTypeExprFromTypes_ = ( ) | Ttuple(listExp) => let innerTypesTranslation = - listExp |> translateTypeExprsFromTypes_(~config, ~typeVarsGen, ~typeEnv) - let innerTypes = innerTypesTranslation |> List.map(({type_}) => type_) + listExp->translateTypeExprsFromTypes_(~config, ~typeVarsGen, ~typeEnv) + let innerTypes = innerTypesTranslation->List.map(({type_}) => type_) let innerTypesDeps = - innerTypesTranslation |> List.map(({dependencies}) => dependencies) |> List.concat + innerTypesTranslation->List.map(({dependencies}) => dependencies)->List.concat let tupleType = Tuple(innerTypes) {dependencies: innerTypesDeps, type_: tupleType} | Tlink(t) => - t |> translateTypeExprFromTypes_(~config, ~typeVarsGen, ~noFunctionReturnDependencies, ~typeEnv) + t->translateTypeExprFromTypes_(~config, ~typeVarsGen, ~noFunctionReturnDependencies, ~typeEnv) | Tvariant(rowDesc) => - switch rowDesc.row_fields |> processVariant { + switch rowDesc.row_fields->processVariant { | {noPayloads, payloads: list{}, unknowns: list{}} => - let noPayloads = noPayloads |> List.map(label => {label: label, labelJS: StringLabel(label)}) + let noPayloads = noPayloads->List.map(label => {label: label, labelJS: StringLabel(label)}) let type_ = createVariant(~noPayloads, ~payloads=list{}, ~polymorphic=true) {dependencies: list{}, type_: type_} | {noPayloads: list{}, payloads: list{(_label, t)}, unknowns: list{}} => /* Handle ReScript's "Arity_" encoding in first argument of Js.Internal.fn(_,_) for uncurried functions. Return the argument tuple. */ - t |> translateTypeExprFromTypes_( + t->translateTypeExprFromTypes_( ~config, ~typeVarsGen, ~noFunctionReturnDependencies, @@ -562,19 +562,19 @@ and translateTypeExprFromTypes_ = ( ) | {noPayloads, payloads, unknowns: list{}} => - let noPayloads = noPayloads |> List.map(label => {label: label, labelJS: StringLabel(label)}) + let noPayloads = noPayloads->List.map(label => {label: label, labelJS: StringLabel(label)}) let payloadTranslations = - payloads |> List.map(((label, payload)) => ( + payloads->List.map(((label, payload)) => ( label, - payload |> translateTypeExprFromTypes_(~config, ~typeVarsGen, ~typeEnv), + payload->translateTypeExprFromTypes_(~config, ~typeVarsGen, ~typeEnv), )) - let payloads = payloadTranslations |> List.map(((label, translation)) => { + let payloads = payloadTranslations->List.map(((label, translation)) => { let numArgs = 1 ({label: label, labelJS: StringLabel(label)}, numArgs, translation.type_) }) let type_ = createVariant(~noPayloads, ~payloads, ~polymorphic=true) let dependencies = - payloadTranslations |> List.map(((_, {dependencies})) => dependencies) |> List.concat + payloadTranslations->List.map(((_, {dependencies})) => dependencies)->List.concat {dependencies: dependencies, type_: type_} | {unknowns: list{_, ..._}} => { @@ -584,22 +584,22 @@ and translateTypeExprFromTypes_ = ( } | Tpackage(path, ids, types) => - switch typeEnv |> TypeEnv.lookupModuleTypeSignature(~path) { + switch typeEnv->TypeEnv.lookupModuleTypeSignature(~path) { | Some((signature, typeEnv)) => let typeEquationsTranslation = - List.combine(ids, types) |> List.map(((x, t)) => ( + List.combine(ids, types)->List.map(((x, t)) => ( x, - t |> translateTypeExprFromTypes_(~config, ~typeVarsGen, ~typeEnv), + t->translateTypeExprFromTypes_(~config, ~typeVarsGen, ~typeEnv), )) let typeEquations = - typeEquationsTranslation |> List.map(((x, translation)) => (x, translation.type_)) + typeEquationsTranslation->List.map(((x, translation)) => (x, translation.type_)) let dependenciesFromTypeEquations = typeEquationsTranslation - |> List.map(((_, translation)) => translation.dependencies) - |> List.flatten - let typeEnv1 = typeEnv |> TypeEnv.addTypeEquations(~typeEquations) + ->List.map(((_, translation)) => translation.dependencies) + ->List.flatten + let typeEnv1 = typeEnv->TypeEnv.addTypeEquations(~typeEquations) let (dependenciesFromRecordType, type_) = - signature.sig_type |> signatureToModuleRuntimeRepresentation( + signature.sig_type->signatureToModuleRuntimeRepresentation( ~config, ~typeVarsGen, ~typeEnv=typeEnv1, @@ -620,14 +620,14 @@ and translateTypeExprFromTypes_ = ( } and translateTypeExprsFromTypes_ = (~config, ~typeVarsGen, ~typeEnv, typeExprs): list< translation, -> => typeExprs |> List.map(translateTypeExprFromTypes_(~config, ~typeVarsGen, ~typeEnv)) +> => typeExprs->List.map(translateTypeExprFromTypes_(~config, ~typeVarsGen, ~typeEnv)) and signatureToModuleRuntimeRepresentation = (~config, ~typeVarsGen, ~typeEnv, signature) => { - let dependenciesAndFields = signature |> List.map(signatureItem => + let dependenciesAndFields = signature->List.map(signatureItem => switch signatureItem { | Types.Sig_value(_id, {val_kind: Val_prim(_)}) => (list{}, list{}) | Types.Sig_value(id, {val_type: typeExpr}) => let {dependencies, type_} = - typeExpr |> translateTypeExprFromTypes_( + typeExpr->translateTypeExprFromTypes_( ~config, ~typeVarsGen, ~noFunctionReturnDependencies=false, @@ -635,21 +635,21 @@ and signatureToModuleRuntimeRepresentation = (~config, ~typeVarsGen, ~typeEnv, s ) let field = { mutable_: Immutable, - nameJS: id |> Ident.name, - nameRE: id |> Ident.name, + nameJS: id->Ident.name, + nameRE: id->Ident.name, optional: Mandatory, type_: type_, } (dependencies, list{field}) | Types.Sig_module(id, moduleDeclaration, _recStatus) => - let typeEnv1 = switch typeEnv |> TypeEnv.getModule(~name=id |> Ident.name) { + let typeEnv1 = switch typeEnv->TypeEnv.getModule(~name=id->Ident.name) { | Some(typeEnv1) => typeEnv1 | None => typeEnv } let (dependencies, type_) = switch moduleDeclaration.md_type { | Mty_signature(signature) => - signature |> signatureToModuleRuntimeRepresentation( + signature->signatureToModuleRuntimeRepresentation( ~config, ~typeVarsGen, ~typeEnv=typeEnv1, @@ -660,8 +660,8 @@ and signatureToModuleRuntimeRepresentation = (~config, ~typeVarsGen, ~typeEnv, s } let field = { mutable_: Immutable, - nameJS: id |> Ident.name, - nameRE: id |> Ident.name, + nameJS: id->Ident.name, + nameRE: id->Ident.name, optional: Mandatory, type_: type_, } @@ -675,8 +675,8 @@ and signatureToModuleRuntimeRepresentation = (~config, ~typeVarsGen, ~typeEnv, s } ) let (dependencies, fields) = { - let (dl, fl) = dependenciesAndFields |> List.split - (dl |> List.concat, fl |> List.concat) + let (dl, fl) = dependenciesAndFields->List.split + (dl->List.concat, fl->List.concat) } (dependencies, config.modulesAsObjects ? Object(Closed, fields) : Record(fields)) } @@ -684,7 +684,7 @@ and signatureToModuleRuntimeRepresentation = (~config, ~typeVarsGen, ~typeEnv, s let translateTypeExprFromTypes = (~config, ~noFunctionReturnDependencies=?, ~typeEnv, typeExpr) => { let typeVarsGen = GenIdent.createTypeVarsGen() let translation = - typeExpr |> translateTypeExprFromTypes_( + typeExpr->translateTypeExprFromTypes_( ~config, ~typeVarsGen, ~noFunctionReturnDependencies?, @@ -692,19 +692,19 @@ let translateTypeExprFromTypes = (~config, ~noFunctionReturnDependencies=?, ~typ ) if Debug.dependencies.contents { - translation.dependencies |> List.iter(dep => Log_.item("Dependency: %s\n", dep |> depToString)) + translation.dependencies->List.iter(dep => Log_.item("Dependency: %s\n", dep->depToString)) } translation } let translateTypeExprsFromTypes = (~config, ~typeEnv, typeExprs) => { let typeVarsGen = GenIdent.createTypeVarsGen() - let translations = typeExprs |> translateTypeExprsFromTypes_(~config, ~typeVarsGen, ~typeEnv) + let translations = typeExprs->translateTypeExprsFromTypes_(~config, ~typeVarsGen, ~typeEnv) if Debug.dependencies.contents { - translations |> List.iter(translation => - translation.dependencies |> List.iter(dep => - Log_.item("Dependency: %s\n", dep |> depToString) + translations->List.iter(translation => + translation.dependencies->List.iter(dep => + Log_.item("Dependency: %s\n", dep->depToString) ) ) } diff --git a/tests/syntax_tests/data/idempotency/genType/src/Translation.res b/tests/syntax_tests/data/idempotency/genType/src/Translation.res index b812517cb3..b59212e84b 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/Translation.res +++ b/tests/syntax_tests/data/idempotency/genType/src/Translation.res @@ -12,21 +12,21 @@ let getImportTypeUniqueName = ({typeName, asTypeName}: CodeItem.importType) => } let importTypeCompare = (i1, i2) => - compare(i1 |> getImportTypeUniqueName, i2 |> getImportTypeUniqueName) + compare(i1->getImportTypeUniqueName, i2->getImportTypeUniqueName) let combine = (translations: list): t => translations - |> List.map(({CodeItem.importTypes: importTypes, codeItems, typeDeclarations}) => ( + ->List.map(({CodeItem.importTypes: importTypes, codeItems, typeDeclarations}) => ( (importTypes, codeItems), typeDeclarations, )) - |> List.split - |> (((x, y)) => (x |> List.split, y)) - |> ( + ->List.split + ->(((x, y)) => (x->List.split, y)) + ->( (((importTypes, codeItems), typeDeclarations)) => { - CodeItem.importTypes: importTypes |> List.concat, - codeItems: codeItems |> List.concat, - typeDeclarations: typeDeclarations |> List.concat, + CodeItem.importTypes: importTypes->List.concat, + codeItems: codeItems->List.concat, + typeDeclarations: typeDeclarations->List.concat, } ) @@ -39,12 +39,12 @@ let abstractTheTypeParameters = (~typeVars, type_) => let depToImportType = (~config, ~outputFileRelative, ~resolver, dep: dep) => switch dep { - | _ if dep |> Dependencies.isInternal => list{} + | _ if dep->Dependencies.isInternal => list{} | External(name) if name == "list" => list{ { CodeItem.typeName: "list", asTypeName: None, - importPath: ModuleName.reasonPervasives |> ModuleResolver.importPathForReasonModuleName( + importPath: ModuleName.reasonPervasives->ModuleResolver.importPathForReasonModuleName( ~config, ~outputFileRelative, ~resolver, @@ -55,11 +55,11 @@ let depToImportType = (~config, ~outputFileRelative, ~resolver, dep: dep) => | Internal(_) => list{} | Dot(_) => - let moduleName = dep |> Dependencies.getOuterModuleName - let typeName = dep |> Dependencies.removeExternalOuterModule |> depToString - let asTypeName = dep |> Dependencies.isInternal ? None : Some(dep |> depToString) + let moduleName = dep->Dependencies.getOuterModuleName + let typeName = dep->Dependencies.removeExternalOuterModule->depToString + let asTypeName = dep->Dependencies.isInternal ? None : Some(dep->depToString) let importPath = - moduleName |> ModuleResolver.importPathForReasonModuleName( + moduleName->ModuleResolver.importPathForReasonModuleName( ~config, ~outputFileRelative, ~resolver, @@ -70,7 +70,7 @@ let depToImportType = (~config, ~outputFileRelative, ~resolver, dep: dep) => let translateDependencies = (~config, ~outputFileRelative, ~resolver, dependencies): list< CodeItem.importType, > => - dependencies |> List.map(depToImportType(~config, ~outputFileRelative, ~resolver)) |> List.concat + dependencies->List.map(depToImportType(~config, ~outputFileRelative, ~resolver))->List.concat let translateValue = ( ~attributes, @@ -88,13 +88,13 @@ let translateValue = ( | _ => name } let typeExprTranslation = - typeExpr |> TranslateTypeExprFromTypes.translateTypeExprFromTypes(~config, ~typeEnv) - let typeVars = typeExprTranslation.type_ |> TypeVars.free + typeExpr->TranslateTypeExprFromTypes.translateTypeExprFromTypes(~config, ~typeEnv) + let typeVars = typeExprTranslation.type_->TypeVars.free let type_ = - typeExprTranslation.type_ |> abstractTheTypeParameters(~typeVars) |> addAnnotationsToFunction - let resolvedNameOriginal = name |> TypeEnv.addModulePath(~typeEnv) |> ResolvedName.toString - let resolvedName = nameAs |> TypeEnv.addModulePath(~typeEnv) - let moduleAccessPath = typeEnv |> TypeEnv.getModuleAccessPath(~name=resolvedNameOriginal) + typeExprTranslation.type_->abstractTheTypeParameters(~typeVars)->addAnnotationsToFunction + let resolvedNameOriginal = name->TypeEnv.addModulePath(~typeEnv)->ResolvedName.toString + let resolvedName = nameAs->TypeEnv.addModulePath(~typeEnv) + let moduleAccessPath = typeEnv->TypeEnv.getModuleAccessPath(~name=resolvedNameOriginal) let codeItems = list{ CodeItem.ExportValue({ @@ -106,7 +106,7 @@ let translateValue = ( }), } { - importTypes: typeExprTranslation.dependencies |> translateDependencies( + importTypes: typeExprTranslation.dependencies->translateDependencies( ~config, ~outputFileRelative, ~resolver, @@ -148,7 +148,7 @@ let translateComponent = ( ~addAnnotationsToFunction: type_ => type_, name, ): t => { - let typeExprTranslation_ = typeExpr |> TranslateTypeExprFromTypes.translateTypeExprFromTypes( + let typeExprTranslation_ = typeExpr->TranslateTypeExprFromTypes.translateTypeExprFromTypes( ~config, /* Only get the dependencies for the prop types. The return type is a ReasonReact component. */ @@ -157,16 +157,16 @@ let translateComponent = ( ) let typeExprTranslation = { ...typeExprTranslation_, - type_: typeExprTranslation_.type_ |> addAnnotationsToFunction, + type_: typeExprTranslation_.type_->addAnnotationsToFunction, } - let freeTypeVarsSet = typeExprTranslation.type_ |> TypeVars.free_ + let freeTypeVarsSet = typeExprTranslation.type_->TypeVars.free_ /* Replace type variables in props/children with any. */ let (typeVars, type_) = ( list{}, - typeExprTranslation.type_ |> TypeVars.substitute(~f=s => - if freeTypeVarsSet |> StringSet.mem(s) { + typeExprTranslation.type_->TypeVars.substitute(~f=s => + if freeTypeVarsSet->StringSet.mem(s) { Some(mixedOrUnknown(~config)) } else { None @@ -226,13 +226,13 @@ let translateComponent = ( | t => t } } - let resolvedTypeName = "Props" |> TypeEnv.addModulePath(~typeEnv) + let resolvedTypeName = "Props"->TypeEnv.addModulePath(~typeEnv) - let nestedModuleName = typeEnv |> TypeEnv.getNestedModuleName + let nestedModuleName = typeEnv->TypeEnv.getNestedModuleName - let moduleAccessPath = typeEnv |> TypeEnv.getModuleAccessPath(~name="make") + let moduleAccessPath = typeEnv->TypeEnv.getModuleAccessPath(~name="make") let componentAccessPath = - typeEnv |> TypeEnv.getModuleAccessPath(~component=true, ~name="component") + typeEnv->TypeEnv.getModuleAccessPath(~component=true, ~name="component") let codeItems = list{ CodeItem.ExportComponent({ @@ -250,7 +250,7 @@ let translateComponent = ( }), } { - importTypes: typeExprTranslation.dependencies |> translateDependencies( + importTypes: typeExprTranslation.dependencies->translateDependencies( ~config, ~outputFileRelative, ~resolver, @@ -261,7 +261,7 @@ let translateComponent = ( | _ => /* not a component: treat make as a normal function */ - name |> translateValue( + name->translateValue( ~attributes, ~config, ~docString, @@ -291,16 +291,16 @@ let translatePrimitive = ( let valueName = switch valueDescription.val_prim { | list{"", ..._} | list{} => - valueDescription.val_id |> Ident.name + valueDescription.val_id->Ident.name | list{nameOfExtern, ..._} => /* extern foo : someType = "abc" The first element of val_prim is "abc" */ nameOfExtern } let typeExprTranslation = - valueDescription.val_desc |> TranslateCoreType.translateCoreType(~config, ~typeEnv) + valueDescription.val_desc->TranslateCoreType.translateCoreType(~config, ~typeEnv) let (attributeImport, attributeRenaming) = - valueDescription.val_attributes |> Annotation.getAttributeImportRenaming + valueDescription.val_attributes->Annotation.getAttributeImportRenaming switch (typeExprTranslation.type_, attributeImport) { | ( Function({ @@ -321,7 +321,7 @@ let translatePrimitive = ( | Some(asPath) => asPath | None => "" } - let typeExprTranslation = valueDescription.val_desc |> TranslateCoreType.translateCoreType( + let typeExprTranslation = valueDescription.val_desc->TranslateCoreType.translateCoreType( ~config, /* Only get the dependencies for the prop types. The return type is a ReasonReact component. */ @@ -329,13 +329,13 @@ let translatePrimitive = ( ~typeEnv, ) - let freeTypeVarsSet = typeExprTranslation.type_ |> TypeVars.free_ + let freeTypeVarsSet = typeExprTranslation.type_->TypeVars.free_ /* Replace type variables in props/children with any. */ let (typeVars, type_) = ( list{}, - typeExprTranslation.type_ |> TypeVars.substitute(~f=s => - if freeTypeVarsSet |> StringSet.mem(s) { + typeExprTranslation.type_->TypeVars.substitute(~f=s => + if freeTypeVarsSet->StringSet.mem(s) { Some(mixedOrUnknown(~config)) } else { None @@ -350,7 +350,7 @@ let translatePrimitive = ( | list{{aType: children}, ..._} => switch propOrChildren { | {aType: GroupOfLabeledArgs(fields)} => ( - fields |> List.map(({optional, type_} as field) => + fields->List.map(({optional, type_} as field) => switch (type_, optional) { | (Option(type1), Optional) => { ...field, @@ -368,8 +368,8 @@ let translatePrimitive = ( | _ => (list{}, mixedOrUnknown(~config)) } let propsTyp = Object(Closed, propsFields) - let resolvedTypeName = "Props" |> TypeEnv.addModulePath(~typeEnv) - let propsTypeName = resolvedTypeName |> ResolvedName.toString + let resolvedTypeName = "Props"->TypeEnv.addModulePath(~typeEnv) + let propsTypeName = resolvedTypeName->ResolvedName.toString let codeItems = list{ CodeItem.ImportComponent({ @@ -382,13 +382,13 @@ let translatePrimitive = ( typeVars: typeVars, resolvedTypeName: resolvedTypeName, }, - importAnnotation: importString |> Annotation.importFromString, + importAnnotation: importString->Annotation.importFromString, propsFields: propsFields, propsTypeName: propsTypeName, }), } { - importTypes: typeExprTranslation.dependencies |> translateDependencies( + importTypes: typeExprTranslation.dependencies->translateDependencies( ~config, ~outputFileRelative, ~resolver, @@ -403,11 +403,11 @@ let translatePrimitive = ( | None => valueName } - let typeVars = typeExprTranslation.type_ |> TypeVars.free - let type_ = typeExprTranslation.type_ |> abstractTheTypeParameters(~typeVars) + let typeVars = typeExprTranslation.type_->TypeVars.free + let type_ = typeExprTranslation.type_->abstractTheTypeParameters(~typeVars) { - importTypes: typeExprTranslation.dependencies |> translateDependencies( + importTypes: typeExprTranslation.dependencies->translateDependencies( ~config, ~outputFileRelative, ~resolver, @@ -415,7 +415,7 @@ let translatePrimitive = ( codeItems: list{ ImportValue({ asPath: asPath, - importAnnotation: importString |> Annotation.importFromString, + importAnnotation: importString->Annotation.importFromString, type_: type_, valueName: valueName, }), @@ -428,19 +428,19 @@ let translatePrimitive = ( } let addTypeDeclarationsFromModuleEquations = (~typeEnv, translation: t) => { - let eqs = typeEnv |> TypeEnv.getModuleEquations + let eqs = typeEnv->TypeEnv.getModuleEquations let newTypeDeclarations = translation.typeDeclarations - |> List.map((typeDeclaration: CodeItem.typeDeclaration) => { + ->List.map((typeDeclaration: CodeItem.typeDeclaration) => { let exportType = typeDeclaration.exportFromTypeDeclaration.exportType - let equations = exportType.resolvedTypeName |> ResolvedName.applyEquations(~eqs) - equations |> List.map(((x, y)) => { + let equations = exportType.resolvedTypeName->ResolvedName.applyEquations(~eqs) + equations->List.map(((x, y)) => { let newExportType = { ...exportType, nameAs: None, type_: y - |> ResolvedName.toString - |> ident(~builtin=false, ~typeArgs=exportType.typeVars |> List.map(s => TypeVar(s))), + ->ResolvedName.toString + ->ident(~builtin=false, ~typeArgs=exportType.typeVars->List.map(s => TypeVar(s))), resolvedTypeName: x, } { @@ -452,7 +452,7 @@ let addTypeDeclarationsFromModuleEquations = (~typeEnv, translation: t) => { } }) }) - |> List.concat + ->List.concat newTypeDeclarations == list{} ? translation : { diff --git a/tests/syntax_tests/data/idempotency/genType/src/TypeEnv.res b/tests/syntax_tests/data/idempotency/genType/src/TypeEnv.res index a1ec35cf81..6ec69b92f3 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/TypeEnv.res +++ b/tests/syntax_tests/data/idempotency/genType/src/TypeEnv.res @@ -20,7 +20,7 @@ and entry = | Type(string) let createTypeEnv = (~name, parent) => { - let moduleItem = Runtime.moduleItemGen() |> Runtime.newModuleItem(~name) + let moduleItem = Runtime.moduleItemGen()->Runtime.newModuleItem(~name) { componentModuleItem: moduleItem, map: StringMap.empty, @@ -33,51 +33,51 @@ let createTypeEnv = (~name, parent) => { } } -let root = () => None |> createTypeEnv(~name="__root__") +let root = () => None->createTypeEnv(~name="__root__") let toString = typeEnv => typeEnv.name let newModule = (~name, typeEnv) => { if Debug.typeEnv.contents { - Log_.item("TypeEnv.newModule %s %s\n", typeEnv |> toString, name) + Log_.item("TypeEnv.newModule %s %s\n", typeEnv->toString, name) } - let newTypeEnv = Some(typeEnv) |> createTypeEnv(~name) - typeEnv.map = typeEnv.map |> StringMap.add(name, Module(newTypeEnv)) + let newTypeEnv = Some(typeEnv)->createTypeEnv(~name) + typeEnv.map = typeEnv.map->StringMap.add(name, Module(newTypeEnv)) newTypeEnv } let newModuleType = (~name, ~signature, typeEnv) => { if Debug.typeEnv.contents { - Log_.item("TypeEnv.newModuleType %s %s\n", typeEnv |> toString, name) + Log_.item("TypeEnv.newModuleType %s %s\n", typeEnv->toString, name) } - let newTypeEnv = Some(typeEnv) |> createTypeEnv(~name) - typeEnv.mapModuleTypes = typeEnv.mapModuleTypes |> StringMap.add(name, (signature, newTypeEnv)) + let newTypeEnv = Some(typeEnv)->createTypeEnv(~name) + typeEnv.mapModuleTypes = typeEnv.mapModuleTypes->StringMap.add(name, (signature, newTypeEnv)) newTypeEnv } let newType = (~name, typeEnv) => { if Debug.typeEnv.contents { - Log_.item("TypeEnv.newType %s %s\n", typeEnv |> toString, name) + Log_.item("TypeEnv.newType %s %s\n", typeEnv->toString, name) } - typeEnv.map = typeEnv.map |> StringMap.add(name, Type(name)) + typeEnv.map = typeEnv.map->StringMap.add(name, Type(name)) } let getModule = (~name, typeEnv) => - switch typeEnv.map |> StringMap.find(name) { + switch typeEnv.map->StringMap.find(name) { | Module(typeEnv1) => Some(typeEnv1) | Type(_) => None | exception Not_found => None } let expandAliasToExternalModule = (~name, typeEnv) => - switch typeEnv |> getModule(~name) { + switch typeEnv->getModule(~name) { | Some({moduleEquation: Some({internal: false, dep})}) => if Debug.typeEnv.contents { Log_.item( "TypeEnv.expandAliasToExternalModule %s %s aliased to %s\n", - typeEnv |> toString, + typeEnv->toString, name, - dep |> depToString, + dep->depToString, ) } Some(dep) @@ -88,9 +88,9 @@ let addModuleEquation = (~dep, ~internal, typeEnv) => { if Debug.typeEnv.contents { Log_.item( "Typenv.addModuleEquation %s %s dep:%s\n", - typeEnv |> toString, + typeEnv->toString, internal ? "Internal" : "External", - dep |> depToString, + dep->depToString, ) } typeEnv.moduleEquation = Some({internal: internal, dep: dep}) @@ -100,15 +100,15 @@ let rec addTypeEquation = (~flattened, ~type_, typeEnv) => switch flattened { | list{name} => { ...typeEnv, - typeEquations: typeEnv.typeEquations |> StringMap.add(name, type_), + typeEquations: typeEnv.typeEquations->StringMap.add(name, type_), } | list{moduleName, ...rest} => - switch typeEnv |> getModule(~name=moduleName) { + switch typeEnv->getModule(~name=moduleName) { | Some(typeEnv1) => { ...typeEnv, - map: typeEnv.map |> StringMap.add( + map: typeEnv.map->StringMap.add( moduleName, - Module(typeEnv1 |> addTypeEquation(~flattened=rest, ~type_)), + Module(typeEnv1->addTypeEquation(~flattened=rest, ~type_)), ), } | None => typeEnv @@ -117,23 +117,23 @@ let rec addTypeEquation = (~flattened, ~type_, typeEnv) => } let addTypeEquations = (~typeEquations, typeEnv) => - typeEquations |> List.fold_left( + typeEquations->List.fold_left( (te, (longIdent, type_)) => - te |> addTypeEquation(~flattened=longIdent |> Longident.flatten, ~type_), + te->addTypeEquation(~flattened=longIdent->Longident.flatten, ~type_), typeEnv, ) let applyTypeEquations = (~config, ~path, typeEnv) => switch path { | Path.Pident(id) => - switch typeEnv.typeEquations |> StringMap.find(id |> Ident.name) { + switch typeEnv.typeEquations->StringMap.find(id->Ident.name) { | type_ => if Debug.typeResolution.contents { Log_.item( "Typenv.applyTypeEquations %s name:%s type_:%s\n", - typeEnv |> toString, - id |> Ident.name, - type_ |> EmitType.typeToString(~config, ~typeNameIsInterface=_ => false), + typeEnv->toString, + id->Ident.name, + type_->EmitType.typeToString(~config, ~typeNameIsInterface=_ => false), ) } @@ -144,12 +144,12 @@ let applyTypeEquations = (~config, ~path, typeEnv) => } let rec lookup = (~name, typeEnv) => - switch typeEnv.map |> StringMap.find(name) { + switch typeEnv.map->StringMap.find(name) { | _ => Some(typeEnv) | exception Not_found => switch typeEnv.parent { | None => None - | Some(parent) => parent |> lookup(~name) + | Some(parent) => parent->lookup(~name) } } @@ -159,29 +159,29 @@ let rec lookupModuleType = (~path, typeEnv) => if Debug.typeEnv.contents { Log_.item( "Typenv.lookupModuleType %s moduleTypeName:%s\n", - typeEnv |> toString, + typeEnv->toString, moduleTypeName, ) } - switch typeEnv.mapModuleTypes |> StringMap.find(moduleTypeName) { + switch typeEnv.mapModuleTypes->StringMap.find(moduleTypeName) { | x => Some(x) | exception Not_found => switch typeEnv.parent { | None => None - | Some(parent) => parent |> lookupModuleType(~path) + | Some(parent) => parent->lookupModuleType(~path) } } | list{moduleName, ...path1} => if Debug.typeEnv.contents { - Log_.item("Typenv.lookupModuleType %s moduleName:%s\n", typeEnv |> toString, moduleName) + Log_.item("Typenv.lookupModuleType %s moduleName:%s\n", typeEnv->toString, moduleName) } - switch typeEnv.map |> StringMap.find(moduleName) { - | Module(typeEnv1) => typeEnv1 |> lookupModuleType(~path=path1) + switch typeEnv.map->StringMap.find(moduleName) { + | Module(typeEnv1) => typeEnv1->lookupModuleType(~path=path1) | Type(_) => None | exception Not_found => switch typeEnv.parent { | None => None - | Some(parent) => parent |> lookupModuleType(~path) + | Some(parent) => parent->lookupModuleType(~path) } } | list{} => None @@ -189,21 +189,21 @@ let rec lookupModuleType = (~path, typeEnv) => let rec pathToList = path => switch path { - | Path.Pident(id) => list{id |> Ident.name} - | Path.Pdot(p, s, _) => list{s, ...p |> pathToList} + | Path.Pident(id) => list{id->Ident.name} + | Path.Pdot(p, s, _) => list{s, ...p->pathToList} | Path.Papply(_) => list{} } let lookupModuleTypeSignature = (~path, typeEnv) => { if Debug.typeEnv.contents { - Log_.item("TypeEnv.lookupModuleTypeSignature %s %s\n", typeEnv |> toString, path |> Path.name) + Log_.item("TypeEnv.lookupModuleTypeSignature %s %s\n", typeEnv->toString, path->Path.name) } - typeEnv |> lookupModuleType(~path=path |> pathToList |> List.rev) + typeEnv->lookupModuleType(~path=path->pathToList->List.rev) } let getNestedModuleName = typeEnv => - typeEnv.parent == None ? None : Some(typeEnv.name |> ModuleName.fromStringUnsafe) + typeEnv.parent == None ? None : Some(typeEnv.name->ModuleName.fromStringUnsafe) let updateModuleItem = (~nameOpt=None, ~moduleItem, typeEnv) => { switch nameOpt { @@ -215,26 +215,26 @@ let updateModuleItem = (~nameOpt=None, ~moduleItem, typeEnv) => { let rec addModulePath = (~typeEnv, name) => switch typeEnv.parent { - | None => name |> ResolvedName.fromString - | Some(parent) => typeEnv.name |> addModulePath(~typeEnv=parent) |> ResolvedName.dot(name) + | None => name->ResolvedName.fromString + | Some(parent) => typeEnv.name->addModulePath(~typeEnv=parent)->ResolvedName.dot(name) } let rec getModuleEquations = (typeEnv): list => { let subEquations = typeEnv.map - |> StringMap.bindings - |> List.map(((_, entry)) => + ->StringMap.bindings + ->List.map(((_, entry)) => switch entry { - | Module(te) => te |> getModuleEquations + | Module(te) => te->getModuleEquations | Type(_) => list{} } ) - |> List.concat + ->List.concat switch (typeEnv.moduleEquation, typeEnv.parent) { | (None, _) | (_, None) => subEquations | (Some({dep}), Some(parent)) => list{ - (dep |> depToResolvedName, typeEnv.name |> addModulePath(~typeEnv=parent)), + (dep->depToResolvedName, typeEnv.name->addModulePath(~typeEnv=parent)), } } } @@ -245,9 +245,9 @@ let getModuleAccessPath = (~component=false, ~name, typeEnv) => { | None => Runtime.Root(name) /* not nested */ | Some(parent) => Dot( - parent.parent == None ? Root(typeEnv.name) : parent |> accessPath, + parent.parent == None ? Root(typeEnv.name) : parent->accessPath, component ? typeEnv.componentModuleItem : typeEnv.moduleItem, ) } - typeEnv |> accessPath + typeEnv->accessPath } diff --git a/tests/syntax_tests/data/idempotency/genType/src/TypeVars.res b/tests/syntax_tests/data/idempotency/genType/src/TypeVars.res index 08d27a6864..0c361afa00 100644 --- a/tests/syntax_tests/data/idempotency/genType/src/TypeVars.res +++ b/tests/syntax_tests/data/idempotency/genType/src/TypeVars.res @@ -1,53 +1,53 @@ open GenTypeCommon -let extractFromTypeExpr = typeParams => typeParams |> List.fold_left((soFar, typeExpr) => +let extractFromTypeExpr = typeParams => typeParams->List.fold_left((soFar, typeExpr) => switch typeExpr { | {Types.desc: Tvar(Some(s))} => let typeName = s list{typeName, ...soFar} | _ => assert(false) } - , list{}) |> List.rev + , list{})->List.rev -let extractFromCoreType = typeParams => typeParams |> List.fold_left((soFar, typeExpr) => +let extractFromCoreType = typeParams => typeParams->List.fold_left((soFar, typeExpr) => switch typeExpr.Typedtree.ctyp_desc { | Ttyp_var(s) => let typeName = s list{typeName, ...soFar} | _ => soFar } - , list{}) |> List.rev + , list{})->List.rev let rec substitute = (~f, type0) => switch type0 { - | Array(t, arrayKind) => Array(t |> substitute(~f), arrayKind) + | Array(t, arrayKind) => Array(t->substitute(~f), arrayKind) | Function(function_) => Function({ ...function_, - argTypes: function_.argTypes |> List.map(({aName, aType: t}) => { + argTypes: function_.argTypes->List.map(({aName, aType: t}) => { aName: aName, - aType: t |> substitute(~f), + aType: t->substitute(~f), }), - retType: function_.retType |> substitute(~f), + retType: function_.retType->substitute(~f), }) | GroupOfLabeledArgs(fields) => GroupOfLabeledArgs( - fields |> List.map(field => {...field, type_: field.type_ |> substitute(~f)}), + fields->List.map(field => {...field, type_: field.type_->substitute(~f)}), ) | Ident({typeArgs: list{}}) => type0 - | Ident({typeArgs} as ident) => Ident({...ident, typeArgs: typeArgs |> List.map(substitute(~f))}) - | Null(type_) => Null(type_ |> substitute(~f)) - | Nullable(type_) => Nullable(type_ |> substitute(~f)) + | Ident({typeArgs} as ident) => Ident({...ident, typeArgs: typeArgs->List.map(substitute(~f))}) + | Null(type_) => Null(type_->substitute(~f)) + | Nullable(type_) => Nullable(type_->substitute(~f)) | Object(closedFlag, fields) => Object( closedFlag, - fields |> List.map(field => {...field, type_: field.type_ |> substitute(~f)}), + fields->List.map(field => {...field, type_: field.type_->substitute(~f)}), ) - | Option(type_) => Option(type_ |> substitute(~f)) - | Promise(type_) => Promise(type_ |> substitute(~f)) + | Option(type_) => Option(type_->substitute(~f)) + | Promise(type_) => Promise(type_->substitute(~f)) | Record(fields) => - Record(fields |> List.map(field => {...field, type_: field.type_ |> substitute(~f)})) - | Tuple(innerTypes) => Tuple(innerTypes |> List.map(substitute(~f))) + Record(fields->List.map(field => {...field, type_: field.type_->substitute(~f)})) + | Tuple(innerTypes) => Tuple(innerTypes->List.map(substitute(~f))) | TypeVar(s) => switch f(s) { | None => type0 @@ -56,45 +56,45 @@ let rec substitute = (~f, type0) => | Variant(variant) => Variant({ ...variant, - payloads: variant.payloads |> List.map(((case, numArgs, t)) => ( + payloads: variant.payloads->List.map(((case, numArgs, t)) => ( case, numArgs, - t |> substitute(~f), + t->substitute(~f), )), }) } let rec free_ = (type0): StringSet.t => switch type0 { - | Array(t, _) => t |> free_ + | Array(t, _) => t->free_ | Function({argTypes, retType, typeVars}) => - StringSet.diff(\"+++"(argTypes |> freeOfList_, retType |> free_), typeVars |> StringSet.of_list) + StringSet.diff(\"+++"(argTypes->freeOfList_, retType->free_), typeVars->StringSet.of_list) | GroupOfLabeledArgs(fields) | Object(_, fields) | Record(fields) => - fields |> List.fold_left((s, {type_}) => StringSet.union(s, type_ |> free_), StringSet.empty) + fields->List.fold_left((s, {type_}) => StringSet.union(s, type_->free_), StringSet.empty) | Ident({typeArgs}) => - typeArgs |> List.fold_left( - (s, typeArg) => StringSet.union(s, typeArg |> free_), + typeArgs->List.fold_left( + (s, typeArg) => StringSet.union(s, typeArg->free_), StringSet.empty, ) | Null(type_) | Nullable(type_) => - type_ |> free_ + type_->free_ | Option(type_) | Promise(type_) => - type_ |> free_ + type_->free_ | Tuple(innerTypes) => - innerTypes |> List.fold_left( - (s, typeArg) => StringSet.union(s, typeArg |> free_), + innerTypes->List.fold_left( + (s, typeArg) => StringSet.union(s, typeArg->free_), StringSet.empty, ) - | TypeVar(s) => s |> StringSet.singleton + | TypeVar(s) => s->StringSet.singleton | Variant({payloads}) => - payloads |> List.fold_left((s, (_, _, t)) => StringSet.union(s, t |> free_), StringSet.empty) + payloads->List.fold_left((s, (_, _, t)) => StringSet.union(s, t->free_), StringSet.empty) } and freeOfList_ = types => - types |> List.fold_left((s, {aType}) => \"+++"(s, aType |> free_), StringSet.empty) + types->List.fold_left((s, {aType}) => \"+++"(s, aType->free_), StringSet.empty) and \"+++" = StringSet.union -let free = type_ => type_ |> free_ |> StringSet.elements +let free = type_ => type_->free_->StringSet.elements diff --git a/tests/syntax_tests/data/idempotency/mareo/Draw.res b/tests/syntax_tests/data/idempotency/mareo/Draw.res index f69bea9f1e..2b948bc4f6 100644 --- a/tests/syntax_tests/data/idempotency/mareo/Draw.res +++ b/tests/syntax_tests/data/idempotency/mareo/Draw.res @@ -55,7 +55,7 @@ let hud = (canvas, score, coins) => { /* Displays the fps. */ let fps = (canvas, fps_val) => { - let fps_str = int_of_float(fps_val) |> string_of_int + let fps_str = int_of_float(fps_val)->string_of_int let canvas = Dom_html.canvasElementToJsObj(canvas) let context = Dom_html.canvasRenderingContext2DToJsObj(canvas["getContext"]("2d")) ignore(context["fillText"](fps_str, 10., 18.)) diff --git a/tests/syntax_tests/data/idempotency/nook-exchange/API.res b/tests/syntax_tests/data/idempotency/nook-exchange/API.res index 7c90c8ee9b..440011849c 100644 --- a/tests/syntax_tests/data/idempotency/nook-exchange/API.res +++ b/tests/syntax_tests/data/idempotency/nook-exchange/API.res @@ -91,7 +91,7 @@ let importItems = (~sessionId, ~updates: array<((int, int), User.itemStatus)>) = ~bodyJson=list{ ( "updates", - updates |> { + updates->{ open Json.Encode array((((itemId, variant), status)) => tuple3(int, int, int, (itemId, variant, User.itemStatusToJs(status))) diff --git a/tests/syntax_tests/data/idempotency/nook-exchange/App.res b/tests/syntax_tests/data/idempotency/nook-exchange/App.res index f67ce62754..f3731fbe28 100644 --- a/tests/syntax_tests/data/idempotency/nook-exchange/App.res +++ b/tests/syntax_tests/data/idempotency/nook-exchange/App.res @@ -59,7 +59,7 @@ let make = () => { let url = ReasonReactRouter.useUrl() let (showLogin, setShowLogin) = React.useState(() => false) let itemDetails = { - let result = url.hash |> Js.Re.exec_(/i(-?\d+)(:(\d+))?/g) + let result = url.hash->Js.Re.exec_(/i(-?\d+)(:(\d+))?/g) switch result { | Some(match_) => let captures = Js.Re.captures(match_) @@ -129,24 +129,24 @@ let make = () => { let (code, state) = { open Webapi.Url.URLSearchParams let searchParams = make(url.search) - (searchParams |> get("code"), searchParams |> get("state")) + (searchParams->get("code"), searchParams->get("state")) } switch (code, state) { | (Some(code), Some(state)) => if ( { open Dom.Storage - localStorage |> getItem("discord_state") + localStorage->getItem("discord_state") } != Some(state) ) { raise(DiscordOauthStateMismatch(state)) } DiscordOauth.process( ~code, - ~isLogin=state |> Js.String.startsWith("login"), - ~isRegister=state |> Js.String.startsWith("register"), - ~isConnect=state |> Js.String.startsWith("connect"), - ) |> ignore + ~isLogin=state->Js.String.startsWith("login"), + ~isRegister=state->Js.String.startsWith("register"), + ~isConnect=state->Js.String.startsWith("connect"), + )->ignore ReasonReactRouter.replace("/") | _ => () } diff --git a/tests/syntax_tests/data/idempotency/nook-exchange/Constants.res b/tests/syntax_tests/data/idempotency/nook-exchange/Constants.res index 78cd3fd26f..8bb2cbb91a 100644 --- a/tests/syntax_tests/data/idempotency/nook-exchange/Constants.res +++ b/tests/syntax_tests/data/idempotency/nook-exchange/Constants.res @@ -2,7 +2,7 @@ external nodeEnv: option = "NODE_ENV" @val @scope(("process", "env")) external gitCommitRef: option = "COMMIT_REF" -let gitCommitRef = Belt.Option.getWithDefault(gitCommitRef, "") |> Js.String.slice(~from=0, ~to_=8) +let gitCommitRef = Belt.Option.getWithDefault(gitCommitRef, "")->Js.String.slice(~from=0, ~to_=8) let apiUrl = nodeEnv === Some("paul-development") ? "http://localhost:3000" : "https://a.nook.exchange" @@ -22,7 +22,7 @@ let discordOauthRedirectUri = state => (encodeURIComponent( { open Webapi.Dom - location |> Location.origin + location->Location.origin } ++ "/discord_oauth2", ) ++ ("&response_type=code&scope=guilds.join%20identify&prompt=none&state=" ++ state)) diff --git a/tests/syntax_tests/data/idempotency/nook-exchange/DeleteFromCatalog.res b/tests/syntax_tests/data/idempotency/nook-exchange/DeleteFromCatalog.res index b80a697fd8..a8bf6792b9 100644 --- a/tests/syntax_tests/data/idempotency/nook-exchange/DeleteFromCatalog.res +++ b/tests/syntax_tests/data/idempotency/nook-exchange/DeleteFromCatalog.res @@ -1,10 +1,10 @@ module PersistConfig = { let key = "confirm_catalog_delete" - let value = ref(Dom.Storage.localStorage |> Dom.Storage.getItem(key)) + let value = ref(Dom.Storage.localStorage->Dom.Storage.getItem(key)) let confirm = () => { let nowString = Js.Date.now()->Js.Float.toString value := Some(nowString) - Dom.Storage.localStorage |> Dom.Storage.setItem(key, nowString) + Dom.Storage.localStorage->Dom.Storage.setItem(key, nowString) } } diff --git a/tests/syntax_tests/data/idempotency/nook-exchange/DiscordBotUpsell.res b/tests/syntax_tests/data/idempotency/nook-exchange/DiscordBotUpsell.res index 5ee71554cc..a6a95e49e6 100644 --- a/tests/syntax_tests/data/idempotency/nook-exchange/DiscordBotUpsell.res +++ b/tests/syntax_tests/data/idempotency/nook-exchange/DiscordBotUpsell.res @@ -1,10 +1,10 @@ module PersistConfig = { let key = "dismiss_discord_bot_notice" - let value = ref(Dom.Storage.localStorage |> Dom.Storage.getItem(key)) + let value = ref(Dom.Storage.localStorage->Dom.Storage.getItem(key)) let dismiss = () => { let nowString = Js.Date.now()->Js.Float.toString value := Some(nowString) - Dom.Storage.localStorage |> Dom.Storage.setItem(key, nowString) + Dom.Storage.localStorage->Dom.Storage.setItem(key, nowString) } } @@ -57,8 +57,8 @@ module Component = { ) open Webapi.Dom window - |> Window.open_(~url="https://discord.gg/9sh66CX", ~name="", ~features=?None) - |> ignore + ->Window.open_(~url="https://discord.gg/9sh66CX", ~name="", ~features=?None) + ->ignore }}> {React.string("Discord bot")}
@@ -79,8 +79,8 @@ module Component = { onClick={_ => { open Webapi.Dom window - |> Window.open_(~url="https://discord.gg/9sh66CX", ~name="", ~features=?None) - |> ignore + ->Window.open_(~url="https://discord.gg/9sh66CX", ~name="", ~features=?None) + ->ignore onDismiss() Analytics.Amplitude.logEventWithProperties( ~eventName="Discord Bot Notice Accepted", diff --git a/tests/syntax_tests/data/idempotency/nook-exchange/DiscordOauth.res b/tests/syntax_tests/data/idempotency/nook-exchange/DiscordOauth.res index 2bce891887..84d408e5b3 100644 --- a/tests/syntax_tests/data/idempotency/nook-exchange/DiscordOauth.res +++ b/tests/syntax_tests/data/idempotency/nook-exchange/DiscordOauth.res @@ -58,7 +58,7 @@ let process = (~code, ~isLogin, ~isRegister, ~isConnect) => Error.showPopup(~message="Something went wrong. Sorry! Please reload and try again.") } Promise.resolved() - }) |> ignore + })->ignore } else if isConnect { - UserStore.connectDiscordAccount(~code) |> ignore + UserStore.connectDiscordAccount(~code)->ignore } diff --git a/tests/syntax_tests/data/idempotency/nook-exchange/Emoji.res b/tests/syntax_tests/data/idempotency/nook-exchange/Emoji.res index ff139a6d29..efb2e03b2a 100644 --- a/tests/syntax_tests/data/idempotency/nook-exchange/Emoji.res +++ b/tests/syntax_tests/data/idempotency/nook-exchange/Emoji.res @@ -37,7 +37,7 @@ let parseText = (text: string): React.element => { let children = [] let iter = ref(0) - let resultRef = ref(text |> Js.Re.exec_(emojiRegex)) + let resultRef = ref(text->Js.Re.exec_(emojiRegex)) while resultRef.contents != None { let result = Belt.Option.getExn(resultRef.contents) let matches = Js.Re.captures(result) @@ -46,15 +46,15 @@ let parseText = (text: string): React.element => { Js.Re.index(result) + Belt.Option.getExn(Js.Nullable.toOption(matches[1]))->Js.String.length if iter.contents < offset { children - |> Js.Array.push( + ->Js.Array.push( - {React.string(text |> Js.String.substring(~from=iter.contents, ~to_=offset))} + {React.string(text->Js.String.substring(~from=iter.contents, ~to_=offset))} , ) - |> ignore + ->ignore } children - |> Js.Array.push( + ->Js.Array.push( switch emojiColons { | ":nmt:" => | ":bell:" => @@ -64,19 +64,19 @@ let parseText = (text: string): React.element => { }, ) - |> ignore + ->ignore - resultRef := text |> Js.Re.exec_(emojiRegex) + resultRef := text->Js.Re.exec_(emojiRegex) iter := offset + Js.String.length(emojiColons) } if iter.contents < Js.String.length(text) { children - |> Js.Array.push( + ->Js.Array.push( - {React.string(text |> Js.String.substringToEnd(~from=iter.contents))} + {React.string(text->Js.String.substringToEnd(~from=iter.contents))} , ) - |> ignore + ->ignore } React.array(children) } diff --git a/tests/syntax_tests/data/idempotency/nook-exchange/Error.res b/tests/syntax_tests/data/idempotency/nook-exchange/Error.res index 9382ff7bc1..9f6020d501 100644 --- a/tests/syntax_tests/data/idempotency/nook-exchange/Error.res +++ b/tests/syntax_tests/data/idempotency/nook-exchange/Error.res @@ -41,4 +41,4 @@ module ErrorPopup = { } let showPopup = (~message) => - ReactAtmosphere.API.pushLayer(~render=_ => ) |> ignore + ReactAtmosphere.API.pushLayer(~render=_ => )->ignore diff --git a/tests/syntax_tests/data/idempotency/nook-exchange/Experiment.res b/tests/syntax_tests/data/idempotency/nook-exchange/Experiment.res index 443836db32..1df6698e2f 100644 --- a/tests/syntax_tests/data/idempotency/nook-exchange/Experiment.res +++ b/tests/syntax_tests/data/idempotency/nook-exchange/Experiment.res @@ -1,11 +1,11 @@ let key = "bucket_hash" let bucketHash = ref( - (Dom.Storage.localStorage |> Dom.Storage.getItem(key))->Belt.Option.flatMap(int_of_string_opt), + (Dom.Storage.localStorage->Dom.Storage.getItem(key))->Belt.Option.flatMap(int_of_string_opt), ) let triggerKey = "triggered_experiments" let triggeredMap = ref( - (Dom.Storage.localStorage |> Dom.Storage.getItem(triggerKey)) + (Dom.Storage.localStorage->Dom.Storage.getItem(triggerKey)) ->Belt.Option.map(value => { let json = Js.Json.parseExn(value) open Json.Decode @@ -16,7 +16,7 @@ let triggeredMap = ref( let addTrigger = (key, value) => { triggeredMap.contents->Js.Dict.set(key, value) open Dom.Storage - localStorage |> setItem( + localStorage->setItem( triggerKey, Js.Json.stringify({ open Json.Encode @@ -32,7 +32,7 @@ let getBucketHash = () => | None => let value = Js.Math.random_int(0, max_int) bucketHash := Some(value) - Dom.Storage.localStorage |> Dom.Storage.setItem(key, string_of_int(value)) + Dom.Storage.localStorage->Dom.Storage.setItem(key, string_of_int(value)) value } diff --git a/tests/syntax_tests/data/idempotency/nook-exchange/FriendsPage.res b/tests/syntax_tests/data/idempotency/nook-exchange/FriendsPage.res index b3402424ec..08fe81649c 100644 --- a/tests/syntax_tests/data/idempotency/nook-exchange/FriendsPage.res +++ b/tests/syntax_tests/data/idempotency/nook-exchange/FriendsPage.res @@ -35,9 +35,9 @@ let fetchFeed = () => open Json.Decode let feed = json - |> array(json => { + ->array(json => { let items = - (json |> field("items", dict(User.itemFromJson))) + (json->field("items", dict(User.itemFromJson))) ->Js.Dict.entries ->Belt.Array.keepMap(((itemKey, item)) => item->Belt.Option.flatMap(item => @@ -48,19 +48,19 @@ let fetchFeed = () => )) ) ) - |> Js.Array.sortInPlaceWith(((_, _, aItem: User.item), (_, _, bItem: User.item)) => + ->Js.Array.sortInPlaceWith(((_, _, aItem: User.item), (_, _, bItem: User.item)) => compareOptionTimestamps(aItem.timeUpdated, bItem.timeUpdated) ) { - id: json |> field("id", string), - username: json |> field("username", string), + id: json->field("id", string), + username: json->field("username", string), lastUpdate: Belt.Array.get(items, 0)->Belt.Option.flatMap(((_, _, item)) => item.timeUpdated ), items: items, } }) - |> Js.Array.sortInPlaceWith((a, b) => compareOptionTimestamps(a.lastUpdate, b.lastUpdate)) + ->Js.Array.sortInPlaceWith((a, b) => compareOptionTimestamps(a.lastUpdate, b.lastUpdate)) Promise.resolved(feed) }) }) @@ -207,7 +207,7 @@ module Followee = { | Error(_) => () } Promise.resolved() - }) |> ignore + })->ignore }} className=Styles.unfollowLink> {React.string("Unfollow")} @@ -217,8 +217,8 @@ module Followee = { {!unfollowed ?
{followee.items - |> Js.Array.slice(~start=0, ~end_=numCards - 1) - |> Js.Array.map(((itemId, variant, userItem)) => + ->Js.Array.slice(~start=0, ~end_=numCards - 1) + ->Js.Array.map(((itemId, variant, userItem)) => ) - |> React.array} + ->React.array} {Js.Array.length(followee.items) > 0 ? ignore + })->ignore None }) @@ -299,8 +299,8 @@ module WithViewer = { Js.Array.length(feed) > 0 ?
{feed - |> Js.Array.map(followee => ) - |> React.array} + ->Js.Array.map(followee => ) + ->React.array}
:
{React.string("Visit people's profiles to add them to your friends page!")} diff --git a/tests/syntax_tests/data/idempotency/nook-exchange/HeaderBar.res b/tests/syntax_tests/data/idempotency/nook-exchange/HeaderBar.res index 8c25586f50..eff9d25227 100644 --- a/tests/syntax_tests/data/idempotency/nook-exchange/HeaderBar.res +++ b/tests/syntax_tests/data/idempotency/nook-exchange/HeaderBar.res @@ -127,8 +127,8 @@ module Menu = { setAnimateIn(_ => true) let onClick = _ => onClose() open Webapi.Dom - window |> Window.addClickEventListener(onClick) - Some(() => window |> Window.removeClickEventListener(onClick)) + window->Window.addClickEventListener(onClick) + Some(() => window->Window.removeClickEventListener(onClick)) })
@@ -157,7 +157,7 @@ module Menu = { href="#" className=MenuStyles.menuItem onClick={e => { - UserStore.logout() |> ignore + UserStore.logout()->ignore ReactEvent.Mouse.preventDefault(e) }}> {React.string("Logout")} @@ -195,12 +195,12 @@ let make = (~onLogin) => { let user = UserStore.useMe() let (isNearTop, setIsNearTop) = React.useState(() => { open Webapi.Dom - window |> Window.pageYOffset < nearTopThreshold + window->Window.pageYOffset < nearTopThreshold }) let (isScrollingUp, setIsScrollingUp) = React.useState(() => false) React.useEffect0(() => { open Webapi.Dom - let scrollTop = ref(window |> Window.pageYOffset) + let scrollTop = ref(window->Window.pageYOffset) let isScrollingUp = ref(false) let newIsNearTop = scrollTop.contents < nearTopThreshold if newIsNearTop != isNearTop { @@ -208,7 +208,7 @@ let make = (~onLogin) => { } let isNearTop = ref(newIsNearTop) let onScroll = e => { - let newScrollTop = window |> Window.pageYOffset + let newScrollTop = window->Window.pageYOffset let newIsScrollingUp = newScrollTop < scrollTop.contents && newScrollTop > scrollTop.contents -. 300. let newIsNearTop = newScrollTop < nearTopThreshold @@ -222,8 +222,8 @@ let make = (~onLogin) => { isScrollingUp := newIsScrollingUp isNearTop := newIsNearTop } - window |> Window.addEventListener("scroll", onScroll) - Some(() => window |> Window.removeEventListener("scroll", onScroll)) + window->Window.addEventListener("scroll", onScroll) + Some(() => window->Window.removeEventListener("scroll", onScroll)) }) let (showMenu, setShowMenu) = React.useState(() => false)
diff --git a/tests/syntax_tests/data/idempotency/nook-exchange/ImportPage.res b/tests/syntax_tests/data/idempotency/nook-exchange/ImportPage.res index 87774b64f0..931ee44660 100644 --- a/tests/syntax_tests/data/idempotency/nook-exchange/ImportPage.res +++ b/tests/syntax_tests/data/idempotency/nook-exchange/ImportPage.res @@ -256,10 +256,10 @@ module ResultRowWithItem = {
{variants - |> Js.Array.map(variant => + ->Js.Array.map(variant => ) - |> React.array} + ->React.array}
} @@ -305,9 +305,9 @@ module BulkActions = { ReactEvent.Mouse.preventDefault(e) setItemStates(itemStates => itemStates - |> Js.Dict.entries - |> Js.Array.map(((key, _value)) => (key, #Ignore)) - |> Js.Dict.fromArray + ->Js.Dict.entries + ->Js.Array.map(((key, _value)) => (key, #Ignore)) + ->Js.Dict.fromArray ) setShowPopup(_ => false) Analytics.Amplitude.logEventWithProperties( @@ -323,9 +323,9 @@ module BulkActions = { ReactEvent.Mouse.preventDefault(e) setItemStates(itemStates => itemStates - |> Js.Dict.entries - |> Js.Array.map(((key, _value)) => (key, #ForTrade)) - |> Js.Dict.fromArray + ->Js.Dict.entries + ->Js.Array.map(((key, _value)) => (key, #ForTrade)) + ->Js.Dict.fromArray ) setShowPopup(_ => false) Analytics.Amplitude.logEventWithProperties( @@ -341,9 +341,9 @@ module BulkActions = { ReactEvent.Mouse.preventDefault(e) setItemStates(itemStates => itemStates - |> Js.Dict.entries - |> Js.Array.map(((key, _value)) => (key, #CatalogOnly)) - |> Js.Dict.fromArray + ->Js.Dict.entries + ->Js.Array.map(((key, _value)) => (key, #CatalogOnly)) + ->Js.Dict.fromArray ) setShowPopup(_ => false) Analytics.Amplitude.logEventWithProperties( @@ -359,8 +359,8 @@ module BulkActions = { ReactEvent.Mouse.preventDefault(e) setItemStates(itemStates => itemStates - |> Js.Dict.entries - |> Js.Array.map(((key, value)) => { + ->Js.Dict.entries + ->Js.Array.map(((key, value)) => { let (itemId, _variant) = User.fromItemKey(~key)->Option.getExn let item = Item.getItem(~itemId) ( @@ -372,7 +372,7 @@ module BulkActions = { }, ) }) - |> Js.Dict.fromArray + ->Js.Dict.fromArray ) setShowPopup(_ => false) Analytics.Amplitude.logEventWithProperties( @@ -388,9 +388,9 @@ module BulkActions = { ReactEvent.Mouse.preventDefault(e) setItemStates(itemStates => itemStates - |> Js.Dict.entries - |> Js.Array.map(((key, _value)) => (key, #Wishlist)) - |> Js.Dict.fromArray + ->Js.Dict.entries + ->Js.Array.map(((key, _value)) => (key, #Wishlist)) + ->Js.Dict.fromArray ) setShowPopup(_ => false) Analytics.Amplitude.logEventWithProperties( @@ -630,7 +630,7 @@ module Results = { setSubmitState(_ => Some(Error("Something went wrong. Sorry!"))) Promise.resolved() } - }) |> ignore + })->ignore }, (), ) @@ -648,13 +648,13 @@ module Results = { let process = value => { let rows = value - |> Js.String.split("\n") - |> Js.Array.map(str => str |> Js.String.trim) - |> Js.Array.filter(x => x != "") + ->Js.String.split("\n") + ->Js.Array.map(str => str->Js.String.trim) + ->Js.Array.filter(x => x != "") let resultMap = Js.Dict.empty() let missingQueries = [] rows->Array.forEach(row => { - let result = row |> Js.Re.exec_(/(.*?) \[(.*?)\]$/g) + let result = row->Js.Re.exec_(/(.*?) \[(.*?)\]$/g) let itemWithVariant = switch result { | Some(match_) => let captures = Js.Re.captures(match_) @@ -683,19 +683,19 @@ let process = value => { resultMap->Js.Dict.set(string_of_int(item.id), arr) arr } - variants |> Js.Array.forEach(variant => - if !(resultMapVariants |> Js.Array.includes(variant)) { - resultMapVariants |> Js.Array.push(variant) |> ignore + variants->Js.Array.forEach(variant => + if !(resultMapVariants->Js.Array.includes(variant)) { + resultMapVariants->Js.Array.push(variant)->ignore } ) - | None => missingQueries |> Js.Array.push(row) |> ignore + | None => missingQueries->Js.Array.push(row)->ignore } }) ( resultMap ->Js.Dict.entries ->Array.map(((itemId, variants)) => (Item.getItem(~itemId=int_of_string(itemId)), variants)) - |> Js.Array.sortInPlaceWith(((aItem, _), (bItem, _)) => + ->Js.Array.sortInPlaceWith(((aItem, _), (bItem, _)) => ItemFilters.compareItemsABC(aItem, bItem) ), missingQueries, @@ -723,7 +723,7 @@ let make = (~showLogin, ~url: ReasonReactRouter.url) => { React.useEffect0(() => { open Webapi.Url.URLSearchParams let searchParams = make(url.search) - let catalogScannerId = searchParams |> get("cs") + let catalogScannerId = searchParams->get("cs") switch catalogScannerId { | Some(catalogScannerId) => setIsFetchingFromCatalogScanner(_ => true) @@ -748,7 +748,7 @@ let make = (~showLogin, ~url: ReasonReactRouter.url) => { } }) | None => Promise.resolved() - } |> ignore + }->ignore Analytics.Amplitude.logEvent(~eventName="Import Page Viewed") None }) diff --git a/tests/syntax_tests/data/idempotency/nook-exchange/Item.res b/tests/syntax_tests/data/idempotency/nook-exchange/Item.res index da96303879..c55b6223a8 100644 --- a/tests/syntax_tests/data/idempotency/nook-exchange/Item.res +++ b/tests/syntax_tests/data/idempotency/nook-exchange/Item.res @@ -87,47 +87,47 @@ let spaceRegex = /\s/g exception Unexpected let jsonToItems = (json: Js.Json.t) => { open Json.Decode - let flags = json |> field("flags", int) - let recipeInfo = json |> optional( + let flags = json->field("flags", int) + let recipeInfo = json->optional( field("recipe", json => { let jsonArray = Js.Json.decodeArray(json)->Belt.Option.getExn ( -int(jsonArray[0]), string(jsonArray[1]), jsonArray - |> Js.Array.sliceFrom(2) - |> Js.Array.map(json => { - let (quantity, itemName) = json |> tuple2(int, string) + ->Js.Array.sliceFrom(2) + ->Js.Array.map(json => { + let (quantity, itemName) = json->tuple2(int, string) (itemName, quantity) }), ) }), ) let item = { - id: json |> field("id", int), + id: json->field("id", int), type_: Item(recipeInfo->Belt.Option.map(((recipeId, _, _)) => recipeId)), - name: json |> field("name", string), - image: json |> field( + name: json->field("name", string), + image: json->field( "image", oneOf(list{json => Base(string(json)), json => Array(array(string, json))}), ), - variations: switch json |> field("variants", array(int)) { + variations: switch json->field("variants", array(int)) { | [] => Single | [a] => OneDimension(a) | [a, b] => TwoDimensions(a, b) | _ => raise(Unexpected) }, - sellPrice: json |> optional(field("sell", int)), - buyPrice: json |> optional(field("buy", int)), + sellPrice: json->optional(field("sell", int)), + buyPrice: json->optional(field("buy", int)), recipe: recipeInfo->Belt.Option.map(((_, _, recipe)) => recipe), orderable: land(flags, 2) !== 0, - source: json |> optional(field("source", string)), + source: json->optional(field("source", string)), bodyCustomizable: land(flags, 4) != 0, patternCustomizable: land(flags, 8) != 0, - customizeCost: json |> optional(field("kitCost", int)), - category: json |> field("category", string), - version: json |> optional(field("v", string)), - tags: (json |> optional(field("tags", array(string))))->Belt.Option.getWithDefault([]), + customizeCost: json->optional(field("kitCost", int)), + category: json->field("category", string), + version: json->optional(field("v", string)), + tags: (json->optional(field("tags", array(string))))->Belt.Option.getWithDefault([]), } let items = switch recipeInfo { | Some((recipeId, recipeSource, _)) => [ @@ -148,20 +148,20 @@ let jsonToItems = (json: Js.Json.t) => { ] | None => [item] } - items |> Js.Array.map((item: t) => { + items->Js.Array.map((item: t) => { let extraTags = [] switch item.source { | Some(source) => if source == "Jolly Redd's Treasure Trawler" { - extraTags |> Js.Array.push("redd") |> ignore + extraTags->Js.Array.push("redd")->ignore } | None => () } - {...item, tags: item.tags |> Js.Array.concat(extraTags)} + {...item, tags: item.tags->Js.Array.concat(extraTags)} }) } -let all = itemsJson |> Json.Decode.array(jsonToItems) |> Belt.Array.concatMany +let all = itemsJson->Json.Decode.array(jsonToItems)->Belt.Array.concatMany let itemMap = { let itemMap = Js.Dict.empty() @@ -243,12 +243,12 @@ let getCanonicalVariant = (~item, ~variant) => type variantNames = | NameOneDimension(array) | NameTwoDimensions((array, array)) -let variantNames: dict = variantsJson |> { +let variantNames: dict = variantsJson->{ open Json.Decode dict( oneOf(list{ - json => NameTwoDimensions(json |> tuple2(array(string), array(string))), - json => NameOneDimension(json |> array(string)), + json => NameTwoDimensions(json->tuple2(array(string), array(string))), + json => NameOneDimension(json->array(string)), }), ) } @@ -269,22 +269,22 @@ let setTranslations = json => { open Json.Decode translations := Some({ - items: json |> field( + items: json->field( "items", dict(json => { let row = Js.Json.decodeArray(json)->Belt.Option.getExn { name: string(row[0]), variants: Belt.Option.map(Belt.Array.get(row, 1), json => - json |> oneOf(list{ - json => NameTwoDimensions(json |> tuple2(array(string), array(string))), - json => NameOneDimension(json |> array(string)), + json->oneOf(list{ + json => NameTwoDimensions(json->tuple2(array(string), array(string))), + json => NameOneDimension(json->array(string)), }) ), } }), ), - materials: json |> field("materials", dict(string)), + materials: json->field("materials", dict(string)), }) } let clearTranslations = () => translations := None @@ -353,7 +353,7 @@ let getMaterialName = (material: string) => { ->Option.getWithDefault(material) } -let getCanonicalName = text => Js.String.toLowerCase(text) |> Js.String.replaceByRe(spaceRegex, "-") +let getCanonicalName = text => Js.String.toLowerCase(text)->Js.String.replaceByRe(spaceRegex, "-") let getByName = (~name: string) => { let searchName = getCanonicalName(name) all->Belt.Array.getBy((item: t) => diff --git a/tests/syntax_tests/data/idempotency/nook-exchange/ItemBrowser.res b/tests/syntax_tests/data/idempotency/nook-exchange/ItemBrowser.res index bdc1f15513..2a9c5852e7 100644 --- a/tests/syntax_tests/data/idempotency/nook-exchange/ItemBrowser.res +++ b/tests/syntax_tests/data/idempotency/nook-exchange/ItemBrowser.res @@ -51,7 +51,7 @@ module Styles = { let getNumResultsPerPage = () => { open Webapi.Dom - let windowWidth = window |> Window.innerWidth + let windowWidth = window->Window.innerWidth if windowWidth >= 1520 { 50 } else if windowWidth >= 1200 { @@ -105,7 +105,7 @@ let make = (~showLogin, ~url: ReasonReactRouter.url) => { ) ReasonReactRouter.push(getUrl(~url, ~urlSearchParams)) } - let excludeString = filters.exclude |> Js.Array.joinWith(",") + let excludeString = filters.exclude->Js.Array.joinWith(",") let excludeUserItemIds = React.useMemo2(() => if isLoggedIn && Js.Array.length(filters.exclude) > 0 { let userItems = UserStore.getUser().items @@ -115,13 +115,13 @@ let make = (~showLogin, ~url: ReasonReactRouter.url) => { ->Belt.Array.forEach(((itemKey, userItem)) => if ( switch userItem.status { - | Wishlist => filters.exclude |> Js.Array.includes(ItemFilters.Wishlist) + | Wishlist => filters.exclude->Js.Array.includes(ItemFilters.Wishlist) | CanCraft => - filters.exclude |> Js.Array.includes(ItemFilters.Catalog) || - filters.exclude |> Js.Array.includes(ItemFilters.CanCraft) + filters.exclude->Js.Array.includes(ItemFilters.Catalog) || + filters.exclude->Js.Array.includes(ItemFilters.CanCraft) | CatalogOnly | ForTrade => - filters.exclude |> Js.Array.includes(ItemFilters.Catalog) + filters.exclude->Js.Array.includes(ItemFilters.Catalog) } ) { let (itemId, variant) = User.fromItemKey(~key=itemKey)->Belt.Option.getExn @@ -132,7 +132,7 @@ let make = (~showLogin, ~url: ReasonReactRouter.url) => { userItemMap->Js.Dict.set(string_of_int(itemId), list) list } - itemVariantList |> Js.Array.push(variant) |> ignore + itemVariantList->Js.Array.push(variant)->ignore } ) userItemMap @@ -160,7 +160,7 @@ let make = (~showLogin, ~url: ReasonReactRouter.url) => { Js.Array.includes(Item.getItemIdForRecipe(~recipe=item), excludeUserItemIds)) ) && ItemFilters.doesItemMatchFilters(~item, ~filters) - ) |> Js.Array.sortInPlaceWith(ItemFilters.getSort(~sort=filters.sort)), + )->Js.Array.sortInPlaceWith(ItemFilters.getSort(~sort=filters.sort)), (filters, excludeUserItemIds), ) let numResults = filteredItems->Belt.Array.length @@ -169,12 +169,12 @@ let make = (~showLogin, ~url: ReasonReactRouter.url) => { React.useEffect1(() => { open Webapi.Dom if React.Ref.current(isInitialLoadRef) { - window |> Window.scrollTo(0., 0.) + window->Window.scrollTo(0., 0.) React.Ref.setCurrent(isInitialLoadRef, false) } else { let rootElement = Utils.getElementForDomRef(rootRef) let boundingRect = Element.getBoundingClientRect(rootElement) - window |> Window.scrollBy( + window->Window.scrollBy( 0., DomRect.top(boundingRect) -. float_of_int(Constants.headerHeight), ) diff --git a/tests/syntax_tests/data/idempotency/nook-exchange/ItemCard.res b/tests/syntax_tests/data/idempotency/nook-exchange/ItemCard.res index d50455c84b..85455357af 100644 --- a/tests/syntax_tests/data/idempotency/nook-exchange/ItemCard.res +++ b/tests/syntax_tests/data/idempotency/nook-exchange/ItemCard.res @@ -233,12 +233,12 @@ module RecipeIcon = { Cn.ifTrue(MetaIconStyles.iconClickable, onClick !== None), Cn.unpack(className), })} - onMouseEnter={_ => Js.Global.setTimeout(() => setShowLayer(_ => true), 10) |> ignore} + onMouseEnter={_ => Js.Global.setTimeout(() => setShowLayer(_ => true), 10)->ignore} onMouseLeave={_ => Js.Global.setTimeout(() => if React.Ref.current(isMountedRef) { setShowLayer(_ => false) } - , 10) |> ignore} + , 10)->ignore} onClick=?{Belt.Option.map(onClick, (onClick, e) => if Utils.browserSupportsHover { onClick() @@ -302,7 +302,7 @@ module StatusButtons = { if UserStore.isLoggedIn() { UserStore.setItemStatus(~itemId, ~variation, ~status) } else { - Option.map(showLogin, showLogin => showLogin()) |> ignore + Option.map(showLogin, showLogin => showLogin())->ignore }} className=Styles.statusButton title={switch status { diff --git a/tests/syntax_tests/data/idempotency/nook-exchange/ItemDetailOverlay.res b/tests/syntax_tests/data/idempotency/nook-exchange/ItemDetailOverlay.res index 5aeee3e4aa..0e126a3e87 100644 --- a/tests/syntax_tests/data/idempotency/nook-exchange/ItemDetailOverlay.res +++ b/tests/syntax_tests/data/idempotency/nook-exchange/ItemDetailOverlay.res @@ -486,16 +486,16 @@ module FriendsSection = { %Repromise.JsExn({ let json = Fetch.Response.json(response) open Json.Decode - let friendItems = json |> array(json => { - userId: json |> field("userId", string), - username: json |> field("username", string), - variant: json |> field("variant", int), - status: json |> field("status", int) |> User.itemStatusFromJs |> Belt.Option.getExn, + let friendItems = json->array(json => { + userId: json->field("userId", string), + username: json->field("username", string), + variant: json->field("variant", int), + status: json->field("status", int)->User.itemStatusFromJs->Belt.Option.getExn, }) setFriendItems(_ => Some(friendItems)) Promise.resolved() }) - }) |> ignore + })->ignore None }) @@ -505,8 +505,8 @@ module FriendsSection = {
{friendItems - |> Js.Array.slice(~start=0, ~end_=showLimit) - |> Js.Array.map(friendItem => + ->Js.Array.slice(~start=0, ~end_=showLimit) + ->Js.Array.map(friendItem =>
@@ -536,7 +536,7 @@ module FriendsSection = {
) - |> React.array} + ->React.array} {Js.Array.length(friendItems) > showLimit ?
} diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesApply__Root.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesApply__Root.res index 6ae53cda6d..89eba610e6 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesApply__Root.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesApply__Root.res @@ -16,10 +16,10 @@ let emailSentMessage = () =>
- {"We've sent you a verification mail." |> str} + {"We've sent you a verification mail."->str}

- {"It should reach you in less than a minute. Click the link in the email to sign up, and get started." |> str} + {"It should reach you in less than a minute. Click the link in the email to sign up, and get started."->str}

@@ -60,7 +60,7 @@ let make = (~courseName, ~courseId, ~thumbnailUrl, ~email, ~name, ~privacyPolicy ? - {"Terms of Use" |> str} + {"Terms of Use"->str} : React.null} {termsOfUse && privacyPolicy @@ -70,7 +70,7 @@ let make = (~courseName, ~courseId, ~thumbnailUrl, ~email, ~name, ~privacyPolicy ? - {"Privacy Policy" |> str} + {"Privacy Policy"->str} : React.null}
diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum.res index d448721e49..b78b5e480b 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum.res @@ -18,15 +18,15 @@ type state = { let targetStatusClasses = targetStatus => { let statusClasses = "curriculum__target-status--" ++ - (targetStatus |> TargetStatus.statusToString |> Js.String.toLowerCase) + (targetStatus->TargetStatus.statusToString->Js.String.toLowerCase) "curriculum__target-status px-3 py-px ml-4 h-6 " ++ statusClasses } let rendertarget = (target, statusOfTargets) => { - let targetId = target |> Target.id + let targetId = target->Target.id let targetStatus = - statusOfTargets |> ListUtils.unsafeFind( - ts => ts |> TargetStatus.targetId == targetId, + statusOfTargets->ListUtils.unsafeFind( + ts => ts->TargetStatus.targetId == targetId, "Could not find targetStatus for listed target with ID " ++ targetId, ) @@ -35,41 +35,41 @@ let rendertarget = (target, statusOfTargets) => { key={"target-" ++ targetId} className="bg-white border-t p-6 flex items-center justify-between hover:bg-gray-200 hover:text-primary-500 cursor-pointer" ariaLabel={"Select Target " ++ targetId}> - {target |> Target.title |> str} + {target->Target.title->str} - {targetStatus |> TargetStatus.statusToString |> str} + {targetStatus->TargetStatus.statusToString->str} } let renderTargetGroup = (targetGroup, targets, statusOfTargets) => { - let targetGroupId = targetGroup |> TargetGroup.id - let targets = targets |> List.filter(t => t |> Target.targetGroupId == targetGroupId) + let targetGroupId = targetGroup->TargetGroup.id + let targets = targets->List.filter(t => t->Target.targetGroupId == targetGroupId)
- {targetGroup |> TargetGroup.milestone + {targetGroup->TargetGroup.milestone ?
- {"Milestone targets" |> str} + {"Milestone targets"->str}
: React.null}
- {targetGroup |> TargetGroup.name |> str} + {targetGroup->TargetGroup.name->str}
- {targetGroup |> TargetGroup.description |> str} + {targetGroup->TargetGroup.description->str}
{targets - |> List.sort((t1, t2) => (t1 |> Target.sortIndex) - (t2 |> Target.sortIndex)) - |> List.map(target => rendertarget(target, statusOfTargets)) - |> Array.of_list - |> React.array} + ->List.sort((t1, t2) => (t1->Target.sortIndex) - (t2->Target.sortIndex)) + ->List.map(target => rendertarget(target, statusOfTargets)) + ->Array.of_list + ->React.array}
} @@ -77,8 +77,8 @@ let renderTargetGroup = (targetGroup, targets, statusOfTargets) => { let addSubmission = (setState, latestSubmission) => setState(state => { let withoutSubmissionForThisTarget = - state.latestSubmissions |> List.filter(s => - s |> LatestSubmission.targetId != (latestSubmission |> LatestSubmission.targetId) + state.latestSubmissions->List.filter(s => + s->LatestSubmission.targetId != (latestSubmission->LatestSubmission.targetId) ) { @@ -89,14 +89,14 @@ let addSubmission = (setState, latestSubmission) => let handleLockedLevel = level =>
-
{"Level Locked" |> str}
+
{"Level Locked"->str}
- {switch level |> Level.unlockOn { + {switch level->Level.unlockOn { | Some(date) => - let dateString = date |> DateFns.parseString |> DateFns.format("MMMM D, YYYY") + let dateString = date->DateFns.parseString->DateFns.format("MMMM D, YYYY")
-

{"The level is currently locked!" |> str}

-

{"You can access the content on " ++ (dateString ++ ".") |> str}

+

{"The level is currently locked!"->str}

+

{"You can access the content on " ++ (dateString ++ ".")->str}

| None => React.null }} @@ -104,23 +104,23 @@ let handleLockedLevel = level => let statusOfMilestoneTargets = (targetGroups, targets, level, statusOfTargets) => { let targetGroupsInLevel = - targetGroups |> List.filter(tg => tg |> TargetGroup.levelId == (level |> Level.id)) + targetGroups->List.filter(tg => tg->TargetGroup.levelId == (level->Level.id)) let milestoneTargetGroupIds = targetGroupsInLevel - |> List.filter(tg => tg |> TargetGroup.milestone) - |> List.map(tg => tg |> TargetGroup.id) + ->List.filter(tg => tg->TargetGroup.milestone) + ->List.map(tg => tg->TargetGroup.id) let milestoneTargetIds = targets - |> List.filter(t => (t |> Target.targetGroupId)->List.mem(milestoneTargetGroupIds)) - |> List.map(t => t |> Target.id) + ->List.filter(t => (t->Target.targetGroupId)->List.mem(milestoneTargetGroupIds)) + ->List.map(t => t->Target.id) - statusOfTargets |> List.filter(ts => (ts |> TargetStatus.targetId)->List.mem(milestoneTargetIds)) + statusOfTargets->List.filter(ts => (ts->TargetStatus.targetId)->List.mem(milestoneTargetIds)) } let isLevelComplete = (targetStatuses, eligibleStatuses) => - targetStatuses |> ListUtils.isNotEmpty && - targetStatuses |> TargetStatus.matchesStatuses(eligibleStatuses) + targetStatuses->ListUtils.isNotEmpty && + targetStatuses->TargetStatus.matchesStatuses(eligibleStatuses) let computeLevelUp = ( levels, @@ -130,11 +130,11 @@ let computeLevelUp = ( statusOfTargets, accessLockedLevels, ) => { - let lastLevel = switch teamLevel |> Level.number { + let lastLevel = switch teamLevel->Level.number { | 0 | 1 => None - | levelTwoOrAbove => levels |> ListUtils.findOpt(l => l |> Level.number == levelTwoOrAbove - 1) + | levelTwoOrAbove => levels->ListUtils.findOpt(l => l->Level.number == levelTwoOrAbove - 1) } let statusOfCurrentMilestoneTargets = statusOfMilestoneTargets( @@ -163,13 +163,13 @@ let computeLevelUp = ( } let nextLevel = - levels |> ListUtils.findOpt(l => l |> Level.number == (teamLevel |> Level.number) + 1) + levels->ListUtils.findOpt(l => l->Level.number == (teamLevel->Level.number) + 1) switch (nextLevel, currentLevelComplete, lastLevelComplete) { | (Some(level), true, true) => - level |> Level.isUnlocked || accessLockedLevels ? Notice.LevelUp : Nothing + level->Level.isUnlocked || accessLockedLevels ? Notice.LevelUp : Nothing | (None, true, true) => CourseComplete - | (Some(_), true, false) => LevelUpBlocked(teamLevel |> Level.number) + | (Some(_), true, false) => LevelUpBlocked(teamLevel->Level.number) | (Some(_) | None, false, false | true) | (None, true, false) => Nothing @@ -187,7 +187,7 @@ let computeNotice = ( preview, accessLockedLevels, ) => - switch (preview, course |> Course.hasEnded, team |> Team.accessEnded) { + switch (preview, course->Course.hasEnded, team->Team.accessEnded) { | (true, _, _) => Notice.Preview | (false, true, true | false) => CourseEnded | (false, false, true) => AccessEnded @@ -205,18 +205,18 @@ let navigationLink = (direction, level, setState) => { icon->Belt.Option.mapWithDefault(React.null, icon => ) } let quickNavigationLinks = (levels, selectedLevel, setState) => { - let previous = selectedLevel |> Level.previous(levels) - let next = selectedLevel |> Level.next(levels) + let previous = selectedLevel->Level.previous(levels) + let next = selectedLevel->Level.next(levels)

@@ -230,7 +230,7 @@ let quickNavigationLinks = (levels, selectedLevel, setState) => {
{navigationLink(#Next, nextLevel, setState)}
, - ] |> React.array + ]->React.array | (Some(previousUrl), None) =>
{navigationLink(#Previous, previousUrl, setState)}
@@ -261,8 +261,8 @@ let make = ( let selectedTarget = switch url.path { | list{"targets", targetId, ..._} => Some( - targets |> ListUtils.unsafeFind( - t => t |> Target.id == targetId, + targets->ListUtils.unsafeFind( + t => t->Target.id == targetId, "Could not find selectedTarget with ID " ++ targetId, ), ) @@ -277,26 +277,26 @@ let make = ( * used to determine currentLevelId, which is the actual level whose contents * are shown on the page. */ - let levelZero = levels |> ListUtils.findOpt(l => l |> Level.number == 0) - let teamLevelId = team |> Team.levelId + let levelZero = levels->ListUtils.findOpt(l => l->Level.number == 0) + let teamLevelId = team->Team.levelId let teamLevel = - levels |> ListUtils.unsafeFind( - l => l |> Level.id == teamLevelId, + levels->ListUtils.unsafeFind( + l => l->Level.id == teamLevelId, "Could not find teamLevel with ID " ++ teamLevelId, ) let targetLevelId = switch selectedTarget { | Some(target) => - let targetGroupId = target |> Target.targetGroupId + let targetGroupId = target->Target.targetGroupId let targetGroup = - targetGroups |> ListUtils.unsafeFind( - t => t |> TargetGroup.id == targetGroupId, + targetGroups->ListUtils.unsafeFind( + t => t->TargetGroup.id == targetGroupId, "Could not find targetGroup with ID " ++ targetGroupId, ) - Some(targetGroup |> TargetGroup.levelId) + Some(targetGroup->TargetGroup.levelId) | None => None } @@ -317,14 +317,14 @@ let make = ( { selectedLevelId: switch (preview, targetLevelId, levelZero) { - | (true, None, None) => levels |> Level.first |> Level.id + | (true, None, None) => levels->Level.first->Level.id | (_, Some(targetLevelId), Some(levelZero)) => - levelZero |> Level.id == targetLevelId ? teamLevelId : targetLevelId + levelZero->Level.id == targetLevelId ? teamLevelId : targetLevelId | (_, Some(targetLevelId), None) => targetLevelId | (_, None, _) => teamLevelId }, showLevelZero: switch (levelZero, targetLevelId) { - | (Some(levelZero), Some(targetLevelId)) => levelZero |> Level.id == targetLevelId + | (Some(levelZero), Some(targetLevelId)) => levelZero->Level.id == targetLevelId | (Some(_), None) | (None, Some(_)) | (None, None) => false @@ -346,26 +346,26 @@ let make = ( }) let currentLevelId = switch (levelZero, state.showLevelZero) { - | (Some(levelZero), true) => levelZero |> Level.id + | (Some(levelZero), true) => levelZero->Level.id | (Some(_), false) | (None, true | false) => state.selectedLevelId } let currentLevel = - levels |> ListUtils.unsafeFind( - l => l |> Level.id == currentLevelId, + levels->ListUtils.unsafeFind( + l => l->Level.id == currentLevelId, "Could not find currentLevel with id " ++ currentLevelId, ) let selectedLevel = - levels |> ListUtils.unsafeFind( - l => l |> Level.id == state.selectedLevelId, + levels->ListUtils.unsafeFind( + l => l->Level.id == state.selectedLevelId, "Could not find selectedLevel with id " ++ state.selectedLevelId, ) React.useEffect1(() => { - if initialRender |> React.Ref.current { + if initialRender->React.Ref.current { initialRender->React.Ref.setCurrent(false) } else { let newStatusOfTargets = computeTargetStatus(state.latestSubmissions) @@ -390,15 +390,15 @@ let make = ( }, [state.latestSubmissions]) let targetGroupsInLevel = - targetGroups |> List.filter(tg => tg |> TargetGroup.levelId == currentLevelId) + targetGroups->List.filter(tg => tg->TargetGroup.levelId == currentLevelId)
{switch selectedTarget { | Some(target) => let targetStatus = - state.statusOfTargets |> ListUtils.unsafeFind( - ts => ts |> TargetStatus.targetId == (target |> Target.id), - "Could not find targetStatus for selectedTarget with ID " ++ (target |> Target.id), + state.statusOfTargets->ListUtils.unsafeFind( + ts => ts->TargetStatus.targetId == (target->Target.id), + "Could not find targetStatus for selectedTarget with ID " ++ (target->Target.id), ) {...state, showLevelZero: showLevelZero})} levelZero /> - {currentLevel |> Level.isLocked && accessLockedLevels + {currentLevel->Level.isLocked && accessLockedLevels ?
- {"This level is still locked for students, and will be unlocked on " |> str} - {currentLevel |> Level.unlockDateString |> str} - {"." |> str} + {"This level is still locked for students, and will be unlocked on "->str} + {currentLevel->Level.unlockDateString->str} + {"."->str}
: React.null} - {currentLevel |> Level.isUnlocked || accessLockedLevels + {currentLevel->Level.isUnlocked || accessLockedLevels ? targetGroupsInLevel - |> TargetGroup.sort - |> List.map(targetGroup => + ->TargetGroup.sort + ->List.map(targetGroup => renderTargetGroup(targetGroup, targets, state.statusOfTargets) ) - |> Array.of_list - |> React.array + ->Array.of_list + ->React.array : handleLockedLevel(currentLevel)}
}} diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__AutoVerify.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__AutoVerify.res index 1c438b6f65..5713736ee4 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__AutoVerify.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__AutoVerify.res @@ -17,7 +17,7 @@ module AutoVerifySubmissionQuery = %graphql(` let redirect = link => { let window = Webapi.Dom.window - window |> Webapi.Dom.Window.open_(~url=link, ~name="_blank", ~features="") |> ignore + window->Webapi.Dom.Window.open_(~url=link, ~name="_blank", ~features="")->ignore } let handleSuccess = (submission, linkToComplete, addSubmissionCB) => { @@ -36,30 +36,30 @@ let handleSuccess = (submission, linkToComplete, addSubmissionCB) => { } let createAutoVerifySubmission = (target, linkToComplete, setSaving, addSubmissionCB, event) => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault setSaving(_ => true) - AutoVerifySubmissionQuery.make(~targetId=target |> Target.id, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => { + AutoVerifySubmissionQuery.make(~targetId=target->Target.id, ()) + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => { switch response["autoVerifySubmission"]["submission"] { | Some(details) => handleSuccess(details, linkToComplete, addSubmissionCB) | None => setSaving(_ => false) } Js.Promise.resolve() }) - |> ignore + ->ignore } let completeButtonText = (title, iconClasses) => - {title |> str} + {title->str} let previewLinkToComplete = link => - {"Visit Link " |> str} + {"Visit Link "->str} let autoVerify = (target, linkToComplete, saving, setSaving, addSubmissionCB, preview) => @@ -87,11 +87,11 @@ let statusBar = (string, linkToComplete) => { - {string |> str} + {string->str}
let visitLink = link => - {"Visit Link" |> str} + {"Visit Link"->str}
@@ -112,17 +112,17 @@ let completionInstructionText = linkToComplete => @react.component let make = (~target, ~targetDetails, ~targetStatus, ~addSubmissionCB, ~preview) => { let (saving, setSaving) = React.useState(() => false) - let linkToComplete = targetDetails |> TargetDetails.linkToComplete + let linkToComplete = targetDetails->TargetDetails.linkToComplete [ ,
- {switch targetStatus |> TargetStatus.status { + {switch targetStatus->TargetStatus.status { | Pending => autoVerify(target, linkToComplete, saving, setSaving, addSubmissionCB, preview) | Locked(_) => React.null | _ => statusBar("Completed", linkToComplete) }}
, - ] |> React.array + ]->React.array } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__ChecklistItem.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__ChecklistItem.res index 7c51e571a5..8a9b12fa6d 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__ChecklistItem.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__ChecklistItem.res @@ -27,10 +27,10 @@ let optional = t => t.optional let make = (~result, ~title, ~optional) => {result: result, title: title, optional: optional} let fromTargetChecklistItem = targetChecklist => - targetChecklist |> Array.map(tc => { - let title = tc |> TargetChecklistItem.title - let optional = tc |> TargetChecklistItem.optional - let result = switch tc |> TargetChecklistItem.kind { + targetChecklist->Array.map(tc => { + let title = tc->TargetChecklistItem.title + let optional = tc->TargetChecklistItem.optional + let result = switch tc->TargetChecklistItem.kind { | Files => Files([]) | Link => Link("") | ShortText => ShortText("") @@ -41,7 +41,7 @@ let fromTargetChecklistItem = targetChecklist => }) let updateResultAtIndex = (index, result, checklist) => - checklist |> Array.mapi((i, c) => i == index ? {...c, result: result} : c) + checklist->Array.mapi((i, c) => i == index ? {...c, result: result} : c) let makeFile = (id, name) => {id: id, name: name} @@ -51,13 +51,13 @@ let fileId = file => file.id let fileIds = checklist => checklist - |> Array.map(c => + ->Array.map(c => switch c.result { - | Files(files) => files |> Array.map(a => a.id) |> Array.to_list + | Files(files) => files->Array.map(a => a.id)->Array.to_list | _anyOtherResult => list{} } ) - |> ArrayUtils.flatten + ->ArrayUtils.flatten let kindAsString = t => switch t.result { @@ -75,11 +75,11 @@ let resultAsString = t => | ShortText(t) | LongText(t) => t | MultiChoice(choices, index) => - index |> OptionUtils.flatMap(i => choices |> ArrayUtils.getOpt(i)) |> OptionUtils.default("") + index->OptionUtils.flatMap(i => choices->ArrayUtils.getOpt(i))->OptionUtils.default("") } let validString = (s, maxLength) => { - let length = s |> String.trim |> String.length + let length = s->String.trim->String.length length >= 1 && length <= maxLength } @@ -87,19 +87,19 @@ let validShortText = s => validString(s, 250) let validLongText = s => validString(s, 5000) -let validFiles = files => files != [] && files |> Array.length < 3 +let validFiles = files => files != [] && files->Array.length < 3 let validMultiChoice = (choices, index) => - index |> OptionUtils.mapWithDefault(i => choices |> Array.length > i, false) + index->OptionUtils.mapWithDefault(i => choices->Array.length > i, false) let validResponse = (response, allowBlank) => { let optional = allowBlank ? response.optional : false switch (response.result, optional) { | (Files(files), false) => validFiles(files) - | (Files(files), true) => files |> ArrayUtils.isEmpty || validFiles(files) - | (Link(link), false) => link |> UrlUtils.isValid(false) - | (Link(link), true) => link |> UrlUtils.isValid(true) + | (Files(files), true) => files->ArrayUtils.isEmpty || validFiles(files) + | (Link(link), false) => link->UrlUtils.isValid(false) + | (Link(link), true) => link->UrlUtils.isValid(true) | (ShortText(t), false) => validShortText(t) | (ShortText(t), true) => validShortText(t) || t == "" | (LongText(t), false) => validLongText(t) @@ -111,43 +111,43 @@ let validResponse = (response, allowBlank) => { let validChecklist = checklist => checklist - |> Array.map(c => validResponse(c, true)) - |> Js.Array.filter(c => !c) - |> ArrayUtils.isEmpty + ->Array.map(c => validResponse(c, true)) + ->Js.Array.filter(c => !c) + ->ArrayUtils.isEmpty -let validResonses = responses => responses |> Js.Array.filter(c => validResponse(c, false)) +let validResonses = responses => responses->Js.Array.filter(c => validResponse(c, false)) let encode = t => { open Json.Encode object_(list{ - ("title", t.title |> string), - ("kind", kindAsString(t) |> string), - ("status", "noAnswer" |> string), - ("result", resultAsString(t) |> string), + ("title", t.title->string), + ("kind", kindAsString(t)->string), + ("status", "noAnswer"->string), + ("result", resultAsString(t)->string), }) } let encodeArray = checklist => - validResonses(checklist) |> { + validResonses(checklist)->{ open Json.Encode array(encode) } let makeFiles = checklist => checklist - |> Js.Array.find(c => + ->Js.Array.find(c => switch c.result { | Files(_files) => true | _anyOtherResult => false } ) - |> OptionUtils.mapWithDefault(c => + ->OptionUtils.mapWithDefault(c => switch c.result { | Files(files) => files | _anyOtherResult => [] } , []) - |> Array.map(f => { + ->Array.map(f => { let url = "/timeline_event_files/" ++ (f.id ++ "/download") SubmissionChecklistItem.makeFile(~name=f.name, ~id=f.id, ~url) }) diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Coach.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Coach.res index 4b93c20338..98ac7681d9 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Coach.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Coach.res @@ -9,7 +9,7 @@ let userId = t => t.userId let decode = json => { open Json.Decode { - id: json |> field("id", string), - userId: json |> field("userId", string), + id: json->field("id", string), + userId: json->field("userId", string), } } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Community.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Community.res index 6670c29a5c..1ee51b54c7 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Community.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Community.res @@ -12,17 +12,17 @@ type t = { let decodeQuestion = json => { open Json.Decode { - questionId: json |> field("id", string), - questionTitle: json |> field("title", string), + questionId: json->field("id", string), + questionTitle: json->field("title", string), } } let decode = json => { open Json.Decode { - id: json |> field("id", string), - name: json |> field("name", string), - questions: json |> field("questions", list(decodeQuestion)), + id: json->field("id", string), + name: json->field("name", string), + questions: json->field("questions", list(decodeQuestion)), } } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__CompletionInstructions.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__CompletionInstructions.res index 0179cd438a..5083fdfa17 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__CompletionInstructions.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__CompletionInstructions.res @@ -4,7 +4,7 @@ open CoursesCurriculum__Types @react.component let make = (~targetDetails, ~title) => - switch targetDetails |> TargetDetails.completionInstructions { + switch targetDetails->TargetDetails.completionInstructions { | Some(completionInstructions) =>
@@ -12,8 +12,8 @@ let make = (~targetDetails, ~title) =>
-

{title |> str}

-

{completionInstructions |> str}

+

{title->str}

+

{completionInstructions->str}

| None => React.null diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Course.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Course.res index 194823d7dd..979dd0745a 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Course.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Course.res @@ -6,8 +6,8 @@ type t = { let decode = json => { open Json.Decode { - id: json |> field("id", string), - endsAt: json |> field("endsAt", nullable(string)) |> Js.Null.toOption, + id: json->field("id", string), + endsAt: json->field("endsAt", nullable(string))->Js.Null.toOption, } } @@ -16,6 +16,6 @@ let id = t => t.id let hasEnded = t => switch t.endsAt { - | Some(date) => date |> DateFns.parseString |> DateFns.isPast + | Some(date) => date->DateFns.parseString->DateFns.isPast | None => false } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Discuss.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Discuss.res index 68e668d1c1..e41cac3a5c 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Discuss.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Discuss.res @@ -9,14 +9,14 @@ let linkToNewQuestion = (communityId, targetId) => "/communities/" ++ (communityId ++ ("/new_question" ++ ("?target_id=" ++ targetId))) let questionCard = question => { - let questionId = question |> Community.questionId + let questionId = question->Community.questionId let questionLink = "/questions/" ++ questionId
- {question |> Community.questionTitle |> str} - {"View" |> str} + {question->Community.questionTitle->str} + {"View"->str}
} @@ -25,59 +25,59 @@ let handleEmpty = () =>

- {"There's been no recent discussion about this target." |> str} + {"There's been no recent discussion about this target."->str}

-

{"Use the community to clear your doubts, and to help your peers!" |> str}

+

{"Use the community to clear your doubts, and to help your peers!"->str}

let actionButtons = (community, targetId) => { - let communityId = community |> Community.id - let communityName = community |> Community.name + let communityId = community->Community.id + let communityName = community->Community.name } let communityTitle = community =>
- {"Questions from " ++ ((community |> Community.name) ++ " community") |> str} + {"Questions from " ++ ((community->Community.name) ++ " community")->str}
@react.component let make = (~targetId, ~communities) =>
{communities - |> List.map(community => { - let communityId = community |> Community.id + ->List.map(community => { + let communityId = community->Community.id
{communityTitle(community)}
{actionButtons(community, targetId)}
- {switch community |> Community.questions { + {switch community->Community.questions { | list{} => handleEmpty() | questions => questions - |> List.map(question => questionCard(question)) - |> Array.of_list - |> React.array + ->List.map(question => questionCard(question)) + ->Array.of_list + ->React.array }}
}) - |> Array.of_list - |> React.array} + ->Array.of_list + ->React.array}
diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Feedback.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Feedback.res index 26d2d78ca1..790035ad58 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Feedback.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Feedback.res @@ -15,9 +15,9 @@ let feedback = t => t.feedback let decode = json => { open Json.Decode { - id: json |> field("id", string), - coachId: json |> field("coachId", string), - submissionId: json |> field("submissionId", string), - feedback: json |> field("feedback", string), + id: json->field("id", string), + coachId: json->field("coachId", string), + submissionId: json->field("submissionId", string), + feedback: json->field("feedback", string), } } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__FileForm.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__FileForm.res index 1f95a0d166..c454d42a9c 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__FileForm.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__FileForm.res @@ -24,7 +24,7 @@ let reducer = (state, action) => } let handleResponseJSON = (filename, send, attachFileCB, json) => { - let id = json |> { + let id = json->{ open Json.Decode field("id", string) } @@ -48,19 +48,19 @@ let uploadFile = (filename, send, attachFileCB, formData) => { (), ), ) - |> then_(response => + ->then_(response => if Fetch.Response.ok(response) { - response |> Fetch.Response.json + response->Fetch.Response.json } else { - Js.Promise.reject(UnexpectedResponse(response |> Fetch.Response.status)) + Js.Promise.reject(UnexpectedResponse(response->Fetch.Response.status)) } ) - |> then_(json => handleResponseJSON(filename, send, attachFileCB, json) |> resolve) - |> catch(error => - switch error |> handleApiError { + ->then_(json => handleResponseJSON(filename, send, attachFileCB, json)->resolve) + ->catch(error => + switch error->handleApiError { | Some(code) => Notification.error( - "Error " ++ (code |> string_of_int), + "Error " ++ (code->string_of_int), "Please reload the page and try again.", ) | None => @@ -68,16 +68,16 @@ let uploadFile = (filename, send, attachFileCB, formData) => { "Something went wrong!", "Our team has been notified of this error. Please reload the page and try again.", ) - } |> resolve + }->resolve ) - |> ignore + ->ignore } let submitForm = (filename, formId, send, addFileAttachmentCB) => { let element = ReactDOMRe._getElementById(formId) switch element { | Some(element) => - DomUtils.FormData.create(element) |> uploadFile(filename, send, addFileAttachmentCB) + DomUtils.FormData.create(element)->uploadFile(filename, send, addFileAttachmentCB) | None => raise(FormNotFound(formId)) } } @@ -93,7 +93,7 @@ let attachFile = (state, send, attachingCB, attachFileCB, preview, event) => let errors = file["size"] > maxFileSize ? list{"The maximum file size is 5 MB."} : list{} - if errors |> ListUtils.isEmpty { + if errors->ListUtils.isEmpty { let filename = file["name"] attachingCB(true) send(AttachFile(filename)) @@ -108,7 +108,7 @@ let make = (~attachFileCB, ~attachingCB, ~preview) => { let (state, send) = React.useReducer( reducer, { - formId: Random.int(99999) |> string_of_int, + formId: Random.int(99999)->string_of_int, filename: defaultTitle, errors: list{}, }, @@ -131,22 +131,22 @@ let make = (~attachFileCB, ~attachingCB, ~preview) => { htmlFor="attachment_file"> - {state.filename |> str} + {state.filename->str} {state.errors - |> List.map(error => + ->List.map(error =>
- {error |> str} + {error->str}
) - |> Array.of_list - |> React.array} - {state.errors |> ListUtils.isEmpty + ->Array.of_list + ->React.array} + {state.errors->ListUtils.isEmpty ? React.null :
- {"Please choose another file for upload." |> str} + {"Please choose another file for upload."->str}
}
} diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Grade.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Grade.res index d92cf72613..576005e622 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Grade.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Grade.res @@ -7,20 +7,20 @@ type t = { let decode = json => { open Json.Decode { - submissionId: json |> field("submissionId", string), - evaluationCriterionId: json |> field("evaluationCriterionId", string), - grade: json |> field("grade", int), + submissionId: json->field("submissionId", string), + evaluationCriterionId: json->field("evaluationCriterionId", string), + grade: json->field("grade", int), } } let sort = (criteria, grades) => grades - |> Array.of_list - |> ArrayUtils.copyAndSort((g1, g2) => { + ->Array.of_list + ->ArrayUtils.copyAndSort((g1, g2) => { let ec1 = criteria - |> Array.of_list - |> ArrayUtils.unsafeFind( + ->Array.of_list + ->ArrayUtils.unsafeFind( ec => EvaluationCriterion.id(ec) == g1.evaluationCriterionId, "Unable to find evaluation criterion with ID: " ++ (g1.evaluationCriterionId ++ @@ -28,16 +28,16 @@ let sort = (criteria, grades) => ) let ec2 = criteria - |> Array.of_list - |> ArrayUtils.unsafeFind( + ->Array.of_list + ->ArrayUtils.unsafeFind( ec => EvaluationCriterion.id(ec) == g2.evaluationCriterionId, "Unable to find evaluation criterion with ID: " ++ (g2.evaluationCriterionId ++ " in CoursesCurriculum__Grade"), ) - String.compare(ec1 |> EvaluationCriterion.name, ec2 |> EvaluationCriterion.name) + String.compare(ec1->EvaluationCriterion.name, ec2->EvaluationCriterion.name) }) - |> Array.to_list + ->Array.to_list let grade = t => t.grade let submissionId = t => t.submissionId diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__GradeBar.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__GradeBar.res index 75fa164141..fc3629d4cd 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__GradeBar.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__GradeBar.res @@ -5,20 +5,20 @@ let str = React.string open CoursesCurriculum__Types let gradeDescription = (gradeLabels, grading) =>
- {grading |> Grading.criterionName |> str} - {switch grading |> Grading.grade { + {grading->Grading.criterionName->str} + {switch grading->Grading.grade { | Some(grade) => - {": " |> str} + {": "->str} - {grade |> GradeLabel.labelFor(gradeLabels) |> str} + {grade->GradeLabel.labelFor(gradeLabels)->str} | None => ReasonReact.null }}
-let maxGrade = gradeLabels => gradeLabels |> GradeLabel.maxGrade |> string_of_int +let maxGrade = gradeLabels => gradeLabels->GradeLabel.maxGrade->string_of_int let gradePillClasses = (gradeReceived, passGrade, pillGrade, callBack) => { let defaultClasses = "grade-bar__grade-pill cursor-auto" @@ -40,12 +40,12 @@ let gradePillClasses = (gradeReceived, passGrade, pillGrade, callBack) => { let gradeBarHeader = (grading, gradeLabels) =>
- {grading |> gradeDescription(gradeLabels)} - {switch grading |> Grading.grade { + {grading->gradeDescription(gradeLabels)} + {switch grading->Grading.grade { | None => ReasonReact.null | Some(grade) =>
- {(grade |> string_of_int) ++ ("/" ++ maxGrade(gradeLabels)) |> str} + {(grade->string_of_int) ++ ("/" ++ maxGrade(gradeLabels))->str}
}}
@@ -53,20 +53,20 @@ let gradeBarHeader = (grading, gradeLabels) => let handleClick = (gradeSelectCB, grading, newGrade) => switch gradeSelectCB { | None => () - | Some(callBack) => callBack(grading |> Grading.updateGrade(newGrade)) + | Some(callBack) => callBack(grading->Grading.updateGrade(newGrade)) } let gradeBarPill = (gradeLabel, grading, gradeSelectCB, passGrade) => { - let myGrade = gradeLabel |> GradeLabel.grade + let myGrade = gradeLabel->GradeLabel.grade
string_of_int} - title={gradeLabel |> GradeLabel.label} + key={myGrade->string_of_int} + title={gradeLabel->GradeLabel.label} role="button" onClick={_event => handleClick(gradeSelectCB, grading, myGrade)} - className={gradePillClasses(grading |> Grading.grade, passGrade, myGrade, gradeSelectCB)}> + className={gradePillClasses(grading->Grading.grade, passGrade, myGrade, gradeSelectCB)}> {switch gradeSelectCB { | None => ReasonReact.null - | Some(_CB) => myGrade |> string_of_int |> str + | Some(_CB) => myGrade->string_of_int->str }}
} @@ -74,15 +74,15 @@ let gradeBarPill = (gradeLabel, grading, gradeSelectCB, passGrade) => { let gradeBarPanel = (grading, gradeLabels, gradeSelectCB, passGrade) =>
{gradeLabels - |> List.map(gradeLabel => gradeBarPill(gradeLabel, grading, gradeSelectCB, passGrade)) - |> Array.of_list - |> ReasonReact.array} + ->List.map(gradeLabel => gradeBarPill(gradeLabel, grading, gradeSelectCB, passGrade)) + ->Array.of_list + ->ReasonReact.array}
@react.component let make = (~grading, ~gradeSelectCB=?, ~criterion) => { - let gradeLabels = criterion |> EvaluationCriterion.gradesAndLabels |> Array.to_list - let passGrade = criterion |> EvaluationCriterion.passGrade + let gradeLabels = criterion->EvaluationCriterion.gradesAndLabels->Array.to_list + let passGrade = criterion->EvaluationCriterion.passGrade
{gradeBarHeader(grading, gradeLabels)} {gradeBarPanel(grading, gradeLabels, gradeSelectCB, passGrade)} diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Grading.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Grading.res index fc9d66d1bd..c0a18faadf 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Grading.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Grading.res @@ -7,15 +7,15 @@ type t = { let decode = json => { open Json.Decode { - criterionId: json |> field("criterionId", string), - criterionName: json |> field("criterionName", string), - grade: json |> field("grade", nullable(int)) |> Js.Null.toOption, + criterionId: json->field("criterionId", string), + criterionName: json->field("criterionName", string), + grade: json->field("grade", nullable(int))->Js.Null.toOption, } } let grade = t => t.grade -let pending = evaluation => evaluation |> List.exists(grading => grading.grade == None) +let pending = evaluation => evaluation->List.exists(grading => grading.grade == None) let isFail = (passGrade, grading) => switch grading.grade { @@ -24,7 +24,7 @@ let isFail = (passGrade, grading) => } let anyFail = (passGrade, evaluation) => - evaluation |> List.exists(grading => grading |> isFail(passGrade)) + evaluation->List.exists(grading => grading->isFail(passGrade)) let criterionId = t => t.criterionId @@ -39,11 +39,11 @@ let updateGrade = (newGrade, t) => { let gradingEncoder = grading => { open Json.Encode object_(list{ - ("criterionId", grading.criterionId |> string), + ("criterionId", grading.criterionId->string), ( "grade", switch grading.grade { - | Some(grade) => grade |> int + | Some(grade) => grade->int | None => null }, ), diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__LatestSubmission.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__LatestSubmission.res index a2d1c08298..7ce36ea752 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__LatestSubmission.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__LatestSubmission.res @@ -7,9 +7,9 @@ type t = { let decode = json => { open Json.Decode { - targetId: json |> field("targetId", string), - passedAt: json |> field("passedAt", nullable(string)) |> Js.Null.toOption, - evaluatorId: json |> field("evaluatorId", nullable(string)) |> Js.Null.toOption, + targetId: json->field("targetId", string), + passedAt: json->field("passedAt", nullable(string))->Js.Null.toOption, + evaluatorId: json->field("evaluatorId", nullable(string))->Js.Null.toOption, } } @@ -29,6 +29,6 @@ let hasBeenEvaluated = t => let make = (~pending, ~targetId) => { targetId: targetId, - passedAt: pending ? None : Some(Js.Date.make() |> Js.Date.toISOString), + passedAt: pending ? None : Some(Js.Date.make()->Js.Date.toISOString), evaluatorId: None, } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Learn.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Learn.res index fd08cb593b..64c2eb1f89 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Learn.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Learn.res @@ -3,6 +3,6 @@ open CoursesCurriculum__Types @react.component let make = (~targetDetails) => { let contentBlocks = - targetDetails |> TargetDetails.contentBlocks |> Array.of_list |> ContentBlock.sort + targetDetails->TargetDetails.contentBlocks->Array.of_list->ContentBlock.sort
} diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Level.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Level.res index 385e0be942..daed165c5e 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Level.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Level.res @@ -8,10 +8,10 @@ type t = { let decode = json => { open Json.Decode { - id: json |> field("id", string), - name: json |> field("name", string), - number: json |> field("number", int), - unlockOn: json |> field("unlockOn", nullable(string)) |> Js.Null.toOption, + id: json->field("id", string), + name: json->field("name", string), + number: json->field("number", int), + unlockOn: json->field("unlockOn", nullable(string))->Js.Null.toOption, } } @@ -22,16 +22,16 @@ let unlockOn = t => t.unlockOn let isUnlocked = t => switch t.unlockOn { - | Some(date) => date |> DateFns.parseString |> DateFns.isPast + | Some(date) => date->DateFns.parseString->DateFns.isPast | None => true } -let isLocked = t => !(t |> isUnlocked) +let isLocked = t => !(t->isUnlocked) -let sort = levels => levels |> List.sort((x, y) => x.number - y.number) +let sort = levels => levels->List.sort((x, y) => x.number - y.number) let first = levels => - switch levels |> sort { + switch levels->sort { | list{} => Rollbar.error("Failed to find the first level from a course's levels.") raise(Not_found) @@ -43,13 +43,13 @@ let unlockDateString = t => | None => Rollbar.error("unlockDateString was called for a CoursesCurriculum__Level without unlockOn") "" - | Some(unlockOn) => unlockOn |> DateFns.parseString |> DateFns.format("MMM D") + | Some(unlockOn) => unlockOn->DateFns.parseString->DateFns.format("MMM D") } let findByLevelNumber = (levels, levelNumber) => - levels |> List.find_opt(l => l.number == levelNumber) + levels->List.find_opt(l => l.number == levelNumber) -let next = (levels, t) => t.number + 1 |> findByLevelNumber(levels) +let next = (levels, t) => t.number + 1->findByLevelNumber(levels) let previous = (levels, t) => { let previousLevelNumber = t.number - 1 @@ -57,6 +57,6 @@ let previous = (levels, t) => { if previousLevelNumber == 0 { None } else { - previousLevelNumber |> findByLevelNumber(levels) + previousLevelNumber->findByLevelNumber(levels) } } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__LevelSelector.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__LevelSelector.res index fdf4fb1504..1b0d6950d0 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__LevelSelector.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__LevelSelector.res @@ -10,19 +10,19 @@ let levelZeroSelectorClasses = isSelected => { } let levelName = level => - "L" ++ ((level |> Level.number |> string_of_int) ++ (": " ++ (level |> Level.name))) + "L" ++ ((level->Level.number->string_of_int) ++ (": " ++ (level->Level.name))) let selectableLevels = (orderedLevels, teamLevel, setSelectedLevelId) => { - let teamLevelNumber = teamLevel |> Level.number + let teamLevelNumber = teamLevel->Level.number orderedLevels - |> List.map(level => { - let levelNumber = level |> Level.number + ->List.map(level => { + let levelNumber = level->Level.number let icon = if levelNumber < teamLevelNumber { "fas fa-check text-green-500" } else if levelNumber == teamLevelNumber { "fas fa-map-marker-alt text-blue-400" - } else if level |> Level.isUnlocked { + } else if level->Level.isUnlocked { "inline-block" } else { "fas fa-lock text-gray-600" @@ -30,20 +30,20 @@ let selectableLevels = (orderedLevels, teamLevel, setSelectedLevelId) => { }) - |> Array.of_list + ->Array.of_list } let untabbedLevelSelector = (selectedLevel, orderedLevels, teamLevel, setSelectedLevelId) => { let selected = @@ -68,7 +68,7 @@ let tabbedLevelSelector = ( @@ -93,9 +93,9 @@ let tabbedLevelSelector = ( className={"border-l rounded-r-lg bg-white border-gray-400 font-semibold truncate hover:bg-gray-100 hover:text-primary-500 " ++ levelZeroSelectorClasses(showLevelZero)} onClick={_e => setShowLevelZero(true)}> - {levelZero |> Level.name |> str} + {levelZero->Level.name->str} , - ] |> React.array + ]->React.array } @react.component @@ -108,7 +108,7 @@ let make = ( ~setShowLevelZero, ~levelZero, ) => { - let orderedLevels = levels |> List.filter(l => l |> Level.number != 0) |> Level.sort + let orderedLevels = levels->List.filter(l => l->Level.number != 0)->Level.sort
{ let submitButtonText = (title, iconClasses) => - {title |> str} + {title->str} saving ? submitButtonText("Saving", "fas fa-spinner fa-spin") @@ -21,20 +21,20 @@ let handleSubmitButton = saving => { let refreshPage = () => { open Webapi.Dom - location |> Location.reload + location->Location.reload } let createLevelUpQuery = (course, setSaving, event) => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault setSaving(_ => true) - LevelUpQuery.make(~courseId=course |> Course.id, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => { + LevelUpQuery.make(~courseId=course->Course.id, ()) + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => { response["levelUp"]["success"] ? refreshPage() : setSaving(_ => false) Js.Promise.resolve() }) - |> ignore + ->ignore } @react.component diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__NoticeManager.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__NoticeManager.res index 8646fe3c04..3011f1ee74 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__NoticeManager.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__NoticeManager.res @@ -10,9 +10,9 @@ let showNotice = ( (), ) =>
- Notice.icon} /> -
{title |> str}
-
{description |> str}
+ Notice.icon} /> +
{title->str}
+
{description->str}
let courseCompletedMessage = () => { @@ -32,9 +32,9 @@ let showPreviewMessage = () => className="flex max-w-lg md:mx-auto mx-3 mt-4 rounded-lg px-3 py-2 shadow-lg items-center border border-primary-300 bg-gray-200 ">
-

{"Preview Mode" |> str}

+

{"Preview Mode"->str}

- {"You are accessing the preview mode for this course" |> str} + {"You are accessing the preview mode for this course"->str}

@@ -47,8 +47,8 @@ let accessEndedMessage = () => { let levelUpBlockedMessage = levelNumber => { let title = "Level Up Blocked" - let currentLevel = levelNumber |> string_of_int - let lastLevel = levelNumber - 1 |> string_of_int + let currentLevel = levelNumber->string_of_int + let lastLevel = levelNumber - 1->string_of_int let description = "You're at Level " ++ (currentLevel ++ diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Overlay.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Overlay.res index 4832f81c6f..5ca46e85df 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Overlay.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Overlay.res @@ -38,27 +38,27 @@ let reducer = (state, action) => | Target.Student => state | Team => { ...state, - targetDetails: state.targetDetails |> OptionUtils.map(TargetDetails.clearPendingUserIds), + targetDetails: state.targetDetails->OptionUtils.map(TargetDetails.clearPendingUserIds), } } } let closeOverlay = course => - ReasonReactRouter.push("/courses/" ++ ((course |> Course.id) ++ "/curriculum")) + ReasonReactRouter.push("/courses/" ++ ((course->Course.id) ++ "/curriculum")) let loadTargetDetails = (target, send, ()) => { { open Js.Promise - Fetch.fetch("/targets/" ++ ((target |> Target.id) ++ "/details_v2")) - |> then_(Fetch.Response.json) - |> then_(json => send(SetTargetDetails(json |> TargetDetails.decode)) |> resolve) - } |> ignore + Fetch.fetch("/targets/" ++ ((target->Target.id) ++ "/details_v2")) + ->then_(Fetch.Response.json) + ->then_(json => send(SetTargetDetails(json->TargetDetails.decode))->resolve) + }->ignore None } let completionTypeToString = (completionType, targetStatus) => - switch (targetStatus |> TargetStatus.status, (completionType: TargetDetails.completionType)) { + switch (targetStatus->TargetStatus.status, (completionType: TargetDetails.completionType)) { | (Pending, Evaluated) => "Complete" | (Pending, TakeQuiz) => "Take Quiz" | (Pending, LinkToComplete) => "Visit Link to Complete" @@ -79,7 +79,7 @@ let tabToString = (targetStatus, tab) => } let selectableTabs = targetDetails => - targetDetails |> TargetDetails.communities |> ListUtils.isNotEmpty + targetDetails->TargetDetails.communities->ListUtils.isNotEmpty ? list{Learn, Discuss} : list{Learn} @@ -91,14 +91,14 @@ let tabClasses = (selection, tab) => ) let scrollCompleteButtonIntoViewEventually = () => Js.Global.setTimeout(() => { - let element = Webapi.Dom.document |> Webapi.Dom.Document.getElementById("auto-verify-target") + let element = Webapi.Dom.document->Webapi.Dom.Document.getElementById("auto-verify-target") switch element { | Some(e) => Webapi.Dom.Element.scrollIntoView(e) e->Webapi.Dom.Element.setClassName("mt-4 complete-button-selected") | None => Rollbar.error("Could not find the 'Complete' button to scroll to.") } - }, 50) |> ignore + }, 50)->ignore let handleTablink = (send, _event) => { send(Select(Learn)) @@ -107,30 +107,30 @@ let handleTablink = (send, _event) => { let tabButton = (tab, state, send, targetStatus) => tabToString(targetStatus))} + key={"select-" ++ (tab->tabToString(targetStatus))} className={tabClasses(tab, state.tab)} onClick={_e => send(Select(tab))}> - {tab |> tabToString(targetStatus) |> str} + {tab->tabToString(targetStatus)->str} let tabLink = (tab, state, send, targetStatus) => - {tab |> tabToString(targetStatus) |> str} + {tab->tabToString(targetStatus)->str} let tabOptions = (state, send, targetDetails, targetStatus) => { - let completionType = targetDetails |> TargetDetails.computeCompletionType + let completionType = targetDetails->TargetDetails.computeCompletionType
{selectableTabs(targetDetails) - |> List.map(selection => tabButton(selection, state, send, targetStatus)) - |> Array.of_list - |> React.array} - {switch (targetStatus |> TargetStatus.status, completionType) { + ->List.map(selection => tabButton(selection, state, send, targetStatus)) + ->Array.of_list + ->React.array} + {switch (targetStatus->TargetStatus.status, completionType) { | (Pending | Submitted | Passed | Failed, Evaluated | TakeQuiz) => tabButton(Complete(completionType), state, send, targetStatus) | (Locked(CourseLocked | AccessLocked), Evaluated | TakeQuiz) => - targetDetails |> TargetDetails.submissions |> ListUtils.isNotEmpty + targetDetails->TargetDetails.submissions->ListUtils.isNotEmpty ? tabButton(Complete(completionType), state, send, targetStatus) : React.null | (Pending | Submitted | Passed | Failed, LinkToComplete | MarkAsComplete) => @@ -143,16 +143,16 @@ let tabOptions = (state, send, targetDetails, targetStatus) => { let addSubmission = (target, state, send, addSubmissionCB, submission) => { switch state.targetDetails { | Some(targetDetails) => - let newTargetDetails = targetDetails |> TargetDetails.addSubmission(submission) + let newTargetDetails = targetDetails->TargetDetails.addSubmission(submission) send(SetTargetDetails(newTargetDetails)) | None => () } - switch submission |> Submission.status { + switch submission->Submission.status { | MarkedAsComplete => - addSubmissionCB(LatestSubmission.make(~pending=false, ~targetId=target |> Target.id)) - | Pending => addSubmissionCB(LatestSubmission.make(~pending=true, ~targetId=target |> Target.id)) + addSubmissionCB(LatestSubmission.make(~pending=false, ~targetId=target->Target.id)) + | Pending => addSubmissionCB(LatestSubmission.make(~pending=true, ~targetId=target->Target.id)) | Passed => raise( UnexpectedSubmissionStatus( @@ -171,16 +171,16 @@ let addSubmission = (target, state, send, addSubmissionCB, submission) => { let addVerifiedSubmission = (target, state, send, addSubmissionCB, submission) => { switch state.targetDetails { | Some(targetDetails) => - let newTargetDetails = targetDetails |> TargetDetails.addSubmission(submission) + let newTargetDetails = targetDetails->TargetDetails.addSubmission(submission) send(SetTargetDetails(newTargetDetails)) | None => () } - addSubmissionCB(LatestSubmission.make(~pending=false, ~targetId=target |> Target.id)) + addSubmissionCB(LatestSubmission.make(~pending=false, ~targetId=target->Target.id)) } let targetStatusClass = (prefix, targetStatus) => - prefix ++ (targetStatus |> TargetStatus.statusToString |> Js.String.toLowerCase) + prefix ++ (targetStatus->TargetStatus.statusToString->Js.String.toLowerCase) let targetStatusClasses = targetStatus => "curriculum__target-status bg-white text-xs mt-2 md:mt-0 py-1 px-2 md:px-4 " ++ @@ -193,7 +193,7 @@ let overlayHeaderTitleCardClasses = targetStatus => let renderLocked = text =>
- {text |> str} + {text->str}
let overlayStatus = (course, target, targetStatus, preview) =>
@@ -203,14 +203,14 @@ let overlayStatus = (course, target, targetStatus, preview) => targetStatusClass("course-overlay__close--", targetStatus)} onClick={_e => closeOverlay(course)}> - {"Close" |> str} + {"Close"->str}

- {target |> Target.title |> str} + {target->Target.title->str}

- {targetStatus |> TargetStatus.statusToString |> str} + {targetStatus->TargetStatus.statusToString->str}
@@ -219,42 +219,42 @@ let overlayStatus = (course, target, targetStatus, preview) => : React.null}
-let renderLockReason = reason => renderLocked(reason |> TargetStatus.lockReasonToString) +let renderLockReason = reason => renderLocked(reason->TargetStatus.lockReasonToString) let prerequisitesIncomplete = (reason, target, targets, statusOfTargets) => { - let prerequisiteTargetIds = target |> Target.prerequisiteTargetIds + let prerequisiteTargetIds = target->Target.prerequisiteTargetIds let prerequisiteTargets = - targets |> List.filter(target => (target |> Target.id)->List.mem(prerequisiteTargetIds)) + targets->List.filter(target => (target->Target.id)->List.mem(prerequisiteTargetIds))
{renderLockReason(reason)}
{prerequisiteTargets - |> List.map(target => { + ->List.map(target => { let targetStatus = - statusOfTargets |> List.find(ts => ts |> TargetStatus.targetId == (target |> Target.id)) + statusOfTargets->List.find(ts => ts->TargetStatus.targetId == (target->Target.id)) Target.id)} - ariaLabel={"Select Target " ++ (target |> Target.id)} - key={target |> Target.id} + href={"/targets/" ++ (target->Target.id)} + ariaLabel={"Select Target " ++ (target->Target.id)} + key={target->Target.id} className="bg-white border-t px-6 py-4 relative z-10 flex items-center justify-between hover:bg-gray-200 hover:text-primary-500 cursor-pointer"> - {target |> Target.title |> str} + {target->Target.title->str} - {targetStatus |> TargetStatus.statusToString |> str} + {targetStatus->TargetStatus.statusToString->str} }) - |> Array.of_list - |> React.array} + ->Array.of_list + ->React.array}
} let handleLocked = (target, targets, targetStatus, statusOfTargets) => - switch targetStatus |> TargetStatus.status { + switch targetStatus->TargetStatus.status { | Locked(reason) => switch reason { | PrerequisitesIncomplete => prerequisitesIncomplete(reason, target, targets, statusOfTargets) @@ -279,7 +279,7 @@ let learnSection = (targetDetails, tab) => let discussSection = (target, targetDetails, tab) =>
Target.id} communities={targetDetails |> TargetDetails.communities} + targetId={target->Target.id} communities={targetDetails->TargetDetails.communities} />
@@ -303,12 +303,12 @@ let completeSection = ( users, preview, ) => { - let completionType = targetDetails |> TargetDetails.computeCompletionType + let completionType = targetDetails->TargetDetails.computeCompletionType let addVerifiedSubmissionCB = addVerifiedSubmission(target, state, send, addSubmissionCB)
- {switch (targetStatus |> TargetStatus.status, completionType) { + {switch (targetStatus->TargetStatus.status, completionType) { | (Pending, Evaluated) => [ TargetDetails.checklist} + checklist={targetDetails->TargetDetails.checklist} addSubmissionCB={addSubmission(target, state, send, addSubmissionCB)} preview />, - ] |> React.array + ]->React.array | (Pending, TakeQuiz) => [ , - ] |> React.array + ]->React.array | (Submitted | Passed | Failed | Locked(CourseLocked | AccessLocked), Evaluated | TakeQuiz) => TargetDetails.checklist} + checklist={targetDetails->TargetDetails.checklist} /> | (Pending | Submitted | Passed | Failed, LinkToComplete | MarkAsComplete) =>
- {"You have team members who are yet to complete this target:" |> str} + {"You have team members who are yet to complete this target:"->str}
{pendingUserIds - |> List.map(studentId => { + ->List.map(studentId => { let user = - users |> ListUtils.unsafeFind( - u => u |> User.id == studentId, + users->ListUtils.unsafeFind( + u => u->User.id == studentId, "Unable to find user with id " ++ (studentId ++ "in CoursesCurriculum__Overlay"), )
User.name) ++ " has not completed this target."} + title={(user->User.name) ++ " has not completed this target."} className="w-10 h-10 rounded-full border border-yellow-400 flex items-center justify-center overflow-hidden mx-1 shadow-md flex-shrink-0 mt-2"> - User.avatarUrl} /> + User.avatarUrl} />
}) - |> Array.of_list - |> React.array} + ->Array.of_list + ->React.array}
let handlePendingStudents = (targetStatus, targetDetails, users) => - switch (targetDetails, targetStatus |> TargetStatus.status) { + switch (targetDetails, targetStatus->TargetStatus.status) { | (Some(targetDetails), Submitted | Passed) => - let pendingUserIds = targetDetails |> TargetDetails.pendingUserIds - pendingUserIds |> ListUtils.isNotEmpty + let pendingUserIds = targetDetails->TargetDetails.pendingUserIds + pendingUserIds->ListUtils.isNotEmpty ? renderPendingStudents(pendingUserIds, users) : React.null | (Some(_) | None, Locked(_) | Pending | Submitted | Passed | Failed) => React.null @@ -396,7 +396,7 @@ let performQuickNavigation = (send, _event) => { { open // Scroll to the top of the overlay before pushing the new URL. Webapi.Dom - switch document |> Document.getElementById("target-overlay") { + switch document->Document.getElementById("target-overlay") { | Some(element) => Webapi.Dom.Element.setScrollTop(element, 0.0) | None => () } @@ -420,7 +420,7 @@ let navigationLink = (direction, url, send) => { onClick={performQuickNavigation(send)} className="block p-2 md:p-4 text-center border rounded-lg bg-gray-100 hover:bg-gray-200"> {arrow(leftIcon)} - {text |> str} + {text->str} {arrow(rightIcon)} } @@ -428,13 +428,13 @@ let navigationLink = (direction, url, send) => { let scrollOverlayToTop = _event => { let element = { open Webapi.Dom - document |> Document.getElementById("target-overlay") + document->Document.getElementById("target-overlay") } element->Belt.Option.mapWithDefault((), element => element->Webapi.Dom.Element.setScrollTop(0.0)) } let quickNavigationLinks = (targetDetails, send) => { - let (previous, next) = targetDetails |> TargetDetails.navigation + let (previous, next) = targetDetails->TargetDetails.navigation

@@ -448,7 +448,7 @@ let quickNavigationLinks = (targetDetails, send) => {
@@ -462,7 +462,7 @@ let quickNavigationLinks = (targetDetails, send) => { } let updatePendingUserIdsWhenAddingSubmission = (send, target, addSubmissionCB, submission) => { - send(AddSubmission(target |> Target.role)) + send(AddSubmission(target->Target.role)) addSubmissionCB(submission) } @@ -481,7 +481,7 @@ let make = ( ) => { let (state, send) = React.useReducer(reducer, initialState) - React.useEffect1(loadTargetDetails(target, send), [target |> Target.id]) + React.useEffect1(loadTargetDetails(target, send), [target->Target.id]) React.useEffect(() => { ScrollLock.activate() diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Quiz.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Quiz.res index a494678913..b1b012b2fe 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Quiz.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Quiz.res @@ -19,16 +19,16 @@ module CreateQuizSubmissionQuery = %graphql(` let createQuizSubmission = (target, selectedAnswersIds, setSaving, addSubmissionCB) => { setSaving(_ => true) CreateQuizSubmissionQuery.make( - ~targetId=target |> Target.id, - ~answerIds=selectedAnswersIds |> Array.of_list, + ~targetId=target->Target.id, + ~answerIds=selectedAnswersIds->Array.of_list, (), ) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => { + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => { switch response["createQuizSubmission"]["submission"] { | Some(submission) => let checklist = - submission["checklist"] |> Json.Decode.array(SubmissionChecklistItem.decode([])) + submission["checklist"]->Json.Decode.array(SubmissionChecklistItem.decode([])) addSubmissionCB( Submission.make( ~id=submission["id"], @@ -41,7 +41,7 @@ let createQuizSubmission = (target, selectedAnswersIds, setSaving, addSubmission } Js.Promise.resolve() }) - |> ignore + ->ignore } let answerOptionClasses = (answerOption, selectedAnswer) => { let defaultClasses = "quiz-root__answer bg-white flex items-center shadow border border-transparent rounded p-3 mt-3 cursor-pointer " @@ -63,48 +63,48 @@ let iconClasses = (answerOption, selectedAnswer) => { } let handleSubmit = (answer, target, selectedAnswersIds, setSaving, addSubmissionCB, event) => { - event |> ReactEvent.Mouse.preventDefault - let answerIds = selectedAnswersIds |> List.append(list{answer |> QuizQuestion.answerId}) + event->ReactEvent.Mouse.preventDefault + let answerIds = selectedAnswersIds->List.append(list{answer->QuizQuestion.answerId}) createQuizSubmission(target, answerIds, setSaving, addSubmissionCB) } @react.component let make = (~target, ~targetDetails, ~addSubmissionCB, ~preview) => { - let quizQuestions = targetDetails |> TargetDetails.quizQuestions + let quizQuestions = targetDetails->TargetDetails.quizQuestions let (saving, setSaving) = React.useState(() => false) - let (selectedQuestion, setSelectedQuestion) = React.useState(() => quizQuestions |> List.hd) + let (selectedQuestion, setSelectedQuestion) = React.useState(() => quizQuestions->List.hd) let (selectedAnswer, setSelectedAnswer) = React.useState(() => None) let (selectedAnswersIds, setSelectedAnswersIds) = React.useState(() => list{}) let currentQuestion = selectedQuestion
- {"Question #" |> str} {string_of_int((currentQuestion |> QuizQuestion.index) + 1) |> str} + {"Question #"->str} {string_of_int((currentQuestion->QuizQuestion.index) + 1)->str} QuizQuestion.question} + markdown={currentQuestion->QuizQuestion.question} className="font-semibold text-lg md:text-xl" profile=Markdown.Permissive />
{currentQuestion - |> QuizQuestion.answerOptions - |> List.map(answerOption => + ->QuizQuestion.answerOptions + ->List.map(answerOption =>
QuizQuestion.answerId} + key={answerOption->QuizQuestion.answerId} onClick={_ => setSelectedAnswer(_ => Some(answerOption))}> QuizQuestion.answerValue} + markdown={answerOption->QuizQuestion.answerValue} className="overflow-auto ml-2 w-full" profile=Markdown.Permissive />
) - |> Array.of_list - |> React.array} + ->Array.of_list + ->React.array}
{switch selectedAnswer { @@ -112,7 +112,7 @@ let make = (~target, ~targetDetails, ~addSubmissionCB, ~preview) => { | Some(answer) =>
- {currentQuestion |> QuizQuestion.isLastQuestion(quizQuestions) + {currentQuestion->QuizQuestion.isLastQuestion(quizQuestions) ? : { - let nextQuestion = currentQuestion |> QuizQuestion.nextQuestion(quizQuestions) + let nextQuestion = currentQuestion->QuizQuestion.nextQuestion(quizQuestions)
let longTextWarning = value => { - let currentLength = value |> String.length + let currentLength = value->String.length let showWarning = notBlank(value) && currentLength > 4500 let colors = currentLength < 4900 ? "text-orange-700 bg-orange-100" : "text-red-600 bg-red-100" @@ -83,12 +83,12 @@ let longTextWarning = value => { className={"hidden md:inline px-2 py-px rounded text-xs font-semibold inline-flex items-center " ++ colors}> - {"Please keep your answer to less than 5000 characters in length." |> str} + {"Please keep your answer to less than 5000 characters in length."->str}
- {currentLength |> string_of_int |> str} {" / 5000" |> str} + {currentLength->string_of_int->str} {" / 5000"->str}
: React.null @@ -117,38 +117,38 @@ let showMultiChoice = (choices, choice, id, updateResultCB) =>
{choices - |> Array.mapi((index, label) => { - let checked = choice |> OptionUtils.mapWithDefault(i => i == index, false) + ->Array.mapi((index, label) => { + let checked = choice->OptionUtils.mapWithDefault(i => i == index, false) string_of_int} - id={id ++ (index |> string_of_int)} + key={index->string_of_int} + id={id ++ (index->string_of_int)} label onChange={checkboxOnChange(choices, index, updateResultCB)} checked /> }) - |> React.array} + ->React.array}
let attachFile = (updateResultCB, attachingCB, files, id, filename) => { attachingCB(false) - updateResultCB(ChecklistItem.Files(files |> Array.append([ChecklistItem.makeFile(id, filename)]))) + updateResultCB(ChecklistItem.Files(files->Array.append([ChecklistItem.makeFile(id, filename)]))) } let removeFile = (updateResultCB, files, id) => updateResultCB( - ChecklistItem.Files(files |> Js.Array.filter(a => a |> ChecklistItem.fileId != id)), + ChecklistItem.Files(files->Js.Array.filter(a => a->ChecklistItem.fileId != id)), ) let showFiles = (files, preview, id, attachingCB, updateResultCB) =>
{files - |> Array.map(file => + ->Array.map(file =>
ChecklistItem.fileId)} - ariaLabel={"file-" ++ (file |> ChecklistItem.filename)} + key={"file-" ++ (file->ChecklistItem.fileId)} + ariaLabel={"file-" ++ (file->ChecklistItem.filename)} target="_blank" className="w-1/3 pr-2 pb-2">
- {file |> ChecklistItem.filename |> str} + {file->ChecklistItem.filename->str}
) - |> React.array} + ->React.array}
- {files |> Array.length < 3 + {files->Array.length < 3 ? @@ -186,7 +186,7 @@ let make = (~index, ~checklistItem, ~updateResultCB, ~attachingCB, ~preview) =>
{placeholder(id, checklistItem)}
- {switch checklistItem |> ChecklistItem.result { + {switch checklistItem->ChecklistItem.result { | Files(files) => showFiles(files, preview, id, attachingCB, updateResultCB) | Link(link) => showLink(link, id, updateResultCB) | ShortText(shortText) => showShortText(shortText, id, updateResultCB) diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__SubmissionsAndFeedback.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__SubmissionsAndFeedback.res index edc02ca29c..297805316f 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__SubmissionsAndFeedback.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__SubmissionsAndFeedback.res @@ -6,18 +6,18 @@ open CoursesCurriculum__Types let gradeBar = (evaluationCriteria, grade) => { let criterion = - evaluationCriteria |> ListUtils.findOpt(c => - c |> EvaluationCriterion.id == (grade |> Grade.evaluationCriterionId) + evaluationCriteria->ListUtils.findOpt(c => + c->EvaluationCriterion.id == (grade->Grade.evaluationCriterionId) ) switch criterion { | Some(criterion) => - let criterionId = criterion |> EvaluationCriterion.id - let criterionName = criterion |> EvaluationCriterion.name - let gradeNumber = grade |> Grade.grade + let criterionId = criterion->EvaluationCriterion.id + let criterionName = criterion->EvaluationCriterion.name + let gradeNumber = grade->Grade.grade let grading = Grading.make(~criterionId, ~criterionName, ~grade=gradeNumber) -
string_of_int} className="mb-4"> +
string_of_int} className="mb-4">
| None => React.null @@ -41,7 +41,7 @@ let statusBar = (~color, ~text) => { className={"font-semibold p-2 py-4 flex border-t w-full items-center justify-center " ++ (textColor ++ bgColor)}> - icon {text |> str} + icon {text->str}
} @@ -58,13 +58,13 @@ let submissionStatusIcon = (~passed) => { : }
-
{text |> str}
+
{text->str}
} let undoSubmissionCB = () => { open Webapi.Dom - location |> Location.reload + location->Location.reload } let gradingSection = (~grades, ~evaluationCriteria, ~gradeBar, ~passed) => @@ -77,20 +77,20 @@ let gradingSection = (~grades, ~evaluationCriteria, ~gradeBar, ~passed) => {submissionStatusIcon(~passed)}
-
{"Grading" |> str}
+
{"Grading"->str}
{grades - |> Grade.sort(evaluationCriteria) - |> List.map(grade => gradeBar(grade)) - |> Array.of_list - |> React.array} + ->Grade.sort(evaluationCriteria) + ->List.map(grade => gradeBar(grade)) + ->Array.of_list + ->React.array}
let handleAddAnotherSubmission = (setShowSubmissionForm, event) => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault setShowSubmissionForm(showSubmissionForm => !showSubmissionForm) } @@ -98,33 +98,33 @@ let submissions = (target, targetStatus, targetDetails, evaluationCriteria, coac let curriedGradeBar = gradeBar(evaluationCriteria) targetDetails - |> TargetDetails.submissions - |> List.sort((s1, s2) => { - let s1CreatedAt = s1 |> Submission.createdAtDate - let s2CreatedAt = s2 |> Submission.createdAtDate + ->TargetDetails.submissions + ->List.sort((s1, s2) => { + let s1CreatedAt = s1->Submission.createdAtDate + let s2CreatedAt = s2->Submission.createdAtDate - s1CreatedAt |> DateFns.differenceInSeconds(s2CreatedAt) |> int_of_float + s1CreatedAt->DateFns.differenceInSeconds(s2CreatedAt)->int_of_float }) - |> List.map(submission => { - let grades = targetDetails |> TargetDetails.grades(submission |> Submission.id) + ->List.map(submission => { + let grades = targetDetails->TargetDetails.grades(submission->Submission.id)
Submission.id} + key={submission->Submission.id} className="mt-4 pb-4 relative curriculum__submission-feedback-container" - ariaLabel={"Details about your submission on " ++ (submission |> Submission.createdAtPretty)}> + ariaLabel={"Details about your submission on " ++ (submission->Submission.createdAtPretty)}>
- {"Submitted on " ++ (submission |> Submission.createdAtPretty) |> str} + {"Submitted on " ++ (submission->Submission.createdAtPretty)->str}
Submission.checklist} + checklist={submission->Submission.checklist} updateChecklistCB=None - pending={submission |> Submission.pending} + pending={submission->Submission.pending} />
- {switch submission |> Submission.status { + {switch submission->Submission.status { | MarkedAsComplete => statusBar(~color="green", ~text="Marked as complete") | Pending =>
- {"Review pending" |> str} + {"Review pending"->str}
- {switch targetStatus |> TargetStatus.status { + {switch targetStatus->TargetStatus.status { | Submitted => - Target.id} /> + Target.id} /> | Pending | Passed @@ -153,25 +153,25 @@ let submissions = (target, targetStatus, targetDetails, evaluationCriteria, coac gradingSection(~grades, ~evaluationCriteria, ~passed=false, ~gradeBar=curriedGradeBar) }} {targetDetails - |> TargetDetails.feedback - |> List.filter(feedback => - feedback |> Feedback.submissionId == (submission |> Submission.id) + ->TargetDetails.feedback + ->List.filter(feedback => + feedback->Feedback.submissionId == (submission->Submission.id) ) - |> List.map(feedback => { + ->List.map(feedback => { let coach = - coaches |> ListUtils.findOpt(c => c |> Coach.id == (feedback |> Feedback.coachId)) + coaches->ListUtils.findOpt(c => c->Coach.id == (feedback->Feedback.coachId)) let user = switch coach { | Some(coach) => - users |> ListUtils.findOpt(up => up |> User.id == (coach |> Coach.userId)) + users->ListUtils.findOpt(up => up->User.id == (coach->Coach.userId)) | None => None } let (coachName, coachTitle, coachAvatar) = switch user { | Some(user) => - let name = user |> User.name - let avatar = user |> User.avatarUrl - let title = user |> User.title + let name = user->User.name + let avatar = user->User.avatarUrl + let title = user->User.title (name, title, ) | None => ( "Unknown Coach", @@ -183,24 +183,24 @@ let submissions = (target, targetStatus, targetDetails, evaluationCriteria, coac ) } -
Feedback.id}> +
Feedback.id}>
coachAvatar
-

{"Feedback from:" |> str}

+

{"Feedback from:"->str}

- {coachName |> str} + {coachName->str}

{switch coachTitle { | Some(title) => - {"(" ++ (title ++ ")") |> str} + {"(" ++ (title ++ ")")->str} | None => React.null }} @@ -210,17 +210,17 @@ let submissions = (target, targetStatus, targetDetails, evaluationCriteria, coac Feedback.feedback} + markdown={feedback->Feedback.feedback} />
}) - |> Array.of_list - |> React.array} + ->Array.of_list + ->React.array}
}) - |> Array.of_list - |> React.array + ->Array.of_list + ->React.array } let addSubmission = (setShowSubmissionForm, addSubmissionCB, submission) => { @@ -244,22 +244,22 @@ let make = (
-

{"Your Submissions" |> str}

- {targetStatus |> TargetStatus.canSubmit(~resubmittable=target |> Target.resubmittable) +

{"Your Submissions"->str}

+ {targetStatus->TargetStatus.canSubmit(~resubmittable=target->Target.resubmittable) ? showSubmissionForm ? : : React.null}
diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Target.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Target.res index 98ea4e6adb..56c437e3bf 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Target.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Target.res @@ -18,18 +18,18 @@ type t = { let decode = json => { open Json.Decode { - id: json |> field("id", string), - role: switch json |> field("role", string) { + id: json->field("id", string), + role: switch json->field("role", string) { | "student" => Student | "team" => Team | unknownRole => raise(CannotParseUnknownRole(unknownRole)) }, - title: json |> field("title", string), - targetGroupId: json |> field("targetGroupId", string), - sortIndex: json |> field("sortIndex", int), - resubmittable: json |> field("resubmittable", bool), - prerequisiteTargetIds: json |> field("prerequisiteTargetIds", list(string)), - reviewed: json |> field("reviewed", bool), + title: json->field("title", string), + targetGroupId: json->field("targetGroupId", string), + sortIndex: json->field("sortIndex", int), + resubmittable: json->field("resubmittable", bool), + prerequisiteTargetIds: json->field("prerequisiteTargetIds", list(string)), + reviewed: json->field("reviewed", bool), } } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__TargetDetails.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__TargetDetails.res index 030354fc6f..0a7f711619 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__TargetDetails.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__TargetDetails.res @@ -34,34 +34,34 @@ type completionType = let decodeNavigation = json => { open Json.Decode { - previous: json |> optional(field("previous", string)), - next: json |> optional(field("next", string)), + previous: json->optional(field("previous", string)), + next: json->optional(field("next", string)), } } let decode = json => { open Json.Decode { - pendingUserIds: json |> field("pendingUserIds", list(string)), - submissions: json |> field("submissions", list(CoursesCurriculum__Submission.decode)), - feedback: json |> field("feedback", list(CoursesCurriculum__Feedback.decode)), - quizQuestions: json |> field("quizQuestions", list(CoursesCurriculum__QuizQuestion.decode)), - contentBlocks: json |> field("contentBlocks", list(ContentBlock.decode)), - communities: json |> field("communities", list(CoursesCurriculum__Community.decode)), - linkToComplete: json |> field("linkToComplete", nullable(string)) |> Js.Null.toOption, - evaluated: json |> field("evaluated", bool), - grading: json |> field("grading", list(CoursesCurriculum__Grade.decode)), + pendingUserIds: json->field("pendingUserIds", list(string)), + submissions: json->field("submissions", list(CoursesCurriculum__Submission.decode)), + feedback: json->field("feedback", list(CoursesCurriculum__Feedback.decode)), + quizQuestions: json->field("quizQuestions", list(CoursesCurriculum__QuizQuestion.decode)), + contentBlocks: json->field("contentBlocks", list(ContentBlock.decode)), + communities: json->field("communities", list(CoursesCurriculum__Community.decode)), + linkToComplete: json->field("linkToComplete", nullable(string))->Js.Null.toOption, + evaluated: json->field("evaluated", bool), + grading: json->field("grading", list(CoursesCurriculum__Grade.decode)), completionInstructions: json - |> field("completionInstructions", nullable(string)) - |> Js.Null.toOption, - navigation: json |> field("navigation", decodeNavigation), - checklist: json |> field("checklist", array(TargetChecklistItem.decode)), + ->field("completionInstructions", nullable(string)) + ->Js.Null.toOption, + navigation: json->field("navigation", decodeNavigation), + checklist: json->field("checklist", array(TargetChecklistItem.decode)), } } let computeCompletionType = targetDetails => { let evaluated = targetDetails.evaluated - let hasQuiz = targetDetails.quizQuestions |> ListUtils.isNotEmpty + let hasQuiz = targetDetails.quizQuestions->ListUtils.isNotEmpty let hasLinkToComplete = switch targetDetails.linkToComplete { | Some(_) => true | None => false @@ -82,11 +82,11 @@ let linkToComplete = t => t.linkToComplete let completionInstructions = t => t.completionInstructions let grades = (submissionId, t) => - t.grading |> List.filter(grade => grade |> CoursesCurriculum__Grade.submissionId == submissionId) + t.grading->List.filter(grade => grade->CoursesCurriculum__Grade.submissionId == submissionId) let addSubmission = (submission, t) => { ...t, - submissions: list{submission, ...t |> submissions}, + submissions: list{submission, ...t->submissions}, } let clearPendingUserIds = t => {...t, pendingUserIds: list{}} diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__TargetGroup.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__TargetGroup.res index 929aea5957..e28b57bdd4 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__TargetGroup.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__TargetGroup.res @@ -10,16 +10,16 @@ type t = { let decode = json => { open Json.Decode { - id: json |> field("id", string), - levelId: json |> field("levelId", string), - name: json |> field("name", string), - description: json |> field("description", string), - sortIndex: json |> field("sortIndex", int), - milestone: json |> field("milestone", bool), + id: json->field("id", string), + levelId: json->field("levelId", string), + name: json->field("name", string), + description: json->field("description", string), + sortIndex: json->field("sortIndex", int), + milestone: json->field("milestone", bool), } } -let sort = targetGroups => targetGroups |> List.sort((x, y) => x.sortIndex - y.sortIndex) +let sort = targetGroups => targetGroups->List.sort((x, y) => x.sortIndex - y.sortIndex) let id = t => t.id let name = t => t.name diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__TargetStatus.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__TargetStatus.res index 898f6df079..6ea7abc19e 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__TargetStatus.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__TargetStatus.res @@ -50,18 +50,18 @@ type cachedTarget = { let isPast = dateString => switch dateString { - | Some(date) => date |> DateFns.parseString |> DateFns.isBefore(Js.Date.make()) + | Some(date) => date->DateFns.parseString->DateFns.isBefore(Js.Date.make()) | None => false } -let makePending = targets => targets |> List.map(t => {targetId: t |> Target.id, status: Pending}) +let makePending = targets => targets->List.map(t => {targetId: t->Target.id, status: Pending}) let lockTargets = (targets, reason) => - targets |> List.map(t => {targetId: t |> Target.id, status: Locked(reason)}) + targets->List.map(t => {targetId: t->Target.id, status: Locked(reason)}) let allTargetsComplete = (targetCache, targetIds) => - targetIds |> List.for_all(targetId => { - let cachedTarget = targetCache |> List.find(ct => ct.targetId == targetId) + targetIds->List.for_all(targetId => { + let cachedTarget = targetCache->List.find(ct => ct.targetId == targetId) cachedTarget.submissionStatus == SubmissionPassed }) @@ -69,37 +69,37 @@ let compute = (preview, team, course, levels, targetGroups, targets, submissions /* Eliminate the two course ended and student access ended conditions. */ if preview { makePending(targets) - } else if course |> Course.endsAt |> isPast { + } else if course->Course.endsAt->isPast { lockTargets(targets, CourseLocked) - } else if team |> Team.accessEndsAt |> isPast { + } else if team->Team.accessEndsAt->isPast { lockTargets(targets, AccessLocked) } else { /* Cache level number of the student. */ let studentLevelNumber = - levels |> List.find(l => l |> Level.id == (team |> Team.levelId)) |> Level.number + levels->List.find(l => l->Level.id == (team->Team.levelId))->Level.number /* Cache level number, milestone boolean, and submission status for all targets. */ - let targetsCache = targets |> List.map(target => { - let targetId = target |> Target.id + let targetsCache = targets->List.map(target => { + let targetId = target->Target.id let targetGroup = - targetGroups |> List.find(tg => tg |> TargetGroup.id == (target |> Target.targetGroupId)) + targetGroups->List.find(tg => tg->TargetGroup.id == (target->Target.targetGroupId)) - let milestone = targetGroup |> TargetGroup.milestone + let milestone = targetGroup->TargetGroup.milestone let levelNumber = levels - |> List.find(l => l |> Level.id == (targetGroup |> TargetGroup.levelId)) - |> Level.number + ->List.find(l => l->Level.id == (targetGroup->TargetGroup.levelId)) + ->Level.number let submission = - submissions |> ListUtils.findOpt(s => s |> LatestSubmission.targetId == targetId) + submissions->ListUtils.findOpt(s => s->LatestSubmission.targetId == targetId) let submissionStatus = switch submission { | Some(s) => - if s |> LatestSubmission.hasPassed { + if s->LatestSubmission.hasPassed { SubmissionPassed - } else if s |> LatestSubmission.hasBeenEvaluated { + } else if s->LatestSubmission.hasBeenEvaluated { SubmissionFailed } else { SubmissionPendingReview @@ -109,16 +109,16 @@ let compute = (preview, team, course, levels, targetGroups, targets, submissions { targetId: targetId, - targetReviewed: target |> Target.reviewed, + targetReviewed: target->Target.reviewed, levelNumber: levelNumber, milestone: milestone, submissionStatus: submissionStatus, - prerequisiteTargetIds: target |> Target.prerequisiteTargetIds, + prerequisiteTargetIds: target->Target.prerequisiteTargetIds, } }) /* Scan the targets cache again to form final list of target statuses. */ - targetsCache |> List.map(ct => { + targetsCache->List.map(ct => { let status = switch ct.submissionStatus { | SubmissionPendingReview => Submitted | SubmissionPassed => Passed @@ -126,7 +126,7 @@ let compute = (preview, team, course, levels, targetGroups, targets, submissions | SubmissionMissing => if ct.levelNumber > studentLevelNumber && ct.targetReviewed { Locked(LevelLocked) - } else if !(ct.prerequisiteTargetIds |> allTargetsComplete(targetsCache)) { + } else if !(ct.prerequisiteTargetIds->allTargetsComplete(targetsCache)) { Locked(PrerequisitesIncomplete) } else { Pending @@ -171,7 +171,7 @@ let currentLevelStatuses = list{Submitted, Passed} let lastLevelStatuses = list{Passed} let matchesStatuses = (statuses, ts) => { - let matchedTargetStatuses = ts |> List.filter(t => t.status->List.mem(statuses)) + let matchedTargetStatuses = ts->List.filter(t => t.status->List.mem(statuses)) ts == matchedTargetStatuses } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Team.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Team.res index 961537cac6..0d0b117d01 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Team.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__Team.res @@ -8,9 +8,9 @@ type t = { let decode = json => { open Json.Decode { - name: json |> field("name", string), - levelId: json |> field("levelId", string), - accessEndsAt: json |> field("accessEndsAt", nullable(string)) |> Js.Null.toOption, + name: json->field("name", string), + levelId: json->field("levelId", string), + accessEndsAt: json->field("accessEndsAt", nullable(string))->Js.Null.toOption, } } @@ -19,6 +19,6 @@ let accessEndsAt = t => t.accessEndsAt let accessEnded = t => switch t.accessEndsAt { - | Some(date) => date |> DateFns.parseString |> DateFns.isPast + | Some(date) => date->DateFns.parseString->DateFns.isPast | None => false } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__UndoButton.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__UndoButton.res index 174496805a..44f554535d 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__UndoButton.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__UndoButton.res @@ -14,17 +14,17 @@ type status = | Errored let handleClick = (targetId, setStatus, undoSubmissionCB, event) => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault if { open Webapi.Dom - window |> Window.confirm("Are you sure you want to delete this submission?") + window->Window.confirm("Are you sure you want to delete this submission?") } { setStatus(_ => Undoing) DeleteSubmissionQuery.make(~targetId, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => { + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => { if response["undoSubmission"]["success"] { undoSubmissionCB() } else { @@ -36,7 +36,7 @@ let handleClick = (targetId, setStatus, undoSubmissionCB, event) => { } Js.Promise.resolve() }) - |> Js.Promise.catch(_ => { + ->Js.Promise.catch(_ => { Notification.error( "Unexpected Error", "An unexpected error occured, and our team has been notified about this. Please reload the page before trying again.", @@ -44,7 +44,7 @@ let handleClick = (targetId, setStatus, undoSubmissionCB, event) => { setStatus(_ => Errored) Js.Promise.resolve() }) - |> ignore + ->ignore } else { () } @@ -52,15 +52,15 @@ let handleClick = (targetId, setStatus, undoSubmissionCB, event) => { let buttonContents = status => switch status { - | Undoing => {"Undoing..." |> str} + | Undoing => {"Undoing..."->str} | Pending => - {"Undo submission" |> str} - {"Undo" |> str} + {"Undo submission"->str} + {"Undo"->str} | Errored => - {"Error!" |> str} + {"Error!"->str} } let isDisabled = status => @@ -86,7 +86,7 @@ let make = (~undoSubmissionCB, ~targetId) => { let (status, setStatus) = React.useState(() => Pending)
{state.errors - |> List.map(error => + ->List.map(error =>
- {error |> str} + {error->str}
) - |> Array.of_list - |> React.array} + ->Array.of_list + ->React.array}
} diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__User.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__User.res index 12df38f27b..d5dd8405b6 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__User.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesCurriculum__User.res @@ -13,9 +13,9 @@ let title = t => t.title let decode = json => { open Json.Decode { - id: json |> field("id", string), - name: json |> field("name", string), - avatarUrl: json |> field("avatarUrl", string), - title: json |> field("title", nullable(string)) |> Js.Null.toOption, + id: json->field("id", string), + name: json->field("name", string), + avatarUrl: json->field("avatarUrl", string), + title: json->field("title", nullable(string))->Js.Null.toOption, } } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__Checklist.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__Checklist.res index c842587e46..befea45e55 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__Checklist.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__Checklist.res @@ -26,10 +26,10 @@ let handleEmpty = setState => - {"Create a review checklist" |> str} + {"Create a review checklist"->str} - {"Prepare for your review by creating a checklist" |> str} + {"Prepare for your review by creating a checklist"->str} @@ -49,7 +49,7 @@ let make = ( - {"Review Checklist" |> str} + {"Review Checklist"->str}
@@ -62,7 +62,7 @@ let make = ( targetId /> | Show => - reviewChecklist |> ArrayUtils.isEmpty + reviewChecklist->ArrayUtils.isEmpty ? handleEmpty(setState) : { setState(state => {...state, saving: true}) - let trimmedChecklist = reviewChecklist |> Array.map(ReviewChecklistItem.trim) + let trimmedChecklist = reviewChecklist->Array.map(ReviewChecklistItem.trim) UpdateReviewChecklistMutation.make( ~targetId, ~reviewChecklist=ReviewChecklistItem.encodeArray(trimmedChecklist), (), ) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => { + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => { if response["updateReviewChecklist"]["success"] { updateReviewChecklistCB(trimmedChecklist) } @@ -36,13 +36,13 @@ let updateReviewChecklist = (targetId, reviewChecklist, setState, updateReviewCh setState(state => {...state, saving: false}) Js.Promise.resolve() }) - |> ignore + ->ignore } let updateChecklistItem = (checklistItem, itemIndex, setState) => setState(state => { ...state, - reviewChecklist: state.reviewChecklist |> ReviewChecklistItem.replace(checklistItem, itemIndex), + reviewChecklist: state.reviewChecklist->ReviewChecklistItem.replace(checklistItem, itemIndex), }) let updateChecklistItemTitle = (itemIndex, title, checklistItem, setState) => @@ -57,10 +57,10 @@ let updateChecklistResultTitle = ( setState, ) => { let newReviewChecklistItem = - reviewChecklistItem |> ReviewChecklistItem.updateChecklist( + reviewChecklistItem->ReviewChecklistItem.updateChecklist( reviewChecklistItem - |> ReviewChecklistItem.result - |> ReviewChecklistResult.updateTitle(title, resultItem, resultIndex), + ->ReviewChecklistItem.result + ->ReviewChecklistResult.updateTitle(title, resultItem, resultIndex), ) updateChecklistItem(newReviewChecklistItem, itemIndex, setState) } @@ -74,17 +74,17 @@ let updateChecklistResultFeedback = ( setState, ) => { let newReviewChecklistItem = - reviewChecklistItem |> ReviewChecklistItem.updateChecklist( + reviewChecklistItem->ReviewChecklistItem.updateChecklist( reviewChecklistItem - |> ReviewChecklistItem.result - |> ReviewChecklistResult.updateFeedback(feedback, resultItem, resultIndex), + ->ReviewChecklistItem.result + ->ReviewChecklistResult.updateFeedback(feedback, resultItem, resultIndex), ) updateChecklistItem(newReviewChecklistItem, itemIndex, setState) } let addEmptyResultItem = (reviewChecklistItem, itemIndex, setState) => updateChecklistItem( - reviewChecklistItem |> ReviewChecklistItem.appendEmptyChecklistItem, + reviewChecklistItem->ReviewChecklistItem.appendEmptyChecklistItem, itemIndex, setState, ) @@ -92,12 +92,12 @@ let addEmptyResultItem = (reviewChecklistItem, itemIndex, setState) => let addEmptyChecklistItem = setState => setState(state => { ...state, - reviewChecklist: ReviewChecklistItem.empty() |> Array.append(state.reviewChecklist), + reviewChecklist: ReviewChecklistItem.empty()->Array.append(state.reviewChecklist), }) let removeChecklistResult = (itemIndex, resultIndex, reviewChecklistItem, setState) => updateChecklistItem( - reviewChecklistItem |> ReviewChecklistItem.deleteResultItem(resultIndex), + reviewChecklistItem->ReviewChecklistItem.deleteResultItem(resultIndex), itemIndex, setState, ) @@ -105,41 +105,41 @@ let removeChecklistResult = (itemIndex, resultIndex, reviewChecklistItem, setSta let removeChecklistItem = (itemIndex, setState) => setState(state => { ...state, - reviewChecklist: state.reviewChecklist |> Js.Array.filteri((_el, i) => i != itemIndex), + reviewChecklist: state.reviewChecklist->Js.Array.filteri((_el, i) => i != itemIndex), }) let initialStateForReviewChecklist = reviewChecklist => - reviewChecklist |> ArrayUtils.isEmpty ? ReviewChecklistItem.emptyTemplate() : reviewChecklist + reviewChecklist->ArrayUtils.isEmpty ? ReviewChecklistItem.emptyTemplate() : reviewChecklist -let invalidTitle = title => title |> String.trim == "" +let invalidTitle = title => title->String.trim == "" let invalidChecklist = reviewChecklist => reviewChecklist - |> Array.map(reviewChecklistItem => - reviewChecklistItem |> ReviewChecklistItem.title |> invalidTitle || + ->Array.map(reviewChecklistItem => + reviewChecklistItem->ReviewChecklistItem.title->invalidTitle || reviewChecklistItem - |> ReviewChecklistItem.result - |> Js.Array.filter(resultItem => resultItem |> ReviewChecklistResult.title |> invalidTitle) - |> ArrayUtils.isNotEmpty + ->ReviewChecklistItem.result + ->Js.Array.filter(resultItem => resultItem->ReviewChecklistResult.title->invalidTitle) + ->ArrayUtils.isNotEmpty ) - |> Js.Array.filter(valid => valid) - |> ArrayUtils.isNotEmpty + ->Js.Array.filter(valid => valid) + ->ArrayUtils.isNotEmpty @react.component let make = (~reviewChecklist, ~updateReviewChecklistCB, ~closeEditModeCB, ~targetId) => { let (state, setState) = React.useState(() => { - reviewChecklist: reviewChecklist |> initialStateForReviewChecklist, + reviewChecklist: reviewChecklist->initialStateForReviewChecklist, saving: false, })
{state.reviewChecklist - |> Array.mapi((itemIndex, reviewChecklistItem) => + ->Array.mapi((itemIndex, reviewChecklistItem) =>
string_of_int} - ariaLabel={"checklist-item-" ++ (itemIndex |> string_of_int)}> + key={itemIndex->string_of_int} + ariaLabel={"checklist-item-" ++ (itemIndex->string_of_int)}>
ReviewChecklistItem.title} + value={reviewChecklistItem->ReviewChecklistItem.title} onChange={event => updateChecklistItemTitle( itemIndex, @@ -158,7 +158,7 @@ let make = (~reviewChecklist, ~updateReviewChecklistCB, ~closeEditModeCB, ~targe /> ReviewChecklistItem.title |> invalidTitle} + active={reviewChecklistItem->ReviewChecklistItem.title->invalidTitle} />
) - |> React.array} + ->React.array}
@@ -281,10 +281,10 @@ let make = (~reviewChecklist, ~updateReviewChecklistCB, ~closeEditModeCB, ~targe updateReviewChecklistCB, )} className="btn btn-success w-1/2 md:w-auto"> - {"Save Checklist" |> str} + {"Save Checklist"->str}
diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__ChecklistShow.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__ChecklistShow.res index 749a0fba04..9ddde9956a 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__ChecklistShow.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__ChecklistShow.res @@ -11,12 +11,12 @@ let str = React.string let selectChecklist = (itemIndex, resultIndex, setSelecton) => setSelecton(selection => - selection |> List.append(list{{itemIndex: itemIndex, resultIndex: resultIndex}}) + selection->List.append(list{{itemIndex: itemIndex, resultIndex: resultIndex}}) ) let unSelectChecklist = (itemIndex, resultIndex, setSelecton) => setSelecton(selection => - selection |> List.filter(item => + selection->List.filter(item => !(item.itemIndex == itemIndex && item.resultIndex == resultIndex) ) ) @@ -31,42 +31,42 @@ let generateFeedback = (reviewChecklist, selection, feedback, updateFeedbackCB) feedback ++ ("\n\n" ++ (reviewChecklist - |> Array.mapi((i, reviewChecklistItem) => { + ->Array.mapi((i, reviewChecklistItem) => { let resultIndexList = selection - |> List.filter(selectionItem => selectionItem.itemIndex == i) - |> List.map(item => item.resultIndex) + ->List.filter(selectionItem => selectionItem.itemIndex == i) + ->List.map(item => item.resultIndex) reviewChecklistItem - |> ReviewChecklistItem.result - |> Array.mapi((index, resultItem) => - resultIndexList |> List.mem(index) - ? switch resultItem |> ReviewChecklistResult.feedback { + ->ReviewChecklistItem.result + ->Array.mapi((index, resultItem) => + resultIndexList->List.mem(index) + ? switch resultItem->ReviewChecklistResult.feedback { | Some(feedback) => list{feedback} | None => list{} } : list{} ) - |> Array.to_list - |> List.flatten + ->Array.to_list + ->List.flatten }) - |> Array.to_list - |> List.flatten - |> Array.of_list - |> Js.Array.joinWith("\n\n"))) + ->Array.to_list + ->List.flatten + ->Array.of_list + ->Js.Array.joinWith("\n\n"))) updateFeedbackCB(newFeedback) } let checklistItemCheckedClasses = (itemIndex, selection) => "mb-4 px-2 pb-2 md:px-4 border-l-2 border-transparent " ++ ( - selection |> List.filter(s => s.itemIndex == itemIndex) |> ListUtils.isNotEmpty + selection->List.filter(s => s.itemIndex == itemIndex)->ListUtils.isNotEmpty ? "border-green-400" : "" ) let checklistItemChecked = (itemIndex, resultIndex, selection) => selection - |> List.filter(s => s.itemIndex == itemIndex && s.resultIndex == resultIndex) - |> ListUtils.isNotEmpty + ->List.filter(s => s.itemIndex == itemIndex && s.resultIndex == resultIndex) + ->ListUtils.isNotEmpty @react.component let make = (~reviewChecklist, ~feedback, ~updateFeedbackCB, ~showEditorCB) => { @@ -78,50 +78,50 @@ let make = (~reviewChecklist, ~feedback, ~updateFeedbackCB, ~showEditorCB) => {
{reviewChecklist - |> Array.mapi((itemIndex, reviewChecklistItem) => + ->Array.mapi((itemIndex, reviewChecklistItem) =>
string_of_int} - ariaLabel={"checklist-item-" ++ (itemIndex |> string_of_int)}> + key={itemIndex->string_of_int} + ariaLabel={"checklist-item-" ++ (itemIndex->string_of_int)}>

- {reviewChecklistItem |> ReviewChecklistItem.title |> str} + {reviewChecklistItem->ReviewChecklistItem.title->str}

{reviewChecklistItem - |> ReviewChecklistItem.result - |> Array.mapi((resultIndex, checklistItem) => + ->ReviewChecklistItem.result + ->Array.mapi((resultIndex, checklistItem) =>
string_of_int)} - key={(itemIndex |> string_of_int) ++ (resultIndex |> string_of_int)}> + ariaLabel={"result-item-" ++ (resultIndex->string_of_int)} + key={(itemIndex->string_of_int) ++ (resultIndex->string_of_int)}> string_of_int) ++ (resultIndex |> string_of_int))} - label={checklistItem |> ReviewChecklistResult.title} + id={id ++ ((itemIndex->string_of_int) ++ (resultIndex->string_of_int))} + label={checklistItem->ReviewChecklistResult.title} onChange={checkboxOnChange(itemIndex, resultIndex, setSelecton)} checked={checklistItemChecked(itemIndex, resultIndex, selection)} />
ReviewChecklistResult.feedback} + feedback={checklistItem->ReviewChecklistResult.feedback} />
) - |> React.array} + ->React.array}
) - |> React.array} + ->React.array}
diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__ChecklistShowFeedback.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__ChecklistShowFeedback.res index c59b688a14..a0a1bfad77 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__ChecklistShowFeedback.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__ChecklistShowFeedback.res @@ -6,13 +6,13 @@ let feedbackClasses = truncated => truncated ? "relative overflow-hidden h-12" : let optionalStringLength = feedback => switch feedback { - | Some(f) => f |> String.length + | Some(f) => f->String.length | None => 0 } @react.component let make = (~feedback) => { - let truncationRequired = feedback |> optionalStringLength > 150 + let truncationRequired = feedback->optionalStringLength > 150 let (truncated, setTruncated) = React.useState(() => truncationRequired) @@ -25,7 +25,7 @@ let make = (~feedback) => {
: React.null} diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__Feedback.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__Feedback.res index 49cdce1fab..b2ced1070a 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__Feedback.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__Feedback.res @@ -9,7 +9,7 @@ let value = t => t.value let coachName = t => t.coachName let coachAvatarUrl = t => t.coachAvatarUrl let coachTitle = t => t.coachTitle -let createdAtPretty = t => t.createdAt |> DateFns.format("MMMM D, YYYY") +let createdAtPretty = t => t.createdAt->DateFns.format("MMMM D, YYYY") let make = (~coachName, ~coachAvatarUrl, ~coachTitle, ~createdAt, ~value) => { coachName: coachName, diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__FeedbackEditor.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__FeedbackEditor.res index c8d671fb53..8713d5eecb 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__FeedbackEditor.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__FeedbackEditor.res @@ -11,7 +11,7 @@ let make = ( ~targetId, ) => { let (checklistVisible, setChecklistVisible) = React.useState(() => checklistVisible) - let reviewChecklistIsNotEmpty = reviewChecklist |> ArrayUtils.isNotEmpty + let reviewChecklistIsNotEmpty = reviewChecklist->ArrayUtils.isNotEmpty
{switch (checklistVisible, reviewChecklistIsNotEmpty) { @@ -30,7 +30,7 @@ let make = ( className="inline-flex w-10 h-10 border border-white items-center justify-center rounded-full bg-primary-100 text-primary-500"> - {"Show Review Checklist" |> str} + {"Show Review Checklist"->str}
}} @@ -40,7 +40,7 @@ let make = ( - {label |> str} + {label->str}
{ } let sort = (criteria, grades) => - grades |> ArrayUtils.copyAndSort((g1, g2) => { + grades->ArrayUtils.copyAndSort((g1, g2) => { let ec1 = - criteria |> ArrayUtils.unsafeFind( + criteria->ArrayUtils.unsafeFind( ec => EvaluationCriterion.id(ec) == g1.evaluationCriterionId, "Unable to find evaluation criterion with ID: " ++ (g1.evaluationCriterionId ++ " in CoursesReview__Grade"), ) let ec2 = - criteria |> ArrayUtils.unsafeFind( + criteria->ArrayUtils.unsafeFind( ec => EvaluationCriterion.id(ec) == g2.evaluationCriterionId, "Unable to find evaluation criterion with ID: " ++ (g2.evaluationCriterionId ++ " in CoursesReview__Grade"), ) - String.compare(ec1 |> EvaluationCriterion.name, ec2 |> EvaluationCriterion.name) + String.compare(ec1->EvaluationCriterion.name, ec2->EvaluationCriterion.name) }) let evaluationCriterionId = t => t.evaluationCriterionId diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__GradeCard.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__GradeCard.res index 9c5f7a9ce6..e11f4cc45f 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__GradeCard.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__GradeCard.res @@ -36,19 +36,19 @@ let reducer = (state, action) => let passed = (grades, evaluationCriteria) => grades - |> Js.Array.filter(g => { + ->Js.Array.filter(g => { let passGrade = evaluationCriteria - |> ArrayUtils.unsafeFind( - ec => EvaluationCriterion.id(ec) == (g |> Grade.evaluationCriterionId), + ->ArrayUtils.unsafeFind( + ec => EvaluationCriterion.id(ec) == (g->Grade.evaluationCriterionId), "CoursesReview__GradeCard: Unable to find evaluation criterion with id - " ++ - (g |> Grade.evaluationCriterionId), + (g->Grade.evaluationCriterionId), ) - |> EvaluationCriterion.passGrade + ->EvaluationCriterion.passGrade - g |> Grade.value < passGrade + g->Grade.value < passGrade }) - |> ArrayUtils.isEmpty + ->ArrayUtils.isEmpty module CreateGradingMutation = %graphql(` mutation CreateGradingMutation($submissionId: ID!, $feedback: String, $grades: [GradeInput!]!, $note: String, $checklist: JSON!) { @@ -70,28 +70,28 @@ let undoGrading = (submissionId, send) => { send(BeginSaving) UndoGradingMutation.make(~submissionId, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => { - response["undoGrading"]["success"] ? DomUtils.reload() |> ignore : send(FinishSaving) + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => { + response["undoGrading"]["success"] ? DomUtils.reload()->ignore : send(FinishSaving) Js.Promise.resolve() }) - |> ignore + ->ignore } let trimToOption = s => - switch s |> String.trim { + switch s->String.trim { | "" => None | s => Some(s) } let gradeSubmissionQuery = (submissionId, state, send, evaluationCriteria, addGradingCB) => { - let jsGradesArray = state.grades |> Array.map(g => g |> Grade.asJsType) + let jsGradesArray = state.grades->Array.map(g => g->Grade.asJsType) - let checklist = state.checklist |> SubmissionChecklistItem.encodeArray + let checklist = state.checklist->SubmissionChecklistItem.encodeArray send(BeginSaving) - let feedback = state.newFeedback |> trimToOption - let note = state.note |> OptionUtils.flatMap(trimToOption) + let feedback = state.newFeedback->trimToOption + let note = state.note->OptionUtils.flatMap(trimToOption) CreateGradingMutation.make( ~submissionId, @@ -101,8 +101,8 @@ let gradeSubmissionQuery = (submissionId, state, send, evaluationCriteria, addGr ~checklist, (), ) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => { + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => { response["createGrading"]["success"] ? addGradingCB( ~newFeedback=state.newFeedback, @@ -114,22 +114,22 @@ let gradeSubmissionQuery = (submissionId, state, send, evaluationCriteria, addGr send(FinishSaving) Js.Promise.resolve() }) - |> ignore + ->ignore } let updateGrading = (grade, state, send) => { let newGrades = state.grades - |> Js.Array.filter(g => - g |> Grade.evaluationCriterionId != (grade |> Grade.evaluationCriterionId) + ->Js.Array.filter(g => + g->Grade.evaluationCriterionId != (grade->Grade.evaluationCriterionId) ) - |> Array.append([grade]) + ->Array.append([grade]) send(UpdateGrades(newGrades)) } let handleGradePillClick = (evaluationCriterionId, value, state, send, event) => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault switch send { | Some(send) => updateGrading(Grade.make(~evaluationCriterionId, ~value), state, send) | None => () @@ -137,8 +137,8 @@ let handleGradePillClick = (evaluationCriterionId, value, state, send, event) => } let findEvaluationCriterion = (evaluationCriteria, evaluationCriterionId) => - switch evaluationCriteria |> Js.Array.find(ec => - ec |> EvaluationCriterion.id == evaluationCriterionId + switch evaluationCriteria->Js.Array.find(ec => + ec->EvaluationCriterion.id == evaluationCriterionId ) { | Some(ec) => ec | None => @@ -152,11 +152,11 @@ let findEvaluationCriterion = (evaluationCriteria, evaluationCriterionId) => let gradePillHeader = (evaluationCriteriaName, selectedGrade, gradeLabels) =>
-

{evaluationCriteriaName |> str}

+

{evaluationCriteriaName->str}

- {(selectedGrade |> string_of_int) ++ + {(selectedGrade->string_of_int) ++ ("/" ++ - (GradeLabel.maxGrade(gradeLabels |> Array.to_list) |> string_of_int)) |> str} + (GradeLabel.maxGrade(gradeLabels->Array.to_list)->string_of_int))->str}

@@ -185,81 +185,81 @@ let gradePillClasses = (selectedGrade, currentGrade, passgrade, send) => { let showGradePill = (key, evaluationCriterion, gradeValue, passGrade, state, send) =>
EvaluationCriterion.id)} - key={key |> string_of_int} + ariaLabel={"evaluation-criterion-" ++ (evaluationCriterion->EvaluationCriterion.id)} + key={key->string_of_int} className="md:pr-8 mt-4"> {gradePillHeader( - evaluationCriterion |> EvaluationCriterion.name, + evaluationCriterion->EvaluationCriterion.name, gradeValue, - evaluationCriterion |> EvaluationCriterion.gradesAndLabels, + evaluationCriterion->EvaluationCriterion.gradesAndLabels, )}
{evaluationCriterion - |> EvaluationCriterion.gradesAndLabels - |> Array.map(gradeLabel => { - let gradeLabelGrade = gradeLabel |> GradeLabel.grade + ->EvaluationCriterion.gradesAndLabels + ->Array.map(gradeLabel => { + let gradeLabelGrade = gradeLabel->GradeLabel.grade
string_of_int} + key={gradeLabelGrade->string_of_int} onClick={handleGradePillClick( - evaluationCriterion |> EvaluationCriterion.id, + evaluationCriterion->EvaluationCriterion.id, gradeLabelGrade, state, send, )} - title={gradeLabel |> GradeLabel.label} + title={gradeLabel->GradeLabel.label} className={gradePillClasses(gradeValue, gradeLabelGrade, passGrade, send)}> {switch send { - | Some(_) => gradeLabelGrade |> string_of_int |> str + | Some(_) => gradeLabelGrade->string_of_int->str | None => React.null }}
}) - |> React.array} + ->React.array}
let showGrades = (grades, evaluationCriteria, state) =>
{grades - |> Grade.sort(evaluationCriteria) - |> Array.mapi((key, grade) => { + ->Grade.sort(evaluationCriteria) + ->Array.mapi((key, grade) => { let gradeEcId = Grade.evaluationCriterionId(grade) let ec = - evaluationCriteria |> ArrayUtils.unsafeFind( - ec => ec |> EvaluationCriterion.id == gradeEcId, + evaluationCriteria->ArrayUtils.unsafeFind( + ec => ec->EvaluationCriterion.id == gradeEcId, "Unable to find evaluation Criterion with id: " ++ (gradeEcId ++ "in CoursesRevew__GradeCard"), ) - showGradePill(key, ec, grade |> Grade.value, ec |> EvaluationCriterion.passGrade, state, None) + showGradePill(key, ec, grade->Grade.value, ec->EvaluationCriterion.passGrade, state, None) }) - |> React.array} + ->React.array}
let renderGradePills = (evaluationCriteria, targetEvaluationCriteriaIds, state, send) => targetEvaluationCriteriaIds - |> Array.mapi((key, evaluationCriterionId) => { + ->Array.mapi((key, evaluationCriterionId) => { let ec = - evaluationCriteria |> ArrayUtils.unsafeFind( - e => e |> EvaluationCriterion.id == evaluationCriterionId, + evaluationCriteria->ArrayUtils.unsafeFind( + e => e->EvaluationCriterion.id == evaluationCriterionId, "CoursesReview__GradeCard: Unable to find evaluation criterion with id - " ++ evaluationCriterionId, ) let grade = - state.grades |> Js.Array.find(g => - g |> Grade.evaluationCriterionId == (ec |> EvaluationCriterion.id) + state.grades->Js.Array.find(g => + g->Grade.evaluationCriterionId == (ec->EvaluationCriterion.id) ) let gradeValue = switch grade { - | Some(g) => g |> Grade.value + | Some(g) => g->Grade.value | None => 0 } - let passGrade = ec |> EvaluationCriterion.passGrade + let passGrade = ec->EvaluationCriterion.passGrade showGradePill(key, ec, gradeValue, passGrade, state, Some(send)) }) - |> React.array + ->React.array let gradeStatusClasses = (color, status) => "w-12 h-10 p-1 mr-2 md:mr-0 md:w-24 md:h-20 rounded md:rounded-lg border flex justify-center items-center bg-" ++ (color ++ @@ -285,22 +285,22 @@ let submissionStatusIcon = (status, overlaySubmission, send) => { className="flex w-full md:w-3/6 flex-col items-center justify-center md:border-l mt-4 md:mt-0">
- {switch (overlaySubmission |> OverlaySubmission.evaluatedAt, status) { + {switch (overlaySubmission->OverlaySubmission.evaluatedAt, status) { | (Some(date), Graded(_)) =>
-

{"Evaluated By" |> str}

+

{"Evaluated By"->str}

- {switch overlaySubmission |> OverlaySubmission.evaluatorName { - | Some(name) => name |> str - | None => {"Deleted Coach" |> str} + {switch overlaySubmission->OverlaySubmission.evaluatorName { + | Some(name) => name->str + | None => {"Deleted Coach"->str} }}

- {"on " ++ (date |> DateFns.format("MMMM D, YYYY")) |> str} + {"on " ++ (date->DateFns.format("MMMM D, YYYY"))->str}
| (None, Graded(_)) @@ -325,17 +325,17 @@ let submissionStatusIcon = (status, overlaySubmission, send) => { (color ++ ("-400 " ++ ("bg-" ++ (color ++ ("-100 " ++ ("text-" ++ (color ++ "-800 "))))))))}> - {text |> str} + {text->str}

- {switch (overlaySubmission |> OverlaySubmission.evaluatedAt, status) { + {switch (overlaySubmission->OverlaySubmission.evaluatedAt, status) { | (Some(_), Graded(_)) =>
| (None, Graded(_)) @@ -354,7 +354,7 @@ let gradeSubmission = ( status, event, ) => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault switch status { | Graded(_) => gradeSubmissionQuery(submissionId, state, send, evaluationCriteria, addGradingCB) | Grading @@ -385,15 +385,15 @@ let reviewButtonDisabled = status => let computeStatus = (overlaySubmission, selectedGrades, evaluationCriteria) => switch ( - overlaySubmission |> OverlaySubmission.passedAt, - overlaySubmission |> OverlaySubmission.grades |> ArrayUtils.isNotEmpty, + overlaySubmission->OverlaySubmission.passedAt, + overlaySubmission->OverlaySubmission.grades->ArrayUtils.isNotEmpty, ) { | (Some(_), _) => Graded(true) | (None, true) => Graded(false) | (_, _) => if selectedGrades == [] { Ungraded - } else if selectedGrades |> Array.length != (evaluationCriteria |> Array.length) { + } else if selectedGrades->Array.length != (evaluationCriteria->Array.length) { Grading } else { Graded(passed(selectedGrades, evaluationCriteria)) @@ -401,7 +401,7 @@ let computeStatus = (overlaySubmission, selectedGrades, evaluationCriteria) => } let submitButtonText = (feedback, grades) => - switch (feedback != "", grades |> ArrayUtils.isNotEmpty) { + switch (feedback != "", grades->ArrayUtils.isNotEmpty) { | (false, false) | (false, true) => "Save grades" | (true, false) @@ -409,7 +409,7 @@ let submitButtonText = (feedback, grades) => } let noteForm = (overlaySubmission, teamSubmission, note, send) => - switch overlaySubmission |> OverlaySubmission.grades { + switch overlaySubmission->OverlaySubmission.grades { | [] => let (noteAbout, additionalHelp) = teamSubmission ? ( @@ -423,10 +423,10 @@ let noteForm = (overlaySubmission, teamSubmission, note, send) => {"Notes can be used to keep track of a " ++ (noteAbout ++ ("'s progress. These notes are shown only to coaches in a student's report." ++ - additionalHelp)) |> str} + additionalHelp))->str} - let textareaId = "note-for-submission-" ++ (overlaySubmission |> OverlaySubmission.id) + let textareaId = "note-for-submission-" ++ (overlaySubmission->OverlaySubmission.id)
@@ -434,19 +434,19 @@ let noteForm = (overlaySubmission, teamSubmission, note, send) => {switch note { | Some(_) => - help + help | None =>
- {"Would you like to write a note about this " ++ (noteAbout ++ "?") |> str} + {"Would you like to write a note about this " ++ (noteAbout ++ "?")->str} help
}} @@ -487,17 +487,17 @@ let make = ( newFeedback: "", saving: false, note: None, - checklist: overlaySubmission |> OverlaySubmission.checklist, + checklist: overlaySubmission->OverlaySubmission.checklist, }, ) let status = computeStatus(overlaySubmission, state.grades, evaluationCriteria) - let updateChecklistCB = switch overlaySubmission |> OverlaySubmission.grades { + let updateChecklistCB = switch overlaySubmission->OverlaySubmission.grades { | [] => Some(checklist => send(UpdateChecklist(checklist))) | _ => None } - let pending = overlaySubmission |> OverlaySubmission.grades |> ArrayUtils.isEmpty + let pending = overlaySubmission->OverlaySubmission.grades->ArrayUtils.isEmpty
@@ -505,7 +505,7 @@ let make = (
{showFeedbackForm( - overlaySubmission |> OverlaySubmission.grades, + overlaySubmission->OverlaySubmission.grades, reviewChecklist, updateReviewChecklistCB, state, @@ -516,12 +516,12 @@ let make = ( {noteForm(overlaySubmission, teamSubmission, state.note, send)}
- {"Grade Card" |> str} + {"Grade Card"->str}
- {switch overlaySubmission |> OverlaySubmission.grades { + {switch overlaySubmission->OverlaySubmission.grades { | [] => renderGradePills(evaluationCriteria, targetEvaluationCriteriaIds, state, send) | grades => showGrades(grades, evaluationCriteria, state) @@ -531,21 +531,21 @@ let make = (
- {switch overlaySubmission |> OverlaySubmission.grades { + {switch overlaySubmission->OverlaySubmission.grades { | [] =>
diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__IndexSubmission.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__IndexSubmission.res index 468326276a..4bfc2d0833 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__IndexSubmission.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__IndexSubmission.res @@ -22,25 +22,25 @@ let coachIds = t => t.coachIds let failed = t => switch t.status { | None => false - | Some(status) => status.passedAt |> OptionUtils.mapWithDefault(_ => false, true) + | Some(status) => status.passedAt->OptionUtils.mapWithDefault(_ => false, true) } -let pendingReview = t => t.status |> OptionUtils.mapWithDefault(_ => false, true) +let pendingReview = t => t.status->OptionUtils.mapWithDefault(_ => false, true) -let feedbackSent = t => t.status |> OptionUtils.mapWithDefault(status => status.feedbackSent, false) +let feedbackSent = t => t.status->OptionUtils.mapWithDefault(status => status.feedbackSent, false) -let createdAtPretty = t => t.createdAt |> DateFns.format("MMMM D, YYYY") +let createdAtPretty = t => t.createdAt->DateFns.format("MMMM D, YYYY") -let timeDistance = t => t.createdAt |> DateFns.distanceInWordsToNow(~addSuffix=true) +let timeDistance = t => t.createdAt->DateFns.distanceInWordsToNow(~addSuffix=true) let sortArray = (sortDirection, submissions) => { let sortDescending = - submissions |> ArrayUtils.copyAndSort((x, y) => - DateFns.differenceInSeconds(y.createdAt, x.createdAt) |> int_of_float + submissions->ArrayUtils.copyAndSort((x, y) => + DateFns.differenceInSeconds(y.createdAt, x.createdAt)->int_of_float ) switch sortDirection { | #Descending => sortDescending - | #Ascending => sortDescending |> Js.Array.reverseInPlace + | #Ascending => sortDescending->Js.Array.reverseInPlace } } @@ -57,13 +57,13 @@ let make = (~id, ~title, ~createdAt, ~levelId, ~userNames, ~status, ~coachIds) = let makeStatus = (~passedAt, ~feedbackSent) => {passedAt: passedAt, feedbackSent: feedbackSent} let decodeJs = details => - details |> Js.Array.map(s => + details->Js.Array.map(s => switch s { | Some(submission) => let status = - submission["evaluatedAt"] |> OptionUtils.map(_ => + submission["evaluatedAt"]->OptionUtils.map(_ => makeStatus( - ~passedAt=submission["passedAt"] |> OptionUtils.map(DateFns.parseString), + ~passedAt=submission["passedAt"]->OptionUtils.map(DateFns.parseString), ~feedbackSent=submission["feedbackSent"], ) ) @@ -72,7 +72,7 @@ let decodeJs = details => make( ~id=submission["id"], ~title=submission["title"], - ~createdAt=submission["createdAt"] |> DateFns.parseString, + ~createdAt=submission["createdAt"]->DateFns.parseString, ~levelId=submission["levelId"], ~userNames=submission["userNames"], ~status, @@ -83,10 +83,10 @@ let decodeJs = details => } ) -let replace = (e, l) => l |> Array.map(s => s.id == e.id ? e : s) +let replace = (e, l) => l->Array.map(s => s.id == e.id ? e : s) let statusEq = (overlaySubmission, t) => - switch (t.status, overlaySubmission |> CoursesReview__OverlaySubmission.evaluatedAt) { + switch (t.status, overlaySubmission->CoursesReview__OverlaySubmission.evaluatedAt) { | (None, None) => true | (Some({passedAt}), Some(_)) => passedAt == CoursesReview__OverlaySubmission.passedAt(overlaySubmission) diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__Level.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__Level.res index e6328c5986..d3293d8a27 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__Level.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__Level.res @@ -7,9 +7,9 @@ type t = { let decode = json => { open Json.Decode { - id: json |> field("id", string), - name: json |> field("name", string), - number: json |> field("number", int), + id: json->field("id", string), + name: json->field("name", string), + number: json->field("number", int), } } @@ -17,14 +17,14 @@ let id = t => t.id let name = t => t.name let number = t => t.number -let sort = levels => levels |> ArrayUtils.copyAndSort((x, y) => x.number - y.number) +let sort = levels => levels->ArrayUtils.copyAndSort((x, y) => x.number - y.number) let unsafeLevelNumber = (levels, componentName, levelId) => "Level " ++ (levels - |> ArrayUtils.unsafeFind( + ->ArrayUtils.unsafeFind( l => l.id == levelId, "Unable to find level with id: " ++ (levelId ++ ("in CoursesRevew__" ++ componentName)), ) - |> number - |> string_of_int) + ->number + ->string_of_int) diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__OverlaySubmission.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__OverlaySubmission.res index c550ba6566..70b810fa21 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__OverlaySubmission.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__OverlaySubmission.res @@ -38,34 +38,34 @@ let make = ( } let makeFromJs = details => - details |> Js.Array.map(s => + details->Js.Array.map(s => make( ~id=s["id"], - ~createdAt=s["createdAt"] |> DateFns.parseString, - ~passedAt=s["passedAt"] |> OptionUtils.map(DateFns.parseString), + ~createdAt=s["createdAt"]->DateFns.parseString, + ~passedAt=s["passedAt"]->OptionUtils.map(DateFns.parseString), ~evaluatorName=s["evaluatorName"], - ~evaluatedAt=s["evaluatedAt"] |> OptionUtils.map(DateFns.parseString), - ~feedback=s["feedback"] |> Js.Array.map(f => + ~evaluatedAt=s["evaluatedAt"]->OptionUtils.map(DateFns.parseString), + ~feedback=s["feedback"]->Js.Array.map(f => CoursesReview__Feedback.make( ~coachName=f["coachName"], ~coachAvatarUrl=f["coachAvatarUrl"], ~coachTitle=f["coachTitle"], - ~createdAt=f["createdAt"] |> DateFns.parseString, + ~createdAt=f["createdAt"]->DateFns.parseString, ~value=f["value"], ) ), - ~grades=s["grades"] |> Js.Array.map(g => + ~grades=s["grades"]->Js.Array.map(g => CoursesReview__Grade.make( ~evaluationCriterionId=g["evaluationCriterionId"], ~value=g["grade"], ) ), - ~checklist=s["checklist"] |> Json.Decode.array( + ~checklist=s["checklist"]->Json.Decode.array( SubmissionChecklistItem.decode(SubmissionChecklistItem.makeFiles(s["files"])), ), ) ) -let feedbackSent = t => t.feedback |> ArrayUtils.isNotEmpty +let feedbackSent = t => t.feedback->ArrayUtils.isNotEmpty let updateFeedback = (feedback, t) => {...t, feedback: feedback} diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__ReviewChecklistItem.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__ReviewChecklistItem.res index 9fed311363..757c82726c 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__ReviewChecklistItem.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__ReviewChecklistItem.res @@ -8,10 +8,10 @@ let result = t => t.result let make = (~title, ~result) => {title: title, result: result} let makeFromJs = data => - data |> Js.Array.map(rc => + data->Js.Array.map(rc => make( ~title=rc["title"], - ~result=rc["result"] |> CoursesReview__ReviewChecklistResult.makeFromJs, + ~result=rc["result"]->CoursesReview__ReviewChecklistResult.makeFromJs, ) ) @@ -26,32 +26,32 @@ let updateTitle = (title, t) => make(~title, ~result=t.result) let updateChecklist = (result, t) => make(~title=t.title, ~result) let replace = (t, itemIndex, result) => - result |> Array.mapi((index, item) => index == itemIndex ? t : item) + result->Array.mapi((index, item) => index == itemIndex ? t : item) let appendEmptyChecklistItem = t => make( ~title=t.title, - ~result=[CoursesReview__ReviewChecklistResult.empty()] |> Array.append(t.result), + ~result=[CoursesReview__ReviewChecklistResult.empty()]->Array.append(t.result), ) let deleteResultItem = (index, t) => - make(~title=t.title, ~result=t.result |> Js.Array.filteri((_el, i) => i != index)) + make(~title=t.title, ~result=t.result->Js.Array.filteri((_el, i) => i != index)) let trim = t => { - title: t.title |> String.trim, - result: t.result |> Array.map(CoursesReview__ReviewChecklistResult.trim), + title: t.title->String.trim, + result: t.result->Array.map(CoursesReview__ReviewChecklistResult.trim), } let encode = t => { open Json.Encode object_(list{ - ("title", t.title |> string), - ("result", t.result |> array(CoursesReview__ReviewChecklistResult.encode)), + ("title", t.title->string), + ("result", t.result->array(CoursesReview__ReviewChecklistResult.encode)), }) } let encodeArray = checklist => - checklist |> { + checklist->{ open Json.Encode array(encode) } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__ReviewChecklistResult.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__ReviewChecklistResult.res index 6605919022..05eddfba37 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__ReviewChecklistResult.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__ReviewChecklistResult.res @@ -7,7 +7,7 @@ let feedback = t => t.feedback let make = (~title, ~feedback) => {title: title, feedback: feedback} -let makeFromJs = data => data |> Js.Array.map(r => make(~title=r["title"], ~feedback=r["feedback"])) +let makeFromJs = data => data->Js.Array.map(r => make(~title=r["title"], ~feedback=r["feedback"])) let emptyTemplate = () => [ make(~title="Yes", ~feedback=Some("Sample feedback for yes")), @@ -17,24 +17,24 @@ let emptyTemplate = () => [ let empty = () => make(~title="", ~feedback=None) let replace = (t, index, checklist) => - checklist |> Array.mapi((resultIndex, result) => resultIndex == index ? t : result) + checklist->Array.mapi((resultIndex, result) => resultIndex == index ? t : result) let updateTitle = (title, t, index, checklist) => - checklist |> replace(make(~title, ~feedback=t.feedback), index) + checklist->replace(make(~title, ~feedback=t.feedback), index) let updateFeedback = (feedback, t, index, checklist) => { - let optionalFeedback = feedback |> Js.String.trim == "" ? None : Some(feedback) + let optionalFeedback = feedback->Js.String.trim == "" ? None : Some(feedback) - checklist |> replace(make(~title=t.title, ~feedback=optionalFeedback), index) + checklist->replace(make(~title=t.title, ~feedback=optionalFeedback), index) } -let trim = t => {...t, title: t.title |> String.trim} +let trim = t => {...t, title: t.title->String.trim} let encode = t => { - let title = list{("title", t.title |> Json.Encode.string)} + let title = list{("title", t.title->Json.Encode.string)} let feedback = switch t.feedback { - | Some(f) => list{("feedback", f |> Json.Encode.string)} + | Some(f) => list{("feedback", f->Json.Encode.string)} | None => list{} } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__Root.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__Root.res index baa18e3e36..66cbf4f51c 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__Root.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__Root.res @@ -85,7 +85,7 @@ let reducer = (state, action) => | Unloaded => Unloaded | PartiallyLoaded({submissions, totalCount}, cursor) => Submissions.partiallyLoaded( - ~submissions=submissions |> IndexSubmission.replace(submission), + ~submissions=submissions->IndexSubmission.replace(submission), ~filter, ~sortDirection=state.sortDirection, ~totalCount, @@ -93,7 +93,7 @@ let reducer = (state, action) => ) | FullyLoaded({submissions, totalCount}) => Submissions.fullyLoaded( - ~submissions=submissions |> IndexSubmission.replace(submission), + ~submissions=submissions->IndexSubmission.replace(submission), ~filter, ~totalCount, ~sortDirection=state.sortDirection, @@ -113,13 +113,13 @@ let reducer = (state, action) => | SyncSubmissionStatus(overlaySubmission) => let skipReload = state.pendingSubmissions - |> Submissions.toArray - |> Array.append(state.reviewedSubmissions |> Submissions.toArray) - |> Js.Array.find(indexSubmission => - indexSubmission |> IndexSubmission.id == OverlaySubmission.id(overlaySubmission) + ->Submissions.toArray + ->Array.append(state.reviewedSubmissions->Submissions.toArray) + ->Js.Array.find(indexSubmission => + indexSubmission->IndexSubmission.id == OverlaySubmission.id(overlaySubmission) ) - |> OptionUtils.mapWithDefault( - indexSubmission => indexSubmission |> IndexSubmission.statusEq(overlaySubmission), + ->OptionUtils.mapWithDefault( + indexSubmission => indexSubmission->IndexSubmission.statusEq(overlaySubmission), true, ) @@ -149,14 +149,14 @@ let computeInitialState = currentTeamCoach => { } let openOverlay = (submissionId, event) => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault ReasonReactRouter.push("/submissions/" ++ submissionId) } let dropdownElementClasses = (level, selectedLevel) => "p-3 w-full text-left font-semibold focus:outline-none " ++ switch (selectedLevel, level) { - | (Some(sl), Some(l)) if l |> Level.id == (sl |> Level.id) => "bg-gray-200 text-primary-500" + | (Some(sl), Some(l)) if l->Level.id == (sl->Level.id) => "bg-gray-200 text-primary-500" | (None, None) => "bg-gray-200 text-primary-500" | _ => "" } @@ -175,26 +175,26 @@ module Selectable = { let label = t => switch t { - | Level(level) => Some("Level " ++ (level |> Level.number |> string_of_int)) + | Level(level) => Some("Level " ++ (level->Level.number->string_of_int)) | AssignedToCoach(_) => Some("Assigned to") } let value = t => switch t { - | Level(level) => level |> Level.name + | Level(level) => level->Level.name | AssignedToCoach(coach, currentCoachId) => - coach |> Coach.id == currentCoachId ? "Me" : coach |> Coach.name + coach->Coach.id == currentCoachId ? "Me" : coach->Coach.name } let searchString = t => switch t { | Level(level) => - "level " ++ ((level |> Level.number |> string_of_int) ++ (" " ++ (level |> Level.name))) + "level " ++ ((level->Level.number->string_of_int) ++ (" " ++ (level->Level.name))) | AssignedToCoach(coach, currentCoachId) => - if coach |> Coach.id == currentCoachId { - (coach |> Coach.name) ++ " assigned to me" + if coach->Coach.id == currentCoachId { + (coach->Coach.name) ++ " assigned to me" } else { - "assigned to " ++ (coach |> Coach.name) + "assigned to " ++ (coach->Coach.name) } } @@ -208,41 +208,41 @@ module Multiselect = MultiselectDropdown.Make(Selectable) let unselected = (levels, coaches, currentCoachId, state) => { let unselectedLevels = levels - |> Js.Array.filter(level => - state.selectedLevel |> OptionUtils.mapWithDefault( - selectedLevel => level |> Level.id != (selectedLevel |> Level.id), + ->Js.Array.filter(level => + state.selectedLevel->OptionUtils.mapWithDefault( + selectedLevel => level->Level.id != (selectedLevel->Level.id), true, ) ) - |> Array.map(Selectable.level) + ->Array.map(Selectable.level) let unselectedCoaches = coaches - |> Js.Array.filter(coach => - state.selectedCoach |> OptionUtils.mapWithDefault( - selectedCoach => coach |> Coach.id != Coach.id(selectedCoach), + ->Js.Array.filter(coach => + state.selectedCoach->OptionUtils.mapWithDefault( + selectedCoach => coach->Coach.id != Coach.id(selectedCoach), true, ) ) - |> Array.map(coach => Selectable.assignedToCoach(coach, currentCoachId)) + ->Array.map(coach => Selectable.assignedToCoach(coach, currentCoachId)) - unselectedLevels |> Array.append(unselectedCoaches) + unselectedLevels->Array.append(unselectedCoaches) } let selected = (state, currentCoachId) => { let selectedLevel = - state.selectedLevel |> OptionUtils.mapWithDefault( + state.selectedLevel->OptionUtils.mapWithDefault( selectedLevel => [Selectable.level(selectedLevel)], [], ) let selectedCoach = - state.selectedCoach |> OptionUtils.mapWithDefault( + state.selectedCoach->OptionUtils.mapWithDefault( selectedCoach => [Selectable.assignedToCoach(selectedCoach, currentCoachId)], [], ) - selectedLevel |> Array.append(selectedCoach) + selectedLevel->Array.append(selectedCoach) } let onSelectFilter = (send, selectable) => @@ -268,16 +268,16 @@ let filterPlaceholder = state => let restoreFilterNotice = (send, currentCoach, message) =>
- {message |> str} + {message->str}
let restoreAssignedToMeFilter = (state, send, currentTeamCoach) => - currentTeamCoach |> OptionUtils.mapWithDefault(currentCoach => + currentTeamCoach->OptionUtils.mapWithDefault(currentCoach => switch state.selectedCoach { | None => restoreFilterNotice( @@ -285,28 +285,28 @@ let restoreAssignedToMeFilter = (state, send, currentTeamCoach) => currentCoach, "Now showing submissions from all students in this course.", ) - | Some(selectedCoach) if selectedCoach |> Coach.id == Coach.id(currentCoach) => React.null + | Some(selectedCoach) if selectedCoach->Coach.id == Coach.id(currentCoach) => React.null | Some(selectedCoach) => restoreFilterNotice( send, currentCoach, - "Now showing submissions assigned to " ++ ((selectedCoach |> Coach.name) ++ "."), + "Now showing submissions assigned to " ++ ((selectedCoach->Coach.name) ++ "."), ) } , React.null) let filterSubmissions = (selectedLevel, selectedCoach, submissions) => { let levelFiltered = - selectedLevel |> OptionUtils.mapWithDefault( + selectedLevel->OptionUtils.mapWithDefault( level => - submissions |> Js.Array.filter(l => l |> IndexSubmission.levelId == (level |> Level.id)), + submissions->Js.Array.filter(l => l->IndexSubmission.levelId == (level->Level.id)), submissions, ) - selectedCoach |> OptionUtils.mapWithDefault( + selectedCoach->OptionUtils.mapWithDefault( coach => - levelFiltered |> Js.Array.filter(l => - l |> IndexSubmission.coachIds |> Array.mem(coach |> Coach.id) + levelFiltered->Js.Array.filter(l => + l->IndexSubmission.coachIds->Array.mem(coach->Coach.id) ), levelFiltered, ) @@ -324,7 +324,7 @@ module SubmissionsSorter = Sorter.Make(Sortable) let submissionsSorter = (state, send) => { let criteria = [{criterion: "Submitted At", criterionType: #Number}]
- + let submissionsCount = submissions => submissions - |> Submissions.totalCount - |> OptionUtils.mapWithDefault( + ->Submissions.totalCount + ->OptionUtils.mapWithDefault( count => - {count |> string_of_int |> str} + {count->string_of_int->str} , React.null, ) @@ -356,7 +356,7 @@ let submissionsCount = submissions => @react.component let make = (~levels, ~courseId, ~teamCoaches, ~currentCoach) => { let (currentTeamCoach, _) = React.useState(() => - teamCoaches->Belt.Array.some(coach => coach |> Coach.id == (currentCoach |> Coach.id)) + teamCoaches->Belt.Array.some(coach => coach->Coach.id == (currentCoach->Coach.id)) ? Some(currentCoach) : None ) @@ -389,24 +389,24 @@ let make = (~levels, ~courseId, ~teamCoaches, ~currentCoach) => {
Coach.id, state)} - selected={selected(state, currentCoach |> Coach.id)} + unselected={unselected(levels, teamCoaches, currentCoach->Coach.id, state)} + selected={selected(state, currentCoach->Coach.id)} onSelect={onSelectFilter(send)} onDeselect={onDeselectFilter(send)} value=state.filterString diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__ShowFeedback.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__ShowFeedback.res index 87c69fd923..ffbcce7e96 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__ShowFeedback.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__ShowFeedback.res @@ -20,8 +20,8 @@ let createFeedback = (submissionId, feedback, setState, addFeedbackCB) => { setState(state => {...state, saving: true}) CreateFeedbackMutation.make(~submissionId, ~feedback, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => { + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => { response["createFeedback"]["success"] ? { addFeedbackCB(feedback) @@ -30,30 +30,30 @@ let createFeedback = (submissionId, feedback, setState, addFeedbackCB) => { : setState(state => {...state, saving: false}) Js.Promise.resolve() }) - |> ignore + ->ignore } let showFeedback = feedback => feedback - |> Array.mapi((index, f) => -
string_of_int} className="border-t p-4 md:p-6"> + ->Array.mapi((index, f) => +
string_of_int} className="border-t p-4 md:p-6">
- {switch f |> Feedback.coachAvatarUrl { + {switch f->Feedback.coachAvatarUrl { | Some(avatarUrl) => - | None => Feedback.coachName} /> + | None => Feedback.coachName} /> }}
-

{"Feedback from:" |> str}

+

{"Feedback from:"->str}

- {f |> Feedback.coachName |> str} + {f->Feedback.coachName->str}

- {"(" ++ ((f |> Feedback.coachTitle) ++ ")") |> str} + {"(" ++ ((f->Feedback.coachTitle) ++ ")")->str}
@@ -61,15 +61,15 @@ let showFeedback = feedback =>

- {f |> Feedback.createdAtPretty |> str} + {f->Feedback.createdAtPretty->str}

Feedback.value} + className="pt-1 text-sm" profile=Markdown.Permissive markdown={f->Feedback.value} />
) - |> React.array + ->React.array let updateFeedbackCB = (setState, newFeedback) => setState(state => {...state, newFeedback: newFeedback}) @@ -112,7 +112,7 @@ let make = ( className="btn btn-success border border-green-600 w-full md:w-auto" onClick={_ => createFeedback(submissionId, state.newFeedback, setState, addFeedbackCB)}> - {"Share Feedback" |> str} + {"Share Feedback"->str}
@@ -123,7 +123,7 @@ let make = ( {switch feedback { | [] => "Add feedback" | _ => "Add another feedback" - } |> str} + }->str}
}
diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__SubmissionDetails.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__SubmissionDetails.res index e600486c4c..3dd1293511 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__SubmissionDetails.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__SubmissionDetails.res @@ -55,49 +55,49 @@ let make = ( let decodeJs = details => make( - ~submissions=details["submissions"] |> OverlaySubmission.makeFromJs, + ~submissions=details["submissions"]->OverlaySubmission.makeFromJs, ~targetId=details["targetId"], ~targetTitle=details["targetTitle"], - ~students=details["students"] |> Array.map(Student.makeFromJs), + ~students=details["students"]->Array.map(Student.makeFromJs), ~levelNumber=details["levelNumber"], ~levelId=details["levelId"], ~targetEvaluationCriteriaIds=details["targetEvaluationCriteriaIds"], ~inactiveStudents=details["inactiveStudents"], - ~evaluationCriteria=details["evaluationCriteria"] |> Js.Array.map(ec => + ~evaluationCriteria=details["evaluationCriteria"]->Js.Array.map(ec => EvaluationCriterion.make( ~id=ec["id"], ~name=ec["name"], ~maxGrade=ec["maxGrade"], ~passGrade=ec["passGrade"], - ~gradesAndLabels=ec["gradeLabels"] |> Array.map(gradeAndLabel => + ~gradesAndLabels=ec["gradeLabels"]->Array.map(gradeAndLabel => GradeLabel.makeFromJs(gradeAndLabel) ), ) ), - ~reviewChecklist=details["reviewChecklist"] |> ReviewChecklistItem.makeFromJs, + ~reviewChecklist=details["reviewChecklist"]->ReviewChecklistItem.makeFromJs, ~coachIds=details["coachIds"], ) let updateSubmission = (submission, t) => { ...t, submissions: t.submissions - |> Js.Array.filter(s => s |> OverlaySubmission.id != (submission |> OverlaySubmission.id)) - |> Array.append([submission]), + ->Js.Array.filter(s => s->OverlaySubmission.id != (submission->OverlaySubmission.id)) + ->Array.append([submission]), } let makeIndexSubmission = (overlaySubmission, t) => IndexSubmission.make( - ~id=overlaySubmission |> OverlaySubmission.id, + ~id=overlaySubmission->OverlaySubmission.id, ~title=t.targetTitle, - ~createdAt=overlaySubmission |> OverlaySubmission.createdAt, + ~createdAt=overlaySubmission->OverlaySubmission.createdAt, ~levelId=t.levelId, ~userNames=t.students - |> Array.map(student => student |> CoursesReview__Student.name) - |> Js.Array.joinWith(", "), + ->Array.map(student => student->CoursesReview__Student.name) + ->Js.Array.joinWith(", "), ~status=Some( IndexSubmission.makeStatus( - ~passedAt=overlaySubmission |> OverlaySubmission.passedAt, - ~feedbackSent=overlaySubmission |> OverlaySubmission.feedbackSent, + ~passedAt=overlaySubmission->OverlaySubmission.passedAt, + ~feedbackSent=overlaySubmission->OverlaySubmission.feedbackSent, ), ), ~coachIds=t.coachIds, diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__SubmissionOverlay.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__SubmissionOverlay.res index 37a4a5424f..eff55a1807 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__SubmissionOverlay.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__SubmissionOverlay.res @@ -51,15 +51,15 @@ module SubmissionDetailsQuery = %graphql(` * Then, set the state of this component to Loaded. */ let updateSubmissionDetails = (setState, submissionId, syncSubmissionCB, details) => { - let submissionDetails = details |> SubmissionDetails.decodeJs + let submissionDetails = details->SubmissionDetails.decodeJs submissionDetails - |> SubmissionDetails.submissions - |> ArrayUtils.unsafeFind( - submission => submission |> OverlaySubmission.id == submissionId, + ->SubmissionDetails.submissions + ->ArrayUtils.unsafeFind( + submission => submission->OverlaySubmission.id == submissionId, "Could not find overlaySubmission with ID " ++ (submissionId ++ " in loaded submissions"), ) - |> syncSubmissionCB + ->syncSubmissionCB setState(_ => Loaded(submissionDetails)) } @@ -67,16 +67,16 @@ let updateSubmissionDetails = (setState, submissionId, syncSubmissionCB, details let getSubmissionDetails = (submissionId, setState, syncSubmissionCB, ()) => { setState(_ => Loading) SubmissionDetailsQuery.make(~submissionId, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => { - response["submissionDetails"] |> updateSubmissionDetails( + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => { + response["submissionDetails"]->updateSubmissionDetails( setState, submissionId, syncSubmissionCB, ) Js.Promise.resolve() }) - |> ignore + ->ignore None } @@ -94,40 +94,40 @@ let headerSection = (submissionDetails, courseId, assignedCoaches) => onClick={_ => closeOverlay(courseId)} className="review-submission-overlay__close flex flex-col items-center justify-center absolute rounded-t-lg lg:rounded-lg leading-tight px-4 py-1 h-8 lg:h-full cursor-pointer border border-b-0 border-gray-400 lg:border-0 lg:shadow lg:border-gray-300 bg-white text-gray-700 hover:text-gray-900 hover:bg-gray-100"> - {"close" |> str} + {"close"->str}
- {"Submitted by " |> str} + {"Submitted by "->str} { - let studentCount = submissionDetails |> SubmissionDetails.students |> Array.length + let studentCount = submissionDetails->SubmissionDetails.students->Array.length submissionDetails - |> SubmissionDetails.students - |> Array.mapi((index, student) => { + ->SubmissionDetails.students + ->Array.mapi((index, student) => { let commaRequired = index + 1 != studentCount - Student.id}> + Student.id}> Student.id) ++ "/report")} + href={"/students/" ++ ((student->Student.id) ++ "/report")} target="_blank"> - {student |> Student.name |> str} + {student->Student.name->str} - {(commaRequired ? ", " : "") |> str} + {(commaRequired ? ", " : "")->str} }) - |> React.array + ->React.array }
@@ -135,7 +135,7 @@ let headerSection = (submissionDetails, courseId, assignedCoaches) => tooltipPosition=#Bottom defaultAvatarSize="8" mdAvatarSize="8" - title={ {"Assigned Coaches" |> str} } + title={ {"Assigned Coaches"->str} } className="mt-2 flex w-full md:w-auto items-center flex-shrink-0" coaches=assignedCoaches /> @@ -145,7 +145,7 @@ let headerSection = (submissionDetails, courseId, assignedCoaches) => let updateSubmissionDetails = (setState, submissionDetails, overlaySubmission) => { // Create new details for overlay with updated overlaySubmission. let newSubmissionDetails = - submissionDetails |> SubmissionDetails.updateSubmission(overlaySubmission) + submissionDetails->SubmissionDetails.updateSubmission(overlaySubmission) // Re-render the overlay with the updated submission details. setState(_ => Loaded(newSubmissionDetails)) @@ -154,7 +154,7 @@ let updateSubmissionDetails = (setState, submissionDetails, overlaySubmission) = } let addGrading = (setState, removePendingSubmissionCB, submissionDetails, overlaySubmission) => { - updateSubmissionDetails(setState, submissionDetails, overlaySubmission) |> ignore + updateSubmissionDetails(setState, submissionDetails, overlaySubmission)->ignore removePendingSubmissionCB() } @@ -166,24 +166,24 @@ let addFeedbackToReviewedSubmission = ( overlaySubmission, ) => updateSubmissionDetails(setState, submissionDetails, overlaySubmission) - |> SubmissionDetails.makeIndexSubmission(overlaySubmission) - |> updateReviewedSubmissionCB + ->SubmissionDetails.makeIndexSubmission(overlaySubmission) + ->updateReviewedSubmissionCB let updateReviewChecklist = (submissionDetails, setState, reviewChecklist) => setState(_ => Loaded( - submissionDetails |> SubmissionDetails.updateReviewChecklist(reviewChecklist), + submissionDetails->SubmissionDetails.updateReviewChecklist(reviewChecklist), )) let inactiveWarning = submissionDetails => - if submissionDetails |> SubmissionDetails.inactiveStudents { - let warning = if submissionDetails |> SubmissionDetails.students |> Array.length > 1 { + if submissionDetails->SubmissionDetails.inactiveStudents { + let warning = if submissionDetails->SubmissionDetails.students->Array.length > 1 { "This submission is linked to one or more students whose access to the course has ended, or have dropped out." } else { "This submission is from a student whose access to the course has ended, or has dropped out." }
- {warning |> str} + {warning->str}
} else { React.null @@ -211,8 +211,8 @@ let make = ( {switch state { | Loaded(submissionDetails) => let assignedCoaches = - teamCoaches |> Js.Array.filter(coach => - submissionDetails |> SubmissionDetails.coachIds |> Array.mem(coach |> Coach.id) + teamCoaches->Js.Array.filter(coach => + submissionDetails->SubmissionDetails.coachIds->Array.mem(coach->Coach.id) )
@@ -223,13 +223,13 @@ let make = (
{submissionDetails - |> SubmissionDetails.submissions - |> Array.mapi((index, overlaySubmission) => + ->SubmissionDetails.submissions + ->Array.mapi((index, overlaySubmission) => string_of_int} + key={index->string_of_int} overlaySubmission - teamSubmission={submissionDetails |> SubmissionDetails.students |> Array.length > 1} - targetEvaluationCriteriaIds={submissionDetails |> SubmissionDetails.targetEvaluationCriteriaIds} + teamSubmission={submissionDetails->SubmissionDetails.students->Array.length > 1} + targetEvaluationCriteriaIds={submissionDetails->SubmissionDetails.targetEvaluationCriteriaIds} addGradingCB={addGrading(setState, removePendingSubmissionCB, submissionDetails)} addFeedbackCB={addFeedbackToReviewedSubmission( setState, @@ -237,16 +237,16 @@ let make = ( submissionDetails, )} submissionNumber={(submissionDetails - |> SubmissionDetails.submissions - |> Array.length) - index} + ->SubmissionDetails.submissions + ->Array.length) - index} currentCoach - evaluationCriteria={submissionDetails |> SubmissionDetails.evaluationCriteria} - reviewChecklist={submissionDetails |> SubmissionDetails.reviewChecklist} + evaluationCriteria={submissionDetails->SubmissionDetails.evaluationCriteria} + reviewChecklist={submissionDetails->SubmissionDetails.reviewChecklist} updateReviewChecklistCB={updateReviewChecklist(submissionDetails, setState)} - targetId={submissionDetails |> SubmissionDetails.targetId} + targetId={submissionDetails->SubmissionDetails.targetId} /> ) - |> React.array} + ->React.array}
diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__Submissions.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__Submissions.res index 95b8c1d05b..572ba08050 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__Submissions.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__Submissions.res @@ -7,12 +7,12 @@ type filter = { let makeFilter = (level, coach) => {level: level, coach: coach} -let filterLevelId = level => level |> OptionUtils.mapWithDefault(Level.id, "none") -let filterCoachId = coach => coach |> OptionUtils.mapWithDefault(UserProxy.id, "none") +let filterLevelId = level => level->OptionUtils.mapWithDefault(Level.id, "none") +let filterCoachId = coach => coach->OptionUtils.mapWithDefault(UserProxy.id, "none") let filterEq = (level, coach, filter) => - filter.level |> filterLevelId == filterLevelId(level) && - filter.coach |> filterCoachId == filterCoachId(coach) + filter.level->filterLevelId == filterLevelId(level) && + filter.coach->filterCoachId == filterCoachId(coach) type sortDirection = [#Ascending | #Descending] @@ -63,7 +63,7 @@ let needsReloading = (selectedLevel, selectedCoach, sortDirection, t) => | Unloaded => true | FullyLoaded(data) | PartiallyLoaded(data, _) => - !(data.filter |> filterEq(selectedLevel, selectedCoach) && data.sortDirection == sortDirection) + !(data.filter->filterEq(selectedLevel, selectedCoach) && data.sortDirection == sortDirection) } let toArray = t => diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__SubmissionsList.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__SubmissionsList.res index 06734ef594..1d80e7a8c5 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__SubmissionsList.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__SubmissionsList.res @@ -3,30 +3,30 @@ let str = React.string let showSubmissionStatus = overlaySubmission => { let (text, classes) = switch ( - overlaySubmission |> OverlaySubmission.passedAt, - overlaySubmission |> OverlaySubmission.evaluatorName, + overlaySubmission->OverlaySubmission.passedAt, + overlaySubmission->OverlaySubmission.evaluatorName, ) { | (None, None) => ("Pending", "bg-orange-100 border border-orange-500 text-orange-800 ") | (None, Some(_)) => ("Failed", "bg-red-100 border border-red-500 text-red-700") | (Some(_), None) | (Some(_), Some(_)) => ("Passed", "bg-green-100 border border-green-500 text-green-800") } -
{text |> str}
+
{text->str}
} let showFeedbackSent = feedbackSent => feedbackSent ?
- {"Feedback Sent" |> str} + {"Feedback Sent"->str}
: React.null let cardClasses = overlaySubmission => "mt-6 rounded-b-lg bg-white border-t-3 " ++ switch ( - overlaySubmission |> OverlaySubmission.passedAt, - overlaySubmission |> OverlaySubmission.evaluatorName, + overlaySubmission->OverlaySubmission.passedAt, + overlaySubmission->OverlaySubmission.evaluatorName, ) { | (None, None) => "border-orange-300" | (None, Some(_)) => "border-red-500" @@ -46,39 +46,39 @@ let updateSubmission = ( ) => { let feedback = switch newFeedback { | Some(f) => - f |> String.trim == "" - ? overlaySubmission |> OverlaySubmission.feedback + f->String.trim == "" + ? overlaySubmission->OverlaySubmission.feedback : overlaySubmission - |> OverlaySubmission.feedback - |> Array.append([ + ->OverlaySubmission.feedback + ->Array.append([ Feedback.make( - ~coachName=currentCoach |> Coach.name, - ~coachAvatarUrl=currentCoach |> Coach.avatarUrl, - ~coachTitle=currentCoach |> Coach.title, + ~coachName=currentCoach->Coach.name, + ~coachAvatarUrl=currentCoach->Coach.avatarUrl, + ~coachTitle=currentCoach->Coach.title, ~createdAt=Js.Date.make(), ~value=f, ), ]) - | None => overlaySubmission |> OverlaySubmission.feedback + | None => overlaySubmission->OverlaySubmission.feedback } let (passedAt, evaluatedAt, newGrades) = switch passed { | Some(p) => (p ? Some(Js.Date.make()) : None, Some(Js.Date.make()), grades) | None => ( - overlaySubmission |> OverlaySubmission.passedAt, - overlaySubmission |> OverlaySubmission.evaluatedAt, - overlaySubmission |> OverlaySubmission.grades, + overlaySubmission->OverlaySubmission.passedAt, + overlaySubmission->OverlaySubmission.evaluatedAt, + overlaySubmission->OverlaySubmission.grades, ) } let newSubmission = OverlaySubmission.make( - ~id=overlaySubmission |> OverlaySubmission.id, - ~createdAt=overlaySubmission |> OverlaySubmission.createdAt, + ~id=overlaySubmission->OverlaySubmission.id, + ~createdAt=overlaySubmission->OverlaySubmission.createdAt, ~passedAt, ~evaluatorName=if feedbackUpdate { - overlaySubmission |> OverlaySubmission.evaluatorName + overlaySubmission->OverlaySubmission.evaluatorName } else { - Some(currentCoach |> Coach.name) + Some(currentCoach->Coach.name) }, ~feedback, ~grades=newGrades, @@ -90,15 +90,15 @@ let updateSubmission = ( } let updateFeedbackArray = (currentCoach, overlaySubmission, newFeedback) => - newFeedback |> String.trim == "" - ? overlaySubmission |> OverlaySubmission.feedback + newFeedback->String.trim == "" + ? overlaySubmission->OverlaySubmission.feedback : overlaySubmission - |> OverlaySubmission.feedback - |> Array.append([ + ->OverlaySubmission.feedback + ->Array.append([ Feedback.make( - ~coachName=currentCoach |> Coach.name, - ~coachAvatarUrl=currentCoach |> Coach.avatarUrl, - ~coachTitle=currentCoach |> Coach.title, + ~coachName=currentCoach->Coach.name, + ~coachAvatarUrl=currentCoach->Coach.avatarUrl, + ~coachTitle=currentCoach->Coach.title, ~createdAt=Js.Date.make(), ~value=newFeedback, ), @@ -119,21 +119,21 @@ let addGrading = ( let evaluatedAt = Some(Js.Date.make()) OverlaySubmission.make( - ~id=overlaySubmission |> OverlaySubmission.id, - ~createdAt=overlaySubmission |> OverlaySubmission.createdAt, + ~id=overlaySubmission->OverlaySubmission.id, + ~createdAt=overlaySubmission->OverlaySubmission.createdAt, ~passedAt, - ~evaluatorName=Some(currentCoach |> Coach.name), + ~evaluatorName=Some(currentCoach->Coach.name), ~feedback, ~grades, ~evaluatedAt, ~checklist, - ) |> addGradingCB + )->addGradingCB } let addFeedback = (addFeedbackCB, currentCoach, overlaySubmission, newFeedback) => { let feedback = updateFeedbackArray(currentCoach, overlaySubmission, newFeedback) - overlaySubmission |> OverlaySubmission.updateFeedback(feedback) |> addFeedbackCB + overlaySubmission->OverlaySubmission.updateFeedback(feedback)->addFeedbackCB } @react.component @@ -151,25 +151,25 @@ let make = ( ~targetEvaluationCriteriaIds, ) =>
OverlaySubmission.id)} + ariaLabel={"submissions-overlay-card-" ++ (overlaySubmission->OverlaySubmission.id)} className={cardClasses(overlaySubmission)}>

- {"Submission #" ++ (submissionNumber |> string_of_int) |> str} + {"Submission #" ++ (submissionNumber->string_of_int)->str}

{overlaySubmission - |> OverlaySubmission.createdAt - |> DateFns.format("MMMM D, YYYY") - |> str} + ->OverlaySubmission.createdAt + ->DateFns.format("MMMM D, YYYY") + ->str}
{showFeedbackSent( - overlaySubmission |> OverlaySubmission.feedback |> ArrayUtils.isNotEmpty, + overlaySubmission->OverlaySubmission.feedback->ArrayUtils.isNotEmpty, )} {showSubmissionStatus(overlaySubmission)}
@@ -185,9 +185,9 @@ let make = ( targetId /> OverlaySubmission.feedback} - reviewed={overlaySubmission |> OverlaySubmission.grades |> ArrayUtils.isNotEmpty} - submissionId={overlaySubmission |> OverlaySubmission.id} + feedback={overlaySubmission->OverlaySubmission.feedback} + reviewed={overlaySubmission->OverlaySubmission.grades->ArrayUtils.isNotEmpty} + submissionId={overlaySubmission->OverlaySubmission.id} reviewChecklist addFeedbackCB={addFeedback(addFeedbackCB, currentCoach, overlaySubmission)} updateReviewChecklistCB diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__SubmissionsTab.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__SubmissionsTab.res index ce68ee90cf..3b1cb43d13 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__SubmissionsTab.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesReview__SubmissionsTab.res @@ -48,14 +48,14 @@ let updateSubmissions = ( nodes, ) => { updateSubmissionsCB( - ~submissions=submissions |> Array.append( + ~submissions=submissions->Array.append( switch nodes { | None => [] - | Some(submissionsArray) => submissionsArray |> IndexSubmission.decodeJs + | Some(submissionsArray) => submissionsArray->IndexSubmission.decodeJs } - |> Array.to_list - |> List.flatten - |> Array.of_list, + ->Array.to_list + ->List.flatten + ->Array.of_list, ), ~selectedTab, ~hasNextPage, @@ -86,8 +86,8 @@ let getSubmissions = ( } ) - let levelId = selectedLevel |> OptionUtils.map(level => level |> Level.id) - let coachId = selectedCoach |> OptionUtils.map(coach => coach |> Coach.id) + let levelId = selectedLevel->OptionUtils.map(level => level->Level.id) + let coachId = selectedCoach->OptionUtils.map(coach => coach->Coach.id) SubmissionsQuery.make( ~courseId, @@ -98,9 +98,9 @@ let getSubmissions = ( ~after=?cursor, (), ) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => { - response["submissions"]["nodes"] |> updateSubmissions( + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => { + response["submissions"]["nodes"]->updateSubmissions( setState, response["submissions"]["pageInfo"]["endCursor"], response["submissions"]["pageInfo"]["hasNextPage"], @@ -111,37 +111,37 @@ let getSubmissions = ( ) Js.Promise.resolve() }) - |> ignore + ->ignore } let submissionStatus = submission => { let classes = "border flex-shrink-0 leading-normal font-semibold px-3 py-px rounded " - let (className, text) = if submission |> IndexSubmission.pendingReview { - (classes ++ "bg-orange-100 text-orange-600", submission |> IndexSubmission.timeDistance) - } else if submission |> IndexSubmission.failed { + let (className, text) = if submission->IndexSubmission.pendingReview { + (classes ++ "bg-orange-100 text-orange-600", submission->IndexSubmission.timeDistance) + } else if submission->IndexSubmission.failed { (classes ++ "bg-red-100 border-red-500 text-red-800", "Failed") } else { ("bg-green-100 border-green-500 text-green-800", "Passed") } -
{text |> str}
+
{text->str}
} let feedbackSentNotice = feedbackSent => feedbackSent ?
- {"Feedback Sent" |> str} + {"Feedback Sent"->str}
: React.null let submissionCardClasses = submission => "flex flex-col md:flex-row items-start md:items-center justify-between bg-white border-l-3 p-3 md:py-6 md:px-5 mb-4 cursor-pointer rounded-r-lg shadow hover:border-primary-500 hover:text-primary-500 hover:shadow-md " ++ if ( - submission |> IndexSubmission.pendingReview + submission->IndexSubmission.pendingReview ) { "border-orange-400" - } else if submission |> IndexSubmission.failed { + } else if submission->IndexSubmission.failed { "border-red-500" } else { "border-green-500" @@ -150,42 +150,42 @@ let submissionCardClasses = submission => let showSubmission = (submissions, levels, sortDirection) =>
{submissions - |> IndexSubmission.sortArray(sortDirection) - |> Array.map(submission => + ->IndexSubmission.sortArray(sortDirection) + ->Array.map(submission => IndexSubmission.id)} - key={submission |> IndexSubmission.id} - ariaLabel={"Submission " ++ (submission |> IndexSubmission.id)} + href={"/submissions/" ++ (submission->IndexSubmission.id)} + key={submission->IndexSubmission.id} + ariaLabel={"Submission " ++ (submission->IndexSubmission.id)} className={submissionCardClasses(submission)}>
{submission - |> IndexSubmission.levelId - |> Level.unsafeLevelNumber(levels, "SubmissionsTab") - |> str} + ->IndexSubmission.levelId + ->Level.unsafeLevelNumber(levels, "SubmissionsTab") + ->str} - {submission |> IndexSubmission.title |> str} + {submission->IndexSubmission.title->str}
- {"Submitted by " |> str} + {"Submitted by "->str} - {submission |> IndexSubmission.userNames |> str} + {submission->IndexSubmission.userNames->str} - {"on " ++ (submission |> IndexSubmission.createdAtPretty) |> str} + {"on " ++ (submission->IndexSubmission.createdAtPretty)->str}
- {feedbackSentNotice(submission |> IndexSubmission.feedbackSent)} + {feedbackSentNotice(submission->IndexSubmission.feedbackSent)} {submissionStatus(submission)}
) - |> React.array} + ->React.array}
let showSubmissions = (submissions, selectedTab, levels, sortDirection) => { @@ -194,10 +194,10 @@ let showSubmissions = (submissions, selectedTab, levels, sortDirection) => { | #Reviewed => reviewedEmptyImage } - submissions |> ArrayUtils.isEmpty + submissions->ArrayUtils.isEmpty ?
- {"No submissions found" |> str} + {"No submissions found"->str}
@@ -218,7 +218,7 @@ let make = ( ) => { let (state, setState) = React.useState(() => Loading) React.useEffect5(() => { - if submissions |> Submissions.needsReloading(selectedLevel, selectedCoach, sortDirection) { + if submissions->Submissions.needsReloading(selectedLevel, selectedCoach, sortDirection) { setState(_ => Reloading) getSubmissions( @@ -260,7 +260,7 @@ let make = ( submissions, updateSubmissionsCB, )}> - {"Load More..." |> str} + {"Load More..."->str} }
| FullyLoaded({submissions}) => showSubmissions(submissions, selectedTab, levels, sortDirection) diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__CoachNote.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__CoachNote.res index c6b6e90950..412d10933d 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__CoachNote.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__CoachNote.res @@ -20,17 +20,17 @@ let createdAt = t => t.createdAt let author = t => t.author -let noteOn = t => t.createdAt |> DateFns.format("MMMM D, YYYY") +let noteOn = t => t.createdAt->DateFns.format("MMMM D, YYYY") let sort = notes => - notes |> ArrayUtils.copyAndSort((x, y) => - DateFns.differenceInSeconds(y.createdAt, x.createdAt) |> int_of_float + notes->ArrayUtils.copyAndSort((x, y) => + DateFns.differenceInSeconds(y.createdAt, x.createdAt)->int_of_float ) let makeFromJs = note => make( ~id=note["id"], ~note=note["note"], - ~createdAt=note["createdAt"] |> DateFns.parseString, - ~author=note["author"] |> OptionUtils.map(User.makeFromJs), + ~createdAt=note["createdAt"]->DateFns.parseString, + ~author=note["author"]->OptionUtils.map(User.makeFromJs), ) diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__CoachNoteShow.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__CoachNoteShow.res index d6b220e0b9..bc22ce429e 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__CoachNoteShow.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__CoachNoteShow.res @@ -13,15 +13,15 @@ module ArchiveCoachNoteMutation = %graphql(` `) let removeCoachNote = (id, removeNoteCB, setArchiving, event) => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault setArchiving(_ => true) if { open Webapi.Dom - window |> Window.confirm("Are you sure you want to delete this note?") + window->Window.confirm("Are you sure you want to delete this note?") } { ArchiveCoachNoteMutation.make(~id, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => { + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => { if response["archiveCoachNote"]["success"] { removeNoteCB(id) } else { @@ -29,7 +29,7 @@ let removeCoachNote = (id, removeNoteCB, setArchiving, event) => { } Js.Promise.resolve() }) - |> ignore + ->ignore } else { () } @@ -39,20 +39,20 @@ let deleteIcon = (note, removeCoachNote, removeNoteCB, setArchiving, archiving) @react.component let make = (~note, ~userId, ~removeNoteCB) => { let (archiving, setArchiving) = React.useState(() => false) -
CoachNote.id} ariaLabel={"Note " ++ (note |> CoachNote.id)}> +
CoachNote.id} ariaLabel={"Note " ++ (note->CoachNote.id)}>
- {switch note |> CoachNote.author { + {switch note->CoachNote.author { | Some(user) => - switch user |> User.avatarUrl { + switch user->User.avatarUrl { | Some(avatarUrl) => { /> | None => User.name} + name={user->User.name} className="w-8 h-8 md:w-10 md:h-10 text-xs border border-gray-400 rounded-full overflow-hidden flex-shrink-0 mt-1 md:mt-0 mr-2 md:mr-3 object-cover" /> } @@ -73,21 +73,21 @@ let make = (~note, ~userId, ~removeNoteCB) => { }}

- {switch note |> CoachNote.author { - | Some(user) => user |> User.name + {switch note->CoachNote.author { + | Some(user) => user->User.name | None => "Deleted Coach" - } |> str} + }->str}

- {switch note |> CoachNote.author { - | Some(user) => user |> User.title + {switch note->CoachNote.author { + | Some(user) => user->User.title | None => "Unknown" - } |> str} + }->str}

{ - let showDeleteIcon = switch note |> CoachNote.author { + let showDeleteIcon = switch note->CoachNote.author { | None => false | Some(user) => User.id(user) == userId } @@ -99,10 +99,10 @@ let make = (~note, ~userId, ~removeNoteCB) => {

- {"on " ++ (note |> CoachNote.noteOn) |> str} + {"on " ++ (note->CoachNote.noteOn)->str}

CoachNote.note} + className="pt-1 text-sm" profile=Markdown.Permissive markdown={note->CoachNote.note} />
diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__CoachNotes.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__CoachNotes.res index 5926b087e1..f975dc8627 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__CoachNotes.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__CoachNotes.res @@ -30,8 +30,8 @@ module CreateCoachNotesMutation = %graphql(` let saveNote = (studentId, setState, state, addNoteCB) => { setState(state => {...state, saving: true}) CreateCoachNotesMutation.make(~studentId, ~note=state.newNote, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => { + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => { switch response["createCoachNote"]["coachNote"] { | Some(note) => let newNote = CoachNote.makeFromJs(note) @@ -41,17 +41,17 @@ let saveNote = (studentId, setState, state, addNoteCB) => { } Js.Promise.resolve() }) - |> Js.Promise.catch(_error => { + ->Js.Promise.catch(_error => { setState(state => {...state, saving: false}) Js.Promise.resolve() }) - |> ignore + ->ignore } let updateCoachNoteCB = (setState, newNote) => setState(state => {...state, newNote: newNote}) let saveNoteButtonText = (title, iconClasses) => - {title |> str} + {title->str} @react.component let make = (~studentId, ~coachNotes, ~addNoteCB, ~removeNoteCB, ~userId) => { @@ -59,7 +59,7 @@ let make = (~studentId, ~coachNotes, ~addNoteCB, ~removeNoteCB, ~userId) => {
{ />
-
{"All Notes" |> str}
- {coachNotes |> ArrayUtils.isEmpty +
{"All Notes"->str}
+ {coachNotes->ArrayUtils.isEmpty ?
-

{"No notes here!" |> str}

+

{"No notes here!"->str}

: React.null} {coachNotes - |> CoachNote.sort - |> Array.map(note => - CoachNote.id} note userId removeNoteCB /> + ->CoachNote.sort + ->Array.map(note => + CoachNote.id} note userId removeNoteCB /> ) - |> React.array} + ->React.array}
} diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__Course.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__Course.res index c5f64e7189..e81d5cbe01 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__Course.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__Course.res @@ -4,5 +4,5 @@ let id = t => t.id let decode = json => { open Json.Decode - {id: json |> field("id", string)} + {id: json->field("id", string)} } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__EvaluationCriterion.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__EvaluationCriterion.res index d24d11a10b..2075da9e88 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__EvaluationCriterion.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__EvaluationCriterion.res @@ -19,6 +19,6 @@ let make = (~id, ~name, ~maxGrade, ~passGrade) => { } let makeFromJs = ecData => - ecData |> Js.Array.map(ec => + ecData->Js.Array.map(ec => make(~id=ec["id"], ~name=ec["name"], ~maxGrade=ec["maxGrade"], ~passGrade=ec["passGrade"]) ) diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__Level.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__Level.res index 23e27df9cc..ad650cce5f 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__Level.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__Level.res @@ -21,31 +21,31 @@ let teamsInLevel = t => t.teamsInLevel let decode = json => { open Json.Decode { - id: json |> field("id", string), - name: json |> field("name", string), - number: json |> field("number", int), - studentsInLevel: json |> field("studentsInLevel", int), - teamsInLevel: json |> field("teamsInLevel", int), - unlocked: json |> field("unlocked", bool), + id: json->field("id", string), + name: json->field("name", string), + number: json->field("number", int), + studentsInLevel: json->field("studentsInLevel", int), + teamsInLevel: json->field("teamsInLevel", int), + unlocked: json->field("unlocked", bool), } } let percentageStudents = (t, totalStudents) => float_of_int(t.studentsInLevel) /. float_of_int(totalStudents) *. 100.0 -let shortName = t => "L" ++ (t.number |> string_of_int) +let shortName = t => "L" ++ (t.number->string_of_int) -let sort = levels => levels |> ArrayUtils.copyAndSort((x, y) => x.number - y.number) +let sort = levels => levels->ArrayUtils.copyAndSort((x, y) => x.number - y.number) let unsafeLevelNumber = (levels, componentName, levelId) => "Level " ++ (levels - |> ArrayUtils.unsafeFind( + ->ArrayUtils.unsafeFind( l => l.id == levelId, "Unable to find level with id: " ++ (levelId ++ (" in CoursesStudents__" ++ componentName)), ) - |> number - |> string_of_int) + ->number + ->string_of_int) let levelsCompletedByAllStudents = levels => { let rec aux = (completedLevels, levels) => @@ -59,6 +59,6 @@ let levelsCompletedByAllStudents = levels => { } } - let ls = levels |> sort |> Array.to_list |> aux([]) - ls |> Array.length == (levels |> Array.length) ? [] : ls + let ls = levels->sort->Array.to_list->aux([]) + ls->Array.length == (levels->Array.length) ? [] : ls } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__LevelDistribution.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__LevelDistribution.res index 3b4ccd07a2..f3832eef0d 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__LevelDistribution.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__LevelDistribution.res @@ -6,7 +6,7 @@ let str = React.string let stylingForLevelPills = percentageStudents => { let emptyStyle = ReactDOMRe.Style.make() let styleWithWidth = ReactDOMRe.Style.make( - ~width=(percentageStudents |> Js.Float.toString) ++ "%", + ~width=(percentageStudents->Js.Float.toString) ++ "%", (), ) if 0.0 <= percentageStudents && percentageStudents < 5.0 { @@ -26,7 +26,7 @@ let stylingForLevelPills = percentageStudents => { @react.component let make = (~levels, ~selectLevelCB) => { - let totalStudentsInCourse = levels |> Array.fold_left((x, y) => x + Level.studentsInLevel(y), 0) + let totalStudentsInCourse = levels->Array.fold_left((x, y) => x + Level.studentsInLevel(y), 0) let completedLevels = Level.levelsCompletedByAllStudents(levels) totalStudentsInCourse > 0 ?
{ className="w-full pt-8 max-w-3xl mx-auto hidden md:block">
{levels - |> Js.Array.filter(level => Level.number(level) != 0) - |> Level.sort - |> Array.map(level => { + ->Js.Array.filter(level => Level.number(level) != 0) + ->Level.sort + ->Array.map(level => { let percentageStudents = Level.percentageStudents(level, totalStudentsInCourse) let (pillClass, style, pillColor) = stylingForLevelPills(percentageStudents) let tip =
-

{"Level: " ++ string_of_int(Level.number(level)) |> str}

-

{"Students: " ++ string_of_int(Level.studentsInLevel(level)) |> str}

+

{"Level: " ++ string_of_int(Level.number(level))->str}

+

{"Students: " ++ string_of_int(Level.studentsInLevel(level))->str}

{Level.studentsInLevel(level) != Level.teamsInLevel(level) - ?

{"Teams: " ++ string_of_int(Level.teamsInLevel(level)) |> str}

+ ?

{"Teams: " ++ string_of_int(Level.teamsInLevel(level))->str}

: React.null}

{"Percentage: " ++ Js.Float.toFixedWithPrecision(percentageStudents, ~digits=1) - |> str} + ->str}

string_of_int)} + ariaLabel={"Students in level " ++ (Level.number(level)->string_of_int)} className={"level-distribution__container text-center relative " ++ pillClass} style>
selectLevelCB(level)} className={"level-distribution__pill hover:shadow-inner focus:shadow-inner relative cursor-pointer border-white text-xs leading-none text-center " ++ ( - completedLevels |> Array.mem(level) + completedLevels->Array.mem(level) ? "bg-yellow-300 text-yellow-900" : Level.unlocked(level) ? pillColor : "level-distribution__pill--locked cursor-default bg-gray-300" ++ " text-gray-800" )}> - {completedLevels |> Array.mem(level) + {completedLevels->Array.mem(level) ? :
Level.unlocked + className={level->Level.unlocked ? "" : "level-distribution__team-count-value"}> - {level |> Level.teamsInLevel |> string_of_int |> str} + {level->Level.teamsInLevel->string_of_int->str}
- {level |> Level.unlocked + {level->Level.unlocked ? React.null :
@@ -88,7 +88,7 @@ let make = (~levels, ~selectLevelCB) => {
}) - |> React.array} + ->React.array}
: React.null diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__Root.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__Root.res index 07d8d5d5fe..654591af5c 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__Root.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__Root.res @@ -83,7 +83,7 @@ let reducer = (state, action) => | UpdateFilterString(filterString) => {...state, filterString: filterString} | LoadTeams(endCursor, hasNextPage, newTeams) => let updatedTeams = switch state.loading { - | LoadingMore => newTeams |> Array.append(state.teams |> Teams.toArray) + | LoadingMore => newTeams->Array.append(state.teams->Teams.toArray) | Reloading => newTeams | NotLoading => newTeams } @@ -127,15 +127,15 @@ module TeamsQuery = %graphql(` `) let getTeams = (send, courseId, cursor, filter) => { - let levelId = filter.level |> OptionUtils.map(Level.id) - let coachId = filter.coach |> OptionUtils.map(Coach.id) + let levelId = filter.level->OptionUtils.map(Level.id) + let coachId = filter.coach->OptionUtils.map(Coach.id) TeamsQuery.make(~courseId, ~after=?cursor, ~levelId?, ~coachId?, ~search=?filter.nameOrEmail, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => { + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => { let newTeams = switch response["teams"]["nodes"] { | None => [] - | Some(teamsArray) => teamsArray |> TeamInfo.makeArrayFromJs + | Some(teamsArray) => teamsArray->TeamInfo.makeArrayFromJs } send( @@ -148,10 +148,10 @@ let getTeams = (send, courseId, cursor, filter) => { Js.Promise.resolve() }) - |> ignore + ->ignore } -let applicableLevels = levels => levels |> Js.Array.filter(level => Level.number(level) != 0) +let applicableLevels = levels => levels->Js.Array.filter(level => Level.number(level) != 0) module Selectable = { type t = @@ -161,28 +161,28 @@ module Selectable = { let label = t => switch t { - | Level(level) => Some("Level " ++ (level |> Level.number |> string_of_int)) + | Level(level) => Some("Level " ++ (level->Level.number->string_of_int)) | AssignedToCoach(_) => Some("Assigned to") | NameOrEmail(_) => Some("Name or Email") } let value = t => switch t { - | Level(level) => level |> Level.name + | Level(level) => level->Level.name | AssignedToCoach(coach, currentCoachId) => - coach |> Coach.id == currentCoachId ? "Me" : coach |> Coach.name + coach->Coach.id == currentCoachId ? "Me" : coach->Coach.name | NameOrEmail(search) => search } let searchString = t => switch t { | Level(level) => - "level " ++ ((level |> Level.number |> string_of_int) ++ (" " ++ (level |> Level.name))) + "level " ++ ((level->Level.number->string_of_int) ++ (" " ++ (level->Level.name))) | AssignedToCoach(coach, currentCoachId) => - if coach |> Coach.id == currentCoachId { - (coach |> Coach.name) ++ " assigned to me" + if coach->Coach.id == currentCoachId { + (coach->Coach.name) ++ " assigned to me" } else { - "assigned to " ++ (coach |> Coach.name) + "assigned to " ++ (coach->Coach.name) } | NameOrEmail(search) => search } @@ -198,50 +198,50 @@ module Multiselect = MultiselectDropdown.Make(Selectable) let unselected = (levels, coaches, currentCoachId, state) => { let unselectedLevels = levels - |> Js.Array.filter(level => - state.filter.level |> OptionUtils.mapWithDefault( - selectedLevel => level |> Level.id != (selectedLevel |> Level.id), + ->Js.Array.filter(level => + state.filter.level->OptionUtils.mapWithDefault( + selectedLevel => level->Level.id != (selectedLevel->Level.id), true, ) ) - |> Array.map(Selectable.level) + ->Array.map(Selectable.level) let unselectedCoaches = coaches - |> Js.Array.filter(coach => - state.filter.coach |> OptionUtils.mapWithDefault( - selectedCoach => coach |> Coach.id != Coach.id(selectedCoach), + ->Js.Array.filter(coach => + state.filter.coach->OptionUtils.mapWithDefault( + selectedCoach => coach->Coach.id != Coach.id(selectedCoach), true, ) ) - |> Array.map(coach => Selectable.assignedToCoach(coach, currentCoachId)) + ->Array.map(coach => Selectable.assignedToCoach(coach, currentCoachId)) - let trimmedFilterString = state.filterString |> String.trim + let trimmedFilterString = state.filterString->String.trim let nameOrEmail = trimmedFilterString == "" ? [] : [Selectable.nameOrEmail(trimmedFilterString)] - unselectedLevels |> Array.append(unselectedCoaches) |> Array.append(nameOrEmail) + unselectedLevels->Array.append(unselectedCoaches)->Array.append(nameOrEmail) } let selected = (state, currentCoachId) => { let selectedLevel = - state.filter.level |> OptionUtils.mapWithDefault( + state.filter.level->OptionUtils.mapWithDefault( selectedLevel => [Selectable.level(selectedLevel)], [], ) let selectedCoach = - state.filter.coach |> OptionUtils.mapWithDefault( + state.filter.coach->OptionUtils.mapWithDefault( selectedCoach => [Selectable.assignedToCoach(selectedCoach, currentCoachId)], [], ) let selectedSearchString = - state.filter.nameOrEmail |> OptionUtils.mapWithDefault( + state.filter.nameOrEmail->OptionUtils.mapWithDefault( nameOrEmail => [Selectable.nameOrEmail(nameOrEmail)], [], ) - selectedLevel |> Array.append(selectedCoach) |> Array.append(selectedSearchString) + selectedLevel->Array.append(selectedCoach)->Array.append(selectedSearchString) } let onSelectFilter = (send, selectable) => @@ -267,24 +267,24 @@ let filterPlaceholder = state => let restoreFilterNotice = (send, currentCoach, message) =>
- {message |> str} + {message->str}
let restoreAssignedToMeFilter = (state, send, currentTeamCoach) => - currentTeamCoach |> OptionUtils.mapWithDefault(currentCoach => + currentTeamCoach->OptionUtils.mapWithDefault(currentCoach => switch state.filter.coach { | None => restoreFilterNotice(send, currentCoach, "Now showing all students in this course.") - | Some(selectedCoach) if selectedCoach |> Coach.id == Coach.id(currentCoach) => React.null + | Some(selectedCoach) if selectedCoach->Coach.id == Coach.id(currentCoach) => React.null | Some(selectedCoach) => restoreFilterNotice( send, currentCoach, - "Now showing students assigned to " ++ ((selectedCoach |> Coach.name) ++ "."), + "Now showing students assigned to " ++ ((selectedCoach->Coach.name) ++ "."), ) } , React.null) @@ -303,14 +303,14 @@ let computeInitialState = currentTeamCoach => { @react.component let make = (~levels, ~course, ~userId, ~teamCoaches, ~currentCoach) => { let (currentTeamCoach, _) = React.useState(() => - teamCoaches->Belt.Array.some(coach => coach |> Coach.id == (currentCoach |> Coach.id)) + teamCoaches->Belt.Array.some(coach => coach->Coach.id == (currentCoach->Coach.id)) ? Some(currentCoach) : None ) let (state, send) = React.useReducerWithMapState(reducer, currentTeamCoach, computeInitialState) - let courseId = course |> Course.id + let courseId = course->Course.id let url = ReasonReactRouter.useUrl() @@ -335,8 +335,8 @@ let make = (~levels, ~course, ~userId, ~teamCoaches, ~currentCoach) => {
Coach.id, state)} - selected={selected(state, currentCoach |> Coach.id)} + unselected={unselected(levels, teamCoaches, currentCoach->Coach.id, state)} + selected={selected(state, currentCoach->Coach.id)} onSelect={onSelectFilter(send)} onDeselect={onDeselectFilter(send)} value=state.filterString @@ -361,7 +361,7 @@ let make = (~levels, ~course, ~userId, ~teamCoaches, ~currentCoach) => { send(BeginLoadingMore) getTeams(send, courseId, Some(cursor), state.filter) }}> - {"Load More..." |> str} + {"Load More..."->str} | Reloading => React.null }} diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__StudentDetails.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__StudentDetails.res index 3f04c2c077..bc01411727 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__StudentDetails.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__StudentDetails.res @@ -20,45 +20,45 @@ type t = { let team = t => t.team -let student = t => t.team |> CoursesStudents__TeamInfo.studentWithId(t.id) +let student = t => t.team->CoursesStudents__TeamInfo.studentWithId(t.id) -let name = t => t |> student |> CoursesStudents__TeamInfo.studentName +let name = t => t->student->CoursesStudents__TeamInfo.studentName -let title = t => t |> student |> CoursesStudents__TeamInfo.studentTitle +let title = t => t->student->CoursesStudents__TeamInfo.studentTitle let email = t => t.email -let levelId = t => t.team |> CoursesStudents__TeamInfo.levelId +let levelId = t => t.team->CoursesStudents__TeamInfo.levelId let phone = t => t.phone let socialLinks = t => t.socialLinks -let avatarUrl = t => t |> student |> CoursesStudents__TeamInfo.studentAvatarUrl +let avatarUrl = t => t->student->CoursesStudents__TeamInfo.studentAvatarUrl let coachNotes = t => t.coachNotes -let teamCoachUserIds = t => t.team |> CoursesStudents__TeamInfo.coachUserIds +let teamCoachUserIds = t => t.team->CoursesStudents__TeamInfo.coachUserIds let makeAverageGrade = gradesData => - gradesData |> Js.Array.map(gradeData => { + gradesData->Js.Array.map(gradeData => { evaluationCriterionId: gradeData["evaluationCriterionId"], grade: gradeData["averageGrade"], }) -let totalTargets = t => t.totalTargets |> float_of_int +let totalTargets = t => t.totalTargets->float_of_int let gradeAsPercentage = ( averageGrade: averageGrade, evaluationCriterion: CoursesStudents__EvaluationCriterion.t, ) => { - let maxGrade = evaluationCriterion.maxGrade |> float_of_int - averageGrade.grade /. maxGrade *. 100.0 |> int_of_float |> string_of_int + let maxGrade = evaluationCriterion.maxGrade->float_of_int + averageGrade.grade /. maxGrade *. 100.0->int_of_float->string_of_int } -let targetsCompleted = t => t.targetsCompleted |> float_of_int +let targetsCompleted = t => t.targetsCompleted->float_of_int -let quizzesAttempted = t => t.quizScores |> Array.length |> string_of_int +let quizzesAttempted = t => t.quizScores->Array.length->string_of_int let evaluationCriteria = t => t.evaluationCriteria @@ -69,7 +69,7 @@ let completedLevelIds = t => t.completedLevelIds let gradeValue = averageGrade => averageGrade.grade let evaluationCriterionForGrade = (grade, evaluationCriteria, componentName) => - evaluationCriteria |> ArrayUtils.unsafeFind( + evaluationCriteria->ArrayUtils.unsafeFind( ec => CoursesStudents__EvaluationCriterion.id(ec) == grade.evaluationCriterionId, "Unable to find evaluation criterion with id: " ++ (grade.evaluationCriterionId ++ @@ -82,43 +82,43 @@ let addNewNote = (note, t) => { } let removeNote = (noteId, t) => { - let notes = t.coachNotes |> Js.Array.filter(note => CoursesStudents__CoachNote.id(note) != noteId) + let notes = t.coachNotes->Js.Array.filter(note => CoursesStudents__CoachNote.id(note) != noteId) {...t, coachNotes: notes} } let computeAverageQuizScore = quizScores => { let sumOfPercentageScores = quizScores - |> Array.map(quizScore => { - let fractionArray = quizScore |> String.split_on_char('/') |> Array.of_list + ->Array.map(quizScore => { + let fractionArray = quizScore->String.split_on_char('/')->Array.of_list let (numerator, denominator) = ( - fractionArray[0] |> float_of_string, - fractionArray[1] |> float_of_string, + fractionArray[0]->float_of_string, + fractionArray[1]->float_of_string, ) numerator /. denominator *. 100.0 }) - |> Js.Array.reduce((a, b) => a +. b, 0.0) - sumOfPercentageScores /. (quizScores |> Array.length |> float_of_int) + ->Js.Array.reduce((a, b) => a +. b, 0.0) + sumOfPercentageScores /. (quizScores->Array.length->float_of_int) } let averageQuizScore = t => - t.quizScores |> ArrayUtils.isEmpty ? None : Some(computeAverageQuizScore(t.quizScores)) + t.quizScores->ArrayUtils.isEmpty ? None : Some(computeAverageQuizScore(t.quizScores)) let makeFromJs = (id, studentDetails) => { id: id, email: studentDetails["email"], phone: studentDetails["phone"], - coachNotes: studentDetails["coachNotes"] |> Js.Array.map(note => - note |> CoursesStudents__CoachNote.makeFromJs + coachNotes: studentDetails["coachNotes"]->Js.Array.map(note => + note->CoursesStudents__CoachNote.makeFromJs ), - evaluationCriteria: studentDetails["evaluationCriteria"] |> CoursesStudents__EvaluationCriterion.makeFromJs, + evaluationCriteria: studentDetails["evaluationCriteria"]->CoursesStudents__EvaluationCriterion.makeFromJs, socialLinks: studentDetails["socialLinks"], totalTargets: studentDetails["totalTargets"], targetsCompleted: studentDetails["targetsCompleted"], quizScores: studentDetails["quizScores"], - averageGrades: studentDetails["averageGrades"] |> makeAverageGrade, + averageGrades: studentDetails["averageGrades"]->makeAverageGrade, completedLevelIds: studentDetails["completedLevelIds"], - team: studentDetails["team"] |> CoursesStudents__TeamInfo.makeFromJS, + team: studentDetails["team"]->CoursesStudents__TeamInfo.makeFromJS, } -let teamHasManyStudents = t => t.team |> CoursesStudents__TeamInfo.students |> Array.length > 1 +let teamHasManyStudents = t => t.team->CoursesStudents__TeamInfo.students->Array.length > 1 diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__StudentOverlay.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__StudentOverlay.res index c80f8a1c3e..d893793281 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__StudentOverlay.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__StudentOverlay.res @@ -73,18 +73,18 @@ module StudentDetailsQuery = %graphql(` let updateStudentDetails = (setState, studentId, details) => setState(state => { ...state, - studentData: Loaded(details |> StudentDetails.makeFromJs(studentId)), + studentData: Loaded(details->StudentDetails.makeFromJs(studentId)), }) let getStudentDetails = (studentId, setState, ()) => { setState(state => {...state, studentData: Loading}) StudentDetailsQuery.make(~studentId, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => { - response["studentDetails"] |> updateStudentDetails(setState, studentId) + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => { + response["studentDetails"]->updateStudentDetails(setState, studentId) Js.Promise.resolve() }) - |> ignore + ->ignore None } @@ -104,21 +104,21 @@ let doughnutChart = (color, percentage) => d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" /> - {percentage ++ "%" |> str} + {percentage ++ "%"->str} let targetsCompletionStatus = (targetsCompleted, totalTargets) => { let targetCompletionPercent = - targetsCompleted /. totalTargets *. 100.0 |> int_of_float |> string_of_int + targetsCompleted /. totalTargets *. 100.0->int_of_float->string_of_int
{doughnutChart("purple", targetCompletionPercent)} -

{"Total Targets Completed" |> str}

+

{"Total Targets Completed"->str}

- {(targetsCompleted |> int_of_float |> string_of_int) ++ + {(targetsCompleted->int_of_float->string_of_int) ++ ("/" ++ - ((totalTargets |> int_of_float |> string_of_int) ++ " Targets")) |> str} + ((totalTargets->int_of_float->string_of_int) ++ " Targets"))->str}

@@ -129,10 +129,10 @@ let quizPerformanceChart = (averageQuizScore, quizzesAttempted) => | Some(score) =>
- {doughnutChart("pink", score |> int_of_float |> string_of_int)} -

{"Average Quiz Score" |> str}

+ {doughnutChart("pink", score->int_of_float->string_of_int)} +

{"Average Quiz Score"->str}

- {quizzesAttempted ++ " Quizzes Attempted" |> str} + {quizzesAttempted ++ " Quizzes Attempted"->str}

@@ -144,18 +144,18 @@ let averageGradeCharts = ( averageGrades: array, ) => averageGrades - |> Array.map(grade => { + ->Array.map(grade => { let criterion = StudentDetails.evaluationCriterionForGrade( grade, evaluationCriteria, "CoursesStudents__StudentOverlay", ) - let passGrade = criterion |> CoursesStudents__EvaluationCriterion.passGrade |> float_of_int - let averageGrade = grade |> StudentDetails.gradeValue + let passGrade = criterion->CoursesStudents__EvaluationCriterion.passGrade->float_of_int + let averageGrade = grade->StudentDetails.gradeValue
CoursesStudents__EvaluationCriterion.id)} - key={criterion |> CoursesStudents__EvaluationCriterion.id} + (criterion->CoursesStudents__EvaluationCriterion.id)} + key={criterion->CoursesStudents__EvaluationCriterion.id} className="flex w-full lg:w-1/2 px-2 mt-2">
@@ -179,33 +179,33 @@ let averageGradeCharts = ( /> - {(grade.grade |> Js.Float.toString) ++ ("/" ++ (criterion.maxGrade |> string_of_int)) - |> str} + {(grade.grade->Js.Float.toString) ++ ("/" ++ (criterion.maxGrade->string_of_int)) + ->str}

- {criterion |> CoursesStudents__EvaluationCriterion.name |> str} + {criterion->CoursesStudents__EvaluationCriterion.name->str}

}) - |> React.array + ->React.array let test = (value, url) => { let tester = Js.Re.fromString(value) - url |> Js.Re.test_(tester) + url->Js.Re.test_(tester) } let socialLinkIconClass = url => switch url { - | url if url |> test("twitter") => "fab fa-twitter" - | url if url |> test("facebook") => "fab fa-facebook-f" - | url if url |> test("instagram") => "fab fa-instagram" - | url if url |> test("youtube") => "fab fa-youtube" - | url if url |> test("linkedin") => "fab fa-linkedin" - | url if url |> test("reddit") => "fab fa-reddit" - | url if url |> test("flickr") => "fab fa-flickr" - | url if url |> test("github") => "fab fa-github" + | url if url->test("twitter") => "fab fa-twitter" + | url if url->test("facebook") => "fab fa-facebook-f" + | url if url->test("instagram") => "fab fa-instagram" + | url if url->test("youtube") => "fab fa-youtube" + | url if url->test("linkedin") => "fab fa-linkedin" + | url if url->test("reddit") => "fab fa-reddit" + | url if url->test("flickr") => "fab fa-flickr" + | url if url->test("github") => "fab fa-github" | _unknownUrl => "fas fa-users" } @@ -213,16 +213,16 @@ let showSocialLinks = socialLinks =>
{socialLinks - |> Array.mapi((index, link) => + ->Array.mapi((index, link) => string_of_int} + key={index->string_of_int} target="_blank" href=link> ) - |> React.array} + ->React.array}
let personalInfo = studentDetails => @@ -230,19 +230,19 @@ let personalInfo = studentDetails =>
-

{studentDetails |> StudentDetails.email |> str}

+

{studentDetails->StudentDetails.email->str}

- {switch studentDetails |> StudentDetails.phone { + {switch studentDetails->StudentDetails.phone { | Some(phone) =>
-

{phone |> str}

+

{phone->str}

| None => React.null }}
{ - let socialLinks = studentDetails |> StudentDetails.socialLinks - socialLinks |> ArrayUtils.isNotEmpty ? showSocialLinks(socialLinks) : React.null + let socialLinks = studentDetails->StudentDetails.socialLinks + socialLinks->ArrayUtils.isNotEmpty ? showSocialLinks(socialLinks) : React.null }
@@ -260,25 +260,25 @@ let studentLevelClasses = (levelNumber, levelCompleted, currentLevelNumber) => { } let levelProgressBar = (levelId, levels, levelsCompleted) => { - let applicableLevels = levels |> Js.Array.filter(level => Level.number(level) != 0) + let applicableLevels = levels->Js.Array.filter(level => Level.number(level) != 0) let courseCompleted = - applicableLevels |> Array.for_all(level => levelsCompleted |> Array.mem(level |> Level.id)) + applicableLevels->Array.for_all(level => levelsCompleted->Array.mem(level->Level.id)) let currentLevelNumber = applicableLevels - |> ArrayUtils.unsafeFind( + ->ArrayUtils.unsafeFind( level => Level.id(level) == levelId, "Unable to find level with id" ++ (levelId ++ "in StudentOverlay"), ) - |> Level.number + ->Level.number
-
{"Level Progress" |> str}
+
{"Level Progress"->str}
{courseCompleted ?

- {`🎉` |> str} {"Course Completed!" |> str} + {`🎉`->str} {"Course Completed!"->str}

: React.null}
@@ -288,21 +288,21 @@ let levelProgressBar = (levelId, levels, levelsCompleted) => { courseCompleted ? "student-overlay__student-level-progress--completed" : "" )}> {applicableLevels - |> Level.sort - |> Array.map(level => { - let levelNumber = level |> Level.number - let levelCompleted = levelsCompleted |> Array.mem(level |> Level.id) + ->Level.sort + ->Array.map(level => { + let levelNumber = level->Level.number + let levelCompleted = levelsCompleted->Array.mem(level->Level.id)
  • Level.id} + key={level->Level.id} className={"flex-1 student-overlay__student-level " ++ studentLevelClasses(levelNumber, levelCompleted, currentLevelNumber)}> - {levelNumber |> string_of_int |> str} + {levelNumber->string_of_int->str}
  • }) - |> React.array} + ->React.array}
    @@ -324,30 +324,30 @@ let userInfo = (~key, ~avatarUrl, ~name, ~title) =>
    {CoursesStudents__TeamCoaches.avatar(avatarUrl, name)}
    -
    {name |> str}
    -
    {title |> str}
    +
    {name->str}
    +
    {title->str}
    let coachInfo = (teamCoaches, studentDetails) => { - let coaches = studentDetails |> StudentDetails.team |> TeamInfo.coaches(teamCoaches) + let coaches = studentDetails->StudentDetails.team->TeamInfo.coaches(teamCoaches) let title = - studentDetails |> StudentDetails.teamHasManyStudents ? "Team Coaches" : "Personal Coaches" + studentDetails->StudentDetails.teamHasManyStudents ? "Team Coaches" : "Personal Coaches" - coaches |> ArrayUtils.isNotEmpty + coaches->ArrayUtils.isNotEmpty ?
    -
    {title |> str}
    +
    {title->str}
    {coaches - |> Array.map(coach => + ->Array.map(coach => userInfo( - ~key=coach |> Coach.userId, - ~avatarUrl=coach |> Coach.avatarUrl, - ~name=coach |> Coach.name, - ~title=coach |> Coach.title, + ~key=coach->Coach.userId, + ~avatarUrl=coach->Coach.avatarUrl, + ~name=coach->Coach.name, + ~title=coach->Coach.title, ) ) - |> React.array} + ->React.array}
    : React.null } @@ -355,58 +355,58 @@ let coachInfo = (teamCoaches, studentDetails) => { let navigateToStudent = (setState, _event) => setState(_ => initialState) let otherTeamMembers = (setState, studentId, studentDetails) => - if studentDetails |> StudentDetails.teamHasManyStudents { + if studentDetails->StudentDetails.teamHasManyStudents {
    -
    {"Other Team Members" |> str}
    +
    {"Other Team Members"->str}
    {studentDetails - |> StudentDetails.team - |> TeamInfo.otherStudents(studentId) - |> Array.map(student => { - let path = "/students/" ++ ((student |> TeamInfo.studentId) ++ "/report") + ->StudentDetails.team + ->TeamInfo.otherStudents(studentId) + ->Array.map(student => { + let path = "/students/" ++ ((student->TeamInfo.studentId) ++ "/report") TeamInfo.studentId}> + key={student->TeamInfo.studentId}> {userInfo( - ~key=student |> TeamInfo.studentId, - ~avatarUrl=student |> TeamInfo.studentAvatarUrl, - ~name=student |> TeamInfo.studentName, - ~title=student |> TeamInfo.studentTitle, + ~key=student->TeamInfo.studentId, + ~avatarUrl=student->TeamInfo.studentAvatarUrl, + ~name=student->TeamInfo.studentName, + ~title=student->TeamInfo.studentTitle, )} }) - |> React.array} + ->React.array}
    } else { React.null } let inactiveWarning = teamInfo => { - let warning = switch (teamInfo |> TeamInfo.droppedOutAt, teamInfo |> TeamInfo.accessEndsAt) { + let warning = switch (teamInfo->TeamInfo.droppedOutAt, teamInfo->TeamInfo.accessEndsAt) { | (Some(droppedOutAt), _) => Some( "This student dropped out of the course on " ++ - ((droppedOutAt |> DateTime.format(DateTime.OnlyDate)) ++ + ((droppedOutAt->DateTime.format(DateTime.OnlyDate)) ++ "."), ) | (None, Some(accessEndsAt)) => - accessEndsAt |> DateFns.isPast + accessEndsAt->DateFns.isPast ? Some( "This student's access to the course ended on " ++ - ((accessEndsAt |> DateTime.format(DateTime.OnlyDate)) ++ + ((accessEndsAt->DateTime.format(DateTime.OnlyDate)) ++ "."), ) : None | (None, None) => None } - warning |> OptionUtils.mapWithDefault( + warning->OptionUtils.mapWithDefault( warning =>
    - {warning |> str} + {warning->str}
    , React.null, ) @@ -438,46 +438,46 @@ let make = (~courseId, ~studentId, ~levels, ~userId, ~teamCoaches) => {
    - {switch studentDetails |> StudentDetails.avatarUrl { + {switch studentDetails->StudentDetails.avatarUrl { | Some(avatarUrl) => | None => - StudentDetails.name} className="object-cover" /> + StudentDetails.name} className="object-cover" /> }}

    - {studentDetails |> StudentDetails.name |> str} + {studentDetails->StudentDetails.name->str}

    - {studentDetails |> StudentDetails.title |> str} + {studentDetails->StudentDetails.title->str}

    {personalInfo(studentDetails)} - {inactiveWarning(studentDetails |> StudentDetails.team)} + {inactiveWarning(studentDetails->StudentDetails.team)}
    {levelProgressBar( - studentDetails |> StudentDetails.levelId, + studentDetails->StudentDetails.levelId, levels, - studentDetails |> StudentDetails.completedLevelIds, + studentDetails->StudentDetails.completedLevelIds, )}
    -
    {"Targets Overview" |> str}
    +
    {"Targets Overview"->str}
    {targetsCompletionStatus( - studentDetails |> StudentDetails.targetsCompleted, - studentDetails |> StudentDetails.totalTargets, + studentDetails->StudentDetails.targetsCompleted, + studentDetails->StudentDetails.totalTargets, )} {quizPerformanceChart( - studentDetails |> StudentDetails.averageQuizScore, - studentDetails |> StudentDetails.quizzesAttempted, + studentDetails->StudentDetails.averageQuizScore, + studentDetails->StudentDetails.quizzesAttempted, )}
    - {studentDetails |> StudentDetails.averageGrades |> ArrayUtils.isNotEmpty + {studentDetails->StudentDetails.averageGrades->ArrayUtils.isNotEmpty ?
    -
    {"Average Grades" |> str}
    +
    {"Average Grades"->str}
    {averageGradeCharts( - studentDetails |> StudentDetails.evaluationCriteria, - studentDetails |> StudentDetails.averageGrades, + studentDetails->StudentDetails.evaluationCriteria, + studentDetails->StudentDetails.averageGrades, )}
    @@ -497,7 +497,7 @@ let make = (~courseId, ~studentId, ~levels, ~userId, ~teamCoaches) => { | Notes => "border-b-3 border-primary-500 text-primary-500 -mb-px" | Submissions => "hover:bg-gray-200 hover:text-gray-900" }}> - {"Notes" |> str} + {"Notes"->str}
  • setSelectedTab(Submissions, setState)} @@ -506,7 +506,7 @@ let make = (~courseId, ~studentId, ~levels, ~userId, ~teamCoaches) => { | Submissions => "border-b-3 border-primary-500 text-primary-500 -mb-px" | Notes => "hover:bg-gray-200 hover:text-gray-900" }}> - {"Submissions" |> str} + {"Submissions"->str}
  • @@ -515,7 +515,7 @@ let make = (~courseId, ~studentId, ~levels, ~userId, ~teamCoaches) => { | Notes => StudentDetails.coachNotes} + coachNotes={studentDetails->StudentDetails.coachNotes} addNoteCB={addNoteCB(setState, studentDetails)} userId removeNoteCB={removeNoteCB(setState, studentDetails)} diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__Submission.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__Submission.res index 2430d3966f..3feca58dca 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__Submission.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__Submission.res @@ -21,8 +21,8 @@ let levelId = t => t.levelId let title = t => t.title let sort = submissions => - submissions |> ArrayUtils.copyAndSort((x, y) => - DateFns.differenceInSeconds(y.createdAt, x.createdAt) |> int_of_float + submissions->ArrayUtils.copyAndSort((x, y) => + DateFns.differenceInSeconds(y.createdAt, x.createdAt)->int_of_float ) let failed = t => @@ -31,15 +31,15 @@ let failed = t => | None => true } -let createdAtPretty = t => t.createdAt |> DateFns.format("MMMM D, YYYY") +let createdAtPretty = t => t.createdAt->DateFns.format("MMMM D, YYYY") let makeFromJs = submissions => - submissions |> Js.Array.map(submission => + submissions->Js.Array.map(submission => switch submission { | Some(submission) => - let createdAt = submission["createdAt"] |> Json.Decode.string |> DateFns.parseString + let createdAt = submission["createdAt"]->Json.Decode.string->DateFns.parseString let passedAt = switch submission["passedAt"] { - | Some(passedAt) => Some(passedAt |> Json.Decode.string |> DateFns.parseString) + | Some(passedAt) => Some(passedAt->Json.Decode.string->DateFns.parseString) | None => None } list{ diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__SubmissionsList.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__SubmissionsList.res index 0cc571c7d3..f5dbfac861 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__SubmissionsList.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__SubmissionsList.res @@ -38,8 +38,8 @@ let updateStudentSubmissions = ( let updatedSubmissions = Array.append( switch nodes { | None => [] - | Some(submissionsArray) => submissionsArray |> Submission.makeFromJs - } |> ArrayUtils.flatten, + | Some(submissionsArray) => submissionsArray->Submission.makeFromJs + }->ArrayUtils.flatten, submissions, ) @@ -60,9 +60,9 @@ let getStudentSubmissions = (studentId, cursor, setState, submissions, updateSub | Some(cursor) => StudentSubmissionsQuery.make(~studentId, ~after=cursor, ()) | None => StudentSubmissionsQuery.make(~studentId, ()) } - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => { - response["studentSubmissions"]["nodes"] |> updateStudentSubmissions( + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => { + response["studentSubmissions"]["nodes"]->updateStudentSubmissions( setState, updateSubmissionsCB, response["studentSubmissions"]["pageInfo"]["endCursor"], @@ -71,70 +71,70 @@ let getStudentSubmissions = (studentId, cursor, setState, submissions, updateSub ) Js.Promise.resolve() }) - |> ignore + ->ignore } let showSubmissionStatus = failed => failed ?
    - {"Failed" |> str} + {"Failed"->str}
    :
    - {"Passed" |> str} + {"Passed"->str}
    let submissionCardClasses = submission => "flex flex-col md:flex-row items-start md:items-center justify-between bg-white border-l-3 p-3 md:py-6 md:px-5 mt-4 cursor-pointer rounded-r-lg shadow hover:border-primary-500 hover:text-primary-500 hover:shadow-md " ++ ( - submission |> Submission.failed ? "border-red-500" : "border-green-500" + submission->Submission.failed ? "border-red-500" : "border-green-500" ) let showSubmission = (submissions, levels) =>
    {submissions - |> Submission.sort - |> Array.map(submission => + ->Submission.sort + ->Array.map(submission => Submission.id} - href={"/submissions/" ++ (submission |> Submission.id)} + key={submission->Submission.id} + href={"/submissions/" ++ (submission->Submission.id)} target="_blank">
    Submission.id} - ariaLabel={"student-submission-card-" ++ (submission |> Submission.id)} + key={submission->Submission.id} + ariaLabel={"student-submission-card-" ++ (submission->Submission.id)} className={submissionCardClasses(submission)}>
    {submission - |> Submission.levelId - |> Level.unsafeLevelNumber(levels, "StudentSubmissionsList") - |> str} + ->Submission.levelId + ->Level.unsafeLevelNumber(levels, "StudentSubmissionsList") + ->str} - {submission |> Submission.title |> str} + {submission->Submission.title->str}
    - {"Submitted on " ++ (submission |> Submission.createdAtPretty) |> str} + {"Submitted on " ++ (submission->Submission.createdAtPretty)->str}
    - {showSubmissionStatus(submission |> Submission.failed)} + {showSubmissionStatus(submission->Submission.failed)}
    ) - |> React.array} + ->React.array}
    let showSubmissions = (submissions, levels) => - submissions |> ArrayUtils.isEmpty + submissions->ArrayUtils.isEmpty ?
    - {"No Reviewed Submission" |> str} + {"No Reviewed Submission"->str}
    @@ -170,7 +170,7 @@ let make = (~studentId, ~levels, ~submissions, ~updateSubmissionsCB) => { submissions, updateSubmissionsCB, )}> - {"Load More..." |> str} + {"Load More..."->str} }
    | FullyLoaded(submissions) => showSubmissions(submissions, levels) diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__TeamCoaches.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__TeamCoaches.res index 5c5b2843eb..9f217d4543 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__TeamCoaches.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__TeamCoaches.res @@ -28,20 +28,20 @@ let make = ( ~className, ~coaches, ) => - if coaches |> ArrayUtils.isNotEmpty { + if coaches->ArrayUtils.isNotEmpty { let listedCoaches = - coaches |> Array.length <= 4 ? coaches : coaches |> Js.Array.slice(~start=0, ~end_=3) + coaches->Array.length <= 4 ? coaches : coaches->Js.Array.slice(~start=0, ~end_=3) - let otherCoaches = if coaches |> Array.length > 4 { + let otherCoaches = if coaches->Array.length > 4 { let names = coaches - |> Js.Array.sliceFrom(3) - |> Js.Array.map(coach => -
    UserProxy.userId}> {coach |> UserProxy.name |> str}
    + ->Js.Array.sliceFrom(3) + ->Js.Array.map(coach => +
    UserProxy.userId}> {coach->UserProxy.name->str}
    ) - |> React.array + ->React.array - let count = (coaches |> Array.length) - 3 + let count = (coaches->Array.length) - 3 Some((names, count)) } else { None @@ -51,25 +51,25 @@ let make = (
    title
    {listedCoaches - |> Array.map(coach => + ->Array.map(coach => UserProxy.name |> str} + tip={coach->UserProxy.name->str} className="-mr-1" - key={coach |> UserProxy.userId}> + key={coach->UserProxy.userId}> {avatar( ~size=(defaultAvatarSize, mdAvatarSize), - coach |> UserProxy.avatarUrl, - coach |> UserProxy.name, + coach->UserProxy.avatarUrl, + coach->UserProxy.name, )} ) - |> React.array} - {otherCoaches |> OptionUtils.mapWithDefault( + ->React.array} + {otherCoaches->OptionUtils.mapWithDefault( ((names, count)) => string_of_int)} + name={"+ " ++ (count->string_of_int)} className={avatarClasses((defaultAvatarSize, mdAvatarSize))} colors=("#EEE", "#000") /> diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__TeamInfo.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__TeamInfo.res index c936cb8d25..d80a0b04d0 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__TeamInfo.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__TeamInfo.res @@ -39,7 +39,7 @@ let droppedOutAt = t => t.droppedOutAt let accessEndsAt = t => t.accessEndsAt let studentWithId = (studentId, t) => - t.students |> ArrayUtils.unsafeFind( + t.students->ArrayUtils.unsafeFind( (student: student) => student.id == studentId, "Could not find student with ID " ++ (studentId ++ (" in team with ID " ++ t.id)), ) @@ -63,7 +63,7 @@ let make = (~id, ~name, ~levelId, ~students, ~coachUserIds, ~droppedOutAt, ~acce let makeFromJS = teamDetails => { let students = - teamDetails["students"] |> Array.map(student => + teamDetails["students"]->Array.map(student => makeStudent( ~id=student["id"], ~name=student["name"], @@ -78,8 +78,8 @@ let makeFromJS = teamDetails => { ~levelId=teamDetails["levelId"], ~students, ~coachUserIds=teamDetails["coachUserIds"], - ~droppedOutAt=teamDetails["droppedOutAt"] |> OptionUtils.map(DateTime.decode), - ~accessEndsAt=teamDetails["accessEndsAt"] |> OptionUtils.map(DateTime.decode), + ~droppedOutAt=teamDetails["droppedOutAt"]->OptionUtils.map(DateTime.decode), + ~accessEndsAt=teamDetails["accessEndsAt"]->OptionUtils.map(DateTime.decode), ) } @@ -87,9 +87,9 @@ let makeArrayFromJs = detailsOfTeams => detailsOfTeams->Belt.Array.keepMap(OptionUtils.map(makeFromJS)) let otherStudents = (studentId, t) => - t.students |> Js.Array.filter((student: student) => student.id != studentId) + t.students->Js.Array.filter((student: student) => student.id != studentId) let coaches = (allTeamCoaches, t) => - allTeamCoaches |> Js.Array.filter(teamCoach => - t |> coachUserIds |> Array.mem(teamCoach |> UserProxy.userId) + allTeamCoaches->Js.Array.filter(teamCoach => + t->coachUserIds->Array.mem(teamCoach->UserProxy.userId) ) diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__TeamsList.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__TeamsList.res index 37428a3d75..cfb72da449 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__TeamsList.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/CoursesStudents__TeamsList.res @@ -7,102 +7,102 @@ let str = React.string let levelInfo = (levelId, levels) => -
    {"Level" |> str}
    +
    {"Level"->str}
    {levels - |> ArrayUtils.unsafeFind( + ->ArrayUtils.unsafeFind( (l: Level.t) => l.id == levelId, "Unable to find level with id: " ++ (levelId ++ "in CoursesStudents__TeamsList"), ) - |> Level.number - |> string_of_int - |> str} + ->Level.number + ->string_of_int + ->str}
    let showStudent = (team, levels, teamCoaches) => { let student = TeamInfo.students(team)[0] TeamInfo.studentId) ++ "/report")} - key={student |> TeamInfo.studentId} - ariaLabel={"student-card-" ++ (student |> TeamInfo.studentId)} + href={"/students/" ++ ((student->TeamInfo.studentId) ++ "/report")} + key={student->TeamInfo.studentId} + ariaLabel={"student-card-" ++ (student->TeamInfo.studentId)} className="flex md:flex-row justify-between bg-white mt-4 rounded-lg shadow cursor-pointer hover:border-primary-500 hover:text-primary-500 hover:shadow-md">
    {CoursesStudents__TeamCoaches.avatar( - student |> TeamInfo.studentAvatarUrl, - student |> TeamInfo.studentName, + student->TeamInfo.studentAvatarUrl, + student->TeamInfo.studentName, )}

    - {student |> TeamInfo.studentName |> str} + {student->TeamInfo.studentName->str}

    - {student |> TeamInfo.studentTitle |> str} + {student->TeamInfo.studentTitle->str}

    TeamInfo.id)} + ariaLabel={"team-level-info-" ++ (team->TeamInfo.id)} className="w-2/5 flex items-center justify-end md:justify-between p-3 md:p-4"> {"Personal Coaches" |> str}
    } + title={
    {"Personal Coaches"->str}
    } className="hidden md:inline-block" coaches=teamCoaches /> - {levelInfo(team |> TeamInfo.levelId, levels)} + {levelInfo(team->TeamInfo.levelId, levels)}
    } let showTeam = (team, levels, teamCoaches) =>
    TeamInfo.id} - ariaLabel={"Info of team " ++ (team |> TeamInfo.id)} + key={team->TeamInfo.id} + ariaLabel={"Info of team " ++ (team->TeamInfo.id)} className="flex shadow bg-white rounded-lg mt-4 overflow-hidden flex-col-reverse md:flex-row">
    {team - |> TeamInfo.students - |> Array.map(student => + ->TeamInfo.students + ->Array.map(student => TeamInfo.studentId) ++ "/report")} - key={student |> TeamInfo.studentId} - ariaLabel={"student-card-" ++ (student |> TeamInfo.studentId)} + href={"/students/" ++ ((student->TeamInfo.studentId) ++ "/report")} + key={student->TeamInfo.studentId} + ariaLabel={"student-card-" ++ (student->TeamInfo.studentId)} className="flex items-center bg-white cursor-pointer hover:border-primary-500 hover:text-primary-500 hover:bg-gray-100">
    {CoursesStudents__TeamCoaches.avatar( - student |> TeamInfo.studentAvatarUrl, - student |> TeamInfo.studentName, + student->TeamInfo.studentAvatarUrl, + student->TeamInfo.studentName, )}

    - {student |> TeamInfo.studentName |> str} + {student->TeamInfo.studentName->str}

    - {student |> TeamInfo.studentTitle |> str} + {student->TeamInfo.studentTitle->str}

    ) - |> React.array} + ->React.array}
    -

    {"Team" |> str}

    -

    {team |> TeamInfo.name |> str}

    +

    {"Team"->str}

    +

    {team->TeamInfo.name->str}

    {"Team Coaches" |> str}
    } + title={
    {"Team Coaches"->str}
    } className="hidden md:inline-block mt-3" coaches=teamCoaches />
    -
    TeamInfo.id)} className="flex-shrink-0"> - {levelInfo(team |> TeamInfo.levelId, levels)} +
    TeamInfo.id)} className="flex-shrink-0"> + {levelInfo(team->TeamInfo.levelId, levels)}
    @@ -110,19 +110,19 @@ let showTeam = (team, levels, teamCoaches) => @react.component let make = (~levels, ~teams, ~teamCoaches) =>
    - {teams |> ArrayUtils.isEmpty + {teams->ArrayUtils.isEmpty ?
    - {"No teams to show" |> str} + {"No teams to show"->str}
    : teams - |> Array.map(team => { - let coaches = team |> TeamInfo.coaches(teamCoaches) + ->Array.map(team => { + let coaches = team->TeamInfo.coaches(teamCoaches) - Array.length(team |> TeamInfo.students) == 1 + Array.length(team->TeamInfo.students) == 1 ? showStudent(team, levels, coaches) : showTeam(team, levels, coaches) }) - |> React.array} + ->React.array}
    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/SubmissionChecklistItem.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/SubmissionChecklistItem.res index 2b261187f7..0c361b7812 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/SubmissionChecklistItem.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/SubmissionChecklistItem.res @@ -33,7 +33,7 @@ let make = (~title, ~result, ~status) => {title: title, result: result, status: let makeFile = (~name, ~url, ~id) => {name: name, url: url, id: id} let makeFiles = data => - data |> Js.Array.map(a => makeFile(~url=a["url"], ~name=a["title"], ~id=a["id"])) + data->Js.Array.map(a => makeFile(~url=a["url"], ~name=a["title"], ~id=a["id"])) let makeResult = (result, kind, files) => switch kind { @@ -62,7 +62,7 @@ let makeStatus = data => } let makeArrayFromJs = (files, checklist) => - checklist |> Js.Array.map(c => + checklist->Js.Array.map(c => make( ~title=c["title"], ~result=makeResult(c["result"], c["kind"], makeFiles(files)), @@ -73,23 +73,23 @@ let makeArrayFromJs = (files, checklist) => let decodeFile = json => { open Json.Decode { - name: json |> field("name", string), - url: json |> field("url", string), - id: json |> field("id", string), + name: json->field("name", string), + url: json->field("url", string), + id: json->field("id", string), } } let decode = (files, json) => { open Json.Decode { - result: makeResult(json |> field("result", string), json |> field("kind", string), files), - status: makeStatus(json |> field("status", string)), - title: json |> field("title", string), + result: makeResult(json->field("result", string), json->field("kind", string), files), + status: makeStatus(json->field("status", string)), + title: json->field("title", string), } } let updateStatus = (checklist, index, status) => - checklist |> Array.mapi((i, t) => + checklist->Array.mapi((i, t) => i == index ? make(~title=t.title, ~result=t.result, ~status) : t ) @@ -127,15 +127,15 @@ let encodeStatus = t => let encode = t => { open Json.Encode object_(list{ - ("title", t.title |> string), - ("kind", encodeKind(t) |> string), - ("status", encodeStatus(t) |> string), - ("result", encodeResult(t) |> string), + ("title", t.title->string), + ("kind", encodeKind(t)->string), + ("status", encodeStatus(t)->string), + ("result", encodeResult(t)->string), }) } let encodeArray = checklist => - checklist |> { + checklist->{ open Json.Encode array(encode) } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/SubmissionChecklistItemShow.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/SubmissionChecklistItemShow.res index 60fd0249ce..3f80f8fd12 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/SubmissionChecklistItemShow.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/SubmissionChecklistItemShow.res @@ -16,22 +16,22 @@ let kindIconClasses = result => let showFiles = files => let showlink = link => @@ -41,7 +41,7 @@ let showlink = link => className="max-w-fc mt-1 mr-3 flex border overflow-hidden rounded hover:shadow-md border-indigo-400 bg-white text-indigo-700 hover:border-blue-600 hover:text-indigo-800"> - {link |> str} + {link->str} @@ -61,11 +61,11 @@ let showStatus = status => switch (status: ChecklistItem.status) { | Passed =>
    - {"Correct" |> str} + {"Correct"->str}
    | Failed =>
    - {"Incorrect" |> str} + {"Incorrect"->str}
    | NoAnswer => React.null } @@ -91,8 +91,8 @@ let statusButtonIcon = bool => let statusButtonOnClick = (bool, callback, checklist, index, _event) => bool - ? callback(checklist |> ChecklistItem.makeNoAnswer(index)) - : callback(checklist |> ChecklistItem.makeFailed(index)) + ? callback(checklist->ChecklistItem.makeNoAnswer(index)) + : callback(checklist->ChecklistItem.makeFailed(index)) let statusButton = (index, status, callback, checklist) =>
    @@ -103,12 +103,12 @@ let statusButton = (index, status, callback, checklist) => - {"Mark as incorrect" |> str} + {"Mark as incorrect"->str}
    let computeShowResult = (pending, checklistItem) => - switch (pending, checklistItem |> ChecklistItem.status) { + switch (pending, checklistItem->ChecklistItem.status) { | (true, NoAnswer | Passed | Failed) => true | (false, Failed) => true | (false, NoAnswer | Passed) => false @@ -133,17 +133,17 @@ let make = (~index, ~checklistItem, ~updateChecklistCB, ~checklist, ~pending) => newShowResult == showResult ? () : setShowResult(_ => newShowResult) None }, [updateChecklistCB]) - let status = checklistItem |> ChecklistItem.status + let status = checklistItem->ChecklistItem.status
    ChecklistItem.title} + ariaLabel={checklistItem->ChecklistItem.title} onClick={_ => setShowResult(_ => true)}>
    {statusIcon(updateChecklistCB, status)} - ChecklistItem.result)} /> -

    {checklistItem |> ChecklistItem.title |> str}

    + ChecklistItem.result)} /> +

    {checklistItem->ChecklistItem.title->str}

    {showResult ? showStatus(status) : } @@ -152,11 +152,11 @@ let make = (~index, ~checklistItem, ~updateChecklistCB, ~checklist, ~pending) => {showResult ?
    - {switch checklistItem |> ChecklistItem.result { - | ShortText(text) =>
    {text |> str}
    + {switch checklistItem->ChecklistItem.result { + | ShortText(text) =>
    {text->str}
    | LongText(markdown) => | Link(link) => showlink(link) - | MultiChoice(text) =>
    {text |> str}
    + | MultiChoice(text) =>
    {text->str}
    | Files(files) => showFiles(files) }}
    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/courses/SubmissionChecklistShow.res b/tests/syntax_tests/data/idempotency/pupilfirst/courses/SubmissionChecklistShow.res index 405b2eadfc..4fb444b4b4 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/courses/SubmissionChecklistShow.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/courses/SubmissionChecklistShow.res @@ -3,13 +3,13 @@ let str = React.string @react.component let make = (~checklist, ~updateChecklistCB, ~pending) =>
    - {checklist |> ArrayUtils.isEmpty - ?
    {"Target was marked as complete." |> str}
    + {checklist->ArrayUtils.isEmpty + ?
    {"Target was marked as complete."->str}
    : checklist - |> Array.mapi((index, checklistItem) => + ->Array.mapi((index, checklistItem) => string_of_int} index checklistItem updateChecklistCB checklist pending + key={index->string_of_int} index checklistItem updateChecklistCB checklist pending /> ) - |> React.array} + ->React.array}
    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/home/HomeStyleguide__MarkdownSyntaxHighlightingPreview.res b/tests/syntax_tests/data/idempotency/pupilfirst/home/HomeStyleguide__MarkdownSyntaxHighlightingPreview.res index 394d611505..189625ddc8 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/home/HomeStyleguide__MarkdownSyntaxHighlightingPreview.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/home/HomeStyleguide__MarkdownSyntaxHighlightingPreview.res @@ -133,7 +133,7 @@ let renderedMarkdown = language => { }
    -

    {title |> str}

    +

    {title->str}

    } @@ -157,14 +157,14 @@ let make = () => { let (language, setLanguage) = React.useState(() => ReasonML)
    - {"Select a language to preview:" |> str} + {"Select a language to preview:"->str} {renderedMarkdown(language)}
    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/layouts/SchoolAdminNavbar__Course.res b/tests/syntax_tests/data/idempotency/pupilfirst/layouts/SchoolAdminNavbar__Course.res index 45559f8e6d..4f11ad2f8b 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/layouts/SchoolAdminNavbar__Course.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/layouts/SchoolAdminNavbar__Course.res @@ -10,10 +10,10 @@ let name = t => t.name let decode = json => { open Json.Decode { - id: json |> field("id", string), - name: json |> field("name", string), + id: json->field("id", string), + name: json->field("name", string), } } let sort = courses => - courses |> List.sort((c1, c2) => Js.String.localeCompare(c2 |> name, c1 |> name) |> int_of_float) + courses->List.sort((c1, c2) => Js.String.localeCompare(c2->name, c1->name)->int_of_float) diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/layouts/SchoolAdminNavbar__CourseDropdown.res b/tests/syntax_tests/data/idempotency/pupilfirst/layouts/SchoolAdminNavbar__CourseDropdown.res index 6b6fc3944c..678e06881a 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/layouts/SchoolAdminNavbar__CourseDropdown.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/layouts/SchoolAdminNavbar__CourseDropdown.res @@ -3,7 +3,7 @@ open SchoolAdminNavbar__Types let str = React.string let handleClick = (setShowDropdown, event) => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault setShowDropdown(showDropdown => !showDropdown) } @@ -11,8 +11,8 @@ let handleClick = (setShowDropdown, event) => { let make = (~courses, ~currentCourseId) => { let (showDropdown, setShowDropdown) = React.useState(() => false) let currentCourse = - courses |> ListUtils.unsafeFind( - course => course |> Course.id == currentCourseId, + courses->ListUtils.unsafeFind( + course => course->Course.id == currentCourseId, "Could not find currentCourse with ID " ++ currentCourseId, ) @@ -20,11 +20,11 @@ let make = (~courses, ~currentCourseId) => {
    @@ -32,18 +32,18 @@ let make = (~courses, ~currentCourseId) => { ?
    {courses - |> Course.sort - |> List.filter(course => course |> Course.id != (currentCourse |> Course.id)) - |> List.map(course => + ->Course.sort + ->List.filter(course => course->Course.id != (currentCourse->Course.id)) + ->List.map(course => Course.id} - href={"/school/courses/" ++ ((course |> Course.id) ++ "/curriculum")}> - {course |> Course.name |> str} + key={course->Course.id} + href={"/school/courses/" ++ ((course->Course.id) ++ "/curriculum")}> + {course->Course.name->str} ) - |> Array.of_list - |> React.array} + ->Array.of_list + ->React.array}
    : React.null}
    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/layouts/SchoolAdminNavbar__Root.res b/tests/syntax_tests/data/idempotency/pupilfirst/layouts/SchoolAdminNavbar__Root.res index 419c20e321..5c5b82b7ce 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/layouts/SchoolAdminNavbar__Root.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/layouts/SchoolAdminNavbar__Root.res @@ -61,7 +61,7 @@ let bottomLink = (path, shrunk, iconClasses, text) => {
  • - {shrunk ? React.null : {text |> str} } + {shrunk ? React.null : {text->str} }
  • } @@ -75,7 +75,7 @@ let topLink = (selectedOption, currentOption, path, shrunk, iconClasses, text) = let title = shrunk ? Some(text) : None - {shrunk ? React.null : {text |> str} } + {shrunk ? React.null : {text->str} } } @@ -83,7 +83,7 @@ let secondaryNavOption = (path, currentSelection, inspectedSelection, text) => { let defaultClasses = "flex text-indigo-800 text-sm py-3 px-4 hover:bg-gray-400 focus:bg-gray-400 font-semibold rounded items-center my-1" let classes = defaultClasses ++ (currentSelection == inspectedSelection ? " bg-gray-400" : "") -
  • {text |> str}
  • +
  • {text->str}
  • } let secondaryNav = (courses, userRole, selectedOption) => @@ -136,7 +136,7 @@ let secondaryNav = (courses, userRole, selectedOption) => Authors, "Authors", ), - ] |> React.array + ]->React.array | CourseAuthor => React.null }} {secondaryNavOption( @@ -200,7 +200,7 @@ let make = (~schoolName, ~schoolLogoPath, ~schoolIconPath, ~courses, ~isCourseAu | _ => Rollbar.critical( "Unknown path encountered by SA navbar: " ++ - (url.path |> Array.of_list |> Js.Array.joinWith("/")), + (url.path->Array.of_list->Js.Array.joinWith("/")), ) raise(UnknownPathEncountered(url.path)) } @@ -267,17 +267,17 @@ let make = (~schoolName, ~schoolLogoPath, ~schoolIconPath, ~courses, ~isCourseAu ? React.null : }
  • @@ -303,11 +303,11 @@ let make = (~schoolName, ~schoolLogoPath, ~schoolIconPath, ~courses, ~isCourseAu rel="nofollow" href="/users/sign_out"> - {shrunk ? React.null : {"Sign Out" |> str} } + {shrunk ? React.null : {"Sign Out"->str} }
  • , - selectedOption |> secondaryNav(courses, userRole), - ] |> React.array + selectedOption->secondaryNav(courses, userRole), + ]->React.array } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/layouts/StudentCourse__Course.res b/tests/syntax_tests/data/idempotency/pupilfirst/layouts/StudentCourse__Course.res index ea97fd1da3..8c31efa083 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/layouts/StudentCourse__Course.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/layouts/StudentCourse__Course.res @@ -6,8 +6,8 @@ type t = { let decode = json => { open Json.Decode { - id: json |> field("id", string), - name: json |> field("name", string), + id: json->field("id", string), + name: json->field("name", string), } } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/layouts/StudentCourse__Header.res b/tests/syntax_tests/data/idempotency/pupilfirst/layouts/StudentCourse__Header.res index 2137304708..f554c39345 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/layouts/StudentCourse__Header.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/layouts/StudentCourse__Header.res @@ -6,16 +6,16 @@ module Course = StudentCourse__Course let courseOptions = courses => courses - |> List.map(course => { - let courseId = course |> Course.id + ->List.map(course => { + let courseId = course->Course.id - {course |> Course.name |> str} + {course->Course.name->str} }) - |> Array.of_list + ->Array.of_list let courseDropdown = (currentCourse, otherCourses) =>
    @@ -24,7 +24,7 @@ let courseDropdown = (currentCourse, otherCourses) =>
    - {currentCourse |> Course.name |> str} + {currentCourse->Course.name->str}
    | otherCourses => @@ -32,7 +32,7 @@ let courseDropdown = (currentCourse, otherCourses) =>
    @@ -37,11 +37,11 @@ let signInLink = () => - {"Sign In" |> str} + {"Sign In"->str}
    -let isMobile = () => Webapi.Dom.window |> Webapi.Dom.Window.innerWidth < 768 +let isMobile = () => Webapi.Dom.window->Webapi.Dom.Window.innerWidth < 768 let headerLinks = (links, isLoggedIn) => { let (visibleLinks, dropdownLinks) = switch (links, isMobile()) { @@ -52,11 +52,11 @@ let headerLinks = (links, isLoggedIn) => { switch visibleLinks { | visibleLinks => - (visibleLinks |> List.mapi((index, l) => headerLink(index |> string_of_int, l))) + (visibleLinks->List.mapi((index, l) => headerLink(index->string_of_int, l))) ->List.append(list{}) ->List.append(list{isLoggedIn ? signOutLink() : signInLink()}) - |> Array.of_list - |> ReasonReact.array + ->Array.of_list + ->ReasonReact.array } } @@ -66,7 +66,7 @@ let make = (~schoolName, ~logoUrl, ~links, ~isLoggedIn) => { React.useEffect(() => { let resizeCB = _ => toggleMenuHidden(_ => isMobile()) - Webapi.Dom.Window.asEventTarget(Webapi.Dom.window) |> Webapi.Dom.EventTarget.addEventListener( + Webapi.Dom.Window.asEventTarget(Webapi.Dom.window)->Webapi.Dom.EventTarget.addEventListener( "resize", resizeCB, ) @@ -84,7 +84,7 @@ let make = (~schoolName, ~logoUrl, ~links, ~isLoggedIn) => { | None =>
    - {schoolName |> str} + {schoolName->str}
    }} diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/layouts/StudentTopNav__DropDown.res b/tests/syntax_tests/data/idempotency/pupilfirst/layouts/StudentTopNav__DropDown.res index 4625ed0d5f..5e9fac5921 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/layouts/StudentTopNav__DropDown.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/layouts/StudentTopNav__DropDown.res @@ -9,17 +9,17 @@ let additionalLinks = (linksVisible, links) => ?
    {links - |> List.mapi((index, link) => -
    string_of_int} className=""> + ->List.mapi((index, link) => + ) - |> Array.of_list - |> ReasonReact.array} + ->Array.of_list + ->ReasonReact.array}
    : ReasonReact.null @@ -34,7 +34,7 @@ let make = (~links) => { className="ml-6 font-semibold text-sm cursor-pointer relative text-black" onClick={handleToggle(setLinksVisible)} key="more-links"> - {"More" |> str} + {"More"->str} {additionalLinks(linksVisible, moreLinks)}
    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/layouts/StudentTopNav__NavLink.res b/tests/syntax_tests/data/idempotency/pupilfirst/layouts/StudentTopNav__NavLink.res index 021273da61..401b156b60 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/layouts/StudentTopNav__NavLink.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/layouts/StudentTopNav__NavLink.res @@ -10,7 +10,7 @@ let url = t => t.url let decode = json => { open Json.Decode { - title: json |> field("title", string), - url: json |> field("url", string), + title: json->field("title", string), + url: json->field("url", string), } } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/packages/MultiselectDropdown.res b/tests/syntax_tests/data/idempotency/pupilfirst/packages/MultiselectDropdown.res index f00df12635..4a38b8021b 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/packages/MultiselectDropdown.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/packages/MultiselectDropdown.res @@ -8,10 +8,10 @@ module DomUtils = { open Webapi.Dom let focus = id => - (switch document |> Document.getElementById(id) { + (switch document->Document.getElementById(id) { | Some(el) => el | None => raise(RootElementMissing(id)) - } |> Element.asHtmlElement)->Belt.Option.map(HtmlElement.focus) |> ignore + }->Element.asHtmlElement)->Belt.Option.map(HtmlElement.focus)->ignore } module type Selectable = { @@ -24,19 +24,19 @@ module type Selectable = { module Make = (Selectable: Selectable) => { let search = (searchString, selections) => - (selections |> Js.Array.filter(selection => + (selections->Js.Array.filter(selection => selection - |> Selectable.searchString - |> String.lowercase_ascii - |> Js.String.includes(searchString |> String.lowercase_ascii) + ->Selectable.searchString + ->String.lowercase_ascii + ->Js.String.includes(searchString->String.lowercase_ascii) )) ->Belt.SortArray.stableSortBy((x, y) => - String.compare(x |> Selectable.value, y |> Selectable.value) + String.compare(x->Selectable.value, y->Selectable.value) ) let selectionTitle = selection => { - let value = selection |> Selectable.value - switch selection |> Selectable.label { + let value = selection->Selectable.value + switch selection->Selectable.label { | Some(label) => "Pick " ++ (label ++ (": " ++ value)) | None => "Pick " ++ value } @@ -56,7 +56,7 @@ module Make = (Selectable: Selectable) => { } let applyFilter = (selection, onSelect, id, event) => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault onSelect(selection) DomUtils.focus(id) @@ -66,27 +66,27 @@ module Make = (Selectable: Selectable) => { // Remove all excess space characters from the user input. let normalizedString = searchInput - |> Js.String.trim - |> Js.String.replaceByRe(Js.Re.fromStringWithFlags("\\s+", ~flags="g"), " ") + ->Js.String.trim + ->Js.String.replaceByRe(Js.Re.fromStringWithFlags("\\s+", ~flags="g"), " ") switch normalizedString { | "" => [] | searchString => - let matchingSelections = unselected |> search(searchString) + let matchingSelections = unselected->search(searchString) - matchingSelections |> Array.mapi((index, selection) => + matchingSelections->Array.mapi((index, selection) => ) @@ -94,21 +94,21 @@ module Make = (Selectable: Selectable) => { } let removeSelection = (onDeselect, selection, event) => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault onDeselect(selection) } let showSelected = (onDeselect, labelSuffix, selected) => - selected |> Array.mapi((index, selection) => { - let value = selection |> Selectable.value -
    string_of_int} className="inline-flex py-1 mr-2"> -
    Selectable.color, false)}> + selected->Array.mapi((index, selection) => { + let value = selection->Selectable.value +
    string_of_int} className="inline-flex py-1 mr-2"> +
    Selectable.color, false)}> - {switch selection |> Selectable.label { + {switch selection->Selectable.label { | Some(label) => label ++ (labelSuffix ++ value) | None => value - } |> str} + }->str} ) - |> React.array + ->React.array :
    -
    {emptySelectionMessage |> str}
    +
    {emptySelectionMessage->str}
    }
    {( - unselected |> Array.length > 0 + unselected->Array.length > 0 ? "Add more from the list below:" : allItemsSelectedMessage - ) |> str} + )->str}
    - {unselected |> Array.length > 0 + {unselected->Array.length > 0 ?
    { : React.null}
    {searchResults - |> Array.mapi((index, item) => + ->Array.mapi((index, item) =>
    string_of_int} + key={index->string_of_int} onClick={_event => { ReactEvent.Mouse.preventDefault(_event) onSelect(item) }} - title={"Select " ++ (item |> Selectable.value)} + title={"Select " ++ (item->Selectable.value)} className="flex multiselect-inline__list-item items-center px-3 py-2 font-semibold hover:bg-primary-100 hover:text-primary-500 cursor-pointer"> { - {item |> Selectable.value |> str} + {item->Selectable.value->str}
    ) - |> React.array} + ->React.array}
    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/packages/MultiselectInline__Example.res b/tests/syntax_tests/data/idempotency/pupilfirst/packages/MultiselectInline__Example.res index 88cd874e87..124e831556 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/packages/MultiselectInline__Example.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/packages/MultiselectInline__Example.res @@ -34,20 +34,20 @@ module Example = { "Formula 1", "Squash", "Boxing", - ] |> Array.map(sportName => Selectable.makeSport(sportName)) - searchCollection |> Js.Array.filter(sport => !(selected |> Array.mem(sport))) + ]->Array.map(sportName => Selectable.makeSport(sportName)) + searchCollection->Js.Array.filter(sport => !(selected->Array.mem(sport))) } let setSportSearch = (setState, value) => setState(state => {...state, searchInput: value}) let select = (setState, state, sport) => { - let selected = state.selected |> Js.Array.concat([sport]) + let selected = state.selected->Js.Array.concat([sport]) setState(_state => {searchInput: "", selected: selected}) } let deSelect = (setState, state, sport) => { let selected = - state.selected |> Js.Array.filter(selected => + state.selected->Js.Array.filter(selected => Selectable.value(sport) != Selectable.value(selected) ) setState(_state => {searchInput: "", selected: selected}) @@ -57,11 +57,11 @@ module Example = { let make = () => { let (state, setState) = React.useState(() => {searchInput: "", selected: []})
    -

    {"Example" |> str}

    +

    {"Example"->str}

    { - let cp = t |> Array.copy - cp |> Array.sort(f) + let cp = t->Array.copy + cp->Array.sort(f) cp } @@ -92,15 +92,15 @@ module Example = { let search = searchString => { let normalizedString = searchString - |> Js.String.trim - |> Js.String.replaceByRe(Js.Re.fromStringWithFlags("\\s+", ~flags="g"), " ") + ->Js.String.trim + ->Js.String.replaceByRe(Js.Re.fromStringWithFlags("\\s+", ~flags="g"), " ") switch normalizedString { | "" => icons | searchString => icons - |> Js.Array.filter(icon => icon |> String.lowercase_ascii |> Js.String.includes(searchString)) - |> copyAndSort(String.compare) + ->Js.Array.filter(icon => icon->String.lowercase_ascii->Js.String.includes(searchString)) + ->copyAndSort(String.compare) } } @@ -113,7 +113,7 @@ module Example = { let make = () => { let (searchString, setSearchString) = React.useState(() => "")
    -

    {"pf-icon" |> str}

    +

    {"pf-icon"->str}

    {switch search(searchString) { - | [] =>
    {"Icon not found" |> str}
    + | [] =>
    {"Icon not found"->str}
    | resultIcons => resultIcons - |> Array.map(icon => { + ->Array.map(icon => { let iconClasses = "if i-" ++ icon
    -
    {icon |> str}
    +
    {icon->str}
    - {"") |> str} + {"")->str}
    }) - |> React.array + ->React.array }}
    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/packs/ConvertMarkdownPack.res b/tests/syntax_tests/data/idempotency/pupilfirst/packs/ConvertMarkdownPack.res index ca192b3b9c..545ed2213e 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/packs/ConvertMarkdownPack.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/packs/ConvertMarkdownPack.res @@ -11,18 +11,18 @@ type props = { let decodeProps = json => { open Json.Decode { - markdown: json |> field("markdown", string), - profile: json |> field("profile", string), + markdown: json->field("markdown", string), + profile: json->field("profile", string), } } let parseElement = (element, attribute) => - switch element |> Element.getAttribute(attribute) { + switch element->Element.getAttribute(attribute) { | Some(props) => props | None => raise(RootAttributeMissing(attribute)) } - |> Json.parseOrRaise - |> decodeProps + ->Json.parseOrRaise + ->decodeProps let profileType = profile => switch profile { @@ -35,11 +35,11 @@ let profileType = profile => let parseMarkdown = (~attributeName="convert-markdown", ~attribute="data-json-props", ()) => document - |> Document.getElementsByClassName(attributeName) - |> HtmlCollection.toArray - |> Array.map(element => { + ->Document.getElementsByClassName(attributeName) + ->HtmlCollection.toArray + ->Array.map(element => { let props = parseElement(element, attribute) - element |> ReactDOMRe.render( + element->ReactDOMRe.render( { open Json.Decode { - courseName: json |> field("courseName", string), - courseId: json |> field("courseId", string), - thumbnailUrl: json |> field("thumbnailUrl", optional(string)), - email: json |> field("email", optional(string)), - name: json |> field("name", optional(string)), - privacyPolicy: json |> field("privacyPolicy", bool), - termsOfUse: json |> field("termsOfUse", bool), + courseName: json->field("courseName", string), + courseId: json->field("courseId", string), + thumbnailUrl: json->field("thumbnailUrl", optional(string)), + email: json->field("email", optional(string)), + name: json->field("name", optional(string)), + privacyPolicy: json->field("privacyPolicy", bool), + termsOfUse: json->field("termsOfUse", bool), } } -let props = DomUtils.parseJsonTag() |> decodeProps +let props = DomUtils.parseJsonTag()->decodeProps ReactDOMRe.renderToElementWithId( { open Json.Decode ( - json |> field("course", Course.decode), - json |> field("levels", list(Level.decode)), - json |> field("targetGroups", list(TargetGroup.decode)), - json |> field("targets", list(Target.decode)), - json |> field("submissions", list(LatestSubmission.decode)), - json |> field("team", Team.decode), - json |> field("coaches", list(Coach.decode)), - json |> field("users", list(User.decode)), - json |> field("evaluationCriteria", list(EvaluationCriterion.decode)), - json |> field("preview", bool), - json |> field("accessLockedLevels", bool), + json->field("course", Course.decode), + json->field("levels", list(Level.decode)), + json->field("targetGroups", list(TargetGroup.decode)), + json->field("targets", list(Target.decode)), + json->field("submissions", list(LatestSubmission.decode)), + json->field("team", Team.decode), + json->field("coaches", list(Coach.decode)), + json->field("users", list(User.decode)), + json->field("evaluationCriteria", list(EvaluationCriterion.decode)), + json->field("preview", bool), + json->field("accessLockedLevels", bool), ) } @@ -30,7 +30,7 @@ let ( preview, accessLockedLevels, ) = - DomUtils.parseJsonTag() |> decodeProps + DomUtils.parseJsonTag()->decodeProps ReactDOMRe.renderToElementWithId( { open Json.Decode ( - json |> field("levels", array(Level.decode)), - json |> field("courseId", string), - json |> field("teamCoaches", array(Coach.decode)), - json |> field("currentCoach", Coach.decode), + json->field("levels", array(Level.decode)), + json->field("courseId", string), + json->field("teamCoaches", array(Coach.decode)), + json->field("currentCoach", Coach.decode), ) } -let (levels, courseId, teamCoaches, currentCoach) = DomUtils.parseJsonAttribute() |> decodeProps +let (levels, courseId, teamCoaches, currentCoach) = DomUtils.parseJsonAttribute()->decodeProps ReactDOMRe.renderToElementWithId( , diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/packs/CoursesStudentsPack.res b/tests/syntax_tests/data/idempotency/pupilfirst/packs/CoursesStudentsPack.res index f443b6b602..275fab9b09 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/packs/CoursesStudentsPack.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/packs/CoursesStudentsPack.res @@ -3,16 +3,16 @@ open CoursesStudents__Types let decodeProps = json => { open Json.Decode ( - json |> field("levels", array(Level.decode)), - json |> field("course", Course.decode), - json |> field("userId", string), - json |> field("teamCoaches", array(Coach.decode)), - json |> field("currentCoach", Coach.decode), + json->field("levels", array(Level.decode)), + json->field("course", Course.decode), + json->field("userId", string), + json->field("teamCoaches", array(Coach.decode)), + json->field("currentCoach", Coach.decode), ) } let (levels, course, userId, teamCoaches, currentCoach) = - DomUtils.parseJsonTag(~id="school-course-students__props", ()) |> decodeProps + DomUtils.parseJsonTag(~id="school-course-students__props", ())->decodeProps ReactDOMRe.renderToElementWithId( , diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/packs/HomeStyleguidePack.res b/tests/syntax_tests/data/idempotency/pupilfirst/packs/HomeStyleguidePack.res index 117bbe59da..8ad26628ce 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/packs/HomeStyleguidePack.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/packs/HomeStyleguidePack.res @@ -3,12 +3,12 @@ ReactDOMRe.renderToElementWithId( "styleguide__markdown-syntax-highlighting-root", ) -let stringRepeat = (n, s) => s |> Array.make(n) |> Array.to_list |> String.concat("") +let stringRepeat = (n, s) => s->Array.make(n)->Array.to_list->String.concat("") ReactDOMRe.renderToElementWithId(
    - {"This is the element being disabled. " |> stringRepeat(10) |> React.string} + {"This is the element being disabled. "->stringRepeat(10)->React.string}
    , "styleguide__disabling-cover-root", diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/packs/QuestionsEditorPack.res b/tests/syntax_tests/data/idempotency/pupilfirst/packs/QuestionsEditorPack.res index 9f5e1cd7a0..b88472fafb 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/packs/QuestionsEditorPack.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/packs/QuestionsEditorPack.res @@ -8,8 +8,8 @@ type props = { let decodeProps = json => { open Json.Decode { - communityId: json |> field("communityId", string), - target: json |> field("target", nullable(LinkedTarget.decode)) |> Js.Null.toOption, + communityId: json->field("communityId", string), + target: json->field("target", nullable(LinkedTarget.decode))->Js.Null.toOption, } } @@ -18,7 +18,7 @@ let props = ~id="questions-editor", ~attribute="data-json-props", (), - ) |> decodeProps + )->decodeProps ReactDOMRe.renderToElementWithId( , diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/packs/QuestionsShowPack.res b/tests/syntax_tests/data/idempotency/pupilfirst/packs/QuestionsShowPack.res index 519063b285..24c32c53b6 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/packs/QuestionsShowPack.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/packs/QuestionsShowPack.res @@ -16,20 +16,20 @@ type props = { let decodeProps = json => { open Json.Decode { - question: json |> field("questions", Question.decode), - answers: json |> field("answers", list(Answer.decode)), - comments: json |> field("comments", list(Comment.decode)), - users: json |> field("users", list(User.decode)), - likes: json |> field("likes", list(Like.decode)), - currentUserId: json |> field("currentUserId", string), - communityPath: json |> field("communityPath", string), - isCoach: json |> field("isCoach", bool), - communityId: json |> field("communityId", string), - target: json |> field("target", nullable(Target.decode)) |> Js.Null.toOption, + question: json->field("questions", Question.decode), + answers: json->field("answers", list(Answer.decode)), + comments: json->field("comments", list(Comment.decode)), + users: json->field("users", list(User.decode)), + likes: json->field("likes", list(Like.decode)), + currentUserId: json->field("currentUserId", string), + communityPath: json->field("communityPath", string), + isCoach: json->field("isCoach", bool), + communityId: json->field("communityId", string), + target: json->field("target", nullable(Target.decode))->Js.Null.toOption, } } -let props = DomUtils.parseJsonAttribute() |> decodeProps +let props = DomUtils.parseJsonAttribute()->decodeProps ReactDOMRe.renderToElementWithId( { open Json.Decode { - currentSchoolAdminId: json |> field("currentSchoolAdminId", string), - admins: json |> field("admins", array(SchoolAdmin.decode)), + currentSchoolAdminId: json->field("currentSchoolAdminId", string), + admins: json->field("admins", array(SchoolAdmin.decode)), } } -let props = DomUtils.parseJsonTag(~id="school-admins-data", ()) |> decodeProps +let props = DomUtils.parseJsonTag(~id="school-admins-data", ())->decodeProps ReactDOMRe.renderToElementWithId( , diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolCommunitiesPack.res b/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolCommunitiesPack.res index c9395df244..749b1d175d 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolCommunitiesPack.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolCommunitiesPack.res @@ -7,9 +7,9 @@ type props = { let decodeProps = json => { open Json.Decode { - communities: json |> field("communities", list(SchoolCommunities__Community.decode)), - courses: json |> field("courses", list(SchoolCommunities__Course.decode)), - connections: json |> field("connections", list(SchoolCommunities__Connection.decode)), + communities: json->field("communities", list(SchoolCommunities__Community.decode)), + courses: json->field("courses", list(SchoolCommunities__Course.decode)), + connections: json->field("connections", list(SchoolCommunities__Connection.decode)), } } @@ -18,7 +18,7 @@ let props = ~id="school-communities", ~attribute="data-json-props", (), - ) |> decodeProps + )->decodeProps ReactDOMRe.renderToElementWithId( { open Json.Decode ( - json |> field("schoolName", string), - json |> field("schoolLogoPath", string), - json |> field("schoolIconPath", string), - json |> field("courses", list(SchoolAdminNavbar__Course.decode)), - json |> field("isCourseAuthor", bool), + json->field("schoolName", string), + json->field("schoolLogoPath", string), + json->field("schoolIconPath", string), + json->field("courses", list(SchoolAdminNavbar__Course.decode)), + json->field("isCourseAuthor", bool), ) } let (schoolName, schoolLogoPath, schoolIconPath, courses, isCourseAuthor) = - DomUtils.parseJsonAttribute(~id="school-admin-navbar__root", ()) |> decodeProps + DomUtils.parseJsonAttribute(~id="school-admin-navbar__root", ())->decodeProps ReactDOMRe.renderToElementWithId( , diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolsCoachesCourseIndexPack.res b/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolsCoachesCourseIndexPack.res index 9f6be347c9..bf225c084d 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolsCoachesCourseIndexPack.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolsCoachesCourseIndexPack.res @@ -10,14 +10,14 @@ type props = { let decodeProps = json => { open Json.Decode { - courseCoaches: json |> field("courseCoaches", array(CourseCoach.decode)), - schoolCoaches: json |> field("schoolCoaches", array(SchoolCoach.decode)), - courseId: json |> field("courseId", string), - authenticityToken: json |> field("authenticityToken", string), + courseCoaches: json->field("courseCoaches", array(CourseCoach.decode)), + schoolCoaches: json->field("schoolCoaches", array(SchoolCoach.decode)), + courseId: json->field("courseId", string), + authenticityToken: json->field("authenticityToken", string), } } -let props = DomUtils.parseJsonTag(~id="course-coaches__props", ()) |> decodeProps +let props = DomUtils.parseJsonTag(~id="course-coaches__props", ())->decodeProps ReactDOMRe.renderToElementWithId( { open Json.Decode { - coaches: json |> field("coaches", list(Coach.decode)), - authenticityToken: json |> field("authenticityToken", string), + coaches: json->field("coaches", list(Coach.decode)), + authenticityToken: json->field("authenticityToken", string), } } let props = - DomUtils.parseJsonAttribute(~id="sa-coaches-panel", ~attribute="data-props", ()) |> decodeProps + DomUtils.parseJsonAttribute(~id="sa-coaches-panel", ~attribute="data-props", ())->decodeProps ReactDOMRe.renderToElementWithId( , diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolsCoursesAuthorsPack.res b/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolsCoursesAuthorsPack.res index 0b92c01917..10af6c1f9f 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolsCoursesAuthorsPack.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolsCoursesAuthorsPack.res @@ -2,11 +2,11 @@ open CourseAuthors__Types let decodeProps = json => { open Json.Decode - (json |> field("courseId", string), json |> field("authors", array(Author.decode))) + (json->field("courseId", string), json->field("authors", array(Author.decode))) } let (courseId, authors) = - DomUtils.parseJsonTag(~id="schools-courses-authors__props", ()) |> decodeProps + DomUtils.parseJsonTag(~id="schools-courses-authors__props", ())->decodeProps ReactDOMRe.renderToElementWithId( , diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolsCoursesCurriculumPack.res b/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolsCoursesCurriculumPack.res index ecde00abc6..f216f7eba9 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolsCoursesCurriculumPack.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolsCoursesCurriculumPack.res @@ -12,17 +12,17 @@ type props = { let decodeProps = json => { open Json.Decode { - course: json |> field("course", Course.decode), - evaluationCriteria: json |> field("evaluationCriteria", list(EvaluationCriteria.decode)), - levels: json |> field("levels", list(Level.decode)), - targetGroups: json |> field("targetGroups", list(TargetGroup.decode)), - targets: json |> field("targets", list(Target.decode)), - authenticityToken: json |> field("authenticityToken", string), + course: json->field("course", Course.decode), + evaluationCriteria: json->field("evaluationCriteria", list(EvaluationCriteria.decode)), + levels: json->field("levels", list(Level.decode)), + targetGroups: json->field("targetGroups", list(TargetGroup.decode)), + targets: json->field("targets", list(Target.decode)), + authenticityToken: json->field("authenticityToken", string), } } let props = - DomUtils.parseJsonAttribute(~id="curriculum-editor", ~attribute="data-props", ()) |> decodeProps + DomUtils.parseJsonAttribute(~id="curriculum-editor", ~attribute="data-props", ())->decodeProps ReactDOMRe.renderToElementWithId( { open Json.Decode { - courseId: json |> field("courseId", string), - evaluationCriteria: json |> field("evaluationCriteria", array(EvaluationCriterion.decode)), + courseId: json->field("courseId", string), + evaluationCriteria: json->field("evaluationCriteria", array(EvaluationCriterion.decode)), } } let props = - DomUtils.parseJsonTag(~id="schools-courses-evaluation-criteria__props", ()) |> decodeProps + DomUtils.parseJsonTag(~id="schools-courses-evaluation-criteria__props", ())->decodeProps ReactDOMRe.renderToElementWithId( , diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolsCoursesExportsPack.res b/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolsCoursesExportsPack.res index 9a94d0d868..d365d1a909 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolsCoursesExportsPack.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolsCoursesExportsPack.res @@ -3,14 +3,14 @@ open CourseExports__Types let decodeProps = json => { open Json.Decode ( - json |> field("course", Course.decode), - json |> field("exports", array(CourseExport.decode)), - json |> field("tags", array(Tag.decode)), + json->field("course", Course.decode), + json->field("exports", array(CourseExport.decode)), + json->field("tags", array(Tag.decode)), ) } let (course, exports, tags) = - DomUtils.parseJsonTag(~id="schools-courses-exports__props", ()) |> decodeProps + DomUtils.parseJsonTag(~id="schools-courses-exports__props", ())->decodeProps ReactDOMRe.renderToElementWithId( , diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolsCoursesInactiveStudentsPack.res b/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolsCoursesInactiveStudentsPack.res index 3dc6f445d7..8f82913213 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolsCoursesInactiveStudentsPack.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/packs/SchoolsCoursesInactiveStudentsPack.res @@ -12,17 +12,17 @@ type props = { let decodeProps = json => { open Json.Decode { - teams: json |> field("teams", list(Team.decode)), - courseId: json |> field("courseId", string), - students: json |> field("students", list(Student.decode)), - authenticityToken: json |> field("authenticityToken", string), - currentPage: json |> field("currentPage", int), - isLastPage: json |> field("isLastPage", bool), + teams: json->field("teams", list(Team.decode)), + courseId: json->field("courseId", string), + students: json->field("students", list(Student.decode)), + authenticityToken: json->field("authenticityToken", string), + currentPage: json->field("currentPage", int), + isLastPage: json->field("isLastPage", bool), } } let props = - DomUtils.parseJsonAttribute(~id="sa-students-panel", ~attribute="data-props", ()) |> decodeProps + DomUtils.parseJsonAttribute(~id="sa-students-panel", ~attribute="data-props", ())->decodeProps ReactDOMRe.renderToElementWithId( { open Json.Decode { - courseId: json |> field("courseId", string), - courseCoachIds: json |> field("courseCoachIds", array(string)), - schoolCoaches: json |> field("schoolCoaches", array(Coach.decode)), - levels: json |> field("levels", array(Level.decode)), - studentTags: json |> field("studentTags", array(string)), + courseId: json->field("courseId", string), + courseCoachIds: json->field("courseCoachIds", array(string)), + schoolCoaches: json->field("schoolCoaches", array(Coach.decode)), + levels: json->field("levels", array(Level.decode)), + studentTags: json->field("studentTags", array(string)), } } -let props = DomUtils.parseJsonTag(~id="sa-students-panel-data", ()) |> decodeProps +let props = DomUtils.parseJsonTag(~id="sa-students-panel-data", ())->decodeProps ReactDOMRe.renderToElementWithId( { open Json.Decode { - authenticityToken: json |> field("authenticityToken", string), - customizations: json |> field("customizations", SchoolCustomize__Customizations.decode), - schoolName: json |> field("schoolName", string), - schoolAbout: json |> field("schoolAbout", optional(string)), + authenticityToken: json->field("authenticityToken", string), + customizations: json->field("customizations", SchoolCustomize__Customizations.decode), + schoolName: json->field("schoolName", string), + schoolAbout: json->field("schoolAbout", optional(string)), } } -let props = DomUtils.parseJsonTag(~id="school-customize-data", ()) |> decodeProps +let props = DomUtils.parseJsonTag(~id="school-customize-data", ())->decodeProps ReactDOMRe.renderToElementWithId( { open Json.Decode ( - json |> field("currentCourseId", string), - json |> field("courses", list(StudentCourse__Course.decode)), - json |> field("additionalLinks", list(string)), - json |> field("coverImage", optional(string)), + json->field("currentCourseId", string), + json->field("courses", list(StudentCourse__Course.decode)), + json->field("additionalLinks", list(string)), + json->field("coverImage", optional(string)), ) } let (currentCourseId, courses, additionalLinks, coverImage) = - DomUtils.parseJsonAttribute(~id="course-header-root", ()) |> decodeProps + DomUtils.parseJsonAttribute(~id="course-header-root", ())->decodeProps ReactDOMRe.renderToElementWithId( , diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/packs/StudentTopNavPack.res b/tests/syntax_tests/data/idempotency/pupilfirst/packs/StudentTopNavPack.res index b5cc6b4ffe..b572b1e531 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/packs/StudentTopNavPack.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/packs/StudentTopNavPack.res @@ -10,14 +10,14 @@ type props = { let decodeProps = json => { open Json.Decode { - schoolName: json |> field("schoolName", string), - logoUrl: json |> field("logoUrl", nullable(string)) |> Js.Null.toOption, - links: json |> field("links", list(NavLink.decode)), - isLoggedIn: json |> field("isLoggedIn", bool), + schoolName: json->field("schoolName", string), + logoUrl: json->field("logoUrl", nullable(string))->Js.Null.toOption, + links: json->field("links", list(NavLink.decode)), + isLoggedIn: json->field("isLoggedIn", bool), } } -let props = DomUtils.parseJsonTag(~id="student-top-nav-props", ()) |> decodeProps +let props = DomUtils.parseJsonTag(~id="student-top-nav-props", ())->decodeProps ReactDOMRe.renderToElementWithId( { open Json.Decode { - schoolName: json |> field("schoolName", string), - authenticityToken: json |> field("authenticityToken", string), - fqdn: json |> field("fqdn", string), - oauthHost: json |> field("oauthHost", string), + schoolName: json->field("schoolName", string), + authenticityToken: json->field("authenticityToken", string), + fqdn: json->field("fqdn", string), + oauthHost: json->field("oauthHost", string), } } @@ -20,7 +20,7 @@ let props = ~id="user-session-new", ~attribute="data-json-props", (), - ) |> decodeProps + )->decodeProps ReactDOMRe.renderToElementWithId( { open Json.Decode { - token: json |> field("token", string), - authenticityToken: json |> field("authenticityToken", string), + token: json->field("token", string), + authenticityToken: json->field("authenticityToken", string), } } @@ -16,7 +16,7 @@ let props = ~id="user-session-reset-password", ~attribute="data-json-props", (), - ) |> decodeProps + )->decodeProps ReactDOMRe.renderToElementWithId( , diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/packs/UsersHomePack.res b/tests/syntax_tests/data/idempotency/pupilfirst/packs/UsersHomePack.res index d7f566be0c..55d4beef66 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/packs/UsersHomePack.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/packs/UsersHomePack.res @@ -11,17 +11,17 @@ type props = { let decodeProps = json => { open Json.Decode { - currentSchoolAdmin: json |> field("currentSchoolAdmin", bool), - showUserEdit: json |> field("showUserEdit", bool), - userName: json |> field("userName", string), - userTitle: json |> field("userTitle", string), - avatarUrl: json |> optional(field("avatarUrl", string)), - courses: json |> field("courses", array(UsersHome__Course.decode)), - communities: json |> field("communities", array(UsersHome__Community.decode)), + currentSchoolAdmin: json->field("currentSchoolAdmin", bool), + showUserEdit: json->field("showUserEdit", bool), + userName: json->field("userName", string), + userTitle: json->field("userTitle", string), + avatarUrl: json->optional(field("avatarUrl", string)), + courses: json->field("courses", array(UsersHome__Course.decode)), + communities: json->field("communities", array(UsersHome__Community.decode)), } } -let props = DomUtils.parseJsonTag(~id="users-home-data", ()) |> decodeProps +let props = DomUtils.parseJsonTag(~id="users-home-data", ())->decodeProps ReactDOMRe.renderToElementWithId( showAnswerCreate: bool, } - | AddLike(like) => {...state, likes: state.likes |> Like.addLike(like)} - | RemoveLike(id) => {...state, likes: state.likes |> Like.removeLike(id)} + | AddLike(like) => {...state, likes: state.likes->Like.addLike(like)} + | RemoveLike(id) => {...state, likes: state.likes->Like.removeLike(id)} | UpdateShowAnswerCreate(bool) => {...state, showAnswerCreate: bool} | UpdateShowQuestionEdit(bool) => {...state, showQuestionEdit: bool} | UpdateQuestion(question) => {...state, question: question, showQuestionEdit: false} | RemoveAnswer(id) => { ...state, - answers: state.answers |> Answer.delete(id), + answers: state.answers->Answer.delete(id), } | RemoveComment(id) => { ...state, - comments: state.comments |> Comment.delete(id), + comments: state.comments->Comment.delete(id), } | UpdateAnswer(answer) => { ...state, @@ -60,20 +60,20 @@ let showAnswersCreateComponent = (answers, showAnswerCreate, currentUserId) => if showAnswerCreate { true } else { - answers |> Answer.answerFromUser(currentUserId) |> ListUtils.isEmpty + answers->Answer.answerFromUser(currentUserId)->ListUtils.isEmpty } -let likesForAnswer = (likes, answerId) => likes |> Like.likesForAnswer(answerId) |> List.length +let likesForAnswer = (likes, answerId) => likes->Like.likesForAnswer(answerId)->List.length let handleUpdateQuestion = (title, description, currentUserId, question, dispatch) => { let newQuestion = Question.create( - question |> Question.id, + question->Question.id, title, description, - question |> Question.creatorId, + question->Question.creatorId, Some(currentUserId), - question |> Question.createdAt, - question |> Question.updatedAt, + question->Question.createdAt, + question->Question.updatedAt, ) dispatch(UpdateQuestion(newQuestion)) } @@ -111,12 +111,12 @@ let make = ( handleUpdateQuestion(title, description, currentUserId, question, dispatch) let archiveCB = (id, resourceType) => switch resourceType { - | "Question" => communityPath |> Webapi.Dom.Window.setLocation(Webapi.Dom.window) + | "Question" => communityPath->Webapi.Dom.Window.setLocation(Webapi.Dom.window) | "Answer" => dispatch(RemoveAnswer(id)) | "Comment" => dispatch(RemoveComment(id)) | _ => Notification.error("Something went wrong", "Please refresh the page and try again") } - let filteredAnswers = state.answers |> List.filter(answer => !(answer |> Answer.archived)) + let filteredAnswers = state.answers->List.filter(answer => !(answer->Answer.archived))
    @@ -127,10 +127,10 @@ let make = ( id="close-button" className="btn btn-subtle cursor-default" onClick={event => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault dispatch(UpdateShowQuestionEdit(false)) }}> - {"Close" |> str} + {"Close"->str}
    {switch target { @@ -150,14 +150,14 @@ let make = ( className="flex py-4 px-4 md:px-5 w-full bg-white border border-primary-500 shadow-md rounded-lg justify-between items-center mb-2">

    - {"Linked Target: " |> str} + {"Linked Target: "->str} - {target |> Target.title |> str} + {target->Target.title->str}

    - {switch target |> Target.id { + {switch target->Target.id { | Some(id) => - {"View Target" |> str} + {"View Target"->str} | None => React.null }} @@ -171,57 +171,57 @@ let make = (
    - {switch state.question |> Question.editorId { + {switch state.question->Question.editorId { | Some(_) => Question.id) ++ "/versions")} + href={"/questions/" ++ ((state.question->Question.id) ++ "/versions")} title="Edit History" className="inline-flex items-center whitespace-no-wrap text-xs font-semibold py-1 px-3 bg-transparent hover:bg-primary-100 hover:text-primary-500 cursor-pointer text-gray-800 border-r border-gray-400"> - {"History" |> str} + {"History"->str} | None => React.null }} - {state.question |> Question.creatorId == currentUserId || isCoach + {state.question->Question.creatorId == currentUserId || isCoach ? : React.null}

    - {state.question |> Question.title |> str} + {state.question->Question.title->str}

    Question.description} + markdown={state.question->Question.description} className="leading-normal text-sm" profile=Markdown.QuestionAndAnswer /> - {switch state.question |> Question.editorId { + {switch state.question->Question.editorId { | Some(editorId) =>
    - {"Last edited by " |> str} + {"Last edited by "->str} - {users |> User.findById(editorId) |> User.name |> str} + {users->User.findById(editorId)->User.name->str} {" on " ++ (state.question - |> Question.updatedAt - |> DateTime.stingToFormatedTime(DateTime.DateWithYearAndTime)) |> str} + ->Question.updatedAt + ->DateTime.stingToFormatedTime(DateTime.DateWithYearAndTime))->str}
    @@ -233,15 +233,15 @@ let make = (

    {state.comments - |> Comment.commentsForQuestion - |> List.length - |> string_of_int - |> str} + ->Comment.commentsForQuestion + ->List.length + ->string_of_int + ->str}

    User.findById(state.question |> Question.creatorId)} - createdAt={state.question |> Question.createdAt} + user={users->User.findById(state.question->Question.creatorId)} + createdAt={state.question->Question.createdAt} textForTimeStamp="Asked" />
    @@ -249,10 +249,10 @@ let make = (
    Comment.commentsForQuestion} + comments={state.comments->Comment.commentsForQuestion} users commentableType="Question" - commentableId={state.question |> Question.id} + commentableId={state.question->Question.id} addCommentCB currentUserId archiveCB @@ -262,29 +262,29 @@ let make = (
    { - let numberOfAnswers = filteredAnswers |> List.length - (numberOfAnswers |> string_of_int) ++ ( + let numberOfAnswers = filteredAnswers->List.length + (numberOfAnswers->string_of_int) ++ ( numberOfAnswers == 1 ? " Answer" : " Answers" - ) |> str + )->str }
    {filteredAnswers - |> List.sort((answerA, answerB) => + ->List.sort((answerA, answerB) => DateFns.differenceInSeconds( - answerB |> Answer.createdAt |> DateFns.parseString, - answerA |> Answer.createdAt |> DateFns.parseString, - ) |> int_of_float + answerB->Answer.createdAt->DateFns.parseString, + answerA->Answer.createdAt->DateFns.parseString, + )->int_of_float ) - |> List.stable_sort((answerA, answerB) => - likesForAnswer(likes, answerB |> Answer.id) - - likesForAnswer(likes, answerA |> Answer.id) + ->List.stable_sort((answerA, answerB) => + likesForAnswer(likes, answerB->Answer.id) - + likesForAnswer(likes, answerA->Answer.id) ) - |> List.map(answer => + ->List.map(answer => Answer.id} + key={answer->Answer.id} answer question=state.question addCommentCB @@ -299,8 +299,8 @@ let make = ( archiveCB /> ) - |> Array.of_list - |> ReasonReact.array} + ->Array.of_list + ->ReasonReact.array}
    {showAnswersCreateComponent(state.answers, state.showAnswerCreate, currentUserId) ? @@ -310,7 +310,7 @@ let make = (
    } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__AddComment.res b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__AddComment.res index 4f3146a8e6..635306c959 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__AddComment.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__AddComment.res @@ -60,14 +60,14 @@ let make = (~commentableType, ~commentableId, ~addCommentCB, ~currentUserId) => } let handleCreateComment = event => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault if validComment { setSaving(_ => true) CreateCommentQuery.make(~value, ~commentableId, ~commentableType, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => switch response["createComment"] { | #CommentId(commentId) => handleResponseCB(commentId) @@ -76,8 +76,8 @@ let make = (~commentableType, ~commentableId, ~addCommentCB, ~currentUserId) => | #Errors(errors) => Js.Promise.reject(CreateCommentErrorHandler.Errors(errors)) } ) - |> CreateCommentErrorHandler.catch(() => setSaving(_ => false)) - |> ignore + ->CreateCommentErrorHandler.catch(() => setSaving(_ => false)) + ->ignore } else { () } @@ -97,7 +97,7 @@ let make = (~commentableType, ~commentableId, ~addCommentCB, ~currentUserId) => ? : ReasonReact.null} diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__Answer.res b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__Answer.res index d30d0c51e2..678df6d17d 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__Answer.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__Answer.res @@ -11,13 +11,13 @@ type t = { let decode = json => { open Json.Decode { - id: json |> field("id", string), - description: json |> field("description", string), - creatorId: json |> field("creatorId", string), - editorId: json |> field("editorId", nullable(string)) |> Js.Null.toOption, - createdAt: json |> field("createdAt", string), - archived: json |> field("archived", bool), - updatedAt: json |> field("updatedAt", string), + id: json->field("id", string), + description: json->field("description", string), + creatorId: json->field("creatorId", string), + editorId: json->field("editorId", nullable(string))->Js.Null.toOption, + createdAt: json->field("createdAt", string), + archived: json->field("archived", bool), + updatedAt: json->field("updatedAt", string), } } @@ -36,14 +36,14 @@ let updatedAt = t => t.updatedAt let addAnswer = (answers, answer) => list{answer, ...answers} let updateAnswer = (answers, newAnswer) => - answers |> List.map(answer => answer.id == newAnswer.id ? newAnswer : answer) + answers->List.map(answer => answer.id == newAnswer.id ? newAnswer : answer) let answerFromUser = (userId, answers) => - answers |> List.filter(answer => answer.creatorId == userId) + answers->List.filter(answer => answer.creatorId == userId) let archived = t => t.archived -let delete = (id, answers) => answers |> List.filter(a => a.id != id) +let delete = (id, answers) => answers->List.filter(a => a.id != id) let create = (id, description, creatorId, editorId, createdAt, updatedAt, archived) => { id: id, diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__AnswerEditor.res b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__AnswerEditor.res index a692530ced..c035686c80 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__AnswerEditor.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__AnswerEditor.res @@ -78,9 +78,9 @@ let handleAnswerUpdateResponseCB = ( let newAnswer = Answer.create( id, description, - answer |> Answer.creatorId, + answer->Answer.creatorId, Some(currentUserId), - answer |> Answer.createdAt, + answer->Answer.createdAt, dateTime, false, ) @@ -99,17 +99,17 @@ let handleAnswer = ( answer, event, ) => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault if description != "" { setSaving(_ => true) switch answer { | Some(answer) => - let answerId = answer |> Answer.id + let answerId = answer->Answer.id UpdateAnswerQuery.make(~description, ~id=answerId, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => switch response["updateAnswer"] { | #Success(answerUpdated) => answerUpdated @@ -128,12 +128,12 @@ let handleAnswer = ( | #Errors(errors) => Js.Promise.reject(UpdateAnswerErrorHandler.Errors(errors)) } ) - |> UpdateAnswerErrorHandler.catch(() => setSaving(_ => false)) - |> ignore + ->UpdateAnswerErrorHandler.catch(() => setSaving(_ => false)) + ->ignore | None => - CreateAnswerQuery.make(~description, ~questionId=question |> Question.id, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => + CreateAnswerQuery.make(~description, ~questionId=question->Question.id, ()) + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => switch response["createAnswer"] { | #AnswerId(answerId) => handleAnswerCreateCB( @@ -149,8 +149,8 @@ let handleAnswer = ( | #Errors(errors) => Js.Promise.reject(CreateAnswerErrorHandler.Errors(errors)) } ) - |> CreateAnswerErrorHandler.catch(() => setSaving(_ => false)) - |> ignore + ->CreateAnswerErrorHandler.catch(() => setSaving(_ => false)) + ->ignore } } else { Notification.error("Empty", "Answer cant be blank") @@ -161,7 +161,7 @@ let handleAnswer = ( let make = (~question, ~currentUserId, ~handleAnswerCB, ~answer=?, ~handleCloseCB=?) => { let (description, setDescription) = React.useState(() => switch answer { - | Some(answer) => answer |> Answer.description + | Some(answer) => answer->Answer.description | None => "" } ) @@ -174,7 +174,7 @@ let make = (~question, ~currentUserId, ~handleAnswerCB, ~answer=?, ~handleCloseC | None => React.null }} @@ -208,7 +208,7 @@ let make = (~question, ~currentUserId, ~handleAnswerCB, ~answer=?, ~handleCloseC {switch answer { | Some(_) => "Update Your Answer" | None => "Post Your Answer" - } |> str} + }->str}
    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__AnswerShow.res b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__AnswerShow.res index 5c69ea2c2e..59d305fa19 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__AnswerShow.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__AnswerShow.res @@ -17,8 +17,8 @@ let make = ( ~isCoach, ~archiveCB, ) => { - let user = users |> User.findById(answer |> Answer.creatorId) - let commentsForAnswer = comments |> Comment.commentsForAnswer(answer |> Answer.id) + let user = users->User.findById(answer->Answer.creatorId) + let commentsForAnswer = comments->Comment.commentsForAnswer(answer->Answer.id) let (showAnswerEdit, toggleShowAnswerEdit) = React.useState(() => false) let handleCloseCB = () => toggleShowAnswerEdit(_ => false) @@ -28,66 +28,66 @@ let make = ( handleAnswerCB(answer, bool) } -
    Answer.id}> +
    Answer.id}> {showAnswerEdit ?
    - :
    Answer.id)}> + :
    Answer.id)}>
    - {switch answer |> Answer.editorId { + {switch answer->Answer.editorId { | Some(_) => Answer.id) ++ "/versions")} + href={"/answers/" ++ ((answer->Answer.id) ++ "/versions")} title="Edit History" className="inline-flex items-center whitespace-no-wrap text-xs font-semibold py-1 px-3 bg-transparent hover:bg-primary-100 hover:text-primary-500 cursor-pointer text-gray-800 border-r border-gray-400"> - {"History" |> str} + {"History"->str} | None => React.null }} - {answer |> Answer.creatorId == currentUserId || isCoach + {answer->Answer.creatorId == currentUserId || isCoach ? : React.null}
    Answer.description} + markdown={answer->Answer.description} className="leading-normal text-sm " profile=Markdown.QuestionAndAnswer /> - {switch answer |> Answer.editorId { + {switch answer->Answer.editorId { | Some(editorId) =>
    - {"Last edited by " |> str} + {"Last edited by "->str} - {users |> User.findById(editorId) |> User.name |> str} + {users->User.findById(editorId)->User.name->str} {" on " ++ (answer - |> Answer.updatedAt - |> DateTime.stingToFormatedTime(DateTime.DateWithYearAndTime)) |> str} + ->Answer.updatedAt + ->DateTime.stingToFormatedTime(DateTime.DateWithYearAndTime))->str}
    @@ -98,7 +98,7 @@ let make = (
    Answer.id} currentUserId addLikeCB removeLikeCB + likes answerId={answer->Answer.id} currentUserId addLikeCB removeLikeCB />

    - {commentsForAnswer |> List.length |> string_of_int |> str} + {commentsForAnswer->List.length->string_of_int->str}

    Answer.createdAt} textForTimeStamp="Answered" + user createdAt={answer->Answer.createdAt} textForTimeStamp="Answered" />
    @@ -122,7 +122,7 @@ let make = ( comments=commentsForAnswer users commentableType="Answer" - commentableId={answer |> Answer.id} + commentableId={answer->Answer.id} addCommentCB currentUserId archiveCB diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__ArchiveManager.res b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__ArchiveManager.res index 78c8fac218..2a0df2d2f6 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__ArchiveManager.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__ArchiveManager.res @@ -9,17 +9,17 @@ module ArchiveQuery = %graphql(` `) let archive = (id, resourceType, archiveCB, setSaving, event) => - Webapi.Dom.window |> Webapi.Dom.Window.confirm( + Webapi.Dom.window->Webapi.Dom.Window.confirm( "Are you sure you want to delete this " ++ - ((resourceType |> Js.String.toLowerCase) ++ + ((resourceType->Js.String.toLowerCase) ++ ". You cannot undo this."), ) ? { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault setSaving(_ => true) ArchiveQuery.make(~id, ~resourceType, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => { + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => { response["archiveCommunityResource"]["success"] ? { Notification.success("Success", resourceType ++ " archived successfully") @@ -28,7 +28,7 @@ let archive = (id, resourceType, archiveCB, setSaving, event) => : Notification.error("Something went wrong", "Please refresh the page and try again") Js.Promise.resolve() }) - |> ignore + ->ignore } : () @@ -40,6 +40,6 @@ let make = (~id, ~resourceType, ~archiveCB) => { onClick={archive(id, resourceType, archiveCB, setSaving)} className="flex items-center justify-center whitespace-no-wrap text-xs font-semibold py-1 px-3 flex-shrink-0 bg-transparent text-gray-700 hover:bg-red-100 hover:text-red-700 cursor-pointer"> {saving ? : } - {resourceType == "Comment" ? React.null : {"Delete" |> str} } + {resourceType == "Comment" ? React.null : {"Delete"->str} } } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__Comment.res b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__Comment.res index c488cbed36..57921cee06 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__Comment.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__Comment.res @@ -10,12 +10,12 @@ type t = { let decode = json => { open Json.Decode { - id: json |> field("id", string), - value: json |> field("value", string), - creatorId: json |> field("creatorId", string), - commentableId: json |> field("commentableId", string), - commentableType: json |> field("commentableType", string), - createdAt: json |> field("createdAt", string), + id: json->field("id", string), + value: json->field("value", string), + creatorId: json->field("creatorId", string), + commentableId: json->field("commentableId", string), + commentableType: json->field("commentableType", string), + createdAt: json->field("createdAt", string), } } @@ -27,17 +27,17 @@ let id = t => t.id let createdAt = t => t.createdAt let commentsForQuestion = comments => - comments |> List.filter(comment => comment.commentableType == "Question") + comments->List.filter(comment => comment.commentableType == "Question") let commentsForAnswer = (answerId, comments) => comments - |> List.filter(comment => comment.commentableType == "Answer") - |> List.filter(comment => comment.commentableId == answerId) + ->List.filter(comment => comment.commentableType == "Answer") + ->List.filter(comment => comment.commentableId == answerId) let addComment = (comments, comment) => - comments |> List.rev |> List.append(list{comment}) |> List.rev + comments->List.rev->List.append(list{comment})->List.rev -let delete = (id, comments) => comments |> List.filter(c => c.id != id) +let delete = (id, comments) => comments->List.filter(c => c.id != id) let create = (id, value, creatorId, commentableId, commentableType, createdAt) => { id: id, @@ -49,4 +49,4 @@ let create = (id, value, creatorId, commentableId, commentableType, createdAt) = } let sort = comments => - comments |> List.sort((c1, c2) => (c1.id |> int_of_string) - (c2.id |> int_of_string)) + comments->List.sort((c1, c2) => (c1.id->int_of_string) - (c2.id->int_of_string)) diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__CommentShow.res b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__CommentShow.res index 3de5fa0b2c..0c7b84a006 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__CommentShow.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__CommentShow.res @@ -13,9 +13,9 @@ let make = ( ~archiveCB, ~isCoach, ) => { - let (showAll, setShowAll) = React.useState(() => comments |> List.length <= 3) + let (showAll, setShowAll) = React.useState(() => comments->List.length <= 3) - let (commentsToShow, allCommentsShown) = switch (showAll, comments |> Comment.sort) { + let (commentsToShow, allCommentsShown) = switch (showAll, comments->Comment.sort) { | (false, list{e1, e2, e3, _e4, ..._rest}) => (list{e1, e2, e3}, false) | (_, comments) => (comments, true) } @@ -23,39 +23,39 @@ let make = (
      {commentsToShow - |> List.sort((commentA, commentB) => + ->List.sort((commentA, commentB) => DateFns.differenceInSeconds( - commentA |> Comment.createdAt |> DateFns.parseString, - commentB |> Comment.createdAt |> DateFns.parseString, - ) |> int_of_float + commentA->Comment.createdAt->DateFns.parseString, + commentB->Comment.createdAt->DateFns.parseString, + )->int_of_float ) - |> List.map(comment => { + ->List.map(comment => { let commentText = - (comment |> Comment.value) ++ + (comment->Comment.value) ++ (" - **" ++ - ((users |> User.findById(comment |> Comment.creatorId) |> User.name) ++ + ((users->User.findById(comment->Comment.creatorId)->User.name) ++ ("** on " ++ (comment - |> Comment.createdAt - |> DateFns.parseString - |> DateFns.format("Do MMMM, YYYY"))))) + ->Comment.createdAt + ->DateFns.parseString + ->DateFns.format("Do MMMM, YYYY")))))
    • Comment.id} className="w-full text-left border border-gray-400 border-t-0"> + key={comment->Comment.id} className="w-full text-left border border-gray-400 border-t-0">
      - {isCoach || comment |> Comment.creatorId == currentUserId + {isCoach || comment->Comment.creatorId == currentUserId ? Comment.id} resourceType="Comment" archiveCB + id={comment->Comment.id} resourceType="Comment" archiveCB /> : React.null}
    • }) - |> Array.of_list - |> ReasonReact.array} + ->Array.of_list + ->ReasonReact.array} {allCommentsShown ? : React.null} @@ -63,7 +63,7 @@ let make = ( ? setShowAll(_ => true)} className="bg-gray-200 rounded-full cursor-pointer border py-1 px-3 flex mx-auto appearance-none text-xs font-semibold hover:bg-primary-100 hover:text-primary-500 -mt-3"> - {"Show More" |> str} + {"Show More"->str} : ReasonReact.null}
    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__Like.res b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__Like.res index 88cc1af605..a366ffaaf1 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__Like.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__Like.res @@ -7,24 +7,24 @@ type t = { let decode = json => { open Json.Decode { - id: json |> field("id", string), - userId: json |> field("userId", string), - answerId: json |> field("answerId", string), + id: json->field("id", string), + userId: json->field("userId", string), + answerId: json->field("answerId", string), } } let id = t => t.id -let likesForAnswer = (answerId, likes) => likes |> List.filter(like => like.answerId == answerId) +let likesForAnswer = (answerId, likes) => likes->List.filter(like => like.answerId == answerId) let likeByCurrentUser = (answerId, currentUserId, likes) => - likesForAnswer(answerId, likes) |> List.filter(like => like.userId == currentUserId) + likesForAnswer(answerId, likes)->List.filter(like => like.userId == currentUserId) let currentUserLiked = (answerId, currentUserId, likes) => - likeByCurrentUser(answerId, currentUserId, likes) |> ListUtils.isNotEmpty + likeByCurrentUser(answerId, currentUserId, likes)->ListUtils.isNotEmpty -let addLike = (like, likes) => likes |> List.append(list{like}) +let addLike = (like, likes) => likes->List.append(list{like}) -let removeLike = (id, likes) => likes |> List.filter(like => like.id != id) +let removeLike = (id, likes) => likes->List.filter(like => like.id != id) let create = (id, userId, answerId) => {id: id, userId: userId, answerId: answerId} diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__LikeManager.res b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__LikeManager.res index 1a46d196e3..d279060508 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__LikeManager.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__LikeManager.res @@ -58,25 +58,25 @@ let handleAnswerLike = ( addLikeCB, event, ) => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault saving ? () : { setSaving(_ => true) if liked { - let id = Like.likeByCurrentUser(answerId, currentUserId, likes) |> List.hd |> Like.id + let id = Like.likeByCurrentUser(answerId, currentUserId, likes)->List.hd->Like.id DestroyAnswerLikeQuery.make(~id, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(_response => { + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(_response => { removeLikeCB(id) setSaving(_ => false) Js.Promise.resolve() }) - |> ignore + ->ignore } else { CreateAnswerLikeQuery.make(~answerId, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => switch response["createAnswerLike"] { | #AnswerLikeId(answerLikeId) => handleCreateResponse(answerLikeId, currentUserId, answerId, setSaving, addLikeCB) @@ -84,15 +84,15 @@ let handleAnswerLike = ( | #Errors(errors) => Js.Promise.reject(CreateAnswerLikeErrorHandler.Errors(errors)) } ) - |> CreateAnswerLikeErrorHandler.catch(() => setSaving(_ => false)) - |> ignore + ->CreateAnswerLikeErrorHandler.catch(() => setSaving(_ => false)) + ->ignore } } } @react.component let make = (~likes, ~answerId, ~currentUserId, ~addLikeCB, ~removeLikeCB) => { - let liked = likes |> Like.currentUserLiked(answerId, currentUserId) + let liked = likes->Like.currentUserLiked(answerId, currentUserId) let (saving, setSaving) = React.useState(() => false)
    @@ -116,7 +116,7 @@ let make = (~likes, ~answerId, ~currentUserId, ~addLikeCB, ~removeLikeCB) => {

    - {likes |> Like.likesForAnswer(answerId) |> List.length |> string_of_int |> str} + {likes->Like.likesForAnswer(answerId)->List.length->string_of_int->str}

    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__LinkedTarget.res b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__LinkedTarget.res index bb6da8f369..db18752d1f 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__LinkedTarget.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__LinkedTarget.res @@ -6,8 +6,8 @@ type t = { let decode = json => { open Json.Decode { - id: json |> field("id", string), - title: json |> field("title", string), + id: json->field("id", string), + title: json->field("title", string), } } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__Question.res b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__Question.res index 325ee01851..e3007213b7 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__Question.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__Question.res @@ -11,13 +11,13 @@ type t = { let decode = json => { open Json.Decode { - id: json |> field("id", string), - title: json |> field("title", string), - description: json |> field("description", string), - creatorId: json |> field("creatorId", string), - editorId: json |> field("editorId", nullable(string)) |> Js.Null.toOption, - createdAt: json |> field("createdAt", string), - updatedAt: json |> field("updatedAt", string), + id: json->field("id", string), + title: json->field("title", string), + description: json->field("description", string), + creatorId: json->field("creatorId", string), + editorId: json->field("editorId", nullable(string))->Js.Null.toOption, + createdAt: json->field("createdAt", string), + updatedAt: json->field("updatedAt", string), } } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__QuestionEditor.res b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__QuestionEditor.res index f7929f3433..719a0adebd 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__QuestionEditor.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__QuestionEditor.res @@ -18,7 +18,7 @@ type state = { let computeInitialState = question => { let (title, description) = switch question { - | Some(question) => (question |> Question.title, question |> Question.description) + | Some(question) => (question->Question.title, question->Question.description) | None => ("", "") } @@ -48,7 +48,7 @@ type action = let reducer = (state, action) => switch action { | UpdateTitle(title) => - let similar = title |> String.trim == "" ? {search: "", suggestions: []} : state.similar + let similar = title->String.trim == "" ? {search: "", suggestions: []} : state.similar {...state, title: title, similar: similar} | UpdateTitleAndTimeout(title, timeoutId) => { @@ -85,16 +85,16 @@ module SimilarQuestionsQuery = %graphql(` let searchForSimilarQuestions = (send, title, communityId, ()) => { send(BeginSearching) - let trimmedTitle = title |> String.trim + let trimmedTitle = title->String.trim SimilarQuestionsQuery.make(~communityId, ~title=trimmedTitle, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(result => { - let suggestions = result["similarQuestions"] |> Array.map(QuestionSuggestion.makeFromJs) + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(result => { + let suggestions = result["similarQuestions"]->Array.map(QuestionSuggestion.makeFromJs) send(FinishSearching(trimmedTitle, suggestions)) Js.Promise.resolve() }) - |> Js.Promise.catch(e => { + ->Js.Promise.catch(e => { Js.log(e) Notification.warn( "Oops!", @@ -103,17 +103,17 @@ let searchForSimilarQuestions = (send, title, communityId, ()) => { send(FailSaving) Js.Promise.resolve() }) - |> ignore + ->ignore } -let isInvalidString = s => s |> String.trim == "" +let isInvalidString = s => s->String.trim == "" let updateTitleAndSearch = (state, send, communityId, title) => { state.titleTimeoutId->Belt.Option.forEach(Js.Global.clearTimeout) - let trimmedTitle = title |> String.trim + let trimmedTitle = title->String.trim - if title |> isInvalidString || trimmedTitle == state.similar.search { + if title->isInvalidString || trimmedTitle == state.similar.search { send(UpdateTitle(title)) } else { let timeoutId = Js.Global.setTimeout( @@ -183,18 +183,18 @@ module UpdateQuestionError = { let handleResponseCB = (id, title) => { let window = Webapi.Dom.window let parameterizedTitle = - title |> Js.String.toLowerCase |> Js.String.replaceByRe(/[^0-9a-zA-Z]+/gi, "-") + title->Js.String.toLowerCase->Js.String.replaceByRe(/[^0-9a-zA-Z]+/gi, "-") let redirectPath = "/questions/" ++ (id ++ ("/" ++ parameterizedTitle)) - redirectPath |> Webapi.Dom.Window.setLocation(window) + redirectPath->Webapi.Dom.Window.setLocation(window) } -let handleBack = () => Webapi.Dom.window |> Webapi.Dom.Window.history |> Webapi.Dom.History.back +let handleBack = () => Webapi.Dom.window->Webapi.Dom.Window.history->Webapi.Dom.History.back module CreateQuestionErrorHandler = GraphqlErrorHandler.Make(CreateQuestionError) module UpdateQuestionErrorHandler = GraphqlErrorHandler.Make(UpdateQuestionError) -let saveDisabled = state => state.description |> isInvalidString || state.title |> isInvalidString +let saveDisabled = state => state.description->isInvalidString || state.title->isInvalidString let handleCreateOrUpdateQuestion = ( state, @@ -205,17 +205,17 @@ let handleCreateOrUpdateQuestion = ( updateQuestionCB, event, ) => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault if !saveDisabled(state) { send(BeginSaving) switch question { | Some(question) => - let id = question |> Question.id + let id = question->Question.id UpdateQuestionQuery.make(~id, ~title=state.title, ~description=state.description, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => switch response["updateQuestion"] { | #Success(updated) => switch (updated, updateQuestionCB) { @@ -229,10 +229,10 @@ let handleCreateOrUpdateQuestion = ( | #Errors(errors) => Js.Promise.reject(UpdateQuestionErrorHandler.Errors(errors)) } ) - |> UpdateQuestionErrorHandler.catch(() => send(FailSaving)) - |> ignore + ->UpdateQuestionErrorHandler.catch(() => send(FailSaving)) + ->ignore | None => - let targetId = target |> OptionUtils.map(LinkedTarget.id) + let targetId = target->OptionUtils.map(LinkedTarget.id) CreateQuestionQuery.make( ~description=state.description, @@ -241,8 +241,8 @@ let handleCreateOrUpdateQuestion = ( ~targetId?, (), ) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => switch response["createQuestion"] { | #QuestionId(questionId) => handleResponseCB(questionId, state.title) @@ -251,8 +251,8 @@ let handleCreateOrUpdateQuestion = ( | #Errors(errors) => Js.Promise.reject(CreateQuestionErrorHandler.Errors(errors)) } ) - |> CreateQuestionErrorHandler.catch(() => send(FailSaving)) - |> ignore + ->CreateQuestionErrorHandler.catch(() => send(FailSaving)) + ->ignore } } else { Notification.error("Error!", "Question title and description must be present.") @@ -262,53 +262,53 @@ let handleCreateOrUpdateQuestion = ( let suggestions = state => { let suggestions = state.similar.suggestions - suggestions |> ArrayUtils.isNotEmpty + suggestions->ArrayUtils.isNotEmpty ?
    - {"Similar Questions" |> str} + {"Similar Questions"->str} {state.searching ? : React.null} {suggestions - |> Array.map(suggestion => { + ->Array.map(suggestion => { let askedOn = - suggestion |> QuestionSuggestion.createdAt |> DateTime.format(DateTime.OnlyDate) - let (answersText, answersClasses) = switch suggestion |> QuestionSuggestion.answersCount { + suggestion->QuestionSuggestion.createdAt->DateTime.format(DateTime.OnlyDate) + let (answersText, answersClasses) = switch suggestion->QuestionSuggestion.answersCount { | 0 => ("No answers", "bg-gray-300 text-gray-700") | 1 => ("1 answer", "bg-green-500 text-white") - | n => ((n |> string_of_int) ++ " answers", "bg-green-500 text-white") + | n => ((n->string_of_int) ++ " answers", "bg-green-500 text-white") } QuestionSuggestion.id)} + href={"/questions/" ++ (suggestion->QuestionSuggestion.id)} target="_blank" - key={suggestion |> QuestionSuggestion.id} + key={suggestion->QuestionSuggestion.id} className="flex w-full items-center justify-between mt-1 p-3 rounded cursor-pointer border bg-gray-100 hover:text-primary-500 hover:bg-gray-200">
    QuestionSuggestion.title} + title={suggestion->QuestionSuggestion.title} className="font-semibold text-sm leading-snug md:text-base pr-1 truncate flex-1"> - {suggestion |> QuestionSuggestion.title |> str} + {suggestion->QuestionSuggestion.title->str}

    - {"Asked on " ++ askedOn |> str} + {"Asked on " ++ askedOn->str}

    - {answersText |> str} + {answersText->str}
    }) - |> React.array} + ->React.array}
    : React.null } let searchingIndicator = state => - state.similar.suggestions |> ArrayUtils.isEmpty && state.searching + state.similar.suggestions->ArrayUtils.isEmpty && state.searching ?
    @@ -325,7 +325,7 @@ let make = (~communityId, ~showBackButton=true, ~target, ~question=?, ~updateQue ? : React.null} @@ -336,10 +336,10 @@ let make = (~communityId, ~showBackButton=true, ~target, ~question=?, ~updateQue

    - {"Linked Target: " |> str} - {target |> LinkedTarget.title |> str} + {"Linked Target: "->str} + {target->LinkedTarget.title->str}

    - {"Clear" |> str} + {"Clear"->str}
    | None => React.null @@ -348,7 +348,7 @@ let make = (~communityId, ~showBackButton=true, ~target, ~question=?, ~updateQue {switch question { | Some(_) => "Edit question" | None => "Ask a new question" - } |> str} + }->str}
    - {"Question" |> str} + {"Question"->str} - {"Description" |> str} + {"Description"->str}
    "Update Question" | None => "Post Your Question" - } |> str} + }->str}
    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__QuestionSuggestion.res b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__QuestionSuggestion.res index 1b9f508558..e4e6c7c468 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__QuestionSuggestion.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__QuestionSuggestion.res @@ -13,6 +13,6 @@ let answersCount = t => t.answersCount let makeFromJs = jsObject => { id: jsObject["id"], title: jsObject["title"], - createdAt: jsObject["createdAt"] |> Json.Decode.string |> DateFns.parseString, + createdAt: jsObject["createdAt"]->Json.Decode.string->DateFns.parseString, answersCount: jsObject["answersCount"], } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__Target.res b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__Target.res index 7610934ed2..e5c848c8c0 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__Target.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__Target.res @@ -9,7 +9,7 @@ let title = t => t.title let decode = json => { open Json.Decode { - id: json |> field("id", nullable(string)) |> Js.Null.toOption, - title: json |> field("title", string), + id: json->field("id", nullable(string))->Js.Null.toOption, + title: json->field("title", string), } } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__User.res b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__User.res index 7c9f009a6b..d18bd5fa60 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__User.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__User.res @@ -8,10 +8,10 @@ type t = { let decode = json => { open Json.Decode { - id: json |> field("id", string), - name: json |> field("name", string), - avatarUrl: json |> field("avatarUrl", string), - title: json |> field("title", string), + id: json->field("id", string), + name: json->field("name", string), + avatarUrl: json->field("avatarUrl", string), + title: json->field("title", string), } } @@ -22,7 +22,7 @@ let avatarUrl = t => t.avatarUrl let title = t => t.title let findById = (id, users) => - users |> ListUtils.unsafeFind( + users->ListUtils.unsafeFind( user => user.id == id, "Unable to find user with id " ++ (id ++ "in QuestionShow__UserData"), ) diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__UserShow.res b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__UserShow.res index 6a0284af1d..0dee905032 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__UserShow.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/questions/QuestionsShow__UserShow.res @@ -8,17 +8,17 @@ let make = (~user, ~createdAt, ~textForTimeStamp) =>

    {textForTimeStamp ++ (" on " ++ - (createdAt |> DateFns.parseString |> DateFns.format("Do MMMM, YYYY HH:mm"))) |> str} + (createdAt->DateFns.parseString->DateFns.format("Do MMMM, YYYY HH:mm")))->str}

    - User.avatarUrl} /> + User.avatarUrl} />
    -

    {user |> User.name |> str}

    -

    {user |> User.title |> str}

    +

    {user->User.name->str}

    +

    {user->User.title->str}

    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CoachesSchoolIndex__Coach.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CoachesSchoolIndex__Coach.res index 01102f36b6..6f63abad01 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CoachesSchoolIndex__Coach.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CoachesSchoolIndex__Coach.res @@ -37,17 +37,17 @@ let affiliation = t => t.affiliation let decode = json => { open Json.Decode { - name: json |> field("name", string), - id: json |> field("id", int), - imageUrl: json |> field("imageUrl", string), - email: json |> field("email", string), - title: json |> field("title", string), - linkedinUrl: json |> field("linkedinUrl", nullable(string)) |> Js.Null.toOption, - public: json |> field("public", bool), - connectLink: json |> field("connectLink", nullable(string)) |> Js.Null.toOption, - exited: json |> field("exited", bool), - imageFileName: json |> field("imageFileName", nullable(string)) |> Js.Null.toOption, - affiliation: json |> field("affiliation", nullable(string)) |> Js.Null.toOption, + name: json->field("name", string), + id: json->field("id", int), + imageUrl: json->field("imageUrl", string), + email: json->field("email", string), + title: json->field("title", string), + linkedinUrl: json->field("linkedinUrl", nullable(string))->Js.Null.toOption, + public: json->field("public", bool), + connectLink: json->field("connectLink", nullable(string))->Js.Null.toOption, + exited: json->field("exited", bool), + imageFileName: json->field("imageFileName", nullable(string))->Js.Null.toOption, + affiliation: json->field("affiliation", nullable(string))->Js.Null.toOption, } } @@ -78,6 +78,6 @@ let make = ( } let updateList = (coaches, coach) => { - let oldList = coaches |> List.filter(t => t.id !== coach.id) - oldList |> List.rev |> List.append(list{coach}) |> List.rev |> List.sort((x, y) => x.id - y.id) + let oldList = coaches->List.filter(t => t.id !== coach.id) + oldList->List.rev->List.append(list{coach})->List.rev->List.sort((x, y) => x.id - y.id) } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseAuthors__Author.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseAuthors__Author.res index 78f0756f40..6f3b5de2d0 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseAuthors__Author.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseAuthors__Author.res @@ -13,10 +13,10 @@ let email = t => t.email let decode = json => { open Json.Decode { - id: json |> field("id", string), - email: json |> field("email", string), - name: json |> field("name", string), - avatarUrl: json |> optional(field("avatarUrl", string)), + id: json->field("id", string), + email: json->field("email", string), + name: json->field("name", string), + avatarUrl: json->optional(field("avatarUrl", string)), } } @@ -27,6 +27,6 @@ let create = (~id, ~name, ~email, ~avatarUrl) => { avatarUrl: avatarUrl, } -let sort = l => l |> ArrayUtils.copyAndSort((x, y) => x.name < y.name ? -1 : 1) +let sort = l => l->ArrayUtils.copyAndSort((x, y) => x.name < y.name ? -1 : 1) let updateName = (name, t) => {...t, name: name} diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseAuthors__Form.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseAuthors__Form.res index a4ff6fcbcf..d84b629853 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseAuthors__Form.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseAuthors__Form.res @@ -24,8 +24,8 @@ module UpdateCourseAuthorQuery = %graphql(` let createCourseAuthorQuery = (courseId, rootPath, email, name, setSaving, addAuthorCB) => { setSaving(_ => true) CreateCourseAuthorQuery.make(~courseId, ~email, ~name, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => { + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => { switch response["createCourseAuthor"]["courseAuthor"] { | Some(courseAuthor) => addAuthorCB( @@ -37,21 +37,21 @@ let createCourseAuthorQuery = (courseId, rootPath, email, name, setSaving, addAu } Js.Promise.resolve() }) - |> Js.Promise.catch(_ => { + ->Js.Promise.catch(_ => { setSaving(_ => false) Js.Promise.resolve() }) - |> ignore + ->ignore } let updateCourseAuthorQuery = (rootPath, author, name, setSaving, updateAuthorCB) => { setSaving(_ => true) - let id = author |> Author.id + let id = author->Author.id UpdateCourseAuthorQuery.make(~id, ~name, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => { + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => { if response["updateCourseAuthor"]["success"] { - updateAuthorCB(author |> Author.updateName(name)) + updateAuthorCB(author->Author.updateName(name)) ReasonReactRouter.push(rootPath) } else { setSaving(_ => false) @@ -59,11 +59,11 @@ let updateCourseAuthorQuery = (rootPath, author, name, setSaving, updateAuthorCB Js.Promise.resolve() }) - |> Js.Promise.catch(_ => { + ->Js.Promise.catch(_ => { setSaving(_ => false) Js.Promise.resolve() }) - |> ignore + ->ignore } let handleButtonClick = ( @@ -77,14 +77,14 @@ let handleButtonClick = ( updateAuthorCB, event, ) => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault switch author { | Some(author) => updateCourseAuthorQuery(rootPath, author, name, setSaving, updateAuthorCB) | None => createCourseAuthorQuery(courseId, rootPath, email, name, setSaving, addAuthorCB) } } -let isInvalidEmail = email => email |> EmailUtils.isInvalid(false) +let isInvalidEmail = email => email->EmailUtils.isInvalid(false) let showInvalidEmailError = (email, author) => switch author { @@ -102,7 +102,7 @@ let saveDisabled = (email, name, saving, author) => (saving || (name == "" || switch author { - | Some(author) => author |> Author.name == name && author |> Author.email == email + | Some(author) => author->Author.name == name && author->Author.email == email | None => false })) @@ -125,14 +125,14 @@ let make = (~courseId, ~rootPath, ~author, ~addAuthorCB, ~updateAuthorCB) => { let (name, setName) = React.useState(() => switch author { - | Some(author) => author |> Author.name + | Some(author) => author->Author.name | None => "" } ) let (email, setEmail) = React.useState(() => switch author { - | Some(author) => author |> Author.email + | Some(author) => author->Author.email | None => "" } ) @@ -143,15 +143,15 @@ let make = (~courseId, ~rootPath, ~author, ~addAuthorCB, ~updateAuthorCB) => {
    {switch author { - | Some(author) => author |> Author.name + | Some(author) => author->Author.name | None => "Add new author" - } |> str} + }->str}
    { { updateAuthorCB, )} className="w-full btn btn-large btn-primary"> - {buttonText(saving, author) |> str} + {buttonText(saving, author)->str}
    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseAuthors__Root.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseAuthors__Root.res index 3ac4d2468c..3fdb65f46b 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseAuthors__Root.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseAuthors__Root.res @@ -22,16 +22,16 @@ let reducer = (state, action) => | FailToDelete => {...state, deleting: false} | FinishDeleting(author) => { deleting: false, - authors: state.authors |> Js.Array.filter(a => a |> Author.id != (author |> Author.id)), + authors: state.authors->Js.Array.filter(a => a->Author.id != (author->Author.id)), } | AddAuthor(author) => { ...state, - authors: state.authors |> Js.Array.concat([author]), + authors: state.authors->Js.Array.concat([author]), } | UpdateAuthor(author) => { ...state, - authors: state.authors |> Array.map(a => - a |> Author.id == (author |> Author.id) ? author : a + authors: state.authors->Array.map(a => + a->Author.id == (author->Author.id) ? author : a ), } } @@ -45,16 +45,16 @@ module DeleteCourseAuthorQuery = %graphql(` `) let removeCourseAuthor = (send, author, event) => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault WindowUtils.confirm( - "Are you sure you want to remove " ++ ((author |> Author.name) ++ " from the list of authors?"), + "Are you sure you want to remove " ++ ((author->Author.name) ++ " from the list of authors?"), () => { send(BeginDeleting) - DeleteCourseAuthorQuery.make(~id=author |> Author.id, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => { + DeleteCourseAuthorQuery.make(~id=author->Author.id, ()) + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => { if response["deleteCourseAuthor"]["success"] { send(FinishDeleting(author)) } else { @@ -63,18 +63,18 @@ let removeCourseAuthor = (send, author, event) => { Js.Promise.resolve() }) - |> Js.Promise.catch(_ => { + ->Js.Promise.catch(_ => { send(FailToDelete) Js.Promise.resolve() }) - |> ignore + ->ignore }, ) } let renderAuthor = (rootPath, author, send) => { - let authorPath = rootPath ++ ("/" ++ (author |> Author.id)) -
    Author.id} className="flex w-1/2 flex-shrink-0 mb-5 px-3"> + let authorPath = rootPath ++ ("/" ++ (author->Author.id)) +
    Author.id} className="flex w-1/2 flex-shrink-0 mb-5 px-3">
    { }}>
    - {switch author |> Author.avatarUrl { + {switch author->Author.avatarUrl { | Some(avatarUrl) => - | None => Author.name} className="w-10 h-10 rounded-full" /> + | None => Author.name} className="w-10 h-10 rounded-full" /> }}
    - {author |> Author.name |> str} + {author->Author.name->str} - {author |> Author.email |> str} + {author->Author.email->str}
    Author.name)} + title={"Delete " ++ (author->Author.name)} onClick={removeCourseAuthor(send, author)}>
    @@ -128,8 +128,8 @@ let make = (~courseId, ~authors) => { None } else { Some( - state.authors |> ArrayUtils.unsafeFind( - author => author |> Author.id == authorId, + state.authors->ArrayUtils.unsafeFind( + author => author->Author.id == authorId, "Could not find author with ID " ++ (authorId ++ (" in the list of known authors for course with ID " ++ courseId)), @@ -155,16 +155,16 @@ let make = (~courseId, ~authors) => { onClick={_ => ReasonReactRouter.push(rootPath ++ "/new")} className="max-w-2xl w-full flex mx-auto items-center justify-center relative bg-white text-primary-500 hover:bg-gray-100 hover:text-primary-600 hover:shadow-lg focus:outline-none border-2 border-gray-400 border-dashed hover:border-primary-300 p-6 rounded-lg mt-8 cursor-pointer"> -
    {"Add New Author" |> str}
    +
    {"Add New Author"->str}
    {state.authors - |> Author.sort - |> Array.map(author => renderAuthor(rootPath, author, send)) - |> ReasonReact.array} + ->Author.sort + ->Array.map(author => renderAuthor(rootPath, author, send)) + ->ReasonReact.array}
    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__CourseCoach.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__CourseCoach.res index 6ba5c959ac..ef794ee58b 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__CourseCoach.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__CourseCoach.res @@ -19,10 +19,10 @@ let title = t => t.title let decode = json => { open Json.Decode { - name: json |> field("name", string), - email: json |> field("email", string), - id: json |> field("id", string), - avatarUrl: json |> optional(field("avatarUrl", string)), - title: json |> field("title", string), + name: json->field("name", string), + email: json->field("email", string), + id: json->field("id", string), + avatarUrl: json->optional(field("avatarUrl", string)), + title: json->field("title", string), } } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__EnrollmentForm.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__EnrollmentForm.res index f9a2770f4a..922a70c4c9 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__EnrollmentForm.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__EnrollmentForm.res @@ -23,12 +23,12 @@ let reducer = (state, action) => let makePayload = state => { let payload = Js.Dict.empty() - Js.Dict.set(payload, "authenticity_token", AuthenticityToken.fromHead() |> Js.Json.string) + Js.Dict.set(payload, "authenticity_token", AuthenticityToken.fromHead()->Js.Json.string) Js.Dict.set( payload, "coach_ids", - state.courseCoaches |> { + state.courseCoaches->{ open Json.Encode array(string) }, @@ -40,20 +40,20 @@ let makePayload = state => { module SelectableCourseCoaches = { type t = SchoolCoach.t - let value = t => t |> SchoolCoach.name + let value = t => t->SchoolCoach.name let searchString = value } let setCoachSearchInput = (send, value) => send(UpdateCoachSearchInput(value)) let selectCoach = (send, state, coach) => { - let updatedCoaches = state.courseCoaches |> Js.Array.concat([coach |> SchoolCoach.id]) + let updatedCoaches = state.courseCoaches->Js.Array.concat([coach->SchoolCoach.id]) send(UpdateCoachesList(updatedCoaches)) } let deSelectCoach = (send, state, coach) => { let updatedCoaches = - state.courseCoaches |> Js.Array.filter(coachId => coachId != SchoolCoach.id(coach)) + state.courseCoaches->Js.Array.filter(coachId => coachId != SchoolCoach.id(coach)) send(UpdateCoachesList(updatedCoaches)) } @@ -61,9 +61,9 @@ module MultiselectForCourseCoaches = MultiselectInline.Make(SelectableCourseCoac let courseCoachEditor = (coaches, state, send) => { let selected = - coaches |> Js.Array.filter(coach => state.courseCoaches |> Array.mem(SchoolCoach.id(coach))) + coaches->Js.Array.filter(coach => state.courseCoaches->Array.mem(SchoolCoach.id(coach))) let unselected = - coaches |> Js.Array.filter(coach => !(state.courseCoaches |> Array.mem(SchoolCoach.id(coach)))) + coaches->Js.Array.filter(coach => !(state.courseCoaches->Array.mem(SchoolCoach.id(coach)))) { } let handleResponseCB = (updateCoachesCB, json) => { - let courseCoaches = json |> { + let courseCoaches = json->{ open Json.Decode field("course_coaches", array(CourseCoach.decode)) } @@ -96,8 +96,8 @@ let updateCourseCoaches = (state, send, courseId, updateCoachesCB) => { } let computeAvailableCoaches = (schoolCoaches, courseCoaches) => { - let courseCoachIds = courseCoaches |> Array.map(CourseCoach.id) - schoolCoaches |> Js.Array.filter(coach => !(courseCoachIds |> Array.mem(coach |> SchoolCoach.id))) + let courseCoachIds = courseCoaches->Array.map(CourseCoach.id) + schoolCoaches->Js.Array.filter(coach => !(courseCoachIds->Array.mem(coach->SchoolCoach.id))) } @react.component @@ -109,20 +109,20 @@ let make = (~schoolCoaches, ~courseCoaches, ~courseId, ~updateCoachesCB) => { let coaches = computeAvailableCoaches(schoolCoaches, courseCoaches) - let saveDisabled = state.courseCoaches |> ArrayUtils.isEmpty || state.saving + let saveDisabled = state.courseCoaches->ArrayUtils.isEmpty || state.saving
    - {"ASSIGN COACHES TO THE COURSE" |> str} + {"ASSIGN COACHES TO THE COURSE"->str}
    - {coaches |> Array.length > 0 + {coaches->Array.length > 0 ?
    - {"Select coaches:" |> str} + {"Select coaches:"->str} {courseCoachEditor(coaches, state, send)}
    @@ -134,7 +134,7 @@ let make = (~schoolCoaches, ~courseCoaches, ~courseId, ~updateCoachesCB) => { disabled=saveDisabled onClick={_e => updateCourseCoaches(state, send, courseId, updateCoachesCB)} className="w-full btn btn-primary btn-large"> - {"Add Course Coaches" |> str} + {"Add Course Coaches"->str}
    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__InfoForm.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__InfoForm.res index 3ebcef3d06..b55dafd0b7 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__InfoForm.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__InfoForm.res @@ -24,7 +24,7 @@ let reducer = (state, action) => | LoadCoachInfo(teams, stats) => {teams: teams, stats: stats, loading: false} | RemoveTeam(id) => { ...state, - teams: state.teams |> Js.Array.filter(team => Team.id(team) != id), + teams: state.teams->Js.Array.filter(team => Team.id(team) != id), } } @@ -49,10 +49,10 @@ module CoachInfoQuery = %graphql(` let loadCoachTeams = (courseId, coachId, send) => CoachInfoQuery.make(~courseId, ~coachId, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(result => { + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(result => { let coachTeams = - result["teams"]["nodes"] |> OptionUtils.mapWithDefault(Team.makeArrayFromJs, []) + result["teams"]["nodes"]->OptionUtils.mapWithDefault(Team.makeArrayFromJs, []) let stats = { reviewedSubmissions: result["coachStats"]["reviewedSubmissions"], @@ -62,7 +62,7 @@ let loadCoachTeams = (courseId, coachId, send) => send(LoadCoachInfo(coachTeams, stats)) Js.Promise.resolve() }) - |> ignore + ->ignore let removeTeamEnrollment = (send, teamId) => send(RemoveTeam(teamId)) @@ -71,22 +71,22 @@ let make = (~courseId, ~coach) => { let (state, send) = React.useReducer(reducer, initialState) React.useEffect1(() => { - loadCoachTeams(courseId, coach |> CourseCoach.id, send) + loadCoachTeams(courseId, coach->CourseCoach.id, send) None }, [courseId])
    - {switch coach |> CourseCoach.avatarUrl { + {switch coach->CourseCoach.avatarUrl { | Some(avatarUrl) => - | None => CourseCoach.name} className="w-12 h-12 mr-4" /> + | None => CourseCoach.name} className="w-12 h-12 mr-4" /> }}
    - {coach |> CourseCoach.name |> str} + {coach->CourseCoach.name->str}
    -
    {coach |> CourseCoach.email |> str}
    +
    {coach->CourseCoach.email->str}
    @@ -101,37 +101,37 @@ let make = (~courseId, ~coach) => {
    - {"Reviewed submissions" |> str} + {"Reviewed submissions"->str} - {state.stats.reviewedSubmissions |> string_of_int |> str} + {state.stats.reviewedSubmissions->string_of_int->str}
    - {"Pending submissions" |> str} + {"Pending submissions"->str} - {state.stats.pendingSubmissions |> string_of_int |> str} + {state.stats.pendingSubmissions->string_of_int->str}
    } - {"Students assigned to coach:" |> str} + {"Students assigned to coach:"->str} {state.loading ?
    {SkeletonLoading.multiple(~count=2, ~element=SkeletonLoading.paragraph())}
    :
    - {state.teams |> ArrayUtils.isEmpty + {state.teams->ArrayUtils.isEmpty ?
    - {"There are no students assigned to this coach. You can assign coaches directly while editing the student details." |> str} + {"There are no students assigned to this coach. You can assign coaches directly while editing the student details."->str}
    : state.teams - |> Array.map(team => + ->Array.map(team => { removeTeamEnrollmentCB={removeTeamEnrollment(send)} /> ) - |> React.array} + ->React.array}
    }
    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__InfoFormTeam.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__InfoFormTeam.res index 8d662cc254..57a55194a0 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__InfoFormTeam.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__InfoFormTeam.res @@ -13,25 +13,25 @@ module DeleteCoachTeamEnrollmentQuery = %graphql(` `) let deleteTeamEnrollment = (team, coach, setDeleting, removeTeamEnrollmentCB, event) => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault WindowUtils.confirm( "Are you sure you want to remove " ++ - ((team |> Team.name) ++ + ((team->Team.name) ++ " from the list of assigned teams?"), () => { setDeleting(_ => true) DeleteCoachTeamEnrollmentQuery.make(~teamId=Team.id(team), ~coachId=CourseCoach.id(coach), ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => { + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => { if response["deleteCoachTeamEnrollment"]["success"] { removeTeamEnrollmentCB(Team.id(team)) } else { setDeleting(_ => false) } - response |> Js.Promise.resolve + response->Js.Promise.resolve }) - |> ignore + ->ignore }, ) } @@ -40,22 +40,22 @@ let deleteTeamEnrollment = (team, coach, setDeleting, removeTeamEnrollmentCB, ev let make = (~team, ~coach, ~removeTeamEnrollmentCB) => { let (deleting, setDeleting) = React.useState(() => false)
    Team.name)} + ariaLabel={"Team " ++ (team->Team.name)} className="flex items-center justify-between bg-gray-100 text-xs text-gray-900 border rounded pl-3 mt-2" - key={team |> Team.id}> + key={team->Team.id}>
    {team - |> Team.students - |> Js.Array.mapi((student, index) => -
    string_of_int}> {student |> str}
    + ->Team.students + ->Js.Array.mapi((student, index) => +
    string_of_int}> {student->str}
    ) - |> React.array} + ->React.array}
    - {team |> Team.students |> Array.length > 1 + {team->Team.students->Array.length > 1 ?
    -

    {"Team" |> str}

    -

    {team |> Team.name |> str}

    +

    {"Team"->str}

    +

    {team->Team.name->str}

    : React.null}
    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__Root.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__Root.res index 54541f9daa..eaa807acd3 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__Root.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__Root.res @@ -24,11 +24,11 @@ let reducer = (state, action) => | UpdateFormVisible(formVisible) => {...state, formVisible: formVisible} | AddCourseCoaches(courseCoaches) => { ...state, - courseCoaches: state.courseCoaches |> Array.append(courseCoaches), + courseCoaches: state.courseCoaches->Array.append(courseCoaches), } | RemoveCoach(coachId) => { ...state, - courseCoaches: state.courseCoaches |> Js.Array.filter(courseCoach => + courseCoaches: state.courseCoaches->Js.Array.filter(courseCoach => CourseCoach.id(courseCoach) !== coachId ), } @@ -42,7 +42,7 @@ let handleErrorCB = (send, ()) => { let handleResponseCB = (send, json) => { send(UpdateSaving) - let coachId = json |> { + let coachId = json->{ open Json.Decode field("coach_id", string) } @@ -51,19 +51,19 @@ let handleResponseCB = (send, json) => { } let removeCoach = (send, courseId, authenticityToken, coach, event) => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault if { open Webapi.Dom - window |> Window.confirm( - "Are you sure you want to remove " ++ ((coach |> CourseCoach.name) ++ " from this course?"), + window->Window.confirm( + "Are you sure you want to remove " ++ ((coach->CourseCoach.name) ++ " from this course?"), ) } { send(UpdateSaving) let url = "/school/courses/" ++ (courseId ++ "/delete_coach_enrollment") let payload = Js.Dict.empty() - Js.Dict.set(payload, "authenticity_token", authenticityToken |> Js.Json.string) - Js.Dict.set(payload, "coach_id", coach |> CourseCoach.id |> Js.Json.string) + Js.Dict.set(payload, "authenticity_token", authenticityToken->Js.Json.string) + Js.Dict.set(payload, "coach_id", coach->CourseCoach.id->Js.Json.string) Api.create(url, payload, handleResponseCB(send), handleErrorCB(send)) } else { () @@ -113,25 +113,25 @@ let make = (~courseCoaches, ~schoolCoaches, ~courseId, ~authenticityToken) => { }} className="max-w-2xl w-full flex mx-auto items-center justify-center relative bg-white text-primary-500 hove:bg-gray-100 hover:text-primary-600 hover:shadow-lg focus:outline-none border-2 border-gray-400 border-dashed hover:border-primary-300 p-6 rounded-lg mt-8 cursor-pointer"> -
    {"Assign Coaches to Course" |> str}
    +
    {"Assign Coaches to Course"->str}
    } - {state.courseCoaches |> ArrayUtils.isEmpty + {state.courseCoaches->ArrayUtils.isEmpty ?
    - {"The course has no coaches assigned!" |> str} + {"The course has no coaches assigned!"->str}
    : React.null}
    {state.courseCoaches->Belt.SortArray.stableSortBy((a, b) => - String.compare(a |> CourseCoach.name, b |> CourseCoach.name) + String.compare(a->CourseCoach.name, b->CourseCoach.name) ) - |> Array.map(coach => -
    CourseCoach.id} className="flex w-1/2 flex-shrink-0 mb-5 px-3"> + ->Array.map(coach => +
    CourseCoach.id} className="flex w-1/2 flex-shrink-0 mb-5 px-3">
    CourseCoach.name} + id={coach->CourseCoach.name} className="shadow bg-whzite cursor-pointer rounded-lg flex w-full border border-transparent overflow-hidden hover:border-primary-400 hover:bg-gray-100">
    { onClick={_ => send(UpdateFormVisible(CoachInfoForm(coach)))} className="flex flex-1 py-4 px-4 items-center"> - {switch coach |> CourseCoach.avatarUrl { + {switch coach->CourseCoach.avatarUrl { | Some(avatarUrl) => | None => CourseCoach.name} className="w-10 h-10 rounded-full" + name={coach->CourseCoach.name} className="w-10 h-10 rounded-full" /> }}

    - {coach |> CourseCoach.name |> str} + {coach->CourseCoach.name->str}

    - {coach |> CourseCoach.title |> str} + {coach->CourseCoach.title->str}

    CourseCoach.name)} + ariaLabel={"Delete " ++ (coach->CourseCoach.name)} onClick={removeCoach(send, courseId, authenticityToken, coach)}>
    @@ -167,7 +167,7 @@ let make = (~courseCoaches, ~schoolCoaches, ~courseId, ~authenticityToken) => {
    ) - |> React.array} + ->React.array}
    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__SchoolCoach.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__SchoolCoach.res index 632c5ddbf6..97ff19b36f 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__SchoolCoach.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__SchoolCoach.res @@ -9,7 +9,7 @@ let name = t => t.name let decode = json => { open Json.Decode { - id: json |> field("id", string), - name: json |> field("name", string), + id: json->field("id", string), + name: json->field("name", string), } } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__Team.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__Team.res index c90378052d..b12ee11ae9 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__Team.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseCoaches__Team.res @@ -12,7 +12,7 @@ let students = t => t.students let makeFromJS = teamData => { id: teamData["id"], name: teamData["name"], - students: teamData["students"] |> Array.map(student => student["name"]), + students: teamData["students"]->Array.map(student => student["name"]), } let makeArrayFromJs = detailsOfTeams => @@ -21,8 +21,8 @@ let makeArrayFromJs = detailsOfTeams => let decode = json => { open Json.Decode { - id: json |> field("id", string), - name: json |> field("name", string), - students: json |> field("students", array(string)), + id: json->field("id", string), + name: json->field("name", string), + students: json->field("students", array(string)), } } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseEditor.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseEditor.res index 930e6ae655..d419b3bc47 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseEditor.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseEditor.res @@ -47,7 +47,7 @@ let reducer = (state, action) => | UpdateEditorAction(editorAction) => {...state, editorAction: editorAction} | UpdateCourses(courses) => {...state, courses: courses} | UpdateCourse(course) => - let newCourses = course |> Course.updateList(state.courses) + let newCourses = course->Course.updateList(state.courses) {courses: newCourses, editorAction: Hidden} } @@ -58,24 +58,24 @@ let updateCourse = (send, course) => send(UpdateCourse(course)) let courseLinks = course =>
    Course.id) ++ "/curriculum")} + href={"/school/courses/" ++ ((course->Course.id) ++ "/curriculum")} className="text-primary-500 bg-gray-100 hover:bg-gray-200 border-l text-sm font-semibold items-center p-4 flex cursor-pointer"> - {"Curriculum" |> str} + {"Curriculum"->str} Course.id) ++ "/students")} + href={"/school/courses/" ++ ((course->Course.id) ++ "/students")} className="text-primary-500 bg-gray-100 hover:bg-gray-200 border-l text-sm font-semibold items-center p-4 flex cursor-pointer"> - {"Students" |> str} + {"Students"->str} Course.id) ++ "/coaches")} + href={"/school/courses/" ++ ((course->Course.id) ++ "/coaches")} className="text-primary-500 bg-gray-100 hover:bg-gray-200 border-l text-sm font-semibold items-center p-4 flex cursor-pointer"> - {"Coaches" |> str} + {"Coaches"->str} Course.id) ++ "/exports")} + href={"/school/courses/" ++ ((course->Course.id) ++ "/exports")} className="text-primary-500 bg-gray-100 hover:bg-gray-200 border-l text-sm font-semibold items-center p-4 flex cursor-pointer"> - {"Exports" |> str} + {"Exports"->str}
    @@ -85,16 +85,16 @@ let make = () => { React.useEffect0(() => { CoursesQuery.make() - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(result => { + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(result => { let courses = result["courses"] - |> Js.Array.map(rawCourse => Course.makeFromJs(rawCourse)) - |> Array.to_list + ->Js.Array.map(rawCourse => Course.makeFromJs(rawCourse)) + ->Array.to_list send(UpdateCourses(courses)) Js.Promise.resolve() }) - |> ignore + ->ignore None }) @@ -117,53 +117,53 @@ let make = () => { className="max-w-2xl w-full flex mx-auto items-center justify-center relative bg-white text-primary-500 hover:bg-gray-100 hover:text-primary-600 hover:shadow-md focus:outline-none border-2 border-gray-400 border-dashed hover:border-primary-300 p-6 rounded-lg mt-8 cursor-pointer" onClick={_ => send(UpdateEditorAction(ShowForm(None)))}> - {"Add New Course" |> str} + {"Add New Course"->str}
    {state.courses - |> Course.sort - |> List.map(course => -
    Course.id}> + ->Course.sort + ->List.map(course => +
    Course.id}>
    Course.id} + key={course->Course.id} className="flex items-center overflow-hidden shadow bg-white rounded-lg mb-4">
    - {switch course |> Course.thumbnail { + {switch course->Course.thumbnail { | Some(image) => - Course.imageUrl} /> + Course.imageUrl} /> | None =>
    }}
    -
    Course.id}> + @@ -172,8 +172,8 @@ let make = () => {
    ) - |> Array.of_list - |> React.array} + ->Array.of_list + ->React.array}
    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseEditor__Course.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseEditor__Course.res index 67791c0f68..2ca599aa63 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseEditor__Course.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseEditor__Course.res @@ -40,16 +40,16 @@ let cover = t => t.cover let thumbnail = t => t.thumbnail -let imageUrl = image => image |> Image.url +let imageUrl = image => image->Image.url -let filename = image => image |> Image.filename +let filename = image => image->Image.filename let sort = courses => - courses |> List.sort((x, y) => (x.id |> int_of_string) - (y.id |> int_of_string)) + courses->List.sort((x, y) => (x.id->int_of_string) - (y.id->int_of_string)) let updateList = (courses, course) => { - let oldCourses = courses |> List.filter(c => c.id !== course.id) - oldCourses |> List.rev |> List.append(list{course}) |> List.rev + let oldCourses = courses->List.filter(c => c.id !== course.id) + oldCourses->List.rev->List.append(list{course})->List.rev } let makeImageFromJs = data => @@ -96,7 +96,7 @@ let replaceImages = (cover, thumbnail, t) => {...t, cover: cover, thumbnail: thu let makeFromJs = rawCourse => { let endsAt = switch rawCourse["endsAt"] { - | Some(endsAt) => Some(endsAt |> Json.Decode.string) |> OptionUtils.map(DateFns.parseString) + | Some(endsAt) => Some(endsAt->Json.Decode.string)->OptionUtils.map(DateFns.parseString) | None => None } create( diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseEditor__Form.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseEditor__Form.res index 0381163e7c..c3e892cc24 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseEditor__Form.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseEditor__Form.res @@ -67,12 +67,12 @@ module UpdateCourseQuery = %graphql(` `) let updateName = (send, name) => { - let hasError = name |> String.trim |> String.length < 2 + let hasError = name->String.trim->String.length < 2 send(UpdateName(name, hasError)) } let updateDescription = (send, description) => { - let lengthOfDescription = description |> String.trim |> String.length + let lengthOfDescription = description->String.trim->String.length let hasError = lengthOfDescription < 2 || lengthOfDescription >= 150 send(UpdateDescription(description, hasError)) } @@ -89,7 +89,7 @@ let formClasses = value => let handleResponseCB = (id, state, updateCourseCB, course) => { let (thumbnail, cover) = switch course { - | Some(c) => (c |> Course.thumbnail, c |> Course.cover) + | Some(c) => (c->Course.thumbnail, c->Course.cover) | None => (None, None) } @@ -114,7 +114,7 @@ let createCourse = (state, send, updateCourseCB) => { let createCourseQuery = CreateCourseQuery.make( ~name=state.name, ~description=state.description, - ~endsAt=?state.endsAt |> OptionUtils.map(Date.iso8601) |> OptionUtils.map(Js.Json.string), + ~endsAt=?state.endsAt->OptionUtils.map(Date.iso8601)->OptionUtils.map(Js.Json.string), ~about=state.about, ~publicSignup=state.publicSignup, ~featured=state.featured, @@ -122,22 +122,22 @@ let createCourse = (state, send, updateCourseCB) => { ) createCourseQuery - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(result => { + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(result => { handleResponseCB(result["createCourse"]["course"]["id"], state, updateCourseCB, None) Js.Promise.resolve() }) - |> ignore + ->ignore } let updateCourse = (state, send, updateCourseCB, course) => { send(UpdateSaving) let updateCourseQuery = UpdateCourseQuery.make( - ~id=course |> Course.id, + ~id=course->Course.id, ~name=state.name, ~description=state.description, - ~endsAt=?state.endsAt |> OptionUtils.map(Date.iso8601) |> OptionUtils.map(Js.Json.string), + ~endsAt=?state.endsAt->OptionUtils.map(Date.iso8601)->OptionUtils.map(Js.Json.string), ~about=state.about, ~publicSignup=state.publicSignup, ~featured=state.featured, @@ -145,12 +145,12 @@ let updateCourse = (state, send, updateCourseCB, course) => { ) updateCourseQuery - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(result => { + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(result => { handleResponseCB(result["updateCourse"]["course"]["id"], state, updateCourseCB, Some(course)) Js.Promise.resolve() }) - |> ignore + ->ignore } let booleanButtonClasses = bool => { @@ -161,7 +161,7 @@ let booleanButtonClasses = bool => { let enablePublicSignupButton = (publicSignup, send) =>
    @@ -182,22 +182,22 @@ let enablePublicSignupButton = (publicSignup, send) => let featuredButton = (featured, send) =>
    let about = course => - switch course |> Course.about { + switch course->Course.about { | Some(about) => about | None => "" } @@ -207,17 +207,17 @@ let updateAboutCB = (send, about) => send(UpdateAbout(about)) let computeInitialState = course => switch course { | Some(course) => { - name: course |> Course.name, - description: course |> Course.description, - endsAt: course |> Course.endsAt, + name: course->Course.name, + description: course->Course.description, + endsAt: course->Course.endsAt, hasNameError: false, hasDateError: false, hasDescriptionError: false, dirty: false, saving: false, about: about(course), - publicSignup: course |> Course.publicSignup, - featured: course |> Course.featured, + publicSignup: course->Course.publicSignup, + featured: course->Course.featured, } | None => { name: "", @@ -253,11 +253,11 @@ let make = (~course, ~hideEditorActionCB, ~updateCourseCB) => {
    - {(course == None ? "Add New Course" : "Edit Course Details") |> str} + {(course == None ? "Add New Course" : "Edit Course Details")->str}
    { {
    - {"(optional)" |> str} + {"(optional)"->str} - {"If specified, course will appear as closed to students on this date. Students will not be able to make any more submissions." |> str} + {"If specified, course will appear as closed to students on this date. Students will not be able to make any more submissions."->str} send(UpdateEndsAt(date))} @@ -331,7 +331,7 @@ let make = (~course, ~hideEditorActionCB, ~updateCourseCB) => { disabled={saveDisabled(state)} onClick={_ => updateCourse(state, send, updateCourseCB, course)} className="w-full btn btn-large btn-primary mt-3"> - {"Update Course" |> str} + {"Update Course"->str} | None => @@ -339,7 +339,7 @@ let make = (~course, ~hideEditorActionCB, ~updateCourseCB) => { disabled={saveDisabled(state)} onClick={_ => createCourse(state, send, updateCourseCB)} className="w-full btn btn-large btn-primary mt-3"> - {"Create Course" |> str} + {"Create Course"->str} }}
    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseEditor__ImagesForm.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseEditor__ImagesForm.res index eb298ecd4e..480f5966e7 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseEditor__ImagesForm.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseEditor__ImagesForm.res @@ -22,20 +22,20 @@ let updateButtonText = updating => updating ? "Updating..." : "Update Images" let formId = "course-editor-form-image-form" -let filename = optionalFilename => optionalFilename |> OptionUtils.default("unknown") +let filename = optionalFilename => optionalFilename->OptionUtils.default("unknown") let handleUpdateCB = (json, state, course, updateCourseCB) => { - let coverUrl = json |> { + let coverUrl = json->{ open Json.Decode field("cover_url", optional(string)) } - let thumbnailUrl = json |> { + let thumbnailUrl = json->{ open Json.Decode field("thumbnail_url", optional(string)) } let newCourse = - course |> Course.addImages( + course->Course.addImages( ~coverUrl, ~thumbnailUrl, ~coverFilename=filename(state.filenameCover), @@ -46,14 +46,14 @@ let handleUpdateCB = (json, state, course, updateCourseCB) => { } let handleUpdateImages = (send, state, course, updateCourseCB, event) => { - event |> ReactEvent.Form.preventDefault + event->ReactEvent.Form.preventDefault send(BeginUpdate) let element = ReactDOMRe._getElementById(formId) switch element { | Some(element) => Api.sendFormData( - "courses/" ++ ((course |> Course.id) ++ "/attach_images"), + "courses/" ++ ((course->Course.id) ++ "/attach_images"), DomUtils.FormData.create(element), json => { Notification.success("Done!", "Images have been updated successfully.") @@ -77,18 +77,18 @@ let optionalImageLabelText = (image, selectedFilename) => switch selectedFilename { | Some(name) => - {"You have selected " |> str} - {name |> str} - {". Click to replace the current image." |> str} + {"You have selected "->str} + {name->str} + {". Click to replace the current image."->str} | None => switch image { | Some(existingImage) => - {"Please pick a file to replace " |> str} - {existingImage |> Course.filename |> str} + {"Please pick a file to replace "->str} + {existingImage->Course.filename->str} - | None => "Please choose an image file." |> str + | None => "Please choose an image file."->str } } @@ -105,8 +105,8 @@ let isInvalidImageFile = image => let updateImage = (send, isCover, event) => { let imageFile = ReactEvent.Form.target(event)["files"][0] isCover - ? send(SelectCover(imageFile["name"], imageFile |> isInvalidImageFile)) - : send(SelectThumb(imageFile["name"], imageFile |> isInvalidImageFile)) + ? send(SelectCover(imageFile["name"], imageFile->isInvalidImageFile)) + : send(SelectThumb(imageFile["name"], imageFile->isInvalidImageFile)) } let initialState = () => { @@ -141,8 +141,8 @@ let reducer = (state, action) => let make = (~course, ~updateCourseCB, ~closeDrawerCB) => { let (state, send) = React.useReducer(reducer, initialState()) - let thumbnail = course |> Course.thumbnail - let cover = course |> Course.cover + let thumbnail = course->Course.thumbnail + let cover = course->Course.cover
    { onSubmit={handleUpdateImages(send, state, course, updateCourseCB)}>
    - {"Course Images" |> str} + {"Course Images"->str}
    - {"The thumbnail will be displayed on the homepage, and here in the admin courses list." |> str} + {"The thumbnail will be displayed on the homepage, and here in the admin courses list."->str} { - {"The cover image for a course will be displayed at the top of all student pages within the course." |> str} + {"The cover image for a course will be displayed at the top of all student pages within the course."->str} { key="sc-images-editor__update-button" disabled={updateButtonDisabled(state)} className="btn btn-primary btn-large mt-6"> - {updateButtonText(state.updating) |> str} + {updateButtonText(state.updating)->str} diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseExports__Course.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseExports__Course.res index 4b2f1afc7c..23cab28d62 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseExports__Course.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseExports__Course.res @@ -6,5 +6,5 @@ let id = t => t.id let decode = json => { open Json.Decode - {id: json |> field("id", string)} + {id: json->field("id", string)} } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseExports__CourseExport.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseExports__CourseExport.res index 96a90903e1..730a21b0b8 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseExports__CourseExport.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseExports__CourseExport.res @@ -32,26 +32,26 @@ let filePath = file => file.path let decodeFile = json => { open Json.Decode { - path: json |> field("path", string), - createdAt: json |> field("createdAt", string), + path: json->field("path", string), + createdAt: json->field("createdAt", string), } } let decode = json => { open Json.Decode { - id: json |> field("id", string), - createdAt: json |> field("createdAt", string), - file: json |> field("file", nullable(decodeFile)) |> Js.Null.toOption, - tags: json |> field("tags", array(string)), - exportType: switch json |> field("exportType", string) { + id: json->field("id", string), + createdAt: json->field("createdAt", string), + file: json->field("file", nullable(decodeFile))->Js.Null.toOption, + tags: json->field("tags", array(string)), + exportType: switch json->field("exportType", string) { | "Students" => Students | "Teams" => Teams | otherExportType => Rollbar.error("Unexpected exportType encountered: " ++ otherExportType) raise(UnexpectedExportType(otherExportType)) }, - reviewedOnly: json |> field("reviewedOnly", bool), + reviewedOnly: json->field("reviewedOnly", bool), } } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseExports__Root.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseExports__Root.res index bb2498ac2d..c6b2cc7839 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseExports__Root.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseExports__Root.res @@ -42,52 +42,52 @@ let reducer = (state, action) => | FinishSaving(courseExport) => { ...state, saving: false, - courseExports: state.courseExports |> Array.append([courseExport]), + courseExports: state.courseExports->Array.append([courseExport]), drawerOpen: false, } | FailSaving => {...state, saving: false} | SetReviewedOnly(reviewedOnly) => {...state, reviewedOnly: reviewedOnly} | SelectTag(tag) => { ...state, - selectedTags: state.selectedTags |> Array.append([tag]), + selectedTags: state.selectedTags->Array.append([tag]), } | DeselectTag(tag) => { ...state, - selectedTags: state.selectedTags |> Js.Array.filter(t => t |> Tag.id != Tag.id(tag)), + selectedTags: state.selectedTags->Js.Array.filter(t => t->Tag.id != Tag.id(tag)), } | SelectExportType(exportType) => {...state, exportType: exportType} | UpdateTagSearch(tagSearch) => {...state, tagSearch: tagSearch} } let readinessString = courseExport => - switch courseExport |> CourseExport.file { + switch courseExport->CourseExport.file { | None => let timeDistance = courseExport - |> CourseExport.createdAt - |> DateFns.parseString - |> DateFns.distanceInWordsToNow(~addSuffix=true) + ->CourseExport.createdAt + ->DateFns.parseString + ->DateFns.distanceInWordsToNow(~addSuffix=true) "Requested " ++ timeDistance | Some(file) => let timeDistance = file - |> CourseExport.fileCreatedAt - |> DateFns.parseString - |> DateFns.distanceInWordsToNow(~addSuffix=true) + ->CourseExport.fileCreatedAt + ->DateFns.parseString + ->DateFns.distanceInWordsToNow(~addSuffix=true) "Prepared " ++ timeDistance } module Selectable = { type t = Tag.t - let value = t => t |> Tag.name - let searchString = t => t |> Tag.name + let value = t => t->Tag.name + let searchString = t => t->Tag.name } module TagsSelector = MultiselectInline.Make(Selectable) let unselected = (allTags, selectedTags) => { - let selectedTagIds = selectedTags |> Array.map(Tag.id) - allTags |> Js.Array.filter(t => !(selectedTagIds |> Array.mem(t |> Tag.id))) + let selectedTagIds = selectedTags->Array.map(Tag.id) + allTags->Js.Array.filter(t => !(selectedTagIds->Array.mem(t->Tag.id))) } module CreateCourseExportQuery = %graphql(` @@ -104,23 +104,23 @@ module CreateCourseExportQuery = %graphql(` `) let createCourseExport = (state, send, course, event) => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault send(BeginSaving) let (tagIds, exportType) = switch state.exportType { - | CourseExport.Students => (state.selectedTags |> Array.map(Tag.id), #Students) + | CourseExport.Students => (state.selectedTags->Array.map(Tag.id), #Students) | Teams => ([], #Teams) } CreateCourseExportQuery.make( - ~courseId=course |> Course.id, + ~courseId=course->Course.id, ~tagIds, ~reviewedOnly=state.reviewedOnly, ~exportType, (), ) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(response => { + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(response => { switch response["createCourseExport"]["courseExport"] { | Some(\"export") => /* Add the new course export to the list of exports known by this component. */ @@ -138,12 +138,12 @@ let createCourseExport = (state, send, course, event) => { Js.Promise.resolve() }) - |> Js.Promise.catch(e => { + ->Js.Promise.catch(e => { Js.log(e) send(FailSaving) Js.Promise.resolve() }) - |> ignore + ->ignore } let toggleChoiceClasses = value => { @@ -164,11 +164,11 @@ let make = (~course, ~exports, ~tags) => {
    - {"Export course data" |> str} + {"Export course data"->str}
    @@ -176,7 +176,7 @@ let make = (~course, ~exports, ~tags) => { onClick={_ => send(SelectExportType(CourseExport.Students))} className={toggleChoiceClasses(state.exportType == CourseExport.Students)}> -
    {"Students" |> str}
    +
    {"Students"->str}
    @@ -184,7 +184,7 @@ let make = (~course, ~exports, ~tags) => { onClick={_ => send(SelectExportType(CourseExport.Teams))} className={toggleChoiceClasses(state.exportType == CourseExport.Teams)}> -
    {"Teams" |> str}
    +
    {"Teams"->str}
    @@ -193,7 +193,7 @@ let make = (~course, ~exports, ~tags) => { | CourseExport.Students =>
    {
    @@ -220,7 +220,7 @@ let make = (~course, ~exports, ~tags) => { onClick={_ => send(SetReviewedOnly(false))} className={toggleChoiceClasses(!state.reviewedOnly)}> -
    {"All targets" |> str}
    +
    {"All targets"->str}
    @@ -229,7 +229,7 @@ let make = (~course, ~exports, ~tags) => { className={toggleChoiceClasses(state.reviewedOnly)}>
    - {"Only targets with reviewed submissions" |> str} + {"Only targets with reviewed submissions"->str}
    @@ -243,10 +243,10 @@ let make = (~course, ~exports, ~tags) => { {if state.saving { - {"Setting up an export..." |> str} + {"Setting up an export..."->str} } else { - "Create Export" |> str + "Create Export"->str }}
    @@ -260,29 +260,29 @@ let make = (~course, ~exports, ~tags) => { onClick={_ => send(OpenDrawer)} className="max-w-2xl w-full flex mx-auto items-center justify-center relative bg-white text-primary-500 hover:bg-gray-100 hover:text-primary-600 hover:shadow-lg focus:outline-none border-2 border-gray-400 border-dashed hover:border-primary-300 p-6 rounded-lg mt-20 cursor-pointer"> -
    {"Create a new export" |> str}
    +
    {"Create a new export"->str}
    - {state.courseExports |> ArrayUtils.isEmpty + {state.courseExports->ArrayUtils.isEmpty ?
    - {"You haven't exported anything yet!" |> str} + {"You haven't exported anything yet!"->str}
    :
    -

    {"Exports" |> str}

    +

    {"Exports"->str}

    {state.courseExports - |> ArrayUtils.copyAndSort((x, y) => + ->ArrayUtils.copyAndSort((x, y) => DateFns.differenceInSeconds( - y |> CourseExport.createdAt |> DateFns.parseString, - x |> CourseExport.createdAt |> DateFns.parseString, - ) |> int_of_float + y->CourseExport.createdAt->DateFns.parseString, + x->CourseExport.createdAt->DateFns.parseString, + )->int_of_float ) - |> Array.map(courseExport => + ->Array.map(courseExport =>
    CourseExport.id} - ariaLabel={"Export " ++ (courseExport |> CourseExport.id)} + key={courseExport->CourseExport.id} + ariaLabel={"Export " ++ (courseExport->CourseExport.id)} className="flex w-1/2 items-center mb-4 px-3">
    @@ -290,43 +290,43 @@ let make = (~course, ~exports, ~tags) => {

    - {courseExport |> CourseExport.exportTypeToString |> str} + {courseExport->CourseExport.exportTypeToString->str}

    - {courseExport |> readinessString |> str} + {courseExport->readinessString->str}

    - {courseExport |> CourseExport.reviewedOnly + {courseExport->CourseExport.reviewedOnly ? - {"Reviewed Submissions Only" |> str} + {"Reviewed Submissions Only"->str} : React.null} - {switch courseExport |> CourseExport.exportType { + {switch courseExport->CourseExport.exportType { | Teams => ReasonReact.null | Students => courseExport - |> CourseExport.tags - |> Array.map(tag => + ->CourseExport.tags + ->Array.map(tag => - {tag |> str} + {tag->str} ) - |> React.array + ->React.array }}
    - {switch courseExport |> CourseExport.file { + {switch courseExport->CourseExport.file { | None => ReasonReact.null | Some(file) => CourseExport.id)} + (courseExport->CourseExport.id)} className="w-10 text-xs text-sm course-faculty__list-item-remove text-gray-700 hover:text-gray-900 cursor-pointer flex items-center justify-center hover:bg-gray-200" - href={file |> CourseExport.filePath}> + href={file->CourseExport.filePath}> }} @@ -334,7 +334,7 @@ let make = (~course, ~exports, ~tags) => {
    ) - |> React.array} + ->React.array}
    } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseExports__Tag.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseExports__Tag.res index d8af2f5454..b8a5320e9b 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseExports__Tag.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CourseExports__Tag.res @@ -11,7 +11,7 @@ let name = t => t.name let decode = json => { open Json.Decode { - id: json |> field("id", string), - name: json |> field("name", string), + id: json->field("id", string), + name: json->field("name", string), } } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor.res index e9ea3474f1..cd8b65fa15 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor.res @@ -31,61 +31,61 @@ let reducer = (state, action) => | SelectLevel(selectedLevel) => {...state, selectedLevel: selectedLevel} | UpdateEditorAction(editorAction) => {...state, editorAction: editorAction} | UpdateLevels(level) => - let newLevels = level |> Level.updateList(state.levels) + let newLevels = level->Level.updateList(state.levels) {...state, levels: newLevels, editorAction: Hidden, selectedLevel: level} | UpdateTargetGroup(targetGroup) => - let newtargetGroups = targetGroup |> TargetGroup.updateList(state.targetGroups) + let newtargetGroups = targetGroup->TargetGroup.updateList(state.targetGroups) {...state, targetGroups: newtargetGroups} | UpdateTargetGroups(targetGroups) => {...state, targetGroups: targetGroups} | UpdateTarget(target) => - let newtargets = target |> Target.updateList(state.targets) + let newtargets = target->Target.updateList(state.targets) {...state, targets: newtargets} | ToggleShowArchived => {...state, showArchived: !state.showArchived} | UpdateTargets(targets) => {...state, targets: targets} } let showArchivedButton = (targetGroupsInLevel, targets) => { - let tgIds = targetGroupsInLevel |> List.map(tg => tg |> TargetGroup.id) + let tgIds = targetGroupsInLevel->List.map(tg => tg->TargetGroup.id) let numberOfArchivedTargetGroupsInLevel = - targetGroupsInLevel |> List.filter(tg => tg |> TargetGroup.archived) |> List.length + targetGroupsInLevel->List.filter(tg => tg->TargetGroup.archived)->List.length let numberOfArchivedTargetsInLevel = targets - |> List.filter(target => tgIds |> List.mem(target |> Target.targetGroupId)) - |> List.filter(target => target |> Target.visibility === Archived) - |> List.length + ->List.filter(target => tgIds->List.mem(target->Target.targetGroupId)) + ->List.filter(target => target->Target.visibility === Archived) + ->List.length numberOfArchivedTargetGroupsInLevel > 0 || numberOfArchivedTargetsInLevel > 0 } let updateTargetSortIndex = (state, send, sortedTargets) => { - let oldTargets = state.targets |> List.filter(t => !(sortedTargets |> List.mem(t))) - send(UpdateTargets(oldTargets |> List.append(sortedTargets |> Target.updateSortIndex))) + let oldTargets = state.targets->List.filter(t => !(sortedTargets->List.mem(t))) + send(UpdateTargets(oldTargets->List.append(sortedTargets->Target.updateSortIndex))) } let updateTargetGroupSortIndex = (state, send, sortedTargetGroups) => { - let oldTargetGroups = state.targetGroups |> List.filter(t => !(sortedTargetGroups |> List.mem(t))) + let oldTargetGroups = state.targetGroups->List.filter(t => !(sortedTargetGroups->List.mem(t))) send( UpdateTargetGroups( - oldTargetGroups |> List.append(sortedTargetGroups |> TargetGroup.updateSortIndex), + oldTargetGroups->List.append(sortedTargetGroups->TargetGroup.updateSortIndex), ), ) } let levelOfTarget = (targetId, targets, levels, targetGroups) => { let target = - targets |> ListUtils.unsafeFind( + targets->ListUtils.unsafeFind( target => Target.id(target) == targetId, "Unable to find target with ID:" ++ (targetId ++ " in CurriculumEditor"), ) let targetGroup = - targetGroups |> ListUtils.unsafeFind( + targetGroups->ListUtils.unsafeFind( tg => TargetGroup.id(tg) == Target.targetGroupId(target), "Unable to find target group with ID:" ++ (Target.targetGroupId(target) ++ " in CurriculumEditor"), ) - levels |> ListUtils.unsafeFind( + levels->ListUtils.unsafeFind( level => Level.id(level) == TargetGroup.levelId(targetGroup), "Unable to find level with ID:" ++ (TargetGroup.levelId(targetGroup) ++ " in CurriculumEditor"), ) @@ -93,7 +93,7 @@ let levelOfTarget = (targetId, targets, levels, targetGroups) => { let computeIntialState = ((levels, targetGroups, targets, path)) => { let maxLevel = - levels |> List.sort((l1, l2) => (l2 |> Level.number) - (l1 |> Level.number)) |> List.hd + levels->List.sort((l1, l2) => (l2->Level.number) - (l1->Level.number))->List.hd let selectedLevel = switch path { | list{"school", "courses", _courseId, "curriculum"} => maxLevel @@ -127,26 +127,26 @@ let make = (~course, ~evaluationCriteria, ~levels, ~targetGroups, ~targets, ~aut let updateLevelsCB = level => send(UpdateLevels(level)) let targetGroupsInLevel = state.targetGroups - |> List.filter(targetGroup => targetGroup |> TargetGroup.levelId == currentLevelId) - |> TargetGroup.sort + ->List.filter(targetGroup => targetGroup->TargetGroup.levelId == currentLevelId) + ->TargetGroup.sort let targetGroupsToDisplay = state.showArchived ? targetGroupsInLevel - : targetGroupsInLevel |> List.filter(tg => !(tg |> TargetGroup.archived)) + : targetGroupsInLevel->List.filter(tg => !(tg->TargetGroup.archived)) let showTargetGroupEditorCB = targetGroup => send(UpdateEditorAction(ShowTargetGroupEditor(targetGroup))) let updateTargetCB = target => { let targetGroup = - state.targetGroups |> ListUtils.unsafeFind( + state.targetGroups->ListUtils.unsafeFind( tg => TargetGroup.id(tg) == Target.targetGroupId(target), "Unabltge to find target group with ID: " ++ Target.targetGroupId(target), ) - let updatedTargetGroup = switch target |> Target.visibility { + let updatedTargetGroup = switch target->Target.visibility { | Archived => targetGroup | Draft | Live => - targetGroup |> TargetGroup.unarchive + targetGroup->TargetGroup.unarchive } send(UpdateTarget(target)) @@ -154,13 +154,13 @@ let make = (~course, ~evaluationCriteria, ~levels, ~targetGroups, ~targets, ~aut } let updateTargetGroupsCB = targetGroup => { - targetGroup |> TargetGroup.archived + targetGroup->TargetGroup.archived ? { let targetIdsInTargerGroup = - state.targets |> Target.targetIdsInTargetGroup(targetGroup |> TargetGroup.id) + state.targets->Target.targetIdsInTargetGroup(targetGroup->TargetGroup.id) let newTargets = - state.targets |> List.map(target => - targetIdsInTargerGroup |> List.mem(target |> Target.id) + state.targets->List.map(target => + targetIdsInTargerGroup->List.mem(target->Target.id) ? Target.archive(target) : target ) @@ -204,19 +204,19 @@ let make = (~course, ~evaluationCriteria, ~levels, ~targetGroups, ~targets, ~aut let level_name = ReactEvent.Form.target(event)["value"] send(SelectLevel(Level.selectLevel(state.levels, level_name))) }} - value={currentLevel |> Level.name} + value={currentLevel->Level.name} className="block appearance-none w-full bg-white border text-sm border-gray-400 hover:border-gray-500 px-4 py-3 pr-8 rounded-r-none leading-tight focus:outline-none"> {state.levels - |> Level.sort - |> List.map(level => - ) - |> Array.of_list - |> ReasonReact.array} + ->Array.of_list + ->ReasonReact.array}
    @@ -232,21 +232,21 @@ let make = (~course, ~evaluationCriteria, ~levels, ~targetGroups, ~targets, ~aut className="btn btn-primary ml-4" onClick={_ => send(UpdateEditorAction(ShowLevelEditor(None)))}> - {"Create Level" |> str} + {"Create Level"->str}
    {showArchivedButton(targetGroupsInLevel, state.targets) ? : ReasonReact.null}
    {targetGroupsToDisplay - |> List.mapi((index, targetGroup) => + ->List.mapi((index, targetGroup) => TargetGroup.id} + key={targetGroup->TargetGroup.id} targetGroup targetGroups=targetGroupsToDisplay targets=state.targets @@ -259,15 +259,15 @@ let make = (~course, ~evaluationCriteria, ~levels, ~targetGroups, ~targets, ~aut course /> ) - |> Array.of_list - |> ReasonReact.array} + ->Array.of_list + ->ReasonReact.array}
    send(UpdateEditorAction(ShowTargetGroupEditor(None)))} className="target-group__create flex flex-col items-center justify-center relative bg-white border-2 border-dashed border-gray-400 p-6 z-10 hover:text-primary-500 hover:shadow-lg hover:border-primary-400 hover:border-primary-400 rounded-lg mt-12 cursor-pointer"> -

    {"Create a target group" |> str}

    +

    {"Create a target group"->str}

    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__AnswerOption.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__AnswerOption.res index 45ff2c946c..a33c3478a6 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__AnswerOption.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__AnswerOption.res @@ -20,7 +20,7 @@ let markAsCorrect = t => {...t, correctAnswer: true} let markAsIncorrect = t => {...t, correctAnswer: false} -let isValidAnswerOption = t => t.answer |> Js.String.trim |> Js.String.length >= 1 +let isValidAnswerOption = t => t.answer->Js.String.trim->Js.String.length >= 1 let makeFromJs = answerData => { id: answerData["id"], @@ -29,4 +29,4 @@ let makeFromJs = answerData => { } let quizAnswersAsJsObject = quizAnswers => - quizAnswers |> Array.map(qa => {"answer": qa.answer, "correctAnswer": qa.correctAnswer}) + quizAnswers->Array.map(qa => {"answer": qa.answer, "correctAnswer": qa.correctAnswer}) diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__ContentBlockCreator.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__ContentBlockCreator.res index c385d5cf43..fd21136f97 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__ContentBlockCreator.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__ContentBlockCreator.res @@ -91,7 +91,7 @@ let containerClasses = (visible, isAboveTarget) => { let handleGraphqlCreateResponse = (aboveContentBlock, send, addContentBlockCB, contentBlock) => { switch contentBlock { | Some(contentBlock) => - contentBlock |> ContentBlock.makeFromJs |> addContentBlockCB + contentBlock->ContentBlock.makeFromJs->addContentBlockCB send(FinishSaving(aboveContentBlock != None)) | None => send(ToggleSaving) } @@ -101,11 +101,11 @@ let handleGraphqlCreateResponse = (aboveContentBlock, send, addContentBlockCB, c let createMarkdownContentBlock = (target, aboveContentBlock, send, addContentBlockCB) => { send(ToggleSaving) - let aboveContentBlockId = aboveContentBlock |> OptionUtils.map(ContentBlock.id) - let targetId = target |> Target.id + let aboveContentBlockId = aboveContentBlock->OptionUtils.map(ContentBlock.id) + let targetId = target->Target.id CreateMarkdownContentBlock.make(~targetId, ~aboveContentBlockId?, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(result => + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(result => handleGraphqlCreateResponse( aboveContentBlock, send, @@ -113,25 +113,25 @@ let createMarkdownContentBlock = (target, aboveContentBlock, send, addContentBlo result["createMarkdownContentBlock"]["contentBlock"], ) ) - |> Js.Promise.catch(_ => { + ->Js.Promise.catch(_ => { send(FailedToCreate) Js.Promise.resolve() }) - |> ignore + ->ignore } let elementId = (prefix, aboveContentBlock) => prefix ++ switch aboveContentBlock { - | Some(contentBlock) => contentBlock |> ContentBlock.id + | Some(contentBlock) => contentBlock->ContentBlock.id | None => "bottom" } -let fileInputId = aboveContentBlock => aboveContentBlock |> elementId("markdown-block-file-input-") +let fileInputId = aboveContentBlock => aboveContentBlock->elementId("markdown-block-file-input-") let imageInputId = aboveContentBlock => - aboveContentBlock |> elementId("markdown-block-image-input-") -let fileFormId = aboveContentBlock => aboveContentBlock |> elementId("markdown-block-file-form-") -let imageFormId = aboveContentBlock => aboveContentBlock |> elementId("markdown-block-image-form-") + aboveContentBlock->elementId("markdown-block-image-input-") +let fileFormId = aboveContentBlock => aboveContentBlock->elementId("markdown-block-file-form-") +let imageFormId = aboveContentBlock => aboveContentBlock->elementId("markdown-block-image-form-") let onBlockTypeSelect = (target, aboveContentBlock, send, addContentBlockCB, blockType, _event) => switch blockType { @@ -142,8 +142,8 @@ let onBlockTypeSelect = (target, aboveContentBlock, send, addContentBlockCB, blo } let button = (target, aboveContentBlock, send, addContentBlockCB, blockType) => { - let fileId = aboveContentBlock |> fileInputId - let imageId = aboveContentBlock |> imageInputId + let fileId = aboveContentBlock->fileInputId + let imageId = aboveContentBlock->imageInputId let (faIcon, buttonText, htmlFor) = switch blockType { | #Markdown => ("fab fa-markdown", "Markdown", None) @@ -157,7 +157,7 @@ let button = (target, aboveContentBlock, send, addContentBlockCB, blockType) => key=buttonText className="content-block-creator__block-content-type-picker px-3 pt-4 pb-3 flex-1 text-center text-primary-200" onClick={onBlockTypeSelect(target, aboveContentBlock, send, addContentBlockCB, blockType)}> -

    {buttonText |> str}

    +

    {buttonText->str}

    } @@ -171,15 +171,15 @@ let isInvalidImageFile = image => | "image/png" => false | _ => true } || - image |> isInvalidFile + image->isInvalidFile let uploadFile = (target, send, addContentBlockCB, isAboveContentBlock, formData) => Api.sendFormData( - "/school/targets/" ++ ((target |> Target.id) ++ "/content_block"), + "/school/targets/" ++ ((target->Target.id) ++ "/content_block"), formData, json => { Notification.success("Done!", "File uploaded successfully.") - let contentBlock = json |> ContentBlock.decode + let contentBlock = json->ContentBlock.decode addContentBlockCB(contentBlock) send(FinishSaving(isAboveContentBlock)) }, @@ -196,7 +196,7 @@ let submitForm = (target, aboveContentBlock, send, addContentBlockCB, blockType) switch element { | Some(element) => - DomUtils.FormData.create(element) |> uploadFile( + DomUtils.FormData.create(element)->uploadFile( target, send, addContentBlockCB, @@ -216,7 +216,7 @@ let handleFileInputChange = ( blockType, event, ) => { - event |> ReactEvent.Form.preventDefault + event->ReactEvent.Form.preventDefault switch ReactEvent.Form.target(event)["files"] { | [] => () @@ -225,9 +225,9 @@ let handleFileInputChange = ( let error = switch blockType { | #File => - file |> isInvalidFile ? Some("Please select a file with a size less than 5 MB.") : None + file->isInvalidFile ? Some("Please select a file with a size less than 5 MB.") : None | #Image => - file |> isInvalidImageFile + file->isInvalidImageFile ? Some( "Please select an image (PNG, JPEG, GIF) with a size less than 5 MB, and less than 4096px wide or high.", ) @@ -273,7 +273,7 @@ let uploadForm = (target, aboveContentBlock, send, addContentBlockCB, blockType) {switch aboveContentBlock { | Some(contentBlock) => - ContentBlock.id} /> + ContentBlock.id} /> | None => React.null }} @@ -301,18 +301,18 @@ let embedUrlRegexes = [ let validEmbedUrl = url => Belt.Array.some(embedUrlRegexes, regex => regex->Js.Re.test_(url)) let onEmbedFormSave = (target, aboveContentBlock, url, send, addContentBlockCB, event) => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault - if url |> validEmbedUrl { + if url->validEmbedUrl { send(ToggleSaving) - let aboveContentBlockId = aboveContentBlock |> OptionUtils.map(ContentBlock.id) + let aboveContentBlockId = aboveContentBlock->OptionUtils.map(ContentBlock.id) - let targetId = target |> Target.id + let targetId = target->Target.id CreateEmbedContentBlock.make(~targetId, ~aboveContentBlockId?, ~url, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(result => + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(result => handleGraphqlCreateResponse( aboveContentBlock, send, @@ -320,11 +320,11 @@ let onEmbedFormSave = (target, aboveContentBlock, url, send, addContentBlockCB, result["createEmbedContentBlock"]["contentBlock"], ) ) - |> Js.Promise.catch(_ => { + ->Js.Promise.catch(_ => { send(FailedToCreate) Js.Promise.resolve() }) - |> ignore + ->ignore } else { send( SetError( @@ -346,7 +346,7 @@ let topButton = (handler, id, title, icon) =>
    let closeEmbedFormButton = (send, aboveContentBlock) => { - let id = aboveContentBlock |> OptionUtils.map(ContentBlock.id) |> OptionUtils.default("bottom") + let id = aboveContentBlock->OptionUtils.map(ContentBlock.id)->OptionUtils.default("bottom") topButton(_e => send(HideEmbedForm), id, "Close Embed Form", "fa-level-up-alt") } @@ -354,7 +354,7 @@ let closeEmbedFormButton = (send, aboveContentBlock) => { let toggleVisibilityButton = (send, contentBlock) => topButton( _e => send(ToggleVisibility), - contentBlock |> ContentBlock.id, + contentBlock->ContentBlock.id, "Toggle Content Block Form", "fa-plus content-block-creator__plus-button-icon", ) @@ -372,7 +372,7 @@ let buttonAboveContentBlock = (state, send, aboveContentBlock) => let make = (~target, ~aboveContentBlock=?, ~addContentBlockCB) => { let (embedInputId, isAboveContentBlock) = switch aboveContentBlock { | Some(contentBlock) => - let id = "embed-" ++ (contentBlock |> ContentBlock.id) + let id = "embed-" ++ (contentBlock->ContentBlock.id) (id, true) | None => ("embed-bottom", false) } @@ -386,7 +386,7 @@ let make = (~target, ~aboveContentBlock=?, ~addContentBlockCB) => { {uploadForm(target, aboveContentBlock, send, addContentBlockCB, #File)} {uploadForm(target, aboveContentBlock, send, addContentBlockCB, #Image)} -
    visible, isAboveContentBlock)}> +
    visible, isAboveContentBlock)}> {buttonAboveContentBlock(state, send, aboveContentBlock)}
    {switch state.ui { @@ -395,19 +395,19 @@ let make = (~target, ~aboveContentBlock=?, ~addContentBlockCB) => {
    {[#Markdown, #Image, #Embed, #File] - |> Array.map(button(target, aboveContentBlock, send, addContentBlockCB)) - |> React.array} + ->Array.map(button(target, aboveContentBlock, send, addContentBlockCB)) + ->React.array}
    | EmbedForm(url) =>
    - {"We support YouTube, Vimeo, and Slideshare URLs. Just copy & paste the full URL to the page that contains the resource that you'd like to embed." |> str} + {"We support YouTube, Vimeo, and Slideshare URLs. Just copy & paste the full URL to the page that contains the resource that you'd like to embed."->str}
    {
    }}
    {switch state.error { - | Some(error) => visible} /> + | Some(error) => visible} /> | None => React.null }}
    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__ContentBlockEditor.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__ContentBlockEditor.res index a3c6b98244..05b930f268 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__ContentBlockEditor.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__ContentBlockEditor.res @@ -97,9 +97,9 @@ let controlIcon = (~icon, ~title, ~color, ~handler) => { let onMove = (contentBlock, cb, direction, _event) => { // We don't actually handle the response for this query. - MoveContentBlockMutation.make(~id=contentBlock |> ContentBlock.id, ~direction, ()) - |> GraphqlQuery.sendQuery - |> ignore + MoveContentBlockMutation.make(~id=contentBlock->ContentBlock.id, ~direction, ()) + ->GraphqlQuery.sendQuery + ->ignore cb(contentBlock) } @@ -107,11 +107,11 @@ let onMove = (contentBlock, cb, direction, _event) => { let onDelete = (contentBlock, removeContentBlockCB, send, _event) => WindowUtils.confirm("Are you sure you want to delete this block?", () => { send(StartSaving("Deleting...")) - let id = contentBlock |> ContentBlock.id + let id = contentBlock->ContentBlock.id DeleteContentBlockMutation.make(~id, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(result => { + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(result => { if result["deleteContentBlock"]["success"] { removeContentBlockCB(id) } else { @@ -120,15 +120,15 @@ let onDelete = (contentBlock, removeContentBlockCB, send, _event) => Js.Promise.resolve() }) - |> Js.Promise.catch(_error => { + ->Js.Promise.catch(_error => { send(FinishSaving) Js.Promise.resolve() }) - |> ignore + ->ignore }) let onUndo = (originalContentBlock, setDirtyCB, send, event) => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault WindowUtils.confirm("Are you sure you want to undo your changes to this block?", () => { setDirtyCB(false) @@ -139,7 +139,7 @@ let onUndo = (originalContentBlock, setDirtyCB, send, event) => { let handleUpdateResult = (updateContentBlockCB, setDirtyCB, send, contentBlock) => { switch contentBlock { | Some(contentBlock) => - contentBlock |> ContentBlock.makeFromJs |> updateContentBlockCB + contentBlock->ContentBlock.makeFromJs->updateContentBlockCB send(FinishSaving) setDirtyCB(false) | None => send(FailSaving) @@ -157,22 +157,22 @@ let updateContentBlockBlock = ( send(StartSaving("Updating...")) mutation - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(result => - result |> contentBlockExtractor |> handleUpdateResult(updateContentBlockCB, setDirtyCB, send) + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(result => + result->contentBlockExtractor->handleUpdateResult(updateContentBlockCB, setDirtyCB, send) ) - |> Js.Promise.catch(_error => { + ->Js.Promise.catch(_error => { send(FinishSaving) Js.Promise.resolve() }) - |> ignore + ->ignore } let onSave = (contentBlock, updateContentBlockCB, setDirtyCB, send, event) => { - event |> ReactEvent.Mouse.preventDefault - let id = contentBlock |> ContentBlock.id + event->ReactEvent.Mouse.preventDefault + let id = contentBlock->ContentBlock.id - switch contentBlock |> ContentBlock.blockType { + switch contentBlock->ContentBlock.blockType { | ContentBlock.File(_url, title, _filename) => let mutation = UpdateFileBlockMutation.make(~id, ~title, ()) let extractor = result => result["updateFileBlock"]["contentBlock"] @@ -202,7 +202,7 @@ let updateContentBlockCB = (originalContentBlock, setDirtyCB, state, send, newCo let innerEditor = (originalContentBlock, contentBlock, setDirtyCB, state, send) => { let updateContentBlockCB = updateContentBlockCB(originalContentBlock, setDirtyCB, state, send) - switch contentBlock |> ContentBlock.blockType { + switch contentBlock->ContentBlock.blockType { | ContentBlock.Embed(_url, embedCode) => TargetContentView.embedContentBlock("", embedCode) | Markdown(markdown) => @@ -227,7 +227,7 @@ let make = (
    ContentBlock.id)}> + ariaLabel={"Editor for content block " ++ (contentBlock->ContentBlock.id)}>
    {innerEditor(contentBlock, state.contentBlock, setDirtyCB, state, send)}
    @@ -237,25 +237,25 @@ let make = ( ~icon="fa-arrow-up", ~title="Move Up", ~color=#Grey, - ~handler=moveContentBlockUpCB |> OptionUtils.map(cb => onMove(contentBlock, cb, #Up)), + ~handler=moveContentBlockUpCB->OptionUtils.map(cb => onMove(contentBlock, cb, #Up)), )} {controlIcon( ~icon="fa-arrow-down", ~title="Move Down", ~color=#Grey, - ~handler=moveContentBlockDownCB |> OptionUtils.map(cb => onMove(contentBlock, cb, #Down)), + ~handler=moveContentBlockDownCB->OptionUtils.map(cb => onMove(contentBlock, cb, #Down)), )} {controlIcon( ~icon="fa-trash-alt", ~title="Delete", ~color=#Grey, - ~handler=removeContentBlockCB |> OptionUtils.map(cb => onDelete(contentBlock, cb, send)), + ~handler=removeContentBlockCB->OptionUtils.map(cb => onDelete(contentBlock, cb, send)), )} {controlIcon( ~icon="fa-undo-alt", ~title="Undo Changes", ~color=#Grey, - ~handler=updateContentBlockCB |> OptionUtils.map(_cb => + ~handler=updateContentBlockCB->OptionUtils.map(_cb => onUndo(contentBlock, setDirtyCB, send) ), )} @@ -263,7 +263,7 @@ let make = ( ~icon="fa-check", ~title="Save Changes", ~color=#Green, - ~handler=updateContentBlockCB |> OptionUtils.map(cb => + ~handler=updateContentBlockCB->OptionUtils.map(cb => onSave(state.contentBlock, cb, setDirtyCB, send) ), )} diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__ContentEditor.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__ContentEditor.res index 458985f7ca..94efef03ec 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__ContentEditor.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__ContentEditor.res @@ -27,45 +27,45 @@ let reducer = (state, action) => dirtyContentBlockIds: Belt.Set.String.empty, } | AddContentBlock(newContentBlock) => - let newBlockSortIndex = newContentBlock |> ContentBlock.sortIndex + let newBlockSortIndex = newContentBlock->ContentBlock.sortIndex { ...state, contentBlocks: state.contentBlocks - |> Array.map(contentBlock => { - let sortIndex = contentBlock |> ContentBlock.sortIndex + ->Array.map(contentBlock => { + let sortIndex = contentBlock->ContentBlock.sortIndex if sortIndex < newBlockSortIndex { contentBlock } else { - contentBlock |> ContentBlock.incrementSortIndex + contentBlock->ContentBlock.incrementSortIndex } }) - |> Array.append([newContentBlock]), + ->Array.append([newContentBlock]), } | UpdateContentBlock(updatedContentBlock) => { ...state, - contentBlocks: state.contentBlocks |> Array.map(contentBlock => - contentBlock |> ContentBlock.id == (updatedContentBlock |> ContentBlock.id) + contentBlocks: state.contentBlocks->Array.map(contentBlock => + contentBlock->ContentBlock.id == (updatedContentBlock->ContentBlock.id) ? updatedContentBlock : contentBlock ), dirtyContentBlockIds: state.dirtyContentBlockIds->Belt.Set.String.remove( - updatedContentBlock |> ContentBlock.id, + updatedContentBlock->ContentBlock.id, ), } | RemoveContentBlock(contentBlockId) => { ...state, - contentBlocks: state.contentBlocks |> Js.Array.filter(contentBlock => - contentBlock |> ContentBlock.id != contentBlockId + contentBlocks: state.contentBlocks->Js.Array.filter(contentBlock => + contentBlock->ContentBlock.id != contentBlockId ), } | MoveContentBlockUp(contentBlock) => { ...state, - contentBlocks: state.contentBlocks |> ContentBlock.moveUp(contentBlock), + contentBlocks: state.contentBlocks->ContentBlock.moveUp(contentBlock), } | MoveContentBlockDown(contentBlock) => { ...state, - contentBlocks: state.contentBlocks |> ContentBlock.moveDown(contentBlock), + contentBlocks: state.contentBlocks->ContentBlock.moveDown(contentBlock), } | SetDirty(contentBlockId, dirty) => let operation = dirty ? Belt.Set.String.add : Belt.Set.String.remove @@ -77,9 +77,9 @@ let reducer = (state, action) => let loadContentBlocks = (targetId, send) => ContentBlock.Query.make(~targetId, ()) - |> GraphqlQuery.sendQuery(~notify=true) - |> Js.Promise.then_(result => { - let contentBlocks = result["contentBlocks"] |> Js.Array.map(ContentBlock.makeFromJs) + ->GraphqlQuery.sendQuery(~notify=true) + ->Js.Promise.then_(result => { + let contentBlocks = result["contentBlocks"]->Js.Array.map(ContentBlock.makeFromJs) let versions = Version.makeArrayFromJs(result["versions"]) @@ -87,7 +87,7 @@ let loadContentBlocks = (targetId, send) => Js.Promise.resolve() }) - |> ignore + ->ignore let addContentBlock = (send, contentBlock) => send(AddContentBlock(contentBlock)) @@ -103,52 +103,52 @@ let updateContentBlock = (send, contentBlock) => send(UpdateContentBlock(content let editor = (target, state, send) => { let currentVersion = switch state.versions { - | [] => {"Not Versioned" |> str} + | [] => {"Not Versioned"->str} | versions => let latestVersion = - versions->Array.unsafe_get(0) |> Version.updatedAt |> DateFns.format("MMM D, YYYY HH:MM") + versions->Array.unsafe_get(0)->Version.updatedAt->DateFns.format("MMM D, YYYY HH:MM") - latestVersion |> str + latestVersion->str } - let sortedContentBlocks = state.contentBlocks |> ContentBlock.sort - let numberOfContentBlocks = state.contentBlocks |> Array.length + let sortedContentBlocks = state.contentBlocks->ContentBlock.sort + let numberOfContentBlocks = state.contentBlocks->Array.length let removeContentBlockCB = numberOfContentBlocks > 1 ? Some(removeContentBlock(send)) : None
    - {switch target |> Target.visibility { + {switch target->Target.visibility { | Live => Target.id)} + href={"/targets/" ++ (target->Target.id)} target="_blank" className="py-2 px-3 font-semibold rounded-lg text-sm focus:outline-none bg-primary-100 text-primary-500"> - {"View as Student" |> str} + {"View as Student"->str} | Draft | Archived => React.null }}
    - + currentVersion
    {sortedContentBlocks - |> Array.mapi((index, contentBlock) => { + ->Array.mapi((index, contentBlock) => { let moveContentBlockUpCB = index == 0 ? None : Some(moveContentBlockUp(send)) let moveContentBlockDownCB = index + 1 == numberOfContentBlocks ? None : Some(moveContentBlockDown(send)) - let isDirty = state.dirtyContentBlockIds->Belt.Set.String.has(contentBlock |> ContentBlock.id) + let isDirty = state.dirtyContentBlockIds->Belt.Set.String.has(contentBlock->ContentBlock.id) let updateContentBlockCB = isDirty ? Some(updateContentBlock(send)) : None -
    ContentBlock.id}> +
    ContentBlock.id}> ContentBlock.id, send)} + setDirtyCB={setDirty(contentBlock->ContentBlock.id, send)} contentBlock ?removeContentBlockCB ?moveContentBlockUpCB @@ -157,7 +157,7 @@ let editor = (target, state, send) => { />
    }) - |> React.array} + ->React.array}
    } @@ -175,12 +175,12 @@ let make = (~target, ~setDirtyCB) => { ) React.useEffect0(() => { - loadContentBlocks(target |> Target.id, send) + loadContentBlocks(target->Target.id, send) None }) React.useEffect1(() => { - let dirty = !(state.dirtyContentBlockIds |> Belt.Set.String.isEmpty) + let dirty = !(state.dirtyContentBlockIds->Belt.Set.String.isEmpty) setDirtyCB(dirty) None }, [state.dirtyContentBlockIds]) diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__ContentTypePicker.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__ContentTypePicker.res index be531ed91a..dd3191a213 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__ContentTypePicker.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__ContentTypePicker.res @@ -23,10 +23,10 @@ let button = (sortIndex, newContentBlockCB, kindOfButton) => { key=buttonText className="add-content-block__block-content-type-picker px-3 pt-4 pb-3 flex-1 text-center text-primary-200" onClick={event => { - event |> ReactEvent.Mouse.preventDefault + event->ReactEvent.Mouse.preventDefault newContentBlockCB(sortIndex, newBlock()) }}> -

    {buttonText |> str}

    +

    {buttonText->str}

    } @@ -41,7 +41,7 @@ let make = (~sortIndex, ~staticMode, ~newContentBlockCB) => { className="add-content-block__plus-button-container relative" onClick={_event => setVisibility(_ => !visibility)}>
    string_of_int)} + id={"add-block-" ++ (sortIndex->string_of_int)} title="Add block" className="add-content-block__plus-button bg-gray-200 hover:bg-gray-300 relative rounded-lg border border-gray-500 w-10 h-10 flex justify-center items-center mx-auto z-20"> @@ -49,10 +49,10 @@ let make = (~sortIndex, ~staticMode, ~newContentBlockCB) => {
    }
    string_of_int)}> + id={"content-type-picker-" ++ (sortIndex->string_of_int)}> {[MarkdownButton, ImageButton, EmbedButton, FileButton] - |> Array.map(button(sortIndex, newContentBlockCB)) - |> React.array} + ->Array.map(button(sortIndex, newContentBlockCB)) + ->React.array}
    } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__Course.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__Course.res index c5f64e7189..e81d5cbe01 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__Course.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__Course.res @@ -4,5 +4,5 @@ let id = t => t.id let decode = json => { open Json.Decode - {id: json |> field("id", string)} + {id: json->field("id", string)} } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__EvaluationCriteria.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__EvaluationCriteria.res index f73eaa62e5..75c2ee7e77 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__EvaluationCriteria.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__EvaluationCriteria.res @@ -10,7 +10,7 @@ let id = t => t.id let decode = json => { open Json.Decode { - name: json |> field("name", string), - id: json |> field("id", string), + name: json->field("name", string), + id: json->field("id", string), } } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__FileBlockEditor.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__FileBlockEditor.res index ceff97c723..c42974fe93 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__FileBlockEditor.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__FileBlockEditor.res @@ -1,15 +1,15 @@ let str = React.string let onChange = (contentBlock, updateContentBlockCB, event) => { - event |> ReactEvent.Form.preventDefault + event->ReactEvent.Form.preventDefault let newTitle = ReactEvent.Form.target(event)["value"] - let newContentBlock = contentBlock |> ContentBlock.updateFile(newTitle) + let newContentBlock = contentBlock->ContentBlock.updateFile(newTitle) updateContentBlockCB(newContentBlock) } @react.component let make = (~url, ~title, ~filename, ~contentBlock, ~updateContentBlockCB) => { - let titleInputId = "title-" ++ (contentBlock |> ContentBlock.id) + let titleInputId = "title-" ++ (contentBlock->ContentBlock.id)
    {
    -
    {title |> str}
    -
    {filename |> str}
    +
    {title->str}
    +
    {filename->str}
    @@ -31,8 +31,8 @@ let make = (~url, ~title, ~filename, ~contentBlock, ~updateContentBlockCB) => {
    - - {"(optional)" |> str} + + {"(optional)"->str} { - event |> ReactEvent.Form.preventDefault + event->ReactEvent.Form.preventDefault let newCaption = ReactEvent.Form.target(event)["value"] - let newContentBlock = contentBlock |> ContentBlock.updateImage(newCaption) + let newContentBlock = contentBlock->ContentBlock.updateImage(newCaption) updateContentBlockCB(newContentBlock) } @react.component let make = (~url, ~caption, ~contentBlock, ~updateContentBlockCB) => { - let captionInputId = "caption-" ++ (contentBlock |> ContentBlock.id) + let captionInputId = "caption-" ++ (contentBlock->ContentBlock.id)
    { | "" => React.null | caption => -
    {caption |> str}
    +
    {caption->str}
    }}
    - - {"(optional)" |> str} + + {"(optional)"->str} t.unlockOn let decode = json => { open Json.Decode { - id: json |> field("id", string), - name: json |> field("name", string), - number: json |> field("number", int), - unlockOn: json |> optional(field("unlockOn", string)) |> OptionUtils.map(DateFns.parseString), + id: json->field("id", string), + name: json->field("name", string), + number: json->field("number", int), + unlockOn: json->optional(field("unlockOn", string))->OptionUtils.map(DateFns.parseString), } } -let selectLevel = (levels, level_name) => levels |> List.find(q => q.name == level_name) +let selectLevel = (levels, level_name) => levels->List.find(q => q.name == level_name) let create = (id, name, number, unlockOn) => { id: id, @@ -33,8 +33,8 @@ let create = (id, name, number, unlockOn) => { } let updateList = (levels, level) => { - let oldLevels = levels |> List.filter(l => l.id !== level.id) - oldLevels |> List.rev |> List.append(list{level}) |> List.rev + let oldLevels = levels->List.filter(l => l.id !== level.id) + oldLevels->List.rev->List.append(list{level})->List.rev } -let sort = levels => levels |> List.sort((x, y) => x.number - y.number) +let sort = levels => levels->List.sort((x, y) => x.number - y.number) diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__LevelEditor.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__LevelEditor.res index 524a9ba5f4..641f85357a 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__LevelEditor.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__LevelEditor.res @@ -28,7 +28,7 @@ let reducer = (state, action) => } let updateName = (send, name) => { - let hasError = name |> String.trim |> String.length < 2 + let hasError = name->String.trim->String.length < 2 send(UpdateName(name, hasError)) } @@ -37,12 +37,12 @@ let saveDisabled = state => state.hasNameError || (!state.dirty || state.saving) let setPayload = (authenticityToken, state) => { let payload = Js.Dict.empty() - Js.Dict.set(payload, "authenticity_token", authenticityToken |> Js.Json.string) - Js.Dict.set(payload, "name", state.name |> Js.Json.string) + Js.Dict.set(payload, "authenticity_token", authenticityToken->Js.Json.string) + Js.Dict.set(payload, "name", state.name->Js.Json.string) switch state.unlockOn { - | Some(date) => Js.Dict.set(payload, "unlock_on", date |> Date.iso8601 |> Js.Json.string) - | None => Js.Dict.set(payload, "unlock_on", "" |> Js.Json.string) + | Some(date) => Js.Dict.set(payload, "unlock_on", date->Date.iso8601->Js.Json.string) + | None => Js.Dict.set(payload, "unlock_on", ""->Js.Json.string) } payload } @@ -52,8 +52,8 @@ let formClasses = value => let computeInitialState = level => switch level { | Some(level) => { - name: level |> Level.name, - unlockOn: level |> Level.unlockOn, + name: level->Level.name, + unlockOn: level->Level.unlockOn, hasNameError: false, dirty: false, saving: false, @@ -72,11 +72,11 @@ let make = (~level, ~course, ~authenticityToken, ~hideEditorActionCB, ~updateLev let (state, send) = React.useReducerWithMapState(reducer, level, computeInitialState) let handleErrorCB = () => send(UpdateSaving) let handleResponseCB = json => { - let id = json |> { + let id = json->{ open Json.Decode field("id", string) } - let number = json |> { + let number = json->{ open Json.Decode field("number", int) } @@ -90,7 +90,7 @@ let make = (~level, ~course, ~authenticityToken, ~hideEditorActionCB, ~updateLev let createLevel = (authenticityToken, course, state) => { send(UpdateSaving) - let course_id = course |> Course.id + let course_id = course->Course.id let url = "/school/courses/" ++ (course_id ++ "/levels") Api.create(url, setPayload(authenticityToken, state), handleResponseCB, handleErrorCB) } @@ -117,13 +117,13 @@ let make = (~level, ~course, ~authenticityToken, ~hideEditorActionCB, ~updateLev
    - {"Level Details" |> str} + {"Level Details"->str}
    - {"*" |> str} + {"*"->str} {state.hasNameError ?
    - {"not a valid name" |> str} + {"not a valid name"->str}
    : ReasonReact.null}
    {switch level { | Some(level) => - let id = level |> Level.id + let id = level->Level.id | None => @@ -165,7 +165,7 @@ let make = (~level, ~course, ~authenticityToken, ~hideEditorActionCB, ~updateLev disabled={saveDisabled(state)} onClick={_event => createLevel(authenticityToken, course, state)} className="w-full btn btn-large btn-primary"> - {"Create New Level" |> str} + {"Create New Level"->str} }}
    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__MarkdownBlockEditor.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__MarkdownBlockEditor.res index e8599ade3d..c1deae83b5 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__MarkdownBlockEditor.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__MarkdownBlockEditor.res @@ -1,7 +1,7 @@ let str = React.string let onChange = (contentBlock, updateContentBlockCB, value) => { - let newContentBlock = contentBlock |> ContentBlock.updateMarkdown(value) + let newContentBlock = contentBlock->ContentBlock.updateMarkdown(value) updateContentBlockCB(newContentBlock) } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__QuizQuestion.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__QuizQuestion.res index d631d960cd..b0001afbee 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__QuizQuestion.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__QuizQuestion.res @@ -25,28 +25,28 @@ let updateQuestion = (question, t) => {...t, question: question} let newAnswerOption = (id, t) => { let answerOption = CurriculumEditor__AnswerOption.empty(id, false) - let newAnswerOptions = t.answerOptions |> ArrayUtils.copyAndPush(answerOption) + let newAnswerOptions = t.answerOptions->ArrayUtils.copyAndPush(answerOption) {...t, answerOptions: newAnswerOptions} } let removeAnswerOption = (id, t) => { let newAnswerOptions = - t.answerOptions |> Js.Array.filter(a => a |> CurriculumEditor__AnswerOption.id !== id) + t.answerOptions->Js.Array.filter(a => a->CurriculumEditor__AnswerOption.id !== id) {...t, answerOptions: newAnswerOptions} } let replace = (id, answerOptionB, t) => { let newAnswerOptions = - t.answerOptions |> Array.map(a => - a |> CurriculumEditor__AnswerOption.id == id ? answerOptionB : a + t.answerOptions->Array.map(a => + a->CurriculumEditor__AnswerOption.id == id ? answerOptionB : a ) {...t, answerOptions: newAnswerOptions} } let markAsCorrect = (id, t) => { let newAnswerOptions = - t.answerOptions |> Array.map(a => - a |> CurriculumEditor__AnswerOption.id == id + t.answerOptions->Array.map(a => + a->CurriculumEditor__AnswerOption.id == id ? CurriculumEditor__AnswerOption.markAsCorrect(a) : CurriculumEditor__AnswerOption.markAsIncorrect(a) ) @@ -54,32 +54,32 @@ let markAsCorrect = (id, t) => { } let isValidQuizQuestion = t => { - let validQuestion = t.question |> Js.String.trim |> Js.String.length >= 1 + let validQuestion = t.question->Js.String.trim->Js.String.length >= 1 let hasZeroInvalidAnswerOptions = t.answerOptions - |> Js.Array.filter(answerOption => - answerOption |> CurriculumEditor__AnswerOption.isValidAnswerOption != true + ->Js.Array.filter(answerOption => + answerOption->CurriculumEditor__AnswerOption.isValidAnswerOption != true ) - |> ArrayUtils.isEmpty + ->ArrayUtils.isEmpty let hasOnlyOneCorrectAnswerOption = t.answerOptions - |> Js.Array.filter(answerOption => - answerOption |> CurriculumEditor__AnswerOption.correctAnswer == true + ->Js.Array.filter(answerOption => + answerOption->CurriculumEditor__AnswerOption.correctAnswer == true ) - |> Array.length == 1 + ->Array.length == 1 validQuestion && (hasZeroInvalidAnswerOptions && hasOnlyOneCorrectAnswerOption) } let makeFromJs = quizData => { id: quizData["id"], question: quizData["question"], - answerOptions: quizData["answerOptions"] |> Array.map(answerOption => - answerOption |> CurriculumEditor__AnswerOption.makeFromJs + answerOptions: quizData["answerOptions"]->Array.map(answerOption => + answerOption->CurriculumEditor__AnswerOption.makeFromJs ), } let quizAsJsObject = quiz => - quiz |> Array.map(quiz => + quiz->Array.map(quiz => { "question": quiz.question, "answerOptions": CurriculumEditor__AnswerOption.quizAnswersAsJsObject(quiz.answerOptions), diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__SortResourcesMutation.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__SortResourcesMutation.res index 18cf7701ed..f5c555ee80 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__SortResourcesMutation.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__SortResourcesMutation.res @@ -18,6 +18,6 @@ let resourceTypeToString = resourceType => let sort = (resourceType, resourceIds) => SortResourceMutation.make(~resourceIds, ~resourceType=resourceTypeToString(resourceType), ()) - |> GraphqlQuery.sendQuery(~notify=false) - |> Js.Promise.then_(_response => Js.Promise.resolve()) - |> ignore + ->GraphqlQuery.sendQuery(~notify=false) + ->Js.Promise.then_(_response => Js.Promise.resolve()) + ->ignore diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__Target.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__Target.res index 575707f4da..267dffc635 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__Target.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__Target.res @@ -34,17 +34,17 @@ let decodeVisbility = visibilityString => let decode = json => { open Json.Decode { - id: json |> field("id", string), - targetGroupId: json |> field("targetGroupId", string), - title: json |> field("title", string), - sortIndex: json |> field("sortIndex", int), - visibility: decodeVisbility(json |> field("visibility", string)), + id: json->field("id", string), + targetGroupId: json->field("targetGroupId", string), + title: json->field("title", string), + sortIndex: json->field("sortIndex", int), + visibility: decodeVisbility(json->field("visibility", string)), } } let updateList = (targets, target) => { - let oldTargets = targets |> List.filter(t => t.id !== target.id) - oldTargets |> List.rev |> List.append(list{target}) |> List.rev + let oldTargets = targets->List.filter(t => t.id !== target.id) + oldTargets->List.rev->List.append(list{target})->List.rev } let create = (~id, ~targetGroupId, ~title, ~sortIndex, ~visibility) => { @@ -55,7 +55,7 @@ let create = (~id, ~targetGroupId, ~title, ~sortIndex, ~visibility) => { visibility: visibility, } -let sort = targets => targets |> List.sort((x, y) => x.sortIndex - y.sortIndex) +let sort = targets => targets->List.sort((x, y) => x.sortIndex - y.sortIndex) let archive = t => {...t, visibility: Archived} @@ -66,13 +66,13 @@ let archived = t => | Draft => false } -let removeTarget = (target, targets) => targets |> List.filter(t => t.id != target.id) +let removeTarget = (target, targets) => targets->List.filter(t => t.id != target.id) let targetIdsInTargetGroup = (id, targets) => - targets |> List.filter(t => t.targetGroupId == id) |> List.map(t => t.id) + targets->List.filter(t => t.targetGroupId == id)->List.map(t => t.id) let updateSortIndex = sortedTargets => - sortedTargets |> List.mapi((sortIndex, t) => + sortedTargets->List.mapi((sortIndex, t) => create( ~id=t.id, ~targetGroupId=t.targetGroupId, diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetChecklistItemEditor.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetChecklistItemEditor.res index a2ef33216b..1bc3830918 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetChecklistItemEditor.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetChecklistItemEditor.res @@ -6,18 +6,18 @@ let str = React.string let updateTitle = (checklistItem, updateChecklistItemCB, event) => { let title = ReactEvent.Form.target(event)["value"] - let newChecklistItem = checklistItem |> ChecklistItem.updateTitle(title) + let newChecklistItem = checklistItem->ChecklistItem.updateTitle(title) updateChecklistItemCB(newChecklistItem) } let updateKind = (checklistItem, updateChecklistItemCB, kind) => { - let newChecklistItem = checklistItem |> ChecklistItem.updateKind(kind) + let newChecklistItem = checklistItem->ChecklistItem.updateKind(kind) updateChecklistItemCB(newChecklistItem) } let updateOptional = (checklistItem, updateChecklistItemCB, event) => { let optional = ReactEvent.Form.target(event)["checked"] - let newChecklistItem = checklistItem |> ChecklistItem.updateOptional(optional) + let newChecklistItem = checklistItem->ChecklistItem.updateOptional(optional) updateChecklistItemCB(newChecklistItem) } @@ -35,7 +35,7 @@ let selectedButtonIcon = kind => | MultiChoice(_choices) => "i-check-circle-alt-regular" } let checklistDropdown = (checklistItem, allowFileKind, updateChecklistItemCB) => { - let selectedKind = checklistItem |> ChecklistItem.kind + let selectedKind = checklistItem->ChecklistItem.kind let selectedButtonColor = switch selectedKind { | LongText => "blue" | ShortText => "orange" @@ -54,7 +54,7 @@ let checklistDropdown = (checklistItem, allowFileKind, updateChecklistItemCB) => - {selectedKind |> ChecklistItem.actionStringForKind |> str} + {selectedKind->ChecklistItem.actionStringForKind->str}
    @@ -65,60 +65,60 @@ let checklistDropdown = (checklistItem, allowFileKind, updateChecklistItemCB) => let defaultKindTypes = [ChecklistItem.LongText, ShortText, Link, MultiChoice(["Yes", "No"])] let allowedKindTypes = allowFileKind - ? defaultKindTypes |> Array.append([ChecklistItem.Files]) + ? defaultKindTypes->Array.append([ChecklistItem.Files]) : defaultKindTypes let contents = allowedKindTypes - |> Js.Array.filter(kind => kind != selectedKind) - |> Array.mapi((index, kind) => + ->Js.Array.filter(kind => kind != selectedKind) + ->Array.mapi((index, kind) => ) } let removeMultichoiceOption = (choiceIndex, checklistItem, updateChecklistItemCB) => { - let newChecklistItem = checklistItem |> ChecklistItem.removeMultichoiceOption(choiceIndex) + let newChecklistItem = checklistItem->ChecklistItem.removeMultichoiceOption(choiceIndex) updateChecklistItemCB(newChecklistItem) } let addMultichoiceOption = (checklistItem, updateChecklistItemCB) => { - let newChecklistItem = checklistItem |> ChecklistItem.addMultichoiceOption + let newChecklistItem = checklistItem->ChecklistItem.addMultichoiceOption updateChecklistItemCB(newChecklistItem) } let updateChoiceText = (choiceIndex, checklistItem, updateChecklistItemCB, event) => { let choice = ReactEvent.Form.target(event)["value"] - let newChecklistItem = checklistItem |> ChecklistItem.updateMultichoiceOption(choiceIndex, choice) + let newChecklistItem = checklistItem->ChecklistItem.updateMultichoiceOption(choiceIndex, choice) updateChecklistItemCB(newChecklistItem) } let multiChoiceEditor = (choices, checklistItem, removeMultichoiceOption, updateChecklistItemCB) =>
    -
    {"Choices:" |> str}
    +
    {"Choices:"->str}
    { let showRemoveIcon = Array.length(choices) > 2 choices - |> Array.mapi((index, choice) => -
    string_of_int}> + ->Array.mapi((index, choice) => +
    string_of_int}>
    string_of_int)} + name={"multichoice-input-" ++ (index + 1->string_of_int)} className="flex-1 appearance-none bg-transparent border-none leading-snug focus:outline-none" onChange={updateChoiceText(index, checklistItem, updateChecklistItemCB)} type_="text" value=choice /> @@ -126,18 +126,18 @@ let multiChoiceEditor = (choices, checklistItem, removeMultichoiceOption, update
    String.trim == ""} + message="Not a valid choice" active={choice->String.trim == ""} />
    ) - |> React.array + ->React.array }
    @@ -154,24 +154,24 @@ let controlIcon = (~icon, ~title, ~handler) => let filesNotice =
    - {"Note:" |> str} + {"Note:"->str} - {"Students can submit up to 3 files, limited to 5 MB each." |> str} + {"Students can submit up to 3 files, limited to 5 MB each."->str}
    let isRequiredStepTitleDuplicated = (checklist, item) => { - let trimmedTitle = item |> ChecklistItem.title |> String.trim + let trimmedTitle = item->ChecklistItem.title->String.trim if trimmedTitle == "" { false } else { checklist - |> Js.Array.filter(item => !ChecklistItem.optional(item)) - |> Js.Array.filter(checklistItem => - checklistItem |> ChecklistItem.title |> String.trim == trimmedTitle + ->Js.Array.filter(item => !ChecklistItem.optional(item)) + ->Js.Array.filter(checklistItem => + checklistItem->ChecklistItem.title->String.trim == trimmedTitle ) - |> Array.length > 1 + ->Array.length > 1 } } @@ -188,8 +188,8 @@ let make = ( ~allowFileKind, ) =>
    string_of_int} - ariaLabel={"Editor for checklist item " ++ (index + 1 |> string_of_int)} + key={index->string_of_int} + ariaLabel={"Editor for checklist item " ++ (index + 1->string_of_int)} className="flex items-start py-2 relative">
    @@ -199,36 +199,36 @@ let make = ( className="leading-tight" type_="checkbox" onChange={updateOptional(checklistItem, updateChecklistItemCB)} - id={index |> string_of_int} - checked={checklistItem |> ChecklistItem.optional} + id={index->string_of_int} + checked={checklistItem->ChecklistItem.optional} /> -
    string_of_int) ++ "-title")} + name={"checklist-item-" ++ ((index + 1->string_of_int) ++ "-title")} className="flex-grow appearance-none bg-transparent border-none leading-relaxed focus:outline-none" placeholder="Describe this step" onChange={updateTitle(checklistItem, updateChecklistItemCB)} type_="text" - value={checklistItem |> ChecklistItem.title} + value={checklistItem->ChecklistItem.title} />
    ChecklistItem.title |> String.trim == ""} + active={checklistItem->ChecklistItem.title->String.trim == ""} />
    - {switch checklistItem |> ChecklistItem.kind { + {switch checklistItem->ChecklistItem.kind { | MultiChoice(choices) => multiChoiceEditor(choices, checklistItem, removeMultichoiceOption, updateChecklistItemCB) | Files => filesNotice @@ -238,17 +238,17 @@ let make = ( }}
    string_of_int)} + ariaLabel={"Controls for checklist item " ++ (index + 1->string_of_int)} className="-mr-10 flex-shrink-0 border bg-gray-100 border rounded-lg flex flex-col text-xs sticky top-0"> {controlIcon( ~icon="fa-arrow-up", ~title="Move Up", - ~handler=moveChecklistItemUpCB |> OptionUtils.map((cb, _) => cb()), + ~handler=moveChecklistItemUpCB->OptionUtils.map((cb, _) => cb()), )} {controlIcon( ~icon="fa-arrow-down", ~title="Move Down", - ~handler=moveChecklistItemDownCB |> OptionUtils.map((cb, _) => cb()), + ~handler=moveChecklistItemDownCB->OptionUtils.map((cb, _) => cb()), )} {controlIcon(~icon="fa-copy", ~title="Copy", ~handler=Some(_ => copyChecklistItemCB()))} {controlIcon( diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetDetails.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetDetails.res index 16b864fa6c..32610cefb3 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetDetails.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetDetails.res @@ -70,11 +70,11 @@ let makeFromJs = targetData => { targetGroupId: targetData["targetGroupId"], evaluationCriteria: targetData["evaluationCriteria"], prerequisiteTargets: targetData["prerequisiteTargets"], - quiz: targetData["quiz"] |> Array.map(quizQuestion => - quizQuestion |> CurriculumEditor__QuizQuestion.makeFromJs + quiz: targetData["quiz"]->Array.map(quizQuestion => + quizQuestion->CurriculumEditor__QuizQuestion.makeFromJs ), linkToComplete: targetData["linkToComplete"], completionInstructions: targetData["completionInstructions"], - checklist: targetData["checklist"] |> Json.Decode.array(TargetChecklistItem.decode), + checklist: targetData["checklist"]->Json.Decode.array(TargetChecklistItem.decode), visibility: visibilityFromJs(targetData["visibility"]), } diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetDetailsEditor.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetDetailsEditor.res index a86d699050..9e21a887f0 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetDetailsEditor.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetDetailsEditor.res @@ -88,21 +88,21 @@ module TargetDetailsQuery = %graphql(` let loadTargetDetails = (targetId, send) => TargetDetailsQuery.make(~targetId, ()) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(result => { + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(result => { let targetDetails = TargetDetails.makeFromJs(result["targetDetails"]) send(SaveTargetDetails(targetDetails)) Js.Promise.resolve() }) - |> ignore + ->ignore let defaultChecklist = [ ChecklistItem.make(~title="Describe your submission", ~kind=LongText, ~optional=false), ] let computeMethodOfCompletion = targetDetails => { - let hasQuiz = targetDetails |> TargetDetails.quiz |> ArrayUtils.isNotEmpty - let hasEvaluationCriteria = targetDetails.evaluationCriteria |> ArrayUtils.isNotEmpty + let hasQuiz = targetDetails->TargetDetails.quiz->ArrayUtils.isNotEmpty + let hasEvaluationCriteria = targetDetails.evaluationCriteria->ArrayUtils.isNotEmpty let hasLinkToComplete = switch targetDetails.linkToComplete { | Some(_) => true | None => false @@ -120,9 +120,9 @@ let reducer = (state, action) => | SaveTargetDetails(targetDetails) => let methodOfCompletion = computeMethodOfCompletion(targetDetails) let checklist = - targetDetails.checklist |> ArrayUtils.isNotEmpty ? targetDetails.checklist : defaultChecklist + targetDetails.checklist->ArrayUtils.isNotEmpty ? targetDetails.checklist : defaultChecklist let quiz = - targetDetails.quiz |> ArrayUtils.isNotEmpty ? targetDetails.quiz : [QuizQuestion.empty("0")] + targetDetails.quiz->ArrayUtils.isNotEmpty ? targetDetails.quiz : [QuizQuestion.empty("0")] { ...state, title: targetDetails.title, @@ -182,18 +182,18 @@ let reducer = (state, action) => } | UpdateTargetRole(role) => {...state, role: role, dirty: true} | AddQuizQuestion => - let quiz = Array.append(state.quiz, [QuizQuestion.empty(Js.Date.now() |> Js.Float.toString)]) + let quiz = Array.append(state.quiz, [QuizQuestion.empty(Js.Date.now()->Js.Float.toString)]) {...state, quiz: quiz, dirty: true} | UpdateQuizQuestion(id, quizQuestion) => - let quiz = state.quiz |> Array.map(q => QuizQuestion.id(q) == id ? quizQuestion : q) + let quiz = state.quiz->Array.map(q => QuizQuestion.id(q) == id ? quizQuestion : q) {...state, quiz: quiz, dirty: true} | RemoveQuizQuestion(id) => - let quiz = state.quiz |> Js.Array.filter(q => QuizQuestion.id(q) != id) + let quiz = state.quiz->Js.Array.filter(q => QuizQuestion.id(q) != id) {...state, quiz: quiz, dirty: true} | UpdateVisibility(visibility) => {...state, visibility: visibility, dirty: true} | UpdateChecklistItem(indexToChange, newItem) => { ...state, - checklist: state.checklist |> Array.mapi((index, checklistItem) => + checklist: state.checklist->Array.mapi((index, checklistItem) => index == indexToChange ? newItem : checklistItem ), dirty: true, @@ -205,22 +205,22 @@ let reducer = (state, action) => } | RemoveChecklistItem(index) => { ...state, - checklist: state.checklist |> ChecklistItem.removeItem(index), + checklist: state.checklist->ChecklistItem.removeItem(index), dirty: true, } | MoveChecklistItemUp(index) => { ...state, - checklist: state.checklist |> ChecklistItem.moveUp(index), + checklist: state.checklist->ChecklistItem.moveUp(index), dirty: true, } | MoveChecklistItemDown(index) => { ...state, - checklist: state.checklist |> ChecklistItem.moveDown(index), + checklist: state.checklist->ChecklistItem.moveDown(index), dirty: true, } | CopyChecklistItem(index) => { ...state, - checklist: state.checklist |> ChecklistItem.copy(index), + checklist: state.checklist->ChecklistItem.copy(index), dirty: true, } | UpdateSaving => {...state, saving: !state.saving} @@ -235,47 +235,47 @@ let updateTitle = (send, event) => { let eligiblePrerequisiteTargets = (targetId, targets, targetGroups) => { let targetGroupId = targets - |> ListUtils.unsafeFind( + ->ListUtils.unsafeFind( target => targetId == Target.id(target), "Unable to find target with ID: " ++ targetId, ) - |> Target.targetGroupId + ->Target.targetGroupId let targetGroup = targetGroups - |> Array.of_list - |> ArrayUtils.unsafeFind( + ->Array.of_list + ->ArrayUtils.unsafeFind( tg => TargetGroup.id(tg) == targetGroupId, "Cannot find target group with ID: " ++ targetGroupId, ) - let levelId = targetGroup |> TargetGroup.levelId + let levelId = targetGroup->TargetGroup.levelId let targetGroupsInSameLevel = targetGroups - |> List.filter(tg => TargetGroup.levelId(tg) == levelId) - |> List.map(tg => TargetGroup.id(tg)) + ->List.filter(tg => TargetGroup.levelId(tg) == levelId) + ->List.map(tg => TargetGroup.id(tg)) targets - |> List.filter(target => !(target |> Target.archived)) - |> List.filter(target => targetGroupsInSameLevel |> List.mem(Target.targetGroupId(target))) - |> List.filter(target => Target.id(target) != targetId) - |> Array.of_list + ->List.filter(target => !(target->Target.archived)) + ->List.filter(target => targetGroupsInSameLevel->List.mem(Target.targetGroupId(target))) + ->List.filter(target => Target.id(target) != targetId) + ->Array.of_list } let setPrerequisiteSearch = (send, value) => send(UpdatePrerequisiteSearchInput(value)) let selectPrerequisiteTarget = (send, state, target) => { - let updatedPrerequisites = state.prerequisiteTargets |> Js.Array.concat([target |> Target.id]) + let updatedPrerequisites = state.prerequisiteTargets->Js.Array.concat([target->Target.id]) send(UpdatePrerequisiteTargets(updatedPrerequisites)) } let deSelectPrerequisiteTarget = (send, state, target) => { let updatedPrerequisites = - state.prerequisiteTargets |> Js.Array.filter(targetId => targetId != Target.id(target)) + state.prerequisiteTargets->Js.Array.filter(targetId => targetId != Target.id(target)) send(UpdatePrerequisiteTargets(updatedPrerequisites)) } module SelectablePrerequisiteTargets = { type t = Target.t - let value = t => t |> Target.title + let value = t => t->Target.title let searchString = value } @@ -283,19 +283,19 @@ module MultiSelectForPrerequisiteTargets = MultiselectInline.Make(SelectablePrer let prerequisiteTargetEditor = (send, eligiblePrerequisiteTargets, state) => { let selected = - eligiblePrerequisiteTargets |> Js.Array.filter(target => - state.prerequisiteTargets |> Array.mem(Target.id(target)) + eligiblePrerequisiteTargets->Js.Array.filter(target => + state.prerequisiteTargets->Array.mem(Target.id(target)) ) let unselected = - eligiblePrerequisiteTargets |> Js.Array.filter(target => - !(state.prerequisiteTargets |> Array.mem(Target.id(target))) + eligiblePrerequisiteTargets->Js.Array.filter(target => + !(state.prerequisiteTargets->Array.mem(Target.id(target))) ) - eligiblePrerequisiteTargets |> ArrayUtils.isNotEmpty + eligiblePrerequisiteTargets->ArrayUtils.isNotEmpty ?
    | MarkAsComplete => false } -let validNumberOfEvaluationCriteria = state => state.evaluationCriteria |> ArrayUtils.isNotEmpty +let validNumberOfEvaluationCriteria = state => state.evaluationCriteria->ArrayUtils.isNotEmpty let setEvaluationCriteriaSearch = (send, value) => send(UpdateEvaluationCriteriaSearchInput(value)) let selectEvaluationCriterion = (send, state, evaluationCriterion) => { let updatedEvaluationCriteria = - state.evaluationCriteria |> Js.Array.concat([evaluationCriterion |> EvaluationCriteria.id]) + state.evaluationCriteria->Js.Array.concat([evaluationCriterion->EvaluationCriteria.id]) send(UpdateEvaluationCriteria(updatedEvaluationCriteria)) } let deSelectEvaluationCriterion = (send, state, evaluationCriterion) => { let updatedEvaluationCriteria = - state.evaluationCriteria |> Js.Array.filter(ecId => + state.evaluationCriteria->Js.Array.filter(ecId => ecId != EvaluationCriteria.id(evaluationCriterion) ) send(UpdateEvaluationCriteria(updatedEvaluationCriteria)) @@ -354,7 +354,7 @@ let deSelectEvaluationCriterion = (send, state, evaluationCriterion) => { module SelectableEvaluationCriteria = { type t = EvaluationCriteria.t - let value = t => t |> EvaluationCriteria.name + let value = t => t->EvaluationCriteria.name let searchString = value let make = (evaluationCriterion): t => evaluationCriterion @@ -365,23 +365,23 @@ module MultiSelectForEvaluationCriteria = MultiselectInline.Make(SelectableEvalu let evaluationCriteriaEditor = (state, evaluationCriteria, send) => { let selected = evaluationCriteria - |> Js.Array.filter(ec => state.evaluationCriteria |> Array.mem(EvaluationCriteria.id(ec))) - |> Array.map(ec => SelectableEvaluationCriteria.make(ec)) + ->Js.Array.filter(ec => state.evaluationCriteria->Array.mem(EvaluationCriteria.id(ec))) + ->Array.map(ec => SelectableEvaluationCriteria.make(ec)) let unselected = evaluationCriteria - |> Js.Array.filter(ec => !(state.evaluationCriteria |> Array.mem(EvaluationCriteria.id(ec)))) - |> Array.map(ec => SelectableEvaluationCriteria.make(ec)) + ->Js.Array.filter(ec => !(state.evaluationCriteria->Array.mem(EvaluationCriteria.id(ec)))) + ->Array.map(ec => SelectableEvaluationCriteria.make(ec))
    {validNumberOfEvaluationCriteria(state) ? React.null :
    - {"Atleast one has to be selected" |> str} + {"Atleast one has to be selected"->str}
    }
    value=state.linkToComplete onChange={updateLinkToComplete(send)} /> - {state.linkToComplete |> UrlUtils.isInvalid(false) + {state.linkToComplete->UrlUtils.isInvalid(false) ? : React.null}
    @@ -474,11 +474,11 @@ let methodOfCompletionButton = (methodOfCompletion, state, send, index) => { | #MarkAsComplete => markIcon } -
    string_of_int} className="w-1/3 px-2"> +
    string_of_int} className="w-1/3 px-2">
    } @@ -490,27 +490,27 @@ let methodOfCompletionSelector = (state, send) => className="block tracking-wide text-sm font-semibold mr-6 mb-3" htmlFor="method_of_completion"> - {"How do you want the student to complete the target?" |> str} + {"How do you want the student to complete the target?"->str}
    {[#MarkAsComplete, #VisitLink, #TakeQuiz] - |> Array.mapi((index, methodOfCompletion) => + ->Array.mapi((index, methodOfCompletion) => methodOfCompletionButton(methodOfCompletion, state, send, index) ) - |> React.array} + ->React.array}
    let isValidQuiz = quiz => quiz - |> Js.Array.filter(quizQuestion => quizQuestion |> QuizQuestion.isValidQuizQuestion != true) - |> ArrayUtils.isEmpty + ->Js.Array.filter(quizQuestion => quizQuestion->QuizQuestion.isValidQuizQuestion != true) + ->ArrayUtils.isEmpty let isValidChecklist = checklist => checklist - |> Js.Array.filter(checklistItem => checklistItem |> ChecklistItem.isValidChecklistItem != true) - |> ArrayUtils.isEmpty + ->Js.Array.filter(checklistItem => checklistItem->ChecklistItem.isValidChecklistItem != true) + ->ArrayUtils.isEmpty let addQuizQuestion = (send, event) => { ReactEvent.Mouse.preventDefault(event) @@ -519,14 +519,14 @@ let addQuizQuestion = (send, event) => { let updateQuizQuestionCB = (send, id, quizQuestion) => send(UpdateQuizQuestion(id, quizQuestion)) let removeQuizQuestionCB = (send, id) => send(RemoveQuizQuestion(id)) -let questionCanBeRemoved = state => state.quiz |> Array.length > 1 +let questionCanBeRemoved = state => state.quiz->Array.length > 1 let quizEditor = (state, send) =>
    {isValidQuiz(state.quiz) @@ -536,45 +536,45 @@ let quizEditor = (state, send) => active=true />} {state.quiz - |> Array.mapi((index, quizQuestion) => + ->Array.mapi((index, quizQuestion) => QuizQuestion.id} - questionNumber={index + 1 |> string_of_int} + key={quizQuestion->QuizQuestion.id} + questionNumber={index + 1->string_of_int} quizQuestion updateQuizQuestionCB={updateQuizQuestionCB(send)} removeQuizQuestionCB={removeQuizQuestionCB(send)} questionCanBeRemoved={questionCanBeRemoved(state)} /> ) - |> ReasonReact.array} + ->ReasonReact.array} -
    {"Add another Question" |> str}
    +
    {"Add another Question"->str}
    let doRequiredStepsHaveUniqueTitles = checklist => { - let requiredSteps = checklist |> Js.Array.filter(item => !(item |> ChecklistItem.optional)) + let requiredSteps = checklist->Js.Array.filter(item => !(item->ChecklistItem.optional)) requiredSteps - |> Array.map(ChecklistItem.title) - |> Array.map(String.trim) - |> ArrayUtils.distinct - |> Array.length == Array.length(requiredSteps) + ->Array.map(ChecklistItem.title) + ->Array.map(String.trim) + ->ArrayUtils.distinct + ->Array.length == Array.length(requiredSteps) } -let isValidTitle = title => title |> String.trim |> String.length > 0 +let isValidTitle = title => title->String.trim->String.length > 0 let isValidMethodOfCompletion = state => switch state.methodOfCompletion { | TakeQuiz => isValidQuiz(state.quiz) | MarkAsComplete => true | Evaluated => - state.evaluationCriteria |> ArrayUtils.isNotEmpty && isValidChecklist(state.checklist) - | VisitLink => !(state.linkToComplete |> UrlUtils.isInvalid(false)) + state.evaluationCriteria->ArrayUtils.isNotEmpty && isValidChecklist(state.checklist) + | VisitLink => !(state.linkToComplete->UrlUtils.isInvalid(false)) } let saveDisabled = ( @@ -599,14 +599,14 @@ module UpdateTargetQuery = %graphql(` let updateTarget = (target, state, send, updateTargetCB, event) => { ReactEvent.Mouse.preventDefault(event) send(UpdateSaving) - let id = target |> Target.id - let sortIndex = target |> Target.sortIndex - let role = state.role |> TargetDetails.roleAsString - let visibilityAsString = state.visibility |> TargetDetails.visibilityAsString + let id = target->Target.id + let sortIndex = target->Target.sortIndex + let role = state.role->TargetDetails.roleAsString + let visibilityAsString = state.visibility->TargetDetails.visibilityAsString let quizAsJs = state.quiz - |> Js.Array.filter(question => QuizQuestion.isValidQuizQuestion(question)) - |> QuizQuestion.quizAsJsObject + ->Js.Array.filter(question => QuizQuestion.isValidQuizQuestion(question)) + ->QuizQuestion.quizAsJsObject let (quiz, evaluationCriteria, linkToComplete, checklist) = switch state.methodOfCompletion { | Evaluated => ([], state.evaluationCriteria, "", state.checklist) @@ -640,11 +640,11 @@ let updateTarget = (target, state, send, updateTargetCB, event) => { ~completionInstructions=state.completionInstructions, ~linkToComplete, ~visibility=visibilityAsString, - ~checklist=checklist |> ChecklistItem.encodeChecklist, + ~checklist=checklist->ChecklistItem.encodeChecklist, (), ) - |> GraphqlQuery.sendQuery - |> Js.Promise.then_(result => { + ->GraphqlQuery.sendQuery + ->Js.Promise.then_(result => { result["updateTarget"]["success"] ? { send(ResetEditor) @@ -653,7 +653,7 @@ let updateTarget = (target, state, send, updateTargetCB, event) => { : send(UpdateSaving) Js.Promise.resolve() }) - |> ignore + ->ignore () } @@ -687,7 +687,7 @@ let make = ( completionInstructions: "", }, ) - let targetId = target |> Target.id + let targetId = target->Target.id React.useEffect1(() => { loadTargetDetails(targetId, send) None @@ -715,7 +715,7 @@ let make = ( className="flex items-center inline-block tracking-wide text-sm font-semibold mb-2" htmlFor="title"> - {"Title" |> str} + {"Title"->str}
    - {"Will a coach review submissions on this target?" |> str} + {"Will a coach review submissions on this target?"->str}
    - {"Yes" |> str} + {"Yes"->str}
    @@ -760,21 +760,21 @@ let make = (
    - {"These are the steps that a student must complete to submit work on a target. This information will be shown to the coach for review." |> str} + {"These are the steps that a student must complete to submit work on a target. This information will be shown to the coach for review."->str}
    { let allowFileKind = state.checklist - |> Js.Array.filter(item => item |> ChecklistItem.isFilesKind) - |> ArrayUtils.isEmpty + ->Js.Array.filter(item => item->ChecklistItem.isFilesKind) + ->ArrayUtils.isEmpty state.checklist - |> Array.mapi((index, checklistItem) => { + ->Array.mapi((index, checklistItem) => { let moveChecklistItemUpCB = index > 0 ? Some(() => send(MoveChecklistItemUp(index))) : None @@ -785,7 +785,7 @@ let make = ( string_of_int} + key={index->string_of_int} checklistItem index updateChecklistItemCB={newChecklistItem => @@ -797,28 +797,28 @@ let make = ( allowFileKind /> }) - |> React.array + ->React.array } - {state.checklist |> ArrayUtils.isEmpty + {state.checklist->ArrayUtils.isEmpty ?
    - {"This target has no steps. Students will be able to submit target without any action!" |> str} + {"This target has no steps. Students will be able to submit target without any action!"->str}
    : React.null} - {state.checklist |> Array.length >= 15 + {state.checklist->Array.length >= 15 ?
    - {"Maximum allowed checklist items is 15!" |> str} + {"Maximum allowed checklist items is 15!"->str}
    : React.null}
    @@ -831,7 +831,7 @@ let make = ( : methodOfCompletionSelector(state, send)} {switch state.methodOfCompletion { | Evaluated => - evaluationCriteriaEditor(state, evaluationCriteria |> Array.of_list, send) + evaluationCriteriaEditor(state, evaluationCriteria->Array.of_list, send) | MarkAsComplete => React.null | TakeQuiz => quizEditor(state, send) | VisitLink => linkEditor(state, send) @@ -839,12 +839,12 @@ let make = (
    - {"Should students in a team submit work on a target individually, or together?" |> str} + {"Should students in a team submit work on a target individually, or together?"->str}
    @@ -884,13 +884,13 @@ let make = ( - {"Use this to remind the student about something important. These instructions will be displayed close to where students complete the target." |> str} + {"Use this to remind the student about something important. These instructions will be displayed close to where students complete the target."->str}
    - {"Target Visibility" |> str} + {"Target Visibility"->str}
    {[TargetDetails.Live, Archived, Draft] - |> Array.mapi((index, visibility) => + ->Array.mapi((index, visibility) => ) - |> React.array} + ->React.array}
    @@ -950,7 +950,7 @@ let make = ( )} onClick={updateTarget(target, state, send, updateTargetCB)} className="btn btn-primary w-full text-white font-bold py-3 px-6 shadow rounded focus:outline-none"> - {"Update Target" |> str} + {"Update Target"->str}
    diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetDrawer.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetDrawer.res index 18ce8ca763..de8f2416a4 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetDrawer.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetDrawer.res @@ -39,12 +39,12 @@ let tab = (page, selectedPage, pathPrefix, dirty, setDirty) => { : None setDirty(_ => false)} className=classes> - {title |> str} + {title->str} } let closeDrawer = course => - ReasonReactRouter.push("/school/courses/" ++ ((course |> Course.id) ++ "/curriculum")) + ReasonReactRouter.push("/school/courses/" ++ ((course->Course.id) ++ "/curriculum")) @react.component let make = (~targets, ~targetGroups, ~evaluationCriteria, ~course, ~updateTargetCB) => { @@ -54,13 +54,13 @@ let make = (~targets, ~targetGroups, ~evaluationCriteria, ~course, ~updateTarget switch url.path { | list{"school", "courses", _courseId, "targets", targetId, pageName} => let target = - targets |> ListUtils.unsafeFind( - t => t |> Target.id == targetId, + targets->ListUtils.unsafeFind( + t => t->Target.id == targetId, "Could not find target for editor drawer with the ID " ++ targetId, ) let pathPrefix = - "/school/courses/" ++ ((course |> Course.id) ++ ("/targets/" ++ (targetId ++ "/"))) + "/school/courses/" ++ ((course->Course.id) ++ ("/targets/" ++ (targetId ++ "/"))) let (innerComponent, selectedPage) = switch pageName { | "content" => ( @@ -81,7 +81,7 @@ let make = (~targets, ~targetGroups, ~evaluationCriteria, ~course, ~updateTarget | "versions" => (, Versions) | otherPage => Rollbar.warning("Unexpected page requested for target editor drawer: " ++ otherPage) - (
    {"Unexpected error. Please reload the page." |> str}
    , Content) + (
    {"Unexpected error. Please reload the page."->str}
    , Content) } confirmDirtyAction(dirty, () => closeDrawer(course))}>
    -

    {target |> Target.title |> str}

    +

    {target->Target.title->str}

    {tab(Content, selectedPage, pathPrefix, dirty, setDirty)} {tab(Details, selectedPage, pathPrefix, dirty, setDirty)} diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetGroup.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetGroup.res index 2f258e19e1..ed11390b03 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetGroup.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetGroup.res @@ -23,13 +23,13 @@ let archived = t => t.archived let decode = json => { open Json.Decode { - id: json |> field("id", string), - name: json |> field("name", string), - description: json |> field("description", nullable(string)) |> Js.Null.toOption, - levelId: json |> field("levelId", string), - milestone: json |> field("milestone", bool), - sortIndex: json |> field("sortIndex", int), - archived: json |> field("archived", bool), + id: json->field("id", string), + name: json->field("name", string), + description: json->field("description", nullable(string))->Js.Null.toOption, + levelId: json->field("levelId", string), + milestone: json->field("milestone", bool), + sortIndex: json->field("sortIndex", int), + archived: json->field("archived", bool), } } @@ -44,17 +44,17 @@ let create = (id, name, description, milestone, levelId, sortIndex, archived) => } let updateList = (targetGroups, targetGroup) => { - let oldTargetGroups = targetGroups |> List.filter(tg => tg.id !== targetGroup.id) - oldTargetGroups |> List.rev |> List.append(list{targetGroup}) |> List.rev + let oldTargetGroups = targetGroups->List.filter(tg => tg.id !== targetGroup.id) + oldTargetGroups->List.rev->List.append(list{targetGroup})->List.rev } -let sort = targetGroups => targetGroups |> List.sort((x, y) => x.sortIndex - y.sortIndex) +let sort = targetGroups => targetGroups->List.sort((x, y) => x.sortIndex - y.sortIndex) let unarchive = t => {...t, archived: false} -let find = (id, targetGroups) => targetGroups |> List.find(tg => tg.id == id) +let find = (id, targetGroups) => targetGroups->List.find(tg => tg.id == id) let updateSortIndex = sortedTargetGroups => - sortedTargetGroups |> List.mapi((sortIndex, t) => + sortedTargetGroups->List.mapi((sortIndex, t) => create(t.id, t.name, t.description, t.milestone, t.levelId, sortIndex, t.archived) ) diff --git a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetGroupEditor.res b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetGroupEditor.res index 060c2df117..439dd563de 100644 --- a/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetGroupEditor.res +++ b/tests/syntax_tests/data/idempotency/pupilfirst/schools/CurriculumEditor__TargetGroupEditor.res @@ -33,7 +33,7 @@ let reducer = (state, action) => } let updateName = (send, name) => { - let hasError = name |> String.length < 2 + let hasError = name->String.length < 2 send(UpdateName(name, hasError)) } @@ -42,11 +42,11 @@ let saveDisabled = state => state.hasNameError || (!state.dirty || state.saving) let setPayload = (authenticityToken, state) => { let payload = Js.Dict.empty() let milestone = state.milestone == true ? "true" : "false" - Js.Dict.set(payload, "authenticity_token", authenticityToken |> Js.Json.string) - Js.Dict.set(payload, "archived", state.isArchived |> Js.Json.boolean) - Js.Dict.set(payload, "name", state.name |> Js.Json.string) - Js.Dict.set(payload, "description", state.description |> Js.Json.string) - Js.Dict.set(payload, "milestone", milestone |> Js.Json.string) + Js.Dict.set(payload, "authenticity_token", authenticityToken->Js.Json.string) + Js.Dict.set(payload, "archived", state.isArchived->Js.Json.boolean) + Js.Dict.set(payload, "name", state.name->Js.Json.string) + Js.Dict.set(payload, "description", state.description->Js.Json.string) + Js.Dict.set(payload, "milestone", milestone->Js.Json.string) payload } @@ -60,15 +60,15 @@ let formClasses = value => let computeInitialState = targetGroup => switch targetGroup { | Some(targetGroup) => { - name: targetGroup |> TargetGroup.name, - description: switch targetGroup |> TargetGroup.description { + name: targetGroup->TargetGroup.name, + description: switch targetGroup->TargetGroup.description { | Some(description) => description | None => "" }, - milestone: targetGroup |> TargetGroup.milestone, + milestone: targetGroup->TargetGroup.milestone, hasNameError: false, dirty: false, - isArchived: targetGroup |> TargetGroup.archived, + isArchived: targetGroup->TargetGroup.archived, saving: false, } | None => { @@ -93,11 +93,11 @@ let make = ( let (state, send) = React.useReducerWithMapState(reducer, targetGroup, computeInitialState) let handleErrorCB = () => send(UpdateSaving) let handleResponseCB = json => { - let id = json |> { + let id = json->{ open Json.Decode field("id", string) } - let sortIndex = json |> { + let sortIndex = json->{ open Json.Decode field("sortIndex", int) } @@ -147,13 +147,13 @@ let make = (
    - {"Target Group Details" |> str} + {"Target Group Details"->str}
    - {"*" |> str} + {"*"->str} - {"not a valid Title" |> str} + {"not a valid Title"->str}
    : ReasonReact.null}