rmails 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (332) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +20 -0
  3. data/Gemfile +24 -0
  4. data/Gemfile.lock +167 -0
  5. data/LICENSE.txt +20 -0
  6. data/README.markdown +9 -0
  7. data/Rakefile +31 -0
  8. data/Rakefile1 +9 -0
  9. data/Vagrantfile +51 -0
  10. data/app/assets/images/arrow_bottom.gif +0 -0
  11. data/app/assets/images/arrow_right.gif +0 -0
  12. data/app/assets/images/at-sign.png +0 -0
  13. data/app/assets/images/checkerboard.gif +0 -0
  14. data/app/assets/images/glyphicons-halflings-white.png +0 -0
  15. data/app/assets/images/glyphicons-halflings.png +0 -0
  16. data/app/assets/images/icon_draft.gif +0 -0
  17. data/app/assets/images/icon_layout.gif +0 -0
  18. data/app/assets/images/icon_move.gif +0 -0
  19. data/app/assets/images/icon_regular.gif +0 -0
  20. data/app/assets/images/icon_snippet.gif +0 -0
  21. data/app/assets/images/nav_arrow.png +0 -0
  22. data/app/assets/images/x.png +0 -0
  23. data/app/assets/javascripts/application.coffee.erb +27 -0
  24. data/app/assets/javascripts/canjs/can.construct.proxy.js +60 -0
  25. data/app/assets/javascripts/canjs/can.construct.super.js +44 -0
  26. data/app/assets/javascripts/canjs/can.control.plugin.js +245 -0
  27. data/app/assets/javascripts/canjs/can.control.view.js +88 -0
  28. data/app/assets/javascripts/canjs/can.dojo.js +3669 -0
  29. data/app/assets/javascripts/canjs/can.dojo.min.js +66 -0
  30. data/app/assets/javascripts/canjs/can.fixture.js +1020 -0
  31. data/app/assets/javascripts/canjs/can.jquery.js +2995 -0
  32. data/app/assets/javascripts/canjs/can.jquery.min.js +52 -0
  33. data/app/assets/javascripts/canjs/can.mootools.js +3462 -0
  34. data/app/assets/javascripts/canjs/can.mootools.min.js +63 -0
  35. data/app/assets/javascripts/canjs/can.observe.attributes.js +293 -0
  36. data/app/assets/javascripts/canjs/can.observe.backup.js +368 -0
  37. data/app/assets/javascripts/canjs/can.observe.delegate.js +359 -0
  38. data/app/assets/javascripts/canjs/can.observe.setter.js +58 -0
  39. data/app/assets/javascripts/canjs/can.observe.validations.js +374 -0
  40. data/app/assets/javascripts/canjs/can.view.modifiers.js +292 -0
  41. data/app/assets/javascripts/canjs/can.yui.js +3530 -0
  42. data/app/assets/javascripts/canjs/can.yui.min.js +65 -0
  43. data/app/assets/javascripts/canjs/can.zepto.js +3426 -0
  44. data/app/assets/javascripts/canjs/can.zepto.min.js +62 -0
  45. data/app/assets/javascripts/controls/admins.coffee.erb +105 -0
  46. data/app/assets/javascripts/controls/aliases.coffee.erb +91 -0
  47. data/app/assets/javascripts/controls/domains.coffee.erb +115 -0
  48. data/app/assets/javascripts/controls/settings.coffee.erb +47 -0
  49. data/app/assets/javascripts/controls/users.coffee.erb +94 -0
  50. data/app/assets/javascripts/lib/facebox.js +311 -0
  51. data/app/assets/javascripts/lib/html5.js +2 -0
  52. data/app/assets/javascripts/lib/jquery.js +9301 -0
  53. data/app/assets/javascripts/lib/jquery_formparams.js +108 -0
  54. data/app/assets/javascripts/lib/jquery_input_hint.js +20 -0
  55. data/app/assets/javascripts/lib/jquery_paginate.js +120 -0
  56. data/app/assets/javascripts/lib/jquery_ui_custom.js +6 -0
  57. data/app/assets/javascripts/lib/json2.js +487 -0
  58. data/app/assets/javascripts/lib/utils.coffee.erb +48 -0
  59. data/app/assets/javascripts/models/admin.coffee.erb +42 -0
  60. data/app/assets/javascripts/models/alias.coffee.erb +28 -0
  61. data/app/assets/javascripts/models/domain.coffee.erb +39 -0
  62. data/app/assets/javascripts/models/property.coffee.erb +18 -0
  63. data/app/assets/javascripts/models/user.coffee.erb +29 -0
  64. data/app/assets/stylesheets/application.sass +156 -0
  65. data/app/assets/stylesheets/base.css.sass +243 -0
  66. data/app/assets/stylesheets/facebox.css +80 -0
  67. data/app/assets/stylesheets/lib/bootstrap.css +9 -0
  68. data/app/assets/stylesheets/twitter/bootstrap-responsive.scss +1 -0
  69. data/app/assets/stylesheets/twitter/bootstrap.scss +63 -0
  70. data/app/assets/stylesheets/twitter/bootstrap/_accordion.scss +34 -0
  71. data/app/assets/stylesheets/twitter/bootstrap/_alerts.scss +79 -0
  72. data/app/assets/stylesheets/twitter/bootstrap/_breadcrumbs.scss +24 -0
  73. data/app/assets/stylesheets/twitter/bootstrap/_button-groups.scss +229 -0
  74. data/app/assets/stylesheets/twitter/bootstrap/_buttons.scss +228 -0
  75. data/app/assets/stylesheets/twitter/bootstrap/_carousel.scss +158 -0
  76. data/app/assets/stylesheets/twitter/bootstrap/_close.scss +32 -0
  77. data/app/assets/stylesheets/twitter/bootstrap/_code.scss +61 -0
  78. data/app/assets/stylesheets/twitter/bootstrap/_component-animations.scss +22 -0
  79. data/app/assets/stylesheets/twitter/bootstrap/_dropdowns.scss +237 -0
  80. data/app/assets/stylesheets/twitter/bootstrap/_forms.scss +689 -0
  81. data/app/assets/stylesheets/twitter/bootstrap/_grid.scss +21 -0
  82. data/app/assets/stylesheets/twitter/bootstrap/_hero-unit.scss +25 -0
  83. data/app/assets/stylesheets/twitter/bootstrap/_labels-badges.scss +83 -0
  84. data/app/assets/stylesheets/twitter/bootstrap/_layouts.scss +16 -0
  85. data/app/assets/stylesheets/twitter/bootstrap/_media.scss +55 -0
  86. data/app/assets/stylesheets/twitter/bootstrap/_mixins.scss +690 -0
  87. data/app/assets/stylesheets/twitter/bootstrap/_modals.scss +95 -0
  88. data/app/assets/stylesheets/twitter/bootstrap/_navbar.scss +497 -0
  89. data/app/assets/stylesheets/twitter/bootstrap/_navs.scss +409 -0
  90. data/app/assets/stylesheets/twitter/bootstrap/_pager.scss +43 -0
  91. data/app/assets/stylesheets/twitter/bootstrap/_pagination.scss +123 -0
  92. data/app/assets/stylesheets/twitter/bootstrap/_popovers.scss +133 -0
  93. data/app/assets/stylesheets/twitter/bootstrap/_progress-bars.scss +122 -0
  94. data/app/assets/stylesheets/twitter/bootstrap/_reset.scss +216 -0
  95. data/app/assets/stylesheets/twitter/bootstrap/_responsive-1200px-min.scss +28 -0
  96. data/app/assets/stylesheets/twitter/bootstrap/_responsive-767px-max.scss +193 -0
  97. data/app/assets/stylesheets/twitter/bootstrap/_responsive-768px-979px.scss +19 -0
  98. data/app/assets/stylesheets/twitter/bootstrap/_responsive-navbar.scss +189 -0
  99. data/app/assets/stylesheets/twitter/bootstrap/_responsive-utilities.scss +74 -0
  100. data/app/assets/stylesheets/twitter/bootstrap/_scaffolding.scss +53 -0
  101. data/app/assets/stylesheets/twitter/bootstrap/_sprites.scss +197 -0
  102. data/app/assets/stylesheets/twitter/bootstrap/_tables.scss +235 -0
  103. data/app/assets/stylesheets/twitter/bootstrap/_thumbnails.scss +53 -0
  104. data/app/assets/stylesheets/twitter/bootstrap/_tooltip.scss +70 -0
  105. data/app/assets/stylesheets/twitter/bootstrap/_type.scss +247 -0
  106. data/app/assets/stylesheets/twitter/bootstrap/_utilities.scss +45 -0
  107. data/app/assets/stylesheets/twitter/bootstrap/_variables.scss +301 -0
  108. data/app/assets/stylesheets/twitter/bootstrap/_wells.scss +29 -0
  109. data/app/assets/stylesheets/twitter/bootstrap/responsive.scss +48 -0
  110. data/app/controllers/admin_users_controller.rb +62 -0
  111. data/app/controllers/aliases_controller.rb +35 -0
  112. data/app/controllers/application_controller.rb +20 -0
  113. data/app/controllers/domains_controller.rb +48 -0
  114. data/app/controllers/server_controller.rb +28 -0
  115. data/app/controllers/users_controller.rb +35 -0
  116. data/app/helpers/admin_users_helper.rb +11 -0
  117. data/app/helpers/application_helper.rb +2 -0
  118. data/app/helpers/domains_helper.rb +25 -0
  119. data/app/helpers/server_helper.rb +30 -0
  120. data/app/mailers/.gitkeep +0 -0
  121. data/app/models/.gitkeep +0 -0
  122. data/app/models/admin_user.rb +54 -0
  123. data/app/models/certificate_manager.rb +46 -0
  124. data/app/models/property.rb +103 -0
  125. data/app/models/property/awstats.rb +15 -0
  126. data/app/models/property/dovecot.rb +61 -0
  127. data/app/models/property/dspam.rb +45 -0
  128. data/app/models/property/nginx.rb +47 -0
  129. data/app/models/property/postfix.rb +64 -0
  130. data/app/models/property_value_validator.rb +41 -0
  131. data/app/models/system_manager.rb +88 -0
  132. data/app/models/virtual_alias.rb +13 -0
  133. data/app/models/virtual_domain.rb +15 -0
  134. data/app/models/virtual_user.rb +51 -0
  135. data/app/views/admin_users/_form.html.haml +21 -0
  136. data/app/views/admin_users/first.html.haml +12 -0
  137. data/app/views/admin_users/index.html.haml +61 -0
  138. data/app/views/aliases/_form.html.haml +11 -0
  139. data/app/views/aliases/_list.html.haml +0 -0
  140. data/app/views/devise/confirmations/new.html.haml +9 -0
  141. data/app/views/devise/mailer/confirmation_instructions.html.haml +4 -0
  142. data/app/views/devise/mailer/reset_password_instructions.html.haml +6 -0
  143. data/app/views/devise/mailer/unlock_instructions.html.haml +5 -0
  144. data/app/views/devise/passwords/edit.html.haml +14 -0
  145. data/app/views/devise/passwords/new.html.haml +12 -0
  146. data/app/views/devise/registrations/edit.html.haml +18 -0
  147. data/app/views/devise/registrations/new.html.haml +10 -0
  148. data/app/views/devise/sessions/new.html.haml +16 -0
  149. data/app/views/devise/shared/_links.haml +17 -0
  150. data/app/views/devise/unlocks/new.html.haml +11 -0
  151. data/app/views/domains/_fields.html.haml +0 -0
  152. data/app/views/domains/_form.html.haml +7 -0
  153. data/app/views/domains/index.html.haml +133 -0
  154. data/app/views/domains/show.html.haml +1 -0
  155. data/app/views/layouts/_nav.html.haml +3 -0
  156. data/app/views/layouts/application.html.haml +29 -0
  157. data/app/views/server/_certificates.html.haml +10 -0
  158. data/app/views/server/_dovecot.html.haml +27 -0
  159. data/app/views/server/_dspam.html.haml +9 -0
  160. data/app/views/server/_postfix_info.html.haml +5 -0
  161. data/app/views/server/_postfix_test.html.haml +5 -0
  162. data/app/views/server/_status.html.haml +11 -0
  163. data/app/views/server/index.html.haml +36 -0
  164. data/app/views/users/_form.html.haml +11 -0
  165. data/app/views/users/_list.html.haml +0 -0
  166. data/bin/rmails +43 -0
  167. data/config.ru +4 -0
  168. data/config/application.rb +62 -0
  169. data/config/boot.rb +6 -0
  170. data/config/environment.rb +5 -0
  171. data/config/environments/development.rb +37 -0
  172. data/config/environments/production.rb +67 -0
  173. data/config/environments/test.rb +37 -0
  174. data/config/initializers/backtrace_silencers.rb +7 -0
  175. data/config/initializers/devise.rb +240 -0
  176. data/config/initializers/devise_encryptable.rb +37 -0
  177. data/config/initializers/devise_models.rb +86 -0
  178. data/config/initializers/inflections.rb +15 -0
  179. data/config/initializers/mime_types.rb +5 -0
  180. data/config/initializers/secret_token.rb +7 -0
  181. data/config/initializers/session_store.rb +8 -0
  182. data/config/initializers/simple_form.rb +142 -0
  183. data/config/initializers/simple_form_bootstrap.rb +45 -0
  184. data/config/initializers/wrap_parameters.rb +14 -0
  185. data/config/locales/cz.yml +45 -0
  186. data/config/locales/devise.cz.yml +47 -0
  187. data/config/locales/devise.en.yml +60 -0
  188. data/config/locales/en.yml +5 -0
  189. data/config/locales/server/cz.yml +14 -0
  190. data/config/locales/server/en.yml +7 -0
  191. data/config/locales/server/help/dovecot/cz.yml +21 -0
  192. data/config/locales/server/help/dovecot/en.yml +18 -0
  193. data/config/locales/server/help/dspam/cz.yml +10 -0
  194. data/config/locales/server/help/dspam/en.yml +4 -0
  195. data/config/locales/server/key/dovecot/cz.yml +23 -0
  196. data/config/locales/server/key/dovecot/en.yml +20 -0
  197. data/config/locales/server/key/dspam/cz.yml +10 -0
  198. data/config/locales/server/key/dspam/en.yml +4 -0
  199. data/config/locales/simple_form.en.yml +26 -0
  200. data/config/locales/views/admin_users/cz.yml +25 -0
  201. data/config/locales/views/admin_users/en.yml +5 -0
  202. data/config/locales/views/aliases/cz.yml +17 -0
  203. data/config/locales/views/aliases/en.yml +1 -0
  204. data/config/locales/views/devise/cz.yml +26 -0
  205. data/config/locales/views/devise/en.yml +13 -0
  206. data/config/locales/views/domains/cz.yml +15 -0
  207. data/config/locales/views/domains/en.yml +15 -0
  208. data/config/locales/views/server/cz.yml +19 -0
  209. data/config/locales/views/server/en.yml +3 -0
  210. data/config/locales/views/users/cz.yml +18 -0
  211. data/config/locales/views/users/en.yml +1 -0
  212. data/config/routes.rb +80 -0
  213. data/db/migrate/20121112201233_virtual_domain.rb +11 -0
  214. data/db/migrate/20121112201247_virtual_alias.rb +10 -0
  215. data/db/migrate/20121112201341_virtual_user.rb +34 -0
  216. data/db/migrate/20121112201359_create_admin_user.rb +30 -0
  217. data/db/migrate/20121112201411_server_configuration.rb +13 -0
  218. data/db/migrate/20130304083938_join_domains_users.rb +12 -0
  219. data/db/migrate/20130311214040_create_versions.rb +18 -0
  220. data/db/seeds.rb +45 -0
  221. data/lib/devise-encryptable.rb +1 -0
  222. data/lib/rmails.rb +5 -0
  223. data/lib/rmails/installer.rb +37 -0
  224. data/lib/rmails/version.rb +3 -0
  225. data/lib/tasks/.gitkeep +0 -0
  226. data/lib/templates/haml/scaffold/_form.html.haml +10 -0
  227. data/locals +0 -0
  228. data/log/.gitkeep +0 -0
  229. data/public/404.html +26 -0
  230. data/public/422.html +26 -0
  231. data/public/500.html +25 -0
  232. data/public/favicon.ico +0 -0
  233. data/public/fonts/London.eot +0 -0
  234. data/public/fonts/London.otf +0 -0
  235. data/public/fonts/London.woff +0 -0
  236. data/public/fonts/LondonBold.otf +0 -0
  237. data/public/robots.txt +5 -0
  238. data/rmails.gemspec +35 -0
  239. data/script/prepflog.pl +576 -0
  240. data/script/rails +6 -0
  241. data/system/config/automateit_env.rb +16 -0
  242. data/system/config/fields.yml +48 -0
  243. data/system/config/tags.yml +39 -0
  244. data/system/dist/README_AutomateIt_dist.txt +20 -0
  245. data/system/dist/amavis/spamassassin.cf.erb +85 -0
  246. data/system/dist/amavis/user.erb +33 -0
  247. data/system/dist/awstats/awstats.mail.conf.erb +41 -0
  248. data/system/dist/awstats/prepflog.pl +576 -0
  249. data/system/dist/dovecot/dovecot-sql.conf.ext.erb +14 -0
  250. data/system/dist/dovecot/dovecot.conf.erb +297 -0
  251. data/system/dist/dovecot/old_dovecot.conf.erb +63 -0
  252. data/system/dist/dspam/conf.erb +96 -0
  253. data/system/dist/dspam/pgsql.conf +33 -0
  254. data/system/dist/nginx/awstats.erb +17 -0
  255. data/system/dist/nginx/rmails.erb +40 -0
  256. data/system/dist/postfix/email2email.cf.erb +5 -0
  257. data/system/dist/postfix/main.cf.erb +118 -0
  258. data/system/dist/postfix/master.cf.erb +74 -0
  259. data/system/dist/postfix/sasl.conf.erb +3 -0
  260. data/system/dist/postfix/sender_login_maps.cf.erb +5 -0
  261. data/system/dist/postfix/virtual_alias_maps.cf.erb +5 -0
  262. data/system/dist/postfix/virtual_mailbox_domains.cf.erb +5 -0
  263. data/system/dist/postfix/virtual_mailbox_maps.cf.erb +5 -0
  264. data/system/dist/postgresql/postgresql.conf.erb +54 -0
  265. data/system/dist/rmails/Gemfile.1 +8 -0
  266. data/system/dist/rmails/Gemfile.2 +24 -0
  267. data/system/dist/rmails/database.yml.erb +15 -0
  268. data/system/dist/sudoers +37 -0
  269. data/system/lib/README_AutomateIt_lib.txt +22 -0
  270. data/system/lib/dkim_key.rb +9 -0
  271. data/system/lib/smtpd_key.rb +39 -0
  272. data/system/lib/ssl.rb +23 -0
  273. data/system/recipes/01_prepare_server.rb +84 -0
  274. data/system/recipes/02_setup_database.rb +65 -0
  275. data/system/recipes/03_setup_postfix.rb +124 -0
  276. data/system/recipes/04_setup_dovecot.rb +78 -0
  277. data/system/recipes/05_setup_nginx.rb +29 -0
  278. data/system/recipes/06_setup_dspam.rb +24 -0
  279. data/system/recipes/07_setup_amavis.rb +16 -0
  280. data/system/recipes/08_setup_spamassassin.rb +22 -0
  281. data/system/recipes/09_setup_awstats.rb +49 -0
  282. data/system/recipes/XX_start_services.rb +5 -0
  283. data/test/fixtures/.gitkeep +0 -0
  284. data/test/functional/.gitkeep +0 -0
  285. data/test/functional/aliases_controller_test.rb +7 -0
  286. data/test/functional/domains_controller_test.rb +7 -0
  287. data/test/functional/users_controller_test.rb +7 -0
  288. data/test/integration/.gitkeep +0 -0
  289. data/test/performance/browsing_test.rb +12 -0
  290. data/test/test_helper.rb +13 -0
  291. data/test/unit/.gitkeep +0 -0
  292. data/test/unit/helpers/aliases_helper_test.rb +4 -0
  293. data/test/unit/helpers/domains_helper_test.rb +4 -0
  294. data/test/unit/helpers/users_helper_test.rb +4 -0
  295. data/vendor/assets/javascripts/.gitkeep +0 -0
  296. data/vendor/assets/javascripts/canjs/can.construct.proxy.js +60 -0
  297. data/vendor/assets/javascripts/canjs/can.construct.super.js +44 -0
  298. data/vendor/assets/javascripts/canjs/can.control.plugin.js +245 -0
  299. data/vendor/assets/javascripts/canjs/can.control.view.js +88 -0
  300. data/vendor/assets/javascripts/canjs/can.dojo.js +3669 -0
  301. data/vendor/assets/javascripts/canjs/can.dojo.min.js +66 -0
  302. data/vendor/assets/javascripts/canjs/can.fixture.js +1020 -0
  303. data/vendor/assets/javascripts/canjs/can.jquery.js +2995 -0
  304. data/vendor/assets/javascripts/canjs/can.jquery.min.js +52 -0
  305. data/vendor/assets/javascripts/canjs/can.mootools.js +3462 -0
  306. data/vendor/assets/javascripts/canjs/can.mootools.min.js +63 -0
  307. data/vendor/assets/javascripts/canjs/can.observe.attributes.js +293 -0
  308. data/vendor/assets/javascripts/canjs/can.observe.backup.js +368 -0
  309. data/vendor/assets/javascripts/canjs/can.observe.delegate.js +359 -0
  310. data/vendor/assets/javascripts/canjs/can.observe.setter.js +58 -0
  311. data/vendor/assets/javascripts/canjs/can.observe.validations.js +374 -0
  312. data/vendor/assets/javascripts/canjs/can.view.modifiers.js +292 -0
  313. data/vendor/assets/javascripts/canjs/can.yui.js +3530 -0
  314. data/vendor/assets/javascripts/canjs/can.yui.min.js +65 -0
  315. data/vendor/assets/javascripts/canjs/can.zepto.js +3426 -0
  316. data/vendor/assets/javascripts/canjs/can.zepto.min.js +62 -0
  317. data/vendor/assets/javascripts/twitter/bootstrap-affix.js +104 -0
  318. data/vendor/assets/javascripts/twitter/bootstrap-alert.js +90 -0
  319. data/vendor/assets/javascripts/twitter/bootstrap-button.js +96 -0
  320. data/vendor/assets/javascripts/twitter/bootstrap-carousel.js +176 -0
  321. data/vendor/assets/javascripts/twitter/bootstrap-collapse.js +158 -0
  322. data/vendor/assets/javascripts/twitter/bootstrap-dropdown.js +150 -0
  323. data/vendor/assets/javascripts/twitter/bootstrap-modal.js +239 -0
  324. data/vendor/assets/javascripts/twitter/bootstrap-popover.js +103 -0
  325. data/vendor/assets/javascripts/twitter/bootstrap-scrollspy.js +151 -0
  326. data/vendor/assets/javascripts/twitter/bootstrap-tab.js +135 -0
  327. data/vendor/assets/javascripts/twitter/bootstrap-tooltip.js +275 -0
  328. data/vendor/assets/javascripts/twitter/bootstrap-transition.js +60 -0
  329. data/vendor/assets/javascripts/twitter/bootstrap-typeahead.js +300 -0
  330. data/vendor/assets/javascripts/twitter/my/bootstrap-typeahead.js +311 -0
  331. data/vendor/assets/stylesheets/.gitkeep +0 -0
  332. metadata +470 -0
