diff --git a/admin/README.md b/admin/README.md index 218a30d9e7e..b561d7edd74 100644 --- a/admin/README.md +++ b/admin/README.md @@ -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) @@ -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 @@ -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` diff --git a/admin/docs/components.md b/admin/docs/components.md new file mode 100644 index 00000000000..cc32ea2c6ed --- /dev/null +++ b/admin/docs/components.md @@ -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. diff --git a/admin/docs/customizing_view_components.md b/admin/docs/customizing_components.md similarity index 99% rename from admin/docs/customizing_view_components.md rename to admin/docs/customizing_components.md index 79e1169fc15..f95a1def3dc 100644 --- a/admin/docs/customizing_view_components.md +++ b/admin/docs/customizing_components.md @@ -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 diff --git a/admin/docs/index_pages.md b/admin/docs/index_pages.md new file mode 100644 index 00000000000..a17379d5529 --- /dev/null +++ b/admin/docs/index_pages.md @@ -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. diff --git a/admin/docs/customizing_menu_items.md b/admin/docs/menu_items.md similarity index 97% rename from admin/docs/customizing_menu_items.md rename to admin/docs/menu_items.md index 64cb3b384ec..cccef8a3179 100644 --- a/admin/docs/customizing_menu_items.md +++ b/admin/docs/menu_items.md @@ -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: diff --git a/admin/docs/stimulusjs.md b/admin/docs/stimulusjs.md new file mode 100644 index 00000000000..1c3a7c50537 --- /dev/null +++ b/admin/docs/stimulusjs.md @@ -0,0 +1,85 @@ +# StimulusJS + +This project uses [StimulusJS](https://stimulusjs.org) to add interactivity to the admin interface. + +## Using ther `stimulus_id` helper + +All JavaScript files are imported using `import-maps`, eliminating the need for compilation. + +Any `component.js` file is automatically loaded as a StimulusJS controller. The component path is used as the identifier, which is achieved by using `parameterize` and replacing `/` with `--`. +For example, `app/components/solidus_admin/foo/component.js` is loaded as `solidus-admin--foo`.. + +To simplify the use of StimulusJS controllers in components, a `stimulus_id` helper is provided. +This helper ensures that the controller identifier is correctly used every time. + +```erb +
-foo-value="123" +> + ... +
+``` + +## Coding Style + +Besides the standard StimulusJS conventions, we have a few additional tricks to make the code more readable and maintainable. + +### Separating the state from the DOM + +Whenever the controller gets beyond trivial we try to separate the state from DOM updates using a `render()` method. + +```js +import { Controller } from "stimulus" + +export default class extends Controller { + static targets = [ "details" ] + + connect() { + this.render() + } + + show() { + this.open = true + } + + render() { + this.detailsTarget.hidden = !this.open + } +} +``` + +### Using values to communicate with the external world + +Values are an excellent tool for communicating with the external environment and representing state. +Any change to them will be reflected in the DOM and the change callbacks provided by StimulusJS are a great way to react to state changes. + +```js +import { Controller } from "stimulus" + +export default class extends Controller { + static values = { open: Boolean } + + connect() { + this.render() + } + + show() { + this.openValue = true + } + + openValueChanged() { + this.render() + } + + render() { + this.detailsTarget.hidden = !this.openValue + } +} +``` + +## Leveraging stimulus-use + +Solidus Admin leverages [stimulus-use](https://github.com/stimulus-use/stimulus-use/), an external library that offers a collection of composable behaviors for Stimulus Controllers. These mixins greatly simplify the work of developers and can be used when adding new components. +For more information, please refer to the project doc. You can also find examples of usage in the Admin codebase (for instance, `useClickOutside` and `useDebounce` mixins are used in admin components). diff --git a/admin/docs/customizing_tailwindcss.md b/admin/docs/tailwindcss.md similarity index 56% rename from admin/docs/customizing_tailwindcss.md rename to admin/docs/tailwindcss.md index 8cd1e0ff12e..a015d35f627 100644 --- a/admin/docs/customizing_tailwindcss.md +++ b/admin/docs/tailwindcss.md @@ -1,4 +1,4 @@ -# Customizing TailwindCSS +# Tailwind CSS for the Admin UI Solidus Admin uses [Tailwind CSS](https://tailwindcss.com/) for styling. The benefit of using Tailwind is that it allows you to customize the look and feel @@ -12,11 +12,28 @@ In case you need to customize the admin's look and feel, or create custom components, you can do so by running Tailwind's build process in your host application. -This process presumes that you have a working knowledge of Tailwind CSS. If you -are not familiar with Tailwind, please refer to the [Tailwind -documentation](https://tailwindcss.com/docs) for more information. +This process presumes that you have a working knowledge of Tailwind CSS. +If you are not familiar with Tailwind, please refer to the [Tailwind documentation](https://tailwindcss.com/docs) for more information. -## Setting up a local TailwindCSS build for Solidus Admin +## Coding Style + +The provided Tailwind CSS configuration is as vanilla as possible, with little to no customizations. +We aim to stay within the boundaries of the default Tailwind CSS classes and avoid custom classes. +Occasionally, we need to add custom styles and in such cases we try to use dynamic square brackets classes. + +CSS classes are all kept in the HTML templates of the components in order to simplify the configuration. + +The few customizations we have added, are through plugins as they support not only classes but also variants. + +## Releasing with a precompiled Tailwind CSS + +Solidus Admin Tailwind CSS stylesheets are precompiled and included in Solidus gems released to Rubygems. + +This means that there's no need to compile the admin Tailwind CSS file in the host application. + +The compiled file is not included in the git repository, but it is generated and incorporated in the gem as part of the `rake release` task (see releasing instructions). This approach completely removes the potential noise created by committing that file to the repository, and the need to keep it updated in pull requests that should affect it. + +## Customizing TailwindCSS In order to customize the admin's look and feel, you'll need to set up a local Tailwind build. This is a two-step process: @@ -48,10 +65,12 @@ Or, to watch for changes and automatically rebuild the CSS file, run: bin/rails solidus_admin:tailwindcss:watch ``` -## Caveats - -### Conflict with sassc-rails +## Caveat: Conflict with sassc-rails Tailwind uses modern CSS features that are not recognized by the sassc-rails extension that was included by default in the Gemfile for Rails 6. In order to avoid any errors like SassC::SyntaxError, you must remove that gem from your Gemfile. *See https://github.com/rails/tailwindcss-rails#conflict-with-sassc-rails.* + +## Development + +The main solidus `bin/dev` command will automatically compile the Tailwind CSS stylesheets and watch for changes. diff --git a/admin/solidus_admin.gemspec b/admin/solidus_admin.gemspec index ff956c3b16e..5878002997a 100644 --- a/admin/solidus_admin.gemspec +++ b/admin/solidus_admin.gemspec @@ -12,11 +12,15 @@ Gem::Specification.new do |s| s.author = 'Solidus Team' s.email = 'contact@solidus.io' - s.homepage = 'http://solidus.io' + s.homepage = 'https://github.com/solidusio/solidus/blob/main/admin/README.md' s.license = 'BSD-3-Clause' s.metadata['rubygems_mfa_required'] = 'true' + s.metadata["homepage_uri"] = s.homepage + s.metadata["source_code_uri"] = "https://github.com/solidusio/solidus/tree/main/api" + s.metadata["changelog_uri"] = "https://github.com/solidusio/solidus/releases?q=%22solidus_admin%2Fv0%22&expanded=true" + s.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(spec|script)/}) end + ["app/assets/builds/solidus_admin/tailwind.css"]