You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.9 KiB

1 month ago
  1. module PagyHelper
  2. include Pagy::Frontend
  3. # preferable to sort_link, prepend page=1 as second args (options like) automatically
  4. def pagy_sort_link(search_object, attribute, *args, &)
  5. prepend_args_with_common_pagy_options(args)
  6. sort_link(search_object, attribute.to_s, *args, &)
  7. end
  8. # TODO: needs some refactoring
  9. def pagy_toggle_link(search_object, attribute, *args, &)
  10. params = preserve_q
  11. state = params.dig(:q, attribute).to_s == 'true'
  12. params[:q] = params[:q].merge(archived: !state)
  13. url = url_for(params:)
  14. # build_toggle_field_tag("q[#{attribute}]", t("actions.#{attribute}"), state, on_change: "Turbo.visit('#{url}')")
  15. build_toggle_field_tag("q[#{attribute}]", '', state, on_change: "Turbo.visit('#{url}')")
  16. end
  17. # TODO: needs some refactoring
  18. def pagy_search_field(search_object, attribute, *args)
  19. params = preserve_q
  20. value = params.dig(:q, attribute)
  21. args << {} unless args.last.is_a?(Hash)
  22. url = url_for(params:)
  23. url += url.include?('?') ? '&' : '?'
  24. url += "q[#{attribute}]="
  25. args.last.merge!({ onkeypress: "if (event.key === \"Enter\") {event.preventDefault(); Turbo.visit('#{url}'+event.target.value, { frame: 'scores', turbo: true, acceptsStreamResponse: true })}" })
  26. # args.last.merge!({ onkeypress: 'if (event.key === "Enter") {event.preventDefault()}' })
  27. search_field_tag("q[#{attribute}]", value, *args)
  28. end
  29. # preserve ransack search parameters from default parameter 'q'
  30. def preserve_q(search_object = nil)
  31. { q: request.params[:q] || {} }
  32. end
  33. # in case q exists and q[:sym] exists, its content is returned else nil
  34. def optional_q(sym) = request.params.fetch(:q, nil)&.fetch(sym, nil)
  35. private
  36. def prepend_args_with_common_pagy_options(args)
  37. args << {} unless args.last.is_a?(Hash)
  38. args.last.merge!(
  39. { page: 1,
  40. data: {
  41. 'turbo-action': 'advance'
  42. } }
  43. )
  44. end
  45. end