diff --git a/README.md b/README.md index 29a5a3a86..60d321eac 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ This is the official documentation platform for the [ReScript](https://rescript- ## System Requirements -- `node@18` or higher +- `node@20` or higher - `npm@10` or higher ## Setup @@ -28,10 +28,7 @@ npm i # Initial build npx rescript -# Only needed for initial clone (or content H2 changes) -npm run update-index - -# Build the index data +# Build the index data. Only needed for initial clone (or content H2 changes) npm run update-index # In a new tab diff --git a/compilers/package-lock.json b/compilers/package-lock.json index 7b622a747..9a20b57aa 100644 --- a/compilers/package-lock.json +++ b/compilers/package-lock.json @@ -9,23 +9,23 @@ "version": "1.0.0", "license": "MIT", "dependencies": { - "@rescript/core": "^0.6.0", + "@rescript/core": "^1.3.0", "@rescript/react": "^0.12.0", "rescript-1000": "npm:rescript@10.0.0", "rescript-1010": "npm:rescript@10.1.0", "rescript-1100": "npm:rescript@11.0.0", - "rescript-1110": "npm:rescript@11.1.0-rc.8", + "rescript-1110": "npm:rescript@11.1.0", "rescript-820": "npm:bs-platform@8.2.0", "rescript-902": "npm:bs-platform@9.0.2", "rescript-912": "npm:rescript@9.1.2" } }, "node_modules/@rescript/core": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/@rescript/core/-/core-0.6.0.tgz", - "integrity": "sha512-D4ykxSpbmxbQa99kCg6/DztwCNt1tV3t11BLSOvJPHNLSIuQxfAU3ddgRruaH9LQSKOrMUjxQS9z6RdG5iFPoA==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@rescript/core/-/core-1.3.0.tgz", + "integrity": "sha512-wNZOZ63sYcaIYZCmTZeIPCeLa3HCGgPbIOR8zjyNkoBYUlxNV8Nb2ZyqlXR5Mb9ttvv8fTV56JbKhyVEZEYo8g==", "peerDependencies": { - "rescript": "^10.1.0 || ^11.0.0-alpha.0 || next" + "rescript": "^11.1.0-rc.7" } }, "node_modules/@rescript/react": { @@ -81,16 +81,18 @@ } }, "node_modules/rescript": { - "version": "10.1.4", - "resolved": "https://registry.npmjs.org/rescript/-/rescript-10.1.4.tgz", - "integrity": "sha512-FFKlS9AG/XrLepWsyw7B+A9DtQBPWEPDPDKghV831Y2KGbie+eeFBOS0xtRHp0xbt7S0N2Dm6hhX+kTZQ/3Ybg==", + "version": "11.1.1", + "resolved": "https://registry.npmjs.org/rescript/-/rescript-11.1.1.tgz", + "integrity": "sha512-FMELeoiR1n3LzBdBt+k7U4l0vsz5Xh0HBSHf+0NhyhzZkMRLkEKEDNrcqZc6RIux9bxmxoO+zEa9qFM01VOXAw==", "hasInstallScript": true, "peer": true, "bin": { "bsc": "bsc", - "bsrefmt": "bsrefmt", "bstracing": "lib/bstracing", "rescript": "rescript" + }, + "engines": { + "node": ">=10" } }, "node_modules/rescript-1000": { @@ -136,9 +138,9 @@ }, "node_modules/rescript-1110": { "name": "rescript", - "version": "11.1.0-rc.8", - "resolved": "https://registry.npmjs.org/rescript/-/rescript-11.1.0-rc.8.tgz", - "integrity": "sha512-5It7moo2zRvxJARi8SlEQ5YTXqsfpOpaiDsOa/9V8rE+xY3Hxt3Bhd4tAyOzSLJlpBbB+0wc6JmujhZ61eRHZg==", + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/rescript/-/rescript-11.1.0.tgz", + "integrity": "sha512-9la2Dv+ACylQ77I8s4spPu1JnLZXbH5WgxcLHLLUBWgFFSiv0wXqgzWztrBIZqwFgVX5BYcwldUqUVcEzdCyHg==", "hasInstallScript": true, "bin": { "bsc": "bsc", @@ -186,9 +188,9 @@ }, "dependencies": { "@rescript/core": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/@rescript/core/-/core-0.6.0.tgz", - "integrity": "sha512-D4ykxSpbmxbQa99kCg6/DztwCNt1tV3t11BLSOvJPHNLSIuQxfAU3ddgRruaH9LQSKOrMUjxQS9z6RdG5iFPoA==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@rescript/core/-/core-1.3.0.tgz", + "integrity": "sha512-wNZOZ63sYcaIYZCmTZeIPCeLa3HCGgPbIOR8zjyNkoBYUlxNV8Nb2ZyqlXR5Mb9ttvv8fTV56JbKhyVEZEYo8g==", "requires": {} }, "@rescript/react": { @@ -232,9 +234,9 @@ } }, "rescript": { - "version": "10.1.4", - "resolved": "https://registry.npmjs.org/rescript/-/rescript-10.1.4.tgz", - "integrity": "sha512-FFKlS9AG/XrLepWsyw7B+A9DtQBPWEPDPDKghV831Y2KGbie+eeFBOS0xtRHp0xbt7S0N2Dm6hhX+kTZQ/3Ybg==", + "version": "11.1.1", + "resolved": "https://registry.npmjs.org/rescript/-/rescript-11.1.1.tgz", + "integrity": "sha512-FMELeoiR1n3LzBdBt+k7U4l0vsz5Xh0HBSHf+0NhyhzZkMRLkEKEDNrcqZc6RIux9bxmxoO+zEa9qFM01VOXAw==", "peer": true }, "rescript-1000": { @@ -253,9 +255,9 @@ "integrity": "sha512-uIUwDZZmDUb7ymGkBiiGioxMg8hXh1mze/2k/qhYQcZGgi7PrLHQIW9AksM7gb9WnpjCAvFsA8U2VgC0nA468w==" }, "rescript-1110": { - "version": "npm:rescript@11.1.0-rc.8", - "resolved": "https://registry.npmjs.org/rescript/-/rescript-11.1.0-rc.8.tgz", - "integrity": "sha512-5It7moo2zRvxJARi8SlEQ5YTXqsfpOpaiDsOa/9V8rE+xY3Hxt3Bhd4tAyOzSLJlpBbB+0wc6JmujhZ61eRHZg==" + "version": "npm:rescript@11.1.0", + "resolved": "https://registry.npmjs.org/rescript/-/rescript-11.1.0.tgz", + "integrity": "sha512-9la2Dv+ACylQ77I8s4spPu1JnLZXbH5WgxcLHLLUBWgFFSiv0wXqgzWztrBIZqwFgVX5BYcwldUqUVcEzdCyHg==" }, "rescript-820": { "version": "npm:bs-platform@8.2.0", diff --git a/compilers/package.json b/compilers/package.json index d5d5eb35b..f03ee4390 100644 --- a/compilers/package.json +++ b/compilers/package.json @@ -5,12 +5,12 @@ "main": "index.js", "license": "MIT", "dependencies": { - "@rescript/core": "^0.6.0", + "@rescript/core": "^1.3.0", "@rescript/react": "^0.12.0", "rescript-1000": "npm:rescript@10.0.0", "rescript-1010": "npm:rescript@10.1.0", "rescript-1100": "npm:rescript@11.0.0", - "rescript-1110": "npm:rescript@11.1.0-rc.8", + "rescript-1110": "npm:rescript@11.1.0", "rescript-820": "npm:bs-platform@8.2.0", "rescript-902": "npm:bs-platform@9.0.2", "rescript-912": "npm:rescript@9.1.2" diff --git a/misc_docs/syntax/decorator_module.mdx b/misc_docs/syntax/decorator_module.mdx index 19fbe7c83..4ec1d47d1 100644 --- a/misc_docs/syntax/decorator_module.mdx +++ b/misc_docs/syntax/decorator_module.mdx @@ -36,7 +36,7 @@ var root = Path.dirname("/User/github"); ```rescript @module({from: "./myJson.json", with: {type_: "json", \"some-exotic-identifier": "someValue"}}) -external myJson: Js.Json.t = "default" +external myJson: JSON.t = "default" Console.log(myJson) ``` diff --git a/package.json b/package.json index fbda9ecf4..0ebd6c802 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "author": "Patrick Ecker ", "license": "MIT", "engines": { - "node": ">=18" + "node": ">=20" }, "type": "module", "postcss": { diff --git a/pages/docs/manual/latest/async-await.mdx b/pages/docs/manual/latest/async-await.mdx index e41e685a3..fa481f8c3 100644 --- a/pages/docs/manual/latest/async-await.mdx +++ b/pages/docs/manual/latest/async-await.mdx @@ -130,15 +130,15 @@ You may use `try / catch` or `switch` to handle exceptions during async executio ```res // For simulation purposes let authenticate = async () => { - raise(Js.Exn.raiseRangeError("Authentication failed.")) + raise(Exn.raiseRangeError("Authentication failed.")) } let checkAuth = async () => { try { await authenticate() } catch { - | Js.Exn.Error(e) => - switch Js.Exn.message(e) { + | Exn.Error(e) => + switch Exn.message(e) { | Some(msg) => Console.log("JS error thrown: " ++ msg) | None => Console.log("Some other exception has been thrown") } @@ -152,14 +152,14 @@ You may unify error and value handling in a single switch as well: ```res let authenticate = async () => { - raise(Js.Exn.raiseRangeError("Authentication failed.")) + raise(Exn.raiseRangeError("Authentication failed.")) } let checkAuth = async () => { switch await authenticate() { | _ => Console.log("ok") - | exception Js.Exn.Error(e) => - switch Js.Exn.message(e) { + | exception Exn.Error(e) => + switch Exn.message(e) { | Some(msg) => Console.log("JS error thrown: " ++ msg) | None => Console.log("Some other exception has been thrown") } diff --git a/pages/docs/manual/latest/exception.mdx b/pages/docs/manual/latest/exception.mdx index 17a917377..d3e2cea9b 100644 --- a/pages/docs/manual/latest/exception.mdx +++ b/pages/docs/manual/latest/exception.mdx @@ -134,7 +134,7 @@ throw { ## Catching JS Exceptions -To distinguish between JavaScript exceptions and ReScript exceptions, ReScript namespaces JS exceptions under the `Js.Exn.Error(payload)` variant. To catch an exception thrown from the JS side: +To distinguish between JavaScript exceptions and ReScript exceptions, ReScript namespaces JS exceptions under the `Exn.Error(payload)` variant. To catch an exception thrown from the JS side: Throw an exception from JS: @@ -158,25 +158,25 @@ try { // call the external method someJSFunctionThatThrows() } catch { -| Js.Exn.Error(obj) => - switch Js.Exn.message(obj) { +| Exn.Error(obj) => + switch Exn.message(obj) { | Some(m) => Console.log("Caught a JS exception! Message: " ++ m) | None => () } } ``` -The `obj` here is of type `Js.Exn.t`, intentionally opaque to disallow illegal operations. To operate on `obj`, do like the code above by using the standard library's [`Js.Exn`](api/js/exn) module's helpers. +The `obj` here is of type `Exn.t`, intentionally opaque to disallow illegal operations. To operate on `obj`, do like the code above by using the standard library's [`Exn`](api/js/exn) module's helpers. ## Raise a JS Exception -`raise(MyException)` raises a ReScript exception. To raise a JavaScript exception (whatever your purpose is), use `Js.Exn.raiseError`: +`raise(MyException)` raises a ReScript exception. To raise a JavaScript exception (whatever your purpose is), use `Exn.raiseError`: ```res example let myTest = () => { - Js.Exn.raiseError("Hello!") + Exn.raiseError("Hello!") } ``` ```js @@ -257,7 +257,7 @@ try { } catch { | Not_found => ... // catch a ReScript exception | Invalid_argument(_) => ... // catch a second ReScript exception -| Js.Exn.Error(obj) => ... // catch the JS exception +| Exn.Error(obj) => ... // catch the JS exception } ``` diff --git a/pages/docs/manual/latest/import-from-export-to-js.mdx b/pages/docs/manual/latest/import-from-export-to-js.mdx index fbfc50edf..4922ec456 100644 --- a/pages/docs/manual/latest/import-from-export-to-js.mdx +++ b/pages/docs/manual/latest/import-from-export-to-js.mdx @@ -102,7 +102,7 @@ var studentName = Student; ```rescript @module({from: "./myJson.json", with: {type_: "json", \"some-exotic-identifier": "someValue"}}) -external myJson: Js.Json.t = "default" +external myJson: JSON.t = "default" Console.log(myJson) ``` @@ -130,7 +130,7 @@ Also notice `type_`. Since `type` is a reserved keyword in ReScript, you can use Leveraging JavaScript's [dynamic `import`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) to reduce bundle size and lazy load code as needed is easy in ReScript. It's also a little bit more convenient than in regular JavaScript because you don't need to keep track of file paths manually with ReScript's module system. ### Dynamically Importing Parts of a Module -Use the `Js.import` function to dynamically import a specific part of a module. Put whatever `let` binding you want to import in there, and you'll get a `promise` back resolving to that specific binding. +Use the `import` function to dynamically import a specific part of a module. Put whatever `let` binding you want to import in there, and you'll get a `promise` back resolving to that specific binding. Let's look at an example. Imagine the following file `MathUtils.res`: @@ -145,7 +145,7 @@ Now let's dynamically import the add function in another module, e.g. `App.res`: ```rescript // App.res let main = async () => { - let add = await Js.import(MathUtils.add) + let add = await import(MathUtils.add) let onePlusOne = add(1, 1) Console.log(onePlusOne) @@ -164,7 +164,7 @@ async function main() { ### Dynamically Importing an Entire Module -The syntax for importing a whole module looks a little different, since we are operating on the module syntax level; instead of using `Js.import`, you may simply `await` the module itself: +The syntax for importing a whole module looks a little different, since we are operating on the module syntax level; instead of using `import`, you may simply `await` the module itself: ```rescript // App.res diff --git a/pages/docs/manual/latest/primitive-types.mdx b/pages/docs/manual/latest/primitive-types.mdx index 82f89dc7d..2ca143d4c 100644 --- a/pages/docs/manual/latest/primitive-types.mdx +++ b/pages/docs/manual/latest/primitive-types.mdx @@ -180,7 +180,7 @@ As `bigint` is a different data type than `int`, it's necessary to open the corr ```res example -open! Js.BigInt +open! BigInt let a = 9007199254740991n + 9007199254740991n let b = 2n ** 2n @@ -198,7 +198,7 @@ It also supports all the bitwise operations, except unsigned shift right (`>>>`) ```res example -open! Js.BigInt +open! BigInt let a = land(1n, 1n) let b = lor(1n, 1n) diff --git a/pages/docs/react/latest/beyond-jsx.mdx b/pages/docs/react/latest/beyond-jsx.mdx index 9cbc3ed1c..add3c766b 100644 --- a/pages/docs/react/latest/beyond-jsx.mdx +++ b/pages/docs/react/latest/beyond-jsx.mdx @@ -99,7 +99,7 @@ type props<'className, 'children, 'ref> = { let make = ( {?className, children, _}: props<'className, 'children, ReactRef.currentDomRef>, - ref: Js.Nullable.t, + ref: Nullable.t, ) => make(~className, ~children, ~ref, ()) ``` diff --git a/pages/docs/react/latest/forwarding-refs.mdx b/pages/docs/react/latest/forwarding-refs.mdx index b1fe51949..76431c114 100644 --- a/pages/docs/react/latest/forwarding-refs.mdx +++ b/pages/docs/react/latest/forwarding-refs.mdx @@ -56,12 +56,10 @@ module FancyInput = { @react.component let make = () => { - let input = React.useRef(Js.Nullable.null) + let input = React.useRef(Nullable.null) let focusInput = () => - input.current - ->Js.Nullable.toOption - ->Belt.Option.forEach(input => input->focus) + input.current->Nullable.forEach(input => input->focus) let onClick = _ => focusInput() @@ -96,7 +94,7 @@ module FancyInput = { Belt.Option.map(ReactDOM.Ref.domRef)} + ref=?{Nullable.toOption(ref)->Option.map(ReactDOM.Ref.domRef)} /> children @@ -107,10 +105,10 @@ module FancyInput = { @react.component let make = () => { - let input = React.useRef(Js.Nullable.null) + let input = React.useRef(Nullable.null) let focusInput = () => - input.current->Js.Nullable.toOption->Belt.Option.forEach(input => input->focus) + input.current->Nullable.forEach(input => input->focus) let onClick = _ => focusInput() diff --git a/pages/docs/react/latest/hooks-reducer.mdx b/pages/docs/react/latest/hooks-reducer.mdx index 885ac59ce..8b36747ca 100644 --- a/pages/docs/react/latest/hooks-reducer.mdx +++ b/pages/docs/react/latest/hooks-reducer.mdx @@ -125,13 +125,13 @@ type state = { let reducer = (state, action) => switch action { | AddTodo(content) => - let todos = Js.Array2.concat( + let todos = Array.concat( state.todos, [{id: state.nextId, content: content, completed: false}], ) {todos: todos, nextId: state.nextId + 1} | RemoveTodo(id) => - let todos = Js.Array2.filter(state.todos, todo => todo.id !== id) + let todos = Array.filter(state.todos, todo => todo.id !== id) {...state, todos: todos} | ToggleTodo(id) => let todos = Belt.Array.map(state.todos, todo => diff --git a/pages/docs/react/latest/hooks-ref.mdx b/pages/docs/react/latest/hooks-ref.mdx index a3d596f7c..053d632df 100644 --- a/pages/docs/react/latest/hooks-ref.mdx +++ b/pages/docs/react/latest/hooks-ref.mdx @@ -56,12 +56,10 @@ More infos on direct DOM manipulation can be found in the [Refs and the DOM](./r @react.component let make = () => { - let inputEl = React.useRef(Js.Nullable.null) + let inputEl = React.useRef(Nullable.null) let onClick = _ => { - inputEl.current - ->Js.Nullable.toOption - ->Belt.Option.forEach(input => input->focus) + inputEl.current->Nullable.forEach(input => input->focus) } <> @@ -75,13 +73,12 @@ let make = () => { function TextInputWithFocusButton(Props) { var inputEl = React.useRef(null); var onClick = function (param) { - return Belt_Option.forEach(Caml_option.nullable_to_opt(inputEl.current), (function (input) { - input.focus(); - - })); + Core__Nullable.forEach(inputEl.current, (function (input) { + input.focus(); + })); }; - return React.createElement(React.Fragment, undefined, React.createElement("input", { - ref: inputEl, + return React.createElement(React.Fragment, {}, React.createElement("input", { + ref: Caml_option.some(inputEl), type: "text" }), React.createElement("button", { onClick: onClick @@ -104,15 +101,13 @@ Reusing the example from our [Refs and the DOM](./refs-and-the-dom#callback-refs @react.component let make = () => { - let textInput = React.useRef(Js.Nullable.null) + let textInput = React.useRef(Nullable.null) let setTextInputRef = element => { textInput.current = element; } let focusTextInput = _ => { - textInput.current - ->Js.Nullable.toOption - ->Belt.Option.forEach(input => input->focus) + textInput.current->Nullable.forEach(input => input->focus) }
@@ -129,16 +124,14 @@ function CustomTextInput(Props) { var textInput = React.useRef(null); var setTextInputRef = function (element) { textInput.current = element; - }; var focusTextInput = function (param) { - return Belt_Option.forEach(Caml_option.nullable_to_opt(textInput.current), (function (input) { - input.focus(); - - })); + Core__Nullable.forEach(textInput.current, (function (input) { + input.focus(); + })); }; return React.createElement("div", undefined, React.createElement("input", { - ref: setTextInputRef, + ref: Caml_option.some(setTextInputRef), type: "text" }), React.createElement("input", { type: "button", diff --git a/pages/docs/react/latest/lazy-components.mdx b/pages/docs/react/latest/lazy-components.mdx index 5a9bee6b6..87c6a1c00 100644 --- a/pages/docs/react/latest/lazy-components.mdx +++ b/pages/docs/react/latest/lazy-components.mdx @@ -33,7 +33,7 @@ Now we can dynamically import the `` component by passing the result of ```rescript // SomeOtherFile.res module LazyTitle = { - let make = React.lazy_(() => Js.import(Title.make)) + let make = React.lazy_(() => import(Title.make)) } let titleJsx = <LazyTitle text="Hello!" /> @@ -41,4 +41,4 @@ let titleJsx = <LazyTitle text="Hello!" /> That's all the code we need! The new `<LazyTitle />` component behaves exactly the same as the wrapped `<Title />` component, but will be lazy loaded via React's built-in lazy mechanism. -> You can read more about `Js.import` and dynamic import in ReScript in [this part of the documentation](/docs/manual/latest/import-from-export-to-js#dynamic-import). \ No newline at end of file +> You can read more about `import` and dynamic import in ReScript in [this part of the documentation](/docs/manual/latest/import-from-export-to-js#dynamic-import). diff --git a/pages/docs/react/latest/migrate-react.mdx b/pages/docs/react/latest/migrate-react.mdx index 21df05fea..bab12646c 100644 --- a/pages/docs/react/latest/migrate-react.mdx +++ b/pages/docs/react/latest/migrate-react.mdx @@ -148,7 +148,7 @@ module FancyInput = { <input type_="text" ?className - ref=?{ref_->Js.Nullable.toOption->Belt.Option.map(ReactDOM.Ref.domRef)} + ref=?{ref_->Nullable.toOption->Option.map(ReactDOM.Ref.domRef)} /> children </div> @@ -157,7 +157,7 @@ module FancyInput = { @react.component let make = () => { - let input = React.useRef(Js.Nullable.null) + let input = React.useRef(Nullable.null) <div> <FancyInput ref=input> // prop @@ -181,7 +181,7 @@ module FancyInput = { <input type_="text" ?className - ref=?{ref->Js.Nullable.toOption->Belt.Option.map(ReactDOM.Ref.domRef)} + ref=?{ref->Nullable.toOption->Option.map(ReactDOM.Ref.domRef)} /> children </div> @@ -190,7 +190,7 @@ module FancyInput = { @react.component let make = () => { - let input = React.useRef(Js.Nullable.null) + let input = React.useRef(Nullable.null) <div> <FancyInput ref=input> diff --git a/pages/docs/react/latest/refs-and-the-dom.mdx b/pages/docs/react/latest/refs-and-the-dom.mdx index db14f0e53..9d3f95629 100644 --- a/pages/docs/react/latest/refs-and-the-dom.mdx +++ b/pages/docs/react/latest/refs-and-the-dom.mdx @@ -64,7 +64,7 @@ let value = myRef.current ``` The value of the ref differs depending on the type of the node: -- When the ref attribute is used on an HTML element, the ref passed via `ReactDOM.Ref.domRef` receives the underlying DOM element as its current property (type of `React.ref<Js.Nullable.t<Dom.element>>`) +- When the ref attribute is used on an HTML element, the ref passed via `ReactDOM.Ref.domRef` receives the underlying DOM element as its current property (type of `React.ref<Nullable.t<Dom.element>>`) - In case of interop, when the ref attribute is used on a custom class component (based on JS classes), the ref object receives the mounted instance of the component as its current (not discussed in this document). - **You may not use the ref attribute on component functions** because they don’t have instances (we don't expose JS classes in ReScript). @@ -83,12 +83,12 @@ This code uses a `React.ref` to store a reference to an `input` DOM node to put @react.component let make = () => { - let textInput = React.useRef(Js.Nullable.null) + let textInput = React.useRef(Nullable.null) let focusInput = () => - switch textInput.current->Js.Nullable.toOption { - | Some(dom) => dom->focus - | None => () + switch textInput.current { + | Value(dom) => dom->focus + | Null | Undefined => () } let onClick = _ => focusInput() @@ -103,22 +103,29 @@ let make = () => { ```js function CustomTextInput(Props) { var textInput = React.useRef(null); - var onClick = function (param) { + var focusInput = function () { var dom = textInput.current; - if (!(dom == null)) { - dom.focus(); + if (dom === null || dom === undefined) { return ; } - + dom.focus(); }; - return React.createElement("div", undefined, React.createElement("input", { - ref: textInput, - type: "text" - }), React.createElement("input", { - type: "button", - value: "Focus the text input", - onClick: onClick - })); + var onClick = function (param) { + focusInput(); + }; + return JsxRuntime.jsxs("div", { + children: [ + JsxRuntime.jsx("input", { + ref: Caml_option.some(textInput), + type: "text" + }), + JsxRuntime.jsx("input", { + type: "button", + value: "Focus the text input", + onClick: onClick + }) + ] + }); } ``` @@ -126,7 +133,7 @@ function CustomTextInput(Props) { A few things happened here, so let's break them down: -- We initialize our `textInput` ref as a `Js.Nullable.null` +- We initialize our `textInput` ref as a `Nullable.null` - We register our `textInput` ref in our `<input>` element with `ReactDOM.Ref.domRef(textInput)` - In our `focusInput` function, we need to first verify that our DOM element is set, and then use the `focus` binding to set the focus @@ -148,7 +155,7 @@ module MyComp = { @react.component let make = () => { - let textInput = React.useRef(Js.Nullable.null) + let textInput = React.useRef(Nullable.null) // This will **not** work <MyComp ref={ReactDOM.Ref.domRef(textInput)} /> @@ -193,15 +200,13 @@ The example below implements a common pattern: using the ref callback to store a @react.component let make = () => { - let textInput = React.useRef(Js.Nullable.null) + let textInput = React.useRef(Nullable.null) let setTextInputRef = element => { textInput.current = element; } let focusTextInput = _ => { - textInput.current - ->Js.Nullable.toOption - ->Belt.Option.forEach(input => input->focus) + textInput.current->Nullable.forEach(input => input->focus) } <div> @@ -218,16 +223,14 @@ function CustomTextInput(Props) { var textInput = React.useRef(null); var setTextInputRef = function (element) { textInput.current = element; - }; var focusTextInput = function (param) { - return Belt_Option.forEach(Caml_option.nullable_to_opt(textInput.current), (function (input) { - input.focus(); - - })); + Core__Nullable.forEach(textInput.current, (function (input) { + input.focus(); + })); }; return React.createElement("div", undefined, React.createElement("input", { - ref: setTextInputRef, + ref: Caml_option.some(setTextInputRef), type: "text" }), React.createElement("input", { type: "button", @@ -261,7 +264,7 @@ module CustomTextInput = { @react.component let make = () => { - let textInput = React.useRef(Js.Nullable.null) + let textInput = React.useRef(Nullable.null) let setInputRef = element => { textInput.current = element} <CustomTextInput setInputRef/> diff --git a/scripts/gendocs.res b/scripts/gendocs.res index d7f0a8ced..33bafdabc 100644 --- a/scripts/gendocs.res +++ b/scripts/gendocs.res @@ -18,28 +18,28 @@ node scripts/gendocs.mjs path/to/rescript-compiler latest true open Node module Docgen = RescriptTools.Docgen -let args = Process.argv->Js.Array2.sliceFrom(2) +let args = Process.argv->Array.sliceToEnd(~start=2) let dirname = url ->URL.fileURLToPath ->Path.dirname -let compilerLibPath = switch args->Belt.Array.get(0) { +let compilerLibPath = switch args->Array.get(0) { | Some(path) => Path.join([path, "jscomp", "others"]) | None => failwith("First argument should be path to rescript-compiler repo") } -let corePath = switch args->Belt.Array.get(1) { +let corePath = switch args->Array.get(1) { | Some(path) => path | _ => failwith("Second argument should be path to rescript-core/src/RescriptCore.res") } -let version = switch args->Belt.Array.get(2) { +let version = switch args->Array.get(2) { | Some(version) => version | None => failwith("Third argument should be a version, `latest`, `v10`") } -let forceReWrite = switch args->Belt.Array.get(3) { +let forceReWrite = switch args->Array.get(3) { | Some("true") => true | _ => false } @@ -47,7 +47,7 @@ let forceReWrite = switch args->Belt.Array.get(3) { let dirVersion = Path.join([dirname, "..", "data", "api", version]) if Fs.existsSync(dirVersion) { - Js.Console.error(`Directory ${dirVersion} already exists`) + Console.error(`Directory ${dirVersion} already exists`) if !forceReWrite { Process.exit(1) } @@ -76,10 +76,10 @@ type section = { let env = Process.env -let docsDecoded = entryPointFiles->Js.Array2.map(libFile => { +let docsDecoded = entryPointFiles->Array.map(libFile => { let entryPointFile = Path.join2(compilerLibPath, libFile) - Js.Dict.set(env, "FROM_COMPILER", "true") + Dict.set(env, "FROM_COMPILER", "true") let output = ChildProcess.execSync( @@ -87,25 +87,25 @@ let docsDecoded = entryPointFiles->Js.Array2.map(libFile => { )->Buffer.toString output - ->Js.Json.parseExn + ->JSON.parseExn ->Docgen.decodeFromJson }) let coreDocs = { - Js.Dict.set(env, "FROM_COMPILER", "false") + Dict.set(env, "FROM_COMPILER", "false") let output = ChildProcess.execSync(`./node_modules/.bin/rescript-tools doc ${corePath}`)->Buffer.toString output - ->Js.Json.parseExn + ->JSON.parseExn ->Docgen.decodeFromJson } -let docsDecoded = Js.Array2.concat(docsDecoded, [coreDocs]) +let docsDecoded = Array.concat(docsDecoded, [coreDocs]) -let docs = docsDecoded->Js.Array2.map(doc => { - let topLevelItems = doc.items->Belt.Array.keepMap(item => +let docs = docsDecoded->Array.map(doc => { + let topLevelItems = doc.items->Array.filterMap(item => switch item { | Value(_) as item | Type(_) as item => item->Some | _ => None @@ -118,14 +118,14 @@ let docs = docsDecoded->Js.Array2.map(doc => { Module({id, items, name, docstrings}) | ModuleAlias({id, items, name, docstrings}), ...rest, } => - if Js.Array2.includes(hiddenModules, id) { + if Array.includes(hiddenModules, id) { getModules(rest, moduleNames) } else { - let id = Js.String2.startsWith(id, "RescriptCore") - ? Js.String2.replace(id, "RescriptCore", "Core") + let id = String.startsWith(id, "RescriptCore") + ? String.replace(id, "RescriptCore", "Core") : id getModules( - list{...rest, ...Belt.List.fromArray(items)}, + list{...rest, ...List.fromArray(items)}, list{{id, items, name, docstrings}, ...moduleNames}, ) } @@ -133,107 +133,111 @@ let docs = docsDecoded->Js.Array2.map(doc => { | list{} => moduleNames } - // let id = Js.String2.startsWith(doc.name, "RescriptCore") ? "Core" : doc.name - let id = Js.String2.startsWith(doc.name, "RescriptCore") - ? Js.String2.replace(doc.name, "RescriptCore", "Core") + let id = String.startsWith(doc.name, "RescriptCore") + ? String.replace(doc.name, "RescriptCore", "Core") : doc.name let top = {id, name: id, docstrings: doc.docstrings, items: topLevelItems} - let submodules = getModules(doc.items->Belt.List.fromArray, list{})->Belt.List.toArray - let result = [top]->Js.Array2.concat(submodules) + let submodules = getModules(doc.items->List.fromArray, list{})->List.toArray + let result = [top]->Array.concat(submodules) (id, result) }) let allModules = { - open Js.Json + open JSON let encodeItem = (docItem: Docgen.item) => { switch docItem { | Value({id, name, docstrings, signature, ?deprecated}) => { - let id = Js.String2.startsWith(id, "RescriptCore") - ? Js.String2.replace(id, "RescriptCore", "Core") + let id = String.startsWith(id, "RescriptCore") + ? String.replace(id, "RescriptCore", "Core") : id - let dict = Js.Dict.fromArray( + let dict = Dict.fromArray( [ - ("id", id->string), - ("kind", "value"->string), - ("name", name->string), - ("docstrings", docstrings->stringArray), - ("signature", signature->string), - ]->Js.Array2.concat( + ("id", id->String), + ("kind", "value"->String), + ("name", name->String), + ( + "docstrings", + docstrings + ->Array.map(s => s->String) + ->Array, + ), + ("signature", signature->String), + ]->Array.concat( switch deprecated { - | Some(v) => [("deprecated", v->string)] + | Some(v) => [("deprecated", v->String)] | None => [] }, ), ) - dict->object_->Some + dict->Object->Some } | Type({id, name, docstrings, signature, ?deprecated}) => - let id = Js.String2.startsWith(id, "RescriptCore") - ? Js.String2.replace(id, "RescriptCore", "Core") + let id = String.startsWith(id, "RescriptCore") + ? String.replace(id, "RescriptCore", "Core") : id - let dict = Js.Dict.fromArray( + let dict = Dict.fromArray( [ - ("id", id->string), - ("kind", "type"->string), - ("name", name->string), - ("docstrings", docstrings->stringArray), - ("signature", signature->string), - ]->Js.Array2.concat( + ("id", id->String), + ("kind", "type"->String), + ("name", name->String), + ("docstrings", docstrings->Array.map(s => s->String)->Array), + ("signature", signature->String), + ]->Array.concat( switch deprecated { - | Some(v) => [("deprecated", v->string)] + | Some(v) => [("deprecated", v->String)] | None => [] }, ), ) - object_(dict)->Some + Object(dict)->Some | _ => None } } - docs->Js.Array2.map(((topLevelName, modules)) => { + docs->Array.map(((topLevelName, modules)) => { let submodules = modules - ->Js.Array2.map(mod => { + ->Array.map(mod => { let items = mod.items - ->Belt.Array.keepMap(item => encodeItem(item)) - ->array + ->Array.filterMap(item => encodeItem(item)) + ->Array - let id = Js.String2.startsWith(mod.id, "RescriptCore") ? "Core" : mod.id + let id = String.startsWith(mod.id, "RescriptCore") ? "Core" : mod.id - let rest = Js.Dict.fromArray([ - ("id", id->string), - ("name", mod.name->string), - ("docstrings", mod.docstrings->stringArray), + let rest = Dict.fromArray([ + ("id", id->String), + ("name", mod.name->String), + ("docstrings", mod.docstrings->Array.map(s => s->String)->Array), ("items", items), ]) ( mod.id - ->Js.String2.split(".") - ->Js.Array2.joinWith("/") - ->Js.String2.toLowerCase, - rest->object_, + ->String.split(".") + ->Array.join("/") + ->String.toLowerCase, + rest->Object, ) }) - ->Js.Dict.fromArray + ->Dict.fromArray (topLevelName, submodules) }) } let () = { - allModules->Js.Array2.forEach(((topLevelName, mod)) => { - let json = Js.Json.object_(mod) + allModules->Array.forEach(((topLevelName, mod)) => { + let json = JSON.Object(mod) - let topLevelName = Js.String2.startsWith(topLevelName, "RescriptCore") ? "Core" : topLevelName + let topLevelName = String.startsWith(topLevelName, "RescriptCore") ? "Core" : topLevelName Fs.writeFileSync( - Path.join([dirVersion, `${topLevelName->Js.String2.toLowerCase}.json`]), - json->Js.Json.stringifyWithSpace(2), + Path.join([dirVersion, `${topLevelName->String.toLowerCase}.json`]), + json->JSON.stringify(~space=2), ) }) } @@ -247,20 +251,20 @@ type rec node = { // Generate TOC modules let () = { let joinPath = (~path: array<string>, ~name: string) => { - Js.Array2.concat(path, [name])->Js.Array2.map(path => path->Js.String2.toLowerCase) + Array.concat(path, [name])->Array.map(path => path->String.toLowerCase) } let rec getModules = (lst: list<Docgen.item>, moduleNames, path) => { switch lst { | list{Module({id, items, name}) | ModuleAlias({id, items, name}), ...rest} => - if Js.Array2.includes(hiddenModules, id) { + if Array.includes(hiddenModules, id) { getModules(rest, moduleNames, path) } else { - let itemsList = items->Belt.List.fromArray + let itemsList = items->List.fromArray let children = getModules(itemsList, [], joinPath(~path, ~name)) getModules( rest, - Js.Array2.concat([{name, path: joinPath(~path, ~name), children}], moduleNames), + Array.concat([{name, path: joinPath(~path, ~name), children}], moduleNames), path, ) } @@ -269,16 +273,16 @@ let () = { } } - let tocTree = docsDecoded->Js.Array2.map(({name, items}) => { - let name = Js.String2.startsWith(name, "RescriptCore") ? "Core" : name - let path = name->Js.String2.toLowerCase + let tocTree = docsDecoded->Array.map(({name, items}) => { + let name = String.startsWith(name, "RescriptCore") ? "Core" : name + let path = name->String.toLowerCase ( path, { name, path: [path], children: items - ->Belt.List.fromArray + ->List.fromArray ->getModules([], [path]), }, ) @@ -287,8 +291,8 @@ let () = { Fs.writeFileSync( Path.join([dirVersion, "toc_tree.json"]), tocTree - ->Js.Dict.fromArray - ->Js.Json.stringifyAny - ->Belt.Option.getExn, + ->Dict.fromArray + ->JSON.stringifyAny + ->Option.getExn, ) } diff --git a/scripts/generate_feed.res b/scripts/generate_feed.res index c968215f7..213aae577 100644 --- a/scripts/generate_feed.res +++ b/scripts/generate_feed.res @@ -3,4 +3,4 @@ let content = { getLatest()->toXmlString } -Js.log(content) +Console.log(content) diff --git a/src/ApiDocs.res b/src/ApiDocs.res index ecfcc34d0..453fb7816 100644 --- a/src/ApiDocs.res +++ b/src/ApiDocs.res @@ -11,13 +11,13 @@ type field = { docstrings: array<string>, signature: string, optional: bool, - deprecated: Js.Null.t<string>, + deprecated: Null.t<string>, } type constructor = { name: string, docstrings: array<string>, signature: string, - deprecated: Js.Null.t<string>, + deprecated: Null.t<string>, } type detail = @@ -30,29 +30,29 @@ type item = docstrings: array<string>, signature: string, name: string, - deprecated: Js.Null.t<string>, + deprecated: Null.t<string>, }) | Type({ id: string, docstrings: array<string>, signature: string, name: string, - deprecated: Js.Null.t<string>, - detail: Js.Null.t<detail>, + deprecated: Null.t<string>, + detail: Null.t<detail>, }) module RightSidebar = { @react.component let make = (~items: array<item>) => { items - ->Js.Array2.map(item => { + ->Array.map(item => { switch item { | Value({name, deprecated}) as kind | Type({name, deprecated}) as kind => let (icon, textColor, bgColor, href) = switch kind { | Type(_) => ("t", "text-fire-30", "bg-fire-5", `#type-${name}`) | Value(_) => ("v", "text-sky-30", "bg-sky-5", `#value-${name}`) } - let deprecatedIcon = switch deprecated->Js.Null.toOption { + let deprecatedIcon = switch deprecated->Null.toOption { | Some(_) => <div className={`bg-orange-100 min-w-[20px] min-h-[20px] w-5 h-5 mr-3 flex justify-center items-center rounded-xl ml-auto`}> @@ -60,7 +60,7 @@ module RightSidebar = { </div>->Some | None => None } - let title = `${Belt.Option.isSome(deprecatedIcon) ? "Deprecated " : ""}` ++ name + let title = `${Option.isSome(deprecatedIcon) ? "Deprecated " : ""}` ++ name let result = <li className="my-3"> <a @@ -94,13 +94,13 @@ module SidebarTree = { let moduleRoute = Webapi.URL.make("file://" ++ router.asPath).pathname - ->Js.String2.replace("/docs/manual/latest/api/", "") - ->Js.String2.split("/") + ->String.replace("/docs/manual/latest/api/", "") + ->String.split("/") let summaryClassName = "truncate py-1 md:h-auto tracking-tight text-gray-60 font-medium text-14 rounded-sm hover:bg-gray-20 hover:-ml-2 hover:py-1 hover:pl-2 " let classNameActive = " bg-fire-5 text-red-500 -ml-2 pl-2 font-medium hover:bg-fire-70" - let subMenu = switch items->Js.Array2.length > 0 { + let subMenu = switch items->Array.length > 0 { | true => <div className={"xl:hidden ml-5"}> <ul className={"list-none py-0.5"}> @@ -111,23 +111,22 @@ module SidebarTree = { } let rec renderNode = node => { - let isCurrentRoute = - Js.Array2.joinWith(moduleRoute, "/") === Js.Array2.joinWith(node.path, "/") + let isCurrentRoute = Array.join(moduleRoute, "/") === Array.join(node.path, "/") let classNameActive = isCurrentRoute ? classNameActive : "" - let hasChildren = node.children->Js.Array2.length > 0 - let href = node.path->Js.Array2.joinWith("/") + let hasChildren = node.children->Array.length > 0 + let href = node.path->Array.join("/") let tocModule = isCurrentRoute ? subMenu : React.null switch hasChildren { | true => let open_ = - node.path->Js.Array2.joinWith("/") === + node.path->Array.join("/") === moduleRoute - ->Js.Array2.slice(~start=0, ~end_=Js.Array2.length(moduleRoute) - 1) - ->Js.Array2.joinWith("/") + ->Array.slice(~start=0, ~end=Array.length(moduleRoute) - 1) + ->Array.join("/") <details key={node.name} open_> <summary className={summaryClassName ++ classNameActive}> @@ -139,7 +138,7 @@ module SidebarTree = { {if hasChildren { <ul className={"ml-5"}> {node.children - ->Js.Array2.map(renderNode) + ->Array.map(renderNode) ->React.array} </ul> } else { @@ -174,8 +173,8 @@ module SidebarTree = { let targetUrl = "/" ++ - (Js.Array2.joinWith(url.base, "/") ++ - ("/" ++ (version ++ ("/" ++ Js.Array2.joinWith(url.pagepath, "/"))))) + (Array.join(url.base, "/") ++ + ("/" ++ (version ++ ("/" ++ Array.join(url.pagepath, "/"))))) router->Next.Router.push(targetUrl) } let version = switch version { @@ -216,16 +215,16 @@ module SidebarTree = { </div> <Next.Link className={"block " ++ - summaryClassName ++ (moduleRoute->Js.Array2.length == 1 ? classNameActive : "")} - href={node.path->Js.Array2.joinWith("/")}> + summaryClassName ++ (moduleRoute->Array.length == 1 ? classNameActive : "")} + href={node.path->Array.join("/")}> {node.name->React.string} </Next.Link> - {moduleRoute->Js.Array2.length === 1 ? subMenu : React.null} + {moduleRoute->Array.length === 1 ? subMenu : React.null} </div> <div className="hl-overline text-gray-80 mt-5 mb-2"> {"submodules"->React.string} </div> {node.children - ->Js.Array2.sortInPlaceWith((v1, v2) => v1.name > v2.name ? 1 : -1) - ->Js.Array2.map(renderNode) + ->Array.toSorted((v1, v2) => String.compare(v1.name, v2.name)) + ->Array.map(renderNode) ->React.array} </aside> </div> @@ -235,7 +234,7 @@ module SidebarTree = { type module_ = { id: string, docstrings: array<string>, - deprecated: Js.Null.t<string>, + deprecated: Null.t<string>, name: string, items: array<item>, } @@ -262,7 +261,7 @@ module MarkdownStylize = { module DeprecatedMessage = { @react.component let make = (~deprecated) => { - switch deprecated->Js.Null.toOption { + switch deprecated->Null.toOption { | Some(content) => <Markdown.Warn> <h4 className={"hl-4 mb-2"}> {"Deprecated"->React.string} </h4> @@ -279,10 +278,10 @@ module DocstringsStylize = { let rehypePlugins = [Rehype.WithOptions([Plugin(Rehype.slug), SlugOption({prefix: slugPrefix ++ "-"})])]->Some - let content = switch docstrings->Js.Array2.length > 1 { - | true => docstrings->Js.Array2.sliceFrom(1) + let content = switch docstrings->Array.length > 1 { + | true => docstrings->Array.sliceToEnd(~start=1) | false => docstrings - }->Js.Array2.joinWith("\n") + }->Array.join("\n") <div className={"mt-3"}> <MarkdownStylize content rehypePlugins /> @@ -304,10 +303,10 @@ let default = (props: props) => { open Markdown switch props { | Ok({module_: {id, name, docstrings, items}}) => - let valuesAndType = items->Js.Array2.map(item => { + let valuesAndType = items->Array.map(item => { switch item { | Value({name, signature, docstrings, deprecated}) => - let code = Js.String2.replaceByRe(signature, %re("/\\n/g"), "\n") + let code = String.replaceRegExp(signature, %re("/\\n/g"), "\n") let slugPrefix = "value-" ++ name <> <H2 id=slugPrefix> {name->React.string} </H2> @@ -316,7 +315,7 @@ let default = (props: props) => { <DocstringsStylize docstrings slugPrefix /> </> | Type({name, signature, docstrings, deprecated}) => - let code = Js.String2.replaceByRe(signature, %re("/\\n/g"), "\n") + let code = String.replaceRegExp(signature, %re("/\\n/g"), "\n") let slugPrefix = "type-" ++ name <> <H2 id=slugPrefix> {name->React.string} </H2> @@ -337,7 +336,7 @@ let default = (props: props) => { } let rightSidebar = switch props { - | Ok({module_: {items}}) if Js.Array2.length(items) > 0 => + | Ok({module_: {items}}) if Array.length(items) > 0 => <div className="hidden xl:block lg:w-1/5 md:h-auto md:relative overflow-y-visible bg-white"> <aside className="relative top-0 pl-4 w-full block md:top-16 md:pt-16 md:sticky border-l border-gray-20 overflow-y-auto pb-24 h-[calc(100vh-4.5rem)]"> @@ -383,8 +382,8 @@ let default = (props: props) => { module Data = { type t = { - mainModule: Js.Dict.t<Js.Json.t>, - tree: Js.Dict.t<Js.Json.t>, + mainModule: Dict.t<JSON.t>, + tree: Dict.t<JSON.t>, } let dir = Node.Path.resolve("data", "api") @@ -394,7 +393,7 @@ module Data = { let pathModule = Path.join([dir, version, `${moduleName}.json`]) - let moduleContent = Fs.readFileSync(pathModule)->Js.Json.parseExn + let moduleContent = Fs.readFileSync(pathModule)->JSON.parseExn let content = switch moduleContent { | Object(dict) => dict->Some @@ -403,7 +402,7 @@ module Data = { let toctree = switch Path.join([dir, version, "toc_tree.json"]) ->Fs.readFileSync - ->Js.Json.parseExn { + ->JSON.parseExn { | Object(dict) => dict->Some | _ => None } @@ -419,23 +418,23 @@ let processStaticProps = (~slug: array<string>, ~version: string) => { let moduleName = slug->Belt.Array.getExn(0) let content = Data.getVersion(~version, ~moduleName) - let modulePath = slug->Js.Array2.joinWith("/") + let modulePath = slug->Array.join("/") switch content { | Some({mainModule, tree}) => - switch mainModule->Js.Dict.get(modulePath) { + switch mainModule->Dict.get(modulePath) { | Some(json) => let {items, docstrings, deprecated, name} = Docgen.decodeFromJson(json) let id = switch json { | Object(dict) => - switch Js.Dict.get(dict, "id") { + switch Dict.get(dict, "id") { | Some(String(s)) => s | _ => "" } | _ => "" } - let items = items->Js.Array2.map(item => + let items = items->Array.map(item => switch item { | Docgen.Value({id, docstrings, signature, name, ?deprecated}) => Value({ @@ -443,14 +442,14 @@ let processStaticProps = (~slug: array<string>, ~version: string) => { docstrings, signature, name, - deprecated: deprecated->Js.Null.fromOption, + deprecated: deprecated->Null.fromOption, }) | Type({id, docstrings, signature, name, ?deprecated, ?detail}) => let detail = switch detail { | Some(kind) => switch kind { | Docgen.Record({items}) => - let items = items->Js.Array2.map(({ + let items = items->Array.map(({ name, docstrings, signature, @@ -462,21 +461,21 @@ let processStaticProps = (~slug: array<string>, ~version: string) => { docstrings, signature, optional, - deprecated: deprecated->Js.Null.fromOption, + deprecated: deprecated->Null.fromOption, } }) - Record({items: items})->Js.Null.return + Record({items: items})->Null.make | Variant({items}) => - let items = items->Js.Array2.map(({name, docstrings, signature, ?deprecated}) => { + let items = items->Array.map(({name, docstrings, signature, ?deprecated}) => { { name, docstrings, signature, - deprecated: deprecated->Js.Null.fromOption, + deprecated: deprecated->Null.fromOption, } }) - Variant({items: items})->Js.Null.return + Variant({items: items})->Null.make } | None => Js.Null.empty } @@ -485,7 +484,7 @@ let processStaticProps = (~slug: array<string>, ~version: string) => { docstrings, signature, name, - deprecated: deprecated->Js.Null.fromOption, + deprecated: deprecated->Null.fromOption, detail, }) | _ => assert(false) @@ -495,11 +494,11 @@ let processStaticProps = (~slug: array<string>, ~version: string) => { id, name, docstrings, - deprecated: deprecated->Js.Null.fromOption, + deprecated: deprecated->Null.fromOption, items, } - let toctree = tree->Js.Dict.get(moduleName) + let toctree = tree->Dict.get(moduleName) switch toctree { | Some(toctree) => Ok({module_, toctree: (Obj.magic(toctree): node)}) @@ -531,24 +530,24 @@ let getStaticPathsByVersion = async (~version: string) => { let slugs = pathDir ->Fs.readdirSync - ->Js.Array2.reduce((acc, file) => { + ->Array.reduce([], (acc, file) => { switch file == "toc_tree.json" { | true => acc | false => let paths = switch Path.join2(pathDir, file) ->Fs.readFileSync - ->Js.Json.parseExn { + ->JSON.parseExn { | Object(dict) => dict - ->Js.Dict.keys - ->Js.Array2.map(modPath => modPath->Js.String2.split("/")) + ->Dict.keysToArray + ->Array.map(modPath => modPath->String.split("/")) | _ => acc } - Js.Array2.concat(acc, paths) + Array.concat(acc, paths) } - }, []) + }) - let paths = slugs->Js.Array2.map(slug => + let paths = slugs->Array.map(slug => { "params": { "slug": slug, diff --git a/src/Blog.res b/src/Blog.res index 42501b5ce..eea39c33f 100644 --- a/src/Blog.res +++ b/src/Blog.res @@ -51,7 +51,7 @@ module CategorySelector = { <div className="text-16 w-full flex items-center justify-between text-gray-60"> {tabs - ->Belt.Array.map(tab => { + ->Array.map(tab => { // Deep comparison here! let isActive = selected == tab let text = (tab :> string) @@ -211,11 +211,11 @@ let default = (props: props): React.element => { <Markdown.Warn> {React.string("This blog is currently in the works.")} </Markdown.Warn> </div> } else { - let result = switch Belt.Array.length(posts) { + let result = switch Array.length(posts) { | 0 => <div> {React.string("No posts for this category available...")} </div> | _ => let first = Belt.Array.getExn(posts, 0) - let rest = Js.Array2.sliceFrom(posts, 1) + let rest = Array.sliceToEnd(posts, ~start=1) let featureBox = <div className="w-full mb-24 lg:px-8 xl:px-0"> @@ -235,7 +235,7 @@ let default = (props: props): React.element => { | rest => <div className="px-4 md:px-8 xl:px-0 grid grid-cols-1 xs:grid-cols-2 md:grid-cols-3 gap-20 gap-y-12 md:gap-y-24 w-full"> - {Js.Array2.map(rest, post => { + {Array.map(rest, post => { let badge = post.frontmatter.badge->Null.toOption <BlogCard diff --git a/src/BlogArticle.res b/src/BlogArticle.res index b13b6318c..9e8d0bb42 100644 --- a/src/BlogArticle.res +++ b/src/BlogArticle.res @@ -63,7 +63,7 @@ module BlogHeader = { ) => { let date = DateStr.toDate(date) - let authors = Belt.Array.concat([author], co_authors) + let authors = Array.concat([author], co_authors) <div className="flex flex-col items-center"> <div className="w-full max-w-740"> @@ -79,7 +79,7 @@ module BlogHeader = { {React.string(Util.Date.toDayMonthYear(date))} </div> <h1 className="hl-title"> {React.string(title)} </h1> - {description->Belt.Option.mapWithDefault(React.null, desc => + {description->Option.mapOr(React.null, desc => switch desc { | "" => <div className="mb-8" /> | desc => @@ -89,7 +89,7 @@ module BlogHeader = { } )} <div className="flex flex-col md:flex-row mb-12"> - {Belt.Array.map(authors, author => + {Array.map(authors, author => <div key=author.username style={ReactDOMStyle.make(~minWidth="8.1875rem", ())} @@ -233,7 +233,7 @@ let getStaticProps: Next.GetStaticProps.t<props, Params.t> = async ctx => { let getStaticPaths: Next.GetStaticPaths.t<Params.t> = async () => { open Next.GetStaticPaths - let paths = BlogApi.getAllPosts()->Belt.Array.map(postData => { + let paths = BlogApi.getAllPosts()->Array.map(postData => { params: { Params.slug: BlogApi.blogPathToSlug(postData.path), }, diff --git a/src/ConsolePanel.res b/src/ConsolePanel.res index 829be69ed..2777aea2b 100644 --- a/src/ConsolePanel.res +++ b/src/ConsolePanel.res @@ -14,7 +14,7 @@ let make = (~compilerState, ~runOutput) => { switch data["type"] { | #...logLevel as logLevel => let args: array<string> = data["args"] - setLogs(previous => previous->Belt.Array.concat([(logLevel, args)])) + setLogs(previous => previous->Array.concat([(logLevel, args)])) | _ => () } } @@ -42,8 +42,8 @@ let make = (~compilerState, ~runOutput) => { | logs => let content = logs - ->Belt.Array.mapWithIndex((i, (logLevel, log)) => { - let log = Js.Array2.joinWith(log, " ") + ->Array.mapWithIndex(((logLevel, log), i) => { + let log = Array.join(log, " ") <pre key={RescriptCore.Int.toString(i)} className={switch logLevel { diff --git a/src/Packages.res b/src/Packages.res index 1230d8137..8d66633b0 100644 --- a/src/Packages.res +++ b/src/Packages.res @@ -14,14 +14,14 @@ type urlResource = { official: bool, } -external unsafeToUrlResource: Js.Json.t => array<urlResource> = "%identity" +external unsafeToUrlResource: JSON.t => array<urlResource> = "%identity" type npmPackage = { name: string, version: string, keywords: array<string>, description: string, - repositoryHref: Js.Null.t<string>, + repositoryHref: Null.t<string>, npmHref: string, searchScore: float, maintenanceScore: float, @@ -44,13 +44,13 @@ module Resource = { let shouldFilter = (res: t) => { switch res { | Npm(pkg) | Outdated(pkg) => - if pkg.name->Js.String2.startsWith("@elm-react") { + if pkg.name->String.startsWith("@elm-react") { true - } else if pkg.name->Js.String2.startsWith("bs-") { + } else if pkg.name->String.startsWith("bs-") { true } else if ( - pkg.name->Js.String2.startsWith("@reason-react-native") || - pkg.name->Js.String2.startsWith("reason-react-native") + pkg.name->String.startsWith("@reason-react-native") || + pkg.name->String.startsWith("reason-react-native") ) { true } else { @@ -61,8 +61,8 @@ module Resource = { } let filterKeywords = (keywords: array<string>): array<string> => { - Belt.Array.keep(keywords, kw => { - switch Js.String2.toLowerCase(kw) { + Array.filter(keywords, kw => { + switch String.toLowerCase(kw) { | "reasonml" | "reason" | "ocaml" @@ -78,9 +78,7 @@ module Resource = { let isOfficial = (res: t) => { switch res { | Npm(pkg) | Outdated(pkg) => - pkg.name === "rescript" || - pkg.name->Js.String2.startsWith("@rescript/") || - pkg.name === "gentype" + pkg.name === "rescript" || pkg.name->String.startsWith("@rescript/") || pkg.name === "gentype" | Url(urlRes) => urlRes.official } } @@ -102,7 +100,7 @@ module Resource = { fuser ->Fuse.search(pattern) - ->Js.Array2.sortInPlaceWith((a, b) => a["item"].searchScore > b["item"].searchScore ? -1 : 1) + ->Array.toSorted((a, b) => Float.compare(a["item"].searchScore, b["item"].searchScore)) } let applyUrlResourceSearch = (urls: array<urlResource>, pattern: string): array< @@ -124,24 +122,20 @@ module Resource = { } let applySearch = (resources: array<t>, pattern: string): array<t> => { - let (allNpms, allUrls, allOutDated) = Belt.Array.reduce(resources, ([], [], []), ( - acc, - next, - ) => { + let (allNpms, allUrls, allOutDated) = Array.reduce(resources, ([], [], []), (acc, next) => { let (npms, resources, outdated) = acc switch next { - | Npm(pkg) => Js.Array2.push(npms, pkg)->ignore - | Url(res) => Js.Array2.push(resources, res)->ignore - | Outdated(pkg) => Js.Array2.push(outdated, pkg)->ignore + | Npm(pkg) => Array.push(npms, pkg)->ignore + | Url(res) => Array.push(resources, res)->ignore + | Outdated(pkg) => Array.push(outdated, pkg)->ignore } (npms, resources, outdated) }) - let filteredNpm = applyNpmSearch(allNpms, pattern)->Belt.Array.map(m => Npm(m["item"])) - let filteredUrls = applyUrlResourceSearch(allUrls, pattern)->Belt.Array.map(m => Url(m["item"])) - let filteredOutdated = - applyNpmSearch(allOutDated, pattern)->Belt.Array.map(m => Outdated(m["item"])) + let filteredNpm = applyNpmSearch(allNpms, pattern)->Array.map(m => Npm(m["item"])) + let filteredUrls = applyUrlResourceSearch(allUrls, pattern)->Array.map(m => Url(m["item"])) + let filteredOutdated = applyNpmSearch(allOutDated, pattern)->Array.map(m => Outdated(m["item"])) Belt.Array.concatMany([filteredNpm, filteredUrls, filteredOutdated]) } @@ -159,12 +153,12 @@ module Card = { } let linkBox = switch value { | Npm(pkg) | Outdated(pkg) => - let repositoryHref = Js.Null.toOption(pkg.repositoryHref) + let repositoryHref = Null.toOption(pkg.repositoryHref) let repoEl = switch repositoryHref { | Some(href) => - let name = if Js.String2.startsWith(href, "https://github.com") { + let name = if String.startsWith(href, "https://github.com") { "GitHub" - } else if Js.String2.startsWith(href, "https://gitlab.com") { + } else if String.startsWith(href, "https://gitlab.com") { "GitLab" } else { "Repository" @@ -183,8 +177,7 @@ module Card = { } let titleHref = switch value { - | Npm(pkg) | Outdated(pkg) => - pkg.repositoryHref->Js.Null.toOption->Belt.Option.getWithDefault(pkg.npmHref) + | Npm(pkg) | Outdated(pkg) => pkg.repositoryHref->Null.toOption->Option.getOr(pkg.npmHref) | Url(res) => res.urlHref } @@ -206,8 +199,8 @@ module Card = { </div> <div className="mt-4 text-16"> {React.string(description)} </div> <div className="space-x-2 mt-4"> - {Belt.Array.map(keywords, keyword => { - let onMouseDown = Belt.Option.map(onKeywordSelect, cb => { + {Array.map(keywords, keyword => { + let onMouseDown = Option.map(onKeywordSelect, cb => { evt => { ReactEvent.Mouse.preventDefault(evt) cb(keyword) @@ -380,9 +373,9 @@ let default = (props: props) => { }) let allResources = { - let npms = props["packages"]->Belt.Array.map(pkg => Resource.Npm(pkg)) - let urls = props["urlResources"]->Belt.Array.map(res => Resource.Url(res)) - let outdated = props["unmaintained"]->Belt.Array.map(pkg => Resource.Outdated(pkg)) + let npms = props["packages"]->Array.map(pkg => Resource.Npm(pkg)) + let urls = props["urlResources"]->Array.map(res => Resource.Url(res)) + let outdated = props["unmaintained"]->Array.map(pkg => Resource.Outdated(pkg)) Belt.Array.concatMany([npms, urls, outdated]) } @@ -409,10 +402,7 @@ let default = (props: props) => { setState(_ => All) } - let (officialResources, communityResources) = Belt.Array.reduce(resources, ([], []), ( - acc, - next, - ) => { + let (officialResources, communityResources) = Array.reduce(resources, ([], []), (acc, next) => { let (official, community) = acc let isResourceIncluded = switch next { | Npm(_) => filter.includeNpm @@ -422,9 +412,9 @@ let default = (props: props) => { if !isResourceIncluded { () } else if filter.includeOfficial && Resource.isOfficial(next) { - Js.Array2.push(official, next)->ignore + Array.push(official, next)->ignore } else if filter.includeCommunity && !Resource.shouldFilter(next) { - Js.Array2.push(community, next)->ignore + Array.push(community, next)->ignore } (official, community) }) @@ -441,7 +431,7 @@ let default = (props: props) => { | resources => <Category title={Category.toString(Official)}> <div className="space-y-4"> - {Belt.Array.map(resources, res => { + {Array.map(resources, res => { <Card key={Resource.getId(res)} onKeywordSelect value={res} /> })->React.array} </div> @@ -453,7 +443,7 @@ let default = (props: props) => { | resources => <Category title={Category.toString(Community)}> <div className="space-y-4"> - {Belt.Array.map(resources, res => { + {Array.map(resources, res => { <Card onKeywordSelect key={Resource.getId(res)} value={res} /> })->React.array} </div> @@ -472,7 +462,7 @@ let default = (props: props) => { // On second render, this hook runs one more time to actually trigger the search. React.useEffect(() => { - router.query->Js.Dict.get("search")->Belt.Option.forEach(onValueChange) + router.query->Dict.get("search")->Option.forEach(onValueChange) None }, [firstRenderDone.current]) @@ -480,7 +470,7 @@ let default = (props: props) => { let updateQuery = value => router->Next.Router.replaceObj({ pathname: router.pathname, - query: value === "" ? Js.Dict.empty() : Js.Dict.fromArray([("search", value)]), + query: value === "" ? Dict.make() : Dict.fromArray([("search", value)]), }) // When the search term changes, update the router query accordingly. @@ -559,14 +549,14 @@ module Response = { @val external fetchNpmPackages: string => promise<Response.t> = "fetch" let parsePkgs = data => - Belt.Array.map(data["objects"], item => { + Array.map(data["objects"], item => { let pkg = item["package"] { name: pkg["name"], version: pkg["version"], keywords: Resource.filterKeywords(pkg["keywords"])->Resource.uniqueKeywords, - description: Belt.Option.getWithDefault(pkg["description"], ""), - repositoryHref: Js.Null.fromOption(pkg["links"]["repository"]), + description: Option.getOr(pkg["description"], ""), + repositoryHref: Null.fromOption(pkg["links"]["repository"]), npmHref: pkg["links"]["npm"], searchScore: item["searchScore"], maintenanceScore: item["score"]["detail"]["maintenance"], @@ -576,13 +566,13 @@ let parsePkgs = data => let getStaticProps: Next.GetStaticProps.revalidate<props, unit> = async _ctx => { let baseUrl = "https://registry.npmjs.org/-/v1/search?text=keywords:rescript&size=250&maintenance=1.0&popularity=0.5&quality=0.9" - let (one, two, three) = await Js.Promise2.all3(( + let (one, two, three) = await Promise.all3(( fetchNpmPackages(baseUrl), fetchNpmPackages(baseUrl ++ "&from=250"), fetchNpmPackages(baseUrl ++ "&from=500"), )) - let (data1, data2, data3) = await Js.Promise2.all3(( + let (data1, data2, data3) = await Promise.all3(( one->Response.json, two->Response.json, three->Response.json, @@ -592,15 +582,15 @@ let getStaticProps: Next.GetStaticProps.revalidate<props, unit> = async _ctx => let pkges = parsePkgs(data1) - ->Js.Array2.concat(parsePkgs(data2)) - ->Js.Array2.concat(parsePkgs(data3)) - ->Js.Array2.filter(pkg => { - if packageAllowList->Js.Array2.includes(pkg.name) { + ->Array.concat(parsePkgs(data2)) + ->Array.concat(parsePkgs(data3)) + ->Array.filter(pkg => { + if packageAllowList->Array.includes(pkg.name) { true - } else if pkg.name->Js.String2.includes("reason") { + } else if pkg.name->String.includes("reason") { false } else if pkg.maintenanceScore < 0.3 { - let _ = unmaintained->Js.Array2.push(pkg) + let _ = unmaintained->Array.push(pkg) false } else { true @@ -611,7 +601,7 @@ let getStaticProps: Next.GetStaticProps.revalidate<props, unit> = async _ctx => let urlResources = Node.Path.join2(index_data_dir, "packages_url_resources.json") ->Node.Fs.readFileSync - ->Js.Json.parseExn + ->JSON.parseExn ->unsafeToUrlResource let props: props = { "packages": pkges, diff --git a/src/Packages.resi b/src/Packages.resi index 68b5c6f96..de70e70d3 100644 --- a/src/Packages.resi +++ b/src/Packages.resi @@ -11,7 +11,7 @@ type npmPackage = { version: string, keywords: array<string>, description: string, - repositoryHref: Js.Null.t<string>, + repositoryHref: Null.t<string>, npmHref: string, searchScore: float, maintenanceScore: float, diff --git a/src/Playground.res b/src/Playground.res index b13fe10d8..c42eb3be5 100644 --- a/src/Playground.res +++ b/src/Playground.res @@ -63,7 +63,7 @@ module ToggleSelection = { | None => 0 } - let elements = Belt.Array.mapWithIndex(values, (i, value) => { + let elements = Array.mapWithIndex(values, (value, i) => { let active = i === selectedIndex ? "bg-fire text-white font-bold" : "bg-gray-80 opacity-50" let label = toLabel(value) @@ -72,7 +72,7 @@ module ToggleSelection = { ReactEvent.Mouse.stopPropagation(evt) if i !== selectedIndex { - switch Belt.Array.get(values, i) { + switch values[i] { | Some(value) => onChange(value) | None => () } @@ -125,7 +125,7 @@ module ResultPane = { <div className={"p-2 " ++ highlightClass}> <span className=prefixColor> {React.string(prefixText)} </span> <span className="font-medium text-gray-40"> - {React.string(` Line ${row->Belt.Int.toString}, column ${column->Belt.Int.toString}:`)} + {React.string(` Line ${row->Int.toString}, column ${column->Int.toString}:`)} </span> <AnsiPre className="whitespace-pre-wrap "> shortMsg </AnsiPre> </div> @@ -150,9 +150,7 @@ module ResultPane = { switch focusedRowCol { | Some(focusedRowCol) => let (fRow, fCol) = focusedRowCol - let filtered = Belt.Array.keep(locMsgs, locMsg => - fRow === locMsg.row && fCol === locMsg.column - ) + let filtered = Array.filter(locMsgs, locMsg => fRow === locMsg.row && fCol === locMsg.column) if Array.length(filtered) === 0 { locMsgs @@ -170,7 +168,7 @@ module ResultPane = { switch focusedRowCol { | Some(focusedRowCol) => let (fRow, fCol) = focusedRowCol - let filtered = Belt.Array.keep(warnings, warning => + let filtered = Array.filter(warnings, warning => switch warning { | Warn({details}) | WarnErr({details}) => @@ -198,8 +196,8 @@ module ResultPane = { | OtherErr(locMsgs) | SyntaxErr(locMsgs) => filterHighlightedLocMsgs(~focusedRowCol, locMsgs) - ->Belt.Array.mapWithIndex((i, locMsg) => - <div key={Belt.Int.toString(i)}> + ->Array.mapWithIndex((locMsg, i) => + <div key={Int.toString(i)}> {compactErrorLine( ~highlight=isHighlighted(~focusedRowCol?, locMsg), ~prefix=#E, @@ -210,12 +208,12 @@ module ResultPane = { ->React.array | WarningErr(warnings) => filterHighlightedLocWarnings(~focusedRowCol, warnings) - ->Belt.Array.mapWithIndex((i, warning) => { + ->Array.mapWithIndex((warning, i) => { let (prefix, details) = switch warning { | Api.Warning.Warn({details}) => (#W, details) | WarnErr({details}) => (#E, details) } - <div key={Belt.Int.toString(i)}> + <div key={Int.toString(i)}> {compactErrorLine(~highlight=isHighlighted(~focusedRowCol?, details), ~prefix, details)} </div> }) @@ -231,12 +229,12 @@ module ResultPane = { <PreWrap> {React.string("0 Errors, 0 Warnings")} </PreWrap> } else { filterHighlightedLocWarnings(~focusedRowCol, warnings) - ->Belt.Array.mapWithIndex((i, warning) => { + ->Array.mapWithIndex((warning, i) => { let (prefix, details) = switch warning { | Api.Warning.Warn({details}) => (#W, details) | WarnErr({details}) => (#E, details) } - <div key={Belt.Int.toString(i)}> + <div key={Int.toString(i)}> {compactErrorLine(~highlight=isHighlighted(~focusedRowCol?, details), ~prefix, details)} </div> }) @@ -253,8 +251,8 @@ module ResultPane = { | Conv(Fail({fromLang, toLang, details})) => let errs = filterHighlightedLocMsgs(~focusedRowCol, details) - ->Belt.Array.mapWithIndex((i, locMsg) => - <div key={Belt.Int.toString(i)}> + ->Array.mapWithIndex((locMsg, i) => + <div key={Int.toString(i)}> {compactErrorLine( ~highlight=isHighlighted(~focusedRowCol?, locMsg), ~prefix=#E, @@ -303,7 +301,7 @@ module ResultPane = { <div className="mt-4"> <PreWrap> <span className=subheader> {React.string("Received JSON payload:")} </span> - <div> {Util.Json.prettyStringify(json)->React.string} </div> + <div> {JSON.stringify(json, ~space=2)->React.string} </div> </PreWrap> </div> </div> @@ -332,11 +330,11 @@ module ResultPane = { } | Conv(Fail(_)) => (errClass, "Syntax Errors") | Comp(Success({warnings})) => - let warningNum = Belt.Array.length(warnings) + let warningNum = Array.length(warnings) if warningNum === 0 { (okClass, "Compiled successfully") } else { - (warnClass, "Compiled with " ++ (Belt.Int.toString(warningNum) ++ " Warning(s)")) + (warnClass, "Compiled with " ++ (Int.toString(warningNum) ++ " Warning(s)")) } | Conv(Success(_)) => (okClass, "Format Successful") | Comp(UnexpectedError(_)) @@ -426,13 +424,13 @@ module WarningFlagsWidget = { | "" => NoSuggestion | _ => // Case: + - let last = input->Js.String2.length - 1 - switch input->Js.String2.get(last) { + let last = input->String.length - 1 + switch input->String.get(last)->Option.getUnsafe { | "+" as modifier | "-" as modifier => let results = WarningFlagDescription.lookupAll() - let partial = input->Js.String2.substring(~from=0, ~to_=last) + let partial = input->String.substring(~start=0, ~end=last) let precedingTokens = switch WarningFlagDescription.Parser.parse(partial) { | Ok(tokens) => tokens @@ -450,19 +448,15 @@ module WarningFlagsWidget = { let results = WarningFlagDescription.Parser.parse(input) switch results { | Ok(tokens) => - let last = Belt.Array.get(tokens, Belt.Array.length(tokens) - 1) + let last = tokens[Array.length(tokens) - 1] switch last { | Some(token) => let results = WarningFlagDescription.fuzzyLookup(token.flag) - if Belt.Array.length(results) === 0 { + if Array.length(results) === 0 { ErrorSuggestion("No results") } else { - let precedingTokens = Belt.Array.slice( - tokens, - ~offset=0, - ~len=Belt.Array.length(tokens) - 1, - ) + let precedingTokens = Array.slice(tokens, ~start=0, ~end=Array.length(tokens) - 1) let modifier = token.enabled ? "+" : "-" FuzzySuggestions({ modifier, @@ -507,7 +501,7 @@ module WarningFlagsWidget = { let nextIdx = if selected > 0 { selected - 1 } else { - Belt.Array.length(results) - 1 + Array.length(results) - 1 } Typing({ ...typing, @@ -521,7 +515,7 @@ module WarningFlagsWidget = { let selectNext = (prev: state) => switch prev { | Typing({suggestion: FuzzySuggestions({selected, results} as suggestion)} as typing) => - let nextIdx = if selected < Belt.Array.length(results) - 1 { + let nextIdx = if selected < Array.length(results) - 1 { selected + 1 } else { 0 @@ -543,18 +537,16 @@ module WarningFlagsWidget = { let (state, setState) = React.useState(_ => HideSuggestion({input: ""})) // Used for the suggestion box list - let listboxRef = React.useRef(Js.Nullable.null) + let listboxRef = React.useRef(Nullable.null) // Used for the text input - let inputRef = React.useRef(Js.Nullable.null) + let inputRef = React.useRef(Nullable.null) - let focusInput = () => - inputRef.current->Js.Nullable.toOption->Belt.Option.forEach(el => el->focus) + let focusInput = () => inputRef.current->Nullable.forEach(el => el->focus) - let blurInput = () => - inputRef.current->Js.Nullable.toOption->Belt.Option.forEach(el => el->blur) + let blurInput = () => inputRef.current->Nullable.forEach(el => el->blur) - let chips = Belt.Array.mapWithIndex(flags, (i, token) => { + let chips = Array.mapWithIndex(flags, (token, i) => { let {WarningFlagDescription.Parser.flag: flag, enabled} = token let isActive = switch state { @@ -604,7 +596,7 @@ module WarningFlagsWidget = { // Removes clicked token from the current flags ReactEvent.Mouse.preventDefault(evt) - let remaining = Belt.Array.keep(flags, t => t.flag !== flag) + let remaining = Array.filter(flags, t => t.flag !== flag) onUpdate(remaining) } @@ -613,7 +605,7 @@ module WarningFlagsWidget = { ?onMouseEnter ?onMouseLeave className={color ++ " hover:cursor-default text-16 inline-block border border-gray-40 rounded-full px-2 mr-1"} - key={Belt.Int.toString(i) ++ flag}> + key={Int.toString(i) ++ flag}> {React.string(full)} </span> })->React.array @@ -623,7 +615,7 @@ module WarningFlagsWidget = { let ctrlKey = ReactEvent.Keyboard.ctrlKey(evt) /* let caretPosition = ReactEvent.Keyboard.target(evt)["selectionStart"] */ - /* Js.log2("caretPosition", caretPosition); */ + /* Console.log2("caretPosition", caretPosition); */ let full = (ctrlKey ? "CTRL+" : "") ++ key switch full { @@ -632,7 +624,7 @@ module WarningFlagsWidget = { | Typing({suggestion: FuzzySuggestions({precedingTokens, modifier, selected, results})}) => // In case a selection was made correctly, add // the flag to the current flags - switch Belt.Array.get(results, selected) { + switch results[selected] { | Some((num, _)) => let token = { WarningFlagDescription.Parser.enabled: modifier === "+", @@ -640,7 +632,7 @@ module WarningFlagsWidget = { } // TODO: merge tokens with flags - let newTokens = Belt.Array.concat(precedingTokens, [token]) + let newTokens = Array.concat(precedingTokens, [token]) let all = WarningFlagDescription.Parser.merge(flags, newTokens) @@ -655,7 +647,7 @@ module WarningFlagsWidget = { | "Tab" => switch state { | Typing({suggestion: FuzzySuggestions({modifier, precedingTokens, selected, results})}) => - switch Belt.Array.get(results, selected) { + switch results[selected] { | Some((num, _)) => let flag = modifier ++ num @@ -683,7 +675,7 @@ module WarningFlagsWidget = { if full !== "Backspace" { ReactEvent.Keyboard.preventDefault(evt) } - | _ => Js.log(full) + | _ => Console.log(full) } } } @@ -691,7 +683,7 @@ module WarningFlagsWidget = { let suggestions = switch state { | ShowTokenHint({token}) => WarningFlagDescription.lookup(token.flag) - ->Belt.Array.map(((num, description)) => { + ->Array.map(((num, description)) => { let (modifier, color) = if token.enabled { ("(Enabled) ", "text-turtle-dark") } else { @@ -710,13 +702,13 @@ module WarningFlagsWidget = { | NoSuggestion => React.string("Type + / - followed by a number or letter (e.g. +a+1)") | ErrorSuggestion(msg) => React.string(msg) | FuzzySuggestions({precedingTokens, selected, results, modifier}) => - Belt.Array.mapWithIndex(results, (i, (flag, desc)) => { + Array.mapWithIndex(results, ((flag, desc), i) => { let activeClass = selected === i ? "bg-gray-40" : "" let ref = if selected === i { ReactDOM.Ref.callbackDomRef(dom => { - let el = Js.Nullable.toOption(dom) - let parent = listboxRef.current->Js.Nullable.toOption + let el = Nullable.toOption(dom) + let parent = listboxRef.current->Nullable.toOption switch (parent, el) { | (Some(parent), Some(el)) => scrollToElement(~parent, el) @@ -765,14 +757,14 @@ module WarningFlagsWidget = { } let suggestionBox = - Belt.Option.map(suggestions, elements => + Option.map(suggestions, elements => <div ref={ReactDOM.Ref.domRef(listboxRef)} className="p-2 absolute overflow-auto z-50 border-b rounded border-l border-r block w-full bg-gray-100" style={ReactDOM.Style.make(~maxHeight="15rem", ())}> elements </div> - )->Belt.Option.getWithDefault(React.null) + )->Option.getOr(React.null) let onChange = evt => { ReactEvent.Form.preventDefault(evt) @@ -897,8 +889,7 @@ module Settings = { setConfig(config) } - let warnFlagTokens = - WarningFlagDescription.Parser.parse(warn_flags)->Belt.Result.getWithDefault([]) + let warnFlagTokens = WarningFlagDescription.Parser.parse(warn_flags)->Result.getOr([]) let onResetClick = evt => { ReactEvent.Mouse.preventDefault(evt) @@ -906,7 +897,7 @@ module Settings = { let open_modules = switch readyState.selected.apiVersion { | V1 | V2 | V3 | UnknownVersion(_) => None | V4 => - readyState.selected.libraries->Belt.Array.some(el => el === "@rescript/core") + readyState.selected.libraries->Array.some(el => el === "@rescript/core") ? Some(["RescriptCore"]) : None } @@ -937,22 +928,24 @@ module Settings = { } }}> { - let (experimentalVersions, stableVersions) = - readyState.versions->Js.Array2.reduce((acc, item) => { + let (experimentalVersions, stableVersions) = readyState.versions->Array.reduce( + ([], []), + (acc, item) => { let (lhs, rhs) = acc - if item.preRelease->Belt.Option.isSome { - Js.Array2.push(lhs, item) + if item.preRelease->Option.isSome { + Array.push(lhs, item) } else { - Js.Array2.push(rhs, item) + Array.push(rhs, item) }->ignore acc - }, ([], [])) + }, + ) <> {switch experimentalVersions { | [] => React.null | experimentalVersions => - let versionByOrder = experimentalVersions->Js.Array2.sortInPlaceWith((a, b) => { + let versionByOrder = experimentalVersions->Belt.SortArray.stableSortBy((a, b) => { let cmp = ({ CompilerManagerHook.Semver.major: major, minor, @@ -971,10 +964,10 @@ module Settings = { } let number = [major, minor, patch] - ->Js.Array2.map(v => v->Belt.Int.toString) - ->Js.Array2.joinWith("") - ->Belt.Int.fromString - ->Belt.Option.getWithDefault(0) + ->Array.map(v => v->Int.toString) + ->Array.join("") + ->Int.fromString + ->Option.getOr(0) number + preRelease } @@ -985,7 +978,7 @@ module Settings = { {React.string("---Experimental---")} </option> {versionByOrder - ->Belt.Array.map(version => { + ->Array.map(version => { let version = CompilerManagerHook.Semver.toString(version) <option className="py-4" key=version value=version> {React.string(version)} @@ -1000,7 +993,7 @@ module Settings = { {switch stableVersions { | [] => React.null | stableVersions => - Belt.Array.map(stableVersions, version => { + Array.map(stableVersions, version => { let version = CompilerManagerHook.Semver.toString(version) <option className="py-4" key=version value=version> {React.string(version)} @@ -1015,7 +1008,7 @@ module Settings = { <div className=titleClass> {React.string("Syntax")} </div> <ToggleSelection values=availableTargetLangs - toLabel={lang => lang->Api.Lang.toExt->Js.String2.toUpperCase} + toLabel={lang => lang->Api.Lang.toExt->String.toUpperCase} selected=readyState.targetLang onChange=onTargetLangSelect /> @@ -1032,7 +1025,7 @@ module Settings = { <div className="mt-6"> <div className=titleClass> {React.string("Loaded Libraries")} </div> <ul> - {Belt.Array.map(readyState.selected.libraries, lib => { + {Array.map(readyState.selected.libraries, lib => { <li className="ml-2" key=lib> {React.string(lib)} </li> })->React.array} </ul> @@ -1171,15 +1164,14 @@ module ControlPanel = { let version = ready.selected.compilerVersion - Js.Array2.push(params, ("version", "v" ++ version))->ignore + Array.push(params, ("version", "v" ++ version))->ignore - Js.Array2.push( + Array.push( params, ("code", editorCode.current->LzString.compressToEncodedURIComponent), )->ignore - let querystring = - params->Js.Array2.map(((key, value)) => key ++ "=" ++ value)->Js.Array2.joinWith("&") + let querystring = params->Array.map(((key, value)) => key ++ "=" ++ value)->Array.join("&") let url = origin ++ router.route ++ "?" ++ querystring Next.Router.replace(router, url) @@ -1396,10 +1388,10 @@ module OutputPanel = { (Settings, settingsPane), ] - let body = Belt.Array.mapWithIndex(tabs, (i, (tab, content)) => { + let body = Array.mapWithIndex(tabs, ((tab, content), i) => { let className = currentTab == tab ? "block h-inherit" : "hidden" - <div key={Belt.Int.toString(i)} className> content </div> + <div key={Int.toString(i)} className> content </div> }) <> {body->React.array} </> @@ -1498,32 +1490,31 @@ let make = (~versions: array<string>) => { let versions = versions - ->Belt.Array.keepMap(v => v->CompilerManagerHook.Semver.parse) - ->Js.Array2.sortInPlaceWith((a, b) => { + ->Array.filterMap(v => v->CompilerManagerHook.Semver.parse) + ->Belt.SortArray.stableSortBy((a, b) => { let cmp = ({CompilerManagerHook.Semver.major: major, minor, patch, _}) => { [major, minor, patch] - ->Js.Array2.map(v => v->Belt.Int.toString) - ->Js.Array2.joinWith("") - ->Belt.Int.fromString - ->Belt.Option.getWithDefault(0) + ->Array.map(v => v->Int.toString) + ->Array.join("") + ->Int.fromString + ->Option.getOr(0) } cmp(b) - cmp(a) }) - let lastStableVersion = - versions->Js.Array2.find(version => version.preRelease->Belt.Option.isNone) + let lastStableVersion = versions->Array.find(version => version.preRelease->Option.isNone) - let initialVersion = switch Js.Dict.get(router.query, "version") { + let initialVersion = switch Dict.get(router.query, "version") { | Some(version) => version->CompilerManagerHook.Semver.parse | None => lastStableVersion } - let initialLang = switch Js.Dict.get(router.query, "ext") { + let initialLang = switch Dict.get(router.query, "ext") { | Some("re") => Api.Lang.Reason | _ => Api.Lang.Res } - let initialContent = switch (Js.Dict.get(router.query, "code"), initialLang) { + let initialContent = switch (Dict.get(router.query, "code"), initialLang) { | (Some(compressedCode), _) => LzString.decompressToEncodedURIComponent(compressedCode) | (None, Reason) => initialReContent | (None, Res) @@ -1591,27 +1582,27 @@ let make = (~versions: array<string>) => { let isDragging = React.useRef(false) - let panelRef = React.useRef(Js.Nullable.null) + let panelRef = React.useRef(Nullable.null) - let separatorRef = React.useRef(Js.Nullable.null) - let leftPanelRef = React.useRef(Js.Nullable.null) - let rightPanelRef = React.useRef(Js.Nullable.null) - let subPanelRef = React.useRef(Js.Nullable.null) + let separatorRef = React.useRef(Nullable.null) + let leftPanelRef = React.useRef(Nullable.null) + let rightPanelRef = React.useRef(Nullable.null) + let subPanelRef = React.useRef(Nullable.null) let onResize = () => { let newLayout = Webapi.Window.innerWidth < breakingPoint ? Column : Row setLayout(_ => newLayout) - switch panelRef.current->Js.Nullable.toOption { + switch panelRef.current->Nullable.toOption { | Some(element) => let offsetTop = Webapi.Element.getBoundingClientRect(element)["top"] - Webapi.Element.Style.height(element, `calc(100vh - ${offsetTop->Belt.Float.toString}px)`) + Webapi.Element.Style.height(element, `calc(100vh - ${offsetTop->Float.toString}px)`) | None => () } - switch subPanelRef.current->Js.Nullable.toOption { + switch subPanelRef.current->Nullable.toOption { | Some(element) => let offsetTop = Webapi.Element.getBoundingClientRect(element)["top"] - Webapi.Element.Style.height(element, `calc(100vh - ${offsetTop->Belt.Float.toString}px)`) + Webapi.Element.Style.height(element, `calc(100vh - ${offsetTop->Float.toString}px)`) | None => () } } @@ -1632,36 +1623,36 @@ let make = (~versions: array<string>) => { let onMove = position => { if isDragging.current { switch ( - panelRef.current->Js.Nullable.toOption, - leftPanelRef.current->Js.Nullable.toOption, - rightPanelRef.current->Js.Nullable.toOption, - subPanelRef.current->Js.Nullable.toOption, + panelRef.current->Nullable.toOption, + leftPanelRef.current->Nullable.toOption, + rightPanelRef.current->Nullable.toOption, + subPanelRef.current->Nullable.toOption, ) { | (Some(panelElement), Some(leftElement), Some(rightElement), Some(subElement)) => let rectPanel = Webapi.Element.getBoundingClientRect(panelElement) // Update OutputPanel height let offsetTop = Webapi.Element.getBoundingClientRect(subElement)["top"] - Webapi.Element.Style.height(subElement, `calc(100vh - ${offsetTop->Belt.Float.toString}px)`) + Webapi.Element.Style.height(subElement, `calc(100vh - ${offsetTop->Float.toString}px)`) switch layout { | Row => - let delta = Belt.Int.toFloat(position) -. rectPanel["left"] + let delta = Int.toFloat(position) -. rectPanel["left"] let leftWidth = delta /. rectPanel["width"] *. 100.0 let rightWidth = (rectPanel["width"] -. delta) /. rectPanel["width"] *. 100.0 - Webapi.Element.Style.width(leftElement, `${leftWidth->Belt.Float.toString}%`) - Webapi.Element.Style.width(rightElement, `${rightWidth->Belt.Float.toString}%`) + Webapi.Element.Style.width(leftElement, `${leftWidth->Float.toString}%`) + Webapi.Element.Style.width(rightElement, `${rightWidth->Float.toString}%`) | Column => - let delta = Belt.Int.toFloat(position) -. rectPanel["top"] + let delta = Int.toFloat(position) -. rectPanel["top"] let topHeight = delta /. rectPanel["height"] *. 100. let bottomHeight = (rectPanel["height"] -. delta) /. rectPanel["height"] *. 100. - Webapi.Element.Style.height(leftElement, `${topHeight->Belt.Float.toString}%`) - Webapi.Element.Style.height(rightElement, `${bottomHeight->Belt.Float.toString}%`) + Webapi.Element.Style.height(leftElement, `${topHeight->Float.toString}%`) + Webapi.Element.Style.height(rightElement, `${bottomHeight->Float.toString}%`) } | _ => () } @@ -1706,9 +1697,9 @@ let make = (~versions: array<string>) => { | SyntaxErr(locMsgs) | TypecheckErr(locMsgs) | OtherErr(locMsgs) => - Js.Array2.map(locMsgs, locMsgToCmError(~kind=#Error, ...)) + Array.map(locMsgs, locMsgToCmError(~kind=#Error, ...)) | WarningErr(warnings) => - Js.Array2.map(warnings, warning => { + Array.map(warnings, warning => { switch warning { | Api.Warning.Warn({details}) | WarnErr({details}) => @@ -1718,14 +1709,14 @@ let make = (~versions: array<string>) => { | WarningFlagErr(_) => [] } | Comp(Success({warnings})) => - Js.Array2.map(warnings, warning => { + Array.map(warnings, warning => { switch warning { | Api.Warning.Warn({details}) | WarnErr({details}) => locMsgToCmError(~kind=#Warning, details) } }) - | Conv(Fail({details})) => Js.Array2.map(details, locMsgToCmError(~kind=#Error, ...)) + | Conv(Fail({details})) => Array.map(details, locMsgToCmError(~kind=#Error, ...)) | Comp(_) | Conv(_) | Nothing => [] @@ -1735,7 +1726,7 @@ let make = (~versions: array<string>) => { let cmHoverHints = switch compilerState { | Ready({result: FinalResult.Comp(Success({type_hints}))}) => - Js.Array2.map(type_hints, hint => { + Array.map(type_hints, hint => { switch hint { | TypeDeclaration({start, end, hint}) | Binding({start, end, hint}) @@ -1774,7 +1765,7 @@ let make = (~versions: array<string>) => { let tabs = [JavaScript, Console, Problems, Settings] - let headers = Belt.Array.mapWithIndex(tabs, (i, tab) => { + let headers = Array.mapWithIndex(tabs, (tab, i) => { let title = switch tab { // | RenderOutput => "Render Output" | Console => "Console" @@ -1791,7 +1782,7 @@ let make = (~versions: array<string>) => { // For Safari iOS12 let onClick = _ => () let className = makeTabClass(active) - <button key={Belt.Int.toString(i) ++ ("-" ++ title)} onMouseDown onClick className disabled> + <button key={Int.toString(i) ++ ("-" ++ title)} onMouseDown onClick className disabled> {React.string(title)} </button> }) @@ -1801,7 +1792,7 @@ let make = (~versions: array<string>) => { <main className={"flex flex-col bg-gray-100 overflow-hidden"}> <ControlPanel - actionIndicatorKey={Belt.Int.toString(actionCount)} + actionIndicatorKey={Int.toString(actionCount)} state=compilerState dispatch=compilerDispatch editorCode @@ -1827,9 +1818,9 @@ let make = (~versions: array<string>) => { switch typingTimer.current { | None => () - | Some(timer) => Js.Global.clearTimeout(timer) + | Some(timer) => clearTimeout(timer) } - let timer = Js.Global.setTimeout(() => { + let timer = setTimeout(() => { timeoutCompile.current() typingTimer.current = None }, 100) diff --git a/src/SyntaxLookup.res b/src/SyntaxLookup.res index 27f2cf986..7e916c775 100644 --- a/src/SyntaxLookup.res +++ b/src/SyntaxLookup.res @@ -91,7 +91,7 @@ type itemInfo = { } let getAnchor = path => { - switch Js.String2.split(path, "#") { + switch String.split(path, "#") { | [_, anchor] => Some(anchor) | _ => None } @@ -114,7 +114,7 @@ module Tag = { module DetailBox = { @react.component let make = (~summary: string, ~children: React.element) => { - let summaryEl = switch Js.String2.split(summary, "`") { + let summaryEl = switch String.split(summary, "`") { | [] => React.null | [first, second, third] => [ @@ -122,11 +122,11 @@ module DetailBox = { <span className="text-fire"> {React.string(second)} </span>, React.string(third), ] - ->Belt.Array.mapWithIndex((i, el) => { - <span key={Belt.Int.toString(i)}> el </span> + ->Array.mapWithIndex((el, i) => { + <span key={Int.toString(i)}> el </span> }) ->React.array - | more => Belt.Array.map(more, s => React.string(s))->React.array + | more => Array.map(more, s => React.string(s))->React.array } <div> @@ -149,7 +149,7 @@ let scrollToTop = () => scrollTo(0, 0) type props = {mdxSources: array<MdxRemote.output>} type params = {slug: string} -let decode = (json: Js.Json.t) => { +let decode = (json: JSON.t) => { open Json.Decode let id = json->(field("id", string, _)) let keywords = json->(field("keywords", array(string, ...), _)) @@ -159,7 +159,7 @@ let decode = (json: Js.Json.t) => { let status = json ->optional(field("status", string, _), _) - ->Belt.Option.mapWithDefault(Status.Active, Status.fromString) + ->Option.mapOr(Status.Active, Status.fromString) { id, @@ -174,7 +174,7 @@ let decode = (json: Js.Json.t) => { let default = (props: props) => { let {mdxSources} = props - let allItems = mdxSources->Js.Array2.map(mdxSource => { + let allItems = mdxSources->Array.map(mdxSource => { let {id, keywords, category, summary, name, status} = decode(mdxSource.frontmatter) let children = @@ -204,14 +204,14 @@ let default = (props: props) => { let router = Next.Router.useRouter() let (state, setState) = React.useState(_ => ShowAll) - let findItemById = id => allItems->Js.Array2.find(item => item.id === id) + let findItemById = id => allItems->Array.find(item => item.id === id) - let findItemByExactName = name => allItems->Js.Array2.find(item => item.name === name) + let findItemByExactName = name => allItems->Array.find(item => item.name === name) let searchItems = value => fuse ->Fuse.search(value) - ->Belt.Array.map(m => { + ->Array.map(m => { m["item"] }) @@ -280,7 +280,7 @@ let default = (props: props) => { ExtensionPoints, SpecialValues, Other, - ]->Belt.Array.map(cat => { + ]->Array.map(cat => { (cat->Category.toString, []) }) @@ -290,15 +290,15 @@ let default = (props: props) => { | ShowFiltered(_, items) => items } - Belt.Array.reduce(items, Js.Dict.fromArray(initial), (acc, item) => { + Array.reduce(items, Dict.fromArray(initial), (acc, item) => { let key = item.category->Category.toString - Js.Dict.get(acc, key)->Belt.Option.mapWithDefault(acc, items => { - Js.Array2.push(items, item)->ignore - Js.Dict.set(acc, key, items) + Dict.get(acc, key)->Option.mapOr(acc, items => { + Array.push(items, item)->ignore + Dict.set(acc, key, items) acc }) }) - ->Js.Dict.entries + ->Dict.toArray ->Array.reduce([], (acc, entry) => { let (title, items) = entry if Array.length(items) === 0 { @@ -320,7 +320,7 @@ let default = (props: props) => { <div key=title className="first:mt-0 mt-12"> <Category title> {React.array(children)} </Category> </div> - Js.Array2.push(acc, el)->ignore + Array.push(acc, el)->ignore acc } }) @@ -351,7 +351,7 @@ let default = (props: props) => { <div className="w-full" style={ReactDOM.Style.make(~maxWidth="34rem", ())}> <SearchBox placeholder="Enter keywords or syntax..." - completionValues={Belt.Array.map(completionItems, item => item.name)} + completionValues={Array.map(completionItems, item => item.name)} value=searchValue onClear=onSearchClear onValueChange=onSearchValueChange @@ -391,7 +391,7 @@ let default = (props: props) => { let getStaticProps: Next.GetStaticProps.t<props, params> = async _ctx => { let dir = Node.Path.resolve("misc_docs", "syntax") - let allFiles = Node.Fs.readdirSync(dir)->Js.Array2.map(async file => { + let allFiles = Node.Fs.readdirSync(dir)->Array.map(async file => { let fullPath = Node.Path.join2(dir, file) let source = fullPath->Node.Fs.readFileSync await MdxRemote.serialize( @@ -400,7 +400,7 @@ let getStaticProps: Next.GetStaticProps.t<props, params> = async _ctx => { ) }) - let mdxSources = await Js.Promise2.all(allFiles) + let mdxSources = await Promise.all(allFiles) {"props": {mdxSources: mdxSources}} } diff --git a/src/Try.res b/src/Try.res index b40e82442..1f9d25940 100644 --- a/src/Try.res +++ b/src/Try.res @@ -4,7 +4,7 @@ let default = props => { let (isOverlayOpen, setOverlayOpen) = React.useState(() => false) let lazyPlayground = Next.Dynamic.dynamic( - async () => await Js.import(Playground.make), + async () => await import(Playground.make), { ssr: false, loading: () => <span> {React.string("Loading...")} </span>, @@ -32,20 +32,16 @@ let getStaticProps: Next.GetStaticProps.t<props, _> = async _ => { let response = await Webapi.Fetch.fetch("https://cdn.rescript-lang.org/") let text = await Webapi.Fetch.Response.text(response) text - ->Js.String2.split("\n") - ->Belt.Array.keepMap(line => { - switch line->Js.String2.startsWith("<a href") { + ->String.split("\n") + ->Array.filterMap(line => { + switch line->String.startsWith("<a href") { | true => // Adapted from https://semver.org/ let semverRe = %re( "/v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?/" ) - switch Js.Re.exec_(semverRe, line) { - | Some(result) => - switch Js.Re.captures(result)->Belt.Array.get(0) { - | Some(str) => Js.Nullable.toOption(str) - | None => None - } + switch Re.exec(semverRe, line) { + | Some(result) => Re.Result.fullMatch(result)->Some | None => None } | false => None diff --git a/src/bindings/DocSearch.res b/src/bindings/DocSearch.res index e01ad2336..e1f9ac842 100644 --- a/src/bindings/DocSearch.res +++ b/src/bindings/DocSearch.res @@ -12,20 +12,20 @@ type contentType = type hierarchy = { lvl0: string, lvl1: string, - lvl2: Js.Nullable.t<string>, - lvl3: Js.Nullable.t<string>, - lvl4: Js.Nullable.t<string>, - lvl5: Js.Nullable.t<string>, - lvl6: Js.Nullable.t<string>, + lvl2: Nullable.t<string>, + lvl3: Nullable.t<string>, + lvl4: Nullable.t<string>, + lvl5: Nullable.t<string>, + lvl6: Nullable.t<string>, } type docSearchHit = { objectID: string, - content: Js.Nullable.t<string>, + content: Nullable.t<string>, url: string, url_without_anchor: string, @as("type") type_: contentType, - anchor: Js.Nullable.t<string>, + anchor: Nullable.t<string>, hierarchy: hierarchy, // NOTE: docsearch need these two fields to highlight results _highlightResult: {.}, diff --git a/src/bindings/MdxRemote.res b/src/bindings/MdxRemote.res index d92f7cb08..855ac0053 100644 --- a/src/bindings/MdxRemote.res +++ b/src/bindings/MdxRemote.res @@ -1,4 +1,4 @@ -type output = {frontmatter: Js.Json.t, compiledSource: string, scope: Js.Json.t} +type output = {frontmatter: JSON.t, compiledSource: string, scope: JSON.t} type mdxOptions = { remarkPlugins?: array<Remark.remarkPlugin>, @@ -24,8 +24,8 @@ let defaultMdxOptions = { @react.component @module("next-mdx-remote") external make: ( - ~frontmatter: Js.Json.t, + ~frontmatter: JSON.t, ~compiledSource: string, - ~scope: Js.Json.t, + ~scope: JSON.t, ~components: MarkdownComponents.t=?, ) => React.element = "MDXRemote" diff --git a/src/bindings/Next.res b/src/bindings/Next.res index c783c5197..87e65dc8f 100644 --- a/src/bindings/Next.res +++ b/src/bindings/Next.res @@ -14,7 +14,7 @@ module GetServerSideProps = { // See: https://github.com/zeit/next.js/blob/canary/packages/next/types/index.d.ts type context<'props, 'params> = { params: 'params, - query: Js.Dict.t<string>, + query: Dict.t<string>, req: Req.t, res: Res.t, } @@ -26,8 +26,8 @@ module GetStaticProps = { // See: https://github.com/zeit/next.js/blob/canary/packages/next/types/index.d.ts type context<'props, 'params> = { params: 'params, - query: Js.Dict.t<string>, - req: Js.Nullable.t<'props>, + query: Dict.t<string>, + req: Nullable.t<'props>, } type t<'props, 'params> = context<'props, 'params> => promise<{"props": 'props}> @@ -101,12 +101,12 @@ module Router = { asPath: string, events: Events.t, pathname: string, - query: Js.Dict.t<string>, + query: Dict.t<string>, } type pathObj = { pathname: string, - query: Js.Dict.t<string>, + query: Dict.t<string>, } @send external push: (router, string) => unit = "push" diff --git a/src/bindings/Next.resi b/src/bindings/Next.resi index 00583343d..d5a0e8b19 100644 --- a/src/bindings/Next.resi +++ b/src/bindings/Next.resi @@ -14,7 +14,7 @@ module GetServerSideProps: { // See: https://github.com/zeit/next.js/blob/canary/packages/next/types/index.d.ts type context<'props, 'params> = { params: 'params, - query: Js.Dict.t<string>, + query: Dict.t<string>, req: Req.t, res: Res.t, } @@ -26,8 +26,8 @@ module GetStaticProps: { // See: https://github.com/zeit/next.js/blob/canary/packages/next/types/index.d.ts type context<'props, 'params> = { params: 'params, - query: Js.Dict.t<string>, - req: Js.Nullable.t<'props>, + query: Dict.t<string>, + req: Nullable.t<'props>, } type t<'props, 'params> = context<'props, 'params> => promise<{"props": 'props}> @@ -97,12 +97,12 @@ module Router: { asPath: string, events: Events.t, pathname: string, - query: Js.Dict.t<string>, + query: Dict.t<string>, } type pathObj = { pathname: string, - query: Js.Dict.t<string>, + query: Dict.t<string>, } let push: (router, string) => unit diff --git a/src/bindings/Node.res b/src/bindings/Node.res index 49c8b20e4..d688f7baa 100644 --- a/src/bindings/Node.res +++ b/src/bindings/Node.res @@ -13,7 +13,7 @@ module URL = { module Process = { @scope("process") external cwd: unit => string = "cwd" - @scope("process") external env: Js.Dict.t<string> = "env" + @scope("process") external env: Dict.t<string> = "env" @scope("process") @val external argv: array<string> = "argv" @scope("process") external exit: int => unit = "exit" } diff --git a/src/bindings/RescriptCompilerApi.res b/src/bindings/RescriptCompilerApi.res index aad035666..fca8838ff 100644 --- a/src/bindings/RescriptCompilerApi.res +++ b/src/bindings/RescriptCompilerApi.res @@ -41,10 +41,10 @@ module Version = { // Helps finding the right API version let fromString = (apiVersion: string): t => - switch Js.String2.split(apiVersion, ".")->Belt.List.fromArray { + switch String.split(apiVersion, ".")->List.fromArray { | list{maj, min, ..._} => - let maj = Belt.Int.fromString(maj) - let min = Belt.Int.fromString(min) + let maj = Int.fromString(maj) + let min = Int.fromString(min) switch (maj, min) { | (Some(maj), Some(_)) @@ -113,28 +113,28 @@ module LocMsg = { | #E => "E" } - `[${prefix}] Line ${row->Belt.Int.toString}, ${column->Belt.Int.toString}: ${shortMsg}` + `[${prefix}] Line ${row->Int.toString}, ${column->Int.toString}: ${shortMsg}` } // Creates a somewhat unique id based on the rows / cols of the locMsg let makeId = t => { - open Belt.Int + open Int toString(t.row) ++ ("-" ++ (toString(t.endRow) ++ ("-" ++ (toString(t.column) ++ ("-" ++ toString(t.endColumn)))))) } let dedupe = (arr: array<t>) => { - let result = Js.Dict.empty() + let result = Dict.make() - for i in 0 to Js.Array.length(arr) - 1 { + for i in 0 to Array.length(arr) - 1 { let locMsg = Array.getUnsafe(arr, i) let id = makeId(locMsg) // The last element with the same id wins - result->Js.Dict.set(id, locMsg) + result->Dict.set(id, locMsg) } - Js.Dict.values(result) + Dict.valuesToArray(result) } } @@ -163,11 +163,11 @@ module Warning = { | Warn({warnNumber, details}) | WarnErr({warnNumber, details}) => let {LocMsg.row: row, column, shortMsg} = details - let msg = `(Warning number ${warnNumber->Belt.Int.toString}) ${shortMsg}` + let msg = `(Warning number ${warnNumber->Int.toString}) ${shortMsg}` (row, column, msg) } - `[${prefix}] Line ${row->Belt.Int.toString}, ${column->Belt.Int.toString}: ${msg}` + `[${prefix}] Line ${row->Int.toString}, ${column->Int.toString}: ${msg}` } } @@ -308,10 +308,10 @@ module CompilationResult = { | Fail(CompileFail.t) // When a compilation failed with some error result | Success(CompileSuccess.t) | UnexpectedError(string) // Errors that slip through as uncaught exceptions of the compiler bundle - | Unknown(string, Js.Json.t) + | Unknown(string, JSON.t) // TODO: We might change this specific api completely before launching - let decode = (~time: float, json: Js.Json.t): t => { + let decode = (~time: float, json: JSON.t): t => { open! Json.Decode try switch field("type", string, json) { @@ -329,7 +329,7 @@ module ConversionResult = { | Success(ConvertSuccess.t) | Fail({fromLang: Lang.t, toLang: Lang.t, details: array<LocMsg.t>}) // When a compilation failed with some error result | UnexpectedError(string) // Errors that slip through as uncaught exceptions within the playground - | Unknown(string, Js.Json.t) + | Unknown(string, JSON.t) let decode = (~fromLang: Lang.t, ~toLang: Lang.t, json): t => { open! Json.Decode @@ -369,7 +369,7 @@ module Compiler = { @get @scope("rescript") external resVersion: t => string = "version" @send @scope("rescript") - external resCompile: (t, string) => Js.Json.t = "compile" + external resCompile: (t, string) => JSON.t = "compile" let resCompile = (t, code): CompilationResult.t => { let startTime = now() @@ -380,7 +380,7 @@ module Compiler = { } @send @scope("rescript") - external resFormat: (t, string) => Js.Json.t = "format" + external resFormat: (t, string) => JSON.t = "format" let resFormat = (t, code): ConversionResult.t => { let json = resFormat(t, code) @@ -388,7 +388,7 @@ module Compiler = { } @send @scope("reason") - external reasonCompile: (t, string) => Js.Json.t = "compile" + external reasonCompile: (t, string) => JSON.t = "compile" let reasonCompile = (t, code): CompilationResult.t => { let startTime = now() let json = reasonCompile(t, code) @@ -398,7 +398,7 @@ module Compiler = { } @send @scope("reason") - external reasonFormat: (t, string) => Js.Json.t = "format" + external reasonFormat: (t, string) => JSON.t = "format" let reasonFormat = (t, code): ConversionResult.t => { let json = reasonFormat(t, code) @@ -408,7 +408,7 @@ module Compiler = { @get @scope("ocaml") external ocamlVersion: t => string = "version" @send @scope("ocaml") - external ocamlCompile: (t, string) => Js.Json.t = "compile" + external ocamlCompile: (t, string) => JSON.t = "compile" let ocamlCompile = (t, code): CompilationResult.t => { let startTime = now() @@ -436,14 +436,14 @@ module Compiler = { | _ => None } - Belt.Option.forEach(moduleSystem, moduleSystem => t->setModuleSystem(moduleSystem)->ignore) - Belt.Option.forEach(config.open_modules, modules => t->setOpenModules(modules)->ignore) + Option.forEach(moduleSystem, moduleSystem => t->setModuleSystem(moduleSystem)->ignore) + Option.forEach(config.open_modules, modules => t->setOpenModules(modules)->ignore) t->setWarnFlags(config.warn_flags)->ignore } @send - external convertSyntax: (t, string, string, string) => Js.Json.t = "convertSyntax" + external convertSyntax: (t, string, string, string) => JSON.t = "convertSyntax" // General format function let convertSyntax = (~fromLang: Lang.t, ~toLang: Lang.t, ~code: string, t): ConversionResult.t => @@ -455,8 +455,8 @@ module Compiler = { ~fromLang, ~toLang, ) catch { - | Js.Exn.Error(obj) => - switch Js.Exn.message(obj) { + | Exn.Error(obj) => + switch Exn.message(obj) { | Some(m) => ConversionResult.UnexpectedError(m) | None => UnexpectedError("") } diff --git a/src/bindings/RescriptCompilerApi.resi b/src/bindings/RescriptCompilerApi.resi index cfb3065aa..b722d91c8 100644 --- a/src/bindings/RescriptCompilerApi.resi +++ b/src/bindings/RescriptCompilerApi.resi @@ -16,7 +16,7 @@ module Lang: { let toExt: t => string - let decode: Js.Json.t => t + let decode: JSON.t => t } module Version: { @@ -47,7 +47,7 @@ module LocMsg: { endColumn: int, } - let decode: Js.Json.t => t + let decode: JSON.t => t type prefix = [#W | #E] @@ -65,7 +65,7 @@ module Warning: { | Warn({warnNumber: int, details: LocMsg.t}) | WarnErr({warnNumber: int, details: LocMsg.t}) // Describes an erronous warning - let decode: Js.Json.t => t + let decode: JSON.t => t // Useful for showing errors in a more compact format let toCompactErrorLine: t => string @@ -78,7 +78,7 @@ module WarningFlag: { warn_error_flags: string, } - let decode: Js.Json.t => t + let decode: JSON.t => t } module TypeHint: { @@ -98,7 +98,7 @@ module TypeHint: { | Binding(data) | CoreType(data) - let decode: Js.Json.t => t + let decode: JSON.t => t } module CompileSuccess: { @@ -109,7 +109,7 @@ module CompileSuccess: { time: float, // total compilation time } - let decode: (~time: float, Js.Json.t) => t + let decode: (~time: float, JSON.t) => t } module ConvertSuccess: { @@ -119,7 +119,7 @@ module ConvertSuccess: { toLang: Lang.t, } - let decode: Js.Json.t => t + let decode: JSON.t => t } module CompileFail: { @@ -130,7 +130,7 @@ module CompileFail: { | WarningFlagErr(WarningFlag.t) | OtherErr(array<LocMsg.t>) - let decode: Js.Json.t => t + let decode: JSON.t => t } module CompilationResult: { @@ -138,10 +138,10 @@ module CompilationResult: { | Fail(CompileFail.t) // When a compilation failed with some error result | Success(CompileSuccess.t) | UnexpectedError(string) // Errors that slip through as uncaught exceptions of the compiler bundle - | Unknown(string, Js.Json.t) + | Unknown(string, JSON.t) // TODO: We might change this specific api completely before launching - let decode: (~time: float, Js.Json.t) => t + let decode: (~time: float, JSON.t) => t } module ConversionResult: { @@ -149,9 +149,9 @@ module ConversionResult: { | Success(ConvertSuccess.t) | Fail({fromLang: Lang.t, toLang: Lang.t, details: array<LocMsg.t>}) // When a compilation failed with some error result | UnexpectedError(string) // Errors that slip through as uncaught exceptions within the playground - | Unknown(string, Js.Json.t) + | Unknown(string, JSON.t) - let decode: (~fromLang: Lang.t, ~toLang: Lang.t, Js.Json.t) => t + let decode: (~fromLang: Lang.t, ~toLang: Lang.t, JSON.t) => t } module Config: { diff --git a/src/bindings/Webapi.res b/src/bindings/Webapi.res index ad43b418e..a3a053279 100644 --- a/src/bindings/Webapi.res +++ b/src/bindings/Webapi.res @@ -19,7 +19,7 @@ module Element = { @send external addEventListener: (Dom.element, string, unit => unit) => unit = "addEventListener" @send - external getElementById: (Dom.element, string) => Js.nullable<Dom.element> = "getElementById" + external getElementById: (Dom.element, string) => Nullable.t<Dom.element> = "getElementById" type contentWindow @get external contentWindow: Dom.element => option<contentWindow> = "contentWindow" @@ -54,7 +54,7 @@ module Fetch = { module Response = { type t @send external text: t => promise<string> = "text" - @send external json: t => promise<Js.Json.t> = "json" + @send external json: t => promise<JSON.t> = "json" } @val external fetch: string => promise<Response.t> = "fetch" diff --git a/src/common/Ansi.res b/src/common/Ansi.res index 512ab85b9..99277341b 100644 --- a/src/common/Ansi.res +++ b/src/common/Ansi.res @@ -54,7 +54,7 @@ module Sgr = { let esc = `\u001B` -let isAscii = (c: string) => Js.Re.test_(%re(`/[\x40-\x7F]/`), c) +let isAscii = (c: string) => Re.test(%re(`/[\x40-\x7F]/`), c) module Location = { type t = { @@ -69,15 +69,15 @@ module Location = { let fromString = input => {input, pos: -1} - let isDone = p => p.pos >= Js.String.length(p.input) + let isDone = p => p.pos >= String.length(p.input) let next = p => if !isDone(p) { - let c = Js.String2.get(p.input, p.pos + 1) + let c = String.get(p.input, p.pos + 1)->Option.getUnsafe p.pos = p.pos + 1 c } else { - Js.String2.get(p.input, p.pos) + String.get(p.input, p.pos)->Option.getUnsafe } let untilNextEsc = p => { @@ -95,7 +95,7 @@ module Location = { // Look is useful to look ahead without reading the character // from the stream let look = (p, num) => { - let length = Js.String.length(p.input) + let length = String.length(p.input) let pos = if p.pos + num >= length { length - 1 @@ -103,7 +103,7 @@ module Location = { p.pos + num } - Js.String2.get(p.input, pos) + String.get(p.input, pos)->Option.getUnsafe } } @@ -152,7 +152,7 @@ module Lexer = { }, content, }) - Js.Array2.push(acc, token)->ignore + Array.push(acc, token)->ignore lex(~acc, ~state=ReadSgr({startPos: p.pos, content: c}), p) } else if isDone(p) { let token = Text({ @@ -162,7 +162,7 @@ module Lexer = { }, content, }) - Js.Array2.push(acc, token)->ignore + Array.push(acc, token)->ignore acc } else { let content = content ++ c @@ -175,49 +175,47 @@ module Lexer = { if c !== "[" && isAscii(c) { let raw = content ++ c - let loc = {startPos, endPos: startPos + Js.String.length(raw) - 1} - - let token = Js.Re.exec_(%re(`/\[([0-9;]+)([\x40-\x7F])/`), raw)->( - x => - switch x { - | Some(result) => - let groups = Js.Re.captures(result) - switch groups[1]->Option.flatMap(o => o->Js.Nullable.toOption) { - | Some(str) => - switch Js.String2.split(str, ";") { - | ["0"] => ClearSgr({loc, raw}) - | other => - let params = Belt.Array.map(other, s => - switch s { - | "1" => Bold - | "30" => Fg(Black) - | "31" => Fg(Red) - | "32" => Fg(Green) - | "33" => Fg(Yellow) - | "34" => Fg(Blue) - | "35" => Fg(Magenta) - | "36" => Fg(Cyan) - | "37" => Fg(White) - | "40" => Bg(Black) - | "41" => Bg(Red) - | "42" => Bg(Green) - | "43" => Bg(Yellow) - | "44" => Bg(Blue) - | "45" => Bg(Magenta) - | "46" => Bg(Cyan) - | "47" => Bg(White) - | o => Unknown(o) - } - ) - Sgr({loc, raw, params}) + let loc = {startPos, endPos: startPos + String.length(raw) - 1} + + let token = switch Re.exec(%re(`/\[([0-9;]+)([\x40-\x7F])/`), raw) { + | Some(result) => + let groups = Re.Result.matches(result) + switch groups[1] { + | Some(str) => + switch String.split(str, ";") { + | ["0"] => ClearSgr({loc, raw}) + | other => + let params = Array.map(other, s => + switch s { + | "1" => Bold + | "30" => Fg(Black) + | "31" => Fg(Red) + | "32" => Fg(Green) + | "33" => Fg(Yellow) + | "34" => Fg(Blue) + | "35" => Fg(Magenta) + | "36" => Fg(Cyan) + | "37" => Fg(White) + | "40" => Bg(Black) + | "41" => Bg(Red) + | "42" => Bg(Green) + | "43" => Bg(Yellow) + | "44" => Bg(Blue) + | "45" => Bg(Magenta) + | "46" => Bg(Cyan) + | "47" => Bg(White) + | o => Unknown(o) } - - | None => Sgr({loc, raw, params: []}) - } - | None => Sgr({loc, raw, params: []}) + ) + Sgr({loc, raw, params}) } - ) - Js.Array2.push(acc, token)->ignore + + | None => Sgr({loc, raw, params: []}) + } + | None => Sgr({loc, raw, params: []}) + } + + Array.push(acc, token)->ignore lex(~acc, ~state=Scan, p) } else { lex(~acc, ~state=ReadSgr({startPos, content: content ++ c}), p) @@ -238,7 +236,7 @@ let parse = (input: string) => { let onlyText = (tokens: array<Lexer.token>) => { open Lexer - Belt.Array.keep(tokens, x => + Array.filter(tokens, x => switch x { | Text(_) => true | _ => false @@ -260,7 +258,7 @@ module SgrString = { let params = ref([]) let content = ref("") - let length = Js.Array.length(tokens) + let length = Array.length(tokens) for i in 0 to length - 1 { let token = Belt.Array.getExn(tokens, i) @@ -271,11 +269,11 @@ module SgrString = { content := content.contents ++ data.content if isLast && content.contents !== "" { let element = {content: content.contents, params: params.contents} - Js.Array2.push(ret, element)->ignore + Array.push(ret, element)->ignore } | Sgr(data) => // merge together specific sgr params - let (fg, bg, rest) = Belt.Array.concat(params.contents, data.params)->Belt.Array.reduce( + let (fg, bg, rest) = Array.concat(params.contents, data.params)->Array.reduce( (None, None, []), (acc, next) => { let (fg, bg, other) = acc @@ -283,8 +281,8 @@ module SgrString = { | Fg(_) => (Some(next), bg, other) | Bg(_) => (fg, Some(next), other) | o => - if Js.Array2.find(other, o2 => o === o2) === None { - Js.Array2.push(other, next)->ignore + if Array.find(other, o2 => o === o2) === None { + Array.push(other, next)->ignore } (fg, bg, other) } @@ -293,20 +291,20 @@ module SgrString = { if content.contents !== "" { let element = {content: content.contents, params: params.contents} - Js.Array2.push(ret, element)->ignore + Array.push(ret, element)->ignore content := "" } params := Belt.Array.concatMany([ - Belt.Option.mapWithDefault(fg, [], v => [v]), - Belt.Option.mapWithDefault(bg, [], v => [v]), + Option.mapOr(fg, [], v => [v]), + Option.mapOr(bg, [], v => [v]), rest, ]) | ClearSgr(_) => if content.contents !== "" { let element = {content: content.contents, params: params.contents} - Js.Array2.push(ret, element)->ignore + Array.push(ret, element)->ignore params := [] content := "" @@ -319,10 +317,10 @@ module SgrString = { let toString = (e: t): string => { let content = { - open Js.String2 - replaceByRe(e.content, %re("/\n/g"), "\\n")->replace(esc, "") + open String + replaceRegExp(e.content, %re("/\n/g"), "\\n")->replace(esc, "") } - let params = Belt.Array.map(e.params, Sgr.paramToString)->Js.Array2.joinWith(", ") + let params = Array.map(e.params, Sgr.paramToString)->Array.join(", ") `SgrString params: ${params} | content: ${content}` } @@ -335,24 +333,24 @@ module Printer = { switch t { | Text({content, loc: {startPos, endPos}}) => let content = { - open Js.String2 - replaceByRe(content, %re("/\n/g"), "\\n")->replace(esc, "") + open String + replaceRegExp(content, %re("/\n/g"), "\\n")->replace(esc, "") } - `Text "${content}" (${startPos->Belt.Int.toString} to ${endPos->Belt.Int.toString})` + `Text "${content}" (${startPos->Int.toString} to ${endPos->Int.toString})` | Sgr({params, raw, loc: {startPos, endPos}}) => - let raw = Js.String2.replace(raw, esc, "") - let params = Belt.Array.map(params, Sgr.paramToString)->Js.Array2.joinWith(", ") - `Sgr "${raw}" -> ${params} (${startPos->Belt.Int.toString} to ${endPos->Belt.Int.toString})` + let raw = String.replace(raw, esc, "") + let params = Array.map(params, Sgr.paramToString)->Array.join(", ") + `Sgr "${raw}" -> ${params} (${startPos->Int.toString} to ${endPos->Int.toString})` | ClearSgr({loc: {startPos, endPos}, raw}) => - let raw = Js.String2.replace(raw, esc, "") - `Clear Sgr "${raw}" (${startPos->Belt.Int.toString} to ${endPos->Belt.Int.toString})` + let raw = String.replace(raw, esc, "") + `Clear Sgr "${raw}" (${startPos->Int.toString} to ${endPos->Int.toString})` } let plainString = (tokens: array<token>): string => - Belt.Array.map(tokens, x => + Array.map(tokens, x => switch x { | Lexer.Text({content}) => content | _ => "" } - )->Js.Array2.joinWith("") + )->Array.join("") } diff --git a/src/common/App.res b/src/common/App.res index 4962cd772..136b7fb0c 100644 --- a/src/common/App.res +++ b/src/common/App.res @@ -38,7 +38,7 @@ type pageProps = {.} type props = {"Component": pageComponent, "pageProps": pageProps} @get -external frontmatter: React.component<{.}> => Js.Json.t = "frontmatter" +external frontmatter: React.component<{.}> => JSON.t = "frontmatter" let make = (props: props): React.element => { let component = props["Component"] @@ -57,16 +57,16 @@ let make = (props: props): React.element => { | {base: ["docs", "manual"], pagepath, version} => // check if it's an api route <EnableCollapsibleNavbar> - {switch Belt.Array.get(pagepath, 0) { + {switch pagepath[0] { | Some("api") => switch version { | Latest => - switch (Belt.Array.length(pagepath), Belt.Array.get(pagepath, 1)) { + switch (Array.length(pagepath), pagepath[1]) { | (1, _) => <ApiOverviewLayout.Docs> content </ApiOverviewLayout.Docs> | _ => content } | Version("v8.0.0") => - switch (Belt.Array.length(pagepath), Belt.Array.get(pagepath, 1)) { + switch (Array.length(pagepath), pagepath[1]) { | (1, _) => <ApiOverviewLayout8_0_0.Docs> content </ApiOverviewLayout8_0_0.Docs> | (2, Some("js")) => <JsDocsLayout8_0_0.Prose> content </JsDocsLayout8_0_0.Prose> | (2, Some("belt")) => <BeltDocsLayout8_0_0.Prose> content </BeltDocsLayout8_0_0.Prose> @@ -76,7 +76,7 @@ let make = (props: props): React.element => { | _ => React.null } | Version("v9.0.0") => - switch (Belt.Array.length(pagepath), Belt.Array.get(pagepath, 1)) { + switch (Array.length(pagepath), pagepath[1]) { | (1, _) => <ApiOverviewLayout9_0_0.Docs> content </ApiOverviewLayout9_0_0.Docs> | (2, Some("js")) => <JsDocsLayout9_0_0.Prose> content </JsDocsLayout9_0_0.Prose> | (2, Some("belt")) => <BeltDocsLayout9_0_0.Prose> content </BeltDocsLayout9_0_0.Prose> @@ -86,7 +86,7 @@ let make = (props: props): React.element => { | _ => React.null } | Version("v10.0.0") => - switch (Belt.Array.length(pagepath), Belt.Array.get(pagepath, 1)) { + switch (Array.length(pagepath), pagepath[1]) { | (1, _) => <ApiOverviewLayout10_0_0.Docs> content </ApiOverviewLayout10_0_0.Docs> | (2, Some("js")) => <JsDocsLayout10_0_0.Prose> content </JsDocsLayout10_0_0.Prose> | (2, Some("belt")) => <BeltDocsLayout10_0_0.Prose> content </BeltDocsLayout10_0_0.Prose> @@ -143,7 +143,7 @@ let make = (props: props): React.element => { </EnableCollapsibleNavbar> // common routes | {base} => - switch Belt.List.fromArray(base) { + switch List.fromArray(base) { | list{"community", ..._rest} => <EnableCollapsibleNavbar> <CommunityLayout frontmatter={component->frontmatter}> content </CommunityLayout> @@ -160,9 +160,9 @@ let make = (props: props): React.element => { let fm = component->frontmatter->DocFrontmatter.decode let title = switch url { | {base: ["docs"]} => Some("Overview | ReScript Documentation") - | _ => Belt.Option.map(fm, fm => fm.title) + | _ => Option.map(fm, fm => fm.title) } - let description = Belt.Option.flatMap(fm, fm => Js.Null.toOption(fm.description)) + let description = Option.flatMap(fm, fm => Null.toOption(fm.description)) <MainLayout> <Meta ?title ?description version=url.version /> <div className="flex justify-center"> diff --git a/src/common/BlogApi.res b/src/common/BlogApi.res index 6f22d9c98..2d009b289 100644 --- a/src/common/BlogApi.res +++ b/src/common/BlogApi.res @@ -25,7 +25,7 @@ module GrayMatter = { type output = { - data: Js.Json.t, + data: JSON.t, content: string, } @@ -39,22 +39,22 @@ type post = { } let blogPathToSlug = path => { - path->Js.String2.replaceByRe(%re(`/^(archive\/)?\d\d\d\d-\d\d-\d\d-(.+)\.mdx$/`), "$2") + path->String.replaceRegExp(%re(`/^(archive\/)?\d\d\d\d-\d\d-\d\d-(.+)\.mdx$/`), "$2") } let mdxFiles = dir => { - Node.Fs.readdirSync(dir)->Js.Array2.filter(path => Node.Path.extname(path) === ".mdx") + Node.Fs.readdirSync(dir)->Array.filter(path => Node.Path.extname(path) === ".mdx") } let getAllPosts = () => { let postsDirectory = Node.Path.join2(Node.Process.cwd(), "_blogposts") let archivedPostsDirectory = Node.Path.join2(postsDirectory, "archive") - let nonArchivedPosts = mdxFiles(postsDirectory)->Js.Array2.map(path => { + let nonArchivedPosts = mdxFiles(postsDirectory)->Array.map(path => { let {GrayMatter.data: data} = Node.Path.join2(postsDirectory, path)->Node.Fs.readFileSync->GrayMatter.matter switch BlogFrontmatter.decode(data) { - | Error(msg) => Js.Exn.raiseError(msg) + | Error(msg) => Exn.raiseError(msg) | Ok(d) => { path, frontmatter: d, @@ -63,11 +63,11 @@ let getAllPosts = () => { } }) - let archivedPosts = mdxFiles(archivedPostsDirectory)->Js.Array2.map(path => { + let archivedPosts = mdxFiles(archivedPostsDirectory)->Array.map(path => { let {GrayMatter.data: data} = Node.Path.join2(archivedPostsDirectory, path)->Node.Fs.readFileSync->GrayMatter.matter switch BlogFrontmatter.decode(data) { - | Error(msg) => Js.Exn.raiseError(msg) + | Error(msg) => Exn.raiseError(msg) | Ok(d) => { path: Node.Path.join2("archive", path), frontmatter: d, @@ -84,11 +84,11 @@ let getAllPosts = () => { let getLivePosts = () => { let postsDirectory = Node.Path.join2(Node.Process.cwd(), "_blogposts") - let livePosts = mdxFiles(postsDirectory)->Js.Array2.map(path => { + let livePosts = mdxFiles(postsDirectory)->Array.map(path => { let {GrayMatter.data: data} = Node.Path.join2(postsDirectory, path)->Node.Fs.readFileSync->GrayMatter.matter switch BlogFrontmatter.decode(data) { - | Error(msg) => Js.Exn.raiseError(msg) + | Error(msg) => Exn.raiseError(msg) | Ok(d) => { path, frontmatter: d, @@ -106,11 +106,11 @@ let getArchivedPosts = () => { let postsDirectory = Node.Path.join2(Node.Process.cwd(), "_blogposts") let archivedPostsDirectory = Node.Path.join2(postsDirectory, "archive") - let archivedPosts = mdxFiles(archivedPostsDirectory)->Js.Array2.map(path => { + let archivedPosts = mdxFiles(archivedPostsDirectory)->Array.map(path => { let {GrayMatter.data: data} = Node.Path.join2(archivedPostsDirectory, path)->Node.Fs.readFileSync->GrayMatter.matter switch BlogFrontmatter.decode(data) { - | Error(msg) => Js.Exn.raiseError(msg) + | Error(msg) => Exn.raiseError(msg) | Ok(d) => { path: Node.Path.join2("archive", path), frontmatter: d, @@ -140,7 +140,7 @@ module RssFeed = { title: string, href: string, description: string, - pubDate: Js.Date.t, + pubDate: Date.t, } // TODO: This is yet again a dirty approach to prevent UTC to substract too many @@ -148,8 +148,8 @@ module RssFeed = { // to 15 o clock. We need to reconsider the way we parse blog article dates, // since the dates should always be parsed from a single timezone perspective let dateToUTCString = date => { - date->Js.Date.setHours(15.0)->ignore - date->Js.Date.toUTCString + date->Date.setHours(15)->ignore + date->Date.toUTCString } // Retrieves the most recent [max] blog post feed items @@ -158,7 +158,7 @@ module RssFeed = { getAllPosts() ->Array.map(post => { let fm = post.frontmatter - let description = Js.Null.toOption(fm.description)->Belt.Option.getWithDefault("") + let description = Null.toOption(fm.description)->Option.getOr("") { title: fm.title, href: baseUrl ++ "/blog/" ++ blogPathToSlug(post.path), @@ -172,16 +172,16 @@ module RssFeed = { let toXmlString = (~siteTitle="ReScript Blog", ~siteDescription="", items: array<item>) => { let latestPubDateElement = - Belt.Array.get(items, 0) - ->Belt.Option.map(item => { + items[0] + ->Option.map(item => { let latestPubDateStr = item.pubDate->dateToUTCString `<lastBuildDate>${latestPubDateStr}</lastBuildDate>` }) - ->Belt.Option.getWithDefault("") + ->Option.getOr("") let itemsStr = items - ->Js.Array2.map(({title, pubDate, description, href}) => { + ->Array.map(({title, pubDate, description, href}) => { let descriptionElement = switch description { | "" => "" | desc => @@ -201,7 +201,7 @@ module RssFeed = { <pubDate>${dateStr}</pubDate> </item>` }) - ->Js.Array2.joinWith("\n") + ->Array.join("\n") let ret = `<?xml version="1.0" encoding="utf-8" ?> <rss version="2.0"> diff --git a/src/common/BlogApi.resi b/src/common/BlogApi.resi index 02482047f..3c47faadc 100644 --- a/src/common/BlogApi.resi +++ b/src/common/BlogApi.resi @@ -14,7 +14,7 @@ module RssFeed: { title: string, href: string, description: string, - pubDate: Js.Date.t, + pubDate: Date.t, } let getLatest: (~max: int=?, ~baseUrl: string=?, unit) => array<item> let toXmlString: (~siteTitle: string=?, ~siteDescription: string=?, array<item>) => string diff --git a/src/common/BlogFrontmatter.res b/src/common/BlogFrontmatter.res index af28d94ef..cd40a7064 100644 --- a/src/common/BlogFrontmatter.res +++ b/src/common/BlogFrontmatter.res @@ -85,15 +85,15 @@ type t = { author: author, co_authors: array<author>, date: DateStr.t, - previewImg: Js.null<string>, - articleImg: Js.null<string>, + previewImg: Null.t<string>, + articleImg: Null.t<string>, title: string, - badge: Js.null<Badge.t>, - description: Js.null<string>, + badge: Null.t<Badge.t>, + description: Null.t<string>, } let decodeBadge = (str: string): Badge.t => - switch Js.String2.toLowerCase(str) { + switch String.toLowerCase(str) { | "release" => Release | "testing" => Testing | "preview" => Preview @@ -104,7 +104,7 @@ let decodeBadge = (str: string): Badge.t => exception AuthorNotFound(string) let decodeAuthor = (~fieldName: string, ~authors, username) => - switch Js.Array2.find(authors, a => a.username === username) { + switch Array.find(authors, a => a.username === username) { | Some(author) => author | None => raise(AuthorNotFound(`Couldn't find author "${username}" in field ${fieldName}`)) } @@ -112,24 +112,24 @@ let decodeAuthor = (~fieldName: string, ~authors, username) => let authorDecoder = (~fieldName: string, ~authors) => { open Json.Decode - let multiple = j => array(string, j)->Belt.Array.map(a => decodeAuthor(~fieldName, ~authors, a)) + let multiple = j => array(string, j)->Array.map(a => decodeAuthor(~fieldName, ~authors, a)) let single = j => [string(j)->decodeAuthor(~fieldName, ~authors)] either(single, multiple) } -let decode = (json: Js.Json.t): result<t, string> => { +let decode = (json: JSON.t): result<t, string> => { open Json.Decode switch { author: json->field("author", string, _)->decodeAuthor(~fieldName="author", ~authors), co_authors: json ->optional(field("co-authors", authorDecoder(~fieldName="co-authors", ~authors), ...), _) - ->Belt.Option.getWithDefault([]), + ->Option.getOr([]), date: json->field("date", string, _)->DateStr.fromString, - badge: json->optional(j => field("badge", string, j)->decodeBadge, _)->Js.Null.fromOption, - previewImg: json->optional(field("previewImg", string, ...), _)->Js.Null.fromOption, - articleImg: json->optional(field("articleImg", string, ...), _)->Js.Null.fromOption, + badge: json->optional(j => field("badge", string, j)->decodeBadge, _)->Null.fromOption, + previewImg: json->optional(field("previewImg", string, ...), _)->Null.fromOption, + articleImg: json->optional(field("articleImg", string, ...), _)->Null.fromOption, title: json->(field("title", string, _)), description: json->(nullable(field("description", string, ...), _)), } { diff --git a/src/common/CompilerManagerHook.res b/src/common/CompilerManagerHook.res index 1f850f732..2e0f7f488 100644 --- a/src/common/CompilerManagerHook.res +++ b/src/common/CompilerManagerHook.res @@ -24,7 +24,7 @@ module LoadScript = { external removeScript: (~src: string) => unit = "removeScript" let loadScriptPromise = (url: string) => { - Js.Promise2.make((~resolve, ~reject as _) => { + Promise.make((resolve, _) => { loadScript( ~src=url, ~onSuccess=() => resolve(Ok()), @@ -45,11 +45,11 @@ module Semver = { */ let parse = (versionStr: string) => { let parsePreRelease = str => { - switch str->Js.String2.split("-") { + switch str->String.split("-") { | [_, identifier] => - switch identifier->Js.String2.split(".") { + switch identifier->String.split(".") { | [name, number] => - switch Belt.Int.fromString(number) { + switch Int.fromString(number) { | None => None | Some(buildIdentifier) => switch name { @@ -67,15 +67,14 @@ module Semver = { } // Some version contain a suffix. Example: v11.0.0-alpha.5, v11.0.0-beta.1 - let isPrerelease = versionStr->Js.String2.search(%re("/-/")) != -1 + let isPrerelease = versionStr->String.search(%re("/-/")) != -1 // Get the first part i.e vX.Y.Z - let versionNumber = - versionStr->Js.String2.split("-")->Belt.Array.get(0)->Belt.Option.getWithDefault(versionStr) + let versionNumber = versionStr->String.split("-")->Array.get(0)->Option.getOr(versionStr) - switch versionNumber->Js.String2.replace("v", "")->Js.String2.split(".") { + switch versionNumber->String.replace("v", "")->String.split(".") { | [major, minor, patch] => - switch (major->Belt.Int.fromString, minor->Belt.Int.fromString, patch->Belt.Int.fromString) { + switch (major->Int.fromString, minor->Int.fromString, patch->Int.fromString) { | (Some(major), Some(minor), Some(patch)) => let preReleaseIdentifier = if isPrerelease { parsePreRelease(versionStr) @@ -90,16 +89,16 @@ module Semver = { } let toString = ({major, minor, patch, preRelease}) => { - let mainVersion = `v${major->Belt.Int.toString}.${minor->Belt.Int.toString}.${patch->Belt.Int.toString}` + let mainVersion = `v${major->Int.toString}.${minor->Int.toString}.${patch->Int.toString}` switch preRelease { | None => mainVersion | Some(identifier) => let identifier = switch identifier { - | Dev(number) => `dev.${number->Belt.Int.toString}` - | Alpha(number) => `alpha.${number->Belt.Int.toString}` - | Beta(number) => `beta.${number->Belt.Int.toString}` - | Rc(number) => `rc.${number->Belt.Int.toString}` + | Dev(number) => `dev.${number->Int.toString}` + | Alpha(number) => `alpha.${number->Int.toString}` + | Beta(number) => `beta.${number->Int.toString}` + | Rc(number) => `rc.${number->Int.toString}` } `${mainVersion}-${identifier}` @@ -138,8 +137,8 @@ let getLibrariesForVersion = (~version: Semver.t): array<string> => { // Since version 11, we ship the compiler-builtins as a separate file, and // we also added @rescript/core as a pre-vendored package if version.major >= 11 { - libraries->Js.Array2.push("@rescript/core")->ignore - libraries->Js.Array2.push("compiler-builtins")->ignore + libraries->Array.push("@rescript/core")->ignore + libraries->Array.push("compiler-builtins")->ignore } libraries @@ -148,7 +147,7 @@ let getLibrariesForVersion = (~version: Semver.t): array<string> => { let getOpenModules = (~apiVersion: Version.t, ~libraries: array<string>): option<array<string>> => switch apiVersion { | V1 | V2 | V3 | UnknownVersion(_) => None - | V4 => libraries->Belt.Array.some(el => el === "@rescript/core") ? Some(["RescriptCore"]) : None + | V4 => libraries->Array.some(el => el === "@rescript/core") ? Some(["RescriptCore"]) : None } /* @@ -176,7 +175,7 @@ let attachCompilerAndLibraries = async (~version, ~libraries: array<string>, ()) switch await LoadScript.loadScriptPromise(compilerUrl) { | Error(_) => Error([`Could not load compiler from url ${compilerUrl}`]) | Ok(_) => - let promises = Belt.Array.map(libraries, async lib => { + let promises = Array.map(libraries, async lib => { let cmijUrl = CdnMeta.getLibraryCmijUrl(version, lib) switch await LoadScript.loadScriptPromise(cmijUrl) { | Error(_) => Error(`Could not load cmij from url ${cmijUrl}`) @@ -184,9 +183,9 @@ let attachCompilerAndLibraries = async (~version, ~libraries: array<string>, ()) } }) - let all = await Js.Promise2.all(promises) + let all = await Promise.all(promises) - let errors = Belt.Array.keepMap(all, r => { + let errors = Array.filterMap(all, r => { switch r { | Error(msg) => Some(msg) | _ => None @@ -259,7 +258,7 @@ let useCompilerManager = ( // Dispatch method for the public interface let dispatch = (action: action): unit => { - Belt.Option.forEach(onAction, cb => cb(action)) + Option.forEach(onAction, cb => cb(action)) switch action { | SwitchToCompiler(id) => switch state { @@ -295,7 +294,7 @@ let useCompilerManager = ( let currentLang = ready.targetLang - Js.Array2.find(availableTargetLangs, l => l === lang)->Belt.Option.forEach(lang => { + Array.find(availableTargetLangs, l => l === lang)->Option.forEach(lang => { // Try to automatically transform code let (result, targetLang) = switch ready.selected.apiVersion { | V1 => @@ -382,7 +381,7 @@ let useCompilerManager = ( | CompilerLoadingError(msg) => msg } switch prev { - | Ready(ready) => Ready({...ready, errors: Js.Array2.concat(ready.errors, [msg])}) + | Ready(ready) => Ready({...ready, errors: Array.concat(ready.errors, [msg])}) | _ => SetupFailed(msg) } }) @@ -429,8 +428,8 @@ let useCompilerManager = ( let targetLang = Version.availableLanguages(apiVersion) - ->Js.Array2.find(l => l === initialLang) - ->Belt.Option.getWithDefault(Version.defaultTargetLang) + ->Array.find(l => l === initialLang) + ->Option.getOr(Version.defaultTargetLang) setState(_ => Ready({ code: "", @@ -441,7 +440,7 @@ let useCompilerManager = ( result: FinalResult.Nothing, })) | Error(errs) => - let msg = Js.Array2.joinWith(errs, "; ") + let msg = Array.join(errs, "; ") dispatchError(CompilerLoadingError(msg)) } @@ -457,7 +456,7 @@ let useCompilerManager = ( LoadScript.removeScript(~src=CdnMeta.getCompilerUrl(ready.selected.id)) // We are removing the previous libraries, therefore we use ready.selected here - Belt.Array.forEach(ready.selected.libraries, lib => + Array.forEach(ready.selected.libraries, lib => LoadScript.removeScript(~src=CdnMeta.getLibraryCmijUrl(ready.selected.id, lib)) ) @@ -487,7 +486,7 @@ let useCompilerManager = ( result: FinalResult.Nothing, })) | Error(errs) => - let msg = Js.Array2.joinWith(errs, "; ") + let msg = Array.join(errs, "; ") dispatchError(CompilerLoadingError(msg)) } diff --git a/src/common/DateStr.res b/src/common/DateStr.res index 93415e99f..5fc0207a6 100644 --- a/src/common/DateStr.res +++ b/src/common/DateStr.res @@ -1,10 +1,10 @@ type t = string // Used to prevent issues with webkit based date representations -let parse = (dateStr: string): Js.Date.t => - dateStr->Js.String2.replaceByRe(%re("/-/g"), "/")->Js.Date.fromString +let parse = (dateStr: string): Date.t => + dateStr->String.replaceRegExp(%re("/-/g"), "/")->Date.fromString -let fromDate = date => Js.Date.toString(date) +let fromDate = date => Date.toString(date) let toDate = dateStr => parse(dateStr) external fromString: string => t = "%identity" diff --git a/src/common/DateStr.resi b/src/common/DateStr.resi index cd2284a4a..80dfc9407 100644 --- a/src/common/DateStr.resi +++ b/src/common/DateStr.resi @@ -3,5 +3,5 @@ type t external fromString: string => t = "%identity" -let fromDate: Js.Date.t => t -let toDate: t => Js.Date.t +let fromDate: Date.t => t +let toDate: t => Date.t diff --git a/src/common/DocFrontmatter.res b/src/common/DocFrontmatter.res index 17909cd4d..2ffb76728 100644 --- a/src/common/DocFrontmatter.res +++ b/src/common/DocFrontmatter.res @@ -1,17 +1,17 @@ type t = { title: string, - metaTitle: Js.null<string>, - description: Js.null<string>, - canonical: Js.null<string>, + metaTitle: Null.t<string>, + description: Null.t<string>, + canonical: Null.t<string>, } let decode = json => { open! Json.Decode try Some({ title: field("title", string, json), - metaTitle: optional(field("metaTitle", string, ...), json)->Js.Null.fromOption, - description: optional(field("description", string, ...), json)->Js.Null.fromOption, - canonical: optional(field("canonical", string, ...), json)->Js.Null.fromOption, + metaTitle: optional(field("metaTitle", string, ...), json)->Null.fromOption, + description: optional(field("description", string, ...), json)->Null.fromOption, + canonical: optional(field("canonical", string, ...), json)->Null.fromOption, }) catch { | DecodeError(_errMsg) => None } diff --git a/src/common/DocFrontmatter.resi b/src/common/DocFrontmatter.resi index e2de6655b..520d4851d 100644 --- a/src/common/DocFrontmatter.resi +++ b/src/common/DocFrontmatter.resi @@ -1,8 +1,8 @@ type t = { title: string, - metaTitle: Js.null<string>, // If there's no metaTitle, we will take title instead - description: Js.null<string>, - canonical: Js.null<string>, + metaTitle: Null.t<string>, // If there's no metaTitle, we will take title instead + description: Null.t<string>, + canonical: Null.t<string>, } -let decode: Js.Json.t => option<t> +let decode: JSON.t => option<t> diff --git a/src/common/EvalIFrame.res b/src/common/EvalIFrame.res index 826b9d5e1..5ba690705 100644 --- a/src/common/EvalIFrame.res +++ b/src/common/EvalIFrame.res @@ -44,7 +44,7 @@ let sendOutput = code => { let frame = Document.document ->Element.getElementById("iframe-eval") - ->Js.Nullable.toOption + ->Nullable.toOption switch frame { | Some(element) => diff --git a/src/common/HighlightJs.res b/src/common/HighlightJs.res index 5ad29453e..f4004174a 100644 --- a/src/common/HighlightJs.res +++ b/src/common/HighlightJs.res @@ -10,21 +10,21 @@ let renderHLJS = (~highlightedLines=[], ~darkmode=false, ~code: string, ~lang: s // If the language couldn't be parsed, we will fall back to text let options = {language: lang} let (lang, highlighted) = try (lang, highlight(~code, ~options)->valueGet) catch { - | Js.Exn.Error(_) => ("text", code) + | Exn.Error(_) => ("text", code) } // Add line highlighting as well - let highlighted = if Belt.Array.length(highlightedLines) > 0 { - Js.String2.split(highlighted, "\n") - ->Belt.Array.mapWithIndex((i, line) => - if Js.Array2.find(highlightedLines, lnum => lnum === i + 1) !== None { + let highlighted = if Array.length(highlightedLines) > 0 { + String.split(highlighted, "\n") + ->Array.mapWithIndex((line, i) => + if Array.find(highlightedLines, lnum => lnum === i + 1) !== None { let content = line === "" ? " " : line "<span class=\"inline-block\">" ++ (content ++ "</span>") } else { "<span class=\"inline-block text-inherit opacity-50\">" ++ (line ++ "</span>") } ) - ->Js.Array2.joinWith("\n") + ->Array.join("\n") } else { highlighted } diff --git a/src/common/Mdx.res b/src/common/Mdx.res index 464047197..fe94b1a5c 100644 --- a/src/common/Mdx.res +++ b/src/common/Mdx.res @@ -42,9 +42,9 @@ module MdxChildren = { let classify = (v: t): case => if %raw(`function (a) { return a instanceof Array}`)(v) { Array((Obj.magic(v): array<mdxComponent>)) - } else if Js.typeof(v) == "string" { + } else if typeof(v) == #string { String((Obj.magic(v): string)) - } else if Js.typeof(v) == "object" { + } else if typeof(v) == #object { Element((Obj.magic(v): mdxComponent)) } else { Unknown((Obj.magic(v): unknown)) diff --git a/src/common/Url.res b/src/common/Url.res index 722017bb7..dfa46b0ed 100644 --- a/src/common/Url.res +++ b/src/common/Url.res @@ -55,9 +55,9 @@ let prettyString = (str: string) => { } let parse = (route: string): t => { - let fullpath = route->Js.String2.split("/")->Belt.Array.keep(s => s !== "") - let foundVersionIndex = Js.Array2.findIndex(fullpath, chunk => { - Js.Re.test_(%re(`/latest|v\d+(\.\d+)?(\.\d+)?/`), chunk) + let fullpath = route->String.split("/")->Array.filter(s => s !== "") + let foundVersionIndex = Array.findIndex(fullpath, chunk => { + Re.test(%re(`/latest|v\d+(\.\d+)?(\.\d+)?/`), chunk) }) let (version, base, pagepath) = if foundVersionIndex == -1 { @@ -70,8 +70,8 @@ let parse = (route: string): t => { } ( version, - fullpath->Js.Array2.slice(~start=0, ~end_=foundVersionIndex), - fullpath->Js.Array2.slice(~start=foundVersionIndex + 1, ~end_=Js.Array2.length(fullpath)), + fullpath->Array.slice(~start=0, ~end=foundVersionIndex), + fullpath->Array.slice(~start=foundVersionIndex + 1, ~end=Array.length(fullpath)), ) } diff --git a/src/common/Util.res b/src/common/Util.res index b0c19da69..a225261e0 100644 --- a/src/common/Util.res +++ b/src/common/Util.res @@ -53,11 +53,6 @@ module String = { }") } -module Json = { - @val @scope("JSON") - external prettyStringify: (Js.Json.t, @as(json`null`) _, @as(4) _) => string = "stringify" -} - module Url = { let isAbsolute: string => bool = %raw(` function(str) { @@ -78,9 +73,9 @@ module Date = { external dateTimeFormat: (string, {"month": string, "day": string, "year": string}) => intl = "DateTimeFormat" - @send external format: (intl, Js.Date.t) => string = "format" + @send external format: (intl, Date.t) => string = "format" - let toDayMonthYear = (date: Js.Date.t) => { + let toDayMonthYear = (date: Date.t) => { dateTimeFormat("en-US", {"month": "short", "day": "numeric", "year": "numeric"})->format(date) } } diff --git a/src/common/Util.resi b/src/common/Util.resi index b1d2d4647..1ac5ccdfd 100644 --- a/src/common/Util.resi +++ b/src/common/Util.resi @@ -12,9 +12,5 @@ module String: { } module Date: { - let toDayMonthYear: Js.Date.t => string -} - -module Json: { - let prettyStringify: Js.Json.t => string + let toDayMonthYear: Date.t => string } diff --git a/src/common/WarningFlagDescription.res b/src/common/WarningFlagDescription.res index dd818eba5..b7890d6a3 100644 --- a/src/common/WarningFlagDescription.res +++ b/src/common/WarningFlagDescription.res @@ -73,7 +73,7 @@ let numeric = [ (110, "Todo found"), ] -let letterAll = numeric->Belt.Array.map(fst) +let letterAll = numeric->Array.map(fst) // we keep the original variable name `letter` like in warnings.ml let _letter = l => @@ -110,18 +110,18 @@ let _letter = l => let letterDescriptions = [("a", "All flags")] let getDescription = (num: int): option<string> => - numeric->Js.Array2.find(((n, _)) => num === n)->Belt.Option.map(((_, desc)) => desc) + numeric->Array.find(((n, _)) => num === n)->Option.map(((_, desc)) => desc) // returns all possible key / description pairs let lookupAll = (): array<(string, string)> => { - let nums = numeric->Belt.Array.map(((num, desc)) => (Belt.Int.toString(num), desc)) + let nums = numeric->Array.map(((num, desc)) => (Int.toString(num), desc)) - Belt.Array.concat(letterDescriptions, nums) + Array.concat(letterDescriptions, nums) } // str: a...z or a string number, returns (numStr, description) let lookup = (str: string): array<(string, string)> => - switch Belt.Int.fromString(str) { + switch Int.fromString(str) { | Some(num) => switch getDescription(num) { | Some(description) => [(str, description)] @@ -140,20 +140,20 @@ let lookup = (str: string): array<(string, string)> => /* | None => acc */ /* } */ /* }); */ - let search = str->Js.String2.toLowerCase - Belt.Array.keep(letterDescriptions, ((l, _)) => l === search) + let search = str->String.toLowerCase + Array.filter(letterDescriptions, ((l, _)) => l === search) } // matches all numbers that start with str let fuzzyLookup = (str: string): array<(string, string)> => { - let letters = Belt.Array.keep(letterDescriptions, ((l, _)) => l->Js.String2.startsWith(str)) + let letters = Array.filter(letterDescriptions, ((l, _)) => l->String.startsWith(str)) let numbers = numeric - ->Belt.Array.keep(((n, _)) => Belt.Int.toString(n)->Js.String2.startsWith(str)) - ->Belt.Array.map(((n, desc)) => (Belt.Int.toString(n), desc)) + ->Array.filter(((n, _)) => Int.toString(n)->String.startsWith(str)) + ->Array.map(((n, desc)) => (Int.toString(n), desc)) - Belt.Array.concat(letters, numbers) + Array.concat(letters, numbers) } module Parser = { @@ -176,20 +176,20 @@ module Parser = { let pos = ref(0) let state = ref(ParseModifier) - let last = Js.String2.length(input) - 1 + let last = String.length(input) - 1 while pos.contents <= last { - let cur = Js.String2.get(input, pos.contents) + let cur = String.get(input, pos.contents)->Option.getUnsafe let newState = switch state.contents { | ParseModifier => if cur === "+" || cur === "-" { ParseFlag({modifier: cur, acc: ""}) } else { - raise(InvalidInput("Expected '+' or '-' on pos " ++ Belt.Int.toString(pos.contents))) + raise(InvalidInput("Expected '+' or '-' on pos " ++ Int.toString(pos.contents))) } | ParseFlag({modifier, acc}) => let next = if pos.contents + 1 < last { - Js.String2.get(input, pos.contents + 1) + String.get(input, pos.contents + 1)->Option.getUnsafe } else { cur } @@ -197,12 +197,12 @@ module Parser = { if cur->isModifier { raise( InvalidInput( - "'+' and '-' not allowed in flag name on pos " ++ Belt.Int.toString(pos.contents), + "'+' and '-' not allowed in flag name on pos " ++ Int.toString(pos.contents), ), ) } else if next === "+" || (next === "-" || pos.contents >= last) { let token = {enabled: modifier === "+", flag: acc ++ cur} - Js.Array2.push(ret, token)->ignore + Array.push(ret, token)->ignore ParseModifier } else { ParseFlag({modifier, acc: acc ++ cur}) @@ -219,17 +219,15 @@ module Parser = { | ParseFlag({modifier, acc: ""}) => raise( InvalidInput( - "Expected flag name after '" ++ - (modifier ++ - ("' on pos " ++ Belt.Int.toString(pos.contents))), + "Expected flag name after '" ++ (modifier ++ ("' on pos " ++ Int.toString(pos.contents))), ), ) | _ => () } ret->Belt.SortArray.stableSortBy((v1, v2) => { - let a = v1.flag->Belt.Int.fromString - let b = v2.flag->Belt.Int.fromString + let a = v1.flag->Int.fromString + let b = v2.flag->Int.fromString compare(a, b) }) @@ -242,18 +240,18 @@ module Parser = { /* // other will override flags within base */ let merge = (base: array<token>, other: array<token>) => { - let dict = Js.Array2.copy(base)->Belt.Array.map(token => (token.flag, token))->Js.Dict.fromArray + let dict = Array.copy(base)->Array.map(token => (token.flag, token))->Dict.fromArray - Belt.Array.forEach(other, token => dict->Js.Dict.set(token.flag, token)) + Array.forEach(other, token => dict->Dict.set(token.flag, token)) - Js.Dict.values(dict)->Js.Array2.sortInPlaceWith((t1, t2) => { - open Js.Float + Dict.valuesToArray(dict)->Belt.SortArray.stableSortBy((t1, t2) => { + open Float let f1 = t1.flag let f2 = t2.flag - switch (f1->fromString->isNaN, f2->fromString->isNaN) { + switch (f1->fromString->Option.isNone, f2->fromString->Option.isNone) { | (false, false) | (true, true) => - Js.String2.localeCompare(f1, f2)->Belt.Float.toInt + String.localeCompare(f1, f2)->Float.toInt | (true, false) => -1 | (false, true) => 1 } @@ -263,10 +261,10 @@ module Parser = { // Creates a compiler compatible warning flag string let tokensToString = tokens => { tokens - ->Js.Array2.map(token => { + ->Array.map(token => { let modifier = token.enabled ? "+" : "-" modifier ++ token.flag }) - ->Js.Array2.joinWith("") + ->Array.join("") } } diff --git a/src/common/XmlHttpRequest.res b/src/common/XmlHttpRequest.res index 18f3a67e2..9025f9281 100644 --- a/src/common/XmlHttpRequest.res +++ b/src/common/XmlHttpRequest.res @@ -118,17 +118,17 @@ let decodeReadyState = x => let readyState = (xhr: t) => decodeReadyState(readyStateNum(xhr)) @get -external responseArrayBuffer: t => Js.Nullable.t<Js.Typed_array.array_buffer> = "response" +external responseArrayBuffer: t => Nullable.t<ArrayBuffer.t> = "response" // Response property with different encodings @get -external responseDocument: t => Js.Nullable.t<Dom.document> = "response" -@get external responseJson: t => Js.Nullable.t<Js.Json.t> = "response" -@get external responseText: t => Js.Nullable.t<string> = "responseText" +external responseDocument: t => Nullable.t<Dom.document> = "response" +@get external responseJson: t => Nullable.t<JSON.t> = "response" +@get external responseText: t => Nullable.t<string> = "responseText" @get external responseType: t => string = "responseType" -@get external responseUrl: t => Js.Nullable.t<string> = "responseUrl" +@get external responseUrl: t => Nullable.t<string> = "responseUrl" @get -external responseXml: t => Js.Nullable.t<Dom.xmlDocument> = "responseXml" +external responseXml: t => Nullable.t<Dom.xmlDocument> = "responseXml" @set external setResponseType: ( @@ -153,10 +153,10 @@ external setResponseType: ( @send external abort: t => unit = "abort" @send -external getAllResponseHeaders: t => Js.Nullable.t<string> = "getAllResponseHeaders" +external getAllResponseHeaders: t => Nullable.t<string> = "getAllResponseHeaders" @send -external getResponseHeader: (t, string) => Js.Nullable.t<string> = "getResponseHeader" +external getResponseHeader: (t, string) => Nullable.t<string> = "getResponseHeader" @send external open_: (t, ~method: string, ~url: string) => unit = "open" @@ -165,7 +165,7 @@ external getResponseHeader: (t, string) => Js.Nullable.t<string> = "getResponseH @send external send: t => unit = "send" @send -external sendArrayBuffer: (t, Js.Typed_array.array_buffer) => unit = "send" +external sendArrayBuffer: (t, ArrayBuffer.t) => unit = "send" @send external sendDocument: (t, Dom.document) => unit = "send" diff --git a/src/components/AnsiPre.res b/src/components/AnsiPre.res index 65a451dea..c599ce003 100644 --- a/src/components/AnsiPre.res +++ b/src/components/AnsiPre.res @@ -49,8 +49,8 @@ let make = (~className=?, ~children: string) => { let spans = Ansi.parse(children) ->SgrString.fromTokens - ->Belt.Array.mapWithIndex((i, str) => { - let key = Belt.Int.toString(i) + ->Array.mapWithIndex((str, i) => { + let key = Int.toString(i) renderSgrString(~key, str) }) diff --git a/src/components/CodeExample.res b/src/components/CodeExample.res index ef613f298..83d8e9cd9 100644 --- a/src/components/CodeExample.res +++ b/src/components/CodeExample.res @@ -63,7 +63,7 @@ module CopyButton = { let make = (~code) => { let (state, setState) = React.useState(_ => Init) - let buttonRef = React.useRef(Js.Nullable.null) + let buttonRef = React.useRef(Nullable.null) let onClick = evt => { ReactEvent.Mouse.preventDefault(evt) @@ -78,7 +78,7 @@ module CopyButton = { switch state { | Copied => open DomUtil - let buttonEl = Js.Nullable.toOption(buttonRef.current)->Belt.Option.getExn + let buttonEl = Nullable.toOption(buttonRef.current)->Option.getExn // Note on this imperative DOM nonsense: // For Tailwind transitions to behave correctly, we need to first paint the DOM element in the tree, @@ -98,7 +98,7 @@ module CopyButton = { bannerEl->classList->toggle("opacity-100") }) - let timeoutId = Js.Global.setTimeout(() => { + let timeoutId = setTimeout(() => { buttonEl->removeChild(bannerEl) setState(_ => Init) }, 3000) @@ -106,7 +106,7 @@ module CopyButton = { Some( () => { cancelAnimationFrame(nextFrameId) - Js.Global.clearTimeout(timeoutId) + clearTimeout(timeoutId) }, ) | _ => None @@ -131,7 +131,7 @@ let make = (~highlightedLines=[], ~code: string, ~showLabel=true, ~lang="text") <div className="absolute right-1 top-0 p-1 font-sans text-12 font-bold text-gray-30 pointer-events-none"> {//RES or JS Label - Js.String2.toUpperCase(label)->React.string} + String.toUpperCase(label)->React.string} </div> } else { React.null @@ -166,15 +166,15 @@ module Toggle = { showLabel: true, }) | multiple => - let numberOfItems = Js.Array.length(multiple) - let tabElements = Belt.Array.mapWithIndex(multiple, (i, tab) => { + let numberOfItems = Array.length(multiple) + let tabElements = Array.mapWithIndex(multiple, (tab, i) => { // if there's no label, infer the label from the language let label = switch tab.label { | Some(label) => label | None => switch tab.lang { - | Some(lang) => langShortname(lang)->Js.String2.toUpperCase - | None => Belt.Int.toString(i) + | Some(lang) => langShortname(lang)->String.toUpperCase + | None => Int.toString(i) } } @@ -188,7 +188,7 @@ module Toggle = { ReactEvent.Mouse.preventDefault(evt) setSelected(_ => i) } - let key = label ++ ("-" ++ Belt.Int.toString(i)) + let key = label ++ ("-" ++ Int.toString(i)) let paddingX = switch numberOfItems { | 1 @@ -215,12 +215,12 @@ module Toggle = { }) let children = - Belt.Array.get(multiple, selected) - ->Belt.Option.map(tab => { - let lang = Belt.Option.getWithDefault(tab.lang, "text") + multiple[selected] + ->Option.map(tab => { + let lang = Option.getOr(tab.lang, "text") HighlightJs.renderHLJS(~highlightedLines=?tab.highlightedLines, ~code=tab.code, ~lang, ()) }) - ->Belt.Option.getWithDefault(React.null) + ->Option.getOr(React.null) // On a ReScript tab, always copy or open the ReScript code. Otherwise, copy the current selected code. let isReScript = tab => @@ -229,7 +229,7 @@ module Toggle = { | _ => false } - let buttonDiv = switch Js.Array2.findi(multiple, (tab, index) => + let buttonDiv = switch Array.findWithIndex(multiple, (tab, index) => tab->isReScript || index === selected ) { | Some({code: ""}) => React.null diff --git a/src/components/CodeMirror.res b/src/components/CodeMirror.res index 4239203e3..b0a327432 100644 --- a/src/components/CodeMirror.res +++ b/src/components/CodeMirror.res @@ -257,7 +257,7 @@ module HoverTooltip = { el: Dom.element, marker: CM.TextMarker.t, hoverHint: HoverHint.t, - hideTimer: option<Js.Global.timeoutId>, + hideTimer: option<timeoutId>, }) let make: unit => t = %raw(` @@ -351,7 +351,7 @@ let useHoverTooltip = (~cmStateRef: React.ref<state>, ~cmRef: React.ref<option<C let col = coords["ch"] let line = coords["line"] + 1 - let found = hoverHints->Js.Array2.find(item => { + let found = hoverHints->Array.find(item => { let {start, end} = item line >= start.line && line <= end.line && col >= start.col && col <= end.col }) @@ -380,7 +380,7 @@ let useHoverTooltip = (~cmStateRef: React.ref<state>, ~cmRef: React.ref<option<C }) | Shown({el, marker: prevMarker, hideTimer}) => switch hideTimer { - | Some(timerId) => Js.Global.clearTimeout(timerId) + | Some(timerId) => clearTimeout(timerId) | None => () } CM.TextMarker.clear(prevMarker) @@ -405,12 +405,12 @@ let useHoverTooltip = (~cmStateRef: React.ref<state>, ~cmRef: React.ref<option<C switch stateRef.current { | Shown({el, hoverHint, marker, hideTimer}) => switch hideTimer { - | Some(timerId) => Js.Global.clearTimeout(timerId) + | Some(timerId) => clearTimeout(timerId) | None => () } marker->CM.TextMarker.clear - let timerId = Js.Global.setTimeout(() => { + let timerId = setTimeout(() => { stateRef.current = Hidden tooltip->HoverTooltip.hide }, 200) @@ -453,7 +453,7 @@ module GutterMarker = { } let (row, col) = rowCol - marker->setId(`gutter-marker_${row->Belt.Int.toString}-${col->Belt.Int.toString}`) + marker->setId(`gutter-marker_${row->Int.toString}-${col->Int.toString}`) marker->setClassName( "flex items-center justify-center text-14 text-center ml-1 h-6 font-bold hover:cursor-pointer " ++ colorClass, @@ -465,17 +465,17 @@ module GutterMarker = { } let _clearMarks = (state: state): unit => { - Belt.Array.forEach(state.marked, mark => mark->CM.TextMarker.clear) + Array.forEach(state.marked, mark => mark->CM.TextMarker.clear) state.marked = [] } let extractRowColFromId = (id: string): option<(int, int)> => - switch Js.String2.split(id, "_") { + switch String.split(id, "_") { | [_, rowColStr] => - switch Js.String2.split(rowColStr, "-") { + switch String.split(rowColStr, "-") { | [rowStr, colStr] => - let row = Belt.Int.fromString(rowStr) - let col = Belt.Int.fromString(colStr) + let row = Int.fromString(rowStr) + let col = Int.fromString(colStr) switch (row, col) { | (Some(row), Some(col)) => Some((row, col)) | _ => None @@ -492,15 +492,15 @@ module ErrorHash = Belt.Id.MakeHashableU({ }) let updateErrors = (~state: state, ~onMarkerFocus=?, ~onMarkerFocusLeave=?, ~cm: CM.t, errors) => { - Belt.Array.forEach(state.marked, mark => mark->CM.TextMarker.clear) + Array.forEach(state.marked, mark => mark->CM.TextMarker.clear) - let errorsMap = Belt.HashMap.make(~hintSize=Belt.Array.length(errors), ~id=module(ErrorHash)) + let errorsMap = Belt.HashMap.make(~hintSize=Array.length(errors), ~id=module(ErrorHash)) state.marked = [] cm->CM.clearGutter(CM.errorGutterId) let wrapper = cm->CM.getWrapperElement - Belt.Array.forEachWithIndex(errors, (idx, e) => { + Array.forEachWithIndex(errors, (e, idx) => { open DomUtil open Error @@ -530,22 +530,20 @@ let updateErrors = (~state: state, ~onMarkerFocus=?, ~onMarkerFocusLeave=?, ~cm: CM.MarkTextOption.make( ~className="border-b border-dotted hover:cursor-pointer " ++ markTextColor, ~attributes=CM.MarkTextOption.Attr.make( - ~id="text-marker_" ++ - (Belt.Int.toString(e.row) ++ - ("-" ++ (Belt.Int.toString(e.column) ++ ""))), + ~id="text-marker_" ++ (Int.toString(e.row) ++ ("-" ++ (Int.toString(e.column) ++ ""))), (), ), (), ), ) - ->Js.Array2.push(state.marked, _) + ->Array.push(state.marked, _) ->ignore () } }) let isMarkerId = id => - Js.String2.startsWith(id, "gutter-marker") || Js.String2.startsWith(id, "text-marker") + String.startsWith(id, "gutter-marker") || String.startsWith(id, "text-marker") wrapper->DomUtil.setOnMouseOver(evt => { let target = DomUtil.Event.target(evt) @@ -553,7 +551,7 @@ let updateErrors = (~state: state, ~onMarkerFocus=?, ~onMarkerFocusLeave=?, ~cm: let id = DomUtil.getId(target) if isMarkerId(id) { switch extractRowColFromId(id) { - | Some(rowCol) => Belt.Option.forEach(onMarkerFocus, cb => cb(rowCol)) + | Some(rowCol) => Option.forEach(onMarkerFocus, cb => cb(rowCol)) | None => () } } @@ -565,7 +563,7 @@ let updateErrors = (~state: state, ~onMarkerFocus=?, ~onMarkerFocusLeave=?, ~cm: let id = DomUtil.getId(target) if isMarkerId(id) { switch extractRowColFromId(id) { - | Some(rowCol) => Belt.Option.forEach(onMarkerFocusLeave, cb => cb(rowCol)) + | Some(rowCol) => Option.forEach(onMarkerFocusLeave, cb => cb(rowCol)) | None => () } } @@ -592,7 +590,7 @@ let make = // props relevant for the react wrapper ~scrollbarStyle="native", ~lineWrapping=false, ): React.element => { - let inputElement = React.useRef(Js.Nullable.null) + let inputElement = React.useRef(Nullable.null) let cmRef: React.ref<option<CM.t>> = React.useRef(None) let cmStateRef = React.useRef({marked: [], hoverHints}) @@ -600,7 +598,7 @@ let make = // props relevant for the react wrapper let (onMouseOver, onMouseOut, onMouseMove) = useHoverTooltip(~cmStateRef, ~cmRef, ()) React.useEffect(() => - switch inputElement.current->Js.Nullable.toOption { + switch inputElement.current->Nullable.toOption { | Some(input) => let options = { CM.Options.theme: "material", @@ -614,15 +612,15 @@ let make = // props relevant for the react wrapper } let cm = CM.fromTextArea(input, options) - Belt.Option.forEach(minHeight, minHeight => + Option.forEach(minHeight, minHeight => cm->CM.getScrollerElement->DomUtil.setMinHeight(minHeight) ) - Belt.Option.forEach(maxHeight, maxHeight => + Option.forEach(maxHeight, maxHeight => cm->CM.getScrollerElement->DomUtil.setMaxHeight(maxHeight) ) - Belt.Option.forEach(onChange, onValueChange => + Option.forEach(onChange, onValueChange => cm->CM.onChange(instance => onValueChange(instance->CM.getValue)) ) @@ -638,7 +636,7 @@ let make = // props relevant for the react wrapper cmRef.current = Some(cm) let cleanup = () => { - /* Js.log2("cleanup", options->CM.Options.mode); */ + /* Console.log2("cleanup", options->CM.Options.mode); */ CM.offMouseOver(wrapper, onMouseOver) CM.offMouseOut(wrapper, onMouseOut) CM.offMouseMove(wrapper, onMouseMove) @@ -692,10 +690,10 @@ let make = // props relevant for the react wrapper so we need to make a single string that React's useEffect is able to act on for equality checks */ - let errorsFingerprint = Belt.Array.map(errors, e => { + let errorsFingerprint = Array.map(errors, e => { let {Error.row: row, column} = e - `${row->Belt.Int.toString}-${column->Belt.Int.toString}` - })->Js.Array2.joinWith(";") + `${row->Int.toString}-${column->Int.toString}` + })->Array.join(";") React.useEffect(() => { let state = cmStateRef.current @@ -710,7 +708,7 @@ let make = // props relevant for the react wrapper }, [errorsFingerprint]) React.useEffect(() => { - let cm = Belt.Option.getExn(cmRef.current) + let cm = Option.getExn(cmRef.current) cm->CM.setMode(mode) None }, [mode]) diff --git a/src/components/Docson.res b/src/components/Docson.res index 6edf9aad1..a7456d0fa 100644 --- a/src/components/Docson.res +++ b/src/components/Docson.res @@ -5,11 +5,11 @@ type t @set external setTemplateBaseUrl: (t, string) => unit = "templateBaseUrl" @module("docson") @scope("default") -external doc: (string, Js.Json.t, option<string>, string) => unit = "doc" +external doc: (string, JSON.t, option<string>, string) => unit = "doc" @react.component let make = (~tag) => { - let element = React.useRef(Js.Nullable.null) + let element = React.useRef(Nullable.null) React.useEffect(() => { let segment = `https://raw.githubusercontent.com/rescript-lang/rescript-compiler/${tag}/docs/docson/build-schema.json` @@ -18,9 +18,9 @@ let make = (~tag) => { // See: https://github.com/lbovet/docson/blob/master/src/index.js let _ = Webapi.Fetch.fetch(segment) - ->Js.Promise2.then(Webapi.Fetch.Response.json) - ->Js.Promise2.then(schema => { - let _ = switch element.current->Js.Nullable.toOption { + ->Promise.then(Webapi.Fetch.Response.json) + ->Promise.then(schema => { + let _ = switch element.current->Nullable.toOption { | Some(_el) => setTemplateBaseUrl(docson, "/static/docson") @@ -28,7 +28,7 @@ let make = (~tag) => { | None => () } - Js.Promise2.resolve() + Promise.resolve() }) None diff --git a/src/components/Footer.res b/src/components/Footer.res index 5947747f1..b75cddfde 100644 --- a/src/components/Footer.res +++ b/src/components/Footer.res @@ -14,7 +14,7 @@ module Section = { let make = () => { let linkClass = "hover:underline hover:pointer" let iconLink = "hover:pointer hover:text-gray-60-tr" - let copyrightYear = Js.Date.make()->Js.Date.getFullYear->Js.Float.toString + let copyrightYear = Date.make()->Date.getFullYear->Int.toString <footer className="flex justify-center border-t border-gray-10"> <div diff --git a/src/components/ImageGallery.res b/src/components/ImageGallery.res index 103445f8f..e649c7d82 100644 --- a/src/components/ImageGallery.res +++ b/src/components/ImageGallery.res @@ -10,10 +10,10 @@ let make = (~className="", ~imgClassName="", ~imgSrcs: array<string>, ~mode=NoAu switch mode { | NoAuto => None | AutoFadeTransition(ms) => - let timerId = Js.Global.setInterval(() => { + let timerId = setInterval(() => { setIndex( prev => { - if prev === imgSrcs->Belt.Array.length - 1 { + if prev === imgSrcs->Array.length - 1 { 0 } else { prev + 1 @@ -24,7 +24,7 @@ let make = (~className="", ~imgClassName="", ~imgSrcs: array<string>, ~mode=NoAu Some( () => { - Js.Global.clearInterval(timerId) + clearInterval(timerId) }, ) } @@ -32,7 +32,7 @@ let make = (~className="", ~imgClassName="", ~imgSrcs: array<string>, ~mode=NoAu let src = imgSrcs->Belt.Array.getExn(index) - let lineEls = imgSrcs->Belt.Array.mapWithIndex((i, src) => { + let lineEls = imgSrcs->Array.mapWithIndex((src, i) => { let bgColor = if i === index { "bg-gray-40" } else { @@ -52,7 +52,7 @@ let make = (~className="", ~imgClassName="", ~imgSrcs: array<string>, ~mode=NoAu ReactEvent.Mouse.preventDefault(evt) setIndex(prev => { - if prev === imgSrcs->Belt.Array.length - 1 { + if prev === imgSrcs->Array.length - 1 { 0 } else { prev + 1 diff --git a/src/components/Markdown.res b/src/components/Markdown.res index d23e3877a..649de3edc 100644 --- a/src/components/Markdown.res +++ b/src/components/Markdown.res @@ -23,7 +23,7 @@ module Cite = { className="my-10 border-l-2 border-fire font-normal pl-10 py-1 text-fire" style={ReactDOM.Style.make(~maxWidth="30rem", ())}> <blockquote className="text-32 italic mb-2"> children </blockquote> - {Belt.Option.mapWithDefault(author, React.null, author => + {Option.mapOr(author, React.null, author => <figcaption className="font-semibold text-14"> {React.string(author)} </figcaption> )} </div> @@ -62,7 +62,7 @@ module UrlBox = { </p> | Array(arr) => // Scenario: Take the first element, rewrap its children with the hyperlink img - let length = Belt.Array.length(arr) + let length = Array.length(arr) if length >= 1 { let head = Belt.Array.getExn(arr, 0) let headChildren = head->getMdxChildren @@ -73,7 +73,7 @@ module UrlBox = { {headChildren->toReactElement} </P> {if length > 1 { - arr->Js.Array2.slice(~start=1, ~end_=length)->Mdx.arrToReactElement + arr->Array.slice(~start=1, ~end=length)->Mdx.arrToReactElement } else { React.null }} @@ -82,7 +82,7 @@ module UrlBox = { React.null } | Unknown(el) => - Js.log2("Received unknown", el) + Console.log2("Received unknown", el) React.null } @@ -231,26 +231,26 @@ module Code = { external unknownAsString: unknown => string = "%identity" let parseNumericRangeMeta = (metastring: string) => - Js.String2.split(metastring, " ") - ->Js.Array2.find(s => Js.String2.startsWith(s, "{") && Js.String2.endsWith(s, "}")) - ->Belt.Option.map(str => { - let nums = Js.String2.replaceByRe(str, %re("/[\{\}]/g"), "")->parseNumericRange + String.split(metastring, " ") + ->Array.find(s => String.startsWith(s, "{") && String.endsWith(s, "}")) + ->Option.map(str => { + let nums = String.replaceRegExp(str, %re("/[\{\}]/g"), "")->parseNumericRange nums }) - ->Belt.Option.getWithDefault([]) + ->Option.getOr([]) let makeCodeElement = (~code, ~metastring, ~lang) => { let baseClass = "md-code font-mono w-full block mt-5 mb-5" let codeElement = switch metastring { | None => <CodeExample code lang /> | Some(metastring) => - let metaSplits = Js.String2.split(metastring, " ")->Belt.List.fromArray + let metaSplits = String.split(metastring, " ")->List.fromArray let highlightedLines = parseNumericRangeMeta(metastring) - if Belt.List.has(metaSplits, "example", \"=") { + if List.has(metaSplits, "example", \"=") { <CodeExample code lang /> - } else if Belt.List.has(metaSplits, "sig", \"=") { + } else if List.has(metaSplits, "sig", \"=") { <CodeExample code lang showLabel=false /> } else { <CodeExample highlightedLines code lang /> @@ -265,7 +265,7 @@ module Code = { let lang = switch className { | None => "text" | Some(str) => - switch Js.String2.split(str, "-") { + switch String.split(str, "-") { | ["language", ""] => "text" | ["language", lang] => lang | _ => "text" @@ -273,7 +273,7 @@ module Code = { } let code = children->unknownAsString - let isMultiline = code->Js.String2.includes("\n") + let isMultiline = code->String.includes("\n") switch lang { | "text" if !isMultiline => <InlineCode> {code->React.string} </InlineCode> @@ -297,29 +297,29 @@ module CodeTab = { | _ => [] } - let tabs = Belt.Array.reduceWithIndex(mdxElements, [], (acc, mdxElement, i) => { + let tabs = Array.reduceWithIndex(mdxElements, [], (acc, mdxElement, i) => { let child = mdxElement->Mdx.MdxChildren.getMdxChildren->Mdx.MdxChildren.classify switch child { | Element(codeEl) => - let className = Mdx.getMdxClassName(codeEl)->Belt.Option.getWithDefault("") + let className = Mdx.getMdxClassName(codeEl)->Option.getOr("") - let metastring = getMdxMetastring(codeEl)->Belt.Option.getWithDefault("") + let metastring = getMdxMetastring(codeEl)->Option.getOr("") - let lang = switch Js.String2.split(className, "-") { + let lang = switch String.split(className, "-") { | ["language", lang] => Some(lang) | _ => None } - let code = Js.String2.make(Mdx.MdxChildren.getMdxChildren(codeEl)) - let label = Belt.Array.get(labels, i) + let code = String.make(Mdx.MdxChildren.getMdxChildren(codeEl)) + let label = labels[i] let tab = { CodeExample.Toggle.lang, code, label, highlightedLines: Some(Code.parseNumericRangeMeta(metastring)), } - Js.Array2.push(acc, tab)->ignore + Array.push(acc, tab)->ignore | _ => () } @@ -375,9 +375,9 @@ module A = { // but it's very unlikely we'd refer to an absolute URL ending // with .md let regex = %re("/\.md(x)?|\.html$/") - let href = switch Js.String2.split(href, "#") { - | [pathname, anchor] => Js.String2.replaceByRe(pathname, regex, "") ++ ("#" ++ anchor) - | [pathname] => Js.String2.replaceByRe(pathname, regex, "") + let href = switch String.split(href, "#") { + | [pathname, anchor] => String.replaceRegExp(pathname, regex, "") ++ ("#" ++ anchor) + | [pathname] => String.replaceRegExp(pathname, regex, "") | _ => href } <Next.Link href className="no-underline text-fire hover:underline" ?target> @@ -417,11 +417,10 @@ module Li = { let elements: React.element = if isArray(children) { let arr = children->asArray let last: React.element = { - open Belt.Array - arr->getExn(arr->length - 1) + arr->Belt.Array.getExn(arr->Array.length - 1) } - let head = Js.Array2.slice(arr, ~start=0, ~end_=arr->Belt.Array.length - 1) + let head = Array.slice(arr, ~start=0, ~end=arr->Array.length - 1) let first = Belt.Array.getExn(head, 0) diff --git a/src/components/MarkdownComponents.res b/src/components/MarkdownComponents.res index 62a3776e9..0dd57bf0e 100644 --- a/src/components/MarkdownComponents.res +++ b/src/components/MarkdownComponents.res @@ -40,7 +40,7 @@ type t = { React.element, >, pre?: Pre.props<React.element> => React.element, - a?: A.props<Js.String2.t, string, React.element> => React.element, + a?: A.props<string, string, React.element> => React.element, } let default = { diff --git a/src/components/Meta.res b/src/components/Meta.res index e8dfcf5a4..661b31bc2 100644 --- a/src/components/Meta.res +++ b/src/components/Meta.res @@ -41,7 +41,7 @@ let make = ( content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, minimal-ui" /> <meta key="description" name="description" content=description /> - <meta key="keywords" name="keywords" content={Js.Array2.joinWith(keywords, ",")} /> + <meta key="keywords" name="keywords" content={Array.join(keywords, ",")} /> {switch canonical { | Some(href) => <link key="canonical" href rel="canonical" /> | None => React.null diff --git a/src/components/Navigation.res b/src/components/Navigation.res index 7ff8dbb48..8bda1a326 100644 --- a/src/components/Navigation.res +++ b/src/components/Navigation.res @@ -6,11 +6,11 @@ let activeLink = "font-medium text-fire-30 border-b border-fire" let linkOrActiveLink = (~target, ~route) => target === route ? activeLink : link let linkOrActiveLinkSubroute = (~target, ~route) => - Js.String2.startsWith(route, target) ? activeLink : link + String.startsWith(route, target) ? activeLink : link let linkOrActiveApiSubroute = (~route) => { let url = Url.parse(route) - switch Belt.Array.get(url.pagepath, 0) { + switch url.pagepath[0] { | Some("api") => activeLink | _ => link } @@ -219,7 +219,7 @@ module DocsSection = { <div> <ul className="space-y-2 ml-2 mt-6"> {languageManual - ->Js.Array2.map(item => { + ->Array.map(item => { let (text, href) = item let linkClass = if router.route === href { @@ -248,7 +248,7 @@ module DocsSection = { </div> <div> <div className="mt-6"> - {Js.Array2.map(documentation, item => { + {Array.map(documentation, item => { let {imgSrc, title, href, description, isActive} = item let icon = <img style={ReactDOM.Style.make(~width="2.1875rem", ())} src={imgSrc} /> @@ -324,8 +324,8 @@ module DocsSection = { | {base: ["docs", "manual"]} => let targetUrl = "/" ++ - (Js.Array2.joinWith(url.base, "/") ++ - ("/" ++ (version ++ ("/" ++ Js.Array2.joinWith(url.pagepath, "/"))))) + (Array.join(url.base, "/") ++ + ("/" ++ (version ++ ("/" ++ Array.join(url.pagepath, "/"))))) router->Next.Router.push(targetUrl) | _ => () } @@ -429,7 +429,7 @@ let make = (~fixed=true, ~isOverlayOpen: bool, ~setOverlayOpen: (bool => bool) = | {base: ["docs", "react"]} | {base: ["docs", "gentype"]} | {base: ["docs", "manual"]} => - switch Belt.Array.get(url.pagepath, 0) { + switch url.pagepath[0] { | Some("api") => false | _ => true } @@ -441,14 +441,13 @@ let make = (~fixed=true, ~isOverlayOpen: bool, ~setOverlayOpen: (bool => bool) = }, ]) - let isSubnavOpen = Js.Array2.find(collapsibles, c => c.state !== Closed) !== None + let isSubnavOpen = Array.find(collapsibles, c => c.state !== Closed) !== None let toggleOverlay = () => setOverlayOpen(prev => !prev) - let resetCollapsibles = () => - setCollapsibles(prev => Belt.Array.map(prev, c => {...c, state: Closed})) + let resetCollapsibles = () => setCollapsibles(prev => Array.map(prev, c => {...c, state: Closed})) - let navRef = React.useRef(Js.Nullable.null) + let navRef = React.useRef(Nullable.null) Hooks.useOutsideClick(ReactDOM.Ref.domRef(navRef), resetCollapsibles) /* let windowWidth = useWindowWidth() */ @@ -488,7 +487,7 @@ let make = (~fixed=true, ~isOverlayOpen: bool, ~setOverlayOpen: (bool => bool) = let onStateChange = (~id, state) => { setCollapsibles(prev => { - Belt.Array.keepMap(prev, next => { + Array.filterMap(prev, next => { if next.title === id { Some({...next, state}) } else { @@ -498,7 +497,7 @@ let make = (~fixed=true, ~isOverlayOpen: bool, ~setOverlayOpen: (bool => bool) = }) } - let collapsibleElements = Js.Array2.map(collapsibles, coll => { + let collapsibleElements = Array.map(collapsibles, coll => { <CollapsibleLink key={coll.title} title={coll.title} diff --git a/src/components/Search.res b/src/components/Search.res index 58660f7fd..6a30dbec8 100644 --- a/src/components/Search.res +++ b/src/components/Search.res @@ -26,28 +26,27 @@ external keyboardEventPreventDefault: keyboardEventLike => unit = "preventDefaul type state = Active | Inactive let hit = ({hit, children}: DocSearch.hitComponent) => { - let toTitle = str => - str->Js.String2.charAt(0)->Js.String2.toUpperCase ++ Js.String2.sliceToEnd(str, ~from=1) + let toTitle = str => str->String.charAt(0)->String.toUpperCase ++ String.sliceToEnd(str, ~start=1) let description = switch hit.url - ->Js.String2.split("/") - ->Js.Array2.sliceFrom(1) - ->Belt.List.fromArray { + ->String.split("/") + ->Array.sliceToEnd(~start=1) + ->List.fromArray { | list{"blog" as r | "community" as r, ..._} => r->toTitle | list{"docs", doc, version, ...rest} => - let path = rest->Belt.List.toArray + let path = rest->List.toArray let info = path - ->Js.Array2.slice(~start=0, ~end_=Js.Array2.length(path) - 1) - ->Js.Array2.map(path => + ->Array.slice(~start=0, ~end=Array.length(path) - 1) + ->Array.map(path => switch path { | "api" => "API" | other => toTitle(other) } ) - [doc->toTitle, version->toTitle]->Js.Array2.concat(info)->Js.Array2.joinWith(" / ") + [doc->toTitle, version->toTitle]->Array.concat(info)->Array.join(" / ") | _ => "" } @@ -60,10 +59,10 @@ let hit = ({hit, children}: DocSearch.hitComponent) => { } let transformItems = (items: DocSearch.transformItems) => { - items->Belt.Array.keepMap(item => { + items->Array.filterMap(item => { let url = try Webapi.URL.make(item.url)->Some catch { - | Js.Exn.Error(obj) => - Js.Console.error2(`Failed to parse URL ${item.url}`, obj) + | Exn.Error(obj) => + Console.error2(`Failed to parse URL ${item.url}`, obj) None } switch url { diff --git a/src/components/SearchBox.res b/src/components/SearchBox.res index 9d63a5eed..2dc0c0c65 100644 --- a/src/components/SearchBox.res +++ b/src/components/SearchBox.res @@ -18,18 +18,18 @@ let make = ( ~onValueChange: string => unit, ) => { let (state, setState) = React.useState(_ => Inactive) - let textInput = React.useRef(Js.Nullable.null) + let textInput = React.useRef(Nullable.null) let onMouseDownClear = evt => { ReactEvent.Mouse.preventDefault(evt) onClear() } - let focusInput = () => - textInput.current->Js.Nullable.toOption->Belt.Option.forEach(el => el->focus) + let focusInput = () => textInput.current->Nullable.forEach(el => el->focus) let onAreaFocus = evt => { let el = ReactEvent.Focus.target(evt) + // TODO(aspeddro): Replace with `Nullable.isNullable` when Core merge https://github.com/rescript-association/rescript-core/pull/227 and publish a new release let isDiv = Js.Null_undefined.isNullable(el["type"]) if isDiv && state === Inactive { @@ -54,7 +54,7 @@ let make = ( switch full { | "Escape" => onClear() | "Tab" => - if Js.Array.length(completionValues) === 1 { + if Array.length(completionValues) === 1 { let targetValue = Belt.Array.getExn(completionValues, 0) if targetValue !== value { diff --git a/src/components/VersionSelect.res b/src/components/VersionSelect.res index b77aaac51..a10c20bec 100644 --- a/src/components/VersionSelect.res +++ b/src/components/VersionSelect.res @@ -2,7 +2,7 @@ let make = (~onChange, ~version: string, ~availableVersions: array<(string, string)>) => { // array<(version, label)> - let children = Belt.Array.map(availableVersions, ((ver, label)) => { + let children = Array.map(availableVersions, ((ver, label)) => { <option className="py-4" key=ver value=ver> {React.string(label)} </option> }) <select diff --git a/src/components/WarningTable.res b/src/components/WarningTable.res index ccb65a2cd..1245eb9b2 100644 --- a/src/components/WarningTable.res +++ b/src/components/WarningTable.res @@ -11,7 +11,7 @@ let make = () => { </Thead> <tbody> {WarningFlagDescription.lookupAll() - ->Belt.Array.map(((number, description)) => + ->Array.map(((number, description)) => <tr key=number> <Td> {React.string(number)} </Td> <Td> {React.string(description)} </Td> diff --git a/src/layouts/ApiLayout.res b/src/layouts/ApiLayout.res index b2a0b04e8..ecbda46da 100644 --- a/src/layouts/ApiLayout.res +++ b/src/layouts/ApiLayout.res @@ -9,13 +9,11 @@ module OldDocsWarning = { let make = (~version: string, ~route: string) => { let url = Url.parse(route) let latestUrl = - "/" ++ - (Js.Array2.joinWith(url.base, "/") ++ - ("/latest/" ++ Js.Array2.joinWith(url.pagepath, "/"))) + "/" ++ (Array.join(url.base, "/") ++ ("/latest/" ++ Array.join(url.pagepath, "/"))) open Markdown - let label = switch Js.Array2.find(allApiVersions, ((v, _)) => { + let label = switch Array.find(allApiVersions, ((v, _)) => { v === version }) { | Some((_, label)) => label @@ -48,12 +46,12 @@ let makeBreadcrumbs = (~prefix: Url.breadcrumb, route: string): list<Url.breadcr let url = route->Url.parse let (_, rest) = // Strip the "api" part of the url before creating the rest of the breadcrumbs - Js.Array2.sliceFrom(url.pagepath, 1)->Belt.Array.reduce((prefix.href, []), (acc, path) => { + Array.sliceToEnd(url.pagepath, ~start=1)->Array.reduce((prefix.href, []), (acc, path) => { let (baseHref, ret) = acc let href = baseHref ++ ("/" ++ path) - Js.Array2.push( + Array.push( ret, { open Url @@ -62,7 +60,7 @@ let makeBreadcrumbs = (~prefix: Url.breadcrumb, route: string): list<Url.breadcr )->ignore (href, ret) }) - Belt.Array.concat([prefix], rest)->Belt.List.fromArray + Array.concat([prefix], rest)->List.fromArray } @react.component @@ -111,8 +109,8 @@ let make = ( let targetUrl = "/" ++ - (Js.Array2.joinWith(url.base, "/") ++ - ("/" ++ (version ++ ("/" ++ Js.Array2.joinWith(url.pagepath, "/"))))) + (Array.join(url.base, "/") ++ + ("/" ++ (version ++ ("/" ++ Array.join(url.pagepath, "/"))))) router->Next.Router.push(targetUrl) } <VersionSelect onChange version availableVersions=allApiVersions /> diff --git a/src/layouts/BeltDocsLayout10_0_0.res b/src/layouts/BeltDocsLayout10_0_0.res index 6ae65ac3e..ab1301fa9 100644 --- a/src/layouts/BeltDocsLayout10_0_0.res +++ b/src/layouts/BeltDocsLayout10_0_0.res @@ -1,6 +1,6 @@ // Structure defined by `scripts/extract-indices.js` @module("index_data/v1000_belt_api_index.json") -external indexData: Js.Dict.t<{ +external indexData: Dict.t<{ "moduleName": string, "headers": array<{ "name": string, @@ -109,17 +109,15 @@ module Docs = { // Gather data for the CollapsibleSection let headers = { - open Belt.Option - Js.Dict.get(indexData, route) - ->map(data => - data["headers"]->Belt.Array.map(header => (header["name"], "#" ++ header["href"])) - ) - ->getWithDefault([]) + open Option + Dict.get(indexData, route) + ->map(data => data["headers"]->Array.map(header => (header["name"], "#" ++ header["href"]))) + ->getOr([]) } let moduleName = { - open Belt.Option - Js.Dict.get(indexData, route)->map(data => data["moduleName"])->getWithDefault("?") + open Option + Dict.get(indexData, route)->map(data => data["moduleName"])->getOr("?") } let url = route->Url.parse @@ -141,7 +139,7 @@ module Docs = { open SidebarLayout.Toc { title: moduleName, - entries: Belt.Array.map(headers, ((name, href)) => {header: name, href}), + entries: Array.map(headers, ((name, href)) => {header: name, href}), } } diff --git a/src/layouts/BeltDocsLayout8_0_0.res b/src/layouts/BeltDocsLayout8_0_0.res index 3714dafdd..32a53b5a7 100644 --- a/src/layouts/BeltDocsLayout8_0_0.res +++ b/src/layouts/BeltDocsLayout8_0_0.res @@ -1,6 +1,6 @@ // Structure defined by `scripts/extract-indices.js` @module("index_data/v800_belt_api_index.json") -external indexData: Js.Dict.t<{ +external indexData: Dict.t<{ "moduleName": string, "headers": array<{ "name": string, @@ -136,17 +136,15 @@ module Docs = { // Gather data for the CollapsibleSection let headers = { - open Belt.Option - Js.Dict.get(indexData, route) - ->map(data => - data["headers"]->Belt.Array.map(header => (header["name"], "#" ++ header["href"])) - ) - ->getWithDefault([]) + open Option + Dict.get(indexData, route) + ->map(data => data["headers"]->Array.map(header => (header["name"], "#" ++ header["href"]))) + ->getOr([]) } let moduleName = { - open Belt.Option - Js.Dict.get(indexData, route)->map(data => data["moduleName"])->getWithDefault("?") + open Option + Dict.get(indexData, route)->map(data => data["moduleName"])->getOr("?") } let url = route->Url.parse @@ -168,7 +166,7 @@ module Docs = { open SidebarLayout.Toc { title: moduleName, - entries: Belt.Array.map(headers, ((name, href)) => {header: name, href}), + entries: Array.map(headers, ((name, href)) => {header: name, href}), } } diff --git a/src/layouts/BeltDocsLayout9_0_0.res b/src/layouts/BeltDocsLayout9_0_0.res index b3072550c..71df69ca1 100644 --- a/src/layouts/BeltDocsLayout9_0_0.res +++ b/src/layouts/BeltDocsLayout9_0_0.res @@ -1,6 +1,6 @@ // Structure defined by `scripts/extract-indices.js` @module("index_data/v900_belt_api_index.json") -external indexData: Js.Dict.t<{ +external indexData: Dict.t<{ "moduleName": string, "headers": array<{ "name": string, @@ -109,17 +109,15 @@ module Docs = { // Gather data for the CollapsibleSection let headers = { - open Belt.Option - Js.Dict.get(indexData, route) - ->map(data => - data["headers"]->Belt.Array.map(header => (header["name"], "#" ++ header["href"])) - ) - ->getWithDefault([]) + open Option + Dict.get(indexData, route) + ->map(data => data["headers"]->Array.map(header => (header["name"], "#" ++ header["href"]))) + ->getOr([]) } let moduleName = { - open Belt.Option - Js.Dict.get(indexData, route)->map(data => data["moduleName"])->getWithDefault("?") + open Option + Dict.get(indexData, route)->map(data => data["moduleName"])->getOr("?") } let url = route->Url.parse @@ -141,7 +139,7 @@ module Docs = { open SidebarLayout.Toc { title: moduleName, - entries: Belt.Array.map(headers, ((name, href)) => {header: name, href}), + entries: Array.map(headers, ((name, href)) => {header: name, href}), } } diff --git a/src/layouts/CommunityLayout.resi b/src/layouts/CommunityLayout.resi index fd33938ba..00db92c04 100644 --- a/src/layouts/CommunityLayout.resi +++ b/src/layouts/CommunityLayout.resi @@ -1,6 +1,6 @@ @react.component let make: ( - ~frontmatter: Js.Json.t=?, + ~frontmatter: JSON.t=?, ~components: MarkdownComponents.t=?, ~children: React.element, ) => React.element diff --git a/src/layouts/DocsLayout.res b/src/layouts/DocsLayout.res index 7a6dcbc5c..a59a5ad84 100644 --- a/src/layouts/DocsLayout.res +++ b/src/layouts/DocsLayout.res @@ -29,12 +29,12 @@ let makeBreadcrumbsFromPaths = (~basePath: string, paths: array<string>): list<U let makeBreadcrumbs = (~basePath: string, route: string): list<Url.breadcrumb> => { let url = route->Url.parse - let (_, rest) = url.pagepath->Belt.Array.reduce((basePath, []), (acc, path) => { + let (_, rest) = url.pagepath->Array.reduce((basePath, []), (acc, path) => { let (baseHref, ret) = acc let href = baseHref ++ ("/" ++ path) - Js.Array2.push( + Array.push( ret, { open Url @@ -43,7 +43,7 @@ let makeBreadcrumbs = (~basePath: string, route: string): list<Url.breadcrumb> = )->ignore (href, ret) }) - rest->Belt.List.fromArray + rest->List.fromArray } @react.component @@ -98,8 +98,8 @@ let make = ( let targetUrl = "/" ++ - (Js.Array2.joinWith(url.base, "/") ++ - ("/" ++ (version ++ ("/" ++ Js.Array2.joinWith(url.pagepath, "/"))))) + (Array.join(url.base, "/") ++ + ("/" ++ (version ++ ("/" ++ Array.join(url.pagepath, "/"))))) router->Next.Router.push(targetUrl) } <VersionSelect onChange version availableVersions /> @@ -123,12 +123,12 @@ let make = ( | Some(frontmatter) => switch DocFrontmatter.decode(frontmatter) { | Some(fm) => - let canonical = Js.Null.toOption(fm.canonical) - let description = Js.Null.toOption(fm.description) + let canonical = Null.toOption(fm.canonical) + let description = Null.toOption(fm.description) let title = switch metaTitleCategory { | Some(titleCategory) => // We will prefer an existing metaTitle over just a title - let metaTitle = switch Js.Null.toOption(fm.metaTitle) { + let metaTitle = switch Null.toOption(fm.metaTitle) { | Some(metaTitle) => metaTitle | None => fm.title } @@ -186,22 +186,17 @@ module Make = (Content: StaticContent) => { let route = router.route // Extend breadcrumbs with document title - let breadcrumbs = Js.Dict.get(Content.tocData, route)->Belt.Option.mapWithDefault( - breadcrumbs, - data => { - let title = data["title"] + let breadcrumbs = Dict.get(Content.tocData, route)->Option.mapOr(breadcrumbs, data => { + let title = data["title"] - Belt.Option.map(breadcrumbs, bc => - Belt.List.concat(bc, list{{Url.name: title, href: route}}) - ) - }, - ) + Option.map(breadcrumbs, bc => List.concat(bc, list{{Url.name: title, href: route}})) + }) let activeToc: option<SidebarLayout.Toc.t> = { - open Belt.Option - Js.Dict.get(Content.tocData, route)->map(data => { + open Option + Dict.get(Content.tocData, route)->map(data => { let title = data["title"] - let entries = Belt.Array.map(data["headers"], header => { + let entries = Array.map(data["headers"], header => { SidebarLayout.Toc.header: header["name"], href: "#" ++ header["href"], }) @@ -210,30 +205,27 @@ module Make = (Content: StaticContent) => { } let categories = { - let groups = Js.Dict.entries(Content.tocData)->Belt.Array.reduce(Js.Dict.empty(), ( - acc, - next, - ) => { + let groups = Dict.toArray(Content.tocData)->Array.reduce(Dict.make(), (acc, next) => { let (_, value) = next - switch Js.Nullable.toOption(value["category"]) { + switch Nullable.toOption(value["category"]) { | Some(category) => - switch acc->Js.Dict.get(category) { - | None => acc->Js.Dict.set(category, [next]) + switch acc->Dict.get(category) { + | None => acc->Dict.set(category, [next]) | Some(arr) => - Js.Array2.push(arr, next)->ignore - acc->Js.Dict.set(category, arr) + Array.push(arr, next)->ignore + acc->Dict.set(category, arr) } | None => - Js.log2("has NO category", next) + Console.log2("has NO category", next) () } acc }) - Js.Dict.entries(groups)->Belt.Array.map(((name, values)) => { + Dict.toArray(groups)->Array.map(((name, values)) => { open Category { name, - items: Belt.Array.map(values, ((href, value)) => { + items: Array.map(values, ((href, value)) => { NavItem.name: value["title"], href, }), diff --git a/src/layouts/DocsLayout.resi b/src/layouts/DocsLayout.resi index 14207cd7e..f02706e2a 100644 --- a/src/layouts/DocsLayout.resi +++ b/src/layouts/DocsLayout.resi @@ -6,7 +6,7 @@ let make: ( ~breadcrumbs: list<Url.breadcrumb>=?, ~title: string, ~metaTitleCategory: string=?, // e.g. Introduction | My Meta Title Category - ~frontmatter: Js.Json.t=?, + ~frontmatter: JSON.t=?, ~version: string=?, ~availableVersions: array<(string, string)>=?, ~activeToc: SidebarLayout.Toc.t=?, @@ -28,7 +28,7 @@ module Make: (Content: StaticContent) => ~breadcrumbs: list<Url.breadcrumb>=?, ~title: string, ~metaTitleCategory: string=?, - ~frontmatter: Js.Json.t=?, + ~frontmatter: JSON.t=?, ~version: string=?, ~availableVersions: array<(string, string)>=?, /* ~activeToc: option<SidebarLayout.Toc.t>=?, */ diff --git a/src/layouts/DomDocsLayout10_0_0.res b/src/layouts/DomDocsLayout10_0_0.res index 4ea8a6cf8..a6bd3743b 100644 --- a/src/layouts/DomDocsLayout10_0_0.res +++ b/src/layouts/DomDocsLayout10_0_0.res @@ -1,6 +1,6 @@ // Structure defined by `scripts/extract-indices.js` @module("index_data/v1000_dom_api_index.json") -external indexData: Js.Dict.t<{ +external indexData: Dict.t<{ "moduleName": string, "headers": array<{ "name": string, @@ -45,17 +45,15 @@ module Docs = { // Gather data for the CollapsibleSection let headers = { - open Belt.Option - Js.Dict.get(indexData, route) - ->map(data => - data["headers"]->Belt.Array.map(header => (header["name"], "#" ++ header["href"])) - ) - ->getWithDefault([]) + open Option + Dict.get(indexData, route) + ->map(data => data["headers"]->Array.map(header => (header["name"], "#" ++ header["href"]))) + ->getOr([]) } let moduleName = { - open Belt.Option - Js.Dict.get(indexData, route)->map(data => data["moduleName"])->getWithDefault("?") + open Option + Dict.get(indexData, route)->map(data => data["moduleName"])->getOr("?") } let url = route->Url.parse @@ -77,7 +75,7 @@ module Docs = { open SidebarLayout.Toc { title: moduleName, - entries: Belt.Array.map(headers, ((name, href)) => {header: name, href}), + entries: Array.map(headers, ((name, href)) => {header: name, href}), } } diff --git a/src/layouts/DomDocsLayout8_0_0.res b/src/layouts/DomDocsLayout8_0_0.res index 056b8c60d..c0155d85f 100644 --- a/src/layouts/DomDocsLayout8_0_0.res +++ b/src/layouts/DomDocsLayout8_0_0.res @@ -1,6 +1,6 @@ // Structure defined by `scripts/extract-indices.js` @module("index_data/v800_dom_api_index.json") -external indexData: Js.Dict.t<{ +external indexData: Dict.t<{ "moduleName": string, "headers": array<{ "name": string, @@ -45,17 +45,15 @@ module Docs = { // Gather data for the CollapsibleSection let headers = { - open Belt.Option - Js.Dict.get(indexData, route) - ->map(data => - data["headers"]->Belt.Array.map(header => (header["name"], "#" ++ header["href"])) - ) - ->getWithDefault([]) + open Option + Dict.get(indexData, route) + ->map(data => data["headers"]->Array.map(header => (header["name"], "#" ++ header["href"]))) + ->getOr([]) } let moduleName = { - open Belt.Option - Js.Dict.get(indexData, route)->map(data => data["moduleName"])->getWithDefault("?") + open Option + Dict.get(indexData, route)->map(data => data["moduleName"])->getOr("?") } let url = route->Url.parse @@ -77,7 +75,7 @@ module Docs = { open SidebarLayout.Toc { title: moduleName, - entries: Belt.Array.map(headers, ((name, href)) => {header: name, href}), + entries: Array.map(headers, ((name, href)) => {header: name, href}), } } diff --git a/src/layouts/DomDocsLayout9_0_0.res b/src/layouts/DomDocsLayout9_0_0.res index 789ca368f..75baff1f8 100644 --- a/src/layouts/DomDocsLayout9_0_0.res +++ b/src/layouts/DomDocsLayout9_0_0.res @@ -1,6 +1,6 @@ // Structure defined by `scripts/extract-indices.js` @module("index_data/v900_dom_api_index.json") -external indexData: Js.Dict.t<{ +external indexData: Dict.t<{ "moduleName": string, "headers": array<{ "name": string, @@ -45,17 +45,15 @@ module Docs = { // Gather data for the CollapsibleSection let headers = { - open Belt.Option - Js.Dict.get(indexData, route) - ->map(data => - data["headers"]->Belt.Array.map(header => (header["name"], "#" ++ header["href"])) - ) - ->getWithDefault([]) + open Option + Dict.get(indexData, route) + ->map(data => data["headers"]->Array.map(header => (header["name"], "#" ++ header["href"]))) + ->getOr([]) } let moduleName = { - open Belt.Option - Js.Dict.get(indexData, route)->map(data => data["moduleName"])->getWithDefault("?") + open Option + Dict.get(indexData, route)->map(data => data["moduleName"])->getOr("?") } let url = route->Url.parse @@ -77,7 +75,7 @@ module Docs = { open SidebarLayout.Toc { title: moduleName, - entries: Belt.Array.map(headers, ((name, href)) => {header: name, href}), + entries: Array.map(headers, ((name, href)) => {header: name, href}), } } diff --git a/src/layouts/JsDocsLayout10_0_0.res b/src/layouts/JsDocsLayout10_0_0.res index a6ee0736f..5ac403eed 100644 --- a/src/layouts/JsDocsLayout10_0_0.res +++ b/src/layouts/JsDocsLayout10_0_0.res @@ -1,6 +1,6 @@ // Structure defined by `scripts/extract-indices.js` @module("index_data/v1000_js_api_index.json") -external indexData: Js.Dict.t<{ +external indexData: Dict.t<{ "moduleName": string, "headers": array<{ "name": string, @@ -153,17 +153,15 @@ module Docs = { // Gather data for the CollapsibleSection let headers = { - open Belt.Option - Js.Dict.get(indexData, route) - ->map(data => - data["headers"]->Belt.Array.map(header => (header["name"], "#" ++ header["href"])) - ) - ->getWithDefault([]) + open Option + Dict.get(indexData, route) + ->map(data => data["headers"]->Array.map(header => (header["name"], "#" ++ header["href"]))) + ->getOr([]) } let moduleName = { - open Belt.Option - Js.Dict.get(indexData, route)->map(data => data["moduleName"])->getWithDefault("?") + open Option + Dict.get(indexData, route)->map(data => data["moduleName"])->getOr("?") } let url = route->Url.parse @@ -185,7 +183,7 @@ module Docs = { open SidebarLayout.Toc { title: moduleName, - entries: Belt.Array.map(headers, ((name, href)) => {header: name, href}), + entries: Array.map(headers, ((name, href)) => {header: name, href}), } } diff --git a/src/layouts/JsDocsLayout8_0_0.res b/src/layouts/JsDocsLayout8_0_0.res index 108248068..33521843c 100644 --- a/src/layouts/JsDocsLayout8_0_0.res +++ b/src/layouts/JsDocsLayout8_0_0.res @@ -1,6 +1,6 @@ // Structure defined by `scripts/extract-indices.js` @module("index_data/v800_js_api_index.json") -external indexData: Js.Dict.t<{ +external indexData: Dict.t<{ "moduleName": string, "headers": array<{ "name": string, @@ -159,17 +159,15 @@ module Docs = { // Gather data for the CollapsibleSection let headers = { - open Belt.Option - Js.Dict.get(indexData, route) - ->map(data => - data["headers"]->Belt.Array.map(header => (header["name"], "#" ++ header["href"])) - ) - ->getWithDefault([]) + open Option + Dict.get(indexData, route) + ->map(data => data["headers"]->Array.map(header => (header["name"], "#" ++ header["href"]))) + ->getOr([]) } let moduleName = { - open Belt.Option - Js.Dict.get(indexData, route)->map(data => data["moduleName"])->getWithDefault("?") + open Option + Dict.get(indexData, route)->map(data => data["moduleName"])->getOr("?") } let url = route->Url.parse @@ -190,7 +188,7 @@ module Docs = { open SidebarLayout.Toc { title: moduleName, - entries: Belt.Array.map(headers, ((name, href)) => {header: name, href}), + entries: Array.map(headers, ((name, href)) => {header: name, href}), } } diff --git a/src/layouts/JsDocsLayout9_0_0.res b/src/layouts/JsDocsLayout9_0_0.res index 00635e37c..aa95c1ce1 100644 --- a/src/layouts/JsDocsLayout9_0_0.res +++ b/src/layouts/JsDocsLayout9_0_0.res @@ -1,6 +1,6 @@ // Structure defined by `scripts/extract-indices.js` @module("index_data/v900_js_api_index.json") -external indexData: Js.Dict.t<{ +external indexData: Dict.t<{ "moduleName": string, "headers": array<{ "name": string, @@ -159,17 +159,15 @@ module Docs = { // Gather data for the CollapsibleSection let headers = { - open Belt.Option - Js.Dict.get(indexData, route) - ->map(data => - data["headers"]->Belt.Array.map(header => (header["name"], "#" ++ header["href"])) - ) - ->getWithDefault([]) + open Option + Dict.get(indexData, route) + ->map(data => data["headers"]->Array.map(header => (header["name"], "#" ++ header["href"]))) + ->getOr([]) } let moduleName = { - open Belt.Option - Js.Dict.get(indexData, route)->map(data => data["moduleName"])->getWithDefault("?") + open Option + Dict.get(indexData, route)->map(data => data["moduleName"])->getOr("?") } let url = route->Url.parse @@ -190,7 +188,7 @@ module Docs = { open SidebarLayout.Toc { title: moduleName, - entries: Belt.Array.map(headers, ((name, href)) => {header: name, href}), + entries: Array.map(headers, ((name, href)) => {header: name, href}), } } diff --git a/src/layouts/LandingPageLayout.res b/src/layouts/LandingPageLayout.res index 6292a9976..f5b78d7fb 100644 --- a/src/layouts/LandingPageLayout.res +++ b/src/layouts/LandingPageLayout.res @@ -67,7 +67,7 @@ export { @react.component let make = () => { - let (example, _setExample) = React.useState(_ => examples->Js.Array2.unsafe_get(0)) + let (example, _setExample) = React.useState(_ => examples->Array.getUnsafe(0)) //Playground Section & Background <section className="relative mt-20 bg-gray-10"> @@ -169,7 +169,7 @@ module QuickInstall = { let make = (~code) => { let (state, setState) = React.useState(_ => Init) - let buttonRef = React.useRef(Js.Nullable.null) + let buttonRef = React.useRef(Nullable.null) let onClick = evt => { ReactEvent.Mouse.preventDefault(evt) @@ -184,7 +184,7 @@ module QuickInstall = { switch state { | Copied => open Webapi - let buttonEl = Js.Nullable.toOption(buttonRef.current)->Belt.Option.getExn + let buttonEl = Nullable.toOption(buttonRef.current)->Option.getExn // Note on this imperative DOM nonsense: // For Tailwind transitions to behave correctly, we need to first paint the DOM element in the tree, @@ -204,7 +204,7 @@ module QuickInstall = { bannerEl->Element.classList->ClassList.toggle("opacity-100") }) - let timeoutId = Js.Global.setTimeout(() => { + let timeoutId = setTimeout(() => { buttonEl->Element.removeChild(bannerEl) setState(_ => Init) }, 2000) @@ -212,7 +212,7 @@ module QuickInstall = { Some( () => { cancelAnimationFrame(nextFrameId) - Js.Global.clearTimeout(timeoutId) + clearTimeout(timeoutId) }, ) | _ => None @@ -524,7 +524,7 @@ module TrustedBy = { <div className="flex flex-wrap mx-4 gap-8 justify-center items-center max-w-xl lg:mx-auto mt-16 mb-16"> {OurUsers.companies - ->Js.Array2.map(company => { + ->Array.map(company => { let (companyKey, renderedCompany) = switch company { | Logo({name, path, url}) => ( name, @@ -642,9 +642,9 @@ module CuratedResources = { <div className="grid grid-flow-col grid-cols-2 grid-rows-2 lg:grid-cols-4 lg:grid-rows-1 gap-2 md:gap-4 lg:gap-8 max-w-1280 px-5 md:px-8 mx-auto"> {cards - ->Belt.Array.mapWithIndex((i, card) => + ->Array.mapWithIndex((card, i) => <Next.Link - key={Belt.Int.toString(i)} + key={Int.toString(i)} href={card.href} className="hover:bg-gray-80 bg-gray-90 px-4 md:px-8 pb-0 md:pb-8 relative rounded-xl md:min-w-[196px]"> <img className="h-[53px] absolute mt-6" src=card.imgSrc /> @@ -665,9 +665,9 @@ module CuratedResources = { <div className="grid grid-flow-col grid-cols-2 lg:grid-cols-3 lg:grid-rows-1 gap-2 md:gap-4 lg:gap-8 max-w-1280 px-5 md:px-8 mx-auto"> {templates - ->Belt.Array.mapWithIndex((i, card) => + ->Array.mapWithIndex((card, i) => <a - key={Belt.Int.toString(i)} + key={Int.toString(i)} href={card.href} className="hover:bg-gray-80 bg-gray-90 px-5 pb-8 relative rounded-xl min-w-[200px]"> <img className="h-12 absolute mt-5" src=card.imgSrc /> diff --git a/src/layouts/ManualDocsLayout.res b/src/layouts/ManualDocsLayout.res index 6fcc0c1a6..fcdeaf6be 100644 --- a/src/layouts/ManualDocsLayout.res +++ b/src/layouts/ManualDocsLayout.res @@ -110,7 +110,7 @@ module V1000 = { module V900 = { @react.component let make = ( - ~frontmatter: option<Js.Json.t>=?, + ~frontmatter: option<JSON.t>=?, ~components=MarkdownComponents.default, ~children, ) => { @@ -190,11 +190,9 @@ module V800 = { open Markdown let latestUrl = - "/" ++ - (Js.Array2.joinWith(url.base, "/") ++ - ("/latest/" ++ Js.Array2.joinWith(url.pagepath, "/"))) + "/" ++ (Array.join(url.base, "/") ++ ("/latest/" ++ Array.join(url.pagepath, "/"))) - let label = switch Js.Array2.find(Constants.allManualVersions, ((v, _)) => { + let label = switch Array.find(Constants.allManualVersions, ((v, _)) => { v === version }) { | Some((_, label)) => label diff --git a/src/layouts/ReactDocsLayout.res b/src/layouts/ReactDocsLayout.res index 66425f5d6..134279c37 100644 --- a/src/layouts/ReactDocsLayout.res +++ b/src/layouts/ReactDocsLayout.res @@ -56,11 +56,9 @@ module Latest = { open Markdown let v011Url = - "/" ++ - (Js.Array2.joinWith(url.base, "/") ++ - ("/v0.11.0/" ++ Js.Array2.joinWith(url.pagepath, "/"))) + "/" ++ (Array.join(url.base, "/") ++ ("/v0.11.0/" ++ Array.join(url.pagepath, "/"))) - let label = switch Js.Array2.find(Constants.allReactVersions, ((v, _)) => { + let label = switch Array.find(Constants.allReactVersions, ((v, _)) => { v === version }) { | Some((_, label)) => label diff --git a/src/layouts/ReasonCompilerDocsLayout.res b/src/layouts/ReasonCompilerDocsLayout.res index 40e07bde0..b9883af68 100644 --- a/src/layouts/ReasonCompilerDocsLayout.res +++ b/src/layouts/ReasonCompilerDocsLayout.res @@ -1,6 +1,6 @@ // Structure defined by `scripts/extract-tocs.js` @module("index_data/reason_compiler_toc.json") -external tocData: Js.Dict.t<{ +external tocData: Dict.t<{ "title": string, "headers": array<{ "name": string, @@ -64,10 +64,10 @@ let make = (~components=MarkdownComponents.default, ~children) => { let route = router.route let activeToc: option<Toc.t> = { - open Belt.Option - Js.Dict.get(tocData, route)->map(data => { + open Option + Dict.get(tocData, route)->map(data => { let title = data["title"] - let entries = Belt.Array.map(data["headers"], header => { + let entries = Array.map(data["headers"], header => { Toc.header: header["name"], href: "#" ++ header["href"], }) @@ -97,7 +97,7 @@ let make = (~components=MarkdownComponents.default, ~children) => { }, } - let breadcrumbs = Belt.List.concat( + let breadcrumbs = List.concat( prefix, DocsLayout.makeBreadcrumbs(~basePath="/docs/manual/" ++ version, route), ) diff --git a/src/layouts/SidebarLayout.res b/src/layouts/SidebarLayout.res index 8b38fc35d..bafdd84ca 100644 --- a/src/layouts/SidebarLayout.res +++ b/src/layouts/SidebarLayout.res @@ -7,9 +7,9 @@ module Link = Next.Link module Toc = { - type raw = Js.Dict.t<{ + type raw = Dict.t<{ "title": string, - "category": Js.Nullable.t<string>, + "category": Nullable.t<string>, "headers": array<{ "name": string, "href": string, @@ -29,7 +29,7 @@ module Toc = { @react.component let make = (~entries: array<entry>) => <ul className="mt-3 py-1 mb-4 border-l border-fire-10"> - {Belt.Array.map(entries, ({header, href}) => + {Array.map(entries, ({header, href}) => <li key=header className="pl-2 mt-2 first:mt-1"> <Link href @@ -66,7 +66,7 @@ module Sidebar = { ~items: array<t>, ) => <ul className="mt-2 text-14 font-medium"> - {Belt.Array.map(items, m => { + {Array.map(items, m => { let hidden = isHidden ? "hidden" : "block" let active = isItemActive(m) ? ` bg-fire-5 text-red-500 leading-5 -ml-2 pl-2 font-medium block hover:bg-fire-70 ` @@ -86,7 +86,7 @@ module Sidebar = { </Link> {switch activeToc { | Some({entries}) => - if Belt.Array.length(entries) === 0 { + if Array.length(entries) === 0 { React.null } else { <Toc entries /> @@ -161,7 +161,7 @@ module Sidebar = { */ <div className="mb-56"> {categories - ->Belt.Array.map(category => + ->Array.map(category => <div key=category.name> <Category getActiveToc isItemActive category /> </div> @@ -178,14 +178,14 @@ module BreadCrumbs = { @react.component let make = (~crumbs: list<Url.breadcrumb>) => <div className="w-full captions overflow-x-auto text-gray-60"> - {Belt.List.mapWithIndex(crumbs, (i, crumb) => { - let item = if i === Belt.List.length(crumbs) - 1 { - <span key={Belt.Int.toString(i)}> {React.string(crumb.name)} </span> + {List.mapWithIndex(crumbs, (crumb, i) => { + let item = if i === List.length(crumbs) - 1 { + <span key={Int.toString(i)}> {React.string(crumb.name)} </span> } else { - <Link key={Belt.Int.toString(i)} href=crumb.href> {React.string(crumb.name)} </Link> + <Link key={Int.toString(i)} href=crumb.href> {React.string(crumb.name)} </Link> } if i > 0 { - <span key={Belt.Int.toString(i)}> + <span key={Int.toString(i)}> {React.string(" / ")} item </span> @@ -193,7 +193,7 @@ module BreadCrumbs = { item } }) - ->Belt.List.toArray + ->List.toArray ->React.array} </div> } @@ -231,8 +231,7 @@ let make = ( | Some(l) => List.length(l) > 0 } - let breadcrumbs = - breadcrumbs->Belt.Option.mapWithDefault(React.null, crumbs => <BreadCrumbs crumbs />) + let breadcrumbs = breadcrumbs->Option.mapOr(React.null, crumbs => <BreadCrumbs crumbs />) let (_isSidebarOpen, setSidebarOpen) = sidebarState let toggleSidebar = () => setSidebarOpen(prev => !prev) @@ -269,12 +268,12 @@ let make = ( let pagination = switch categories { | Some(categories) => - let items = categories->Belt.Array.flatMap(c => c.items) + let items = categories->Array.flatMap(c => c.items) - switch items->Js.Array2.findIndex(item => item.href === router.route) { + switch items->Array.findIndex(item => item.href === router.route) { | -1 => React.null | i => - let previous = switch items->Belt.Array.get(i - 1) { + let previous = switch items->Array.get(i - 1) { | Some({name, href}) => <Link href @@ -284,7 +283,7 @@ let make = ( </Link> | None => React.null } - let next = switch items->Belt.Array.get(i + 1) { + let next = switch items->Array.get(i + 1) { | Some({name, href}) => <Link href diff --git a/src/layouts/SidebarLayout.resi b/src/layouts/SidebarLayout.resi index d20033a4d..34c7a7eed 100644 --- a/src/layouts/SidebarLayout.resi +++ b/src/layouts/SidebarLayout.resi @@ -1,8 +1,8 @@ module Toc: { // the plain data coming from the toc file - type raw = Js.Dict.t<{ + type raw = Dict.t<{ "title": string, - "category": Js.Nullable.t<string>, + "category": Nullable.t<string>, "headers": array<{ "name": string, "href": string, diff --git a/src/others/Revalidate.res b/src/others/Revalidate.res index f065486a6..893d87036 100644 --- a/src/others/Revalidate.res +++ b/src/others/Revalidate.res @@ -1,5 +1,5 @@ module Req = { - type req = {query: Js.Dict.t<string>} + type req = {query: Dict.t<string>} } module Res = { @@ -17,9 +17,9 @@ module Res = { } let handler = async (req: Req.req, res: Res.res) => { - switch req.query->Js.Dict.get("secret") { + switch req.query->Dict.get("secret") { | Some(secret) => - switch Node.Process.env->Js.Dict.get("NEXT_REVALIDATE_SECRET_TOKEN") { + switch Node.Process.env->Dict.get("NEXT_REVALIDATE_SECRET_TOKEN") { | Some(token) => if secret !== token { res->Res.Status.make(401)->Res.Status.json({"message": "Invalid secret"}) @@ -28,7 +28,7 @@ let handler = async (req: Req.req, res: Res.res) => { let () = await res->Res.revalidate("/try") res->Res.json({"revalidated": true}) } catch { - | Js.Exn.Error(_) => res->Res.Status.make(500)->Res.Status.send("Error revalidating") + | Exn.Error(_) => res->Res.Status.make(500)->Res.Status.send("Error revalidating") } } | None =>