Designing a Phoenix Framework web application using LiveView for a dynamic search interface involves several key components. Below is an architectural guide to help you structure your application effectively.
Overview
We aim to create a responsive user interface that provides:
- Homepage with a Search Bar:
- Real-time autocomplete suggestions as the user types.
- Search Results Page:
- Displays detailed search results.
- Includes pagination.
- Offers filtering options.
Application Architecture
1. Project Structure
Your Phoenix application will follow the standard structure with some additions:
my_app/
├── lib/
│ ├── my_app/
│ │ ├── web/
│ │ │ ├── live/
│ │ │ │ ├── search_live/
│ │ │ │ │ ├── index.ex
│ │ │ │ │ ├── results.ex
│ │ │ │ │ └── components/
│ │ │ │ │ ├── autocomplete_component.ex
│ │ │ │ │ ├── pagination_component.ex
│ │ │ │ │ └── filters_component.ex
│ │ │ ├── templates/
│ │ │ └── views/
│ │ └── ...
│ └── ...
└── ...
2. Contexts
Use Phoenix contexts to separate your domain logic:
- Search Context (
MyApp.Search):
- Functions to handle search queries.
- Interfaces with the database.
- Implements filtering and pagination logic.
3. LiveViews and Components
SearchLive.Index LiveView:
- Renders the homepage with the search bar.
- Handles real-time autocomplete.
SearchLive.Results LiveView:
- Displays the search results.
- Manages pagination and filtering.
- Components:
- AutocompleteComponent: Manages and displays autocomplete suggestions.
- PaginationComponent: Handles pagination controls.
- FiltersComponent: Provides filtering options to the user.
Implementation Details
1. Real-time Autocomplete on Homepage
SearchLive.Index LiveView:
-
Mounting:
def mount(_params, _session, socket) do
{:ok, assign(socket, query: "", suggestions: [])}
end
-
Template:
<div>
<form phx-change="suggest" phx-submit="search">
<input type="text" name="query" value="<%= @query %>" placeholder="Search..." autocomplete="off" />
</form>
<%= if @suggestions != [] do %>
<ul>
<%= for suggestion <- @suggestions do %>
<li><%= suggestion %></li>
<% end %>
</ul>
<% end %>
</div>
-
Event Handlers:
def handle_event("suggest", %{"query" => query}, socket) do
suggestions = MyApp.Search.get_autocomplete_suggestions(query)
{:noreply, assign(socket, suggestions: suggestions, query: query)}
end
def handle_event("search", %{"query" => query}, socket) do
{:noreply, push_redirect(socket, to: Routes.search_results_path(socket, :index, query: query))}
end
Autocomplete Logic:
-
Function in Search Context:
def get_autocomplete_suggestions(query) do
# Use case-insensitive matching and limit results.
from(s in SearchableSchema,
where: ilike(s.field, ^"%#{query}%"),
select: s.field,
limit: 10
)
|> Repo.all()
end
2. Displaying Search Results with Pagination and Filtering
SearchLive.Results LiveView:
-
Mounting:
def mount(%{"query" => query}, _session, socket) do
{:ok, fetch_results(socket, query, %{}, 1)}
end
-
Data Assignment:
defp fetch_results(socket, query, filters, page) do
%{results: results, total_pages: total_pages} = MyApp.Search.search(query, filters, page)
assign(socket, query: query, results: results, filters: filters, page: page, total_pages: total_pages)
end
-
Template:
<div>
<h1>Results for "<%= @query %>"</h1>
<%= live_component @socket, FiltersComponent, id: :filters, filters: @filters %>
<ul>
<%= for result <- @results do %>
<li><%= result.name %></li>
<% end %>
</ul>
<%= live_component @socket, PaginationComponent, id: :pagination, page: @page, total_pages: @total_pages %>
</div>
-
Event Handlers:
def handle_event("filter", %{"filters" => filters}, socket) do
{:noreply, fetch_results(socket, socket.assigns.query, filters, 1)}
end
def handle_event("paginate", %{"page" => page}, socket) do
{:noreply, fetch_results(socket, socket.assigns.query, socket.assigns.filters, String.to_integer(page))}
end
Search Logic with Pagination and Filtering:
-
Function in Search Context:
def search(query, filters, page) do
base_query =
from(s in SearchableSchema,
where: ilike(s.field, ^"%#{query}%")
)
filtered_query = apply_filters(base_query, filters)
paginated_query = filtered_query |> Repo.paginate(page: page)
%{
results: paginated_query.entries,
total_pages: paginated_query.total_pages
}
end
defp apply_filters(query, filters) do
Enum.reduce(filters, query, fn
{"category", value}, query -> from(q in query, where: q.category == ^value)
{"date_range", %{"start" => start_date, "end" => end_date}}, query ->
from(q in query, where: q.inserted_at >= ^start_date and q.inserted_at <= ^end_date)
_, query -> query
end)
end
Pagination Component:
3. Filtering Options
Filters Component:
-
Template:
<form phx-change="filter">
<!-- Example filter: Category -->
<select name="filters[category]">
<option value="">All Categories</option>
<%= for category <- @categories do %>
<option value="<%= category %>"><%= category %></option>
<% end %>
</select>
<!-- Additional filters can be added here -->
</form>
-
Mounting and Assignment:
def mount(socket) do
categories = MyApp.Search.list_categories()
{:ok, assign(socket, categories: categories)}
end
4. Database Considerations
- Indexes:
- Ensure database indexes are in place for fields used in
WHERE clauses to optimize search performance.
- Full-text Search:
- For more advanced search capabilities, consider implementing full-text search using PostgreSQL's
tsvector or integrating with Elasticsearch.
5. LiveView Best Practices
- Minimize Data Transfer:
- Only send necessary data to the client to keep LiveView efficient.
- Use
handle_event Wisely:
- Debounce events if necessary to reduce server load.
- Error Handling:
- Provide feedback to users for long-running queries or errors.
Additional Tips
- User Experience:
- Implement loading indicators for search results.
- Use debounce on autocomplete to prevent excessive database calls.
- Testing:
- Write comprehensive tests for LiveViews and contexts.
- Deployment:
- Ensure your server can handle WebSocket connections required by LiveView.
Conclusion
By structuring your Phoenix application with dedicated contexts and LiveViews, you create a maintainable and scalable codebase. Utilizing LiveView's real-time capabilities enhances user experience with instant feedback through autocomplete suggestions, dynamic pagination, and filtering without full page reloads.
Remember to monitor performance, especially with real-time features, and optimize database queries accordingly. With this architecture, you set a solid foundation for a responsive and interactive web application using Phoenix LiveView.