As we discussed in previous parts of this documentation, we can use domino-history to listen for the changes applied to the URL throw the StateHistory.fireState(...) function, But in most of the cases in a listener we will be interested in specific changes and any change that is applied, because most likely we are listening to those changes to take actions based on the change or the new URL value, Domino-history API provide a way to actually filter what changes to the URL will trigger a specific listener, this is achieved through TokenFilters.
A TokenFilter works like a condition we check over the new URL value after it is changed, and if the condition pass we call the listener associated with the TokenFilter, When we define a listener without a TokenFilter we are actually using a default TokenFilter which is the `AnyTokenFilter` and this filter simply return always True since it just means any change.
Domino-history comes with a long list of a ready to use built-in token filters that we will list below, but it is not limited to those filters, the user can still implement his own filters, this because the TokenFilter is an interface and any implementation of this interface is acceptable. For example the following custom TokenFilter :
import org.dominokit.domino.history.HistoryToken;
import org.dominokit.domino.history.TokenFilter;
public class UserTokenFilter implements TokenFilter {
private final UserContext userContext;
public UserTokenFilter(UserContext userContext) {
this.userContext = userContext;
}
@Override
public boolean filter(HistoryToken token) {
if(token.containsPath("secure")){
return userContext.isUserLoggedIn();
}
return true;
}
public static class UserContext {
public boolean isUserLoggedIn(){
//Some actual checks goes here to check if the user is actually logged in or not and return true or false based on that
return true;
}
}
}
Then we can use it just like any other token filter:
stateHistory.listen(new UserTokenFilter(new UserTokenFilter.UserContext()), state -> {
//Do something if a logged-in user navigated to a secure path
});
Here the TokenFilter checks if the user is trying to navigate to a secure path, then it assumes the user should be logged in to return true or else will return false, but if the path isn't secure it won't check for a user login and will just return true.
There is no restriction on what you can with a custom TokenFilter, except as we will discuss later for the use with wildcards when try to normalize a token to match the expressions with the matching values from the token.
Below is a list of the built-in token filters: