diff --git a/CHANGES.md b/CHANGES.md
index bdfbc432e..eb5cf76fc 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -1,5 +1,6 @@
# 0.17.0
+* Support custom `data-*` attributes in DOM JSX, including optional string values (@anmonteiro in https://github.com/reasonml/reason-react/pull/933)
* Upgrade `ppxlib` lower bound to `0.36` (@anmonteiro in https://github.com/reasonml/reason-react/pull/883)
* Remove `fomat` from ReactDOM's props (@davesnx in https://github.com/reasonml/reason-react/pull/929)
* Fix typo on `onEncrypted` (@davesnx in https://github.com/reasonml/reason-react/pull/930)
diff --git a/ppx/dom_props.ml b/ppx/dom_props.ml
new file mode 100644
index 000000000..74625d3c5
--- /dev/null
+++ b/ppx/dom_props.ml
@@ -0,0 +1,295 @@
+open Ppxlib
+open Ast_builder.Default
+
+let attribute ~loc ?(payload = PStr []) name =
+ attribute ~loc ~name:{ txt = name; loc } ~payload
+
+let data_attribute name =
+ (* Keep the standard [data] and [datatype] props on the ordinary DOM path.
+ Other data-prefixed names follow server-reason-react's conversion. *)
+ if
+ String.starts_with ~prefix:"data" name
+ && name <> "data" && name <> "datatype"
+ then (
+ let len = String.length name in
+ let is_upper c = c >= 'A' && c <= 'Z' in
+ let is_lower c = c >= 'a' && c <= 'z' in
+ let buffer = Buffer.create (len + 4) in
+ String.iteri
+ (fun i c ->
+ if c = '_' then Buffer.add_char buffer '_'
+ else if is_upper c then (
+ let prev = if i > 0 then Some name.[i - 1] else None in
+ let next_is_lower = i + 1 < len && is_lower name.[i + 1] in
+ let starts_word =
+ match prev with
+ | None | Some '_' -> false
+ | Some p -> (not (is_upper p)) || next_is_lower
+ in
+ if starts_word then Buffer.add_char buffer '-';
+ Buffer.add_char buffer (Char.lowercase_ascii c))
+ else Buffer.add_char buffer c)
+ name;
+ Some (Buffer.contents buffer))
+ else None
+
+(* These are the [mel.as] conventions used by ReactDOM.domProps. Ordinary
+ React prop names, such as className and onClick, keep their spelling. *)
+let js_name name =
+ match name with
+ | "as_" | "begin_" | "end_" | "in_" | "open_" | "to_" | "type_" ->
+ Some (String.sub name 0 (String.length name - 1))
+ | _ when String.length name > 4 && String.sub name 0 4 = "aria" ->
+ Some
+ ("aria-"
+ ^ String.lowercase_ascii (String.sub name 4 (String.length name - 4)))
+ | _ -> None
+
+let mel_obj_name name =
+ let rec has_double_underscore i =
+ i + 1 < String.length name
+ && ((name.[i] = '_' && name.[i + 1] = '_') || has_double_underscore (i + 1))
+ in
+ (* [mel.obj] strips the last [__] suffix even after [mel.as]. Append a suffix
+ of our own so underscores in the actual attribute name remain intact. *)
+ if has_double_underscore 0 then name ^ "__" else name
+
+let label_name = function
+ | Labelled name | Optional name -> name
+ | Nolabel -> ""
+
+let validate_data_attributes ~tag_name args =
+ let seen = Hashtbl.create 8 in
+ List.iter
+ (fun (label, expression) ->
+ let jsx_name = label_name label in
+ Option.iter
+ (fun name ->
+ if String.contains name '\'' then
+ Location.raise_errorf ~loc:expression.pexp_loc
+ "JSX: %s renders as the invalid DOM attribute name %S" jsx_name
+ name;
+ match Hashtbl.find_opt seen name with
+ | None -> Hashtbl.add seen name jsx_name
+ | Some first when String.equal first jsx_name ->
+ Location.raise_errorf ~loc:expression.pexp_loc
+ "JSX: the prop %s appears more than once on <%s>" jsx_name
+ tag_name
+ | Some first ->
+ Location.raise_errorf ~loc:expression.pexp_loc
+ "JSX: %s and %s both render as the attribute %s" jsx_name first
+ name)
+ (data_attribute jsx_name))
+ args
+
+let ignored_type ~loc typ =
+ { typ with ptyp_attributes = [ attribute ~loc "mel.ignore" ] }
+
+(* [mel.obj] requires a literal [unit] type for unlabelled arguments. Use an
+ ignored labelled argument so the type can be qualified against shadowing. *)
+let make_label = function Nolabel -> Labelled "__jsx_unit" | label -> label
+
+type prop = {
+ label : arg_label;
+ variable : string;
+ typ : core_type;
+ data_name : string option;
+ expression : expression;
+}
+
+let make ~loc ~tag_name ~dom_props args =
+ if
+ not
+ (List.exists
+ (fun (label, _) -> Option.is_some (data_attribute (label_name label)))
+ args)
+ then dom_props args
+ else
+ let () = validate_data_attributes ~tag_name args in
+ let ghost_loc = { loc with loc_ghost = true } in
+ let synthetic_loc = Location.none in
+ let stdlib_type name =
+ ptyp_constr ~loc:ghost_loc
+ { txt = Ldot (Ldot (Lident "Stdlib", name), "t"); loc = ghost_loc }
+ []
+ in
+ let unit_type = stdlib_type "Unit" in
+ let string_type = stdlib_type "String" in
+ let props_type =
+ ptyp_constr ~loc:ghost_loc
+ { txt = Ldot (Lident "ReactDOM", "domProps"); loc = ghost_loc }
+ []
+ in
+ let props =
+ List.map
+ (fun (label, expression) ->
+ let variable = gen_symbol ~prefix:"prop" () in
+ let data_name = data_attribute (label_name label) in
+ let typ =
+ match (label, data_name) with
+ | Nolabel, _ -> unit_type
+ | _, Some _ -> string_type
+ | _, None -> ptyp_var ~loc:synthetic_loc variable
+ in
+ { label; variable; typ; data_name; expression })
+ args
+ in
+ let ordinary_props =
+ List.filter (fun prop -> prop.data_name = None) props
+ in
+ let arrow { label; typ; _ } result =
+ ptyp_arrow ~loc:ghost_loc label typ result
+ in
+ (* The shared type variables connect each supplied prop to the corresponding
+ argument of ReactDOM.domProps. Melange erases this pure callback after
+ OCaml has checked both its labels and its types. *)
+ let check_type =
+ ignored_type ~loc:ghost_loc
+ (List.fold_right arrow ordinary_props props_type)
+ in
+ let editor_copy { pexp_desc; _ } =
+ (* Reason represents completion holes and partially typed props as
+ identifiers. Copy only those small expressions: copying arbitrary
+ values would duplicate nested JSX expansions and their typing work. *)
+ match pexp_desc with
+ | Pexp_ident _ -> true
+ | _ -> false
+ in
+ let editor_attributes =
+ (* Report diagnostics on the original expression only. The copy exists
+ solely to give Merlin the ordinary DOM constructor's context. *)
+ List.map
+ (fun (name, flags) ->
+ attribute ~loc:ghost_loc name
+ ~payload:
+ (PStr
+ [ pstr_eval ~loc:ghost_loc (estring ~loc:ghost_loc flags) [] ]))
+ [ ("alert", "-all"); ("warning", "-a") ]
+ in
+ let check_args =
+ List.map
+ (fun { label; variable; expression; _ } ->
+ (label, evar ~loc:expression.pexp_loc variable))
+ ordinary_props
+ in
+ let hidden_check = dom_props check_args in
+ let hidden_check =
+ {
+ hidden_check with
+ pexp_attributes = [ attribute ~loc:ghost_loc "merlin.hide" ];
+ }
+ in
+ let editor_args =
+ List.map
+ (fun { label; variable; expression; _ } ->
+ let expr =
+ if editor_copy expression then
+ {
+ expression with
+ pexp_attributes =
+ attribute ~loc:expression.pexp_loc "merlin.focus"
+ :: expression.pexp_attributes
+ @ editor_attributes;
+ }
+ else
+ let expr = evar ~loc:expression.pexp_loc variable in
+ {
+ expr with
+ pexp_attributes = [ attribute ~loc:synthetic_loc "merlin.hide" ];
+ }
+ in
+ (label, expr))
+ ordinary_props
+ in
+ let check_body =
+ (* Infer the constructor's argument types first, then give Merlin a DOM
+ application containing the original identifiers. Other values remain
+ visible in the constructor, with the inferred types as their context. *)
+ pexp_let ~loc:ghost_loc Nonrecursive
+ [
+ value_binding ~loc:synthetic_loc
+ ~pat:(ppat_any ~loc:synthetic_loc)
+ ~expr:hidden_check;
+ ]
+ (dom_props editor_args)
+ in
+ let check =
+ List.fold_right
+ (fun { label; variable; _ } body ->
+ pexp_fun ~loc:ghost_loc label None
+ (pvar ~loc:synthetic_loc variable)
+ body)
+ ordinary_props check_body
+ in
+ let make_type =
+ List.fold_right
+ (fun { label; typ; data_name; _ } result ->
+ let name =
+ match data_name with
+ | Some _ as name -> name
+ | None -> js_name (label_name label)
+ in
+ let attributes =
+ match (label, name) with
+ | Nolabel, _ -> [ attribute ~loc:ghost_loc "mel.ignore" ]
+ | _, None -> []
+ | _, Some name ->
+ [
+ attribute ~loc:ghost_loc "mel.as"
+ ~payload:
+ (PStr
+ [
+ pstr_eval ~loc:ghost_loc
+ (estring ~loc:ghost_loc (mel_obj_name name))
+ [];
+ ]);
+ ]
+ in
+ ptyp_arrow ~loc:ghost_loc (make_label label)
+ { typ with ptyp_attributes = attributes }
+ result)
+ props props_type
+ in
+ let make_type =
+ ptyp_arrow ~loc:ghost_loc (Labelled "check") check_type make_type
+ in
+ let make =
+ value_description ~loc:ghost_loc
+ ~name:{ txt = "make"; loc = ghost_loc }
+ ~type_:make_type ~prim:[ "" ]
+ in
+ let make =
+ { make with pval_attributes = [ attribute ~loc:ghost_loc "mel.obj" ] }
+ in
+ let module_name = gen_symbol ~prefix:"Jsx_props" () in
+ let module_ =
+ pmod_structure ~loc:synthetic_loc
+ [ pstr_primitive ~loc:synthetic_loc make ]
+ in
+ let call =
+ pexp_apply ~loc
+ (pexp_ident ~loc:synthetic_loc
+ { txt = Ldot (Lident module_name, "make"); loc = synthetic_loc })
+ ((Labelled "check", check)
+ :: List.map
+ (fun (label, expression) ->
+ let expression =
+ if
+ Option.is_none (data_attribute (label_name label))
+ && (editor_copy expression
+ || (label = Nolabel && expression.pexp_loc.loc_ghost))
+ then
+ {
+ expression with
+ pexp_attributes =
+ attribute ~loc:expression.pexp_loc "merlin.hide"
+ :: expression.pexp_attributes;
+ }
+ else expression
+ in
+ (make_label label, expression))
+ args)
+ in
+ pexp_letmodule ~loc:ghost_loc
+ { txt = Some module_name; loc = ghost_loc }
+ module_ call
diff --git a/ppx/reason_react_ppx.ml b/ppx/reason_react_ppx.ml
index 1f5f4d24e..ef25c3c83 100644
--- a/ppx/reason_react_ppx.ml
+++ b/ppx/reason_react_ppx.ml
@@ -526,11 +526,16 @@ let jsxMapper =
reactJsxExprAndChildren ~loc:parentExpLoc ~ctxt ~keyProps mapper children
in
let propsArg =
- (match childrenProp with
- | Some childrenProp -> (labelled "children", childrenProp) :: otherProps
- | None -> otherProps)
- |> List.map (fun (label, expression) ->
- (label, mapper#expression ctxt expression))
+ let otherProps =
+ List.map
+ (fun (label, expression) ->
+ (label, mapper#expression ctxt expression))
+ otherProps
+ in
+ (* [reactJsxExprAndChildren] has already transformed the children. *)
+ match childrenProp with
+ | Some childrenProp -> (labelled "children", childrenProp) :: otherProps
+ | None -> otherProps
in
let isCap str =
match String.length str with
@@ -610,17 +615,25 @@ let jsxMapper =
children
in
let props =
- (match childrenProp with
- | Some childrenProp ->
- (labelled "children", childrenProp) :: nonChildrenProps
- | None -> nonChildrenProps)
- |> List.map (fun (label, expression) ->
- (label, mapper#expression ctxt expression))
+ let nonChildrenProps =
+ List.map
+ (fun (label, expression) ->
+ (label, mapper#expression ctxt expression))
+ nonChildrenProps
+ in
+ (* Avoid walking the already transformed children at every parent. *)
+ match childrenProp with
+ | Some childrenProp ->
+ (labelled "children", childrenProp) :: nonChildrenProps
+ | None -> nonChildrenProps
in
let component = (nolabel, componentNameExpr)
and props =
( nolabel,
- Binding.ReactDOM.domProps ~applyLoc:parentExpLoc ~loc:callerLoc props )
+ Dom_props.make ~loc:parentExpLoc ~tag_name:id
+ ~dom_props:
+ (Binding.ReactDOM.domProps ~applyLoc:parentExpLoc ~loc:callerLoc)
+ props )
in
let loc = parentExpLoc in
let gloc = { loc with loc_ghost = true } in
diff --git a/ppx/test/data-attribute-collisions.t/input.re b/ppx/test/data-attribute-collisions.t/input.re
index 6dc684a4b..69fc25d22 100644
--- a/ppx/test/data-attribute-collisions.t/input.re
+++ b/ppx/test/data-attribute-collisions.t/input.re
@@ -1,5 +1,4 @@
-let aliases =
;
-let repeated = ;
+let distinct = ;
let optional = (first, second) => ;
let optionalFirst = first => ;
@@ -9,7 +8,7 @@ let effects =
;
let serverNames =
@@ -20,10 +19,11 @@ let serverNames =
dataFoo_bar="single"
dataURL="acronym"
dataURLPath="acronym then word"
- dataFoo_Bar="underscore then uppercase"
dataVersion2="digit"
dataVersion20="digits"
data2="leading digit"
data_foo="leading underscore"
datafoo="lowercase"
/>;
+
+let underscoreThenUppercase = ;
diff --git a/ppx/test/data-attribute-collisions.t/run.t b/ppx/test/data-attribute-collisions.t/run.t
index 77406201a..55b7db152 100644
--- a/ppx/test/data-attribute-collisions.t/run.t
+++ b/ppx/test/data-attribute-collisions.t/run.t
@@ -1,38 +1,179 @@
-Snapshot DOM JSX with repeated data props and names that normalize to the same
-attribute in server-reason-react#412. Run only the JSX PPX so this baseline can
-capture the expansion before data attribute type-checking is supported.
+Snapshot distinct data names and reject repeated or aliased names, following
+server-reason-react#420. This exercises the JSX PPX before type-checking.
$ ../ppx.sh --output ml input.re
- let aliases =
+ let distinct =
ReactDOM.jsx "div"
- (((ReactDOM.domProps)[@merlin.hide ]) ~dataFoo:"first" ~data_foo:"second"
- ())
- let repeated =
- ReactDOM.jsx "div"
- (((ReactDOM.domProps)[@merlin.hide ]) ~dataFoo:"first" ~dataFoo:"second"
- ())
+ (let module Jsx_props__004_ =
+ struct
+ external make :
+ check:((Stdlib.Unit.t -> ReactDOM.domProps)[@mel.ignore ]) ->
+ dataFoo:((Stdlib.String.t)[@mel.as "data-foo"]) ->
+ data_foo:((Stdlib.String.t)[@mel.as "data_foo"]) ->
+ __jsx_unit:((Stdlib.Unit.t)[@mel.ignore ]) ->
+ ReactDOM.domProps = ""[@@mel.obj ]
+ end in
+ Jsx_props__004_.make
+ ~check:(fun prop__003_ ->
+ let _ = ((((ReactDOM.domProps)[@merlin.hide ]) prop__003_)
+ [@merlin.hide ]) in
+ ((ReactDOM.domProps)[@merlin.hide ]) ((prop__003_)
+ [@merlin.hide ])) ~dataFoo:"first" ~data_foo:"second"
+ ~__jsx_unit:())
let optional first =
fun second ->
ReactDOM.jsx "div"
- (((ReactDOM.domProps)[@merlin.hide ]) ?dataFoo:first ?data_foo:second
- ())
+ (let module Jsx_props__008_ =
+ struct
+ external make :
+ check:((Stdlib.Unit.t -> ReactDOM.domProps)[@mel.ignore ]) ->
+ ?dataFoo:((Stdlib.String.t)[@mel.as "data-foo"]) ->
+ ?data_foo:((Stdlib.String.t)[@mel.as "data_foo"]) ->
+ __jsx_unit:((Stdlib.Unit.t)[@mel.ignore ]) ->
+ ReactDOM.domProps = ""[@@mel.obj ]
+ end in
+ Jsx_props__008_.make
+ ~check:(fun prop__007_ ->
+ let _ =
+ ((((ReactDOM.domProps)[@merlin.hide ]) prop__007_)
+ [@merlin.hide ]) in
+ ((ReactDOM.domProps)[@merlin.hide ]) ((prop__007_)
+ [@merlin.hide ])) ?dataFoo:first ?data_foo:second
+ ~__jsx_unit:())
let optionalFirst first =
ReactDOM.jsx "div"
- (((ReactDOM.domProps)[@merlin.hide ]) ?dataFoo:first ~data_foo:"fallback"
- ())
+ (let module Jsx_props__012_ =
+ struct
+ external make :
+ check:((Stdlib.Unit.t -> ReactDOM.domProps)[@mel.ignore ]) ->
+ ?dataFoo:((Stdlib.String.t)[@mel.as "data-foo"]) ->
+ data_foo:((Stdlib.String.t)[@mel.as "data_foo"]) ->
+ __jsx_unit:((Stdlib.Unit.t)[@mel.ignore ]) ->
+ ReactDOM.domProps = ""[@@mel.obj ]
+ end in
+ Jsx_props__012_.make
+ ~check:(fun prop__011_ ->
+ let _ = ((((ReactDOM.domProps)[@merlin.hide ]) prop__011_)
+ [@merlin.hide ]) in
+ ((ReactDOM.domProps)[@merlin.hide ]) ((prop__011_)
+ [@merlin.hide ])) ?dataFoo:first ~data_foo:"fallback"
+ ~__jsx_unit:())
let requiredFirst second =
ReactDOM.jsx "div"
- (((ReactDOM.domProps)[@merlin.hide ]) ~dataFoo:"first" ?data_foo:second
- ())
+ (let module Jsx_props__016_ =
+ struct
+ external make :
+ check:((Stdlib.Unit.t -> ReactDOM.domProps)[@mel.ignore ]) ->
+ dataFoo:((Stdlib.String.t)[@mel.as "data-foo"]) ->
+ ?data_foo:((Stdlib.String.t)[@mel.as "data_foo"]) ->
+ __jsx_unit:((Stdlib.Unit.t)[@mel.ignore ]) ->
+ ReactDOM.domProps = ""[@@mel.obj ]
+ end in
+ Jsx_props__016_.make
+ ~check:(fun prop__015_ ->
+ let _ = ((((ReactDOM.domProps)[@merlin.hide ]) prop__015_)
+ [@merlin.hide ]) in
+ ((ReactDOM.domProps)[@merlin.hide ]) ((prop__015_)
+ [@merlin.hide ])) ~dataFoo:"first" ?data_foo:second
+ ~__jsx_unit:())
let effects =
ReactDOM.jsx "div"
- (((ReactDOM.domProps)[@merlin.hide ]) ~className:(next "class")
- ~dataURL:(next "first") ~dataUrl:(next "second") ())
+ (let module Jsx_props__021_ =
+ struct
+ external make :
+ check:((className:'prop__017_ ->
+ Stdlib.Unit.t -> ReactDOM.domProps)[@mel.ignore ])
+ ->
+ className:'prop__017_ ->
+ dataURL:((Stdlib.String.t)[@mel.as "data-url"]) ->
+ data_URL:((Stdlib.String.t)[@mel.as "data_url"]) ->
+ __jsx_unit:((Stdlib.Unit.t)[@mel.ignore ]) ->
+ ReactDOM.domProps = ""[@@mel.obj ]
+ end in
+ Jsx_props__021_.make
+ ~check:(fun ~className:prop__017_ prop__020_ ->
+ let _ =
+ ((((ReactDOM.domProps)[@merlin.hide ])
+ ~className:prop__017_ prop__020_)
+ [@merlin.hide ]) in
+ ((ReactDOM.domProps)[@merlin.hide ])
+ ~className:((prop__017_)[@merlin.hide ]) ((prop__020_)
+ [@merlin.hide ])) ~className:(next "class")
+ ~dataURL:(next "first") ~data_URL:(next "second") ~__jsx_unit:())
let serverNames =
ReactDOM.jsx "div"
- (((ReactDOM.domProps)[@merlin.hide ]) ~dataFoo:"plain"
- ~dataFoo__bar:"double" ~dataFoo___:"trailing" ~dataFoo_bar:"single"
- ~dataURL:"acronym" ~dataURLPath:"acronym then word"
- ~dataFoo_Bar:"underscore then uppercase" ~dataVersion2:"digit"
- ~dataVersion20:"digits" ~data2:"leading digit"
- ~data_foo:"leading underscore" ~datafoo:"lowercase" ())
+ (let module Jsx_props__034_ =
+ struct
+ external make :
+ check:((Stdlib.Unit.t -> ReactDOM.domProps)[@mel.ignore ]) ->
+ dataFoo:((Stdlib.String.t)[@mel.as "data-foo"]) ->
+ dataFoo__bar:((Stdlib.String.t)[@mel.as "data-foo__bar__"]) ->
+ dataFoo___:((Stdlib.String.t)[@mel.as "data-foo_____"]) ->
+ dataFoo_bar:((Stdlib.String.t)[@mel.as "data-foo_bar"]) ->
+ dataURL:((Stdlib.String.t)[@mel.as "data-url"]) ->
+ dataURLPath:((Stdlib.String.t)[@mel.as
+ "data-url-path"])
+ ->
+ dataVersion2:((Stdlib.String.t)[@mel.as
+ "data-version2"])
+ ->
+ dataVersion20:((Stdlib.String.t)[@mel.as
+ "data-version20"])
+ ->
+ data2:((Stdlib.String.t)[@mel.as "data2"]) ->
+ data_foo:((Stdlib.String.t)[@mel.as
+ "data_foo"])
+ ->
+ datafoo:((Stdlib.String.t)[@mel.as
+ "datafoo"])
+ ->
+ __jsx_unit:((Stdlib.Unit.t)[@mel.ignore ])
+ -> ReactDOM.domProps = ""[@@mel.obj ]
+ end in
+ Jsx_props__034_.make
+ ~check:(fun prop__033_ ->
+ let _ = ((((ReactDOM.domProps)[@merlin.hide ]) prop__033_)
+ [@merlin.hide ]) in
+ ((ReactDOM.domProps)[@merlin.hide ]) ((prop__033_)
+ [@merlin.hide ])) ~dataFoo:"plain"
+ ~dataFoo__bar:"double" ~dataFoo___:"trailing" ~dataFoo_bar:"single"
+ ~dataURL:"acronym" ~dataURLPath:"acronym then word"
+ ~dataVersion2:"digit" ~dataVersion20:"digits" ~data2:"leading digit"
+ ~data_foo:"leading underscore" ~datafoo:"lowercase" ~__jsx_unit:())
+ let underscoreThenUppercase =
+ ReactDOM.jsx "div"
+ (let module Jsx_props__037_ =
+ struct
+ external make :
+ check:((Stdlib.Unit.t -> ReactDOM.domProps)[@mel.ignore ]) ->
+ dataFoo_Bar:((Stdlib.String.t)[@mel.as "data-foo_bar"]) ->
+ __jsx_unit:((Stdlib.Unit.t)[@mel.ignore ]) ->
+ ReactDOM.domProps = ""[@@mel.obj ]
+ end in
+ Jsx_props__037_.make
+ ~check:(fun prop__036_ ->
+ let _ = ((((ReactDOM.domProps)[@merlin.hide ]) prop__036_)
+ [@merlin.hide ]) in
+ ((ReactDOM.domProps)[@merlin.hide ]) ((prop__036_)
+ [@merlin.hide ]))
+ ~dataFoo_Bar:"underscore then uppercase" ~__jsx_unit:())
+
+ $ cat > repeated.re < let element = ;
+ > EOF
+ $ ../ppx.sh --output ml repeated.re
+ File "output.ml", line 1, characters 42-45:
+ 1 | let element = ((div ~dataFoo:"a" ~dataFoo:"b" ~children:[] ())[@JSX ])
+ ^^^
+ Error: JSX: the prop dataFoo appears more than once on
");
@@ -155,10 +215,7 @@ describe("ReactDOM data attributes", () => {
present ? Some(value) : None;
};
let element =
- React.cloneElement(
- ,
- { "data-foo": next("data")->Js.Undefined.fromOption },
- );
+ ;
expect(evaluations.contents)->toBe(2);
let html = ReactDOMServer.renderToStaticMarkup(element);
expect(evaluations.contents)->toBe(2);
@@ -168,4 +225,14 @@ describe("ReactDOM data attributes", () => {
expect(render(true))
->toBe("");
});
+
+ test("evaluates the final unit argument once", () => {
+ let evaluations = ref(0);
+ let nextUnit = () => incr(evaluations);
+ let element = [@JSX] div(~dataFoo="value", nextUnit());
+ expect(evaluations.contents)->toBe(1);
+ expect(ReactDOMServer.renderToStaticMarkup(element))
+ ->toBe("");
+ expect(evaluations.contents)->toBe(1);
+ });
});
diff --git a/test/blackbox-tests/data-attributes.t/input.re.in b/test/blackbox-tests/data-attributes.t/input.re.in
new file mode 100644
index 000000000..d52a40956
--- /dev/null
+++ b/test/blackbox-tests/data-attributes.t/input.re.in
@@ -0,0 +1,115 @@
+let first = ;
+let second = ;
+let onlyData = ;
+let svg = ;
+let ordinaryData = ;
+
+let optional = (~className=?, ~dataFoo=?, ()) => ;
+
+let renamed =
+ ;
+
+let withChildren =
+
+
+
+
;
+
+let withRefAndEvent = (elementRef, handleClick) =>
+ ;
+
+let optionalKey = (~key=?, ()) => ;
+
+module Component = {
+ [@react.component]
+ let make = (~dataFoo) => ;
+};
+
+let component = ;
+
+external next: string => string = "next";
+let effects = ;
+
+let ordinary = ;
+
+let names =
+ ;
+
+let underscoreNames =
+ ;
+
+module ShadowedTypes = {
+ type string = int;
+ type unit = int;
+
+ let element = ;
+ let optional = (~dataFoo=?, ()) => ;
+};
+
+module IntegerComponent = {
+ [@react.component]
+ let make = (~dataFoo: int) => ;
+};
+
+let integerComponent = ;
+
+external nextUnit: unit => unit = "nextUnit";
+let effectfulUnit = [@JSX] div(~dataFoo="unit", nextUnit());
+
+let distinctNames =
+ ;
+
+let optionalDistinctNames = (first, second) =>
+ ;
+let optionalUnderscores = (~dataFoo__bar=?, ~dataFoo___=?, ()) =>
+ ;
+let requiredThenOptional = second => ;
+let optionalThenRequired = first => ;
+
+let distinctEffects =
+ ;
+
+module ComponentAliases = {
+ [@react.component]
+ let make = (~dataURL, ~dataUrl) => ;
+};
+
+let componentAliases = ;
diff --git a/test/blackbox-tests/data-attributes.t/run.t b/test/blackbox-tests/data-attributes.t/run.t
index c9b13a7bb..893680d50 100644
--- a/test/blackbox-tests/data-attributes.t/run.t
+++ b/test/blackbox-tests/data-attributes.t/run.t
@@ -1,5 +1,5 @@
-DOM JSX currently rejects arbitrary data attributes. These expected failures
-document the limitation before adding support for them.
+DOM data attributes use a constructor for each JSX occurrence, with ordinary
+props checked against ReactDOM.domProps and no runtime validation callback.
$ cat > dune-project < (lang dune 3.8)
@@ -15,33 +15,568 @@ document the limitation before adding support for them.
> (preprocess (pps melange.ppx reason-react-ppx)))
> EOF
-Check the failure status before showing the final diagnostic, since the full
-list of accepted DOM props is long.
+ $ cp input.re.in input.re
+ $ chmod u+w input.re
+ $ dune build @mel
+
+ $ cat _build/default/output/input.js
+ // Generated by Melange
+ 'use strict';
+
+ const Caml_option = require("melange.js/caml_option.js");
+ const JsxRuntime = require("react/jsx-runtime");
+
+ const first = JsxRuntime.jsx("div", {
+ className: "first",
+ "data-foo": "one"
+ });
+
+ const second = JsxRuntime.jsx("div", {
+ id: "second",
+ "data-bar": "two",
+ "data-test-id": "three"
+ });
+
+ const onlyData = JsxRuntime.jsx("div", {
+ "data-foo": "one"
+ });
+
+ const svg = JsxRuntime.jsx("svg", {
+ "data-foo": "value"
+ });
+
+ const ordinaryData = JsxRuntime.jsx("object", {
+ data: "file",
+ datatype: "text",
+ "data-test-id": "object"
+ });
+
+ function optional(className, dataFoo, param) {
+ let tmp = {};
+ if (className !== undefined) {
+ tmp.className = Caml_option.valFromOption(className);
+ }
+ if (dataFoo !== undefined) {
+ tmp["data-foo"] = Caml_option.valFromOption(dataFoo);
+ }
+ return JsxRuntime.jsx("div", tmp);
+ }
+
+ const renamed = JsxRuntime.jsx("div", {
+ "data-test-id": "aliases",
+ "aria-label": "label",
+ "aria-activedescendant": "descendant",
+ as: "button",
+ begin: "0",
+ end: "1",
+ in: "source",
+ open: true,
+ to: "target",
+ type: "button"
+ });
+
+ const withChildren = JsxRuntime.jsxs("div", {
+ children: [
+ JsxRuntime.jsx("span", {
+ "data-foo": "child"
+ }),
+ JsxRuntime.jsx("span", {})
+ ],
+ "data-test-id": "parent"
+ }, "parent");
+
+ function withRefAndEvent(elementRef, handleClick) {
+ return JsxRuntime.jsx("button", {
+ ref: elementRef,
+ onClick: handleClick,
+ "data-test-id": "button"
+ });
+ }
+
+ function optionalKey(key, param) {
+ return JsxRuntime.jsx("div", {
+ "data-foo": "keyed"
+ }, key !== undefined ? Caml_option.valFromOption(key) : undefined);
+ }
+
+ function Input$Component(Props) {
+ let dataFoo = Props.dataFoo;
+ return JsxRuntime.jsx("div", {
+ "data-foo": dataFoo
+ });
+ }
+
+ const Component = {
+ make: Input$Component
+ };
+
+ const component = JsxRuntime.jsx(Input$Component, {
+ dataFoo: "component"
+ });
+
+ const effects = JsxRuntime.jsx("div", {
+ className: next("class"),
+ "data-foo": next("data")
+ });
+
+ const ordinary = JsxRuntime.jsx("div", {
+ className: "unchanged"
+ });
+
+ const names = JsxRuntime.jsx("div", {
+ "data-foo": "plain",
+ "data-foo__bar": "double",
+ "data-foo___": "trailing",
+ "data-foo_bar": "single",
+ "data-url": "acronym",
+ "data-url-path": "acronym then word",
+ "data-version2": "digit",
+ "data-version20": "digits",
+ data2: "leading digit",
+ datafoo: "lowercase"
+ });
+
+ const underscoreNames = JsxRuntime.jsx("div", {
+ data_foo: "leading underscore",
+ "data-foo_bar": "underscore then uppercase",
+ data_api_key: "uppercase words",
+ "data-url2-path": "digit then uppercase",
+ "data-xml-http-request": "acronym then lowercase"
+ });
+
+ const element = JsxRuntime.jsx("div", {
+ "data-foo": "value"
+ });
+
+ function optional$1(dataFoo, param) {
+ let tmp = {};
+ if (dataFoo !== undefined) {
+ tmp["data-foo"] = Caml_option.valFromOption(dataFoo);
+ }
+ return JsxRuntime.jsx("div", tmp);
+ }
+
+ const ShadowedTypes = {
+ element,
+ optional: optional$1
+ };
+
+ function Input$IntegerComponent(Props) {
+ let dataFoo = Props.dataFoo;
+ return JsxRuntime.jsx("div", {
+ "data-foo": String(dataFoo)
+ });
+ }
+
+ const IntegerComponent = {
+ make: Input$IntegerComponent
+ };
+
+ const integerComponent = JsxRuntime.jsx(Input$IntegerComponent, {
+ dataFoo: 42
+ });
+
+ const effectfulUnit = JsxRuntime.jsx("div", (nextUnit(), {
+ "data-foo": "unit"
+ }));
+
+ const distinctNames = JsxRuntime.jsx("div", {
+ className: "distinct",
+ "data-foo": "camelCase",
+ data_foo: "underscore",
+ "data-foo-bar": "words",
+ "data-foo_bar": "underscored words"
+ });
+
+ function optionalDistinctNames(first, second) {
+ let tmp = {};
+ if (first !== undefined) {
+ tmp["data-foo"] = Caml_option.valFromOption(first);
+ }
+ if (second !== undefined) {
+ tmp.data_foo = Caml_option.valFromOption(second);
+ }
+ return JsxRuntime.jsx("div", tmp);
+ }
+
+ function optionalUnderscores(dataFoo__bar, dataFoo___, param) {
+ let tmp = {};
+ if (dataFoo__bar !== undefined) {
+ tmp["data-foo__bar"] = Caml_option.valFromOption(dataFoo__bar);
+ }
+ if (dataFoo___ !== undefined) {
+ tmp["data-foo___"] = Caml_option.valFromOption(dataFoo___);
+ }
+ return JsxRuntime.jsx("div", tmp);
+ }
+
+ function requiredThenOptional(second) {
+ let tmp = {
+ "data-foo": "first"
+ };
+ if (second !== undefined) {
+ tmp.data_foo = Caml_option.valFromOption(second);
+ }
+ return JsxRuntime.jsx("div", tmp);
+ }
+
+ function optionalThenRequired(first) {
+ let tmp = {
+ data_foo: "second"
+ };
+ if (first !== undefined) {
+ tmp["data-foo"] = Caml_option.valFromOption(first);
+ }
+ return JsxRuntime.jsx("div", tmp);
+ }
+
+ const distinctEffects = JsxRuntime.jsx("div", {
+ className: next("class"),
+ "data-foo": next("first"),
+ data_foo: next("second")
+ });
+
+ function Input$ComponentAliases(Props) {
+ let dataURL = Props.dataURL;
+ let dataUrl = Props.dataUrl;
+ return JsxRuntime.jsx("div", {
+ title: dataURL + dataUrl
+ });
+ }
+
+ const ComponentAliases = {
+ make: Input$ComponentAliases
+ };
+
+ const componentAliases = JsxRuntime.jsx(Input$ComponentAliases, {
+ dataURL: "first",
+ dataUrl: "second"
+ });
+
+ module.exports = {
+ first,
+ second,
+ onlyData,
+ svg,
+ ordinaryData,
+ optional,
+ renamed,
+ withChildren,
+ withRefAndEvent,
+ optionalKey,
+ Component,
+ component,
+ effects,
+ ordinary,
+ names,
+ underscoreNames,
+ ShadowedTypes,
+ IntegerComponent,
+ integerComponent,
+ effectfulUnit,
+ distinctNames,
+ optionalDistinctNames,
+ optionalUnderscores,
+ requiredThenOptional,
+ optionalThenRequired,
+ distinctEffects,
+ ComponentAliases,
+ componentAliases,
+ }
+ /* first Not a pure module */
+
+Ordinary prop types are still checked.
$ cat > input.re < let element = ;
+ > let element = ;
> EOF
- $ dune build @mel > error.log 2>&1
+ $ dune build @mel
+ File "input.re", line 1, characters 29-31:
+ 1 | let element = ;
+ ^^
+ Error: The constant 42 has type int but an expression was expected of type
+ string
[1]
- $ tail -n 1 error.log
- This argument cannot be applied with label ~dataFoo
-Optional data attributes are also rejected.
+Data attribute values must be strings.
$ cat > input.re < let element = (~dataFoo=?, ()) => ;
+ > let element = ;
> EOF
- $ dune build @mel > error.log 2>&1
+ $ dune build @mel
+ File "input.re", line 1, characters 27-29:
+ 1 | let element = ;
+ ^^
+ Error: The constant 42 has type int but an expression was expected of type
+ string
+ [1]
+
+Optional data attribute values are checked too.
+
+ $ cat > input.re < let element = ;
+ > EOF
+ $ dune build @mel
+ File "input.re", line 1, characters 33-35:
+ 1 | let element = ;
+ ^^
+ Error: The constant 42 has type int but an expression was expected of type
+ string
+ [1]
+
+Renamed ordinary props retain their original types.
+
+ $ cat > input.re < let element = ;
+ > EOF
+ $ dune build @mel
+ File "input.re", line 1, characters 25-30:
+ 1 | let element = ;
+ ^^^^^
+ Error: This constant has type string but an expression was expected of type
+ bool
[1]
- $ tail -n 1 error.log
- This argument cannot be applied with label ?dataFoo
-SVG elements have the same limitation.
+Unknown ordinary props still fail. Only show the final diagnostic, since the
+constructor's list of valid props is long.
$ cat > input.re < let element = ;
+ > let element = ;
> EOF
$ dune build @mel > error.log 2>&1
[1]
$ tail -n 1 error.log
- This argument cannot be applied with label ~dataFoo
+ This argument cannot be applied with label ~clasName
+
+Underscored names remain distinct and their values are checked as strings.
+
+ $ cat > input.re < let element = ;
+ > EOF
+ $ dune build @mel
+ File "input.re", line 1, characters 44-46:
+ 1 | let element = ;
+ ^^
+ Error: The constant 42 has type int but an expression was expected of type
+ string
+ [1]
+
+ $ cat > input.re < let element = ;
+ > EOF
+ $ dune build @mel
+ File "input.re", line 1, characters 50-52:
+ 1 | let element = ;
+ ^^
+ Error: The constant 42 has type int but an expression was expected of type
+ string
+ [1]
+
+Attribute names must be valid even when the prop is optional and absent.
+
+ $ cat > input.re < let element = ;
+ > EOF
+ $ dune build @mel
+ File "input.re", line 1, characters 28-35:
+ 1 | let element = ;
+ ^^^^^^^
+ Error: JSX: dataFoo' renders as the invalid DOM attribute name "data-foo'"
+ [1]
+
+ $ cat > input.re < let element = ;
+ > EOF
+ $ dune build @mel
+ File "input.re", line 1, characters 29-33:
+ 1 | let element = ;
+ ^^^^
+ Error: JSX: dataFoo' renders as the invalid DOM attribute name "data-foo'"
+ [1]
+
+Repeated labels are rejected.
+
+ $ cat > input.re < let element = ;
+ > EOF
+ $ dune build @mel
+ File "input.re", line 1, characters 39-42:
+ 1 | let element = ;
+ ^^^
+ Error: JSX: the prop dataFoo appears more than once on
+ [1]
+
+Optional props collide even when absent.
+
+ $ cat > input.re < let element = ;
+ > EOF
+ $ dune build @mel
+ File "input.re", line 1, characters 40-44:
+ 1 | let element = ;
+ ^^^^
+ Error: JSX: the prop dataFoo appears more than once on
+ [1]
+
+The check also handles optional props before required ones.
+
+ $ cat > input.re < let element = ;
+ > EOF
+ $ dune build @mel
+ File "input.re", line 1, characters 41-44:
+ 1 | let element = ;
+ ^^^
+ Error: JSX: the prop dataFoo appears more than once on
+ [1]
+
+Two absent optional props still collide.
+
+ $ cat > input.re < let element = ;
+ > EOF
+ $ dune build @mel
+ File "input.re", line 1, characters 42-46:
+ 1 | let element = ;
+ ^^^^
+ Error: JSX: the prop dataFoo appears more than once on
+ [1]
+
+Acronym aliases are compared after name conversion.
+
+ $ cat > input.re < let element = ;
+ > EOF
+ $ dune build @mel
+ File "input.re", line 1, characters 39-42:
+ 1 | let element = ;
+ ^^^
+ Error: JSX: dataUrl and dataURL both render as the attribute data-url
+ [1]
+
+An uppercase letter after an underscore does not add a word boundary.
+
+ $ cat > input.re < let element = ;
+ > EOF
+ $ dune build @mel
+ File "input.re", line 1, characters 48-52:
+ 1 | let element = ;
+ ^^^^
+ Error: JSX: dataFoo_Bar and dataFoo_bar both render as the attribute data-foo_bar
+ [1]
+
+Collisions in names with repeated underscores are rejected too.
+
+ $ cat > input.re < let element = ;
+ > EOF
+ $ dune build @mel
+ File "input.re", line 1, characters 50-54:
+ 1 | let element = ;
+ ^^^^
+ Error: JSX: dataFoo__Bar and dataFoo__bar both render as the attribute data-foo__bar
+ [1]
+
+Collision checks also apply to SVG elements.
+
+ $ cat > input.re < let element = ;
+ > EOF
+ $ dune build @mel
+ File "input.re", line 1, characters 41-44:
+ 1 | let element = ;
+ ^^^
+ Error: JSX: dataURL and dataUrl both render as the attribute data-url
+ [1]
+
+Shadowing string must not change the type of a data attribute.
+
+ $ cat > input.re < type string = int;
+ > let element = ;
+ > EOF
+ $ dune build @mel
+ File "input.re", line 2, characters 27-29:
+ 2 | let element = ;
+ ^^
+ Error: The constant 42 has type string but an expression was expected of type
+ string
+ [1]
+
+Optional ordinary props, event handlers, and refs retain their types.
+
+ $ cat > input.re < let element = ;
+ > EOF
+ $ dune build @mel
+ File "input.re", line 1, characters 35-37:
+ 1 | let element = ;
+ ^^
+ Error: The constant 42 has type int but an expression was expected of type
+ string
+ [1]
+
+ $ cat > input.re < let element =
event + 1} dataFoo="x" />;
+ > EOF
+ $ dune build @mel
+ File "input.re", line 1, characters 37-42:
+ 1 | let element =
event + 1} dataFoo="x" />;
+ ^^^^^
+ Error: The value event has type
+ React.Event.Mouse.t = React.Event.Mouse.tag React.Event.synthetic
+ but an expression was expected of type int
+ [1]
+
+ $ cat > input.re < let element = ;
+ > EOF
+ $ dune build @mel
+ File "input.re", line 1, characters 23-25:
+ 1 | let element = ;
+ ^^
+ Error: The constant 42 has type int but an expression was expected of type
+ ReactDOM.domRef
+ [1]
+
+Diagnostics on ordinary prop identifiers are reported once, including optional
+props, even though Merlin needs a copy for completion.
+
+ $ cat > legacy.re < let value = "legacy";
+ > let optional = Some(value);
+ > EOF
+ $ cat > legacy.rei < [@deprecated "use newName"] let value: string;
+ > [@deprecated "use newName"] let optional: option(string);
+ > EOF
+ $ cat > input.re < let ordinary = ;
+ > let withData = ;
+ > let optional = ;
+ > EOF
+ $ dune build @mel
+ File "input.re", line 1, characters 30-42:
+ 1 | let ordinary = ;
+ ^^^^^^^^^^^^
+ Error (alert deprecated): Melange.Legacy.value
+ use newName
+
+ File "input.re", line 2, characters 30-42:
+ 2 | let withData = ;
+ ^^^^^^^^^^^^
+ Error (alert deprecated): Melange.Legacy.value
+ use newName
+
+ File "input.re", line 3, characters 31-46:
+ 3 | let optional = ;
+ ^^^^^^^^^^^^^^^
+ Error (alert deprecated): Melange.Legacy.optional
+ use newName
+ [1]
+
+Merlin also reports each use once at the source expression.
+
+ $ ocamlmerlin single errors -filename input.re < input.re | jq -c '[.value[] | {start, end, message: (.message | split("\n") | last)}]'
+ [{"start":{"line":1,"col":30},"end":{"line":1,"col":42},"message":"use newName"},{"start":{"line":2,"col":30},"end":{"line":2,"col":42},"message":"use newName"},{"start":{"line":3,"col":31},"end":{"line":3,"col":46},"message":"use newName"}]
diff --git a/test/blackbox-tests/dom-props-completion.t b/test/blackbox-tests/dom-props-completion.t
index 1fd85c1b9..1d2b783d3 100644
--- a/test/blackbox-tests/dom-props-completion.t
+++ b/test/blackbox-tests/dom-props-completion.t
@@ -106,3 +106,21 @@ expressions.
> EOF
$ complete 4:9 onC
["?id","?onClick","?style"]
+
+Distinct underscored data names retain ordinary prop completion.
+
+ $ cat > component.re < let element =
+ >