# See the Pagy documentation: https://ddnexus.github.io/pagy/docs/extras/calendar# frozen_string_literal: truerequire_relative'../calendar'classPagy# :nodoc:# Add pagination filtering by calendar unit (:year, :quarter, :month, :week, :day) to the regular paginationmoduleCalendarExtra# Additions for the Backend modulemoduleBackendAddOnCONF_KEYS=(Calendar::UNITS+%i[pagy active]).freezeprivate# Take a collection and a conf Hash with keys in CONF_KEYS and return an array with 3 items: [calendar, pagy, results]defpagy_calendar(collection,conf)raiseArgumentError,"keys must be in #{CONF_KEYS.inspect}"\unlessconf.is_a?(Hash)&&(conf.keys-CONF_KEYS).empty?conf[:pagy]||={}unlessconf.key?(:active)&&!conf[:active]calendar,from,to=Calendar.send(:init,conf,pagy_calendar_period(collection),params)do|unit,period|pagy_calendar_counts(collection,unit,*period)ifrespond_to?(:pagy_calendar_counts)endcollection=pagy_calendar_filter(collection,from,to)endpagy,results=send(conf[:pagy][:backend]||:pagy,collection,**conf[:pagy])# use backend: :pagy when omitted[calendar,pagy,results]end# This method must be implemented by the applicationdefpagy_calendar_period(*)raiseNoMethodError,'the pagy_calendar_period method must be implemented by the application '\'(see https://ddnexus.github.io/pagy/docs/extras/calendar/#pagy-calendar-period-collection)'end# This method must be implemented by the applicationdefpagy_calendar_filter(*)raiseNoMethodError,'the pagy_calendar_filter method must be implemented by the application '\'(see https://ddnexus.github.io/pagy/docs/extras/calendar/#pagy-calendar-filter-collection-from-to)'endend# Override the pagy_anchormoduleFrontendOverride# Consider the vars[:counts]defpagy_anchor(pagy,anchor_string: nil)returnsuperunless(counts=pagy.vars[:counts])anchor_string&&=%( #{anchor_string})left,right=%(<a#{anchor_string} href="#{pagy_url_for(pagy,PAGE_TOKEN)}").split(PAGE_TOKEN,2)# lambda used by all the helperslambdado|page,text=pagy.label_for(page),classes: nil,aria_label: nil|count=counts[page-1]ifcount.zero?classes="#{classes&&(classes+' ')}empty-page"info_key='pagy.info.no_items'elseinfo_key='pagy.info.single_page'endtitle=%( title="#{pagy_t(info_key,item_name: pagy_t('pagy.item_name',count:),count:)}")classes=%( class="#{classes}")ifclassesaria_label=%( aria-label="#{aria_label}")ifaria_label%(#{left}#{page}#{right}#{title}#{classes}#{aria_label}>#{text}</a>)endendend# Additions for the Frontend modulemoduleUrlHelperAddOn# Return the url for the calendar page at timedefpagy_calendar_url_at(calendar,time,**opts)pagy_url_for(calendar.send(:calendar_at,time,**opts),1,**opts)endendendBackend.prependCalendarExtra::BackendAddOn,CalendarExtra::UrlHelperAddOnFrontend.prependCalendarExtra::UrlHelperAddOn,CalendarExtra::FrontendOverrideend