Skip to content

A command palette implementation for Rails with Hotwire and Meilisearch

License

Notifications You must be signed in to change notification settings

traels-it/kommandant

Repository files navigation

Kommandant logo

Do you need a command palette? Would you like to do as little work as possible to get one? Then you've come to the right place!

Kommandant is a command palette engine for Rails. It is built with Hotwire for the slick interaction and Meilisearch as the super-fast search engine.

Installation

You need to have Meilisearch installed on your system. They have some pretty nice docs describing how right here.

Kommandant depends on the meilisearch-rails gem, which needs to be configured:

# config/initializers/meilisearch.rb
MeiliSearch::Rails.configuration = {
  meilisearch_url: ENV.fetch("MEILI_HTTP_ADDR") { "http://localhost:7700" },
  meilisearch_api_key: ENV.fetch("MEILI_MASTER_KEY") { "MASTER_KEY" },
  per_environment: true
}

Now run

bundle add kommandant
bin/rails kommandant:install:migrations
bin/rails db:migrate

and add the following line app/assets/application.css

*= require kommandant

Pin kommandant in config/importmap.rb to get access to the Stimulus controllers. Kommandant currently only support importmap, but PRs are very welcome.

pin "kommandant", to: "kommandant.js"

Register the Stimulus controllers in app/javascript/controllers/index.js

import { CommandPalette, KeyboardNavigation } from "kommandant"
application.register("command-palette", CommandPalette)
application.register("keyboard-navigation", KeyboardNavigation)

Mount the engine in your config/routes.rb

Rails.application.routes.draw do
  [...]

  mount Kommandant::Engine => "/kommandant"
end

And finally run:

bin/rails generate kommandant:install

You might want to configure the gem. As Kommandant has been extracted from one of our apps, we have tailored the default configuration to this app. You might want to turn some stuff off.

# config/initializers/kommandant.rb
Kommandant.configure do |config|
  # Commands are a central part of Kommandant. They are loaded from a json file at "config/kommandant/commands.json" by default. We will go into more detail about commands further down the page.
  # config.commands_path = "your/custom/path"
  
  # When meilisearch returns a result, it might include items, that the current user is not allowed to see. You can filter these results with a lamda. This setting has no default, but below is an example that works with cancancan.
  # config.search_result_filter_lambda = ->(current_ability, resource) { current_ability.can?(:show, resource) }
  
  # Another search result filter. We use this to allow admins, who are impersonating users, access to all their commands. This setting has no default.
  # config.admin_only_filter_lambda = ->(current_user, current_admin) { current_user.admin? || current_admin }

  # If you want Kommandant to use a different parent controller, this is the setting for you. Defaults to ApplicationController
  # config :parent_controller = "YourVerySpecialController"
  
  # We assume there is a logged in user and therefore a current_user method. The name of this method can be set here. It defaults to current_user.
  # config.current_user_method = current_account

  # Kommandant highlights search terms by default. Uncomment this to turn it off. This only turns highlighting off, when using the views provided by the gem. You can still highlight terms if providing your own partial.
  # config.highligt_search_term = false
  
  # If you use Kredis, Kommandant can display the current user's most recently used commands. It requires your user model to have kredis_unique_list called recent_commands. If you don't use Kredis or do not want this behavior, it can be disabled. It defaults to being enabled.
  # class User < ApplicationRecord
  # kredis_unique_list :recent_commands, limit: 5
  # config.recent_commands.enabled = false

  # When a search returns a lot of results, it can be useful to paginate them. We use Pagy by default to handle this. If you do not use Pagy, this functinality can be turned off or configured to suit your needs. It defaults to being enabled.
  # config.pagination.enabled = false
  # config.pagination.items_per_page = 10 # defaults to 10
  # config.pagination.pagination_lambda = ->(results, items, controller) { controller.send(:pagy_array, results, items: items) }
  # config.pagination.info_label_lambda = ->(pagination, controller) { controller.send(:pagy_info, pagination).html_safe }
  # config.pagination.module = "Pagy::Frontend"
  end
end

Setting up the views

Kommandant supplies two Stimulus controllers, command-palette and keyboard-navigation, containing all the JavaScript necessary to show, hide and navigate the command palette. This requires a data-controller attribute that catches all the events nested under its element. We recommend setting this on the body tag of your layout, so that all events are caught.

Stimulus data-action attributes are used to trigger the command palette. There are no default keybindings for this. Instead we utilize the keyboard event filters in Stimulus to trigger the toggle action. You can use this to set any keyboard shortcut you want - as well as trigger it by clicking a button or any other event, you want to display the palette.

<body
  data-controller="command-palette keyboard-navigation"
  data-action="keydown.meta+k->command-palette#toggle keydown.ctrl+k->command-palette#toggle keydown.esc->command-palette#hide keydown.down->keyboard-navigation#down keydown.up->keyboard-navigation#up keydown.enter->keyboard-navigation#select">
  ...
</body>

Usage

Commands

An open command palette with a list of commands Commands are the building blocks of the command palette. Any action in the command palette is backed by a command, implemented in the Kommandant::Command class, which inherits from ApplicationRecord.

