├── .gitignore ├── .travis.yml ├── Gemfile ├── History.md ├── LICENSE ├── README.markdown ├── Rakefile ├── VERSION ├── app └── assets │ └── javascripts │ └── cocoon.js ├── cocoon.gemspec ├── gemfiles ├── Gemfile.default ├── Gemfile.rails-3.2.13 └── Gemfile.rails-4-r2 ├── lib ├── cocoon.rb ├── cocoon │ └── view_helpers.rb └── generators │ └── cocoon │ └── install │ └── install_generator.rb ├── npm ├── README.md └── package.json.erb └── spec ├── cocoon_spec.rb ├── dummy ├── Rakefile ├── app │ ├── controllers │ │ └── application_controller.rb │ ├── decorators │ │ └── comment_decorator.rb │ ├── helpers │ │ └── application_helper.rb │ ├── models │ │ ├── comment.rb │ │ ├── person.rb │ │ └── post.rb │ └── views │ │ └── layouts │ │ └── application.html.erb ├── config.ru ├── config │ ├── application.rb │ ├── boot.rb │ ├── database.yml │ ├── environment.rb │ ├── environments │ │ ├── development.rb │ │ ├── production.rb │ │ └── test.rb │ ├── initializers │ │ ├── backtrace_silencers.rb │ │ ├── inflections.rb │ │ ├── mime_types.rb │ │ ├── rails_version_helper.rb │ │ ├── secret_token.rb │ │ └── session_store.rb │ ├── locales │ │ └── en.yml │ └── routes.rb ├── db │ ├── migrate │ │ ├── 20110306212208_create_posts.rb │ │ ├── 20110306212250_create_comments.rb │ │ └── 20110420222224_create_people.rb │ └── schema.rb ├── public │ ├── 404.html │ ├── 422.html │ ├── 500.html │ ├── favicon.ico │ ├── javascripts │ │ ├── application.js │ │ ├── controls.js │ │ ├── dragdrop.js │ │ ├── effects.js │ │ ├── prototype.js │ │ └── rails.js │ └── stylesheets │ │ └── .gitkeep └── script │ └── rails ├── generators └── install_generator_spec.rb ├── integration └── navigation_spec.rb ├── spec_helper.rb └── support ├── i18n.rb ├── rails_version_helper.rb └── shared_examples.rb /.gitignore: -------------------------------------------------------------------------------- 1 | .bundle/ 2 | log/*.log 3 | pkg/ 4 | dist/ 5 | spec/dummy/db/*.sqlite3 6 | spec/dummy/log/*.log 7 | spec/dummy/tmp/ 8 | .rvmrc 9 | .idea 10 | coverage/ 11 | 12 | Gemfile.lock 13 | 14 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: ruby 2 | rvm: 3 | - 2.1.5 4 | - 2.2.6 5 | - 2.3.2 6 | - 2.4.1 7 | - 2.4.5 8 | - 2.4.6 9 | - 2.5.4 10 | - 2.5.5 11 | - 2.6.3 12 | - rbx-2 13 | 14 | before_install: 15 | - find /home/travis/.rvm/rubies -wholename '*default/bundler-*.gemspec' -delete 16 | - gem install bundler -v '< 2' 17 | 18 | gemfile: 19 | - gemfiles/Gemfile.rails-3.2.13 20 | - gemfiles/Gemfile.rails-4-r2 21 | - gemfiles/Gemfile.default 22 | 23 | matrix: 24 | fast_finish: true 25 | exclude: 26 | - rvm: 2.0.0 27 | gemfile: gemfiles/Gemfile.default 28 | - rvm: 2.1.5 29 | gemfile: gemfiles/Gemfile.default 30 | - rvm: 2.2.6 31 | gemfile: gemfiles/Gemfile.rails-3.2.13 32 | - rvm: 2.2.6 33 | gemfile: gemfiles/Gemfile.rails-4-r2 34 | - rvm: 2.3.2 35 | gemfile: gemfiles/Gemfile.rails-3.2.13 36 | - rvm: 2.3.2 37 | gemfile: gemfiles/Gemfile.rails-4-r2 38 | - rvm: 2.4.1 39 | gemfile: gemfiles/Gemfile.rails-3.2.13 40 | - rvm: 2.4.1 41 | gemfile: gemfiles/Gemfile.rails-4-r2 42 | - rvm: 2.4.6 43 | gemfile: gemfiles/Gemfile.rails-3.2.13 44 | - rvm: 2.4.6 45 | gemfile: gemfiles/Gemfile.rails-4-r2 46 | - rvm: 2.4.5 47 | gemfile: gemfiles/Gemfile.rails-3.2.13 48 | - rvm: 2.4.5 49 | gemfile: gemfiles/Gemfile.rails-4-r2 50 | - rvm: 2.5.4 51 | gemfile: gemfiles/Gemfile.rails-3.2.13 52 | - rvm: 2.5.4 53 | gemfile: gemfiles/Gemfile.rails-4-r2 54 | - rvm: 2.5.5 55 | gemfile: gemfiles/Gemfile.rails-3.2.13 56 | - rvm: 2.5.5 57 | gemfile: gemfiles/Gemfile.rails-4-r2 58 | - rvm: 2.6.3 59 | gemfile: gemfiles/Gemfile.rails-3.2.13 60 | - rvm: 2.6.3 61 | gemfile: gemfiles/Gemfile.rails-4-r2 62 | allow_failures: 63 | - rvm: rbx-2 64 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source "http://rubygems.org" 2 | 3 | 4 | group :development, :test do 5 | gem "rails", "~> 4.2" 6 | gem "sqlite3", '1.3.13' 7 | gem "json_pure" 8 | gem "jeweler", git: 'git@github.com:technicalpickles/jeweler' 9 | # gem "jeweler", "~> 2.3" 10 | gem "rspec-rails", "~> 3.0.0" 11 | gem "rspec", "~> 3.0.0" 12 | gem "actionpack", ">=4.0.0" 13 | gem "simplecov", :require => false 14 | gem "rake", "~> 10.1" 15 | 16 | gem 'nokogiri' 17 | 18 | gem "generator_spec" 19 | 20 | platforms :rbx do 21 | gem 'rubysl' 22 | gem 'rubysl-test-unit' 23 | gem 'psych', '~> 2.2' 24 | gem 'racc' 25 | gem 'rubinius-developer_tools' 26 | end 27 | 28 | end 29 | 30 | 31 | # To use debugger (ruby-debug for Ruby 1.8.7+, ruby-debug19 for Ruby 1.9.2+) 32 | # gem 'ruby-debug' 33 | # gem 'ruby-debug19' 34 | -------------------------------------------------------------------------------- /History.md: -------------------------------------------------------------------------------- 1 | # Change History / Release Notes 2 | 3 | ## Unreleased 4 | 5 | * Fix jquery deprecation. [Joseph Chen] 6 | * Add event listener for @hotwired/turbo. [Jeremiah] 7 | * Fix JSON import. [Gonçalo Morais] 8 | 9 | ## Version 1.2.15 10 | 11 | * Rails 6 compatible: publish the js to npm. [nathanvda] 12 | * Remove side-effects on render_options. Fixes #478. [nathanvda] 13 | * Prevent propagation to parent elements on add field event. [Ashley Van De Poel] 14 | 15 | ## Version 1.2.14 16 | 17 | * Use form builder to add hidden `_destroy` field. [Ranko Radonic] 18 | 19 | ## Version 1.2.13 20 | 21 | * Add originalEvent extra param to insert and remove events. [Daniel Olivares] 22 | * Prevent propagation to parent elements. [Zmago Devetak] 23 | 24 | ## Version 1.2.12 25 | 26 | * Fix compatibility for Mongoid 7. [Cyril Duchon-Doris] 27 | * Use .detach() instead of .remove() for removing dynamic assocs. [Jeremiah Megel] 28 | 29 | ## Version 1.2.11 30 | 31 | * Allow events to be cancelled in the 'before' callbacks. [Will Gordon] 32 | 33 | ## Version 1.2.10 34 | 35 | * Don't directly load AV::Base in the initializer, but use AS lazy load hook. [Akira Matsuda] 36 | * Correctly work with Turbolinks 5 events. [nathanvda] 37 | 38 | ## Version 1.2.9 39 | 40 | * Allow passing a function to `data-association-insertion-node` that takes the 41 | `link_to_add_association` node as the parameter and returns a node. [Ryo Yamada] 42 | 43 | ## Version 1.2.8 44 | 45 | * Make turbolinks compliant. [nathanvda] 46 | 47 | ## Version 1.2.7 48 | 49 | * Use I18n for link_to_*_association texts. 50 | * Check form class to more accurately render add association form partials. Fixes #291. 51 | * Move to rspec ~> 3.0. 52 | 53 | ## Version 1.2.6 54 | 55 | * added some explicit documentation we use haml. Fixed the formtastic example. 56 | * "unfreeze" frozen objects. Fixes #193. 57 | * IE8 jquery fix (thanks @niuage). 58 | * merged #191 which fixes an issue with a monkeypatched CGI. For more info, see 59 | ticket #191. Thanks gsmendoza. 60 | 61 | ## Version 1.2.5 62 | 63 | * fix gem dependencies: we added gems to allow building for rubinius, but those are only 64 | needed when developing 65 | 66 | ## Version 1.2.4 67 | 68 | * the wrapper class is now configurable. Before it was assumed to be `nested-fields`. 69 | Now it is configurable by handing. See #180. Thanks Yoav Matchulsky. 70 | * fix build on travis-ci for rubinius (thanks brixen). 71 | 72 | ## Version 1.2.3 73 | 74 | * add license info 75 | 76 | ## Version 1.2.2 77 | 78 | * added option to add multiple items on one click. See #175. 79 | * cleaned up javascript code. See #171. 80 | 81 | 82 | ## Version 1.2.1 83 | 84 | * added a `:form_name` parameter (fixes #153) which allows to use a self-chosen 85 | parameter in the nested views. Up until now `f` was assumed (and enforced). 86 | * improvement of creation of the objects on the association (thanks to Dirk von Grünigen). This 87 | alleviates the need for the `:force_non_association_create` option in most cases. 88 | That option is for now still kept. 89 | * after validation errors, already deleted (but not saved) nested elements, will remain deleted 90 | (e.g. the state is remembered, and they remain hidden, and will be correctly deleted on next 91 | succesfull save) (fixes #136). 92 | 93 | ## Version 1.2.0 94 | 95 | * support for rails 4.0 96 | 97 | ## Version 1.1.2 98 | 99 | * pull #118 (thanks @ahmozkya): remove the deprecated `.live` function, and use `.on` instead. 100 | Note: at least jquery 1.7 is required now! 101 | 102 | ## Version 1.1.1 103 | 104 | * added the to be added/deleted element to the event, this allows to add animations/actions onto them 105 | * added extra option :wrap_object, allowing to use Decorators instead of the association object 106 | * added an option :force_non_association_create, that will allow to use `link_to_add_association` inside the fields-partial 107 | 108 | ## Version 1.1.0 109 | 110 | * BREAKING: the triggered javascript events `removal-callback`, `after-removal-callback`, and `insertion-callback` are renamed to the more correct and symmetric 111 | `cocoon:after-insert, cocoon:before-insert, cocoon:after-remove, cocoon:before-remove`. Also the events are namespaced to prevent collisions with other libraries. 112 | * allow created objects to be decorated with a callable. This is especially useful if you are using Draper or some decorator instead of the plain model in your views. 113 | * it is now possible to specify a relative node, and use standard jquery traversal methods on insertion 114 | * trigger insertion event on correct `insertionNode` 115 | * thanks to #90 cocoon now supports non-AR associations and array-fields, you just have to supply your own `build_` methods 116 | 117 | I would really really like to thank all contributors, check them out https://github.com/nathanvda/cocoon/graphs/contributors 118 | They made cocoon way more awesome than I could have done in my lonesome. 119 | 120 | ## Version 1.0.22 121 | 122 | * Fix that it still works for mongoid 123 | 124 | ## Version 1.0.21 125 | 126 | * Use association build methods instead of assoc.klass.new. This avoids mass-assignment errors and other misbehaviors around attribute accessibility. 127 | 128 | 129 | ## Version 1.0.20 130 | 131 | * improved handing of the `:partial`: remove the extra options-hash, and just make it use the single hash, so now we can just write 132 | 133 | = link_to_add_association 'add something', f, :tasks, :partial => 'shared/task_fields' 134 | = link_to_add_association 'add something', f, :tasks, :class => 'your-special-class', :partial => 'shared/task_fields' 135 | 136 | 137 | ## Version 1.0.19 138 | 139 | * pull #53 (@CuriousCurmudgeon): fixed some bugs introduced in previous version (ooooops! Thanks!!!) 140 | 141 | ## Version 1.0.18 142 | 143 | * pull in #51 (@erwin): adding an `after-removal-callback` in javascript, very useful if you want to recalculate e.g. total-items or indexes 144 | * pull in #42 (@zacstewart): allow to hand extra `:locals` to the partial 145 | * updated documentation 146 | 147 | ## Version 1.0.17 148 | 149 | * fix: make sure that cocoon still works for rails 3.0, where the `conditions` is not available yet 150 | 151 | ## Version 1.0.16 152 | 153 | * merged pull request #33 (@fl00r): added the a custom partial option! genius :) 154 | Also the creation of the nested objects takes any available conditions into account. 155 | Now you can write 156 | 157 | = link_to_add_association 'add something', f, :tasks, {}, :partial => 'shared/task_fields' 158 | 159 | ## Version 1.0.15 160 | 161 | * added `data-association-insertion-method` that gives more control over where to insert the new nested fields. 162 | It takes a jquery method as parameter that inserts the new data. `before`, `after`, `append`, `prepend`, etc. Default: `before`. 163 | * `data-association-insertion-position` is still available and acts as an alias. Probably this will be deprecated in the future. 164 | 165 | 166 | ## Version 1.0.14 167 | 168 | * When playing with `simple_form` and `twitter-bootstrap`, I noticed it is crucial that I call the correct nested-fields function. 169 | That is: `fields_for` for standard forms, `semantic_fields_for` in formtastic and `simple_fields_for` for simple_form. 170 | Secondly, this was not enough, I needed to be able to hand down options to that method. So in the `link_to_add_association` method you 171 | can now an extra option `:render_options` and that hash will be handed to the association-builder. 172 | 173 | This allows the nested fields to be built correctly with `simple_form` for `twitter-bootstrap`. 174 | 175 | ## Version 1.0.13 176 | 177 | * A while ago we added the option to add a javascript callback on inserting a new associated object, I now made sure we can add a callback on insertion 178 | and on removal of a new item. One example where this was useful for me is visible in the demo project `cocoon_simple_form_demo` where I implemented a 179 | `belongs_to` relation, and either select from a list, or add a new element. 180 | So: the callback-mechanism has changed, and now the callback is bound to the parent container, instead of the link itself. This is because we can also 181 | bind the removal callback there (as the removal link is inserted in the html dynamically). 182 | 183 | For more info, see the `README`. 184 | 185 | ## Version 1.0.12 186 | 187 | * using "this" in `association-insertion-node` is now possible 188 | 189 | If you are using rails < 3.1, you should run 190 | 191 | rails g cocoon:install 192 | 193 | to install the new `cocoon.js` to your `public/javascripts` folder. 194 | 195 | 196 | ## Version 1.0.11 197 | 198 | 199 | ## Version 1.0.10 200 | 201 | * Fuck! Built the gem with 1.9.2 again. Built the gem again with 1.8.7. 202 | 203 | ## Version 1.0.9 204 | 205 | * is now rails 3.1 compatible. If you are not using Rails 3.1 yet, this should have no effect. 206 | For rails 3.1 the cocoon.js no longer needs to be installed using the `rails g cocoon:install`. It is 207 | automatically used from the gem. 208 | 209 | ## Version 1.0.8 210 | 211 | * Loosened the gem dependencies. 212 | 213 | ## Version 1.0.7 (20/06/2011) 214 | 215 | Apparently, the gem 1.0.6 which was generated with ruby 1.9.2 gave the following error upon install: 216 | 217 | uninitialized constant Psych::Syck (NameError) 218 | 219 | This is related to this bug: http://rubyforge.org/tracker/?group_id=126&atid=575&func=detail&aid=29163 220 | 221 | This should be fixed in the next release of rubygems, the fix should be to build the gem with ruby 1.8.7. 222 | Let's hope this works. 223 | 224 | ## Version 1.0.6 (19/06/2011) 225 | 226 | * The javascript has been improved to consistently use `e.preventDefault` instead of returning false. 227 | 228 | Run 229 | 230 | rails g cocoon:install 231 | 232 | to copy the new `cocoon.js` to your `public/javascripts` folder. 233 | 234 | 235 | ## Version 1.0.5 (17/06/2011) 236 | 237 | * This release make sure that the `link_to_add_association` generates a correctly clickable 238 | link in the newer rails 3 versions as well. In rails 3.0.8. the html was double escaped. 239 | 240 | If you are upgrading from 1.0.4, you just have to update the gem. No other actions needed. If you are updating 241 | from earlier versions, it is safer to do 242 | 243 | rails g cocoon:install 244 | 245 | This will copy the new `cocoon.js` files to your `public/javascripts` folder. 246 | 247 | 248 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2011 Nathan Van der Auwera 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 18 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 19 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 20 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /README.markdown: -------------------------------------------------------------------------------- 1 | # cocoon 2 | 3 | [![Build Status](https://travis-ci.org/nathanvda/cocoon.png?branch=master)](https://travis-ci.org/nathanvda/cocoon) 4 | 5 | Cocoon makes it easier to handle nested forms. 6 | 7 | Nested forms are forms that handle nested models and attributes in one form; 8 | e.g. a project with its tasks or an invoice with its line items. 9 | 10 | Cocoon is form builder-agnostic, so it works with standard Rails, [Formtastic](https://github.com/justinfrench/formtastic), or [SimpleForm](https://github.com/plataformatec/simple_form). 11 | It is compatible with rails 3, 4 and 5. 12 | 13 | This project is not related to [Apache Cocoon](http://cocoon.apache.org/). 14 | 15 | ## Prerequisites 16 | 17 | This gem depends on jQuery, so it's most useful in a Rails project where you are already using jQuery. 18 | Furthermore, I would advise you to use either [Formtastic](https://github.com/justinfrench/formtastic) or [SimpleForm](https://github.com/plataformatec/simple_form). 19 | 20 | ## Installation 21 | 22 | Inside your `Gemfile` add the following: 23 | 24 | ```ruby 25 | gem "cocoon" 26 | ``` 27 | 28 | > Please note that for rails 4 you will need at least v1.2.0 or later. 29 | 30 | ### Rails 6/Webpacker 31 | 32 | Add the companion package 33 | 34 | yarn add @nathanvda/cocoon 35 | 36 | and then in your `app/javascripts/packs/application.js` you should add 37 | 38 | require("jquery") 39 | require("@nathanvda/cocoon") 40 | 41 | 42 | > Note: there are alternative npm packages, which might better suit your needs. 43 | E.g. some offer the cocoon functionality without using jquery (search for `cocoon + vanilla` --I found three packages on npm already). 44 | Obviously you are free to use those, however the code samples in this README will (still) rely on jquery. 45 | 46 | 47 | ### Rails 3.1+/Rails 4/Rails 5 48 | 49 | Add the following to `application.js` so it compiles to the asset pipeline: 50 | 51 | ```ruby 52 | //= require cocoon 53 | ``` 54 | 55 | ### Rails 3.0.x 56 | 57 | If you are using Rails 3.0.x, you need to run the installation task (since rails 3.1 this is no longer needed): 58 | 59 | ```bash 60 | rails g cocoon:install 61 | ``` 62 | 63 | This will install the Cocoon JavaScript file. In your application layout, add the following below the default javascripts: 64 | 65 | ```haml 66 | = javascript_include_tag :cocoon 67 | ``` 68 | 69 | ## Basic Usage 70 | 71 | Suppose you have a `Project` model: 72 | 73 | ```bash 74 | rails g scaffold Project name:string description:string 75 | ``` 76 | 77 | And a project has many `tasks`: 78 | 79 | ```bash 80 | rails g model Task description:string done:boolean project:belongs_to 81 | ``` 82 | 83 | Your models are associated like this: 84 | 85 | ```ruby 86 | class Project < ActiveRecord::Base 87 | has_many :tasks, inverse_of: :project 88 | accepts_nested_attributes_for :tasks, reject_if: :all_blank, allow_destroy: true 89 | end 90 | 91 | class Task < ActiveRecord::Base 92 | belongs_to :project 93 | end 94 | ``` 95 | 96 | > *Rails 5 Note*: since rails 5 a `belongs_to` relation is by default required. While this absolutely makes sense, this also means 97 | > associations have to be declared more explicitly. 98 | > When saving nested items, theoretically the parent is not yet saved on validation, so rails needs help to know 99 | > the link between relations. There are two ways: either declare the `belongs_to` as `optional: false`, but the 100 | > cleanest way is to specify the `inverse_of:` on the `has_many`. That is why we write : `has_many :tasks, inverse_of: :project` 101 | 102 | 103 | 104 | Now we want a project form where we can add and remove tasks dynamically. 105 | To do this, we need the fields for a new or existing `task` to be defined in a partial 106 | named `_task_fields.html`. 107 | 108 | ### Strong Parameters Gotcha 109 | 110 | To destroy nested models, rails uses a virtual attribute called `_destroy`. 111 | When `_destroy` is set, the nested model will be deleted. If the record is persisted, rails performs `id` field lookup to destroy the real record, so if `id` wasn't specified, it will treat current set of parameters like a parameters for a new record. 112 | 113 | When using strong parameters (default in rails 4), you need to explicitly 114 | add both `:id` and `:_destroy` to the list of permitted parameters. 115 | 116 | E.g. in your `ProjectsController`: 117 | 118 | ```ruby 119 | def project_params 120 | params.require(:project).permit(:name, :description, tasks_attributes: [:id, :description, :done, :_destroy]) 121 | end 122 | ``` 123 | 124 | ### Has One Gotcha 125 | 126 | If you have a `has_one` association, then you (probably) need to set `force_non_association_create: true` on `link_to_add_association` 127 | 128 | If you don't do this, then rails will automatically delete your existing association when you view the edit form! 129 | 130 | More details in the [wiki](https://github.com/nathanvda/cocoon/wiki/has_one-association) 131 | 132 | ## Examples 133 | 134 | Cocoon's default configuration requires `link_to_add_association` and associated partials to 135 | be properly wrapped with elements. The examples below illustrate simple layouts. 136 | 137 | Please note these examples rely on the `haml` gem ([click here](https://github.com/nathanvda/cocoon/wiki/ERB-examples) for the default `erb` views). 138 | 139 | ### Formtastic 140 | 141 | In our `projects/_form` partial we'd write: 142 | 143 | ```haml 144 | = semantic_form_for @project do |f| 145 | = f.inputs do 146 | = f.input :name 147 | = f.input :description 148 | %h3 Tasks 149 | #tasks 150 | = f.semantic_fields_for :tasks do |task| 151 | = render 'task_fields', f: task 152 | .links 153 | = link_to_add_association 'add task', f, :tasks 154 | = f.actions do 155 | = f.action :submit 156 | ``` 157 | 158 | And in our `_task_fields` partial we'd write: 159 | 160 | ```haml 161 | .nested-fields 162 | = f.inputs do 163 | = f.input :description 164 | = f.input :done, as: :boolean 165 | = link_to_remove_association "remove task", f 166 | ``` 167 | 168 | The example project [cocoon_formtastic_demo](https://github.com/nathanvda/cocoon_formtastic_demo) demonstrates this. 169 | 170 | ### SimpleForm 171 | 172 | In our `projects/_form` partial we'd write: 173 | 174 | ```haml 175 | = simple_form_for @project do |f| 176 | = f.input :name 177 | = f.input :description 178 | %h3 Tasks 179 | #tasks 180 | = f.simple_fields_for :tasks do |task| 181 | = render 'task_fields', f: task 182 | .links 183 | = link_to_add_association 'add task', f, :tasks 184 | = f.submit 185 | ``` 186 | 187 | In our `_task_fields` partial we write: 188 | 189 | ```haml 190 | .nested-fields 191 | = f.input :description 192 | = f.input :done, as: :boolean 193 | = link_to_remove_association "remove task", f 194 | ``` 195 | 196 | The example project [cocoon_simple_form_demo](https://github.com/nathanvda/cocoon_simple_form_demo) demonstrates this. 197 | 198 | ### Standard Rails forms 199 | 200 | In our `projects/_form` partial we'd write: 201 | 202 | ```haml 203 | = form_for @project do |f| 204 | .field 205 | = f.label :name 206 | %br 207 | = f.text_field :name 208 | .field 209 | = f.label :description 210 | %br 211 | = f.text_field :description 212 | %h3 Tasks 213 | #tasks 214 | = f.fields_for :tasks do |task| 215 | = render 'task_fields', f: task 216 | .links 217 | = link_to_add_association 'add task', f, :tasks 218 | = f.submit 219 | ``` 220 | 221 | In our `_task_fields` partial we'd write: 222 | 223 | ```haml 224 | .nested-fields 225 | .field 226 | = f.label :description 227 | %br 228 | = f.text_field :description 229 | .field 230 | = f.check_box :done 231 | = f.label :done 232 | = link_to_remove_association "remove task", f 233 | ``` 234 | 235 | ## How it works 236 | 237 | Cocoon defines two helper functions: 238 | 239 | ### link_to_add_association 240 | 241 | This function adds a link to your markup that, when clicked, dynamically adds a new partial form for the given association. 242 | This should be called within the form builder. 243 | 244 | `link_to_add_association` takes four parameters: 245 | 246 | - **name**: the text to show in the link 247 | - **f**: the form builder 248 | - **association**: the name of the association (plural) of which a new instance needs to be added (symbol or string). 249 | - **html_options**: extra html-options (see [`link_to`](http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to) 250 | There are some special options, the first three allow to control the placement of the new link-data: 251 | - `data-association-insertion-traversal` : the jquery traversal method to allow node selection relative to the link. `closest`, `next`, `children`, etc. Default: absolute selection 252 | - `data-association-insertion-node` : the jquery selector of the node as string, or a function that takes the `link_to_add_association` node as the parameter and returns a node. Default: parent node 253 | - `data-association-insertion-method` : jquery method that inserts the new data. `before`, `after`, `append`, `prepend`, etc. Default: `before` 254 | - `data-association-insertion-position` : old method specifying where to insert new data. 255 | - this setting still works but `data-association-insertion-method` takes precedence. may be removed in a future version. 256 | - `partial`: explicitly declare the name of the partial that will be used 257 | - `render_options` : options passed through to the form-builder function (e.g. `simple_fields_for`, `semantic_fields_for` or `fields_for`). 258 | If it contains a `:locals` option containing a hash, that is handed to the partial. 259 | - `wrap_object` : a proc that will allow to wrap your object, especially useful if you are using decorators (e.g. draper). See example lower. 260 | - `force_non_association_create`: if true, it will _not_ create the new object using the association (see lower) 261 | - `form_name` : the name of the form parameter in your nested partial. By default this is `f`. 262 | - `count` : the number of nested items to insert at once. Default `1`. 263 | 264 | Optionally, you can omit the name and supply a block that is captured to render the link body (if you want to do something more complicated). 265 | 266 | #### :render_options 267 | Inside the `html_options` you can add an option `:render_options`, and the containing hash will be handed down to the form builder for the inserted 268 | form. 269 | 270 | When using Twitter Bootstrap and SimpleForm together, `simple_fields_for` needs the option `wrapper: 'inline'` which can 271 | be handed down as follows: 272 | 273 | (Note: In certain newer versions of simple_form, the option to use is `wrapper: 'bootstrap'`.) 274 | 275 | ```haml 276 | = link_to_add_association 'add something', f, :something, 277 | render_options: { wrapper: 'inline' } 278 | ``` 279 | 280 | To specify locals that needed to handed down to the partial: 281 | 282 | ```haml 283 | = link_to_add_association 'add something', f, :something, 284 | render_options: {locals: { sherlock: 'Holmes' }} 285 | ``` 286 | 287 | #### :partial 288 | 289 | To override the default partial name, e.g. because it shared between multiple views: 290 | 291 | ```haml 292 | = link_to_add_association 'add something', f, :something, 293 | partial: 'shared/something_fields' 294 | ``` 295 | 296 | #### :wrap_object 297 | 298 | If you are using decorators, the normal instantiation of the associated object will not be enough. You actually want to generate the decorated object. 299 | 300 | A simple decorator would look like: 301 | 302 | ```ruby 303 | class CommentDecorator 304 | def initialize(comment) 305 | @comment = comment 306 | end 307 | 308 | def formatted_created_at 309 | @comment.created_at.to_formatted_s(:short) 310 | end 311 | 312 | def method_missing(method_sym, *args) 313 | if @comment.respond_to?(method_sym) 314 | @comment.send(method_sym, *args) 315 | else 316 | super 317 | end 318 | end 319 | end 320 | ``` 321 | 322 | To use this: 323 | 324 | ```haml 325 | = link_to_add_association('add something', @form_obj, :comments, 326 | wrap_object: Proc.new {|comment| CommentDecorator.new(comment) }) 327 | ``` 328 | 329 | Note that the `:wrap_object` expects an object that is _callable_, so any `Proc` will do. So you could as well use it to do some fancy extra initialisation (if needed). 330 | But note you will have to return the (nested) object you want used. 331 | E.g. 332 | 333 | 334 | ```haml 335 | = link_to_add_association('add something', @form_obj, :comments, 336 | wrap_object: Proc.new { |comment| comment.name = current_user.name; comment }) 337 | ``` 338 | 339 | #### :force_non_association_create 340 | 341 | In normal cases we create a new nested object using the association relation itself. This is the cleanest way to create 342 | a new nested object. 343 | 344 | This used to have a side-effect: for each call of `link_to_add_association` a new element was added to the association. 345 | This is no longer the case. 346 | 347 | For backward compatibility we keep this option for now. Or if for some specific reason you would really need an object 348 | to be _not_ created on the association, for example if you did not want `after_add` callback to be triggered on 349 | the association. 350 | 351 | Example use: 352 | 353 | ```haml 354 | = link_to_add_association('add something', @form_obj, :comments, 355 | force_non_association_create: true) 356 | ``` 357 | 358 | By default `:force_non_association_create` is `false`. 359 | 360 | ### link_to_remove_association 361 | 362 | This function will add a link to your markup that, when clicked, dynamically removes the surrounding partial form. 363 | This should be placed inside the partial `__fields`. 364 | 365 | It takes three parameters: 366 | 367 | - **name**: the text to show in the link 368 | - **f**: referring to the containing form-object 369 | - **html_options**: extra html-options (see `link_to`) 370 | 371 | Optionally you could also leave out the name and supply a block that is captured to give the name (if you want to do something more complicated). 372 | 373 | Optionally, you can add an html option called `wrapper_class` to use a different wrapper div instead of `.nested-fields`. 374 | The class should be added without a preceding dot (`.`). 375 | 376 | > Note: the javascript behind the generated link relies on the presence of a wrapper class (default `.nested-fields`) to function correctly. 377 | 378 | Example: 379 | ```haml 380 | = link_to_remove_association('remove this', @form_obj, 381 | { wrapper_class: 'my-wrapper-class' }) 382 | ``` 383 | 384 | ### Callbacks (upon insert and remove of items) 385 | 386 | On insertion or removal the following events are triggered: 387 | 388 | * `cocoon:before-insert`: called before inserting a new nested child, can be [canceled](#canceling-a-callback) 389 | * `cocoon:after-insert`: called after inserting 390 | * `cocoon:before-remove`: called before removing the nested child, can be [canceled](#canceling-a-callback) 391 | * `cocoon:after-remove`: called after removal 392 | 393 | To listen to the events in your JavaScript: 394 | 395 | ```javascript 396 | $('#container').on('cocoon:before-insert', function(e, insertedItem, originalEvent) { 397 | // ... do something 398 | }); 399 | ``` 400 | 401 | ...where `e` is the event and the second parameter is the inserted or removed item. This allows you to change markup, or 402 | add effects/animations (see example below). 403 | `originalEvent` is also passed and references the event that triggered an insertion or removal (e.g. the `click` event on the link to add an association) 404 | 405 | 406 | If in your view you have the following snippet to select an `owner`: 407 | 408 | ```haml 409 | #owner 410 | #owner_from_list 411 | = f.association :owner, collection: Person.all(order: 'name'), prompt: 'Choose an existing owner' 412 | = link_to_add_association 'add a new person as owner', f, :owner 413 | ``` 414 | 415 | This will either let you select an owner from the list of persons, or show the fields to add a new person as owner. 416 | 417 | The callbacks can be added as follows: 418 | 419 | ```javascript 420 | $(document).ready(function() { 421 | $('#owner') 422 | .on('cocoon:before-insert', function() { 423 | $("#owner_from_list").hide(); 424 | $("#owner a.add_fields").hide(); 425 | }) 426 | .on('cocoon:after-insert', function() { 427 | /* ... do something ... */ 428 | }) 429 | .on("cocoon:before-remove", function() { 430 | $("#owner_from_list").show(); 431 | $("#owner a.add_fields").show(); 432 | }) 433 | .on("cocoon:after-remove", function() { 434 | /* e.g. recalculate order of child items */ 435 | }); 436 | 437 | // example showing manipulating the inserted/removed item 438 | 439 | $('#tasks') 440 | .on('cocoon:before-insert', function(e,task_to_be_added) { 441 | task_to_be_added.fadeIn('slow'); 442 | }) 443 | .on('cocoon:after-insert', function(e, added_task) { 444 | // e.g. set the background of inserted task 445 | added_task.css("background","red"); 446 | }) 447 | .on('cocoon:before-remove', function(e, task) { 448 | // allow some time for the animation to complete 449 | $(this).data('remove-timeout', 1000); 450 | task.fadeOut('slow'); 451 | }); 452 | }); 453 | ``` 454 | 455 | Note that for the callbacks to work there has to be a surrounding container to which you can bind the callbacks. 456 | 457 | When adding animations and effects to make the removal of items more interesting, you will also have to provide a timeout. 458 | This is accomplished by the following line: 459 | 460 | ```javascript 461 | $(this).data('remove-timeout', 1000); 462 | ``` 463 | 464 | You could also immediately add this to your view, on the `.nested-fields` container (or the `wrapper_class` element you are using). 465 | 466 | #### Canceling a Callback 467 | 468 | You can cancel an action from occurring, either an insertion or removal, within the `before-` callback by calling `event.preventDefault()` anywhere within the callback. 469 | 470 | For example: 471 | 472 | ```javascript 473 | $('#container').on('cocoon:before-insert', function(event, insertedItem) { 474 | var confirmation = confirm("Are you sure?"); 475 | if( confirmation === false ){ 476 | event.preventDefault(); 477 | } 478 | }); 479 | ``` 480 | 481 | ### Control the Insertion Behaviour 482 | 483 | The default insertion location is at the back of the current container. But we have added two `data-` attributes that are read to determine the insertion-node and -method. 484 | 485 | For example: 486 | 487 | ```javascript 488 | $(document).ready(function() { 489 | $("#owner a.add_fields"). 490 | data("association-insertion-method", 'before'). 491 | data("association-insertion-node", 'this'); 492 | }); 493 | ``` 494 | 495 | The `association-insertion-node` will determine where to add it. You can choose any selector here, or specify this. Also, you can pass a function that returns an arbitrary node. The default is the parent-container, if you don't specify anything. 496 | 497 | The `association-insertion-method` will determine where to add it in relation with the node. Any jQuery DOM Manipulation method can be set but we recommend sticking to any of the following: `before`, `after`, `append`, `prepend`. It is unknown at this time what others would do. 498 | 499 | The `association-insertion-traversal` will allow node selection to be relative to the link. 500 | 501 | For example: 502 | 503 | ```javascript 504 | $(document).ready(function() { 505 | $("#owner a.add_fields"). 506 | data("association-insertion-method", 'append'). 507 | data("association-insertion-traversal", 'closest'). 508 | data("association-insertion-node", '#parent_table'); 509 | }); 510 | ``` 511 | 512 | (if you pass `association-insertion-node` as a function, this value will be ignored) 513 | 514 | 515 | Note, if you want to add templates to the specific location which is: 516 | 517 | - not a direct parent or sibling of the link 518 | - the link appears multiple times - for instance, inside a deeply nested form 519 | 520 | you need to specify `association-insertion-node` as a function. 521 | 522 | 523 | For example, suppose Task has many SubTasks in the [Example](#examples), and have subtask forms like the following. 524 | 525 | ```haml 526 | .row 527 | .col-lg-12 528 | .add_sub_task= link_to_add_association 'add a new sub task', f, :sub_tasks 529 | .row 530 | .col-lg-12 531 | .sub_tasks_form 532 | fields_for :sub_tasks do |sub_task_form| 533 | = render 'sub_task_fields', f: sub_task_form 534 | ``` 535 | 536 | Then this will do the thing. 537 | 538 | ```javascript 539 | $(document).ready(function() { 540 | $(".add_sub_task a"). 541 | data("association-insertion-method", 'append'). 542 | data("association-insertion-node", function(link){ 543 | return link.closest('.row').next('.row').find('.sub_tasks_form') 544 | }); 545 | }); 546 | ``` 547 | 548 | 549 | ### Partial 550 | 551 | If no explicit partial name is given, `cocoon` looks for a file named `__fields`. 552 | To override the default partial use the `:partial` option. 553 | 554 | For the JavaScript to behave correctly, the partial should start with a container (e.g. `div`) of class `.nested-fields`, or a class of your choice which you can define in the `link_to_remove_association` method. 555 | 556 | There is no limit to the amount of nesting, though. 557 | 558 | ## I18n 559 | 560 | As you seen in previous sections, the helper method `link_to_add_association` treats the first parameter as a name. Additionally, if it's skipped and the `form` object is passed as the first one, then **Cocoon** names it using **I18n**. 561 | 562 | It allows to invoke helper methods like this: 563 | 564 | ```haml 565 | = link_to_add_association form_object, :tasks 566 | = link_to_remove_association form_object 567 | ``` 568 | 569 | instead of: 570 | 571 | ```haml 572 | = link_to_add_association "Add task", form_object, :tasks 573 | = link_to_remove_association "remove task", form_object 574 | ``` 575 | 576 | **Cocoon** uses the name of `association` as a translations scope key. If custom translations for association is not present it fallbacks to default name. Example of translations tree: 577 | 578 | ```yaml 579 | en: 580 | cocoon: 581 | defaults: 582 | add: "Add record" 583 | remove: "Remove record" 584 | tasks: 585 | add: "Add new task" 586 | remove: "Remove old task" 587 | ``` 588 | 589 | Note that `link_to_remove_association` does not require `association` name as an argument. In order to get correct translation key, **Cocoon** tableizes `class` name of the target object of form builder (`form_object.object` from previous example). 590 | 591 | ## Note on Patches/Pull Requests 592 | 593 | * Fork the project. 594 | * Make your feature addition or bug fix. 595 | * Add tests for it. This is important so I don't break it in a 596 | future version unintentionally. 597 | * Commit, do not mess with rakefile, version, or history. 598 | (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull) 599 | * Send me a pull request. Bonus points for topic branches. 600 | 601 | 602 | ## Contributors 603 | 604 | The list of contributors just keeps on growing. [Check it out!](https://github.com/nathanvda/cocoon/graphs/contributors) 605 | I would really really like to thank all of them. They make cocoon more awesome every day. Thanks. 606 | 607 | ## Todo 608 | 609 | * add more sample relations: `has_many :through`, `belongs_to`, ... 610 | * improve the tests (test the javascript too)(if anybody wants to lend a hand ...?) 611 | 612 | ## Copyright 613 | 614 | Copyright (c) 2010 Nathan Van der Auwera. See LICENSE for details. 615 | 616 | ## Not Related To Apache Cocoon 617 | 618 | Please note that this project is not related to the Apache Cocoon web framework project. 619 | 620 | [Apache Cocoon](http://cocoon.apache.org/), Cocoon, and Apache are either registered trademarks or trademarks of the [Apache Software Foundation](http://www.apache.org/) in the United States and/or other countries. 621 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | require 'rubygems' 3 | begin 4 | require 'bundler/setup' 5 | rescue LoadError 6 | puts 'You must `gem install bundler` and `bundle install` to run rake tasks' 7 | end 8 | 9 | require 'rake' 10 | require 'rdoc/task' 11 | 12 | require 'rspec/core' 13 | require 'rspec/core/rake_task' 14 | require 'erb' 15 | require 'json' 16 | 17 | 18 | RSpec::Core::RakeTask.new(:spec) 19 | 20 | task :default => :spec 21 | 22 | Rake::RDocTask.new(:rdoc) do |rdoc| 23 | rdoc.rdoc_dir = 'rdoc' 24 | rdoc.title = 'Cocoon' 25 | rdoc.options << '--line-numbers' << '--inline-source' 26 | rdoc.rdoc_files.include('README.rdoc') 27 | rdoc.rdoc_files.include('lib/**/*.rb') 28 | end 29 | 30 | begin 31 | require 'jeweler' 32 | Jeweler::Tasks.new do |gem| 33 | gem.name = "cocoon" 34 | gem.summary = %Q{gem that enables easier nested forms with standard forms, formtastic and simple-form} 35 | gem.description = %Q{Unobtrusive nested forms handling, using jQuery. Use this and discover cocoon-heaven.} 36 | gem.email = "nathan@dixis.com" 37 | gem.homepage = "https://github.com/nathanvda/cocoon" 38 | gem.authors = ["Nathan Van der Auwera"] 39 | gem.licenses = ["MIT"] 40 | # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings 41 | end 42 | Jeweler::GemcutterTasks.new 43 | rescue LoadError 44 | puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler" 45 | end 46 | 47 | 48 | require 'bundler/gem_tasks' 49 | 50 | spec = Bundler.load_gemspec('./cocoon.gemspec') 51 | 52 | 53 | npm_src_dir = './npm' 54 | npm_dest_dir = './dist' 55 | CLOBBER.include 'dist' 56 | 57 | assets_dir = './app/assets/' 58 | 59 | npm_files = { 60 | File.join(npm_dest_dir, 'cocoon.js') => File.join(assets_dir, 'javascripts', 'cocoon.js'), 61 | File.join(npm_dest_dir, 'README.md') => File.join(npm_src_dir, 'README.md'), 62 | File.join(npm_dest_dir, 'LICENSE') => './LICENSE' 63 | } 64 | 65 | namespace :npm do 66 | npm_files.each do |dest, src| 67 | file dest => src do 68 | cp src, dest 69 | end 70 | end 71 | 72 | task :'package-json' do 73 | template = ERB.new(File.read(File.join(npm_src_dir, 'package.json.erb'))) 74 | content = template.result_with_hash(spec: spec) 75 | File.write(File.join(npm_dest_dir, 'package.json'), 76 | JSON.pretty_generate(JSON.parse(content))) 77 | end 78 | 79 | desc "Build nathanvda-cocoon-#{spec.version}.tgz into the pkg directory" 80 | task build: (%i[package-json] + npm_files.keys) do 81 | system("cd #{npm_dest_dir} && npm pack && mv ./nathanvda-cocoon-#{spec.version}.tgz ../pkg/") 82 | end 83 | 84 | desc "Build and push nathanvda-cocoon-#{spec.version}.tgz to https://npmjs.org" 85 | task release: %i[build] do 86 | system("npm publish ./pkg/nathanvda-cocoon-#{spec.version}.tgz --access public") 87 | end 88 | end 89 | -------------------------------------------------------------------------------- /VERSION: -------------------------------------------------------------------------------- 1 | 1.2.15 -------------------------------------------------------------------------------- /app/assets/javascripts/cocoon.js: -------------------------------------------------------------------------------- 1 | (function($) { 2 | 3 | var cocoon_element_counter = 0; 4 | 5 | var create_new_id = function() { 6 | return (new Date().getTime() + cocoon_element_counter++); 7 | } 8 | 9 | var newcontent_braced = function(id) { 10 | return '[' + id + ']$1'; 11 | } 12 | 13 | var newcontent_underscord = function(id) { 14 | return '_' + id + '_$1'; 15 | } 16 | 17 | var getInsertionNodeElem = function(insertionNode, insertionTraversal, $this){ 18 | 19 | if (!insertionNode){ 20 | return $this.parent(); 21 | } 22 | 23 | if (typeof insertionNode == 'function'){ 24 | if(insertionTraversal){ 25 | console.warn('association-insertion-traversal is ignored, because association-insertion-node is given as a function.') 26 | } 27 | return insertionNode($this); 28 | } 29 | 30 | if(typeof insertionNode == 'string'){ 31 | if (insertionTraversal){ 32 | return $this[insertionTraversal](insertionNode); 33 | }else{ 34 | return insertionNode == "this" ? $this : $(insertionNode); 35 | } 36 | } 37 | 38 | } 39 | 40 | $(document).on('click', '.add_fields', function(e) { 41 | e.preventDefault(); 42 | e.stopPropagation(); 43 | 44 | var $this = $(this), 45 | assoc = $this.data('association'), 46 | assocs = $this.data('associations'), 47 | content = $this.data('association-insertion-template'), 48 | insertionMethod = $this.data('association-insertion-method') || $this.data('association-insertion-position') || 'before', 49 | insertionNode = $this.data('association-insertion-node'), 50 | insertionTraversal = $this.data('association-insertion-traversal'), 51 | count = parseInt($this.data('count'), 10), 52 | regexp_braced = new RegExp('\\[new_' + assoc + '\\](.*?\\s)', 'g'), 53 | regexp_underscord = new RegExp('_new_' + assoc + '_(\\w*)', 'g'), 54 | new_id = create_new_id(), 55 | new_content = content.replace(regexp_braced, newcontent_braced(new_id)), 56 | new_contents = [], 57 | originalEvent = e; 58 | 59 | 60 | if (new_content == content) { 61 | regexp_braced = new RegExp('\\[new_' + assocs + '\\](.*?\\s)', 'g'); 62 | regexp_underscord = new RegExp('_new_' + assocs + '_(\\w*)', 'g'); 63 | new_content = content.replace(regexp_braced, newcontent_braced(new_id)); 64 | } 65 | 66 | new_content = new_content.replace(regexp_underscord, newcontent_underscord(new_id)); 67 | new_contents = [new_content]; 68 | 69 | count = (isNaN(count) ? 1 : Math.max(count, 1)); 70 | count -= 1; 71 | 72 | while (count) { 73 | new_id = create_new_id(); 74 | new_content = content.replace(regexp_braced, newcontent_braced(new_id)); 75 | new_content = new_content.replace(regexp_underscord, newcontent_underscord(new_id)); 76 | new_contents.push(new_content); 77 | 78 | count -= 1; 79 | } 80 | 81 | var insertionNodeElem = getInsertionNodeElem(insertionNode, insertionTraversal, $this) 82 | 83 | if( !insertionNodeElem || (insertionNodeElem.length == 0) ){ 84 | console.warn("Couldn't find the element to insert the template. Make sure your `data-association-insertion-*` on `link_to_add_association` is correct.") 85 | } 86 | 87 | $.each(new_contents, function(i, node) { 88 | var contentNode = $(node); 89 | 90 | var before_insert = jQuery.Event('cocoon:before-insert'); 91 | insertionNodeElem.trigger(before_insert, [contentNode, originalEvent]); 92 | 93 | if (!before_insert.isDefaultPrevented()) { 94 | // allow any of the jquery dom manipulation methods (after, before, append, prepend, etc) 95 | // to be called on the node. allows the insertion node to be the parent of the inserted 96 | // code and doesn't force it to be a sibling like after/before does. default: 'before' 97 | var addedContent = insertionNodeElem[insertionMethod](contentNode); 98 | 99 | insertionNodeElem.trigger('cocoon:after-insert', [contentNode, 100 | originalEvent]); 101 | } 102 | }); 103 | }); 104 | 105 | $(document).on('click', '.remove_fields.dynamic, .remove_fields.existing', function(e) { 106 | var $this = $(this), 107 | wrapper_class = $this.data('wrapper-class') || 'nested-fields', 108 | node_to_delete = $this.closest('.' + wrapper_class), 109 | trigger_node = node_to_delete.parent(), 110 | originalEvent = e; 111 | 112 | e.preventDefault(); 113 | e.stopPropagation(); 114 | 115 | var before_remove = jQuery.Event('cocoon:before-remove'); 116 | trigger_node.trigger(before_remove, [node_to_delete, originalEvent]); 117 | 118 | if (!before_remove.isDefaultPrevented()) { 119 | var timeout = trigger_node.data('remove-timeout') || 0; 120 | 121 | setTimeout(function() { 122 | if ($this.hasClass('dynamic')) { 123 | node_to_delete.detach(); 124 | } else { 125 | $this.prev("input[type=hidden]").val("1"); 126 | node_to_delete.hide(); 127 | } 128 | trigger_node.trigger('cocoon:after-remove', [node_to_delete, 129 | originalEvent]); 130 | }, timeout); 131 | } 132 | }); 133 | 134 | var hideRemoveFields = function() { 135 | $('.remove_fields.existing.destroyed').each(function(i, obj) { 136 | var $this = $(this), 137 | wrapper_class = $this.data('wrapper-class') || 'nested-fields'; 138 | 139 | $this.closest('.' + wrapper_class).hide(); 140 | }); 141 | }; 142 | 143 | $(function() { 144 | hideRemoveFields(); 145 | $(document).on('page:load turbolinks:load turbo:load', hideRemoveFields); // Turbolinks support 146 | }); 147 | 148 | })(jQuery); 149 | 150 | 151 | -------------------------------------------------------------------------------- /cocoon.gemspec: -------------------------------------------------------------------------------- 1 | # Generated by jeweler 2 | # DO NOT EDIT THIS FILE DIRECTLY 3 | # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' 4 | # -*- encoding: utf-8 -*- 5 | # stub: cocoon 1.2.15 ruby lib 6 | 7 | Gem::Specification.new do |s| 8 | s.name = "cocoon".freeze 9 | s.version = "1.2.15" 10 | 11 | s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= 12 | s.require_paths = ["lib".freeze] 13 | s.authors = ["Nathan Van der Auwera".freeze] 14 | s.date = "2020-09-08" 15 | s.description = "Unobtrusive nested forms handling, using jQuery. Use this and discover cocoon-heaven.".freeze 16 | s.email = "nathan@dixis.com".freeze 17 | s.extra_rdoc_files = [ 18 | "LICENSE", 19 | "README.markdown" 20 | ] 21 | s.files = [ 22 | ".travis.yml", 23 | "Gemfile", 24 | "History.md", 25 | "LICENSE", 26 | "README.markdown", 27 | "Rakefile", 28 | "VERSION", 29 | "app/assets/javascripts/cocoon.js", 30 | "cocoon.gemspec", 31 | "gemfiles/Gemfile.default", 32 | "gemfiles/Gemfile.rails-3.2.13", 33 | "gemfiles/Gemfile.rails-4-r2", 34 | "lib/cocoon.rb", 35 | "lib/cocoon/view_helpers.rb", 36 | "lib/generators/cocoon/install/install_generator.rb", 37 | "npm/README.md", 38 | "npm/package.json.erb", 39 | "spec/cocoon_spec.rb", 40 | "spec/dummy/Rakefile", 41 | "spec/dummy/app/controllers/application_controller.rb", 42 | "spec/dummy/app/decorators/comment_decorator.rb", 43 | "spec/dummy/app/helpers/application_helper.rb", 44 | "spec/dummy/app/models/comment.rb", 45 | "spec/dummy/app/models/person.rb", 46 | "spec/dummy/app/models/post.rb", 47 | "spec/dummy/app/views/layouts/application.html.erb", 48 | "spec/dummy/config.ru", 49 | "spec/dummy/config/application.rb", 50 | "spec/dummy/config/boot.rb", 51 | "spec/dummy/config/database.yml", 52 | "spec/dummy/config/environment.rb", 53 | "spec/dummy/config/environments/development.rb", 54 | "spec/dummy/config/environments/production.rb", 55 | "spec/dummy/config/environments/test.rb", 56 | "spec/dummy/config/initializers/backtrace_silencers.rb", 57 | "spec/dummy/config/initializers/inflections.rb", 58 | "spec/dummy/config/initializers/mime_types.rb", 59 | "spec/dummy/config/initializers/rails_version_helper.rb", 60 | "spec/dummy/config/initializers/secret_token.rb", 61 | "spec/dummy/config/initializers/session_store.rb", 62 | "spec/dummy/config/locales/en.yml", 63 | "spec/dummy/config/routes.rb", 64 | "spec/dummy/db/migrate/20110306212208_create_posts.rb", 65 | "spec/dummy/db/migrate/20110306212250_create_comments.rb", 66 | "spec/dummy/db/migrate/20110420222224_create_people.rb", 67 | "spec/dummy/db/schema.rb", 68 | "spec/dummy/public/404.html", 69 | "spec/dummy/public/422.html", 70 | "spec/dummy/public/500.html", 71 | "spec/dummy/public/favicon.ico", 72 | "spec/dummy/public/javascripts/application.js", 73 | "spec/dummy/public/javascripts/controls.js", 74 | "spec/dummy/public/javascripts/dragdrop.js", 75 | "spec/dummy/public/javascripts/effects.js", 76 | "spec/dummy/public/javascripts/prototype.js", 77 | "spec/dummy/public/javascripts/rails.js", 78 | "spec/dummy/public/stylesheets/.gitkeep", 79 | "spec/dummy/script/rails", 80 | "spec/generators/install_generator_spec.rb", 81 | "spec/integration/navigation_spec.rb", 82 | "spec/spec_helper.rb", 83 | "spec/support/i18n.rb", 84 | "spec/support/rails_version_helper.rb", 85 | "spec/support/shared_examples.rb" 86 | ] 87 | s.homepage = "https://github.com/nathanvda/cocoon".freeze 88 | s.licenses = ["MIT".freeze] 89 | s.rubygems_version = "3.0.8".freeze 90 | s.summary = "gem that enables easier nested forms with standard forms, formtastic and simple-form".freeze 91 | 92 | if s.respond_to? :specification_version then 93 | s.specification_version = 4 94 | 95 | if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then 96 | s.add_development_dependency(%q.freeze, ["~> 4.2"]) 97 | s.add_development_dependency(%q.freeze, ["= 1.3.13"]) 98 | s.add_development_dependency(%q.freeze, [">= 0"]) 99 | s.add_development_dependency(%q.freeze, [">= 0"]) 100 | s.add_development_dependency(%q.freeze, ["~> 3.0.0"]) 101 | s.add_development_dependency(%q.freeze, ["~> 3.0.0"]) 102 | s.add_development_dependency(%q.freeze, [">= 4.0.0"]) 103 | s.add_development_dependency(%q.freeze, [">= 0"]) 104 | s.add_development_dependency(%q.freeze, ["~> 10.1"]) 105 | s.add_development_dependency(%q.freeze, [">= 0"]) 106 | s.add_development_dependency(%q.freeze, [">= 0"]) 107 | s.add_development_dependency(%q.freeze, [">= 0"]) 108 | s.add_development_dependency(%q.freeze, [">= 0"]) 109 | s.add_development_dependency(%q.freeze, ["~> 2.2"]) 110 | s.add_development_dependency(%q.freeze, [">= 0"]) 111 | s.add_development_dependency(%q.freeze, [">= 0"]) 112 | else 113 | s.add_dependency(%q.freeze, ["~> 4.2"]) 114 | s.add_dependency(%q.freeze, ["= 1.3.13"]) 115 | s.add_dependency(%q.freeze, [">= 0"]) 116 | s.add_dependency(%q.freeze, [">= 0"]) 117 | s.add_dependency(%q.freeze, ["~> 3.0.0"]) 118 | s.add_dependency(%q.freeze, ["~> 3.0.0"]) 119 | s.add_dependency(%q.freeze, [">= 4.0.0"]) 120 | s.add_dependency(%q.freeze, [">= 0"]) 121 | s.add_dependency(%q.freeze, ["~> 10.1"]) 122 | s.add_dependency(%q.freeze, [">= 0"]) 123 | s.add_dependency(%q.freeze, [">= 0"]) 124 | s.add_dependency(%q.freeze, [">= 0"]) 125 | s.add_dependency(%q.freeze, [">= 0"]) 126 | s.add_dependency(%q.freeze, ["~> 2.2"]) 127 | s.add_dependency(%q.freeze, [">= 0"]) 128 | s.add_dependency(%q.freeze, [">= 0"]) 129 | end 130 | else 131 | s.add_dependency(%q.freeze, ["~> 4.2"]) 132 | s.add_dependency(%q.freeze, ["= 1.3.13"]) 133 | s.add_dependency(%q.freeze, [">= 0"]) 134 | s.add_dependency(%q.freeze, [">= 0"]) 135 | s.add_dependency(%q.freeze, ["~> 3.0.0"]) 136 | s.add_dependency(%q.freeze, ["~> 3.0.0"]) 137 | s.add_dependency(%q.freeze, [">= 4.0.0"]) 138 | s.add_dependency(%q.freeze, [">= 0"]) 139 | s.add_dependency(%q.freeze, ["~> 10.1"]) 140 | s.add_dependency(%q.freeze, [">= 0"]) 141 | s.add_dependency(%q.freeze, [">= 0"]) 142 | s.add_dependency(%q.freeze, [">= 0"]) 143 | s.add_dependency(%q.freeze, [">= 0"]) 144 | s.add_dependency(%q.freeze, ["~> 2.2"]) 145 | s.add_dependency(%q.freeze, [">= 0"]) 146 | s.add_dependency(%q.freeze, [">= 0"]) 147 | end 148 | end 149 | -------------------------------------------------------------------------------- /gemfiles/Gemfile.default: -------------------------------------------------------------------------------- 1 | source "http://rubygems.org" 2 | 3 | 4 | group :development, :test do 5 | gem "rails", "~> 4.2" 6 | gem "sqlite3", '~> 1.3.13' 7 | gem "json_pure" 8 | gem "jeweler" 9 | gem "rspec-rails", "~> 3.0.0" 10 | gem "rspec", "~> 3.0.0" 11 | gem "simplecov", :require => false 12 | gem "rake", "~> 10.1" 13 | 14 | gem 'nokogiri' 15 | 16 | gem "generator_spec" 17 | 18 | platforms :rbx do 19 | gem 'rubysl' 20 | gem 'rubysl-test-unit' 21 | gem 'psych' 22 | gem 'racc' 23 | gem 'rubinius-developer_tools' 24 | end 25 | 26 | end 27 | 28 | 29 | # To use debugger (ruby-debug for Ruby 1.8.7+, ruby-debug19 for Ruby 1.9.2+) 30 | # gem 'ruby-debug' 31 | # gem 'ruby-debug19' 32 | -------------------------------------------------------------------------------- /gemfiles/Gemfile.rails-3.2.13: -------------------------------------------------------------------------------- 1 | source "http://rubygems.org" 2 | 3 | 4 | group :development, :test do 5 | gem "rails", "~> 3.2.0" 6 | gem "sqlite3", "1.3.8" 7 | gem "json_pure" 8 | gem "jeweler", "~> 1.8" 9 | gem "rspec-rails", "~> 3.0.0" 10 | gem "rspec", "~> 3.0.0" 11 | gem "actionpack", "~> 3.2.0" 12 | gem "simplecov", :require => false 13 | gem "rake", "~> 10.1" 14 | 15 | gem 'nokogiri' 16 | 17 | gem "generator_spec" 18 | end 19 | 20 | platforms :rbx do 21 | gem 'rubysl' 22 | gem 'rubysl-test-unit' 23 | gem 'psych' 24 | gem 'racc' 25 | gem 'rubinius-developer_tools' 26 | end 27 | 28 | # To use debugger (ruby-debug for Ruby 1.8.7+, ruby-debug19 for Ruby 1.9.2+) 29 | # gem 'ruby-debug' 30 | # gem 'ruby-debug19' 31 | -------------------------------------------------------------------------------- /gemfiles/Gemfile.rails-4-r2: -------------------------------------------------------------------------------- 1 | source "http://rubygems.org" 2 | 3 | 4 | group :development, :test do 5 | gem "rails", "~> 4.0.2" 6 | gem "sqlite3", "1.3.8" 7 | gem "json_pure" 8 | gem "jeweler", "~> 1.8" 9 | gem "rspec-rails", "~> 3.0.0" 10 | gem "rspec", "~> 3.0.0" 11 | gem "actionpack", "~> 4.0.2" 12 | gem "simplecov", :require => false 13 | gem "rake", "~> 10.1" 14 | 15 | gem 'nokogiri' 16 | 17 | gem "generator_spec" 18 | 19 | platforms :rbx do 20 | gem 'rubysl' 21 | gem 'rubysl-test-unit' 22 | gem 'psych' 23 | gem 'racc' 24 | gem 'rubinius-developer_tools' 25 | end 26 | 27 | end 28 | -------------------------------------------------------------------------------- /lib/cocoon.rb: -------------------------------------------------------------------------------- 1 | require 'cocoon/view_helpers' 2 | 3 | module Cocoon 4 | class Engine < ::Rails::Engine 5 | 6 | config.before_initialize do 7 | if config.action_view.javascript_expansions 8 | config.action_view.javascript_expansions[:cocoon] = %w(cocoon) 9 | end 10 | end 11 | 12 | # configure our plugin on boot 13 | initializer "cocoon.initialize" do |app| 14 | ActiveSupport.on_load :action_view do 15 | ActionView::Base.send :include, Cocoon::ViewHelpers 16 | end 17 | end 18 | 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /lib/cocoon/view_helpers.rb: -------------------------------------------------------------------------------- 1 | module Cocoon 2 | module ViewHelpers 3 | 4 | 5 | # this will show a link to remove the current association. This should be placed inside the partial. 6 | # either you give 7 | # - *name* : the text of the link 8 | # - *f* : the form this link should be placed in 9 | # - *html_options*: html options to be passed to link_to (see link_to) 10 | # 11 | # or you use the form without *name* with a *&block* 12 | # - *f* : the form this link should be placed in 13 | # - *html_options*: html options to be passed to link_to (see link_to) 14 | # - *&block*: the output of the block will be show in the link, see link_to 15 | 16 | def link_to_remove_association(*args, &block) 17 | if block_given? 18 | link_to_remove_association(capture(&block), *args) 19 | elsif args.first.respond_to?(:object) 20 | form = args.first 21 | association = form.object.class.to_s.tableize 22 | name = I18n.translate("cocoon.#{association}.remove", default: I18n.translate('cocoon.defaults.remove')) 23 | 24 | link_to_remove_association(name, *args) 25 | else 26 | name, f, html_options = *args 27 | html_options ||= {} 28 | 29 | is_dynamic = f.object.new_record? 30 | 31 | classes = [] 32 | classes << "remove_fields" 33 | classes << (is_dynamic ? 'dynamic' : 'existing') 34 | classes << 'destroyed' if f.object.marked_for_destruction? 35 | html_options[:class] = [html_options[:class], classes.join(' ')].compact.join(' ') 36 | 37 | wrapper_class = html_options.delete(:wrapper_class) 38 | html_options[:'data-wrapper-class'] = wrapper_class if wrapper_class.present? 39 | 40 | f.hidden_field(:_destroy, value: f.object._destroy) + link_to(name, '#', html_options) 41 | end 42 | end 43 | 44 | # :nodoc: 45 | def render_association(association, f, new_object, form_name, received_render_options={}, custom_partial=nil) 46 | partial = get_partial_path(custom_partial, association) 47 | render_options = received_render_options.dup 48 | locals = render_options.delete(:locals) || {} 49 | ancestors = f.class.ancestors.map{|c| c.to_s} 50 | method_name = ancestors.include?('SimpleForm::FormBuilder') ? :simple_fields_for : (ancestors.include?('Formtastic::FormBuilder') ? :semantic_fields_for : :fields_for) 51 | f.send(method_name, association, new_object, {:child_index => "new_#{association}"}.merge(render_options)) do |builder| 52 | partial_options = {form_name.to_sym => builder, :dynamic => true}.merge(locals) 53 | render(partial, partial_options) 54 | end 55 | end 56 | 57 | # shows a link that will allow to dynamically add a new associated object. 58 | # 59 | # - *name* : the text to show in the link 60 | # - *f* : the form this should come in (the formtastic form) 61 | # - *association* : the associated objects, e.g. :tasks, this should be the name of the has_many relation. 62 | # - *html_options*: html options to be passed to link_to (see link_to) 63 | # - *:render_options* : options passed to `simple_fields_for, semantic_fields_for or fields_for` 64 | # - *:locals* : the locals hash in the :render_options is handed to the partial 65 | # - *:partial* : explicitly override the default partial name 66 | # - *:wrap_object* : a proc that will allow to wrap your object, especially suited when using 67 | # decorators, or if you want special initialisation 68 | # - *:form_name* : the parameter for the form in the nested form partial. Default `f`. 69 | # - *:count* : Count of how many objects will be added on a single click. Default `1`. 70 | # - *&block*: see link_to 71 | 72 | def link_to_add_association(*args, &block) 73 | if block_given? 74 | link_to_add_association(capture(&block), *args) 75 | elsif args.first.respond_to?(:object) 76 | association = args.second 77 | name = I18n.translate("cocoon.#{association}.add", default: I18n.translate('cocoon.defaults.add')) 78 | 79 | link_to_add_association(name, *args) 80 | else 81 | name, f, association, html_options = *args 82 | html_options ||= {} 83 | 84 | render_options = html_options.delete(:render_options) 85 | render_options ||= {} 86 | override_partial = html_options.delete(:partial) 87 | wrap_object = html_options.delete(:wrap_object) 88 | force_non_association_create = html_options.delete(:force_non_association_create) || false 89 | form_parameter_name = html_options.delete(:form_name) || 'f' 90 | count = html_options.delete(:count).to_i 91 | 92 | html_options[:class] = [html_options[:class], "add_fields"].compact.join(' ') 93 | html_options[:'data-association'] = association.to_s.singularize 94 | html_options[:'data-associations'] = association.to_s.pluralize 95 | 96 | new_object = create_object(f, association, force_non_association_create) 97 | new_object = wrap_object.call(new_object) if wrap_object.respond_to?(:call) 98 | 99 | html_options[:'data-association-insertion-template'] = CGI.escapeHTML(render_association(association, f, new_object, form_parameter_name, render_options, override_partial).to_str).html_safe 100 | 101 | html_options[:'data-count'] = count if count > 0 102 | 103 | link_to(name, '#', html_options) 104 | end 105 | end 106 | 107 | # creates new association object with its conditions, like 108 | # `` has_many :admin_comments, class_name: "Comment", conditions: { author: "Admin" } 109 | # will create new Comment with author "Admin" 110 | 111 | def create_object(f, association, force_non_association_create=false) 112 | assoc = f.object.class.reflect_on_association(association) 113 | 114 | assoc ? create_object_on_association(f, association, assoc, force_non_association_create) : create_object_on_non_association(f, association) 115 | end 116 | 117 | def get_partial_path(partial, association) 118 | partial ? partial : association.to_s.singularize + "_fields" 119 | end 120 | 121 | private 122 | 123 | def create_object_on_non_association(f, association) 124 | builder_method = %W{build_#{association} build_#{association.to_s.singularize}}.select { |m| f.object.respond_to?(m) }.first 125 | return f.object.send(builder_method) if builder_method 126 | raise "Association #{association} doesn't exist on #{f.object.class}" 127 | end 128 | 129 | def create_object_on_association(f, association, instance, force_non_association_create) 130 | if instance.class.name.starts_with?('Mongoid::') || force_non_association_create 131 | create_object_with_conditions(instance) 132 | else 133 | assoc_obj = nil 134 | 135 | # assume ActiveRecord or compatible 136 | if instance.collection? 137 | assoc_obj = f.object.send(association).build 138 | f.object.send(association).delete(assoc_obj) 139 | else 140 | assoc_obj = f.object.send("build_#{association}") 141 | f.object.send(association).delete 142 | end 143 | 144 | assoc_obj = assoc_obj.dup if assoc_obj.frozen? 145 | 146 | assoc_obj 147 | end 148 | end 149 | 150 | def create_object_with_conditions(instance) 151 | # in rails 4, an association is defined with a proc 152 | # and I did not find how to extract the conditions from a scope 153 | # except building from the scope, but then why not just build from the 154 | # association??? 155 | conditions = instance.respond_to?(:conditions) ? instance.conditions.flatten : [] 156 | instance.klass.new(*conditions) 157 | end 158 | 159 | end 160 | end 161 | -------------------------------------------------------------------------------- /lib/generators/cocoon/install/install_generator.rb: -------------------------------------------------------------------------------- 1 | module Cocoon 2 | module Generators 3 | class InstallGenerator < ::Rails::Generators::Base 4 | source_root File.expand_path('../templates', __FILE__) 5 | 6 | desc "This generator installs the javascript needed for cocoon" 7 | def copy_the_javascript 8 | if ::Rails.version[0..2].to_f >= 3.1 9 | puts "Installing is no longer required since Rails 3.1" 10 | else 11 | copy_file "../../../../../app/assets/javascripts/cocoon.js", "public/javascripts/cocoon.js" 12 | end 13 | end 14 | 15 | end 16 | end 17 | end -------------------------------------------------------------------------------- /npm/README.md: -------------------------------------------------------------------------------- 1 | # cocoon 2 | 3 | Cocoon is the companion javascript code for the 4 | rails gem [cocoon](https://github.com/nathanvda/cocoon) 5 | which offers "dynamic" nested forms. 6 | 7 | This code depends on jQuery. 8 | 9 | -------------------------------------------------------------------------------- /npm/package.json.erb: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@nathanvda/cocoon", 3 | "version": "<%= spec.version %>", 4 | "license": "MIT", 5 | 6 | "description": "Companion package for the cocoon Ruby gem.", 7 | "homepage": "https://github.com/nathanvda/cocoon", 8 | "repository": "https://github.com/nathanvda/cocoon", 9 | "bugs": { 10 | "url": "https://github.com/nathanvda/cocoon/issues" 11 | }, 12 | 13 | "author": "nathan@dixis.com", 14 | 15 | "main": "cocoon.js", 16 | "files": ["cocoon.js", "README", "LICENSE", "package.json"], 17 | 18 | "dependencies": { 19 | "jquery": "^3.3.1" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /spec/cocoon_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | require 'nokogiri' 3 | 4 | describe Cocoon do 5 | class TestClass < ActionView::Base 6 | 7 | end 8 | 9 | subject {TestClass.new} 10 | 11 | it { is_expected.to respond_to(:link_to_add_association) } 12 | it { is_expected.to respond_to(:link_to_remove_association) } 13 | 14 | before(:each) do 15 | @tester = TestClass.new 16 | @post = Post.new 17 | end 18 | 19 | 20 | context "link_to_add_association" do 21 | before(:each) do 22 | @form_obj = double(:object => @post, :object_name => @post.class.name) 23 | allow(@tester).to receive(:render_association).and_return('form') 24 | end 25 | 26 | context "without a block" do 27 | 28 | context "and given a name" do 29 | before do 30 | @html = @tester.link_to_add_association('add something', @form_obj, :comments) 31 | end 32 | 33 | it_behaves_like "a correctly rendered add link", {} 34 | end 35 | 36 | context 'and no name given' do 37 | context 'custom translation exists' do 38 | before do 39 | I18n.backend.store_translations(:en, :cocoon => { :comments => { :add => 'Add comment' } }) 40 | 41 | @html = @tester.link_to_add_association(@form_obj, :comments) 42 | end 43 | 44 | it_behaves_like "a correctly rendered add link", { text: 'Add comment' } 45 | end 46 | 47 | context 'uses default translation' do 48 | before do 49 | I18n.backend.store_translations(:en, :cocoon => { :defaults => { :add => 'Add' } }) 50 | 51 | @html = @tester.link_to_add_association(@form_obj, :comments) 52 | end 53 | 54 | it_behaves_like "a correctly rendered add link", { text: 'Add' } 55 | end 56 | end 57 | 58 | context "and given html options to pass them to link_to" do 59 | before do 60 | @html = @tester.link_to_add_association('add something', @form_obj, :comments, {:class => 'something silly'}) 61 | end 62 | 63 | it_behaves_like "a correctly rendered add link", {class: 'something silly add_fields' } 64 | end 65 | 66 | context "and explicitly specifying the wanted partial" do 67 | before do 68 | allow(@tester).to receive(:render_association).and_call_original 69 | expect(@tester).to receive(:render_association).with(anything(), anything(), anything(), "f", anything(), "shared/partial").and_return('partiallll') 70 | @html = @tester.link_to_add_association('add something', @form_obj, :comments, :partial => "shared/partial") 71 | end 72 | 73 | it_behaves_like "a correctly rendered add link", {template: "partiallll"} 74 | end 75 | 76 | it "gives an opportunity to wrap/decorate created objects" do 77 | allow(@tester).to receive(:render_association).and_call_original 78 | expect(@tester).to receive(:render_association).with(anything(), anything(), kind_of(CommentDecorator), "f", anything(), anything()).and_return('partiallll') 79 | @tester.link_to_add_association('add something', @form_obj, :comments, :wrap_object => Proc.new {|comment| CommentDecorator.new(comment) }) 80 | end 81 | 82 | context "force non association create" do 83 | context "default case: create object on association" do 84 | before do 85 | expect(@tester).to receive(:create_object).with(anything, :comments , false) 86 | @html = @tester.link_to_add_association('add something', @form_obj, :comments) 87 | end 88 | 89 | it_behaves_like "a correctly rendered add link", {} 90 | end 91 | 92 | context "and explicitly specifying false is the same as default" do 93 | before do 94 | expect(@tester).to receive(:create_object).with(anything, :comments , false) 95 | @html = @tester.link_to_add_association('add something', @form_obj, :comments, :force_non_association_create => false) 96 | end 97 | it_behaves_like "a correctly rendered add link", {} 98 | end 99 | 100 | context "specifying true will not create objects on association but using the conditions" do 101 | before do 102 | expect(@tester).to receive(:create_object).with(anything, :comments , true) 103 | @html = @tester.link_to_add_association('add something', @form_obj, :comments, :force_non_association_create => true) 104 | end 105 | it_behaves_like "a correctly rendered add link", {} 106 | end 107 | end 108 | end 109 | 110 | context "with a block" do 111 | context "and the block specifies the link text" do 112 | before do 113 | @html = @tester.link_to_add_association(@form_obj, :comments) do 114 | "some long name" 115 | end 116 | end 117 | it_behaves_like "a correctly rendered add link", {text: 'some long name'} 118 | end 119 | 120 | context "accepts html options and pass them to link_to" do 121 | before do 122 | @html = @tester.link_to_add_association(@form_obj, :comments, {:class => 'floppy disk'}) do 123 | "some long name" 124 | end 125 | end 126 | it_behaves_like "a correctly rendered add link", {class: 'floppy disk add_fields', text: 'some long name'} 127 | end 128 | 129 | context "accepts extra attributes and pass them to link_to" do 130 | context 'when using the old notation' do 131 | before do 132 | @html = @tester.link_to_add_association(@form_obj, :comments, {:class => 'floppy disk', 'data-something' => 'bla'}) do 133 | "some long name" 134 | end 135 | end 136 | it_behaves_like "a correctly rendered add link", {class: 'floppy disk add_fields', text: 'some long name', :extra_attributes => {'data-something' => 'bla'}} 137 | end 138 | if Rails.rails4? 139 | context 'when using the new notation' do 140 | before do 141 | @html = @tester.link_to_add_association(@form_obj, :comments, {:class => 'floppy disk', :data => {:'association-something' => 'foobar'}}) do 142 | "some long name" 143 | end 144 | end 145 | it_behaves_like "a correctly rendered add link", {class: 'floppy disk add_fields', text: 'some long name', :extra_attributes => {'data-association-something' => 'foobar'}} 146 | end 147 | end 148 | end 149 | 150 | context "and explicitly specifying the wanted partial" do 151 | before do 152 | allow(@tester).to receive(:render_association).and_call_original 153 | expect(@tester).to receive(:render_association).with(anything(), anything(), anything(), "f", anything(), "shared/partial").and_return('partiallll') 154 | @html = @tester.link_to_add_association( @form_obj, :comments, :class => 'floppy disk', :partial => "shared/partial") do 155 | "some long name" 156 | end 157 | end 158 | 159 | it_behaves_like "a correctly rendered add link", {class: 'floppy disk add_fields', template: "partiallll", text: 'some long name'} 160 | end 161 | end 162 | 163 | context "with an irregular plural" do 164 | context "uses the correct plural" do 165 | before do 166 | @html = @tester.link_to_add_association('add something', @form_obj, :people) 167 | end 168 | it_behaves_like "a correctly rendered add link", {association: 'person', associations: 'people' } 169 | end 170 | end 171 | 172 | context "when using aliased association and class-name" do 173 | context "uses the correct name" do 174 | before do 175 | @html = @tester.link_to_add_association('add something', @form_obj, :admin_comments) 176 | end 177 | it_behaves_like "a correctly rendered add link", {association: 'admin_comment', associations: 'admin_comments'} 178 | end 179 | end 180 | 181 | it "tttt" do 182 | expect(@post.class.reflect_on_association(:people).klass.new).to be_a(Person) 183 | end 184 | 185 | context "with extra render-options for rendering the child relation" do 186 | context "uses the correct plural" do 187 | before do 188 | expect(@tester).to receive(:render_association).with(:people, @form_obj, anything, "f", {:wrapper => 'inline'}, nil) 189 | @html = @tester.link_to_add_association('add something', @form_obj, :people, :render_options => {:wrapper => 'inline'}) 190 | end 191 | it_behaves_like "a correctly rendered add link", {association: 'person', associations: 'people' } 192 | end 193 | end 194 | 195 | context "passing locals to the partial" do 196 | context "when given: passes the locals to the partials" do 197 | before do 198 | allow(@tester).to receive(:render_association).and_call_original 199 | expect(@form_obj).to receive(:fields_for) { | association, new_object, options_hash, &block| block.call } 200 | expect(@tester).to receive(:render).with("person_fields", {:f=>nil, :dynamic=>true, :alfred=>"Judoka"}).and_return ("partiallll") 201 | @render_options = {:wrapper => 'inline', :locals => {:alfred => 'Judoka'}} 202 | @html = @tester.link_to_add_association('add something', @form_obj, :people, :render_options => @render_options) 203 | end 204 | it_behaves_like "a correctly rendered add link", {template: 'partiallll', association: 'person', associations: 'people' } 205 | it "does not afffect render-options" do 206 | expect(@render_options[:locals]).to eq({alfred: 'Judoka'}) 207 | end 208 | end 209 | context "if no locals are given it still works" do 210 | before do 211 | allow(@tester).to receive(:render_association).and_call_original 212 | expect(@form_obj).to receive(:fields_for) { | association, new_object, options_hash, &block| block.call } 213 | expect(@tester).to receive(:render).with("person_fields", {:f=>nil, :dynamic=>true}).and_return ("partiallll") 214 | @html = @tester.link_to_add_association('add something', @form_obj, :people, :render_options => {:wrapper => 'inline'}) 215 | end 216 | it_behaves_like "a correctly rendered add link", {template: 'partiallll', association: 'person', associations: 'people' } 217 | 218 | #result.to_s.should == 'add something' 219 | end 220 | end 221 | 222 | context "overruling the form parameter name" do 223 | context "when given a form_name it passes it correctly to the partials" do 224 | before do 225 | allow(@tester).to receive(:render_association).and_call_original 226 | expect(@form_obj).to receive(:fields_for) { | association, new_object, options_hash, &block| block.call } 227 | expect(@tester).to receive(:render).with("person_fields", {:people_form => nil, :dynamic=>true}).and_return ("partiallll") 228 | @html = @tester.link_to_add_association('add something', @form_obj, :people, :form_name => 'people_form') 229 | end 230 | it_behaves_like "a correctly rendered add link", {template: 'partiallll', association: 'person', associations: 'people' } 231 | end 232 | end 233 | 234 | 235 | context "when using formtastic" do 236 | before(:each) do 237 | allow(@tester).to receive(:render_association).and_call_original 238 | allow(@form_obj).to receive(:semantic_fields_for).and_return('form') 239 | end 240 | context "calls semantic_fields_for and not fields_for" do 241 | before do 242 | allow(@form_obj).to receive_message_chain(:class, :ancestors) { ['Formtastic::FormBuilder'] } 243 | expect(@form_obj).to receive(:semantic_fields_for) 244 | expect(@form_obj).to receive(:fields_for).never 245 | @html = @tester.link_to_add_association('add something', @form_obj, :people) 246 | end 247 | it_behaves_like "a correctly rendered add link", {template: 'form', association: 'person', associations: 'people' } 248 | end 249 | end 250 | context "when using simple_form" do 251 | before(:each) do 252 | allow(@tester).to receive(:render_association).and_call_original 253 | allow(@form_obj).to receive(:simple_fields_for).and_return('form') 254 | end 255 | it "responds_to :simple_fields_for" do 256 | expect(@form_obj).to respond_to(:simple_fields_for) 257 | end 258 | context "calls simple_fields_for and not fields_for" do 259 | before do 260 | allow(@form_obj).to receive_message_chain(:class, :ancestors) { ['SimpleForm::FormBuilder'] } 261 | expect(@form_obj).to receive(:simple_fields_for) 262 | expect(@form_obj).to receive(:fields_for).never 263 | @html = @tester.link_to_add_association('add something', @form_obj, :people) 264 | end 265 | it_behaves_like "a correctly rendered add link", {template: 'form', association: 'person', associations: 'people' } 266 | end 267 | end 268 | 269 | context 'when adding a count' do 270 | before do 271 | @html = @tester.link_to_add_association('add something', @form_obj, :comments, { :count => 3 }) 272 | end 273 | it_behaves_like "a correctly rendered add link", { :extra_attributes => { 'data-count' => '3' } } 274 | end 275 | 276 | end 277 | 278 | context "link_to_remove_association" do 279 | before do 280 | @form_obj = @tester.send(:instantiate_builder, @post.class.name, @post, {}) 281 | end 282 | context "without a block" do 283 | context "accepts a name" do 284 | before do 285 | @html = @tester.link_to_remove_association('remove something', @form_obj) 286 | end 287 | 288 | it "is rendered inside a input element" do 289 | doc = Nokogiri::HTML(@html) 290 | removed = doc.at('input') 291 | expect(removed.attribute('id').value).to eq("Post__destroy") 292 | expect(removed.attribute('name').value).to eq("Post[_destroy]") 293 | expect(removed.attribute('value').value).to eq("false") 294 | end 295 | 296 | it_behaves_like "a correctly rendered remove link", {} 297 | end 298 | 299 | context 'no name given' do 300 | context 'custom translation exists' do 301 | before do 302 | I18n.backend.store_translations(:en, :cocoon => { :posts => { :remove => 'Remove post' } }) 303 | 304 | @html = @tester.link_to_remove_association(@form_obj) 305 | end 306 | 307 | it_behaves_like "a correctly rendered remove link", { text: 'Remove post' } 308 | end 309 | 310 | context 'uses default translation' do 311 | before do 312 | I18n.backend.store_translations(:en, :cocoon => { :defaults => { :remove => 'Remove' } }) 313 | 314 | @html = @tester.link_to_remove_association(@form_obj) 315 | end 316 | 317 | it_behaves_like "a correctly rendered remove link", { text: 'Remove' } 318 | end 319 | end 320 | 321 | context "accepts html options and pass them to link_to" do 322 | before do 323 | @html = @tester.link_to_remove_association('remove something', @form_obj, {:class => 'add_some_class', :'data-something' => 'bla'}) 324 | end 325 | it_behaves_like "a correctly rendered remove link", {class: 'add_some_class remove_fields dynamic', extra_attributes: {'data-something' => 'bla'}} 326 | end 327 | 328 | end 329 | 330 | # this is needed when due to some validation error, objects that 331 | # were already marked for destruction need to remain hidden 332 | context "for a object marked for destruction" do 333 | before do 334 | @post_marked_for_destruction = Post.new 335 | @post_marked_for_destruction.mark_for_destruction 336 | @form_obj_destroyed = @tester.send(:instantiate_builder, @post_marked_for_destruction.class.name, @post_marked_for_destruction, {}) 337 | @html = @tester.link_to_remove_association('remove something', @form_obj_destroyed) 338 | end 339 | 340 | it "is rendered inside a input element" do 341 | doc = Nokogiri::HTML(@html) 342 | removed = doc.at('input') 343 | expect(removed.attribute('id').value).to eq("Post__destroy") 344 | expect(removed.attribute('name').value).to eq("Post[_destroy]") 345 | expect(removed.attribute('value').value).to eq("true") 346 | end 347 | 348 | it_behaves_like "a correctly rendered remove link", {class: 'remove_fields dynamic destroyed'} 349 | end 350 | 351 | context "with a block" do 352 | context "the block gives the name" do 353 | before do 354 | @html = @tester.link_to_remove_association(@form_obj) do 355 | "remove some long name" 356 | end 357 | end 358 | it_behaves_like "a correctly rendered remove link", {text: 'remove some long name'} 359 | end 360 | 361 | context "accepts html options and pass them to link_to" do 362 | before do 363 | @html = @tester.link_to_remove_association(@form_obj, {:class => 'add_some_class', :'data-something' => 'bla'}) do 364 | "remove some long name" 365 | end 366 | end 367 | it_behaves_like "a correctly rendered remove link", {text: 'remove some long name', class: 'add_some_class remove_fields dynamic', extra_attributes: {'data-something' => 'bla'}} 368 | end 369 | end 370 | 371 | context 'when changing the wrapper class' do 372 | context 'should use the default nested-fields class' do 373 | before do 374 | @html = @tester.link_to_remove_association('remove something', @form_obj) 375 | end 376 | 377 | it_behaves_like "a correctly rendered remove link", { } 378 | end 379 | 380 | context 'should use the given wrapper class' do 381 | before do 382 | @html = @tester.link_to_remove_association('remove something', @form_obj, { wrapper_class: 'another-class' }) 383 | end 384 | 385 | it_behaves_like "a correctly rendered remove link", { extra_attributes: { 'data-wrapper-class' => 'another-class' } } 386 | end 387 | end 388 | end 389 | 390 | context "create_object" do 391 | it "creates correct association with conditions" do 392 | expect(@tester).not_to receive(:create_object_with_conditions) 393 | # in rails4 we cannot create an associated object when the object has not been saved before 394 | # I submitted a bug for this: https://github.com/rails/rails/issues/11376 395 | if Rails.rails4? 396 | @post = Post.create(title: 'Testing') 397 | end 398 | form_obj = double(:object => @post, :object_name => @post.class.name) 399 | result = @tester.create_object(form_obj, :admin_comments) 400 | expect(result.author).to eq("Admin") 401 | expect(form_obj.object.admin_comments).to be_empty 402 | end 403 | 404 | it "creates correct association for belongs_to associations" do 405 | comment = Comment.new 406 | form_obj = double(:object => Comment.new) 407 | result = @tester.create_object(form_obj, :post) 408 | expect(result).to be_a Post 409 | expect(comment.post).to be_nil 410 | end 411 | 412 | it "raises an error if cannot reflect on association" do 413 | expect { @tester.create_object(double(:object => Comment.new), :not_existing) }.to raise_error /association/i 414 | end 415 | 416 | it "creates an association if object responds to 'build_association' as singular" do 417 | object = Comment.new 418 | expect(object).to receive(:build_custom_item).and_return 'custom' 419 | expect(@tester.create_object(double(:object => object), :custom_item)).to eq('custom') 420 | end 421 | 422 | it "creates an association if object responds to 'build_association' as plural" do 423 | object = Comment.new 424 | expect(object).to receive(:build_custom_item).and_return 'custom' 425 | expect(@tester.create_object(double(:object => object), :custom_items)).to eq('custom') 426 | end 427 | 428 | it "can create using only conditions not the association" do 429 | expect(@tester).to receive(:create_object_with_conditions).and_return('flappie') 430 | form_obj = @tester.send(:instantiate_builder, @post.class.name, @post, {}) 431 | expect(@tester.create_object(form_obj, :comments, true)).to eq('flappie') 432 | end 433 | end 434 | 435 | context "get_partial_path" do 436 | it "generates the default partial name if no partial given" do 437 | result = @tester.get_partial_path(nil, :admin_comments) 438 | expect(result).to eq("admin_comment_fields") 439 | end 440 | it "uses the given partial name" do 441 | result = @tester.get_partial_path("comment_fields", :admin_comments) 442 | expect(result).to eq("comment_fields") 443 | end 444 | end 445 | 446 | end 447 | -------------------------------------------------------------------------------- /spec/dummy/Rakefile: -------------------------------------------------------------------------------- 1 | # Add your own tasks in files placed in lib/tasks ending in .rake, 2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 3 | 4 | require File.expand_path('../config/application', __FILE__) 5 | require 'rake' 6 | 7 | Dummy::Application.load_tasks 8 | -------------------------------------------------------------------------------- /spec/dummy/app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::Base 2 | protect_from_forgery 3 | end 4 | -------------------------------------------------------------------------------- /spec/dummy/app/decorators/comment_decorator.rb: -------------------------------------------------------------------------------- 1 | class CommentDecorator 2 | def initialize(comment) 3 | @comment = comment 4 | end 5 | 6 | def formatted_created_at 7 | @comment.created_at.to_formatted_s(:short) 8 | end 9 | 10 | def method_missing(method_sym, *args) 11 | if @comment.respond_to?(method_sym) 12 | @comment.send(method_sym, *args) 13 | else 14 | super 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /spec/dummy/app/helpers/application_helper.rb: -------------------------------------------------------------------------------- 1 | module ApplicationHelper 2 | end 3 | -------------------------------------------------------------------------------- /spec/dummy/app/models/comment.rb: -------------------------------------------------------------------------------- 1 | class Comment < ActiveRecord::Base 2 | belongs_to :post 3 | 4 | unless Rails.rails4? 5 | attr_protected :author 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /spec/dummy/app/models/person.rb: -------------------------------------------------------------------------------- 1 | class Person < ActiveRecord::Base 2 | belongs_to :post 3 | end 4 | -------------------------------------------------------------------------------- /spec/dummy/app/models/post.rb: -------------------------------------------------------------------------------- 1 | class Post < ActiveRecord::Base 2 | has_many :comments 3 | if Rails.rails4? 4 | has_many :admin_comments, -> { where author: "Admin" }, :class_name => "Comment" 5 | else 6 | has_many :admin_comments, :class_name => "Comment", :conditions => { :author => "Admin" } 7 | end 8 | has_many :people 9 | end 10 | -------------------------------------------------------------------------------- /spec/dummy/app/views/layouts/application.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Dummy 5 | <%= stylesheet_link_tag :all %> 6 | <%= javascript_include_tag :defaults %> 7 | <%= csrf_meta_tag %> 8 | 9 | 10 | 11 | <%= yield %> 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /spec/dummy/config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require ::File.expand_path('../config/environment', __FILE__) 4 | run Dummy::Application 5 | -------------------------------------------------------------------------------- /spec/dummy/config/application.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path('../boot', __FILE__) 2 | 3 | require "active_model/railtie" 4 | require "active_record/railtie" 5 | require "action_controller/railtie" 6 | require "action_view/railtie" 7 | require "action_mailer/railtie" 8 | 9 | Bundler.require 10 | require "cocoon" 11 | 12 | module Dummy 13 | class Application < Rails::Application 14 | # Settings in config/environments/* take precedence over those specified here. 15 | # Application configuration should go into files in config/initializers 16 | # -- all .rb files in that directory are automatically loaded. 17 | 18 | # Custom directories with classes and modules you want to be autoloadable. 19 | # config.autoload_paths += %W(#{config.root}/extras) 20 | 21 | # Only load the plugins named here, in the order given (default is alphabetical). 22 | # :all can be used as a placeholder for all plugins not explicitly named. 23 | # config.plugins = [ :exception_notification, :ssl_requirement, :all ] 24 | 25 | # Activate observers that should always be running. 26 | # config.active_record.observers = :cacher, :garbage_collector, :forum_observer 27 | 28 | # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. 29 | # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. 30 | # config.time_zone = 'Central Time (US & Canada)' 31 | 32 | # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. 33 | # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] 34 | # config.i18n.default_locale = :de 35 | 36 | # JavaScript files you want as :defaults (application.js is always included). 37 | # config.action_view.javascript_expansions[:defaults] = %w(jquery rails) 38 | 39 | # Configure the default encoding used in templates for Ruby 1.9. 40 | config.encoding = "utf-8" 41 | 42 | # Configure sensitive parameters which will be filtered from the log file. 43 | config.filter_parameters += [:password] 44 | end 45 | end 46 | -------------------------------------------------------------------------------- /spec/dummy/config/boot.rb: -------------------------------------------------------------------------------- 1 | require 'rubygems' 2 | gemfile = File.expand_path('../../../../Gemfile', __FILE__) 3 | 4 | if File.exist?(gemfile) 5 | ENV['BUNDLE_GEMFILE'] = gemfile 6 | require 'bundler' 7 | Bundler.setup 8 | end 9 | 10 | $:.unshift File.expand_path('../../../../lib', __FILE__) -------------------------------------------------------------------------------- /spec/dummy/config/database.yml: -------------------------------------------------------------------------------- 1 | # SQLite version 3.x 2 | # gem install sqlite3-ruby (not necessary on OS X Leopard) 3 | development: 4 | adapter: sqlite3 5 | database: db/development.sqlite3 6 | pool: 5 7 | timeout: 5000 8 | 9 | # Warning: The database defined as "test" will be erased and 10 | # re-generated from your development database when you run "rake". 11 | # Do not set this db to the same as development or production. 12 | test: 13 | adapter: sqlite3 14 | database: db/test.sqlite3 15 | pool: 5 16 | timeout: 5000 17 | 18 | production: 19 | adapter: sqlite3 20 | database: db/production.sqlite3 21 | pool: 5 22 | timeout: 5000 23 | -------------------------------------------------------------------------------- /spec/dummy/config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the rails application 2 | require File.expand_path('../application', __FILE__) 3 | 4 | # Initialize the rails application 5 | Dummy::Application.initialize! 6 | -------------------------------------------------------------------------------- /spec/dummy/config/environments/development.rb: -------------------------------------------------------------------------------- 1 | Dummy::Application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb 3 | 4 | # In the development environment your application's code is reloaded on 5 | # every request. This slows down response time but is perfect for development 6 | # since you don't have to restart the webserver when you make code changes. 7 | config.cache_classes = false 8 | 9 | config.eager_load = false 10 | 11 | # Show full error reports and disable caching 12 | config.consider_all_requests_local = true 13 | #config.action_view.debug_rjs = true 14 | config.action_controller.perform_caching = false 15 | 16 | # Don't care if the mailer can't send 17 | config.action_mailer.raise_delivery_errors = false 18 | 19 | # Print deprecation notices to the Rails logger 20 | config.active_support.deprecation = :log 21 | 22 | # Only use best-standards-support built into browsers 23 | config.action_dispatch.best_standards_support = :builtin 24 | end 25 | 26 | -------------------------------------------------------------------------------- /spec/dummy/config/environments/production.rb: -------------------------------------------------------------------------------- 1 | Dummy::Application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb 3 | 4 | # The production environment is meant for finished, "live" apps. 5 | # Code is not reloaded between requests 6 | config.cache_classes = true 7 | config.eager_load = true 8 | 9 | # Full error reports are disabled and caching is turned on 10 | config.consider_all_requests_local = false 11 | config.action_controller.perform_caching = true 12 | 13 | # Specifies the header that your server uses for sending files 14 | config.action_dispatch.x_sendfile_header = "X-Sendfile" 15 | 16 | # For nginx: 17 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' 18 | 19 | # If you have no front-end server that supports something like X-Sendfile, 20 | # just comment this out and Rails will serve the files 21 | 22 | # See everything in the log (default is :info) 23 | # config.log_level = :debug 24 | 25 | # Use a different logger for distributed setups 26 | # config.logger = SyslogLogger.new 27 | 28 | # Use a different cache store in production 29 | # config.cache_store = :mem_cache_store 30 | 31 | # Disable Rails's static asset server 32 | # In production, Apache or nginx will already do this 33 | config.serve_static_assets = false 34 | 35 | # Enable serving of images, stylesheets, and javascripts from an asset server 36 | # config.action_controller.asset_host = "http://assets.example.com" 37 | 38 | # Disable delivery errors, bad email addresses will be ignored 39 | # config.action_mailer.raise_delivery_errors = false 40 | 41 | # Enable threaded mode 42 | # config.threadsafe! 43 | 44 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 45 | # the I18n.default_locale when a translation can not be found) 46 | config.i18n.fallbacks = true 47 | 48 | # Send deprecation notices to registered listeners 49 | config.active_support.deprecation = :notify 50 | end 51 | -------------------------------------------------------------------------------- /spec/dummy/config/environments/test.rb: -------------------------------------------------------------------------------- 1 | Dummy::Application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb 3 | 4 | # The test environment is used exclusively to run your application's 5 | # test suite. You never need to work with it otherwise. Remember that 6 | # your test database is "scratch space" for the test suite and is wiped 7 | # and recreated between test runs. Don't rely on the data there! 8 | config.cache_classes = true 9 | config.eager_load = false 10 | 11 | # Show full error reports and disable caching 12 | config.consider_all_requests_local = true 13 | config.action_controller.perform_caching = false 14 | 15 | # Raise exceptions instead of rendering exception templates 16 | config.action_dispatch.show_exceptions = false 17 | 18 | # Disable request forgery protection in test environment 19 | config.action_controller.allow_forgery_protection = false 20 | 21 | # Tell Action Mailer not to deliver emails to the real world. 22 | # The :test delivery method accumulates sent emails in the 23 | # ActionMailer::Base.deliveries array. 24 | config.action_mailer.delivery_method = :test 25 | 26 | # Use SQL instead of Active Record's schema dumper when creating the test database. 27 | # This is necessary if your schema can't be completely dumped by the schema dumper, 28 | # like if you have constraints or database-specific column types 29 | # config.active_record.schema_format = :sql 30 | 31 | # Print deprecation notices to the stderr 32 | config.active_support.deprecation = :stderr 33 | end 34 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 4 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } 5 | 6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. 7 | # Rails.backtrace_cleaner.remove_silencers! 8 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new inflection rules using the following format 4 | # (all these examples are active by default): 5 | # ActiveSupport::Inflector.inflections do |inflect| 6 | # inflect.plural /^(ox)$/i, '\1en' 7 | # inflect.singular /^(ox)en/i, '\1' 8 | # inflect.irregular 'person', 'people' 9 | # inflect.uncountable %w( fish sheep ) 10 | # end 11 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/mime_types.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new mime types for use in respond_to blocks: 4 | # Mime::Type.register "text/richtext", :rtf 5 | # Mime::Type.register_alias "text/html", :iphone 6 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/rails_version_helper.rb: -------------------------------------------------------------------------------- 1 | module Rails 2 | 3 | def self.rails4? 4 | Rails.version.start_with? '4' 5 | end 6 | end -------------------------------------------------------------------------------- /spec/dummy/config/initializers/secret_token.rb: -------------------------------------------------------------------------------- 1 | config = Rails.application.config 2 | 3 | if Rails.rails4? 4 | config.secret_key_base = '58698a8f83e3ccc8e503d18280e17a23008a8f08a6813472dca7873ad0b497428dc00f62ee2225f94bce0d8e04c4befa922e4372772a2e1de89cebaa98a18c0a' 5 | else 6 | config.secret_token = '58698a8f83e3ccc8e503d18280e17a23008a8f08a6813472dca7873ad0b497428dc00f62ee2225f94bce0d8e04c4befa922e4372772a2e1de89cebaa98a18c0a' 7 | config.session_store :cookie_store, :key => "dummy" 8 | end -------------------------------------------------------------------------------- /spec/dummy/config/initializers/session_store.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | Dummy::Application.config.session_store :cookie_store, :key => '_dummy_session' 4 | 5 | # Use the database for sessions instead of the cookie-based default, 6 | # which shouldn't be used to store highly confidential information 7 | # (create the session table with "rails generate session_migration") 8 | # Dummy::Application.config.session_store :active_record_store 9 | -------------------------------------------------------------------------------- /spec/dummy/config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # Sample localization file for English. Add more files in this directory for other locales. 2 | # See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points. 3 | 4 | en: 5 | hello: "Hello world" 6 | -------------------------------------------------------------------------------- /spec/dummy/config/routes.rb: -------------------------------------------------------------------------------- 1 | Dummy::Application.routes.draw do 2 | # The priority is based upon order of creation: 3 | # first created -> highest priority. 4 | 5 | # Sample of regular route: 6 | # match 'products/:id' => 'catalog#view' 7 | # Keep in mind you can assign values other than :controller and :action 8 | 9 | # Sample of named route: 10 | # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase 11 | # This route can be invoked with purchase_url(:id => product.id) 12 | 13 | # Sample resource route (maps HTTP verbs to controller actions automatically): 14 | # resources :products 15 | 16 | # Sample resource route with options: 17 | # resources :products do 18 | # member do 19 | # get 'short' 20 | # post 'toggle' 21 | # end 22 | # 23 | # collection do 24 | # get 'sold' 25 | # end 26 | # end 27 | 28 | # Sample resource route with sub-resources: 29 | # resources :products do 30 | # resources :comments, :sales 31 | # resource :seller 32 | # end 33 | 34 | # Sample resource route with more complex sub-resources 35 | # resources :products do 36 | # resources :comments 37 | # resources :sales do 38 | # get 'recent', :on => :collection 39 | # end 40 | # end 41 | 42 | # Sample resource route within a namespace: 43 | # namespace :admin do 44 | # # Directs /admin/products/* to Admin::ProductsController 45 | # # (app/controllers/admin/products_controller.rb) 46 | # resources :products 47 | # end 48 | 49 | # You can have the root of your site routed with "root" 50 | # just remember to delete public/index.html. 51 | # root :to => "welcome#index" 52 | 53 | # See how all your routes lay out with "rake routes" 54 | 55 | # This is a legacy wild controller route that's not recommended for RESTful applications. 56 | # Note: This route will make all actions in every controller accessible via GET requests. 57 | # match ':controller(/:action(/:id(.:format)))' 58 | end 59 | -------------------------------------------------------------------------------- /spec/dummy/db/migrate/20110306212208_create_posts.rb: -------------------------------------------------------------------------------- 1 | class CreatePosts < ActiveRecord::Migration 2 | def self.up 3 | create_table :posts do |t| 4 | t.string :title 5 | t.text :body 6 | 7 | t.timestamps null: false 8 | end 9 | end 10 | 11 | def self.down 12 | drop_table :posts 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /spec/dummy/db/migrate/20110306212250_create_comments.rb: -------------------------------------------------------------------------------- 1 | class CreateComments < ActiveRecord::Migration 2 | def self.up 3 | create_table :comments do |t| 4 | t.text :body 5 | t.string :author 6 | t.integer :post_id 7 | 8 | t.timestamps null: false 9 | end 10 | end 11 | 12 | def self.down 13 | drop_table :comments 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /spec/dummy/db/migrate/20110420222224_create_people.rb: -------------------------------------------------------------------------------- 1 | class CreatePeople < ActiveRecord::Migration 2 | def self.up 3 | create_table :people do |t| 4 | t.string :name 5 | t.string :description 6 | t.integer :post_id 7 | 8 | t.timestamps null: false 9 | end 10 | end 11 | 12 | def self.down 13 | drop_table :people 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /spec/dummy/db/schema.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # This file is auto-generated from the current state of the database. Instead 3 | # of editing this file, please use the migrations feature of Active Record to 4 | # incrementally modify your database, and then regenerate this schema definition. 5 | # 6 | # Note that this schema.rb definition is the authoritative source for your 7 | # database schema. If you need to create the application database on another 8 | # system, you should be using db:schema:load, not running all the migrations 9 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations 10 | # you'll amass, the slower it'll run and the greater likelihood for issues). 11 | # 12 | # It's strongly recommended that you check this file into your version control system. 13 | 14 | ActiveRecord::Schema.define(version: 20110420222224) do 15 | 16 | create_table "comments", force: :cascade do |t| 17 | t.text "body" 18 | t.string "author" 19 | t.integer "post_id" 20 | t.datetime "created_at", null: false 21 | t.datetime "updated_at", null: false 22 | end 23 | 24 | create_table "people", force: :cascade do |t| 25 | t.string "name" 26 | t.string "description" 27 | t.integer "post_id" 28 | t.datetime "created_at", null: false 29 | t.datetime "updated_at", null: false 30 | end 31 | 32 | create_table "posts", force: :cascade do |t| 33 | t.string "title" 34 | t.text "body" 35 | t.datetime "created_at", null: false 36 | t.datetime "updated_at", null: false 37 | end 38 | 39 | end 40 | -------------------------------------------------------------------------------- /spec/dummy/public/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The page you were looking for doesn't exist (404) 5 | 17 | 18 | 19 | 20 | 21 |
22 |

