Welcome to the second part of the Build a Web App with Oats~i tutorial series. In the first part, we went through installing Oats~i in your development environment. In case you missed that one, check it out here.
In this part of the series, we’ll go through how to start an Oats~i app. This will cover all instances where you want to start an Oats~i app and have the framework run on the front end.
Instead of building a whole project from scratch, we’ll use the inbuilt starter project that comes with Oats~i when you set it up using the Oats~i cli. We’ll open the important bits of the code necessary for this tutorial and use that to explain how Oats~i loads up when it gets to the client/browser and starts running your web app.
Let’s dive in.
Create a new folder where you want to install the Oats~i starter project and open the terminal. Then run:
npx oats-i-cli
Follow the prompts.
This will install Oats~i and the starter project bundled with it to your current working directory.
Finally, to run the starter project, run
npm run dev
Navigate to the address provided in the terminal (often localhost:8080) and see the starter project in action. Navigate back and forth between the available pages to see Oats~i handle routing and build views through fragments.
Now let’s get to the code that brings Oats~i to life in the client/browser.
Open the index.js file found in src -> app -> index -> scripts.
This file contains the code that starts Oats~i for the starter project bundled in the cli. This is more or less the same code you’d write to start Oats~i in your own project.
Let’s break it down.
Oats~i is typically initialized from the appRoot module through the appRoot.initApp() method.
appRoot is a singleton instance of the AppRoot class that manages the initialization of an Oats~i web app, main navigation, and loading the root view if its template is provided.
The initApp() method takes several arguments, including an instance of the AppStateManager, MainRouter, AppRootView object, a default route, and optional extra options that currently allow you to define the app’s external link interception behavior.
Let’s break these down.
The app state manager is a module responsible for managing the route states of an Oats~i app. Primarily, it helps Oats~i understand whether a history pop event is a click on the forward or back button on the browser by the user.
This information is not obvious using the history API as is.
Having this information is crucial because Oats~i saves fragment states as the web app is navigated by the user. Therefore, if they are to go back or forward to a page they were in before, the fragment(s) responsible for rendering and running those pages will “remember” their state and show the right information and automatically be scrolled to the right position the user was at.
Knowing whether the pop event is a forward or back movement makes retrieving state information accurate.
You simply create an instance of the AppStateManager by invoking new, passing in the web app’s routing info.
In our index.js file, we do this in the line:
const appStateManager = new AppStateManager(AppRoutingInfo);
We have already defined our AppRoutingInfo in a separate file (more on this later).
The main router handles routing in an Oats~i web app. You create a router instance by invoking “new”, passing in the app’s routing info, app state manager instance, an error callback, a root path, and a route consent callback.
We’ve already talked about the app routing info and app state manager instance, so let’s talk about the other arguments that you pass to the main router.
In case of a problem routing, the main router can fire the error callback and inform you of the reasons why routing has failed. As long as you’ve defined your routes well, you shouldn’t worry about implementing this method, other than merely providing it.
The main router allows you to directly call for routing from your JavaScript code using the routeTO() method. It also determines the valid route to follow based on your app’s main routing info.
Now, if you have Oats~i running in your website with a special address such as /admin, it can be repetitive having to start every routing call or routing info with the /admin root. Instead, you can supply this to the main router as the root path, and just append the rest of your route to your routing calls or routing info.
So, instead of /admin/create, with the root path set to /admin, you can just have the route as /create. However, href attributes in links MUST be fully qualified.
Before the main router can trigger routing for a given path, it attempts to see whether routing for that route has been permitted. The route consent callback allows you to specify this, giving you the ability to control which sections of your web app can be accessed by a given user or based on any other business or app logic.
Note: This is different from fragment consenting, which we’ll cover later.
The app root view object consists of the root view template and array of main navigation infos.
Every Oats~i app has a root view. This is the permanent section of the view which the user will always see regardless of the path they’re navigating to. The root view is wrapped within an tag and will typically contain elements such as your navbar and footer.
Here’s an example, sourced from home.sv.hbs in the Oats~i starter project
Home About
Note: As you can infer from the Oats~i starter project, you can skip passing in a template for the app root view in the initApp() method as long as you’ve provided it in the html markup sourced for your page from the server.
Your root view object should also have a single tag specified within, where the app’s fragments will be loaded.
The AppRootView object also takes a main navigation info array, which contains a list of selectors and their active routes, which Oats~i will use to show you which navigation selector is active.
In the Oats~i starter project, specifying the main nav info makes it possible to update the styling and looks of the navigation links when you click on it and navigate to its url.
Oats~i handles the click and update boiler plate for the navigation links or buttons. All you have to do is style the links or buttons based on which one is marked as active using the attribute ‘navigation-state=”active”’
The default route is the route Oats~i will default to incase the page loads from a url that is not specified in your app’s routing info. You can use this to curate the default web app behavior especially if it results from a log in or authentication action.
For instance, if the user has come in from a login page and is redirected to their admin page, but the initial page load is at “/admin”, you can specify the default route to be “/admin/dashboard”.
Oats~i will reroute the web app to /admin/dashboard on load and the user will always access their dashboard every time they come from logging into the app.
If you want to change this behavior to say, profile, you can simply change the default route in your web app to /admin/profile and all users logging in will have their profile page as the default page.
Oats~i also takes in optional extra options, with the current implementation allowing you to intercept external links within your web app. This allows you to warn users of their navigation away from your site and the url they’re about to access, in case you want to build a content protection system.
The complete code for starting an Oats~i app will look something like this:
//sourced from index.js in the starter app const appStateManager = new AppStateManager(AppRoutingInfo); appRoot.initApp(appStateManager, new MainRouter(AppRoutingInfo, appStateManager, (args) => {}, "", async (url) => { return { canAccess: true, fallbackRoute: "/" } }), { template: null, mainNavInfos: AppMainNavInfo }, "");
You can wrap this code within a function that is automatically invoked when your index.js file downloads in the browser to have the web app automatically started on page load. In the starter project’s case, this is the initApp() function.
Now, there are two more things left to explain.
From the startup code, you can point out that providing routing information is mandatory for an Oats~i web app to initialize. From the example’s I’ve given, we define this info elsewhere then import it in our startup script. Defining your routing info in a separate file is not mandatory, but I find it to be good practice especially when you want to add more routes or main navigation in your web app.
Here’s how routing information is defined for an Oats~i web app, using the example from the starter project.
const AppRoutingInfo = RoutingInfoUtils.buildMainRoutingInfo([ { route: "/", target: homeMainFragmentBuilder, nestedChildFragments: null }, { route: "/about", target: aboutMainFragmentBuilder, nestedChildFragments: null } ], AppMainNavInfo);
You can call the routing info any name you want, as long as you use the method RoutingInfoUtils.buildMainRoutingInfo() to build it.
The method will return an array of routing information, with each info holding:
You can notice that we also pass AppMainNavInfo to the buildMainRoutingInfo() method as well. This is the same info we passed in to the app state manager and initApp method in the starter script. Let’s look at it.
A good web app needs good navigation. And often, setting up navigation can involve a lot of boiler plate code to not only set up the click listeners for the navigation links or buttons, but also change their styling based on which one is active.
Oats~i takes care of the boiler plate for you by requiring you only provide the navigation information needed by your web app. This takes the following format (example sourced from the starter project).
const AppMainNavInfo = MainNavigationInfoBuilder.buildMainNavigationInfo([ { selector: "home-link", defaultRoute: "/", baseActiveRoute: "/", }, { selector: "about-link", defaultRoute: "/about", baseActiveRoute: "/about", } ]);
You create a main navigation info in Oats~i using the method MainNavigationInfoBuilder.buildMainNavigationInfo(). It returns an array of navigation infos, with each containing:
Let’s put everything together and have the final picture of what you need to get an Oats~i app up and running. Typically, you must have defined:
Then, simply get a new instance of the app state manager, and call appRoot.initApp passing this instance, the app routing info, app main nav info, and main router instance. Again, here’s the example code from the Oats~i starter project that comes bundled with the cli, now wrapped in a function that we call immediately the index.js file loads in the browser.
function initApp(){ const appStateManager = new AppStateManager(AppRoutingInfo); appRoot.initApp(appStateManager, new MainRouter(AppRoutingInfo, appStateManager, (args) => {}, "", async (url) => { return { canAccess: true, fallbackRoute: "/" } }), { template: null, mainNavInfos: AppMainNavInfo }, ""); } initApp();
As your web app grows and changes, the only bits of this code you’ll ever need to change are the app routing infos and main navigation infos (AppRoutingInfo and AppMainNavInfo). This will be typically because you’re adding new routes to your web app (thus updating the routing information) or adding new main navigation buttons or links (thus updating the main navigation infos).
The rest of the code will be fine untouched.
A lot of this will make sense when we build our very own small project in Oats~i. That’s what we’ll be doing in the next part of this series, to learn the next fundamental concepts around building an Oats~i web app.
See you then.
Support Oats~i
You can support the development of Oats~i through Patreon or buy me a coffee.
Isenção de responsabilidade: Todos os recursos fornecidos são parcialmente provenientes da Internet. Se houver qualquer violação de seus direitos autorais ou outros direitos e interesses, explique os motivos detalhados e forneça prova de direitos autorais ou direitos e interesses e envie-a para o e-mail: [email protected]. Nós cuidaremos disso para você o mais rápido possível.
Copyright© 2022 湘ICP备2022001581号-3