diff --git a/.github/workflows/week3_intro.yml b/.github/workflows/week3_intro.yml index 3acdee3c..a44c45c6 100644 --- a/.github/workflows/week3_intro.yml +++ b/.github/workflows/week3_intro.yml @@ -9,7 +9,7 @@ on: workflow_dispatch: jobs: - week2: + week3: runs-on: ubuntu-latest steps: @@ -19,7 +19,6 @@ jobs: - name: Install Ruby uses: ruby/setup-ruby@v1 with: - ruby-version: 3.0.5 working-directory: week_3/hello_world bundler-cache: true diff --git a/.github/workflows/week3_model.yml b/.github/workflows/week3_model.yml index 2ac537ac..8eb8b058 100644 --- a/.github/workflows/week3_model.yml +++ b/.github/workflows/week3_model.yml @@ -9,7 +9,7 @@ on: workflow_dispatch: jobs: - week2: + week3_model: runs-on: ubuntu-latest steps: @@ -19,7 +19,6 @@ jobs: - name: Install Ruby uses: ruby/setup-ruby@v1 with: - ruby-version: 3.0.5 working-directory: week_3/football bundler-cache: true diff --git a/.github/workflows/week4_assignement.yml b/.github/workflows/week4_assignement.yml new file mode 100644 index 00000000..12291a77 --- /dev/null +++ b/.github/workflows/week4_assignement.yml @@ -0,0 +1,35 @@ +name: 'Week 3 Model' + +on: + pull_request: + types: [synchronize, opened, reopened, edited] + branches: + - 'week4_*' + + workflow_dispatch: + +jobs: + week3_model: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v3 + + - name: Install Ruby + uses: ruby/setup-ruby@v1 + with: + working-directory: week_4/activity-tracker + bundler-cache: true + + - name: Install NPM packages + uses: bahmutov/npm-install@v1 + with: + working-directory: week_4/activity-tracker + + - name: Test Controller Actions + working-directory: week_4/activity-tracker + run: | + bundle exec rails db:create + bundle exec rails db:migrate + bundle exec rails test diff --git a/README.md b/README.md index aa3fc22b..598c9fe9 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,8 @@ We have provided three ways of setting up a development environment, and [Dev Container](/setup/dev_container.md). We recommend you to choose [GitHub codespaces](/setup/github_codespaces.md) if you face any issues while installing ruby [locally](/setup/local_setup.md). -> We recommend sticking to the versions mentioned in the Installation Guide and -> run commands exactly as instructed, as all assignments in this Bootcamp are +> We recommend sticking to the versions mentioned in the Installation Guide and +> run commands exactly as instructed, as all assignments in this Bootcamp are > tested with these versions. ## [Week 1 - HTML and CSS](/week_1) @@ -24,5 +24,14 @@ create a new Rails project and build a simple website. Later we will take a closer look at Model of the MVC Architecture and talk about databases and working with records. +## [Week 4 - Controllers and Authentication](/week_4) + +This week, we will look into controllers, routing and authentication. + +## [Week 5 - Views](/week_4) + +So after 4 weeks, we have our basic app ready! 🥳 +However, there is one problem. It looks 🥴. Lets fix that! We'll now style our application using [Bootstrap](https://getbootstrap.com/docs/5.0/getting-started/introduction/) and look at the _View_ layer which is responsible for presenting data appropriately. + ## Contact In case of doubts related to the Bootcamp, feel free to reach out to the mentors on the [**#doubts**](https://discord.com/channels/1052463702558908416/1052467811143913552) channel on [Discord](https://discord.gg/HQKpB6XH). diff --git a/week_3/README.md b/week_3/README.md index d7b18080..723706cd 100644 --- a/week_3/README.md +++ b/week_3/README.md @@ -1,90 +1,72 @@ -# Week 3 - Getting Started with Rails +# Week 3 - Getting Started with Rails + Models In this week we will get started with Rails. -We will create a simple rails app with two pages, a Home Page and an About Me page. +At first, we will create a simple rails app with two pages, a Home Page and an About Me page. -## Steps -- [Set Up Local Workplace](../setup/) +Follow [these](./getting_started_with_rails.md) instructions to get started. -- Create a new [gemset](../setup/README.md#RVM) and install rails -```bash -cd week_3 -rvm gemset create week_3 -rvm use 3.0.5@week_3 -gem install rails --version 7.0.4 -``` +# Models -- Create a new Rails project `hello_world` in the directory `week_1` -```bash -rails new hello_world --css=bootstrap --skip-git -cd hello_world -rvm use 3.0.5@week_3 -``` +We take a closer look at _Model_ of the MVC architecture and talk about +databases, migrations and working with records. -> The command `rails new` initialises a Rails project. We have passed -> the flag `--skip-git` to avoid initializing Git again as we are -> already within a Git repository. +The _model_ layer is responsible for storing and processing data. -- Run the rails server using below command and go to http://localhost:3000/. -```bash -rails server -``` +We store data in a _relational database_ and process it in the +`app/models` of the Rails application. -You should see the rails logo. +A _relational database_ stores information as a set of tables with columns +and rows (_records_). The tables and their columns are together called +a _schema_. You can think of relational database as a spreadsheet with +each table on a different sheet. -### Add a controller +> There are other non-tabular databases as well, which are better suited +> to specific problems: [What is a Database | Oracle](https://www.oracle.com/in/database/what-is-database/) -- Generate a new controller `PageController` with actions `root` and - `about_me`: +_Structured Query Language_ (SQL) is used to access and manipulate +databases. SQL can retrieve, create, read, update and destroy records, +modify schema and more. Working with SQL directly is difficult, so we +usually have a Rails equivalent. -```bash -rails generate controller Page root about_me -``` +The assignment is split into different sub-tasks, each testing a +different aspect of Model layer. -> A _controller_ is responsible for making sense of request and producing -> the appropriate output. It acts as a middleman between the Data -> (Model) and Presentation (View). Controllers are stored in -> `app/controllers` directory. +> We will be using SQLite as our database program, as it requires no +> setup and is Rails's default. -> The generator creates the files and fills it with some default code. -> the above command creates a controller -> `PagesController`, creates new view files `root.html.erb` and -> `about_me.html.erb` and modifies the routes file +## Task 1 - Creating Tables -- Edit the routes file (`config/routes.rb`) as follow to add new routes: +Relational databases stores information using tables. You can think of +tables and their columns as the format in which data is stored. -```ruby -Rails.application.routes.draw do - get '/', to: 'page#root' - get 'about_me', to: 'page#about_me' -end -``` +In this sub-task, we will build an activity tracker because as programmers we spend long hours sitting and need to keep track of our health. During the course of this bootcamp, we'll build the entire application, adding functionality each week. At the end, you'll have a fully functional acticity tracker! -The routes file specifies the URLs that are recognized by the application. +Head over to [activity-tracker](./activity-tracker/README.md) to learn more. -- Edit the view files `app/views/page/root.html.erb` and `app/views/page/about_me.html.erb`. +## Task 2 - Working with Records -- You should be able to see see your changes at `http://localhost:3000` and - `http://localhost:3000/about_me`. - -![image](https://user-images.githubusercontent.com/66632353/211770375-4cc14806-7e60-4135-9e40-7b73e3c4ed23.png) -![image](https://user-images.githubusercontent.com/66632353/211770741-56dfaea8-2095-474b-974a-2b151953a3de.png) +Once a table is created, we have to fill it with actual data. In +particular, we can create, read, update and destroy records in a table. +Each operation maps to a different SQL command and a different Rails +equivalent. -- Copy the test file from week_3 directory to hello_world/test/controllers: -```bash -cp page_controller_test.rb hello_world/test/controllers -``` +In this sub-task, we will work on some statistics from Football! + +Head over to [football](football/README.md) directory to learn more. + + +## Interactive Console -- Execute the test suite to ensure the page works as expected. +The Rails console is useful for testing out quick ideas with code and +debugging applications. ```bash -rails test +rails console ``` -- If the test fails, check the view files and debug the application. -- Once the test works locally, submit your changes. +This should open a console, similar to IRB in the first session. We can +access your model functions and execute any valid ruby code. -# Model -Once done head over to [football](./football) directory to learn more about models. \ No newline at end of file +- [The Rails Command Line](https://guides.rubyonrails.org/command_line.html#bin-rails-console) diff --git a/week_3/activity-tracker/.ruby-version b/week_3/activity-tracker/.ruby-version new file mode 100644 index 00000000..316881c9 --- /dev/null +++ b/week_3/activity-tracker/.ruby-version @@ -0,0 +1 @@ +ruby-3.0.5 diff --git a/week_3/activity-tracker/Gemfile b/week_3/activity-tracker/Gemfile new file mode 100644 index 00000000..0e74c513 --- /dev/null +++ b/week_3/activity-tracker/Gemfile @@ -0,0 +1,72 @@ +source "https://rubygems.org" +git_source(:github) { |repo| "https://github.com/#{repo}.git" } + +ruby "3.0.5" + +# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" +gem "rails", "~> 7.0.4" + +# The original asset pipeline for Rails [https://github.com/rails/sprockets-rails] +gem "sprockets-rails" + +# Use sqlite3 as the database for Active Record +gem "sqlite3", "~> 1.4" + +# Use the Puma web server [https://github.com/puma/puma] +gem "puma", "~> 5.0" + +# Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails] +gem "importmap-rails" + +# Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev] +gem "turbo-rails" + +# Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev] +gem "stimulus-rails" + +# Build JSON APIs with ease [https://github.com/rails/jbuilder] +gem "jbuilder" + +# Use Redis adapter to run Action Cable in production +# gem "redis", "~> 4.0" + +# Use Kredis to get higher-level data types in Redis [https://github.com/rails/kredis] +# gem "kredis" + +# Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword] +# gem "bcrypt", "~> 3.1.7" + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem "tzinfo-data", platforms: %i[ mingw mswin x64_mingw jruby ] + +# Reduces boot times through caching; required in config/boot.rb +gem "bootsnap", require: false + +# Use Sass to process CSS +# gem "sassc-rails" + +# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images] +# gem "image_processing", "~> 1.2" + +group :development, :test do + # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem + gem "debug", platforms: %i[ mri mingw x64_mingw ] +end + +group :development do + # Use console on exceptions pages [https://github.com/rails/web-console] + gem "web-console" + + # Add speed badges [https://github.com/MiniProfiler/rack-mini-profiler] + # gem "rack-mini-profiler" + + # Speed up commands on slow machines / big apps [https://github.com/rails/spring] + # gem "spring" +end + +group :test do + # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing] + gem "capybara" + gem "selenium-webdriver" + gem "webdrivers" +end diff --git a/week_3/activity-tracker/Gemfile.lock b/week_3/activity-tracker/Gemfile.lock new file mode 100644 index 00000000..2429566c --- /dev/null +++ b/week_3/activity-tracker/Gemfile.lock @@ -0,0 +1,232 @@ +GEM + remote: https://rubygems.org/ + specs: + actioncable (7.0.4) + actionpack (= 7.0.4) + activesupport (= 7.0.4) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + actionmailbox (7.0.4) + actionpack (= 7.0.4) + activejob (= 7.0.4) + activerecord (= 7.0.4) + activestorage (= 7.0.4) + activesupport (= 7.0.4) + mail (>= 2.7.1) + net-imap + net-pop + net-smtp + actionmailer (7.0.4) + actionpack (= 7.0.4) + actionview (= 7.0.4) + activejob (= 7.0.4) + activesupport (= 7.0.4) + mail (~> 2.5, >= 2.5.4) + net-imap + net-pop + net-smtp + rails-dom-testing (~> 2.0) + actionpack (7.0.4) + actionview (= 7.0.4) + activesupport (= 7.0.4) + rack (~> 2.0, >= 2.2.0) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.0, >= 1.2.0) + actiontext (7.0.4) + actionpack (= 7.0.4) + activerecord (= 7.0.4) + activestorage (= 7.0.4) + activesupport (= 7.0.4) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (7.0.4) + activesupport (= 7.0.4) + builder (~> 3.1) + erubi (~> 1.4) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.1, >= 1.2.0) + activejob (7.0.4) + activesupport (= 7.0.4) + globalid (>= 0.3.6) + activemodel (7.0.4) + activesupport (= 7.0.4) + activerecord (7.0.4) + activemodel (= 7.0.4) + activesupport (= 7.0.4) + activestorage (7.0.4) + actionpack (= 7.0.4) + activejob (= 7.0.4) + activerecord (= 7.0.4) + activesupport (= 7.0.4) + marcel (~> 1.0) + mini_mime (>= 1.1.0) + activesupport (7.0.4) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (>= 1.6, < 2) + minitest (>= 5.1) + tzinfo (~> 2.0) + addressable (2.8.1) + public_suffix (>= 2.0.2, < 6.0) + bindex (0.8.1) + bootsnap (1.15.0) + msgpack (~> 1.2) + builder (3.2.4) + capybara (3.38.0) + addressable + matrix + mini_mime (>= 0.1.3) + nokogiri (~> 1.8) + rack (>= 1.6.0) + rack-test (>= 0.6.3) + regexp_parser (>= 1.5, < 3.0) + xpath (~> 3.2) + concurrent-ruby (1.1.10) + crass (1.0.6) + date (3.3.3) + debug (1.7.1) + irb (>= 1.5.0) + reline (>= 0.3.1) + erubi (1.12.0) + globalid (1.0.0) + activesupport (>= 5.0) + i18n (1.12.0) + concurrent-ruby (~> 1.0) + importmap-rails (1.1.5) + actionpack (>= 6.0.0) + railties (>= 6.0.0) + io-console (0.6.0) + irb (1.6.2) + reline (>= 0.3.0) + jbuilder (2.11.5) + actionview (>= 5.0.0) + activesupport (>= 5.0.0) + loofah (2.19.1) + crass (~> 1.0.2) + nokogiri (>= 1.5.9) + mail (2.8.0.1) + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.0.2) + matrix (0.4.2) + method_source (1.0.0) + mini_mime (1.1.2) + minitest (5.17.0) + msgpack (1.6.0) + net-imap (0.3.4) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.2.1) + timeout + net-smtp (0.3.3) + net-protocol + nio4r (2.5.8) + nokogiri (1.14.0-x86_64-linux) + racc (~> 1.4) + public_suffix (5.0.1) + puma (5.6.5) + nio4r (~> 2.0) + racc (1.6.2) + rack (2.2.5) + rack-test (2.0.2) + rack (>= 1.3) + rails (7.0.4) + actioncable (= 7.0.4) + actionmailbox (= 7.0.4) + actionmailer (= 7.0.4) + actionpack (= 7.0.4) + actiontext (= 7.0.4) + actionview (= 7.0.4) + activejob (= 7.0.4) + activemodel (= 7.0.4) + activerecord (= 7.0.4) + activestorage (= 7.0.4) + activesupport (= 7.0.4) + bundler (>= 1.15.0) + railties (= 7.0.4) + rails-dom-testing (2.0.3) + activesupport (>= 4.2.0) + nokogiri (>= 1.6) + rails-html-sanitizer (1.4.4) + loofah (~> 2.19, >= 2.19.1) + railties (7.0.4) + actionpack (= 7.0.4) + activesupport (= 7.0.4) + method_source + rake (>= 12.2) + thor (~> 1.0) + zeitwerk (~> 2.5) + rake (13.0.6) + regexp_parser (2.6.1) + reline (0.3.2) + io-console (~> 0.5) + rexml (3.2.5) + rubyzip (2.3.2) + selenium-webdriver (4.7.1) + rexml (~> 3.2, >= 3.2.5) + rubyzip (>= 1.2.2, < 3.0) + websocket (~> 1.0) + sprockets (4.2.0) + concurrent-ruby (~> 1.0) + rack (>= 2.2.4, < 4) + sprockets-rails (3.4.2) + actionpack (>= 5.2) + activesupport (>= 5.2) + sprockets (>= 3.0.0) + sqlite3 (1.5.4-x86_64-linux) + stimulus-rails (1.2.1) + railties (>= 6.0.0) + thor (1.2.1) + timeout (0.3.1) + turbo-rails (1.3.2) + actionpack (>= 6.0.0) + activejob (>= 6.0.0) + railties (>= 6.0.0) + tzinfo (2.0.5) + concurrent-ruby (~> 1.0) + web-console (4.2.0) + actionview (>= 6.0.0) + activemodel (>= 6.0.0) + bindex (>= 0.4.0) + railties (>= 6.0.0) + webdrivers (5.2.0) + nokogiri (~> 1.6) + rubyzip (>= 1.3.0) + selenium-webdriver (~> 4.0) + websocket (1.2.9) + websocket-driver (0.7.5) + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + xpath (3.2.0) + nokogiri (~> 1.8) + zeitwerk (2.6.6) + +PLATFORMS + x86_64-linux + +DEPENDENCIES + bootsnap + capybara + debug + importmap-rails + jbuilder + puma (~> 5.0) + rails (~> 7.0.4) + selenium-webdriver + sprockets-rails + sqlite3 (~> 1.4) + stimulus-rails + turbo-rails + tzinfo-data + web-console + webdrivers + +RUBY VERSION + ruby 3.0.5p211 + +BUNDLED WITH + 2.2.33 diff --git a/week_3/activity-tracker/README.md b/week_3/activity-tracker/README.md new file mode 100644 index 00000000..169969be --- /dev/null +++ b/week_3/activity-tracker/README.md @@ -0,0 +1,151 @@ +# Creating Tables | Activity Tracker + +We will learn about creating tables in Rails while keeping ourselves fit! + +Tables are the database objects that contain all the data in a database. +In tables, data is locally organized in a row-and-column format similar +to a spreadsheet. Each row represents a unique record and each column +represents a field in the record. + +For example, a table that contains employee data might contain a row for +each employee and columns representing employee information such as +employee number, name, address, job title and phone number. + +Tables are created executing the SQL statement `CREATE TABLE` on the +database. For example: + +```sql +CREATE TABLE employees ( + employee_number INTEGER, + name VARCHAR(80), + address VARCHAR(255), + title VARCHAR(80), + phone_number VARCHAR(10) + salary DECIMAL +); +``` + +In Rails, each table represents a class in `app/models` and creating new +tables is simpler and more convenient, thanks to the generator and +migrations. + +Rails equivalent of the above statement would be: + +```bash +rails generate model Employee employee_number:integer name:string \ +address:string title:string phone_number:string{10} salary:decimal +``` + +For this exercise, we will create a table `activity` with the following +attributes and data-types: +- Title: `string` +- Type: `string` +- Start: `datetime` +- Duration: `decimal` +- Calories: `integer` + +## Steps + +1. ### Prepare Local Database + +- Change directory to activity-tracker + + ```bash + cd activity-tracker + ``` + +- Create the database + ``` + rails db:create + ``` + + You should see two new files are created if not present already - `development.sqlite3` and `test.sqlite3`. + + - Run the migrations + + ```bash + rails db:migrate + ``` + +2. ### Create the tables + Models can be created using Rails generator with the following syntax: + + ```bash + rails generate model NAME field[:type] field[:type]... + ``` + + So for our requirement, execute the following command: + ```bash + rails generate model Activity title:string type:string start:datetime duration:decimal calories:integer + ``` + + > Rails has great emphasis on naming conventions. The model name must be + > `CamelCase` and column names must be `snake_case`. Read about other + > [rails naming conventions](https://gist.github.com/iangreenleaf/b206d09c587e8fc6399e). + + - [Understanding the SQL Decimal data type](https://www.sqlshack.com/understanding-sql-decimal-data-type/) + - [Precision and scale for decimals](https://millarian.com/rails/precision-and-scale-for-ruby-on-rails-migrations/) + + The command creates multiple files - most important of which are + `app/models/activity.rb` and `db/migrate/_create_activities.rb` + + > The number in the beginning of the migration file is a UTC timestamp. + > Rails uses this timestamp to determine which migration should be run + > and in what order. + + The file `db/migrations/_create_activities.rb` looks like: + + ```ruby + class CreateActivities < ActiveRecord::Migration[7.0] + def change + create_table :activities do |t| + t.string :title + t.string :type + t.datetime :start + t.decimal :duration + t.integer :calories + + t.timestamps + end + end + end + ``` + + The migration roughly translates to "create table activities with the five columns and their types described above" which is exactly what we wanted! + The migration also uses the code `t.timestamps` to add timestamps `created_at` and `updated_at` to the activities table automatically. + + - Run the migration. + + ```bash + rails db:migrate + ``` + + > Running the migration commits the changes to the database. Therefore, + > your changes are not reflected in the database unless migrated. + + - Execute the test suite and submit your changes when tests pass. + + ```bash + rails test + ``` + +
+ +## Rolling Back Migrations + +If the migration was incorrect (say wrong column names or datatype), +you can "undo" the migration by the following command: + +```bash +rails db:rollback +``` + +Then, fix the migration file `db/migrations/_create_students.rb` +and re-run the migration to commit your changes to the dabase. + +Read more about migrations at: [Running Migrations | Active Record Migrations](https://edgeguides.rubyonrails.org/active_record_migrations.html#rolling-back) + +
+ +## References +- [Rails Active Record Migration](https://guides.rubyonrails.org/active_record_migrations.html) diff --git a/week_3/activity-tracker/Rakefile b/week_3/activity-tracker/Rakefile new file mode 100644 index 00000000..9a5ea738 --- /dev/null +++ b/week_3/activity-tracker/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative "config/application" + +Rails.application.load_tasks diff --git a/week_3/activity-tracker/app/assets/config/manifest.js b/week_3/activity-tracker/app/assets/config/manifest.js new file mode 100644 index 00000000..ddd546a0 --- /dev/null +++ b/week_3/activity-tracker/app/assets/config/manifest.js @@ -0,0 +1,4 @@ +//= link_tree ../images +//= link_directory ../stylesheets .css +//= link_tree ../../javascript .js +//= link_tree ../../../vendor/javascript .js diff --git a/week_3/activity-tracker/app/assets/images/.keep b/week_3/activity-tracker/app/assets/images/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/app/assets/stylesheets/application.css b/week_3/activity-tracker/app/assets/stylesheets/application.css new file mode 100644 index 00000000..288b9ab7 --- /dev/null +++ b/week_3/activity-tracker/app/assets/stylesheets/application.css @@ -0,0 +1,15 @@ +/* + * This is a manifest file that'll be compiled into application.css, which will include all the files + * listed below. + * + * Any CSS (and SCSS, if configured) file within this directory, lib/assets/stylesheets, or any plugin's + * vendor/assets/stylesheets directory can be referenced here using a relative path. + * + * You're free to add application-wide styles to this file and they'll appear at the bottom of the + * compiled file so the styles you add here take precedence over styles defined in any other CSS + * files in this directory. Styles in this file should be added after the last require_* statement. + * It is generally better to create a new file per style scope. + * + *= require_tree . + *= require_self + */ diff --git a/week_3/activity-tracker/app/channels/application_cable/channel.rb b/week_3/activity-tracker/app/channels/application_cable/channel.rb new file mode 100644 index 00000000..d6726972 --- /dev/null +++ b/week_3/activity-tracker/app/channels/application_cable/channel.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end diff --git a/week_3/activity-tracker/app/channels/application_cable/connection.rb b/week_3/activity-tracker/app/channels/application_cable/connection.rb new file mode 100644 index 00000000..0ff5442f --- /dev/null +++ b/week_3/activity-tracker/app/channels/application_cable/connection.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Connection < ActionCable::Connection::Base + end +end diff --git a/week_3/activity-tracker/app/controllers/application_controller.rb b/week_3/activity-tracker/app/controllers/application_controller.rb new file mode 100644 index 00000000..09705d12 --- /dev/null +++ b/week_3/activity-tracker/app/controllers/application_controller.rb @@ -0,0 +1,2 @@ +class ApplicationController < ActionController::Base +end diff --git a/week_3/activity-tracker/app/controllers/concerns/.keep b/week_3/activity-tracker/app/controllers/concerns/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/app/helpers/application_helper.rb b/week_3/activity-tracker/app/helpers/application_helper.rb new file mode 100644 index 00000000..de6be794 --- /dev/null +++ b/week_3/activity-tracker/app/helpers/application_helper.rb @@ -0,0 +1,2 @@ +module ApplicationHelper +end diff --git a/week_3/activity-tracker/app/javascript/application.js b/week_3/activity-tracker/app/javascript/application.js new file mode 100644 index 00000000..0d7b4940 --- /dev/null +++ b/week_3/activity-tracker/app/javascript/application.js @@ -0,0 +1,3 @@ +// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails +import "@hotwired/turbo-rails" +import "controllers" diff --git a/week_3/activity-tracker/app/javascript/controllers/application.js b/week_3/activity-tracker/app/javascript/controllers/application.js new file mode 100644 index 00000000..1213e85c --- /dev/null +++ b/week_3/activity-tracker/app/javascript/controllers/application.js @@ -0,0 +1,9 @@ +import { Application } from "@hotwired/stimulus" + +const application = Application.start() + +// Configure Stimulus development experience +application.debug = false +window.Stimulus = application + +export { application } diff --git a/week_3/activity-tracker/app/javascript/controllers/hello_controller.js b/week_3/activity-tracker/app/javascript/controllers/hello_controller.js new file mode 100644 index 00000000..5975c078 --- /dev/null +++ b/week_3/activity-tracker/app/javascript/controllers/hello_controller.js @@ -0,0 +1,7 @@ +import { Controller } from "@hotwired/stimulus" + +export default class extends Controller { + connect() { + this.element.textContent = "Hello World!" + } +} diff --git a/week_3/activity-tracker/app/javascript/controllers/index.js b/week_3/activity-tracker/app/javascript/controllers/index.js new file mode 100644 index 00000000..54ad4cad --- /dev/null +++ b/week_3/activity-tracker/app/javascript/controllers/index.js @@ -0,0 +1,11 @@ +// Import and register all your controllers from the importmap under controllers/* + +import { application } from "controllers/application" + +// Eager load all controllers defined in the import map under controllers/**/*_controller +import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading" +eagerLoadControllersFrom("controllers", application) + +// Lazy load controllers as they appear in the DOM (remember not to preload controllers in import map!) +// import { lazyLoadControllersFrom } from "@hotwired/stimulus-loading" +// lazyLoadControllersFrom("controllers", application) diff --git a/week_3/activity-tracker/app/jobs/application_job.rb b/week_3/activity-tracker/app/jobs/application_job.rb new file mode 100644 index 00000000..d394c3d1 --- /dev/null +++ b/week_3/activity-tracker/app/jobs/application_job.rb @@ -0,0 +1,7 @@ +class ApplicationJob < ActiveJob::Base + # Automatically retry jobs that encountered a deadlock + # retry_on ActiveRecord::Deadlocked + + # Most jobs are safe to ignore if the underlying records are no longer available + # discard_on ActiveJob::DeserializationError +end diff --git a/week_3/activity-tracker/app/mailers/application_mailer.rb b/week_3/activity-tracker/app/mailers/application_mailer.rb new file mode 100644 index 00000000..3c34c814 --- /dev/null +++ b/week_3/activity-tracker/app/mailers/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: "from@example.com" + layout "mailer" +end diff --git a/week_3/activity-tracker/app/models/activity.rb b/week_3/activity-tracker/app/models/activity.rb new file mode 100644 index 00000000..a99f990d --- /dev/null +++ b/week_3/activity-tracker/app/models/activity.rb @@ -0,0 +1,2 @@ +class Activity < ApplicationRecord +end diff --git a/week_3/activity-tracker/app/models/application_record.rb b/week_3/activity-tracker/app/models/application_record.rb new file mode 100644 index 00000000..b63caeb8 --- /dev/null +++ b/week_3/activity-tracker/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + primary_abstract_class +end diff --git a/week_3/activity-tracker/app/models/concerns/.keep b/week_3/activity-tracker/app/models/concerns/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/app/views/layouts/application.html.erb b/week_3/activity-tracker/app/views/layouts/application.html.erb new file mode 100644 index 00000000..5f65d83d --- /dev/null +++ b/week_3/activity-tracker/app/views/layouts/application.html.erb @@ -0,0 +1,16 @@ + + + + ActivityTracker + + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> + <%= javascript_importmap_tags %> + + + + <%= yield %> + + diff --git a/week_3/activity-tracker/app/views/layouts/mailer.html.erb b/week_3/activity-tracker/app/views/layouts/mailer.html.erb new file mode 100644 index 00000000..cbd34d2e --- /dev/null +++ b/week_3/activity-tracker/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/week_3/activity-tracker/app/views/layouts/mailer.text.erb b/week_3/activity-tracker/app/views/layouts/mailer.text.erb new file mode 100644 index 00000000..37f0bddb --- /dev/null +++ b/week_3/activity-tracker/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/week_3/activity-tracker/bin/bundle b/week_3/activity-tracker/bin/bundle new file mode 100755 index 00000000..374a0a1f --- /dev/null +++ b/week_3/activity-tracker/bin/bundle @@ -0,0 +1,114 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'bundle' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require "rubygems" + +m = Module.new do + module_function + + def invoked_as_script? + File.expand_path($0) == File.expand_path(__FILE__) + end + + def env_var_version + ENV["BUNDLER_VERSION"] + end + + def cli_arg_version + return unless invoked_as_script? # don't want to hijack other binstubs + return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update` + bundler_version = nil + update_index = nil + ARGV.each_with_index do |a, i| + if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN + bundler_version = a + end + next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ + bundler_version = $1 + update_index = i + end + bundler_version + end + + def gemfile + gemfile = ENV["BUNDLE_GEMFILE"] + return gemfile if gemfile && !gemfile.empty? + + File.expand_path("../../Gemfile", __FILE__) + end + + def lockfile + lockfile = + case File.basename(gemfile) + when "gems.rb" then gemfile.sub(/\.rb$/, gemfile) + else "#{gemfile}.lock" + end + File.expand_path(lockfile) + end + + def lockfile_version + return unless File.file?(lockfile) + lockfile_contents = File.read(lockfile) + return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ + Regexp.last_match(1) + end + + def bundler_requirement + @bundler_requirement ||= + env_var_version || cli_arg_version || + bundler_requirement_for(lockfile_version) + end + + def bundler_requirement_for(version) + return "#{Gem::Requirement.default}.a" unless version + + bundler_gem_version = Gem::Version.new(version) + + requirement = bundler_gem_version.approximate_recommendation + + return requirement unless Gem::Version.new(Gem::VERSION) < Gem::Version.new("2.7.0") + + requirement += ".a" if bundler_gem_version.prerelease? + + requirement + end + + def load_bundler! + ENV["BUNDLE_GEMFILE"] ||= gemfile + + activate_bundler + end + + def activate_bundler + gem_error = activation_error_handling do + gem "bundler", bundler_requirement + end + return if gem_error.nil? + require_error = activation_error_handling do + require "bundler/version" + end + return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION)) + warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`" + exit 42 + end + + def activation_error_handling + yield + nil + rescue StandardError, LoadError => e + e + end +end + +m.load_bundler! + +if m.invoked_as_script? + load Gem.bin_path("bundler", "bundle") +end diff --git a/week_3/activity-tracker/bin/importmap b/week_3/activity-tracker/bin/importmap new file mode 100755 index 00000000..36502ab1 --- /dev/null +++ b/week_3/activity-tracker/bin/importmap @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby + +require_relative "../config/application" +require "importmap/commands" diff --git a/week_3/activity-tracker/bin/rails b/week_3/activity-tracker/bin/rails new file mode 100755 index 00000000..efc03774 --- /dev/null +++ b/week_3/activity-tracker/bin/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path("../config/application", __dir__) +require_relative "../config/boot" +require "rails/commands" diff --git a/week_3/activity-tracker/bin/rake b/week_3/activity-tracker/bin/rake new file mode 100755 index 00000000..4fbf10b9 --- /dev/null +++ b/week_3/activity-tracker/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "rake" +Rake.application.run diff --git a/week_3/activity-tracker/bin/setup b/week_3/activity-tracker/bin/setup new file mode 100755 index 00000000..ec47b79b --- /dev/null +++ b/week_3/activity-tracker/bin/setup @@ -0,0 +1,33 @@ +#!/usr/bin/env ruby +require "fileutils" + +# path to your application root. +APP_ROOT = File.expand_path("..", __dir__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +FileUtils.chdir APP_ROOT do + # This script is a way to set up or update your development environment automatically. + # This script is idempotent, so that you can run it at any time and get an expectable outcome. + # Add necessary setup steps to this file. + + puts "== Installing dependencies ==" + system! "gem install bundler --conservative" + system("bundle check") || system!("bundle install") + + # puts "\n== Copying sample files ==" + # unless File.exist?("config/database.yml") + # FileUtils.cp "config/database.yml.sample", "config/database.yml" + # end + + puts "\n== Preparing database ==" + system! "bin/rails db:prepare" + + puts "\n== Removing old logs and tempfiles ==" + system! "bin/rails log:clear tmp:clear" + + puts "\n== Restarting application server ==" + system! "bin/rails restart" +end diff --git a/week_3/activity-tracker/config.ru b/week_3/activity-tracker/config.ru new file mode 100644 index 00000000..4a3c09a6 --- /dev/null +++ b/week_3/activity-tracker/config.ru @@ -0,0 +1,6 @@ +# This file is used by Rack-based servers to start the application. + +require_relative "config/environment" + +run Rails.application +Rails.application.load_server diff --git a/week_3/activity-tracker/config/application.rb b/week_3/activity-tracker/config/application.rb new file mode 100644 index 00000000..eaab4107 --- /dev/null +++ b/week_3/activity-tracker/config/application.rb @@ -0,0 +1,22 @@ +require_relative "boot" + +require "rails/all" + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module ActivityTracker + class Application < Rails::Application + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 7.0 + + # Configuration for the application, engines, and railties goes here. + # + # These settings can be overridden in specific environments using the files + # in config/environments, which are processed later. + # + # config.time_zone = "Central Time (US & Canada)" + # config.eager_load_paths << Rails.root.join("extras") + end +end diff --git a/week_3/activity-tracker/config/boot.rb b/week_3/activity-tracker/config/boot.rb new file mode 100644 index 00000000..988a5ddc --- /dev/null +++ b/week_3/activity-tracker/config/boot.rb @@ -0,0 +1,4 @@ +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +require "bundler/setup" # Set up gems listed in the Gemfile. +require "bootsnap/setup" # Speed up boot time by caching expensive operations. diff --git a/week_3/activity-tracker/config/cable.yml b/week_3/activity-tracker/config/cable.yml new file mode 100644 index 00000000..fc223da2 --- /dev/null +++ b/week_3/activity-tracker/config/cable.yml @@ -0,0 +1,10 @@ +development: + adapter: async + +test: + adapter: test + +production: + adapter: redis + url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> + channel_prefix: activity_tracker_production diff --git a/week_3/activity-tracker/config/credentials.yml.enc b/week_3/activity-tracker/config/credentials.yml.enc new file mode 100644 index 00000000..4410c9ad --- /dev/null +++ b/week_3/activity-tracker/config/credentials.yml.enc @@ -0,0 +1 @@ +vy9Yyajw1b8PCBzOL90ahf4dlXAdev9jaGcu43MsIEltJ9tLudTQHZhztOYwXgig6D1/W6vai5IQKKPbfBCioSi0cdsXraMUQpVx6wPgHjU4CRMYm5gbMJ8MoGpTTRO3546ceKYioiXoAtBnnM6jyHlqdqPm/xIND5SfytLSBOJrUxg8v06TISxfhIbRlGneBeEV7I8HcrBC2ulCNToXou0oojijWGkCUYjFV/0452pmrHDX+HC4Psc252O0H7emGpqjh6puxAV6aYmiNU3cvqNjUQXxHmaH7N1jgAnR/5xB1bwZHKUB7ngTufyFzt+3ZQg5UCbuuJ+4f8lSGbrJUKNJjpVVwW5jNrRCrDm8ZMbvHCus2ApGtHu/vVjxw5bo3hWda83vQhVcBI74bNo5JnbzuKNhmQi8VEHm--ByL641PQMhBRCAI2--Mnwv25FxL4SSK6RIuW8L1Q== \ No newline at end of file diff --git a/week_3/activity-tracker/config/database.yml b/week_3/activity-tracker/config/database.yml new file mode 100644 index 00000000..fcba57f1 --- /dev/null +++ b/week_3/activity-tracker/config/database.yml @@ -0,0 +1,25 @@ +# SQLite. Versions 3.8.0 and up are supported. +# gem install sqlite3 +# +# Ensure the SQLite 3 gem is defined in your Gemfile +# gem "sqlite3" +# +default: &default + adapter: sqlite3 + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + timeout: 5000 + +development: + <<: *default + database: db/development.sqlite3 + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: db/test.sqlite3 + +production: + <<: *default + database: db/production.sqlite3 diff --git a/week_3/activity-tracker/config/environment.rb b/week_3/activity-tracker/config/environment.rb new file mode 100644 index 00000000..cac53157 --- /dev/null +++ b/week_3/activity-tracker/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative "application" + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/week_3/activity-tracker/config/environments/development.rb b/week_3/activity-tracker/config/environments/development.rb new file mode 100644 index 00000000..f2a3adc8 --- /dev/null +++ b/week_3/activity-tracker/config/environments/development.rb @@ -0,0 +1,72 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded any time + # it changes. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.cache_classes = false + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable server timing + config.server_timing = true + + # Enable/disable caching. By default caching is disabled. + # Run rails dev:cache to toggle caching. + if Rails.root.join("tmp/caching-dev.txt").exist? + config.action_controller.perform_caching = true + config.action_controller.enable_fragment_cache_logging = true + + config.cache_store = :memory_store + config.public_file_server.headers = { + "Cache-Control" => "public, max-age=#{2.days.to_i}" + } + else + config.action_controller.perform_caching = false + + config.cache_store = :null_store + end + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + config.action_mailer.perform_caching = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + # Highlight code that triggered database queries in logs. + config.active_record.verbose_query_logs = true + + # Suppress logger output for asset requests. + config.assets.quiet = true + + config.hosts << "mittal-parth-animated-cod-gpxgvr5gwp62v4v5-3000.preview.app.github.dev" + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true + + # Uncomment if you wish to allow Action Cable access from any origin. + # config.action_cable.disable_request_forgery_protection = true +end diff --git a/week_3/activity-tracker/config/environments/production.rb b/week_3/activity-tracker/config/environments/production.rb new file mode 100644 index 00000000..86a19e32 --- /dev/null +++ b/week_3/activity-tracker/config/environments/production.rb @@ -0,0 +1,93 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.cache_classes = true + + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + config.action_controller.perform_caching = true + + # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] + # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). + # config.require_master_key = true + + # Disable serving static files from the `/public` folder by default since + # Apache or NGINX already handles this. + config.public_file_server.enabled = ENV["RAILS_SERVE_STATIC_FILES"].present? + + # Compress CSS using a preprocessor. + # config.assets.css_compressor = :sass + + # Do not fallback to assets pipeline if a precompiled asset is missed. + config.assets.compile = false + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.asset_host = "http://assets.example.com" + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache + # config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" # for NGINX + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Mount Action Cable outside main process or domain. + # config.action_cable.mount_path = nil + # config.action_cable.url = "wss://example.com/cable" + # config.action_cable.allowed_request_origins = [ "http://example.com", /http:\/\/example.*/ ] + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # Include generic and useful information about system operation, but avoid logging too much + # information to avoid inadvertent exposure of personally identifiable information (PII). + config.log_level = :info + + # Prepend all log lines with the following tags. + config.log_tags = [ :request_id ] + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Use a real queuing backend for Active Job (and separate queues per environment). + # config.active_job.queue_adapter = :resque + # config.active_job.queue_name_prefix = "activity_tracker_production" + + config.action_mailer.perform_caching = false + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Don't log any deprecations. + config.active_support.report_deprecations = false + + # Use default logging formatter so that PID and timestamp are not suppressed. + config.log_formatter = ::Logger::Formatter.new + + # Use a different logger for distributed setups. + # require "syslog/logger" + # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new "app-name") + + if ENV["RAILS_LOG_TO_STDOUT"].present? + logger = ActiveSupport::Logger.new(STDOUT) + logger.formatter = config.log_formatter + config.logger = ActiveSupport::TaggedLogging.new(logger) + end + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false +end diff --git a/week_3/activity-tracker/config/environments/test.rb b/week_3/activity-tracker/config/environments/test.rb new file mode 100644 index 00000000..6ea4d1e7 --- /dev/null +++ b/week_3/activity-tracker/config/environments/test.rb @@ -0,0 +1,60 @@ +require "active_support/core_ext/integer/time" + +# The test environment is used exclusively to run your application's +# test suite. You never need to work with it otherwise. Remember that +# your test database is "scratch space" for the test suite and is wiped +# and recreated between test runs. Don't rely on the data there! + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Turn false under Spring and add config.action_view.cache_template_loading = true. + config.cache_classes = true + + # Eager loading loads your whole application. When running a single test locally, + # this probably isn't necessary. It's a good idea to do in a continuous integration + # system, or in some way before deploying your code. + config.eager_load = ENV["CI"].present? + + # Configure public file server for tests with Cache-Control for performance. + config.public_file_server.enabled = true + config.public_file_server.headers = { + "Cache-Control" => "public, max-age=#{1.hour.to_i}" + } + + # Show full error reports and disable caching. + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + config.cache_store = :null_store + + # Raise exceptions instead of rendering exception templates. + config.action_dispatch.show_exceptions = false + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + + # Store uploaded files on the local file system in a temporary directory. + config.active_storage.service = :test + + config.action_mailer.perform_caching = false + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true +end diff --git a/week_3/activity-tracker/config/importmap.rb b/week_3/activity-tracker/config/importmap.rb new file mode 100644 index 00000000..8dce42d4 --- /dev/null +++ b/week_3/activity-tracker/config/importmap.rb @@ -0,0 +1,7 @@ +# Pin npm packages by running ./bin/importmap + +pin "application", preload: true +pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true +pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true +pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true +pin_all_from "app/javascript/controllers", under: "controllers" diff --git a/week_3/activity-tracker/config/initializers/assets.rb b/week_3/activity-tracker/config/initializers/assets.rb new file mode 100644 index 00000000..2eeef966 --- /dev/null +++ b/week_3/activity-tracker/config/initializers/assets.rb @@ -0,0 +1,12 @@ +# Be sure to restart your server when you modify this file. + +# Version of your assets, change this if you want to expire all your assets. +Rails.application.config.assets.version = "1.0" + +# Add additional assets to the asset load path. +# Rails.application.config.assets.paths << Emoji.images_path + +# Precompile additional assets. +# application.js, application.css, and all non-JS/CSS in the app/assets +# folder are already added. +# Rails.application.config.assets.precompile += %w( admin.js admin.css ) diff --git a/week_3/activity-tracker/config/initializers/content_security_policy.rb b/week_3/activity-tracker/config/initializers/content_security_policy.rb new file mode 100644 index 00000000..54f47cf1 --- /dev/null +++ b/week_3/activity-tracker/config/initializers/content_security_policy.rb @@ -0,0 +1,25 @@ +# Be sure to restart your server when you modify this file. + +# Define an application-wide content security policy. +# See the Securing Rails Applications Guide for more information: +# https://guides.rubyonrails.org/security.html#content-security-policy-header + +# Rails.application.configure do +# config.content_security_policy do |policy| +# policy.default_src :self, :https +# policy.font_src :self, :https, :data +# policy.img_src :self, :https, :data +# policy.object_src :none +# policy.script_src :self, :https +# policy.style_src :self, :https +# # Specify URI for violation reports +# # policy.report_uri "/csp-violation-report-endpoint" +# end +# +# # Generate session nonces for permitted importmap and inline scripts +# config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } +# config.content_security_policy_nonce_directives = %w(script-src) +# +# # Report violations without enforcing the policy. +# # config.content_security_policy_report_only = true +# end diff --git a/week_3/activity-tracker/config/initializers/filter_parameter_logging.rb b/week_3/activity-tracker/config/initializers/filter_parameter_logging.rb new file mode 100644 index 00000000..adc6568c --- /dev/null +++ b/week_3/activity-tracker/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +# Configure parameters to be filtered from the log file. Use this to limit dissemination of +# sensitive information. See the ActiveSupport::ParameterFilter documentation for supported +# notations and behaviors. +Rails.application.config.filter_parameters += [ + :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn +] diff --git a/week_3/activity-tracker/config/initializers/inflections.rb b/week_3/activity-tracker/config/initializers/inflections.rb new file mode 100644 index 00000000..3860f659 --- /dev/null +++ b/week_3/activity-tracker/config/initializers/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, "\\1en" +# inflect.singular /^(ox)en/i, "\\1" +# inflect.irregular "person", "people" +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym "RESTful" +# end diff --git a/week_3/activity-tracker/config/initializers/permissions_policy.rb b/week_3/activity-tracker/config/initializers/permissions_policy.rb new file mode 100644 index 00000000..00f64d71 --- /dev/null +++ b/week_3/activity-tracker/config/initializers/permissions_policy.rb @@ -0,0 +1,11 @@ +# Define an application-wide HTTP permissions policy. For further +# information see https://developers.google.com/web/updates/2018/06/feature-policy +# +# Rails.application.config.permissions_policy do |f| +# f.camera :none +# f.gyroscope :none +# f.microphone :none +# f.usb :none +# f.fullscreen :self +# f.payment :self, "https://secure.example.com" +# end diff --git a/week_3/activity-tracker/config/locales/en.yml b/week_3/activity-tracker/config/locales/en.yml new file mode 100644 index 00000000..8ca56fc7 --- /dev/null +++ b/week_3/activity-tracker/config/locales/en.yml @@ -0,0 +1,33 @@ +# Files in the config/locales directory are used for internationalization +# and are automatically loaded by Rails. If you want to use locales other +# than English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t "hello" +# +# In views, this is aliased to just `t`: +# +# <%= t("hello") %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# The following keys must be escaped otherwise they will not be retrieved by +# the default I18n backend: +# +# true, false, on, off, yes, no +# +# Instead, surround them with single quotes. +# +# en: +# "true": "foo" +# +# To learn more, please read the Rails Internationalization guide +# available at https://guides.rubyonrails.org/i18n.html. + +en: + hello: "Hello world" diff --git a/week_3/activity-tracker/config/master.key b/week_3/activity-tracker/config/master.key new file mode 100644 index 00000000..3e69d63e --- /dev/null +++ b/week_3/activity-tracker/config/master.key @@ -0,0 +1 @@ +7ffae4e43de01027f283f3630db4227c \ No newline at end of file diff --git a/week_3/activity-tracker/config/puma.rb b/week_3/activity-tracker/config/puma.rb new file mode 100644 index 00000000..daaf0369 --- /dev/null +++ b/week_3/activity-tracker/config/puma.rb @@ -0,0 +1,43 @@ +# Puma can serve each request in a thread from an internal thread pool. +# The `threads` method setting takes two numbers: a minimum and maximum. +# Any libraries that use thread pools should be configured to match +# the maximum value specified for Puma. Default is set to 5 threads for minimum +# and maximum; this matches the default thread size of Active Record. +# +max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } +min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count } +threads min_threads_count, max_threads_count + +# Specifies the `worker_timeout` threshold that Puma will use to wait before +# terminating a worker in development environments. +# +worker_timeout 3600 if ENV.fetch("RAILS_ENV", "development") == "development" + +# Specifies the `port` that Puma will listen on to receive requests; default is 3000. +# +port ENV.fetch("PORT") { 3000 } + +# Specifies the `environment` that Puma will run in. +# +environment ENV.fetch("RAILS_ENV") { "development" } + +# Specifies the `pidfile` that Puma will use. +pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } + +# Specifies the number of `workers` to boot in clustered mode. +# Workers are forked web server processes. If using threads and workers together +# the concurrency of the application would be max `threads` * `workers`. +# Workers do not work on JRuby or Windows (both of which do not support +# processes). +# +# workers ENV.fetch("WEB_CONCURRENCY") { 2 } + +# Use the `preload_app!` method when specifying a `workers` number. +# This directive tells Puma to first boot the application and load code +# before forking the application. This takes advantage of Copy On Write +# process behavior so workers use less memory. +# +# preload_app! + +# Allow puma to be restarted by `bin/rails restart` command. +plugin :tmp_restart diff --git a/week_3/activity-tracker/config/routes.rb b/week_3/activity-tracker/config/routes.rb new file mode 100644 index 00000000..262ffd54 --- /dev/null +++ b/week_3/activity-tracker/config/routes.rb @@ -0,0 +1,6 @@ +Rails.application.routes.draw do + # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html + + # Defines the root path route ("/") + # root "articles#index" +end diff --git a/week_3/activity-tracker/config/storage.yml b/week_3/activity-tracker/config/storage.yml new file mode 100644 index 00000000..4942ab66 --- /dev/null +++ b/week_3/activity-tracker/config/storage.yml @@ -0,0 +1,34 @@ +test: + service: Disk + root: <%= Rails.root.join("tmp/storage") %> + +local: + service: Disk + root: <%= Rails.root.join("storage") %> + +# Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) +# amazon: +# service: S3 +# access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> +# secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> +# region: us-east-1 +# bucket: your_own_bucket-<%= Rails.env %> + +# Remember not to checkin your GCS keyfile to a repository +# google: +# service: GCS +# project: your_project +# credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> +# bucket: your_own_bucket-<%= Rails.env %> + +# Use bin/rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) +# microsoft: +# service: AzureStorage +# storage_account_name: your_account_name +# storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> +# container: your_container_name-<%= Rails.env %> + +# mirror: +# service: Mirror +# primary: local +# mirrors: [ amazon, google, microsoft ] diff --git a/week_3/activity-tracker/db/migrate/20230207164018_create_activities.rb b/week_3/activity-tracker/db/migrate/20230207164018_create_activities.rb new file mode 100644 index 00000000..002ad6a2 --- /dev/null +++ b/week_3/activity-tracker/db/migrate/20230207164018_create_activities.rb @@ -0,0 +1,13 @@ +class CreateActivities < ActiveRecord::Migration[7.0] + def change + create_table :activities do |t| + t.string :title + t.string :type + t.datetime :start + t.decimal :duration + t.integer :calories + + t.timestamps + end + end +end diff --git a/week_3/activity-tracker/db/schema.rb b/week_3/activity-tracker/db/schema.rb new file mode 100644 index 00000000..b03ab78a --- /dev/null +++ b/week_3/activity-tracker/db/schema.rb @@ -0,0 +1,24 @@ +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# This file is the source Rails uses to define your schema when running `bin/rails +# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to +# be faster and is potentially less error prone than running all of your +# migrations from scratch. Old migrations may fail to apply correctly if those +# migrations use external dependencies or application code. +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema[7.0].define(version: 2023_02_07_164018) do + create_table "activities", force: :cascade do |t| + t.string "title" + t.string "type" + t.datetime "start" + t.decimal "duration" + t.integer "calories" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + +end diff --git a/week_3/activity-tracker/db/seeds.rb b/week_3/activity-tracker/db/seeds.rb new file mode 100644 index 00000000..bc25fce3 --- /dev/null +++ b/week_3/activity-tracker/db/seeds.rb @@ -0,0 +1,7 @@ +# This file should contain all the record creation needed to seed the database with its default values. +# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). +# +# Examples: +# +# movies = Movie.create([{ name: "Star Wars" }, { name: "Lord of the Rings" }]) +# Character.create(name: "Luke", movie: movies.first) diff --git a/week_3/activity-tracker/lib/assets/.keep b/week_3/activity-tracker/lib/assets/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/lib/tasks/.keep b/week_3/activity-tracker/lib/tasks/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/public/404.html b/week_3/activity-tracker/public/404.html new file mode 100644 index 00000000..2be3af26 --- /dev/null +++ b/week_3/activity-tracker/public/404.html @@ -0,0 +1,67 @@ + + + + The page you were looking for doesn't exist (404) + + + + + + +
+
+