The page you were looking for doesn't exist.

23 |

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

24 |
25 | 26 | 27 | -------------------------------------------------------------------------------- /spec/dummy/public/422.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The change you wanted was rejected (422) 5 | 17 | 18 | 19 | 20 | 21 |
22 |

The change you wanted was rejected.

23 |

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

24 |
25 | 26 | 27 | -------------------------------------------------------------------------------- /spec/dummy/public/500.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | We're sorry, but something went wrong (500) 5 | 17 | 18 | 19 | 20 | 21 |
22 |

We're sorry, but something went wrong.

23 |

We've been notified about this issue and we'll take a look at it shortly.

24 |
25 | 26 | 27 | -------------------------------------------------------------------------------- /spec/dummy/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nathanvda/cocoon/b3f4e6d1920937063cba2a4472dc4508bbac00f3/spec/dummy/public/favicon.ico -------------------------------------------------------------------------------- /spec/dummy/public/javascripts/application.js: -------------------------------------------------------------------------------- 1 | // Place your application-specific JavaScript functions and classes here 2 | // This file is automatically included by javascript_include_tag :defaults 3 | -------------------------------------------------------------------------------- /spec/dummy/public/javascripts/controls.js: -------------------------------------------------------------------------------- 1 | // script.aculo.us controls.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009 2 | 3 | // Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) 4 | // (c) 2005-2009 Ivan Krstic (http://blogs.law.harvard.edu/ivan) 5 | // (c) 2005-2009 Jon Tirsen (http://www.tirsen.com) 6 | // Contributors: 7 | // Richard Livsey 8 | // Rahul Bhargava 9 | // Rob Wills 10 | // 11 | // script.aculo.us is freely distributable under the terms of an MIT-style license. 12 | // For details, see the script.aculo.us web site: http://script.aculo.us/ 13 | 14 | // Autocompleter.Base handles all the autocompletion functionality 15 | // that's independent of the data source for autocompletion. This 16 | // includes drawing the autocompletion menu, observing keyboard 17 | // and mouse events, and similar. 18 | // 19 | // Specific autocompleters need to provide, at the very least, 20 | // a getUpdatedChoices function that will be invoked every time 21 | // the text inside the monitored textbox changes. This method 22 | // should get the text for which to provide autocompletion by 23 | // invoking this.getToken(), NOT by directly accessing 24 | // this.element.value. This is to allow incremental tokenized 25 | // autocompletion. Specific auto-completion logic (AJAX, etc) 26 | // belongs in getUpdatedChoices. 27 | // 28 | // Tokenized incremental autocompletion is enabled automatically 29 | // when an autocompleter is instantiated with the 'tokens' option 30 | // in the options parameter, e.g.: 31 | // new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' }); 32 | // will incrementally autocomplete with a comma as the token. 33 | // Additionally, ',' in the above example can be replaced with 34 | // a token array, e.g. { tokens: [',', '\n'] } which 35 | // enables autocompletion on multiple tokens. This is most 36 | // useful when one of the tokens is \n (a newline), as it 37 | // allows smart autocompletion after linebreaks. 38 | 39 | if(typeof Effect == 'undefined') 40 | throw("controls.js requires including script.aculo.us' effects.js library"); 41 | 42 | var Autocompleter = { }; 43 | Autocompleter.Base = Class.create({ 44 | baseInitialize: function(element, update, options) { 45 | element = $(element); 46 | this.element = element; 47 | this.update = $(update); 48 | this.hasFocus = false; 49 | this.changed = false; 50 | this.active = false; 51 | this.index = 0; 52 | this.entryCount = 0; 53 | this.oldElementValue = this.element.value; 54 | 55 | if(this.setOptions) 56 | this.setOptions(options); 57 | else 58 | this.options = options || { }; 59 | 60 | this.options.paramName = this.options.paramName || this.element.name; 61 | this.options.tokens = this.options.tokens || []; 62 | this.options.frequency = this.options.frequency || 0.4; 63 | this.options.minChars = this.options.minChars || 1; 64 | this.options.onShow = this.options.onShow || 65 | function(element, update){ 66 | if(!update.style.position || update.style.position=='absolute') { 67 | update.style.position = 'absolute'; 68 | Position.clone(element, update, { 69 | setHeight: false, 70 | offsetTop: element.offsetHeight 71 | }); 72 | } 73 | Effect.Appear(update,{duration:0.15}); 74 | }; 75 | this.options.onHide = this.options.onHide || 76 | function(element, update){ new Effect.Fade(update,{duration:0.15}) }; 77 | 78 | if(typeof(this.options.tokens) == 'string') 79 | this.options.tokens = new Array(this.options.tokens); 80 | // Force carriage returns as token delimiters anyway 81 | if (!this.options.tokens.include('\n')) 82 | this.options.tokens.push('\n'); 83 | 84 | this.observer = null; 85 | 86 | this.element.setAttribute('autocomplete','off'); 87 | 88 | Element.hide(this.update); 89 | 90 | Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this)); 91 | Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this)); 92 | }, 93 | 94 | show: function() { 95 | if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update); 96 | if(!this.iefix && 97 | (Prototype.Browser.IE) && 98 | (Element.getStyle(this.update, 'position')=='absolute')) { 99 | new Insertion.After(this.update, 100 | ''); 103 | this.iefix = $(this.update.id+'_iefix'); 104 | } 105 | if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50); 106 | }, 107 | 108 | fixIEOverlapping: function() { 109 | Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)}); 110 | this.iefix.style.zIndex = 1; 111 | this.update.style.zIndex = 2; 112 | Element.show(this.iefix); 113 | }, 114 | 115 | hide: function() { 116 | this.stopIndicator(); 117 | if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update); 118 | if(this.iefix) Element.hide(this.iefix); 119 | }, 120 | 121 | startIndicator: function() { 122 | if(this.options.indicator) Element.show(this.options.indicator); 123 | }, 124 | 125 | stopIndicator: function() { 126 | if(this.options.indicator) Element.hide(this.options.indicator); 127 | }, 128 | 129 | onKeyPress: function(event) { 130 | if(this.active) 131 | switch(event.keyCode) { 132 | case Event.KEY_TAB: 133 | case Event.KEY_RETURN: 134 | this.selectEntry(); 135 | Event.stop(event); 136 | case Event.KEY_ESC: 137 | this.hide(); 138 | this.active = false; 139 | Event.stop(event); 140 | return; 141 | case Event.KEY_LEFT: 142 | case Event.KEY_RIGHT: 143 | return; 144 | case Event.KEY_UP: 145 | this.markPrevious(); 146 | this.render(); 147 | Event.stop(event); 148 | return; 149 | case Event.KEY_DOWN: 150 | this.markNext(); 151 | this.render(); 152 | Event.stop(event); 153 | return; 154 | } 155 | else 156 | if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN || 157 | (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return; 158 | 159 | this.changed = true; 160 | this.hasFocus = true; 161 | 162 | if(this.observer) clearTimeout(this.observer); 163 | this.observer = 164 | setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000); 165 | }, 166 | 167 | activate: function() { 168 | this.changed = false; 169 | this.hasFocus = true; 170 | this.getUpdatedChoices(); 171 | }, 172 | 173 | onHover: function(event) { 174 | var element = Event.findElement(event, 'LI'); 175 | if(this.index != element.autocompleteIndex) 176 | { 177 | this.index = element.autocompleteIndex; 178 | this.render(); 179 | } 180 | Event.stop(event); 181 | }, 182 | 183 | onClick: function(event) { 184 | var element = Event.findElement(event, 'LI'); 185 | this.index = element.autocompleteIndex; 186 | this.selectEntry(); 187 | this.hide(); 188 | }, 189 | 190 | onBlur: function(event) { 191 | // needed to make click events working 192 | setTimeout(this.hide.bind(this), 250); 193 | this.hasFocus = false; 194 | this.active = false; 195 | }, 196 | 197 | render: function() { 198 | if(this.entryCount > 0) { 199 | for (var i = 0; i < this.entryCount; i++) 200 | this.index==i ? 201 | Element.addClassName(this.getEntry(i),"selected") : 202 | Element.removeClassName(this.getEntry(i),"selected"); 203 | if(this.hasFocus) { 204 | this.show(); 205 | this.active = true; 206 | } 207 | } else { 208 | this.active = false; 209 | this.hide(); 210 | } 211 | }, 212 | 213 | markPrevious: function() { 214 | if(this.index > 0) this.index--; 215 | else this.index = this.entryCount-1; 216 | this.getEntry(this.index).scrollIntoView(true); 217 | }, 218 | 219 | markNext: function() { 220 | if(this.index < this.entryCount-1) this.index++; 221 | else this.index = 0; 222 | this.getEntry(this.index).scrollIntoView(false); 223 | }, 224 | 225 | getEntry: function(index) { 226 | return this.update.firstChild.childNodes[index]; 227 | }, 228 | 229 | getCurrentEntry: function() { 230 | return this.getEntry(this.index); 231 | }, 232 | 233 | selectEntry: function() { 234 | this.active = false; 235 | this.updateElement(this.getCurrentEntry()); 236 | }, 237 | 238 | updateElement: function(selectedElement) { 239 | if (this.options.updateElement) { 240 | this.options.updateElement(selectedElement); 241 | return; 242 | } 243 | var value = ''; 244 | if (this.options.select) { 245 | var nodes = $(selectedElement).select('.' + this.options.select) || []; 246 | if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select); 247 | } else 248 | value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal'); 249 | 250 | var bounds = this.getTokenBounds(); 251 | if (bounds[0] != -1) { 252 | var newValue = this.element.value.substr(0, bounds[0]); 253 | var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/); 254 | if (whitespace) 255 | newValue += whitespace[0]; 256 | this.element.value = newValue + value + this.element.value.substr(bounds[1]); 257 | } else { 258 | this.element.value = value; 259 | } 260 | this.oldElementValue = this.element.value; 261 | this.element.focus(); 262 | 263 | if (this.options.afterUpdateElement) 264 | this.options.afterUpdateElement(this.element, selectedElement); 265 | }, 266 | 267 | updateChoices: function(choices) { 268 | if(!this.changed && this.hasFocus) { 269 | this.update.innerHTML = choices; 270 | Element.cleanWhitespace(this.update); 271 | Element.cleanWhitespace(this.update.down()); 272 | 273 | if(this.update.firstChild && this.update.down().childNodes) { 274 | this.entryCount = 275 | this.update.down().childNodes.length; 276 | for (var i = 0; i < this.entryCount; i++) { 277 | var entry = this.getEntry(i); 278 | entry.autocompleteIndex = i; 279 | this.addObservers(entry); 280 | } 281 | } else { 282 | this.entryCount = 0; 283 | } 284 | 285 | this.stopIndicator(); 286 | this.index = 0; 287 | 288 | if(this.entryCount==1 && this.options.autoSelect) { 289 | this.selectEntry(); 290 | this.hide(); 291 | } else { 292 | this.render(); 293 | } 294 | } 295 | }, 296 | 297 | addObservers: function(element) { 298 | Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this)); 299 | Event.observe(element, "click", this.onClick.bindAsEventListener(this)); 300 | }, 301 | 302 | onObserverEvent: function() { 303 | this.changed = false; 304 | this.tokenBounds = null; 305 | if(this.getToken().length>=this.options.minChars) { 306 | this.getUpdatedChoices(); 307 | } else { 308 | this.active = false; 309 | this.hide(); 310 | } 311 | this.oldElementValue = this.element.value; 312 | }, 313 | 314 | getToken: function() { 315 | var bounds = this.getTokenBounds(); 316 | return this.element.value.substring(bounds[0], bounds[1]).strip(); 317 | }, 318 | 319 | getTokenBounds: function() { 320 | if (null != this.tokenBounds) return this.tokenBounds; 321 | var value = this.element.value; 322 | if (value.strip().empty()) return [-1, 0]; 323 | var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue); 324 | var offset = (diff == this.oldElementValue.length ? 1 : 0); 325 | var prevTokenPos = -1, nextTokenPos = value.length; 326 | var tp; 327 | for (var index = 0, l = this.options.tokens.length; index < l; ++index) { 328 | tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1); 329 | if (tp > prevTokenPos) prevTokenPos = tp; 330 | tp = value.indexOf(this.options.tokens[index], diff + offset); 331 | if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp; 332 | } 333 | return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]); 334 | } 335 | }); 336 | 337 | Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) { 338 | var boundary = Math.min(newS.length, oldS.length); 339 | for (var index = 0; index < boundary; ++index) 340 | if (newS[index] != oldS[index]) 341 | return index; 342 | return boundary; 343 | }; 344 | 345 | Ajax.Autocompleter = Class.create(Autocompleter.Base, { 346 | initialize: function(element, update, url, options) { 347 | this.baseInitialize(element, update, options); 348 | this.options.asynchronous = true; 349 | this.options.onComplete = this.onComplete.bind(this); 350 | this.options.defaultParams = this.options.parameters || null; 351 | this.url = url; 352 | }, 353 | 354 | getUpdatedChoices: function() { 355 | this.startIndicator(); 356 | 357 | var entry = encodeURIComponent(this.options.paramName) + '=' + 358 | encodeURIComponent(this.getToken()); 359 | 360 | this.options.parameters = this.options.callback ? 361 | this.options.callback(this.element, entry) : entry; 362 | 363 | if(this.options.defaultParams) 364 | this.options.parameters += '&' + this.options.defaultParams; 365 | 366 | new Ajax.Request(this.url, this.options); 367 | }, 368 | 369 | onComplete: function(request) { 370 | this.updateChoices(request.responseText); 371 | } 372 | }); 373 | 374 | // The local array autocompleter. Used when you'd prefer to 375 | // inject an array of autocompletion options into the page, rather 376 | // than sending out Ajax queries, which can be quite slow sometimes. 377 | // 378 | // The constructor takes four parameters. The first two are, as usual, 379 | // the id of the monitored textbox, and id of the autocompletion menu. 380 | // The third is the array you want to autocomplete from, and the fourth 381 | // is the options block. 382 | // 383 | // Extra local autocompletion options: 384 | // - choices - How many autocompletion choices to offer 385 | // 386 | // - partialSearch - If false, the autocompleter will match entered 387 | // text only at the beginning of strings in the 388 | // autocomplete array. Defaults to true, which will 389 | // match text at the beginning of any *word* in the 390 | // strings in the autocomplete array. If you want to 391 | // search anywhere in the string, additionally set 392 | // the option fullSearch to true (default: off). 393 | // 394 | // - fullSsearch - Search anywhere in autocomplete array strings. 395 | // 396 | // - partialChars - How many characters to enter before triggering 397 | // a partial match (unlike minChars, which defines 398 | // how many characters are required to do any match 399 | // at all). Defaults to 2. 400 | // 401 | // - ignoreCase - Whether to ignore case when autocompleting. 402 | // Defaults to true. 403 | // 404 | // It's possible to pass in a custom function as the 'selector' 405 | // option, if you prefer to write your own autocompletion logic. 406 | // In that case, the other options above will not apply unless 407 | // you support them. 408 | 409 | Autocompleter.Local = Class.create(Autocompleter.Base, { 410 | initialize: function(element, update, array, options) { 411 | this.baseInitialize(element, update, options); 412 | this.options.array = array; 413 | }, 414 | 415 | getUpdatedChoices: function() { 416 | this.updateChoices(this.options.selector(this)); 417 | }, 418 | 419 | setOptions: function(options) { 420 | this.options = Object.extend({ 421 | choices: 10, 422 | partialSearch: true, 423 | partialChars: 2, 424 | ignoreCase: true, 425 | fullSearch: false, 426 | selector: function(instance) { 427 | var ret = []; // Beginning matches 428 | var partial = []; // Inside matches 429 | var entry = instance.getToken(); 430 | var count = 0; 431 | 432 | for (var i = 0; i < instance.options.array.length && 433 | ret.length < instance.options.choices ; i++) { 434 | 435 | var elem = instance.options.array[i]; 436 | var foundPos = instance.options.ignoreCase ? 437 | elem.toLowerCase().indexOf(entry.toLowerCase()) : 438 | elem.indexOf(entry); 439 | 440 | while (foundPos != -1) { 441 | if (foundPos == 0 && elem.length != entry.length) { 442 | ret.push("
  • " + elem.substr(0, entry.length) + "" + 443 | elem.substr(entry.length) + "
  • "); 444 | break; 445 | } else if (entry.length >= instance.options.partialChars && 446 | instance.options.partialSearch && foundPos != -1) { 447 | if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) { 448 | partial.push("
  • " + elem.substr(0, foundPos) + "" + 449 | elem.substr(foundPos, entry.length) + "" + elem.substr( 450 | foundPos + entry.length) + "
  • "); 451 | break; 452 | } 453 | } 454 | 455 | foundPos = instance.options.ignoreCase ? 456 | elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) : 457 | elem.indexOf(entry, foundPos + 1); 458 | 459 | } 460 | } 461 | if (partial.length) 462 | ret = ret.concat(partial.slice(0, instance.options.choices - ret.length)); 463 | return "
      " + ret.join('') + "
    "; 464 | } 465 | }, options || { }); 466 | } 467 | }); 468 | 469 | // AJAX in-place editor and collection editor 470 | // Full rewrite by Christophe Porteneuve (April 2007). 471 | 472 | // Use this if you notice weird scrolling problems on some browsers, 473 | // the DOM might be a bit confused when this gets called so do this 474 | // waits 1 ms (with setTimeout) until it does the activation 475 | Field.scrollFreeActivate = function(field) { 476 | setTimeout(function() { 477 | Field.activate(field); 478 | }, 1); 479 | }; 480 | 481 | Ajax.InPlaceEditor = Class.create({ 482 | initialize: function(element, url, options) { 483 | this.url = url; 484 | this.element = element = $(element); 485 | this.prepareOptions(); 486 | this._controls = { }; 487 | arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!! 488 | Object.extend(this.options, options || { }); 489 | if (!this.options.formId && this.element.id) { 490 | this.options.formId = this.element.id + '-inplaceeditor'; 491 | if ($(this.options.formId)) 492 | this.options.formId = ''; 493 | } 494 | if (this.options.externalControl) 495 | this.options.externalControl = $(this.options.externalControl); 496 | if (!this.options.externalControl) 497 | this.options.externalControlOnly = false; 498 | this._originalBackground = this.element.getStyle('background-color') || 'transparent'; 499 | this.element.title = this.options.clickToEditText; 500 | this._boundCancelHandler = this.handleFormCancellation.bind(this); 501 | this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this); 502 | this._boundFailureHandler = this.handleAJAXFailure.bind(this); 503 | this._boundSubmitHandler = this.handleFormSubmission.bind(this); 504 | this._boundWrapperHandler = this.wrapUp.bind(this); 505 | this.registerListeners(); 506 | }, 507 | checkForEscapeOrReturn: function(e) { 508 | if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return; 509 | if (Event.KEY_ESC == e.keyCode) 510 | this.handleFormCancellation(e); 511 | else if (Event.KEY_RETURN == e.keyCode) 512 | this.handleFormSubmission(e); 513 | }, 514 | createControl: function(mode, handler, extraClasses) { 515 | var control = this.options[mode + 'Control']; 516 | var text = this.options[mode + 'Text']; 517 | if ('button' == control) { 518 | var btn = document.createElement('input'); 519 | btn.type = 'submit'; 520 | btn.value = text; 521 | btn.className = 'editor_' + mode + '_button'; 522 | if ('cancel' == mode) 523 | btn.onclick = this._boundCancelHandler; 524 | this._form.appendChild(btn); 525 | this._controls[mode] = btn; 526 | } else if ('link' == control) { 527 | var link = document.createElement('a'); 528 | link.href = '#'; 529 | link.appendChild(document.createTextNode(text)); 530 | link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler; 531 | link.className = 'editor_' + mode + '_link'; 532 | if (extraClasses) 533 | link.className += ' ' + extraClasses; 534 | this._form.appendChild(link); 535 | this._controls[mode] = link; 536 | } 537 | }, 538 | createEditField: function() { 539 | var text = (this.options.loadTextURL ? this.options.loadingText : this.getText()); 540 | var fld; 541 | if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) { 542 | fld = document.createElement('input'); 543 | fld.type = 'text'; 544 | var size = this.options.size || this.options.cols || 0; 545 | if (0 < size) fld.size = size; 546 | } else { 547 | fld = document.createElement('textarea'); 548 | fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows); 549 | fld.cols = this.options.cols || 40; 550 | } 551 | fld.name = this.options.paramName; 552 | fld.value = text; // No HTML breaks conversion anymore 553 | fld.className = 'editor_field'; 554 | if (this.options.submitOnBlur) 555 | fld.onblur = this._boundSubmitHandler; 556 | this._controls.editor = fld; 557 | if (this.options.loadTextURL) 558 | this.loadExternalText(); 559 | this._form.appendChild(this._controls.editor); 560 | }, 561 | createForm: function() { 562 | var ipe = this; 563 | function addText(mode, condition) { 564 | var text = ipe.options['text' + mode + 'Controls']; 565 | if (!text || condition === false) return; 566 | ipe._form.appendChild(document.createTextNode(text)); 567 | }; 568 | this._form = $(document.createElement('form')); 569 | this._form.id = this.options.formId; 570 | this._form.addClassName(this.options.formClassName); 571 | this._form.onsubmit = this._boundSubmitHandler; 572 | this.createEditField(); 573 | if ('textarea' == this._controls.editor.tagName.toLowerCase()) 574 | this._form.appendChild(document.createElement('br')); 575 | if (this.options.onFormCustomization) 576 | this.options.onFormCustomization(this, this._form); 577 | addText('Before', this.options.okControl || this.options.cancelControl); 578 | this.createControl('ok', this._boundSubmitHandler); 579 | addText('Between', this.options.okControl && this.options.cancelControl); 580 | this.createControl('cancel', this._boundCancelHandler, 'editor_cancel'); 581 | addText('After', this.options.okControl || this.options.cancelControl); 582 | }, 583 | destroy: function() { 584 | if (this._oldInnerHTML) 585 | this.element.innerHTML = this._oldInnerHTML; 586 | this.leaveEditMode(); 587 | this.unregisterListeners(); 588 | }, 589 | enterEditMode: function(e) { 590 | if (this._saving || this._editing) return; 591 | this._editing = true; 592 | this.triggerCallback('onEnterEditMode'); 593 | if (this.options.externalControl) 594 | this.options.externalControl.hide(); 595 | this.element.hide(); 596 | this.createForm(); 597 | this.element.parentNode.insertBefore(this._form, this.element); 598 | if (!this.options.loadTextURL) 599 | this.postProcessEditField(); 600 | if (e) Event.stop(e); 601 | }, 602 | enterHover: function(e) { 603 | if (this.options.hoverClassName) 604 | this.element.addClassName(this.options.hoverClassName); 605 | if (this._saving) return; 606 | this.triggerCallback('onEnterHover'); 607 | }, 608 | getText: function() { 609 | return this.element.innerHTML.unescapeHTML(); 610 | }, 611 | handleAJAXFailure: function(transport) { 612 | this.triggerCallback('onFailure', transport); 613 | if (this._oldInnerHTML) { 614 | this.element.innerHTML = this._oldInnerHTML; 615 | this._oldInnerHTML = null; 616 | } 617 | }, 618 | handleFormCancellation: function(e) { 619 | this.wrapUp(); 620 | if (e) Event.stop(e); 621 | }, 622 | handleFormSubmission: function(e) { 623 | var form = this._form; 624 | var value = $F(this._controls.editor); 625 | this.prepareSubmission(); 626 | var params = this.options.callback(form, value) || ''; 627 | if (Object.isString(params)) 628 | params = params.toQueryParams(); 629 | params.editorId = this.element.id; 630 | if (this.options.htmlResponse) { 631 | var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions); 632 | Object.extend(options, { 633 | parameters: params, 634 | onComplete: this._boundWrapperHandler, 635 | onFailure: this._boundFailureHandler 636 | }); 637 | new Ajax.Updater({ success: this.element }, this.url, options); 638 | } else { 639 | var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); 640 | Object.extend(options, { 641 | parameters: params, 642 | onComplete: this._boundWrapperHandler, 643 | onFailure: this._boundFailureHandler 644 | }); 645 | new Ajax.Request(this.url, options); 646 | } 647 | if (e) Event.stop(e); 648 | }, 649 | leaveEditMode: function() { 650 | this.element.removeClassName(this.options.savingClassName); 651 | this.removeForm(); 652 | this.leaveHover(); 653 | this.element.style.backgroundColor = this._originalBackground; 654 | this.element.show(); 655 | if (this.options.externalControl) 656 | this.options.externalControl.show(); 657 | this._saving = false; 658 | this._editing = false; 659 | this._oldInnerHTML = null; 660 | this.triggerCallback('onLeaveEditMode'); 661 | }, 662 | leaveHover: function(e) { 663 | if (this.options.hoverClassName) 664 | this.element.removeClassName(this.options.hoverClassName); 665 | if (this._saving) return; 666 | this.triggerCallback('onLeaveHover'); 667 | }, 668 | loadExternalText: function() { 669 | this._form.addClassName(this.options.loadingClassName); 670 | this._controls.editor.disabled = true; 671 | var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); 672 | Object.extend(options, { 673 | parameters: 'editorId=' + encodeURIComponent(this.element.id), 674 | onComplete: Prototype.emptyFunction, 675 | onSuccess: function(transport) { 676 | this._form.removeClassName(this.options.loadingClassName); 677 | var text = transport.responseText; 678 | if (this.options.stripLoadedTextTags) 679 | text = text.stripTags(); 680 | this._controls.editor.value = text; 681 | this._controls.editor.disabled = false; 682 | this.postProcessEditField(); 683 | }.bind(this), 684 | onFailure: this._boundFailureHandler 685 | }); 686 | new Ajax.Request(this.options.loadTextURL, options); 687 | }, 688 | postProcessEditField: function() { 689 | var fpc = this.options.fieldPostCreation; 690 | if (fpc) 691 | $(this._controls.editor)['focus' == fpc ? 'focus' : 'activate'](); 692 | }, 693 | prepareOptions: function() { 694 | this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions); 695 | Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks); 696 | [this._extraDefaultOptions].flatten().compact().each(function(defs) { 697 | Object.extend(this.options, defs); 698 | }.bind(this)); 699 | }, 700 | prepareSubmission: function() { 701 | this._saving = true; 702 | this.removeForm(); 703 | this.leaveHover(); 704 | this.showSaving(); 705 | }, 706 | registerListeners: function() { 707 | this._listeners = { }; 708 | var listener; 709 | $H(Ajax.InPlaceEditor.Listeners).each(function(pair) { 710 | listener = this[pair.value].bind(this); 711 | this._listeners[pair.key] = listener; 712 | if (!this.options.externalControlOnly) 713 | this.element.observe(pair.key, listener); 714 | if (this.options.externalControl) 715 | this.options.externalControl.observe(pair.key, listener); 716 | }.bind(this)); 717 | }, 718 | removeForm: function() { 719 | if (!this._form) return; 720 | this._form.remove(); 721 | this._form = null; 722 | this._controls = { }; 723 | }, 724 | showSaving: function() { 725 | this._oldInnerHTML = this.element.innerHTML; 726 | this.element.innerHTML = this.options.savingText; 727 | this.element.addClassName(this.options.savingClassName); 728 | this.element.style.backgroundColor = this._originalBackground; 729 | this.element.show(); 730 | }, 731 | triggerCallback: function(cbName, arg) { 732 | if ('function' == typeof this.options[cbName]) { 733 | this.options[cbName](this, arg); 734 | } 735 | }, 736 | unregisterListeners: function() { 737 | $H(this._listeners).each(function(pair) { 738 | if (!this.options.externalControlOnly) 739 | this.element.stopObserving(pair.key, pair.value); 740 | if (this.options.externalControl) 741 | this.options.externalControl.stopObserving(pair.key, pair.value); 742 | }.bind(this)); 743 | }, 744 | wrapUp: function(transport) { 745 | this.leaveEditMode(); 746 | // Can't use triggerCallback due to backward compatibility: requires 747 | // binding + direct element 748 | this._boundComplete(transport, this.element); 749 | } 750 | }); 751 | 752 | Object.extend(Ajax.InPlaceEditor.prototype, { 753 | dispose: Ajax.InPlaceEditor.prototype.destroy 754 | }); 755 | 756 | Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, { 757 | initialize: function($super, element, url, options) { 758 | this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions; 759 | $super(element, url, options); 760 | }, 761 | 762 | createEditField: function() { 763 | var list = document.createElement('select'); 764 | list.name = this.options.paramName; 765 | list.size = 1; 766 | this._controls.editor = list; 767 | this._collection = this.options.collection || []; 768 | if (this.options.loadCollectionURL) 769 | this.loadCollection(); 770 | else 771 | this.checkForExternalText(); 772 | this._form.appendChild(this._controls.editor); 773 | }, 774 | 775 | loadCollection: function() { 776 | this._form.addClassName(this.options.loadingClassName); 777 | this.showLoadingText(this.options.loadingCollectionText); 778 | var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); 779 | Object.extend(options, { 780 | parameters: 'editorId=' + encodeURIComponent(this.element.id), 781 | onComplete: Prototype.emptyFunction, 782 | onSuccess: function(transport) { 783 | var js = transport.responseText.strip(); 784 | if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check 785 | throw('Server returned an invalid collection representation.'); 786 | this._collection = eval(js); 787 | this.checkForExternalText(); 788 | }.bind(this), 789 | onFailure: this.onFailure 790 | }); 791 | new Ajax.Request(this.options.loadCollectionURL, options); 792 | }, 793 | 794 | showLoadingText: function(text) { 795 | this._controls.editor.disabled = true; 796 | var tempOption = this._controls.editor.firstChild; 797 | if (!tempOption) { 798 | tempOption = document.createElement('option'); 799 | tempOption.value = ''; 800 | this._controls.editor.appendChild(tempOption); 801 | tempOption.selected = true; 802 | } 803 | tempOption.update((text || '').stripScripts().stripTags()); 804 | }, 805 | 806 | checkForExternalText: function() { 807 | this._text = this.getText(); 808 | if (this.options.loadTextURL) 809 | this.loadExternalText(); 810 | else 811 | this.buildOptionList(); 812 | }, 813 | 814 | loadExternalText: function() { 815 | this.showLoadingText(this.options.loadingText); 816 | var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); 817 | Object.extend(options, { 818 | parameters: 'editorId=' + encodeURIComponent(this.element.id), 819 | onComplete: Prototype.emptyFunction, 820 | onSuccess: function(transport) { 821 | this._text = transport.responseText.strip(); 822 | this.buildOptionList(); 823 | }.bind(this), 824 | onFailure: this.onFailure 825 | }); 826 | new Ajax.Request(this.options.loadTextURL, options); 827 | }, 828 | 829 | buildOptionList: function() { 830 | this._form.removeClassName(this.options.loadingClassName); 831 | this._collection = this._collection.map(function(entry) { 832 | return 2 === entry.length ? entry : [entry, entry].flatten(); 833 | }); 834 | var marker = ('value' in this.options) ? this.options.value : this._text; 835 | var textFound = this._collection.any(function(entry) { 836 | return entry[0] == marker; 837 | }.bind(this)); 838 | this._controls.editor.update(''); 839 | var option; 840 | this._collection.each(function(entry, index) { 841 | option = document.createElement('option'); 842 | option.value = entry[0]; 843 | option.selected = textFound ? entry[0] == marker : 0 == index; 844 | option.appendChild(document.createTextNode(entry[1])); 845 | this._controls.editor.appendChild(option); 846 | }.bind(this)); 847 | this._controls.editor.disabled = false; 848 | Field.scrollFreeActivate(this._controls.editor); 849 | } 850 | }); 851 | 852 | //**** DEPRECATION LAYER FOR InPlace[Collection]Editor! **** 853 | //**** This only exists for a while, in order to let **** 854 | //**** users adapt to the new API. Read up on the new **** 855 | //**** API and convert your code to it ASAP! **** 856 | 857 | Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) { 858 | if (!options) return; 859 | function fallback(name, expr) { 860 | if (name in options || expr === undefined) return; 861 | options[name] = expr; 862 | }; 863 | fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' : 864 | options.cancelLink == options.cancelButton == false ? false : undefined))); 865 | fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' : 866 | options.okLink == options.okButton == false ? false : undefined))); 867 | fallback('highlightColor', options.highlightcolor); 868 | fallback('highlightEndColor', options.highlightendcolor); 869 | }; 870 | 871 | Object.extend(Ajax.InPlaceEditor, { 872 | DefaultOptions: { 873 | ajaxOptions: { }, 874 | autoRows: 3, // Use when multi-line w/ rows == 1 875 | cancelControl: 'link', // 'link'|'button'|false 876 | cancelText: 'cancel', 877 | clickToEditText: 'Click to edit', 878 | externalControl: null, // id|elt 879 | externalControlOnly: false, 880 | fieldPostCreation: 'activate', // 'activate'|'focus'|false 881 | formClassName: 'inplaceeditor-form', 882 | formId: null, // id|elt 883 | highlightColor: '#ffff99', 884 | highlightEndColor: '#ffffff', 885 | hoverClassName: '', 886 | htmlResponse: true, 887 | loadingClassName: 'inplaceeditor-loading', 888 | loadingText: 'Loading...', 889 | okControl: 'button', // 'link'|'button'|false 890 | okText: 'ok', 891 | paramName: 'value', 892 | rows: 1, // If 1 and multi-line, uses autoRows 893 | savingClassName: 'inplaceeditor-saving', 894 | savingText: 'Saving...', 895 | size: 0, 896 | stripLoadedTextTags: false, 897 | submitOnBlur: false, 898 | textAfterControls: '', 899 | textBeforeControls: '', 900 | textBetweenControls: '' 901 | }, 902 | DefaultCallbacks: { 903 | callback: function(form) { 904 | return Form.serialize(form); 905 | }, 906 | onComplete: function(transport, element) { 907 | // For backward compatibility, this one is bound to the IPE, and passes 908 | // the element directly. It was too often customized, so we don't break it. 909 | new Effect.Highlight(element, { 910 | startcolor: this.options.highlightColor, keepBackgroundImage: true }); 911 | }, 912 | onEnterEditMode: null, 913 | onEnterHover: function(ipe) { 914 | ipe.element.style.backgroundColor = ipe.options.highlightColor; 915 | if (ipe._effect) 916 | ipe._effect.cancel(); 917 | }, 918 | onFailure: function(transport, ipe) { 919 | alert('Error communication with the server: ' + transport.responseText.stripTags()); 920 | }, 921 | onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls. 922 | onLeaveEditMode: null, 923 | onLeaveHover: function(ipe) { 924 | ipe._effect = new Effect.Highlight(ipe.element, { 925 | startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor, 926 | restorecolor: ipe._originalBackground, keepBackgroundImage: true 927 | }); 928 | } 929 | }, 930 | Listeners: { 931 | click: 'enterEditMode', 932 | keydown: 'checkForEscapeOrReturn', 933 | mouseover: 'enterHover', 934 | mouseout: 'leaveHover' 935 | } 936 | }); 937 | 938 | Ajax.InPlaceCollectionEditor.DefaultOptions = { 939 | loadingCollectionText: 'Loading options...' 940 | }; 941 | 942 | // Delayed observer, like Form.Element.Observer, 943 | // but waits for delay after last key input 944 | // Ideal for live-search fields 945 | 946 | Form.Element.DelayedObserver = Class.create({ 947 | initialize: function(element, delay, callback) { 948 | this.delay = delay || 0.5; 949 | this.element = $(element); 950 | this.callback = callback; 951 | this.timer = null; 952 | this.lastValue = $F(this.element); 953 | Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this)); 954 | }, 955 | delayedListener: function(event) { 956 | if(this.lastValue == $F(this.element)) return; 957 | if(this.timer) clearTimeout(this.timer); 958 | this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000); 959 | this.lastValue = $F(this.element); 960 | }, 961 | onTimerEvent: function() { 962 | this.timer = null; 963 | this.callback(this.element, $F(this.element)); 964 | } 965 | }); -------------------------------------------------------------------------------- /spec/dummy/public/javascripts/dragdrop.js: -------------------------------------------------------------------------------- 1 | // script.aculo.us dragdrop.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009 2 | 3 | // Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) 4 | // 5 | // script.aculo.us is freely distributable under the terms of an MIT-style license. 6 | // For details, see the script.aculo.us web site: http://script.aculo.us/ 7 | 8 | if(Object.isUndefined(Effect)) 9 | throw("dragdrop.js requires including script.aculo.us' effects.js library"); 10 | 11 | var Droppables = { 12 | drops: [], 13 | 14 | remove: function(element) { 15 | this.drops = this.drops.reject(function(d) { return d.element==$(element) }); 16 | }, 17 | 18 | add: function(element) { 19 | element = $(element); 20 | var options = Object.extend({ 21 | greedy: true, 22 | hoverclass: null, 23 | tree: false 24 | }, arguments[1] || { }); 25 | 26 | // cache containers 27 | if(options.containment) { 28 | options._containers = []; 29 | var containment = options.containment; 30 | if(Object.isArray(containment)) { 31 | containment.each( function(c) { options._containers.push($(c)) }); 32 | } else { 33 | options._containers.push($(containment)); 34 | } 35 | } 36 | 37 | if(options.accept) options.accept = [options.accept].flatten(); 38 | 39 | Element.makePositioned(element); // fix IE 40 | options.element = element; 41 | 42 | this.drops.push(options); 43 | }, 44 | 45 | findDeepestChild: function(drops) { 46 | deepest = drops[0]; 47 | 48 | for (i = 1; i < drops.length; ++i) 49 | if (Element.isParent(drops[i].element, deepest.element)) 50 | deepest = drops[i]; 51 | 52 | return deepest; 53 | }, 54 | 55 | isContained: function(element, drop) { 56 | var containmentNode; 57 | if(drop.tree) { 58 | containmentNode = element.treeNode; 59 | } else { 60 | containmentNode = element.parentNode; 61 | } 62 | return drop._containers.detect(function(c) { return containmentNode == c }); 63 | }, 64 | 65 | isAffected: function(point, element, drop) { 66 | return ( 67 | (drop.element!=element) && 68 | ((!drop._containers) || 69 | this.isContained(element, drop)) && 70 | ((!drop.accept) || 71 | (Element.classNames(element).detect( 72 | function(v) { return drop.accept.include(v) } ) )) && 73 | Position.within(drop.element, point[0], point[1]) ); 74 | }, 75 | 76 | deactivate: function(drop) { 77 | if(drop.hoverclass) 78 | Element.removeClassName(drop.element, drop.hoverclass); 79 | this.last_active = null; 80 | }, 81 | 82 | activate: function(drop) { 83 | if(drop.hoverclass) 84 | Element.addClassName(drop.element, drop.hoverclass); 85 | this.last_active = drop; 86 | }, 87 | 88 | show: function(point, element) { 89 | if(!this.drops.length) return; 90 | var drop, affected = []; 91 | 92 | this.drops.each( function(drop) { 93 | if(Droppables.isAffected(point, element, drop)) 94 | affected.push(drop); 95 | }); 96 | 97 | if(affected.length>0) 98 | drop = Droppables.findDeepestChild(affected); 99 | 100 | if(this.last_active && this.last_active != drop) this.deactivate(this.last_active); 101 | if (drop) { 102 | Position.within(drop.element, point[0], point[1]); 103 | if(drop.onHover) 104 | drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element)); 105 | 106 | if (drop != this.last_active) Droppables.activate(drop); 107 | } 108 | }, 109 | 110 | fire: function(event, element) { 111 | if(!this.last_active) return; 112 | Position.prepare(); 113 | 114 | if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active)) 115 | if (this.last_active.onDrop) { 116 | this.last_active.onDrop(element, this.last_active.element, event); 117 | return true; 118 | } 119 | }, 120 | 121 | reset: function() { 122 | if(this.last_active) 123 | this.deactivate(this.last_active); 124 | } 125 | }; 126 | 127 | var Draggables = { 128 | drags: [], 129 | observers: [], 130 | 131 | register: function(draggable) { 132 | if(this.drags.length == 0) { 133 | this.eventMouseUp = this.endDrag.bindAsEventListener(this); 134 | this.eventMouseMove = this.updateDrag.bindAsEventListener(this); 135 | this.eventKeypress = this.keyPress.bindAsEventListener(this); 136 | 137 | Event.observe(document, "mouseup", this.eventMouseUp); 138 | Event.observe(document, "mousemove", this.eventMouseMove); 139 | Event.observe(document, "keypress", this.eventKeypress); 140 | } 141 | this.drags.push(draggable); 142 | }, 143 | 144 | unregister: function(draggable) { 145 | this.drags = this.drags.reject(function(d) { return d==draggable }); 146 | if(this.drags.length == 0) { 147 | Event.stopObserving(document, "mouseup", this.eventMouseUp); 148 | Event.stopObserving(document, "mousemove", this.eventMouseMove); 149 | Event.stopObserving(document, "keypress", this.eventKeypress); 150 | } 151 | }, 152 | 153 | activate: function(draggable) { 154 | if(draggable.options.delay) { 155 | this._timeout = setTimeout(function() { 156 | Draggables._timeout = null; 157 | window.focus(); 158 | Draggables.activeDraggable = draggable; 159 | }.bind(this), draggable.options.delay); 160 | } else { 161 | window.focus(); // allows keypress events if window isn't currently focused, fails for Safari 162 | this.activeDraggable = draggable; 163 | } 164 | }, 165 | 166 | deactivate: function() { 167 | this.activeDraggable = null; 168 | }, 169 | 170 | updateDrag: function(event) { 171 | if(!this.activeDraggable) return; 172 | var pointer = [Event.pointerX(event), Event.pointerY(event)]; 173 | // Mozilla-based browsers fire successive mousemove events with 174 | // the same coordinates, prevent needless redrawing (moz bug?) 175 | if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return; 176 | this._lastPointer = pointer; 177 | 178 | this.activeDraggable.updateDrag(event, pointer); 179 | }, 180 | 181 | endDrag: function(event) { 182 | if(this._timeout) { 183 | clearTimeout(this._timeout); 184 | this._timeout = null; 185 | } 186 | if(!this.activeDraggable) return; 187 | this._lastPointer = null; 188 | this.activeDraggable.endDrag(event); 189 | this.activeDraggable = null; 190 | }, 191 | 192 | keyPress: function(event) { 193 | if(this.activeDraggable) 194 | this.activeDraggable.keyPress(event); 195 | }, 196 | 197 | addObserver: function(observer) { 198 | this.observers.push(observer); 199 | this._cacheObserverCallbacks(); 200 | }, 201 | 202 | removeObserver: function(element) { // element instead of observer fixes mem leaks 203 | this.observers = this.observers.reject( function(o) { return o.element==element }); 204 | this._cacheObserverCallbacks(); 205 | }, 206 | 207 | notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag' 208 | if(this[eventName+'Count'] > 0) 209 | this.observers.each( function(o) { 210 | if(o[eventName]) o[eventName](eventName, draggable, event); 211 | }); 212 | if(draggable.options[eventName]) draggable.options[eventName](draggable, event); 213 | }, 214 | 215 | _cacheObserverCallbacks: function() { 216 | ['onStart','onEnd','onDrag'].each( function(eventName) { 217 | Draggables[eventName+'Count'] = Draggables.observers.select( 218 | function(o) { return o[eventName]; } 219 | ).length; 220 | }); 221 | } 222 | }; 223 | 224 | /*--------------------------------------------------------------------------*/ 225 | 226 | var Draggable = Class.create({ 227 | initialize: function(element) { 228 | var defaults = { 229 | handle: false, 230 | reverteffect: function(element, top_offset, left_offset) { 231 | var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02; 232 | new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur, 233 | queue: {scope:'_draggable', position:'end'} 234 | }); 235 | }, 236 | endeffect: function(element) { 237 | var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0; 238 | new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity, 239 | queue: {scope:'_draggable', position:'end'}, 240 | afterFinish: function(){ 241 | Draggable._dragging[element] = false 242 | } 243 | }); 244 | }, 245 | zindex: 1000, 246 | revert: false, 247 | quiet: false, 248 | scroll: false, 249 | scrollSensitivity: 20, 250 | scrollSpeed: 15, 251 | snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] } 252 | delay: 0 253 | }; 254 | 255 | if(!arguments[1] || Object.isUndefined(arguments[1].endeffect)) 256 | Object.extend(defaults, { 257 | starteffect: function(element) { 258 | element._opacity = Element.getOpacity(element); 259 | Draggable._dragging[element] = true; 260 | new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7}); 261 | } 262 | }); 263 | 264 | var options = Object.extend(defaults, arguments[1] || { }); 265 | 266 | this.element = $(element); 267 | 268 | if(options.handle && Object.isString(options.handle)) 269 | this.handle = this.element.down('.'+options.handle, 0); 270 | 271 | if(!this.handle) this.handle = $(options.handle); 272 | if(!this.handle) this.handle = this.element; 273 | 274 | if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) { 275 | options.scroll = $(options.scroll); 276 | this._isScrollChild = Element.childOf(this.element, options.scroll); 277 | } 278 | 279 | Element.makePositioned(this.element); // fix IE 280 | 281 | this.options = options; 282 | this.dragging = false; 283 | 284 | this.eventMouseDown = this.initDrag.bindAsEventListener(this); 285 | Event.observe(this.handle, "mousedown", this.eventMouseDown); 286 | 287 | Draggables.register(this); 288 | }, 289 | 290 | destroy: function() { 291 | Event.stopObserving(this.handle, "mousedown", this.eventMouseDown); 292 | Draggables.unregister(this); 293 | }, 294 | 295 | currentDelta: function() { 296 | return([ 297 | parseInt(Element.getStyle(this.element,'left') || '0'), 298 | parseInt(Element.getStyle(this.element,'top') || '0')]); 299 | }, 300 | 301 | initDrag: function(event) { 302 | if(!Object.isUndefined(Draggable._dragging[this.element]) && 303 | Draggable._dragging[this.element]) return; 304 | if(Event.isLeftClick(event)) { 305 | // abort on form elements, fixes a Firefox issue 306 | var src = Event.element(event); 307 | if((tag_name = src.tagName.toUpperCase()) && ( 308 | tag_name=='INPUT' || 309 | tag_name=='SELECT' || 310 | tag_name=='OPTION' || 311 | tag_name=='BUTTON' || 312 | tag_name=='TEXTAREA')) return; 313 | 314 | var pointer = [Event.pointerX(event), Event.pointerY(event)]; 315 | var pos = this.element.cumulativeOffset(); 316 | this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) }); 317 | 318 | Draggables.activate(this); 319 | Event.stop(event); 320 | } 321 | }, 322 | 323 | startDrag: function(event) { 324 | this.dragging = true; 325 | if(!this.delta) 326 | this.delta = this.currentDelta(); 327 | 328 | if(this.options.zindex) { 329 | this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0); 330 | this.element.style.zIndex = this.options.zindex; 331 | } 332 | 333 | if(this.options.ghosting) { 334 | this._clone = this.element.cloneNode(true); 335 | this._originallyAbsolute = (this.element.getStyle('position') == 'absolute'); 336 | if (!this._originallyAbsolute) 337 | Position.absolutize(this.element); 338 | this.element.parentNode.insertBefore(this._clone, this.element); 339 | } 340 | 341 | if(this.options.scroll) { 342 | if (this.options.scroll == window) { 343 | var where = this._getWindowScroll(this.options.scroll); 344 | this.originalScrollLeft = where.left; 345 | this.originalScrollTop = where.top; 346 | } else { 347 | this.originalScrollLeft = this.options.scroll.scrollLeft; 348 | this.originalScrollTop = this.options.scroll.scrollTop; 349 | } 350 | } 351 | 352 | Draggables.notify('onStart', this, event); 353 | 354 | if(this.options.starteffect) this.options.starteffect(this.element); 355 | }, 356 | 357 | updateDrag: function(event, pointer) { 358 | if(!this.dragging) this.startDrag(event); 359 | 360 | if(!this.options.quiet){ 361 | Position.prepare(); 362 | Droppables.show(pointer, this.element); 363 | } 364 | 365 | Draggables.notify('onDrag', this, event); 366 | 367 | this.draw(pointer); 368 | if(this.options.change) this.options.change(this); 369 | 370 | if(this.options.scroll) { 371 | this.stopScrolling(); 372 | 373 | var p; 374 | if (this.options.scroll == window) { 375 | with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; } 376 | } else { 377 | p = Position.page(this.options.scroll); 378 | p[0] += this.options.scroll.scrollLeft + Position.deltaX; 379 | p[1] += this.options.scroll.scrollTop + Position.deltaY; 380 | p.push(p[0]+this.options.scroll.offsetWidth); 381 | p.push(p[1]+this.options.scroll.offsetHeight); 382 | } 383 | var speed = [0,0]; 384 | if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity); 385 | if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity); 386 | if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity); 387 | if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity); 388 | this.startScrolling(speed); 389 | } 390 | 391 | // fix AppleWebKit rendering 392 | if(Prototype.Browser.WebKit) window.scrollBy(0,0); 393 | 394 | Event.stop(event); 395 | }, 396 | 397 | finishDrag: function(event, success) { 398 | this.dragging = false; 399 | 400 | if(this.options.quiet){ 401 | Position.prepare(); 402 | var pointer = [Event.pointerX(event), Event.pointerY(event)]; 403 | Droppables.show(pointer, this.element); 404 | } 405 | 406 | if(this.options.ghosting) { 407 | if (!this._originallyAbsolute) 408 | Position.relativize(this.element); 409 | delete this._originallyAbsolute; 410 | Element.remove(this._clone); 411 | this._clone = null; 412 | } 413 | 414 | var dropped = false; 415 | if(success) { 416 | dropped = Droppables.fire(event, this.element); 417 | if (!dropped) dropped = false; 418 | } 419 | if(dropped && this.options.onDropped) this.options.onDropped(this.element); 420 | Draggables.notify('onEnd', this, event); 421 | 422 | var revert = this.options.revert; 423 | if(revert && Object.isFunction(revert)) revert = revert(this.element); 424 | 425 | var d = this.currentDelta(); 426 | if(revert && this.options.reverteffect) { 427 | if (dropped == 0 || revert != 'failure') 428 | this.options.reverteffect(this.element, 429 | d[1]-this.delta[1], d[0]-this.delta[0]); 430 | } else { 431 | this.delta = d; 432 | } 433 | 434 | if(this.options.zindex) 435 | this.element.style.zIndex = this.originalZ; 436 | 437 | if(this.options.endeffect) 438 | this.options.endeffect(this.element); 439 | 440 | Draggables.deactivate(this); 441 | Droppables.reset(); 442 | }, 443 | 444 | keyPress: function(event) { 445 | if(event.keyCode!=Event.KEY_ESC) return; 446 | this.finishDrag(event, false); 447 | Event.stop(event); 448 | }, 449 | 450 | endDrag: function(event) { 451 | if(!this.dragging) return; 452 | this.stopScrolling(); 453 | this.finishDrag(event, true); 454 | Event.stop(event); 455 | }, 456 | 457 | draw: function(point) { 458 | var pos = this.element.cumulativeOffset(); 459 | if(this.options.ghosting) { 460 | var r = Position.realOffset(this.element); 461 | pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY; 462 | } 463 | 464 | var d = this.currentDelta(); 465 | pos[0] -= d[0]; pos[1] -= d[1]; 466 | 467 | if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) { 468 | pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft; 469 | pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop; 470 | } 471 | 472 | var p = [0,1].map(function(i){ 473 | return (point[i]-pos[i]-this.offset[i]) 474 | }.bind(this)); 475 | 476 | if(this.options.snap) { 477 | if(Object.isFunction(this.options.snap)) { 478 | p = this.options.snap(p[0],p[1],this); 479 | } else { 480 | if(Object.isArray(this.options.snap)) { 481 | p = p.map( function(v, i) { 482 | return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this)); 483 | } else { 484 | p = p.map( function(v) { 485 | return (v/this.options.snap).round()*this.options.snap }.bind(this)); 486 | } 487 | }} 488 | 489 | var style = this.element.style; 490 | if((!this.options.constraint) || (this.options.constraint=='horizontal')) 491 | style.left = p[0] + "px"; 492 | if((!this.options.constraint) || (this.options.constraint=='vertical')) 493 | style.top = p[1] + "px"; 494 | 495 | if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering 496 | }, 497 | 498 | stopScrolling: function() { 499 | if(this.scrollInterval) { 500 | clearInterval(this.scrollInterval); 501 | this.scrollInterval = null; 502 | Draggables._lastScrollPointer = null; 503 | } 504 | }, 505 | 506 | startScrolling: function(speed) { 507 | if(!(speed[0] || speed[1])) return; 508 | this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed]; 509 | this.lastScrolled = new Date(); 510 | this.scrollInterval = setInterval(this.scroll.bind(this), 10); 511 | }, 512 | 513 | scroll: function() { 514 | var current = new Date(); 515 | var delta = current - this.lastScrolled; 516 | this.lastScrolled = current; 517 | if(this.options.scroll == window) { 518 | with (this._getWindowScroll(this.options.scroll)) { 519 | if (this.scrollSpeed[0] || this.scrollSpeed[1]) { 520 | var d = delta / 1000; 521 | this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] ); 522 | } 523 | } 524 | } else { 525 | this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000; 526 | this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000; 527 | } 528 | 529 | Position.prepare(); 530 | Droppables.show(Draggables._lastPointer, this.element); 531 | Draggables.notify('onDrag', this); 532 | if (this._isScrollChild) { 533 | Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer); 534 | Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000; 535 | Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000; 536 | if (Draggables._lastScrollPointer[0] < 0) 537 | Draggables._lastScrollPointer[0] = 0; 538 | if (Draggables._lastScrollPointer[1] < 0) 539 | Draggables._lastScrollPointer[1] = 0; 540 | this.draw(Draggables._lastScrollPointer); 541 | } 542 | 543 | if(this.options.change) this.options.change(this); 544 | }, 545 | 546 | _getWindowScroll: function(w) { 547 | var T, L, W, H; 548 | with (w.document) { 549 | if (w.document.documentElement && documentElement.scrollTop) { 550 | T = documentElement.scrollTop; 551 | L = documentElement.scrollLeft; 552 | } else if (w.document.body) { 553 | T = body.scrollTop; 554 | L = body.scrollLeft; 555 | } 556 | if (w.innerWidth) { 557 | W = w.innerWidth; 558 | H = w.innerHeight; 559 | } else if (w.document.documentElement && documentElement.clientWidth) { 560 | W = documentElement.clientWidth; 561 | H = documentElement.clientHeight; 562 | } else { 563 | W = body.offsetWidth; 564 | H = body.offsetHeight; 565 | } 566 | } 567 | return { top: T, left: L, width: W, height: H }; 568 | } 569 | }); 570 | 571 | Draggable._dragging = { }; 572 | 573 | /*--------------------------------------------------------------------------*/ 574 | 575 | var SortableObserver = Class.create({ 576 | initialize: function(element, observer) { 577 | this.element = $(element); 578 | this.observer = observer; 579 | this.lastValue = Sortable.serialize(this.element); 580 | }, 581 | 582 | onStart: function() { 583 | this.lastValue = Sortable.serialize(this.element); 584 | }, 585 | 586 | onEnd: function() { 587 | Sortable.unmark(); 588 | if(this.lastValue != Sortable.serialize(this.element)) 589 | this.observer(this.element) 590 | } 591 | }); 592 | 593 | var Sortable = { 594 | SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/, 595 | 596 | sortables: { }, 597 | 598 | _findRootElement: function(element) { 599 | while (element.tagName.toUpperCase() != "BODY") { 600 | if(element.id && Sortable.sortables[element.id]) return element; 601 | element = element.parentNode; 602 | } 603 | }, 604 | 605 | options: function(element) { 606 | element = Sortable._findRootElement($(element)); 607 | if(!element) return; 608 | return Sortable.sortables[element.id]; 609 | }, 610 | 611 | destroy: function(element){ 612 | element = $(element); 613 | var s = Sortable.sortables[element.id]; 614 | 615 | if(s) { 616 | Draggables.removeObserver(s.element); 617 | s.droppables.each(function(d){ Droppables.remove(d) }); 618 | s.draggables.invoke('destroy'); 619 | 620 | delete Sortable.sortables[s.element.id]; 621 | } 622 | }, 623 | 624 | create: function(element) { 625 | element = $(element); 626 | var options = Object.extend({ 627 | element: element, 628 | tag: 'li', // assumes li children, override with tag: 'tagname' 629 | dropOnEmpty: false, 630 | tree: false, 631 | treeTag: 'ul', 632 | overlap: 'vertical', // one of 'vertical', 'horizontal' 633 | constraint: 'vertical', // one of 'vertical', 'horizontal', false 634 | containment: element, // also takes array of elements (or id's); or false 635 | handle: false, // or a CSS class 636 | only: false, 637 | delay: 0, 638 | hoverclass: null, 639 | ghosting: false, 640 | quiet: false, 641 | scroll: false, 642 | scrollSensitivity: 20, 643 | scrollSpeed: 15, 644 | format: this.SERIALIZE_RULE, 645 | 646 | // these take arrays of elements or ids and can be 647 | // used for better initialization performance 648 | elements: false, 649 | handles: false, 650 | 651 | onChange: Prototype.emptyFunction, 652 | onUpdate: Prototype.emptyFunction 653 | }, arguments[1] || { }); 654 | 655 | // clear any old sortable with same element 656 | this.destroy(element); 657 | 658 | // build options for the draggables 659 | var options_for_draggable = { 660 | revert: true, 661 | quiet: options.quiet, 662 | scroll: options.scroll, 663 | scrollSpeed: options.scrollSpeed, 664 | scrollSensitivity: options.scrollSensitivity, 665 | delay: options.delay, 666 | ghosting: options.ghosting, 667 | constraint: options.constraint, 668 | handle: options.handle }; 669 | 670 | if(options.starteffect) 671 | options_for_draggable.starteffect = options.starteffect; 672 | 673 | if(options.reverteffect) 674 | options_for_draggable.reverteffect = options.reverteffect; 675 | else 676 | if(options.ghosting) options_for_draggable.reverteffect = function(element) { 677 | element.style.top = 0; 678 | element.style.left = 0; 679 | }; 680 | 681 | if(options.endeffect) 682 | options_for_draggable.endeffect = options.endeffect; 683 | 684 | if(options.zindex) 685 | options_for_draggable.zindex = options.zindex; 686 | 687 | // build options for the droppables 688 | var options_for_droppable = { 689 | overlap: options.overlap, 690 | containment: options.containment, 691 | tree: options.tree, 692 | hoverclass: options.hoverclass, 693 | onHover: Sortable.onHover 694 | }; 695 | 696 | var options_for_tree = { 697 | onHover: Sortable.onEmptyHover, 698 | overlap: options.overlap, 699 | containment: options.containment, 700 | hoverclass: options.hoverclass 701 | }; 702 | 703 | // fix for gecko engine 704 | Element.cleanWhitespace(element); 705 | 706 | options.draggables = []; 707 | options.droppables = []; 708 | 709 | // drop on empty handling 710 | if(options.dropOnEmpty || options.tree) { 711 | Droppables.add(element, options_for_tree); 712 | options.droppables.push(element); 713 | } 714 | 715 | (options.elements || this.findElements(element, options) || []).each( function(e,i) { 716 | var handle = options.handles ? $(options.handles[i]) : 717 | (options.handle ? $(e).select('.' + options.handle)[0] : e); 718 | options.draggables.push( 719 | new Draggable(e, Object.extend(options_for_draggable, { handle: handle }))); 720 | Droppables.add(e, options_for_droppable); 721 | if(options.tree) e.treeNode = element; 722 | options.droppables.push(e); 723 | }); 724 | 725 | if(options.tree) { 726 | (Sortable.findTreeElements(element, options) || []).each( function(e) { 727 | Droppables.add(e, options_for_tree); 728 | e.treeNode = element; 729 | options.droppables.push(e); 730 | }); 731 | } 732 | 733 | // keep reference 734 | this.sortables[element.identify()] = options; 735 | 736 | // for onupdate 737 | Draggables.addObserver(new SortableObserver(element, options.onUpdate)); 738 | 739 | }, 740 | 741 | // return all suitable-for-sortable elements in a guaranteed order 742 | findElements: function(element, options) { 743 | return Element.findChildren( 744 | element, options.only, options.tree ? true : false, options.tag); 745 | }, 746 | 747 | findTreeElements: function(element, options) { 748 | return Element.findChildren( 749 | element, options.only, options.tree ? true : false, options.treeTag); 750 | }, 751 | 752 | onHover: function(element, dropon, overlap) { 753 | if(Element.isParent(dropon, element)) return; 754 | 755 | if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) { 756 | return; 757 | } else if(overlap>0.5) { 758 | Sortable.mark(dropon, 'before'); 759 | if(dropon.previousSibling != element) { 760 | var oldParentNode = element.parentNode; 761 | element.style.visibility = "hidden"; // fix gecko rendering 762 | dropon.parentNode.insertBefore(element, dropon); 763 | if(dropon.parentNode!=oldParentNode) 764 | Sortable.options(oldParentNode).onChange(element); 765 | Sortable.options(dropon.parentNode).onChange(element); 766 | } 767 | } else { 768 | Sortable.mark(dropon, 'after'); 769 | var nextElement = dropon.nextSibling || null; 770 | if(nextElement != element) { 771 | var oldParentNode = element.parentNode; 772 | element.style.visibility = "hidden"; // fix gecko rendering 773 | dropon.parentNode.insertBefore(element, nextElement); 774 | if(dropon.parentNode!=oldParentNode) 775 | Sortable.options(oldParentNode).onChange(element); 776 | Sortable.options(dropon.parentNode).onChange(element); 777 | } 778 | } 779 | }, 780 | 781 | onEmptyHover: function(element, dropon, overlap) { 782 | var oldParentNode = element.parentNode; 783 | var droponOptions = Sortable.options(dropon); 784 | 785 | if(!Element.isParent(dropon, element)) { 786 | var index; 787 | 788 | var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only}); 789 | var child = null; 790 | 791 | if(children) { 792 | var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap); 793 | 794 | for (index = 0; index < children.length; index += 1) { 795 | if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) { 796 | offset -= Element.offsetSize (children[index], droponOptions.overlap); 797 | } else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) { 798 | child = index + 1 < children.length ? children[index + 1] : null; 799 | break; 800 | } else { 801 | child = children[index]; 802 | break; 803 | } 804 | } 805 | } 806 | 807 | dropon.insertBefore(element, child); 808 | 809 | Sortable.options(oldParentNode).onChange(element); 810 | droponOptions.onChange(element); 811 | } 812 | }, 813 | 814 | unmark: function() { 815 | if(Sortable._marker) Sortable._marker.hide(); 816 | }, 817 | 818 | mark: function(dropon, position) { 819 | // mark on ghosting only 820 | var sortable = Sortable.options(dropon.parentNode); 821 | if(sortable && !sortable.ghosting) return; 822 | 823 | if(!Sortable._marker) { 824 | Sortable._marker = 825 | ($('dropmarker') || Element.extend(document.createElement('DIV'))). 826 | hide().addClassName('dropmarker').setStyle({position:'absolute'}); 827 | document.getElementsByTagName("body").item(0).appendChild(Sortable._marker); 828 | } 829 | var offsets = dropon.cumulativeOffset(); 830 | Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'}); 831 | 832 | if(position=='after') 833 | if(sortable.overlap == 'horizontal') 834 | Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'}); 835 | else 836 | Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'}); 837 | 838 | Sortable._marker.show(); 839 | }, 840 | 841 | _tree: function(element, options, parent) { 842 | var children = Sortable.findElements(element, options) || []; 843 | 844 | for (var i = 0; i < children.length; ++i) { 845 | var match = children[i].id.match(options.format); 846 | 847 | if (!match) continue; 848 | 849 | var child = { 850 | id: encodeURIComponent(match ? match[1] : null), 851 | element: element, 852 | parent: parent, 853 | children: [], 854 | position: parent.children.length, 855 | container: $(children[i]).down(options.treeTag) 856 | }; 857 | 858 | /* Get the element containing the children and recurse over it */ 859 | if (child.container) 860 | this._tree(child.container, options, child); 861 | 862 | parent.children.push (child); 863 | } 864 | 865 | return parent; 866 | }, 867 | 868 | tree: function(element) { 869 | element = $(element); 870 | var sortableOptions = this.options(element); 871 | var options = Object.extend({ 872 | tag: sortableOptions.tag, 873 | treeTag: sortableOptions.treeTag, 874 | only: sortableOptions.only, 875 | name: element.id, 876 | format: sortableOptions.format 877 | }, arguments[1] || { }); 878 | 879 | var root = { 880 | id: null, 881 | parent: null, 882 | children: [], 883 | container: element, 884 | position: 0 885 | }; 886 | 887 | return Sortable._tree(element, options, root); 888 | }, 889 | 890 | /* Construct a [i] index for a particular node */ 891 | _constructIndex: function(node) { 892 | var index = ''; 893 | do { 894 | if (node.id) index = '[' + node.position + ']' + index; 895 | } while ((node = node.parent) != null); 896 | return index; 897 | }, 898 | 899 | sequence: function(element) { 900 | element = $(element); 901 | var options = Object.extend(this.options(element), arguments[1] || { }); 902 | 903 | return $(this.findElements(element, options) || []).map( function(item) { 904 | return item.id.match(options.format) ? item.id.match(options.format)[1] : ''; 905 | }); 906 | }, 907 | 908 | setSequence: function(element, new_sequence) { 909 | element = $(element); 910 | var options = Object.extend(this.options(element), arguments[2] || { }); 911 | 912 | var nodeMap = { }; 913 | this.findElements(element, options).each( function(n) { 914 | if (n.id.match(options.format)) 915 | nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode]; 916 | n.parentNode.removeChild(n); 917 | }); 918 | 919 | new_sequence.each(function(ident) { 920 | var n = nodeMap[ident]; 921 | if (n) { 922 | n[1].appendChild(n[0]); 923 | delete nodeMap[ident]; 924 | } 925 | }); 926 | }, 927 | 928 | serialize: function(element) { 929 | element = $(element); 930 | var options = Object.extend(Sortable.options(element), arguments[1] || { }); 931 | var name = encodeURIComponent( 932 | (arguments[1] && arguments[1].name) ? arguments[1].name : element.id); 933 | 934 | if (options.tree) { 935 | return Sortable.tree(element, arguments[1]).children.map( function (item) { 936 | return [name + Sortable._constructIndex(item) + "[id]=" + 937 | encodeURIComponent(item.id)].concat(item.children.map(arguments.callee)); 938 | }).flatten().join('&'); 939 | } else { 940 | return Sortable.sequence(element, arguments[1]).map( function(item) { 941 | return name + "[]=" + encodeURIComponent(item); 942 | }).join('&'); 943 | } 944 | } 945 | }; 946 | 947 | // Returns true if child is contained within element 948 | Element.isParent = function(child, element) { 949 | if (!child.parentNode || child == element) return false; 950 | if (child.parentNode == element) return true; 951 | return Element.isParent(child.parentNode, element); 952 | }; 953 | 954 | Element.findChildren = function(element, only, recursive, tagName) { 955 | if(!element.hasChildNodes()) return null; 956 | tagName = tagName.toUpperCase(); 957 | if(only) only = [only].flatten(); 958 | var elements = []; 959 | $A(element.childNodes).each( function(e) { 960 | if(e.tagName && e.tagName.toUpperCase()==tagName && 961 | (!only || (Element.classNames(e).detect(function(v) { return only.include(v) })))) 962 | elements.push(e); 963 | if(recursive) { 964 | var grandchildren = Element.findChildren(e, only, recursive, tagName); 965 | if(grandchildren) elements.push(grandchildren); 966 | } 967 | }); 968 | 969 | return (elements.length>0 ? elements.flatten() : []); 970 | }; 971 | 972 | Element.offsetSize = function (element, type) { 973 | return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')]; 974 | }; -------------------------------------------------------------------------------- /spec/dummy/public/javascripts/rails.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | // Technique from Juriy Zaytsev 3 | // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ 4 | function isEventSupported(eventName) { 5 | var el = document.createElement('div'); 6 | eventName = 'on' + eventName; 7 | var isSupported = (eventName in el); 8 | if (!isSupported) { 9 | el.setAttribute(eventName, 'return;'); 10 | isSupported = typeof el[eventName] == 'function'; 11 | } 12 | el = null; 13 | return isSupported; 14 | } 15 | 16 | function isForm(element) { 17 | return Object.isElement(element) && element.nodeName.toUpperCase() == 'FORM' 18 | } 19 | 20 | function isInput(element) { 21 | if (Object.isElement(element)) { 22 | var name = element.nodeName.toUpperCase() 23 | return name == 'INPUT' || name == 'SELECT' || name == 'TEXTAREA' 24 | } 25 | else return false 26 | } 27 | 28 | var submitBubbles = isEventSupported('submit'), 29 | changeBubbles = isEventSupported('change') 30 | 31 | if (!submitBubbles || !changeBubbles) { 32 | // augment the Event.Handler class to observe custom events when needed 33 | Event.Handler.prototype.initialize = Event.Handler.prototype.initialize.wrap( 34 | function(init, element, eventName, selector, callback) { 35 | init(element, eventName, selector, callback) 36 | // is the handler being attached to an element that doesn't support this event? 37 | if ( (!submitBubbles && this.eventName == 'submit' && !isForm(this.element)) || 38 | (!changeBubbles && this.eventName == 'change' && !isInput(this.element)) ) { 39 | // "submit" => "emulated:submit" 40 | this.eventName = 'emulated:' + this.eventName 41 | } 42 | } 43 | ) 44 | } 45 | 46 | if (!submitBubbles) { 47 | // discover forms on the page by observing focus events which always bubble 48 | document.on('focusin', 'form', function(focusEvent, form) { 49 | // special handler for the real "submit" event (one-time operation) 50 | if (!form.retrieve('emulated:submit')) { 51 | form.on('submit', function(submitEvent) { 52 | var emulated = form.fire('emulated:submit', submitEvent, true) 53 | // if custom event received preventDefault, cancel the real one too 54 | if (emulated.returnValue === false) submitEvent.preventDefault() 55 | }) 56 | form.store('emulated:submit', true) 57 | } 58 | }) 59 | } 60 | 61 | if (!changeBubbles) { 62 | // discover form inputs on the page 63 | document.on('focusin', 'input, select, texarea', function(focusEvent, input) { 64 | // special handler for real "change" events 65 | if (!input.retrieve('emulated:change')) { 66 | input.on('change', function(changeEvent) { 67 | input.fire('emulated:change', changeEvent, true) 68 | }) 69 | input.store('emulated:change', true) 70 | } 71 | }) 72 | } 73 | 74 | function handleRemote(element) { 75 | var method, url, params; 76 | 77 | var event = element.fire("ajax:before"); 78 | if (event.stopped) return false; 79 | 80 | if (element.tagName.toLowerCase() === 'form') { 81 | method = element.readAttribute('method') || 'post'; 82 | url = element.readAttribute('action'); 83 | params = element.serialize(); 84 | } else { 85 | method = element.readAttribute('data-method') || 'get'; 86 | url = element.readAttribute('href'); 87 | params = {}; 88 | } 89 | 90 | new Ajax.Request(url, { 91 | method: method, 92 | parameters: params, 93 | evalScripts: true, 94 | 95 | onComplete: function(request) { element.fire("ajax:complete", request); }, 96 | onSuccess: function(request) { element.fire("ajax:success", request); }, 97 | onFailure: function(request) { element.fire("ajax:failure", request); } 98 | }); 99 | 100 | element.fire("ajax:after"); 101 | } 102 | 103 | function handleMethod(element) { 104 | var method = element.readAttribute('data-method'), 105 | url = element.readAttribute('href'), 106 | csrf_param = $$('meta[name=csrf-param]')[0], 107 | csrf_token = $$('meta[name=csrf-token]')[0]; 108 | 109 | var form = new Element('form', { method: "POST", action: url, style: "display: none;" }); 110 | element.parentNode.insert(form); 111 | 112 | if (method !== 'post') { 113 | var field = new Element('input', { type: 'hidden', name: '_method', value: method }); 114 | form.insert(field); 115 | } 116 | 117 | if (csrf_param) { 118 | var param = csrf_param.readAttribute('content'), 119 | token = csrf_token.readAttribute('content'), 120 | field = new Element('input', { type: 'hidden', name: param, value: token }); 121 | form.insert(field); 122 | } 123 | 124 | form.submit(); 125 | } 126 | 127 | 128 | document.on("click", "*[data-confirm]", function(event, element) { 129 | var message = element.readAttribute('data-confirm'); 130 | if (!confirm(message)) event.stop(); 131 | }); 132 | 133 | document.on("click", "a[data-remote]", function(event, element) { 134 | if (event.stopped) return; 135 | handleRemote(element); 136 | event.stop(); 137 | }); 138 | 139 | document.on("click", "a[data-method]", function(event, element) { 140 | if (event.stopped) return; 141 | handleMethod(element); 142 | event.stop(); 143 | }); 144 | 145 | document.on("submit", function(event) { 146 | var element = event.findElement(), 147 | message = element.readAttribute('data-confirm'); 148 | if (message && !confirm(message)) { 149 | event.stop(); 150 | return false; 151 | } 152 | 153 | var inputs = element.select("input[type=submit][data-disable-with]"); 154 | inputs.each(function(input) { 155 | input.disabled = true; 156 | input.writeAttribute('data-original-value', input.value); 157 | input.value = input.readAttribute('data-disable-with'); 158 | }); 159 | 160 | var element = event.findElement("form[data-remote]"); 161 | if (element) { 162 | handleRemote(element); 163 | event.stop(); 164 | } 165 | }); 166 | 167 | document.on("ajax:after", "form", function(event, element) { 168 | var inputs = element.select("input[type=submit][disabled=true][data-disable-with]"); 169 | inputs.each(function(input) { 170 | input.value = input.readAttribute('data-original-value'); 171 | input.removeAttribute('data-original-value'); 172 | input.disabled = false; 173 | }); 174 | }); 175 | })(); 176 | -------------------------------------------------------------------------------- /spec/dummy/public/stylesheets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nathanvda/cocoon/b3f4e6d1920937063cba2a4472dc4508bbac00f3/spec/dummy/public/stylesheets/.gitkeep -------------------------------------------------------------------------------- /spec/dummy/script/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. 3 | 4 | APP_PATH = File.expand_path('../../config/application', __FILE__) 5 | require File.expand_path('../../config/boot', __FILE__) 6 | require 'rails/commands' 7 | -------------------------------------------------------------------------------- /spec/generators/install_generator_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | require 'generator_spec/test_case' 4 | require 'generators/cocoon/install/install_generator' 5 | 6 | describe Cocoon::Generators::InstallGenerator do 7 | include GeneratorSpec::TestCase 8 | 9 | destination File.expand_path("../../tmp", __FILE__) 10 | 11 | context "in rails 3.0" do 12 | context "with no arguments" do 13 | before(:each) do 14 | allow(::Rails).to receive(:version) { '3.0.8' } 15 | prepare_destination 16 | run_generator 17 | end 18 | 19 | it "stubs the version correctly" do 20 | expect(::Rails.version[0..2]).to eq("3.0") 21 | end 22 | 23 | it "stubs the version correctly" do 24 | test_version = (::Rails.version[0..2].to_f >= 3.1) 25 | expect(test_version).to be_falsey 26 | end 27 | 28 | it "copies cocoon.js to the correct folder" do 29 | assert_file "public/javascripts/cocoon.js" 30 | end 31 | end 32 | end 33 | 34 | context "in rails 3.1" do 35 | context "with no arguments" do 36 | before(:each) do 37 | allow(::Rails).to receive(:version) { '3.1.0' } 38 | prepare_destination 39 | run_generator 40 | end 41 | 42 | it "does not copy cocoon.js" do 43 | assert_no_file "public/javascripts/cocoon.js" 44 | end 45 | end 46 | end 47 | 48 | end 49 | -------------------------------------------------------------------------------- /spec/integration/navigation_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | describe "Navigation", :type => :request do 4 | # include Capybara 5 | 6 | it "should be a valid app" do 7 | expect(::Rails.application).to be_a(Dummy::Application) 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | # Configure Rails Envinronment 2 | ENV["RAILS_ENV"] = "test" 3 | 4 | # only start SimpleCov on ruby 1.9.x 5 | if RUBY_VERSION[0..2].to_f >= 1.9 6 | require 'simplecov' 7 | SimpleCov.start 8 | end 9 | 10 | 11 | require File.expand_path("../dummy/config/environment.rb", __FILE__) 12 | require "rspec/rails" 13 | 14 | 15 | ActionMailer::Base.delivery_method = :test 16 | ActionMailer::Base.perform_deliveries = true 17 | ActionMailer::Base.default_url_options[:host] = "test.com" 18 | 19 | Rails.backtrace_cleaner.remove_silencers! 20 | 21 | ## Configure capybara for integration testing 22 | #require "capybara/rails" 23 | #Capybara.default_driver = :rack_test 24 | #Capybara.default_selector = :css 25 | 26 | # Run any available migration 27 | ActiveRecord::Migrator.migrate File.expand_path("../dummy/db/migrate/", __FILE__) 28 | 29 | # Load support files 30 | Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f } 31 | 32 | RSpec.configure do |config| 33 | # Remove this line if you don't want RSpec's should and should_not 34 | # methods or matchers 35 | require 'rspec/expectations' 36 | config.include RSpec::Matchers 37 | 38 | # == Mock Framework 39 | config.mock_with :rspec 40 | end 41 | -------------------------------------------------------------------------------- /spec/support/i18n.rb: -------------------------------------------------------------------------------- 1 | RSpec.configure do |config| 2 | config.after(:each) { I18n.reload! } 3 | end 4 | -------------------------------------------------------------------------------- /spec/support/rails_version_helper.rb: -------------------------------------------------------------------------------- 1 | def rails4? 2 | Rails.version.start_with? '4' 3 | end -------------------------------------------------------------------------------- /spec/support/shared_examples.rb: -------------------------------------------------------------------------------- 1 | # -*- encoding : utf-8 -*- 2 | shared_examples_for "a correctly rendered add link" do |options| 3 | context "the rendered link" do 4 | before do 5 | default_options = { 6 | href: '#', 7 | class: 'add_fields', 8 | template: "form", 9 | association: 'comment', 10 | associations: 'comments', 11 | text: 'add something', 12 | extra_attributes: {} 13 | } 14 | @options = default_options.merge options 15 | 16 | doc = Nokogiri::HTML(@html) 17 | @link = doc.at('a') 18 | end 19 | it 'has a correct href' do 20 | expect(@link.attribute('href').value).to eq(@options[:href]) 21 | end 22 | it 'has a correct class' do 23 | expect(@link.attribute('class').value).to eq(@options[:class]) 24 | end 25 | it 'has a correct template' do 26 | expect(@link.attribute('data-association-insertion-template').value).to eq(@options[:template]) 27 | end 28 | it 'has a correct associations' do 29 | expect(@link.attribute('data-association').value).to eq(@options[:association]) 30 | expect(@link.attribute('data-associations').value).to eq(@options[:associations]) 31 | end 32 | it 'has the correct text' do 33 | expect(@link.text).to eq(@options[:text]) 34 | end 35 | it 'sets extra attributes correctly' do 36 | @options[:extra_attributes].each do |key, value| 37 | expect(@link.attribute(key).value).to eq(value) 38 | end 39 | end 40 | 41 | end 42 | end 43 | 44 | shared_examples_for "a correctly rendered remove link" do |options| 45 | context "the rendered link" do 46 | before do 47 | default_options = { 48 | href: '#', 49 | class: 'remove_fields dynamic', 50 | text: 'remove something', 51 | extra_attributes: {} 52 | } 53 | @options = default_options.merge options 54 | 55 | doc = Nokogiri::HTML(@html) 56 | @link = doc.at('a') 57 | end 58 | it 'has a correct href' do 59 | expect(@link.attribute('href').value).to eq(@options[:href]) 60 | end 61 | it 'has a correct class' do 62 | expect(@link.attribute('class').value).to eq(@options[:class]) 63 | end 64 | it 'has the correct text' do 65 | expect(@link.text).to eq(@options[:text]) 66 | end 67 | it 'sets extra attributes correctly' do 68 | @options[:extra_attributes].each do |key, value| 69 | expect(@link.attribute(key).value).to eq(value) 70 | end 71 | end 72 | end 73 | end 74 | --------------------------------------------------------------------------------