Class PlaceManager

java.lang.Object
org.jboss.elemento.router.PlaceManager

public class PlaceManager extends Object
The place manager is the central part of the router. It keeps track of registered places, handles navigation events, and updates the DOM accordingly. The place manager can be customized using builder like methods and has a start() method to show the initial page.

public static class TimeLoader implements LoadData<String> {

    @Override
    public Promise<String> load(Place place, Parameter parameter) {
        String area = parameter.get("area");
        String location = parameter.get("location");
        String url = "https://worldtimeapi.org/api/timezone/" + area + "/" + location;
        return fetch(url)
                .then(Response::json)
                .then(json -> {
                    JsPropertyMap<String> map = Js.cast(json);
                    return Promise.resolve(map.get("datetime"));
                });
    }
}

public static class TimePage implements Page {

    @Override
    public Iterable<HTMLElement> elements(Place place, Parameter parameter, LoadedData data) {
        String area = parameter.get("area");
        String location = parameter.get("location");
        String currentTime = data.get();
        return asList(
                h(1, "Current time").element(),
                p()
                        .add("It's ")
                        .add(span().text(currentTime))
                        .add(" in " + area + "/" + location)
                        .element());
    }
}

public static class HomePage implements Page {

    @Override
    public Iterable<HTMLElement> elements(Place place, Parameter parameter, LoadedData data) {
        return asList(
                h(1, "Welcome").element(),
                p()
                        .add("What time is it in ")
                        .add(a("/time/Europe/Berlin").text("Berlin"))
                        .add("?")
                        .element());
    }
}

public static class Application {

