Skip to content

Commit

Permalink
Merge pull request solidusio#5595 from solidusio/elia+rainer/admin/co…
Browse files Browse the repository at this point in the history
…ntributing

[admin] Document SolidusAdmin intended usage and how to contribute
  • Loading branch information
elia authored Feb 8, 2024
2 parents 628c615 + c758304 commit 020f3c2
Show file tree
Hide file tree
Showing 8 changed files with 431 additions and 14 deletions.
60 changes: 57 additions & 3 deletions admin/README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,59 @@
# solidus_admin (WIP)
# Solidus Admin

A Rails engine that provides an administrative interface to the Solidus ecommerce platform.

## Overview

- Based on ViewComponent and TailwindCSS
- Uses StimulusJS and Turbo for interactivity
- Works as a separate engine with its own routes
- Uses the same models as the main Solidus engine
- Has its own set of controllers

## Installation

`solidus_admin` is included by default in new stores generated with Solidus 4.3 or later, as well as those generated from the main branch.

`solidus_admin` can be added to existing stores by bundling it in the Gemfile and running the installer generator:

```bash
bundle add solidus_admin
bin/rails g solidus_admin:install
```

If you're using an authentication system other than `solidus_auth_devise` you'll need to manually configure authentication methods (see api documentation for `SolidusAdmin::Configuration`).

If you encounter the error `couldn't find file 'solidus_admin/tailwind.css'` when loading admin pages, you need to manually build the `solidus_admin` tailwind CSS styles.
This issue typically occurs when you bundle Solidus from a GitHub branch or from the local filesystem, or with the sandbox application.
Please see [Customizing tailwind](docs/customizing_tailwind.md) for more information.

### Components

See [docs/contributing/components.md](docs/components.md) for more information about components.

### Using it alongside `solidus_backend`

`solidus_backend` is the current admin interface for Solidus. `SolidusAdmin` is under development, acts as a drop-in replacement for `solidus_backend` and will eventually replace it. It's designed to gradually take over existing functions.

For now, you can use both `solidus_backend` and `SolidusAdmin` in the same application. To do this, mount the `SolidusAdmin` engine before `Spree::Core::Engine`.

You can use a route `constraint` to replace any `solidus_backend` routes with `SolidusAdmin` routes.

By default, `SolidusAdmin` routes are turned off if a cookie named `solidus_admin` is set to `false`, or if a query parameter named `solidus_admin` is set to `false`. This lets you switch between the two admin interfaces easily.

This constraint is set up in the application's routes file, so you can easily change it:

```ruby
# config/routes.rb
mount SolidusAdmin::Engine, at: '/admin', constraints: ->(req) {
$redis.get('solidus_admin') == 'true' # or any other logic
}
```

### Authentication & Authorization

- Solidus Amidn delegates authentication to `solidus_backend` and relies on `solidus_core` for authorization.

## Development

- [Customizing tailwind](docs/customizing_tailwind.md)
Expand All @@ -10,8 +62,7 @@ A Rails engine that provides an administrative interface to the Solidus ecommerc

### Adding components to Solidus Admin

When using the component generator from within the admin folder it will generate the component in the library
instead of the sandbox application.
Solidus Admin components can be generated with the `solidus_admin:component`generator:

```bash
# the `solidus_admin/` namespace is added by default
Expand All @@ -23,6 +74,9 @@ bin/rails admin g solidus_admin:component foo
create spec/components/solidus_admin/foo/component_spec.rb
```

Please note that when using the component generator from within the admin folder it will generate the component in the library
instead of the sandbox application.

## Releasing

1. Update the version in `lib/solidus_admin/version.rb`
Expand Down
109 changes: 109 additions & 0 deletions admin/docs/components.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
# Components

Components are the main building blocks of the admin interface. They are implemented as ViewComponents and are rendered directly by controllers.

