-
Notifications
You must be signed in to change notification settings - Fork 0
Live search #6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: day-2
Are you sure you want to change the base?
Live search #6
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,13 +1,19 @@ | ||
| class SearchController < ApplicationController | ||
| def index | ||
| q = params[:q] | ||
| q = params.fetch(:q, "") | ||
|
|
||
| if q.blank? || q.length < 3 | ||
| if !turbo_frame_request? && q.length < 3 | ||
| return redirect_back(fallback_location: root_path, alert: "Please, enter at least 3 characters") | ||
| end | ||
|
|
||
| @artists = Artist.search(q).limit(10) | ||
| @albums = Album.search(q).limit(10) | ||
| @tracks = Track.search(q).limit(10) | ||
| artists = Artist.search(q).limit(10) | ||
| albums = Album.search(q).limit(10) | ||
| tracks = Track.search(q).limit(10) | ||
|
|
||
| if turbo_frame_request? | ||
| render partial: "preview", locals: {artists:, albums:, tracks:} | ||
| else | ||
| render action: :index, locals: {artists:, albums:, tracks:} | ||
| end | ||
| end | ||
| end | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| import { Controller } from "@hotwired/stimulus"; | ||
|
|
||
| const buildUrlWithQuery = (baseUrl, queryObj = {}) => { | ||
| const queryParams = new URLSearchParams(queryObj); | ||
| if (queryParams.toString().length === 0) return baseUrl; | ||
|
|
||
| return `${baseUrl}?${queryParams.toString()}`; | ||
| }; | ||
|
|
||
| export default class extends Controller { | ||
| static values = { | ||
| debounceTimeout: { type: Number, default: 300 }, | ||
| previewFrameId: String, | ||
| searchPath: String, | ||
| searchParamName: { type: String, default: "q" }, | ||
| }; | ||
|
|
||
| initialize() { | ||
| this.previewFrame = document.getElementById(this.previewFrameIdValue); | ||
| this.onFrameUpdate = this.onFrameUpdate.bind(this); | ||
| } | ||
|
|
||
| connect() { | ||
| this.previewFrame.addEventListener("turbo:frame-load", this.onFrameUpdate); | ||
| } | ||
|
|
||
| disconnect() { | ||
| this.previewFrame.removeEventListener( | ||
| "turbo:frame-load", | ||
| this.onFrameUpdate, | ||
| ); | ||
| } | ||
|
|
||
| get query() { | ||
| return this.element.value; | ||
| } | ||
|
|
||
| get searchUrl() { | ||
| return buildUrlWithQuery(this.searchPathValue, { | ||
| [this.searchParamNameValue]: this.query, | ||
| }); | ||
|
Comment on lines
+39
to
+41
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Вот это красиво. Вроде и запрос конструируем сами, а вроде и всё контролируется извне. |
||
| } | ||
|
|
||
| search() { | ||
| if (this.timer) clearTimeout(this.timer); | ||
|
|
||
| this.timer = setTimeout(() => { | ||
| this.updateFrame(); | ||
| }, this.debounceTimeoutValue); | ||
| } | ||
|
|
||
| updateFrame() { | ||
| if (this.query.length >= 3) { | ||
| this.reloadFrame(); | ||
| } else { | ||
| this.resetFrame(); | ||
| } | ||
| } | ||
|
|
||
| reloadFrame() { | ||
| this.previewFrame.src = this.searchUrl; | ||
| this.previewFrame.reload(); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. А разве нужен отдельный |
||
| } | ||
|
|
||
| resetFrame() { | ||
| this.previewFrame.src = ""; | ||
| this.previewFrame.innerHTML = ""; | ||
| } | ||
|
|
||
| onFrameUpdate() { | ||
| if (this.navigationalElements) { | ||
| this.navigationalElements.forEach((el) => | ||
| el.removeEventListener("turbo:click", this.resetFrame), | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Хорошая идея — использовать |
||
| ); | ||
| } | ||
| this.navigationalElements = this.previewFrame.querySelectorAll("a"); | ||
| this.navigationalElements.forEach((link) => | ||
| link.addEventListener("turbo:click", this.resetFrame), | ||
| ); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -12,6 +12,6 @@ class Album < ApplicationRecord | |||||
| normalizes :title, with: -> { _1.squish } | ||||||
|
|
||||||
| scope :search, ->(q) { | ||||||
| where(arel_table[:title].lower.matches("%#{q.downcase}%")) | ||||||
| q.blank? ? none : where(arel_table[:title].lower.matches("%#{q.downcase}%")) | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Лучше так (надо использовать фишки скоупов):
Suggested change
|
||||||
| } | ||||||
| end | ||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| <%# locals: (album:, album_counter: nil, album_iteration: nil) -%> | ||
| <li class="nav--search--result"> | ||
| <%= link_to album.title, album_path(album), class: "hover:text-secondary", target: "_top" %> | ||
| <span class="ml-2 text-primary text-xsmall"><%= album.artist.name %></span> | ||
| </li> |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| <%# locals: (artist:, artist_counter: nil, artist_iteration: nil) -%> | ||
| <li class="nav--search--result"> | ||
| <%= link_to artist.name, artist_path(artist), class: "hover:text-secondary", target: "_top" %> | ||
| </li> |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| <%# locals: (artists: [], albums: [], tracks: []) -%> | ||
| <%= turbo_frame_tag :search_results, class: "nav--search--frame" do %> | ||
| <% if [artists, albums, tracks].any?(&:present?) %> | ||
| <ul class="nav--search--results"> | ||
| <%= render collection: artists, partial: "artist" %> | ||
| <%= render collection: albums, partial: "album" %> | ||
| <%= render collection: tracks, partial: "track" %> | ||
| </ul> | ||
| <% end %> | ||
| <% end %> |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| <%# locals: (track:, track_counter: nil, track_iteration: nil) -%> | ||
| <li class="nav--search--result"> | ||
| <%= link_to track.title, play_track_path(track), class: "hover:text-primary", data: {"turbo-frame" => "player"} %> | ||
| <span class="ml-2 text-secondary text-xsmall"><%= track.album.artist.name %></span> | ||
| </li> |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -14,18 +14,26 @@ | |
| <% end %> | ||
| <% end %> | ||
| <%- end -%> | ||
| <%= form_with(url: search_path, method: :get, class: "nav--search") do |f| %> | ||
| <div class="nav--search--icon"> | ||
| <%= render "icons/search" %> | ||
| </div> | ||
| <%= f.search_field :q, value: params[:q], class: "nav--search--input" %> | ||
| <% end %> | ||
| <div class="nav--search"> | ||
| <%= form_with(url: search_path, method: :get) do |f| %> | ||
| <div class="nav--search--icon"> | ||
| <%= render "icons/search" %> | ||
| </div> | ||
| <%= f.search_field :q, class: "nav--search--input", data: { | ||
| controller: "live-search", | ||
| action: "live-search#search", | ||
| "live-search-search-path-value": search_path, | ||
| "live-search-preview-frame-id-value": :search_results, | ||
| } %> | ||
| <% end %> | ||
| <%= turbo_frame_tag :search_results, class: "nav--search--frame", src: search_path %> | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. А нужен ли тут |
||
| </div> | ||
| </div> | ||
| <div class="nav--right"> | ||
| <%- if current_user -%> | ||
| <span class="nav--username"><%= User::PREFIX + current_user.username %></span> | ||
| <%= button_to "Sign out", sign_out_path, method: :delete, class: "nav--btn--outlined ml-2" %> | ||
| <%- else- %> | ||
| <%- else -%> | ||
| <%= link_to "Sign up", sign_up_path, class: "nav--btn--outlined" %> | ||
| <%= link_to "Log in", sign_in_path, class: "nav--btn ml-2" %> | ||
| <%- end -%> | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Для превью тоже имеет смысл подождать, пока пользователь введёт первые символы; ограничение можно "продублировать" на клиенте через Values в контроллере, например (или вообще через стандартные HTML атрибуты).