    public void entryPoint() {
        body().add(div().id("main"));

        Places places = Places.places()
                .add(place("/"), HomePage::new)
                .add(place("/time/:area/:location")
                        .loader(new TimeLoader()), TimePage::new);

        PlaceManager placeManager = new PlaceManager()
                .root(By.id("main"))
                .register(places);
        placeManager.start();
    }
}
See Also:
  • Constructor Details

    • PlaceManager

      public PlaceManager()
  • Method Details

    • base

      public PlaceManager base(String base)
      The base URL for all locations. If your app is served from a subdirectory on your server, you’ll want to set this to the subdirectory. A properly formatted basename should have a leading slash but no trailing slash.
    • root

      public PlaceManager root(String selector)
      Sets the root HTMLElement for the application's UI using a CSS selector.
      Parameters:
      selector - a CSS selector string used to identify the root element
    • root

      public PlaceManager root(By selector)
      Sets the root HTMLElement for the application's UI using a By selector.
      Parameters:
      selector - a By selector used to identify the root element
    • root

      public PlaceManager root(HTMLElement element)
      Sets the root HTMLElement for the application's UI.
      Parameters:
      element - the HTMLElement to be used as the root of the application's UI
    • root

      public PlaceManager root(Supplier<HTMLElement> root)
      Sets the root HTMLElement for the application's UI using a supplier. The supplier provides an instance of the HTMLElement that serves as the root container for the UI. This method allows dynamic determination of the root element at runtime.
      Parameters:
      root - a Supplier that provides an HTMLElement to be used as the root of the application's UI
    • title

      public PlaceManager title(Function<String,String> title)
      Sets the function to resolve or modify the title for the current place or page. This function can be used to dynamically determine the title based on the input.
      Parameters:
      title - a Function that takes a String and returns a String, representing the dynamic resolution or modification of the title.
    • notFound

      public PlaceManager notFound(Function<Place,Page> notFound)
      Sets the callback function to handle cases where no matching place is found.
      Parameters:
      notFound - a Function that takes a Place as input and returns a Page. This function will be called to provide a fallback page when a requested place doesn't match any registered routes.
    • noData

      public PlaceManager noData(Supplier<Page> noData)
      Sets the callback function to handle cases where no data is available for a given place. This function is invoked to provide a fallback Page when there is an absence of data.
      Parameters:
      noData - a Supplier that provides a fallback Page in scenarios where no data is available.
    • errorPage

      public PlaceManager errorPage(BiFunction<Place,String,Page> errorPage)
      Sets the callback function to handle error scenarios. This function is invoked to provide a fallback Page when an error occurs during navigation or page rendering.
      Parameters:
      errorPage - a BiFunction that takes a Place and a String (representing the error message) as input and returns a Page to be used as the fallback error page.
      Returns:
      the current PlaceManager instance for method chaining.
    • beforePlace

      public PlaceManager beforePlace(BeforePlaceHandler beforePlace)
      Registers a handler that is executed before a place transition occurs. The provided BeforePlaceHandler can perform pre-processing, validation, or cancellation of the transition based on its implementation.
      Parameters:
      beforePlace - the BeforePlaceHandler to be executed before the place transition
    • afterPlace

      public PlaceManager afterPlace(AfterPlaceHandler afterPlace)
      Registers a handler to be executed after a place transition occurs. The provided AfterPlaceHandler can perform post-processing or additional actions based on the new place state.
      Parameters:
      afterPlace - the AfterPlaceHandler to be executed after the place transition
      Returns:
      the current PlaceManager instance for method chaining
    • linkSelector

      public PlaceManager linkSelector(String selector)
      Sets the link selector for selecting links that should be monitored by this place manager. This method uses a CSS selector string to define the selector.
      Parameters:
      selector - a CSS selector string used to identify links
    • linkSelector

      public PlaceManager linkSelector(String selector, boolean not)
      Sets the link selector for selecting links that should be monitored by this place manager. This method uses a By selector to define the selector and allows specifying whether the selection should be negated.
      Parameters:
      selector - a By selector used to identify links
      not - a boolean flag indicating whether the selector should be negated
    • linkSelector

      public PlaceManager linkSelector(By selector)
      Sets the link selector for links that should be monitored by this place manager. This method uses a By selector to define the links to be selected.
      Parameters:
      selector - a By selector used to identify links
    • linkSelector

      public PlaceManager linkSelector(By selector, boolean not)
      Sets the link selector for links that should be monitored by this place manager. This method uses a By selector to define the links to be selected and allows specifying whether the selection should be negated.
      Parameters:
      selector - a By selector used to identify links
      not - a boolean flag indicating whether the selector should be negated
    • register

      public PlaceManager register(Place place, Supplier<Page> page)
      Registers a new place and its associated page supplier with the place manager.
      Parameters:
      place - the Place object representing a specific location in the application
      page - a Supplier that provides the Page associated with the given place
    • register

      public PlaceManager register(Places places)
      Registers a collection of places and their associated page suppliers with the PlaceManager.
      Parameters:
      places - a Places object containing a collection of Place objects and their corresponding Supplier for Page. Each entry in the collection represents a mapping between a place and a page supplier.
    • current

      public Place current()
      Returns the current Place instance being managed by the PlaceManager.
      Returns:
      the current Place instance
    • place

      public Place place(String path)
    • start

      public void start()
      Initializes the PlaceManager by setting up necessary event bindings and navigating to the place that corresponds to the current URL.

      This method performs the following steps:

      1. Calls bindClickHandler() to set up click event handling for links, enabling SPA navigation by preventing default link behavior.
      2. Calls bindHistoryHandler() to set up handling for browser's history state changes.
      3. Determines the initial place to navigate to based on the current location's path by invoking findPlace().
      4. Calls gotoPlace() to transition to the identified place. If successful, updates browser history using updateHistory(). If unsuccessful, logs an error indicating the inability to start with the resolved place.
    • goTo

      public void goTo(String route, String... values)
      Navigates to a route with parameter values. Values are encoded automatically — pass raw/decoded values.

      Example:

      placeManager.goTo("/resource/:name", "my/file");
      placeManager.goTo("/time/:area/:location", "America", "New_York");
      
      Parameters:
      route - the route template with :param placeholders
      values - the raw parameter values in the order they appear in the route
      Throws:
      IllegalArgumentException - if the number of values doesn't match the number of parameters
      See Also:
    • goTo

      public void goTo(String path)
      Navigates to a specific path within the application. The method resolves the corresponding place to the given path, attempts to move to the associated page, and logs an error if the navigation fails.

      No encoding is applied — the path is used as-is. If the path contains parameter values with special characters, encode them first using Parameter.encodePath(String, String...) or Parameter.encode(String).

      Parameters:
      path - the string representation of the target path to navigate to
    • href

      public String href(String route, String... values)
      Generates an absolute URL for a route with parameter values. Values are encoded automatically — pass raw/decoded values.

      Example:

      String url = placeManager.href("/resource/:name", "my/file");
      // returns the absolute URL with "my%2Ffile" in the path
      
      Parameters:
      route - the route template with :param placeholders
      values - the raw parameter values in the order they appear in the route
      Returns:
      the absolute URL for the corresponding place, or "#" if not found
      Throws:
      IllegalArgumentException - if the number of values doesn't match the number of parameters
      See Also:
    • href

      public String href(String path)
      Generates an absolute URL for the given path based on the application's base URL and routing configuration. If the specified path corresponds to an existing place, the method returns the absolute URL for that place. If the path does not correspond to an existing place, the method returns a fallback URL (e.g., "#").

      No encoding is applied — the path is used as-is. If the path contains parameter values with special characters, encode them first using Parameter.encodePath(String, String...) or Parameter.encode(String).

      Parameters:
      path - the path for which the URL is to be generated; typically represents a route within the application
      Returns:
      the absolute URL as a String for the corresponding place if found, or a fallback URL ("#") if the place does not exist
    • places

      public List<Place> places()
      Returns an unmodifiable list of all registered places.