The page you were looking for doesn't exist.

+

You may have mistyped the address or the page may have moved.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/week_3/activity-tracker/public/422.html b/week_3/activity-tracker/public/422.html new file mode 100644 index 00000000..c08eac0d --- /dev/null +++ b/week_3/activity-tracker/public/422.html @@ -0,0 +1,67 @@ + + + + The change you wanted was rejected (422) + + + + + + +
+
+

The change you wanted was rejected.

+

Maybe you tried to change something you didn't have access to.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/week_3/activity-tracker/public/500.html b/week_3/activity-tracker/public/500.html new file mode 100644 index 00000000..78a030af --- /dev/null +++ b/week_3/activity-tracker/public/500.html @@ -0,0 +1,66 @@ + + + + We're sorry, but something went wrong (500) + + + + + + +
+
+

We're sorry, but something went wrong.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/week_3/activity-tracker/public/apple-touch-icon-precomposed.png b/week_3/activity-tracker/public/apple-touch-icon-precomposed.png new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/public/apple-touch-icon.png b/week_3/activity-tracker/public/apple-touch-icon.png new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/public/favicon.ico b/week_3/activity-tracker/public/favicon.ico new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/public/robots.txt b/week_3/activity-tracker/public/robots.txt new file mode 100644 index 00000000..c19f78ab --- /dev/null +++ b/week_3/activity-tracker/public/robots.txt @@ -0,0 +1 @@ +# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file diff --git a/week_3/activity-tracker/storage/.keep b/week_3/activity-tracker/storage/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/test/application_system_test_case.rb b/week_3/activity-tracker/test/application_system_test_case.rb new file mode 100644 index 00000000..d19212ab --- /dev/null +++ b/week_3/activity-tracker/test/application_system_test_case.rb @@ -0,0 +1,5 @@ +require "test_helper" + +class ApplicationSystemTestCase < ActionDispatch::SystemTestCase + driven_by :selenium, using: :chrome, screen_size: [1400, 1400] +end diff --git a/week_3/activity-tracker/test/channels/application_cable/connection_test.rb b/week_3/activity-tracker/test/channels/application_cable/connection_test.rb new file mode 100644 index 00000000..800405f1 --- /dev/null +++ b/week_3/activity-tracker/test/channels/application_cable/connection_test.rb @@ -0,0 +1,11 @@ +require "test_helper" + +class ApplicationCable::ConnectionTest < ActionCable::Connection::TestCase + # test "connects with cookies" do + # cookies.signed[:user_id] = 42 + # + # connect + # + # assert_equal connection.user_id, "42" + # end +end diff --git a/week_3/activity-tracker/test/controllers/.keep b/week_3/activity-tracker/test/controllers/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/test/fixtures/activities.yml b/week_3/activity-tracker/test/fixtures/activities.yml new file mode 100644 index 00000000..72efbb8c --- /dev/null +++ b/week_3/activity-tracker/test/fixtures/activities.yml @@ -0,0 +1,15 @@ +# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +one: + title: MyString + type: + start: 2023-02-07 16:40:18 + duration: 9.99 + calories: 1 + +two: + title: MyString + type: + start: 2023-02-07 16:40:18 + duration: 9.99 + calories: 1 diff --git a/week_3/activity-tracker/test/fixtures/files/.keep b/week_3/activity-tracker/test/fixtures/files/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/test/helpers/.keep b/week_3/activity-tracker/test/helpers/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/test/integration/.keep b/week_3/activity-tracker/test/integration/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/test/mailers/.keep b/week_3/activity-tracker/test/mailers/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/test/models/.keep b/week_3/activity-tracker/test/models/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/test/models/activity_model_test.rb b/week_3/activity-tracker/test/models/activity_model_test.rb new file mode 100644 index 00000000..9af6029e --- /dev/null +++ b/week_3/activity-tracker/test/models/activity_model_test.rb @@ -0,0 +1,23 @@ +require "test_helper" + +class ActivityTest < ActiveSupport::TestCase + test 'has a string column title' do + assert_equal :string, Activity.type_for_attribute('title').type + end + + test 'has a string column type' do + assert_equal :string, Activity.type_for_attribute('type').type + end + + test 'has a datetime column start' do + assert_equal :datetime, Activity.type_for_attribute('start').type + end + + test 'has a decimal column duration' do + assert_equal :decimal, Activity.type_for_attribute('duration').type + end + + test 'has an integer column calories' do + assert_equal :integer, Activity.type_for_attribute('calories').type + end +end \ No newline at end of file diff --git a/week_3/activity-tracker/test/models/activity_test.rb b/week_3/activity-tracker/test/models/activity_test.rb new file mode 100644 index 00000000..c07a8b91 --- /dev/null +++ b/week_3/activity-tracker/test/models/activity_test.rb @@ -0,0 +1,7 @@ +require "test_helper" + +class ActivityTest < ActiveSupport::TestCase + # test "the truth" do + # assert true + # end +end diff --git a/week_3/activity-tracker/test/system/.keep b/week_3/activity-tracker/test/system/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/test/test_helper.rb b/week_3/activity-tracker/test/test_helper.rb new file mode 100644 index 00000000..d713e377 --- /dev/null +++ b/week_3/activity-tracker/test/test_helper.rb @@ -0,0 +1,13 @@ +ENV["RAILS_ENV"] ||= "test" +require_relative "../config/environment" +require "rails/test_help" + +class ActiveSupport::TestCase + # Run tests in parallel with specified workers + parallelize(workers: :number_of_processors) + + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + fixtures :all + + # Add more helper methods to be used by all tests here... +end diff --git a/week_3/activity-tracker/vendor/.keep b/week_3/activity-tracker/vendor/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/vendor/javascript/.keep b/week_3/activity-tracker/vendor/javascript/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/football/README.md b/week_3/football/README.md index 24e18349..c642794a 100644 --- a/week_3/football/README.md +++ b/week_3/football/README.md @@ -75,6 +75,9 @@ rails db:fixtures:load ``` This adds some sample data(/test/fixtures/football_players.yml) to the database. +## Assignment +> For this assignment you have to implement the function inside [app/models/football_player.rb](https://github.com/IRIS-NITK/IRIS-RoR-Bootcamp-2022/blob/main/week_3/football/app/models/football_player.rb) + ### Creating Records The INSERT INTO statement is used to insert new records in a table @@ -216,3 +219,17 @@ FootballPlayer.find_by(name: "Messi").destroy - [DELETE | ActiveRecord](https://guides.rubyonrails.org/active_record_basics.html#delete) + +Once you start implementing functions in app/models/football_player.rb, you can test your code. + +```bash +rails test:models +``` + +# Rails console +The Rails console is useful for testing out quick ideas with code and debugging applications. + +```bash +rails console +``` +![image](https://user-images.githubusercontent.com/66632353/212348259-fbf59057-7eb1-4e1a-af8c-634161164afc.png) diff --git a/week_3/football/app/assets/builds/application.js b/week_3/football/app/assets/builds/application.js index f65952ea..649a2cba 100644 --- a/week_3/football/app/assets/builds/application.js +++ b/week_3/football/app/assets/builds/application.js @@ -1,3 +1,11963 @@ (() => { + var __defProp = Object.defineProperty; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __esm = (fn2, res) => function __init() { + return fn2 && (res = (0, fn2[__getOwnPropNames(fn2)[0]])(fn2 = 0)), res; + }; + var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); + }; + + // node_modules/@rails/actioncable/src/adapters.js + var adapters_default; + var init_adapters = __esm({ + "node_modules/@rails/actioncable/src/adapters.js"() { + adapters_default = { + logger: self.console, + WebSocket: self.WebSocket + }; + } + }); + + // node_modules/@rails/actioncable/src/logger.js + var logger_default; + var init_logger = __esm({ + "node_modules/@rails/actioncable/src/logger.js"() { + init_adapters(); + logger_default = { + log(...messages) { + if (this.enabled) { + messages.push(Date.now()); + adapters_default.logger.log("[ActionCable]", ...messages); + } + } + }; + } + }); + + // node_modules/@rails/actioncable/src/connection_monitor.js + var now, secondsSince, ConnectionMonitor, connection_monitor_default; + var init_connection_monitor = __esm({ + "node_modules/@rails/actioncable/src/connection_monitor.js"() { + init_logger(); + now = () => new Date().getTime(); + secondsSince = (time) => (now() - time) / 1e3; + ConnectionMonitor = class { + constructor(connection) { + this.visibilityDidChange = this.visibilityDidChange.bind(this); + this.connection = connection; + this.reconnectAttempts = 0; + } + start() { + if (!this.isRunning()) { + this.startedAt = now(); + delete this.stoppedAt; + this.startPolling(); + addEventListener("visibilitychange", this.visibilityDidChange); + logger_default.log(`ConnectionMonitor started. stale threshold = ${this.constructor.staleThreshold} s`); + } + } + stop() { + if (this.isRunning()) { + this.stoppedAt = now(); + this.stopPolling(); + removeEventListener("visibilitychange", this.visibilityDidChange); + logger_default.log("ConnectionMonitor stopped"); + } + } + isRunning() { + return this.startedAt && !this.stoppedAt; + } + recordPing() { + this.pingedAt = now(); + } + recordConnect() { + this.reconnectAttempts = 0; + this.recordPing(); + delete this.disconnectedAt; + logger_default.log("ConnectionMonitor recorded connect"); + } + recordDisconnect() { + this.disconnectedAt = now(); + logger_default.log("ConnectionMonitor recorded disconnect"); + } + // Private + startPolling() { + this.stopPolling(); + this.poll(); + } + stopPolling() { + clearTimeout(this.pollTimeout); + } + poll() { + this.pollTimeout = setTimeout( + () => { + this.reconnectIfStale(); + this.poll(); + }, + this.getPollInterval() + ); + } + getPollInterval() { + const { staleThreshold, reconnectionBackoffRate } = this.constructor; + const backoff = Math.pow(1 + reconnectionBackoffRate, Math.min(this.reconnectAttempts, 10)); + const jitterMax = this.reconnectAttempts === 0 ? 1 : reconnectionBackoffRate; + const jitter = jitterMax * Math.random(); + return staleThreshold * 1e3 * backoff * (1 + jitter); + } + reconnectIfStale() { + if (this.connectionIsStale()) { + logger_default.log(`ConnectionMonitor detected stale connection. reconnectAttempts = ${this.reconnectAttempts}, time stale = ${secondsSince(this.refreshedAt)} s, stale threshold = ${this.constructor.staleThreshold} s`); + this.reconnectAttempts++; + if (this.disconnectedRecently()) { + logger_default.log(`ConnectionMonitor skipping reopening recent disconnect. time disconnected = ${secondsSince(this.disconnectedAt)} s`); + } else { + logger_default.log("ConnectionMonitor reopening"); + this.connection.reopen(); + } + } + } + get refreshedAt() { + return this.pingedAt ? this.pingedAt : this.startedAt; + } + connectionIsStale() { + return secondsSince(this.refreshedAt) > this.constructor.staleThreshold; + } + disconnectedRecently() { + return this.disconnectedAt && secondsSince(this.disconnectedAt) < this.constructor.staleThreshold; + } + visibilityDidChange() { + if (document.visibilityState === "visible") { + setTimeout( + () => { + if (this.connectionIsStale() || !this.connection.isOpen()) { + logger_default.log(`ConnectionMonitor reopening stale connection on visibilitychange. visibilityState = ${document.visibilityState}`); + this.connection.reopen(); + } + }, + 200 + ); + } + } + }; + ConnectionMonitor.staleThreshold = 6; + ConnectionMonitor.reconnectionBackoffRate = 0.15; + connection_monitor_default = ConnectionMonitor; + } + }); + + // node_modules/@rails/actioncable/src/internal.js + var internal_default; + var init_internal = __esm({ + "node_modules/@rails/actioncable/src/internal.js"() { + internal_default = { + "message_types": { + "welcome": "welcome", + "disconnect": "disconnect", + "ping": "ping", + "confirmation": "confirm_subscription", + "rejection": "reject_subscription" + }, + "disconnect_reasons": { + "unauthorized": "unauthorized", + "invalid_request": "invalid_request", + "server_restart": "server_restart" + }, + "default_mount_path": "/cable", + "protocols": [ + "actioncable-v1-json", + "actioncable-unsupported" + ] + }; + } + }); + + // node_modules/@rails/actioncable/src/connection.js + var message_types, protocols, supportedProtocols, indexOf, Connection, connection_default; + var init_connection = __esm({ + "node_modules/@rails/actioncable/src/connection.js"() { + init_adapters(); + init_connection_monitor(); + init_internal(); + init_logger(); + ({ message_types, protocols } = internal_default); + supportedProtocols = protocols.slice(0, protocols.length - 1); + indexOf = [].indexOf; + Connection = class { + constructor(consumer2) { + this.open = this.open.bind(this); + this.consumer = consumer2; + this.subscriptions = this.consumer.subscriptions; + this.monitor = new connection_monitor_default(this); + this.disconnected = true; + } + send(data) { + if (this.isOpen()) { + this.webSocket.send(JSON.stringify(data)); + return true; + } else { + return false; + } + } + open() { + if (this.isActive()) { + logger_default.log(`Attempted to open WebSocket, but existing socket is ${this.getState()}`); + return false; + } else { + logger_default.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${protocols}`); + if (this.webSocket) { + this.uninstallEventHandlers(); + } + this.webSocket = new adapters_default.WebSocket(this.consumer.url, protocols); + this.installEventHandlers(); + this.monitor.start(); + return true; + } + } + close({ allowReconnect } = { allowReconnect: true }) { + if (!allowReconnect) { + this.monitor.stop(); + } + if (this.isOpen()) { + return this.webSocket.close(); + } + } + reopen() { + logger_default.log(`Reopening WebSocket, current state is ${this.getState()}`); + if (this.isActive()) { + try { + return this.close(); + } catch (error2) { + logger_default.log("Failed to reopen WebSocket", error2); + } finally { + logger_default.log(`Reopening WebSocket in ${this.constructor.reopenDelay}ms`); + setTimeout(this.open, this.constructor.reopenDelay); + } + } else { + return this.open(); + } + } + getProtocol() { + if (this.webSocket) { + return this.webSocket.protocol; + } + } + isOpen() { + return this.isState("open"); + } + isActive() { + return this.isState("open", "connecting"); + } + // Private + isProtocolSupported() { + return indexOf.call(supportedProtocols, this.getProtocol()) >= 0; + } + isState(...states) { + return indexOf.call(states, this.getState()) >= 0; + } + getState() { + if (this.webSocket) { + for (let state in adapters_default.WebSocket) { + if (adapters_default.WebSocket[state] === this.webSocket.readyState) { + return state.toLowerCase(); + } + } + } + return null; + } + installEventHandlers() { + for (let eventName in this.events) { + const handler = this.events[eventName].bind(this); + this.webSocket[`on${eventName}`] = handler; + } + } + uninstallEventHandlers() { + for (let eventName in this.events) { + this.webSocket[`on${eventName}`] = function() { + }; + } + } + }; + Connection.reopenDelay = 500; + Connection.prototype.events = { + message(event) { + if (!this.isProtocolSupported()) { + return; + } + const { identifier, message, reason, reconnect, type } = JSON.parse(event.data); + switch (type) { + case message_types.welcome: + this.monitor.recordConnect(); + return this.subscriptions.reload(); + case message_types.disconnect: + logger_default.log(`Disconnecting. Reason: ${reason}`); + return this.close({ allowReconnect: reconnect }); + case message_types.ping: + return this.monitor.recordPing(); + case message_types.confirmation: + this.subscriptions.confirmSubscription(identifier); + return this.subscriptions.notify(identifier, "connected"); + case message_types.rejection: + return this.subscriptions.reject(identifier); + default: + return this.subscriptions.notify(identifier, "received", message); + } + }, + open() { + logger_default.log(`WebSocket onopen event, using '${this.getProtocol()}' subprotocol`); + this.disconnected = false; + if (!this.isProtocolSupported()) { + logger_default.log("Protocol is unsupported. Stopping monitor and disconnecting."); + return this.close({ allowReconnect: false }); + } + }, + close(event) { + logger_default.log("WebSocket onclose event"); + if (this.disconnected) { + return; + } + this.disconnected = true; + this.monitor.recordDisconnect(); + return this.subscriptions.notifyAll("disconnected", { willAttemptReconnect: this.monitor.isRunning() }); + }, + error() { + logger_default.log("WebSocket onerror event"); + } + }; + connection_default = Connection; + } + }); + + // node_modules/@rails/actioncable/src/subscription.js + var extend, Subscription; + var init_subscription = __esm({ + "node_modules/@rails/actioncable/src/subscription.js"() { + extend = function(object, properties) { + if (properties != null) { + for (let key in properties) { + const value = properties[key]; + object[key] = value; + } + } + return object; + }; + Subscription = class { + constructor(consumer2, params = {}, mixin) { + this.consumer = consumer2; + this.identifier = JSON.stringify(params); + extend(this, mixin); + } + // Perform a channel action with the optional data passed as an attribute + perform(action, data = {}) { + data.action = action; + return this.send(data); + } + send(data) { + return this.consumer.send({ command: "message", identifier: this.identifier, data: JSON.stringify(data) }); + } + unsubscribe() { + return this.consumer.subscriptions.remove(this); + } + }; + } + }); + + // node_modules/@rails/actioncable/src/subscription_guarantor.js + var SubscriptionGuarantor, subscription_guarantor_default; + var init_subscription_guarantor = __esm({ + "node_modules/@rails/actioncable/src/subscription_guarantor.js"() { + init_logger(); + SubscriptionGuarantor = class { + constructor(subscriptions) { + this.subscriptions = subscriptions; + this.pendingSubscriptions = []; + } + guarantee(subscription) { + if (this.pendingSubscriptions.indexOf(subscription) == -1) { + logger_default.log(`SubscriptionGuarantor guaranteeing ${subscription.identifier}`); + this.pendingSubscriptions.push(subscription); + } else { + logger_default.log(`SubscriptionGuarantor already guaranteeing ${subscription.identifier}`); + } + this.startGuaranteeing(); + } + forget(subscription) { + logger_default.log(`SubscriptionGuarantor forgetting ${subscription.identifier}`); + this.pendingSubscriptions = this.pendingSubscriptions.filter((s) => s !== subscription); + } + startGuaranteeing() { + this.stopGuaranteeing(); + this.retrySubscribing(); + } + stopGuaranteeing() { + clearTimeout(this.retryTimeout); + } + retrySubscribing() { + this.retryTimeout = setTimeout( + () => { + if (this.subscriptions && typeof this.subscriptions.subscribe === "function") { + this.pendingSubscriptions.map((subscription) => { + logger_default.log(`SubscriptionGuarantor resubscribing ${subscription.identifier}`); + this.subscriptions.subscribe(subscription); + }); + } + }, + 500 + ); + } + }; + subscription_guarantor_default = SubscriptionGuarantor; + } + }); + + // node_modules/@rails/actioncable/src/subscriptions.js + var Subscriptions; + var init_subscriptions = __esm({ + "node_modules/@rails/actioncable/src/subscriptions.js"() { + init_subscription(); + init_subscription_guarantor(); + init_logger(); + Subscriptions = class { + constructor(consumer2) { + this.consumer = consumer2; + this.guarantor = new subscription_guarantor_default(this); + this.subscriptions = []; + } + create(channelName, mixin) { + const channel = channelName; + const params = typeof channel === "object" ? channel : { channel }; + const subscription = new Subscription(this.consumer, params, mixin); + return this.add(subscription); + } + // Private + add(subscription) { + this.subscriptions.push(subscription); + this.consumer.ensureActiveConnection(); + this.notify(subscription, "initialized"); + this.subscribe(subscription); + return subscription; + } + remove(subscription) { + this.forget(subscription); + if (!this.findAll(subscription.identifier).length) { + this.sendCommand(subscription, "unsubscribe"); + } + return subscription; + } + reject(identifier) { + return this.findAll(identifier).map((subscription) => { + this.forget(subscription); + this.notify(subscription, "rejected"); + return subscription; + }); + } + forget(subscription) { + this.guarantor.forget(subscription); + this.subscriptions = this.subscriptions.filter((s) => s !== subscription); + return subscription; + } + findAll(identifier) { + return this.subscriptions.filter((s) => s.identifier === identifier); + } + reload() { + return this.subscriptions.map((subscription) => this.subscribe(subscription)); + } + notifyAll(callbackName, ...args) { + return this.subscriptions.map((subscription) => this.notify(subscription, callbackName, ...args)); + } + notify(subscription, callbackName, ...args) { + let subscriptions; + if (typeof subscription === "string") { + subscriptions = this.findAll(subscription); + } else { + subscriptions = [subscription]; + } + return subscriptions.map((subscription2) => typeof subscription2[callbackName] === "function" ? subscription2[callbackName](...args) : void 0); + } + subscribe(subscription) { + if (this.sendCommand(subscription, "subscribe")) { + this.guarantor.guarantee(subscription); + } + } + confirmSubscription(identifier) { + logger_default.log(`Subscription confirmed ${identifier}`); + this.findAll(identifier).map((subscription) => this.guarantor.forget(subscription)); + } + sendCommand(subscription, command) { + const { identifier } = subscription; + return this.consumer.send({ command, identifier }); + } + }; + } + }); + + // node_modules/@rails/actioncable/src/consumer.js + function createWebSocketURL(url) { + if (typeof url === "function") { + url = url(); + } + if (url && !/^wss?:/i.test(url)) { + const a = document.createElement("a"); + a.href = url; + a.href = a.href; + a.protocol = a.protocol.replace("http", "ws"); + return a.href; + } else { + return url; + } + } + var Consumer; + var init_consumer = __esm({ + "node_modules/@rails/actioncable/src/consumer.js"() { + init_connection(); + init_subscriptions(); + Consumer = class { + constructor(url) { + this._url = url; + this.subscriptions = new Subscriptions(this); + this.connection = new connection_default(this); + } + get url() { + return createWebSocketURL(this._url); + } + send(data) { + return this.connection.send(data); + } + connect() { + return this.connection.open(); + } + disconnect() { + return this.connection.close({ allowReconnect: false }); + } + ensureActiveConnection() { + if (!this.connection.isActive()) { + return this.connection.open(); + } + } + }; + } + }); + + // node_modules/@rails/actioncable/src/index.js + var src_exports = {}; + __export(src_exports, { + Connection: () => connection_default, + ConnectionMonitor: () => connection_monitor_default, + Consumer: () => Consumer, + INTERNAL: () => internal_default, + Subscription: () => Subscription, + SubscriptionGuarantor: () => subscription_guarantor_default, + Subscriptions: () => Subscriptions, + adapters: () => adapters_default, + createConsumer: () => createConsumer, + createWebSocketURL: () => createWebSocketURL, + getConfig: () => getConfig, + logger: () => logger_default + }); + function createConsumer(url = getConfig("url") || internal_default.default_mount_path) { + return new Consumer(url); + } + function getConfig(name) { + const element = document.head.querySelector(`meta[name='action-cable-${name}']`); + if (element) { + return element.getAttribute("content"); + } + } + var init_src = __esm({ + "node_modules/@rails/actioncable/src/index.js"() { + init_connection(); + init_connection_monitor(); + init_consumer(); + init_internal(); + init_subscription(); + init_subscriptions(); + init_subscription_guarantor(); + init_adapters(); + init_logger(); + } + }); + + // node_modules/@hotwired/turbo/dist/turbo.es2017-esm.js + (function() { + if (window.Reflect === void 0 || window.customElements === void 0 || window.customElements.polyfillWrapFlushCallback) { + return; + } + const BuiltInHTMLElement = HTMLElement; + const wrapperForTheName = { + HTMLElement: function HTMLElement2() { + return Reflect.construct(BuiltInHTMLElement, [], this.constructor); + } + }; + window.HTMLElement = wrapperForTheName["HTMLElement"]; + HTMLElement.prototype = BuiltInHTMLElement.prototype; + HTMLElement.prototype.constructor = HTMLElement; + Object.setPrototypeOf(HTMLElement, BuiltInHTMLElement); + })(); + (function(prototype) { + if (typeof prototype.requestSubmit == "function") + return; + prototype.requestSubmit = function(submitter) { + if (submitter) { + validateSubmitter(submitter, this); + submitter.click(); + } else { + submitter = document.createElement("input"); + submitter.type = "submit"; + submitter.hidden = true; + this.appendChild(submitter); + submitter.click(); + this.removeChild(submitter); + } + }; + function validateSubmitter(submitter, form) { + submitter instanceof HTMLElement || raise(TypeError, "parameter 1 is not of type 'HTMLElement'"); + submitter.type == "submit" || raise(TypeError, "The specified element is not a submit button"); + submitter.form == form || raise(DOMException, "The specified element is not owned by this form element", "NotFoundError"); + } + function raise(errorConstructor, message, name) { + throw new errorConstructor("Failed to execute 'requestSubmit' on 'HTMLFormElement': " + message + ".", name); + } + })(HTMLFormElement.prototype); + var submittersByForm = /* @__PURE__ */ new WeakMap(); + function findSubmitterFromClickTarget(target) { + const element = target instanceof Element ? target : target instanceof Node ? target.parentElement : null; + const candidate = element ? element.closest("input, button") : null; + return (candidate === null || candidate === void 0 ? void 0 : candidate.type) == "submit" ? candidate : null; + } + function clickCaptured(event) { + const submitter = findSubmitterFromClickTarget(event.target); + if (submitter && submitter.form) { + submittersByForm.set(submitter.form, submitter); + } + } + (function() { + if ("submitter" in Event.prototype) + return; + let prototype; + if ("SubmitEvent" in window && /Apple Computer/.test(navigator.vendor)) { + prototype = window.SubmitEvent.prototype; + } else if ("SubmitEvent" in window) { + return; + } else { + prototype = window.Event.prototype; + } + addEventListener("click", clickCaptured, true); + Object.defineProperty(prototype, "submitter", { + get() { + if (this.type == "submit" && this.target instanceof HTMLFormElement) { + return submittersByForm.get(this.target); + } + } + }); + })(); + var FrameLoadingStyle; + (function(FrameLoadingStyle2) { + FrameLoadingStyle2["eager"] = "eager"; + FrameLoadingStyle2["lazy"] = "lazy"; + })(FrameLoadingStyle || (FrameLoadingStyle = {})); + var FrameElement = class extends HTMLElement { + constructor() { + super(); + this.loaded = Promise.resolve(); + this.delegate = new FrameElement.delegateConstructor(this); + } + static get observedAttributes() { + return ["disabled", "complete", "loading", "src"]; + } + connectedCallback() { + this.delegate.connect(); + } + disconnectedCallback() { + this.delegate.disconnect(); + } + reload() { + return this.delegate.sourceURLReloaded(); + } + attributeChangedCallback(name) { + if (name == "loading") { + this.delegate.loadingStyleChanged(); + } else if (name == "complete") { + this.delegate.completeChanged(); + } else if (name == "src") { + this.delegate.sourceURLChanged(); + } else { + this.delegate.disabledChanged(); + } + } + get src() { + return this.getAttribute("src"); + } + set src(value) { + if (value) { + this.setAttribute("src", value); + } else { + this.removeAttribute("src"); + } + } + get loading() { + return frameLoadingStyleFromString(this.getAttribute("loading") || ""); + } + set loading(value) { + if (value) { + this.setAttribute("loading", value); + } else { + this.removeAttribute("loading"); + } + } + get disabled() { + return this.hasAttribute("disabled"); + } + set disabled(value) { + if (value) { + this.setAttribute("disabled", ""); + } else { + this.removeAttribute("disabled"); + } + } + get autoscroll() { + return this.hasAttribute("autoscroll"); + } + set autoscroll(value) { + if (value) { + this.setAttribute("autoscroll", ""); + } else { + this.removeAttribute("autoscroll"); + } + } + get complete() { + return !this.delegate.isLoading; + } + get isActive() { + return this.ownerDocument === document && !this.isPreview; + } + get isPreview() { + var _a, _b; + return (_b = (_a = this.ownerDocument) === null || _a === void 0 ? void 0 : _a.documentElement) === null || _b === void 0 ? void 0 : _b.hasAttribute("data-turbo-preview"); + } + }; + function frameLoadingStyleFromString(style) { + switch (style.toLowerCase()) { + case "lazy": + return FrameLoadingStyle.lazy; + default: + return FrameLoadingStyle.eager; + } + } + function expandURL(locatable) { + return new URL(locatable.toString(), document.baseURI); + } + function getAnchor(url) { + let anchorMatch; + if (url.hash) { + return url.hash.slice(1); + } else if (anchorMatch = url.href.match(/#(.*)$/)) { + return anchorMatch[1]; + } + } + function getAction(form, submitter) { + const action = (submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute("formaction")) || form.getAttribute("action") || form.action; + return expandURL(action); + } + function getExtension(url) { + return (getLastPathComponent(url).match(/\.[^.]*$/) || [])[0] || ""; + } + function isHTML(url) { + return !!getExtension(url).match(/^(?:|\.(?:htm|html|xhtml|php))$/); + } + function isPrefixedBy(baseURL, url) { + const prefix = getPrefix(url); + return baseURL.href === expandURL(prefix).href || baseURL.href.startsWith(prefix); + } + function locationIsVisitable(location2, rootLocation) { + return isPrefixedBy(location2, rootLocation) && isHTML(location2); + } + function getRequestURL(url) { + const anchor = getAnchor(url); + return anchor != null ? url.href.slice(0, -(anchor.length + 1)) : url.href; + } + function toCacheKey(url) { + return getRequestURL(url); + } + function urlsAreEqual(left2, right2) { + return expandURL(left2).href == expandURL(right2).href; + } + function getPathComponents(url) { + return url.pathname.split("/").slice(1); + } + function getLastPathComponent(url) { + return getPathComponents(url).slice(-1)[0]; + } + function getPrefix(url) { + return addTrailingSlash(url.origin + url.pathname); + } + function addTrailingSlash(value) { + return value.endsWith("/") ? value : value + "/"; + } + var FetchResponse = class { + constructor(response) { + this.response = response; + } + get succeeded() { + return this.response.ok; + } + get failed() { + return !this.succeeded; + } + get clientError() { + return this.statusCode >= 400 && this.statusCode <= 499; + } + get serverError() { + return this.statusCode >= 500 && this.statusCode <= 599; + } + get redirected() { + return this.response.redirected; + } + get location() { + return expandURL(this.response.url); + } + get isHTML() { + return this.contentType && this.contentType.match(/^(?:text\/([^\s;,]+\b)?html|application\/xhtml\+xml)\b/); + } + get statusCode() { + return this.response.status; + } + get contentType() { + return this.header("Content-Type"); + } + get responseText() { + return this.response.clone().text(); + } + get responseHTML() { + if (this.isHTML) { + return this.response.clone().text(); + } else { + return Promise.resolve(void 0); + } + } + header(name) { + return this.response.headers.get(name); + } + }; + function isAction(action) { + return action == "advance" || action == "replace" || action == "restore"; + } + function activateScriptElement(element) { + if (element.getAttribute("data-turbo-eval") == "false") { + return element; + } else { + const createdScriptElement = document.createElement("script"); + const cspNonce = getMetaContent("csp-nonce"); + if (cspNonce) { + createdScriptElement.nonce = cspNonce; + } + createdScriptElement.textContent = element.textContent; + createdScriptElement.async = false; + copyElementAttributes(createdScriptElement, element); + return createdScriptElement; + } + } + function copyElementAttributes(destinationElement, sourceElement) { + for (const { name, value } of sourceElement.attributes) { + destinationElement.setAttribute(name, value); + } + } + function createDocumentFragment(html) { + const template = document.createElement("template"); + template.innerHTML = html; + return template.content; + } + function dispatch(eventName, { target, cancelable, detail } = {}) { + const event = new CustomEvent(eventName, { + cancelable, + bubbles: true, + detail + }); + if (target && target.isConnected) { + target.dispatchEvent(event); + } else { + document.documentElement.dispatchEvent(event); + } + return event; + } + function nextAnimationFrame() { + return new Promise((resolve) => requestAnimationFrame(() => resolve())); + } + function nextEventLoopTick() { + return new Promise((resolve) => setTimeout(() => resolve(), 0)); + } + function nextMicrotask() { + return Promise.resolve(); + } + function parseHTMLDocument(html = "") { + return new DOMParser().parseFromString(html, "text/html"); + } + function unindent(strings, ...values) { + const lines = interpolate(strings, values).replace(/^\n/, "").split("\n"); + const match = lines[0].match(/^\s+/); + const indent = match ? match[0].length : 0; + return lines.map((line) => line.slice(indent)).join("\n"); + } + function interpolate(strings, values) { + return strings.reduce((result, string, i) => { + const value = values[i] == void 0 ? "" : values[i]; + return result + string + value; + }, ""); + } + function uuid() { + return Array.from({ length: 36 }).map((_, i) => { + if (i == 8 || i == 13 || i == 18 || i == 23) { + return "-"; + } else if (i == 14) { + return "4"; + } else if (i == 19) { + return (Math.floor(Math.random() * 4) + 8).toString(16); + } else { + return Math.floor(Math.random() * 15).toString(16); + } + }).join(""); + } + function getAttribute(attributeName, ...elements) { + for (const value of elements.map((element) => element === null || element === void 0 ? void 0 : element.getAttribute(attributeName))) { + if (typeof value == "string") + return value; + } + return null; + } + function hasAttribute(attributeName, ...elements) { + return elements.some((element) => element && element.hasAttribute(attributeName)); + } + function markAsBusy(...elements) { + for (const element of elements) { + if (element.localName == "turbo-frame") { + element.setAttribute("busy", ""); + } + element.setAttribute("aria-busy", "true"); + } + } + function clearBusyState(...elements) { + for (const element of elements) { + if (element.localName == "turbo-frame") { + element.removeAttribute("busy"); + } + element.removeAttribute("aria-busy"); + } + } + function waitForLoad(element, timeoutInMilliseconds = 2e3) { + return new Promise((resolve) => { + const onComplete = () => { + element.removeEventListener("error", onComplete); + element.removeEventListener("load", onComplete); + resolve(); + }; + element.addEventListener("load", onComplete, { once: true }); + element.addEventListener("error", onComplete, { once: true }); + setTimeout(resolve, timeoutInMilliseconds); + }); + } + function getHistoryMethodForAction(action) { + switch (action) { + case "replace": + return history.replaceState; + case "advance": + case "restore": + return history.pushState; + } + } + function getVisitAction(...elements) { + const action = getAttribute("data-turbo-action", ...elements); + return isAction(action) ? action : null; + } + function getMetaElement(name) { + return document.querySelector(`meta[name="${name}"]`); + } + function getMetaContent(name) { + const element = getMetaElement(name); + return element && element.content; + } + function setMetaContent(name, content) { + let element = getMetaElement(name); + if (!element) { + element = document.createElement("meta"); + element.setAttribute("name", name); + document.head.appendChild(element); + } + element.setAttribute("content", content); + return element; + } + var FetchMethod; + (function(FetchMethod2) { + FetchMethod2[FetchMethod2["get"] = 0] = "get"; + FetchMethod2[FetchMethod2["post"] = 1] = "post"; + FetchMethod2[FetchMethod2["put"] = 2] = "put"; + FetchMethod2[FetchMethod2["patch"] = 3] = "patch"; + FetchMethod2[FetchMethod2["delete"] = 4] = "delete"; + })(FetchMethod || (FetchMethod = {})); + function fetchMethodFromString(method) { + switch (method.toLowerCase()) { + case "get": + return FetchMethod.get; + case "post": + return FetchMethod.post; + case "put": + return FetchMethod.put; + case "patch": + return FetchMethod.patch; + case "delete": + return FetchMethod.delete; + } + } + var FetchRequest = class { + constructor(delegate, method, location2, body = new URLSearchParams(), target = null) { + this.abortController = new AbortController(); + this.resolveRequestPromise = (_value) => { + }; + this.delegate = delegate; + this.method = method; + this.headers = this.defaultHeaders; + this.body = body; + this.url = location2; + this.target = target; + } + get location() { + return this.url; + } + get params() { + return this.url.searchParams; + } + get entries() { + return this.body ? Array.from(this.body.entries()) : []; + } + cancel() { + this.abortController.abort(); + } + async perform() { + var _a, _b; + const { fetchOptions } = this; + (_b = (_a = this.delegate).prepareHeadersForRequest) === null || _b === void 0 ? void 0 : _b.call(_a, this.headers, this); + await this.allowRequestToBeIntercepted(fetchOptions); + try { + this.delegate.requestStarted(this); + const response = await fetch(this.url.href, fetchOptions); + return await this.receive(response); + } catch (error2) { + if (error2.name !== "AbortError") { + if (this.willDelegateErrorHandling(error2)) { + this.delegate.requestErrored(this, error2); + } + throw error2; + } + } finally { + this.delegate.requestFinished(this); + } + } + async receive(response) { + const fetchResponse = new FetchResponse(response); + const event = dispatch("turbo:before-fetch-response", { + cancelable: true, + detail: { fetchResponse }, + target: this.target + }); + if (event.defaultPrevented) { + this.delegate.requestPreventedHandlingResponse(this, fetchResponse); + } else if (fetchResponse.succeeded) { + this.delegate.requestSucceededWithResponse(this, fetchResponse); + } else { + this.delegate.requestFailedWithResponse(this, fetchResponse); + } + return fetchResponse; + } + get fetchOptions() { + var _a; + return { + method: FetchMethod[this.method].toUpperCase(), + credentials: "same-origin", + headers: this.headers, + redirect: "follow", + body: this.isIdempotent ? null : this.body, + signal: this.abortSignal, + referrer: (_a = this.delegate.referrer) === null || _a === void 0 ? void 0 : _a.href + }; + } + get defaultHeaders() { + return { + Accept: "text/html, application/xhtml+xml" + }; + } + get isIdempotent() { + return this.method == FetchMethod.get; + } + get abortSignal() { + return this.abortController.signal; + } + acceptResponseType(mimeType) { + this.headers["Accept"] = [mimeType, this.headers["Accept"]].join(", "); + } + async allowRequestToBeIntercepted(fetchOptions) { + const requestInterception = new Promise((resolve) => this.resolveRequestPromise = resolve); + const event = dispatch("turbo:before-fetch-request", { + cancelable: true, + detail: { + fetchOptions, + url: this.url, + resume: this.resolveRequestPromise + }, + target: this.target + }); + if (event.defaultPrevented) + await requestInterception; + } + willDelegateErrorHandling(error2) { + const event = dispatch("turbo:fetch-request-error", { + target: this.target, + cancelable: true, + detail: { request: this, error: error2 } + }); + return !event.defaultPrevented; + } + }; + var AppearanceObserver = class { + constructor(delegate, element) { + this.started = false; + this.intersect = (entries) => { + const lastEntry = entries.slice(-1)[0]; + if (lastEntry === null || lastEntry === void 0 ? void 0 : lastEntry.isIntersecting) { + this.delegate.elementAppearedInViewport(this.element); + } + }; + this.delegate = delegate; + this.element = element; + this.intersectionObserver = new IntersectionObserver(this.intersect); + } + start() { + if (!this.started) { + this.started = true; + this.intersectionObserver.observe(this.element); + } + } + stop() { + if (this.started) { + this.started = false; + this.intersectionObserver.unobserve(this.element); + } + } + }; + var StreamMessage = class { + constructor(fragment) { + this.fragment = importStreamElements(fragment); + } + static wrap(message) { + if (typeof message == "string") { + return new this(createDocumentFragment(message)); + } else { + return message; + } + } + }; + StreamMessage.contentType = "text/vnd.turbo-stream.html"; + function importStreamElements(fragment) { + for (const element of fragment.querySelectorAll("turbo-stream")) { + const streamElement = document.importNode(element, true); + for (const inertScriptElement of streamElement.templateElement.content.querySelectorAll("script")) { + inertScriptElement.replaceWith(activateScriptElement(inertScriptElement)); + } + element.replaceWith(streamElement); + } + return fragment; + } + var FormSubmissionState; + (function(FormSubmissionState2) { + FormSubmissionState2[FormSubmissionState2["initialized"] = 0] = "initialized"; + FormSubmissionState2[FormSubmissionState2["requesting"] = 1] = "requesting"; + FormSubmissionState2[FormSubmissionState2["waiting"] = 2] = "waiting"; + FormSubmissionState2[FormSubmissionState2["receiving"] = 3] = "receiving"; + FormSubmissionState2[FormSubmissionState2["stopping"] = 4] = "stopping"; + FormSubmissionState2[FormSubmissionState2["stopped"] = 5] = "stopped"; + })(FormSubmissionState || (FormSubmissionState = {})); + var FormEnctype; + (function(FormEnctype2) { + FormEnctype2["urlEncoded"] = "application/x-www-form-urlencoded"; + FormEnctype2["multipart"] = "multipart/form-data"; + FormEnctype2["plain"] = "text/plain"; + })(FormEnctype || (FormEnctype = {})); + function formEnctypeFromString(encoding) { + switch (encoding.toLowerCase()) { + case FormEnctype.multipart: + return FormEnctype.multipart; + case FormEnctype.plain: + return FormEnctype.plain; + default: + return FormEnctype.urlEncoded; + } + } + var FormSubmission = class { + constructor(delegate, formElement, submitter, mustRedirect = false) { + this.state = FormSubmissionState.initialized; + this.delegate = delegate; + this.formElement = formElement; + this.submitter = submitter; + this.formData = buildFormData(formElement, submitter); + this.location = expandURL(this.action); + if (this.method == FetchMethod.get) { + mergeFormDataEntries(this.location, [...this.body.entries()]); + } + this.fetchRequest = new FetchRequest(this, this.method, this.location, this.body, this.formElement); + this.mustRedirect = mustRedirect; + } + static confirmMethod(message, _element, _submitter) { + return Promise.resolve(confirm(message)); + } + get method() { + var _a; + const method = ((_a = this.submitter) === null || _a === void 0 ? void 0 : _a.getAttribute("formmethod")) || this.formElement.getAttribute("method") || ""; + return fetchMethodFromString(method.toLowerCase()) || FetchMethod.get; + } + get action() { + var _a; + const formElementAction = typeof this.formElement.action === "string" ? this.formElement.action : null; + if ((_a = this.submitter) === null || _a === void 0 ? void 0 : _a.hasAttribute("formaction")) { + return this.submitter.getAttribute("formaction") || ""; + } else { + return this.formElement.getAttribute("action") || formElementAction || ""; + } + } + get body() { + if (this.enctype == FormEnctype.urlEncoded || this.method == FetchMethod.get) { + return new URLSearchParams(this.stringFormData); + } else { + return this.formData; + } + } + get enctype() { + var _a; + return formEnctypeFromString(((_a = this.submitter) === null || _a === void 0 ? void 0 : _a.getAttribute("formenctype")) || this.formElement.enctype); + } + get isIdempotent() { + return this.fetchRequest.isIdempotent; + } + get stringFormData() { + return [...this.formData].reduce((entries, [name, value]) => { + return entries.concat(typeof value == "string" ? [[name, value]] : []); + }, []); + } + async start() { + const { initialized, requesting } = FormSubmissionState; + const confirmationMessage = getAttribute("data-turbo-confirm", this.submitter, this.formElement); + if (typeof confirmationMessage === "string") { + const answer = await FormSubmission.confirmMethod(confirmationMessage, this.formElement, this.submitter); + if (!answer) { + return; + } + } + if (this.state == initialized) { + this.state = requesting; + return this.fetchRequest.perform(); + } + } + stop() { + const { stopping, stopped } = FormSubmissionState; + if (this.state != stopping && this.state != stopped) { + this.state = stopping; + this.fetchRequest.cancel(); + return true; + } + } + prepareHeadersForRequest(headers, request) { + if (!request.isIdempotent) { + const token = getCookieValue(getMetaContent("csrf-param")) || getMetaContent("csrf-token"); + if (token) { + headers["X-CSRF-Token"] = token; + } + } + if (this.requestAcceptsTurboStreamResponse(request)) { + request.acceptResponseType(StreamMessage.contentType); + } + } + requestStarted(_request) { + var _a; + this.state = FormSubmissionState.waiting; + (_a = this.submitter) === null || _a === void 0 ? void 0 : _a.setAttribute("disabled", ""); + dispatch("turbo:submit-start", { + target: this.formElement, + detail: { formSubmission: this } + }); + this.delegate.formSubmissionStarted(this); + } + requestPreventedHandlingResponse(request, response) { + this.result = { success: response.succeeded, fetchResponse: response }; + } + requestSucceededWithResponse(request, response) { + if (response.clientError || response.serverError) { + this.delegate.formSubmissionFailedWithResponse(this, response); + } else if (this.requestMustRedirect(request) && responseSucceededWithoutRedirect(response)) { + const error2 = new Error("Form responses must redirect to another location"); + this.delegate.formSubmissionErrored(this, error2); + } else { + this.state = FormSubmissionState.receiving; + this.result = { success: true, fetchResponse: response }; + this.delegate.formSubmissionSucceededWithResponse(this, response); + } + } + requestFailedWithResponse(request, response) { + this.result = { success: false, fetchResponse: response }; + this.delegate.formSubmissionFailedWithResponse(this, response); + } + requestErrored(request, error2) { + this.result = { success: false, error: error2 }; + this.delegate.formSubmissionErrored(this, error2); + } + requestFinished(_request) { + var _a; + this.state = FormSubmissionState.stopped; + (_a = this.submitter) === null || _a === void 0 ? void 0 : _a.removeAttribute("disabled"); + dispatch("turbo:submit-end", { + target: this.formElement, + detail: Object.assign({ formSubmission: this }, this.result) + }); + this.delegate.formSubmissionFinished(this); + } + requestMustRedirect(request) { + return !request.isIdempotent && this.mustRedirect; + } + requestAcceptsTurboStreamResponse(request) { + return !request.isIdempotent || hasAttribute("data-turbo-stream", this.submitter, this.formElement); + } + }; + function buildFormData(formElement, submitter) { + const formData = new FormData(formElement); + const name = submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute("name"); + const value = submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute("value"); + if (name) { + formData.append(name, value || ""); + } + return formData; + } + function getCookieValue(cookieName) { + if (cookieName != null) { + const cookies = document.cookie ? document.cookie.split("; ") : []; + const cookie = cookies.find((cookie2) => cookie2.startsWith(cookieName)); + if (cookie) { + const value = cookie.split("=").slice(1).join("="); + return value ? decodeURIComponent(value) : void 0; + } + } + } + function responseSucceededWithoutRedirect(response) { + return response.statusCode == 200 && !response.redirected; + } + function mergeFormDataEntries(url, entries) { + const searchParams = new URLSearchParams(); + for (const [name, value] of entries) { + if (value instanceof File) + continue; + searchParams.append(name, value); + } + url.search = searchParams.toString(); + return url; + } + var Snapshot = class { + constructor(element) { + this.element = element; + } + get activeElement() { + return this.element.ownerDocument.activeElement; + } + get children() { + return [...this.element.children]; + } + hasAnchor(anchor) { + return this.getElementForAnchor(anchor) != null; + } + getElementForAnchor(anchor) { + return anchor ? this.element.querySelector(`[id='${anchor}'], a[name='${anchor}']`) : null; + } + get isConnected() { + return this.element.isConnected; + } + get firstAutofocusableElement() { + const inertDisabledOrHidden = "[inert], :disabled, [hidden], details:not([open]), dialog:not([open])"; + for (const element of this.element.querySelectorAll("[autofocus]")) { + if (element.closest(inertDisabledOrHidden) == null) + return element; + else + continue; + } + return null; + } + get permanentElements() { + return queryPermanentElementsAll(this.element); + } + getPermanentElementById(id) { + return getPermanentElementById(this.element, id); + } + getPermanentElementMapForSnapshot(snapshot) { + const permanentElementMap = {}; + for (const currentPermanentElement of this.permanentElements) { + const { id } = currentPermanentElement; + const newPermanentElement = snapshot.getPermanentElementById(id); + if (newPermanentElement) { + permanentElementMap[id] = [currentPermanentElement, newPermanentElement]; + } + } + return permanentElementMap; + } + }; + function getPermanentElementById(node, id) { + return node.querySelector(`#${id}[data-turbo-permanent]`); + } + function queryPermanentElementsAll(node) { + return node.querySelectorAll("[id][data-turbo-permanent]"); + } + var FormSubmitObserver = class { + constructor(delegate, eventTarget) { + this.started = false; + this.submitCaptured = () => { + this.eventTarget.removeEventListener("submit", this.submitBubbled, false); + this.eventTarget.addEventListener("submit", this.submitBubbled, false); + }; + this.submitBubbled = (event) => { + if (!event.defaultPrevented) { + const form = event.target instanceof HTMLFormElement ? event.target : void 0; + const submitter = event.submitter || void 0; + if (form && submissionDoesNotDismissDialog(form, submitter) && submissionDoesNotTargetIFrame(form, submitter) && this.delegate.willSubmitForm(form, submitter)) { + event.preventDefault(); + event.stopImmediatePropagation(); + this.delegate.formSubmitted(form, submitter); + } + } + }; + this.delegate = delegate; + this.eventTarget = eventTarget; + } + start() { + if (!this.started) { + this.eventTarget.addEventListener("submit", this.submitCaptured, true); + this.started = true; + } + } + stop() { + if (this.started) { + this.eventTarget.removeEventListener("submit", this.submitCaptured, true); + this.started = false; + } + } + }; + function submissionDoesNotDismissDialog(form, submitter) { + const method = (submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute("formmethod")) || form.getAttribute("method"); + return method != "dialog"; + } + function submissionDoesNotTargetIFrame(form, submitter) { + const target = (submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute("formtarget")) || form.target; + for (const element of document.getElementsByName(target)) { + if (element instanceof HTMLIFrameElement) + return false; + } + return true; + } + var View = class { + constructor(delegate, element) { + this.resolveRenderPromise = (_value) => { + }; + this.resolveInterceptionPromise = (_value) => { + }; + this.delegate = delegate; + this.element = element; + } + scrollToAnchor(anchor) { + const element = this.snapshot.getElementForAnchor(anchor); + if (element) { + this.scrollToElement(element); + this.focusElement(element); + } else { + this.scrollToPosition({ x: 0, y: 0 }); + } + } + scrollToAnchorFromLocation(location2) { + this.scrollToAnchor(getAnchor(location2)); + } + scrollToElement(element) { + element.scrollIntoView(); + } + focusElement(element) { + if (element instanceof HTMLElement) { + if (element.hasAttribute("tabindex")) { + element.focus(); + } else { + element.setAttribute("tabindex", "-1"); + element.focus(); + element.removeAttribute("tabindex"); + } + } + } + scrollToPosition({ x, y }) { + this.scrollRoot.scrollTo(x, y); + } + scrollToTop() { + this.scrollToPosition({ x: 0, y: 0 }); + } + get scrollRoot() { + return window; + } + async render(renderer) { + const { isPreview, shouldRender, newSnapshot: snapshot } = renderer; + if (shouldRender) { + try { + this.renderPromise = new Promise((resolve) => this.resolveRenderPromise = resolve); + this.renderer = renderer; + await this.prepareToRenderSnapshot(renderer); + const renderInterception = new Promise((resolve) => this.resolveInterceptionPromise = resolve); + const options = { resume: this.resolveInterceptionPromise, render: this.renderer.renderElement }; + const immediateRender = this.delegate.allowsImmediateRender(snapshot, options); + if (!immediateRender) + await renderInterception; + await this.renderSnapshot(renderer); + this.delegate.viewRenderedSnapshot(snapshot, isPreview); + this.delegate.preloadOnLoadLinksForView(this.element); + this.finishRenderingSnapshot(renderer); + } finally { + delete this.renderer; + this.resolveRenderPromise(void 0); + delete this.renderPromise; + } + } else { + this.invalidate(renderer.reloadReason); + } + } + invalidate(reason) { + this.delegate.viewInvalidated(reason); + } + async prepareToRenderSnapshot(renderer) { + this.markAsPreview(renderer.isPreview); + await renderer.prepareToRender(); + } + markAsPreview(isPreview) { + if (isPreview) { + this.element.setAttribute("data-turbo-preview", ""); + } else { + this.element.removeAttribute("data-turbo-preview"); + } + } + async renderSnapshot(renderer) { + await renderer.render(); + } + finishRenderingSnapshot(renderer) { + renderer.finishRendering(); + } + }; + var FrameView = class extends View { + invalidate() { + this.element.innerHTML = ""; + } + get snapshot() { + return new Snapshot(this.element); + } + }; + var LinkInterceptor = class { + constructor(delegate, element) { + this.clickBubbled = (event) => { + if (this.respondsToEventTarget(event.target)) { + this.clickEvent = event; + } else { + delete this.clickEvent; + } + }; + this.linkClicked = (event) => { + if (this.clickEvent && this.respondsToEventTarget(event.target) && event.target instanceof Element) { + if (this.delegate.shouldInterceptLinkClick(event.target, event.detail.url, event.detail.originalEvent)) { + this.clickEvent.preventDefault(); + event.preventDefault(); + this.delegate.linkClickIntercepted(event.target, event.detail.url, event.detail.originalEvent); + } + } + delete this.clickEvent; + }; + this.willVisit = (_event) => { + delete this.clickEvent; + }; + this.delegate = delegate; + this.element = element; + } + start() { + this.element.addEventListener("click", this.clickBubbled); + document.addEventListener("turbo:click", this.linkClicked); + document.addEventListener("turbo:before-visit", this.willVisit); + } + stop() { + this.element.removeEventListener("click", this.clickBubbled); + document.removeEventListener("turbo:click", this.linkClicked); + document.removeEventListener("turbo:before-visit", this.willVisit); + } + respondsToEventTarget(target) { + const element = target instanceof Element ? target : target instanceof Node ? target.parentElement : null; + return element && element.closest("turbo-frame, html") == this.element; + } + }; + var LinkClickObserver = class { + constructor(delegate, eventTarget) { + this.started = false; + this.clickCaptured = () => { + this.eventTarget.removeEventListener("click", this.clickBubbled, false); + this.eventTarget.addEventListener("click", this.clickBubbled, false); + }; + this.clickBubbled = (event) => { + if (event instanceof MouseEvent && this.clickEventIsSignificant(event)) { + const target = event.composedPath && event.composedPath()[0] || event.target; + const link = this.findLinkFromClickTarget(target); + if (link && doesNotTargetIFrame(link)) { + const location2 = this.getLocationForLink(link); + if (this.delegate.willFollowLinkToLocation(link, location2, event)) { + event.preventDefault(); + this.delegate.followedLinkToLocation(link, location2); + } + } + } + }; + this.delegate = delegate; + this.eventTarget = eventTarget; + } + start() { + if (!this.started) { + this.eventTarget.addEventListener("click", this.clickCaptured, true); + this.started = true; + } + } + stop() { + if (this.started) { + this.eventTarget.removeEventListener("click", this.clickCaptured, true); + this.started = false; + } + } + clickEventIsSignificant(event) { + return !(event.target && event.target.isContentEditable || event.defaultPrevented || event.which > 1 || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey); + } + findLinkFromClickTarget(target) { + if (target instanceof Element) { + return target.closest("a[href]:not([target^=_]):not([download])"); + } + } + getLocationForLink(link) { + return expandURL(link.getAttribute("href") || ""); + } + }; + function doesNotTargetIFrame(anchor) { + for (const element of document.getElementsByName(anchor.target)) { + if (element instanceof HTMLIFrameElement) + return false; + } + return true; + } + var FormLinkClickObserver = class { + constructor(delegate, element) { + this.delegate = delegate; + this.linkInterceptor = new LinkClickObserver(this, element); + } + start() { + this.linkInterceptor.start(); + } + stop() { + this.linkInterceptor.stop(); + } + willFollowLinkToLocation(link, location2, originalEvent) { + return this.delegate.willSubmitFormLinkToLocation(link, location2, originalEvent) && link.hasAttribute("data-turbo-method"); + } + followedLinkToLocation(link, location2) { + const action = location2.href; + const form = document.createElement("form"); + form.setAttribute("data-turbo", "true"); + form.setAttribute("action", action); + form.setAttribute("hidden", ""); + const method = link.getAttribute("data-turbo-method"); + if (method) + form.setAttribute("method", method); + const turboFrame = link.getAttribute("data-turbo-frame"); + if (turboFrame) + form.setAttribute("data-turbo-frame", turboFrame); + const turboAction = link.getAttribute("data-turbo-action"); + if (turboAction) + form.setAttribute("data-turbo-action", turboAction); + const turboConfirm = link.getAttribute("data-turbo-confirm"); + if (turboConfirm) + form.setAttribute("data-turbo-confirm", turboConfirm); + const turboStream = link.hasAttribute("data-turbo-stream"); + if (turboStream) + form.setAttribute("data-turbo-stream", ""); + this.delegate.submittedFormLinkToLocation(link, location2, form); + document.body.appendChild(form); + form.addEventListener("turbo:submit-end", () => form.remove(), { once: true }); + requestAnimationFrame(() => form.requestSubmit()); + } + }; + var Bardo = class { + constructor(delegate, permanentElementMap) { + this.delegate = delegate; + this.permanentElementMap = permanentElementMap; + } + static preservingPermanentElements(delegate, permanentElementMap, callback) { + const bardo = new this(delegate, permanentElementMap); + bardo.enter(); + callback(); + bardo.leave(); + } + enter() { + for (const id in this.permanentElementMap) { + const [currentPermanentElement, newPermanentElement] = this.permanentElementMap[id]; + this.delegate.enteringBardo(currentPermanentElement, newPermanentElement); + this.replaceNewPermanentElementWithPlaceholder(newPermanentElement); + } + } + leave() { + for (const id in this.permanentElementMap) { + const [currentPermanentElement] = this.permanentElementMap[id]; + this.replaceCurrentPermanentElementWithClone(currentPermanentElement); + this.replacePlaceholderWithPermanentElement(currentPermanentElement); + this.delegate.leavingBardo(currentPermanentElement); + } + } + replaceNewPermanentElementWithPlaceholder(permanentElement) { + const placeholder = createPlaceholderForPermanentElement(permanentElement); + permanentElement.replaceWith(placeholder); + } + replaceCurrentPermanentElementWithClone(permanentElement) { + const clone = permanentElement.cloneNode(true); + permanentElement.replaceWith(clone); + } + replacePlaceholderWithPermanentElement(permanentElement) { + const placeholder = this.getPlaceholderById(permanentElement.id); + placeholder === null || placeholder === void 0 ? void 0 : placeholder.replaceWith(permanentElement); + } + getPlaceholderById(id) { + return this.placeholders.find((element) => element.content == id); + } + get placeholders() { + return [...document.querySelectorAll("meta[name=turbo-permanent-placeholder][content]")]; + } + }; + function createPlaceholderForPermanentElement(permanentElement) { + const element = document.createElement("meta"); + element.setAttribute("name", "turbo-permanent-placeholder"); + element.setAttribute("content", permanentElement.id); + return element; + } + var Renderer = class { + constructor(currentSnapshot, newSnapshot, renderElement, isPreview, willRender = true) { + this.activeElement = null; + this.currentSnapshot = currentSnapshot; + this.newSnapshot = newSnapshot; + this.isPreview = isPreview; + this.willRender = willRender; + this.renderElement = renderElement; + this.promise = new Promise((resolve, reject) => this.resolvingFunctions = { resolve, reject }); + } + get shouldRender() { + return true; + } + get reloadReason() { + return; + } + prepareToRender() { + return; + } + finishRendering() { + if (this.resolvingFunctions) { + this.resolvingFunctions.resolve(); + delete this.resolvingFunctions; + } + } + preservingPermanentElements(callback) { + Bardo.preservingPermanentElements(this, this.permanentElementMap, callback); + } + focusFirstAutofocusableElement() { + const element = this.connectedSnapshot.firstAutofocusableElement; + if (elementIsFocusable(element)) { + element.focus(); + } + } + enteringBardo(currentPermanentElement) { + if (this.activeElement) + return; + if (currentPermanentElement.contains(this.currentSnapshot.activeElement)) { + this.activeElement = this.currentSnapshot.activeElement; + } + } + leavingBardo(currentPermanentElement) { + if (currentPermanentElement.contains(this.activeElement) && this.activeElement instanceof HTMLElement) { + this.activeElement.focus(); + this.activeElement = null; + } + } + get connectedSnapshot() { + return this.newSnapshot.isConnected ? this.newSnapshot : this.currentSnapshot; + } + get currentElement() { + return this.currentSnapshot.element; + } + get newElement() { + return this.newSnapshot.element; + } + get permanentElementMap() { + return this.currentSnapshot.getPermanentElementMapForSnapshot(this.newSnapshot); + } + }; + function elementIsFocusable(element) { + return element && typeof element.focus == "function"; + } + var FrameRenderer = class extends Renderer { + constructor(delegate, currentSnapshot, newSnapshot, renderElement, isPreview, willRender = true) { + super(currentSnapshot, newSnapshot, renderElement, isPreview, willRender); + this.delegate = delegate; + } + static renderElement(currentElement, newElement) { + var _a; + const destinationRange = document.createRange(); + destinationRange.selectNodeContents(currentElement); + destinationRange.deleteContents(); + const frameElement = newElement; + const sourceRange = (_a = frameElement.ownerDocument) === null || _a === void 0 ? void 0 : _a.createRange(); + if (sourceRange) { + sourceRange.selectNodeContents(frameElement); + currentElement.appendChild(sourceRange.extractContents()); + } + } + get shouldRender() { + return true; + } + async render() { + await nextAnimationFrame(); + this.preservingPermanentElements(() => { + this.loadFrameElement(); + }); + this.scrollFrameIntoView(); + await nextAnimationFrame(); + this.focusFirstAutofocusableElement(); + await nextAnimationFrame(); + this.activateScriptElements(); + } + loadFrameElement() { + this.delegate.willRenderFrame(this.currentElement, this.newElement); + this.renderElement(this.currentElement, this.newElement); + } + scrollFrameIntoView() { + if (this.currentElement.autoscroll || this.newElement.autoscroll) { + const element = this.currentElement.firstElementChild; + const block = readScrollLogicalPosition(this.currentElement.getAttribute("data-autoscroll-block"), "end"); + const behavior = readScrollBehavior(this.currentElement.getAttribute("data-autoscroll-behavior"), "auto"); + if (element) { + element.scrollIntoView({ block, behavior }); + return true; + } + } + return false; + } + activateScriptElements() { + for (const inertScriptElement of this.newScriptElements) { + const activatedScriptElement = activateScriptElement(inertScriptElement); + inertScriptElement.replaceWith(activatedScriptElement); + } + } + get newScriptElements() { + return this.currentElement.querySelectorAll("script"); + } + }; + function readScrollLogicalPosition(value, defaultValue) { + if (value == "end" || value == "start" || value == "center" || value == "nearest") { + return value; + } else { + return defaultValue; + } + } + function readScrollBehavior(value, defaultValue) { + if (value == "auto" || value == "smooth") { + return value; + } else { + return defaultValue; + } + } + var ProgressBar = class { + constructor() { + this.hiding = false; + this.value = 0; + this.visible = false; + this.trickle = () => { + this.setValue(this.value + Math.random() / 100); + }; + this.stylesheetElement = this.createStylesheetElement(); + this.progressElement = this.createProgressElement(); + this.installStylesheetElement(); + this.setValue(0); + } + static get defaultCSS() { + return unindent` + .turbo-progress-bar { + position: fixed; + display: block; + top: 0; + left: 0; + height: 3px; + background: #0076ff; + z-index: 2147483647; + transition: + width ${ProgressBar.animationDuration}ms ease-out, + opacity ${ProgressBar.animationDuration / 2}ms ${ProgressBar.animationDuration / 2}ms ease-in; + transform: translate3d(0, 0, 0); + } + `; + } + show() { + if (!this.visible) { + this.visible = true; + this.installProgressElement(); + this.startTrickling(); + } + } + hide() { + if (this.visible && !this.hiding) { + this.hiding = true; + this.fadeProgressElement(() => { + this.uninstallProgressElement(); + this.stopTrickling(); + this.visible = false; + this.hiding = false; + }); + } + } + setValue(value) { + this.value = value; + this.refresh(); + } + installStylesheetElement() { + document.head.insertBefore(this.stylesheetElement, document.head.firstChild); + } + installProgressElement() { + this.progressElement.style.width = "0"; + this.progressElement.style.opacity = "1"; + document.documentElement.insertBefore(this.progressElement, document.body); + this.refresh(); + } + fadeProgressElement(callback) { + this.progressElement.style.opacity = "0"; + setTimeout(callback, ProgressBar.animationDuration * 1.5); + } + uninstallProgressElement() { + if (this.progressElement.parentNode) { + document.documentElement.removeChild(this.progressElement); + } + } + startTrickling() { + if (!this.trickleInterval) { + this.trickleInterval = window.setInterval(this.trickle, ProgressBar.animationDuration); + } + } + stopTrickling() { + window.clearInterval(this.trickleInterval); + delete this.trickleInterval; + } + refresh() { + requestAnimationFrame(() => { + this.progressElement.style.width = `${10 + this.value * 90}%`; + }); + } + createStylesheetElement() { + const element = document.createElement("style"); + element.type = "text/css"; + element.textContent = ProgressBar.defaultCSS; + if (this.cspNonce) { + element.nonce = this.cspNonce; + } + return element; + } + createProgressElement() { + const element = document.createElement("div"); + element.className = "turbo-progress-bar"; + return element; + } + get cspNonce() { + return getMetaContent("csp-nonce"); + } + }; + ProgressBar.animationDuration = 300; + var HeadSnapshot = class extends Snapshot { + constructor() { + super(...arguments); + this.detailsByOuterHTML = this.children.filter((element) => !elementIsNoscript(element)).map((element) => elementWithoutNonce(element)).reduce((result, element) => { + const { outerHTML } = element; + const details = outerHTML in result ? result[outerHTML] : { + type: elementType(element), + tracked: elementIsTracked(element), + elements: [] + }; + return Object.assign(Object.assign({}, result), { [outerHTML]: Object.assign(Object.assign({}, details), { elements: [...details.elements, element] }) }); + }, {}); + } + get trackedElementSignature() { + return Object.keys(this.detailsByOuterHTML).filter((outerHTML) => this.detailsByOuterHTML[outerHTML].tracked).join(""); + } + getScriptElementsNotInSnapshot(snapshot) { + return this.getElementsMatchingTypeNotInSnapshot("script", snapshot); + } + getStylesheetElementsNotInSnapshot(snapshot) { + return this.getElementsMatchingTypeNotInSnapshot("stylesheet", snapshot); + } + getElementsMatchingTypeNotInSnapshot(matchedType, snapshot) { + return Object.keys(this.detailsByOuterHTML).filter((outerHTML) => !(outerHTML in snapshot.detailsByOuterHTML)).map((outerHTML) => this.detailsByOuterHTML[outerHTML]).filter(({ type }) => type == matchedType).map(({ elements: [element] }) => element); + } + get provisionalElements() { + return Object.keys(this.detailsByOuterHTML).reduce((result, outerHTML) => { + const { type, tracked, elements } = this.detailsByOuterHTML[outerHTML]; + if (type == null && !tracked) { + return [...result, ...elements]; + } else if (elements.length > 1) { + return [...result, ...elements.slice(1)]; + } else { + return result; + } + }, []); + } + getMetaValue(name) { + const element = this.findMetaElementByName(name); + return element ? element.getAttribute("content") : null; + } + findMetaElementByName(name) { + return Object.keys(this.detailsByOuterHTML).reduce((result, outerHTML) => { + const { elements: [element] } = this.detailsByOuterHTML[outerHTML]; + return elementIsMetaElementWithName(element, name) ? element : result; + }, void 0); + } + }; + function elementType(element) { + if (elementIsScript(element)) { + return "script"; + } else if (elementIsStylesheet(element)) { + return "stylesheet"; + } + } + function elementIsTracked(element) { + return element.getAttribute("data-turbo-track") == "reload"; + } + function elementIsScript(element) { + const tagName = element.localName; + return tagName == "script"; + } + function elementIsNoscript(element) { + const tagName = element.localName; + return tagName == "noscript"; + } + function elementIsStylesheet(element) { + const tagName = element.localName; + return tagName == "style" || tagName == "link" && element.getAttribute("rel") == "stylesheet"; + } + function elementIsMetaElementWithName(element, name) { + const tagName = element.localName; + return tagName == "meta" && element.getAttribute("name") == name; + } + function elementWithoutNonce(element) { + if (element.hasAttribute("nonce")) { + element.setAttribute("nonce", ""); + } + return element; + } + var PageSnapshot = class extends Snapshot { + constructor(element, headSnapshot) { + super(element); + this.headSnapshot = headSnapshot; + } + static fromHTMLString(html = "") { + return this.fromDocument(parseHTMLDocument(html)); + } + static fromElement(element) { + return this.fromDocument(element.ownerDocument); + } + static fromDocument({ head, body }) { + return new this(body, new HeadSnapshot(head)); + } + clone() { + const clonedElement = this.element.cloneNode(true); + const selectElements = this.element.querySelectorAll("select"); + const clonedSelectElements = clonedElement.querySelectorAll("select"); + for (const [index, source] of selectElements.entries()) { + const clone = clonedSelectElements[index]; + for (const option of clone.selectedOptions) + option.selected = false; + for (const option of source.selectedOptions) + clone.options[option.index].selected = true; + } + for (const clonedPasswordInput of clonedElement.querySelectorAll('input[type="password"]')) { + clonedPasswordInput.value = ""; + } + return new PageSnapshot(clonedElement, this.headSnapshot); + } + get headElement() { + return this.headSnapshot.element; + } + get rootLocation() { + var _a; + const root = (_a = this.getSetting("root")) !== null && _a !== void 0 ? _a : "/"; + return expandURL(root); + } + get cacheControlValue() { + return this.getSetting("cache-control"); + } + get isPreviewable() { + return this.cacheControlValue != "no-preview"; + } + get isCacheable() { + return this.cacheControlValue != "no-cache"; + } + get isVisitable() { + return this.getSetting("visit-control") != "reload"; + } + getSetting(name) { + return this.headSnapshot.getMetaValue(`turbo-${name}`); + } + }; + var TimingMetric; + (function(TimingMetric2) { + TimingMetric2["visitStart"] = "visitStart"; + TimingMetric2["requestStart"] = "requestStart"; + TimingMetric2["requestEnd"] = "requestEnd"; + TimingMetric2["visitEnd"] = "visitEnd"; + })(TimingMetric || (TimingMetric = {})); + var VisitState; + (function(VisitState2) { + VisitState2["initialized"] = "initialized"; + VisitState2["started"] = "started"; + VisitState2["canceled"] = "canceled"; + VisitState2["failed"] = "failed"; + VisitState2["completed"] = "completed"; + })(VisitState || (VisitState = {})); + var defaultOptions = { + action: "advance", + historyChanged: false, + visitCachedSnapshot: () => { + }, + willRender: true, + updateHistory: true, + shouldCacheSnapshot: true, + acceptsStreamResponse: false + }; + var SystemStatusCode; + (function(SystemStatusCode2) { + SystemStatusCode2[SystemStatusCode2["networkFailure"] = 0] = "networkFailure"; + SystemStatusCode2[SystemStatusCode2["timeoutFailure"] = -1] = "timeoutFailure"; + SystemStatusCode2[SystemStatusCode2["contentTypeMismatch"] = -2] = "contentTypeMismatch"; + })(SystemStatusCode || (SystemStatusCode = {})); + var Visit = class { + constructor(delegate, location2, restorationIdentifier, options = {}) { + this.identifier = uuid(); + this.timingMetrics = {}; + this.followedRedirect = false; + this.historyChanged = false; + this.scrolled = false; + this.shouldCacheSnapshot = true; + this.acceptsStreamResponse = false; + this.snapshotCached = false; + this.state = VisitState.initialized; + this.delegate = delegate; + this.location = location2; + this.restorationIdentifier = restorationIdentifier || uuid(); + const { action, historyChanged, referrer, snapshot, snapshotHTML, response, visitCachedSnapshot, willRender, updateHistory, shouldCacheSnapshot, acceptsStreamResponse } = Object.assign(Object.assign({}, defaultOptions), options); + this.action = action; + this.historyChanged = historyChanged; + this.referrer = referrer; + this.snapshot = snapshot; + this.snapshotHTML = snapshotHTML; + this.response = response; + this.isSamePage = this.delegate.locationWithActionIsSamePage(this.location, this.action); + this.visitCachedSnapshot = visitCachedSnapshot; + this.willRender = willRender; + this.updateHistory = updateHistory; + this.scrolled = !willRender; + this.shouldCacheSnapshot = shouldCacheSnapshot; + this.acceptsStreamResponse = acceptsStreamResponse; + } + get adapter() { + return this.delegate.adapter; + } + get view() { + return this.delegate.view; + } + get history() { + return this.delegate.history; + } + get restorationData() { + return this.history.getRestorationDataForIdentifier(this.restorationIdentifier); + } + get silent() { + return this.isSamePage; + } + start() { + if (this.state == VisitState.initialized) { + this.recordTimingMetric(TimingMetric.visitStart); + this.state = VisitState.started; + this.adapter.visitStarted(this); + this.delegate.visitStarted(this); + } + } + cancel() { + if (this.state == VisitState.started) { + if (this.request) { + this.request.cancel(); + } + this.cancelRender(); + this.state = VisitState.canceled; + } + } + complete() { + if (this.state == VisitState.started) { + this.recordTimingMetric(TimingMetric.visitEnd); + this.state = VisitState.completed; + this.followRedirect(); + if (!this.followedRedirect) { + this.adapter.visitCompleted(this); + this.delegate.visitCompleted(this); + } + } + } + fail() { + if (this.state == VisitState.started) { + this.state = VisitState.failed; + this.adapter.visitFailed(this); + } + } + changeHistory() { + var _a; + if (!this.historyChanged && this.updateHistory) { + const actionForHistory = this.location.href === ((_a = this.referrer) === null || _a === void 0 ? void 0 : _a.href) ? "replace" : this.action; + const method = getHistoryMethodForAction(actionForHistory); + this.history.update(method, this.location, this.restorationIdentifier); + this.historyChanged = true; + } + } + issueRequest() { + if (this.hasPreloadedResponse()) { + this.simulateRequest(); + } else if (this.shouldIssueRequest() && !this.request) { + this.request = new FetchRequest(this, FetchMethod.get, this.location); + this.request.perform(); + } + } + simulateRequest() { + if (this.response) { + this.startRequest(); + this.recordResponse(); + this.finishRequest(); + } + } + startRequest() { + this.recordTimingMetric(TimingMetric.requestStart); + this.adapter.visitRequestStarted(this); + } + recordResponse(response = this.response) { + this.response = response; + if (response) { + const { statusCode } = response; + if (isSuccessful(statusCode)) { + this.adapter.visitRequestCompleted(this); + } else { + this.adapter.visitRequestFailedWithStatusCode(this, statusCode); + } + } + } + finishRequest() { + this.recordTimingMetric(TimingMetric.requestEnd); + this.adapter.visitRequestFinished(this); + } + loadResponse() { + if (this.response) { + const { statusCode, responseHTML } = this.response; + this.render(async () => { + if (this.shouldCacheSnapshot) + this.cacheSnapshot(); + if (this.view.renderPromise) + await this.view.renderPromise; + if (isSuccessful(statusCode) && responseHTML != null) { + await this.view.renderPage(PageSnapshot.fromHTMLString(responseHTML), false, this.willRender, this); + this.performScroll(); + this.adapter.visitRendered(this); + this.complete(); + } else { + await this.view.renderError(PageSnapshot.fromHTMLString(responseHTML), this); + this.adapter.visitRendered(this); + this.fail(); + } + }); + } + } + getCachedSnapshot() { + const snapshot = this.view.getCachedSnapshotForLocation(this.location) || this.getPreloadedSnapshot(); + if (snapshot && (!getAnchor(this.location) || snapshot.hasAnchor(getAnchor(this.location)))) { + if (this.action == "restore" || snapshot.isPreviewable) { + return snapshot; + } + } + } + getPreloadedSnapshot() { + if (this.snapshotHTML) { + return PageSnapshot.fromHTMLString(this.snapshotHTML); + } + } + hasCachedSnapshot() { + return this.getCachedSnapshot() != null; + } + loadCachedSnapshot() { + const snapshot = this.getCachedSnapshot(); + if (snapshot) { + const isPreview = this.shouldIssueRequest(); + this.render(async () => { + this.cacheSnapshot(); + if (this.isSamePage) { + this.adapter.visitRendered(this); + } else { + if (this.view.renderPromise) + await this.view.renderPromise; + await this.view.renderPage(snapshot, isPreview, this.willRender, this); + this.performScroll(); + this.adapter.visitRendered(this); + if (!isPreview) { + this.complete(); + } + } + }); + } + } + followRedirect() { + var _a; + if (this.redirectedToLocation && !this.followedRedirect && ((_a = this.response) === null || _a === void 0 ? void 0 : _a.redirected)) { + this.adapter.visitProposedToLocation(this.redirectedToLocation, { + action: "replace", + response: this.response + }); + this.followedRedirect = true; + } + } + goToSamePageAnchor() { + if (this.isSamePage) { + this.render(async () => { + this.cacheSnapshot(); + this.performScroll(); + this.changeHistory(); + this.adapter.visitRendered(this); + }); + } + } + prepareHeadersForRequest(headers, request) { + if (this.acceptsStreamResponse) { + request.acceptResponseType(StreamMessage.contentType); + } + } + requestStarted() { + this.startRequest(); + } + requestPreventedHandlingResponse(_request, _response) { + } + async requestSucceededWithResponse(request, response) { + const responseHTML = await response.responseHTML; + const { redirected, statusCode } = response; + if (responseHTML == void 0) { + this.recordResponse({ + statusCode: SystemStatusCode.contentTypeMismatch, + redirected + }); + } else { + this.redirectedToLocation = response.redirected ? response.location : void 0; + this.recordResponse({ statusCode, responseHTML, redirected }); + } + } + async requestFailedWithResponse(request, response) { + const responseHTML = await response.responseHTML; + const { redirected, statusCode } = response; + if (responseHTML == void 0) { + this.recordResponse({ + statusCode: SystemStatusCode.contentTypeMismatch, + redirected + }); + } else { + this.recordResponse({ statusCode, responseHTML, redirected }); + } + } + requestErrored(_request, _error) { + this.recordResponse({ + statusCode: SystemStatusCode.networkFailure, + redirected: false + }); + } + requestFinished() { + this.finishRequest(); + } + performScroll() { + if (!this.scrolled && !this.view.forceReloaded) { + if (this.action == "restore") { + this.scrollToRestoredPosition() || this.scrollToAnchor() || this.view.scrollToTop(); + } else { + this.scrollToAnchor() || this.view.scrollToTop(); + } + if (this.isSamePage) { + this.delegate.visitScrolledToSamePageLocation(this.view.lastRenderedLocation, this.location); + } + this.scrolled = true; + } + } + scrollToRestoredPosition() { + const { scrollPosition } = this.restorationData; + if (scrollPosition) { + this.view.scrollToPosition(scrollPosition); + return true; + } + } + scrollToAnchor() { + const anchor = getAnchor(this.location); + if (anchor != null) { + this.view.scrollToAnchor(anchor); + return true; + } + } + recordTimingMetric(metric) { + this.timingMetrics[metric] = new Date().getTime(); + } + getTimingMetrics() { + return Object.assign({}, this.timingMetrics); + } + getHistoryMethodForAction(action) { + switch (action) { + case "replace": + return history.replaceState; + case "advance": + case "restore": + return history.pushState; + } + } + hasPreloadedResponse() { + return typeof this.response == "object"; + } + shouldIssueRequest() { + if (this.isSamePage) { + return false; + } else if (this.action == "restore") { + return !this.hasCachedSnapshot(); + } else { + return this.willRender; + } + } + cacheSnapshot() { + if (!this.snapshotCached) { + this.view.cacheSnapshot(this.snapshot).then((snapshot) => snapshot && this.visitCachedSnapshot(snapshot)); + this.snapshotCached = true; + } + } + async render(callback) { + this.cancelRender(); + await new Promise((resolve) => { + this.frame = requestAnimationFrame(() => resolve()); + }); + await callback(); + delete this.frame; + } + cancelRender() { + if (this.frame) { + cancelAnimationFrame(this.frame); + delete this.frame; + } + } + }; + function isSuccessful(statusCode) { + return statusCode >= 200 && statusCode < 300; + } + var BrowserAdapter = class { + constructor(session2) { + this.progressBar = new ProgressBar(); + this.showProgressBar = () => { + this.progressBar.show(); + }; + this.session = session2; + } + visitProposedToLocation(location2, options) { + this.navigator.startVisit(location2, (options === null || options === void 0 ? void 0 : options.restorationIdentifier) || uuid(), options); + } + visitStarted(visit2) { + this.location = visit2.location; + visit2.loadCachedSnapshot(); + visit2.issueRequest(); + visit2.goToSamePageAnchor(); + } + visitRequestStarted(visit2) { + this.progressBar.setValue(0); + if (visit2.hasCachedSnapshot() || visit2.action != "restore") { + this.showVisitProgressBarAfterDelay(); + } else { + this.showProgressBar(); + } + } + visitRequestCompleted(visit2) { + visit2.loadResponse(); + } + visitRequestFailedWithStatusCode(visit2, statusCode) { + switch (statusCode) { + case SystemStatusCode.networkFailure: + case SystemStatusCode.timeoutFailure: + case SystemStatusCode.contentTypeMismatch: + return this.reload({ + reason: "request_failed", + context: { + statusCode + } + }); + default: + return visit2.loadResponse(); + } + } + visitRequestFinished(_visit) { + this.progressBar.setValue(1); + this.hideVisitProgressBar(); + } + visitCompleted(_visit) { + } + pageInvalidated(reason) { + this.reload(reason); + } + visitFailed(_visit) { + } + visitRendered(_visit) { + } + formSubmissionStarted(_formSubmission) { + this.progressBar.setValue(0); + this.showFormProgressBarAfterDelay(); + } + formSubmissionFinished(_formSubmission) { + this.progressBar.setValue(1); + this.hideFormProgressBar(); + } + showVisitProgressBarAfterDelay() { + this.visitProgressBarTimeout = window.setTimeout(this.showProgressBar, this.session.progressBarDelay); + } + hideVisitProgressBar() { + this.progressBar.hide(); + if (this.visitProgressBarTimeout != null) { + window.clearTimeout(this.visitProgressBarTimeout); + delete this.visitProgressBarTimeout; + } + } + showFormProgressBarAfterDelay() { + if (this.formProgressBarTimeout == null) { + this.formProgressBarTimeout = window.setTimeout(this.showProgressBar, this.session.progressBarDelay); + } + } + hideFormProgressBar() { + this.progressBar.hide(); + if (this.formProgressBarTimeout != null) { + window.clearTimeout(this.formProgressBarTimeout); + delete this.formProgressBarTimeout; + } + } + reload(reason) { + var _a; + dispatch("turbo:reload", { detail: reason }); + window.location.href = ((_a = this.location) === null || _a === void 0 ? void 0 : _a.toString()) || window.location.href; + } + get navigator() { + return this.session.navigator; + } + }; + var CacheObserver = class { + constructor() { + this.started = false; + this.removeStaleElements = (_event) => { + const staleElements = [...document.querySelectorAll('[data-turbo-cache="false"]')]; + for (const element of staleElements) { + element.remove(); + } + }; + } + start() { + if (!this.started) { + this.started = true; + addEventListener("turbo:before-cache", this.removeStaleElements, false); + } + } + stop() { + if (this.started) { + this.started = false; + removeEventListener("turbo:before-cache", this.removeStaleElements, false); + } + } + }; + var FrameRedirector = class { + constructor(session2, element) { + this.session = session2; + this.element = element; + this.linkInterceptor = new LinkInterceptor(this, element); + this.formSubmitObserver = new FormSubmitObserver(this, element); + } + start() { + this.linkInterceptor.start(); + this.formSubmitObserver.start(); + } + stop() { + this.linkInterceptor.stop(); + this.formSubmitObserver.stop(); + } + shouldInterceptLinkClick(element, _location, _event) { + return this.shouldRedirect(element); + } + linkClickIntercepted(element, url, event) { + const frame = this.findFrameElement(element); + if (frame) { + frame.delegate.linkClickIntercepted(element, url, event); + } + } + willSubmitForm(element, submitter) { + return element.closest("turbo-frame") == null && this.shouldSubmit(element, submitter) && this.shouldRedirect(element, submitter); + } + formSubmitted(element, submitter) { + const frame = this.findFrameElement(element, submitter); + if (frame) { + frame.delegate.formSubmitted(element, submitter); + } + } + shouldSubmit(form, submitter) { + var _a; + const action = getAction(form, submitter); + const meta = this.element.ownerDocument.querySelector(`meta[name="turbo-root"]`); + const rootLocation = expandURL((_a = meta === null || meta === void 0 ? void 0 : meta.content) !== null && _a !== void 0 ? _a : "/"); + return this.shouldRedirect(form, submitter) && locationIsVisitable(action, rootLocation); + } + shouldRedirect(element, submitter) { + const isNavigatable = element instanceof HTMLFormElement ? this.session.submissionIsNavigatable(element, submitter) : this.session.elementIsNavigatable(element); + if (isNavigatable) { + const frame = this.findFrameElement(element, submitter); + return frame ? frame != element.closest("turbo-frame") : false; + } else { + return false; + } + } + findFrameElement(element, submitter) { + const id = (submitter === null || submitter === void 0 ? void 0 : submitter.getAttribute("data-turbo-frame")) || element.getAttribute("data-turbo-frame"); + if (id && id != "_top") { + const frame = this.element.querySelector(`#${id}:not([disabled])`); + if (frame instanceof FrameElement) { + return frame; + } + } + } + }; + var History = class { + constructor(delegate) { + this.restorationIdentifier = uuid(); + this.restorationData = {}; + this.started = false; + this.pageLoaded = false; + this.onPopState = (event) => { + if (this.shouldHandlePopState()) { + const { turbo } = event.state || {}; + if (turbo) { + this.location = new URL(window.location.href); + const { restorationIdentifier } = turbo; + this.restorationIdentifier = restorationIdentifier; + this.delegate.historyPoppedToLocationWithRestorationIdentifier(this.location, restorationIdentifier); + } + } + }; + this.onPageLoad = async (_event) => { + await nextMicrotask(); + this.pageLoaded = true; + }; + this.delegate = delegate; + } + start() { + if (!this.started) { + addEventListener("popstate", this.onPopState, false); + addEventListener("load", this.onPageLoad, false); + this.started = true; + this.replace(new URL(window.location.href)); + } + } + stop() { + if (this.started) { + removeEventListener("popstate", this.onPopState, false); + removeEventListener("load", this.onPageLoad, false); + this.started = false; + } + } + push(location2, restorationIdentifier) { + this.update(history.pushState, location2, restorationIdentifier); + } + replace(location2, restorationIdentifier) { + this.update(history.replaceState, location2, restorationIdentifier); + } + update(method, location2, restorationIdentifier = uuid()) { + const state = { turbo: { restorationIdentifier } }; + method.call(history, state, "", location2.href); + this.location = location2; + this.restorationIdentifier = restorationIdentifier; + } + getRestorationDataForIdentifier(restorationIdentifier) { + return this.restorationData[restorationIdentifier] || {}; + } + updateRestorationData(additionalData) { + const { restorationIdentifier } = this; + const restorationData = this.restorationData[restorationIdentifier]; + this.restorationData[restorationIdentifier] = Object.assign(Object.assign({}, restorationData), additionalData); + } + assumeControlOfScrollRestoration() { + var _a; + if (!this.previousScrollRestoration) { + this.previousScrollRestoration = (_a = history.scrollRestoration) !== null && _a !== void 0 ? _a : "auto"; + history.scrollRestoration = "manual"; + } + } + relinquishControlOfScrollRestoration() { + if (this.previousScrollRestoration) { + history.scrollRestoration = this.previousScrollRestoration; + delete this.previousScrollRestoration; + } + } + shouldHandlePopState() { + return this.pageIsLoaded(); + } + pageIsLoaded() { + return this.pageLoaded || document.readyState == "complete"; + } + }; + var Navigator = class { + constructor(delegate) { + this.delegate = delegate; + } + proposeVisit(location2, options = {}) { + if (this.delegate.allowsVisitingLocationWithAction(location2, options.action)) { + if (locationIsVisitable(location2, this.view.snapshot.rootLocation)) { + this.delegate.visitProposedToLocation(location2, options); + } else { + window.location.href = location2.toString(); + } + } + } + startVisit(locatable, restorationIdentifier, options = {}) { + this.stop(); + this.currentVisit = new Visit(this, expandURL(locatable), restorationIdentifier, Object.assign({ referrer: this.location }, options)); + this.currentVisit.start(); + } + submitForm(form, submitter) { + this.stop(); + this.formSubmission = new FormSubmission(this, form, submitter, true); + this.formSubmission.start(); + } + stop() { + if (this.formSubmission) { + this.formSubmission.stop(); + delete this.formSubmission; + } + if (this.currentVisit) { + this.currentVisit.cancel(); + delete this.currentVisit; + } + } + get adapter() { + return this.delegate.adapter; + } + get view() { + return this.delegate.view; + } + get history() { + return this.delegate.history; + } + formSubmissionStarted(formSubmission) { + if (typeof this.adapter.formSubmissionStarted === "function") { + this.adapter.formSubmissionStarted(formSubmission); + } + } + async formSubmissionSucceededWithResponse(formSubmission, fetchResponse) { + if (formSubmission == this.formSubmission) { + const responseHTML = await fetchResponse.responseHTML; + if (responseHTML) { + const shouldCacheSnapshot = formSubmission.method == FetchMethod.get; + if (!shouldCacheSnapshot) { + this.view.clearSnapshotCache(); + } + const { statusCode, redirected } = fetchResponse; + const action = this.getActionForFormSubmission(formSubmission); + const visitOptions = { + action, + shouldCacheSnapshot, + response: { statusCode, responseHTML, redirected } + }; + this.proposeVisit(fetchResponse.location, visitOptions); + } + } + } + async formSubmissionFailedWithResponse(formSubmission, fetchResponse) { + const responseHTML = await fetchResponse.responseHTML; + if (responseHTML) { + const snapshot = PageSnapshot.fromHTMLString(responseHTML); + if (fetchResponse.serverError) { + await this.view.renderError(snapshot, this.currentVisit); + } else { + await this.view.renderPage(snapshot, false, true, this.currentVisit); + } + this.view.scrollToTop(); + this.view.clearSnapshotCache(); + } + } + formSubmissionErrored(formSubmission, error2) { + console.error(error2); + } + formSubmissionFinished(formSubmission) { + if (typeof this.adapter.formSubmissionFinished === "function") { + this.adapter.formSubmissionFinished(formSubmission); + } + } + visitStarted(visit2) { + this.delegate.visitStarted(visit2); + } + visitCompleted(visit2) { + this.delegate.visitCompleted(visit2); + } + locationWithActionIsSamePage(location2, action) { + const anchor = getAnchor(location2); + const currentAnchor = getAnchor(this.view.lastRenderedLocation); + const isRestorationToTop = action === "restore" && typeof anchor === "undefined"; + return action !== "replace" && getRequestURL(location2) === getRequestURL(this.view.lastRenderedLocation) && (isRestorationToTop || anchor != null && anchor !== currentAnchor); + } + visitScrolledToSamePageLocation(oldURL, newURL) { + this.delegate.visitScrolledToSamePageLocation(oldURL, newURL); + } + get location() { + return this.history.location; + } + get restorationIdentifier() { + return this.history.restorationIdentifier; + } + getActionForFormSubmission(formSubmission) { + const { formElement, submitter } = formSubmission; + const action = getAttribute("data-turbo-action", submitter, formElement); + return isAction(action) ? action : "advance"; + } + }; + var PageStage; + (function(PageStage2) { + PageStage2[PageStage2["initial"] = 0] = "initial"; + PageStage2[PageStage2["loading"] = 1] = "loading"; + PageStage2[PageStage2["interactive"] = 2] = "interactive"; + PageStage2[PageStage2["complete"] = 3] = "complete"; + })(PageStage || (PageStage = {})); + var PageObserver = class { + constructor(delegate) { + this.stage = PageStage.initial; + this.started = false; + this.interpretReadyState = () => { + const { readyState } = this; + if (readyState == "interactive") { + this.pageIsInteractive(); + } else if (readyState == "complete") { + this.pageIsComplete(); + } + }; + this.pageWillUnload = () => { + this.delegate.pageWillUnload(); + }; + this.delegate = delegate; + } + start() { + if (!this.started) { + if (this.stage == PageStage.initial) { + this.stage = PageStage.loading; + } + document.addEventListener("readystatechange", this.interpretReadyState, false); + addEventListener("pagehide", this.pageWillUnload, false); + this.started = true; + } + } + stop() { + if (this.started) { + document.removeEventListener("readystatechange", this.interpretReadyState, false); + removeEventListener("pagehide", this.pageWillUnload, false); + this.started = false; + } + } + pageIsInteractive() { + if (this.stage == PageStage.loading) { + this.stage = PageStage.interactive; + this.delegate.pageBecameInteractive(); + } + } + pageIsComplete() { + this.pageIsInteractive(); + if (this.stage == PageStage.interactive) { + this.stage = PageStage.complete; + this.delegate.pageLoaded(); + } + } + get readyState() { + return document.readyState; + } + }; + var ScrollObserver = class { + constructor(delegate) { + this.started = false; + this.onScroll = () => { + this.updatePosition({ x: window.pageXOffset, y: window.pageYOffset }); + }; + this.delegate = delegate; + } + start() { + if (!this.started) { + addEventListener("scroll", this.onScroll, false); + this.onScroll(); + this.started = true; + } + } + stop() { + if (this.started) { + removeEventListener("scroll", this.onScroll, false); + this.started = false; + } + } + updatePosition(position) { + this.delegate.scrollPositionChanged(position); + } + }; + var StreamMessageRenderer = class { + render({ fragment }) { + Bardo.preservingPermanentElements(this, getPermanentElementMapForFragment(fragment), () => document.documentElement.appendChild(fragment)); + } + enteringBardo(currentPermanentElement, newPermanentElement) { + newPermanentElement.replaceWith(currentPermanentElement.cloneNode(true)); + } + leavingBardo() { + } + }; + function getPermanentElementMapForFragment(fragment) { + const permanentElementsInDocument = queryPermanentElementsAll(document.documentElement); + const permanentElementMap = {}; + for (const permanentElementInDocument of permanentElementsInDocument) { + const { id } = permanentElementInDocument; + for (const streamElement of fragment.querySelectorAll("turbo-stream")) { + const elementInStream = getPermanentElementById(streamElement.templateElement.content, id); + if (elementInStream) { + permanentElementMap[id] = [permanentElementInDocument, elementInStream]; + } + } + } + return permanentElementMap; + } + var StreamObserver = class { + constructor(delegate) { + this.sources = /* @__PURE__ */ new Set(); + this.started = false; + this.inspectFetchResponse = (event) => { + const response = fetchResponseFromEvent(event); + if (response && fetchResponseIsStream(response)) { + event.preventDefault(); + this.receiveMessageResponse(response); + } + }; + this.receiveMessageEvent = (event) => { + if (this.started && typeof event.data == "string") { + this.receiveMessageHTML(event.data); + } + }; + this.delegate = delegate; + } + start() { + if (!this.started) { + this.started = true; + addEventListener("turbo:before-fetch-response", this.inspectFetchResponse, false); + } + } + stop() { + if (this.started) { + this.started = false; + removeEventListener("turbo:before-fetch-response", this.inspectFetchResponse, false); + } + } + connectStreamSource(source) { + if (!this.streamSourceIsConnected(source)) { + this.sources.add(source); + source.addEventListener("message", this.receiveMessageEvent, false); + } + } + disconnectStreamSource(source) { + if (this.streamSourceIsConnected(source)) { + this.sources.delete(source); + source.removeEventListener("message", this.receiveMessageEvent, false); + } + } + streamSourceIsConnected(source) { + return this.sources.has(source); + } + async receiveMessageResponse(response) { + const html = await response.responseHTML; + if (html) { + this.receiveMessageHTML(html); + } + } + receiveMessageHTML(html) { + this.delegate.receivedMessageFromStream(StreamMessage.wrap(html)); + } + }; + function fetchResponseFromEvent(event) { + var _a; + const fetchResponse = (_a = event.detail) === null || _a === void 0 ? void 0 : _a.fetchResponse; + if (fetchResponse instanceof FetchResponse) { + return fetchResponse; + } + } + function fetchResponseIsStream(response) { + var _a; + const contentType = (_a = response.contentType) !== null && _a !== void 0 ? _a : ""; + return contentType.startsWith(StreamMessage.contentType); + } + var ErrorRenderer = class extends Renderer { + static renderElement(currentElement, newElement) { + const { documentElement, body } = document; + documentElement.replaceChild(newElement, body); + } + async render() { + this.replaceHeadAndBody(); + this.activateScriptElements(); + } + replaceHeadAndBody() { + const { documentElement, head } = document; + documentElement.replaceChild(this.newHead, head); + this.renderElement(this.currentElement, this.newElement); + } + activateScriptElements() { + for (const replaceableElement of this.scriptElements) { + const parentNode = replaceableElement.parentNode; + if (parentNode) { + const element = activateScriptElement(replaceableElement); + parentNode.replaceChild(element, replaceableElement); + } + } + } + get newHead() { + return this.newSnapshot.headSnapshot.element; + } + get scriptElements() { + return document.documentElement.querySelectorAll("script"); + } + }; + var PageRenderer = class extends Renderer { + static renderElement(currentElement, newElement) { + if (document.body && newElement instanceof HTMLBodyElement) { + document.body.replaceWith(newElement); + } else { + document.documentElement.appendChild(newElement); + } + } + get shouldRender() { + return this.newSnapshot.isVisitable && this.trackedElementsAreIdentical; + } + get reloadReason() { + if (!this.newSnapshot.isVisitable) { + return { + reason: "turbo_visit_control_is_reload" + }; + } + if (!this.trackedElementsAreIdentical) { + return { + reason: "tracked_element_mismatch" + }; + } + } + async prepareToRender() { + await this.mergeHead(); + } + async render() { + if (this.willRender) { + this.replaceBody(); + } + } + finishRendering() { + super.finishRendering(); + if (!this.isPreview) { + this.focusFirstAutofocusableElement(); + } + } + get currentHeadSnapshot() { + return this.currentSnapshot.headSnapshot; + } + get newHeadSnapshot() { + return this.newSnapshot.headSnapshot; + } + get newElement() { + return this.newSnapshot.element; + } + async mergeHead() { + const newStylesheetElements = this.copyNewHeadStylesheetElements(); + this.copyNewHeadScriptElements(); + this.removeCurrentHeadProvisionalElements(); + this.copyNewHeadProvisionalElements(); + await newStylesheetElements; + } + replaceBody() { + this.preservingPermanentElements(() => { + this.activateNewBody(); + this.assignNewBody(); + }); + } + get trackedElementsAreIdentical() { + return this.currentHeadSnapshot.trackedElementSignature == this.newHeadSnapshot.trackedElementSignature; + } + async copyNewHeadStylesheetElements() { + const loadingElements = []; + for (const element of this.newHeadStylesheetElements) { + loadingElements.push(waitForLoad(element)); + document.head.appendChild(element); + } + await Promise.all(loadingElements); + } + copyNewHeadScriptElements() { + for (const element of this.newHeadScriptElements) { + document.head.appendChild(activateScriptElement(element)); + } + } + removeCurrentHeadProvisionalElements() { + for (const element of this.currentHeadProvisionalElements) { + document.head.removeChild(element); + } + } + copyNewHeadProvisionalElements() { + for (const element of this.newHeadProvisionalElements) { + document.head.appendChild(element); + } + } + activateNewBody() { + document.adoptNode(this.newElement); + this.activateNewBodyScriptElements(); + } + activateNewBodyScriptElements() { + for (const inertScriptElement of this.newBodyScriptElements) { + const activatedScriptElement = activateScriptElement(inertScriptElement); + inertScriptElement.replaceWith(activatedScriptElement); + } + } + assignNewBody() { + this.renderElement(this.currentElement, this.newElement); + } + get newHeadStylesheetElements() { + return this.newHeadSnapshot.getStylesheetElementsNotInSnapshot(this.currentHeadSnapshot); + } + get newHeadScriptElements() { + return this.newHeadSnapshot.getScriptElementsNotInSnapshot(this.currentHeadSnapshot); + } + get currentHeadProvisionalElements() { + return this.currentHeadSnapshot.provisionalElements; + } + get newHeadProvisionalElements() { + return this.newHeadSnapshot.provisionalElements; + } + get newBodyScriptElements() { + return this.newElement.querySelectorAll("script"); + } + }; + var SnapshotCache = class { + constructor(size) { + this.keys = []; + this.snapshots = {}; + this.size = size; + } + has(location2) { + return toCacheKey(location2) in this.snapshots; + } + get(location2) { + if (this.has(location2)) { + const snapshot = this.read(location2); + this.touch(location2); + return snapshot; + } + } + put(location2, snapshot) { + this.write(location2, snapshot); + this.touch(location2); + return snapshot; + } + clear() { + this.snapshots = {}; + } + read(location2) { + return this.snapshots[toCacheKey(location2)]; + } + write(location2, snapshot) { + this.snapshots[toCacheKey(location2)] = snapshot; + } + touch(location2) { + const key = toCacheKey(location2); + const index = this.keys.indexOf(key); + if (index > -1) + this.keys.splice(index, 1); + this.keys.unshift(key); + this.trim(); + } + trim() { + for (const key of this.keys.splice(this.size)) { + delete this.snapshots[key]; + } + } + }; + var PageView = class extends View { + constructor() { + super(...arguments); + this.snapshotCache = new SnapshotCache(10); + this.lastRenderedLocation = new URL(location.href); + this.forceReloaded = false; + } + renderPage(snapshot, isPreview = false, willRender = true, visit2) { + const renderer = new PageRenderer(this.snapshot, snapshot, PageRenderer.renderElement, isPreview, willRender); + if (!renderer.shouldRender) { + this.forceReloaded = true; + } else { + visit2 === null || visit2 === void 0 ? void 0 : visit2.changeHistory(); + } + return this.render(renderer); + } + renderError(snapshot, visit2) { + visit2 === null || visit2 === void 0 ? void 0 : visit2.changeHistory(); + const renderer = new ErrorRenderer(this.snapshot, snapshot, ErrorRenderer.renderElement, false); + return this.render(renderer); + } + clearSnapshotCache() { + this.snapshotCache.clear(); + } + async cacheSnapshot(snapshot = this.snapshot) { + if (snapshot.isCacheable) { + this.delegate.viewWillCacheSnapshot(); + const { lastRenderedLocation: location2 } = this; + await nextEventLoopTick(); + const cachedSnapshot = snapshot.clone(); + this.snapshotCache.put(location2, cachedSnapshot); + return cachedSnapshot; + } + } + getCachedSnapshotForLocation(location2) { + return this.snapshotCache.get(location2); + } + get snapshot() { + return PageSnapshot.fromElement(this.element); + } + }; + var Preloader = class { + constructor(delegate) { + this.selector = "a[data-turbo-preload]"; + this.delegate = delegate; + } + get snapshotCache() { + return this.delegate.navigator.view.snapshotCache; + } + start() { + if (document.readyState === "loading") { + return document.addEventListener("DOMContentLoaded", () => { + this.preloadOnLoadLinksForView(document.body); + }); + } else { + this.preloadOnLoadLinksForView(document.body); + } + } + preloadOnLoadLinksForView(element) { + for (const link of element.querySelectorAll(this.selector)) { + this.preloadURL(link); + } + } + async preloadURL(link) { + const location2 = new URL(link.href); + if (this.snapshotCache.has(location2)) { + return; + } + try { + const response = await fetch(location2.toString(), { headers: { "VND.PREFETCH": "true", Accept: "text/html" } }); + const responseText = await response.text(); + const snapshot = PageSnapshot.fromHTMLString(responseText); + this.snapshotCache.put(location2, snapshot); + } catch (_) { + } + } + }; + var Session = class { + constructor() { + this.navigator = new Navigator(this); + this.history = new History(this); + this.preloader = new Preloader(this); + this.view = new PageView(this, document.documentElement); + this.adapter = new BrowserAdapter(this); + this.pageObserver = new PageObserver(this); + this.cacheObserver = new CacheObserver(); + this.linkClickObserver = new LinkClickObserver(this, window); + this.formSubmitObserver = new FormSubmitObserver(this, document); + this.scrollObserver = new ScrollObserver(this); + this.streamObserver = new StreamObserver(this); + this.formLinkClickObserver = new FormLinkClickObserver(this, document.documentElement); + this.frameRedirector = new FrameRedirector(this, document.documentElement); + this.streamMessageRenderer = new StreamMessageRenderer(); + this.drive = true; + this.enabled = true; + this.progressBarDelay = 500; + this.started = false; + this.formMode = "on"; + } + start() { + if (!this.started) { + this.pageObserver.start(); + this.cacheObserver.start(); + this.formLinkClickObserver.start(); + this.linkClickObserver.start(); + this.formSubmitObserver.start(); + this.scrollObserver.start(); + this.streamObserver.start(); + this.frameRedirector.start(); + this.history.start(); + this.preloader.start(); + this.started = true; + this.enabled = true; + } + } + disable() { + this.enabled = false; + } + stop() { + if (this.started) { + this.pageObserver.stop(); + this.cacheObserver.stop(); + this.formLinkClickObserver.stop(); + this.linkClickObserver.stop(); + this.formSubmitObserver.stop(); + this.scrollObserver.stop(); + this.streamObserver.stop(); + this.frameRedirector.stop(); + this.history.stop(); + this.started = false; + } + } + registerAdapter(adapter) { + this.adapter = adapter; + } + visit(location2, options = {}) { + const frameElement = options.frame ? document.getElementById(options.frame) : null; + if (frameElement instanceof FrameElement) { + frameElement.src = location2.toString(); + frameElement.loaded; + } else { + this.navigator.proposeVisit(expandURL(location2), options); + } + } + connectStreamSource(source) { + this.streamObserver.connectStreamSource(source); + } + disconnectStreamSource(source) { + this.streamObserver.disconnectStreamSource(source); + } + renderStreamMessage(message) { + this.streamMessageRenderer.render(StreamMessage.wrap(message)); + } + clearCache() { + this.view.clearSnapshotCache(); + } + setProgressBarDelay(delay) { + this.progressBarDelay = delay; + } + setFormMode(mode) { + this.formMode = mode; + } + get location() { + return this.history.location; + } + get restorationIdentifier() { + return this.history.restorationIdentifier; + } + historyPoppedToLocationWithRestorationIdentifier(location2, restorationIdentifier) { + if (this.enabled) { + this.navigator.startVisit(location2, restorationIdentifier, { + action: "restore", + historyChanged: true + }); + } else { + this.adapter.pageInvalidated({ + reason: "turbo_disabled" + }); + } + } + scrollPositionChanged(position) { + this.history.updateRestorationData({ scrollPosition: position }); + } + willSubmitFormLinkToLocation(link, location2) { + return this.elementIsNavigatable(link) && locationIsVisitable(location2, this.snapshot.rootLocation); + } + submittedFormLinkToLocation() { + } + willFollowLinkToLocation(link, location2, event) { + return this.elementIsNavigatable(link) && locationIsVisitable(location2, this.snapshot.rootLocation) && this.applicationAllowsFollowingLinkToLocation(link, location2, event); + } + followedLinkToLocation(link, location2) { + const action = this.getActionForLink(link); + const acceptsStreamResponse = link.hasAttribute("data-turbo-stream"); + this.visit(location2.href, { action, acceptsStreamResponse }); + } + allowsVisitingLocationWithAction(location2, action) { + return this.locationWithActionIsSamePage(location2, action) || this.applicationAllowsVisitingLocation(location2); + } + visitProposedToLocation(location2, options) { + extendURLWithDeprecatedProperties(location2); + this.adapter.visitProposedToLocation(location2, options); + } + visitStarted(visit2) { + if (!visit2.acceptsStreamResponse) { + markAsBusy(document.documentElement); + } + extendURLWithDeprecatedProperties(visit2.location); + if (!visit2.silent) { + this.notifyApplicationAfterVisitingLocation(visit2.location, visit2.action); + } + } + visitCompleted(visit2) { + clearBusyState(document.documentElement); + this.notifyApplicationAfterPageLoad(visit2.getTimingMetrics()); + } + locationWithActionIsSamePage(location2, action) { + return this.navigator.locationWithActionIsSamePage(location2, action); + } + visitScrolledToSamePageLocation(oldURL, newURL) { + this.notifyApplicationAfterVisitingSamePageLocation(oldURL, newURL); + } + willSubmitForm(form, submitter) { + const action = getAction(form, submitter); + return this.submissionIsNavigatable(form, submitter) && locationIsVisitable(expandURL(action), this.snapshot.rootLocation); + } + formSubmitted(form, submitter) { + this.navigator.submitForm(form, submitter); + } + pageBecameInteractive() { + this.view.lastRenderedLocation = this.location; + this.notifyApplicationAfterPageLoad(); + } + pageLoaded() { + this.history.assumeControlOfScrollRestoration(); + } + pageWillUnload() { + this.history.relinquishControlOfScrollRestoration(); + } + receivedMessageFromStream(message) { + this.renderStreamMessage(message); + } + viewWillCacheSnapshot() { + var _a; + if (!((_a = this.navigator.currentVisit) === null || _a === void 0 ? void 0 : _a.silent)) { + this.notifyApplicationBeforeCachingSnapshot(); + } + } + allowsImmediateRender({ element }, options) { + const event = this.notifyApplicationBeforeRender(element, options); + const { defaultPrevented, detail: { render } } = event; + if (this.view.renderer && render) { + this.view.renderer.renderElement = render; + } + return !defaultPrevented; + } + viewRenderedSnapshot(_snapshot, _isPreview) { + this.view.lastRenderedLocation = this.history.location; + this.notifyApplicationAfterRender(); + } + preloadOnLoadLinksForView(element) { + this.preloader.preloadOnLoadLinksForView(element); + } + viewInvalidated(reason) { + this.adapter.pageInvalidated(reason); + } + frameLoaded(frame) { + this.notifyApplicationAfterFrameLoad(frame); + } + frameRendered(fetchResponse, frame) { + this.notifyApplicationAfterFrameRender(fetchResponse, frame); + } + applicationAllowsFollowingLinkToLocation(link, location2, ev) { + const event = this.notifyApplicationAfterClickingLinkToLocation(link, location2, ev); + return !event.defaultPrevented; + } + applicationAllowsVisitingLocation(location2) { + const event = this.notifyApplicationBeforeVisitingLocation(location2); + return !event.defaultPrevented; + } + notifyApplicationAfterClickingLinkToLocation(link, location2, event) { + return dispatch("turbo:click", { + target: link, + detail: { url: location2.href, originalEvent: event }, + cancelable: true + }); + } + notifyApplicationBeforeVisitingLocation(location2) { + return dispatch("turbo:before-visit", { + detail: { url: location2.href }, + cancelable: true + }); + } + notifyApplicationAfterVisitingLocation(location2, action) { + return dispatch("turbo:visit", { detail: { url: location2.href, action } }); + } + notifyApplicationBeforeCachingSnapshot() { + return dispatch("turbo:before-cache"); + } + notifyApplicationBeforeRender(newBody, options) { + return dispatch("turbo:before-render", { + detail: Object.assign({ newBody }, options), + cancelable: true + }); + } + notifyApplicationAfterRender() { + return dispatch("turbo:render"); + } + notifyApplicationAfterPageLoad(timing = {}) { + return dispatch("turbo:load", { + detail: { url: this.location.href, timing } + }); + } + notifyApplicationAfterVisitingSamePageLocation(oldURL, newURL) { + dispatchEvent(new HashChangeEvent("hashchange", { + oldURL: oldURL.toString(), + newURL: newURL.toString() + })); + } + notifyApplicationAfterFrameLoad(frame) { + return dispatch("turbo:frame-load", { target: frame }); + } + notifyApplicationAfterFrameRender(fetchResponse, frame) { + return dispatch("turbo:frame-render", { + detail: { fetchResponse }, + target: frame, + cancelable: true + }); + } + submissionIsNavigatable(form, submitter) { + if (this.formMode == "off") { + return false; + } else { + const submitterIsNavigatable = submitter ? this.elementIsNavigatable(submitter) : true; + if (this.formMode == "optin") { + return submitterIsNavigatable && form.closest('[data-turbo="true"]') != null; + } else { + return submitterIsNavigatable && this.elementIsNavigatable(form); + } + } + } + elementIsNavigatable(element) { + const container = element.closest("[data-turbo]"); + const withinFrame = element.closest("turbo-frame"); + if (this.drive || withinFrame) { + if (container) { + return container.getAttribute("data-turbo") != "false"; + } else { + return true; + } + } else { + if (container) { + return container.getAttribute("data-turbo") == "true"; + } else { + return false; + } + } + } + getActionForLink(link) { + const action = link.getAttribute("data-turbo-action"); + return isAction(action) ? action : "advance"; + } + get snapshot() { + return this.view.snapshot; + } + }; + function extendURLWithDeprecatedProperties(url) { + Object.defineProperties(url, deprecatedLocationPropertyDescriptors); + } + var deprecatedLocationPropertyDescriptors = { + absoluteURL: { + get() { + return this.toString(); + } + } + }; + var Cache = class { + constructor(session2) { + this.session = session2; + } + clear() { + this.session.clearCache(); + } + resetCacheControl() { + this.setCacheControl(""); + } + exemptPageFromCache() { + this.setCacheControl("no-cache"); + } + exemptPageFromPreview() { + this.setCacheControl("no-preview"); + } + setCacheControl(value) { + setMetaContent("turbo-cache-control", value); + } + }; + var StreamActions = { + after() { + this.targetElements.forEach((e) => { + var _a; + return (_a = e.parentElement) === null || _a === void 0 ? void 0 : _a.insertBefore(this.templateContent, e.nextSibling); + }); + }, + append() { + this.removeDuplicateTargetChildren(); + this.targetElements.forEach((e) => e.append(this.templateContent)); + }, + before() { + this.targetElements.forEach((e) => { + var _a; + return (_a = e.parentElement) === null || _a === void 0 ? void 0 : _a.insertBefore(this.templateContent, e); + }); + }, + prepend() { + this.removeDuplicateTargetChildren(); + this.targetElements.forEach((e) => e.prepend(this.templateContent)); + }, + remove() { + this.targetElements.forEach((e) => e.remove()); + }, + replace() { + this.targetElements.forEach((e) => e.replaceWith(this.templateContent)); + }, + update() { + this.targetElements.forEach((e) => e.replaceChildren(this.templateContent)); + } + }; + var session = new Session(); + var cache = new Cache(session); + var { navigator: navigator$1 } = session; + function start() { + session.start(); + } + function registerAdapter(adapter) { + session.registerAdapter(adapter); + } + function visit(location2, options) { + session.visit(location2, options); + } + function connectStreamSource(source) { + session.connectStreamSource(source); + } + function disconnectStreamSource(source) { + session.disconnectStreamSource(source); + } + function renderStreamMessage(message) { + session.renderStreamMessage(message); + } + function clearCache() { + console.warn("Please replace `Turbo.clearCache()` with `Turbo.cache.clear()`. The top-level function is deprecated and will be removed in a future version of Turbo.`"); + session.clearCache(); + } + function setProgressBarDelay(delay) { + session.setProgressBarDelay(delay); + } + function setConfirmMethod(confirmMethod) { + FormSubmission.confirmMethod = confirmMethod; + } + function setFormMode(mode) { + session.setFormMode(mode); + } + var Turbo = /* @__PURE__ */ Object.freeze({ + __proto__: null, + navigator: navigator$1, + session, + cache, + PageRenderer, + PageSnapshot, + FrameRenderer, + start, + registerAdapter, + visit, + connectStreamSource, + disconnectStreamSource, + renderStreamMessage, + clearCache, + setProgressBarDelay, + setConfirmMethod, + setFormMode, + StreamActions + }); + var FrameController = class { + constructor(element) { + this.fetchResponseLoaded = (_fetchResponse) => { + }; + this.currentFetchRequest = null; + this.resolveVisitPromise = () => { + }; + this.connected = false; + this.hasBeenLoaded = false; + this.ignoredAttributes = /* @__PURE__ */ new Set(); + this.action = null; + this.visitCachedSnapshot = ({ element: element2 }) => { + const frame = element2.querySelector("#" + this.element.id); + if (frame && this.previousFrameElement) { + frame.replaceChildren(...this.previousFrameElement.children); + } + delete this.previousFrameElement; + }; + this.element = element; + this.view = new FrameView(this, this.element); + this.appearanceObserver = new AppearanceObserver(this, this.element); + this.formLinkClickObserver = new FormLinkClickObserver(this, this.element); + this.linkInterceptor = new LinkInterceptor(this, this.element); + this.restorationIdentifier = uuid(); + this.formSubmitObserver = new FormSubmitObserver(this, this.element); + } + connect() { + if (!this.connected) { + this.connected = true; + if (this.loadingStyle == FrameLoadingStyle.lazy) { + this.appearanceObserver.start(); + } else { + this.loadSourceURL(); + } + this.formLinkClickObserver.start(); + this.linkInterceptor.start(); + this.formSubmitObserver.start(); + } + } + disconnect() { + if (this.connected) { + this.connected = false; + this.appearanceObserver.stop(); + this.formLinkClickObserver.stop(); + this.linkInterceptor.stop(); + this.formSubmitObserver.stop(); + } + } + disabledChanged() { + if (this.loadingStyle == FrameLoadingStyle.eager) { + this.loadSourceURL(); + } + } + sourceURLChanged() { + if (this.isIgnoringChangesTo("src")) + return; + if (this.element.isConnected) { + this.complete = false; + } + if (this.loadingStyle == FrameLoadingStyle.eager || this.hasBeenLoaded) { + this.loadSourceURL(); + } + } + sourceURLReloaded() { + const { src } = this.element; + this.ignoringChangesToAttribute("complete", () => { + this.element.removeAttribute("complete"); + }); + this.element.src = null; + this.element.src = src; + return this.element.loaded; + } + completeChanged() { + if (this.isIgnoringChangesTo("complete")) + return; + this.loadSourceURL(); + } + loadingStyleChanged() { + if (this.loadingStyle == FrameLoadingStyle.lazy) { + this.appearanceObserver.start(); + } else { + this.appearanceObserver.stop(); + this.loadSourceURL(); + } + } + async loadSourceURL() { + if (this.enabled && this.isActive && !this.complete && this.sourceURL) { + this.element.loaded = this.visit(expandURL(this.sourceURL)); + this.appearanceObserver.stop(); + await this.element.loaded; + this.hasBeenLoaded = true; + } + } + async loadResponse(fetchResponse) { + if (fetchResponse.redirected || fetchResponse.succeeded && fetchResponse.isHTML) { + this.sourceURL = fetchResponse.response.url; + } + try { + const html = await fetchResponse.responseHTML; + if (html) { + const { body } = parseHTMLDocument(html); + const newFrameElement = await this.extractForeignFrameElement(body); + if (newFrameElement) { + const snapshot = new Snapshot(newFrameElement); + const renderer = new FrameRenderer(this, this.view.snapshot, snapshot, FrameRenderer.renderElement, false, false); + if (this.view.renderPromise) + await this.view.renderPromise; + this.changeHistory(); + await this.view.render(renderer); + this.complete = true; + session.frameRendered(fetchResponse, this.element); + session.frameLoaded(this.element); + this.fetchResponseLoaded(fetchResponse); + } else if (this.willHandleFrameMissingFromResponse(fetchResponse)) { + console.warn(`A matching frame for #${this.element.id} was missing from the response, transforming into full-page Visit.`); + this.visitResponse(fetchResponse.response); + } + } + } catch (error2) { + console.error(error2); + this.view.invalidate(); + } finally { + this.fetchResponseLoaded = () => { + }; + } + } + elementAppearedInViewport(_element) { + this.loadSourceURL(); + } + willSubmitFormLinkToLocation(link) { + return this.shouldInterceptNavigation(link); + } + submittedFormLinkToLocation(link, _location, form) { + const frame = this.findFrameElement(link); + if (frame) + form.setAttribute("data-turbo-frame", frame.id); + } + shouldInterceptLinkClick(element, _location, _event) { + return this.shouldInterceptNavigation(element); + } + linkClickIntercepted(element, location2) { + this.navigateFrame(element, location2); + } + willSubmitForm(element, submitter) { + return element.closest("turbo-frame") == this.element && this.shouldInterceptNavigation(element, submitter); + } + formSubmitted(element, submitter) { + if (this.formSubmission) { + this.formSubmission.stop(); + } + this.formSubmission = new FormSubmission(this, element, submitter); + const { fetchRequest } = this.formSubmission; + this.prepareHeadersForRequest(fetchRequest.headers, fetchRequest); + this.formSubmission.start(); + } + prepareHeadersForRequest(headers, request) { + var _a; + headers["Turbo-Frame"] = this.id; + if ((_a = this.currentNavigationElement) === null || _a === void 0 ? void 0 : _a.hasAttribute("data-turbo-stream")) { + request.acceptResponseType(StreamMessage.contentType); + } + } + requestStarted(_request) { + markAsBusy(this.element); + } + requestPreventedHandlingResponse(_request, _response) { + this.resolveVisitPromise(); + } + async requestSucceededWithResponse(request, response) { + await this.loadResponse(response); + this.resolveVisitPromise(); + } + async requestFailedWithResponse(request, response) { + console.error(response); + await this.loadResponse(response); + this.resolveVisitPromise(); + } + requestErrored(request, error2) { + console.error(error2); + this.resolveVisitPromise(); + } + requestFinished(_request) { + clearBusyState(this.element); + } + formSubmissionStarted({ formElement }) { + markAsBusy(formElement, this.findFrameElement(formElement)); + } + formSubmissionSucceededWithResponse(formSubmission, response) { + const frame = this.findFrameElement(formSubmission.formElement, formSubmission.submitter); + frame.delegate.proposeVisitIfNavigatedWithAction(frame, formSubmission.formElement, formSubmission.submitter); + frame.delegate.loadResponse(response); + } + formSubmissionFailedWithResponse(formSubmission, fetchResponse) { + this.element.delegate.loadResponse(fetchResponse); + } + formSubmissionErrored(formSubmission, error2) { + console.error(error2); + } + formSubmissionFinished({ formElement }) { + clearBusyState(formElement, this.findFrameElement(formElement)); + } + allowsImmediateRender({ element: newFrame }, options) { + const event = dispatch("turbo:before-frame-render", { + target: this.element, + detail: Object.assign({ newFrame }, options), + cancelable: true + }); + const { defaultPrevented, detail: { render } } = event; + if (this.view.renderer && render) { + this.view.renderer.renderElement = render; + } + return !defaultPrevented; + } + viewRenderedSnapshot(_snapshot, _isPreview) { + } + preloadOnLoadLinksForView(element) { + session.preloadOnLoadLinksForView(element); + } + viewInvalidated() { + } + willRenderFrame(currentElement, _newElement) { + this.previousFrameElement = currentElement.cloneNode(true); + } + async visit(url) { + var _a; + const request = new FetchRequest(this, FetchMethod.get, url, new URLSearchParams(), this.element); + (_a = this.currentFetchRequest) === null || _a === void 0 ? void 0 : _a.cancel(); + this.currentFetchRequest = request; + return new Promise((resolve) => { + this.resolveVisitPromise = () => { + this.resolveVisitPromise = () => { + }; + this.currentFetchRequest = null; + resolve(); + }; + request.perform(); + }); + } + navigateFrame(element, url, submitter) { + const frame = this.findFrameElement(element, submitter); + this.pageSnapshot = PageSnapshot.fromElement(frame).clone(); + frame.delegate.proposeVisitIfNavigatedWithAction(frame, element, submitter); + this.withCurrentNavigationElement(element, () => { + frame.src = url; + }); + } + proposeVisitIfNavigatedWithAction(frame, element, submitter) { + this.action = getVisitAction(submitter, element, frame); + if (isAction(this.action)) { + const { visitCachedSnapshot } = frame.delegate; + frame.delegate.fetchResponseLoaded = (fetchResponse) => { + if (frame.src) { + const { statusCode, redirected } = fetchResponse; + const responseHTML = frame.ownerDocument.documentElement.outerHTML; + const response = { statusCode, redirected, responseHTML }; + const options = { + response, + visitCachedSnapshot, + willRender: false, + updateHistory: false, + restorationIdentifier: this.restorationIdentifier, + snapshot: this.pageSnapshot + }; + if (this.action) + options.action = this.action; + session.visit(frame.src, options); + } + }; + } + } + changeHistory() { + if (this.action) { + const method = getHistoryMethodForAction(this.action); + session.history.update(method, expandURL(this.element.src || ""), this.restorationIdentifier); + } + } + willHandleFrameMissingFromResponse(fetchResponse) { + this.element.setAttribute("complete", ""); + const response = fetchResponse.response; + const visit2 = async (url, options = {}) => { + if (url instanceof Response) { + this.visitResponse(url); + } else { + session.visit(url, options); + } + }; + const event = dispatch("turbo:frame-missing", { + target: this.element, + detail: { response, visit: visit2 }, + cancelable: true + }); + return !event.defaultPrevented; + } + async visitResponse(response) { + const wrapped = new FetchResponse(response); + const responseHTML = await wrapped.responseHTML; + const { location: location2, redirected, statusCode } = wrapped; + return session.visit(location2, { response: { redirected, statusCode, responseHTML } }); + } + findFrameElement(element, submitter) { + var _a; + const id = getAttribute("data-turbo-frame", submitter, element) || this.element.getAttribute("target"); + return (_a = getFrameElementById(id)) !== null && _a !== void 0 ? _a : this.element; + } + async extractForeignFrameElement(container) { + let element; + const id = CSS.escape(this.id); + try { + element = activateElement(container.querySelector(`turbo-frame#${id}`), this.sourceURL); + if (element) { + return element; + } + element = activateElement(container.querySelector(`turbo-frame[src][recurse~=${id}]`), this.sourceURL); + if (element) { + await element.loaded; + return await this.extractForeignFrameElement(element); + } + } catch (error2) { + console.error(error2); + return new FrameElement(); + } + return null; + } + formActionIsVisitable(form, submitter) { + const action = getAction(form, submitter); + return locationIsVisitable(expandURL(action), this.rootLocation); + } + shouldInterceptNavigation(element, submitter) { + const id = getAttribute("data-turbo-frame", submitter, element) || this.element.getAttribute("target"); + if (element instanceof HTMLFormElement && !this.formActionIsVisitable(element, submitter)) { + return false; + } + if (!this.enabled || id == "_top") { + return false; + } + if (id) { + const frameElement = getFrameElementById(id); + if (frameElement) { + return !frameElement.disabled; + } + } + if (!session.elementIsNavigatable(element)) { + return false; + } + if (submitter && !session.elementIsNavigatable(submitter)) { + return false; + } + return true; + } + get id() { + return this.element.id; + } + get enabled() { + return !this.element.disabled; + } + get sourceURL() { + if (this.element.src) { + return this.element.src; + } + } + set sourceURL(sourceURL) { + this.ignoringChangesToAttribute("src", () => { + this.element.src = sourceURL !== null && sourceURL !== void 0 ? sourceURL : null; + }); + } + get loadingStyle() { + return this.element.loading; + } + get isLoading() { + return this.formSubmission !== void 0 || this.resolveVisitPromise() !== void 0; + } + get complete() { + return this.element.hasAttribute("complete"); + } + set complete(value) { + this.ignoringChangesToAttribute("complete", () => { + if (value) { + this.element.setAttribute("complete", ""); + } else { + this.element.removeAttribute("complete"); + } + }); + } + get isActive() { + return this.element.isActive && this.connected; + } + get rootLocation() { + var _a; + const meta = this.element.ownerDocument.querySelector(`meta[name="turbo-root"]`); + const root = (_a = meta === null || meta === void 0 ? void 0 : meta.content) !== null && _a !== void 0 ? _a : "/"; + return expandURL(root); + } + isIgnoringChangesTo(attributeName) { + return this.ignoredAttributes.has(attributeName); + } + ignoringChangesToAttribute(attributeName, callback) { + this.ignoredAttributes.add(attributeName); + callback(); + this.ignoredAttributes.delete(attributeName); + } + withCurrentNavigationElement(element, callback) { + this.currentNavigationElement = element; + callback(); + delete this.currentNavigationElement; + } + }; + function getFrameElementById(id) { + if (id != null) { + const element = document.getElementById(id); + if (element instanceof FrameElement) { + return element; + } + } + } + function activateElement(element, currentURL) { + if (element) { + const src = element.getAttribute("src"); + if (src != null && currentURL != null && urlsAreEqual(src, currentURL)) { + throw new Error(`Matching element has a source URL which references itself`); + } + if (element.ownerDocument !== document) { + element = document.importNode(element, true); + } + if (element instanceof FrameElement) { + element.connectedCallback(); + element.disconnectedCallback(); + return element; + } + } + } + var StreamElement = class extends HTMLElement { + static async renderElement(newElement) { + await newElement.performAction(); + } + async connectedCallback() { + try { + await this.render(); + } catch (error2) { + console.error(error2); + } finally { + this.disconnect(); + } + } + async render() { + var _a; + return (_a = this.renderPromise) !== null && _a !== void 0 ? _a : this.renderPromise = (async () => { + const event = this.beforeRenderEvent; + if (this.dispatchEvent(event)) { + await nextAnimationFrame(); + await event.detail.render(this); + } + })(); + } + disconnect() { + try { + this.remove(); + } catch (_a) { + } + } + removeDuplicateTargetChildren() { + this.duplicateChildren.forEach((c) => c.remove()); + } + get duplicateChildren() { + var _a; + const existingChildren = this.targetElements.flatMap((e) => [...e.children]).filter((c) => !!c.id); + const newChildrenIds = [...((_a = this.templateContent) === null || _a === void 0 ? void 0 : _a.children) || []].filter((c) => !!c.id).map((c) => c.id); + return existingChildren.filter((c) => newChildrenIds.includes(c.id)); + } + get performAction() { + if (this.action) { + const actionFunction = StreamActions[this.action]; + if (actionFunction) { + return actionFunction; + } + this.raise("unknown action"); + } + this.raise("action attribute is missing"); + } + get targetElements() { + if (this.target) { + return this.targetElementsById; + } else if (this.targets) { + return this.targetElementsByQuery; + } else { + this.raise("target or targets attribute is missing"); + } + } + get templateContent() { + return this.templateElement.content.cloneNode(true); + } + get templateElement() { + if (this.firstElementChild === null) { + const template = this.ownerDocument.createElement("template"); + this.appendChild(template); + return template; + } else if (this.firstElementChild instanceof HTMLTemplateElement) { + return this.firstElementChild; + } + this.raise("first child element must be a