aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorsimonbrandhof <simon.brandhof@gmail.com>2010-10-28 08:02:18 +0000
committersimonbrandhof <simon.brandhof@gmail.com>2010-10-28 08:02:18 +0000
commitec7f0817eed5c7824bb2145c6bd520ab480ba3b9 (patch)
treea05550c2d4f7004ddafee228c6b07d932a680d8c
parent91493e94947de67103dea121e894b89fda37f767 (diff)
downloadsonarqube-ec7f0817eed5c7824bb2145c6bd520ab480ba3b9.tar.gz
sonarqube-ec7f0817eed5c7824bb2145c6bd520ab480ba3b9.zip
SONAR-1643 apply a part of the GSOC branch
-rw-r--r--plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/CorePlugin.java10
-rw-r--r--plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultAlertsWidget.java39
-rw-r--r--plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultCodeCoverageWidget.java39
-rw-r--r--plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultCommentsDuplicationsWidget.java39
-rw-r--r--plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultDescriptionWidget.java39
-rw-r--r--plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultExtendedAnalysisWidget.java39
-rw-r--r--plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultRulesWidget.java39
-rw-r--r--plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultStaticAnalysisWidget.java39
-rw-r--r--plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_alerts.html.erb10
-rw-r--r--plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_code_coverage.html.erb45
-rw-r--r--plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_comments_duplications.html.erb37
-rw-r--r--plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_description.html.erb27
-rw-r--r--plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_extended_analysis.html.erb126
-rw-r--r--plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_rules.html.erb132
-rw-r--r--plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_static_analysis.html.erb63
-rw-r--r--sonar-core/src/main/java/org/sonar/jpa/entity/SchemaMigration.java2
-rw-r--r--sonar-plugin-api/src/main/java/org/sonar/api/web/Description.java37
-rw-r--r--sonar-plugin-api/src/main/java/org/sonar/api/web/WidgetProperties.java36
-rw-r--r--sonar-plugin-api/src/main/java/org/sonar/api/web/WidgetProperty.java50
-rw-r--r--sonar-server/pom.xml4
-rw-r--r--sonar-server/src/main/java/org/sonar/server/ui/JRubyFacade.java9
-rw-r--r--sonar-server/src/main/java/org/sonar/server/ui/ViewProxy.java20
-rw-r--r--sonar-server/src/main/java/org/sonar/server/ui/Views.java5
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/controllers/admin_dashboards_controller.rb101
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/controllers/dashboard_controller.rb154
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/controllers/dashboards_controller.rb152
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/helpers/dashboard_helper.rb65
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/helpers/dashboards_helper.rb66
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/helpers/widget_properties_helper.rb73
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/models/active_dashboard.rb59
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/models/dashboard.rb77
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/models/user.rb3
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/models/widget.rb86
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/models/widget_property.rb49
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/views/admin_dashboards/index.html.erb72
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/_configure_widget.html.erb41
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/_header.html.erb29
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/_widget.html.erb22
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/_widget_definition.html.erb7
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/configure.html.erb82
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/edit_layout.html.erb28
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/index.html.erb26
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_create.html.erb35
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_dashboard.html.erb186
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_edit.html.erb32
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_editform.html.erb47
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_layouts.html.erb25
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_snapshot_title.html.erb12
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_tabs.html.erb21
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_widget.html.erb100
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_widget_update.rjs6
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/index.html.erb62
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/manage.html.erb86
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/new.html.erb6
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/views/layouts/_head.html.erb2
-rw-r--r--sonar-server/src/main/webapp/WEB-INF/app/views/layouts/_layout.html.erb5
-rwxr-xr-xsonar-server/src/main/webapp/WEB-INF/db/migrate/151_create_dashboards.rb89
-rw-r--r--sonar-server/src/main/webapp/images/layout100.pngbin0 -> 321 bytes
-rw-r--r--sonar-server/src/main/webapp/images/layout3070.pngbin0 -> 369 bytes
-rw-r--r--sonar-server/src/main/webapp/images/layout333333.pngbin0 -> 431 bytes
-rw-r--r--sonar-server/src/main/webapp/images/layout5050.pngbin0 -> 364 bytes
-rw-r--r--sonar-server/src/main/webapp/images/layout7030.pngbin0 -> 355 bytes
-rw-r--r--sonar-server/src/main/webapp/javascripts/dashboard.js100
-rw-r--r--sonar-server/src/main/webapp/javascripts/scriptaculous.js5377
-rw-r--r--sonar-server/src/main/webapp/stylesheets/dashboard.css216
-rw-r--r--sonar-server/src/main/webapp/stylesheets/style.css4
66 files changed, 6313 insertions, 2176 deletions
diff --git a/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/CorePlugin.java b/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/CorePlugin.java
index 2fa67c2613a..e96985a92cb 100644
--- a/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/CorePlugin.java
+++ b/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/CorePlugin.java
@@ -39,6 +39,7 @@ import org.sonar.plugins.core.sensors.*;
import org.sonar.plugins.core.testdetailsviewer.TestsViewerDefinition;
import org.sonar.plugins.core.ui.pageselector.GwtPageSelector;
import org.sonar.plugins.core.violationsviewer.ViolationsViewerDefinition;
+import org.sonar.plugins.core.widgets.*;
import java.util.ArrayList;
import java.util.List;
@@ -143,6 +144,15 @@ public class CorePlugin implements Plugin {
extensions.add(Clouds.class);
extensions.add(Hotspots.class);
+ //widgets
+ extensions.add(DefaultAlertsWidget.class);
+ extensions.add(DefaultCodeCoverageWidget.class);
+ extensions.add(DefaultCommentsDuplicationsWidget.class);
+ extensions.add(DefaultDescriptionWidget.class);
+ extensions.add(DefaultExtendedAnalysisWidget.class);
+ extensions.add(DefaultRulesWidget.class);
+ extensions.add(DefaultStaticAnalysisWidget.class);
+
// chart
extensions.add(XradarChart.class);
extensions.add(DistributionBarChart.class);
diff --git a/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultAlertsWidget.java b/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultAlertsWidget.java
new file mode 100644
index 00000000000..b826b83fdd7
--- /dev/null
+++ b/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultAlertsWidget.java
@@ -0,0 +1,39 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.plugins.core.widgets;
+
+import org.sonar.api.web.AbstractRubyTemplate;
+import org.sonar.api.web.RubyRailsWidget;
+
+public class DefaultAlertsWidget extends AbstractRubyTemplate implements RubyRailsWidget {
+ public String getId() {
+ return "alerts";
+ }
+
+ public String getTitle() {
+ // not used for the moment by widgets.
+ return "Alerts";
+ }
+
+ @Override
+ protected String getTemplatePath() {
+ return "/org/sonar/plugins/core/widgets/_alerts.html.erb";
+ }
+} \ No newline at end of file
diff --git a/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultCodeCoverageWidget.java b/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultCodeCoverageWidget.java
new file mode 100644
index 00000000000..88471b2f755
--- /dev/null
+++ b/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultCodeCoverageWidget.java
@@ -0,0 +1,39 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.plugins.core.widgets;
+
+import org.sonar.api.web.AbstractRubyTemplate;
+import org.sonar.api.web.RubyRailsWidget;
+
+public class DefaultCodeCoverageWidget extends AbstractRubyTemplate implements RubyRailsWidget {
+ public String getId() {
+ return "code_coverage";
+ }
+
+ public String getTitle() {
+ // not used for the moment by widgets.
+ return "Code coverage";
+ }
+
+ @Override
+ protected String getTemplatePath() {
+ return "/org/sonar/plugins/core/widgets/_code_coverage.html.erb";
+ }
+} \ No newline at end of file
diff --git a/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultCommentsDuplicationsWidget.java b/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultCommentsDuplicationsWidget.java
new file mode 100644
index 00000000000..8d1a8da9eec
--- /dev/null
+++ b/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultCommentsDuplicationsWidget.java
@@ -0,0 +1,39 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.plugins.core.widgets;
+
+import org.sonar.api.web.AbstractRubyTemplate;
+import org.sonar.api.web.RubyRailsWidget;
+
+public class DefaultCommentsDuplicationsWidget extends AbstractRubyTemplate implements RubyRailsWidget {
+ public String getId() {
+ return "comments_duplications";
+ }
+
+ public String getTitle() {
+ // not used for the moment by widgets.
+ return "Comments duplications";
+ }
+
+ @Override
+ protected String getTemplatePath() {
+ return "/org/sonar/plugins/core/widgets/_comments_duplications.html.erb";
+ }
+} \ No newline at end of file
diff --git a/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultDescriptionWidget.java b/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultDescriptionWidget.java
new file mode 100644
index 00000000000..455fe019dd7
--- /dev/null
+++ b/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultDescriptionWidget.java
@@ -0,0 +1,39 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.plugins.core.widgets;
+
+import org.sonar.api.web.AbstractRubyTemplate;
+import org.sonar.api.web.RubyRailsWidget;
+
+public class DefaultDescriptionWidget extends AbstractRubyTemplate implements RubyRailsWidget {
+ public String getId() {
+ return "description";
+ }
+
+ public String getTitle() {
+ // not used for the moment by widgets.
+ return "Description";
+ }
+
+ @Override
+ protected String getTemplatePath() {
+ return "/org/sonar/plugins/core/widgets/_description.html.erb";
+ }
+} \ No newline at end of file
diff --git a/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultExtendedAnalysisWidget.java b/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultExtendedAnalysisWidget.java
new file mode 100644
index 00000000000..516b910653c
--- /dev/null
+++ b/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultExtendedAnalysisWidget.java
@@ -0,0 +1,39 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.plugins.core.widgets;
+
+import org.sonar.api.web.AbstractRubyTemplate;
+import org.sonar.api.web.RubyRailsWidget;
+
+public class DefaultExtendedAnalysisWidget extends AbstractRubyTemplate implements RubyRailsWidget {
+ public String getId() {
+ return "extended_analysis";
+ }
+
+ public String getTitle() {
+ // not used for the moment by widgets.
+ return "Extended analysis";
+ }
+
+ @Override
+ protected String getTemplatePath() {
+ return "/org/sonar/plugins/core/widgets/_extended_analysis.html.erb";
+ }
+} \ No newline at end of file
diff --git a/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultRulesWidget.java b/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultRulesWidget.java
new file mode 100644
index 00000000000..f2985fa6ccf
--- /dev/null
+++ b/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultRulesWidget.java
@@ -0,0 +1,39 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.plugins.core.widgets;
+
+import org.sonar.api.web.AbstractRubyTemplate;
+import org.sonar.api.web.RubyRailsWidget;
+
+public class DefaultRulesWidget extends AbstractRubyTemplate implements RubyRailsWidget {
+ public String getId() {
+ return "rules";
+ }
+
+ public String getTitle() {
+ // not used for the moment by widgets.
+ return "Rules";
+ }
+
+ @Override
+ protected String getTemplatePath() {
+ return "/org/sonar/plugins/core/widgets/_rules.html.erb";
+ }
+} \ No newline at end of file
diff --git a/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultStaticAnalysisWidget.java b/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultStaticAnalysisWidget.java
new file mode 100644
index 00000000000..9c10430c774
--- /dev/null
+++ b/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/DefaultStaticAnalysisWidget.java
@@ -0,0 +1,39 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.plugins.core.widgets;
+
+import org.sonar.api.web.AbstractRubyTemplate;
+import org.sonar.api.web.RubyRailsWidget;
+
+public class DefaultStaticAnalysisWidget extends AbstractRubyTemplate implements RubyRailsWidget {
+ public String getId() {
+ return "static_analysis";
+ }
+
+ public String getTitle() {
+ // not used for the moment by widgets.
+ return "Static analysis";
+ }
+
+ @Override
+ protected String getTemplatePath() {
+ return "/org/sonar/plugins/core/widgets/_static_analysis.html.erb";
+ }
+}
diff --git a/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_alerts.html.erb b/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_alerts.html.erb
new file mode 100644
index 00000000000..095afb59331
--- /dev/null
+++ b/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_alerts.html.erb
@@ -0,0 +1,10 @@
+<% m=measure(Metric::ALERT_STATUS)
+ if m && !m.alert_status.blank?
+ css_class = "widget color_#{m.alert_status}"
+ if m.alert_status==Metric::TYPE_LEVEL_OK
+ label = '<b>No alerts</b>.'
+ else
+ label = "<b>Alerts</b> : #{h(m.alert_text)}."
+ end
+%> <div><%= format_measure(m) -%> <%= label -%></div>
+<% end %>
diff --git a/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_code_coverage.html.erb b/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_code_coverage.html.erb
new file mode 100644
index 00000000000..02b1dc5ef5a
--- /dev/null
+++ b/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_code_coverage.html.erb
@@ -0,0 +1,45 @@
+<%
+code_coverage_measure=measure(Metric::COVERAGE)
+tests_measure=measure(Metric::TESTS)
+if code_coverage_measure || tests_measure %>
+<div class="yui-g">
+ <div class="yui-u first">
+<div class="dashbox">
+ <p class="title">Code coverage</p>
+ <p><span class="big"><%= format_measure(code_coverage_measure, :suffix => '', :url => url_for_drilldown(Metric::COVERAGE), :default => '-') %> <%= tendency_icon(code_coverage_measure, false) %></span></p>
+ <% line_coverage=measure(Metric::LINE_COVERAGE)
+ if line_coverage %>
+ <p><%= format_measure(line_coverage, :suffix => ' line coverage', :url => url_for_drilldown(Metric::UNCOVERED_LINES, :highlight => Metric::LINE_COVERAGE)) %> <%= tendency_icon(line_coverage) %></p>
+ <% end %>
+ <% branch_coverage=measure(Metric::BRANCH_COVERAGE)
+ if branch_coverage %>
+ <p><%= format_measure(branch_coverage, :suffix => ' branch coverage', :url => url_for_drilldown(Metric::UNCOVERED_CONDITIONS, :highlight => Metric::BRANCH_COVERAGE)) %> <%= tendency_icon(branch_coverage) %></p>
+ <% end %>
+ <p><%= format_measure(tests_measure, :suffix => ' tests', :url => url_for_drilldown(Metric::TESTS)) %> <%= tendency_icon(tests_measure) %></p>
+ <% skipped_measure=measure(Metric::SKIPPED_TESTS)
+ if skipped_measure && skipped_measure.value>0
+ %>
+ <p>+<%= format_measure(skipped_measure, :suffix => ' skipped', :url => url_for_drilldown(Metric::SKIPPED_TESTS)) %> <%= tendency_icon(skipped_measure) %></p>
+ <% end %>
+ <p><%= format_measure(Metric::TEST_EXECUTION_TIME, :suffix => '', :url => url_for_drilldown(Metric::TEST_EXECUTION_TIME)) %> <%= tendency_icon(measure(Metric::TEST_EXECUTION_TIME)) %></p>
+</div>
+</div>
+<div class="yui-u">
+ <%
+ success_percentage=measure(Metric::TEST_SUCCESS_DENSITY)
+ if success_percentage
+ %>
+ <div class="dashbox">
+ <h3>Test success</h3>
+ <p><span class="big"><%= format_measure(success_percentage, :suffix => '', :url => url_for_drilldown(success_percentage)) %> <%= tendency_icon(measure(Metric::TEST_SUCCESS_DENSITY), false) %></span></p>
+ <p>
+ <%= format_measure(Metric::TEST_FAILURES, :suffix => ' failures', :url => url_for_drilldown(Metric::TEST_FAILURES)) %> <%= tendency_icon(measure(Metric::TEST_FAILURES)) %>
+ </p>
+ <p>
+ <%= format_measure(Metric::TEST_ERRORS, :suffix => ' errors', :url => url_for_drilldown(Metric::TEST_ERRORS)) %> <%= tendency_icon(measure(Metric::TEST_ERRORS)) %>
+ </p>
+ </div>
+ <% end %>
+</div>
+</div>
+<% end %>
diff --git a/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_comments_duplications.html.erb b/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_comments_duplications.html.erb
new file mode 100644
index 00000000000..b7b7e2f54cd
--- /dev/null
+++ b/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_comments_duplications.html.erb
@@ -0,0 +1,37 @@
+<% if measure(Metric::LINES) || measure(Metric::NCLOC) %>
+<table width="100%">
+ <tr>
+ <td valign="top" width="48%" nowrap>
+ <% if (measure(Metric::COMMENT_LINES)) %>
+ <div class="dashbox">
+ <h3>Comments</h3>
+ <p><span class="big"><%= format_measure(Metric::COMMENT_LINES_DENSITY, :suffix => '', :url => url_for_drilldown(Metric::COMMENT_LINES_DENSITY)) -%> <%= tendency_icon(Metric::COMMENT_LINES_DENSITY, false) -%></span></p>
+ <p><%= format_measure(Metric::COMMENT_LINES, :suffix => ' lines', :url => url_for_drilldown(Metric::COMMENT_LINES)) -%> <%= tendency_icon(Metric::COMMENT_LINES) -%></p>
+ <%
+ comment_blank_lines=measure('comment_blank_lines')
+ if comment_blank_lines && comment_blank_lines.value>0
+ %>
+ <p>+<%= format_measure(comment_blank_lines, :suffix => ' blank', :url => url_for_drilldown(comment_blank_lines)) -%> <%= tendency_icon(comment_blank_lines) -%></p>
+ <% end %>
+ <p><%= format_measure(Metric::PUBLIC_DOCUMENTED_API_DENSITY, :suffix => ' docu. API', :url => url_for_drilldown(Metric::PUBLIC_UNDOCUMENTED_API, :highlight => Metric::PUBLIC_DOCUMENTED_API_DENSITY)) -%> <%= tendency_icon(Metric::PUBLIC_DOCUMENTED_API_DENSITY) -%></p>
+ <p><%= format_measure(Metric::PUBLIC_UNDOCUMENTED_API, :suffix => ' undocu. API', :url => url_for_drilldown(Metric::PUBLIC_UNDOCUMENTED_API, :highlight => Metric::PUBLIC_UNDOCUMENTED_API)) -%> <%= tendency_icon(Metric::PUBLIC_UNDOCUMENTED_API) -%></p>
+ <p><%= format_measure(Metric::COMMENTED_OUT_CODE_LINES, :suffix => ' commented LOCs', :url => url_for_drilldown(Metric::COMMENTED_OUT_CODE_LINES, :highlight => Metric::COMMENTED_OUT_CODE_LINES)) -%> <%= tendency_icon(Metric::COMMENTED_OUT_CODE_LINES) -%></p>
+ </div>
+ <% end %>
+ </td>
+ <td width="10"> </td>
+ <td valign="top">
+ <% if (measure(Metric::DUPLICATED_LINES_DENSITY)) %>
+ <div class="dashbox">
+ <h3>Duplications</h3>
+ <p><span class="big"><%= format_measure(Metric::DUPLICATED_LINES_DENSITY, :suffix => '', :url => url_for_drilldown(Metric::DUPLICATED_LINES, :highlight => Metric::DUPLICATED_LINES_DENSITY)) -%> <%= tendency_icon(Metric::DUPLICATED_LINES_DENSITY, false) -%></span></p>
+ <p><%= format_measure(Metric::DUPLICATED_LINES, :suffix => ' lines', :url => url_for_drilldown(Metric::DUPLICATED_LINES)) -%> <%= tendency_icon(Metric::DUPLICATED_LINES) -%></p>
+ <p><%= format_measure(Metric::DUPLICATED_BLOCKS, :suffix => ' blocks', :url => url_for_drilldown(Metric::DUPLICATED_BLOCKS)) -%> <%= tendency_icon(Metric::DUPLICATED_BLOCKS) -%></p>
+ <p><%= format_measure(Metric::DUPLICATED_FILES, :suffix => ' files', :url => url_for_drilldown(Metric::DUPLICATED_FILES)) -%> <%= tendency_icon(Metric::DUPLICATED_FILES) -%></p>
+ </div>
+ <% end %>
+
+ </td>
+ </tr>
+</table>
+<% end %> \ No newline at end of file
diff --git a/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_description.html.erb b/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_description.html.erb
new file mode 100644
index 00000000000..8ae52acc63b
--- /dev/null
+++ b/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_description.html.erb
@@ -0,0 +1,27 @@
+ <% if not @project.description.blank? %>
+ <%= h @project.description %><br/>
+ <% end %>
+
+ Key : <%= @project.key %><br/>
+<% if @project.language %>
+ Language : <%= @project.language %><br/>
+<% end %>
+
+ <table width="100%">
+ <% links_count=@project.project_links.size
+ if links_count > 0 %>
+ <tr><td width="50%">
+ <% @project.project_links.sort.each_with_index do |link, index| %>
+ <% if index==links_count/2 %></td><td width="50%"><% end %>
+ <%= link_to(image_tag(link.icon, :alt => link.name), link.href , :popup => true, :class => 'nolink') -%>
+ <%= link_to(h(link.name), link.href, :popup => true) -%><br/>
+ <% end %>
+ </td></tr>
+ <% end %>
+ <% if Project::SCOPE_SET==@project.scope %>
+ <tr><td colspan="2">
+ <a href="<%= url_for :controller => :feeds, :action => 'project', :id => @project.key, :category => EventCategory::KEY_ALERT -%>" class="nolink"><%= image_tag 'feed-icon-14x14.png' %></a>
+ <a href="<%= url_for :controller => :feeds, :action => 'project', :id => @project.key, :category => EventCategory::KEY_ALERT -%>" class="action">Alerts feed</a>
+ </td></tr>
+ <% end %>
+ </table>
diff --git a/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_extended_analysis.html.erb b/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_extended_analysis.html.erb
new file mode 100644
index 00000000000..230633d4e24
--- /dev/null
+++ b/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_extended_analysis.html.erb
@@ -0,0 +1,126 @@
+<%
+ file_complexity=measure('file_complexity')
+ function_complexity=measure('function_complexity')
+ class_complexity=measure('class_complexity')
+ paragraph_complexity=measure('paragraph_complexity')
+
+ if file_complexity || function_complexity || class_complexity || paragraph_complexity
+ complexity=measure('complexity')
+%>
+<div class="dashbox" >
+ <h3>Complexity</h3>
+ <% if function_complexity %>
+ <p>
+ <span class="big"><%= format_measure(function_complexity, :suffix => '', :url => url_for_drilldown(function_complexity)) -%> <%= tendency_icon(function_complexity, false) -%></span>/ method
+ </p>
+ <% end %>
+ <% if paragraph_complexity %>
+ <p>
+ <span class="big"><%= format_measure(paragraph_complexity, :suffix => '', :url => url_for_drilldown(paragraph_complexity)) -%> <%= tendency_icon(paragraph_complexity, false) -%></span>/ paragraph
+ </p>
+ <% end %>
+ <% if class_complexity %>
+ <p>
+ <span class="big"><%= format_measure(class_complexity, :suffix => '', :url => url_for_drilldown(class_complexity)) -%> <%= tendency_icon(class_complexity, false) -%></span>/ class
+ </p>
+ <% end %>
+ <% if file_complexity %>
+ <p>
+ <span class="big"><%= format_measure(file_complexity, :suffix => '', :url => url_for_drilldown(file_complexity)) -%> <%= tendency_icon(file_complexity, false) -%></span>/ file
+ </p>
+ <% end %>
+ <% if complexity %>
+ <p>
+ Total: <%= format_measure(complexity, :url => url_for_drilldown(complexity)) -%> <%= tendency_icon(complexity) -%>
+ </p>
+ <% end %>
+</div>
+
+
+<%
+ function_distribution=measure('function_complexity_distribution')
+ paragraph_distribution=measure('paragraph_complexity_distribution')
+ class_distribution=measure('class_complexity_distribution')
+ file_distribution=measure('file_complexity_distribution')
+ distributions=[function_distribution,paragraph_distribution,class_distribution,file_distribution].compact
+ selected_distribution=nil
+ if distributions.size>0
+ selected_distribution=distributions.first
+ end
+ if selected_distribution
+%>
+<div class="dashbox" id="cmp_charts" style="float:right">
+ <script type='text/javascript'>
+ //<![CDATA[
+ function selectComplexity(metric) {
+ $$('#cmp_charts .chart').each(function(chart) {
+ chart.hide();
+ });
+ $('chart_' + metric).show();
+ }
+ </script>
+ <style>
+ #cmp_charts form {
+ font-size: 93%;padding-left: 30px;
+ }
+ #cmp_charts form label {
+ padding-right: 5px;
+ }
+ </style>
+ <% distributions.each do |distribution_measure| %>
+ <% metric = distribution_measure.metric.key
+ dist_measure = measure(metric)
+ title = distribution_measure.metric.description
+ visible = (selected_distribution==distribution_measure)
+ if dist_measure && !dist_measure.data.blank?
+ %>
+ <div id="chart_<%= metric -%>" class="chart" style="display: <%= visible ? "block" : "none" %>">
+ <%
+ query="ck=distbar&c=777777&v=" + u(dist_measure.data)
+ small_size_query=query + '&w=220&h=100&fs=8&bgc=ffffff'
+ big_size_query=query + '&w=300&h=150&fs=12&bgc=CAE3F2'
+ %><%= chart(small_size_query, :id => 'chart_img_' + metric, :alt => title) -%>
+
+ <script type='text/javascript'>
+ //<![CDATA[
+ new Tip('chart_img_<%=metric-%>', '<div style="width:300px;"><b><%= title -%></b><br>' +
+ '<%= chart(big_size_query, :id => 'chart_img_' + metric, :alt => title) -%></div>');
+ //]]>
+ </script>
+ </div>
+ <% end %>
+ <% end %>
+
+ <form>
+ <%
+ count_dist=0
+ if function_distribution
+ count_dist+=1
+ %>
+ <input type="radio" name="cmp_dist" value="function_complexity_distribution" id="cmp_dist_function_complexity_distribution" onClick="selectComplexity('function_complexity_distribution');" <%= 'checked' if function_distribution==selected_distribution -%>></input> <label for="cmp_dist_function_complexity_distribution">Methods</label>
+ <%
+ end
+ if paragraph_distribution
+ count_dist+=1
+ %>
+ <input type="radio" name="cmp_dist" value="paragraph_complexity_distribution" id="cmp_dist_paragraph_complexity_distribution" onClick="selectComplexity('paragraph_complexity_distribution');" <%= 'checked' if paragraph_distribution==selected_distribution -%>></input> <label for="cmp_dist_paragraph_complexity_distribution">Paragraphs</label><%= '<br/>' if count_dist==2 %>
+ <%
+ end
+ if class_distribution
+ count_dist+=1
+ %>
+ <input type="radio" name="cmp_dist" value="class_complexity_distribution" id="cmp_dist_class_complexity_distribution" onClick="selectComplexity('class_complexity_distribution');" <%= 'checked' if class_distribution==selected_distribution -%>></input> <label for="cmp_dist_class_complexity_distribution">Classes</label><%= '<br/>' if count_dist==2 %>
+ <%
+ end
+ if file_distribution
+ count_dist+=1
+ %>
+ <input type="radio" name="cmp_dist" value="file_complexity_distribution" id="cmp_dist_file_complexity_distribution" onClick="selectComplexity('file_complexity_distribution');" <%= 'checked' if file_distribution==selected_distribution -%>></input> <label for="cmp_dist_file_complexity_distribution">Files</label>
+ <% end %>
+
+ </form>
+
+</div>
+<% end %>
+<% end %>
+
diff --git a/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_rules.html.erb b/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_rules.html.erb
new file mode 100644
index 00000000000..7befce2e792
--- /dev/null
+++ b/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_rules.html.erb
@@ -0,0 +1,132 @@
+<% if measure(Metric::LINES) %>
+ <table width="100%">
+ <tr>
+ <td valign="top">
+ <div class="dashbox">
+ <h3>Rules compliance</h3>
+ <div class="big">
+ <%= format_measure(Metric::VIOLATIONS_DENSITY, :url => url_for_drilldown(Metric::WEIGHTED_VIOLATIONS, {:highlight => Metric::WEIGHTED_VIOLATIONS})) -%> <%= tendency_icon(Metric::VIOLATIONS_DENSITY) -%>
+ </div>
+ <%
+ maintainability=@snapshot.measure(Metric::MAINTAINABILITY)
+ efficiency=@snapshot.measure(Metric::EFFICIENCY)
+ usability=@snapshot.measure(Metric::USABILITY)
+ reliability=@snapshot.measure(Metric::RELIABILITY)
+ portability=@snapshot.measure(Metric::PORTABILITY)
+ %>
+ <div class="mandatory">
+ <a class="tip" href="<%= url_for :controller => 'drilldown', :action => 'violations', :id => @project.id, :filter => 'category' -%>">
+ <img width="140" height="110" alt="" src="<%= ApplicationController.root_context -%>/chart?ck=xradar&w=140&h=110&c=777777|F8A036&m=100&g=0.25&l=Eff.,Mai.,Por.,Rel.,Usa.&v=<%= efficiency ? efficiency.value : 0 -%>,<%= maintainability ? maintainability.value : 0 -%>,<%= portability ? portability.value : 0 -%>,<%= reliability ? reliability.value : 0 -%>,<%= usability ? usability.value : 0 -%>">
+ <span>
+ <table>
+ <tr>
+ <td align="left" nowrap>Efficiency &nbsp;</td>
+ <td align="right" id="m_efficiency"><%= formatted_value(efficiency) %></td>
+ <td nowrap> &nbsp;<%= tendency_icon(efficiency) -%></td>
+ </tr>
+ <tr>
+ <td align="left" nowrap>Maintainability &nbsp;</td>
+ <td align="right" id="m_maintainability"><%= formatted_value(maintainability) %></td>
+ <td nowrap> &nbsp;<%= tendency_icon(maintainability) -%></td>
+ </tr>
+ <tr>
+ <td align="left" nowrap>Portability &nbsp;</td>
+ <td align="right" id="m_portability"><%= formatted_value(portability) %></td>
+ <td nowrap> &nbsp;<%= tendency_icon(portability) -%></td>
+ </tr>
+ <tr>
+ <td align="left" nowrap>Reliability &nbsp;</td>
+ <td align="right" id="m_reliability"><%= formatted_value(reliability) %></td>
+ <td nowrap> &nbsp;<%= tendency_icon(reliability) -%></td>
+ </tr>
+ <tr>
+ <td align="left" nowrap>Usability &nbsp;</td>
+ <td align="right" id="m_usability"><%= formatted_value(usability) %></td>
+ <td nowrap> &nbsp;<%= tendency_icon(usability) -%></td>
+ </tr>
+ </table>
+ </span>
+ </a>
+ </div>
+ </div>
+ </td>
+ <td width="10"> </td>
+ <td valign="top">
+ <div class="dashbox">
+ <h3>Violations</h3>
+ <div class="big">
+ <%= format_measure(Metric::VIOLATIONS, :url => url_for(:controller => 'drilldown', :action => 'violations', :id => @project.key)) -%> <%= tendency_icon(Metric::VIOLATIONS) -%>
+ </div>
+ <%
+ blocker_violations = @snapshot.measure(Metric::BLOCKER_VIOLATIONS)
+ critical_violations = @snapshot.measure(Metric::CRITICAL_VIOLATIONS)
+ major_violations = @snapshot.measure(Metric::MAJOR_VIOLATIONS)
+ minor_violations = @snapshot.measure(Metric::MINOR_VIOLATIONS)
+ info_violations = @snapshot.measure(Metric::INFO_VIOLATIONS)
+ max = 0
+ [blocker_violations,critical_violations,major_violations,minor_violations,info_violations].each do |m|
+ max = m.value if m and m.value and m.value>max
+ end
+ %>
+ <table>
+ <tr>
+ <td><%= image_tag 'priority/BLOCKER.png'%></td>
+ <td> &nbsp;<%= link_to 'Blocker', {:controller => 'drilldown', :action => 'violations', :id => @project.key, :priority => 'BLOCKER'} %></td>
+ <td style="padding-left: 10px;" align="right">
+ <%= format_measure(blocker_violations) -%>
+ </td>
+ <td width="1%"><%= tendency_icon(blocker_violations) -%></td>
+ <td align="left" style="padding-bottom:2px; padding-top:2px;">
+ <%= barchart(:width => 60, :percent => (blocker_violations ? (100 * blocker_violations.value / max).to_i : 0), :color => '#777777') if max>0 %>
+ </td>
+ </tr>
+ <tr>
+ <td><%= image_tag 'priority/CRITICAL.png' %></td>
+ <td> &nbsp;<%= link_to 'Critical', {:controller => 'drilldown', :action => 'violations', :id => @project.key, :priority => 'CRITICAL'} %></td>
+ <td style="padding-left: 10px;" align="right">
+ <%= format_measure(critical_violations) -%>
+ </td>
+ <td width="1%"><%= tendency_icon(critical_violations) -%></td>
+ <td align="left" style="padding-bottom:2px; padding-top:2px;">
+ <%= barchart(:width => 60, :percent => (critical_violations ? (100 * critical_violations.value / max).to_i : 0), :color => '#777777') if max>0 %>
+ </td>
+ </tr>
+ <tr>
+ <td><%= image_tag 'priority/MAJOR.png' %></td>
+ <td> &nbsp;<%= link_to 'Major', {:controller => 'drilldown', :action => 'violations', :id => @project.key, :priority => 'MAJOR'} %></td>
+ <td style="padding-left: 10px;" align="right">
+ <%= format_measure(major_violations) -%>
+ </td>
+ <td width="1%"><%= tendency_icon(major_violations) -%></td>
+ <td align="left" style="padding-bottom:2px; padding-top:2px;">
+ <%= barchart(:width => 60, :percent => (major_violations ? (100 * major_violations.value / max).to_i : 0), :color => '#777777') if max>0 %>
+ </td>
+ </tr>
+ <tr>
+ <td><%= image_tag 'priority/MINOR.png' %></td>
+ <td> &nbsp;<%= link_to 'Minor', {:controller => 'drilldown', :action => 'violations', :id => @project.key, :priority => 'MINOR'} %></td>
+ <td style="padding-left: 10px;" align="right">
+ <%= format_measure(minor_violations) -%>
+ </td>
+ <td width="1%"><%= tendency_icon(minor_violations) -%></td>
+ <td align="left" style="padding-bottom:2px; padding-top:2px;">
+ <%= barchart(:width => 60, :percent => (minor_violations ? (100 * minor_violations.value / max).to_i : 0), :color => '#777777') if max>0 %>
+ </td>
+ </tr>
+ <tr>
+ <td><%= image_tag 'priority/INFO.png' %></td>
+ <td> &nbsp;<%= link_to 'Info', {:controller => 'drilldown', :action => 'violations', :id => @project.key, :priority => 'INFO'} %></td>
+ <td style="padding-left: 10px;" align="right">
+ <%= format_measure(info_violations) -%>
+ </td>
+ <td width="1%"><%= tendency_icon(info_violations) -%></td>
+ <td align="left" style="padding-bottom:2px; padding-top:2px;">
+ <%= barchart(:width => 60, :percent => (info_violations ? (100 * info_violations.value / max).to_i : 0), :color => '#777777') if max>0 %>
+ </td>
+ </tr>
+ </table>
+ </div>
+ </td>
+ </tr>
+ </table>
+<% end %> \ No newline at end of file
diff --git a/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_static_analysis.html.erb b/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_static_analysis.html.erb
new file mode 100644
index 00000000000..6ada91d46ae
--- /dev/null
+++ b/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/_static_analysis.html.erb
@@ -0,0 +1,63 @@
+<%
+if measure('lines') || measure('ncloc')
+ files=measure('files')
+ statements=measure('statements')
+%>
+<table width="100%">
+ <tr>
+ <td valign="top" width="48%" nowrap>
+ <div class="dashbox">
+ <h3>Lines of code</h3>
+ <% if measure('ncloc') %>
+ <p><span class="big">
+ <%= format_measure('ncloc', :suffix => '', :url => url_for_drilldown('ncloc')) -%> <%= tendency_icon('ncloc', false) -%></span></p>
+ <%
+ generated_ncloc=measure('generated_ncloc')
+ if generated_ncloc && generated_ncloc.value>0
+ %>
+ <p>+<%= format_measure(generated_ncloc, :suffix => ' generated', :url => url_for_drilldown(generated_ncloc)) -%> <%= tendency_icon(generated_ncloc) -%></p>
+ <% end %>
+ <p><%= format_measure('lines', :suffix => ' lines', :url => url_for_drilldown('lines')) -%> <%= tendency_icon('lines') -%></p>
+ <% else%>
+ <p><span class="big"><%= format_measure('lines', :suffix => '', :url => url_for_drilldown('lines')) -%> <%= tendency_icon('lines', false) -%></span></p>
+ <% end %>
+ <%
+ generated_lines=measure('generated_lines')
+ if generated_lines && generated_lines.value>0
+ %>
+ <p>incl. <%= format_measure(generated_lines, :suffix => ' generated', :url => url_for_drilldown(generated_lines)) -%> <%= tendency_icon(generated_lines) -%></p>
+ <% end %>
+ <% if statements %>
+ <p>
+ <%= format_measure(statements, :suffix => ' statements', :url => url_for_drilldown(statements)) -%> <%= tendency_icon(statements) -%>
+ </p>
+ <% end %>
+ <% if files && measure('classes') %>
+ <p><%= format_measure(files, :suffix => ' files', :url => url_for_drilldown(files)) -%> <%= tendency_icon(files) -%></p>
+ <% end %>
+ </div>
+ </td>
+ <td width="10"> </td>
+ <td valign="top">
+ <div class="dashbox">
+ <% if measure('classes') %>
+ <h3>Classes</h3>
+ <p><span class="big"><%= format_measure('classes', :url => url_for_drilldown('classes')) -%> <%= tendency_icon('classes') -%></span></p>
+ <p><%= format_measure('packages', :suffix => ' packages', :url => url_for_drilldown('packages')) -%> <%= tendency_icon('packages') -%></p>
+ <% else %>
+ <h3>Files</h3>
+ <p><span class="big"><%= format_measure('files', :url => url_for_drilldown('files')) -%> <%= tendency_icon('files') -%></span></p>
+ <p><%= format_measure('directories', :suffix => ' directories', :url => url_for_drilldown('directories')) -%> <%= tendency_icon('directories') -%></p>
+ <% end %>
+ <p><%= format_measure('functions', :suffix => ' methods', :url => url_for_drilldown('functions')) -%> <%= tendency_icon('functions') -%></p>
+ <% if (measure('accessors')) %>
+ <p><%= format_measure('accessors', :prefix => '+', :suffix => ' accessors', :url => url_for_drilldown('accessors')) -%> <%= tendency_icon('accessors') -%></p>
+ <% end %>
+ <% if measure('paragraphs') %>
+ <p><%= format_measure('paragraphs', :suffix => ' paragraphs', :url => url_for_drilldown('paragraphs')) -%> <%= tendency_icon('paragraphs') -%></p>
+ <% end %>
+ </div>
+ </td>
+ </tr>
+</table>
+<% end %> \ No newline at end of file
diff --git a/sonar-core/src/main/java/org/sonar/jpa/entity/SchemaMigration.java b/sonar-core/src/main/java/org/sonar/jpa/entity/SchemaMigration.java
index 60f57295f39..a7920936481 100644
--- a/sonar-core/src/main/java/org/sonar/jpa/entity/SchemaMigration.java
+++ b/sonar-core/src/main/java/org/sonar/jpa/entity/SchemaMigration.java
@@ -30,7 +30,7 @@ import java.sql.Statement;
public class SchemaMigration {
public final static int VERSION_UNKNOWN = -1;
- public static final int LAST_VERSION = 150;
+ public static final int LAST_VERSION = 151;
public final static String TABLE_NAME = "schema_migrations";
diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/web/Description.java b/sonar-plugin-api/src/main/java/org/sonar/api/web/Description.java
new file mode 100644
index 00000000000..34d44a6f341
--- /dev/null
+++ b/sonar-plugin-api/src/main/java/org/sonar/api/web/Description.java
@@ -0,0 +1,37 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.api.web;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Created by IntelliJ IDEA.
+ * User: dreik
+ * Date: 02.08.2010
+ * Time: 13:00:45
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.TYPE)
+public @interface Description {
+ String value();
+}
diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/web/WidgetProperties.java b/sonar-plugin-api/src/main/java/org/sonar/api/web/WidgetProperties.java
new file mode 100644
index 00000000000..86d6d7c7706
--- /dev/null
+++ b/sonar-plugin-api/src/main/java/org/sonar/api/web/WidgetProperties.java
@@ -0,0 +1,36 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.api.web;
+
+import org.sonar.api.Property;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * Created by IntelliJ IDEA.
+ * User: dreik
+ * Date: 09.08.2010
+ * Time: 10:40:09
+ */
+@Retention(RetentionPolicy.RUNTIME)
+public @interface WidgetProperties {
+ WidgetProperty[] value() default {};
+}
diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/web/WidgetProperty.java b/sonar-plugin-api/src/main/java/org/sonar/api/web/WidgetProperty.java
new file mode 100644
index 00000000000..7ec6bf86f8d
--- /dev/null
+++ b/sonar-plugin-api/src/main/java/org/sonar/api/web/WidgetProperty.java
@@ -0,0 +1,50 @@
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2009 SonarSource SA
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.api.web;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Created by IntelliJ IDEA.
+ * User: dreik
+ * Date: 09.08.2010
+ * Time: 10:33:35
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.TYPE)
+public @interface WidgetProperty {
+
+ String key();
+
+ String defaultValue() default "";
+
+ String name();
+
+ String description() default "";
+
+ String type() default "STRING";
+
+ String parameter() default "";
+
+ boolean optional() default true;
+}
diff --git a/sonar-server/pom.xml b/sonar-server/pom.xml
index 3427d048c85..be35e82f60f 100644
--- a/sonar-server/pom.xml
+++ b/sonar-server/pom.xml
@@ -251,6 +251,8 @@
<include>**/tablekit-min.js</include>
<include>**/prototip-min.js</include>
<include>**/tooltip-min.js</include>
+ <include>**/dashboard-min.js</include>
+
</includes>
<output>${project.build.directory}/${project.build.finalName}/javascripts/sonar.js</output>
</aggregation>
@@ -260,6 +262,7 @@
<include>**/calendar-min.css</include>
<include>**/style-min.css</include>
<include>**/sonar-colorizer-min.css</include>
+ <include>**/dashboard-min.css</include>
</includes>
<output>${project.build.directory}/${project.build.finalName}/stylesheets/sonar.css</output>
</aggregation>
@@ -336,7 +339,6 @@
<overWriteIfNewer>true</overWriteIfNewer>
<overWriteReleases>true</overWriteReleases>
<overWriteSnapshots>true</overWriteSnapshots>
- <includeGroupIds>org.codehaus.sonar.plugins</includeGroupIds>
<outputDirectory>${project.build.directory}/sonar-dev-home/extensions/plugins/</outputDirectory>
</configuration>
</execution>
diff --git a/sonar-server/src/main/java/org/sonar/server/ui/JRubyFacade.java b/sonar-server/src/main/java/org/sonar/server/ui/JRubyFacade.java
index e9b556c55d8..f5dc477cd43 100644
--- a/sonar-server/src/main/java/org/sonar/server/ui/JRubyFacade.java
+++ b/sonar-server/src/main/java/org/sonar/server/ui/JRubyFacade.java
@@ -108,6 +108,15 @@ public final class JRubyFacade implements ServerComponent {
return getContainer().getComponent(Views.class).getWidgets(resourceScope, resourceQualifier, resourceLanguage);
}
+ public List<ViewProxy<Widget>> getWidgets() {
+ return getContainer().getComponent(Views.class).getWidgets();
+ }
+
+ public ViewProxy<Widget> getWidget(String id) {
+ return getContainer().getComponent(Views.class).getWidget(id);
+ }
+
+
public List<ViewProxy<Page>> getPages(String section, String resourceScope, String resourceQualifier, String resourceLanguage) {
return getContainer().getComponent(Views.class).getPages(section, resourceScope, resourceQualifier, resourceLanguage);
}
diff --git a/sonar-server/src/main/java/org/sonar/server/ui/ViewProxy.java b/sonar-server/src/main/java/org/sonar/server/ui/ViewProxy.java
index d224d790a07..17582d0703a 100644
--- a/sonar-server/src/main/java/org/sonar/server/ui/ViewProxy.java
+++ b/sonar-server/src/main/java/org/sonar/server/ui/ViewProxy.java
@@ -34,6 +34,8 @@ public class ViewProxy<V extends View> implements Comparable<ViewProxy> {
private String[] resourceQualifiers = {};
private String[] resourceLanguages = {};
private String[] defaultForMetrics = {};
+ private String description = "";
+ private WidgetProperty[] properties = {};
private boolean isDefaultTab=false;
private boolean isWidget = false;
@@ -77,6 +79,16 @@ public class ViewProxy<V extends View> implements Comparable<ViewProxy> {
}
}
+ Description descriptionAnnotation = AnnotationUtils.getClassAnnotation(view, Description.class);
+ if (descriptionAnnotation != null) {
+ description = descriptionAnnotation.value();
+ }
+
+ WidgetProperties widgetProperties = AnnotationUtils.getClassAnnotation(view, WidgetProperties.class);
+ if (widgetProperties != null) {
+ properties = widgetProperties.value();
+ }
+
isWidget = (view instanceof Widget);
}
@@ -92,6 +104,14 @@ public class ViewProxy<V extends View> implements Comparable<ViewProxy> {
return view.getTitle();
}
+ public String getDescription() {
+ return description;
+ }
+
+ public WidgetProperty[] getProperties() {
+ return properties;
+ }
+
public String[] getSections() {
return sections;
}
diff --git a/sonar-server/src/main/java/org/sonar/server/ui/Views.java b/sonar-server/src/main/java/org/sonar/server/ui/Views.java
index ebc666a8f4f..6addb165827 100644
--- a/sonar-server/src/main/java/org/sonar/server/ui/Views.java
+++ b/sonar-server/src/main/java/org/sonar/server/ui/Views.java
@@ -19,6 +19,7 @@
*/
package org.sonar.server.ui;
+import com.google.common.collect.Lists;
import org.apache.commons.lang.ArrayUtils;
import org.sonar.api.ServerComponent;
import org.sonar.api.web.Page;
@@ -85,6 +86,10 @@ public class Views implements ServerComponent {
return result;
}
+ public List<ViewProxy<Widget>> getWidgets() {
+ return new ArrayList<ViewProxy<Widget>>(widgets);
+ }
+
private static boolean accept(ViewProxy proxy, String section, String resourceScope, String resourceQualifier, String resourceLanguage) {
return acceptNavigationSection(proxy, section)
&& acceptResourceScope(proxy, resourceScope)
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/controllers/admin_dashboards_controller.rb b/sonar-server/src/main/webapp/WEB-INF/app/controllers/admin_dashboards_controller.rb
new file mode 100644
index 00000000000..7824a235adc
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/controllers/admin_dashboards_controller.rb
@@ -0,0 +1,101 @@
+#
+# Sonar, entreprise quality control tool.
+# Copyright (C) 2009 SonarSource SA
+# mailto:contact AT sonarsource DOT com
+#
+# Sonar is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 3 of the License, or (at your option) any later version.
+#
+# Sonar is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with Sonar; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+#
+class AdminDashboardsController < ApplicationController
+
+ SECTION=Navigation::SECTION_CONFIGURATION
+
+ verify :method => :post, :only => [:up, :down, :remove, :add], :redirect_to => {:action => :index}
+ before_filter :admin_required
+ before_filter :load_active_dashboards
+
+ def index
+ @default_dashboards=::Dashboard.find(:all, :conditions => {:shared => true})
+ ids=@actives.map{|af| af.dashboard_id}
+ if !ids.nil? && !ids.empty?
+ @default_dashboards=@default_dashboards.reject!{|f| ids.include?(f.id) }
+ end
+ end
+
+ def up
+ dashboard_index=-1
+ dashboard=nil
+ @actives.each_index do |index|
+ if @actives[index].id==params[:id].to_i
+ dashboard_index=index
+ dashboard=@actives[index]
+ end
+ end
+ if dashboard && dashboard_index>0
+ @actives[dashboard_index]=@actives[dashboard_index-1]
+ @actives[dashboard_index-1]=dashboard
+
+ @actives.each_index do |index|
+ @actives[index].order_index=index+1
+ @actives[index].save
+ end
+ end
+ redirect_to :action => 'index'
+ end
+
+ def down
+ dashboard_index=-1
+ dashboard=nil
+ @actives.each_index do |index|
+ if @actives[index].id==params[:id].to_i
+ dashboard_index=index
+ dashboard=@actives[index]
+ end
+ end
+ if dashboard && dashboard_index<@actives.size-1
+ @actives[dashboard_index]=@actives[dashboard_index+1]
+ @actives[dashboard_index+1]=dashboard
+
+ @actives.each_index do |index|
+ @actives[index].order_index=index+1
+ @actives[index].save
+ end
+ end
+ redirect_to :action => 'index'
+ end
+
+ def add
+ dashboard=::Dashboard.find(:first, :conditions => ['shared=? and id=?', true, params[:id].to_i()])
+ if dashboard
+ ActiveDashboard.create(:dashboard => dashboard, :user => nil, :order_index => @actives.size+1)
+ flash[:notice]='Default dashboard added.'
+ end
+ redirect_to :action => 'index'
+ end
+
+ def remove
+ active=@actives.to_a.find{|af| af.id==params[:id].to_i}
+ if active
+ active.destroy
+ flash[:notice]='Dashboard removed from default dashboards.'
+ end
+ redirect_to :action => 'index'
+ end
+
+ private
+
+ def load_active_dashboards
+ @actives=ActiveDashboard.default_active_dashboards
+ end
+end
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/controllers/dashboard_controller.rb b/sonar-server/src/main/webapp/WEB-INF/app/controllers/dashboard_controller.rb
new file mode 100644
index 00000000000..61f4c54f61e
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/controllers/dashboard_controller.rb
@@ -0,0 +1,154 @@
+#
+# Sonar, entreprise quality control tool.
+# Copyright (C) 2009 SonarSource SA
+# mailto:contact AT sonarsource DOT com
+#
+# Sonar is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 3 of the License, or (at your option) any later version.
+#
+# Sonar is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with Sonar; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+#
+class DashboardController < ApplicationController
+
+ SECTION=Navigation::SECTION_RESOURCE
+
+ verify :method => :post, :only => [:set_layout, :add_widget, :set_dashboard], :redirect_to => {:action => :index}
+ before_filter :login_required, :except => [:index]
+
+ def index
+ # TODO display error page if no dashboard or no resource
+ load_dashboard()
+ load_resource()
+ load_widget_definitions()
+ end
+
+ def configure
+ # TODO display error page if no dashboard or no resource
+ load_dashboard()
+ load_resource()
+ load_widget_definitions()
+ end
+
+ def edit_layout
+ load_dashboard()
+ load_resource()
+ end
+
+ def set_layout
+ dashboard=Dashboard.find(params[:id].to_i)
+ if dashboard.editable_by?(current_user)
+ dashboard.column_layout=params[:layout]
+ if dashboard.save
+ columns=dashboard.column_layout.split('-')
+ dashboard.widgets.find(:all, :conditions => ["column_index > ?",columns.size()]).each do |widget|
+ widget.column_index=columns.size()
+ widget.save
+ end
+ end
+ end
+ redirect_to :action => 'index', :id => dashboard.id, :resource => params[:resource]
+ end
+
+ def set_dashboard
+ load_dashboard()
+
+ dashboardstate=params[:dashboardstate]
+
+ columns=dashboardstate.split(";")
+ all_ids=[]
+ columns.each_with_index do |col, index|
+ ids=col.split(",")
+ ids.each_with_index do |id, order|
+ widget=@dashboard.widgets.to_a.find { |i| i.id==id.to_i() }
+ if widget
+ widget.column_index=index+1
+ widget.order_index=order+1
+ widget.save!
+ all_ids<<widget.id
+ end
+ end
+ end
+ @dashboard.widgets.reject{|w| all_ids.include?(w.id)}.each do |w|
+ w.destroy
+ end
+ render :json => {:status => 'ok'}
+ end
+
+ def add_widget
+ dashboard=Dashboard.find(params[:id].to_i)
+ widget_id=nil
+ if dashboard.editable_by?(current_user)
+ definition=java_facade.getWidget(params[:widget])
+ if definition
+ new_widget=dashboard.widgets.create(:widget_key => definition.getId(),
+ :name => definition.getTitle(),
+ :column_index => dashboard.number_of_columns,
+ :order_index => dashboard.column_size(dashboard.number_of_columns) + 1,
+ :state => Widget::STATE_ACTIVE)
+ widget_id=new_widget.id
+ end
+ end
+ redirect_to :action => 'configure', :id => dashboard.id, :resource => params[:resource], :highlight => widget_id
+ end
+
+ private
+
+ def load_dashboard
+ @active=nil
+ if logged_in?
+ if params[:id]
+ @active=ActiveDashboard.find(:first, :include => 'dashboard', :conditions => ['active_dashboards.dashboard_id=? AND active_dashboards.user_id=?', params[:id].to_i, current_user.id])
+ elsif params[:name]
+ @active=ActiveDashboard.find(:first, :include => 'dashboard', :conditions => ['dashboards.name=? AND active_dashboards.user_id=?', params[:name], current_user.id])
+ end
+ end
+
+ if @active.nil?
+ # anonymous or not found in user dashboards
+ if params[:id]
+ @active=ActiveDashboard.find(:first, :include => 'dashboard', :conditions => ['active_dashboards.dashboard_id=? AND active_dashboards.user_id IS NULL', params[:id].to_i])
+ elsif params[:name]
+ @active=ActiveDashboard.find(:first, :include => 'dashboard', :conditions => ['dashboards.name=? AND active_dashboards.user_id IS NULL', params[:name]])
+ else
+ @active=ActiveDashboard.find(:first, :include => 'dashboard', :conditions => ['active_dashboards.user_id IS NULL'], :order => 'order_index ASC')
+ end
+ end
+ @dashboard=(@active ? @active.dashboard : nil)
+ end
+
+ def load_resource
+ @resource=Project.by_key(params[:resource])
+ if @resource.nil?
+ # TODO display error page
+ redirect_to home_path
+ return false
+ end
+ return access_denied unless has_role?(:user, @resource)
+ @snapshot = @resource.last_snapshot
+ @project=@resource # variable name used in old widgets
+ end
+
+ # TODO display unauthorized widgets instead of hiding them
+ def load_widget_definitions()
+ @widget_definitions = java_facade.getWidgets(@resource.scope, @resource.qualifier, @resource.language)
+ @widget_definitions=@widget_definitions.select do |widget|
+ authorized=widget.getUserRoles().size==0
+ unless authorized
+ widget.getUserRoles().each do |role|
+ authorized=(role=='user') || (role=='viewer') || has_role?(role, @resource)
+ break if authorized
+ end
+ end
+ authorized
+ end
+ end
+end \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/controllers/dashboards_controller.rb b/sonar-server/src/main/webapp/WEB-INF/app/controllers/dashboards_controller.rb
new file mode 100644
index 00000000000..670f637e425
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/controllers/dashboards_controller.rb
@@ -0,0 +1,152 @@
+#
+# Sonar, entreprise quality control tool.
+# Copyright (C) 2009 SonarSource SA
+# mailto:contact AT sonarsource DOT com
+#
+# Sonar is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 3 of the License, or (at your option) any later version.
+#
+# Sonar is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with Sonar; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+#
+class DashboardsController < ApplicationController
+
+ SECTION=Navigation::SECTION_RESOURCE
+
+ verify :method => :post, :only => [:create, :update, :delete, :up, :down], :redirect_to => {:action => :index}
+ before_filter :login_required
+
+ def index
+ @actives=ActiveDashboard.user_dashboards(current_user)
+
+ @resource=Project.by_key(params[:resource])
+ if @resource.nil?
+ # TODO display error page
+ redirect_to home_path
+ return false
+ end
+ return access_denied unless has_role?(:user, @resource)
+ @snapshot = @resource.last_snapshot
+ @project=@resource # variable name used in old widgets
+ end
+
+ def create
+ @dashboard=Dashboard.new()
+ load_dashboard_from_params(@dashboard)
+ if @dashboard.valid?
+ @dashboard.save
+
+ add_default_dashboards_if_first_user_dashboard
+ last_active_dashboard=current_user.active_dashboards.max{|x,y| x.order_index<=>y.order_index}
+ current_user.active_dashboards.create(:dashboard => @dashboard, :user_id => current_user.id, :order_index => (last_active_dashboard ? last_active_dashboard.order_index+1: 1))
+ redirect_to :controller => 'dashboard', :action => 'configure', :id => @dashboard.id, :resource => params[:resource]
+ else
+ flash[:error]=@dashboard.errors.full_messages.join('<br/>')
+ redirect_to :controller => 'dashboards', :action => 'index', :resource => params[:resource]
+ end
+ end
+
+ def edit
+ # TODO check ownership
+ @dashboard=Dashboard.find(params[:id])
+ render :partial => "edit"
+ end
+
+ def update
+ dashboard=Dashboard.find(params[:id])
+ if dashboard.owner?(current_user)
+ load_dashboard_from_params(dashboard)
+
+ if dashboard.save
+ if !dashboard.shared?
+ ActiveDashboard.destroy_all(["dashboard_id = ? and (user_id<>? OR user_id IS NULL)", dashboard.id, current_user.id])
+ end
+ else
+ flash[:error]=dashboard.errors.full_messages.join('<br/>')
+ end
+ else
+ # TODO explicit error
+ end
+ redirect :action => 'index', :resource => params[:resource]
+ end
+
+ def delete
+ dashboard=Dashboard.find(params[:id])
+ if dashboard.owner?(current_user)
+ dashboard.destroy
+ flash[:notice]='Dashboard deleted'
+ redirect_to :action => 'index', :resource => params[:resource]
+ else
+ # TODO explicit error
+ redirect_to home_path
+ end
+ end
+
+ def down
+ add_default_dashboards_if_first_user_dashboard
+ dashboard_index=-1
+ current_user.active_dashboards.each_with_index do |ad, index|
+ ad.order_index=index+1
+ if ad.dashboard_id==params[:id].to_i
+ dashboard_index=index
+ end
+ end
+ if dashboard_index>-1 && dashboard_index<current_user.active_dashboards.size-1
+ current_user.active_dashboards[dashboard_index].order_index+=1
+ current_user.active_dashboards[dashboard_index+1].order_index-=1
+ end
+ current_user.active_dashboards.each do |ad|
+ ad.save
+ end
+ redirect_to :action => 'index', :resource => params[:resource]
+ end
+
+ def up
+ add_default_dashboards_if_first_user_dashboard
+ dashboard_index=-1
+ current_user.active_dashboards.each_with_index do |ad, index|
+ ad.order_index=index+1
+ dashboard_index=index if ad.dashboard_id==params[:id].to_i
+ end
+ if dashboard_index>0
+ current_user.active_dashboards[dashboard_index].order_index-=1
+ current_user.active_dashboards[dashboard_index-1].order_index+=1
+ end
+ current_user.active_dashboards.each do |ad|
+ ad.save
+ end
+ redirect_to :action => 'index', :resource => params[:resource]
+ end
+
+
+
+ private
+
+ def load_dashboard_from_params(dashboard)
+ dashboard.name=params[:name]
+ dashboard.description=params[:description]
+ dashboard.shared=(params[:shared].present? && is_admin?)
+ dashboard.user_id=current_user.id
+ dashboard.column_layout='50-50' if !dashboard.column_layout
+ end
+
+ def add_default_dashboards_if_first_user_dashboard
+ if current_user.active_dashboards.empty?
+ defaults=ActiveDashboard.default_dashboards
+ defaults.each do |default_active|
+ current_user.active_dashboards.create(:dashboard => default_active.dashboard, :user => current_user, :order_index => current_user.active_dashboards.size+1)
+ end
+ end
+ end
+
+
+
+end \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/helpers/dashboard_helper.rb b/sonar-server/src/main/webapp/WEB-INF/app/helpers/dashboard_helper.rb
new file mode 100644
index 00000000000..e34f593a533
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/helpers/dashboard_helper.rb
@@ -0,0 +1,65 @@
+#
+# Sonar, entreprise quality control tool.
+# Copyright (C) 2009 SonarSource SA
+# mailto:contact AT sonarsource DOT com
+#
+# Sonar is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 3 of the License, or (at your option) any later version.
+#
+# Sonar is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with Sonar; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+#
+module DashboardHelper
+
+ def item_by_metric_id(items, metric_id)
+ return nil if items.nil?
+ items.each do |item|
+ return item if (item.metric.id==metric_id and item.rules_category_id.nil?)
+ end
+ nil
+ end
+
+ def active_widgets_ids_formatted(column)
+ active_widget_ids=[]
+ @dashboard.widgets.find(:all, :conditions => {:column_index => column}, :order => :order_index).each do |widget|
+ widget_view=nil
+ found_index=-1
+ @widgets.each_with_index {|item, index|
+ if item.getId()==widget.widget_key
+ found_index=index
+ end
+ }
+ if found_index>-1
+ active_widget_ids=active_widget_ids << (widget.widget_key+"_"+found_index.to_s())
+ end
+ end
+ return "\'"+active_widget_ids.join("\',\'")+"\'"
+ end
+
+ def item_by_metric_name_and_categ_id(items, metric_name, rules_category_id)
+ return nil if items.nil?
+ items.each do |item|
+ return item if (item.metric.name==metric_name and
+ item.rules_category_id == rules_category_id and
+ item.rule_id.nil?)
+ end
+ nil
+ end
+
+ def formatted_value(measure, default='')
+ measure ? measure.formatted_value : default
+ end
+
+ def measure(metric_key)
+ @snapshot.measure(metric_key)
+ end
+
+end \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/helpers/dashboards_helper.rb b/sonar-server/src/main/webapp/WEB-INF/app/helpers/dashboards_helper.rb
new file mode 100644
index 00000000000..4893c32db0d
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/helpers/dashboards_helper.rb
@@ -0,0 +1,66 @@
+#
+# Sonar, entreprise quality control tool.
+# Copyright (C) 2009 SonarSource SA
+# mailto:contact AT sonarsource DOT com
+#
+# Sonar is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 3 of the License, or (at your option) any later version.
+#
+# Sonar is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with Sonar; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+#
+module DashboardsHelper
+ include ActionView::Helpers::UrlHelper
+ include WidgetPropertiesHelper
+
+ def item_by_metric_id(items, metric_id)
+ return nil if items.nil?
+ items.each do |item|
+ return item if (item.metric.id==metric_id and item.rules_category_id.nil?)
+ end
+ nil
+ end
+
+ def active_widgets_ids_formatted(column)
+ active_widget_ids=[]
+ @dashboard.widgets.find(:all, :conditions => {:column_index => column}, :order => :order_index).each do |widget|
+ widget_view=nil
+ found_index=-1
+ @widgets.each_with_index {|item, index|
+ if item.getId()==widget.widget_key
+ found_index=index
+ end
+ }
+ if found_index>-1
+ active_widget_ids=active_widget_ids << (widget.widget_key+"_"+found_index.to_s())
+ end
+ end
+ return "\'"+active_widget_ids.join("\',\'")+"\'"
+ end
+
+ def item_by_metric_name_and_categ_id(items, metric_name, rules_category_id)
+ return nil if items.nil?
+ items.each do |item|
+ return item if (item.metric.name==metric_name and
+ item.rules_category_id == rules_category_id and
+ item.rule_id.nil?)
+ end
+ nil
+ end
+
+ def formatted_value(measure, default='')
+ measure ? measure.formatted_value : default
+ end
+
+ def measure(metric_key)
+ @snapshot.measure(metric_key)
+ end
+end \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/helpers/widget_properties_helper.rb b/sonar-server/src/main/webapp/WEB-INF/app/helpers/widget_properties_helper.rb
new file mode 100644
index 00000000000..543a2864f63
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/helpers/widget_properties_helper.rb
@@ -0,0 +1,73 @@
+#
+# Sonar, entreprise quality control tool.
+# Copyright (C) 2009 SonarSource SA
+# mailto:contact AT sonarsource DOT com
+#
+# Sonar is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 3 of the License, or (at your option) any later version.
+#
+# Sonar is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with Sonar; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+#
+module WidgetPropertiesHelper
+ VALUE_TYPE_INT = 'INT'
+ VALUE_TYPE_BOOLEAN = 'BOOL'
+ VALUE_TYPE_FLOAT = 'FLOAT'
+ VALUE_TYPE_STRING = 'STRING'
+ VALUE_TYPE_REGEXP = 'REGEXP'
+
+ def valid_property_value?(type, value, parameter="")
+ if type==VALUE_TYPE_INT
+ value.to_i.to_s == value
+
+ elsif type==VALUE_TYPE_FLOAT
+ true if Float(value) rescue false
+
+ elsif type==VALUE_TYPE_BOOLEAN
+ value=="1" || value=="0"
+
+ elsif type==VALUE_TYPE_STRING
+ true
+
+ elsif type==VALUE_TYPE_REGEXP
+ value.to_s.match(parameter) == nil ? false : true
+
+ else
+ false
+ end
+ end
+
+ def property_value_field(type, fieldname, value, param_value="")
+ val= param_value ? param_value : value
+
+ if type==VALUE_TYPE_INT
+ text_field_tag fieldname, val , :size => 10
+
+ elsif type==VALUE_TYPE_FLOAT
+ text_field_tag fieldname, val, :size => 10
+
+ elsif type==VALUE_TYPE_BOOLEAN
+ opts="<option value=''>Select value</option>"
+ opts+="<option value='1'"+(val=="1" ? " selected" : "" )+">Yes</option>"
+ opts+="<option value='0'"+(val=="0" ? " selected" : "" )+">No</option>"
+ select_tag fieldname, opts
+
+ elsif type==VALUE_TYPE_STRING
+ text_field_tag fieldname, val, :size => 10
+
+ elsif type==VALUE_TYPE_REGEXP
+ text_field_tag fieldname, val, :size => 10
+ else
+ hidden_field_tag fieldname
+ end
+ end
+
+end \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/models/active_dashboard.rb b/sonar-server/src/main/webapp/WEB-INF/app/models/active_dashboard.rb
new file mode 100644
index 00000000000..3ca3383aa8d
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/models/active_dashboard.rb
@@ -0,0 +1,59 @@
+#
+# Sonar, entreprise quality control tool.
+# Copyright (C) 2009 SonarSource SA
+# mailto:contact AT sonarsource DOT com
+#
+# Sonar is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 3 of the License, or (at your option) any later version.
+#
+# Sonar is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with Sonar; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+#
+class ActiveDashboard < ActiveRecord::Base
+
+ belongs_to :user
+ belongs_to :dashboard
+
+ def name
+ dashboard.name
+ end
+
+ def order_index
+ read_attribute(:order_index) || 1
+ end
+
+ def shared?
+ dashboard.shared
+ end
+
+ def owner?(user)
+ dashboard.owner?(user)
+ end
+
+ def follower?(user)
+ self.user.nil? || self.user_id==user.id
+ end
+
+ def self.user_dashboards(user)
+ result=nil
+ if user && user.id
+ result=find(:all, :include => 'dashboard', :conditions => ['user_id=?', user.id], :order => 'order_index')
+ end
+ if result.nil? || result.empty?
+ result=default_dashboards
+ end
+ result
+ end
+
+ def self.default_dashboards
+ find(:all, :include => 'dashboard', :conditions => ['user_id IS NULL'], :order => 'order_index')
+ end
+end \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/models/dashboard.rb b/sonar-server/src/main/webapp/WEB-INF/app/models/dashboard.rb
new file mode 100644
index 00000000000..a36f6aa1066
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/models/dashboard.rb
@@ -0,0 +1,77 @@
+#
+# Sonar, entreprise quality control tool.
+# Copyright (C) 2009 SonarSource SA
+# mailto:contact AT sonarsource DOT com
+#
+# Sonar is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 3 of the License, or (at your option) any later version.
+#
+# Sonar is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with Sonar; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+#
+class Dashboard < ActiveRecord::Base
+ belongs_to :user
+
+ has_many :widgets, :include => 'widget_properties', :dependent => :delete_all
+ has_many :active_dashboards, :dependent => :delete_all
+
+ validates_length_of :name, :within => 1..256
+ validates_length_of :description, :maximum => 1000, :allow_blank => true, :allow_nil => true
+ validates_length_of :column_layout, :maximum => 10, :allow_blank => false, :allow_nil => false
+ validates_uniqueness_of :name, :scope => :user_id
+
+ def shared?
+ read_attribute(:shared) || false
+ end
+
+ def author
+ dashboard.user
+ end
+
+ def author_name
+ author ? author.name : nil
+ end
+
+ def editable_by?(user)
+ (user && user_id==user.id) || (user_id.nil? && user.has_role?(:admin))
+ end
+
+ def owner?(user)
+ self.user_id==user.id
+ end
+
+ def number_of_columns
+ column_layout.split('-').size
+ end
+
+ def column_size(column_index)
+ last_widget=widgets.select{|w| w.column_index==column_index}.max{|x,y| x.order_index <=> y.order_index}
+ last_widget ? last_widget.order_index : 0
+ end
+
+ def deep_copy()
+ dashboard=Dashboard.new(attributes)
+ dashboard.shared=false
+ self.widgets.each do |child|
+ new_widget = Widget.create(child.attributes)
+
+ child.widget_properties.each do |prop|
+ widget_prop = WidgetProperty.create(prop.attributes)
+ new_widget.widget_properties << widget_prop
+ end
+
+ new_widget.save
+ dashboard.widgets << new_widget
+ end
+ dashboard.save
+ dashboard
+ end
+end \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/models/user.rb b/sonar-server/src/main/webapp/WEB-INF/app/models/user.rb
index 867dd27a6c5..6e08e3b17fd 100644
--- a/sonar-server/src/main/webapp/WEB-INF/app/models/user.rb
+++ b/sonar-server/src/main/webapp/WEB-INF/app/models/user.rb
@@ -28,6 +28,9 @@ class User < ActiveRecord::Base
has_many :properties, :foreign_key => 'user_id', :dependent => :delete_all
has_many :active_filters, :include => 'filter', :order => 'order_index'
has_many :filters, :dependent => :delete_all
+
+ has_many :active_dashboards, :dependent => :delete_all, :order => 'order_index'
+ has_many :dashboards, :dependent => :delete_all
include Authentication
include Authentication::ByPassword
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/models/widget.rb b/sonar-server/src/main/webapp/WEB-INF/app/models/widget.rb
new file mode 100644
index 00000000000..62e04d842cc
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/models/widget.rb
@@ -0,0 +1,86 @@
+#
+# Sonar, entreprise quality control tool.
+# Copyright (C) 2009 SonarSource SA
+# mailto:contact AT sonarsource DOT com
+#
+# Sonar is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 3 of the License, or (at your option) any later version.
+#
+# Sonar is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with Sonar; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+#
+class Widget < ActiveRecord::Base
+ STATE_ACTIVE='A'
+ STATE_INACTIVE='I'
+
+ has_many :widget_properties, :dependent => :delete_all
+ belongs_to :dashboards
+
+ validates_presence_of :name
+ validates_length_of :name, :within => 1..256
+
+ validates_presence_of :widget_key
+ validates_length_of :widget_key, :within => 1..256
+
+ validates_length_of :description, :maximum => 1000, :allow_blank => true, :allow_nil => true
+
+ def state
+ read_attribute(:state) || 'V'
+ end
+
+ #---------------------------------------------------------------------
+ # WIDGET PROPERTIES
+ #---------------------------------------------------------------------
+ def properties
+ widget_properties
+ end
+
+ def widget_property(key)
+ widget_properties().each do |p|
+ return p if (p.key==key)
+ end
+ nil
+ end
+
+ def widget_property_value(key)
+ prop=widget_property(key)
+ prop ? prop.value : nil
+ end
+
+ def set_widget_property(options)
+ key=options[:kee]
+ prop=widget_property(key)
+ if prop
+ prop.attributes=options
+ prop.widget_id=id
+ prop.save!
+ else
+ prop=WidgetProperty.new(options)
+ prop.widget_id=id
+ widget_properties<<prop
+ end
+ end
+
+ def delete_widget_property(key)
+ prop=widget_property(key)
+ if prop
+ widget_properties.delete(prop)
+ end
+ end
+
+ def properties_as_hash
+ hash={}
+ widget_properties.each do |prop|
+ hash[prop.key]=prop.value
+ end
+ hash
+ end
+end \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/models/widget_property.rb b/sonar-server/src/main/webapp/WEB-INF/app/models/widget_property.rb
new file mode 100644
index 00000000000..be6b9522aa5
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/models/widget_property.rb
@@ -0,0 +1,49 @@
+#
+# Sonar, entreprise quality control tool.
+# Copyright (C) 2009 SonarSource SA
+# mailto:contact AT sonarsource DOT com
+#
+# Sonar is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 3 of the License, or (at your option) any later version.
+#
+# Sonar is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with Sonar; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+#
+class WidgetProperty < ActiveRecord::Base
+
+ belongs_to :widgets
+
+ validates_presence_of :kee
+ validates_length_of :kee, :within => 1..100
+ validates_length_of :description, :maximum => 4000, :allow_blank => true, :allow_nil => true
+ validates_length_of :text_value, :maximum => 4000, :allow_blank => true, :allow_nil => true
+
+ def key
+ kee
+ end
+
+ def value
+ text_value
+ end
+
+ def to_hash_json
+ {:key => key, :value => value.to_s}
+ end
+
+ def to_xml(xml=Builder::XmlMarkup.new(:indent => 0))
+ xml.property do
+ xml.key(prop_key)
+ xml.value {xml.cdata!(text_value.to_s)}
+ end
+ xml
+ end
+
+end \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/admin_dashboards/index.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/admin_dashboards/index.html.erb
new file mode 100644
index 00000000000..aade1013455
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/views/admin_dashboards/index.html.erb
@@ -0,0 +1,72 @@
+<h1>Default dashboards</h1>
+<p>These dashboards are displayed to anonymous users or users that haven't customized their dashboards.</p>
+<br/>
+<table class="data" id="admin_console">
+ <thead>
+ <tr>
+ <th>Name</th>
+ <th>Shared by</th>
+ <th>Order</th>
+ <th>Operations</th>
+ </tr>
+ </thead>
+ <tbody>
+ <% if @actives.empty? %>
+ <tr class="even"><td colspan="4">No results.</td></tr>
+ <% else %>
+ <% @actives.each_with_index do |active,index| %>
+ <tr id="active-<%= u active.name -%>" class="<%= cycle('even','odd', :name => 'actives') -%>">
+ <td>
+ <%= h(active.name) %><br>
+ <span style="font-size: 85%;font-weight: normal;"><%= active.dashboard.description %></span>
+ </td>
+ <td><%= h(active.dashboard.user.name) if active.dashboard.user %></td>
+ <td>
+ <% if index>0 %>
+ <%= link_to image_tag('blue-up.png'), {:action => :up, :id => active.id}, :method => :post, :id => "up-#{u active.name}" %>
+ <% else %>
+ <%= image_tag('transparent_16.gif') %>
+ <% end %>
+ <% if index<@actives.size-1 %>
+ <%= link_to image_tag('blue-down.png'), {:action => :down, :id => active.id}, :method => :post, :id => "down-#{u active.name}" %>
+ <% end %>
+ </td>
+ <td>
+ <%= link_to 'Remove', {:action => 'remove', :id => active.id}, :confirm => 'Are you sure to remove it from default dashboards ?', :method => :post, :id => "remove-#{u active.name}" %>
+ </td>
+ </tr>
+ <% end %>
+ <% end %>
+ </tbody>
+</table>
+
+<br/><br/>
+<h1>Admin dashboards</h1>
+<p>These dashboards can be added to default dashboards.</p>
+<br/>
+<table class="data" id="shared">
+ <thead>
+ <tr>
+ <th>Name</th>
+ <th>Shared by</th>
+ <th>Operations</th>
+ </tr>
+ </thead>
+ <tbody>
+ <% if @default_dashboards.nil? || @default_dashboards.empty? %>
+ <tr class="even"><td colspan="3">No results.</td></tr>
+ <% else %>
+ <% @default_dashboards.each do |dashboard| %>
+ <tr class="<%= cycle('even', 'odd') -%>">
+ <td>
+ <%= h(dashboard.name) -%><br>
+ <span style="font-size: 85%;font-weight: normal;"><%= dashboard.description %></span>
+ </td>
+ <td><%= h(dashboard.user.name) if dashboard.user %></td>
+ <td><%= link_to 'Add to defaults', {:action => 'add', :id => dashboard.id}, :method => :post, :id => "add-#{u dashboard.name}" %></td>
+ </tr>
+ <% end %>
+ <% end %>
+ </tbody>
+</table>
+
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/_configure_widget.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/_configure_widget.html.erb
new file mode 100644
index 00000000000..bf0c1ce7280
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/_configure_widget.html.erb
@@ -0,0 +1,41 @@
+<%
+ begin
+ widget_body=render :inline => definition.getTarget().getTemplate(), :locals => {:widget_properties => widget.properties_as_hash}
+ rescue => error
+ logger.error("Can not render widget #{definition.getId()}: " + error)
+ logger.error(error.backtrace.join("\n"))
+ widget_body=""
+ end
+%>
+
+<div class="handle" style="//overflow:hidden;//zoom:1;">
+ <%= definition.getTitle() -%>
+ <a class="block-remove" onclick="remove_widget(this);return false;">Delete</a>
+ <a class="block-view-toggle" onclick="return toggle_block(this);">Edit</a> &nbsp;
+</div>
+<% if defined?(validation_result) %>
+ <div class="error" style="<%= "display: none;" unless validation_result["errormsg"] %>clear:both;margin: 0;border-bottom:0;">
+ <span class="errormsg"><%= validation_result["errormsg"] if validation_result["errormsg"] %></span> &nbsp;&nbsp;[<a href="#" onclick="hide_block_info($(this).up('.block'));return false;">hide</a>]
+ </div>
+ <div class="notice" style="<%= "display: none;" unless validation_result["infomsg"] %>clear:both;margin: 0;border-bottom:0;">
+ <span class="infomsg"><%= validation_result["infomsg"] if validation_result["infomsg"] %></span> &nbsp;&nbsp;[<a href="#" onclick="hide_block_info($(this).up('.block'));return false;">hide</a>]
+ </div>
+<% end %>
+
+<div id="widget_<%= definition.getId().tr('_', '') -%>" class="content <%= definition.getId() -%>" style="height:100%;">
+ <!--[if lte IE 6]>
+ <style type="text/css">
+ #dashboard .block .content .transparent {
+ display: none;
+ }
+ </style>
+ <![endif]-->
+<div class="transparent"></div>
+ <% if widget_body.include? '<' %>
+ <%= widget_body %>
+ <% else %>
+ <p>Can not render widget <b><%= definition.getTitle() %></b>.</p>
+ <% end %>
+<div style="clear: both;"></div>
+</div>
+
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/_header.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/_header.html.erb
new file mode 100644
index 00000000000..a3ee6996874
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/_header.html.erb
@@ -0,0 +1,29 @@
+<div class="line-block" style="position:relative;">
+<% if logged_in? %>
+ <ul class="operations">
+ <% if back %>
+ <li class="last"><%= link_to 'Back to dashboard', {:action => 'index', :id => @dashboard.id, :resource => @resource.id } -%></li>
+ <% else %>
+ <li><%= link_to 'Configure', {:action => 'configure', :id => @dashboard.id, :resource => @resource.id } -%></li>
+ <li><%= link_to 'Edit layout', {:action => 'edit_layout', :id => @dashboard.id, :resource => @resource.id } -%></li>
+ <li class="last"><%= link_to 'Manage dashboards', {:controller => 'dashboards', :action => 'index', :resource => @resource.id } -%></li>
+ <% end %>
+ </ul>
+<% end %>
+
+ <% if @snapshot %>
+ <div id="snapshot_title" class="page_title">
+ <h4>
+ <%
+ version_event=@snapshot.event(EventCategory::KEY_VERSION)
+ profile_measure=@snapshot.measure(Metric::PROFILE)
+ %>
+ <%= link_to_favourite(@project) -%> <%= "#{version_event.fullname} - " if version_event %> <%= l @snapshot.created_at %>
+ <% if profile_measure %> - profile <%= link_to profile_measure.data, :controller => '/rules_configuration', :action => 'index', :id => profile_measure.value.to_i %><% end %>
+ </h4>
+ </div>
+ <% end %>
+</div>
+
+
+
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/_widget.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/_widget.html.erb
new file mode 100644
index 00000000000..748a16b8e99
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/_widget.html.erb
@@ -0,0 +1,22 @@
+<div id="widget_<%= definition.getId().tr('_', '') -%>" class="content <%= definition.getId() %>" style="height:100%;">
+<%
+ begin
+ widget_body=render :inline => definition.getTarget().getTemplate(), :locals => {:widget_properties => widget.properties_as_hash}
+ rescue => error
+ logger.error("Can not render widget #{definition.getId()}: " + error)
+ logger.error(error.backtrace.join("\n"))
+ widget_body=""
+ end
+
+ if widget_body.include?('<')
+%>
+ <%= widget_body %>
+<%
+ else
+%>
+ <p>Can not render widget <b><%= definition.getTitle() %></b>.</p>
+<%
+ end
+%>
+<div style="clear: both;"></div>
+</div> \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/_widget_definition.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/_widget_definition.html.erb
new file mode 100644
index 00000000000..ee7ca54dc24
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/_widget_definition.html.erb
@@ -0,0 +1,7 @@
+<div class="widget_def" id="def_<%= definition.getId().tr('_', '') -%>">
+<p><%= h definition.getTitle() -%></p>
+<p><%= h definition.getDescription() -%></p>
+<%= form_tag :action => 'add_widget', :id => @dashboard.id, :resource => params[:resource], :widget => definition.getId() %>
+ <input type="submit" value="Add" >
+</form>
+</div> \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/configure.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/configure.html.erb
new file mode 100644
index 00000000000..5605bda6cff
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/configure.html.erb
@@ -0,0 +1,82 @@
+<script type="text/javascript">
+ <!--
+ var options = {
+ editorEnabled: true,
+ portal: 'dashboard',
+ column: 'dashboard-column',
+ columnhandle: 'column-handle',
+ block: 'block',
+ content: 'content',
+ handle: 'none',
+ hoverclass: 'block-hover',
+ dashboardstate: 'dashboardstate',
+ toggle: 'block-toggle',
+ blocklist: 'dashboard-block-carousel',
+ widgetedit: 'widgetedit',
+ highlight_duration: 2,
+ highlight_startcolor: '#ffff99',
+ highlight_endcolor: '#ffffff',
+ saveurl: '<%= url_for :action => 'set_dashboard', :id => @dashboard.id, :resource => @resource.id -%>'
+ };
+ var portal;
+ function init_dashboard() {
+ portal = new Portal(options);
+ <% if params[:highlight] %>
+ portal.highlightWidget(<%= params[:highlight] -%>);
+ <% end %>
+ }
+ Event.observe(window, 'load', init_dashboard, false);
+
+ function remove_widget(link) {
+ $(link).up('.block').remove();
+ portal.saveDashboardsState();
+ }
+ //-->
+</script>
+
+
+<div id="dashboard">
+ <%= render :partial => 'dashboard/header', :locals => {:back => true} %>
+
+<div id="dashboard-block-carousel" class="admin marginbottom10">
+
+ <div id="dashboard-block-container" class="container">
+ <div id="widget_definitions">
+ <ul>
+ <% @widget_definitions.each_with_index do |definition, index| %>
+ <li>
+ <%= render :partial => 'dashboard/widget_definition', :locals => {:definition => definition} %>
+ </li>
+ <% end %>
+ </ul>
+ </div>
+ </div>
+ <div style="clear: both;"></div>
+</div>
+
+
+ <%
+ columns=@dashboard.column_layout.split('-')
+ for index in 1..columns.size()
+ %>
+ <div class="dashboard-column-wrapper" style="width: <%= (columns.size()>0) ? columns[index-1].to_i : 100 %>%; clear: right;">
+ <div class="dashboard-column" id="dashboard-column-<%= index -%>" style="margin: 0px <%= index<columns.size() ? "5px" : "0px" %> 0px <%= index>1 ? "5px" : "0px" %>;">
+ <div class="column-handle" style="display: none"> </div>
+
+ <%
+ @dashboard.widgets.select{|widget| widget.column_index==index}.sort_by{|widget| widget.order_index}.each do |widget|
+ widget_definition=@widget_definitions.find{|wd| wd.getId()==widget.widget_key }
+ if widget_definition
+ %>
+ <div class="block" id="block_<%= widget.id -%>">
+ <%= render :partial => 'dashboard/configure_widget', :locals => {:widget => widget, :definition => widget_definition} %>
+ </div>
+ <%
+ end
+ end
+ %>
+ </div>
+ </div>
+ <% end %>
+ <div style="clear: both;"></div>
+</div> \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/edit_layout.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/edit_layout.html.erb
new file mode 100644
index 00000000000..9d906e9b323
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/edit_layout.html.erb
@@ -0,0 +1,28 @@
+<div id="dashboard">
+ <%= render :partial => 'dashboard/header', :locals => {:back => true} %>
+
+ <div id="edit-layout" class="admin">
+ <p class="note">Click to choose the layout: </p><br/>
+ <!--100%-->
+ <div class="layout-example-wrapper" style="text-align:center;width: 20%;">
+ <%= link_to image_tag('layout100.png'), {:action => 'set_layout', :id => @dashboard.id, :resource => @resource.id, :layout => "100"}, :method => "post" %>
+ </div>
+ <!--50%-50%-->
+ <div class="layout-example-wrapper" style="text-align:center;width: 20%;">
+ <%= link_to image_tag('layout5050.png'), {:action => 'set_layout', :id => @dashboard.id, :resource => @resource.id, :layout => "50-50"}, :method => "post" %>
+ </div>
+ <!--30%-70%-->
+ <div class="layout-example-wrapper" style="text-align:center;width: 20%;">
+ <%= link_to image_tag('layout3070.png'), {:action => 'set_layout', :id => @dashboard.id, :resource => @resource.id, :layout => "30-70"}, :method => "post" %>
+ </div>
+ <!--70%-30%-->
+ <div class="layout-example-wrapper" style="text-align:center;width: 20%;">
+ <%= link_to image_tag('layout7030.png'), {:action => 'set_layout', :id => @dashboard.id, :resource => @resource.id, :layout => "70-30"}, :method => "post" %>
+ </div>
+ <!--33%-33%-33%-->
+ <div class="layout-example-wrapper" style="text-align:center;width: 19%;">
+ <%= link_to image_tag('layout333333.png'), {:action => 'set_layout', :id => @dashboard.id, :resource => @resource.id, :layout => "33-33-33"}, :method => "post" %>
+ </div>
+ <div style="clear:both;"></div>
+ </div>
+</div> \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/index.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/index.html.erb
new file mode 100644
index 00000000000..e7a6d569daa
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboard/index.html.erb
@@ -0,0 +1,26 @@
+<div id="dashboard">
+ <%= render :partial => 'dashboard/header', :locals => {:back => false} %>
+
+ <%
+ columns=@dashboard.column_layout.split('-')
+ for index in 1..columns.size()
+ %>
+ <div class="dashboard-column-wrapper" style="width: <%= (columns.size()>0) ? columns[index-1].to_i : 100 %>%; clear: right;">
+ <div class="dashboard-column" id="dashboard-column-<%= index -%>" style="margin: 0px <%= index<columns.size() ? "5px" : "0px" %> 0px <%= index>1 ? "5px" : "0px" %>;">
+ <%
+ @dashboard.widgets.select{|widget| widget.column_index==index}.sort_by{|widget| widget.order_index}.each do |widget|
+ widget_definition=@widget_definitions.find{|wd| wd.getId()==widget.widget_key }
+ if widget_definition
+ %>
+ <div class="block" id="block_<%= widget.id -%>">
+ <%= render :partial => 'dashboard/widget', :locals => {:widget => widget, :definition => widget_definition} %>
+ </div>
+ <%
+ end
+ end
+ %>
+ </div>
+ </div>
+ <% end %>
+ <div style="clear: both;"></div>
+</div> \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_create.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_create.html.erb
new file mode 100644
index 00000000000..72f6133a23f
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_create.html.erb
@@ -0,0 +1,35 @@
+
+<table class="admintable" width="100%">
+ <form action="<%= url_for :action => 'create', :resource => params[:resource] -%>" id="create-dashboard-form" method="POST">
+ <tbody>
+ <tr>
+ <td colspan="2"><h1>Create dashboard</h1></td>
+ </tr>
+ <tr>
+ <td class="left" valign="top">
+ Name:<br/><input type="text" name="name" size="30" maxlength="256"></input>
+ </td>
+ </tr>
+ <tr>
+ <td class="left" valign="top">
+ Description:<br/><input type="text" name="description" size="30" maxlength="1000"></input>
+ </td>
+ </tr>
+ <% if is_admin? %>
+ <tr>
+ <td class="left" valign="top">
+ Shared:<br/><input type="checkbox" name="shared" value="true"></input>
+ </td>
+ </tr>
+ <% end %>
+ <tr>
+ <td class="left" valign="top">
+ <input type="submit" value="Create dashboard"/>
+ </td>
+ </tr>
+ </tbody>
+ </form>
+</table>
+<script>
+ $('create-dashboard-form').name.focus();
+</script> \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_dashboard.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_dashboard.html.erb
new file mode 100644
index 00000000000..8835f7c85ff
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_dashboard.html.erb
@@ -0,0 +1,186 @@
+<% if @dashboard && ((@dashboard.widgets.size > 0 && @dashboard.column_layout.split("-").size() > 0)||dashboard_edit) %>
+ <script type="text/javascript">
+ <!--
+ var options = {
+ <% if dashboard_edit %>
+ editorEnabled: true,
+ <% else %>
+ editorEnabled: false,
+ <% end %>
+ portal: 'dashboard',
+ column: 'dashboard-column',
+ columnhandle: 'column-handle',
+ block: 'block',
+ content: 'content',
+ handle: 'none',
+ hoverclass: 'block-hover',
+ dashboardstate: 'dashboardstate',
+ toggle: 'block-toggle',
+ blocklist: 'dashboard-block-carousel',
+ widgetedit: 'widgetedit',
+ highlight_duration: 2,
+ highlight_startcolor: '#ffff99',
+ highlight_endcolor: '#ffffff',
+ <% if dashboard_edit %>
+ saveurl: '<%= url_for :action => 'savedashboard', :id => @project.id, :dashboard => @dashboard.id -%>'
+ <% else %>
+ saveurl: ''
+ <% end %>
+ };
+ var portal;
+ function init() {
+ portal = new Portal(options);
+
+ if ($("dashboard-block-carousel") && $("dashboard-block-carousel").visible()) {
+ new UI.Carousel("dashboard-block-carousel");
+ }
+ }
+ Event.observe(window, 'load', init, false);
+ //-->
+ </script>
+
+ <div id='dashboard'>
+ <% if dashboard_edit %>
+ <script type="text/javascript">
+ <!--
+ function operations_toggle(link_element, editzone) {
+ $('dashboard-edit').hide();
+ $('dashboard-layout').hide();
+ $('dashboard-block-carousel').hide();
+
+ $(link_element).up('ul').childElements().each(
+ function (li_element) {
+ $(li_element).removeClassName('selected');
+ });
+
+ var li_element = $(link_element).up('li');
+ li_element.addClassName('selected');
+
+ $(editzone).show();
+
+ if ($(editzone)==$("dashboard-block-carousel") && $("dashboard-block-carousel").visible()) {
+ new UI.Carousel("dashboard-block-carousel");
+ }
+ }
+
+ function toggle_block(link) {
+ if ($(link).innerHTML=="[view]") {
+ $(link).up('.block').down(".widgetedit").fade({duration: 0.2, afterFinish: function() {
+ $(link).up('.block').down(".content").show();
+ }});
+ $(link).update("[edit]");
+ } else {
+ $(link).up('.block').down(".content").fade({duration: 0.2, afterFinish: function() {
+ $(link).up('.block').down(".widgetedit").show();
+ }});
+ if (Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE") + 5)) == 6) {
+ $(link).update("");
+ } else {
+ $(link).update("[view]");
+ }
+ }
+ return false;
+ }
+
+ function remove_block(link) {
+ $(link).up('.block').remove();
+ portal.saveDashboardsState();
+ }
+
+ function hide_block_info(widget_block) {
+ if ($(widget_block).down(".error")) {
+ $(widget_block).down(".error").hide();
+ }
+ if ($(widget_block).down(".notice")) {
+ $(widget_block).down(".notice").hide();
+ }
+ $A($(widget_block).select(".editrow")).each(function (row, row_index) {
+ row.removeClassName('valid-editrow')
+ row.removeClassName('invalid-editrow')
+ });
+ }
+ //-->
+ </script>
+ <div id="dashboard-operations">
+ <ul class="operations">
+ <li><a href="#" onclick="operations_toggle(this, 'dashboard-edit');">Edit dashboard</a></li>
+ <li><a href="#" onclick="operations_toggle(this, 'dashboard-layout');">Edit layout</a></li>
+ <li class="selected last">
+ <a href="#" onclick="operations_toggle(this, 'dashboard-block-carousel');">Add widgets</a></li>
+ </ul>
+ <div style="clear:both;"></div>
+ </div>
+
+ <%= render :partial => 'dashboards/editform' %>
+
+ <%= render :partial => 'dashboards/layouts' %>
+
+ <div id="dashboard-block-carousel" class="admin">
+
+ <p>Drag and drop to arrange widgets the way you like in available columns. If you want delete widget drag
+ it back into this area.</p>
+ <br/>
+
+ <div class="button-wrapper">
+ <div class="previous_button"></div>
+ </div>
+ <div id="dashboard-block-container" class="container">
+ <ul>
+ <% @widgets.each_with_index do |widget_view, index|
+ if widget_view %>
+ <li>
+ <div class="block" id="block_<%= widget_view.getId().tr('_', '') -%>">
+
+ <%= render :partial => 'dashboards/widget',
+ :locals => {:dashboard_edit => dashboard_edit,
+ :widget => nil,
+ :widget_view => widget_view,
+ :edit_mode => false} %>
+
+ </div>
+ </li>
+ <% end %>
+ <% end %>
+ </ul>
+ </div>
+ <div class="button-wrapper">
+ <div class="next_button"></div>
+ </div>
+ <div style="clear: both;"></div>
+ </div>
+
+ <% end %>
+
+ <% columns=Array.new
+ if @dashboard && @dashboard.column_layout
+ columns=@dashboard.column_layout.split("-")
+ end
+ for index in 1..columns.size() %>
+ <div class="dashboard-column-wrapper" style="width: <%=(columns.size()>0) ? columns[index-1].to_i : 100/columns.size() %>%; clear: right;">
+ <div class="dashboard-column" id="dashboard-column-<%= index -%>" style="margin: 0px <%= index<columns.size() ? "5px" : "0px" %> 0px <%= index>1 ? "5px" : "0px" %>;">
+ <% if dashboard_edit %>
+ <div style="width: 100%; height:20px; margin: 0; padding: 0;"></div>
+ <div class="column-handle"<%= ' style="display: none;"' if @dashboard.widgets.find(:all, :conditions => {:column_index => index}).size()>0 %>>Drop widgets here</div>
+ <% end %>
+
+ <% @dashboard.widgets.find(:all, :conditions => {:column_index => index}, :order => :order_index).each do |widget|
+ widget_view=@widgets.find { |w| w.getId()== widget.widget_key }
+ if widget_view %>
+ <div class="block" id="block_<%= widget.id -%>">
+
+ <%= render :partial => 'dashboards/widget',
+ :locals => {:dashboard_edit => dashboard_edit,
+ :widget => widget,
+ :widget_view => widget_view,
+ :edit_mode => false} %>
+
+ </div>
+ <% end %>
+ <% end %>
+
+ </div>
+ </div>
+ <% end %>
+ <div style="clear: both;"></div>
+ </div>
+<% end %> \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_edit.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_edit.html.erb
new file mode 100644
index 00000000000..14b734c41b7
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_edit.html.erb
@@ -0,0 +1,32 @@
+<form action="<%= url_for :action => 'update', :id => @dashboard.id, :resource => params[:resource] -%>" method="POST">
+<table class="admintable" width="100%">
+ <tbody>
+ <tr>
+ <td colspan="2"><h1>Edit dashboard</h1></td>
+ </tr>
+ <tr>
+ <td class="left" valign="top">
+ Name:<br/><input type="text" name="name" size="30" maxlength="256" value="<%= @dashboard.name -%>"></input>
+ </td>
+ </tr>
+ <tr>
+ <td class="left" valign="top">
+ Description:<br/><input type="text" name="description" size="30" maxlength="1000" value="<%= @dashboard.description -%>"></input>
+ </td>
+ </tr>
+ <% if is_admin? %>
+ <tr>
+ <td class="left" valign="top">
+ Shared:<br/><input type="checkbox" name="shared" value="true" <%= 'checked' if @dashboard.shared -%>></input>
+ </td>
+ </tr>
+ <% end %>
+ <tr>
+ <td class="left" valign="top">
+ <input type="submit" value="Update dashboard"/>
+ <a href="<%= url_for :action => 'index', :resource => params[:resource] -%>">Cancel</a>
+ </td>
+ </tr>
+ </tbody>
+</table>
+</form> \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_editform.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_editform.html.erb
new file mode 100644
index 00000000000..f330d0f5bc7
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_editform.html.erb
@@ -0,0 +1,47 @@
+<div id="dashboard-edit" class="admin" <%= (@dashboard.id ? 'style="display: none;"' : "") %>>
+ <form id="dashboard_form" name="dashboard_form" action="<%= url_for :action => (@dashboard.id ? 'update' : 'create'), :id => @project.id, :dashboard => @dashboard.id -%>" method="post">
+ <table class="form">
+ <tbody>
+ <tr>
+ <td class="first">Name:</td>
+ <td>
+ <input type="text" name="name" id="name" size="40" value="<%= @dashboard.name -%>" class="spaced"/>
+ </td>
+ </tr>
+ </tbody>
+ <% if is_admin? %>
+ <tbody id="simple-form">
+ <tr>
+ <td class="first">Shared:</td>
+ <td>
+ <input type="checkbox" name="shared" id="shared" <%= 'checked' if @dashboard.shared? -%>/>
+ </td>
+ </tr>
+ </tbody>
+ <% end %>
+ <tbody>
+ <tr>
+ <td class="first">Description:</td>
+ <td>
+ <textarea name="description" cols="40" rows="4" id="description"><%= @dashboard.description -%></textarea>
+ </td>
+ </tr>
+ </tbody>
+ <tbody>
+ <tr>
+ <td colspan="2">
+ <input type="submit" value="Save"/>
+ <span class="spacer"> </span>
+ <% if @dashboard.id %>
+ <%= link_to "Delete", {:action => 'delete', :id => @project.id, :dashboard => @dashboard.id}, :method => :post, :confirm => 'Do you want to delete this dashboard ?' %>
+ <span class="spacer"> </span>
+ <a href="<%= url_for :action => 'index', :id => @project.id, :dashboard => @dashboard.id -%>">Cancel</a>
+ <% else %>
+ <a href="<%= url_for :action => 'index', :id => @project.id -%>">Cancel</a>
+ <% end %>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </form>
+</div> \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_layouts.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_layouts.html.erb
new file mode 100644
index 00000000000..9fdacdb52cd
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_layouts.html.erb
@@ -0,0 +1,25 @@
+ <div id="dashboard-layout" class="admin" style="display: none; margin:0; padding:0;">
+ <p>Choose predefined layout.</p>
+ <br/>
+ <!--100%-->
+ <div class="layout-example-wrapper" style="text-align:center;width: 20%;">
+ <%= link_to image_tag('layout100.png'), {:action => 'layout', :id => @project.id, :dashboard => @dashboard.id, :layout => "100"}, :method => "post" %>
+ </div>
+ <!--50%-50%-->
+ <div class="layout-example-wrapper" style="text-align:center;width: 20%;">
+ <%= link_to image_tag('layout5050.png'), {:action => 'layout', :id => @project.id, :dashboard => @dashboard.id, :layout => "50-50"}, :method => "post" %>
+ </div>
+ <!--30%-70%-->
+ <div class="layout-example-wrapper" style="text-align:center;width: 20%;">
+ <%= link_to image_tag('layout3070.png'), {:action => 'layout', :id => @project.id, :dashboard => @dashboard.id, :layout => "30-70"}, :method => "post" %>
+ </div>
+ <!--70%-30%-->
+ <div class="layout-example-wrapper" style="text-align:center;width: 20%;">
+ <%= link_to image_tag('layout7030.png'), {:action => 'layout', :id => @project.id, :dashboard => @dashboard.id, :layout => "70-30"}, :method => "post" %>
+ </div>
+ <!--33%-33%-33%-->
+ <div class="layout-example-wrapper" style="text-align:center;width: 19%;">
+ <%= link_to image_tag('layout333333.png'), {:action => 'layout', :id => @project.id, :dashboard => @dashboard.id, :layout => "33-33-33"}, :method => "post" %>
+ </div>
+ <div style="clear:both;"></div>
+ </div> \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_snapshot_title.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_snapshot_title.html.erb
new file mode 100644
index 00000000000..c5a57fb1533
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_snapshot_title.html.erb
@@ -0,0 +1,12 @@
+<% if @snapshot %>
+<div id="snapshot_title" class="page_title">
+<h4>
+<%
+ version_event=@snapshot.event(EventCategory::KEY_VERSION)
+ profile_measure=@snapshot.measure(Metric::PROFILE)
+ %>
+<%= link_to_favourite(@project) -%> <%= "#{version_event.fullname} - " if version_event %> <%= l @snapshot.created_at %>
+<% if profile_measure %> - profile <%= link_to profile_measure.data, :controller => '/rules_configuration', :action => 'index', :id => profile_measure.value.to_i %><% end %>
+</h4>
+</div>
+<% end %> \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_tabs.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_tabs.html.erb
new file mode 100644
index 00000000000..1e594e2730d
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_tabs.html.erb
@@ -0,0 +1,21 @@
+<% if logged_in? %>
+<div id="page-operations" style="position:relative;">
+ <ul class="operations">
+ <li><%= link_to 'Add dashboard', {:action => 'new', :id => @project.id } -%></li>
+ <% if selected_tab && @dashboard %>
+ <li><%= link_to 'Edit dashboard', {:action => 'edit', :id => @project.id, :dashboard => @dashboard.id } -%></li>
+ <% end %>
+ <li class="last"><%= link_to 'Manage dashboards', {:action => 'manage', :id => @project.id } -%></li>
+ </ul>
+</div>
+<% end %>
+
+<% if @actives && !@actives.empty? %>
+<ul class="tabs" id="dashboard-tabs" style="border-bottom: 1px solid #cdcdcd; margin-bottom:3px;">
+<% @actives.each do |active| %>
+ <li>
+ <a href="<%= url_for :action => 'index', :id => @project.id, :dashboard => active.dashboard.id -%>" class="<%= 'selected' if selected_tab==active.dashboard.id -%>"><%= active.name -%><%= " *" if active.dashboard.shared? %></a>
+ </li>
+<% end %>
+</ul>
+<% end %>
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_widget.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_widget.html.erb
new file mode 100644
index 00000000000..d7c834d0f50
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_widget.html.erb
@@ -0,0 +1,100 @@
+<%
+ properties_available=widget_view.getProperties() && widget_view.getProperties().size() != 0
+
+ if !properties_available || (widget && widget.state==Widget::STATE_ACTIVE)
+ begin
+ widget_properties=Hash.new
+ if widget
+ widget.widget_properties.each do |property|
+ widget_properties[property.key]=property.value
+ end
+ end
+ widget_body=render :inline => widget_view.getTarget().getTemplate(), :locals => {:widget_properties => widget_properties}
+ rescue => error
+ logger.error("Can not render widget #{widget_view.getId()}: " + error)
+ logger.error(error.backtrace.join("\n"))
+ widget_body=""
+ end
+ end
+%>
+
+<% if dashboard_edit || (widget.state==Widget::STATE_ACTIVE && widget_body.include?('<')) %>
+
+ <div class="handle" style="//overflow:hidden;//zoom:1;<%= !dashboard_edit ? "display: none;" : "" %>">
+ <%= (widget) ? widget.name : widget_view.getTitle() -%>
+ <% if dashboard_edit %>
+ <a class="block-remove" style="//margin: -1em 0 0 0;" onclick="remove_block(this);return false;">[x]</a>
+ <% if properties_available && widget && widget.state==Widget::STATE_ACTIVE %>
+ <a class="block-view-toggle" style="//margin: -1em 0 0 0;" onclick="return toggle_block(this);">[<%= edit_mode ? "view" : "edit" %>]</a> &nbsp;
+ <% end %>
+ <% end %>
+ </div>
+ <% if defined?(validation_result) %>
+ <div class="error" style="<%= "display: none;" unless validation_result["errormsg"] %>clear:both;margin: 0;border-bottom:0;">
+ <span class="errormsg"><%= validation_result["errormsg"] if validation_result["errormsg"] %></span> &nbsp;&nbsp;[<a href="#" onclick="hide_block_info($(this).up('.block'));return false;">hide</a>]
+ </div>
+ <div class="notice" style="<%= "display: none;" unless validation_result["infomsg"] %>clear:both;margin: 0;border-bottom:0;">
+ <span class="infomsg"><%= validation_result["infomsg"] if validation_result["infomsg"] %></span> &nbsp;&nbsp;[<a href="#" onclick="hide_block_info($(this).up('.block'));return false;">hide</a>]
+ </div>
+ <% end %>
+
+ <div class="description">
+ <div style="height:90px;overflow-y:auto;"><%= widget_view.getDescription() -%></div>
+
+ <div align="center"><%= button_to_function "Add", "portal.addNewWidget($(this).up('.block'),$$('.column-handle')[0]);", :style => "width:40px;"%></div>
+ </div>
+
+ <% if properties_available && dashboard_edit %>
+ <div class="widgetedit" style="height:100%;<%= "display: none;" unless (edit_mode || (widget && widget.state==Widget::STATE_INACTIVE)) %>">
+ <% form_remote_tag :url => {:action => 'savewidget', :id => @project.id, :dashboard => @dashboard.id},
+ :method => "post",
+ :before => "$(this).down('.widgetid').value=$(this).up('.block').identify().split('_').pop();hide_block_info($(this).up('.block'))" do -%>
+ <table class="form" align="center" style="border-collapse:separate;border-spacing:5px;">
+ <tbody>
+ <% widget_view.getProperties().each do |property|
+ db_property_value=widget.widget_property_value(property.key()) if widget
+ entered_value=params[property.key()]
+ entered_value=property.defaultValue() if !entered_value || entered_value.empty?
+ entered_value=nil unless edit_mode
+ editrow_class=""
+ if defined?(validation_result)
+ editrow_class= validation_result[property.key()]=="valid" ? "valid-editrow" : "invalid-editrow"
+ end
+ %>
+ <tr>
+ <td class="first"><%= property.name() -%>:<br>
+ <span style="font-size: 85%;font-weight: normal;">[<%= property.type()+" "+property.key() -%>]</span></td>
+ <td id="row_<%= property.key() -%>" class="editrow <%= editrow_class %>" style="vertical-align: middle;"><%= property_value_field(property.type(), property.key(), db_property_value, entered_value) %><%= "&nbsp;*" unless property.optional() %>
+ <br>
+ <span style="font-size: 85%;font-weight: normal;">[<%= property.description() -%>]</span></td>
+ </tr>
+ <% end %>
+ </tbody>
+ </table>
+ <%= hidden_field_tag "widgetid", "", :class => "widgetid" %>
+ <div align="center"><%= submit_tag 'Save' %></div>
+ <% end -%>
+ </div>
+ <% end %>
+
+ <% if (dashboard_edit && (!properties_available || (widget && widget.state==Widget::STATE_ACTIVE))) || (widget_body && widget_body.include?('<')) %>
+ <div id="widget_<%= (widget) ? widget.id : widget_view.getId().tr('_', '') -%>" class="content <%= widget_view.getId() %>" style="height:100%;<%= "display: none;" if edit_mode || (properties_available && widget && widget.state==Widget::STATE_INACTIVE) %>">
+ <% if dashboard_edit %>
+ <!--[if lte IE 6]>
+ <style type="text/css">
+ #dashboard .block .content .transparent {
+ display: none;
+ }
+ </style>
+ <![endif]-->
+ <div class="transparent"></div>
+ <% end %>
+ <% if widget_body.include? '<' %>
+ <%= widget_body %>
+ <% else %>
+ <p>Can not render widget <b><%= widget_view.getTitle() %></b>.
+ <% end %>
+ <div style="clear: both;"></div>
+ </div>
+ <% end %>
+<% end %> \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_widget_update.rjs b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_widget_update.rjs
new file mode 100644
index 00000000000..39b20ce7278
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/_widget_update.rjs
@@ -0,0 +1,6 @@
+page.replace_html 'block_'+widget.id.to_s(), :partial => 'dashboards/widget',
+ :locals => {:dashboard_edit => true,
+ :widget => widget,
+ :widget_view => widget_view,
+ :edit_mode => result["saved"]!="true",
+ :validation_result => result}
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/index.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/index.html.erb
new file mode 100644
index 00000000000..e2244e56b5f
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/index.html.erb
@@ -0,0 +1,62 @@
+<% is_admin=is_admin? %>
+<table width="100%">
+ <tr>
+ <td valign="top">
+
+ <h1 class="marginbottom10">My dashboards</h1>
+ <table class="data" id="dashboards">
+ <thead>
+ <tr>
+ <th>Name</th>
+ <% if is_admin %><th>Shared</th><% end %>
+ <th>Order</th>
+ <th>Operations</th>
+ </tr>
+ </thead>
+ <tbody>
+ <% if @actives.nil? || @actives.empty? %>
+ <tr class="even"><td colspan="5">No dashboards</td></tr>
+ <%
+ else
+ @actives.each_with_index do |active,index| %>
+ <tr id="dashboard-<%= u active.name -%>" class="<%= cycle('even','odd', :name => 'dashboards') -%>">
+ <td><%= active.name %></td>
+ <% if is_admin %>
+ <td>
+ <%= boolean_icon(active.dashboard.shared, {:display_false => false}) -%>
+ </td>
+ <% end %>
+ <td>
+ <% if index>0 %>
+ <%= link_to image_tag('blue-up.png'), {:action => 'up', :id => active.dashboard_id, :resource => params[:resource]}, :method => :post, :id => "up-#{u active.name}" %>
+ <% else %>
+ <%= image_tag('transparent_16.gif') %>
+ <% end %>
+ <% if index<@actives.size-1 %>
+ <%= link_to image_tag('blue-down.png'), {:action => 'down', :id => active.dashboard.id, :resource => params[:resource]}, :method => :post, :id => "down-#{u active.name}" %>
+ <% end %>
+ </td>
+ <td>
+ <% if !active.shared? || is_admin %>
+ <%= link_to_remote "Edit", :update => "admin_form", :url => { :action => "edit", :id => active.dashboard_id, :resource => params[:resource] }, :id => "edit-#{u active.name}", :method => :get %>
+ <%= link_to 'Delete', {:action => 'delete', :id => active.dashboard_id, :resource => params[:resource]}, :method => :post, :confirm => 'Do you want to delete this dashboard ?', :id => "delete-#{u active.name}" %>
+ <% else %>
+ <%= link_to 'Unfollow', {:action => 'unfollow', :id => active.dashboard_id}, :method => :post, :id => "hide-#{u active.name}" %>
+ <% end %>
+ </td>
+ </tr>
+ <% end
+ end
+ %>
+ </tbody>
+ </table>
+
+ </td>
+ <td class="sep"> </td>
+ <td width="210" valign="top" align="right">
+ <div id="admin_form">
+ <%= render :partial => 'dashboards/create' %>
+ </div>
+ </td>
+ </tr>
+</table>
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/manage.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/manage.html.erb
new file mode 100644
index 00000000000..2dfc964f2b3
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/manage.html.erb
@@ -0,0 +1,86 @@
+<%= render :partial => 'dashboards/tabs', :locals => {:selected_tab => nil} %>
+
+<h1>My dashboards</h1>
+<p>These dashboards are active and visible.</p>
+<br/>
+<table class="data" id="actives">
+ <thead>
+ <tr>
+ <th>Name</th>
+ <th>Default</th>
+ <th>Order</th>
+ <th>Operations</th>
+ </tr>
+ </thead>
+ <tbody>
+ <% if @actives.nil? || @actives.empty? %>
+ <tr class="even"><td colspan="5">No dashboards</td></tr>
+
+ <%
+ else
+ @actives.each_with_index do |active,index| %>
+ <tr id="active-<%= u active.name -%>" class="<%= cycle('even','odd', :name => 'actives') -%>">
+ <td><%= active.name %></td>
+ <td>
+ <%= boolean_icon(active.dashboard.shared, {:display_false => false}) -%>
+ </td>
+ <td>
+ <% if index>0 %>
+ <%= link_to image_tag('blue-up.png'), {:action => 'up', :id => @project.id, :dashboard => active.dashboard.id}, :method => :post, :id => "up-#{u active.name}" %>
+ <% else %>
+ <%= image_tag('transparent_16.gif') %>
+ <% end %>
+ <% if index<@actives.size-1 %>
+ <%= link_to image_tag('blue-down.png'), {:action => 'down', :id => @project.id, :dashboard => active.dashboard.id}, :method => :post, :id => "down-#{u active.name}" %>
+ <% end %>
+ </td>
+ <td>
+ <% if !active.shared? || is_admin? %>
+ <%= link_to 'Edit', {:action => 'edit', :id => @project.id, :dashboard => active.dashboard_id}, :method => :post, :id => "edit-#{u active.name}" %> |
+ <%= link_to 'Delete', {:action => 'delete', :id => @project.id, :dashboard => active.dashboard_id, :manage => true}, :method => :post, :confirm => 'Do you want to delete this dashboard ?', :id => "delete-#{u active.name}" %>
+ <% else %>
+ <%= link_to 'Edit', {:action => 'edit', :id => @project.id, :dashboard => active.dashboard_id}, :method => :post, :id => "edit-#{u active.name}" %> |
+ <%= link_to 'Hide', {:action => 'hide', :id => @project.id, :dashboard => active.dashboard_id}, :method => :post, :id => "hide-#{u active.name}" %>
+ <% end %>
+ </td>
+ </tr>
+ <% end
+ end
+ %>
+ </tbody>
+</table>
+
+<br/><br/><br/>
+<h1>Disabled dashboards</h1>
+<p>These dashboards are hided.</p>
+<br/>
+<table class="data" id="shared">
+ <thead>
+ <tr>
+ <th>Name</th>
+ <th>Default</th>
+ <th>Operations</th>
+ </tr>
+ </thead>
+ <tbody>
+ <% if @disabled_dashboards.nil? || @disabled_dashboards.empty? %>
+ <tr class="even"><td colspan="3">No dashboards</td></tr>
+
+ <%
+ else
+ @disabled_dashboards.each_with_index do |disabled,index|
+ %>
+ <tr id="active-<%= u disabled.name -%>" class="<%= cycle('even','odd', :name => 'actives') -%>">
+ <td><%= disabled.name %></td>
+ <td>
+ <%= boolean_icon(disabled.dashboard.shared, {:display_false => false}) -%>
+ </td>
+ <td>
+ <%= link_to 'Show', {:action => 'show', :id => @project.id, :dashboard => disabled.dashboard_id}, :method => :post, :id => "show-#{u disabled.name}" %>
+ </td>
+ </tr>
+ <% end
+ end
+ %>
+ </tbody>
+</table> \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/new.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/new.html.erb
new file mode 100644
index 00000000000..4158e623378
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/app/views/dashboards/new.html.erb
@@ -0,0 +1,6 @@
+<%= render :partial => 'dashboards/tabs', :locals => {:selected_tab => (@dashboard ? @dashboard.id : 'new') } %>
+<% if @dashboard.id %>
+ <%= render :partial => 'dashboards/dashboard', :locals => {:dashboard_edit => true } %>
+<% else %>
+ <%= render :partial => 'dashboards/editform' %>
+<% end %> \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/layouts/_head.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/layouts/_head.html.erb
index 44741eea52d..4c6de8ef374 100644
--- a/sonar-server/src/main/webapp/WEB-INF/app/views/layouts/_head.html.erb
+++ b/sonar-server/src/main/webapp/WEB-INF/app/views/layouts/_head.html.erb
@@ -18,6 +18,7 @@
<%= stylesheet_link_tag 'calendar', :media => 'all' %>
<%= stylesheet_link_tag 'style', :media => 'all' %>
<%= stylesheet_link_tag 'sonar-colorizer', :media => 'all' %>
+<%= stylesheet_link_tag 'dashboard', :media => 'all' %>
<%= javascript_include_tag 'calendar/yahoo-dom-event.js' %>
<%= javascript_include_tag 'calendar/calendar.js' %>
<%= javascript_include_tag 'application' %>
@@ -25,6 +26,7 @@
<%= javascript_include_tag 'scriptaculous' %>
<%= javascript_include_tag 'tablekit' %>
<%= javascript_include_tag 'prototip' %>
+<%= javascript_include_tag 'dashboard' %>
<% end %>
<!--[if lte IE 6]>
<link href="<%= ApplicationController.root_context -%>/ie6/index" media="all" rel="stylesheet" type="text/css" />
diff --git a/sonar-server/src/main/webapp/WEB-INF/app/views/layouts/_layout.html.erb b/sonar-server/src/main/webapp/WEB-INF/app/views/layouts/_layout.html.erb
index 8a2a24bb8ff..97bcfe6c11d 100644
--- a/sonar-server/src/main/webapp/WEB-INF/app/views/layouts/_layout.html.erb
+++ b/sonar-server/src/main/webapp/WEB-INF/app/views/layouts/_layout.html.erb
@@ -34,7 +34,9 @@
<% end %>
<% elsif (selected_section==Navigation::SECTION_RESOURCE) %>
-
+ <% ActiveDashboard.user_dashboards(current_user).each do |active_dashboard| %>
+ <li class="<%= 'selected' if controller.controller_path=='dashboard' && active_dashboard.dashboard_id==params[:id].to_i -%>"><a href="<%= ApplicationController.root_context -%>/dashboard/index/<%= active_dashboard.dashboard_id -%>?resource=<%= @project.id -%>"><%= active_dashboard.dashboard.name -%></a></li>
+ <% end %>
<li class="<%= 'selected' if request.request_uri.include?('/project/index') || request.request_uri.include?('/drilldown/measures') -%>"><a href="<%= ApplicationController.root_context -%>/project/index/<%= @project.id -%>">Dashboard</a></li>
<li class="<%= 'selected' if request.request_uri.include?('/components/index') -%>"><a href="<%= ApplicationController.root_context -%>/components/index/<%= @project.id -%>">Components</a></li>
<li class="<%= 'selected' if request.request_uri.include?('/drilldown/violations') -%>"><a href="<%= ApplicationController.root_context -%>/drilldown/violations/<%= @project.id -%>">Violations drilldown</a></li>
@@ -59,6 +61,7 @@
<li class="<%= 'selected' if controller.controller_path=='event_categories' -%>"><a href="<%= ApplicationController.root_context -%>/event_categories/index">Event categories</a></li>
<li class="<%= 'selected' if controller.controller_path=='metrics' -%>"><a href="<%= ApplicationController.root_context -%>/metrics/index">Manual metrics</a></li>
<li class="<%= 'selected' if controller.controller_path=='admin_filters' -%>"><a href="<%= ApplicationController.root_context -%>/admin_filters/index">Default filters</a></li>
+ <li class="<%= 'selected' if controller.controller_path=='admin_dashboards' -%>"><a href="<%= ApplicationController.root_context -%>/admin_dashboards/index">Default dashboards</a></li>
<li class="<%= 'selected' if controller.controller_path=='account' -%>"><a href="<%= ApplicationController.root_context -%>/account/index">My profile</a></li>
<% controller.java_facade.getPages(Navigation::SECTION_CONFIGURATION, nil,nil, nil).each do |page| %>
<li class="<%= 'selected' if request.request_uri.include?("plugins/configuration/#{page.getId()}") -%>"><a href="<%= ApplicationController.root_context -%>/plugins/configuration/<%= page.getId() -%>"><%= page.getTitle() %></a></li>
diff --git a/sonar-server/src/main/webapp/WEB-INF/db/migrate/151_create_dashboards.rb b/sonar-server/src/main/webapp/WEB-INF/db/migrate/151_create_dashboards.rb
new file mode 100755
index 00000000000..ae2e92e41eb
--- /dev/null
+++ b/sonar-server/src/main/webapp/WEB-INF/db/migrate/151_create_dashboards.rb
@@ -0,0 +1,89 @@
+#
+# Sonar, entreprise quality control tool.
+# Copyright (C) 2009 SonarSource SA
+# mailto:contact AT sonarsource DOT com
+#
+# Sonar is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 3 of the License, or (at your option) any later version.
+#
+# Sonar is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with Sonar; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+#
+
+class CreateDashboards < ActiveRecord::Migration
+ def self.up
+
+ create_table :active_dashboards do |t|
+ t.column :dashboard_id, :integer, :null => false
+ t.column :user_id, :integer, :null => true
+ t.column :order_index, :integer, :null => true
+ end
+ add_index :active_dashboards, [:user_id], :name => 'active_dashboards_userid'
+ add_index :active_dashboards, [:dashboard_id], :name => 'active_dashboards_dashboardid'
+
+ create_table :dashboards do |t|
+ t.column :user_id, :integer, :null => true
+ t.column :name, :string, :null => true, :limit => 256
+ t.column :description, :string, :null => true, :limit => 1000
+ t.column :column_layout, :string, :null => true, :limit => 10
+ t.column :shared, :boolean, :null => true
+ t.timestamps
+ end
+
+ create_table :widgets do |t|
+ t.column :dashboard_id, :integer, :null => false
+ t.column :widget_key, :string, :null => false, :limit => 256
+ t.column :name, :string, :null => true, :limit => 256
+ t.column :description, :string, :null => true, :limit => 1000
+ t.column :column_index, :integer, :null => true
+ t.column :order_index, :integer, :null => true
+ t.column :state, :string, :null => true, :limit => 1
+ t.timestamps
+ end
+ add_index :widgets, [:dashboard_id], :name => 'widgets_dashboards'
+ add_index :widgets, [:widget_key], :name => 'widgets_widgetkey'
+
+ create_table :widget_properties do |t|
+ t.column :widget_id, :integer, :null => false
+ t.column :description, :string, :null => true, :limit => 4000
+ t.column :kee, :string, :null => true, :limit => 100
+ t.column :text_value, :string, :null => true, :limit => 4000
+ end
+ add_index :widget_properties, [:widget_id], :name => 'widget_properties_widgets'
+
+ add_default_dashboards()
+ end
+
+ private
+
+ def self.create_dashboard
+ dashboard=::Dashboard.new(:name => 'Default', :shared => true, :description => 'Default dashboard', :column_layout => "50-50")
+ dashboard.widgets.build(:widget_key => 'static_analysis', :name => 'Static analysis', :column_index => 1, :order_index => 1, :state => Widget::STATE_ACTIVE)
+ dashboard.widgets.build(:widget_key => 'comments_duplications', :name => 'Comments duplications', :column_index => 1, :order_index => 2, :state => Widget::STATE_ACTIVE)
+ dashboard.widgets.build(:widget_key => 'extended_analysis', :name => 'Extended analysis', :column_index => 1, :order_index => 3, :state => Widget::STATE_ACTIVE)
+ dashboard.widgets.build(:widget_key => 'code_coverage', :name => 'Code coverage', :column_index => 1, :order_index => 4, :state => Widget::STATE_ACTIVE)
+ dashboard.widgets.build(:widget_key => 'events', :name => 'Events', :column_index => 1, :order_index => 5, :state => Widget::STATE_ACTIVE)
+ dashboard.widgets.build(:widget_key => 'description', :name => 'Description', :column_index => 1, :order_index => 6, :state => Widget::STATE_ACTIVE)
+ dashboard.widgets.build(:widget_key => 'rules', :name => 'Rules', :column_index => 2, :order_index => 1, :state => Widget::STATE_ACTIVE)
+ dashboard.widgets.build(:widget_key => 'alerts', :name => 'Alerts', :column_index => 2, :order_index => 2, :state => Widget::STATE_ACTIVE)
+ dashboard.widgets.build(:widget_key => 'file-design', :name => 'File design', :column_index => 2, :order_index => 3, :state => Widget::STATE_ACTIVE)
+ dashboard.widgets.build(:widget_key => 'package-design', :name => 'Package design', :column_index => 2, :order_index => 4, :state => Widget::STATE_ACTIVE)
+ dashboard.widgets.build(:widget_key => 'ckjm', :name => 'CKJM', :column_index => 2, :order_index => 5, :state => Widget::STATE_ACTIVE)
+
+ dashboard.save
+ dashboard
+ end
+
+ def self.add_default_dashboards
+ dashboard=create_dashboard()
+ ActiveDashboard.create(:dashboard => dashboard, :user_id => nil, :order_index => 1)
+ end
+end
diff --git a/sonar-server/src/main/webapp/images/layout100.png b/sonar-server/src/main/webapp/images/layout100.png
new file mode 100644
index 00000000000..133f6c9d130
--- /dev/null
+++ b/sonar-server/src/main/webapp/images/layout100.png
Binary files differ
diff --git a/sonar-server/src/main/webapp/images/layout3070.png b/sonar-server/src/main/webapp/images/layout3070.png
new file mode 100644
index 00000000000..5a226881da3
--- /dev/null
+++ b/sonar-server/src/main/webapp/images/layout3070.png
Binary files differ
diff --git a/sonar-server/src/main/webapp/images/layout333333.png b/sonar-server/src/main/webapp/images/layout333333.png
new file mode 100644
index 00000000000..dfe7e5cb0aa
--- /dev/null
+++ b/sonar-server/src/main/webapp/images/layout333333.png
Binary files differ
diff --git a/sonar-server/src/main/webapp/images/layout5050.png b/sonar-server/src/main/webapp/images/layout5050.png
new file mode 100644
index 00000000000..65b18dc1235
--- /dev/null
+++ b/sonar-server/src/main/webapp/images/layout5050.png
Binary files differ
diff --git a/sonar-server/src/main/webapp/images/layout7030.png b/sonar-server/src/main/webapp/images/layout7030.png
new file mode 100644
index 00000000000..e759a514f23
--- /dev/null
+++ b/sonar-server/src/main/webapp/images/layout7030.png
Binary files differ
diff --git a/sonar-server/src/main/webapp/javascripts/dashboard.js b/sonar-server/src/main/webapp/javascripts/dashboard.js
new file mode 100644
index 00000000000..dcc5b58ce4b
--- /dev/null
+++ b/sonar-server/src/main/webapp/javascripts/dashboard.js
@@ -0,0 +1,100 @@
+var Portal = Class.create();
+Portal.prototype = {
+ initialize: function (options) {
+ this.setOptions(options);
+ if (!this.options.editorEnabled) return;
+
+ Droppables.add(this.options.blocklist, {
+ containment : $A($$("."+this.options.column)),
+ hoverclass : this.options.hoverclass,
+ overlap : 'horizontal',
+ onDrop: function(dragged, dropped) {
+ $(dragged).remove();
+ }
+ });
+
+ this.createAllSortables();
+
+ this.lastSaveString = "";
+
+ this.saveDashboardsState();
+ },
+ /****************************************************/
+
+ createAllSortables: function () {
+ var sortables = $$("."+this.options.column);
+ $A(sortables).each(function (sortable) {
+ Sortable.create(sortable, {
+ containment: $A(sortables),
+ constraint: false,
+ tag: 'div',
+ only: this.options.block,
+ dropOnEmpty: true,
+ hoverclass: this.options.hoverclass,
+ starteffect: function(widget) {
+ $(widget).addClassName("shadow-block");
+ }.bind(this),
+ endeffect: function(widget) {
+ $(widget).removeClassName("shadow-block");
+ }.bind(this),
+ onUpdate: function () {
+ this.saveDashboardsState();
+ }.bind(this)
+ });
+ }.bind(this));
+ },
+
+ highlightWidget: function(widgetId) {
+ new Effect.Highlight($('block_' + widgetId), {duration: this.options.highlight_duration,
+ startcolor: this.options.highlight_startcolor,
+ endcolor: this.options.highlight_endcolor});
+ },
+
+ /****************************************************/
+
+ saveDashboardsState: function () {
+ var result = "";
+ var index = 1;
+ $$("."+this.options.column).each(function (sortable) {
+ if ($(sortable).select("."+this.options.block).length == 0) {
+ $(sortable).select("."+this.options.columnhandle)[0].show();
+ } else {
+ $(sortable).select("."+this.options.columnhandle)[0].hide();
+ }
+ if (index > 1) result += ";";
+ result += Sortable.sequence($(sortable).identify());
+ index++;
+ });
+ if (result==this.lastSaveString) {
+ return;
+ }
+ var firstTime=this.lastSaveString=="";
+ this.lastSaveString=result;
+
+ if (firstTime) return;
+
+ try {
+ if ($(this.options.dashboardstate)) {
+ $(this.options.dashboardstate).value = result;
+ }
+ if (this.options.saveurl) {
+ var url = this.options.saveurl;
+ var postBody = this.options.dashboardstate + '=' +escape(result);
+
+ new Ajax.Request(url,
+ {
+ evalscripts:false,
+ method: 'post',
+ postBody: postBody
+ });
+ }
+ } catch(e) {
+ }
+ },
+
+ setOptions: function (options) {
+ this.options = {}
+ Object.extend(this.options, options || {});
+ }
+};
+
diff --git a/sonar-server/src/main/webapp/javascripts/scriptaculous.js b/sonar-server/src/main/webapp/javascripts/scriptaculous.js
index 6509f888813..b5d327f416c 100644
--- a/sonar-server/src/main/webapp/javascripts/scriptaculous.js
+++ b/sonar-server/src/main/webapp/javascripts/scriptaculous.js
@@ -1,2173 +1,3204 @@
-// script.aculo.us builder.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
-
-// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
-//
-// script.aculo.us is freely distributable under the terms of an MIT-style license.
-// For details, see the script.aculo.us web site: http://script.aculo.us/
-
-var Builder = {
- NODEMAP: {
- AREA: 'map',
- CAPTION: 'table',
- COL: 'table',
- COLGROUP: 'table',
- LEGEND: 'fieldset',
- OPTGROUP: 'select',
- OPTION: 'select',
- PARAM: 'object',
- TBODY: 'table',
- TD: 'table',
- TFOOT: 'table',
- TH: 'table',
- THEAD: 'table',
- TR: 'table'
- },
- // note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken,
- // due to a Firefox bug
- node: function(elementName) {
- elementName = elementName.toUpperCase();
-
- // try innerHTML approach
- var parentTag = this.NODEMAP[elementName] || 'div';
- var parentElement = document.createElement(parentTag);
- try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
- parentElement.innerHTML = "<" + elementName + "></" + elementName + ">";
- } catch(e) {}
- var element = parentElement.firstChild || null;
-
- // see if browser added wrapping tags
- if(element && (element.tagName.toUpperCase() != elementName))
- element = element.getElementsByTagName(elementName)[0];
-
- // fallback to createElement approach
- if(!element) element = document.createElement(elementName);
-
- // abort if nothing could be created
- if(!element) return;
-
- // attributes (or text)
- if(arguments[1])
- if(this._isStringOrNumber(arguments[1]) ||
- (arguments[1] instanceof Array) ||
- arguments[1].tagName) {
- this._children(element, arguments[1]);
- } else {
- var attrs = this._attributes(arguments[1]);
- if(attrs.length) {
- try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
- parentElement.innerHTML = "<" +elementName + " " +
- attrs + "></" + elementName + ">";
- } catch(e) {}
- element = parentElement.firstChild || null;
- // workaround firefox 1.0.X bug
- if(!element) {
- element = document.createElement(elementName);
- for(attr in arguments[1])
- element[attr == 'class' ? 'className' : attr] = arguments[1][attr];
- }
- if(element.tagName.toUpperCase() != elementName)
- element = parentElement.getElementsByTagName(elementName)[0];
- }
- }
-
- // text, or array of children
- if(arguments[2])
- this._children(element, arguments[2]);
-
- return $(element);
- },
- _text: function(text) {
- return document.createTextNode(text);
- },
-
- ATTR_MAP: {
- 'className': 'class',
- 'htmlFor': 'for'
- },
-
- _attributes: function(attributes) {
- var attrs = [];
- for(attribute in attributes)
- attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) +
- '="' + attributes[attribute].toString().escapeHTML().gsub(/"/,'&quot;') + '"');
- return attrs.join(" ");
- },
- _children: function(element, children) {
- if(children.tagName) {
- element.appendChild(children);
- return;
- }
- if(typeof children=='object') { // array can hold nodes and text
- children.flatten().each( function(e) {
- if(typeof e=='object')
- element.appendChild(e);
- else
- if(Builder._isStringOrNumber(e))
- element.appendChild(Builder._text(e));
- });
- } else
- if(Builder._isStringOrNumber(children))
- element.appendChild(Builder._text(children));
- },
- _isStringOrNumber: function(param) {
- return(typeof param=='string' || typeof param=='number');
- },
- build: function(html) {
- var element = this.node('div');
- $(element).update(html.strip());
- return element.down();
- },
- dump: function(scope) {
- if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope
-
- var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " +
- "BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " +
- "FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+
- "KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+
- "PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+
- "TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/);
-
- tags.each( function(tag){
- scope[tag] = function() {
- return Builder.node.apply(Builder, [tag].concat($A(arguments)));
- };
- });
- }
-};
-String.prototype.parseColor = function() {
- var color = '#';
- if (this.slice(0,4) == 'rgb(') {
- var cols = this.slice(4,this.length-1).split(',');
- var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);
- } else {
- if (this.slice(0,1) == '#') {
- if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();
- if (this.length==7) color = this.toLowerCase();
- }
- }
- return (color.length==7 ? color : (arguments[0] || this));
-};
-
-/*--------------------------------------------------------------------------*/
-
-Element.collectTextNodes = function(element) {
- return $A($(element).childNodes).collect( function(node) {
- return (node.nodeType==3 ? node.nodeValue :
- (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
- }).flatten().join('');
-};
-
-Element.collectTextNodesIgnoreClass = function(element, className) {
- return $A($(element).childNodes).collect( function(node) {
- return (node.nodeType==3 ? node.nodeValue :
- ((node.hasChildNodes() && !Element.hasClassName(node,className)) ?
- Element.collectTextNodesIgnoreClass(node, className) : ''));
- }).flatten().join('');
-};
-
-Element.setContentZoom = function(element, percent) {
- element = $(element);
- element.setStyle({fontSize: (percent/100) + 'em'});
- if (Prototype.Browser.WebKit) window.scrollBy(0,0);
- return element;
-};
-
-Element.getInlineOpacity = function(element){
- return $(element).style.opacity || '';
-};
-
-Element.forceRerendering = function(element) {
- try {
- element = $(element);
- var n = document.createTextNode(' ');
- element.appendChild(n);
- element.removeChild(n);
- } catch(e) { }
-};
-
-/*--------------------------------------------------------------------------*/
-
-var Effect = {
- _elementDoesNotExistError: {
- name: 'ElementDoesNotExistError',
- message: 'The specified DOM element does not exist, but is required for this effect to operate'
- },
- Transitions: {
- linear: Prototype.K,
- sinoidal: function(pos) {
- return (-Math.cos(pos*Math.PI)/2) + .5;
- },
- reverse: function(pos) {
- return 1-pos;
- },
- flicker: function(pos) {
- var pos = ((-Math.cos(pos*Math.PI)/4) + .75) + Math.random()/4;
- return pos > 1 ? 1 : pos;
- },
- wobble: function(pos) {
- return (-Math.cos(pos*Math.PI*(9*pos))/2) + .5;
- },
- pulse: function(pos, pulses) {
- return (-Math.cos((pos*((pulses||5)-.5)*2)*Math.PI)/2) + .5;
- },
- spring: function(pos) {
- return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6));
- },
- none: function(pos) {
- return 0;
- },
- full: function(pos) {
- return 1;
- }
- },
- DefaultOptions: {
- duration: 1.0, // seconds
- fps: 100, // 100= assume 66fps max.
- sync: false, // true for combining
- from: 0.0,
- to: 1.0,
- delay: 0.0,
- queue: 'parallel'
- },
- tagifyText: function(element) {
- var tagifyStyle = 'position:relative';
- if (Prototype.Browser.IE) tagifyStyle += ';zoom:1';
-
- element = $(element);
- $A(element.childNodes).each( function(child) {
- if (child.nodeType==3) {
- child.nodeValue.toArray().each( function(character) {
- element.insertBefore(
- new Element('span', {style: tagifyStyle}).update(
- character == ' ' ? String.fromCharCode(160) : character),
- child);
- });
- Element.remove(child);
- }
- });
- },
- multiple: function(element, effect) {
- var elements;
- if (((typeof element == 'object') ||
- Object.isFunction(element)) &&
- (element.length))
- elements = element;
- else
- elements = $(element).childNodes;
-
- var options = Object.extend({
- speed: 0.1,
- delay: 0.0
- }, arguments[2] || { });
- var masterDelay = options.delay;
-
- $A(elements).each( function(element, index) {
- new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
- });
- },
- PAIRS: {
- 'slide': ['SlideDown','SlideUp'],
- 'blind': ['BlindDown','BlindUp'],
- 'appear': ['Appear','Fade']
- },
- toggle: function(element, effect, options) {
- element = $(element);
- effect = (effect || 'appear').toLowerCase();
-
- return Effect[ Effect.PAIRS[ effect ][ element.visible() ? 1 : 0 ] ](element, Object.extend({
- queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
- }, options || {}));
- }
-};
-
-Effect.DefaultOptions.transition = Effect.Transitions.sinoidal;
-
-/* ------------- core effects ------------- */
-
-Effect.ScopedQueue = Class.create(Enumerable, {
- initialize: function() {
- this.effects = [];
- this.interval = null;
- },
- _each: function(iterator) {
- this.effects._each(iterator);
- },
- add: function(effect) {
- var timestamp = new Date().getTime();
-
- var position = Object.isString(effect.options.queue) ?
- effect.options.queue : effect.options.queue.position;
-
- switch(position) {
- case 'front':
- // move unstarted effects after this effect
- this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
- e.startOn += effect.finishOn;
- e.finishOn += effect.finishOn;
- });
- break;
- case 'with-last':
- timestamp = this.effects.pluck('startOn').max() || timestamp;
- break;
- case 'end':
- // start effect after last queued effect has finished
- timestamp = this.effects.pluck('finishOn').max() || timestamp;
- break;
- }
-
- effect.startOn += timestamp;
- effect.finishOn += timestamp;
-
- if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
- this.effects.push(effect);
-
- if (!this.interval)
- this.interval = setInterval(this.loop.bind(this), 15);
- },
- remove: function(effect) {
- this.effects = this.effects.reject(function(e) { return e==effect });
- if (this.effects.length == 0) {
- clearInterval(this.interval);
- this.interval = null;
- }
- },
- loop: function() {
- var timePos = new Date().getTime();
- for(var i=0, len=this.effects.length;i<len;i++)
- this.effects[i] && this.effects[i].loop(timePos);
- }
-});
-
-Effect.Queues = {
- instances: $H(),
- get: function(queueName) {
- if (!Object.isString(queueName)) return queueName;
-
- return this.instances.get(queueName) ||
- this.instances.set(queueName, new Effect.ScopedQueue());
- }
-};
-Effect.Queue = Effect.Queues.get('global');
-
-Effect.Base = Class.create({
- position: null,
- start: function(options) {
- if (options && options.transition === false) options.transition = Effect.Transitions.linear;
- this.options = Object.extend(Object.extend({ },Effect.DefaultOptions), options || { });
- this.currentFrame = 0;
- this.state = 'idle';
- this.startOn = this.options.delay*1000;
- this.finishOn = this.startOn+(this.options.duration*1000);
- this.fromToDelta = this.options.to-this.options.from;
- this.totalTime = this.finishOn-this.startOn;
- this.totalFrames = this.options.fps*this.options.duration;
-
- this.render = (function() {
- function dispatch(effect, eventName) {
- if (effect.options[eventName + 'Internal'])
- effect.options[eventName + 'Internal'](effect);
- if (effect.options[eventName])
- effect.options[eventName](effect);
- }
-
- return function(pos) {
- if (this.state === "idle") {
- this.state = "running";
- dispatch(this, 'beforeSetup');
- if (this.setup) this.setup();
- dispatch(this, 'afterSetup');
- }
- if (this.state === "running") {
- pos = (this.options.transition(pos) * this.fromToDelta) + this.options.from;
- this.position = pos;
- dispatch(this, 'beforeUpdate');
- if (this.update) this.update(pos);
- dispatch(this, 'afterUpdate');
- }
- };
- })();
-
- this.event('beforeStart');
- if (!this.options.sync)
- Effect.Queues.get(Object.isString(this.options.queue) ?
- 'global' : this.options.queue.scope).add(this);
- },
- loop: function(timePos) {
- if (timePos >= this.startOn) {
- if (timePos >= this.finishOn) {
- this.render(1.0);
- this.cancel();
- this.event('beforeFinish');
- if (this.finish) this.finish();
- this.event('afterFinish');
- return;
- }
- var pos = (timePos - this.startOn) / this.totalTime,
- frame = (pos * this.totalFrames).round();
- if (frame > this.currentFrame) {
- this.render(pos);
- this.currentFrame = frame;
- }
- }
- },
- cancel: function() {
- if (!this.options.sync)
- Effect.Queues.get(Object.isString(this.options.queue) ?
- 'global' : this.options.queue.scope).remove(this);
- this.state = 'finished';
- },
- event: function(eventName) {
- if (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
- if (this.options[eventName]) this.options[eventName](this);
- },
- inspect: function() {
- var data = $H();
- for(property in this)
- if (!Object.isFunction(this[property])) data.set(property, this[property]);
- return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
- }
-});
-
-Effect.Parallel = Class.create(Effect.Base, {
- initialize: function(effects) {
- this.effects = effects || [];
- this.start(arguments[1]);
- },
- update: function(position) {
- this.effects.invoke('render', position);
- },
- finish: function(position) {
- this.effects.each( function(effect) {
- effect.render(1.0);
- effect.cancel();
- effect.event('beforeFinish');
- if (effect.finish) effect.finish(position);
- effect.event('afterFinish');
- });
- }
-});
-
-Effect.Tween = Class.create(Effect.Base, {
- initialize: function(object, from, to) {
- object = Object.isString(object) ? $(object) : object;
- var args = $A(arguments), method = args.last(),
- options = args.length == 5 ? args[3] : null;
- this.method = Object.isFunction(method) ? method.bind(object) :
- Object.isFunction(object[method]) ? object[method].bind(object) :
- function(value) { object[method] = value };
- this.start(Object.extend({ from: from, to: to }, options || { }));
- },
- update: function(position) {
- this.method(position);
- }
-});
-
-Effect.Event = Class.create(Effect.Base, {
- initialize: function() {
- this.start(Object.extend({ duration: 0 }, arguments[0] || { }));
- },
- update: Prototype.emptyFunction
-});
-
-Effect.Opacity = Class.create(Effect.Base, {
- initialize: function(element) {
- this.element = $(element);
- if (!this.element) throw(Effect._elementDoesNotExistError);
- // make this work on IE on elements without 'layout'
- if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
- this.element.setStyle({zoom: 1});
- var options = Object.extend({
- from: this.element.getOpacity() || 0.0,
- to: 1.0
- }, arguments[1] || { });
- this.start(options);
- },
- update: function(position) {
- this.element.setOpacity(position);
- }
-});
-
-Effect.Move = Class.create(Effect.Base, {
- initialize: function(element) {
- this.element = $(element);
- if (!this.element) throw(Effect._elementDoesNotExistError);
- var options = Object.extend({
- x: 0,
- y: 0,
- mode: 'relative'
- }, arguments[1] || { });
- this.start(options);
- },
- setup: function() {
- this.element.makePositioned();
- this.originalLeft = parseFloat(this.element.getStyle('left') || '0');
- this.originalTop = parseFloat(this.element.getStyle('top') || '0');
- if (this.options.mode == 'absolute') {
- this.options.x = this.options.x - this.originalLeft;
- this.options.y = this.options.y - this.originalTop;
- }
- },
- update: function(position) {
- this.element.setStyle({
- left: (this.options.x * position + this.originalLeft).round() + 'px',
- top: (this.options.y * position + this.originalTop).round() + 'px'
- });
- }
-});
-
-// for backwards compatibility
-Effect.MoveBy = function(element, toTop, toLeft) {
- return new Effect.Move(element,
- Object.extend({ x: toLeft, y: toTop }, arguments[3] || { }));
-};
-
-Effect.Scale = Class.create(Effect.Base, {
- initialize: function(element, percent) {
- this.element = $(element);
- if (!this.element) throw(Effect._elementDoesNotExistError);
- var options = Object.extend({
- scaleX: true,
- scaleY: true,
- scaleContent: true,
- scaleFromCenter: false,
- scaleMode: 'box', // 'box' or 'contents' or { } with provided values
- scaleFrom: 100.0,
- scaleTo: percent
- }, arguments[2] || { });
- this.start(options);
- },
- setup: function() {
- this.restoreAfterFinish = this.options.restoreAfterFinish || false;
- this.elementPositioning = this.element.getStyle('position');
-
- this.originalStyle = { };
- ['top','left','width','height','fontSize'].each( function(k) {
- this.originalStyle[k] = this.element.style[k];
- }.bind(this));
-
- this.originalTop = this.element.offsetTop;
- this.originalLeft = this.element.offsetLeft;
-
- var fontSize = this.element.getStyle('font-size') || '100%';
- ['em','px','%','pt'].each( function(fontSizeType) {
- if (fontSize.indexOf(fontSizeType)>0) {
- this.fontSize = parseFloat(fontSize);
- this.fontSizeType = fontSizeType;
- }
- }.bind(this));
-
- this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
-
- this.dims = null;
- if (this.options.scaleMode=='box')
- this.dims = [this.element.offsetHeight, this.element.offsetWidth];
- if (/^content/.test(this.options.scaleMode))
- this.dims = [this.element.scrollHeight, this.element.scrollWidth];
- if (!this.dims)
- this.dims = [this.options.scaleMode.originalHeight,
- this.options.scaleMode.originalWidth];
- },
- update: function(position) {
- var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
- if (this.options.scaleContent && this.fontSize)
- this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
- this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
- },
- finish: function(position) {
- if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
- },
- setDimensions: function(height, width) {
- var d = { };
- if (this.options.scaleX) d.width = width.round() + 'px';
- if (this.options.scaleY) d.height = height.round() + 'px';
- if (this.options.scaleFromCenter) {
- var topd = (height - this.dims[0])/2;
- var leftd = (width - this.dims[1])/2;
- if (this.elementPositioning == 'absolute') {
- if (this.options.scaleY) d.top = this.originalTop-topd + 'px';
- if (this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
- } else {
- if (this.options.scaleY) d.top = -topd + 'px';
- if (this.options.scaleX) d.left = -leftd + 'px';
- }
- }
- this.element.setStyle(d);
- }
-});
-
-Effect.Highlight = Class.create(Effect.Base, {
- initialize: function(element) {
- this.element = $(element);
- if (!this.element) throw(Effect._elementDoesNotExistError);
- var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { });
- this.start(options);
- },
- setup: function() {
- // Prevent executing on elements not in the layout flow
- if (this.element.getStyle('display')=='none') { this.cancel(); return; }
- // Disable background image during the effect
- this.oldStyle = { };
- if (!this.options.keepBackgroundImage) {
- this.oldStyle.backgroundImage = this.element.getStyle('background-image');
- this.element.setStyle({backgroundImage: 'none'});
- }
- if (!this.options.endcolor)
- this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
- if (!this.options.restorecolor)
- this.options.restorecolor = this.element.getStyle('background-color');
- // init color calculations
- this._base = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
- this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
- },
- update: function(position) {
- this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
- return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) });
- },
- finish: function() {
- this.element.setStyle(Object.extend(this.oldStyle, {
- backgroundColor: this.options.restorecolor
- }));
- }
-});
-
-Effect.ScrollTo = function(element) {
- var options = arguments[1] || { },
- scrollOffsets = document.viewport.getScrollOffsets(),
- elementOffsets = $(element).cumulativeOffset();
-
- if (options.offset) elementOffsets[1] += options.offset;
-
- return new Effect.Tween(null,
- scrollOffsets.top,
- elementOffsets[1],
- options,
- function(p){ scrollTo(scrollOffsets.left, p.round()); }
- );
-};
-
-/* ------------- combination effects ------------- */
-
-Effect.Fade = function(element) {
- element = $(element);
- var oldOpacity = element.getInlineOpacity();
- var options = Object.extend({
- from: element.getOpacity() || 1.0,
- to: 0.0,
- afterFinishInternal: function(effect) {
- if (effect.options.to!=0) return;
- effect.element.hide().setStyle({opacity: oldOpacity});
- }
- }, arguments[1] || { });
- return new Effect.Opacity(element,options);
-};
-
-Effect.Appear = function(element) {
- element = $(element);
- var options = Object.extend({
- from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
- to: 1.0,
- // force Safari to render floated elements properly
- afterFinishInternal: function(effect) {
- effect.element.forceRerendering();
- },
- beforeSetup: function(effect) {
- effect.element.setOpacity(effect.options.from).show();
- }}, arguments[1] || { });
- return new Effect.Opacity(element,options);
-};
-
-Effect.Puff = function(element) {
- element = $(element);
- var oldStyle = {
- opacity: element.getInlineOpacity(),
- position: element.getStyle('position'),
- top: element.style.top,
- left: element.style.left,
- width: element.style.width,
- height: element.style.height
- };
- return new Effect.Parallel(
- [ new Effect.Scale(element, 200,
- { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }),
- new Effect.Opacity(element, { sync: true, to: 0.0 } ) ],
- Object.extend({ duration: 1.0,
- beforeSetupInternal: function(effect) {
- Position.absolutize(effect.effects[0].element);
- },
- afterFinishInternal: function(effect) {
- effect.effects[0].element.hide().setStyle(oldStyle); }
- }, arguments[1] || { })
- );
-};
-
-Effect.BlindUp = function(element) {
- element = $(element);
- element.makeClipping();
- return new Effect.Scale(element, 0,
- Object.extend({ scaleContent: false,
- scaleX: false,
- restoreAfterFinish: true,
- afterFinishInternal: function(effect) {
- effect.element.hide().undoClipping();
- }
- }, arguments[1] || { })
- );
-};
-
-Effect.BlindDown = function(element) {
- element = $(element);
- var elementDimensions = element.getDimensions();
- return new Effect.Scale(element, 100, Object.extend({
- scaleContent: false,
- scaleX: false,
- scaleFrom: 0,
- scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
- restoreAfterFinish: true,
- afterSetup: function(effect) {
- effect.element.makeClipping().setStyle({height: '0px'}).show();
- },
- afterFinishInternal: function(effect) {
- effect.element.undoClipping();
- }
- }, arguments[1] || { }));
-};
-
-Effect.SwitchOff = function(element) {
- element = $(element);
- var oldOpacity = element.getInlineOpacity();
- return new Effect.Appear(element, Object.extend({
- duration: 0.4,
- from: 0,
- transition: Effect.Transitions.flicker,
- afterFinishInternal: function(effect) {
- new Effect.Scale(effect.element, 1, {
- duration: 0.3, scaleFromCenter: true,
- scaleX: false, scaleContent: false, restoreAfterFinish: true,
- beforeSetup: function(effect) {
- effect.element.makePositioned().makeClipping();
- },
- afterFinishInternal: function(effect) {
- effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
- }
- });
- }
- }, arguments[1] || { }));
-};
-
-Effect.DropOut = function(element) {
- element = $(element);
- var oldStyle = {
- top: element.getStyle('top'),
- left: element.getStyle('left'),
- opacity: element.getInlineOpacity() };
- return new Effect.Parallel(
- [ new Effect.Move(element, {x: 0, y: 100, sync: true }),
- new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
- Object.extend(
- { duration: 0.5,
- beforeSetup: function(effect) {
- effect.effects[0].element.makePositioned();
- },
- afterFinishInternal: function(effect) {
- effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
- }
- }, arguments[1] || { }));
-};
-
-Effect.Shake = function(element) {
- element = $(element);
- var options = Object.extend({
- distance: 20,
- duration: 0.5
- }, arguments[1] || {});
- var distance = parseFloat(options.distance);
- var split = parseFloat(options.duration) / 10.0;
- var oldStyle = {
- top: element.getStyle('top'),
- left: element.getStyle('left') };
- return new Effect.Move(element,
- { x: distance, y: 0, duration: split, afterFinishInternal: function(effect) {
- new Effect.Move(effect.element,
- { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
- new Effect.Move(effect.element,
- { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
- new Effect.Move(effect.element,
- { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
- new Effect.Move(effect.element,
- { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
- new Effect.Move(effect.element,
- { x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) {
- effect.element.undoPositioned().setStyle(oldStyle);
- }}); }}); }}); }}); }}); }});
-};
-
-Effect.SlideDown = function(element) {
- element = $(element).cleanWhitespace();
- // SlideDown need to have the content of the element wrapped in a container element with fixed height!
- var oldInnerBottom = element.down().getStyle('bottom');
- var elementDimensions = element.getDimensions();
- return new Effect.Scale(element, 100, Object.extend({
- scaleContent: false,
- scaleX: false,
- scaleFrom: window.opera ? 0 : 1,
- scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
- restoreAfterFinish: true,
- afterSetup: function(effect) {
- effect.element.makePositioned();
- effect.element.down().makePositioned();
- if (window.opera) effect.element.setStyle({top: ''});
- effect.element.makeClipping().setStyle({height: '0px'}).show();
- },
- afterUpdateInternal: function(effect) {
- effect.element.down().setStyle({bottom:
- (effect.dims[0] - effect.element.clientHeight) + 'px' });
- },
- afterFinishInternal: function(effect) {
- effect.element.undoClipping().undoPositioned();
- effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
- }, arguments[1] || { })
- );
-};
-
-Effect.SlideUp = function(element) {
- element = $(element).cleanWhitespace();
- var oldInnerBottom = element.down().getStyle('bottom');
- var elementDimensions = element.getDimensions();
- return new Effect.Scale(element, window.opera ? 0 : 1,
- Object.extend({ scaleContent: false,
- scaleX: false,
- scaleMode: 'box',
- scaleFrom: 100,
- scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
- restoreAfterFinish: true,
- afterSetup: function(effect) {
- effect.element.makePositioned();
- effect.element.down().makePositioned();
- if (window.opera) effect.element.setStyle({top: ''});
- effect.element.makeClipping().show();
- },
- afterUpdateInternal: function(effect) {
- effect.element.down().setStyle({bottom:
- (effect.dims[0] - effect.element.clientHeight) + 'px' });
- },
- afterFinishInternal: function(effect) {
- effect.element.hide().undoClipping().undoPositioned();
- effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom});
- }
- }, arguments[1] || { })
- );
-};
-
-// Bug in opera makes the TD containing this element expand for a instance after finish
-Effect.Squish = function(element) {
- return new Effect.Scale(element, window.opera ? 1 : 0, {
- restoreAfterFinish: true,
- beforeSetup: function(effect) {
- effect.element.makeClipping();
- },
- afterFinishInternal: function(effect) {
- effect.element.hide().undoClipping();
- }
- });
-};
-
-Effect.Grow = function(element) {
- element = $(element);
- var options = Object.extend({
- direction: 'center',
- moveTransition: Effect.Transitions.sinoidal,
- scaleTransition: Effect.Transitions.sinoidal,
- opacityTransition: Effect.Transitions.full
- }, arguments[1] || { });
- var oldStyle = {
- top: element.style.top,
- left: element.style.left,
- height: element.style.height,
- width: element.style.width,
- opacity: element.getInlineOpacity() };
-
- var dims = element.getDimensions();
- var initialMoveX, initialMoveY;
- var moveX, moveY;
-
- switch (options.direction) {
- case 'top-left':
- initialMoveX = initialMoveY = moveX = moveY = 0;
- break;
- case 'top-right':
- initialMoveX = dims.width;
- initialMoveY = moveY = 0;
- moveX = -dims.width;
- break;
- case 'bottom-left':
- initialMoveX = moveX = 0;
- initialMoveY = dims.height;
- moveY = -dims.height;
- break;
- case 'bottom-right':
- initialMoveX = dims.width;
- initialMoveY = dims.height;
- moveX = -dims.width;
- moveY = -dims.height;
- break;
- case 'center':
- initialMoveX = dims.width / 2;
- initialMoveY = dims.height / 2;
- moveX = -dims.width / 2;
- moveY = -dims.height / 2;
- break;
- }
-
- return new Effect.Move(element, {
- x: initialMoveX,
- y: initialMoveY,
- duration: 0.01,
- beforeSetup: function(effect) {
- effect.element.hide().makeClipping().makePositioned();
- },
- afterFinishInternal: function(effect) {
- new Effect.Parallel(
- [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
- new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
- new Effect.Scale(effect.element, 100, {
- scaleMode: { originalHeight: dims.height, originalWidth: dims.width },
- sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
- ], Object.extend({
- beforeSetup: function(effect) {
- effect.effects[0].element.setStyle({height: '0px'}).show();
- },
- afterFinishInternal: function(effect) {
- effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);
- }
- }, options)
- );
- }
- });
-};
-
-Effect.Shrink = function(element) {
- element = $(element);
- var options = Object.extend({
- direction: 'center',
- moveTransition: Effect.Transitions.sinoidal,
- scaleTransition: Effect.Transitions.sinoidal,
- opacityTransition: Effect.Transitions.none
- }, arguments[1] || { });
- var oldStyle = {
- top: element.style.top,
- left: element.style.left,
- height: element.style.height,
- width: element.style.width,
- opacity: element.getInlineOpacity() };
-
- var dims = element.getDimensions();
- var moveX, moveY;
-
- switch (options.direction) {
- case 'top-left':
- moveX = moveY = 0;
- break;
- case 'top-right':
- moveX = dims.width;
- moveY = 0;
- break;
- case 'bottom-left':
- moveX = 0;
- moveY = dims.height;
- break;
- case 'bottom-right':
- moveX = dims.width;
- moveY = dims.height;
- break;
- case 'center':
- moveX = dims.width / 2;
- moveY = dims.height / 2;
- break;
- }
-
- return new Effect.Parallel(
- [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
- new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
- new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
- ], Object.extend({
- beforeStartInternal: function(effect) {
- effect.effects[0].element.makePositioned().makeClipping();
- },
- afterFinishInternal: function(effect) {
- effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
- }, options)
- );
-};
-
-Effect.Pulsate = function(element) {
- element = $(element);
- var options = arguments[1] || { },
- oldOpacity = element.getInlineOpacity(),
- transition = options.transition || Effect.Transitions.linear,
- reverser = function(pos){
- return 1 - transition((-Math.cos((pos*(options.pulses||5)*2)*Math.PI)/2) + .5);
- };
-
- return new Effect.Opacity(element,
- Object.extend(Object.extend({ duration: 2.0, from: 0,
- afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
- }, options), {transition: reverser}));
-};
-
-Effect.Fold = function(element) {
- element = $(element);
- var oldStyle = {
- top: element.style.top,
- left: element.style.left,
- width: element.style.width,
- height: element.style.height };
- element.makeClipping();
- return new Effect.Scale(element, 5, Object.extend({
- scaleContent: false,
- scaleX: false,
- afterFinishInternal: function(effect) {
- new Effect.Scale(element, 1, {
- scaleContent: false,
- scaleY: false,
- afterFinishInternal: function(effect) {
- effect.element.hide().undoClipping().setStyle(oldStyle);
- } });
- }}, arguments[1] || { }));
-};
-
-Effect.Morph = Class.create(Effect.Base, {
- initialize: function(element) {
- this.element = $(element);
- if (!this.element) throw(Effect._elementDoesNotExistError);
- var options = Object.extend({
- style: { }
- }, arguments[1] || { });
-
- if (!Object.isString(options.style)) this.style = $H(options.style);
- else {
- if (options.style.include(':'))
- this.style = options.style.parseStyle();
- else {
- this.element.addClassName(options.style);
- this.style = $H(this.element.getStyles());
- this.element.removeClassName(options.style);
- var css = this.element.getStyles();
- this.style = this.style.reject(function(style) {
- return style.value == css[style.key];
- });
- options.afterFinishInternal = function(effect) {
- effect.element.addClassName(effect.options.style);
- effect.transforms.each(function(transform) {
- effect.element.style[transform.style] = '';
- });
- };
- }
- }
- this.start(options);
- },
-
- setup: function(){
- function parseColor(color){
- if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
- color = color.parseColor();
- return $R(0,2).map(function(i){
- return parseInt( color.slice(i*2+1,i*2+3), 16 );
- });
- }
- this.transforms = this.style.map(function(pair){
- var property = pair[0], value = pair[1], unit = null;
-
- if (value.parseColor('#zzzzzz') != '#zzzzzz') {
- value = value.parseColor();
- unit = 'color';
- } else if (property == 'opacity') {
- value = parseFloat(value);
- if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
- this.element.setStyle({zoom: 1});
- } else if (Element.CSS_LENGTH.test(value)) {
- var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/);
- value = parseFloat(components[1]);
- unit = (components.length == 3) ? components[2] : null;
- }
-
- var originalValue = this.element.getStyle(property);
- return {
- style: property.camelize(),
- originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0),
- targetValue: unit=='color' ? parseColor(value) : value,
- unit: unit
- };
- }.bind(this)).reject(function(transform){
- return (
- (transform.originalValue == transform.targetValue) ||
- (
- transform.unit != 'color' &&
- (isNaN(transform.originalValue) || isNaN(transform.targetValue))
- )
- );
- });
- },
- update: function(position) {
- var style = { }, transform, i = this.transforms.length;
- while(i--)
- style[(transform = this.transforms[i]).style] =
- transform.unit=='color' ? '#'+
- (Math.round(transform.originalValue[0]+
- (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() +
- (Math.round(transform.originalValue[1]+
- (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() +
- (Math.round(transform.originalValue[2]+
- (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() :
- (transform.originalValue +
- (transform.targetValue - transform.originalValue) * position).toFixed(3) +
- (transform.unit === null ? '' : transform.unit);
- this.element.setStyle(style, true);
- }
-});
-
-Effect.Transform = Class.create({
- initialize: function(tracks){
- this.tracks = [];
- this.options = arguments[1] || { };
- this.addTracks(tracks);
- },
- addTracks: function(tracks){
- tracks.each(function(track){
- track = $H(track);
- var data = track.values().first();
- this.tracks.push($H({
- ids: track.keys().first(),
- effect: Effect.Morph,
- options: { style: data }
- }));
- }.bind(this));
- return this;
- },
- play: function(){
- return new Effect.Parallel(
- this.tracks.map(function(track){
- var ids = track.get('ids'), effect = track.get('effect'), options = track.get('options');
- var elements = [$(ids) || $$(ids)].flatten();
- return elements.map(function(e){ return new effect(e, Object.extend({ sync:true }, options)) });
- }).flatten(),
- this.options
- );
- }
-});
-
-Element.CSS_PROPERTIES = $w(
- 'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' +
- 'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
- 'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
- 'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
- 'fontSize fontWeight height left letterSpacing lineHeight ' +
- 'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
- 'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
- 'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
- 'right textIndent top width wordSpacing zIndex');
-
-Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;
-
-String.__parseStyleElement = document.createElement('div');
-String.prototype.parseStyle = function(){
- var style, styleRules = $H();
- if (Prototype.Browser.WebKit)
- style = new Element('div',{style:this}).style;
- else {
- String.__parseStyleElement.innerHTML = '<div style="' + this + '"></div>';
- style = String.__parseStyleElement.childNodes[0].style;
- }
-
- Element.CSS_PROPERTIES.each(function(property){
- if (style[property]) styleRules.set(property, style[property]);
- });
-
- if (Prototype.Browser.IE && this.include('opacity'))
- styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);
-
- return styleRules;
-};
-
-if (document.defaultView && document.defaultView.getComputedStyle) {
- Element.getStyles = function(element) {
- var css = document.defaultView.getComputedStyle($(element), null);
- return Element.CSS_PROPERTIES.inject({ }, function(styles, property) {
- styles[property] = css[property];
- return styles;
- });
- };
-} else {
- Element.getStyles = function(element) {
- element = $(element);
- var css = element.currentStyle, styles;
- styles = Element.CSS_PROPERTIES.inject({ }, function(results, property) {
- results[property] = css[property];
- return results;
- });
- if (!styles.opacity) styles.opacity = element.getOpacity();
- return styles;
- };
-}
-
-Effect.Methods = {
- morph: function(element, style) {
- element = $(element);
- new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { }));
- return element;
- },
- visualEffect: function(element, effect, options) {
- element = $(element);
- var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1);
- new Effect[klass](element, options);
- return element;
- },
- highlight: function(element, options) {
- element = $(element);
- new Effect.Highlight(element, options);
- return element;
- }
-};
-
-$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+
- 'pulsate shake puff squish switchOff dropOut').each(
- function(effect) {
- Effect.Methods[effect] = function(element, options){
- element = $(element);
- Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options);
- return element;
- };
- }
-);
-
-$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each(
- function(f) { Effect.Methods[f] = Element[f]; }
-);
-
-Element.addMethods(Effect.Methods);
-if(typeof Effect == 'undefined')
- throw("controls.js requires including script.aculo.us' effects.js library");
-
-var Autocompleter = { };
-Autocompleter.Base = Class.create({
- baseInitialize: function(element, update, options) {
- element = $(element);
- this.element = element;
- this.update = $(update);
- this.hasFocus = false;
- this.changed = false;
- this.active = false;
- this.index = 0;
- this.entryCount = 0;
- this.oldElementValue = this.element.value;
-
- if(this.setOptions)
- this.setOptions(options);
- else
- this.options = options || { };
-
- this.options.paramName = this.options.paramName || this.element.name;
- this.options.tokens = this.options.tokens || [];
- this.options.frequency = this.options.frequency || 0.4;
- this.options.minChars = this.options.minChars || 1;
- this.options.onShow = this.options.onShow ||
- function(element, update){
- if(!update.style.position || update.style.position=='absolute') {
- update.style.position = 'absolute';
- Position.clone(element, update, {
- setHeight: false,
- offsetTop: element.offsetHeight
- });
- }
- Effect.Appear(update,{duration:0.15});
- };
- this.options.onHide = this.options.onHide ||
- function(element, update){ new Effect.Fade(update,{duration:0.15}) };
-
- if(typeof(this.options.tokens) == 'string')
- this.options.tokens = new Array(this.options.tokens);
- // Force carriage returns as token delimiters anyway
- if (!this.options.tokens.include('\n'))
- this.options.tokens.push('\n');
-
- this.observer = null;
-
- this.element.setAttribute('autocomplete','off');
-
- Element.hide(this.update);
-
- Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
- Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
- },
-
- show: function() {
- if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
- if(!this.iefix &&
- (Prototype.Browser.IE) &&
- (Element.getStyle(this.update, 'position')=='absolute')) {
- new Insertion.After(this.update,
- '<iframe id="' + this.update.id + '_iefix" '+
- 'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
- 'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
- this.iefix = $(this.update.id+'_iefix');
- }
- if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
- },
-
- fixIEOverlapping: function() {
- Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
- this.iefix.style.zIndex = 1;
- this.update.style.zIndex = 2;
- Element.show(this.iefix);
- },
-
- hide: function() {
- this.stopIndicator();
- if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
- if(this.iefix) Element.hide(this.iefix);
- },
-
- startIndicator: function() {
- if(this.options.indicator) Element.show(this.options.indicator);
- },
-
- stopIndicator: function() {
- if(this.options.indicator) Element.hide(this.options.indicator);
- },
-
- onKeyPress: function(event) {
- if(this.active)
- switch(event.keyCode) {
- case Event.KEY_TAB:
- case Event.KEY_RETURN:
- this.selectEntry();
- Event.stop(event);
- case Event.KEY_ESC:
- this.hide();
- this.active = false;
- Event.stop(event);
- return;
- case Event.KEY_LEFT:
- case Event.KEY_RIGHT:
- return;
- case Event.KEY_UP:
- this.markPrevious();
- this.render();
- Event.stop(event);
- return;
- case Event.KEY_DOWN:
- this.markNext();
- this.render();
- Event.stop(event);
- return;
- }
- else
- if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
- (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
-
- this.changed = true;
- this.hasFocus = true;
-
- if(this.observer) clearTimeout(this.observer);
- this.observer =
- setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
- },
-
- activate: function() {
- this.changed = false;
- this.hasFocus = true;
- this.getUpdatedChoices();
- },
-
- onHover: function(event) {
- var element = Event.findElement(event, 'LI');
- if(this.index != element.autocompleteIndex)
- {
- this.index = element.autocompleteIndex;
- this.render();
- }
- Event.stop(event);
- },
-
- onClick: function(event) {
- var element = Event.findElement(event, 'LI');
- this.index = element.autocompleteIndex;
- this.selectEntry();
- this.hide();
- },
-
- onBlur: function(event) {
- // needed to make click events working
- setTimeout(this.hide.bind(this), 250);
- this.hasFocus = false;
- this.active = false;
- },
-
- render: function() {
- if(this.entryCount > 0) {
- for (var i = 0; i < this.entryCount; i++)
- this.index==i ?
- Element.addClassName(this.getEntry(i),"selected") :
- Element.removeClassName(this.getEntry(i),"selected");
- if(this.hasFocus) {
- this.show();
- this.active = true;
- }
- } else {
- this.active = false;
- this.hide();
- }
- },
-
- markPrevious: function() {
- if(this.index > 0) this.index--;
- else this.index = this.entryCount-1;
- this.getEntry(this.index).scrollIntoView(true);
- },
-
- markNext: function() {
- if(this.index < this.entryCount-1) this.index++;
- else this.index = 0;
- this.getEntry(this.index).scrollIntoView(false);
- },
-
- getEntry: function(index) {
- return this.update.firstChild.childNodes[index];
- },
-
- getCurrentEntry: function() {
- return this.getEntry(this.index);
- },
-
- selectEntry: function() {
- this.active = false;
- this.updateElement(this.getCurrentEntry());
- },
-
- updateElement: function(selectedElement) {
- if (this.options.updateElement) {
- this.options.updateElement(selectedElement);
- return;
- }
- var value = '';
- if (this.options.select) {
- var nodes = $(selectedElement).select('.' + this.options.select) || [];
- if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
- } else
- value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
-
- var bounds = this.getTokenBounds();
- if (bounds[0] != -1) {
- var newValue = this.element.value.substr(0, bounds[0]);
- var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
- if (whitespace)
- newValue += whitespace[0];
- this.element.value = newValue + value + this.element.value.substr(bounds[1]);
- } else {
- this.element.value = value;
- }
- this.oldElementValue = this.element.value;
- this.element.focus();
-
- if (this.options.afterUpdateElement)
- this.options.afterUpdateElement(this.element, selectedElement);
- },
-
- updateChoices: function(choices) {
- if(!this.changed && this.hasFocus) {
- this.update.innerHTML = choices;
- Element.cleanWhitespace(this.update);
- Element.cleanWhitespace(this.update.down());
-
- if(this.update.firstChild && this.update.down().childNodes) {
- this.entryCount =
- this.update.down().childNodes.length;
- for (var i = 0; i < this.entryCount; i++) {
- var entry = this.getEntry(i);
- entry.autocompleteIndex = i;
- this.addObservers(entry);
- }
- } else {
- this.entryCount = 0;
- }
-
- this.stopIndicator();
- this.index = 0;
-
- if(this.entryCount==1 && this.options.autoSelect) {
- this.selectEntry();
- this.hide();
- } else {
- this.render();
- }
- }
- },
-
- addObservers: function(element) {
- Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
- Event.observe(element, "click", this.onClick.bindAsEventListener(this));
- },
-
- onObserverEvent: function() {
- this.changed = false;
- this.tokenBounds = null;
- if(this.getToken().length>=this.options.minChars) {
- this.getUpdatedChoices();
- } else {
- this.active = false;
- this.hide();
- }
- this.oldElementValue = this.element.value;
- },
-
- getToken: function() {
- var bounds = this.getTokenBounds();
- return this.element.value.substring(bounds[0], bounds[1]).strip();
- },
-
- getTokenBounds: function() {
- if (null != this.tokenBounds) return this.tokenBounds;
- var value = this.element.value;
- if (value.strip().empty()) return [-1, 0];
- var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
- var offset = (diff == this.oldElementValue.length ? 1 : 0);
- var prevTokenPos = -1, nextTokenPos = value.length;
- var tp;
- for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
- tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
- if (tp > prevTokenPos) prevTokenPos = tp;
- tp = value.indexOf(this.options.tokens[index], diff + offset);
- if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
- }
- return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
- }
-});
-
-Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
- var boundary = Math.min(newS.length, oldS.length);
- for (var index = 0; index < boundary; ++index)
- if (newS[index] != oldS[index])
- return index;
- return boundary;
-};
-
-Ajax.Autocompleter = Class.create(Autocompleter.Base, {
- initialize: function(element, update, url, options) {
- this.baseInitialize(element, update, options);
- this.options.asynchronous = true;
- this.options.onComplete = this.onComplete.bind(this);
- this.options.defaultParams = this.options.parameters || null;
- this.url = url;
- },
-
- getUpdatedChoices: function() {
- this.startIndicator();
-
- var entry = encodeURIComponent(this.options.paramName) + '=' +
- encodeURIComponent(this.getToken());
-
- this.options.parameters = this.options.callback ?
- this.options.callback(this.element, entry) : entry;
-
- if(this.options.defaultParams)
- this.options.parameters += '&' + this.options.defaultParams;
-
- new Ajax.Request(this.url, this.options);
- },
-
- onComplete: function(request) {
- this.updateChoices(request.responseText);
- }
-});
-
-// The local array autocompleter. Used when you'd prefer to
-// inject an array of autocompletion options into the page, rather
-// than sending out Ajax queries, which can be quite slow sometimes.
-//
-// The constructor takes four parameters. The first two are, as usual,
-// the id of the monitored textbox, and id of the autocompletion menu.
-// The third is the array you want to autocomplete from, and the fourth
-// is the options block.
-//
-// Extra local autocompletion options:
-// - choices - How many autocompletion choices to offer
-//
-// - partialSearch - If false, the autocompleter will match entered
-// text only at the beginning of strings in the
-// autocomplete array. Defaults to true, which will
-// match text at the beginning of any *word* in the
-// strings in the autocomplete array. If you want to
-// search anywhere in the string, additionally set
-// the option fullSearch to true (default: off).
-//
-// - fullSsearch - Search anywhere in autocomplete array strings.
-//
-// - partialChars - How many characters to enter before triggering
-// a partial match (unlike minChars, which defines
-// how many characters are required to do any match
-// at all). Defaults to 2.
-//
-// - ignoreCase - Whether to ignore case when autocompleting.
-// Defaults to true.
-//
-// It's possible to pass in a custom function as the 'selector'
-// option, if you prefer to write your own autocompletion logic.
-// In that case, the other options above will not apply unless
-// you support them.
-
-Autocompleter.Local = Class.create(Autocompleter.Base, {
- initialize: function(element, update, array, options) {
- this.baseInitialize(element, update, options);
- this.options.array = array;
- },
-
- getUpdatedChoices: function() {
- this.updateChoices(this.options.selector(this));
- },
-
- setOptions: function(options) {
- this.options = Object.extend({
- choices: 10,
- partialSearch: true,
- partialChars: 2,
- ignoreCase: true,
- fullSearch: false,
- selector: function(instance) {
- var ret = []; // Beginning matches
- var partial = []; // Inside matches
- var entry = instance.getToken();
- var count = 0;
-
- for (var i = 0; i < instance.options.array.length &&
- ret.length < instance.options.choices ; i++) {
-
- var elem = instance.options.array[i];
- var foundPos = instance.options.ignoreCase ?
- elem.toLowerCase().indexOf(entry.toLowerCase()) :
- elem.indexOf(entry);
-
- while (foundPos != -1) {
- if (foundPos == 0 && elem.length != entry.length) {
- ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
- elem.substr(entry.length) + "</li>");
- break;
- } else if (entry.length >= instance.options.partialChars &&
- instance.options.partialSearch && foundPos != -1) {
- if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
- partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
- elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
- foundPos + entry.length) + "</li>");
- break;
- }
- }
-
- foundPos = instance.options.ignoreCase ?
- elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
- elem.indexOf(entry, foundPos + 1);
-
- }
- }
- if (partial.length)
- ret = ret.concat(partial.slice(0, instance.options.choices - ret.length));
- return "<ul>" + ret.join('') + "</ul>";
- }
- }, options || { });
- }
-});
-
-// AJAX in-place editor and collection editor
-// Full rewrite by Christophe Porteneuve <tdd@tddsworld.com> (April 2007).
-
-// Use this if you notice weird scrolling problems on some browsers,
-// the DOM might be a bit confused when this gets called so do this
-// waits 1 ms (with setTimeout) until it does the activation
-Field.scrollFreeActivate = function(field) {
- setTimeout(function() {
- Field.activate(field);
- }, 1);
-};
-
-Ajax.InPlaceEditor = Class.create({
- initialize: function(element, url, options) {
- this.url = url;
- this.element = element = $(element);
- this.prepareOptions();
- this._controls = { };
- arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
- Object.extend(this.options, options || { });
- if (!this.options.formId && this.element.id) {
- this.options.formId = this.element.id + '-inplaceeditor';
- if ($(this.options.formId))
- this.options.formId = '';
- }
- if (this.options.externalControl)
- this.options.externalControl = $(this.options.externalControl);
- if (!this.options.externalControl)
- this.options.externalControlOnly = false;
- this._originalBackground = this.element.getStyle('background-color') || 'transparent';
- this.element.title = this.options.clickToEditText;
- this._boundCancelHandler = this.handleFormCancellation.bind(this);
- this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
- this._boundFailureHandler = this.handleAJAXFailure.bind(this);
- this._boundSubmitHandler = this.handleFormSubmission.bind(this);
- this._boundWrapperHandler = this.wrapUp.bind(this);
- this.registerListeners();
- },
- checkForEscapeOrReturn: function(e) {
- if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
- if (Event.KEY_ESC == e.keyCode)
- this.handleFormCancellation(e);
- else if (Event.KEY_RETURN == e.keyCode)
- this.handleFormSubmission(e);
- },
- createControl: function(mode, handler, extraClasses) {
- var control = this.options[mode + 'Control'];
- var text = this.options[mode + 'Text'];
- if ('button' == control) {
- var btn = document.createElement('input');
- btn.type = 'submit';
- btn.value = text;
- btn.className = 'editor_' + mode + '_button';
- if ('cancel' == mode)
- btn.onclick = this._boundCancelHandler;
- this._form.appendChild(btn);
- this._controls[mode] = btn;
- } else if ('link' == control) {
- var link = document.createElement('a');
- link.href = '#';
- link.appendChild(document.createTextNode(text));
- link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
- link.className = 'editor_' + mode + '_link';
- if (extraClasses)
- link.className += ' ' + extraClasses;
- this._form.appendChild(link);
- this._controls[mode] = link;
- }
- },
- createEditField: function() {
- var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
- var fld;
- if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
- fld = document.createElement('input');
- fld.type = 'text';
- var size = this.options.size || this.options.cols || 0;
- if (0 < size) fld.size = size;
- } else {
- fld = document.createElement('textarea');
- fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
- fld.cols = this.options.cols || 40;
- }
- fld.name = this.options.paramName;
- fld.value = text; // No HTML breaks conversion anymore
- fld.className = 'editor_field';
- if (this.options.submitOnBlur)
- fld.onblur = this._boundSubmitHandler;
- this._controls.editor = fld;
- if (this.options.loadTextURL)
- this.loadExternalText();
- this._form.appendChild(this._controls.editor);
- },
- createForm: function() {
- var ipe = this;
- function addText(mode, condition) {
- var text = ipe.options['text' + mode + 'Controls'];
- if (!text || condition === false) return;
- ipe._form.appendChild(document.createTextNode(text));
- };
- this._form = $(document.createElement('form'));
- this._form.id = this.options.formId;
- this._form.addClassName(this.options.formClassName);
- this._form.onsubmit = this._boundSubmitHandler;
- this.createEditField();
- if ('textarea' == this._controls.editor.tagName.toLowerCase())
- this._form.appendChild(document.createElement('br'));
- if (this.options.onFormCustomization)
- this.options.onFormCustomization(this, this._form);
- addText('Before', this.options.okControl || this.options.cancelControl);
- this.createControl('ok', this._boundSubmitHandler);
- addText('Between', this.options.okControl && this.options.cancelControl);
- this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');
- addText('After', this.options.okControl || this.options.cancelControl);
- },
- destroy: function() {
- if (this._oldInnerHTML)
- this.element.innerHTML = this._oldInnerHTML;
- this.leaveEditMode();
- this.unregisterListeners();
- },
- enterEditMode: function(e) {
- if (this._saving || this._editing) return;
- this._editing = true;
- this.triggerCallback('onEnterEditMode');
- if (this.options.externalControl)
- this.options.externalControl.hide();
- this.element.hide();
- this.createForm();
- this.element.parentNode.insertBefore(this._form, this.element);
- if (!this.options.loadTextURL)
- this.postProcessEditField();
- if (e) Event.stop(e);
- },
- enterHover: function(e) {
- if (this.options.hoverClassName)
- this.element.addClassName(this.options.hoverClassName);
- if (this._saving) return;
- this.triggerCallback('onEnterHover');
- },
- getText: function() {
- return this.element.innerHTML.unescapeHTML();
- },
- handleAJAXFailure: function(transport) {
- this.triggerCallback('onFailure', transport);
- if (this._oldInnerHTML) {
- this.element.innerHTML = this._oldInnerHTML;
- this._oldInnerHTML = null;
- }
- },
- handleFormCancellation: function(e) {
- this.wrapUp();
- if (e) Event.stop(e);
- },
- handleFormSubmission: function(e) {
- var form = this._form;
- var value = $F(this._controls.editor);
- this.prepareSubmission();
- var params = this.options.callback(form, value) || '';
- if (Object.isString(params))
- params = params.toQueryParams();
- params.editorId = this.element.id;
- if (this.options.htmlResponse) {
- var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
- Object.extend(options, {
- parameters: params,
- onComplete: this._boundWrapperHandler,
- onFailure: this._boundFailureHandler
- });
- new Ajax.Updater({ success: this.element }, this.url, options);
- } else {
- var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
- Object.extend(options, {
- parameters: params,
- onComplete: this._boundWrapperHandler,
- onFailure: this._boundFailureHandler
- });
- new Ajax.Request(this.url, options);
- }
- if (e) Event.stop(e);
- },
- leaveEditMode: function() {
- this.element.removeClassName(this.options.savingClassName);
- this.removeForm();
- this.leaveHover();
- this.element.style.backgroundColor = this._originalBackground;
- this.element.show();
- if (this.options.externalControl)
- this.options.externalControl.show();
- this._saving = false;
- this._editing = false;
- this._oldInnerHTML = null;
- this.triggerCallback('onLeaveEditMode');
- },
- leaveHover: function(e) {
- if (this.options.hoverClassName)
- this.element.removeClassName(this.options.hoverClassName);
- if (this._saving) return;
- this.triggerCallback('onLeaveHover');
- },
- loadExternalText: function() {
- this._form.addClassName(this.options.loadingClassName);
- this._controls.editor.disabled = true;
- var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
- Object.extend(options, {
- parameters: 'editorId=' + encodeURIComponent(this.element.id),
- onComplete: Prototype.emptyFunction,
- onSuccess: function(transport) {
- this._form.removeClassName(this.options.loadingClassName);
- var text = transport.responseText;
- if (this.options.stripLoadedTextTags)
- text = text.stripTags();
- this._controls.editor.value = text;
- this._controls.editor.disabled = false;
- this.postProcessEditField();
- }.bind(this),
- onFailure: this._boundFailureHandler
- });
- new Ajax.Request(this.options.loadTextURL, options);
- },
- postProcessEditField: function() {
- var fpc = this.options.fieldPostCreation;
- if (fpc)
- $(this._controls.editor)['focus' == fpc ? 'focus' : 'activate']();
- },
- prepareOptions: function() {
- this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions);
- Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks);
- [this._extraDefaultOptions].flatten().compact().each(function(defs) {
- Object.extend(this.options, defs);
- }.bind(this));
- },
- prepareSubmission: function() {
- this._saving = true;
- this.removeForm();
- this.leaveHover();
- this.showSaving();
- },
- registerListeners: function() {
- this._listeners = { };
- var listener;
- $H(Ajax.InPlaceEditor.Listeners).each(function(pair) {
- listener = this[pair.value].bind(this);
- this._listeners[pair.key] = listener;
- if (!this.options.externalControlOnly)
- this.element.observe(pair.key, listener);
- if (this.options.externalControl)
- this.options.externalControl.observe(pair.key, listener);
- }.bind(this));
- },
- removeForm: function() {
- if (!this._form) return;
- this._form.remove();
- this._form = null;
- this._controls = { };
- },
- showSaving: function() {
- this._oldInnerHTML = this.element.innerHTML;
- this.element.innerHTML = this.options.savingText;
- this.element.addClassName(this.options.savingClassName);
- this.element.style.backgroundColor = this._originalBackground;
- this.element.show();
- },
- triggerCallback: function(cbName, arg) {
- if ('function' == typeof this.options[cbName]) {
- this.options[cbName](this, arg);
- }
- },
- unregisterListeners: function() {
- $H(this._listeners).each(function(pair) {
- if (!this.options.externalControlOnly)
- this.element.stopObserving(pair.key, pair.value);
- if (this.options.externalControl)
- this.options.externalControl.stopObserving(pair.key, pair.value);
- }.bind(this));
- },
- wrapUp: function(transport) {
- this.leaveEditMode();
- // Can't use triggerCallback due to backward compatibility: requires
- // binding + direct element
- this._boundComplete(transport, this.element);
- }
-});
-
-Object.extend(Ajax.InPlaceEditor.prototype, {
- dispose: Ajax.InPlaceEditor.prototype.destroy
-});
-
-Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
- initialize: function($super, element, url, options) {
- this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions;
- $super(element, url, options);
- },
-
- createEditField: function() {
- var list = document.createElement('select');
- list.name = this.options.paramName;
- list.size = 1;
- this._controls.editor = list;
- this._collection = this.options.collection || [];
- if (this.options.loadCollectionURL)
- this.loadCollection();
- else
- this.checkForExternalText();
- this._form.appendChild(this._controls.editor);
- },
-
- loadCollection: function() {
- this._form.addClassName(this.options.loadingClassName);
- this.showLoadingText(this.options.loadingCollectionText);
- var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
- Object.extend(options, {
- parameters: 'editorId=' + encodeURIComponent(this.element.id),
- onComplete: Prototype.emptyFunction,
- onSuccess: function(transport) {
- var js = transport.responseText.strip();
- if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
- throw('Server returned an invalid collection representation.');
- this._collection = eval(js);
- this.checkForExternalText();
- }.bind(this),
- onFailure: this.onFailure
- });
- new Ajax.Request(this.options.loadCollectionURL, options);
- },
-
- showLoadingText: function(text) {
- this._controls.editor.disabled = true;
- var tempOption = this._controls.editor.firstChild;
- if (!tempOption) {
- tempOption = document.createElement('option');
- tempOption.value = '';
- this._controls.editor.appendChild(tempOption);
- tempOption.selected = true;
- }
- tempOption.update((text || '').stripScripts().stripTags());
- },
-
- checkForExternalText: function() {
- this._text = this.getText();
- if (this.options.loadTextURL)
- this.loadExternalText();
- else
- this.buildOptionList();
- },
-
- loadExternalText: function() {
- this.showLoadingText(this.options.loadingText);
- var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
- Object.extend(options, {
- parameters: 'editorId=' + encodeURIComponent(this.element.id),
- onComplete: Prototype.emptyFunction,
- onSuccess: function(transport) {
- this._text = transport.responseText.strip();
- this.buildOptionList();
- }.bind(this),
- onFailure: this.onFailure
- });
- new Ajax.Request(this.options.loadTextURL, options);
- },
-
- buildOptionList: function() {
- this._form.removeClassName(this.options.loadingClassName);
- this._collection = this._collection.map(function(entry) {
- return 2 === entry.length ? entry : [entry, entry].flatten();
- });
- var marker = ('value' in this.options) ? this.options.value : this._text;
- var textFound = this._collection.any(function(entry) {
- return entry[0] == marker;
- }.bind(this));
- this._controls.editor.update('');
- var option;
- this._collection.each(function(entry, index) {
- option = document.createElement('option');
- option.value = entry[0];
- option.selected = textFound ? entry[0] == marker : 0 == index;
- option.appendChild(document.createTextNode(entry[1]));
- this._controls.editor.appendChild(option);
- }.bind(this));
- this._controls.editor.disabled = false;
- Field.scrollFreeActivate(this._controls.editor);
- }
-});
-
-//**** DEPRECATION LAYER FOR InPlace[Collection]Editor! ****
-//**** This only exists for a while, in order to let ****
-//**** users adapt to the new API. Read up on the new ****
-//**** API and convert your code to it ASAP! ****
-
-Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) {
- if (!options) return;
- function fallback(name, expr) {
- if (name in options || expr === undefined) return;
- options[name] = expr;
- };
- fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' :
- options.cancelLink == options.cancelButton == false ? false : undefined)));
- fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' :
- options.okLink == options.okButton == false ? false : undefined)));
- fallback('highlightColor', options.highlightcolor);
- fallback('highlightEndColor', options.highlightendcolor);
-};
-
-Object.extend(Ajax.InPlaceEditor, {
- DefaultOptions: {
- ajaxOptions: { },
- autoRows: 3, // Use when multi-line w/ rows == 1
- cancelControl: 'link', // 'link'|'button'|false
- cancelText: 'cancel',
- clickToEditText: 'Click to edit',
- externalControl: null, // id|elt
- externalControlOnly: false,
- fieldPostCreation: 'activate', // 'activate'|'focus'|false
- formClassName: 'inplaceeditor-form',
- formId: null, // id|elt
- highlightColor: '#ffff99',
- highlightEndColor: '#ffffff',
- hoverClassName: '',
- htmlResponse: true,
- loadingClassName: 'inplaceeditor-loading',
- loadingText: 'Loading...',
- okControl: 'button', // 'link'|'button'|false
- okText: 'ok',
- paramName: 'value',
- rows: 1, // If 1 and multi-line, uses autoRows
- savingClassName: 'inplaceeditor-saving',
- savingText: 'Saving...',
- size: 0,
- stripLoadedTextTags: false,
- submitOnBlur: false,
- textAfterControls: '',
- textBeforeControls: '',
- textBetweenControls: ''
- },
- DefaultCallbacks: {
- callback: function(form) {
- return Form.serialize(form);
- },
- onComplete: function(transport, element) {
- // For backward compatibility, this one is bound to the IPE, and passes
- // the element directly. It was too often customized, so we don't break it.
- new Effect.Highlight(element, {
- startcolor: this.options.highlightColor, keepBackgroundImage: true });
- },
- onEnterEditMode: null,
- onEnterHover: function(ipe) {
- ipe.element.style.backgroundColor = ipe.options.highlightColor;
- if (ipe._effect)
- ipe._effect.cancel();
- },
- onFailure: function(transport, ipe) {
- alert('Error communication with the server: ' + transport.responseText.stripTags());
- },
- onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls.
- onLeaveEditMode: null,
- onLeaveHover: function(ipe) {
- ipe._effect = new Effect.Highlight(ipe.element, {
- startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor,
- restorecolor: ipe._originalBackground, keepBackgroundImage: true
- });
- }
- },
- Listeners: {
- click: 'enterEditMode',
- keydown: 'checkForEscapeOrReturn',
- mouseover: 'enterHover',
- mouseout: 'leaveHover'
- }
-});
-
-Ajax.InPlaceCollectionEditor.DefaultOptions = {
- loadingCollectionText: 'Loading options...'
-};
-
-// Delayed observer, like Form.Element.Observer,
-// but waits for delay after last key input
-// Ideal for live-search fields
-
-Form.Element.DelayedObserver = Class.create({
- initialize: function(element, delay, callback) {
- this.delay = delay || 0.5;
- this.element = $(element);
- this.callback = callback;
- this.timer = null;
- this.lastValue = $F(this.element);
- Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
- },
- delayedListener: function(event) {
- if(this.lastValue == $F(this.element)) return;
- if(this.timer) clearTimeout(this.timer);
- this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
- this.lastValue = $F(this.element);
- },
- onTimerEvent: function() {
- this.timer = null;
- this.callback(this.element, $F(this.element));
- }
-}); \ No newline at end of file
+// script.aculo.us builder.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
+
+// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+//
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
+
+var Builder = {
+ NODEMAP: {
+ AREA: 'map',
+ CAPTION: 'table',
+ COL: 'table',
+ COLGROUP: 'table',
+ LEGEND: 'fieldset',
+ OPTGROUP: 'select',
+ OPTION: 'select',
+ PARAM: 'object',
+ TBODY: 'table',
+ TD: 'table',
+ TFOOT: 'table',
+ TH: 'table',
+ THEAD: 'table',
+ TR: 'table'
+ },
+ // note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken,
+ // due to a Firefox bug
+ node: function(elementName) {
+ elementName = elementName.toUpperCase();
+
+ // try innerHTML approach
+ var parentTag = this.NODEMAP[elementName] || 'div';
+ var parentElement = document.createElement(parentTag);
+ try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
+ parentElement.innerHTML = "<" + elementName + "></" + elementName + ">";
+ } catch(e) {}
+ var element = parentElement.firstChild || null;
+
+ // see if browser added wrapping tags
+ if(element && (element.tagName.toUpperCase() != elementName))
+ element = element.getElementsByTagName(elementName)[0];
+
+ // fallback to createElement approach
+ if(!element) element = document.createElement(elementName);
+
+ // abort if nothing could be created
+ if(!element) return;
+
+ // attributes (or text)
+ if(arguments[1])
+ if(this._isStringOrNumber(arguments[1]) ||
+ (arguments[1] instanceof Array) ||
+ arguments[1].tagName) {
+ this._children(element, arguments[1]);
+ } else {
+ var attrs = this._attributes(arguments[1]);
+ if(attrs.length) {
+ try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
+ parentElement.innerHTML = "<" +elementName + " " +
+ attrs + "></" + elementName + ">";
+ } catch(e) {}
+ element = parentElement.firstChild || null;
+ // workaround firefox 1.0.X bug
+ if(!element) {
+ element = document.createElement(elementName);
+ for(attr in arguments[1])
+ element[attr == 'class' ? 'className' : attr] = arguments[1][attr];
+ }
+ if(element.tagName.toUpperCase() != elementName)
+ element = parentElement.getElementsByTagName(elementName)[0];
+ }
+ }
+
+ // text, or array of children
+ if(arguments[2])
+ this._children(element, arguments[2]);
+
+ return $(element);
+ },
+ _text: function(text) {
+ return document.createTextNode(text);
+ },
+
+ ATTR_MAP: {
+ 'className': 'class',
+ 'htmlFor': 'for'
+ },
+
+ _attributes: function(attributes) {
+ var attrs = [];
+ for(attribute in attributes)
+ attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) +
+ '="' + attributes[attribute].toString().escapeHTML().gsub(/"/,'&quot;') + '"');
+ return attrs.join(" ");
+ },
+ _children: function(element, children) {
+ if(children.tagName) {
+ element.appendChild(children);
+ return;
+ }
+ if(typeof children=='object') { // array can hold nodes and text
+ children.flatten().each( function(e) {
+ if(typeof e=='object')
+ element.appendChild(e);
+ else
+ if(Builder._isStringOrNumber(e))
+ element.appendChild(Builder._text(e));
+ });
+ } else
+ if(Builder._isStringOrNumber(children))
+ element.appendChild(Builder._text(children));
+ },
+ _isStringOrNumber: function(param) {
+ return(typeof param=='string' || typeof param=='number');
+ },
+ build: function(html) {
+ var element = this.node('div');
+ $(element).update(html.strip());
+ return element.down();
+ },
+ dump: function(scope) {
+ if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope
+
+ var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " +
+ "BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " +
+ "FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+
+ "KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+
+ "PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+
+ "TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/);
+
+ tags.each( function(tag){
+ scope[tag] = function() {
+ return Builder.node.apply(Builder, [tag].concat($A(arguments)));
+ };
+ });
+ }
+};
+
+
+// script.aculo.us effects.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
+
+// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// Contributors:
+// Justin Palmer (http://encytemedia.com/)
+// Mark Pilgrim (http://diveintomark.org/)
+// Martin Bialasinki
+//
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
+
+// converts rgb() and #xxx to #xxxxxx format,
+// returns self (or first argument) if not convertable
+String.prototype.parseColor = function() {
+ var color = '#';
+ if (this.slice(0,4) == 'rgb(') {
+ var cols = this.slice(4,this.length-1).split(',');
+ var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);
+ } else {
+ if (this.slice(0,1) == '#') {
+ if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();
+ if (this.length==7) color = this.toLowerCase();
+ }
+ }
+ return (color.length==7 ? color : (arguments[0] || this));
+};
+
+/*--------------------------------------------------------------------------*/
+
+Element.collectTextNodes = function(element) {
+ return $A($(element).childNodes).collect( function(node) {
+ return (node.nodeType==3 ? node.nodeValue :
+ (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
+ }).flatten().join('');
+};
+
+Element.collectTextNodesIgnoreClass = function(element, className) {
+ return $A($(element).childNodes).collect( function(node) {
+ return (node.nodeType==3 ? node.nodeValue :
+ ((node.hasChildNodes() && !Element.hasClassName(node,className)) ?
+ Element.collectTextNodesIgnoreClass(node, className) : ''));
+ }).flatten().join('');
+};
+
+Element.setContentZoom = function(element, percent) {
+ element = $(element);
+ element.setStyle({fontSize: (percent/100) + 'em'});
+ if (Prototype.Browser.WebKit) window.scrollBy(0,0);
+ return element;
+};
+
+Element.getInlineOpacity = function(element){
+ return $(element).style.opacity || '';
+};
+
+Element.forceRerendering = function(element) {
+ try {
+ element = $(element);
+ var n = document.createTextNode(' ');
+ element.appendChild(n);
+ element.removeChild(n);
+ } catch(e) { }
+};
+
+/*--------------------------------------------------------------------------*/
+
+var Effect = {
+ _elementDoesNotExistError: {
+ name: 'ElementDoesNotExistError',
+ message: 'The specified DOM element does not exist, but is required for this effect to operate'
+ },
+ Transitions: {
+ linear: Prototype.K,
+ sinoidal: function(pos) {
+ return (-Math.cos(pos*Math.PI)/2) + .5;
+ },
+ reverse: function(pos) {
+ return 1-pos;
+ },
+ flicker: function(pos) {
+ var pos = ((-Math.cos(pos*Math.PI)/4) + .75) + Math.random()/4;
+ return pos > 1 ? 1 : pos;
+ },
+ wobble: function(pos) {
+ return (-Math.cos(pos*Math.PI*(9*pos))/2) + .5;
+ },
+ pulse: function(pos, pulses) {
+ return (-Math.cos((pos*((pulses||5)-.5)*2)*Math.PI)/2) + .5;
+ },
+ spring: function(pos) {
+ return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6));
+ },
+ none: function(pos) {
+ return 0;
+ },
+ full: function(pos) {
+ return 1;
+ }
+ },
+ DefaultOptions: {
+ duration: 1.0, // seconds
+ fps: 100, // 100= assume 66fps max.
+ sync: false, // true for combining
+ from: 0.0,
+ to: 1.0,
+ delay: 0.0,
+ queue: 'parallel'
+ },
+ tagifyText: function(element) {
+ var tagifyStyle = 'position:relative';
+ if (Prototype.Browser.IE) tagifyStyle += ';zoom:1';
+
+ element = $(element);
+ $A(element.childNodes).each( function(child) {
+ if (child.nodeType==3) {
+ child.nodeValue.toArray().each( function(character) {
+ element.insertBefore(
+ new Element('span', {style: tagifyStyle}).update(
+ character == ' ' ? String.fromCharCode(160) : character),
+ child);
+ });
+ Element.remove(child);
+ }
+ });
+ },
+ multiple: function(element, effect) {
+ var elements;
+ if (((typeof element == 'object') ||
+ Object.isFunction(element)) &&
+ (element.length))
+ elements = element;
+ else
+ elements = $(element).childNodes;
+
+ var options = Object.extend({
+ speed: 0.1,
+ delay: 0.0
+ }, arguments[2] || { });
+ var masterDelay = options.delay;
+
+ $A(elements).each( function(element, index) {
+ new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
+ });
+ },
+ PAIRS: {
+ 'slide': ['SlideDown','SlideUp'],
+ 'blind': ['BlindDown','BlindUp'],
+ 'appear': ['Appear','Fade']
+ },
+ toggle: function(element, effect, options) {
+ element = $(element);
+ effect = (effect || 'appear').toLowerCase();
+
+ return Effect[ Effect.PAIRS[ effect ][ element.visible() ? 1 : 0 ] ](element, Object.extend({
+ queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
+ }, options || {}));
+ }
+};
+
+Effect.DefaultOptions.transition = Effect.Transitions.sinoidal;
+
+/* ------------- core effects ------------- */
+
+Effect.ScopedQueue = Class.create(Enumerable, {
+ initialize: function() {
+ this.effects = [];
+ this.interval = null;
+ },
+ _each: function(iterator) {
+ this.effects._each(iterator);
+ },
+ add: function(effect) {
+ var timestamp = new Date().getTime();
+
+ var position = Object.isString(effect.options.queue) ?
+ effect.options.queue : effect.options.queue.position;
+
+ switch(position) {
+ case 'front':
+ // move unstarted effects after this effect
+ this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
+ e.startOn += effect.finishOn;
+ e.finishOn += effect.finishOn;
+ });
+ break;
+ case 'with-last':
+ timestamp = this.effects.pluck('startOn').max() || timestamp;
+ break;
+ case 'end':
+ // start effect after last queued effect has finished
+ timestamp = this.effects.pluck('finishOn').max() || timestamp;
+ break;
+ }
+
+ effect.startOn += timestamp;
+ effect.finishOn += timestamp;
+
+ if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
+ this.effects.push(effect);
+
+ if (!this.interval)
+ this.interval = setInterval(this.loop.bind(this), 15);
+ },
+ remove: function(effect) {
+ this.effects = this.effects.reject(function(e) { return e==effect });
+ if (this.effects.length == 0) {
+ clearInterval(this.interval);
+ this.interval = null;
+ }
+ },
+ loop: function() {
+ var timePos = new Date().getTime();
+ for(var i=0, len=this.effects.length;i<len;i++)
+ this.effects[i] && this.effects[i].loop(timePos);
+ }
+});
+
+Effect.Queues = {
+ instances: $H(),
+ get: function(queueName) {
+ if (!Object.isString(queueName)) return queueName;
+
+ return this.instances.get(queueName) ||
+ this.instances.set(queueName, new Effect.ScopedQueue());
+ }
+};
+Effect.Queue = Effect.Queues.get('global');
+
+Effect.Base = Class.create({
+ position: null,
+ start: function(options) {
+ if (options && options.transition === false) options.transition = Effect.Transitions.linear;
+ this.options = Object.extend(Object.extend({ },Effect.DefaultOptions), options || { });
+ this.currentFrame = 0;
+ this.state = 'idle';
+ this.startOn = this.options.delay*1000;
+ this.finishOn = this.startOn+(this.options.duration*1000);
+ this.fromToDelta = this.options.to-this.options.from;
+ this.totalTime = this.finishOn-this.startOn;
+ this.totalFrames = this.options.fps*this.options.duration;
+
+ this.render = (function() {
+ function dispatch(effect, eventName) {
+ if (effect.options[eventName + 'Internal'])
+ effect.options[eventName + 'Internal'](effect);
+ if (effect.options[eventName])
+ effect.options[eventName](effect);
+ }
+
+ return function(pos) {
+ if (this.state === "idle") {
+ this.state = "running";
+ dispatch(this, 'beforeSetup');
+ if (this.setup) this.setup();
+ dispatch(this, 'afterSetup');
+ }
+ if (this.state === "running") {
+ pos = (this.options.transition(pos) * this.fromToDelta) + this.options.from;
+ this.position = pos;
+ dispatch(this, 'beforeUpdate');
+ if (this.update) this.update(pos);
+ dispatch(this, 'afterUpdate');
+ }
+ };
+ })();
+
+ this.event('beforeStart');
+ if (!this.options.sync)
+ Effect.Queues.get(Object.isString(this.options.queue) ?
+ 'global' : this.options.queue.scope).add(this);
+ },
+ loop: function(timePos) {
+ if (timePos >= this.startOn) {
+ if (timePos >= this.finishOn) {
+ this.render(1.0);
+ this.cancel();
+ this.event('beforeFinish');
+ if (this.finish) this.finish();
+ this.event('afterFinish');
+ return;
+ }
+ var pos = (timePos - this.startOn) / this.totalTime,
+ frame = (pos * this.totalFrames).round();
+ if (frame > this.currentFrame) {
+ this.render(pos);
+ this.currentFrame = frame;
+ }
+ }
+ },
+ cancel: function() {
+ if (!this.options.sync)
+ Effect.Queues.get(Object.isString(this.options.queue) ?
+ 'global' : this.options.queue.scope).remove(this);
+ this.state = 'finished';
+ },
+ event: function(eventName) {
+ if (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
+ if (this.options[eventName]) this.options[eventName](this);
+ },
+ inspect: function() {
+ var data = $H();
+ for(property in this)
+ if (!Object.isFunction(this[property])) data.set(property, this[property]);
+ return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
+ }
+});
+
+Effect.Parallel = Class.create(Effect.Base, {
+ initialize: function(effects) {
+ this.effects = effects || [];
+ this.start(arguments[1]);
+ },
+ update: function(position) {
+ this.effects.invoke('render', position);
+ },
+ finish: function(position) {
+ this.effects.each( function(effect) {
+ effect.render(1.0);
+ effect.cancel();
+ effect.event('beforeFinish');
+ if (effect.finish) effect.finish(position);
+ effect.event('afterFinish');
+ });
+ }
+});
+
+Effect.Tween = Class.create(Effect.Base, {
+ initialize: function(object, from, to) {
+ object = Object.isString(object) ? $(object) : object;
+ var args = $A(arguments), method = args.last(),
+ options = args.length == 5 ? args[3] : null;
+ this.method = Object.isFunction(method) ? method.bind(object) :
+ Object.isFunction(object[method]) ? object[method].bind(object) :
+ function(value) { object[method] = value };
+ this.start(Object.extend({ from: from, to: to }, options || { }));
+ },
+ update: function(position) {
+ this.method(position);
+ }
+});
+
+Effect.Event = Class.create(Effect.Base, {
+ initialize: function() {
+ this.start(Object.extend({ duration: 0 }, arguments[0] || { }));
+ },
+ update: Prototype.emptyFunction
+});
+
+Effect.Opacity = Class.create(Effect.Base, {
+ initialize: function(element) {
+ this.element = $(element);
+ if (!this.element) throw(Effect._elementDoesNotExistError);
+ // make this work on IE on elements without 'layout'
+ if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
+ this.element.setStyle({zoom: 1});
+ var options = Object.extend({
+ from: this.element.getOpacity() || 0.0,
+ to: 1.0
+ }, arguments[1] || { });
+ this.start(options);
+ },
+ update: function(position) {
+ this.element.setOpacity(position);
+ }
+});
+
+Effect.Move = Class.create(Effect.Base, {
+ initialize: function(element) {
+ this.element = $(element);
+ if (!this.element) throw(Effect._elementDoesNotExistError);
+ var options = Object.extend({
+ x: 0,
+ y: 0,
+ mode: 'relative'
+ }, arguments[1] || { });
+ this.start(options);
+ },
+ setup: function() {
+ this.element.makePositioned();
+ this.originalLeft = parseFloat(this.element.getStyle('left') || '0');
+ this.originalTop = parseFloat(this.element.getStyle('top') || '0');
+ if (this.options.mode == 'absolute') {
+ this.options.x = this.options.x - this.originalLeft;
+ this.options.y = this.options.y - this.originalTop;
+ }
+ },
+ update: function(position) {
+ this.element.setStyle({
+ left: (this.options.x * position + this.originalLeft).round() + 'px',
+ top: (this.options.y * position + this.originalTop).round() + 'px'
+ });
+ }
+});
+
+// for backwards compatibility
+Effect.MoveBy = function(element, toTop, toLeft) {
+ return new Effect.Move(element,
+ Object.extend({ x: toLeft, y: toTop }, arguments[3] || { }));
+};
+
+Effect.Scale = Class.create(Effect.Base, {
+ initialize: function(element, percent) {
+ this.element = $(element);
+ if (!this.element) throw(Effect._elementDoesNotExistError);
+ var options = Object.extend({
+ scaleX: true,
+ scaleY: true,
+ scaleContent: true,
+ scaleFromCenter: false,
+ scaleMode: 'box', // 'box' or 'contents' or { } with provided values
+ scaleFrom: 100.0,
+ scaleTo: percent
+ }, arguments[2] || { });
+ this.start(options);
+ },
+ setup: function() {
+ this.restoreAfterFinish = this.options.restoreAfterFinish || false;
+ this.elementPositioning = this.element.getStyle('position');
+
+ this.originalStyle = { };
+ ['top','left','width','height','fontSize'].each( function(k) {
+ this.originalStyle[k] = this.element.style[k];
+ }.bind(this));
+
+ this.originalTop = this.element.offsetTop;
+ this.originalLeft = this.element.offsetLeft;
+
+ var fontSize = this.element.getStyle('font-size') || '100%';
+ ['em','px','%','pt'].each( function(fontSizeType) {
+ if (fontSize.indexOf(fontSizeType)>0) {
+ this.fontSize = parseFloat(fontSize);
+ this.fontSizeType = fontSizeType;
+ }
+ }.bind(this));
+
+ this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
+
+ this.dims = null;
+ if (this.options.scaleMode=='box')
+ this.dims = [this.element.offsetHeight, this.element.offsetWidth];
+ if (/^content/.test(this.options.scaleMode))
+ this.dims = [this.element.scrollHeight, this.element.scrollWidth];
+ if (!this.dims)
+ this.dims = [this.options.scaleMode.originalHeight,
+ this.options.scaleMode.originalWidth];
+ },
+ update: function(position) {
+ var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
+ if (this.options.scaleContent && this.fontSize)
+ this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
+ this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
+ },
+ finish: function(position) {
+ if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
+ },
+ setDimensions: function(height, width) {
+ var d = { };
+ if (this.options.scaleX) d.width = width.round() + 'px';
+ if (this.options.scaleY) d.height = height.round() + 'px';
+ if (this.options.scaleFromCenter) {
+ var topd = (height - this.dims[0])/2;
+ var leftd = (width - this.dims[1])/2;
+ if (this.elementPositioning == 'absolute') {
+ if (this.options.scaleY) d.top = this.originalTop-topd + 'px';
+ if (this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
+ } else {
+ if (this.options.scaleY) d.top = -topd + 'px';
+ if (this.options.scaleX) d.left = -leftd + 'px';
+ }
+ }
+ this.element.setStyle(d);
+ }
+});
+
+Effect.Highlight = Class.create(Effect.Base, {
+ initialize: function(element) {
+ this.element = $(element);
+ if (!this.element) throw(Effect._elementDoesNotExistError);
+ var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { });
+ this.start(options);
+ },
+ setup: function() {
+ // Prevent executing on elements not in the layout flow
+ if (this.element.getStyle('display')=='none') { this.cancel(); return; }
+ // Disable background image during the effect
+ this.oldStyle = { };
+ if (!this.options.keepBackgroundImage) {
+ this.oldStyle.backgroundImage = this.element.getStyle('background-image');
+ this.element.setStyle({backgroundImage: 'none'});
+ }
+ if (!this.options.endcolor)
+ this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
+ if (!this.options.restorecolor)
+ this.options.restorecolor = this.element.getStyle('background-color');
+ // init color calculations
+ this._base = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
+ this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
+ },
+ update: function(position) {
+ this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
+ return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) });
+ },
+ finish: function() {
+ this.element.setStyle(Object.extend(this.oldStyle, {
+ backgroundColor: this.options.restorecolor
+ }));
+ }
+});
+
+Effect.ScrollTo = function(element) {
+ var options = arguments[1] || { },
+ scrollOffsets = document.viewport.getScrollOffsets(),
+ elementOffsets = $(element).cumulativeOffset();
+
+ if (options.offset) elementOffsets[1] += options.offset;
+
+ return new Effect.Tween(null,
+ scrollOffsets.top,
+ elementOffsets[1],
+ options,
+ function(p){ scrollTo(scrollOffsets.left, p.round()); }
+ );
+};
+
+/* ------------- combination effects ------------- */
+
+Effect.Fade = function(element) {
+ element = $(element);
+ var oldOpacity = element.getInlineOpacity();
+ var options = Object.extend({
+ from: element.getOpacity() || 1.0,
+ to: 0.0,
+ afterFinishInternal: function(effect) {
+ if (effect.options.to!=0) return;
+ effect.element.hide().setStyle({opacity: oldOpacity});
+ }
+ }, arguments[1] || { });
+ return new Effect.Opacity(element,options);
+};
+
+Effect.Appear = function(element) {
+ element = $(element);
+ var options = Object.extend({
+ from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
+ to: 1.0,
+ // force Safari to render floated elements properly
+ afterFinishInternal: function(effect) {
+ effect.element.forceRerendering();
+ },
+ beforeSetup: function(effect) {
+ effect.element.setOpacity(effect.options.from).show();
+ }}, arguments[1] || { });
+ return new Effect.Opacity(element,options);
+};
+
+Effect.Puff = function(element) {
+ element = $(element);
+ var oldStyle = {
+ opacity: element.getInlineOpacity(),
+ position: element.getStyle('position'),
+ top: element.style.top,
+ left: element.style.left,
+ width: element.style.width,
+ height: element.style.height
+ };
+ return new Effect.Parallel(
+ [ new Effect.Scale(element, 200,
+ { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }),
+ new Effect.Opacity(element, { sync: true, to: 0.0 } ) ],
+ Object.extend({ duration: 1.0,
+ beforeSetupInternal: function(effect) {
+ Position.absolutize(effect.effects[0].element);
+ },
+ afterFinishInternal: function(effect) {
+ effect.effects[0].element.hide().setStyle(oldStyle); }
+ }, arguments[1] || { })
+ );
+};
+
+Effect.BlindUp = function(element) {
+ element = $(element);
+ element.makeClipping();
+ return new Effect.Scale(element, 0,
+ Object.extend({ scaleContent: false,
+ scaleX: false,
+ restoreAfterFinish: true,
+ afterFinishInternal: function(effect) {
+ effect.element.hide().undoClipping();
+ }
+ }, arguments[1] || { })
+ );
+};
+
+Effect.BlindDown = function(element) {
+ element = $(element);
+ var elementDimensions = element.getDimensions();
+ return new Effect.Scale(element, 100, Object.extend({
+ scaleContent: false,
+ scaleX: false,
+ scaleFrom: 0,
+ scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
+ restoreAfterFinish: true,
+ afterSetup: function(effect) {
+ effect.element.makeClipping().setStyle({height: '0px'}).show();
+ },
+ afterFinishInternal: function(effect) {
+ effect.element.undoClipping();
+ }
+ }, arguments[1] || { }));
+};
+
+Effect.SwitchOff = function(element) {
+ element = $(element);
+ var oldOpacity = element.getInlineOpacity();
+ return new Effect.Appear(element, Object.extend({
+ duration: 0.4,
+ from: 0,
+ transition: Effect.Transitions.flicker,
+ afterFinishInternal: function(effect) {
+ new Effect.Scale(effect.element, 1, {
+ duration: 0.3, scaleFromCenter: true,
+ scaleX: false, scaleContent: false, restoreAfterFinish: true,
+ beforeSetup: function(effect) {
+ effect.element.makePositioned().makeClipping();
+ },
+ afterFinishInternal: function(effect) {
+ effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
+ }
+ });
+ }
+ }, arguments[1] || { }));
+};
+
+Effect.DropOut = function(element) {
+ element = $(element);
+ var oldStyle = {
+ top: element.getStyle('top'),
+ left: element.getStyle('left'),
+ opacity: element.getInlineOpacity() };
+ return new Effect.Parallel(
+ [ new Effect.Move(element, {x: 0, y: 100, sync: true }),
+ new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
+ Object.extend(
+ { duration: 0.5,
+ beforeSetup: function(effect) {
+ effect.effects[0].element.makePositioned();
+ },
+ afterFinishInternal: function(effect) {
+ effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
+ }
+ }, arguments[1] || { }));
+};
+
+Effect.Shake = function(element) {
+ element = $(element);
+ var options = Object.extend({
+ distance: 20,
+ duration: 0.5
+ }, arguments[1] || {});
+ var distance = parseFloat(options.distance);
+ var split = parseFloat(options.duration) / 10.0;
+ var oldStyle = {
+ top: element.getStyle('top'),
+ left: element.getStyle('left') };
+ return new Effect.Move(element,
+ { x: distance, y: 0, duration: split, afterFinishInternal: function(effect) {
+ new Effect.Move(effect.element,
+ { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
+ new Effect.Move(effect.element,
+ { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
+ new Effect.Move(effect.element,
+ { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
+ new Effect.Move(effect.element,
+ { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) {
+ new Effect.Move(effect.element,
+ { x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) {
+ effect.element.undoPositioned().setStyle(oldStyle);
+ }}); }}); }}); }}); }}); }});
+};
+
+Effect.SlideDown = function(element) {
+ element = $(element).cleanWhitespace();
+ // SlideDown need to have the content of the element wrapped in a container element with fixed height!
+ var oldInnerBottom = element.down().getStyle('bottom');
+ var elementDimensions = element.getDimensions();
+ return new Effect.Scale(element, 100, Object.extend({
+ scaleContent: false,
+ scaleX: false,
+ scaleFrom: window.opera ? 0 : 1,
+ scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
+ restoreAfterFinish: true,
+ afterSetup: function(effect) {
+ effect.element.makePositioned();
+ effect.element.down().makePositioned();
+ if (window.opera) effect.element.setStyle({top: ''});
+ effect.element.makeClipping().setStyle({height: '0px'}).show();
+ },
+ afterUpdateInternal: function(effect) {
+ effect.element.down().setStyle({bottom:
+ (effect.dims[0] - effect.element.clientHeight) + 'px' });
+ },
+ afterFinishInternal: function(effect) {
+ effect.element.undoClipping().undoPositioned();
+ effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
+ }, arguments[1] || { })
+ );
+};
+
+Effect.SlideUp = function(element) {
+ element = $(element).cleanWhitespace();
+ var oldInnerBottom = element.down().getStyle('bottom');
+ var elementDimensions = element.getDimensions();
+ return new Effect.Scale(element, window.opera ? 0 : 1,
+ Object.extend({ scaleContent: false,
+ scaleX: false,
+ scaleMode: 'box',
+ scaleFrom: 100,
+ scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
+ restoreAfterFinish: true,
+ afterSetup: function(effect) {
+ effect.element.makePositioned();
+ effect.element.down().makePositioned();
+ if (window.opera) effect.element.setStyle({top: ''});
+ effect.element.makeClipping().show();
+ },
+ afterUpdateInternal: function(effect) {
+ effect.element.down().setStyle({bottom:
+ (effect.dims[0] - effect.element.clientHeight) + 'px' });
+ },
+ afterFinishInternal: function(effect) {
+ effect.element.hide().undoClipping().undoPositioned();
+ effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom});
+ }
+ }, arguments[1] || { })
+ );
+};
+
+// Bug in opera makes the TD containing this element expand for a instance after finish
+Effect.Squish = function(element) {
+ return new Effect.Scale(element, window.opera ? 1 : 0, {
+ restoreAfterFinish: true,
+ beforeSetup: function(effect) {
+ effect.element.makeClipping();
+ },
+ afterFinishInternal: function(effect) {
+ effect.element.hide().undoClipping();
+ }
+ });
+};
+
+Effect.Grow = function(element) {
+ element = $(element);
+ var options = Object.extend({
+ direction: 'center',
+ moveTransition: Effect.Transitions.sinoidal,
+ scaleTransition: Effect.Transitions.sinoidal,
+ opacityTransition: Effect.Transitions.full
+ }, arguments[1] || { });
+ var oldStyle = {
+ top: element.style.top,
+ left: element.style.left,
+ height: element.style.height,
+ width: element.style.width,
+ opacity: element.getInlineOpacity() };
+
+ var dims = element.getDimensions();
+ var initialMoveX, initialMoveY;
+ var moveX, moveY;
+
+ switch (options.direction) {
+ case 'top-left':
+ initialMoveX = initialMoveY = moveX = moveY = 0;
+ break;
+ case 'top-right':
+ initialMoveX = dims.width;
+ initialMoveY = moveY = 0;
+ moveX = -dims.width;
+ break;
+ case 'bottom-left':
+ initialMoveX = moveX = 0;
+ initialMoveY = dims.height;
+ moveY = -dims.height;
+ break;
+ case 'bottom-right':
+ initialMoveX = dims.width;
+ initialMoveY = dims.height;
+ moveX = -dims.width;
+ moveY = -dims.height;
+ break;
+ case 'center':
+ initialMoveX = dims.width / 2;
+ initialMoveY = dims.height / 2;
+ moveX = -dims.width / 2;
+ moveY = -dims.height / 2;
+ break;
+ }
+
+ return new Effect.Move(element, {
+ x: initialMoveX,
+ y: initialMoveY,
+ duration: 0.01,
+ beforeSetup: function(effect) {
+ effect.element.hide().makeClipping().makePositioned();
+ },
+ afterFinishInternal: function(effect) {
+ new Effect.Parallel(
+ [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
+ new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
+ new Effect.Scale(effect.element, 100, {
+ scaleMode: { originalHeight: dims.height, originalWidth: dims.width },
+ sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
+ ], Object.extend({
+ beforeSetup: function(effect) {
+ effect.effects[0].element.setStyle({height: '0px'}).show();
+ },
+ afterFinishInternal: function(effect) {
+ effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);
+ }
+ }, options)
+ );
+ }
+ });
+};
+
+Effect.Shrink = function(element) {
+ element = $(element);
+ var options = Object.extend({
+ direction: 'center',
+ moveTransition: Effect.Transitions.sinoidal,
+ scaleTransition: Effect.Transitions.sinoidal,
+ opacityTransition: Effect.Transitions.none
+ }, arguments[1] || { });
+ var oldStyle = {
+ top: element.style.top,
+ left: element.style.left,
+ height: element.style.height,
+ width: element.style.width,
+ opacity: element.getInlineOpacity() };
+
+ var dims = element.getDimensions();
+ var moveX, moveY;
+
+ switch (options.direction) {
+ case 'top-left':
+ moveX = moveY = 0;
+ break;
+ case 'top-right':
+ moveX = dims.width;
+ moveY = 0;
+ break;
+ case 'bottom-left':
+ moveX = 0;
+ moveY = dims.height;
+ break;
+ case 'bottom-right':
+ moveX = dims.width;
+ moveY = dims.height;
+ break;
+ case 'center':
+ moveX = dims.width / 2;
+ moveY = dims.height / 2;
+ break;
+ }
+
+ return new Effect.Parallel(
+ [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
+ new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
+ new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
+ ], Object.extend({
+ beforeStartInternal: function(effect) {
+ effect.effects[0].element.makePositioned().makeClipping();
+ },
+ afterFinishInternal: function(effect) {
+ effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
+ }, options)
+ );
+};
+
+Effect.Pulsate = function(element) {
+ element = $(element);
+ var options = arguments[1] || { },
+ oldOpacity = element.getInlineOpacity(),
+ transition = options.transition || Effect.Transitions.linear,
+ reverser = function(pos){
+ return 1 - transition((-Math.cos((pos*(options.pulses||5)*2)*Math.PI)/2) + .5);
+ };
+
+ return new Effect.Opacity(element,
+ Object.extend(Object.extend({ duration: 2.0, from: 0,
+ afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
+ }, options), {transition: reverser}));
+};
+
+Effect.Fold = function(element) {
+ element = $(element);
+ var oldStyle = {
+ top: element.style.top,
+ left: element.style.left,
+ width: element.style.width,
+ height: element.style.height };
+ element.makeClipping();
+ return new Effect.Scale(element, 5, Object.extend({
+ scaleContent: false,
+ scaleX: false,
+ afterFinishInternal: function(effect) {
+ new Effect.Scale(element, 1, {
+ scaleContent: false,
+ scaleY: false,
+ afterFinishInternal: function(effect) {
+ effect.element.hide().undoClipping().setStyle(oldStyle);
+ } });
+ }}, arguments[1] || { }));
+};
+
+Effect.Morph = Class.create(Effect.Base, {
+ initialize: function(element) {
+ this.element = $(element);
+ if (!this.element) throw(Effect._elementDoesNotExistError);
+ var options = Object.extend({
+ style: { }
+ }, arguments[1] || { });
+
+ if (!Object.isString(options.style)) this.style = $H(options.style);
+ else {
+ if (options.style.include(':'))
+ this.style = options.style.parseStyle();
+ else {
+ this.element.addClassName(options.style);
+ this.style = $H(this.element.getStyles());
+ this.element.removeClassName(options.style);
+ var css = this.element.getStyles();
+ this.style = this.style.reject(function(style) {
+ return style.value == css[style.key];
+ });
+ options.afterFinishInternal = function(effect) {
+ effect.element.addClassName(effect.options.style);
+ effect.transforms.each(function(transform) {
+ effect.element.style[transform.style] = '';
+ });
+ };
+ }
+ }
+ this.start(options);
+ },
+
+ setup: function(){
+ function parseColor(color){
+ if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
+ color = color.parseColor();
+ return $R(0,2).map(function(i){
+ return parseInt( color.slice(i*2+1,i*2+3), 16 );
+ });
+ }
+ this.transforms = this.style.map(function(pair){
+ var property = pair[0], value = pair[1], unit = null;
+
+ if (value.parseColor('#zzzzzz') != '#zzzzzz') {
+ value = value.parseColor();
+ unit = 'color';
+ } else if (property == 'opacity') {
+ value = parseFloat(value);
+ if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
+ this.element.setStyle({zoom: 1});
+ } else if (Element.CSS_LENGTH.test(value)) {
+ var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/);
+ value = parseFloat(components[1]);
+ unit = (components.length == 3) ? components[2] : null;
+ }
+
+ var originalValue = this.element.getStyle(property);
+ return {
+ style: property.camelize(),
+ originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0),
+ targetValue: unit=='color' ? parseColor(value) : value,
+ unit: unit
+ };
+ }.bind(this)).reject(function(transform){
+ return (
+ (transform.originalValue == transform.targetValue) ||
+ (
+ transform.unit != 'color' &&
+ (isNaN(transform.originalValue) || isNaN(transform.targetValue))
+ )
+ );
+ });
+ },
+ update: function(position) {
+ var style = { }, transform, i = this.transforms.length;
+ while(i--)
+ style[(transform = this.transforms[i]).style] =
+ transform.unit=='color' ? '#'+
+ (Math.round(transform.originalValue[0]+
+ (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() +
+ (Math.round(transform.originalValue[1]+
+ (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() +
+ (Math.round(transform.originalValue[2]+
+ (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() :
+ (transform.originalValue +
+ (transform.targetValue - transform.originalValue) * position).toFixed(3) +
+ (transform.unit === null ? '' : transform.unit);
+ this.element.setStyle(style, true);
+ }
+});
+
+Effect.Transform = Class.create({
+ initialize: function(tracks){
+ this.tracks = [];
+ this.options = arguments[1] || { };
+ this.addTracks(tracks);
+ },
+ addTracks: function(tracks){
+ tracks.each(function(track){
+ track = $H(track);
+ var data = track.values().first();
+ this.tracks.push($H({
+ ids: track.keys().first(),
+ effect: Effect.Morph,
+ options: { style: data }
+ }));
+ }.bind(this));
+ return this;
+ },
+ play: function(){
+ return new Effect.Parallel(
+ this.tracks.map(function(track){
+ var ids = track.get('ids'), effect = track.get('effect'), options = track.get('options');
+ var elements = [$(ids) || $$(ids)].flatten();
+ return elements.map(function(e){ return new effect(e, Object.extend({ sync:true }, options)) });
+ }).flatten(),
+ this.options
+ );
+ }
+});
+
+Element.CSS_PROPERTIES = $w(
+ 'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' +
+ 'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
+ 'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
+ 'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
+ 'fontSize fontWeight height left letterSpacing lineHeight ' +
+ 'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
+ 'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
+ 'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
+ 'right textIndent top width wordSpacing zIndex');
+
+Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;
+
+String.__parseStyleElement = document.createElement('div');
+String.prototype.parseStyle = function(){
+ var style, styleRules = $H();
+ if (Prototype.Browser.WebKit)
+ style = new Element('div',{style:this}).style;
+ else {
+ String.__parseStyleElement.innerHTML = '<div style="' + this + '"></div>';
+ style = String.__parseStyleElement.childNodes[0].style;
+ }
+
+ Element.CSS_PROPERTIES.each(function(property){
+ if (style[property]) styleRules.set(property, style[property]);
+ });
+
+ if (Prototype.Browser.IE && this.include('opacity'))
+ styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);
+
+ return styleRules;
+};
+
+if (document.defaultView && document.defaultView.getComputedStyle) {
+ Element.getStyles = function(element) {
+ var css = document.defaultView.getComputedStyle($(element), null);
+ return Element.CSS_PROPERTIES.inject({ }, function(styles, property) {
+ styles[property] = css[property];
+ return styles;
+ });
+ };
+} else {
+ Element.getStyles = function(element) {
+ element = $(element);
+ var css = element.currentStyle, styles;
+ styles = Element.CSS_PROPERTIES.inject({ }, function(results, property) {
+ results[property] = css[property];
+ return results;
+ });
+ if (!styles.opacity) styles.opacity = element.getOpacity();
+ return styles;
+ };
+}
+
+Effect.Methods = {
+ morph: function(element, style) {
+ element = $(element);
+ new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { }));
+ return element;
+ },
+ visualEffect: function(element, effect, options) {
+ element = $(element);
+ var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1);
+ new Effect[klass](element, options);
+ return element;
+ },
+ highlight: function(element, options) {
+ element = $(element);
+ new Effect.Highlight(element, options);
+ return element;
+ }
+};
+
+$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+
+ 'pulsate shake puff squish switchOff dropOut').each(
+ function(effect) {
+ Effect.Methods[effect] = function(element, options){
+ element = $(element);
+ Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options);
+ return element;
+ };
+ }
+);
+
+$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each(
+ function(f) { Effect.Methods[f] = Element[f]; }
+);
+
+Element.addMethods(Effect.Methods);
+
+
+// script.aculo.us controls.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
+
+// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// (c) 2005-2009 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
+// (c) 2005-2009 Jon Tirsen (http://www.tirsen.com)
+// Contributors:
+// Richard Livsey
+// Rahul Bhargava
+// Rob Wills
+//
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
+
+// Autocompleter.Base handles all the autocompletion functionality
+// that's independent of the data source for autocompletion. This
+// includes drawing the autocompletion menu, observing keyboard
+// and mouse events, and similar.
+//
+// Specific autocompleters need to provide, at the very least,
+// a getUpdatedChoices function that will be invoked every time
+// the text inside the monitored textbox changes. This method
+// should get the text for which to provide autocompletion by
+// invoking this.getToken(), NOT by directly accessing
+// this.element.value. This is to allow incremental tokenized
+// autocompletion. Specific auto-completion logic (AJAX, etc)
+// belongs in getUpdatedChoices.
+//
+// Tokenized incremental autocompletion is enabled automatically
+// when an autocompleter is instantiated with the 'tokens' option
+// in the options parameter, e.g.:
+// new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
+// will incrementally autocomplete with a comma as the token.
+// Additionally, ',' in the above example can be replaced with
+// a token array, e.g. { tokens: [',', '\n'] } which
+// enables autocompletion on multiple tokens. This is most
+// useful when one of the tokens is \n (a newline), as it
+// allows smart autocompletion after linebreaks.
+
+if(typeof Effect == 'undefined')
+ throw("controls.js requires including script.aculo.us' effects.js library");
+
+var Autocompleter = { };
+Autocompleter.Base = Class.create({
+ baseInitialize: function(element, update, options) {
+ element = $(element);
+ this.element = element;
+ this.update = $(update);
+ this.hasFocus = false;
+ this.changed = false;
+ this.active = false;
+ this.index = 0;
+ this.entryCount = 0;
+ this.oldElementValue = this.element.value;
+
+ if(this.setOptions)
+ this.setOptions(options);
+ else
+ this.options = options || { };
+
+ this.options.paramName = this.options.paramName || this.element.name;
+ this.options.tokens = this.options.tokens || [];
+ this.options.frequency = this.options.frequency || 0.4;
+ this.options.minChars = this.options.minChars || 1;
+ this.options.onShow = this.options.onShow ||
+ function(element, update){
+ if(!update.style.position || update.style.position=='absolute') {
+ update.style.position = 'absolute';
+ Position.clone(element, update, {
+ setHeight: false,
+ offsetTop: element.offsetHeight
+ });
+ }
+ Effect.Appear(update,{duration:0.15});
+ };
+ this.options.onHide = this.options.onHide ||
+ function(element, update){ new Effect.Fade(update,{duration:0.15}) };
+
+ if(typeof(this.options.tokens) == 'string')
+ this.options.tokens = new Array(this.options.tokens);
+ // Force carriage returns as token delimiters anyway
+ if (!this.options.tokens.include('\n'))
+ this.options.tokens.push('\n');
+
+ this.observer = null;
+
+ this.element.setAttribute('autocomplete','off');
+
+ Element.hide(this.update);
+
+ Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
+ Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
+ },
+
+ show: function() {
+ if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
+ if(!this.iefix &&
+ (Prototype.Browser.IE) &&
+ (Element.getStyle(this.update, 'position')=='absolute')) {
+ new Insertion.After(this.update,
+ '<iframe id="' + this.update.id + '_iefix" '+
+ 'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
+ 'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
+ this.iefix = $(this.update.id+'_iefix');
+ }
+ if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
+ },
+
+ fixIEOverlapping: function() {
+ Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
+ this.iefix.style.zIndex = 1;
+ this.update.style.zIndex = 2;
+ Element.show(this.iefix);
+ },
+
+ hide: function() {
+ this.stopIndicator();
+ if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
+ if(this.iefix) Element.hide(this.iefix);
+ },
+
+ startIndicator: function() {
+ if(this.options.indicator) Element.show(this.options.indicator);
+ },
+
+ stopIndicator: function() {
+ if(this.options.indicator) Element.hide(this.options.indicator);
+ },
+
+ onKeyPress: function(event) {
+ if(this.active)
+ switch(event.keyCode) {
+ case Event.KEY_TAB:
+ case Event.KEY_RETURN:
+ this.selectEntry();
+ Event.stop(event);
+ case Event.KEY_ESC:
+ this.hide();
+ this.active = false;
+ Event.stop(event);
+ return;
+ case Event.KEY_LEFT:
+ case Event.KEY_RIGHT:
+ return;
+ case Event.KEY_UP:
+ this.markPrevious();
+ this.render();
+ Event.stop(event);
+ return;
+ case Event.KEY_DOWN:
+ this.markNext();
+ this.render();
+ Event.stop(event);
+ return;
+ }
+ else
+ if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
+ (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
+
+ this.changed = true;
+ this.hasFocus = true;
+
+ if(this.observer) clearTimeout(this.observer);
+ this.observer =
+ setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
+ },
+
+ activate: function() {
+ this.changed = false;
+ this.hasFocus = true;
+ this.getUpdatedChoices();
+ },
+
+ onHover: function(event) {
+ var element = Event.findElement(event, 'LI');
+ if(this.index != element.autocompleteIndex)
+ {
+ this.index = element.autocompleteIndex;
+ this.render();
+ }
+ Event.stop(event);
+ },
+
+ onClick: function(event) {
+ var element = Event.findElement(event, 'LI');
+ this.index = element.autocompleteIndex;
+ this.selectEntry();
+ this.hide();
+ },
+
+ onBlur: function(event) {
+ // needed to make click events working
+ setTimeout(this.hide.bind(this), 250);
+ this.hasFocus = false;
+ this.active = false;
+ },
+
+ render: function() {
+ if(this.entryCount > 0) {
+ for (var i = 0; i < this.entryCount; i++)
+ this.index==i ?
+ Element.addClassName(this.getEntry(i),"selected") :
+ Element.removeClassName(this.getEntry(i),"selected");
+ if(this.hasFocus) {
+ this.show();
+ this.active = true;
+ }
+ } else {
+ this.active = false;
+ this.hide();
+ }
+ },
+
+ markPrevious: function() {
+ if(this.index > 0) this.index--;
+ else this.index = this.entryCount-1;
+ this.getEntry(this.index).scrollIntoView(true);
+ },
+
+ markNext: function() {
+ if(this.index < this.entryCount-1) this.index++;
+ else this.index = 0;
+ this.getEntry(this.index).scrollIntoView(false);
+ },
+
+ getEntry: function(index) {
+ return this.update.firstChild.childNodes[index];
+ },
+
+ getCurrentEntry: function() {
+ return this.getEntry(this.index);
+ },
+
+ selectEntry: function() {
+ this.active = false;
+ this.updateElement(this.getCurrentEntry());
+ },
+
+ updateElement: function(selectedElement) {
+ if (this.options.updateElement) {
+ this.options.updateElement(selectedElement);
+ return;
+ }
+ var value = '';
+ if (this.options.select) {
+ var nodes = $(selectedElement).select('.' + this.options.select) || [];
+ if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
+ } else
+ value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
+
+ var bounds = this.getTokenBounds();
+ if (bounds[0] != -1) {
+ var newValue = this.element.value.substr(0, bounds[0]);
+ var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
+ if (whitespace)
+ newValue += whitespace[0];
+ this.element.value = newValue + value + this.element.value.substr(bounds[1]);
+ } else {
+ this.element.value = value;
+ }
+ this.oldElementValue = this.element.value;
+ this.element.focus();
+
+ if (this.options.afterUpdateElement)
+ this.options.afterUpdateElement(this.element, selectedElement);
+ },
+
+ updateChoices: function(choices) {
+ if(!this.changed && this.hasFocus) {
+ this.update.innerHTML = choices;
+ Element.cleanWhitespace(this.update);
+ Element.cleanWhitespace(this.update.down());
+
+ if(this.update.firstChild && this.update.down().childNodes) {
+ this.entryCount =
+ this.update.down().childNodes.length;
+ for (var i = 0; i < this.entryCount; i++) {
+ var entry = this.getEntry(i);
+ entry.autocompleteIndex = i;
+ this.addObservers(entry);
+ }
+ } else {
+ this.entryCount = 0;
+ }
+
+ this.stopIndicator();
+ this.index = 0;
+
+ if(this.entryCount==1 && this.options.autoSelect) {
+ this.selectEntry();
+ this.hide();
+ } else {
+ this.render();
+ }
+ }
+ },
+
+ addObservers: function(element) {
+ Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
+ Event.observe(element, "click", this.onClick.bindAsEventListener(this));
+ },
+
+ onObserverEvent: function() {
+ this.changed = false;
+ this.tokenBounds = null;
+ if(this.getToken().length>=this.options.minChars) {
+ this.getUpdatedChoices();
+ } else {
+ this.active = false;
+ this.hide();
+ }
+ this.oldElementValue = this.element.value;
+ },
+
+ getToken: function() {
+ var bounds = this.getTokenBounds();
+ return this.element.value.substring(bounds[0], bounds[1]).strip();
+ },
+
+ getTokenBounds: function() {
+ if (null != this.tokenBounds) return this.tokenBounds;
+ var value = this.element.value;
+ if (value.strip().empty()) return [-1, 0];
+ var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
+ var offset = (diff == this.oldElementValue.length ? 1 : 0);
+ var prevTokenPos = -1, nextTokenPos = value.length;
+ var tp;
+ for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
+ tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
+ if (tp > prevTokenPos) prevTokenPos = tp;
+ tp = value.indexOf(this.options.tokens[index], diff + offset);
+ if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
+ }
+ return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
+ }
+});
+
+Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
+ var boundary = Math.min(newS.length, oldS.length);
+ for (var index = 0; index < boundary; ++index)
+ if (newS[index] != oldS[index])
+ return index;
+ return boundary;
+};
+
+Ajax.Autocompleter = Class.create(Autocompleter.Base, {
+ initialize: function(element, update, url, options) {
+ this.baseInitialize(element, update, options);
+ this.options.asynchronous = true;
+ this.options.onComplete = this.onComplete.bind(this);
+ this.options.defaultParams = this.options.parameters || null;
+ this.url = url;
+ },
+
+ getUpdatedChoices: function() {
+ this.startIndicator();
+
+ var entry = encodeURIComponent(this.options.paramName) + '=' +
+ encodeURIComponent(this.getToken());
+
+ this.options.parameters = this.options.callback ?
+ this.options.callback(this.element, entry) : entry;
+
+ if(this.options.defaultParams)
+ this.options.parameters += '&' + this.options.defaultParams;
+
+ new Ajax.Request(this.url, this.options);
+ },
+
+ onComplete: function(request) {
+ this.updateChoices(request.responseText);
+ }
+});
+
+// The local array autocompleter. Used when you'd prefer to
+// inject an array of autocompletion options into the page, rather
+// than sending out Ajax queries, which can be quite slow sometimes.
+//
+// The constructor takes four parameters. The first two are, as usual,
+// the id of the monitored textbox, and id of the autocompletion menu.
+// The third is the array you want to autocomplete from, and the fourth
+// is the options block.
+//
+// Extra local autocompletion options:
+// - choices - How many autocompletion choices to offer
+//
+// - partialSearch - If false, the autocompleter will match entered
+// text only at the beginning of strings in the
+// autocomplete array. Defaults to true, which will
+// match text at the beginning of any *word* in the
+// strings in the autocomplete array. If you want to
+// search anywhere in the string, additionally set
+// the option fullSearch to true (default: off).
+//
+// - fullSsearch - Search anywhere in autocomplete array strings.
+//
+// - partialChars - How many characters to enter before triggering
+// a partial match (unlike minChars, which defines
+// how many characters are required to do any match
+// at all). Defaults to 2.
+//
+// - ignoreCase - Whether to ignore case when autocompleting.
+// Defaults to true.
+//
+// It's possible to pass in a custom function as the 'selector'
+// option, if you prefer to write your own autocompletion logic.
+// In that case, the other options above will not apply unless
+// you support them.
+
+Autocompleter.Local = Class.create(Autocompleter.Base, {
+ initialize: function(element, update, array, options) {
+ this.baseInitialize(element, update, options);
+ this.options.array = array;
+ },
+
+ getUpdatedChoices: function() {
+ this.updateChoices(this.options.selector(this));
+ },
+
+ setOptions: function(options) {
+ this.options = Object.extend({
+ choices: 10,
+ partialSearch: true,
+ partialChars: 2,
+ ignoreCase: true,
+ fullSearch: false,
+ selector: function(instance) {
+ var ret = []; // Beginning matches
+ var partial = []; // Inside matches
+ var entry = instance.getToken();
+ var count = 0;
+
+ for (var i = 0; i < instance.options.array.length &&
+ ret.length < instance.options.choices ; i++) {
+
+ var elem = instance.options.array[i];
+ var foundPos = instance.options.ignoreCase ?
+ elem.toLowerCase().indexOf(entry.toLowerCase()) :
+ elem.indexOf(entry);
+
+ while (foundPos != -1) {
+ if (foundPos == 0 && elem.length != entry.length) {
+ ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
+ elem.substr(entry.length) + "</li>");
+ break;
+ } else if (entry.length >= instance.options.partialChars &&
+ instance.options.partialSearch && foundPos != -1) {
+ if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
+ partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
+ elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
+ foundPos + entry.length) + "</li>");
+ break;
+ }
+ }
+
+ foundPos = instance.options.ignoreCase ?
+ elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
+ elem.indexOf(entry, foundPos + 1);
+
+ }
+ }
+ if (partial.length)
+ ret = ret.concat(partial.slice(0, instance.options.choices - ret.length));
+ return "<ul>" + ret.join('') + "</ul>";
+ }
+ }, options || { });
+ }
+});
+
+// AJAX in-place editor and collection editor
+// Full rewrite by Christophe Porteneuve <tdd@tddsworld.com> (April 2007).
+
+// Use this if you notice weird scrolling problems on some browsers,
+// the DOM might be a bit confused when this gets called so do this
+// waits 1 ms (with setTimeout) until it does the activation
+Field.scrollFreeActivate = function(field) {
+ setTimeout(function() {
+ Field.activate(field);
+ }, 1);
+};
+
+Ajax.InPlaceEditor = Class.create({
+ initialize: function(element, url, options) {
+ this.url = url;
+ this.element = element = $(element);
+ this.prepareOptions();
+ this._controls = { };
+ arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
+ Object.extend(this.options, options || { });
+ if (!this.options.formId && this.element.id) {
+ this.options.formId = this.element.id + '-inplaceeditor';
+ if ($(this.options.formId))
+ this.options.formId = '';
+ }
+ if (this.options.externalControl)
+ this.options.externalControl = $(this.options.externalControl);
+ if (!this.options.externalControl)
+ this.options.externalControlOnly = false;
+ this._originalBackground = this.element.getStyle('background-color') || 'transparent';
+ this.element.title = this.options.clickToEditText;
+ this._boundCancelHandler = this.handleFormCancellation.bind(this);
+ this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
+ this._boundFailureHandler = this.handleAJAXFailure.bind(this);
+ this._boundSubmitHandler = this.handleFormSubmission.bind(this);
+ this._boundWrapperHandler = this.wrapUp.bind(this);
+ this.registerListeners();
+ },
+ checkForEscapeOrReturn: function(e) {
+ if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
+ if (Event.KEY_ESC == e.keyCode)
+ this.handleFormCancellation(e);
+ else if (Event.KEY_RETURN == e.keyCode)
+ this.handleFormSubmission(e);
+ },
+ createControl: function(mode, handler, extraClasses) {
+ var control = this.options[mode + 'Control'];
+ var text = this.options[mode + 'Text'];
+ if ('button' == control) {
+ var btn = document.createElement('input');
+ btn.type = 'submit';
+ btn.value = text;
+ btn.className = 'editor_' + mode + '_button';
+ if ('cancel' == mode)
+ btn.onclick = this._boundCancelHandler;
+ this._form.appendChild(btn);
+ this._controls[mode] = btn;
+ } else if ('link' == control) {
+ var link = document.createElement('a');
+ link.href = '#';
+ link.appendChild(document.createTextNode(text));
+ link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
+ link.className = 'editor_' + mode + '_link';
+ if (extraClasses)
+ link.className += ' ' + extraClasses;
+ this._form.appendChild(link);
+ this._controls[mode] = link;
+ }
+ },
+ createEditField: function() {
+ var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
+ var fld;
+ if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
+ fld = document.createElement('input');
+ fld.type = 'text';
+ var size = this.options.size || this.options.cols || 0;
+ if (0 < size) fld.size = size;
+ } else {
+ fld = document.createElement('textarea');
+ fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
+ fld.cols = this.options.cols || 40;
+ }
+ fld.name = this.options.paramName;
+ fld.value = text; // No HTML breaks conversion anymore
+ fld.className = 'editor_field';
+ if (this.options.submitOnBlur)
+ fld.onblur = this._boundSubmitHandler;
+ this._controls.editor = fld;
+ if (this.options.loadTextURL)
+ this.loadExternalText();
+ this._form.appendChild(this._controls.editor);
+ },
+ createForm: function() {
+ var ipe = this;
+ function addText(mode, condition) {
+ var text = ipe.options['text' + mode + 'Controls'];
+ if (!text || condition === false) return;
+ ipe._form.appendChild(document.createTextNode(text));
+ };
+ this._form = $(document.createElement('form'));
+ this._form.id = this.options.formId;
+ this._form.addClassName(this.options.formClassName);
+ this._form.onsubmit = this._boundSubmitHandler;
+ this.createEditField();
+ if ('textarea' == this._controls.editor.tagName.toLowerCase())
+ this._form.appendChild(document.createElement('br'));
+ if (this.options.onFormCustomization)
+ this.options.onFormCustomization(this, this._form);
+ addText('Before', this.options.okControl || this.options.cancelControl);
+ this.createControl('ok', this._boundSubmitHandler);
+ addText('Between', this.options.okControl && this.options.cancelControl);
+ this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');
+ addText('After', this.options.okControl || this.options.cancelControl);
+ },
+ destroy: function() {
+ if (this._oldInnerHTML)
+ this.element.innerHTML = this._oldInnerHTML;
+ this.leaveEditMode();
+ this.unregisterListeners();
+ },
+ enterEditMode: function(e) {
+ if (this._saving || this._editing) return;
+ this._editing = true;
+ this.triggerCallback('onEnterEditMode');
+ if (this.options.externalControl)
+ this.options.externalControl.hide();
+ this.element.hide();
+ this.createForm();
+ this.element.parentNode.insertBefore(this._form, this.element);
+ if (!this.options.loadTextURL)
+ this.postProcessEditField();
+ if (e) Event.stop(e);
+ },
+ enterHover: function(e) {
+ if (this.options.hoverClassName)
+ this.element.addClassName(this.options.hoverClassName);
+ if (this._saving) return;
+ this.triggerCallback('onEnterHover');
+ },
+ getText: function() {
+ return this.element.innerHTML.unescapeHTML();
+ },
+ handleAJAXFailure: function(transport) {
+ this.triggerCallback('onFailure', transport);
+ if (this._oldInnerHTML) {
+ this.element.innerHTML = this._oldInnerHTML;
+ this._oldInnerHTML = null;
+ }
+ },
+ handleFormCancellation: function(e) {
+ this.wrapUp();
+ if (e) Event.stop(e);
+ },
+ handleFormSubmission: function(e) {
+ var form = this._form;
+ var value = $F(this._controls.editor);
+ this.prepareSubmission();
+ var params = this.options.callback(form, value) || '';
+ if (Object.isString(params))
+ params = params.toQueryParams();
+ params.editorId = this.element.id;
+ if (this.options.htmlResponse) {
+ var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: params,
+ onComplete: this._boundWrapperHandler,
+ onFailure: this._boundFailureHandler
+ });
+ new Ajax.Updater({ success: this.element }, this.url, options);
+ } else {
+ var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: params,
+ onComplete: this._boundWrapperHandler,
+ onFailure: this._boundFailureHandler
+ });
+ new Ajax.Request(this.url, options);
+ }
+ if (e) Event.stop(e);
+ },
+ leaveEditMode: function() {
+ this.element.removeClassName(this.options.savingClassName);
+ this.removeForm();
+ this.leaveHover();
+ this.element.style.backgroundColor = this._originalBackground;
+ this.element.show();
+ if (this.options.externalControl)
+ this.options.externalControl.show();
+ this._saving = false;
+ this._editing = false;
+ this._oldInnerHTML = null;
+ this.triggerCallback('onLeaveEditMode');
+ },
+ leaveHover: function(e) {
+ if (this.options.hoverClassName)
+ this.element.removeClassName(this.options.hoverClassName);
+ if (this._saving) return;
+ this.triggerCallback('onLeaveHover');
+ },
+ loadExternalText: function() {
+ this._form.addClassName(this.options.loadingClassName);
+ this._controls.editor.disabled = true;
+ var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: 'editorId=' + encodeURIComponent(this.element.id),
+ onComplete: Prototype.emptyFunction,
+ onSuccess: function(transport) {
+ this._form.removeClassName(this.options.loadingClassName);
+ var text = transport.responseText;
+ if (this.options.stripLoadedTextTags)
+ text = text.stripTags();
+ this._controls.editor.value = text;
+ this._controls.editor.disabled = false;
+ this.postProcessEditField();
+ }.bind(this),
+ onFailure: this._boundFailureHandler
+ });
+ new Ajax.Request(this.options.loadTextURL, options);
+ },
+ postProcessEditField: function() {
+ var fpc = this.options.fieldPostCreation;
+ if (fpc)
+ $(this._controls.editor)['focus' == fpc ? 'focus' : 'activate']();
+ },
+ prepareOptions: function() {
+ this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions);
+ Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks);
+ [this._extraDefaultOptions].flatten().compact().each(function(defs) {
+ Object.extend(this.options, defs);
+ }.bind(this));
+ },
+ prepareSubmission: function() {
+ this._saving = true;
+ this.removeForm();
+ this.leaveHover();
+ this.showSaving();
+ },
+ registerListeners: function() {
+ this._listeners = { };
+ var listener;
+ $H(Ajax.InPlaceEditor.Listeners).each(function(pair) {
+ listener = this[pair.value].bind(this);
+ this._listeners[pair.key] = listener;
+ if (!this.options.externalControlOnly)
+ this.element.observe(pair.key, listener);
+ if (this.options.externalControl)
+ this.options.externalControl.observe(pair.key, listener);
+ }.bind(this));
+ },
+ removeForm: function() {
+ if (!this._form) return;
+ this._form.remove();
+ this._form = null;
+ this._controls = { };
+ },
+ showSaving: function() {
+ this._oldInnerHTML = this.element.innerHTML;
+ this.element.innerHTML = this.options.savingText;
+ this.element.addClassName(this.options.savingClassName);
+ this.element.style.backgroundColor = this._originalBackground;
+ this.element.show();
+ },
+ triggerCallback: function(cbName, arg) {
+ if ('function' == typeof this.options[cbName]) {
+ this.options[cbName](this, arg);
+ }
+ },
+ unregisterListeners: function() {
+ $H(this._listeners).each(function(pair) {
+ if (!this.options.externalControlOnly)
+ this.element.stopObserving(pair.key, pair.value);
+ if (this.options.externalControl)
+ this.options.externalControl.stopObserving(pair.key, pair.value);
+ }.bind(this));
+ },
+ wrapUp: function(transport) {
+ this.leaveEditMode();
+ // Can't use triggerCallback due to backward compatibility: requires
+ // binding + direct element
+ this._boundComplete(transport, this.element);
+ }
+});
+
+Object.extend(Ajax.InPlaceEditor.prototype, {
+ dispose: Ajax.InPlaceEditor.prototype.destroy
+});
+
+Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
+ initialize: function($super, element, url, options) {
+ this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions;
+ $super(element, url, options);
+ },
+
+ createEditField: function() {
+ var list = document.createElement('select');
+ list.name = this.options.paramName;
+ list.size = 1;
+ this._controls.editor = list;
+ this._collection = this.options.collection || [];
+ if (this.options.loadCollectionURL)
+ this.loadCollection();
+ else
+ this.checkForExternalText();
+ this._form.appendChild(this._controls.editor);
+ },
+
+ loadCollection: function() {
+ this._form.addClassName(this.options.loadingClassName);
+ this.showLoadingText(this.options.loadingCollectionText);
+ var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: 'editorId=' + encodeURIComponent(this.element.id),
+ onComplete: Prototype.emptyFunction,
+ onSuccess: function(transport) {
+ var js = transport.responseText.strip();
+ if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
+ throw('Server returned an invalid collection representation.');
+ this._collection = eval(js);
+ this.checkForExternalText();
+ }.bind(this),
+ onFailure: this.onFailure
+ });
+ new Ajax.Request(this.options.loadCollectionURL, options);
+ },
+
+ showLoadingText: function(text) {
+ this._controls.editor.disabled = true;
+ var tempOption = this._controls.editor.firstChild;
+ if (!tempOption) {
+ tempOption = document.createElement('option');
+ tempOption.value = '';
+ this._controls.editor.appendChild(tempOption);
+ tempOption.selected = true;
+ }
+ tempOption.update((text || '').stripScripts().stripTags());
+ },
+
+ checkForExternalText: function() {
+ this._text = this.getText();
+ if (this.options.loadTextURL)
+ this.loadExternalText();
+ else
+ this.buildOptionList();
+ },
+
+ loadExternalText: function() {
+ this.showLoadingText(this.options.loadingText);
+ var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: 'editorId=' + encodeURIComponent(this.element.id),
+ onComplete: Prototype.emptyFunction,
+ onSuccess: function(transport) {
+ this._text = transport.responseText.strip();
+ this.buildOptionList();
+ }.bind(this),
+ onFailure: this.onFailure
+ });
+ new Ajax.Request(this.options.loadTextURL, options);
+ },
+
+ buildOptionList: function() {
+ this._form.removeClassName(this.options.loadingClassName);
+ this._collection = this._collection.map(function(entry) {
+ return 2 === entry.length ? entry : [entry, entry].flatten();
+ });
+ var marker = ('value' in this.options) ? this.options.value : this._text;
+ var textFound = this._collection.any(function(entry) {
+ return entry[0] == marker;
+ }.bind(this));
+ this._controls.editor.update('');
+ var option;
+ this._collection.each(function(entry, index) {
+ option = document.createElement('option');
+ option.value = entry[0];
+ option.selected = textFound ? entry[0] == marker : 0 == index;
+ option.appendChild(document.createTextNode(entry[1]));
+ this._controls.editor.appendChild(option);
+ }.bind(this));
+ this._controls.editor.disabled = false;
+ Field.scrollFreeActivate(this._controls.editor);
+ }
+});
+
+//**** DEPRECATION LAYER FOR InPlace[Collection]Editor! ****
+//**** This only exists for a while, in order to let ****
+//**** users adapt to the new API. Read up on the new ****
+//**** API and convert your code to it ASAP! ****
+
+Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) {
+ if (!options) return;
+ function fallback(name, expr) {
+ if (name in options || expr === undefined) return;
+ options[name] = expr;
+ };
+ fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' :
+ options.cancelLink == options.cancelButton == false ? false : undefined)));
+ fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' :
+ options.okLink == options.okButton == false ? false : undefined)));
+ fallback('highlightColor', options.highlightcolor);
+ fallback('highlightEndColor', options.highlightendcolor);
+};
+
+Object.extend(Ajax.InPlaceEditor, {
+ DefaultOptions: {
+ ajaxOptions: { },
+ autoRows: 3, // Use when multi-line w/ rows == 1
+ cancelControl: 'link', // 'link'|'button'|false
+ cancelText: 'cancel',
+ clickToEditText: 'Click to edit',
+ externalControl: null, // id|elt
+ externalControlOnly: false,
+ fieldPostCreation: 'activate', // 'activate'|'focus'|false
+ formClassName: 'inplaceeditor-form',
+ formId: null, // id|elt
+ highlightColor: '#ffff99',
+ highlightEndColor: '#ffffff',
+ hoverClassName: '',
+ htmlResponse: true,
+ loadingClassName: 'inplaceeditor-loading',
+ loadingText: 'Loading...',
+ okControl: 'button', // 'link'|'button'|false
+ okText: 'ok',
+ paramName: 'value',
+ rows: 1, // If 1 and multi-line, uses autoRows
+ savingClassName: 'inplaceeditor-saving',
+ savingText: 'Saving...',
+ size: 0,
+ stripLoadedTextTags: false,
+ submitOnBlur: false,
+ textAfterControls: '',
+ textBeforeControls: '',
+ textBetweenControls: ''
+ },
+ DefaultCallbacks: {
+ callback: function(form) {
+ return Form.serialize(form);
+ },
+ onComplete: function(transport, element) {
+ // For backward compatibility, this one is bound to the IPE, and passes
+ // the element directly. It was too often customized, so we don't break it.
+ new Effect.Highlight(element, {
+ startcolor: this.options.highlightColor, keepBackgroundImage: true });
+ },
+ onEnterEditMode: null,
+ onEnterHover: function(ipe) {
+ ipe.element.style.backgroundColor = ipe.options.highlightColor;
+ if (ipe._effect)
+ ipe._effect.cancel();
+ },
+ onFailure: function(transport, ipe) {
+ alert('Error communication with the server: ' + transport.responseText.stripTags());
+ },
+ onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls.
+ onLeaveEditMode: null,
+ onLeaveHover: function(ipe) {
+ ipe._effect = new Effect.Highlight(ipe.element, {
+ startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor,
+ restorecolor: ipe._originalBackground, keepBackgroundImage: true
+ });
+ }
+ },
+ Listeners: {
+ click: 'enterEditMode',
+ keydown: 'checkForEscapeOrReturn',
+ mouseover: 'enterHover',
+ mouseout: 'leaveHover'
+ }
+});
+
+Ajax.InPlaceCollectionEditor.DefaultOptions = {
+ loadingCollectionText: 'Loading options...'
+};
+
+// Delayed observer, like Form.Element.Observer,
+// but waits for delay after last key input
+// Ideal for live-search fields
+
+Form.Element.DelayedObserver = Class.create({
+ initialize: function(element, delay, callback) {
+ this.delay = delay || 0.5;
+ this.element = $(element);
+ this.callback = callback;
+ this.timer = null;
+ this.lastValue = $F(this.element);
+ Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
+ },
+ delayedListener: function(event) {
+ if(this.lastValue == $F(this.element)) return;
+ if(this.timer) clearTimeout(this.timer);
+ this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
+ this.lastValue = $F(this.element);
+ },
+ onTimerEvent: function() {
+ this.timer = null;
+ this.callback(this.element, $F(this.element));
+ }
+});
+
+
+// script.aculo.us dragdrop.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
+
+// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+//
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
+
+if(Object.isUndefined(Effect))
+ throw("dragdrop.js requires including script.aculo.us' effects.js library");
+
+var Droppables = {
+ drops: [],
+
+ remove: function(element) {
+ this.drops = this.drops.reject(function(d) { return d.element==$(element) });
+ },
+
+ add: function(element) {
+ element = $(element);
+ var options = Object.extend({
+ greedy: true,
+ hoverclass: null,
+ tree: false
+ }, arguments[1] || { });
+
+ // cache containers
+ if(options.containment) {
+ options._containers = [];
+ var containment = options.containment;
+ if(Object.isArray(containment)) {
+ containment.each( function(c) { options._containers.push($(c)) });
+ } else {
+ options._containers.push($(containment));
+ }
+ }
+
+ if(options.accept) options.accept = [options.accept].flatten();
+
+ Element.makePositioned(element); // fix IE
+ options.element = element;
+
+ this.drops.push(options);
+ },
+
+ findDeepestChild: function(drops) {
+ deepest = drops[0];
+
+ for (i = 1; i < drops.length; ++i)
+ if (Element.isParent(drops[i].element, deepest.element))
+ deepest = drops[i];
+
+ return deepest;
+ },
+
+ isContained: function(element, drop) {
+ var containmentNode;
+ if(drop.tree) {
+ containmentNode = element.treeNode;
+ } else {
+ containmentNode = element.parentNode;
+ }
+ return drop._containers.detect(function(c) { return containmentNode == c });
+ },
+
+ isAffected: function(point, element, drop) {
+ return (
+ (drop.element!=element) &&
+ ((!drop._containers) ||
+ this.isContained(element, drop)) &&
+ ((!drop.accept) ||
+ (Element.classNames(element).detect(
+ function(v) { return drop.accept.include(v) } ) )) &&
+ Position.within(drop.element, point[0], point[1]) );
+ },
+
+ deactivate: function(drop) {
+ if(drop.hoverclass)
+ Element.removeClassName(drop.element, drop.hoverclass);
+ this.last_active = null;
+ },
+
+ activate: function(drop) {
+ if(drop.hoverclass)
+ Element.addClassName(drop.element, drop.hoverclass);
+ this.last_active = drop;
+ },
+
+ show: function(point, element) {
+ if(!this.drops.length) return;
+ var drop, affected = [];
+
+ this.drops.each( function(drop) {
+ if(Droppables.isAffected(point, element, drop))
+ affected.push(drop);
+ });
+
+ if(affected.length>0)
+ drop = Droppables.findDeepestChild(affected);
+
+ if(this.last_active && this.last_active != drop) this.deactivate(this.last_active);
+ if (drop) {
+ Position.within(drop.element, point[0], point[1]);
+ if(drop.onHover)
+ drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
+
+ if (drop != this.last_active) Droppables.activate(drop);
+ }
+ },
+
+ fire: function(event, element) {
+ if(!this.last_active) return;
+ Position.prepare();
+
+ if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
+ if (this.last_active.onDrop) {
+ this.last_active.onDrop(element, this.last_active.element, event);
+ return true;
+ }
+ },
+
+ reset: function() {
+ if(this.last_active)
+ this.deactivate(this.last_active);
+ }
+};
+
+var Draggables = {
+ drags: [],
+ observers: [],
+
+ register: function(draggable) {
+ if(this.drags.length == 0) {
+ this.eventMouseUp = this.endDrag.bindAsEventListener(this);
+ this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
+ this.eventKeypress = this.keyPress.bindAsEventListener(this);
+
+ Event.observe(document, "mouseup", this.eventMouseUp);
+ Event.observe(document, "mousemove", this.eventMouseMove);
+ Event.observe(document, "keypress", this.eventKeypress);
+ }
+ this.drags.push(draggable);
+ },
+
+ unregister: function(draggable) {
+ this.drags = this.drags.reject(function(d) { return d==draggable });
+ if(this.drags.length == 0) {
+ Event.stopObserving(document, "mouseup", this.eventMouseUp);
+ Event.stopObserving(document, "mousemove", this.eventMouseMove);
+ Event.stopObserving(document, "keypress", this.eventKeypress);
+ }
+ },
+
+ activate: function(draggable) {
+ if(draggable.options.delay) {
+ this._timeout = setTimeout(function() {
+ Draggables._timeout = null;
+ window.focus();
+ Draggables.activeDraggable = draggable;
+ }.bind(this), draggable.options.delay);
+ } else {
+ window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
+ this.activeDraggable = draggable;
+ }
+ },
+
+ deactivate: function() {
+ this.activeDraggable = null;
+ },
+
+ updateDrag: function(event) {
+ if(!this.activeDraggable) return;
+ var pointer = [Event.pointerX(event), Event.pointerY(event)];
+ // Mozilla-based browsers fire successive mousemove events with
+ // the same coordinates, prevent needless redrawing (moz bug?)
+ if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
+ this._lastPointer = pointer;
+
+ this.activeDraggable.updateDrag(event, pointer);
+ },
+
+ endDrag: function(event) {
+ if(this._timeout) {
+ clearTimeout(this._timeout);
+ this._timeout = null;
+ }
+ if(!this.activeDraggable) return;
+ this._lastPointer = null;
+ this.activeDraggable.endDrag(event);
+ this.activeDraggable = null;
+ },
+
+ keyPress: function(event) {
+ if(this.activeDraggable)
+ this.activeDraggable.keyPress(event);
+ },
+
+ addObserver: function(observer) {
+ this.observers.push(observer);
+ this._cacheObserverCallbacks();
+ },
+
+ removeObserver: function(element) { // element instead of observer fixes mem leaks
+ this.observers = this.observers.reject( function(o) { return o.element==element });
+ this._cacheObserverCallbacks();
+ },
+
+ notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag'
+ if(this[eventName+'Count'] > 0)
+ this.observers.each( function(o) {
+ if(o[eventName]) o[eventName](eventName, draggable, event);
+ });
+ if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
+ },
+
+ _cacheObserverCallbacks: function() {
+ ['onStart','onEnd','onDrag'].each( function(eventName) {
+ Draggables[eventName+'Count'] = Draggables.observers.select(
+ function(o) { return o[eventName]; }
+ ).length;
+ });
+ }
+};
+
+/*--------------------------------------------------------------------------*/
+
+var Draggable = Class.create({
+ initialize: function(element) {
+ var defaults = {
+ handle: false,
+ reverteffect: function(element, top_offset, left_offset) {
+ var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
+ new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur,
+ queue: {scope:'_draggable', position:'end'}
+ });
+ },
+ endeffect: function(element) {
+ var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0;
+ new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
+ queue: {scope:'_draggable', position:'end'},
+ afterFinish: function(){
+ Draggable._dragging[element] = false
+ }
+ });
+ },
+ zindex: 1000,
+ revert: false,
+ quiet: false,
+ scroll: false,
+ scrollSensitivity: 20,
+ scrollSpeed: 15,
+ snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] }
+ delay: 0
+ };
+
+ if(!arguments[1] || Object.isUndefined(arguments[1].endeffect))
+ Object.extend(defaults, {
+ starteffect: function(element) {
+ element._opacity = Element.getOpacity(element);
+ Draggable._dragging[element] = true;
+ new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
+ }
+ });
+
+ var options = Object.extend(defaults, arguments[1] || { });
+
+ this.element = $(element);
+
+ if(options.handle && Object.isString(options.handle))
+ this.handle = this.element.down('.'+options.handle, 0);
+
+ if(!this.handle) this.handle = $(options.handle);
+ if(!this.handle) this.handle = this.element;
+
+ if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) {
+ options.scroll = $(options.scroll);
+ this._isScrollChild = Element.childOf(this.element, options.scroll);
+ }
+
+ Element.makePositioned(this.element); // fix IE
+
+ this.options = options;
+ this.dragging = false;
+
+ this.eventMouseDown = this.initDrag.bindAsEventListener(this);
+ Event.observe(this.handle, "mousedown", this.eventMouseDown);
+
+ Draggables.register(this);
+ },
+
+ destroy: function() {
+ Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
+ Draggables.unregister(this);
+ },
+
+ currentDelta: function() {
+ return([
+ parseInt(Element.getStyle(this.element,'left') || '0'),
+ parseInt(Element.getStyle(this.element,'top') || '0')]);
+ },
+
+ initDrag: function(event) {
+ if(!Object.isUndefined(Draggable._dragging[this.element]) &&
+ Draggable._dragging[this.element]) return;
+ if(Event.isLeftClick(event)) {
+ // abort on form elements, fixes a Firefox issue
+ var src = Event.element(event);
+ if((tag_name = src.tagName.toUpperCase()) && (
+ tag_name=='INPUT' ||
+ tag_name=='SELECT' ||
+ tag_name=='OPTION' ||
+ tag_name=='BUTTON' ||
+ tag_name=='TEXTAREA')) return;
+
+ var pointer = [Event.pointerX(event), Event.pointerY(event)];
+ var pos = this.element.cumulativeOffset();
+ this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
+
+ Draggables.activate(this);
+ Event.stop(event);
+ }
+ },
+
+ startDrag: function(event) {
+ this.dragging = true;
+ if(!this.delta)
+ this.delta = this.currentDelta();
+
+ if(this.options.zindex) {
+ this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
+ this.element.style.zIndex = this.options.zindex;
+ }
+
+ if(this.options.ghosting) {
+ this._clone = this.element.cloneNode(true);
+ this._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
+ if (!this._originallyAbsolute)
+ Position.absolutize(this.element);
+ this.element.parentNode.insertBefore(this._clone, this.element);
+ }
+
+ if(this.options.scroll) {
+ if (this.options.scroll == window) {
+ var where = this._getWindowScroll(this.options.scroll);
+ this.originalScrollLeft = where.left;
+ this.originalScrollTop = where.top;
+ } else {
+ this.originalScrollLeft = this.options.scroll.scrollLeft;
+ this.originalScrollTop = this.options.scroll.scrollTop;
+ }
+ }
+
+ Draggables.notify('onStart', this, event);
+
+ if(this.options.starteffect) this.options.starteffect(this.element);
+ },
+
+ updateDrag: function(event, pointer) {
+ if(!this.dragging) this.startDrag(event);
+
+ if(!this.options.quiet){
+ Position.prepare();
+ Droppables.show(pointer, this.element);
+ }
+
+ Draggables.notify('onDrag', this, event);
+
+ this.draw(pointer);
+ if(this.options.change) this.options.change(this);
+
+ if(this.options.scroll) {
+ this.stopScrolling();
+
+ var p;
+ if (this.options.scroll == window) {
+ with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
+ } else {
+ p = Position.page(this.options.scroll);
+ p[0] += this.options.scroll.scrollLeft + Position.deltaX;
+ p[1] += this.options.scroll.scrollTop + Position.deltaY;
+ p.push(p[0]+this.options.scroll.offsetWidth);
+ p.push(p[1]+this.options.scroll.offsetHeight);
+ }
+ var speed = [0,0];
+ if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity);
+ if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity);
+ if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity);
+ if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
+ this.startScrolling(speed);
+ }
+
+ // fix AppleWebKit rendering
+ if(Prototype.Browser.WebKit) window.scrollBy(0,0);
+
+ Event.stop(event);
+ },
+
+ finishDrag: function(event, success) {
+ this.dragging = false;
+
+ if(this.options.quiet){
+ Position.prepare();
+ var pointer = [Event.pointerX(event), Event.pointerY(event)];
+ Droppables.show(pointer, this.element);
+ }
+
+ if(this.options.ghosting) {
+ if (!this._originallyAbsolute)
+ Position.relativize(this.element);
+ delete this._originallyAbsolute;
+ Element.remove(this._clone);
+ this._clone = null;
+ }
+
+ var dropped = false;
+ if(success) {
+ dropped = Droppables.fire(event, this.element);
+ if (!dropped) dropped = false;
+ }
+ if(dropped && this.options.onDropped) this.options.onDropped(this.element);
+ Draggables.notify('onEnd', this, event);
+
+ var revert = this.options.revert;
+ if(revert && Object.isFunction(revert)) revert = revert(this.element);
+
+ var d = this.currentDelta();
+ if(revert && this.options.reverteffect) {
+ if (dropped == 0 || revert != 'failure')
+ this.options.reverteffect(this.element,
+ d[1]-this.delta[1], d[0]-this.delta[0]);
+ } else {
+ this.delta = d;
+ }
+
+ if(this.options.zindex)
+ this.element.style.zIndex = this.originalZ;
+
+ if(this.options.endeffect)
+ this.options.endeffect(this.element);
+
+ Draggables.deactivate(this);
+ Droppables.reset();
+ },
+
+ keyPress: function(event) {
+ if(event.keyCode!=Event.KEY_ESC) return;
+ this.finishDrag(event, false);
+ Event.stop(event);
+ },
+
+ endDrag: function(event) {
+ if(!this.dragging) return;
+ this.stopScrolling();
+ this.finishDrag(event, true);
+ Event.stop(event);
+ },
+
+ draw: function(point) {
+ var pos = this.element.cumulativeOffset();
+ if(this.options.ghosting) {
+ var r = Position.realOffset(this.element);
+ pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
+ }
+
+ var d = this.currentDelta();
+ pos[0] -= d[0]; pos[1] -= d[1];
+
+ if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
+ pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
+ pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
+ }
+
+ var p = [0,1].map(function(i){
+ return (point[i]-pos[i]-this.offset[i])
+ }.bind(this));
+
+ if(this.options.snap) {
+ if(Object.isFunction(this.options.snap)) {
+ p = this.options.snap(p[0],p[1],this);
+ } else {
+ if(Object.isArray(this.options.snap)) {
+ p = p.map( function(v, i) {
+ return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this));
+ } else {
+ p = p.map( function(v) {
+ return (v/this.options.snap).round()*this.options.snap }.bind(this));
+ }
+ }}
+
+ var style = this.element.style;
+ if((!this.options.constraint) || (this.options.constraint=='horizontal'))
+ style.left = p[0] + "px";
+ if((!this.options.constraint) || (this.options.constraint=='vertical'))
+ style.top = p[1] + "px";
+
+ if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
+ },
+
+ stopScrolling: function() {
+ if(this.scrollInterval) {
+ clearInterval(this.scrollInterval);
+ this.scrollInterval = null;
+ Draggables._lastScrollPointer = null;
+ }
+ },
+
+ startScrolling: function(speed) {
+ if(!(speed[0] || speed[1])) return;
+ this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
+ this.lastScrolled = new Date();
+ this.scrollInterval = setInterval(this.scroll.bind(this), 10);
+ },
+
+ scroll: function() {
+ var current = new Date();
+ var delta = current - this.lastScrolled;
+ this.lastScrolled = current;
+ if(this.options.scroll == window) {
+ with (this._getWindowScroll(this.options.scroll)) {
+ if (this.scrollSpeed[0] || this.scrollSpeed[1]) {
+ var d = delta / 1000;
+ this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] );
+ }
+ }
+ } else {
+ this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
+ this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000;
+ }
+
+ Position.prepare();
+ Droppables.show(Draggables._lastPointer, this.element);
+ Draggables.notify('onDrag', this);
+ if (this._isScrollChild) {
+ Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
+ Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
+ Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
+ if (Draggables._lastScrollPointer[0] < 0)
+ Draggables._lastScrollPointer[0] = 0;
+ if (Draggables._lastScrollPointer[1] < 0)
+ Draggables._lastScrollPointer[1] = 0;
+ this.draw(Draggables._lastScrollPointer);
+ }
+
+ if(this.options.change) this.options.change(this);
+ },
+
+ _getWindowScroll: function(w) {
+ var T, L, W, H;
+ with (w.document) {
+ if (w.document.documentElement && documentElement.scrollTop) {
+ T = documentElement.scrollTop;
+ L = documentElement.scrollLeft;
+ } else if (w.document.body) {
+ T = body.scrollTop;
+ L = body.scrollLeft;
+ }
+ if (w.innerWidth) {
+ W = w.innerWidth;
+ H = w.innerHeight;
+ } else if (w.document.documentElement && documentElement.clientWidth) {
+ W = documentElement.clientWidth;
+ H = documentElement.clientHeight;
+ } else {
+ W = body.offsetWidth;
+ H = body.offsetHeight;
+ }
+ }
+ return { top: T, left: L, width: W, height: H };
+ }
+});
+
+Draggable._dragging = { };
+
+/*--------------------------------------------------------------------------*/
+
+var SortableObserver = Class.create({
+ initialize: function(element, observer) {
+ this.element = $(element);
+ this.observer = observer;
+ this.lastValue = Sortable.serialize(this.element);
+ },
+
+ onStart: function() {
+ this.lastValue = Sortable.serialize(this.element);
+ },
+
+ onEnd: function() {
+ Sortable.unmark();
+ if(this.lastValue != Sortable.serialize(this.element))
+ this.observer(this.element)
+ }
+});
+
+var Sortable = {
+ SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
+
+ sortables: { },
+
+ _findRootElement: function(element) {
+ while (element.tagName.toUpperCase() != "BODY") {
+ if(element.id && Sortable.sortables[element.id]) return element;
+ element = element.parentNode;
+ }
+ },
+
+ options: function(element) {
+ element = Sortable._findRootElement($(element));
+ if(!element) return;
+ return Sortable.sortables[element.id];
+ },
+
+ destroy: function(element){
+ element = $(element);
+ var s = Sortable.sortables[element.id];
+
+ if(s) {
+ Draggables.removeObserver(s.element);
+ s.droppables.each(function(d){ Droppables.remove(d) });
+ s.draggables.invoke('destroy');
+
+ delete Sortable.sortables[s.element.id];
+ }
+ },
+
+ create: function(element) {
+ element = $(element);
+ var options = Object.extend({
+ element: element,
+ tag: 'li', // assumes li children, override with tag: 'tagname'
+ dropOnEmpty: false,
+ tree: false,
+ treeTag: 'ul',
+ overlap: 'vertical', // one of 'vertical', 'horizontal'
+ constraint: 'vertical', // one of 'vertical', 'horizontal', false
+ containment: element, // also takes array of elements (or id's); or false
+ handle: false, // or a CSS class
+ only: false,
+ delay: 0,
+ hoverclass: null,
+ ghosting: false,
+ quiet: false,
+ scroll: false,
+ scrollSensitivity: 20,
+ scrollSpeed: 15,
+ format: this.SERIALIZE_RULE,
+
+ // these take arrays of elements or ids and can be
+ // used for better initialization performance
+ elements: false,
+ handles: false,
+
+ onChange: Prototype.emptyFunction,
+ onUpdate: Prototype.emptyFunction
+ }, arguments[1] || { });
+
+ // clear any old sortable with same element
+ this.destroy(element);
+
+ // build options for the draggables
+ var options_for_draggable = {
+ revert: true,
+ quiet: options.quiet,
+ scroll: options.scroll,
+ scrollSpeed: options.scrollSpeed,
+ scrollSensitivity: options.scrollSensitivity,
+ delay: options.delay,
+ ghosting: options.ghosting,
+ constraint: options.constraint,
+ handle: options.handle };
+
+ if(options.starteffect)
+ options_for_draggable.starteffect = options.starteffect;
+
+ if(options.reverteffect)
+ options_for_draggable.reverteffect = options.reverteffect;
+ else
+ if(options.ghosting) options_for_draggable.reverteffect = function(element) {
+ element.style.top = 0;
+ element.style.left = 0;
+ };
+
+ if(options.endeffect)
+ options_for_draggable.endeffect = options.endeffect;
+
+ if(options.zindex)
+ options_for_draggable.zindex = options.zindex;
+
+ // build options for the droppables
+ var options_for_droppable = {
+ overlap: options.overlap,
+ containment: options.containment,
+ tree: options.tree,
+ hoverclass: options.hoverclass,
+ onHover: Sortable.onHover
+ };
+
+ var options_for_tree = {
+ onHover: Sortable.onEmptyHover,
+ overlap: options.overlap,
+ containment: options.containment,
+ hoverclass: options.hoverclass
+ };
+
+ // fix for gecko engine
+ Element.cleanWhitespace(element);
+
+ options.draggables = [];
+ options.droppables = [];
+
+ // drop on empty handling
+ if(options.dropOnEmpty || options.tree) {
+ Droppables.add(element, options_for_tree);
+ options.droppables.push(element);
+ }
+
+ (options.elements || this.findElements(element, options) || []).each( function(e,i) {
+ var handle = options.handles ? $(options.handles[i]) :
+ (options.handle ? $(e).select('.' + options.handle)[0] : e);
+ options.draggables.push(
+ new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
+ Droppables.add(e, options_for_droppable);
+ if(options.tree) e.treeNode = element;
+ options.droppables.push(e);
+ });
+
+ if(options.tree) {
+ (Sortable.findTreeElements(element, options) || []).each( function(e) {
+ Droppables.add(e, options_for_tree);
+ e.treeNode = element;
+ options.droppables.push(e);
+ });
+ }
+
+ // keep reference
+ this.sortables[element.identify()] = options;
+
+ // for onupdate
+ Draggables.addObserver(new SortableObserver(element, options.onUpdate));
+
+ },
+
+ // return all suitable-for-sortable elements in a guaranteed order
+ findElements: function(element, options) {
+ return Element.findChildren(
+ element, options.only, options.tree ? true : false, options.tag);
+ },
+
+ findTreeElements: function(element, options) {
+ return Element.findChildren(
+ element, options.only, options.tree ? true : false, options.treeTag);
+ },
+
+ onHover: function(element, dropon, overlap) {
+ if(Element.isParent(dropon, element)) return;
+
+ if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) {
+ return;
+ } else if(overlap>0.5) {
+ Sortable.mark(dropon, 'before');
+ if(dropon.previousSibling != element) {
+ var oldParentNode = element.parentNode;
+ element.style.visibility = "hidden"; // fix gecko rendering
+ dropon.parentNode.insertBefore(element, dropon);
+ if(dropon.parentNode!=oldParentNode)
+ Sortable.options(oldParentNode).onChange(element);
+ Sortable.options(dropon.parentNode).onChange(element);
+ }
+ } else {
+ Sortable.mark(dropon, 'after');
+ var nextElement = dropon.nextSibling || null;
+ if(nextElement != element) {
+ var oldParentNode = element.parentNode;
+ element.style.visibility = "hidden"; // fix gecko rendering
+ dropon.parentNode.insertBefore(element, nextElement);
+ if(dropon.parentNode!=oldParentNode)
+ Sortable.options(oldParentNode).onChange(element);
+ Sortable.options(dropon.parentNode).onChange(element);
+ }
+ }
+ },
+
+ onEmptyHover: function(element, dropon, overlap) {
+ var oldParentNode = element.parentNode;
+ var droponOptions = Sortable.options(dropon);
+
+ if(!Element.isParent(dropon, element)) {
+ var index;
+
+ var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
+ var child = null;
+
+ if(children) {
+ var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);
+
+ for (index = 0; index < children.length; index += 1) {
+ if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
+ offset -= Element.offsetSize (children[index], droponOptions.overlap);
+ } else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) {
+ child = index + 1 < children.length ? children[index + 1] : null;
+ break;
+ } else {
+ child = children[index];
+ break;
+ }
+ }
+ }
+
+ dropon.insertBefore(element, child);
+
+ Sortable.options(oldParentNode).onChange(element);
+ droponOptions.onChange(element);
+ }
+ },
+
+ unmark: function() {
+ if(Sortable._marker) Sortable._marker.hide();
+ },
+
+ mark: function(dropon, position) {
+ // mark on ghosting only
+ var sortable = Sortable.options(dropon.parentNode);
+ if(sortable && !sortable.ghosting) return;
+
+ if(!Sortable._marker) {
+ Sortable._marker =
+ ($('dropmarker') || Element.extend(document.createElement('DIV'))).
+ hide().addClassName('dropmarker').setStyle({position:'absolute'});
+ document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
+ }
+ var offsets = dropon.cumulativeOffset();
+ Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
+
+ if(position=='after')
+ if(sortable.overlap == 'horizontal')
+ Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
+ else
+ Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
+
+ Sortable._marker.show();
+ },
+
+ _tree: function(element, options, parent) {
+ var children = Sortable.findElements(element, options) || [];
+
+ for (var i = 0; i < children.length; ++i) {
+ var match = children[i].id.match(options.format);
+
+ if (!match) continue;
+
+ var child = {
+ id: encodeURIComponent(match ? match[1] : null),
+ element: element,
+ parent: parent,
+ children: [],
+ position: parent.children.length,
+ container: $(children[i]).down(options.treeTag)
+ };
+
+ /* Get the element containing the children and recurse over it */
+ if (child.container)
+ this._tree(child.container, options, child);
+
+ parent.children.push (child);
+ }
+
+ return parent;
+ },
+
+ tree: function(element) {
+ element = $(element);
+ var sortableOptions = this.options(element);
+ var options = Object.extend({
+ tag: sortableOptions.tag,
+ treeTag: sortableOptions.treeTag,
+ only: sortableOptions.only,
+ name: element.id,
+ format: sortableOptions.format
+ }, arguments[1] || { });
+
+ var root = {
+ id: null,
+ parent: null,
+ children: [],
+ container: element,
+ position: 0
+ };
+
+ return Sortable._tree(element, options, root);
+ },
+
+ /* Construct a [i] index for a particular node */
+ _constructIndex: function(node) {
+ var index = '';
+ do {
+ if (node.id) index = '[' + node.position + ']' + index;
+ } while ((node = node.parent) != null);
+ return index;
+ },
+
+ sequence: function(element) {
+ element = $(element);
+ var options = Object.extend(this.options(element), arguments[1] || { });
+
+ return $(this.findElements(element, options) || []).map( function(item) {
+ return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
+ });
+ },
+
+ setSequence: function(element, new_sequence) {
+ element = $(element);
+ var options = Object.extend(this.options(element), arguments[2] || { });
+
+ var nodeMap = { };
+ this.findElements(element, options).each( function(n) {
+ if (n.id.match(options.format))
+ nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
+ n.parentNode.removeChild(n);
+ });
+
+ new_sequence.each(function(ident) {
+ var n = nodeMap[ident];
+ if (n) {
+ n[1].appendChild(n[0]);
+ delete nodeMap[ident];
+ }
+ });
+ },
+
+ serialize: function(element) {
+ element = $(element);
+ var options = Object.extend(Sortable.options(element), arguments[1] || { });
+ var name = encodeURIComponent(
+ (arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
+
+ if (options.tree) {
+ return Sortable.tree(element, arguments[1]).children.map( function (item) {
+ return [name + Sortable._constructIndex(item) + "[id]=" +
+ encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
+ }).flatten().join('&');
+ } else {
+ return Sortable.sequence(element, arguments[1]).map( function(item) {
+ return name + "[]=" + encodeURIComponent(item);
+ }).join('&');
+ }
+ }
+};
+
+// Returns true if child is contained within element
+Element.isParent = function(child, element) {
+ if (!child.parentNode || child == element) return false;
+ if (child.parentNode == element) return true;
+ return Element.isParent(child.parentNode, element);
+};
+
+Element.findChildren = function(element, only, recursive, tagName) {
+ if(!element.hasChildNodes()) return null;
+ tagName = tagName.toUpperCase();
+ if(only) only = [only].flatten();
+ var elements = [];
+ $A(element.childNodes).each( function(e) {
+ if(e.tagName && e.tagName.toUpperCase()==tagName &&
+ (!only || (Element.classNames(e).detect(function(v) { return only.include(v) }))))
+ elements.push(e);
+ if(recursive) {
+ var grandchildren = Element.findChildren(e, only, recursive, tagName);
+ if(grandchildren) elements.push(grandchildren);
+ }
+ });
+
+ return (elements.length>0 ? elements.flatten() : []);
+};
+
+Element.offsetSize = function (element, type) {
+ return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
+}; \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/stylesheets/dashboard.css b/sonar-server/src/main/webapp/stylesheets/dashboard.css
new file mode 100644
index 00000000000..5ec39ec47a3
--- /dev/null
+++ b/sonar-server/src/main/webapp/stylesheets/dashboard.css
@@ -0,0 +1,216 @@
+/*DASHBOARD*/
+#dashboard {
+ position: relative;
+ align: center;
+ width: 100%;
+}
+
+#dashboard .transparent {
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ top: 0;
+ left: 0;
+ background: url('../images/transparent.gif') repeat;
+ z-index: 1000;
+}
+
+/*LAYOUT*/
+#dashboard .layout-example .transparent {
+ cursor: pointer;
+}
+
+#dashboard .layout-example-wrapper {
+ text-align: center;
+ float: left;
+ margin: 0;
+ padding: 0;
+}
+
+#dashboard .layout-example {
+ position: relative;
+ margin: 0 20px 10px 20px;
+ padding: 0;
+}
+
+#dashboard .layout-example .layout-column-wrapper {
+ float: left;
+ margin: 0px;
+ padding: 0px;
+ background-color: #cccccc;
+}
+
+#dashboard .layout-example .layout-column {
+ margin: 5px 5px 5px 0px;
+ padding: 0px;
+ height: 70px;
+ background-color: #ffffff;
+}
+
+#dashboard .layout-example .first {
+ margin-left: 5px;
+}
+
+/*CONFIGURATION*/
+#dashboard #widget_definitions {
+ width: 100%;
+ overflow: auto;
+}
+
+#dashboard #widget_definitions ul {
+ list-style-type: none;
+ margin: 0;
+ white-space: nowrap;
+ width: 100000px;
+}
+
+#dashboard #widget_definitions li {
+ float: left;
+ margin: 0;
+ padding: 2px 7px;
+ display: inline-block;
+ width: 200px;
+}
+
+#dashboard .widget_def {
+
+ border: 1px solid #ddd;
+ padding: 5px;
+}
+
+/*OPERATIONS*/
+#dashboard #dashboard-operations {
+ position: relative;
+ display: inline-block;
+ width: 100%;
+}
+
+#dashboard #dashboard-operations ul.operations {
+ float: left;
+ list-style-type: none;
+ border: 1px solid #cdcdcd;
+ padding: 0;
+ margin: 0;
+ -moz-border-radius: 3px;
+ -webkit-border-radius: 3px;
+}
+
+#dashboard #dashboard-operations ul.operations li {
+ float: left;
+ margin: 0;
+ padding: 2px 10px;
+ position: relative;
+ background-color: #f4f4f4;
+ font-size: 85%;
+ border-right: 1px solid #cdcdcd;
+}
+
+#dashboard #dashboard-operations ul.operations li.last {
+ border-right-width: 0;
+}
+
+#dashboard #dashboard-operations ul.operations li.selected {
+ background-color: #d4d4d4;
+}
+
+#dashboard #dashboard-operations ul.operations li a {
+ color: #555;
+}
+
+#dashboard .dashboard-column {
+ margin: 0;
+ padding: 0;
+ overflow: visible;
+}
+
+#dashboard .dashboard-column-wrapper {
+ float: left;
+ margin: 0;
+ padding: 0;
+}
+
+#dashboard .column-handle {
+ height: 100px;
+ width: 100%;
+ margin: 10px 0px 10px 0px;
+ padding: 0px;
+ display: inline-block;
+ line-height: 100px;
+ text-align: center;
+ font-size: x-large;
+ vertical-align: middle;
+ color: #555;
+}
+#dashboard .block {
+ position: relative;
+ width: 100%;
+ margin: 0 0 10px 0;
+ padding: 0;
+}
+
+#dashboard .block .handle {
+ margin: 0;
+ padding: 3px 5px;
+ background-color: #efefef;
+ cursor: move;
+ border: 1px solid #ddd;
+ border-bottom: 0;
+}
+
+#dashboard .block .block-view-toggle {
+ display: block;
+ float: right;
+ cursor: pointer;
+ padding-left: 5px;
+ text-decoration: underline;
+}
+
+#dashboard .block .block-remove {
+ display: block;
+ float: right;
+ cursor: pointer;
+ padding-left: 5px;
+ text-decoration: underline;
+}
+
+#dashboard .block .description {
+ display: none;
+}
+
+#dashboard .block .content {
+ display: block;
+ position: relative;
+ padding: 8px 5px 5px 8px;
+ overflow-x: visible;
+ border: 1px solid #ddd;
+}
+
+#dashboard .block .widgetedit {
+ display: block;
+ position: relative;
+ padding: 8px 5px 5px 8px;
+ overflow-x: auto;
+ border: 1px solid #ddd;
+}
+
+#dashboard .block .transparent {
+ cursor: move;
+}
+
+#dashboard .block-hover {
+ border: 3px dashed #ddd;
+}
+
+#dashboard .valid-editrow {
+ border: 1px solid #0f0;
+}
+
+#dashboard .invalid-editrow {
+ border: 1px solid #f00;
+}
+
+#dashboard .shadow-block {
+ box-shadow: 8px 8px 8px #ddd;
+ -moz-box-shadow: 8px 8px 8px #ddd;
+ -webkit-box-shadow: 8px 8px 8px #ddd;
+} \ No newline at end of file
diff --git a/sonar-server/src/main/webapp/stylesheets/style.css b/sonar-server/src/main/webapp/stylesheets/style.css
index c762d13293d..db877c562e5 100644
--- a/sonar-server/src/main/webapp/stylesheets/style.css
+++ b/sonar-server/src/main/webapp/stylesheets/style.css
@@ -577,6 +577,7 @@ ul.operations {
margin: 0;
background-color: #f4f4f4;
border: 1px solid #cdcdcd;
+ border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
}
@@ -587,6 +588,9 @@ ul.operations li {
font-size: 85%;
border-right: 1px solid #cdcdcd;
}
+ul.operations li.selected {
+ background-color: #d4d4d4;
+}
ul.operations li.last {
border-right-width:0;
}