lib/generators/coupdoeil/install/install_generator.rb



# frozen_string_literal: true

module Coupdoeil
  class InstallGenerator < Rails::Generators::Base
    Coupdoeil::InstallGenerator.source_root(Coupdoeil::Engine.root.join("lib/generators/coupdoeil/install/templates"))

    desc "Create base class for popovers and default layout."

    def create_base_class
      create_file("app/popovers/application_popover.rb", <<~RUBY)
        class ApplicationPopover < Coupdoeil::Popover
        end
      RUBY
    end

    def insert_default_layout
      template("layout.html.erb.tt", "app/popovers/layouts/popover.html.erb")
    end

    def install_javascripts
      puts ""
      if Rails.root.join("config/importmap.rb").exist?
        append_to_importmap
      elsif Rails.root.join("package.json").exist?
        add_with_node
      else
        puts "You must either be running with node (package.json) or importmap-rails (config/importmap.rb) to use this gem."
      end
    end

    def install_stylesheets
      puts ""
      import_stylesheet
      hidden_class_requirement
    end

    private

    def append_to_importmap
      puts "Using importmap"
      puts "Pin Coupdoeil"
      append_to_file("config/importmap.rb", %(pin "coupdoeil", to: "coupdoeil.min.js", preload: true\n))

      puts "Import Coupdoeil"
      append_to_file("app/javascript/application.js", %(import "coupdoeil"\n))
    end

    def add_with_node
      if Rails.root.join("app/javascript/application.js").exist?
        say("Import Coupdoeil")
        append_to_file("app/javascript/application.js", %(import "coupdoeil"\n))
      else
        say("You must import coupdoeil in your JavaScript entrypoint file", :red)
      end

      say("Install Coupdoeil")
      run("yarn add coupdoeil")
    end

    def import_stylesheet
      puts "To use Coupdoeil popover style, add to your layout's head:"
      puts ""
      puts <<-ERB
      <%= stylesheet_link_tag "coupdoeil/popover" %>
      ERB
      puts ""
      puts "Or one of two:"
      puts ""
      puts <<-ERB
      <%= stylesheet_link_tag "coupdoeil/popover-arrow" %>
      <%= stylesheet_link_tag "coupdoeil/popover-animation" %>
      ERB
    end

    def hidden_class_requirement
      puts ""
      puts "Also make sure you have a CSS implementation of .hidden class:"
      puts ""
      puts <<-CSS
        .hidden {
            display: none;
        }
      CSS
      puts ""
    end
  end
end