The following documentation assumes familiariry with ViewComponents. If you are not please refer to the [ViewComponent documentation](https://viewcomponent.org/guide/).

There are two types of components:

- **UI components** are the building blocks of the interface. Tipically, they are small components that are used to build more complex components and are generic enough to be reused in various contexts. UI components are located under the `app/components/solidus_admin/ui` folder.
- **Page components** are the primary components rendered by the controllers. Generally, they are full-page components rendered directly by the controllers. They are located under the `app/components/solidus_admin` directory following the naming convention of the controller and action names they are used in. For example `app/components/solidus_admin/orders/index/component.rb` is the component that is rendered by the `SolidusAdmin::OrdersController#index` action.

## Generating components

Components can be generated using the `solidus_admin:component` generator combined with the `bin/rails` command from the Solidus repository.

```shell
$ bin/rails admin g solidus_admin:component foo
create app/components/solidus_admin/foo/component.rb
create app/components/solidus_admin/foo/component.html.erb
create app/components/solidus_admin/foo/component.yml
create app/components/solidus_admin/foo/component.js
```

Using `bin/rails admin` will run the generator from the `solidus_admin` engine, instead of the sandbox application.

## Coding style

For UI components in particular, it's preferable to accept only simple Ruby values in the initializer and use alternative constructors to accept more complex objects. This makes components easier to use and test. For example:

```ruby
# bad

class SolidusAdmin::UI::OrderStatus::Component < ViewComponent::Base
def initialize(order:)
@order = order
end
end

# good

class SolidusAdmin::UI::OrderStatus::Component < ViewComponent::Base
def initialize(status:)
@status = status
end

def self.for_order(order)
new(status: order.status)
end
end
```

For style variations within the component we use the term `scheme` rather than `variant` to avoid confusion with product variants.

For size variations we use the term `size` with single letter values, e.g. `s`, `m`, `l`, `xl`, `xxl`.

For text content we use the term `text` rather than `name` to avoid confusion with the `name` attribute of the HTML tag.

## Component registry

Components are registered in the `SolidusAdmin::Config.components` registry. This allows replacing components for customization purposes and components deprecation between versions.

To retrieve component classes from the registry, use the `component` helper within controllers and components that inherit from `SolidusAdmin::BaseComponent` or include `SolidusAdmin::ComponentHelper`. For example, `component('ui/button')` will fetch `SolidusAdmin::UI::Button::Component`.

## When to use UI vs. Page components

Generally new components are built for a specific controller action and are used only within that action. In such cases, it's better to use a Page component and define it under the namespace of the action, e.g. `app/components/solidus_admin/orders/index/payment_status/component.rb`.

If a component is used by multiple actions of the same controller it can be moved to the controller namespace, e.g. `app/components/solidus_admin/orders/payment_status/component.rb`.

When a component is used by multiple controllers, you can either duplicate it in multiple places or move it to the `ui` namespace.

Although it may seem counterintuitive, duplicating the component can often be beneficial. This allows you to modify the component in one place without affecting other components that might be using it. Over time, the two copies may share enough generic code that it can be extracted into a UI component.

UI components should be very generic and reusable. However, they should not try to anticipate all possible use cases. Instead, they should be extracted from existing components that are already used in multiple places. This has proven to be the most effective way to build UI components. We've found that trying to anticipate theoretical use cases often leads to over-engineered code that eventually needs to be adapted to the actual use cases or is never used at all.

## Naming conventions

The project uses a naming convention for components that slightly deviates from ViewComponent defaults. This is done to simplify renaming components and moving them around.

All files related to a component have a base name of `component`, each with its own extension. These files are placed in a folder named after the component class they define.


E.g. `app/components/solidus_admin/orders/index/payment_status/component.rb` defines the `SolidusAdmin::Orders::Index::PaymentStatus::Component` class.

With this approach, renaming a component is as simple as renaming the folder and the class name, without the need to change the names of all the files.

## Translations

Components can define their own translations in the `component.yml` file and they're expected to be self contained. This means that translations defined in `solidus_core` should not be used in components.

Please refer to the [ViewComponent documentation](https://viewcomponent.org/guide/translations.html) for more information.

## Previews and Lookbook

For UI components we leverage [ViewComponent previews](https://viewcomponent.org/guide/previews.html) combined with [Lookbook](https://lookbook.build) to provide a live preview of the component. This approach is highly beneficial for understanding the component's appearance and how it can be modified using different arguments.

Creating previews for page components can be challenging and prone to errors, as they often require a more complex context for rendering. Therefore, we typically don't use previews for page components, except for the most basic ones. However, if a component has a wide range of arguments and we want to cover all combinations, we might create a preview for it.

In order to inspect previews it's enough to visit `/lookbook` in the browser while the server is running.

## Testing

Testing methods for components vary depending on whether they are UI or Page components. UI components are tested in isolation, while Page components, which often require a more complex context, are tested through feature specs.

For UI components, we use previews to achieve maximum coverage. This approach is sufficient for most basic components, but more complex components may require additional specs. This method has proven to minimize maintenance and code churn in the spec code, and it avoids repeating the code needed to render the component with different arguments.

Page components are tested in the context of the controller action they are used in. For example, `admin/spec/features/orders_spec.rb` covers interactions with the order listing and indirectly tests the `SolidusAdmin::Orders::Index::Component` class, among others.
We've found this to be the most effective way to test page components, as recreating the context needed for them in isolation can be difficult and prone to errors.
However, this is not a hard rule. If a Page component needs to be tested in isolation, or if a UI component requires a more complex context, you can always write additional specs.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Customizing view components
# Customizing components

Solidus Admin uses [view components](https://viewcomponent.org/) to render the views. Components are
a pattern for breaking up the view layer into small, reusable pieces, easy to
Expand Down
146 changes: 146 additions & 0 deletions admin/docs/index_pages.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
# Adding index pages

Index pages are common in the admin interface, and they are used to display a list of records for a specific model.

Since these pages often have a similar appearance, we have a dedicated component to build them. This component helps avoid writing repetitive boilerplate code.

## The `index` action

The `index` action is the standard action used to display index pages. It's a standard `GET` action that renders the `index` component.

To support search scopes and filters the controller should include the `SolidusAdmin::ControllerHelpers::Search` module and call
`apply_search_to` as follows:

```ruby
class SolidusAdmin::UsersController < SolidusAdmin::BaseController
include SolidusAdmin::ControllerHelpers::Search

def index
users = apply_search_to(Spree.user_class.order(id: :desc), param: :q)
# ...
```

For pagination support, the index action should also call the `set_page_and_extract_portion_from` method provided by the `geared_pagination` gem. This method sets the `@page` instance variable to the paginated collection and returns the portion of the collection to be displayed on the current page.

```ruby
def index
users = apply_search_to(Spree.user_class.order(id: :desc), param: :q)
set_page_and_extract_portion_from(users)
# ...
```

Finally, the index action should render the `index` component passing the `@page` instance variable as the `collection` prop.

```ruby
def index
users = apply_search_to(Spree.user_class.order(id: :desc), param: :q)
set_page_and_extract_portion_from(users)
render component('users/index').new(page: @page)
end
```

## The `ui/pages/index` component

The `ui/pages/index` component is an abstract component that provides sensible defaults for index pages. It also offers template methods that can be used to customize the behavior of these pages.

We recommend examining existing index pages and the UI component itself to understand how they work. In this section, we'll cover the most important aspects.

The index component requires only the `page` argument during initialization, all other parameters are provided through template methods.

```ruby
class SolidusAdmin::Users::Index < Solidus::Admin::UI::Pages::Index
def model_class
Spree.user_class
end
end

render component('users/index').new(page: @page)
```

## Batch Actions

Batch actions are operations that can be performed on multiple records simultaneously. The index page internally uses the `ui/table` component and depends on the `batch_actions` method to render the batch actions dropdown.

In the component, batch actions are provided as an array of hashes, with each hash representing a single batch action. Each hash must contain the following keys:

- `label`: the name of the batch action, this will be used as the label of the dropdown item
- `icon`: the remix icon-name to be used as the icon of the dropdown item (see the `ui/icon` component for more information)
- `action`: the name of the action to be performed when the batch action is selected. It can be a URL or a path
- `method`: the HTTP method to be used when performing the action, such as `:delete`

The `batch_actions` method is called in the context of the controller, so you can use any controller method or helper to build the batch actions.

Batch actions will be submitted to the specified action with an `id` parameter containing the IDs of the selected records. Using `id` as the
parameter name allows the same action to support both batch and single-record actions for standard routes.

E.g.

```ruby
# in the component
def batch_actions
[
{
label: "Delete",
icon: "trash",
action: solidus_admin.delete_admin_users_path,
method: :delete
}
]
end
```

```ruby
# in the controller
def delete
@users = Spree.user_class.where(id: params[:id])
@users.destroy_all
flash[:success] = "Admin users deleted"
redirect_to solidus_admin.users_path, status: :see_other
end
```

## Search Scopes

Search scopes are used to filter the records displayed on the index page. The index page internally uses the `ui/table` component and relies on the `scopes` method to render the search scope buttons.

In the component, search scopes are provided as an array of hashes, with each hash representing a single search scope. Each hash must contain the following keys:

- `label`: the name of the search scope, used as the label of the button
- `name`: the name of the search scope, sent via `q[scope]` parameter when the button is clicked
- `default`: whether this is the default search scope, used to highlight the button when when the page is loaded

On the controller side, search scopes can be defined with the `search_scope` helper, provided by `SolidusAdmin::ControllerHelpers::Search`. This helper takes a name, an optional `default` keyword argument, and a block. The block will be called with the current scope and should return a new ActiveRecord scope.
E.g.

```ruby
module SolidusAdmin
class UsersController < SolidusAdmin::BaseController
include SolidusAdmin::ControllerHelpers::Search

search_scope(:customers, default: true) { _1.left_outer_joins(:role_users).where(role_users: { id: nil }) }
search_scope(:admin) { _1.joins(:role_users).distinct }
search_scope(:with_orders) { _1.joins(:orders).distinct }
search_scope(:without_orders) { _1.left_outer_joins(:orders).where(orders: { id: nil }) }
search_scope(:all)

def index
users = apply_search_to(Spree.user_class.order(id: :desc), param: :q)
# ...
```

## Filters

Filters are used to narrow down the records displayed on the index page. The index page internally uses the `ui/table/ransack_filter` component and depends on the `filters` method to render the filters dropdown.

In the component, filters are represented as an array of hashes, with each hash representing a single filter. Each hash must contain the following keys:


- `label`: the name of the filter, used as the label in the filter bar
- `attribute`: the name of the ransack-enabled attribute to be filtered
- `predicate`: the name of the ransack predicate to be used, e.g. `eq`, `in`, `cont`
- `options`: an array of options to be used for the filter, in the standard rails form of `[["label", "value"], ...]`

On the controller side it's enough to add ransack support to the index action by including `SolidusAdmin::ControllerHelpers::Search` and calling
`apply_search_to` as explained in the [Index action](#index-action) section.

On the controller side, you simply need to add Ransack support to the index action by including the `SolidusAdmin::ControllerHelpers::Search` module and calling the `apply_search_to` method, as explained in the [Index action](#index-action) section.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Customizing the main navigation
# Customizing the Menu

You are allowed to add your custom links to the main navigation. To do so, you can access `SolidusAdmin::Config.menu_items` in an initializer:

Expand Down
Loading

0 comments on commit 020f3c2

Please sign in to comment.