Screenshot of the web UI

There is only the one model, but the commands act in two distinct manners referred to as the basic and the resource command. In the future these might be extended further and split into two (or more) different models.

The basic command

A log out command

A basic command is meant to hit a controller without a specific resource. It will mostly be used for simple actions like logging out, toggling some setting or navigation. It requires all the fields below to work as expected.

translations use I18n under the hood. Kommandant uses I18n.available_locales to generate these form inputs. Only name needs to be filled out here.

icon is the name of an icon you want displayed with the command in the command palette. You must supply your own partial at kommandant/shared/icons/#{name of your icon}.html.erb to render the icon. This partial is given the icon name in a local variable called icon. See more details under the Icons section

path is the path, that the command palette goes to when selected. In the example above, selecting the command will fire a request to the app's logout route. The existing logic takes over and logs the user out in exactly the same way as clicking through the UI.

http_method should match http method expected of the controller action, you want to hit.

The resource command

A selected resource command A resource command search result

Most of your commands will be resource commands. They operate on a database backed model that has been setup to be indexed by meilisearch.

class Customer < ApplicationRecord
  include MeiliSearch::Rails

  meilisearch do
    # This makes the customer's id searchable
    attribute :id
    attribute :name do
      # And this lets you find it by its legal_entity association's name
      legal_entity.name
    end
  end

  belongs_to :legal_entity
end

Basic example of indexing a model. For more details see the meilisearch-rails docs

Any time a new model gets a meilisearch configuration or an attribute is modified, meilisearch must be updated.

MeiliSearch::Rails::Utilities.reindex_all_models

Resource command form Again all the fields below are required to make the command function as excpected. However this type of command has an extra step. Once the user has selected a resource command, they will be presented with a new search bar, that allows them to search all this resource.

icon and http_method work exactly as for the basic command.

path is inferred by Kommandant when left blank. This is the path the user is redirected to, when the command is selected. Only change this if you want to handle rendering the command palette's response yourself or you want to add another step to your command, that Kommandant does not support.

resource_class is the model whose attributes you want to search Meilisearch for. The select is populated with all descendants of ApplicationRecord.

search_result_text_method calls a method on an instance of the resource class (e.g. Customer#name) that returns the text you want displayed in a search result.

translations can have an extra key called placeholders. This does what it says on the tin. It is highly recommended to tell the users what they can search for here.

redirect_path is used when the path cannot be inferred from the model's class name. The path is inferred like this:

"/#{command.resource_class.downcase.pluralize}/#{resource.id}"

admin_only is used to filter out commands that only the admin is allowed to use. The admin_only_filter_lambda in the configuration is used here.

Icons

Kommandant assumes the presence of a partial in app/views/kommandant/shared/icons/_command.html.erb. This partial has the responsibility for rendering the icons named in each command. An example implementation could be as follows.

<% if lookup_context.exists?("kommandant/shared/icons/#{icon.underscore}", [], true) %>
  <%= render "kommandant/shared/icons/#{icon.underscore}" %>
<% end %>

This renders any partial named after the icon (e.g. the partial kommandant/shared/icons/_user.html.erb if the command has defined user as its icon). You can also use this to use a ViewComponent for your icons:

<%= render UI::IconComponent.new(name: icon, width: :fixed, size: :large) %>

Tasks

The gem comes with several tasks for reindexing and clearing the search engine. You will probably use rails kommandant:reindex the most. We recommend you run this on every deploy to make sure the search engine contains the data you expect.

rails kommandant:clear_command_index                 # Clears the Kommandant commands from the search engine
rails kommandant:clear_indexes                       # Clears the search engine of all commands and models
rails kommandant:clear_model_index                   # Clears the search engine of all models set up with Kommandant
rails kommandant:install:migrations                  # Copy migrations from kommandant to application
rails kommandant:reindex                             # Reindexes all commands and models
rails kommandant:reindex_commands                    # Reindexes all commmands defined in the commands json file (or w...
rails kommandant:reindex_models                      # Reindexes all models set up with Kommandant

Future improvements

We will continue to improve this gem. Some of the things on the planning board are:

  • Better support for navigation commands
  • Build own macros for indexing models in meilisearch
  • Generate views task

Things that (probably) won't happen

  • Different search backends, like ElasticSearch. We don't need it ourselves, so we don't want the maintenance overhead. But we will welcome PRs that supply this as a plugin somehow!
  • Optional translations. We use translations in all our projects. If you hate having to supply translations, PRs are welcome.

Development

You either need to install and run meilisearch and redis or use the included docker-compose.yml.

docker compose up -d

-d runs the container detached, so you can use your terminal for other things.

Kommandant uses TailwindCSS. When developing you can run the following command to watch views for new classes to be added:

tailwindcss -i app/assets/stylesheets/kommandant/application.tailwind.css -o app/assets/builds/kommandant.css -w

Any class needs to be prefixed with kommandant (e.g. kommandant-bg-black) to prevent collisions with changes in the parent app's Tailwind configuration.

Contributing

Contributions are welcome. We expect you to treat others well.

License

The gem is available as open source under the terms of the MIT License.