@@ -0,0 +1,292 @@
1
+ (function(can, window, undefined){
2
+
3
+ //---- ADD jQUERY HELPERS -----
4
+ //converts jquery functions to use views
5
+ var convert, modify, isTemplate, isHTML, isDOM, getCallback,
6
+ // text and val cannot produce an element, so don't run hookups on them
7
+ noHookup = {'val':true,'text':true};
8
+
9
+ convert = function( func_name ) {
10
+ // save the old jQuery helper
11
+ var old = $.fn[func_name];
12
+
13
+ // replace it with our new helper
14
+ $.fn[func_name] = function() {
15
+
16
+ var args = can.makeArray(arguments),
17
+ callbackNum,
18
+ callback,
19
+ self = this,
20
+ result;
21
+
22
+ // if the first arg is a deferred
23
+ // wait until it finishes, and call
24
+ // modify with the result
25
+ if ( can.isDeferred(args[0]) ) {
26
+ args[0].done(function( res ) {
27
+ modify.call(self, [res], old);
28
+ })
29
+ return this;
30
+ }
31
+ //check if a template
32
+ else if ( isTemplate(args) ) {
33
+
34
+ // if we should operate async
35
+ if ((callbackNum = getCallback(args))) {
36
+ callback = args[callbackNum];
37
+ args[callbackNum] = function( result ) {
38
+ modify.call(self, [result], old);
39
+ callback.call(self, result);
40
+ };
41
+ can.view.apply(can.view, args);
42
+ return this;
43
+ }
44
+ // call view with args (there might be deferreds)
45
+ result = can.view.apply(can.view, args);
46
+
47
+ // if we got a string back
48
+ if (!can.isDeferred(result) ) {
49
+ // we are going to call the old method with that string
50
+ args = [result];
51
+ } else {
52
+ // if there is a deferred, wait until it is done before calling modify
53
+ result.done(function( res ) {
54
+ modify.call(self, [res], old);
55
+ })
56
+ return this;
57
+ }
58
+ }
59
+ return noHookup[func_name] ? old.apply(this,args) :
60
+ modify.call(this, args, old);
61
+ };
62
+ };
63
+
64
+ // modifies the content of the element
65
+ // but also will run any hookup
66
+ modify = function( args, old ) {
67
+ var res, stub, hooks;
68
+
69
+ //check if there are new hookups
70
+ for ( var hasHookups in can.view.hookups ) {
71
+ break;
72
+ }
73
+
74
+ //if there are hookups, turn into a frag
75
+ // and insert that
76
+ // by using a frag, the element can be recursively hooked up
77
+ // before insterion
78
+ if ( hasHookups && args[0] && isHTML(args[0]) ) {
79
+ args[0] = can.view.frag(args[0])
80
+ }
81
+
82
+ //then insert into DOM
83
+ res = old.apply(this, args);
84
+
85
+ return res;
86
+ };
87
+
88
+ // returns true or false if the args indicate a template is being used
89
+ // $('#foo').html('/path/to/template.ejs',{data})
90
+ // in general, we want to make sure the first arg is a string
91
+ // and the second arg is data
92
+ isTemplate = function( args ) {
93
+ // save the second arg type
94
+ var secArgType = typeof args[1];
95
+
96
+ // the first arg is a string
97
+ return typeof args[0] == "string" &&
98
+ // the second arg is an object or function
99
+ (secArgType == 'object' || secArgType == 'function') &&
100
+ // but it is not a dom element
101
+ !isDOM(args[1]);
102
+ };
103
+ // returns true if the arg is a jQuery object or HTMLElement
104
+ isDOM = function(arg){
105
+ return arg.nodeType || (arg[0] && arg[0].nodeType)
106
+ };
107
+ // returns whether the argument is some sort of HTML data
108
+ isHTML = function( arg ) {
109
+ if ( isDOM(arg) ) {
110
+ // if jQuery object or DOM node we're good
111
+ return true;
112
+ } else if ( typeof arg === "string" ) {
113
+ // if string, do a quick sanity check that we're HTML
114
+ arg = can.trim(arg);
115
+ return arg.substr(0, 1) === "<" && arg.substr(arg.length - 1, 1) === ">" && arg.length >= 3;
116
+ } else {
117
+ // don't know what you are
118
+ return false;
119
+ }
120
+ };
121
+
122
+ //returns the callback arg number if there is one (for async view use)
123
+ getCallback = function( args ) {
124
+ return typeof args[3] === 'function' ? 3 : typeof args[2] === 'function' && 2;
125
+ };
126
+
127
+ /**
128
+ * @add jQuery.fn
129
+ * @parent can.View
130
+ * Called on a jQuery collection that was rendered with can.View with pending hookups. can.View can render a
131
+ * template with hookups, but not actually perform the hookup, because it returns a string without actual DOM
132
+ * elements to hook up to. So hookup performs the hookup and clears the pending hookups, preventing errors in
133
+ * future templates.
134
+ *
135
+ * @codestart
136
+ * $(can.View('//views/recipes.ejs',recipeData)).hookup()
137
+ * @codeend
138
+ */
139
+ $.fn.hookup = function() {
140
+ can.view.frag(this);
141
+ return this;
142
+ };
143
+
144
+ /**
145
+ * @add jQuery.fn
146
+ */
147
+ can.each([
148
+ /**
149
+ * @function jQuery.fn.prepend
150
+ * @parent can.view.modifiers
151
+ *
152
+ * Extending the original [http://api.jquery.com/prepend/ jQuery().prepend()]
153
+ * to render [can.view] templates inserted at the beginning of each element in the set of matched elements.
154
+ *
155
+ * $('#test').prepend('path/to/template.ejs', { name : 'canjs' });
156
+ *
157
+ * @param {String|Object|Function} content A template filename or the id of a view script tag
158
+ * or a DOM element, array of elements, HTML string, or can object.
159
+ * @param {Object} [data] The data to render the view with.
160
+ * If rendering a view template this parameter always has to be present
161
+ * (use the empty object initializer {} for no data).
162
+ * @param {Function} [callback] A success callback to load the view asynchronously
163
+ *
164
+ * @return {jQuery|can.Deferred} The jQuery object or a [can.Deferred] if a deferred has
165
+ * been passed in data.
166
+ */
167
+ "prepend",
168
+ /**
169
+ * @function jQuery.fn.append
170
+ * @parent can.view.modifiers
171
+ *
172
+ * Extending the original [http://api.jquery.com/append/ jQuery().append()]
173
+ * to render [can.view] templates inserted at the end of each element in the set of matched elements.
174
+ *
175
+ * $('#test').append('path/to/template.ejs', { name : 'canjs' });
176
+ *
177
+ * @param {String|Object|Function} content A template filename or the id of a view script tag
178
+ * or a DOM element, array of elements, HTML string, or can object.
179
+ * @param {Object} [data] The data to render the view with.
180
+ * If rendering a view template this parameter always has to be present
181
+ * (use the empty object initializer {} for no data).
182
+ * @param {Function} [callback] A success callback to load the view asynchronously
183
+ *
184
+ * @return {jQuery|can.Deferred} The jQuery object or a [can.Deferred] if a deferred has
185
+ * been passed in data.
186
+ */
187
+ "append",
188
+ /**
189
+ * @function jQuery.fn.after
190
+ * @parent can.view.modifiers
191
+ *
192
+ * Extending the original [http://api.jquery.com/after/ jQuery().after()]
193
+ * to render [can.view] templates inserted after each element in the set of matched elements.
194
+ *
195
+ * $('#test').after('path/to/template.ejs', { name : 'canjs' });
196
+ *
197
+ * @param {String|Object|Function} content A template filename or the id of a view script tag
198
+ * or a DOM element, array of elements, HTML string, or can object.
199
+ * @param {Object} [data] The data to render the view with.
200
+ * If rendering a view template this parameter always has to be present
201
+ * (use the empty object initializer {} for no data).
202
+ * @param {Function} [callback] A success callback to load the view asynchronously
203
+ *
204
+ * @return {jQuery|can.Deferred} The jQuery object or a [can.Deferred] if a deferred has
205
+ * been passed in data.
206
+ */
207
+ "after",
208
+ /**
209
+ * @function jQuery.fn.before
210
+ * @parent can.view.modifiers
211
+ *
212
+ * Extending the original [http://api.jquery.com/before/ jQuery().before()]
213
+ * to render [can.view] templates inserted before each element in the set of matched elements.
214
+ *
215
+ * $('#test').before('path/to/template.ejs', { name : 'canjs' });
216
+ *
217
+ * @param {String|Object|Function} content A template filename or the id of a view script tag
218
+ * or a DOM element, array of elements, HTML string, or can object.
219
+ * @param {Object} [data] The data to render the view with.
220
+ * If rendering a view template this parameter always has to be present
221
+ * (use the empty object initializer {} for no data).
222
+ * @param {Function} [callback] A success callback to load the view asynchronously
223
+ *
224
+ * @return {jQuery|can.Deferred} The jQuery object or a [can.Deferred] if a deferred has
225
+ * been passed in data.
226
+ */
227
+ "before",
228
+ /**
229
+ * @function jQuery.fn.text
230
+ * @parent can.view.modifiers
231
+ *
232
+ * Extending the original [http://api.jquery.com/text/ jQuery().text()]
233
+ * to render [can.View] templates as the content of each matched element.
234
+ * Unlike [jQuery.fn.html] jQuery.fn.text also works with XML, escaping the provided
235
+ * string as necessary.
236
+ *
237
+ * $('#test').text('path/to/template.ejs', { name : 'canjs' });
238
+ *
239
+ * @param {String|Object|Function} content A template filename or the id of a view script tag
240
+ * or a DOM element, array of elements, HTML string, or can object.
241
+ * @param {Object} [data] The data to render the view with.
242
+ * If rendering a view template this parameter always has to be present
243
+ * (use the empty object initializer {} for no data).
244
+ * @param {Function} [callback] A success callback to load the view asynchronously
245
+ *
246
+ * @return {jQuery|can.Deferred} The jQuery object or a [can.Deferred] if a deferred has
247
+ * been passed in data.
248
+ */
249
+ "text",
250
+ /**
251
+ * @function jQuery.fn.html
252
+ * @parent can.view.modifiers
253
+ *
254
+ * Extending the original [http://api.jquery.com/html/ jQuery().html()]
255
+ * to render [can.view] templates as the content of each matched element.
256
+ *
257
+ * $('#test').html('path/to/template.ejs', { name : 'canjs' });
258
+ *
259
+ * @param {String|Object|Function} content A template filename or the id of a view script tag
260
+ * or a DOM element, array of elements, HTML string, or can object.
261
+ * @param {Object} [data] The data to render the view with.
262
+ * If rendering a view template this parameter always has to be present
263
+ * (use the empty object initializer {} for no data).
264
+ * @param {Function} [callback] A success callback to load the view asynchronously
265
+ *
266
+ * @return {jQuery|can.Deferred} The jQuery object or a [can.Deferred] if a deferred has
267
+ * been passed in data.
268
+ */
269
+ "html",
270
+ /**
271
+ * @function jQuery.fn.replaceWith
272
+ * @parent can.view.modifiers
273
+ *
274
+ * Extending the original [http://api.jquery.com/replaceWith/ jQuery().replaceWith()]
275
+ * to render [can.view] templates replacing each element in the set of matched elements.
276
+ *
277
+ * $('#test').replaceWith('path/to/template.ejs', { name : 'canjs' });
278
+ *
279
+ * @param {String|Object|Function} content A template filename or the id of a view script tag
280
+ * or a DOM element, array of elements, HTML string, or can object.
281
+ * @param {Object} [data] The data to render the view with.
282
+ * If rendering a view template this parameter always has to be present
283
+ * (use the empty object initializer {} for no data).
284
+ * @param {Function} [callback] A success callback to load the view asynchronously
285
+ *
286
+ * @return {jQuery|can.Deferred} The jQuery object or a [can.Deferred] if a deferred has
287
+ * been passed in data.
288
+ */
289
+ "replaceWith", "val"],function(func){
290
+ convert(func);
291
+ });
292
+ })(this.can, this )
@@ -0,0 +1,3530 @@
1
+ (function(can, window, undefined){
2
+ YUI().add("can", function(Y) {
3
+ can.Y = Y;
4
+
5
+ // event.js
6
+ // ---------
7
+ // _Basic event wrapper._
8
+ can.addEvent = function(event, fn){
9
+ if(!this.__bindEvents){
10
+ this.__bindEvents = {};
11
+ }
12
+ var eventName = event.split(".")[0];
13
+
14
+ if(!this.__bindEvents[eventName]){
15
+ this.__bindEvents[eventName] = [];
16
+ }
17
+ this.__bindEvents[eventName].push({
18
+ handler: fn,
19
+ name: event
20
+ });
21
+ return this;
22
+ };
23
+ can.removeEvent = function(event, fn){
24
+ if(!this.__bindEvents){
25
+ return;
26
+ }
27
+ var i =0,
28
+ events = this.__bindEvents[event.split(".")[0]],
29
+ ev;
30
+ while(i < events.length){
31
+ ev = events[i]
32
+ if((fn && ev.handler === fn) || (!fn && ev.name === event)){
33
+ events.splice(i, 1);
34
+ } else {
35
+ i++;
36
+ }
37
+ }
38
+ return this;
39
+ };
40
+ can.dispatch = function(event){
41
+ if(!this.__bindEvents){
42
+ return;
43
+ }
44
+
45
+ var eventName = event.type.split(".")[0],
46
+ handlers = (this.__bindEvents[eventName] || []).slice(0),
47
+ self= this,
48
+ args = [event].concat(event.data || []);
49
+
50
+ can.each(handlers, function(ev){
51
+ event.data = args.slice(1);
52
+ ev.handler.apply(self, args);
53
+ });
54
+ }
55
+
56
+ ;
57
+
58
+ can.each = function (elements, callback, context) {
59
+ var i = 0,
60
+ key;
61
+ if (elements) {
62
+ if (typeof elements.length == 'number' && elements.pop) {
63
+ elements.attr && elements.attr('length');
64
+ for (var len = elements.length; i < len; i++) {
65
+ if (callback.call(context || elements[i], elements[i], i, elements) === false) {
66
+ break;
67
+ }
68
+ }
69
+ } else {
70
+ for (key in elements) {
71
+ if (callback.call(context || elements[i], elements[key], key, elements) === false) {
72
+ break;
73
+ }
74
+ }
75
+ }
76
+ }
77
+ return elements;
78
+ }
79
+ ;
80
+
81
+ // ---------
82
+ // _YUI node list._
83
+ // `can.Y` is set as part of the build process.
84
+ // `YUI().use('*')` is called for when `YUI` is statically loaded (like when running tests).
85
+ var Y = can.Y = can.Y || YUI().use('*');
86
+
87
+ // Map string helpers.
88
+ can.trim = function( s ) {
89
+ return Y.Lang.trim(s);
90
+ }
91
+
92
+ // Map array helpers.
93
+ can.makeArray = function( arr ) {
94
+ return Y.Array(arr);
95
+ };
96
+ can.isArray = Y.Lang.isArray;
97
+ can.inArray = function( item, arr ) {
98
+ return Y.Array.indexOf(arr, item);
99
+ };
100
+
101
+ can.map = function( arr, fn ) {
102
+ return Y.Array.map(can.makeArray(arr || []), fn);
103
+ };
104
+
105
+ // Map object helpers.
106
+ can.extend = function( first ) {
107
+ var deep = first === true ? 1 : 0,
108
+ target = arguments[deep],
109
+ i = deep + 1,
110
+ arg;
111
+ for (; arg = arguments[i]; i++ ) {
112
+ Y.mix(target, arg, true, null, null, !! deep);
113
+ }
114
+ return target;
115
+ }
116
+ can.param = function( object ) {
117
+ return Y.QueryString.stringify(object, {arrayKey: true})
118
+ }
119
+ can.isEmptyObject = function( object ) {
120
+ return Y.Object.isEmpty(object);
121
+ }
122
+
123
+ // Map function helpers.
124
+ can.proxy = function( func, context ) {
125
+ return Y.bind.apply(Y, arguments);
126
+ }
127
+ can.isFunction = function( f ) {
128
+ return Y.Lang.isFunction(f);
129
+ }
130
+
131
+ // Element -- get the wrapped helper.
132
+ var prepareNodeList = function( nodelist ) {
133
+ nodelist.each(function( node, i ) {
134
+ nodelist[i] = node.getDOMNode();
135
+ });
136
+ nodelist.length = nodelist.size();
137
+ return nodelist;
138
+ }
139
+ can.$ = function( selector ) {
140
+ if ( selector === window ) {
141
+ return window;
142
+ } else if ( selector instanceof Y.NodeList ) {
143
+ return prepareNodeList(selector);
144
+ } else if ( typeof selector === "object" && !can.isArray(selector) && typeof selector.nodeType === "undefined" && !selector.getDOMNode ) {
145
+ return selector;
146
+ } else {
147
+ return prepareNodeList(Y.all(selector));
148
+ }
149
+ }
150
+ can.get = function( wrapped, index ) {
151
+ return wrapped._nodes[index];
152
+ }
153
+ can.buildFragment = function( html, node ) {
154
+ var owner = node && node.ownerDocument,
155
+ frag = Y.Node.create(html, owner);
156
+ frag = (frag && frag.getDOMNode()) || document.createDocumentFragment();
157
+ if ( frag.nodeType !== 11 ) {
158
+ var tmp = document.createDocumentFragment();
159
+ tmp.appendChild(frag)
160
+ frag = tmp;
161
+ }
162
+ return frag;
163
+ }
164
+ can.append = function( wrapped, html ) {
165
+ wrapped.each(function( node ) {
166
+ if ( typeof html === 'string' ) {
167
+ html = can.buildFragment(html, node)
168
+ }
169
+ node.append(html)
170
+ });
171
+ }
172
+ can.addClass = function( wrapped, className ) {
173
+ return wrapped.addClass(className);
174
+ }
175
+ can.data = function( wrapped, key, value ) {
176
+ if ( value === undefined ) {
177
+
178
+ return wrapped.item(0).getData(key)
179
+ } else {
180
+ return wrapped.item(0).setData(key, value)
181
+ }
182
+ }
183
+ can.remove = function( wrapped ) {
184
+ return wrapped.remove() && wrapped.destroy();
185
+ }
186
+ // Destroyed method.
187
+ can._yNodeDestroy = can._yNodeDestroy || Y.Node.prototype.destroy;
188
+ Y.Node.prototype.destroy = function() {
189
+ can.trigger(this, "destroyed", [], false)
190
+ can._yNodeDestroy.apply(this, arguments)
191
+ }
192
+ // Let `nodelist` know about the new destroy...
193
+ Y.NodeList.addMethod("destroy", Y.Node.prototype.destroy);
194
+
195
+ // Ajax
196
+ var optionsMap = {
197
+ type: "method",
198
+ success: undefined,
199
+ error: undefined
200
+ }
201
+ var updateDeferred = function( request, d ) {
202
+ // `YUI` only returns a request if it is asynchronous.
203
+ if ( request && request.io ) {
204
+ var xhr = request.io;
205
+ for ( var prop in xhr ) {
206
+ if ( typeof d[prop] == 'function' ) {
207
+ d[prop] = function() {
208
+ xhr[prop].apply(xhr, arguments)
209
+ }
210
+ } else {
211
+ d[prop] = prop[xhr]
212
+ }
213
+ }
214
+ }
215
+ }
216
+ can.ajax = function( options ) {
217
+ var d = can.Deferred(),
218
+ requestOptions = can.extend({}, options);
219
+
220
+ for ( var option in optionsMap ) {
221
+ if ( requestOptions[option] !== undefined ) {
222
+ requestOptions[optionsMap[option]] = requestOptions[option];
223
+ delete requestOptions[option]
224
+ }
225
+ }
226
+ requestOptions.sync = !options.async;
227
+
228
+ var success = options.success,
229
+ error = options.error;
230
+
231
+ requestOptions.on = {
232
+ success: function( transactionid, response ) {
233
+ var data = response.responseText;
234
+ if ( options.dataType === 'json' ) {
235
+ data = eval("(" + data + ")")
236
+ }
237
+ updateDeferred(request, d);
238
+ d.resolve(data, "success", request);
239
+ success && success(data, "success", request);
240
+ },
241
+ failure: function( transactionid, response ) {
242
+ updateDeferred(request, d);
243
+ d.reject(request, "error");
244
+ error && error(request, "error");
245
+ }
246
+ };
247
+
248
+ var request = Y.io(requestOptions.url, requestOptions);
249
+ updateDeferred(request, d);
250
+ return d;
251
+
252
+ }
253
+
254
+ // Events - The `id` of the `function` to be bound, used as an expando on the `function`
255
+ // so we can lookup it's `remove` object.
256
+ var id = 0,
257
+ // Takes a node list, goes through each node
258
+ // and adds events data that has a map of events to
259
+ // `callbackId` to `remove` object. It looks like
260
+ // `{click: {5: {remove: fn}}}`.
261
+ addBinding = function( nodelist, selector, ev, cb ) {
262
+ if ( nodelist instanceof Y.NodeList || !nodelist.on || nodelist.getDOMNode ) {
263
+ nodelist.each(function( node ) {
264
+ var node = can.$(node);
265
+ var events = can.data(node, "events"),
266
+ eventName = ev + ":" + selector;
267
+ if (!events ) {
268
+ can.data(node, "events", events = {});
269
+ }
270
+ if (!events[eventName] ) {
271
+ events[eventName] = {};
272
+ }
273
+ if ( cb.__bindingsIds === undefined ) {
274
+ cb.__bindingsIds = id++;
275
+ }
276
+ events[eventName][cb.__bindingsIds] = selector ? node.item(0).delegate(ev, cb, selector) : node.item(0).on(ev, cb);
277
+ });
278
+ } else {
279
+ var obj = nodelist,
280
+ events = obj.__canEvents = obj.__canEvents || {};
281
+ if (!events[ev] ) {
282
+ events[ev] = {};
283
+ }
284
+ if ( cb.__bindingsIds === undefined ) {
285
+ cb.__bindingsIds = id++;
286
+ }
287
+ events[ev][cb.__bindingsIds] = obj.on(ev, cb);
288
+ }
289
+ },
290
+ // Removes a binding on a `nodelist` by finding
291
+ // the remove object within the object's data.
292
+ removeBinding = function( nodelist, selector, ev, cb ) {
293
+ if ( nodelist instanceof Y.NodeList || !nodelist.on || nodelist.getDOMNode ) {
294
+ nodelist.each(function( node ) {
295
+ var node = can.$(node),
296
+ events = can.data(node, "events"),
297
+ eventName = ev + ":" + selector,
298
+ handlers = events[eventName],
299
+ handler = handlers[cb.__bindingsIds];
300
+ handler.detach();
301
+ delete handlers[cb.__bindingsIds];
302
+ if ( can.isEmptyObject(handlers) ) {
303
+ delete events[ev];
304
+ }
305
+ if ( can.isEmptyObject(events) ) {}
306
+ });
307
+ } else {
308
+ var obj = nodelist,
309
+ events = obj.__canEvents || {},
310
+ handlers = events[ev],
311
+ handler = handlers[cb.__bindingsIds];
312
+ handler.detach();
313
+ delete handlers[cb.__bindingsIds];
314
+ if ( can.isEmptyObject(handlers) ) {
315
+ delete events[ev];
316
+ }
317
+ if ( can.isEmptyObject(events) ) {}
318
+ }
319
+ }
320
+ can.bind = function( ev, cb ) {
321
+ // If we can bind to it...
322
+ if ( this.bind && this.bind !== can.bind ) {
323
+ this.bind(ev, cb)
324
+ } else if ( this.on || this.nodeType ) {
325
+ addBinding(can.$(this), undefined, ev, cb)
326
+ } else if ( this.addEvent ) {
327
+ this.addEvent(ev, cb)
328
+ } else {
329
+ // Make it bind-able...
330
+ can.addEvent.call(this, ev, cb)
331
+ }
332
+ return this;
333
+ }
334
+ can.unbind = function( ev, cb ) {
335
+ // If we can bind to it...
336
+ if ( this.unbind && this.unbind !== can.unbind ) {
337
+ this.unbind(ev, cb)
338
+ }
339
+
340
+ else if ( this.on || this.nodeType ) {
341
+ removeBinding(can.$(this), undefined, ev, cb);
342
+ } else {
343
+ // Make it bind-able...
344
+ can.removeEvent.call(this, ev, cb)
345
+ }
346
+ return this;
347
+ }
348
+ can.trigger = function( item, event, args, bubble ) {
349
+ if ( item instanceof Y.NodeList ) {
350
+ item = item.item(0);
351
+ }
352
+ if ( item.getDOMNode ) {
353
+ item = item.getDOMNode();
354
+ }
355
+
356
+ if ( item.nodeName ) {
357
+ item = Y.Node(item);
358
+ if ( bubble === false ) {
359
+ // Force stop propagation by listening to `on` and then
360
+ // immediately disconnecting
361
+ item.once(event, function( ev ) {
362
+ ev.stopPropagation && ev.stopPropagation();
363
+ ev.cancelBubble = true;
364
+ ev._stopper && ev._stopper();
365
+ })
366
+ }
367
+ realTrigger(item.getDOMNode(), event, {})
368
+ } else {
369
+ if ( typeof event === 'string' ) {
370
+ event = {
371
+ type: event
372
+ }
373
+ }
374
+ event.target = event.target || item
375
+ event.data = args
376
+ can.dispatch.call(item, event)
377
+ }
378
+ };
379
+ // Allow `dom` `destroyed` events.
380
+ Y.mix(Y.Node.DOM_EVENTS, {
381
+ destroyed: true
382
+ });
383
+
384
+ can.delegate = function( selector, ev, cb ) {
385
+ if ( this.on || this.nodeType ) {
386
+ addBinding(can.$(this), selector, ev, cb)
387
+ } else if ( this.delegate ) {
388
+ this.delegate(selector, ev, cb)
389
+ }
390
+ return this;
391
+ }
392
+ can.undelegate = function( selector, ev, cb ) {
393
+ if ( this.on || this.nodeType ) {
394
+ removeBinding(can.$(this), selector, ev, cb);
395
+ } else if ( this.undelegate ) {
396
+ this.undelegate(selector, ev, cb)
397
+ }
398
+ return this;
399
+ }
400
+
401
+ // `realTrigger` taken from `dojo`.
402
+ var leaveRe = /mouse(enter|leave)/,
403
+ _fix = function( _, p ) {
404
+ return "mouse" + (p == "enter" ? "over" : "out");
405
+ },
406
+ realTrigger = document.createEvent ?
407
+ function( n, e, a ) {
408
+ // the same branch
409
+ var ev = document.createEvent("HTMLEvents");
410
+ e = e.replace(leaveRe, _fix);
411
+ ev.initEvent(e, true, true);
412
+ a && can.extend(ev, a);
413
+ n.dispatchEvent(ev);
414
+ } : function( n, e, a ) {
415
+ // the janktastic branch
416
+ var ev = "on" + e,
417
+ stop = false,
418
+ lc = e.toLowerCase(),
419
+ node = n;
420
+ try {
421
+ // FIXME: is this worth it? for mixed-case native event support:? Opera ends up in the
422
+ // createEvent path above, and also fails on _some_ native-named events.
423
+ // if(lc !== e && d.indexOf(d.NodeList.events, lc) >= 0){
424
+ // // if the event is one of those listed in our NodeList list
425
+ // // in lowercase form but is mixed case, throw to avoid
426
+ // // fireEvent. /me sighs. http://gist.github.com/315318
427
+ // throw("janktastic");
428
+ // }
429
+ n.fireEvent(ev);
430
+ } catch (er) {
431
+ // a lame duck to work with. we're probably a 'custom event'
432
+ var evdata = can.extend({
433
+ type: e,
434
+ target: n,
435
+ faux: true,
436
+ // HACK: [needs] added support for customStopper to _base/event.js
437
+ // some tests will fail until del._stopPropagation has support.
438
+ _stopper: function() {
439
+ stop = this.cancelBubble;
440
+ }
441
+ }, a);
442
+ realTriggerHandler(n, e, evdata);
443
+
444
+ // handle bubbling of custom events, unless the event was stopped.
445
+ while (!stop && n !== document && n.parentNode ) {
446
+ n = n.parentNode;
447
+ realTriggerHandler(n, e, evdata);
448
+ //can.isFunction(n[ev]) && n[ev](evdata);
449
+ }
450
+ }
451
+ },
452
+ realTriggerHandler = function( n, e, evdata ) {
453
+ var node = Y.Node(n),
454
+ handlers = can.Y.Event.getListeners(node._yuid, e);
455
+ if ( handlers ) {
456
+ for ( var i = 0; i < handlers.length; i++ ) {
457
+ handlers[i].fire(evdata)
458
+ }
459
+ }
460
+ };
461
+
462
+ // deferred.js
463
+ // ---------
464
+ // _Lightweight, jQuery style deferreds._
465
+
466
+ var Deferred = function( func ) {
467
+ if ( ! ( this instanceof Deferred ))
468
+ return new Deferred();
469
+
470
+ this._doneFuncs = [];
471
+ this._failFuncs = [];
472
+ this._resultArgs = null;
473
+ this._status = "";
474
+
475
+ // Check for option `function` -- call it with this as context and as first
476
+ // parameter, as specified in jQuery API.
477
+ func && func.call(this, this);
478
+ };
479
+ can.Deferred = Deferred;
480
+ can.when = Deferred.when = function() {
481
+ var args = can.makeArray( arguments );
482
+ if (args.length < 2) {
483
+ var obj = args[0];
484
+ if (obj && ( can.isFunction( obj.isResolved ) && can.isFunction( obj.isRejected ))) {
485
+ return obj;
486
+ } else {
487
+ return Deferred().resolve(obj);
488
+ }
489
+ } else {
490
+
491
+ var df = Deferred(),
492
+ done = 0,
493
+ // Resolve params -- params of each resolve, we need to track them down
494
+ // to be able to pass them in the correct order if the master
495
+ // needs to be resolved.
496
+ rp = [];
497
+
498
+ can.each(args, function(arg, j){
499
+ arg.done(function() {
500
+ rp[j] = (arguments.length < 2) ? arguments[0] : arguments;
501
+ if (++done == args.length) {
502
+ df.resolve.apply(df, rp);
503
+ }
504
+ }).fail(function() {
505
+ df.reject(arguments);
506
+ });
507
+ });
508
+
509
+ return df;
510
+
511
+ }
512
+ }
513
+
514
+ var resolveFunc = function(type, _status){
515
+ return function(context){
516
+ var args = this._resultArgs = (arguments.length > 1) ? arguments[1] : [];
517
+ return this.exec(context, this[type], args, _status);
518
+ }
519
+ },
520
+ doneFunc = function(type, _status){
521
+ return function(){
522
+ var self = this;
523
+ // In Safari, the properties of the `arguments` object are not enumerable,
524
+ // so we have to convert arguments to an `Array` that allows `can.each` to loop over them.
525
+ can.each(Array.prototype.slice.call(arguments), function( v, i, args ) {
526
+ if ( ! v )
527
+ return;
528
+ if ( v.constructor === Array ) {
529
+ args.callee.apply(self, v)
530
+ } else {
531
+ // Immediately call the `function` if the deferred has been resolved.
532
+ if (self._status === _status)
533
+ v.apply(self, self._resultArgs || []);
534
+
535
+ self[type].push(v);
536
+ }
537
+ });
538
+ return this;
539
+ }
540
+ };
541
+
542
+ can.extend( Deferred.prototype, {
543
+ pipe : function(done, fail){
544
+ var d = can.Deferred();
545
+ this.done(function(){
546
+ d.resolve( done.apply(this, arguments) );
547
+ });
548
+
549
+ this.fail(function(){
550
+ if(fail){
551
+ d.reject( fail.apply(this, arguments) );
552
+ } else {
553
+ d.reject.apply(d, arguments);
554
+ }
555
+ });
556
+ return d;
557
+ },
558
+ resolveWith : resolveFunc("_doneFuncs","rs"),
559
+ rejectWith : resolveFunc("_failFuncs","rj"),
560
+ done : doneFunc("_doneFuncs","rs"),
561
+ fail : doneFunc("_failFuncs","rj"),
562
+ always : function() {
563
+ var args = can.makeArray(arguments);
564
+ if (args.length && args[0])
565
+ this.done(args[0]).fail(args[0]);
566
+
567
+ return this;
568
+ },
569
+
570
+ then : function() {
571
+ var args = can.makeArray( arguments );
572
+ // Fail `function`(s)
573
+ if (args.length > 1 && args[1])
574
+ this.fail(args[1]);
575
+
576
+ // Done `function`(s)
577
+ if (args.length && args[0])
578
+ this.done(args[0]);
579
+
580
+ return this;
581
+ },
582
+
583
+ isResolved : function() {
584
+ return this._status === "rs";
585
+ },
586
+
587
+ isRejected : function() {
588
+ return this._status === "rj";
589
+ },
590
+
591
+ reject : function() {
592
+ return this.rejectWith(this, arguments);
593
+ },
594
+
595
+ resolve : function() {
596
+ return this.resolveWith(this, arguments);
597
+ },
598
+
599
+ exec : function(context, dst, args, st) {
600
+ if (this._status !== "")
601
+ return this;
602
+
603
+ this._status = st;
604
+
605
+ can.each(dst, function(d){
606
+ d.apply(context, args);
607
+ });
608
+
609
+ return this;
610
+ }
611
+ });
612
+
613
+ // ##string.js
614
+ // _Miscellaneous string utility functions._
615
+
616
+ // Several of the methods in this plugin use code adapated from Prototype
617
+ // Prototype JavaScript framework, version 1.6.0.1.
618
+ // © 2005-2007 Sam Stephenson
619
+ var undHash = /_|-/,
620
+ colons = /==/,
621
+ words = /([A-Z]+)([A-Z][a-z])/g,
622
+ lowUp = /([a-z\d])([A-Z])/g,
623
+ dash = /([a-z\d])([A-Z])/g,
624
+ replacer = /\{([^\}]+)\}/g,
625
+ quote = /"/g,
626
+ singleQuote = /'/g,
627
+
628
+ // Returns the `prop` property from `obj`.
629
+ // If `add` is true and `prop` doesn't exist in `obj`, create it as an
630
+ // empty object.
631
+ getNext = function( obj, prop, add ) {
632
+ return prop in obj ?
633
+ obj[ prop ] :
634
+ ( add && ( obj[ prop ] = {} ));
635
+ },
636
+
637
+ // Returns `true` if the object can have properties (no `null`s).
638
+ isContainer = function( current ) {
639
+ return /^f|^o/.test( typeof current );
640
+ };
641
+
642
+ can.extend(can, {
643
+ // Escapes strings for HTML.
644
+ esc : function( content ) {
645
+ return ( "" + content )
646
+ .replace(/&/g, '&amp;')
647
+ .replace(/</g, '&lt;')
648
+ .replace(/>/g, '&gt;')
649
+ .replace(quote, '&#34;')
650
+ .replace(singleQuote, "&#39;");
651
+ },
652
+
653
+ getObject : function( name, roots, add ) {
654
+
655
+ // The parts of the name we are looking up
656
+ // `['App','Models','Recipe']`
657
+ var parts = name ? name.split('.') : [],
658
+ length = parts.length,
659
+ current,
660
+ r = 0,
661
+ ret, i;
662
+
663
+ // Make sure roots is an `array`.
664
+ roots = can.isArray(roots) ? roots : [roots || window];
665
+
666
+ if ( ! length ) {
667
+ return roots[0];
668
+ }
669
+
670
+ // For each root, mark it as current.
671
+ while( current = roots[r++] ) {
672
+
673
+ // Walk current to the 2nd to last object or until there
674
+ // is not a container.
675
+ for (i =0; i < length - 1 && isContainer( current ); i++ ) {
676
+ current = getNext( current, parts[i], add );
677
+ }
678
+
679
+ // If we can get a property from the 2nd to last object...
680
+ if( isContainer(current) ) {
681
+
682
+ // Get (and possibly set) the property.
683
+ ret = getNext(current, parts[i], add);
684
+
685
+ // If there is a value, we exit.
686
+ if ( ret !== undefined ) {
687
+ // If `add` is `false`, delete the property
688
+ if ( add === false ) {
689
+ delete current[parts[i]];
690
+ }
691
+ return ret;
692
+
693
+ }
694
+ }
695
+ }
696
+ },
697
+ // Capitalizes a string.
698
+ capitalize: function( s, cache ) {
699
+ // Used to make newId.
700
+ return s.charAt(0).toUpperCase() + s.slice(1);
701
+ },
702
+
703
+ // Underscores a string.
704
+ underscore: function( s ) {
705
+ return s
706
+ .replace(colons, '/')
707
+ .replace(words, '$1_$2')
708
+ .replace(lowUp, '$1_$2')
709
+ .replace(dash, '_')
710
+ .toLowerCase();
711
+ },
712
+ // Micro-templating.
713
+ sub: function( str, data, remove ) {
714
+
715
+ var obs = [];
716
+
717
+ obs.push( str.replace( replacer, function( whole, inside ) {
718
+
719
+ // Convert inside to type.
720
+ var ob = can.getObject( inside, data, remove === undefined? remove : !remove );
721
+
722
+ // If a container, push into objs (which will return objects found).
723
+ if ( isContainer( ob ) ) {
724
+ obs.push( ob );
725
+ return "";
726
+ } else {
727
+ return "" + ob;
728
+ }
729
+ }));
730
+
731
+ return obs.length <= 1 ? obs[0] : obs;
732
+ },
733
+
734
+ // These regex's are used throughout the rest of can, so let's make
735
+ // them available.
736
+ replacer : replacer,
737
+ undHash : undHash
738
+ });
739
+
740
+ // ## construct.js
741
+ // `can.Construct`
742
+ // _This is a modified version of
743
+ // [John Resig's class](http://ejohn.org/blog/simple-javascript-inheritance/).
744
+ // It provides class level inheritance and callbacks._
745
+
746
+ // A private flag used to initialize a new class instance without
747
+ // initializing it's bindings.
748
+ var initializing = 0;
749
+
750
+ can.Construct = function() {
751
+ if (arguments.length) {
752
+ return can.Construct.extend.apply(can.Construct, arguments);
753
+ }
754
+ };
755
+
756
+ can.extend(can.Construct, {
757
+ newInstance: function() {
758
+ // Get a raw instance object (`init` is not called).
759
+ var inst = this.instance(),
760
+ arg = arguments,
761
+ args;
762
+
763
+ // Call `setup` if there is a `setup`
764
+ if ( inst.setup ) {
765
+ args = inst.setup.apply(inst, arguments);
766
+ }
767
+
768
+ // Call `init` if there is an `init`
769
+ // If `setup` returned `args`, use those as the arguments
770
+ if ( inst.init ) {
771
+ inst.init.apply(inst, args || arguments);
772
+ }
773
+
774
+ return inst;
775
+ },
776
+ // Overwrites an object with methods. Used in the `super` plugin.
777
+ // `newProps` - New properties to add.
778
+ // `oldProps` - Where the old properties might be (used with `super`).
779
+ // `addTo` - What we are adding to.
780
+ _inherit: function( newProps, oldProps, addTo ) {
781
+ can.extend(addTo || newProps, newProps || {})
782
+ },
783
+ // used for overwriting a single property.
784
+ // this should be used for patching other objects
785
+ // the super plugin overwrites this
786
+ _overwrite : function(what, oldProps, propName, val){
787
+ what[propName] = val;
788
+ },
789
+ // Set `defaults` as the merger of the parent `defaults` and this
790
+ // object's `defaults`. If you overwrite this method, make sure to
791
+ // include option merging logic.
792
+ setup: function( base, fullName ) {
793
+ this.defaults = can.extend(true,{}, base.defaults, this.defaults);
794
+ },
795
+ // Create's a new `class` instance without initializing by setting the
796
+ // `initializing` flag.
797
+ instance: function() {
798
+
799
+ // Prevents running `init`.
800
+ initializing = 1;
801
+
802
+ var inst = new this();
803
+
804
+ // Allow running `init`.
805
+ initializing = 0;
806
+
807
+ return inst;
808
+ },
809
+ // Extends classes.
810
+ extend: function( fullName, klass, proto ) {
811
+ // Figure out what was passed and normalize it.
812
+ if ( typeof fullName != 'string' ) {
813
+ proto = klass;
814
+ klass = fullName;
815
+ fullName = null;
816
+ }
817
+
818
+ if ( ! proto ) {
819
+ proto = klass;
820
+ klass = null;
821
+ }
822
+ proto = proto || {};
823
+
824
+ var _super_class = this,
825
+ _super = this.prototype,
826
+ name, shortName, namespace, prototype;
827
+
828
+ // Instantiate a base class (but only create the instance,
829
+ // don't run the init constructor).
830
+ prototype = this.instance();
831
+
832
+ // Copy the properties over onto the new prototype.
833
+ can.Construct._inherit(proto, _super, prototype);
834
+
835
+ // The dummy class constructor.
836
+ function Constructor() {
837
+ // All construction is actually done in the init method.
838
+ if ( ! initializing ) {
839
+ return this.constructor !== Constructor && arguments.length ?
840
+ // We are being called without `new` or we are extending.
841
+ arguments.callee.extend.apply(arguments.callee, arguments) :
842
+ // We are being called with `new`.
843
+ this.constructor.newInstance.apply(this.constructor, arguments);
844
+ }
845
+ }
846
+
847
+ // Copy old stuff onto class (can probably be merged w/ inherit)
848
+ for ( name in _super_class ) {
849
+ if ( _super_class.hasOwnProperty(name) ) {
850
+ Constructor[name] = _super_class[name];
851
+ }
852
+ }
853
+
854
+ // Copy new static properties on class.
855
+ can.Construct._inherit(klass, _super_class, Constructor);
856
+
857
+ // Setup namespaces.
858
+ if ( fullName ) {
859
+
860
+ var parts = fullName.split('.'),
861
+ shortName = parts.pop(),
862
+ current = can.getObject(parts.join('.'), window, true),
863
+ namespace = current,
864
+ _fullName = can.underscore(fullName.replace(/\./g, "_")),
865
+ _shortName = can.underscore(shortName);
866
+
867
+ //@steal-remove-start
868
+ if(current[shortName]){
869
+
870
+ }
871
+ //@steal-remove-end
872
+
873
+ current[shortName] = Constructor;
874
+ }
875
+
876
+ // Set things that shouldn't be overwritten.
877
+ can.extend(Constructor, {
878
+ constructor: Constructor,
879
+ prototype: prototype,
880
+ namespace: namespace,
881
+ shortName: shortName,
882
+ _shortName : _shortName,
883
+ fullName: fullName,
884
+ _fullName: _fullName
885
+ });
886
+
887
+ // Make sure our prototype looks nice.
888
+ Constructor.prototype.constructor = Constructor;
889
+
890
+
891
+ // Call the class `setup` and `init`
892
+ var t = [_super_class].concat(can.makeArray(arguments)),
893
+ args = Constructor.setup.apply(Constructor, t );
894
+
895
+ if ( Constructor.init ) {
896
+ Constructor.init.apply(Constructor, args || t );
897
+ }
898
+
899
+ return Constructor;
900
+ //
901
+ //
902
+ }
903
+
904
+ });
905
+
906
+ // ## observe.js
907
+ // `can.Observe`
908
+ // _Provides the observable pattern for JavaScript Objects._
909
+ //
910
+ // Returns `true` if something is an object with properties of its own.
911
+ var canMakeObserve = function( obj ) {
912
+ return obj && typeof obj === 'object' && !(obj instanceof Date);
913
+ },
914
+
915
+ // Removes all listeners.
916
+ unhookup = function(items, namespace){
917
+ return can.each(items, function(item){
918
+ if(item && item.unbind){
919
+ item.unbind("change" + namespace);
920
+ }
921
+ });
922
+ },
923
+ // Listens to changes on `val` and "bubbles" the event up.
924
+ // `val` - The object to listen for changes on.
925
+ // `prop` - The property name is at on.
926
+ // `parent` - The parent object of prop.
927
+ hookupBubble = function( val, prop, parent ) {
928
+ // If it's an `array` make a list, otherwise a val.
929
+ if (val instanceof Observe){
930
+ // We have an `observe` already...
931
+ // Make sure it is not listening to this already
932
+ unhookup([val], parent._namespace);
933
+ } else if ( can.isArray(val) ) {
934
+ val = new Observe.List(val);
935
+ } else {
936
+ val = new Observe(val);
937
+ }
938
+
939
+ // Listen to all changes and `batchTrigger` upwards.
940
+ val.bind("change" + parent._namespace, function( ev, attr ) {
941
+ // `batchTrigger` the type on this...
942
+ var args = can.makeArray(arguments),
943
+ ev = args.shift();
944
+ args[0] = prop === "*" ?
945
+ parent.indexOf(val)+"." + args[0] :
946
+ prop + "." + args[0];
947
+ // track objects dispatched on this observe
948
+ ev.triggeredNS = ev.triggeredNS || {};
949
+ // if it has already been dispatched exit
950
+ if (ev.triggeredNS[parent._namespace]) {
951
+ return;
952
+ }
953
+ ev.triggeredNS[parent._namespace] = true;
954
+
955
+ can.trigger(parent, ev, args);
956
+ can.trigger(parent,args[0],args);
957
+ });
958
+
959
+ return val;
960
+ },
961
+
962
+ // An `id` to track events for a given observe.
963
+ observeId = 0,
964
+ // A reference to an `array` of events that will be dispatched.
965
+ collecting = undefined,
966
+ // Call to start collecting events (`Observe` sends all events at
967
+ // once).
968
+ collect = function() {
969
+ if (!collecting ) {
970
+ collecting = [];
971
+ return true;
972
+ }
973
+ },
974
+ // Creates an event on item, but will not send immediately
975
+ // if collecting events.
976
+ // `item` - The item the event should happen on.
977
+ // `event` - The event name, ex: `change`.
978
+ // `args` - Tn array of arguments.
979
+ batchTrigger = function( item, event, args ) {
980
+ // Don't send events if initalizing.
981
+ if ( ! item._init) {
982
+ if (!collecting ) {
983
+ return can.trigger(item, event, args);
984
+ } else {
985
+ collecting.push([
986
+ item,
987
+ {
988
+ type: event,
989
+ batchNum : batchNum
990
+ },
991
+ args ] );
992
+ }
993
+ }
994
+ },
995
+ // Which batch of events this is for -- might not want to send multiple
996
+ // messages on the same batch. This is mostly for event delegation.
997
+ batchNum = 1,
998
+ // Sends all pending events.
999
+ sendCollection = function() {
1000
+ var items = collecting.slice(0);
1001
+ collecting = undefined;
1002
+ batchNum++;
1003
+ can.each(items, function( item ) {
1004
+ can.trigger.apply(can, item)
1005
+ })
1006
+
1007
+ },
1008
+ // A helper used to serialize an `Observe` or `Observe.List`.
1009
+ // `observe` - The observable.
1010
+ // `how` - To serialize with `attr` or `serialize`.
1011
+ // `where` - To put properties, in an `{}` or `[]`.
1012
+ serialize = function( observe, how, where ) {
1013
+ // Go through each property.
1014
+ observe.each(function( val, name ) {
1015
+ // If the value is an `object`, and has an `attrs` or `serialize` function.
1016
+ where[name] = canMakeObserve(val) && can.isFunction( val[how] ) ?
1017
+ // Call `attrs` or `serialize` to get the original data back.
1018
+ val[how]() :
1019
+ // Otherwise return the value.
1020
+ val
1021
+ })
1022
+ return where;
1023
+ },
1024
+ $method = function( name ) {
1025
+ return function() {
1026
+ return can[name].apply(this, arguments );
1027
+ }
1028
+ },
1029
+ bind = $method('addEvent'),
1030
+ unbind = $method('removeEvent'),
1031
+ attrParts = function(attr){
1032
+ return can.isArray(attr) ? attr : (""+attr).split(".")
1033
+ };
1034
+ var Observe = can.Construct('can.Observe', {
1035
+ // keep so it can be overwritten
1036
+ setup : function(){
1037
+ can.Construct.setup.apply(this, arguments)
1038
+ },
1039
+ bind : bind,
1040
+ unbind: unbind,
1041
+ id: "id"
1042
+ },
1043
+ {
1044
+ setup: function( obj ) {
1045
+ // `_data` is where we keep the properties.
1046
+ this._data = {};
1047
+ // The namespace this `object` uses to listen to events.
1048
+ this._namespace = ".observe" + (++observeId);
1049
+ // Sets all `attrs`.
1050
+ this._init = 1;
1051
+ this.attr(obj);
1052
+ delete this._init;
1053
+ },
1054
+ attr: function( attr, val ) {
1055
+ // This is super obfuscated for space -- basically, we're checking
1056
+ // if the type of the attribute is not a `number` or a `string`.
1057
+ if ( !~ "ns".indexOf((typeof attr).charAt(0))) {
1058
+ return this._attrs(attr, val)
1059
+ } else if ( val === undefined ) {// If we are getting a value.
1060
+ // Let people know we are reading.
1061
+ Observe.__reading && Observe.__reading(this, attr)
1062
+ return this._get(attr)
1063
+ } else {
1064
+ // Otherwise we are setting.
1065
+ this._set(attr, val);
1066
+ return this;
1067
+ }
1068
+ },
1069
+ each: function() {
1070
+ return can.each.apply(undefined, [this.__get()].concat(can.makeArray(arguments)))
1071
+ },
1072
+ removeAttr: function( attr ) {
1073
+ // Convert the `attr` into parts (if nested).
1074
+ var parts = attrParts(attr),
1075
+ // The actual property to remove.
1076
+ prop = parts.shift(),
1077
+ // The current value.
1078
+ current = this._data[prop];
1079
+
1080
+ // If we have more parts, call `removeAttr` on that part.
1081
+ if ( parts.length ) {
1082
+ return current.removeAttr(parts)
1083
+ } else {
1084
+ // Otherwise, `delete`.
1085
+ delete this._data[prop];
1086
+ // Create the event.
1087
+ if (!(prop in this.constructor.prototype)) {
1088
+ delete this[prop]
1089
+ }
1090
+ batchTrigger(this, "change", [prop, "remove", undefined, current]);
1091
+ batchTrigger(this, prop, [undefined, current]);
1092
+ return current;
1093
+ }
1094
+ },
1095
+ // Reads a property from the `object`.
1096
+ _get: function( attr ) {
1097
+ var parts = attrParts(attr),
1098
+ current = this.__get(parts.shift());
1099
+ return parts.length ? current ? current._get(parts) : undefined : current;
1100
+ },
1101
+ // Reads a property directly if an `attr` is provided, otherwise
1102
+ // returns the "real" data object itself.
1103
+ __get: function( attr ) {
1104
+ return attr ? this._data[attr] : this._data;
1105
+ },
1106
+ // Sets `attr` prop as value on this object where.
1107
+ // `attr` - Is a string of properties or an array of property values.
1108
+ // `value` - The raw value to set.
1109
+ _set: function( attr, value ) {
1110
+ // Convert `attr` to attr parts (if it isn't already).
1111
+ var parts = attrParts(attr),
1112
+ // The immediate prop we are setting.
1113
+ prop = parts.shift(),
1114
+ // The current value.
1115
+ current = this.__get(prop);
1116
+
1117
+ // If we have an `object` and remaining parts.
1118
+ if ( canMakeObserve(current) && parts.length ) {
1119
+ // That `object` should set it (this might need to call attr).
1120
+ current._set(parts, value)
1121
+ } else if (!parts.length ) {
1122
+ // We're in "real" set territory.
1123
+ if(this.__convert){
1124
+ value = this.__convert(prop, value)
1125
+ }
1126
+ this.__set(prop, value, current)
1127
+
1128
+ } else {
1129
+ throw "can.Observe: Object does not exist"
1130
+ }
1131
+ },
1132
+ __set : function(prop, value, current){
1133
+
1134
+ // Otherwise, we are setting it on this `object`.
1135
+ // TODO: Check if value is object and transform
1136
+ // are we changing the value.
1137
+ if ( value !== current ) {
1138
+
1139
+ // Check if we are adding this for the first time --
1140
+ // if we are, we need to create an `add` event.
1141
+ var changeType = this.__get().hasOwnProperty(prop) ? "set" : "add";
1142
+
1143
+ // Set the value on data.
1144
+ this.___set(prop,
1145
+
1146
+ // If we are getting an object.
1147
+ canMakeObserve(value) ?
1148
+
1149
+ // Hook it up to send event.
1150
+ hookupBubble(value, prop, this) :
1151
+ // Value is normal.
1152
+ value);
1153
+
1154
+ // `batchTrigger` the change event.
1155
+ batchTrigger(this, "change", [prop, changeType, value, current]);
1156
+ batchTrigger(this, prop, [value, current]);
1157
+ // If we can stop listening to our old value, do it.
1158
+ current && unhookup([current], this._namespace);
1159
+ }
1160
+
1161
+ },
1162
+ // Directly sets a property on this `object`.
1163
+ ___set: function( prop, val ) {
1164
+ this._data[prop] = val;
1165
+ // Add property directly for easy writing.
1166
+ // Check if its on the `prototype` so we don't overwrite methods like `attrs`.
1167
+ if (!(prop in this.constructor.prototype)) {
1168
+ this[prop] = val
1169
+ }
1170
+ },
1171
+ bind: bind,
1172
+ unbind: unbind,
1173
+ serialize: function() {
1174
+ return serialize(this, 'serialize', {});
1175
+ },
1176
+ _attrs: function( props, remove ) {
1177
+ if ( props === undefined ) {
1178
+ return serialize(this, 'attr', {})
1179
+ }
1180
+
1181
+ props = can.extend(true, {}, props);
1182
+ var prop,
1183
+ collectingStarted = collect(),
1184
+ self = this,
1185
+ newVal;
1186
+
1187
+ this.each(function(curVal, prop){
1188
+ newVal = props[prop];
1189
+
1190
+ // If we are merging...
1191
+ if ( newVal === undefined ) {
1192
+ remove && self.removeAttr(prop);
1193
+ return;
1194
+ }
1195
+ if ( canMakeObserve(curVal) && canMakeObserve(newVal) ) {
1196
+ curVal.attr(newVal, remove)
1197
+ } else if ( curVal != newVal ) {
1198
+ self._set(prop, newVal)
1199
+ } else {
1200
+
1201
+ }
1202
+ delete props[prop];
1203
+ })
1204
+ // Add remaining props.
1205
+ for ( var prop in props ) {
1206
+ newVal = props[prop];
1207
+ this._set(prop, newVal)
1208
+ }
1209
+ if ( collectingStarted ) {
1210
+ sendCollection();
1211
+ }
1212
+ return this;
1213
+ }
1214
+ });
1215
+ // Helpers for `observable` lists.
1216
+ var splice = [].splice,
1217
+ list = Observe('can.Observe.List',
1218
+ {
1219
+ setup: function( instances, options ) {
1220
+ this.length = 0;
1221
+ this._namespace = ".observe" + (++observeId);
1222
+ this._init = 1;
1223
+ this.bind('change',can.proxy(this._changes,this));
1224
+ this.push.apply(this, can.makeArray(instances || []));
1225
+ can.extend(this, options);
1226
+ delete this._init;
1227
+ },
1228
+ _changes : function(ev, attr, how, newVal, oldVal){
1229
+ // `batchTrigger` direct add and remove events...
1230
+ if ( !~ attr.indexOf('.')){
1231
+
1232
+ if( how === 'add' ) {
1233
+ batchTrigger(this, how, [newVal,+attr]);
1234
+ batchTrigger(this,'length',[this.length]);
1235
+ } else if( how === 'remove' ) {
1236
+ batchTrigger(this, how, [oldVal, +attr]);
1237
+ batchTrigger(this,'length',[this.length]);
1238
+ } else {
1239
+ batchTrigger(this,how,[newVal, +attr])
1240
+ }
1241
+
1242
+ }
1243
+ },
1244
+ __get : function(attr){
1245
+ return attr ? this[attr] : this;
1246
+ },
1247
+ ___set : function(attr, val){
1248
+ this[attr] = val;
1249
+ if(+attr >= this.length){
1250
+ this.length = (+attr+1)
1251
+ }
1252
+ },
1253
+ // Returns the serialized form of this list.
1254
+ serialize: function() {
1255
+ return serialize(this, 'serialize', []);
1256
+ },
1257
+ //
1258
+ splice: function( index, howMany ) {
1259
+ var args = can.makeArray(arguments),
1260
+ i;
1261
+
1262
+ for ( i = 2; i < args.length; i++ ) {
1263
+ var val = args[i];
1264
+ if ( canMakeObserve(val) ) {
1265
+ args[i] = hookupBubble(val, "*", this)
1266
+ }
1267
+ }
1268
+ if ( howMany === undefined ) {
1269
+ howMany = args[1] = this.length - index;
1270
+ }
1271
+ var removed = splice.apply(this, args);
1272
+ if ( howMany > 0 ) {
1273
+ batchTrigger(this, "change", [""+index, "remove", undefined, removed]);
1274
+ unhookup(removed, this._namespace);
1275
+ }
1276
+ if ( args.length > 2 ) {
1277
+ batchTrigger(this, "change", [""+index, "add", args.slice(2), removed]);
1278
+ }
1279
+ return removed;
1280
+ },
1281
+ _attrs: function( props, remove ) {
1282
+ if ( props === undefined ) {
1283
+ return serialize(this, 'attr', []);
1284
+ }
1285
+
1286
+ // Create a copy.
1287
+ props = props.slice(0);
1288
+
1289
+ var len = Math.min(props.length, this.length),
1290
+ collectingStarted = collect(),
1291
+ prop;
1292
+
1293
+ for ( var prop = 0; prop < len; prop++ ) {
1294
+ var curVal = this[prop],
1295
+ newVal = props[prop];
1296
+
1297
+ if ( canMakeObserve(curVal) && canMakeObserve(newVal) ) {
1298
+ curVal.attr(newVal, remove)
1299
+ } else if ( curVal != newVal ) {
1300
+ this._set(prop, newVal)
1301
+ } else {
1302
+
1303
+ }
1304
+ }
1305
+ if ( props.length > this.length ) {
1306
+ // Add in the remaining props.
1307
+ this.push(props.slice(this.length))
1308
+ } else if ( props.length < this.length && remove ) {
1309
+ this.splice(props.length)
1310
+ }
1311
+
1312
+ if ( collectingStarted ) {
1313
+ sendCollection()
1314
+ }
1315
+ }
1316
+ }),
1317
+
1318
+ // Converts to an `array` of arguments.
1319
+ getArgs = function( args ) {
1320
+ return args[0] && can.isArray(args[0]) ?
1321
+ args[0] :
1322
+ can.makeArray(args);
1323
+ };
1324
+ // Create `push`, `pop`, `shift`, and `unshift`
1325
+ can.each({
1326
+ push: "length",
1327
+ unshift: 0
1328
+ },
1329
+ // Adds a method
1330
+ // `name` - The method name.
1331
+ // `where` - Where items in the `array` should be added.
1332
+ function( where, name ) {
1333
+ list.prototype[name] = function() {
1334
+ // Get the items being added.
1335
+ var args = getArgs(arguments),
1336
+ // Where we are going to add items.
1337
+ len = where ? this.length : 0;
1338
+
1339
+ // Go through and convert anything to an `observe` that needs to be converted.
1340
+ for ( var i = 0; i < args.length; i++ ) {
1341
+ var val = args[i];
1342
+ if ( canMakeObserve(val) ) {
1343
+ args[i] = hookupBubble(val, "*", this)
1344
+ }
1345
+ }
1346
+
1347
+ // Call the original method.
1348
+ var res = [][name].apply(this, args);
1349
+
1350
+ if ( !this.comparator || !args.length ) {
1351
+ batchTrigger(this, "change", [""+len, "add", args, undefined])
1352
+ }
1353
+
1354
+ return res;
1355
+ }
1356
+ });
1357
+
1358
+ can.each({
1359
+ pop: "length",
1360
+ shift: 0
1361
+ },
1362
+ // Creates a `remove` type method
1363
+ function( where, name ) {
1364
+ list.prototype[name] = function() {
1365
+
1366
+ var args = getArgs(arguments),
1367
+ len = where && this.length ? this.length - 1 : 0;
1368
+
1369
+ var res = [][name].apply(this, args)
1370
+
1371
+ // Create a change where the args are
1372
+ // `*` - Change on potentially multiple properties.
1373
+ // `remove` - Items removed.
1374
+ // `undefined` - The new values (there are none).
1375
+ // `res` - The old, removed values (should these be unbound).
1376
+ // `len` - Where these items were removed.
1377
+ batchTrigger(this, "change", [""+len, "remove", undefined, [res]])
1378
+
1379
+ if ( res && res.unbind ) {
1380
+ res.unbind("change" + this._namespace)
1381
+ }
1382
+ return res;
1383
+ }
1384
+ });
1385
+
1386
+ list.prototype.
1387
+ indexOf = [].indexOf || function(item){
1388
+ return can.inArray(item, this)
1389
+ };
1390
+
1391
+
1392
+ // ## model.js
1393
+ // `can.Model`
1394
+ // _A `can.Observe` that connects to a RESTful interface._
1395
+ //
1396
+ // Generic deferred piping function
1397
+ var pipe = function( def, model, func ) {
1398
+ var d = new can.Deferred();
1399
+ def.then(function(){
1400
+ arguments[0] = model[func](arguments[0])
1401
+ d.resolve.apply(d, arguments)
1402
+ },function(){
1403
+ d.rejectWith.apply(this,arguments)
1404
+ })
1405
+ return d;
1406
+ },
1407
+ modelNum = 0,
1408
+ ignoreHookup = /change.observe\d+/,
1409
+ getId = function( inst ) {
1410
+ return inst[inst.constructor.id]
1411
+ },
1412
+ // Ajax `options` generator function
1413
+ ajax = function( ajaxOb, data, type, dataType, success, error ) {
1414
+
1415
+
1416
+ // If we get a string, handle it.
1417
+ if ( typeof ajaxOb == "string" ) {
1418
+ // If there's a space, it's probably the type.
1419
+ var parts = ajaxOb.split(" ")
1420
+ ajaxOb = {
1421
+ url : parts.pop()
1422
+ };
1423
+ if(parts.length){
1424
+ ajaxOb.type = parts.pop();
1425
+ }
1426
+ }
1427
+
1428
+ // If we are a non-array object, copy to a new attrs.
1429
+ ajaxOb.data = typeof data == "object" && !can.isArray(data) ?
1430
+ can.extend(ajaxOb.data || {}, data) : data;
1431
+
1432
+
1433
+ // Get the url with any templated values filled out.
1434
+ ajaxOb.url = can.sub(ajaxOb.url, ajaxOb.data, true);
1435
+
1436
+ return can.ajax(can.extend({
1437
+ type: type || "post",
1438
+ dataType: dataType ||"json",
1439
+ success : success,
1440
+ error: error
1441
+ }, ajaxOb ));
1442
+ },
1443
+ makeRequest = function( self, type, success, error, method ) {
1444
+ var deferred ,
1445
+ args = [self.serialize()],
1446
+ // The model.
1447
+ model = self.constructor,
1448
+ jqXHR;
1449
+
1450
+ // `destroy` does not need data.
1451
+ if ( type == 'destroy' ) {
1452
+ args.shift();
1453
+ }
1454
+ // `update` and `destroy` need the `id`.
1455
+ if ( type !== 'create' ) {
1456
+ args.unshift(getId(self))
1457
+ }
1458
+
1459
+ jqXHR = model[type].apply(model, args);
1460
+
1461
+ deferred = jqXHR.pipe(function(data){
1462
+ self[method || type + "d"](data, jqXHR);
1463
+ return self
1464
+ })
1465
+
1466
+ // Hook up `abort`
1467
+ if(jqXHR.abort){
1468
+ deferred.abort = function(){
1469
+ jqXHR.abort();
1470
+ }
1471
+ }
1472
+
1473
+ return deferred.then(success,error);
1474
+ },
1475
+
1476
+ // This object describes how to make an ajax request for each ajax method.
1477
+ // The available properties are:
1478
+ // `url` - The default url to use as indicated as a property on the model.
1479
+ // `type` - The default http request type
1480
+ // `data` - A method that takes the `arguments` and returns `data` used for ajax.
1481
+ //
1482
+ //
1483
+ //
1484
+ ajaxMethods = {
1485
+ create : {
1486
+ url : "_shortName",
1487
+ type :"post"
1488
+ },
1489
+ update : {
1490
+ data : function(id, attrs){
1491
+ attrs = attrs || {};
1492
+ var identity = this.id;
1493
+ if ( attrs[identity] && attrs[identity] !== id ) {
1494
+ attrs["new" + can.capitalize(id)] = attrs[identity];
1495
+ delete attrs[identity];
1496
+ }
1497
+ attrs[identity] = id;
1498
+ return attrs;
1499
+ },
1500
+ type : "put"
1501
+ },
1502
+ destroy : {
1503
+ type : "delete",
1504
+ data : function(id){
1505
+ var args = {};
1506
+ args[this.id] = id;
1507
+ return args;
1508
+ }
1509
+ },
1510
+ findAll : {
1511
+ url : "_shortName"
1512
+ },
1513
+ findOne: {}
1514
+ },
1515
+ // Makes an ajax request `function` from a string.
1516
+ // `ajaxMethod` - The `ajaxMethod` object defined above.
1517
+ // `str` - The string the user provided. Ex: `findAll: "/recipes.json"`.
1518
+ ajaxMaker = function(ajaxMethod, str){
1519
+ // Return a `function` that serves as the ajax method.
1520
+ return function(data){
1521
+ // If the ajax method has it's own way of getting `data`, use that.
1522
+ data = ajaxMethod.data ?
1523
+ ajaxMethod.data.apply(this, arguments) :
1524
+ // Otherwise use the data passed in.
1525
+ data;
1526
+ // Return the ajax method with `data` and the `type` provided.
1527
+ return ajax(str || this[ajaxMethod.url || "_url"], data, ajaxMethod.type || "get")
1528
+ }
1529
+ }
1530
+
1531
+
1532
+
1533
+ can.Observe("can.Model",{
1534
+ setup : function(base){
1535
+ can.Observe.apply(this, arguments);
1536
+ if(this === can.Model){
1537
+ return;
1538
+ }
1539
+ var self = this,
1540
+ clean = can.proxy(this._clean, self);
1541
+
1542
+ can.each(ajaxMethods, function(method, name){
1543
+ if ( ! can.isFunction( self[name] )) {
1544
+ self[name] = ajaxMaker(method, self[name]);
1545
+ }
1546
+ if (self["make"+can.capitalize(name)]){
1547
+ var newMethod = self["make"+can.capitalize(name)](self[name]);
1548
+ can.Construct._overwrite(self, base, name,function(){
1549
+ this._super;
1550
+ this._reqs++;
1551
+ return newMethod.apply(this, arguments).then(clean, clean);
1552
+ })
1553
+ }
1554
+ });
1555
+
1556
+ if(!self.fullName || self.fullName == base.fullName){
1557
+ self.fullName = self._shortName = "Model"+(++modelNum);
1558
+ }
1559
+ // Ddd ajax converters.
1560
+ this.store = {};
1561
+ this._reqs = 0;
1562
+ this._url = this._shortName+"/{"+this.id+"}"
1563
+ },
1564
+ _ajax : ajaxMaker,
1565
+ _clean : function(){
1566
+ this._reqs--;
1567
+ if(!this._reqs){
1568
+ for(var id in this.store) {
1569
+ if(!this.store[id]._bindings){
1570
+ delete this.store[id];
1571
+ }
1572
+ }
1573
+ }
1574
+ },
1575
+ models: function( instancesRawData ) {
1576
+
1577
+ if ( ! instancesRawData ) {
1578
+ return;
1579
+ }
1580
+
1581
+ if ( instancesRawData instanceof this.List ) {
1582
+ return instancesRawData;
1583
+ }
1584
+
1585
+ // Get the list type.
1586
+ var self = this,
1587
+ res = new( self.List || ML),
1588
+ // Did we get an `array`?
1589
+ arr = can.isArray(instancesRawData),
1590
+
1591
+ // Did we get a model list?
1592
+ ml = (instancesRawData instanceof ML),
1593
+
1594
+ // Get the raw `array` of objects.
1595
+ raw = arr ?
1596
+
1597
+ // If an `array`, return the `array`.
1598
+ instancesRawData :
1599
+
1600
+ // Otherwise if a model list.
1601
+ (ml ?
1602
+
1603
+ // Get the raw objects from the list.
1604
+ instancesRawData.serialize() :
1605
+
1606
+ // Get the object's data.
1607
+ instancesRawData.data),
1608
+ i = 0;
1609
+
1610
+
1611
+
1612
+ can.each(raw, function( rawPart ) {
1613
+ res.push( self.model( rawPart ));
1614
+ });
1615
+
1616
+ if ( ! arr ) { // Push other stuff onto `array`.
1617
+ can.each(instancesRawData, function(val, prop){
1618
+ if ( prop !== 'data' ) {
1619
+ res[prop] = val;
1620
+ }
1621
+ })
1622
+ }
1623
+ return res;
1624
+ },
1625
+ model: function( attributes ) {
1626
+ if (!attributes ) {
1627
+ return;
1628
+ }
1629
+ if ( attributes instanceof this ) {
1630
+ attributes = attributes.serialize();
1631
+ }
1632
+ var model = this.store[attributes[this.id]] ? this.store[attributes[this.id]].attr(attributes) : new this( attributes );
1633
+ if(this._reqs){
1634
+ this.store[attributes[this.id]] = model;
1635
+ }
1636
+ return model;
1637
+ }
1638
+ },
1639
+ {
1640
+ isNew: function() {
1641
+ var id = getId(this);
1642
+ return ! ( id || id === 0 ); // If `null` or `undefined`
1643
+ },
1644
+ save: function( success, error ) {
1645
+ return makeRequest(this, this.isNew() ? 'create' : 'update', success, error);
1646
+ },
1647
+ destroy: function( success, error ) {
1648
+ return makeRequest(this, 'destroy', success, error, 'destroyed');
1649
+ },
1650
+ bind : function(eventName){
1651
+ if ( ! ignoreHookup.test( eventName )) {
1652
+ if ( ! this._bindings ) {
1653
+ this.constructor.store[getId(this)] = this;
1654
+ this._bindings = 0;
1655
+ }
1656
+ this._bindings++;
1657
+ }
1658
+
1659
+ return can.Observe.prototype.bind.apply( this, arguments );
1660
+ },
1661
+ unbind : function(eventName){
1662
+ if(!ignoreHookup.test(eventName)) {
1663
+ this._bindings--;
1664
+ if(!this._bindings){
1665
+ delete this.constructor.store[getId(this)];
1666
+ }
1667
+ }
1668
+ return can.Observe.prototype.unbind.apply(this, arguments);
1669
+ },
1670
+ // Change `id`.
1671
+ ___set: function( prop, val ) {
1672
+ can.Observe.prototype.___set.call(this,prop, val)
1673
+ // If we add an `id`, move it to the store.
1674
+ if(prop === this.constructor.id && this._bindings){
1675
+ this.constructor.store[getId(this)] = this;
1676
+ }
1677
+ }
1678
+ });
1679
+
1680
+
1681
+
1682
+
1683
+ can.each({makeFindAll : "models", makeFindOne: "model"}, function(method, name){
1684
+ can.Model[name] = function(oldFind){
1685
+ return function(params, success, error){
1686
+ return pipe( oldFind.call( this, params ),
1687
+ this,
1688
+ method ).then(success,error)
1689
+ }
1690
+ };
1691
+ });
1692
+
1693
+ can.each([
1694
+ "created",
1695
+ "updated",
1696
+ "destroyed"], function( funcName ) {
1697
+ can.Model.prototype[funcName] = function( attrs ) {
1698
+ var stub,
1699
+ constructor = this.constructor;
1700
+
1701
+ // Update attributes if attributes have been passed
1702
+ stub = attrs && typeof attrs == 'object' && this.attr(attrs.attr ? attrs.attr() : attrs);
1703
+
1704
+ // Call event on the instance
1705
+ can.trigger(this,funcName);
1706
+ can.trigger(this,"change",funcName)
1707
+
1708
+
1709
+ // Call event on the instance's Class
1710
+ can.trigger(constructor,funcName, this);
1711
+ };
1712
+ });
1713
+
1714
+ // Model lists are just like `Observe.List` except that when their items are
1715
+ // destroyed, it automatically gets removed from the list.
1716
+ var ML = can.Observe.List('can.Model.List',{
1717
+ setup : function(){
1718
+ can.Observe.List.prototype.setup.apply(this, arguments );
1719
+ // Send destroy events.
1720
+ var self = this;
1721
+ this.bind('change', function(ev, how){
1722
+ if(/\w+\.destroyed/.test(how)){
1723
+ self.splice(self.indexOf(ev.target),1);
1724
+ }
1725
+ })
1726
+ }
1727
+ })
1728
+
1729
+ ;
1730
+
1731
+
1732
+ // ## deparam.js
1733
+ // `can.deparam`
1734
+ // _Takes a string of name value pairs and returns a Object literal that represents those params._
1735
+ var digitTest = /^\d+$/,
1736
+ keyBreaker = /([^\[\]]+)|(\[\])/g,
1737
+ paramTest = /([^?#]*)(#.*)?$/,
1738
+ prep = function( str ) {
1739
+ return decodeURIComponent( str.replace(/\+/g, " ") );
1740
+ }
1741
+
1742
+
1743
+ can.extend(can, {
1744
+ deparam: function(params){
1745
+
1746
+ var data = {},
1747
+ pairs, lastPart;
1748
+
1749
+ if ( params && paramTest.test( params )) {
1750
+
1751
+ pairs = params.split('&'),
1752
+
1753
+ can.each( pairs, function( pair ) {
1754
+
1755
+ var parts = pair.split('='),
1756
+ key = prep( parts.shift() ),
1757
+ value = prep( parts.join("=") );
1758
+
1759
+ current = data;
1760
+ parts = key.match(keyBreaker);
1761
+
1762
+ for ( var j = 0, l = parts.length - 1; j < l; j++ ) {
1763
+ if (!current[parts[j]] ) {
1764
+ // If what we are pointing to looks like an `array`
1765
+ current[parts[j]] = digitTest.test(parts[j+1]) || parts[j+1] == "[]" ? [] : {}
1766
+ }
1767
+ current = current[parts[j]];
1768
+ }
1769
+ lastPart = parts.pop()
1770
+ if ( lastPart == "[]" ) {
1771
+ current.push(value)
1772
+ } else {
1773
+ current[lastPart] = value;
1774
+ }
1775
+ });
1776
+ }
1777
+ return data;
1778
+ }
1779
+ });
1780
+
1781
+ // ## route.js
1782
+ // `can.route`
1783
+ // _Helps manage browser history (and client state) by synchronizing the
1784
+ // `window.location.hash` with a `can.Observe`._
1785
+ //
1786
+ // Helper methods used for matching routes.
1787
+ var
1788
+ // `RegExp` used to match route variables of the type ':name'.
1789
+ // Any word character or a period is matched.
1790
+ matcher = /\:([\w\.]+)/g,
1791
+ // Regular expression for identifying &amp;key=value lists.
1792
+ paramsMatcher = /^(?:&[^=]+=[^&]*)+/,
1793
+ // Converts a JS Object into a list of parameters that can be
1794
+ // inserted into an html element tag.
1795
+ makeProps = function( props ) {
1796
+ var tags = [];
1797
+ can.each(props, function(val, name){
1798
+ tags.push( ( name === 'className' ? 'class' : name )+ '="' +
1799
+ (name === "href" ? val : can.esc(val) ) + '"');
1800
+ });
1801
+ return tags.join(" ");
1802
+ },
1803
+ // Checks if a route matches the data provided. If any route variable
1804
+ // is not present in the data, the route does not match. If all route
1805
+ // variables are present in the data, the number of matches is returned
1806
+ // to allow discerning between general and more specific routes.
1807
+ matchesData = function(route, data) {
1808
+ var count = 0, i = 0, defaults = {};
1809
+ // look at default values, if they match ...
1810
+ for( var name in route.defaults ) {
1811
+ if(route.defaults[name] === data[name]){
1812
+ // mark as matched
1813
+ defaults[name] = 1;
1814
+ count++;
1815
+ }
1816
+ }
1817
+ for (; i < route.names.length; i++ ) {
1818
+ if (!data.hasOwnProperty(route.names[i]) ) {
1819
+ return -1;
1820
+ }
1821
+ if(!defaults[route.names[i]]){
1822
+ count++;
1823
+ }
1824
+
1825
+ }
1826
+
1827
+ return count;
1828
+ },
1829
+ onready = !0,
1830
+ location = window.location,
1831
+ each = can.each,
1832
+ extend = can.extend;
1833
+
1834
+ can.route = function( url, defaults ) {
1835
+ defaults = defaults || {}
1836
+ // Extract the variable names and replace with `RegExp` that will match
1837
+ // an atual URL with values.
1838
+ var names = [],
1839
+ test = url.replace(matcher, function( whole, name, i ) {
1840
+ names.push(name);
1841
+ var next = "\\"+( url.substr(i+whole.length,1) || "&" )
1842
+ // a name without a default value HAS to have a value
1843
+ // a name that has a default value can be empty
1844
+ // The `\\` is for string-escaping giving single `\` for `RegExp` escaping.
1845
+ return "([^" +next+"]"+(defaults[name] ? "*" : "+")+")"
1846
+ });
1847
+
1848
+ // Add route in a form that can be easily figured out.
1849
+ can.route.routes[url] = {
1850
+ // A regular expression that will match the route when variable values
1851
+ // are present; i.e. for `:page/:type` the `RegExp` is `/([\w\.]*)/([\w\.]*)/` which
1852
+ // will match for any value of `:page` and `:type` (word chars or period).
1853
+ test: new RegExp("^" + test+"($|&)"),
1854
+ // The original URL, same as the index for this entry in routes.
1855
+ route: url,
1856
+ // An `array` of all the variable names in this route.
1857
+ names: names,
1858
+ // Default values provided for the variables.
1859
+ defaults: defaults,
1860
+ // The number of parts in the URL separated by `/`.
1861
+ length: url.split('/').length
1862
+ }
1863
+ return can.route;
1864
+ };
1865
+
1866
+ extend(can.route, {
1867
+ param: function( data , _setRoute ) {
1868
+ // Check if the provided data keys match the names in any routes;
1869
+ // Get the one with the most matches.
1870
+ var route,
1871
+ // Need to have at least 1 match.
1872
+ matches = 0,
1873
+ matchCount,
1874
+ routeName = data.route,
1875
+ propCount = 0;
1876
+
1877
+ delete data.route;
1878
+
1879
+ each(data, function(){propCount++});
1880
+ // Otherwise find route.
1881
+ each(can.route.routes, function(temp, name){
1882
+ // best route is the first with all defaults matching
1883
+
1884
+
1885
+ matchCount = matchesData(temp, data);
1886
+ if ( matchCount > matches ) {
1887
+ route = temp;
1888
+ matches = matchCount
1889
+ }
1890
+ if(matchCount >= propCount){
1891
+ return false;
1892
+ }
1893
+ });
1894
+ // If we have a route name in our `can.route` data, and it's
1895
+ // just as good as what currently matches, use that
1896
+ if (can.route.routes[routeName] && matchesData(can.route.routes[routeName], data ) === matches) {
1897
+ route = can.route.routes[routeName];
1898
+ }
1899
+ // If this is match...
1900
+ if ( route ) {
1901
+ var cpy = extend({}, data),
1902
+ // Create the url by replacing the var names with the provided data.
1903
+ // If the default value is found an empty string is inserted.
1904
+ res = route.route.replace(matcher, function( whole, name ) {
1905
+ delete cpy[name];
1906
+ return data[name] === route.defaults[name] ? "" : encodeURIComponent( data[name] );
1907
+ }),
1908
+ after;
1909
+ // Remove matching default values
1910
+ each(route.defaults, function(val,name){
1911
+ if(cpy[name] === val) {
1912
+ delete cpy[name]
1913
+ }
1914
+ })
1915
+
1916
+ // The remaining elements of data are added as
1917
+ // `&amp;` separated parameters to the url.
1918
+ after = can.param(cpy);
1919
+ // if we are paraming for setting the hash
1920
+ // we also want to make sure the route value is updated
1921
+ if(_setRoute){
1922
+ can.route.attr('route',route.route);
1923
+ }
1924
+ return res + (after ? "&" + after : "")
1925
+ }
1926
+ // If no route was found, there is no hash URL, only paramters.
1927
+ return can.isEmptyObject(data) ? "" : "&" + can.param(data);
1928
+ },
1929
+ deparam: function( url ) {
1930
+ // See if the url matches any routes by testing it against the `route.test` `RegExp`.
1931
+ // By comparing the URL length the most specialized route that matches is used.
1932
+ var route = {
1933
+ length: -1
1934
+ };
1935
+ each(can.route.routes, function(temp, name){
1936
+ if ( temp.test.test(url) && temp.length > route.length ) {
1937
+ route = temp;
1938
+ }
1939
+ });
1940
+ // If a route was matched.
1941
+ if ( route.length > -1 ) {
1942
+ var // Since `RegExp` backreferences are used in `route.test` (parens)
1943
+ // the parts will contain the full matched string and each variable (back-referenced) value.
1944
+ parts = url.match(route.test),
1945
+ // Start will contain the full matched string; parts contain the variable values.
1946
+ start = parts.shift(),
1947
+ // The remainder will be the `&amp;key=value` list at the end of the URL.
1948
+ remainder = url.substr(start.length - (parts[parts.length-1] === "&" ? 1 : 0) ),
1949
+ // If there is a remainder and it contains a `&amp;key=value` list deparam it.
1950
+ obj = (remainder && paramsMatcher.test(remainder)) ? can.deparam( remainder.slice(1) ) : {};
1951
+
1952
+ // Add the default values for this route.
1953
+ obj = extend(true, {}, route.defaults, obj);
1954
+ // Overwrite each of the default values in `obj` with those in
1955
+ // parts if that part is not empty.
1956
+ each(parts,function(part, i){
1957
+ if ( part && part !== '&') {
1958
+ obj[route.names[i]] = decodeURIComponent( part );
1959
+ }
1960
+ });
1961
+ obj.route = route.route;
1962
+ return obj;
1963
+ }
1964
+ // If no route was matched, it is parsed as a `&amp;key=value` list.
1965
+ if ( url.charAt(0) !== '&' ) {
1966
+ url = '&' + url;
1967
+ }
1968
+ return paramsMatcher.test(url) ? can.deparam( url.slice(1) ) : {};
1969
+ },
1970
+ data: new can.Observe({}),
1971
+ routes: {},
1972
+ ready: function(val) {
1973
+ if( val === false ) {
1974
+ onready = val;
1975
+ }
1976
+ if( val === true || onready === true ) {
1977
+ setState();
1978
+ }
1979
+ return can.route;
1980
+ },
1981
+ url: function( options, merge ) {
1982
+ if (merge) {
1983
+ options = extend({}, curParams, options)
1984
+ }
1985
+ return "#!" + can.route.param(options)
1986
+ },
1987
+ link: function( name, options, props, merge ) {
1988
+ return "<a " + makeProps(
1989
+ extend({
1990
+ href: can.route.url(options, merge)
1991
+ }, props)) + ">" + name + "</a>";
1992
+ },
1993
+ current: function( options ) {
1994
+ return location.hash == "#!" + can.route.param(options)
1995
+ }
1996
+ });
1997
+
1998
+
1999
+ // The functions in the following list applied to `can.route` (e.g. `can.route.attr('...')`) will
2000
+ // instead act on the `can.route.data` observe.
2001
+ each(['bind','unbind','delegate','undelegate','attr','removeAttr'], function(name){
2002
+ can.route[name] = function(){
2003
+ return can.route.data[name].apply(can.route.data, arguments)
2004
+ }
2005
+ })
2006
+
2007
+ var // A ~~throttled~~ debounced function called multiple times will only fire once the
2008
+ // timer runs down. Each call resets the timer.
2009
+ timer,
2010
+ // Intermediate storage for `can.route.data`.
2011
+ curParams,
2012
+ // Deparameterizes the portion of the hash of interest and assign the
2013
+ // values to the `can.route.data` removing existing values no longer in the hash.
2014
+ // setState is called typically by hashchange which fires asynchronously
2015
+ // So it's possible that someone started changing the data before the
2016
+ // hashchange event fired. For this reason, it will not set the route data
2017
+ // if the data is changing and the hash already matches the hash that was set.
2018
+ setState = function() {
2019
+ var hash = location.href.split(/#!?/)[1] || ""
2020
+ curParams = can.route.deparam( hash );
2021
+
2022
+
2023
+ // if the hash data is currently changing, and
2024
+ // the hash is what we set it to anyway, do NOT change the hash
2025
+ if(!changingData || hash !== lastHash){
2026
+ can.route.attr(curParams, true);
2027
+ }
2028
+ },
2029
+ // The last hash caused by a data change
2030
+ lastHash,
2031
+ // Are data changes pending that haven't yet updated the hash
2032
+ changingData;
2033
+
2034
+ // If the hash changes, update the `can.route.data`.
2035
+ can.bind.call(window,'hashchange', setState);
2036
+
2037
+ // If the `can.route.data` changes, update the hash.
2038
+ // Using `.serialize()` retrieves the raw data contained in the `observable`.
2039
+ // This function is ~~throttled~~ debounced so it only updates once even if multiple values changed.
2040
+ // This might be able to use batchNum and avoid this.
2041
+ can.route.bind("change", function(ev, attr) {
2042
+ // indicate that data is changing
2043
+ changingData = 1;
2044
+ clearTimeout( timer );
2045
+ timer = setTimeout(function() {
2046
+ // indicate that the hash is set to look like the data
2047
+ changingData = 0;
2048
+ var serialized = can.route.data.serialize();
2049
+ location.hash = "#!" + (lastHash = can.route.param(serialized, true))
2050
+ }, 1);
2051
+ });
2052
+ // `onready` event...
2053
+ can.bind.call(document,"ready",can.route.ready);
2054
+
2055
+ (function() {
2056
+
2057
+
2058
+ // ## control.js
2059
+ // `can.Control`
2060
+ // _Controller_
2061
+
2062
+ // Binds an element, returns a function that unbinds.
2063
+ var bind = function( el, ev, callback ) {
2064
+
2065
+ can.bind.call( el, ev, callback )
2066
+
2067
+ return function() {
2068
+ can.unbind.call(el, ev, callback);
2069
+ };
2070
+ },
2071
+ isFunction = can.isFunction,
2072
+ extend = can.extend,
2073
+ each = can.each,
2074
+ slice = [].slice,
2075
+ paramReplacer = /\{([^\}]+)\}/g,
2076
+ special = can.getObject("$.event.special") || {},
2077
+
2078
+ // Binds an element, returns a function that unbinds.
2079
+ delegate = function( el, selector, ev, callback ) {
2080
+ can.delegate.call(el, selector, ev, callback)
2081
+ return function() {
2082
+ can.undelegate.call(el, selector, ev, callback);
2083
+ };
2084
+ },
2085
+
2086
+ // Calls bind or unbind depending if there is a selector.
2087
+ binder = function( el, ev, callback, selector ) {
2088
+ return selector ?
2089
+ delegate( el, can.trim( selector ), ev, callback ) :
2090
+ bind( el, ev, callback );
2091
+ },
2092
+
2093
+ // Moves `this` to the first argument, wraps it with `jQuery` if it's an element
2094
+ shifter = function shifter(context, name) {
2095
+ var method = typeof name == "string" ? context[name] : name;
2096
+ if(!isFunction(method)){
2097
+ method = context[method];
2098
+ }
2099
+ return function() {
2100
+ context.called = name;
2101
+ return method.apply(context, [this.nodeName ? can.$(this) : this].concat( slice.call(arguments, 0)));
2102
+ };
2103
+ },
2104
+ basicProcessor;
2105
+
2106
+ can.Construct("can.Control",
2107
+ {
2108
+ // Setup pre-processes which methods are event listeners.
2109
+ setup: function() {
2110
+
2111
+ // Allow contollers to inherit "defaults" from super-classes as it
2112
+ // done in `can.Construct`
2113
+ can.Construct.setup.apply( this, arguments );
2114
+
2115
+ // If you didn't provide a name, or are `control`, don't do anything.
2116
+ if ( this !== can.Control ) {
2117
+
2118
+ // Cache the underscored names.
2119
+ var control = this,
2120
+ funcName;
2121
+
2122
+ // Calculate and cache actions.
2123
+ control.actions = {};
2124
+ for ( funcName in control.prototype ) {
2125
+ if ( control._isAction(funcName) ) {
2126
+ control.actions[funcName] = control._action(funcName);
2127
+ }
2128
+ }
2129
+ }
2130
+ },
2131
+ // Return `true` if is an action.
2132
+ _isAction: function( methodName ) {
2133
+
2134
+ var val = this.prototype[methodName],
2135
+ type = typeof val;
2136
+ // if not the constructor
2137
+ return (methodName !== 'constructor') &&
2138
+ // and is a function or links to a function
2139
+ ( type == "function" || (type == "string" && isFunction(this.prototype[val] ) ) ) &&
2140
+ // and is in special, a processor, or has a funny character
2141
+ !! ( special[methodName] || processors[methodName] || /[^\w]/.test(methodName) );
2142
+ },
2143
+ // Takes a method name and the options passed to a control
2144
+ // and tries to return the data necessary to pass to a processor
2145
+ // (something that binds things).
2146
+ _action: function( methodName, options ) {
2147
+
2148
+ // If we don't have options (a `control` instance), we'll run this
2149
+ // later.
2150
+ paramReplacer.lastIndex = 0;
2151
+ if ( options || ! paramReplacer.test( methodName )) {
2152
+ // If we have options, run sub to replace templates `{}` with a
2153
+ // value from the options or the window
2154
+ var convertedName = options ? can.sub(methodName, [options, window]) : methodName,
2155
+
2156
+ // If a `{}` resolves to an object, `convertedName` will be
2157
+ // an array
2158
+ arr = can.isArray(convertedName),
2159
+
2160
+ // Get the parts of the function
2161
+ // `[convertedName, delegatePart, eventPart]`
2162
+ // `/^(?:(.*?)\s)?([\w\.\:>]+)$/` - Breaker `RegExp`.
2163
+ parts = (arr ? convertedName[1] : convertedName).match(/^(?:(.*?)\s)?([\w\.\:>]+)$/);
2164
+
2165
+ var event = parts[2],
2166
+ processor = processors[event] || basicProcessor;
2167
+ return {
2168
+ processor: processor,
2169
+ parts: parts,
2170
+ delegate : arr ? convertedName[0] : undefined
2171
+ };
2172
+ }
2173
+ },
2174
+ // An object of `{eventName : function}` pairs that Control uses to
2175
+ // hook up events auto-magically.
2176
+ processors: {},
2177
+ // A object of name-value pairs that act as default values for a
2178
+ // control instance
2179
+ defaults: {}
2180
+ },
2181
+ {
2182
+ // Sets `this.element`, saves the control in `data, binds event
2183
+ // handlers.
2184
+ setup: function( element, options ) {
2185
+
2186
+ var cls = this.constructor,
2187
+ pluginname = cls.pluginName || cls._fullName,
2188
+ arr;
2189
+
2190
+ // Want the raw element here.
2191
+ this.element = can.$(element)
2192
+
2193
+ if ( pluginname && pluginname !== 'can_control') {
2194
+ // Set element and `className` on element.
2195
+ this.element.addClass(pluginname);
2196
+ }
2197
+
2198
+ (arr = can.data(this.element,"controls")) || can.data(this.element,"controls",arr = []);
2199
+ arr.push(this);
2200
+
2201
+ // Option merging.
2202
+ this.options = extend({}, cls.defaults, options);
2203
+
2204
+ // Bind all event handlers.
2205
+ this.on();
2206
+
2207
+ // Get's passed into `init`.
2208
+ return [this.element, this.options];
2209
+ },
2210
+ on: function( el, selector, eventName, func ) {
2211
+
2212
+ if ( ! el ) {
2213
+
2214
+ // Adds bindings.
2215
+ this.off();
2216
+
2217
+ // Go through the cached list of actions and use the processor
2218
+ // to bind
2219
+ var cls = this.constructor,
2220
+ bindings = this._bindings,
2221
+ actions = cls.actions,
2222
+ element = this.element,
2223
+ destroyCB = shifter(this,"destroy"),
2224
+ funcName, ready;
2225
+
2226
+ for ( funcName in actions ) {
2227
+ if ( actions.hasOwnProperty( funcName )) {
2228
+ ready = actions[funcName] || cls._action(funcName, this.options);
2229
+ bindings.push(
2230
+ ready.processor(ready.delegate || element,
2231
+ ready.parts[2],
2232
+ ready.parts[1],
2233
+ funcName,
2234
+ this));
2235
+ }
2236
+ }
2237
+
2238
+
2239
+ // Setup to be destroyed...
2240
+ // don't bind because we don't want to remove it.
2241
+ can.bind.call(element,"destroyed", destroyCB);
2242
+ bindings.push(function( el ) {
2243
+ can.unbind.call(el,"destroyed", destroyCB);
2244
+ });
2245
+ return bindings.length;
2246
+ }
2247
+
2248
+ if ( typeof el == 'string' ) {
2249
+ func = eventName;
2250
+ eventName = selector;
2251
+ selector = el;
2252
+ el = this.element;
2253
+ }
2254
+
2255
+ if ( typeof func == 'string' ) {
2256
+ func = shifter(this,func);
2257
+ }
2258
+
2259
+ this._bindings.push( binder( el, eventName, func, selector ));
2260
+
2261
+ return this._bindings.length;
2262
+ },
2263
+ // Unbinds all event handlers on the controller.
2264
+ off : function(){
2265
+ var el = this.element[0]
2266
+ each(this._bindings || [], function( value ) {
2267
+ value(el);
2268
+ });
2269
+ // Adds bindings.
2270
+ this._bindings = [];
2271
+ },
2272
+ // Prepares a `control` for garbage collection
2273
+ destroy: function() {
2274
+ var Class = this.constructor,
2275
+ pluginName = Class.pluginName || Class._fullName,
2276
+ controls;
2277
+
2278
+ // Unbind bindings.
2279
+ this.off();
2280
+
2281
+ if(pluginName && pluginName !== 'can_control'){
2282
+ // Remove the `className`.
2283
+ this.element.removeClass(pluginName);
2284
+ }
2285
+
2286
+ // Remove from `data`.
2287
+ controls = can.data(this.element,"controls");
2288
+ controls.splice(can.inArray(this, controls),1);
2289
+
2290
+ can.trigger( this, "destroyed"); // In case we want to know if the `control` is removed.
2291
+
2292
+ this.element = null;
2293
+ }
2294
+ });
2295
+
2296
+ var processors = can.Control.processors,
2297
+
2298
+ // Processors do the binding.
2299
+ // They return a function that unbinds when called.
2300
+ //
2301
+ // The basic processor that binds events.
2302
+ basicProcessor = function( el, event, selector, methodName, control ) {
2303
+ return binder( el, event, shifter(control, methodName), selector);
2304
+ };
2305
+
2306
+ // Set common events to be processed as a `basicProcessor`
2307
+ each(["change", "click", "contextmenu", "dblclick", "keydown", "keyup",
2308
+ "keypress", "mousedown", "mousemove", "mouseout", "mouseover",
2309
+ "mouseup", "reset", "resize", "scroll", "select", "submit", "focusin",
2310
+ "focusout", "mouseenter", "mouseleave"], function( v ) {
2311
+ processors[v] = basicProcessor;
2312
+ });
2313
+
2314
+ }());
2315
+
2316
+
2317
+ // ## control/route.js
2318
+ // _Controller route integration._
2319
+
2320
+ can.Control.processors.route = function( el, event, selector, funcName, controller ) {
2321
+ can.route( selector || "" )
2322
+ var batchNum,
2323
+ check = function( ev, attr, how ) {
2324
+ if ( can.route.attr('route') === ( selector || "" ) &&
2325
+ ( ev.batchNum === undefined || ev.batchNum !== batchNum ) ) {
2326
+
2327
+ batchNum = ev.batchNum;
2328
+
2329
+ var d = can.route.attr();
2330
+ delete d.route;
2331
+ if(can.isFunction(controller[funcName])){
2332
+ controller[funcName]( d )
2333
+ }else {
2334
+ controller[controller[funcName]](d)
2335
+ }
2336
+
2337
+ }
2338
+ }
2339
+ can.route.bind( 'change', check );
2340
+ return function() {
2341
+ can.route.unbind( 'change', check )
2342
+ }
2343
+ }
2344
+ ;
2345
+
2346
+ // ## view.js
2347
+ // `can.view`
2348
+ // _Templating abstraction._
2349
+
2350
+ var isFunction = can.isFunction,
2351
+ makeArray = can.makeArray,
2352
+ // Used for hookup `id`s.
2353
+ hookupId = 1,
2354
+ $view = can.view = function(view, data, helpers, callback){
2355
+ // Get the result.
2356
+ var result = $view.render(view, data, helpers, callback);
2357
+ if(can.isDeferred(result)){
2358
+ return result.pipe(function(result){
2359
+ return $view.frag(result);
2360
+ })
2361
+ }
2362
+
2363
+ // Convert it into a dom frag.
2364
+ return $view.frag(result);
2365
+ };
2366
+
2367
+ can.extend( $view, {
2368
+ // creates a frag and hooks it up all at once
2369
+ frag: function(result, parentNode ){
2370
+ return $view.hookup( $view.fragment(result), parentNode );
2371
+ },
2372
+ // simply creates a frag
2373
+ // this is used internally to create a frag
2374
+ // insert it
2375
+ // then hook it up
2376
+ fragment: function(result){
2377
+ var frag = can.buildFragment(result,document.body);
2378
+ // If we have an empty frag...
2379
+ if(!frag.childNodes.length) {
2380
+ frag.appendChild(document.createTextNode(''))
2381
+ }
2382
+ return frag;
2383
+ },
2384
+ // Convert a path like string into something that's ok for an `element` ID.
2385
+ toId : function( src ) {
2386
+ return can.map(src.toString().split(/\/|\./g), function( part ) {
2387
+ // Dont include empty strings in toId functions
2388
+ if ( part ) {
2389
+ return part;
2390
+ }
2391
+ }).join("_");
2392
+ },
2393
+ hookup: function(fragment, parentNode ){
2394
+ var hookupEls = [],
2395
+ id,
2396
+ func,
2397
+ el,
2398
+ i=0;
2399
+
2400
+ // Get all `childNodes`.
2401
+ can.each(fragment.childNodes ? can.makeArray(fragment.childNodes) : fragment, function(node){
2402
+ if(node.nodeType === 1){
2403
+ hookupEls.push(node)
2404
+ hookupEls.push.apply(hookupEls, can.makeArray( node.getElementsByTagName('*')))
2405
+ }
2406
+ });
2407
+ // Filter by `data-view-id` attribute.
2408
+ for (; el = hookupEls[i++]; ) {
2409
+
2410
+ if ( el.getAttribute && (id = el.getAttribute('data-view-id')) && (func = $view.hookups[id]) ) {
2411
+ func(el, parentNode, id);
2412
+ delete $view.hookups[id];
2413
+ el.removeAttribute('data-view-id');
2414
+ }
2415
+ }
2416
+ return fragment;
2417
+ },
2418
+ hookups: {},
2419
+ hook: function( cb ) {
2420
+ $view.hookups[++hookupId] = cb;
2421
+ return " data-view-id='"+hookupId+"'";
2422
+ },
2423
+ cached: {},
2424
+ cache: true,
2425
+ register: function( info ) {
2426
+ this.types["." + info.suffix] = info;
2427
+ },
2428
+ types: {},
2429
+ ext: ".ejs",
2430
+ registerScript: function() {},
2431
+ preload: function( ) {},
2432
+ render: function( view, data, helpers, callback ) {
2433
+ // If helpers is a `function`, it is actually a callback.
2434
+ if ( isFunction( helpers )) {
2435
+ callback = helpers;
2436
+ helpers = undefined;
2437
+ }
2438
+
2439
+ // See if we got passed any deferreds.
2440
+ var deferreds = getDeferreds(data);
2441
+
2442
+
2443
+ if ( deferreds.length ) { // Does data contain any deferreds?
2444
+ // The deferred that resolves into the rendered content...
2445
+ var deferred = new can.Deferred();
2446
+
2447
+ // Add the view request to the list of deferreds.
2448
+ deferreds.push(get(view, true))
2449
+
2450
+ // Wait for the view and all deferreds to finish...
2451
+ can.when.apply(can, deferreds).then(function( resolved ) {
2452
+ // Get all the resolved deferreds.
2453
+ var objs = makeArray(arguments),
2454
+ // Renderer is the last index of the data.
2455
+ renderer = objs.pop(),
2456
+ // The result of the template rendering with data.
2457
+ result;
2458
+
2459
+ // Make data look like the resolved deferreds.
2460
+ if ( can.isDeferred(data) ) {
2461
+ data = usefulPart(resolved);
2462
+ }
2463
+ else {
2464
+ // Go through each prop in data again and
2465
+ // replace the defferreds with what they resolved to.
2466
+ for ( var prop in data ) {
2467
+ if ( can.isDeferred(data[prop]) ) {
2468
+ data[prop] = usefulPart(objs.shift());
2469
+ }
2470
+ }
2471
+ }
2472
+ // Get the rendered result.
2473
+ result = renderer(data, helpers);
2474
+
2475
+ // Resolve with the rendered view.
2476
+ deferred.resolve(result);
2477
+ // If there's a `callback`, call it back with the result.
2478
+ callback && callback(result);
2479
+ });
2480
+ // Return the deferred...
2481
+ return deferred;
2482
+ }
2483
+ else {
2484
+ // No deferreds! Render this bad boy.
2485
+ var response,
2486
+ // If there's a `callback` function
2487
+ async = isFunction( callback ),
2488
+ // Get the `view` type
2489
+ deferred = get(view, async);
2490
+
2491
+ // If we are `async`...
2492
+ if ( async ) {
2493
+ // Return the deferred
2494
+ response = deferred;
2495
+ // And fire callback with the rendered result.
2496
+ deferred.then(function( renderer ) {
2497
+ callback(renderer(data, helpers))
2498
+ })
2499
+ } else {
2500
+ // Otherwise, the deferred is complete, so
2501
+ // set response to the result of the rendering.
2502
+ deferred.then(function( renderer ) {
2503
+ response = renderer(data, helpers);
2504
+ });
2505
+ }
2506
+
2507
+ return response;
2508
+ }
2509
+ }
2510
+ });
2511
+ // Returns `true` if something looks like a deferred.
2512
+ can.isDeferred = function( obj ) {
2513
+ return obj && isFunction(obj.then) && isFunction(obj.pipe) // Check if `obj` is a `can.Deferred`.
2514
+ }
2515
+ // Makes sure there's a template, if not, have `steal` provide a warning.
2516
+ var checkText = function( text, url ) {
2517
+ if ( ! text.length ) {
2518
+ //@steal-remove-start
2519
+ //@steal-remove-end
2520
+ throw "can.view: No template or empty template:" + url;
2521
+ }
2522
+ },
2523
+ // `Returns a `view` renderer deferred.
2524
+ // `url` - The url to the template.
2525
+ // `async` - If the ajax request should be asynchronous.
2526
+ // Returns a deferred.
2527
+ get = function( url, async ) {
2528
+
2529
+
2530
+ var suffix = url.match(/\.[\w\d]+$/),
2531
+ type,
2532
+ // If we are reading a script element for the content of the template,
2533
+ // `el` will be set to that script element.
2534
+ el,
2535
+ // A unique identifier for the view (used for caching).
2536
+ // This is typically derived from the element id or
2537
+ // the url for the template.
2538
+ id,
2539
+ // The ajax request used to retrieve the template content.
2540
+ jqXHR,
2541
+ // Used to generate the response.
2542
+ response = function( text ) {
2543
+ // Get the renderer function.
2544
+ var func = type.renderer(id, text),
2545
+ d = new can.Deferred();
2546
+ d.resolve(func)
2547
+ // Cache if we are caching.
2548
+ if ( $view.cache ) {
2549
+ $view.cached[id] = d;
2550
+ }
2551
+ // Return the objects for the response's `dataTypes`
2552
+ // (in this case view).
2553
+ return d;
2554
+ };
2555
+
2556
+ //If the url has a #, we assume we want to use an inline template
2557
+ //from a script element and not current page's HTML
2558
+ if( url.match(/^#/) ) {
2559
+ url = url.substr(1);
2560
+ }
2561
+ // If we have an inline template, derive the suffix from the `text/???` part.
2562
+ // This only supports `<script>` tags.
2563
+ if ( el = document.getElementById(url) ) {
2564
+ suffix = "."+el.type.match(/\/(x\-)?(.+)/)[2];
2565
+ }
2566
+
2567
+ // If there is no suffix, add one.
2568
+ if (!suffix && !$view.cached[url] ) {
2569
+ url += ( suffix = $view.ext );
2570
+ }
2571
+
2572
+ if ( can.isArray( suffix )) {
2573
+ suffix = suffix[0]
2574
+ }
2575
+
2576
+ // Convert to a unique and valid id.
2577
+ id = can.view.toId(url);
2578
+
2579
+ // If an absolute path, use `steal` to get it.
2580
+ // You should only be using `//` if you are using `steal`.
2581
+ if ( url.match(/^\/\//) ) {
2582
+ var sub = url.substr(2);
2583
+ url = ! window.steal ?
2584
+ "/" + sub :
2585
+ steal.root.mapJoin(sub);
2586
+ }
2587
+
2588
+ // Set the template engine type.
2589
+ type = $view.types[suffix];
2590
+
2591
+ // If it is cached,
2592
+ if ( $view.cached[id] ) {
2593
+ // Return the cached deferred renderer.
2594
+ return $view.cached[id];
2595
+
2596
+ // Otherwise if we are getting this from a `<script>` element.
2597
+ } else if ( el ) {
2598
+ // Resolve immediately with the element's `innerHTML`.
2599
+ return response(el.innerHTML);
2600
+ } else {
2601
+ // Make an ajax request for text.
2602
+ var d = new can.Deferred();
2603
+ can.ajax({
2604
+ async: async,
2605
+ url: url,
2606
+ dataType: "text",
2607
+ error: function(jqXHR) {
2608
+ checkText("", url);
2609
+ d.reject(jqXHR);
2610
+ },
2611
+ success: function( text ) {
2612
+ // Make sure we got some text back.
2613
+ checkText(text, url);
2614
+ d.resolve(type.renderer(id, text))
2615
+ // Cache if if we are caching.
2616
+ if ( $view.cache ) {
2617
+ $view.cached[id] = d;
2618
+ }
2619
+
2620
+ }
2621
+ });
2622
+ return d;
2623
+ }
2624
+ },
2625
+ // Gets an `array` of deferreds from an `object`.
2626
+ // This only goes one level deep.
2627
+ getDeferreds = function( data ) {
2628
+ var deferreds = [];
2629
+
2630
+ // pull out deferreds
2631
+ if ( can.isDeferred(data) ) {
2632
+ return [data]
2633
+ } else {
2634
+ for ( var prop in data ) {
2635
+ if ( can.isDeferred(data[prop]) ) {
2636
+ deferreds.push(data[prop]);
2637
+ }
2638
+ }
2639
+ }
2640
+ return deferreds;
2641
+ },
2642
+ // Gets the useful part of a resolved deferred.
2643
+ // This is for `model`s and `can.ajax` that resolve to an `array`.
2644
+ usefulPart = function( resolved ) {
2645
+ return can.isArray(resolved) && resolved[1] === 'success' ? resolved[0] : resolved
2646
+ };
2647
+
2648
+
2649
+ if ( window.steal ) {
2650
+ steal.type("view js", function( options, success, error ) {
2651
+ var type = can.view.types["." + options.type],
2652
+ id = can.view.toId(options.rootSrc);
2653
+
2654
+ options.text = "steal('" + (type.plugin || "can/view/" + options.type) + "').then(function($){" + "can.view.preload('" + id + "'," + options.text + ");\n})";
2655
+ success();
2656
+ })
2657
+ }
2658
+
2659
+ //!steal-pluginify-remove-start
2660
+ can.extend(can.view, {
2661
+ register: function( info ) {
2662
+ this.types["." + info.suffix] = info;
2663
+
2664
+ if ( window.steal ) {
2665
+ steal.type(info.suffix + " view js", function( options, success, error ) {
2666
+ var type = can.view.types["." + options.type],
2667
+ id = can.view.toId(options.rootSrc+'');
2668
+
2669
+ options.text = type.script(id, options.text)
2670
+ success();
2671
+ })
2672
+ }
2673
+ can.view[info.suffix] = function(id, text){
2674
+ $view.preload(id, info.renderer(id, text) )
2675
+ }
2676
+ },
2677
+ registerScript: function( type, id, src ) {
2678
+ return "can.view.preload('" + id + "'," + $view.types["." + type].script(id, src) + ");";
2679
+ },
2680
+ preload: function( id, renderer ) {
2681
+ can.view.cached[id] = new can.Deferred().resolve(function( data, helpers ) {
2682
+ return renderer.call(data, data, helpers);
2683
+ });
2684
+ }
2685
+
2686
+ });
2687
+ //!steal-pluginify-remove-end
2688
+
2689
+
2690
+ // returns the
2691
+ // - observes and attr methods are called by func
2692
+ // - the value returned by func
2693
+ // ex: `{value: 100, observed: [{obs: o, attr: "completed"}]}`
2694
+ var getValueAndObserved = function(func, self){
2695
+
2696
+ var oldReading;
2697
+ if (can.Observe) {
2698
+ // Set a callback on can.Observe to know
2699
+ // when an attr is read.
2700
+ // Keep a reference to the old reader
2701
+ // if there is one. This is used
2702
+ // for nested live binding.
2703
+ oldReading = can.Observe.__reading;
2704
+ can.Observe.__reading = function(obj, attr){
2705
+ // Add the observe and attr that was read
2706
+ // to `observed`
2707
+ observed.push({
2708
+ obj: obj,
2709
+ attr: attr
2710
+ });
2711
+ }
2712
+ }
2713
+
2714
+ var observed = [],
2715
+ // Call the "wrapping" function to get the value. `observed`
2716
+ // will have the observe/attribute pairs that were read.
2717
+ value = func.call(self);
2718
+
2719
+ // Set back so we are no longer reading.
2720
+ if(can.Observe){
2721
+ can.Observe.__reading = oldReading;
2722
+ }
2723
+ return {
2724
+ value : value,
2725
+ observed : observed
2726
+ }
2727
+ },
2728
+ // Calls `callback(newVal, oldVal)` everytime an observed property
2729
+ // called within `getterSetter` is changed and creates a new result of `getterSetter`.
2730
+ // Also returns an object that can teardown all event handlers.
2731
+ computeBinder = function(getterSetter, context, callback){
2732
+ // track what we are observing
2733
+ var observing = {},
2734
+ // a flag indicating if this observe/attr pair is already bound
2735
+ matched = true,
2736
+ // the data to return
2737
+ data = {
2738
+ // we will maintain the value while live-binding is taking place
2739
+ value : undefined,
2740
+ // a teardown method that stops listening
2741
+ teardown: function(){
2742
+ for ( var name in observing ) {
2743
+ var ob = observing[name];
2744
+ ob.observe.obj.unbind(ob.observe.attr, onchanged);
2745
+ delete observing[name];
2746
+ }
2747
+ }
2748
+ };
2749
+
2750
+ // when a property value is cahnged
2751
+ var onchanged = function(){
2752
+ // store the old value
2753
+ var oldValue = data.value,
2754
+ // get the new value
2755
+ newvalue = getValueAndBind();
2756
+ // update the value reference (in case someone reads)
2757
+ data.value = newvalue
2758
+ // if a change happened
2759
+ if(newvalue !== oldValue){
2760
+ callback(newvalue, oldValue);
2761
+ };
2762
+ };
2763
+
2764
+ // gets the value returned by `getterSetter` and also binds to any attributes
2765
+ // read by the call
2766
+ var getValueAndBind = function(){
2767
+ var info = getValueAndObserved( getterSetter, context ),
2768
+ newObserveSet = info.observed;
2769
+
2770
+ var value = info.value;
2771
+ matched = !matched;
2772
+
2773
+ // go through every attribute read by this observe
2774
+ can.each(newObserveSet, function(ob){
2775
+ // if the observe/attribute pair is being observed
2776
+ if(observing[ob.obj._namespace+"|"+ob.attr]){
2777
+ // mark at as observed
2778
+ observing[ob.obj._namespace+"|"+ob.attr].matched = matched;
2779
+ } else {
2780
+ // otherwise, set the observe/attribute on oldObserved, marking it as being observed
2781
+ observing[ob.obj._namespace+"|"+ob.attr] = {
2782
+ matched: matched,
2783
+ observe: ob
2784
+ };
2785
+ ob.obj.bind(ob.attr, onchanged)
2786
+ }
2787
+ });
2788
+
2789
+ // Iterate through oldObserved, looking for observe/attributes
2790
+ // that are no longer being bound and unbind them
2791
+ for ( var name in observing ) {
2792
+ var ob = observing[name];
2793
+ if(ob.matched !== matched){
2794
+ ob.observe.obj.unbind(ob.observe.attr, onchanged);
2795
+ delete observing[name];
2796
+ }
2797
+ }
2798
+ return value;
2799
+ }
2800
+ // set the initial value
2801
+ data.value = getValueAndBind();
2802
+ data.isListening = ! can.isEmptyObject(observing);
2803
+ return data;
2804
+ }
2805
+
2806
+ // if no one is listening ... we can not calculate every time
2807
+ can.compute = function(getterSetter, context){
2808
+ if(getterSetter.isComputed){
2809
+ return getterSetter;
2810
+ }
2811
+ // get the value right away
2812
+ // TODO: eventually we can defer this until a bind or a read
2813
+ var computedData,
2814
+ bindings = 0,
2815
+ computed,
2816
+ canbind = true;
2817
+ if(typeof getterSetter === "function"){
2818
+ computed = function(value){
2819
+ if(value === undefined){
2820
+ // we are reading
2821
+ if(computedData){
2822
+ return computedData.value;
2823
+ } else {
2824
+ return getterSetter.call(context || this)
2825
+ }
2826
+ } else {
2827
+ return getterSetter.apply(context || this, arguments)
2828
+ }
2829
+ }
2830
+
2831
+ } else {
2832
+ // we just gave it a value
2833
+ computed = function(val){
2834
+ if(val === undefined){
2835
+ return getterSetter;
2836
+ } else {
2837
+ var old = getterSetter;
2838
+ getterSetter = val;
2839
+ if( old !== val){
2840
+ can.trigger(computed, "change",[val, old]);
2841
+ }
2842
+
2843
+ return val;
2844
+ }
2845
+
2846
+ }
2847
+ canbind = false;
2848
+ }
2849
+ computed.isComputed = true;
2850
+
2851
+
2852
+ computed.bind = function(ev, handler){
2853
+ can.addEvent.apply(computed, arguments);
2854
+ if( bindings === 0 && canbind){
2855
+ // setup live-binding
2856
+ computedData = computeBinder(getterSetter, context || this, function(newValue, oldValue){
2857
+ can.trigger(computed, "change",[newValue, oldValue])
2858
+ });
2859
+ }
2860
+ bindings++;
2861
+ }
2862
+ computed.unbind = function(ev, handler){
2863
+ can.removeEvent.apply(computed, arguments);
2864
+ bindings--;
2865
+ if( bindings === 0 && canbind){
2866
+ computedData.teardown();
2867
+ }
2868
+
2869
+ };
2870
+ return computed;
2871
+ };
2872
+ can.compute.binder = computeBinder;
2873
+
2874
+ // ## ejs.js
2875
+ // `can.EJS`
2876
+ // _Embedded JavaScript Templates._
2877
+
2878
+ // Helper methods.
2879
+ var myEval = function( script ) {
2880
+ eval(script);
2881
+ },
2882
+ extend = can.extend,
2883
+ // Regular expressions for caching.
2884
+ quickFunc = /\s*\(([\$\w]+)\)\s*->([^\n]*)/,
2885
+ attrReg = /([^\s]+)=$/,
2886
+ newLine = /(\r|\n)+/g,
2887
+ attributeReplace = /__!!__/g,
2888
+ tagMap = {
2889
+ "": "span",
2890
+ table: "tr",
2891
+ tr: "td",
2892
+ ol: "li",
2893
+ ul: "li",
2894
+ tbody: "tr",
2895
+ thead: "tr",
2896
+ tfoot: "tr"
2897
+ },
2898
+ // Escapes characters starting with `\`.
2899
+ clean = function( content ) {
2900
+ return content
2901
+ .split('\\').join("\\\\")
2902
+ .split("\n").join("\\n")
2903
+ .split('"').join('\\"')
2904
+ .split("\t").join("\\t");
2905
+ },
2906
+ bracketNum = function(content){
2907
+ return (--content.split("{").length) - (--content.split("}").length);
2908
+ },
2909
+ // Cross-browser attribute methods.
2910
+ // These should be mapped to the underlying library.
2911
+ attrMap = {
2912
+ "class" : "className"
2913
+ },
2914
+ bool = can.each(["checked","disabled","readonly","required"], function(n){
2915
+ attrMap[n] = n;
2916
+ }),
2917
+ setAttr = function(el, attrName, val){
2918
+ attrMap[attrName] ?
2919
+ (el[attrMap[attrName]] = can.inArray(attrName,bool) > -1? true : val):
2920
+ el.setAttribute(attrName, val);
2921
+ },
2922
+ getAttr = function(el, attrName){
2923
+ return attrMap[attrName]?
2924
+ el[attrMap[attrName]]:
2925
+ el.getAttribute(attrName);
2926
+ },
2927
+ removeAttr = function(el, attrName){
2928
+ if(can.inArray(attrName,bool) > -1){
2929
+ el[attrName] = false;
2930
+ } else{
2931
+ el.removeAttribute(attrName)
2932
+ }
2933
+ },
2934
+ // a helper to get the parentNode for a given element el
2935
+ // if el is in a documentFragment, it will return defaultParentNode
2936
+ getParentNode = function(el, defaultParentNode){
2937
+ return defaultParentNode && el.parentNode.nodeType === 11 ? defaultParentNode : el.parentNode;
2938
+ },
2939
+ // helper to know if property is not an expando on oldObserved's list of observes
2940
+ // this should probably be removed and oldObserved should just have a
2941
+ // property with observes
2942
+ observeProp = function(name){
2943
+ return name.indexOf("|") >= 0;
2944
+ },
2945
+ // Returns escaped/sanatized content for anything other than a live-binding
2946
+ contentEscape = function( txt ) {
2947
+ return (typeof txt == 'string' || typeof txt == 'number') ?
2948
+ can.esc( txt ) :
2949
+ contentText(txt);
2950
+ },
2951
+ // Returns text content for anything other than a live-binding
2952
+ contentText = function( input ) {
2953
+
2954
+ // If it's a string, return.
2955
+ if ( typeof input == 'string' ) {
2956
+ return input;
2957
+ }
2958
+ // If has no value, return an empty string.
2959
+ if ( !input && input != 0 ) {
2960
+ return '';
2961
+ }
2962
+
2963
+ // If it's an object, and it has a hookup method.
2964
+ var hook = (input.hookup &&
2965
+
2966
+ // Make a function call the hookup method.
2967
+ function( el, id ) {
2968
+ input.hookup.call(input, el, id);
2969
+ }) ||
2970
+
2971
+ // Or if it's a `function`, just use the input.
2972
+ (typeof input == 'function' && input);
2973
+
2974
+ // Finally, if there is a `function` to hookup on some dom,
2975
+ // add it to pending hookups.
2976
+ if ( hook ) {
2977
+ pendingHookups.push(hook);
2978
+ return '';
2979
+ }
2980
+
2981
+ // Finally, if all else is `false`, `toString()` it.
2982
+ return "" + input;
2983
+ },
2984
+ // The EJS constructor function
2985
+ EJS = function( options ) {
2986
+ // Supports calling EJS without the constructor
2987
+ // This returns a function that renders the template.
2988
+ if ( this.constructor != EJS ) {
2989
+ var ejs = new EJS(options);
2990
+ return function( data, helpers ) {
2991
+ return ejs.render(data, helpers);
2992
+ };
2993
+ }
2994
+ // If we get a `function` directly, it probably is coming from
2995
+ // a `steal`-packaged view.
2996
+ if ( typeof options == "function" ) {
2997
+ this.template = {
2998
+ fn: options
2999
+ };
3000
+ return;
3001
+ }
3002
+ // Set options on self.
3003
+ extend(this, options);
3004
+ this.template = scan(this.text, this.name);
3005
+ };
3006
+
3007
+ can.EJS = EJS;
3008
+ EJS.prototype.
3009
+ render = function( object, extraHelpers ) {
3010
+ object = object || {};
3011
+ return this.template.fn.call(object, object, new EJS.Helpers(object, extraHelpers || {}));
3012
+ };
3013
+ extend(EJS, {
3014
+ // Called to return the content within a magic tag like `<%= %>`.
3015
+ // - escape - if the content returned should be escaped
3016
+ // - tagName - the tag name the magic tag is within or the one that proceeds the magic tag
3017
+ // - status - where the tag is in. The status can be:
3018
+ // - _STRING_ - The name of the attribute the magic tag is within
3019
+ // - `1` - The magic tag is within a tag like `<div <%= %>>`
3020
+ // - `0` - The magic tag is outside (or between) tags like `<div><%= %></div>`
3021
+ // - self - the `this` the template was called with
3022
+ // - func - the "wrapping" function. For example: `<%= task.attr('name') %>` becomes
3023
+ // `(function(){return task.attr('name')})
3024
+ txt : function(escape, tagName, status, self, func){
3025
+ // call the "wrapping" function and get the binding information
3026
+ var binding = can.compute.binder(func, self, function(newVal, oldVal){
3027
+ // call the update method we will define for each
3028
+ // type of attribute
3029
+ update(newVal, oldVal)
3030
+ });
3031
+
3032
+ // If we had no observes just return the value returned by func.
3033
+ if(!binding.isListening){
3034
+ return (escape || status !== 0? contentEscape : contentText)(binding.value);
3035
+ }
3036
+ // The following are helper methods or varaibles that will
3037
+ // be defined by one of the various live-updating schemes.
3038
+
3039
+ // The parent element we are listening to for teardown
3040
+ var parentElement,
3041
+ // if the parent element is removed, teardown the binding
3042
+ setupTeardownOnDestroy = function(el){
3043
+ can.bind.call(el,'destroyed', binding.teardown)
3044
+ parentElement = el;
3045
+ },
3046
+ // if there is no parent, undo bindings
3047
+ teardownCheck = function(parent){
3048
+ if(!parent){
3049
+ binding.teardown();
3050
+ can.unbind.call(parentElement,'destroyed', binding.teardown)
3051
+ }
3052
+ },
3053
+ // the tag type to insert
3054
+ tag = (tagMap[tagName] || "span"),
3055
+ // this will be filled in if binding.isListening
3056
+ update;
3057
+
3058
+
3059
+ // The magic tag is outside or between tags.
3060
+ if(status == 0){
3061
+ // Return an element tag with a hookup in place of the content
3062
+ return "<" +tag+can.view.hook(
3063
+ escape ?
3064
+ // If we are escaping, replace the parentNode with
3065
+ // a text node who's value is `func`'s return value.
3066
+ function(el, parentNode){
3067
+ // updates the text of the text node
3068
+ update = function(newVal){
3069
+ node.nodeValue = ""+newVal;
3070
+ teardownCheck(node.parentNode);
3071
+ };
3072
+
3073
+ var parent = getParentNode(el, parentNode),
3074
+ node = document.createTextNode(binding.value);
3075
+
3076
+ parent.insertBefore(node, el);
3077
+ parent.removeChild(el);
3078
+ setupTeardownOnDestroy(parent);
3079
+ }
3080
+ :
3081
+ // If we are not escaping, replace the parentNode with a
3082
+ // documentFragment created as with `func`'s return value.
3083
+ function(span, parentNode){
3084
+ // updates the elements with the new content
3085
+ update = function(newVal){
3086
+ // is this still part of the DOM?
3087
+ var attached = nodes[0].parentNode;
3088
+ // update the nodes in the DOM with the new rendered value
3089
+ if( attached ) {
3090
+ nodes = makeAndPut(newVal, nodes);
3091
+ }
3092
+ teardownCheck(nodes[0].parentNode)
3093
+ }
3094
+
3095
+ // make sure we have a valid parentNode
3096
+ parentNode = getParentNode(span, parentNode)
3097
+ // A helper function to manage inserting the contents
3098
+ // and removing the old contents
3099
+ var makeAndPut = function(val, remove){
3100
+ // create the fragment, but don't hook it up
3101
+ // we need to insert it into the document first
3102
+
3103
+ var frag = can.view.frag(val, parentNode),
3104
+ // keep a reference to each node
3105
+ nodes = can.map(frag.childNodes,function(node){
3106
+ return node;
3107
+ }),
3108
+ last = remove[remove.length - 1];
3109
+
3110
+ // Insert it in the `document` or `documentFragment`
3111
+ if( last.nextSibling ){
3112
+ last.parentNode.insertBefore(frag, last.nextSibling)
3113
+ } else {
3114
+ last.parentNode.appendChild(frag)
3115
+ }
3116
+ // Remove the old content.
3117
+ can.remove( can.$(remove) );
3118
+
3119
+ return nodes;
3120
+ },
3121
+ // nodes are the nodes that any updates will replace
3122
+ // at this point, these nodes could be part of a documentFragment
3123
+ nodes = makeAndPut(binding.value, [span]);
3124
+
3125
+
3126
+ setupTeardownOnDestroy(parentNode);
3127
+
3128
+ }) + "></" +tag+">";
3129
+ // In a tag, but not in an attribute
3130
+ } else if(status === 1){
3131
+ // remember the old attr name
3132
+ var attrName = binding.value.replace(/['"]/g, '').split('=')[0];
3133
+ pendingHookups.push(function(el) {
3134
+ update = function(newVal){
3135
+ var parts = (newVal|| "").replace(/['"]/g, '').split('='),
3136
+ newAttrName = parts[0];
3137
+
3138
+ // Remove if we have a change and used to have an `attrName`.
3139
+ if((newAttrName != attrName) && attrName){
3140
+ removeAttr(el,attrName)
3141
+ }
3142
+ // Set if we have a new `attrName`.
3143
+ if(newAttrName){
3144
+ setAttr(el, newAttrName, parts[1]);
3145
+ attrName = newAttrName;
3146
+ }
3147
+ }
3148
+ setupTeardownOnDestroy(el);
3149
+ });
3150
+
3151
+ return binding.value;
3152
+ } else { // In an attribute...
3153
+ pendingHookups.push(function(el){
3154
+ // update will call this attribute's render method
3155
+ // and set the attribute accordingly
3156
+ update = function(){
3157
+ setAttr(el, status, hook.render())
3158
+ }
3159
+
3160
+ var wrapped = can.$(el),
3161
+ hooks;
3162
+
3163
+ // Get the list of hookups or create one for this element.
3164
+ // Hooks is a map of attribute names to hookup `data`s.
3165
+ // Each hookup data has:
3166
+ // `render` - A `function` to render the value of the attribute.
3167
+ // `funcs` - A list of hookup `function`s on that attribute.
3168
+ // `batchNum` - The last event `batchNum`, used for performance.
3169
+ (hooks = can.data(wrapped,'hooks')) || can.data(wrapped, 'hooks', hooks = {});
3170
+
3171
+ // Get the attribute value.
3172
+ var attr = getAttr(el, status),
3173
+ // Split the attribute value by the template.
3174
+ parts = attr.split("__!!__"),
3175
+ hook;
3176
+
3177
+
3178
+ // If we already had a hookup for this attribute...
3179
+ if(hooks[status]) {
3180
+ // Just add to that attribute's list of `function`s.
3181
+ hooks[status].bindings.push(binding);
3182
+ }
3183
+ else {
3184
+ // Create the hookup data.
3185
+ hooks[status] = {
3186
+ render: function() {
3187
+ var i =0,
3188
+ newAttr = attr.replace(attributeReplace, function() {
3189
+ return contentText( hook.bindings[i++].value );
3190
+ });
3191
+ return newAttr;
3192
+ },
3193
+ bindings: [binding],
3194
+ batchNum : undefined
3195
+ };
3196
+ };
3197
+
3198
+ // Save the hook for slightly faster performance.
3199
+ hook = hooks[status];
3200
+
3201
+ // Insert the value in parts.
3202
+ parts.splice(1,0,binding.value);
3203
+
3204
+ // Set the attribute.
3205
+ setAttr(el, status, parts.join(""));
3206
+
3207
+ // Bind on change.
3208
+ //liveBind(observed, el, binder,oldObserved);
3209
+ setupTeardownOnDestroy(el)
3210
+ })
3211
+ return "__!!__";
3212
+ }
3213
+ },
3214
+ pending: function() {
3215
+ if(pendingHookups.length) {
3216
+ var hooks = pendingHookups.slice(0);
3217
+
3218
+ pendingHookups = [];
3219
+ return can.view.hook(function(el){
3220
+ can.each(hooks, function(fn){
3221
+ fn(el);
3222
+ })
3223
+ });
3224
+ }else {
3225
+ return "";
3226
+ }
3227
+ }
3228
+ });
3229
+ // Start scanning code.
3230
+ var tokenReg = new RegExp("(" +[ "<%%", "%%>", "<%==", "<%=",
3231
+ "<%#", "<%", "%>", "<", ">", '"', "'"].join("|")+")","g"),
3232
+ // Commands for caching.
3233
+ startTxt = 'var ___v1ew = [];',
3234
+ finishTxt = "return ___v1ew.join('')",
3235
+ put_cmd = "___v1ew.push(",
3236
+ insert_cmd = put_cmd,
3237
+ // Global controls (used by other functions to know where we are).
3238
+ //
3239
+ // Are we inside a tag?
3240
+ htmlTag = null,
3241
+ // Are we within a quote within a tag?
3242
+ quote = null,
3243
+ // What was the text before the current quote? (used to get the `attr` name)
3244
+ beforeQuote = null,
3245
+ // Used to mark where the element is.
3246
+ status = function(){
3247
+ // `t` - `1`.
3248
+ // `h` - `0`.
3249
+ // `q` - String `beforeQuote`.
3250
+ return quote ? "'"+beforeQuote.match(attrReg)[1]+"'" : (htmlTag ? 1 : 0)
3251
+ },
3252
+ pendingHookups = [],
3253
+ scan = function(source, name){
3254
+ var tokens = [],
3255
+ last = 0;
3256
+
3257
+ source = source.replace(newLine, "\n");
3258
+ source.replace(tokenReg, function(whole, part, offset){
3259
+ // if the next token starts after the last token ends
3260
+ // push what's in between
3261
+ if(offset > last){
3262
+ tokens.push( source.substring(last, offset) );
3263
+ }
3264
+ // push the token
3265
+ tokens.push(part);
3266
+ // update the position of the last part of the last token
3267
+ last = offset+part.length;
3268
+ })
3269
+ // if there's something at the end, add it
3270
+ if(last < source.length){
3271
+ tokens.push(source.substr(last))
3272
+ }
3273
+
3274
+ var content = '',
3275
+ buff = [startTxt],
3276
+ // Helper `function` for putting stuff in the view concat.
3277
+ put = function( content, bonus ) {
3278
+ buff.push(put_cmd, '"', clean(content), '"'+(bonus||'')+');');
3279
+ },
3280
+ // A stack used to keep track of how we should end a bracket
3281
+ // `}`.
3282
+ // Once we have a `<%= %>` with a `leftBracket`,
3283
+ // we store how the file should end here (either `))` or `;`).
3284
+ endStack =[],
3285
+ // The last token, used to remember which tag we are in.
3286
+ lastToken,
3287
+ // The corresponding magic tag.
3288
+ startTag = null,
3289
+ // Was there a magic tag inside an html tag?
3290
+ magicInTag = false,
3291
+ // The current tag name.
3292
+ tagName = '',
3293
+ // stack of tagNames
3294
+ tagNames = [],
3295
+ // Declared here.
3296
+ bracketCount,
3297
+ i = 0,
3298
+ token;
3299
+
3300
+ // Reinitialize the tag state goodness.
3301
+ htmlTag = quote = beforeQuote = null;
3302
+
3303
+ for (; (token = tokens[i++]) !== undefined;) {
3304
+
3305
+ if ( startTag === null ) {
3306
+ switch ( token ) {
3307
+ case '<%':
3308
+ case '<%=':
3309
+ case '<%==':
3310
+ magicInTag = 1;
3311
+ case '<%#':
3312
+ // A new line -- just add whatever content within a clean.
3313
+ // Reset everything.
3314
+ startTag = token;
3315
+ if ( content.length ) {
3316
+ put(content);
3317
+ }
3318
+ content = '';
3319
+ break;
3320
+
3321
+ case '<%%':
3322
+ // Replace `<%%` with `<%`.
3323
+ content += '<%';
3324
+ break;
3325
+ case '<':
3326
+ // Make sure we are not in a comment.
3327
+ if(tokens[i].indexOf("!--") !== 0) {
3328
+ htmlTag = 1;
3329
+ magicInTag = 0;
3330
+ }
3331
+ content += token;
3332
+ break;
3333
+ case '>':
3334
+ htmlTag = 0;
3335
+ // TODO: all `<%=` in tags should be added to pending hookups.
3336
+ if(magicInTag){
3337
+ put(content, ",can.EJS.pending(),\">\"");
3338
+ content = '';
3339
+ } else {
3340
+ content += token;
3341
+ }
3342
+ // if it's a tag like <input/>
3343
+ if(lastToken.substr(-1) == "/"){
3344
+ // remove the current tag in the stack
3345
+ tagNames.pop();
3346
+ // set the current tag to the previous parent
3347
+ tagName = tagNames[tagNames.length-1];
3348
+ }
3349
+ break;
3350
+ case "'":
3351
+ case '"':
3352
+ // If we are in an html tag, finding matching quotes.
3353
+ if(htmlTag){
3354
+ // We have a quote and it matches.
3355
+ if(quote && quote === token){
3356
+ // We are exiting the quote.
3357
+ quote = null;
3358
+ // Otherwise we are creating a quote.
3359
+ // TODO: does this handle `\`?
3360
+ } else if(quote === null){
3361
+ quote = token;
3362
+ beforeQuote = lastToken;
3363
+ }
3364
+ }
3365
+ default:
3366
+ // Track the current tag
3367
+ if(lastToken === '<'){
3368
+ tagName = token.split(' ')[0];
3369
+ // If
3370
+ if( tagName.indexOf("/") === 0 && tagNames.pop() === tagName.substr(1) ) {
3371
+ tagName = tagNames[tagNames.length-1]|| tagName.substr(1)
3372
+ } else {
3373
+ tagNames.push(tagName);
3374
+ }
3375
+ }
3376
+ content += token;
3377
+ break;
3378
+ }
3379
+ }
3380
+ else {
3381
+ // We have a start tag.
3382
+ switch ( token ) {
3383
+ case '%>':
3384
+ // `%>`
3385
+ switch ( startTag ) {
3386
+ case '<%':
3387
+ // `<%`
3388
+
3389
+ // Get the number of `{ minus }`
3390
+ bracketCount = bracketNum(content);
3391
+
3392
+ // We are ending a block.
3393
+ if (bracketCount == 1) {
3394
+
3395
+ // We are starting on.
3396
+ buff.push(insert_cmd, "can.EJS.txt(0,'"+tagName+"'," + status() + ",this,function(){", startTxt, content);
3397
+
3398
+ endStack.push({
3399
+ before: "",
3400
+ after: finishTxt+"}));\n"
3401
+ })
3402
+ }
3403
+ else {
3404
+
3405
+ // How are we ending this statement?
3406
+ var last = // If the stack has value and we are ending a block...
3407
+ endStack.length && bracketCount == -1 ? // Use the last item in the block stack.
3408
+ endStack.pop() : // Or use the default ending.
3409
+ {
3410
+ after: ";"
3411
+ };
3412
+
3413
+ // If we are ending a returning block,
3414
+ // add the finish text which returns the result of the
3415
+ // block.
3416
+ if (last.before) {
3417
+ buff.push(last.before)
3418
+ }
3419
+ // Add the remaining content.
3420
+ buff.push(content, ";",last.after);
3421
+ }
3422
+ break;
3423
+ case '<%=':
3424
+ case '<%==':
3425
+ // We have an extra `{` -> `block`.
3426
+ // Get the number of `{ minus }`.
3427
+ bracketCount = bracketNum(content);
3428
+ // If we have more `{`, it means there is a block.
3429
+ if( bracketCount ){
3430
+ // When we return to the same # of `{` vs `}` end with a `doubleParent`.
3431
+ endStack.push({
3432
+ before : finishTxt,
3433
+ after: "}));"
3434
+ })
3435
+ }
3436
+ // Check if its a func like `()->`
3437
+ if(quickFunc.test(content)){
3438
+ var parts = content.match(quickFunc)
3439
+ content = "function(__){var "+parts[1]+"=can.$(__);"+parts[2]+"}"
3440
+ }
3441
+
3442
+ // If we have `<%== a(function(){ %>` then we want
3443
+ // `can.EJS.text(0,this, function(){ return a(function(){ var _v1ew = [];`.
3444
+ buff.push(insert_cmd, "can.EJS.txt("+(startTag === '<%=' ? 1 : 0)+",'"+tagName+"'," + status()+",this,function(){ return ", content,
3445
+ // If we have a block.
3446
+ bracketCount ?
3447
+ // Start with startTxt `"var _v1ew = [];"`.
3448
+ startTxt :
3449
+ // If not, add `doubleParent` to close push and text.
3450
+ "}));"
3451
+ );
3452
+ break;
3453
+ }
3454
+ startTag = null;
3455
+ content = '';
3456
+ break;
3457
+ case '<%%':
3458
+ content += '<%';
3459
+ break;
3460
+ default:
3461
+ content += token;
3462
+ break;
3463
+ }
3464
+
3465
+ }
3466
+ lastToken = token;
3467
+ }
3468
+
3469
+ // Put it together...
3470
+ if ( content.length ) {
3471
+ // Should be `content.dump` in Ruby.
3472
+ put(content)
3473
+ }
3474
+ buff.push(";")
3475
+
3476
+ var template = buff.join(''),
3477
+ out = {
3478
+ out: 'with(_VIEW) { with (_CONTEXT) {' + template + " "+finishTxt+"}}"
3479
+ };
3480
+ // Use `eval` instead of creating a function, because it is easier to debug.
3481
+ myEval.call(out, 'this.fn = (function(_CONTEXT,_VIEW){' + out.out + '});\r\n//@ sourceURL=' + name + ".js");
3482
+ return out;
3483
+ };
3484
+
3485
+
3486
+
3487
+ EJS.Helpers = function( data, extras ) {
3488
+ this._data = data;
3489
+ this._extras = extras;
3490
+ extend(this, extras);
3491
+ };
3492
+ EJS.Helpers.prototype = {
3493
+ // TODO Deprecated!!
3494
+ list : function(list, cb){
3495
+ can.each(list, function(item, i){
3496
+ cb(item, i, list)
3497
+ })
3498
+ }
3499
+ };
3500
+
3501
+ // Options for `steal`'s build.
3502
+ can.view.register({
3503
+ suffix: "ejs",
3504
+ // returns a `function` that renders the view.
3505
+ script: function( id, src ) {
3506
+ return "can.EJS(function(_CONTEXT,_VIEW) { " + new EJS({
3507
+ text: src,
3508
+ name: id
3509
+ }).template.out + " })";
3510
+ },
3511
+ renderer: function( id, text ) {
3512
+ return EJS({
3513
+ text: text,
3514
+ name: id
3515
+ });
3516
+ }
3517
+ });
3518
+
3519
+ // Register as an AMD module if supported, otherwise attach to the window
3520
+ if ( typeof define === "function" && define.amd ) {
3521
+ define( "can", [], function () { return can; } );
3522
+ } else {
3523
+ window.can = can;
3524
+ }
3525
+
3526
+ }, "0.0.1", {
3527
+ requires: ["node", "io-base", "querystring", "event-focus", "array-extras"],
3528
+ optional: ["selector-css2", "selector-css3"]
3529
+ });
3530
+ })(can = {}, this )