summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--app/assets/javascripts/graphs/graphs_bundle.js4
-rw-r--r--app/assets/javascripts/pages/projects/graphs/charts/index.js (renamed from app/assets/javascripts/graphs/graphs_charts.js)2
-rw-r--r--app/assets/javascripts/pages/projects/graphs/show/index.js (renamed from app/assets/javascripts/graphs/graphs_show.js)6
-rw-r--r--app/assets/javascripts/pages/projects/graphs/show/stat_graph_contributors.js (renamed from app/assets/javascripts/graphs/stat_graph_contributors.js)2
-rw-r--r--app/assets/javascripts/pages/projects/graphs/show/stat_graph_contributors_graph.js (renamed from app/assets/javascripts/graphs/stat_graph_contributors_graph.js)2
-rw-r--r--app/assets/javascripts/pages/projects/graphs/show/stat_graph_contributors_util.js (renamed from app/assets/javascripts/graphs/stat_graph_contributors_util.js)0
-rw-r--r--app/assets/javascripts/pages/projects/pipelines/charts/index.js2
-rw-r--r--app/assets/stylesheets/framework/stacked_progress_bar.scss2
-rw-r--r--app/mailers/emails/members.rb11
-rw-r--r--app/models/commit.rb8
-rw-r--r--app/models/deployment.rb4
-rw-r--r--app/models/environment.rb2
-rw-r--r--app/models/user.rb2
-rw-r--r--app/services/notification_service.rb17
-rw-r--r--app/views/devise/sessions/two_factor.html.haml2
-rw-r--r--app/views/profiles/_head.html.haml2
-rw-r--r--app/views/profiles/two_factor_auths/show.html.haml4
-rw-r--r--app/views/projects/blob/_upload.html.haml2
-rw-r--r--app/views/projects/blob/edit.html.haml2
-rw-r--r--app/views/projects/blob/new.html.haml2
-rw-r--r--app/views/projects/blob/viewers/_balsamiq.html.haml2
-rw-r--r--app/views/projects/blob/viewers/_notebook.html.haml4
-rw-r--r--app/views/projects/blob/viewers/_pdf.html.haml4
-rw-r--r--app/views/projects/blob/viewers/_sketch.html.haml4
-rw-r--r--app/views/projects/blob/viewers/_stl.html.haml2
-rw-r--r--app/views/projects/commit/_pipelines_list.haml4
-rw-r--r--app/views/projects/commit/show.html.haml4
-rw-r--r--app/views/projects/cycle_analytics/show.html.haml4
-rw-r--r--app/views/projects/environments/folder.html.haml4
-rw-r--r--app/views/projects/environments/index.html.haml4
-rw-r--r--app/views/projects/environments/metrics.html.haml1
-rw-r--r--app/views/projects/environments/terminal.html.haml2
-rw-r--r--app/views/projects/graphs/charts.html.haml4
-rw-r--r--app/views/projects/graphs/show.html.haml4
-rw-r--r--app/views/projects/issues/show.html.haml4
-rw-r--r--app/views/projects/merge_requests/conflicts.html.haml4
-rw-r--r--app/views/projects/merge_requests/conflicts/show.html.haml4
-rw-r--r--app/views/projects/network/show.html.haml2
-rw-r--r--app/views/projects/pipelines/index.html.haml4
-rw-r--r--app/views/projects/protected_branches/_index.html.haml2
-rw-r--r--app/views/projects/protected_tags/_index.html.haml2
-rw-r--r--app/views/projects/registry/repositories/index.html.haml4
-rw-r--r--app/views/projects/settings/repository/show.html.haml4
-rw-r--r--app/views/shared/issuable/_sidebar.html.haml4
-rw-r--r--app/views/shared/snippets/_form.html.haml2
-rw-r--r--app/workers/process_commit_worker.rb12
-rw-r--r--changelogs/unreleased/32564-fix-double-system-closing-notes.yml5
-rw-r--r--changelogs/unreleased/42274-group-request-membership-long-too.yml5
-rw-r--r--changelogs/unreleased/4826-github-import-wiki-fix-1.yml5
-rw-r--r--changelogs/unreleased/flipper-caching.yml5
-rw-r--r--changelogs/unreleased/kp-fix-stacked-bar-progress-value-clipping.yml5
-rw-r--r--changelogs/unreleased/remove-unnecessary-validate-project.yml5
-rw-r--r--changelogs/unreleased/sh-fix-squash-rebase-utf8-data.yml5
-rw-r--r--changelogs/unreleased/sh-guard-read-only-user-updates.yml5
-rw-r--r--config/initializers/flipper.rb2
-rw-r--r--config/webpack.config.js17
-rw-r--r--doc/administration/auth/how_to_configure_ldap_gitlab_ce/index.md13
-rw-r--r--doc/ci/examples/artifactory_and_gitlab/index.md10
-rw-r--r--doc/ci/examples/laravel_with_gitlab_and_envoy/index.md10
-rw-r--r--doc/development/changelog.md4
-rw-r--r--doc/development/writing_documentation.md29
-rw-r--r--doc/install/openshift_and_gitlab/index.md13
-rw-r--r--doc/topics/git/how_to_install_git/index.md13
-rw-r--r--doc/topics/git/numerous_undo_possibilities_in_git/index.md13
-rw-r--r--doc/user/project/pages/getting_started_part_four.md32
-rw-r--r--doc/user/project/pages/getting_started_part_one.md39
-rw-r--r--doc/user/project/pages/getting_started_part_three.md54
-rw-r--r--doc/user/project/pages/getting_started_part_two.md63
-rw-r--r--doc/user/project/pages/index.md8
-rw-r--r--doc/workflow/lfs/manage_large_binaries_with_git_lfs.md4
-rw-r--r--features/project/network_graph.feature46
-rw-r--r--features/steps/project/network_graph.rb116
-rw-r--r--lib/gitlab/checks/change_access.rb7
-rw-r--r--lib/gitlab/checks/commit_check.rb4
-rw-r--r--lib/gitlab/git/commit.rb2
-rw-r--r--lib/gitlab/git/repository.rb1
-rw-r--r--lib/gitlab/github_import/importer/repository_importer.rb1
-rw-r--r--lib/gitlab/metrics/transaction.rb5
-rw-r--r--package.json1
-rw-r--r--qa/qa/factory/resource/secret_variable.rb12
-rw-r--r--qa/qa/page/base.rb4
-rw-r--r--qa/qa/page/project/settings/secret_variables.rb26
-rw-r--r--qa/qa/specs/features/project/add_secret_variable_spec.rb21
-rw-r--r--qa/spec/page/base_spec.rb11
-rw-r--r--spec/features/projects/network_graph_spec.rb108
-rw-r--r--spec/javascripts/graphs/stat_graph_contributors_graph_spec.js2
-rw-r--r--spec/javascripts/graphs/stat_graph_contributors_spec.js4
-rw-r--r--spec/javascripts/graphs/stat_graph_contributors_util_spec.js2
-rw-r--r--spec/lib/gitlab/checks/change_access_spec.rb4
-rw-r--r--spec/lib/gitlab/git/repository_spec.rb12
-rw-r--r--spec/lib/gitlab/github_import/importer/repository_importer_spec.rb8
-rw-r--r--spec/mailers/notify_spec.rb70
-rw-r--r--spec/models/user_spec.rb8
-rw-r--r--spec/requests/api/issues_spec.rb26
-rw-r--r--spec/requests/api/v3/issues_spec.rb26
-rw-r--r--spec/services/notification_service_spec.rb89
-rw-r--r--spec/workers/process_commit_worker_spec.rb49
-rw-r--r--vendor/assets/javascripts/Chart.js3477
-rw-r--r--yarn.lock4
99 files changed, 592 insertions, 4091 deletions
diff --git a/app/assets/javascripts/graphs/graphs_bundle.js b/app/assets/javascripts/graphs/graphs_bundle.js
deleted file mode 100644
index 534bc535bb6..00000000000
--- a/app/assets/javascripts/graphs/graphs_bundle.js
+++ /dev/null
@@ -1,4 +0,0 @@
-import Chart from 'vendor/Chart';
-
-// export to global scope
-window.Chart = Chart;
diff --git a/app/assets/javascripts/graphs/graphs_charts.js b/app/assets/javascripts/pages/projects/graphs/charts/index.js
index ec6eab34989..42df19c2968 100644
--- a/app/assets/javascripts/graphs/graphs_charts.js
+++ b/app/assets/javascripts/pages/projects/graphs/charts/index.js
@@ -1,4 +1,4 @@
-import Chart from 'vendor/Chart';
+import Chart from 'chart.js';
import _ from 'underscore';
document.addEventListener('DOMContentLoaded', () => {
diff --git a/app/assets/javascripts/graphs/graphs_show.js b/app/assets/javascripts/pages/projects/graphs/show/index.js
index b670e907a5c..f516ff20995 100644
--- a/app/assets/javascripts/graphs/graphs_show.js
+++ b/app/assets/javascripts/pages/projects/graphs/show/index.js
@@ -1,6 +1,6 @@
-import flash from '../flash';
-import { __ } from '../locale';
-import axios from '../lib/utils/axios_utils';
+import flash from '~/flash';
+import { __ } from '~/locale';
+import axios from '~/lib/utils/axios_utils';
import ContributorsStatGraph from './stat_graph_contributors';
document.addEventListener('DOMContentLoaded', () => {
diff --git a/app/assets/javascripts/graphs/stat_graph_contributors.js b/app/assets/javascripts/pages/projects/graphs/show/stat_graph_contributors.js
index 151a4ce012c..9ac0b4c07e5 100644
--- a/app/assets/javascripts/graphs/stat_graph_contributors.js
+++ b/app/assets/javascripts/pages/projects/graphs/show/stat_graph_contributors.js
@@ -1,9 +1,9 @@
/* eslint-disable func-names, space-before-function-paren, wrap-iife, no-var, one-var, camelcase, one-var-declaration-per-line, quotes, no-param-reassign, quote-props, comma-dangle, prefer-template, max-len, no-return-assign, no-shadow */
import _ from 'underscore';
+import { n__, s__, createDateTimeFormat, sprintf } from '~/locale';
import { ContributorsGraph, ContributorsAuthorGraph, ContributorsMasterGraph } from './stat_graph_contributors_graph';
import ContributorsStatGraphUtil from './stat_graph_contributors_util';
-import { n__, s__, createDateTimeFormat, sprintf } from '../locale';
export default (function() {
function ContributorsStatGraph() {
diff --git a/app/assets/javascripts/graphs/stat_graph_contributors_graph.js b/app/assets/javascripts/pages/projects/graphs/show/stat_graph_contributors_graph.js
index 9a4012232a0..6ffaa277a0a 100644
--- a/app/assets/javascripts/graphs/stat_graph_contributors_graph.js
+++ b/app/assets/javascripts/pages/projects/graphs/show/stat_graph_contributors_graph.js
@@ -7,7 +7,7 @@ import { axisLeft, axisBottom } from 'd3-axis';
import { area } from 'd3-shape';
import { brushX } from 'd3-brush';
import { timeParse } from 'd3-time-format';
-import { dateTickFormat } from '../lib/utils/tick_formats';
+import { dateTickFormat } from '~/lib/utils/tick_formats';
const d3 = { extent, max, select, scaleTime, scaleLinear, axisLeft, axisBottom, area, brushX, timeParse };
diff --git a/app/assets/javascripts/graphs/stat_graph_contributors_util.js b/app/assets/javascripts/pages/projects/graphs/show/stat_graph_contributors_util.js
index 77135ad1f0e..77135ad1f0e 100644
--- a/app/assets/javascripts/graphs/stat_graph_contributors_util.js
+++ b/app/assets/javascripts/pages/projects/graphs/show/stat_graph_contributors_util.js
diff --git a/app/assets/javascripts/pages/projects/pipelines/charts/index.js b/app/assets/javascripts/pages/projects/pipelines/charts/index.js
index c1dafda0e24..bb92f4e1459 100644
--- a/app/assets/javascripts/pages/projects/pipelines/charts/index.js
+++ b/app/assets/javascripts/pages/projects/pipelines/charts/index.js
@@ -1,4 +1,4 @@
-import Chart from 'vendor/Chart';
+import Chart from 'chart.js';
const options = {
scaleOverlay: true,
diff --git a/app/assets/stylesheets/framework/stacked_progress_bar.scss b/app/assets/stylesheets/framework/stacked_progress_bar.scss
index 4869cda73e5..528ba53a48b 100644
--- a/app/assets/stylesheets/framework/stacked_progress_bar.scss
+++ b/app/assets/stylesheets/framework/stacked_progress_bar.scss
@@ -10,7 +10,7 @@
.status-neutral,
.status-red, {
height: 100%;
- min-width: 25px;
+ min-width: 30px;
padding: 0 5px;
font-size: $tooltip-font-size;
font-weight: normal;
diff --git a/app/mailers/emails/members.rb b/app/mailers/emails/members.rb
index d76c61c369f..75cf56a51f2 100644
--- a/app/mailers/emails/members.rb
+++ b/app/mailers/emails/members.rb
@@ -7,18 +7,11 @@ module Emails
helper_method :member_source, :member
end
- def member_access_requested_email(member_source_type, member_id)
+ def member_access_requested_email(member_source_type, member_id, recipient_notification_email)
@member_source_type = member_source_type
@member_id = member_id
- admins = member_source.members.owners_and_masters.pluck(:notification_email)
- # A project in a group can have no explicit owners/masters, in that case
- # we fallbacks to the group's owners/masters.
- if admins.empty? && member_source.respond_to?(:group) && member_source.group
- admins = member_source.group.members.owners_and_masters.pluck(:notification_email)
- end
-
- mail(to: admins,
+ mail(to: recipient_notification_email,
subject: subject("Request to join the #{member_source.human_name} #{member_source.model_name.singular}"))
end
diff --git a/app/models/commit.rb b/app/models/commit.rb
index 8c960389652..add5fcf0e79 100644
--- a/app/models/commit.rb
+++ b/app/models/commit.rb
@@ -417,6 +417,10 @@ class Commit
!!(title =~ WIP_REGEX)
end
+ def merged_merge_request?(user)
+ !!merged_merge_request(user)
+ end
+
private
def commit_reference(from, referable_commit_id, full: false)
@@ -445,10 +449,6 @@ class Commit
changes
end
- def merged_merge_request?(user)
- !!merged_merge_request(user)
- end
-
def merged_merge_request_no_cache(user)
MergeRequestsFinder.new(user, project_id: project.id).find_by(merge_commit_sha: id) if merge_commit?
end
diff --git a/app/models/deployment.rb b/app/models/deployment.rb
index 3aed071dd49..b6cf168d60e 100644
--- a/app/models/deployment.rb
+++ b/app/models/deployment.rb
@@ -1,8 +1,8 @@
class Deployment < ActiveRecord::Base
include InternalId
- belongs_to :project, required: true, validate: true
- belongs_to :environment, required: true, validate: true
+ belongs_to :project, required: true
+ belongs_to :environment, required: true
belongs_to :user
belongs_to :deployable, polymorphic: true # rubocop:disable Cop/PolymorphicAssociations
diff --git a/app/models/environment.rb b/app/models/environment.rb
index 2f6eae605ee..f78c21aebe5 100644
--- a/app/models/environment.rb
+++ b/app/models/environment.rb
@@ -4,7 +4,7 @@ class Environment < ActiveRecord::Base
NUMBERS = '0'..'9'
SUFFIX_CHARS = LETTERS.to_a + NUMBERS.to_a
- belongs_to :project, required: true, validate: true
+ belongs_to :project, required: true
has_many :deployments, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
diff --git a/app/models/user.rb b/app/models/user.rb
index 5e84d2da805..f5eeba27572 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -59,6 +59,8 @@ class User < ActiveRecord::Base
# Override Devise::Models::Trackable#update_tracked_fields!
# to limit database writes to at most once every hour
def update_tracked_fields!(request)
+ return if Gitlab::Database.read_only?
+
update_tracked_fields(request)
lease = Gitlab::ExclusiveLease.new("user_update_tracked_fields:#{id}", timeout: 1.hour.to_i)
diff --git a/app/services/notification_service.rb b/app/services/notification_service.rb
index 8c84ccfcc92..56e941d90ff 100644
--- a/app/services/notification_service.rb
+++ b/app/services/notification_service.rb
@@ -208,7 +208,12 @@ class NotificationService
def new_access_request(member)
return true unless member.notifiable?(:subscription)
- mailer.member_access_requested_email(member.real_source_type, member.id).deliver_later
+ recipients = member.source.members.owners_and_masters
+ if fallback_to_group_owners_masters?(recipients, member)
+ recipients = member.source.group.members.owners_and_masters
+ end
+
+ recipients.each { |recipient| deliver_access_request_email(recipient, member) }
end
def decline_access_request(member)
@@ -435,4 +440,14 @@ class NotificationService
def notifiable_users(*args)
NotificationRecipientService.notifiable_users(*args)
end
+
+ def deliver_access_request_email(recipient, member)
+ mailer.member_access_requested_email(member.real_source_type, member.id, recipient.user.notification_email).deliver_later
+ end
+
+ def fallback_to_group_owners_masters?(recipients, member)
+ return false if recipients.present?
+
+ member.source.respond_to?(:group) && member.source.group
+ end
end
diff --git a/app/views/devise/sessions/two_factor.html.haml b/app/views/devise/sessions/two_factor.html.haml
index a039756c7e2..56ec1b3db0d 100644
--- a/app/views/devise/sessions/two_factor.html.haml
+++ b/app/views/devise/sessions/two_factor.html.haml
@@ -1,6 +1,6 @@
- if inject_u2f_api?
- content_for :page_specific_javascripts do
- = page_specific_javascript_bundle_tag('u2f')
+ = webpack_bundle_tag('u2f')
%div
= render 'devise/shared/tab_single', tab_title: 'Two-Factor Authentication'
diff --git a/app/views/profiles/_head.html.haml b/app/views/profiles/_head.html.haml
index 83ae9129807..a8eb66ca13c 100644
--- a/app/views/profiles/_head.html.haml
+++ b/app/views/profiles/_head.html.haml
@@ -1,2 +1,2 @@
- content_for :page_specific_javascripts do
- = page_specific_javascript_bundle_tag('profile')
+ = webpack_bundle_tag('profile')
diff --git a/app/views/profiles/two_factor_auths/show.html.haml b/app/views/profiles/two_factor_auths/show.html.haml
index 5207dac3ac2..e58cd20402c 100644
--- a/app/views/profiles/two_factor_auths/show.html.haml
+++ b/app/views/profiles/two_factor_auths/show.html.haml
@@ -6,8 +6,8 @@
- content_for :page_specific_javascripts do
- if inject_u2f_api?
- = page_specific_javascript_bundle_tag('u2f')
- = page_specific_javascript_bundle_tag('two_factor_auth')
+ = webpack_bundle_tag('u2f')
+ = webpack_bundle_tag('two_factor_auth')
.js-two-factor-auth{ 'data-two-factor-skippable' => "#{two_factor_skippable?}", 'data-two_factor_skip_url' => skip_profile_two_factor_auth_path }
.row.prepend-top-default
diff --git a/app/views/projects/blob/_upload.html.haml b/app/views/projects/blob/_upload.html.haml
index 21b6aa4bad9..16c56ea604a 100644
--- a/app/views/projects/blob/_upload.html.haml
+++ b/app/views/projects/blob/_upload.html.haml
@@ -29,4 +29,4 @@
= commit_in_fork_help
- content_for :page_specific_javascripts do
- = page_specific_javascript_bundle_tag('blob')
+ = webpack_bundle_tag('blob')
diff --git a/app/views/projects/blob/edit.html.haml b/app/views/projects/blob/edit.html.haml
index 626cbc9e41d..60bd1c2528a 100644
--- a/app/views/projects/blob/edit.html.haml
+++ b/app/views/projects/blob/edit.html.haml
@@ -3,7 +3,7 @@
- page_title "Edit", @blob.path, @ref
- content_for :page_specific_javascripts do
= page_specific_javascript_tag('lib/ace.js')
- = page_specific_javascript_bundle_tag('blob')
+ = webpack_bundle_tag('blob')
%div{ class: container_class }
- if @conflict
diff --git a/app/views/projects/blob/new.html.haml b/app/views/projects/blob/new.html.haml
index a4263774dfd..4e4288390f5 100644
--- a/app/views/projects/blob/new.html.haml
+++ b/app/views/projects/blob/new.html.haml
@@ -2,7 +2,7 @@
- page_title "New File", @path.presence, @ref
- content_for :page_specific_javascripts do
= page_specific_javascript_tag('lib/ace.js')
- = page_specific_javascript_bundle_tag('blob')
+ = webpack_bundle_tag('blob')
.editor-title-row
%h3.page-title.blob-new-page-title
New file
diff --git a/app/views/projects/blob/viewers/_balsamiq.html.haml b/app/views/projects/blob/viewers/_balsamiq.html.haml
index 1e7c461f02e..15349387eb2 100644
--- a/app/views/projects/blob/viewers/_balsamiq.html.haml
+++ b/app/views/projects/blob/viewers/_balsamiq.html.haml
@@ -1,4 +1,4 @@
- content_for :page_specific_javascripts do
- = page_specific_javascript_bundle_tag('balsamiq_viewer')
+ = webpack_bundle_tag('balsamiq_viewer')
.file-content.balsamiq-viewer#js-balsamiq-viewer{ data: { endpoint: blob_raw_path } }
diff --git a/app/views/projects/blob/viewers/_notebook.html.haml b/app/views/projects/blob/viewers/_notebook.html.haml
index 8a41bc53004..d1ffaca35b9 100644
--- a/app/views/projects/blob/viewers/_notebook.html.haml
+++ b/app/views/projects/blob/viewers/_notebook.html.haml
@@ -1,5 +1,5 @@
- content_for :page_specific_javascripts do
- = page_specific_javascript_bundle_tag('common_vue')
- = page_specific_javascript_bundle_tag('notebook_viewer')
+ = webpack_bundle_tag('common_vue')
+ = webpack_bundle_tag('notebook_viewer')
.file-content#js-notebook-viewer{ data: { endpoint: blob_raw_path } }
diff --git a/app/views/projects/blob/viewers/_pdf.html.haml b/app/views/projects/blob/viewers/_pdf.html.haml
index ec2b18bd4ab..fc3f0d922b1 100644
--- a/app/views/projects/blob/viewers/_pdf.html.haml
+++ b/app/views/projects/blob/viewers/_pdf.html.haml
@@ -1,5 +1,5 @@
- content_for :page_specific_javascripts do
- = page_specific_javascript_bundle_tag('common_vue')
- = page_specific_javascript_bundle_tag('pdf_viewer')
+ = webpack_bundle_tag('common_vue')
+ = webpack_bundle_tag('pdf_viewer')
.file-content#js-pdf-viewer{ data: { endpoint: blob_raw_path } }
diff --git a/app/views/projects/blob/viewers/_sketch.html.haml b/app/views/projects/blob/viewers/_sketch.html.haml
index 775e4584f77..8fb67c819c1 100644
--- a/app/views/projects/blob/viewers/_sketch.html.haml
+++ b/app/views/projects/blob/viewers/_sketch.html.haml
@@ -1,6 +1,6 @@
- content_for :page_specific_javascripts do
- = page_specific_javascript_bundle_tag('common_vue')
- = page_specific_javascript_bundle_tag('sketch_viewer')
+ = webpack_bundle_tag('common_vue')
+ = webpack_bundle_tag('sketch_viewer')
.file-content#js-sketch-viewer{ data: { endpoint: blob_raw_path } }
.js-loading-icon.text-center.prepend-top-default.append-bottom-default.js-loading-icon{ 'aria-label' => 'Loading Sketch preview' }
diff --git a/app/views/projects/blob/viewers/_stl.html.haml b/app/views/projects/blob/viewers/_stl.html.haml
index 6578d826ace..e58809ec008 100644
--- a/app/views/projects/blob/viewers/_stl.html.haml
+++ b/app/views/projects/blob/viewers/_stl.html.haml
@@ -1,5 +1,5 @@
- content_for :page_specific_javascripts do
- = page_specific_javascript_bundle_tag('stl_viewer')
+ = webpack_bundle_tag('stl_viewer')
.file-content.is-stl-loading
.text-center#js-stl-viewer{ data: { endpoint: blob_raw_path } }
diff --git a/app/views/projects/commit/_pipelines_list.haml b/app/views/projects/commit/_pipelines_list.haml
index 49b0b314e1d..3f699882c5f 100644
--- a/app/views/projects/commit/_pipelines_list.haml
+++ b/app/views/projects/commit/_pipelines_list.haml
@@ -8,5 +8,5 @@
} }
- content_for :page_specific_javascripts do
- = page_specific_javascript_bundle_tag('common_vue')
- = page_specific_javascript_bundle_tag('commit_pipelines')
+ = webpack_bundle_tag('common_vue')
+ = webpack_bundle_tag('commit_pipelines')
diff --git a/app/views/projects/commit/show.html.haml b/app/views/projects/commit/show.html.haml
index 2890e9d2b65..4058e61eb9a 100644
--- a/app/views/projects/commit/show.html.haml
+++ b/app/views/projects/commit/show.html.haml
@@ -7,8 +7,8 @@
- page_title "#{@commit.title} (#{@commit.short_id})", "Commits"
- page_description @commit.description
- content_for :page_specific_javascripts do
- = page_specific_javascript_bundle_tag('common_vue')
- = page_specific_javascript_bundle_tag('diff_notes')
+ = webpack_bundle_tag('common_vue')
+ = webpack_bundle_tag('diff_notes')
.container-fluid{ class: [limited_container_width, container_class] }
= render "commit_box"
diff --git a/app/views/projects/cycle_analytics/show.html.haml b/app/views/projects/cycle_analytics/show.html.haml
index 71d30da14a9..d98e0564da4 100644
--- a/app/views/projects/cycle_analytics/show.html.haml
+++ b/app/views/projects/cycle_analytics/show.html.haml
@@ -1,8 +1,8 @@
- @no_container = true
- page_title "Cycle Analytics"
- content_for :page_specific_javascripts do
- = page_specific_javascript_bundle_tag('common_vue')
- = page_specific_javascript_bundle_tag('cycle_analytics')
+ = webpack_bundle_tag('common_vue')
+ = webpack_bundle_tag('cycle_analytics')
#cycle-analytics{ class: container_class, "v-cloak" => "true", data: { request_path: project_cycle_analytics_path(@project) } }
- if @cycle_analytics_no_data
diff --git a/app/views/projects/environments/folder.html.haml b/app/views/projects/environments/folder.html.haml
index d9c9f0ed546..eca10d99908 100644
--- a/app/views/projects/environments/folder.html.haml
+++ b/app/views/projects/environments/folder.html.haml
@@ -2,8 +2,8 @@
- page_title "Environments"
- content_for :page_specific_javascripts do
- = page_specific_javascript_bundle_tag('common_vue')
- = page_specific_javascript_bundle_tag("environments_folder")
+ = webpack_bundle_tag('common_vue')
+ = webpack_bundle_tag("environments_folder")
#environments-folder-list-view{ data: { endpoint: folder_project_environments_path(@project, @folder, format: :json),
"folder-name" => @folder,
diff --git a/app/views/projects/environments/index.html.haml b/app/views/projects/environments/index.html.haml
index 88f1348da47..31cf173fa9c 100644
--- a/app/views/projects/environments/index.html.haml
+++ b/app/views/projects/environments/index.html.haml
@@ -3,8 +3,8 @@
- add_to_breadcrumbs("Pipelines", project_pipelines_path(@project))
- content_for :page_specific_javascripts do
- = page_specific_javascript_bundle_tag("common_vue")
- = page_specific_javascript_bundle_tag("environments")
+ = webpack_bundle_tag("common_vue")
+ = webpack_bundle_tag("environments")
#environments-list-view{ data: { environments_data: environments_list_data,
"can-create-deployment" => can?(current_user, :create_deployment, @project).to_s,
diff --git a/app/views/projects/environments/metrics.html.haml b/app/views/projects/environments/metrics.html.haml
index 10812f67cbe..91b3743e9e7 100644
--- a/app/views/projects/environments/metrics.html.haml
+++ b/app/views/projects/environments/metrics.html.haml
@@ -2,7 +2,6 @@
- page_title "Metrics for environment", @environment.name
- content_for :page_specific_javascripts do
= webpack_bundle_tag 'common_vue'
- = webpack_bundle_tag 'common_d3'
.prometheus-container{ class: container_class }
.top-area
diff --git a/app/views/projects/environments/terminal.html.haml b/app/views/projects/environments/terminal.html.haml
index a073a164f11..7be4ef39117 100644
--- a/app/views/projects/environments/terminal.html.haml
+++ b/app/views/projects/environments/terminal.html.haml
@@ -3,7 +3,7 @@
- content_for :page_specific_javascripts do
= stylesheet_link_tag "xterm/xterm"
- = page_specific_javascript_bundle_tag("terminal")
+ = webpack_bundle_tag("terminal")
%div{ class: container_class }
.top-area
diff --git a/app/views/projects/graphs/charts.html.haml b/app/views/projects/graphs/charts.html.haml
index 300a39fe257..d4b4a6203f3 100644
--- a/app/views/projects/graphs/charts.html.haml
+++ b/app/views/projects/graphs/charts.html.haml
@@ -1,9 +1,5 @@
- @no_container = true
- page_title "Charts"
-- content_for :page_specific_javascripts do
- = webpack_bundle_tag('common_d3')
- = webpack_bundle_tag('graphs')
- = webpack_bundle_tag('graphs_charts')
.repo-charts{ class: container_class }
%h4.sub-header
diff --git a/app/views/projects/graphs/show.html.haml b/app/views/projects/graphs/show.html.haml
index cce16bc58b3..c81ee6874e3 100644
--- a/app/views/projects/graphs/show.html.haml
+++ b/app/views/projects/graphs/show.html.haml
@@ -1,9 +1,5 @@
- @no_container = true
- page_title _('Contributors')
-- content_for :page_specific_javascripts do
- = webpack_bundle_tag('common_d3')
- = webpack_bundle_tag('graphs')
- = webpack_bundle_tag('graphs_show')
.js-graphs-show{ class: container_class, 'data-project-graph-path': project_graph_path(@project, current_ref, format: :json) }
.sub-header-block
diff --git a/app/views/projects/issues/show.html.haml b/app/views/projects/issues/show.html.haml
index 1f28d8acff6..b9dd4c27e63 100644
--- a/app/views/projects/issues/show.html.haml
+++ b/app/views/projects/issues/show.html.haml
@@ -87,5 +87,5 @@
= render 'shared/issuable/sidebar', issuable: @issue
-= page_specific_javascript_bundle_tag('common_vue')
-= page_specific_javascript_bundle_tag('issue_show')
+= webpack_bundle_tag('common_vue')
+= webpack_bundle_tag('issue_show')
diff --git a/app/views/projects/merge_requests/conflicts.html.haml b/app/views/projects/merge_requests/conflicts.html.haml
index 454bc359b6b..2a2e57027be 100644
--- a/app/views/projects/merge_requests/conflicts.html.haml
+++ b/app/views/projects/merge_requests/conflicts.html.haml
@@ -1,7 +1,7 @@
- page_title "Merge Conflicts", "#{@merge_request.title} (#{@merge_request.to_reference}", "Merge Requests"
- content_for :page_specific_javascripts do
- = page_specific_javascript_bundle_tag('common_vue')
- = page_specific_javascript_bundle_tag('merge_conflicts')
+ = webpack_bundle_tag('common_vue')
+ = webpack_bundle_tag('merge_conflicts')
= page_specific_javascript_tag('lib/ace.js')
= render "projects/merge_requests/mr_title"
diff --git a/app/views/projects/merge_requests/conflicts/show.html.haml b/app/views/projects/merge_requests/conflicts/show.html.haml
index 454bc359b6b..2a2e57027be 100644
--- a/app/views/projects/merge_requests/conflicts/show.html.haml
+++ b/app/views/projects/merge_requests/conflicts/show.html.haml
@@ -1,7 +1,7 @@
- page_title "Merge Conflicts", "#{@merge_request.title} (#{@merge_request.to_reference}", "Merge Requests"
- content_for :page_specific_javascripts do
- = page_specific_javascript_bundle_tag('common_vue')
- = page_specific_javascript_bundle_tag('merge_conflicts')
+ = webpack_bundle_tag('common_vue')
+ = webpack_bundle_tag('merge_conflicts')
= page_specific_javascript_tag('lib/ace.js')
= render "projects/merge_requests/mr_title"
diff --git a/app/views/projects/network/show.html.haml b/app/views/projects/network/show.html.haml
index 2efb7fc719f..97be8950db0 100644
--- a/app/views/projects/network/show.html.haml
+++ b/app/views/projects/network/show.html.haml
@@ -1,7 +1,7 @@
- breadcrumb_title "Graph"
- page_title "Graph", @ref
- content_for :page_specific_javascripts do
- = page_specific_javascript_bundle_tag('network')
+ = webpack_bundle_tag('network')
= render "head"
%div{ class: container_class }
.project-network
diff --git a/app/views/projects/pipelines/index.html.haml b/app/views/projects/pipelines/index.html.haml
index f8555f11aab..fdcc60f48a5 100644
--- a/app/views/projects/pipelines/index.html.haml
+++ b/app/views/projects/pipelines/index.html.haml
@@ -13,5 +13,5 @@
"ci-lint-path" => ci_lint_path,
"reset-cache-path" => reset_cache_project_settings_ci_cd_path(@project) } }
- = page_specific_javascript_bundle_tag('common_vue')
- = page_specific_javascript_bundle_tag('pipelines')
+ = webpack_bundle_tag('common_vue')
+ = webpack_bundle_tag('pipelines')
diff --git a/app/views/projects/protected_branches/_index.html.haml b/app/views/projects/protected_branches/_index.html.haml
index 2f30fe33a97..127a338e413 100644
--- a/app/views/projects/protected_branches/_index.html.haml
+++ b/app/views/projects/protected_branches/_index.html.haml
@@ -1,5 +1,5 @@
- content_for :page_specific_javascripts do
- = page_specific_javascript_bundle_tag('protected_branches')
+ = webpack_bundle_tag('protected_branches')
- content_for :create_protected_branch do
= render 'projects/protected_branches/create_protected_branch'
diff --git a/app/views/projects/protected_tags/_index.html.haml b/app/views/projects/protected_tags/_index.html.haml
index 955220562a6..74f7f63c941 100644
--- a/app/views/projects/protected_tags/_index.html.haml
+++ b/app/views/projects/protected_tags/_index.html.haml
@@ -1,5 +1,5 @@
- content_for :page_specific_javascripts do
- = page_specific_javascript_bundle_tag('protected_tags')
+ = webpack_bundle_tag('protected_tags')
- content_for :create_protected_tag do
= render 'projects/protected_tags/create_protected_tag'
diff --git a/app/views/projects/registry/repositories/index.html.haml b/app/views/projects/registry/repositories/index.html.haml
index 36ea5e013e4..744b88760bc 100644
--- a/app/views/projects/registry/repositories/index.html.haml
+++ b/app/views/projects/registry/repositories/index.html.haml
@@ -14,8 +14,8 @@
.col-lg-12
#js-vue-registry-images{ data: { endpoint: project_container_registry_index_path(@project, format: :json) } }
- = page_specific_javascript_bundle_tag('common_vue')
- = page_specific_javascript_bundle_tag('registry_list')
+ = webpack_bundle_tag('common_vue')
+ = webpack_bundle_tag('registry_list')
.row.prepend-top-10
.col-lg-12
diff --git a/app/views/projects/settings/repository/show.html.haml b/app/views/projects/settings/repository/show.html.haml
index 517d51993d2..3077203c2a6 100644
--- a/app/views/projects/settings/repository/show.html.haml
+++ b/app/views/projects/settings/repository/show.html.haml
@@ -3,8 +3,8 @@
- @content_class = "limit-container-width" unless fluid_layout
- content_for :page_specific_javascripts do
- = page_specific_javascript_bundle_tag('common_vue')
- = page_specific_javascript_bundle_tag('deploy_keys')
+ = webpack_bundle_tag('common_vue')
+ = webpack_bundle_tag('deploy_keys')
-# Protected branches & tags use a lot of nested partials.
-# The shared parts of the views can be found in the `shared` directory.
diff --git a/app/views/shared/issuable/_sidebar.html.haml b/app/views/shared/issuable/_sidebar.html.haml
index 15fd01c8429..dc583d3eb3b 100644
--- a/app/views/shared/issuable/_sidebar.html.haml
+++ b/app/views/shared/issuable/_sidebar.html.haml
@@ -1,7 +1,7 @@
- todo = issuable_todo(issuable)
- content_for :page_specific_javascripts do
- = page_specific_javascript_bundle_tag('common_vue')
- = page_specific_javascript_bundle_tag('sidebar')
+ = webpack_bundle_tag('common_vue')
+ = webpack_bundle_tag('sidebar')
%aside.right-sidebar.js-right-sidebar.js-issuable-sidebar{ data: { signed: { in: current_user.present? } }, class: sidebar_gutter_collapsed_class, 'aria-live' => 'polite' }
.issuable-sidebar{ data: { endpoint: "#{issuable_json_path(issuable)}" } }
diff --git a/app/views/shared/snippets/_form.html.haml b/app/views/shared/snippets/_form.html.haml
index 43322978749..2726a4934fb 100644
--- a/app/views/shared/snippets/_form.html.haml
+++ b/app/views/shared/snippets/_form.html.haml
@@ -1,6 +1,6 @@
- content_for :page_specific_javascripts do
= page_specific_javascript_tag('lib/ace.js')
- = page_specific_javascript_bundle_tag('snippet')
+ = webpack_bundle_tag('snippet')
.snippet-form-holder
= form_for @snippet, url: url, html: { class: "form-horizontal snippet-form js-requires-input js-quick-submit common-note-form" } do |f|
diff --git a/app/workers/process_commit_worker.rb b/app/workers/process_commit_worker.rb
index 52eebe475ec..5b25d980bdb 100644
--- a/app/workers/process_commit_worker.rb
+++ b/app/workers/process_commit_worker.rb
@@ -23,27 +23,25 @@ class ProcessCommitWorker
return unless user
commit = build_commit(project, commit_hash)
-
author = commit.author || user
process_commit_message(project, commit, user, author, default)
-
update_issue_metrics(commit, author)
end
def process_commit_message(project, commit, user, author, default = false)
- closed_issues = default ? commit.closes_issues(user) : []
+ # this is a GitLab generated commit message, ignore it.
+ return if commit.merged_merge_request?(user)
- unless closed_issues.empty?
- close_issues(project, user, author, commit, closed_issues)
- end
+ closed_issues = default ? commit.closes_issues(user) : []
+ close_issues(project, user, author, commit, closed_issues) if closed_issues.any?
commit.create_cross_references!(author, closed_issues)
end
def close_issues(project, user, author, commit, issues)
# We don't want to run permission related queries for every single issue,
- # therefor we use IssueCollection here and skip the authorization check in
+ # therefore we use IssueCollection here and skip the authorization check in
# Issues::CloseService#execute.
IssueCollection.new(issues).updatable_by_user(user).each do |issue|
Issues::CloseService.new(project, author)
diff --git a/changelogs/unreleased/32564-fix-double-system-closing-notes.yml b/changelogs/unreleased/32564-fix-double-system-closing-notes.yml
new file mode 100644
index 00000000000..e6e1ef8c76d
--- /dev/null
+++ b/changelogs/unreleased/32564-fix-double-system-closing-notes.yml
@@ -0,0 +1,5 @@
+---
+title: Fix duplicate system notes when merging a merge request.
+merge_request: 17035
+author:
+type: fixed
diff --git a/changelogs/unreleased/42274-group-request-membership-long-too.yml b/changelogs/unreleased/42274-group-request-membership-long-too.yml
new file mode 100644
index 00000000000..03efedba638
--- /dev/null
+++ b/changelogs/unreleased/42274-group-request-membership-long-too.yml
@@ -0,0 +1,5 @@
+---
+title: Fix long list of recipients on group request membership email
+merge_request: 17121
+author: Jacopo Beschi @jacopo-beschi
+type: fixed
diff --git a/changelogs/unreleased/4826-github-import-wiki-fix-1.yml b/changelogs/unreleased/4826-github-import-wiki-fix-1.yml
new file mode 100644
index 00000000000..69145cb6daf
--- /dev/null
+++ b/changelogs/unreleased/4826-github-import-wiki-fix-1.yml
@@ -0,0 +1,5 @@
+---
+title: "[GitHub Import] Create an empty wiki if wiki import failed"
+merge_request:
+author:
+type: fixed
diff --git a/changelogs/unreleased/flipper-caching.yml b/changelogs/unreleased/flipper-caching.yml
new file mode 100644
index 00000000000..6db27fd579e
--- /dev/null
+++ b/changelogs/unreleased/flipper-caching.yml
@@ -0,0 +1,5 @@
+---
+title: Increase feature flag cache TTL to one hour
+merge_request:
+author:
+type: performance
diff --git a/changelogs/unreleased/kp-fix-stacked-bar-progress-value-clipping.yml b/changelogs/unreleased/kp-fix-stacked-bar-progress-value-clipping.yml
new file mode 100644
index 00000000000..690536a533b
--- /dev/null
+++ b/changelogs/unreleased/kp-fix-stacked-bar-progress-value-clipping.yml
@@ -0,0 +1,5 @@
+---
+title: Fix single digit value clipping for stacked progress bar
+merge_request: 17217
+author:
+type: fixed
diff --git a/changelogs/unreleased/remove-unnecessary-validate-project.yml b/changelogs/unreleased/remove-unnecessary-validate-project.yml
new file mode 100644
index 00000000000..ebc8da03dd8
--- /dev/null
+++ b/changelogs/unreleased/remove-unnecessary-validate-project.yml
@@ -0,0 +1,5 @@
+---
+title: 'Remove unecessary validate: true from belongs_to :project'
+merge_request:
+author:
+type: fixed
diff --git a/changelogs/unreleased/sh-fix-squash-rebase-utf8-data.yml b/changelogs/unreleased/sh-fix-squash-rebase-utf8-data.yml
new file mode 100644
index 00000000000..aa43487d741
--- /dev/null
+++ b/changelogs/unreleased/sh-fix-squash-rebase-utf8-data.yml
@@ -0,0 +1,5 @@
+---
+title: Fix squash not working when diff contained non-ASCII data
+merge_request:
+author:
+type: fixed
diff --git a/changelogs/unreleased/sh-guard-read-only-user-updates.yml b/changelogs/unreleased/sh-guard-read-only-user-updates.yml
new file mode 100644
index 00000000000..b8dbd840ed9
--- /dev/null
+++ b/changelogs/unreleased/sh-guard-read-only-user-updates.yml
@@ -0,0 +1,5 @@
+---
+title: Don't attempt to update user tracked fields if database is in read-only
+merge_request:
+author:
+type: fixed
diff --git a/config/initializers/flipper.rb b/config/initializers/flipper.rb
index cc9167d29b9..c60ad535fd5 100644
--- a/config/initializers/flipper.rb
+++ b/config/initializers/flipper.rb
@@ -8,7 +8,7 @@ Flipper.configure do |config|
cached_adapter = Flipper::Adapters::ActiveSupportCacheStore.new(
adapter,
Rails.cache,
- expires_in: 10.seconds)
+ expires_in: 1.hour)
Flipper.new(cached_adapter)
end
diff --git a/config/webpack.config.js b/config/webpack.config.js
index f81f7067258..31b29075d62 100644
--- a/config/webpack.config.js
+++ b/config/webpack.config.js
@@ -62,9 +62,6 @@ var config = {
environments: './environments/environments_bundle.js',
environments_folder: './environments/folder/environments_folder_bundle.js',
filtered_search: './filtered_search/filtered_search_bundle.js',
- graphs: './graphs/graphs_bundle.js',
- graphs_charts: './graphs/graphs_charts.js',
- graphs_show: './graphs/graphs_show.js',
help: './help/help.js',
how_to_merge: './how_to_merge.js',
issue_show: './issue_show/index.js',
@@ -279,20 +276,6 @@ var config = {
},
}),
- // create cacheable common library bundle for all d3 chunks
- new webpack.optimize.CommonsChunkPlugin({
- name: 'common_d3',
- chunks: [
- 'graphs',
- 'graphs_show',
- 'monitoring',
- 'users',
- ],
- minChunks: function (module, count) {
- return module.resource && /d3-/.test(module.resource);
- },
- }),
-
// create cacheable common library bundles
new webpack.optimize.CommonsChunkPlugin({
names: ['main', 'common', 'webpack_runtime'],
diff --git a/doc/administration/auth/how_to_configure_ldap_gitlab_ce/index.md b/doc/administration/auth/how_to_configure_ldap_gitlab_ce/index.md
index 9b9b8ca89e5..aa5e9513290 100644
--- a/doc/administration/auth/how_to_configure_ldap_gitlab_ce/index.md
+++ b/doc/administration/auth/how_to_configure_ldap_gitlab_ce/index.md
@@ -1,9 +1,12 @@
-# How to configure LDAP with GitLab CE
+---
+author: Chris Wilson
+author_gitlab: MrChrisW
+level: intermediary
+article_type: admin guide
+date: 2017-05-03
+---
-> **[Article Type](../../../development/writing_documentation.html#types-of-technical-articles):** admin guide ||
-> **Level:** intermediary ||
-> **Author:** [Chris Wilson](https://gitlab.com/MrChrisW) ||
-> **Publication date:** 2017-05-03
+# How to configure LDAP with GitLab CE
## Introduction
diff --git a/doc/ci/examples/artifactory_and_gitlab/index.md b/doc/ci/examples/artifactory_and_gitlab/index.md
index 8e91cd05d8a..d931c9a77f4 100644
--- a/doc/ci/examples/artifactory_and_gitlab/index.md
+++ b/doc/ci/examples/artifactory_and_gitlab/index.md
@@ -1,14 +1,14 @@
---
redirect_from: 'https://docs.gitlab.com/ee/articles/artifactory_and_gitlab/index.html'
+author: Fabio Busatto
+author_gitlab: bikebilly
+level: intermediary
+article_type: tutorial
+date: 2017-08-15
---
# How to deploy Maven projects to Artifactory with GitLab CI/CD
-> **[Article Type](../../../development/writing_documentation.md#types-of-technical-articles):** tutorial ||
-> **Level:** intermediary ||
-> **Author:** [Fabio Busatto](https://gitlab.com/bikebilly) ||
-> **Publication date:** 2017-08-15
-
## Introduction
In this article, we will show how you can leverage the power of [GitLab CI/CD](https://about.gitlab.com/features/gitlab-ci-cd/)
diff --git a/doc/ci/examples/laravel_with_gitlab_and_envoy/index.md b/doc/ci/examples/laravel_with_gitlab_and_envoy/index.md
index e1aff6fdf36..b62874ef029 100644
--- a/doc/ci/examples/laravel_with_gitlab_and_envoy/index.md
+++ b/doc/ci/examples/laravel_with_gitlab_and_envoy/index.md
@@ -1,14 +1,14 @@
---
redirect_from: 'https://docs.gitlab.com/ee/articles/laravel_with_gitlab_and_envoy/index.html'
+author: Mehran Rasulian
+author_gitlab: mehranrasulian
+level: intermediary
+article_type: tutorial
+date: 2017-08-31
---
# Test and deploy Laravel applications with GitLab CI/CD and Envoy
-> **[Article Type](../../../development/writing_documentation.md#types-of-technical-articles):** tutorial ||
-> **Level:** intermediary ||
-> **Author:** [Mehran Rasulian](https://gitlab.com/mehranrasulian) ||
-> **Publication date:** 2017-08-31
-
## Introduction
GitLab features our applications with Continuous Integration, and it is possible to easily deploy the new code changes to the production server whenever we want.
diff --git a/doc/development/changelog.md b/doc/development/changelog.md
index c1f783ce877..757987b2e7a 100644
--- a/doc/development/changelog.md
+++ b/doc/development/changelog.md
@@ -279,8 +279,8 @@ After much discussion we settled on the current solution of one file per entry,
and then compiling the entries into the overall `CHANGELOG.md` file during the
[release process].
-[boring solution]: https://about.gitlab.com/handbook/#boring-solutions
-[release managers]: https://gitlab.com/gitlab-org/release-tools/blob/master/doc/release-manager.md
+[boring solution]: https://about.gitlab.com/handbook/values/#boring-solutions
+[release managers]: https://gitlab.com/gitlab-org/release/docs/blob/master/quickstart/release-manager.md
[started brainstorming]: https://gitlab.com/gitlab-org/gitlab-ce/issues/17826
[release process]: https://gitlab.com/gitlab-org/release-tools
diff --git a/doc/development/writing_documentation.md b/doc/development/writing_documentation.md
index 2a1d744668b..403c9d08752 100644
--- a/doc/development/writing_documentation.md
+++ b/doc/development/writing_documentation.md
@@ -240,7 +240,7 @@ Suppose there's a process to go from point A to point B in 5 steps: `(A) 1 > 2 >
A **guide** can be understood as a description of certain processes to achieve a particular objective. A guide brings you from A to B describing the characteristics of that process, but not necessarily going over each step. It can mention, for example, steps 2 and 3, but does not necessarily explain how to accomplish them.
-- Live example: "GitLab Pages from A to Z - [Part 1](../user/project/pages/getting_started_part_one.md) to [Part 4](../user/project/pages/getting_started_part_four.md)"
+- Live example: "[Static sites and GitLab Pages domains (Part 1)](../user/project/pages/getting_started_part_one.md) to [Creating and Tweaking GitLab CI/CD for GitLab Pages (Part 4)](../user/project/pages/getting_started_part_four.md)"
A **tutorial** requires a clear **step-by-step** guidance to achieve a singular objective. It brings you from A to B, describing precisely all the necessary steps involved in that process, showing each of the 5 steps to go from A to B.
It does not only describes steps 2 and 3, but also shows you how to accomplish them.
@@ -254,18 +254,25 @@ through the process of how to use it systematically.
#### Special format
-Every **Technical Article** contains, in the very beginning, a blockquote with the following information:
+Every **Technical Article** contains a frontmatter at the beginning of the doc
+with the following information:
-- A reference to the **type of article** (user guide, admin guide, tech overview, tutorial)
-- A reference to the **knowledge level** expected from the reader to be able to follow through (beginner, intermediate, advanced)
-- A reference to the **author's name** and **GitLab.com handle**
-- A reference of the **publication date**
+- **Type of article** (user guide, admin guide, technical overview, tutorial)
+- **Knowledge level** expected from the reader to be able to follow through (beginner, intermediate, advanced)
+- **Author's name** and **GitLab.com handle**
+- **Publication date** (ISO format YYYY-MM-DD)
-```md
-> **[Article Type](../../development/writing_documentation.html#types-of-technical-articles):** tutorial ||
-> **Level:** intermediary ||
-> **Author:** [Name Surname](https://gitlab.com/username) ||
-> **Publication date:** AAAA-MM-DD
+For example:
+
+
+```yaml
+---
+author: John Doe
+author_gitlab: johnDoe
+level: beginner
+article_type: user guide
+date: 2017-02-01
+---
```
#### Technical Articles - Writing Method
diff --git a/doc/install/openshift_and_gitlab/index.md b/doc/install/openshift_and_gitlab/index.md
index 448cbe1077d..1f46ee4c1ea 100644
--- a/doc/install/openshift_and_gitlab/index.md
+++ b/doc/install/openshift_and_gitlab/index.md
@@ -1,9 +1,12 @@
-# Getting started with OpenShift Origin 3 and GitLab
+---
+author: Achilleas Pipinellis
+author_gitlab: axil
+level: intermediary
+article_type: tutorial
+date: 2016-06-28
+---
-> **[Article Type](../../development/writing_documentation.html#types-of-technical-articles):** tutorial ||
-> **Level:** intermediary ||
-> **Author:** [Achilleas Pipinellis](https://gitlab.com/axil) ||
-> **Publication date:** 2016-06-28
+# Getting started with OpenShift Origin 3 and GitLab
## Introduction
diff --git a/doc/topics/git/how_to_install_git/index.md b/doc/topics/git/how_to_install_git/index.md
index 7fb578e9ea8..6c909a1ba86 100644
--- a/doc/topics/git/how_to_install_git/index.md
+++ b/doc/topics/git/how_to_install_git/index.md
@@ -1,9 +1,12 @@
-# Installing Git
+---
+author: Sean Packham
+author_gitlab: SeanPackham
+level: beginner
+article_type: user guide
+date: 2017-05-15
+---
-> **[Article Type](../../../development/writing_documentation.html#types-of-technical-articles):** user guide ||
-> **Level:** beginner ||
-> **Author:** [Sean Packham](https://gitlab.com/SeanPackham) ||
-> **Publication date:** 2017-05-15
+# Installing Git
To begin contributing to GitLab projects
you will need to install the Git client on your computer.
diff --git a/doc/topics/git/numerous_undo_possibilities_in_git/index.md b/doc/topics/git/numerous_undo_possibilities_in_git/index.md
index 6a2f7b30dd3..4cb8f083fb5 100644
--- a/doc/topics/git/numerous_undo_possibilities_in_git/index.md
+++ b/doc/topics/git/numerous_undo_possibilities_in_git/index.md
@@ -1,9 +1,12 @@
-# Numerous undo possibilities in Git
+---
+author: Crt Mori
+author_gitlab: Letme
+level: intermediary
+article_type: tutorial
+date: 2017-05-15
+---
-> **[Article Type](../../../development/writing_documentation.md#types-of-technical-articles):** tutorial ||
-> **Level:** intermediary ||
-> **Author:** [Crt Mori](https://gitlab.com/Letme) ||
-> **Publication date:** 2017-08-17
+# Numerous undo possibilities in Git
## Introduction
diff --git a/doc/user/project/pages/getting_started_part_four.md b/doc/user/project/pages/getting_started_part_four.md
index bd0cb437924..e4ee2f7cdfa 100644
--- a/doc/user/project/pages/getting_started_part_four.md
+++ b/doc/user/project/pages/getting_started_part_four.md
@@ -1,16 +1,13 @@
-# GitLab Pages from A to Z: Part 4
+---
+last_updated: 2018-02-16
+author: Marcia Ramos
+author_gitlab: marcia
+level: intermediate
+article_type: user guide
+date: 2017-02-22
+---
-> **Article [Type](../../../development/writing_documentation.html#types-of-technical-articles)**: user guide ||
-> **Level**: intermediate ||
-> **Author**: [Marcia Ramos](https://gitlab.com/marcia) ||
-> **Publication date:** 2017/02/22
-
-- [Part 1: Static sites and GitLab Pages domains](getting_started_part_one.md)
-- [Part 2: Quick start guide - Setting up GitLab Pages](getting_started_part_two.md)
-- [Part 3: Setting Up Custom Domains - DNS Records and SSL/TLS Certificates](getting_started_part_three.md)
-- **Part 4: Creating and tweaking `.gitlab-ci.yml` for GitLab Pages**
-
-## Creating and Tweaking `.gitlab-ci.yml` for GitLab Pages
+# Creating and Tweaking GitLab CI/CD for GitLab Pages
[GitLab CI](https://about.gitlab.com/gitlab-ci/) serves
numerous purposes, to build, test, and deploy your app
@@ -19,10 +16,13 @@ from GitLab through
methods. You will need it to build your website with GitLab Pages,
and deploy it to the Pages server.
+To implement GitLab CI/CD, the first thing we need is a configuration
+file called `.gitlab-ci.yml` placed at your website's root directory.
+
What this file actually does is telling the
[GitLab Runner](https://docs.gitlab.com/runner/) to run scripts
as you would do from the command line. The Runner acts as your
-terminal. GitLab CI tells the Runner which commands to run.
+terminal. GitLab CI/CD tells the Runner which commands to run.
Both are built-in in GitLab, and you don't need to set up
anything for them to work.
@@ -34,7 +34,7 @@ need to understand just a few things to be able to write our own
with its own syntax. You can always check your CI syntax with
the [GitLab CI Lint Tool](https://gitlab.com/ci/lint).
-**Practical Example:**
+## Practical example
Let's consider you have a [Jekyll](https://jekyllrb.com/) site.
To build it locally, you would open your terminal, and run `jekyll build`.
@@ -384,7 +384,3 @@ in parallel, or build a custom pipeline](https://about.gitlab.com/2016/07/29/the
[pulling specific directories from different projects](https://about.gitlab.com/2016/12/07/building-a-new-gitlab-docs-site-with-nanoc-gitlab-ci-and-gitlab-pages/)
to deploy this website you're looking at, docs.gitlab.com.
- On this blog post, we teach you [how to use GitLab Pages to produce a code coverage report](https://about.gitlab.com/2016/11/03/publish-code-coverage-report-with-gitlab-pages/).
-
-|||
-|:--|--:|
-|[**← Part 3: Setting Up Custom Domains - DNS Records and SSL/TLS Certificates**](getting_started_part_three.md)||
diff --git a/doc/user/project/pages/getting_started_part_one.md b/doc/user/project/pages/getting_started_part_one.md
index 1e19f422d94..290dfa5af84 100644
--- a/doc/user/project/pages/getting_started_part_one.md
+++ b/doc/user/project/pages/getting_started_part_one.md
@@ -1,31 +1,28 @@
-# GitLab Pages from A to Z: Part 1
-
-> **Article [Type](../../../development/writing_documentation.html#types-of-technical-articles)**: user guide ||
-> **Level**: beginner ||
-> **Author**: [Marcia Ramos](https://gitlab.com/marcia) ||
-> **Publication date:** 2017/02/22
-
-- **Part 1: Static sites and GitLab Pages domains**
-- [Part 2: Quick start guide - Setting up GitLab Pages](getting_started_part_two.md)
-- [Part 3: Setting Up Custom Domains - DNS Records and SSL/TLS Certificates](getting_started_part_three.md)
-- [Part 4: Creating and tweaking `.gitlab-ci.yml` for GitLab Pages](getting_started_part_four.md)
-
-## GitLab Pages from A to Z
-
-This is a comprehensive guide, made for those who want to
+---
+last_updated: 2018-02-16
+author: Marcia Ramos
+author_gitlab: marcia
+level: beginner
+article_type: user guide
+date: 2017-02-22
+---
+
+# Static sites and GitLab Pages domains
+
+This document is the beginning of a comprehensive guide, made for those who want to
publish a website with GitLab Pages but aren't familiar with
the entire process involved.
-This [first part](#what-you-need-to-know-before-getting-started) of this series will present you to the concepts of
+This [first document](#what-you-need-to-know-before-getting-started) of this series will present you to the concepts of
static sites, and go over how the default Pages domains work.
-The [second part](getting_started_part_two.md) covers how to get started with GitLab Pages: deploy
+The [second document](getting_started_part_two.md) covers how to get started with GitLab Pages: deploy
a website from a forked project or create a new one from scratch.
-The [third part](getting_started_part_three.md) will show you how to set up a custom domain or subdomain
+The [third document](getting_started_part_three.md) will show you how to set up a custom domain or subdomain
to your site already deployed.
-The [fourth part](getting_started_part_four.md) will show you how to create and tweak GitLab CI for
+The [fourth document](getting_started_part_four.md) will show you how to create and tweak GitLab CI for
GitLab Pages.
To **enable** GitLab Pages for GitLab CE (Community Edition)
@@ -113,6 +110,4 @@ You can only create the highest level group website.
- On your GitLab instance, replace `gitlab.io` above with your
Pages server domain. Ask your sysadmin for this information.
-|||
-|:--|--:|
-||[**Part 2: Quick start guide - Setting up GitLab Pages →**](getting_started_part_two.md)|
+_Read on about [Projects for GitLab Pages and URL structure](getting_started_part_two.md)._
diff --git a/doc/user/project/pages/getting_started_part_three.md b/doc/user/project/pages/getting_started_part_three.md
index a153610c712..b6cf68a02a2 100644
--- a/doc/user/project/pages/getting_started_part_three.md
+++ b/doc/user/project/pages/getting_started_part_three.md
@@ -1,27 +1,19 @@
---
-last_updated: 2017-09-28
+last_updated: 2018-02-16
+author: Marcia Ramos
+author_gitlab: marcia
+level: beginner
+article_type: user guide
+date: 2017-02-22
---
-# GitLab Pages from A to Z: Part 3
+# GitLab Pages custom domains and SSL/TLS Certificates
-> **[Article Type](../../../development/writing_documentation.md#types-of-technical-articles)**: user guide ||
-> **Level**: beginner ||
-> **Author**: [Marcia Ramos](https://gitlab.com/marcia) ||
-> **Publication date:** 2017-02-22 ||
-> **Last updated**: 2017-09-28
-
-- [Part 1: Static sites and GitLab Pages domains](getting_started_part_one.md)
-- [Part 2: Quick start guide - Setting up GitLab Pages](getting_started_part_two.md)
-- **Part 3: Setting Up Custom Domains - DNS Records and SSL/TLS Certificates**
-- [Part 4: Creating and tweaking `.gitlab-ci.yml` for GitLab Pages](getting_started_part_four.md)
-
-## Setting Up Custom Domains - DNS Records and SSL/TLS Certificates
-
-As described in the previous part of this series, setting up GitLab Pages with custom domains, and adding SSL/TLS certificates to them, are optional features of GitLab Pages.
+Setting up GitLab Pages with custom domains, and adding SSL/TLS certificates to them, are optional features of GitLab Pages.
These steps assume you've already [set your site up](getting_started_part_two.md) and and it's served under the default Pages domain `namespace.gitlab.io`, or `namespace.gitlab.io/project-name`.
-### Adding your custom domain to GitLab Pages
+## Adding your custom domain to GitLab Pages
To use one or more custom domain with your Pages site, there are two things
you should consider first, which we'll cover in this guide:
@@ -36,7 +28,7 @@ Let's start from the beginning with [DNS records](#dns-records).
If you already know how they work and want to skip the introduction to DNS,
you may be interested in skipping it until the [TL;DR](#tl-dr) section below.
-### DNS Records
+## DNS Records
A Domain Name System (DNS) web service routes visitors to websites
by translating domain names (such as `www.example.com`) into the
@@ -72,7 +64,7 @@ for the most popular hosting services:
If your hosting service is not listed above, you can just try to
search the web for "how to add dns record on <my hosting service>".
-#### DNS A record
+### DNS A record
In case you want to point a root domain (`example.com`) to your
GitLab Pages site, deployed to `namespace.gitlab.io`, you need to
@@ -87,7 +79,7 @@ running on your instance).
![DNS A record pointing to GitLab.com Pages server](img/dns_add_new_a_record_example_updated.png)
-#### DNS CNAME record
+### DNS CNAME record
In case you want to point a subdomain (`hello-world.example.com`)
to your GitLab Pages site initially deployed to `namespace.gitlab.io`,
@@ -103,7 +95,7 @@ without any `/project-name`.
![DNS CNAME record pointing to GitLab.com project](img/dns_cname_record_example.png)
-#### TL;DR
+### TL;DR
| From | DNS Record | To |
| ---- | ---------- | -- |
@@ -119,7 +111,7 @@ domain. E.g., **do not** point your `subdomain.domain.com` to
`namespace.gitlab.io.` or `namespace.gitlab.io/`.
> - GitLab Pages IP on GitLab.com [has been changed](https://about.gitlab.com/2017/03/06/we-are-changing-the-ip-of-gitlab-pages-on-gitlab-com/) from `104.208.235.32` to `52.167.214.135`.
-### Add your custom domain to GitLab Pages settings
+## Add your custom domain to GitLab Pages settings
Once you've set the DNS record, you'll need navigate to your project's
**Setting > Pages** and click **+ New domain** to add your custom domain to
@@ -142,7 +134,7 @@ to your domain will respond with a 404.
Read through the [general documentation on GitLab Pages](introduction.md#add-a-custom-domain-to-your-pages-website) to learn more about adding
custom domains to GitLab Pages sites.
-### SSL/TLS Certificates
+## SSL/TLS Certificates
Every GitLab Pages project on GitLab.com will be available under
HTTPS for the default Pages domain (`*.gitlab.io`). Once you set
@@ -158,7 +150,7 @@ highly recommendable.
Let's start with an introduction to the importance of HTTPS.
Alternatively, jump ahead to [adding certificates to your project](#adding-certificates-to-your-project).
-#### Why should I care about HTTPS?
+### Why should I care about HTTPS?
This might be your first question. If our sites are hosted by GitLab Pages,
they are static, hence we are not dealing with server-side scripts
@@ -179,7 +171,7 @@ authentications and validations.
How about taking Josh's advice and protecting our sites too? We will be
well supported, and we'll contribute to a safer internet.
-#### Organizations supporting HTTPS
+### Organizations supporting HTTPS
There is a huge movement in favor of securing all the web. W3C fully
[supports the cause](https://w3ctag.github.io/web-https/) and explains very well
@@ -189,7 +181,7 @@ and would no longer accept unsecured connections. Recently, Mozilla published a
[communication](https://blog.mozilla.org/security/2016/03/29/march-2016-ca-communication/)
reiterating the importance of HTTPS.
-### Issuing Certificates
+## Issuing Certificates
GitLab Pages accepts [PEM](https://support.quovadisglobal.com/kb/a37/what-is-pem-format.aspx) certificates issued by
[Certificate Authorities (CA)](https://en.wikipedia.org/wiki/Certificate_authority)
@@ -218,7 +210,7 @@ Their certs are valid up to 15 years. Read through the tutorial on
Regardless the CA you choose, the steps to add your certificate to
your Pages project are the same.
-#### What do you need
+### What do you need
1. A PEM certificate
1. An intermediate certificate
@@ -228,7 +220,7 @@ your Pages project are the same.
These fields are found under your **Project**'s **Settings** > **Pages** > **New Domain**.
-#### What's what?
+### What's what?
- A PEM certificate is the certificate generated by the CA,
which needs to be added to the field **Certificate (PEM)**.
@@ -241,7 +233,7 @@ are one of these cases.
- A public key is an encrypted key which validates
your PEM against your domain.
-#### Now what?
+### Now what?
Now that you hopefully understand why you need all
of this, it's simple:
@@ -258,6 +250,4 @@ just jumping a line between them.
regular text editors. Always use code editors (such as
Sublime Text, Atom, Dreamweaver, Brackets, etc).
-|||
-|:--|--:|
-|[**← Part 2: Quick start guide - Setting up GitLab Pages**](getting_started_part_two.md)|[**Part 4: Creating and tweaking `.gitlab-ci.yml` for GitLab Pages →**](getting_started_part_four.md)|
+_Read on about [Creating and Tweaking GitLab CI/CD for GitLab Pages](getting_started_part_four.md)_
diff --git a/doc/user/project/pages/getting_started_part_two.md b/doc/user/project/pages/getting_started_part_two.md
index 4a724dd5c1b..2274cac8ace 100644
--- a/doc/user/project/pages/getting_started_part_two.md
+++ b/doc/user/project/pages/getting_started_part_two.md
@@ -1,27 +1,23 @@
-# GitLab Pages from A to Z: Part 2
+---
+last_updated: 2018-02-16
+author: Marcia Ramos
+author_gitlab: marcia
+level: beginner
+article_type: user guide
+date: 2017-02-22
+---
-> **Article [Type](../../../development/writing_documentation.html#types-of-technical-articles)**: user guide ||
-> **Level**: beginner ||
-> **Author**: [Marcia Ramos](https://gitlab.com/marcia) ||
-> **Publication date:** 2017/02/22
-
-- [Part 1: Static sites and GitLab Pages domains](getting_started_part_one.md)
-- **Part 2: Quick start guide - Setting up GitLab Pages**
-- [Part 3: Setting Up Custom Domains - DNS Records and SSL/TLS Certificates](getting_started_part_three.md)
-- [Part 4: Creating and tweaking `.gitlab-ci.yml` for GitLab Pages](getting_started_part_four.md)
-
-## Setting up GitLab Pages
-
-For a complete step-by-step tutorial, please read the
-blog post [Hosting on GitLab.com with GitLab Pages](https://about.gitlab.com/2016/04/07/gitlab-pages-setup/). The following sections will explain
-what do you need and why do you need them.
+# Projects for GitLab Pages and URL structure
## What you need to get started
+To get started with GitLab Pages, you need:
+
1. A project
1. A configuration file (`.gitlab-ci.yml`) to deploy your site
1. A specific `job` called `pages` in the configuration file
that will make GitLab aware that you are deploying a GitLab Pages website
+1. A `public` directory with the content of the website
Optional Features:
@@ -51,35 +47,26 @@ containing the most popular SSGs templates.
Watch the [video tutorial](https://youtu.be/TWqh9MtT4Bg) we've
created for the steps below.
-1. Choose your SSG template
-1. Fork a project from the [Pages group](https://gitlab.com/pages)
-1. Remove the fork relationship by navigating to your **Project**'s **Settings** > **Edit Project**
+1. [Fork a sample project](../../../gitlab-basics/fork-project.md) from the [Pages group](https://gitlab.com/pages)
+1. Trigger a build (push a change to any file)
+1. As soon as the build passes, your website will have been deployed with GitLab Pages. Your website URL will be available under your project's **Settings** > **Pages**
+1. Optionally, remove the fork relationship by navigating to your project's **Settings** > expanding **Advanced settings** and scrolling down to **Remove fork relashionship**:
![remove fork relashionship](img/remove_fork_relashionship.png)
-1. Enable Shared Runners for your fork: navigate to your **Project**'s **Settings** > **Pipelines**
-1. Trigger a build (push a change to any file)
-1. As soon as the build passes, your website will have been deployed with GitLab Pages. Your website URL will be available under your **Project**'s **Settings** > **Pages**
-
To turn a **project website** forked from the Pages group into a **user/group** website, you'll need to:
-- Rename it to `namespace.gitlab.io`: navigate to **Project**'s **Settings** > **Edit Project** > **Rename repository**
+- Rename it to `namespace.gitlab.io`: navigate to project's **Settings** > expand **Advanced settings** > and scroll down to **Rename repository**
- Adjust your SSG's [base URL](#urls-and-baseurls) to from `"project-name"` to `""`. This setting will be at a different place for each SSG, as each of them have their own structure and file tree. Most likelly, it will be in the SSG's config file.
> **Notes:**
>
->1. Why do I need to remove the fork relationship?
+> Why do I need to remove the fork relationship?
>
-> Unless you want to contribute to the original project,
+> Unless you want to contribute to the original project,
you won't need it connected to the upstream. A
[fork](https://about.gitlab.com/2016/12/01/how-to-keep-your-fork-up-to-date-with-its-origin/#fork)
is useful for submitting merge requests to the upstream.
->
-> 2. Why do I need to enable Shared Runners?
->
-> Shared Runners will run the script set by your GitLab CI/CD
-configuration file. They're enabled by default to new projects,
-but not to forks.
### Create a project from scratch
@@ -108,7 +95,7 @@ where you'll find its default URL.
> - GitLab Pages [supports any SSG](https://about.gitlab.com/2016/06/17/ssg-overview-gitlab-pages-part-3-examples-ci/), but,
if you don't find yours among the templates, you'll need
to configure your own `.gitlab-ci.yml`. Do do that, please
-read through the article [Creating and Tweaking `.gitlab-ci.yml` for GitLab Pages](getting_started_part_four.md). New SSGs are very welcome among
+read through the article [Creating and Tweaking GitLab CI/CD for GitLab Pages](getting_started_part_four.md). New SSGs are very welcome among
the [example projects](https://gitlab.com/pages). If you set
up a new one, please
[contribute](https://gitlab.com/pages/pages.gitlab.io/blob/master/CONTRIBUTING.md)
@@ -121,7 +108,7 @@ you can run `git init` in your local website directory, add the
remote URL: `git remote add origin git@gitlab.com:namespace/project-name.git`,
then add, commit, and push.
-### URLs and Baseurls
+## URLs and Baseurls
Every Static Site Generator (SSG) default configuration expects
to find your website under a (sub)domain (`example.com`), not
@@ -149,11 +136,7 @@ example we've just mentioned, you'd have to change Jekyll's `_config.yml` to:
baseurl: ""
```
-### Custom Domains
+## Custom Domains
-GitLab Pages supports custom domains and subdomains, served under HTTPS or HTTPS.
+GitLab Pages supports custom domains and subdomains, served under HTTP or HTTPS.
Please check the [next part](getting_started_part_three.md) of this series for an overview.
-
-|||
-|:--|--:|
-|[**← Part 1: Static sites, domains, DNS records, and SSL/TLS certificates**](getting_started_part_one.md)|[**Setting Up Custom Domains - DNS Records and SSL/TLS Certificates →**](getting_started_part_three.md)|
diff --git a/doc/user/project/pages/index.md b/doc/user/project/pages/index.md
index df245710940..a65aa758198 100644
--- a/doc/user/project/pages/index.md
+++ b/doc/user/project/pages/index.md
@@ -37,10 +37,10 @@ to secure them.
Read the following tutorials to know more about:
-- [Static websites and GitLab Pages domains](getting_started_part_one.md)
-- [Forking projects and creating new ones from scratch, URLs and baseurls](getting_started_part_two.md)
-- [Custom domains and subdomains, DNS records, SSL/TLS certificates](getting_started_part_three.md)
-- [How to create your own `.gitlab-ci.yml` for your site](getting_started_part_four.md)
+- [Static websites and GitLab Pages domains](getting_started_part_one.md): Understand what is a static website, and how GitLab Pages default domains work
+- [Projects for GitLab Pages and URL structure](getting_started_part_two.md): Forking projects and creating new ones from scratch, understanding URLs structure and baseurls
+- [GitLab Pages custom domains and SSL/TLS Certificates](getting_started_part_three.md): How to add custom domains and subdomains to your website, configure DNS records, and SSL/TLS certificates
+- [Creating and Tweaking GitLab CI/CD for GitLab Pages](getting_started_part_four.md): Understand how to create your own `.gitlab-ci.yml` for your site
- [Technical aspects, custom 404 pages, limitations](introduction.md)
- [Hosting on GitLab.com with GitLab Pages](https://about.gitlab.com/2016/04/07/gitlab-pages-setup/) (outdated)
diff --git a/doc/workflow/lfs/manage_large_binaries_with_git_lfs.md b/doc/workflow/lfs/manage_large_binaries_with_git_lfs.md
index 8fff3d591fe..377eee69c11 100644
--- a/doc/workflow/lfs/manage_large_binaries_with_git_lfs.md
+++ b/doc/workflow/lfs/manage_large_binaries_with_git_lfs.md
@@ -34,7 +34,7 @@ Documentation for GitLab instance administrators is under [LFS administration do
credentials store is recommended
* Git LFS always assumes HTTPS so if you have GitLab server on HTTP you will have
to add the URL to Git config manually (see [troubleshooting](#troubleshooting))
-
+
>**Note**: With 8.12 GitLab added LFS support to SSH. The Git LFS communication
still goes over HTTP, but now the SSH client passes the correct credentials
to the Git LFS client, so no action is required by the user.
@@ -85,6 +85,8 @@ git lfs fetch master
## File Locking
+> [Introduced](https://gitlab.com/gitlab-org/gitlab-ce/issues/35856) in GitLab 10.5.
+
The first thing to do before using File Locking is to tell Git LFS which
kind of files are lockable. The following command will store PNG files
in LFS and flag them as lockable:
diff --git a/features/project/network_graph.feature b/features/project/network_graph.feature
deleted file mode 100644
index 93c884e23c5..00000000000
--- a/features/project/network_graph.feature
+++ /dev/null
@@ -1,46 +0,0 @@
-Feature: Project Network Graph
- Background:
- Given I sign in as a user
- And I own project "Shop"
- And I visit project "Shop" network page
-
- @javascript
- Scenario: I should see project network
- Then page should have network graph
- And page should select "master" in select box
- And page should have "master" on graph
-
- @javascript
- Scenario: I should see project network with 'test' branch
- When I visit project network page on branch 'test'
- Then page should have 'test' on graph
-
- @javascript
- Scenario: I should switch "branch" and "tag"
- When I switch ref to "feature"
- Then page should select "feature" in select box
- And page should have "feature" on graph
- When I switch ref to "v1.0.0"
- Then page should select "v1.0.0" in select box
- And page should have "v1.0.0" on graph
-
- @javascript
- Scenario: I should looking for a commit by SHA
- When I looking for a commit by SHA of "v1.0.0"
- Then page should have network graph
- And page should select "master" in select box
- And page should have "v1.0.0" on graph
-
- @javascript
- Scenario: I should filter selected tag
- When I switch ref to "v1.0.0"
- Then page should have "v1.0.0" in title
- Then page should have content not containing "v1.0.0"
- When click "Show only selected branch" checkbox
- Then page should only have content from "v1.0.0"
- When click "Show only selected branch" checkbox
- Then page should have content not containing "v1.0.0"
-
- Scenario: I should fail to look for a commit
- When I look for a commit by ";"
- Then I should see non-existent git revision error message
diff --git a/features/steps/project/network_graph.rb b/features/steps/project/network_graph.rb
deleted file mode 100644
index ba98d861e7b..00000000000
--- a/features/steps/project/network_graph.rb
+++ /dev/null
@@ -1,116 +0,0 @@
-class Spinach::Features::ProjectNetworkGraph < Spinach::FeatureSteps
- include SharedAuthentication
- include SharedPaths
- include SharedProject
-
- step 'page should have network graph' do
- expect(page).to have_selector ".network-graph"
- end
-
- When 'I visit project "Shop" network page' do
- # Stub Graph max_size to speed up test (10 commits vs. 650)
- Network::Graph.stub(max_count: 10)
-
- @project = Project.find_by(name: "Shop")
- visit project_network_path(@project, "master")
- end
-
- step "I visit project network page on branch 'test'" do
- visit project_network_path(@project, "'test'")
- end
-
- step 'page should select "master" in select box' do
- expect(page).to have_selector '.dropdown-menu-toggle', text: "master"
- end
-
- step 'page should select "v1.0.0" in select box' do
- expect(page).to have_selector '.dropdown-menu-toggle', text: "v1.0.0"
- end
-
- step 'page should have "master" on graph' do
- page.within '.network-graph' do
- expect(page).to have_content 'master'
- end
- end
-
- step "page should have 'test' on graph" do
- page.within '.network-graph' do
- expect(page).to have_content "'test'"
- end
- end
-
- When 'I switch ref to "feature"' do
- first('.js-project-refs-dropdown').click
-
- page.within '.project-refs-form' do
- click_link 'feature'
- end
- end
-
- When 'I switch ref to "v1.0.0"' do
- first('.js-project-refs-dropdown').click
-
- page.within '.project-refs-form' do
- click_link 'v1.0.0'
- end
- end
-
- When 'click "Show only selected branch" checkbox' do
- find('#filter_ref').click
- end
-
- step 'page should have content not containing "v1.0.0"' do
- page.within '.network-graph' do
- expect(page).to have_content 'Change some files'
- end
- end
-
- step 'page should have "v1.0.0" in title' do
- expect(page).to have_css 'title', text: 'Graph · v1.0.0', visible: false
- end
-
- step 'page should only have content from "v1.0.0"' do
- page.within '.network-graph' do
- expect(page).not_to have_content 'Change some files'
- end
- end
-
- step 'page should select "feature" in select box' do
- expect(page).to have_selector '.dropdown-menu-toggle', text: "feature"
- end
-
- step 'page should select "v1.0.0" in select box' do
- expect(page).to have_selector '.dropdown-menu-toggle', text: "v1.0.0"
- end
-
- step 'page should have "feature" on graph' do
- page.within '.network-graph' do
- expect(page).to have_content 'feature'
- end
- end
-
- When 'I looking for a commit by SHA of "v1.0.0"' do
- page.within ".network-form" do
- fill_in 'extended_sha1', with: '6f6d7e7ed97bb5f0054f2b1df789b39ca89b6ff9'
- find('button').click
- end
- sleep 2
- end
-
- step 'page should have "v1.0.0" on graph' do
- page.within '.network-graph' do
- expect(page).to have_content 'v1.0.0'
- end
- end
-
- When 'I look for a commit by ";"' do
- page.within ".network-form" do
- fill_in 'extended_sha1', with: ';'
- find('button').click
- end
- end
-
- step 'I should see non-existent git revision error message' do
- expect(page).to have_selector '.flash-alert', text: "Git revision ';' does not exist."
- end
-end
diff --git a/lib/gitlab/checks/change_access.rb b/lib/gitlab/checks/change_access.rb
index 521680b8708..3ce5f807989 100644
--- a/lib/gitlab/checks/change_access.rb
+++ b/lib/gitlab/checks/change_access.rb
@@ -121,6 +121,7 @@ module Gitlab
def commits_check
return if deletion? || newrev.nil?
+ return unless should_run_commit_validations?
# n+1: https://gitlab.com/gitlab-org/gitlab-ee/issues/3593
::Gitlab::GitalyClient.allow_n_plus_1_calls do
@@ -139,6 +140,10 @@ module Gitlab
private
+ def should_run_commit_validations?
+ commit_check.validate_lfs_file_locks?
+ end
+
def updated_from_web?
protocol == 'web'
end
@@ -176,7 +181,7 @@ module Gitlab
end
def commits
- project.repository.new_commits(newrev)
+ @commits ||= project.repository.new_commits(newrev)
end
end
end
diff --git a/lib/gitlab/checks/commit_check.rb b/lib/gitlab/checks/commit_check.rb
index ae0cd142378..43a52b493bb 100644
--- a/lib/gitlab/checks/commit_check.rb
+++ b/lib/gitlab/checks/commit_check.rb
@@ -35,14 +35,14 @@ module Gitlab
end
end
- private
-
def validate_lfs_file_locks?
strong_memoize(:validate_lfs_file_locks) do
project.lfs_enabled? && project.lfs_file_locks.any? && newrev && oldrev
end
end
+ private
+
def lfs_file_locks_validation
lambda do |paths|
lfs_lock = project.lfs_file_locks.where(path: paths).where.not(user_id: user.id).first
diff --git a/lib/gitlab/git/commit.rb b/lib/gitlab/git/commit.rb
index d95561fe1b2..ae27a138b7c 100644
--- a/lib/gitlab/git/commit.rb
+++ b/lib/gitlab/git/commit.rb
@@ -508,7 +508,7 @@ module Gitlab
@committed_date = Time.at(commit.committer.date.seconds).utc
@committer_name = commit.committer.name.dup
@committer_email = commit.committer.email.dup
- @parent_ids = commit.parent_ids
+ @parent_ids = Array(commit.parent_ids)
end
def serialize_keys
diff --git a/lib/gitlab/git/repository.rb b/lib/gitlab/git/repository.rb
index 5f014e43c6f..a10bc0dd32b 100644
--- a/lib/gitlab/git/repository.rb
+++ b/lib/gitlab/git/repository.rb
@@ -2195,6 +2195,7 @@ module Gitlab
# Apply diff of the `diff_range` to the worktree
diff = run_git!(%W(diff --binary #{diff_range}))
run_git!(%w(apply --index), chdir: squash_path, env: env) do |stdin|
+ stdin.binmode
stdin.write(diff)
end
diff --git a/lib/gitlab/github_import/importer/repository_importer.rb b/lib/gitlab/github_import/importer/repository_importer.rb
index 7dd68a0d1cd..ab0b751fe24 100644
--- a/lib/gitlab/github_import/importer/repository_importer.rb
+++ b/lib/gitlab/github_import/importer/repository_importer.rb
@@ -63,6 +63,7 @@ module Gitlab
true
rescue Gitlab::Shell::Error => e
if e.message !~ /repository not exported/
+ project.create_wiki
fail_import("Failed to import the wiki: #{e.message}")
else
true
diff --git a/lib/gitlab/metrics/transaction.rb b/lib/gitlab/metrics/transaction.rb
index 45b9e14ba55..f3e48083c19 100644
--- a/lib/gitlab/metrics/transaction.rb
+++ b/lib/gitlab/metrics/transaction.rb
@@ -73,7 +73,7 @@ module Gitlab
# event_name - The name of the event (e.g. "git_push").
# tags - A set of tags to attach to the event.
def add_event(event_name, tags = {})
- self.class.transaction_metric(event_name, :counter, prefix: 'event_', tags: tags).increment(tags.merge(labels))
+ self.class.transaction_metric(event_name, :counter, prefix: 'event_', use_feature_flag: true, tags: tags).increment(tags.merge(labels))
@metrics << Metric.new(EVENT_SERIES, { count: 1 }, tags.merge(event: event_name), :event)
end
@@ -150,11 +150,12 @@ module Gitlab
with_feature :prometheus_metrics_transaction_allocated_memory
end
- def self.transaction_metric(name, type, prefix: nil, tags: {})
+ def self.transaction_metric(name, type, prefix: nil, use_feature_flag: false, tags: {})
metric_name = "gitlab_transaction_#{prefix}#{name}_total".to_sym
fetch_metric(type, metric_name) do
docstring "Transaction #{prefix}#{name} #{type}"
base_labels tags.merge(BASE_LABELS)
+ with_feature "prometheus_transaction_#{prefix}#{name}_total".to_sym if use_feature_flag
if type == :gauge
multiprocess_mode :livesum
diff --git a/package.json b/package.json
index 4eccd51a3a6..7498bb486dc 100644
--- a/package.json
+++ b/package.json
@@ -24,6 +24,7 @@
"blackst0ne-mermaid": "^7.1.0-fixed",
"bootstrap-sass": "^3.3.6",
"brace-expansion": "^1.1.8",
+ "chart.js": "1.0.2",
"classlist-polyfill": "^1.2.0",
"clipboard": "^1.7.1",
"compression-webpack-plugin": "^1.0.0",
diff --git a/qa/qa/factory/resource/secret_variable.rb b/qa/qa/factory/resource/secret_variable.rb
index af0fa8af2df..c734d739b4a 100644
--- a/qa/qa/factory/resource/secret_variable.rb
+++ b/qa/qa/factory/resource/secret_variable.rb
@@ -4,18 +4,6 @@ module QA
class SecretVariable < Factory::Base
attr_accessor :key, :value
- product :key do
- Page::Project::Settings::CICD.act do
- expand_secret_variables(&:variable_key)
- end
- end
-
- product :value do
- Page::Project::Settings::CICD.act do
- expand_secret_variables(&:variable_value)
- end
- end
-
dependency Factory::Resource::Project, as: :project do |project|
project.name = 'project-with-secret-variables'
project.description = 'project for adding secret variable test'
diff --git a/qa/qa/page/base.rb b/qa/qa/page/base.rb
index 7924479e2a1..a313d46205d 100644
--- a/qa/qa/page/base.rb
+++ b/qa/qa/page/base.rb
@@ -98,6 +98,10 @@ module QA
views.map(&:errors).flatten
end
+ def self.elements
+ views.map(&:elements).flatten
+ end
+
class DSL
attr_reader :views
diff --git a/qa/qa/page/project/settings/secret_variables.rb b/qa/qa/page/project/settings/secret_variables.rb
index fea4acb389a..c95c79f137d 100644
--- a/qa/qa/page/project/settings/secret_variables.rb
+++ b/qa/qa/page/project/settings/secret_variables.rb
@@ -6,39 +6,37 @@ module QA
include Common
view 'app/views/ci/variables/_variable_row.html.haml' do
+ element :variable_row, '.ci-variable-row-body'
element :variable_key, '.js-ci-variable-input-key'
element :variable_value, '.js-ci-variable-input-value'
+ element :key_placeholder, 'Input variable key'
+ element :value_placeholder, 'Input variable value'
end
view 'app/views/ci/variables/_index.html.haml' do
element :save_variables, '.js-secret-variables-save-button'
+ element :reveal_values, '.js-secret-value-reveal-button'
end
def fill_variable_key(key)
- page.within('.js-ci-variable-list-section .js-row:nth-child(1)') do
- page.find('.js-ci-variable-input-key').set(key)
- end
+ fill_in('Input variable key', with: key, match: :first)
end
def fill_variable_value(value)
- page.within('.js-ci-variable-list-section .js-row:nth-child(1)') do
- page.find('.js-ci-variable-input-value').set(value)
- end
+ fill_in('Input variable value', with: value, match: :first)
end
def save_variables
- click_button('Save variables')
+ find('.js-secret-variables-save-button').click
end
- def variable_key
- page.within('.js-ci-variable-list-section .js-row:nth-child(1)') do
- page.find('.js-ci-variable-input-key').value
- end
+ def reveal_variables
+ find('.js-secret-value-reveal-button').click
end
- def variable_value
- page.within('.js-ci-variable-list-section .js-row:nth-child(1)') do
- page.find('.js-ci-variable-input-value').value
+ def variable_value(key)
+ within('.ci-variable-row-body', text: key) do
+ find('.js-ci-variable-input-value').value
end
end
end
diff --git a/qa/qa/specs/features/project/add_secret_variable_spec.rb b/qa/qa/specs/features/project/add_secret_variable_spec.rb
index 36422a92afc..d1bf7849bd0 100644
--- a/qa/qa/specs/features/project/add_secret_variable_spec.rb
+++ b/qa/qa/specs/features/project/add_secret_variable_spec.rb
@@ -4,16 +4,21 @@ module QA
Runtime::Browser.visit(:gitlab, Page::Main::Login)
Page::Main::Login.act { sign_in_using_credentials }
- variable_key = 'VARIABLE_KEY'
- variable_value = 'variable value'
-
- variable = Factory::Resource::SecretVariable.fabricate! do |resource|
- resource.key = variable_key
- resource.value = variable_value
+ Factory::Resource::SecretVariable.fabricate! do |resource|
+ resource.key = 'VARIABLE_KEY'
+ resource.value = 'some secret variable'
end
- expect(variable.key).to eq(variable_key)
- expect(variable.value).to eq(variable_value)
+ Page::Project::Settings::CICD.perform do |settings|
+ settings.expand_secret_variables do |page|
+ expect(page).to have_field(with: 'VARIABLE_KEY')
+ expect(page).not_to have_field(with: 'some secret variable')
+
+ page.reveal_variables
+
+ expect(page).to have_field(with: 'some secret variable')
+ end
+ end
end
end
end
diff --git a/qa/spec/page/base_spec.rb b/qa/spec/page/base_spec.rb
index 287adf35c46..52daa9697ee 100644
--- a/qa/spec/page/base_spec.rb
+++ b/qa/spec/page/base_spec.rb
@@ -14,7 +14,7 @@ describe QA::Page::Base do
end
view 'path/to/some/_partial.html.haml' do
- element :something, 'string pattern'
+ element :another_element, 'string pattern'
end
end
end
@@ -25,11 +25,10 @@ describe QA::Page::Base do
end
it 'populates views objects with data about elements' do
- subject.views.first.elements.tap do |elements|
- expect(elements.size).to eq 2
- expect(elements).to all(be_an_instance_of QA::Page::Element)
- expect(elements.map(&:name)).to eq [:something, :something_else]
- end
+ expect(subject.elements.size).to eq 3
+ expect(subject.elements).to all(be_an_instance_of QA::Page::Element)
+ expect(subject.elements.map(&:name))
+ .to eq [:something, :something_else, :another_element]
end
end
diff --git a/spec/features/projects/network_graph_spec.rb b/spec/features/projects/network_graph_spec.rb
new file mode 100644
index 00000000000..9f9a7787093
--- /dev/null
+++ b/spec/features/projects/network_graph_spec.rb
@@ -0,0 +1,108 @@
+require 'spec_helper'
+
+describe 'Project Network Graph', :js do
+ let(:user) { create :user }
+ let(:project) { create :project, :repository, namespace: user.namespace }
+
+ before do
+ sign_in(user)
+
+ # Stub Graph max_size to speed up test (10 commits vs. 650)
+ allow(Network::Graph).to receive(:max_count).and_return(10)
+ end
+
+ context 'when branch is master' do
+ def switch_ref_to(ref_name)
+ first('.js-project-refs-dropdown').click
+
+ page.within '.project-refs-form' do
+ click_link ref_name
+ end
+ end
+
+ def click_show_only_selected_branch_checkbox
+ find('#filter_ref').click
+ end
+
+ before do
+ visit project_network_path(project, 'master')
+ end
+
+ it 'renders project network' do
+ expect(page).to have_selector ".network-graph"
+ expect(page).to have_selector '.dropdown-menu-toggle', text: "master"
+ page.within '.network-graph' do
+ expect(page).to have_content 'master'
+ end
+ end
+
+ it 'switches ref to branch' do
+ switch_ref_to('feature')
+
+ expect(page).to have_selector '.dropdown-menu-toggle', text: 'feature'
+ page.within '.network-graph' do
+ expect(page).to have_content 'feature'
+ end
+ end
+
+ it 'switches ref to tag' do
+ switch_ref_to('v1.0.0')
+
+ expect(page).to have_selector '.dropdown-menu-toggle', text: 'v1.0.0'
+ page.within '.network-graph' do
+ expect(page).to have_content 'v1.0.0'
+ end
+ end
+
+ it 'renders by commit sha of "v1.0.0"' do
+ page.within ".network-form" do
+ fill_in 'extended_sha1', with: '6f6d7e7ed97bb5f0054f2b1df789b39ca89b6ff9'
+ find('button').click
+ end
+
+ expect(page).to have_selector ".network-graph"
+ expect(page).to have_selector '.dropdown-menu-toggle', text: "master"
+ page.within '.network-graph' do
+ expect(page).to have_content 'v1.0.0'
+ end
+ end
+
+ it 'filters select tag' do
+ switch_ref_to('v1.0.0')
+
+ expect(page).to have_css 'title', text: 'Graph · v1.0.0', visible: false
+ page.within '.network-graph' do
+ expect(page).to have_content 'Change some files'
+ end
+
+ click_show_only_selected_branch_checkbox
+
+ page.within '.network-graph' do
+ expect(page).not_to have_content 'Change some files'
+ end
+
+ click_show_only_selected_branch_checkbox
+
+ page.within '.network-graph' do
+ expect(page).to have_content 'Change some files'
+ end
+ end
+
+ it 'renders error message when sha commit not exists' do
+ page.within ".network-form" do
+ fill_in 'extended_sha1', with: ';'
+ find('button').click
+ end
+
+ expect(page).to have_selector '.flash-alert', text: "Git revision ';' does not exist."
+ end
+ end
+
+ it 'renders project network with test branch' do
+ visit project_network_path(project, "'test'")
+
+ page.within '.network-graph' do
+ expect(page).to have_content "'test'"
+ end
+ end
+end
diff --git a/spec/javascripts/graphs/stat_graph_contributors_graph_spec.js b/spec/javascripts/graphs/stat_graph_contributors_graph_spec.js
index 6599839a526..d8a8c8cc260 100644
--- a/spec/javascripts/graphs/stat_graph_contributors_graph_spec.js
+++ b/spec/javascripts/graphs/stat_graph_contributors_graph_spec.js
@@ -1,7 +1,7 @@
/* eslint-disable quotes, jasmine/no-suite-dupes, vars-on-top, no-var */
import { scaleLinear, scaleTime } from 'd3-scale';
import { timeParse } from 'd3-time-format';
-import { ContributorsGraph, ContributorsMasterGraph } from '~/graphs/stat_graph_contributors_graph';
+import { ContributorsGraph, ContributorsMasterGraph } from '~/pages/projects/graphs/show/stat_graph_contributors_graph';
const d3 = { scaleLinear, scaleTime, timeParse };
diff --git a/spec/javascripts/graphs/stat_graph_contributors_spec.js b/spec/javascripts/graphs/stat_graph_contributors_spec.js
index 962423462e7..e03114c1cc5 100644
--- a/spec/javascripts/graphs/stat_graph_contributors_spec.js
+++ b/spec/javascripts/graphs/stat_graph_contributors_spec.js
@@ -1,5 +1,5 @@
-import ContributorsStatGraph from '~/graphs/stat_graph_contributors';
-import { ContributorsGraph } from '~/graphs/stat_graph_contributors_graph';
+import ContributorsStatGraph from '~/pages/projects/graphs/show/stat_graph_contributors';
+import { ContributorsGraph } from '~/pages/projects/graphs/show/stat_graph_contributors_graph';
import { setLanguage } from '../helpers/locale_helper';
diff --git a/spec/javascripts/graphs/stat_graph_contributors_util_spec.js b/spec/javascripts/graphs/stat_graph_contributors_util_spec.js
index 9b47ab62181..22a9afe1a9d 100644
--- a/spec/javascripts/graphs/stat_graph_contributors_util_spec.js
+++ b/spec/javascripts/graphs/stat_graph_contributors_util_spec.js
@@ -1,6 +1,6 @@
/* eslint-disable quotes, no-var, camelcase, object-property-newline, comma-dangle, max-len, vars-on-top, quote-props */
-import ContributorsStatGraphUtil from '~/graphs/stat_graph_contributors_util';
+import ContributorsStatGraphUtil from '~/pages/projects/graphs/show/stat_graph_contributors_util';
describe("ContributorsStatGraphUtil", function () {
describe("#parse_log", function () {
diff --git a/spec/lib/gitlab/checks/change_access_spec.rb b/spec/lib/gitlab/checks/change_access_spec.rb
index 475b5c5cfb2..b49ddbfc780 100644
--- a/spec/lib/gitlab/checks/change_access_spec.rb
+++ b/spec/lib/gitlab/checks/change_access_spec.rb
@@ -190,7 +190,7 @@ describe Gitlab::Checks::ChangeAccess do
context 'with LFS not enabled' do
it 'skips the validation' do
- expect_any_instance_of(described_class).not_to receive(:lfs_file_locks_validation)
+ expect_any_instance_of(Gitlab::Checks::CommitCheck).not_to receive(:validate)
subject.exec
end
@@ -207,7 +207,7 @@ describe Gitlab::Checks::ChangeAccess do
end
end
- context 'when change is sent by the author od the lock' do
+ context 'when change is sent by the author of the lock' do
let(:user) { owner }
it "doesn't raise any error" do
diff --git a/spec/lib/gitlab/git/repository_spec.rb b/spec/lib/gitlab/git/repository_spec.rb
index edcf8889c27..0e9150964fa 100644
--- a/spec/lib/gitlab/git/repository_spec.rb
+++ b/spec/lib/gitlab/git/repository_spec.rb
@@ -1,3 +1,4 @@
+# coding: utf-8
require "spec_helper"
describe Gitlab::Git::Repository, seed_helper: true do
@@ -2221,6 +2222,17 @@ describe Gitlab::Git::Repository, seed_helper: true do
subject
end
end
+
+ context 'with an ASCII-8BIT diff', :skip_gitaly_mock do
+ let(:diff) { "diff --git a/README.md b/README.md\nindex faaf198..43c5edf 100644\n--- a/README.md\n+++ b/README.md\n@@ -1,4 +1,4 @@\n-testme\n+✓ testme\n ======\n \n Sample repo for testing gitlab features\n" }
+
+ it 'applies a ASCII-8BIT diff' do
+ allow(repository).to receive(:run_git!).and_call_original
+ allow(repository).to receive(:run_git!).with(%W(diff --binary #{start_sha}...#{end_sha})).and_return(diff.force_encoding('ASCII-8BIT'))
+
+ expect(subject.length).to eq(40)
+ end
+ end
end
end
diff --git a/spec/lib/gitlab/github_import/importer/repository_importer_spec.rb b/spec/lib/gitlab/github_import/importer/repository_importer_spec.rb
index 46a57e08963..5bedfc79dd3 100644
--- a/spec/lib/gitlab/github_import/importer/repository_importer_spec.rb
+++ b/spec/lib/gitlab/github_import/importer/repository_importer_spec.rb
@@ -11,7 +11,8 @@ describe Gitlab::GithubImport::Importer::RepositoryImporter do
import_source: 'foo/bar',
repository_storage_path: 'foo',
disk_path: 'foo',
- repository: repository
+ repository: repository,
+ create_wiki: true
)
end
@@ -192,7 +193,7 @@ describe Gitlab::GithubImport::Importer::RepositoryImporter do
expect(importer.import_wiki_repository).to eq(true)
end
- it 'marks the import as failed if an error was raised' do
+ it 'marks the import as failed and creates an empty repo if an error was raised' do
expect(importer.gitlab_shell)
.to receive(:import_repository)
.and_raise(Gitlab::Shell::Error)
@@ -201,6 +202,9 @@ describe Gitlab::GithubImport::Importer::RepositoryImporter do
.to receive(:fail_import)
.and_return(false)
+ expect(project)
+ .to receive(:create_wiki)
+
expect(importer.import_wiki_repository).to eq(false)
end
end
diff --git a/spec/mailers/notify_spec.rb b/spec/mailers/notify_spec.rb
index 59eda025108..bcbb9287199 100644
--- a/spec/mailers/notify_spec.rb
+++ b/spec/mailers/notify_spec.rb
@@ -463,59 +463,30 @@ describe Notify do
end
describe 'project access requested' do
- context 'for a project in a user namespace' do
- let(:project) do
- create(:project, :public, :access_requestable) do |project|
- project.add_master(project.owner, current_user: project.owner)
- end
- end
-
- let(:project_member) do
- project.request_access(user)
- project.requesters.find_by(user_id: user.id)
- end
- subject { described_class.member_access_requested_email('project', project_member.id) }
-
- it_behaves_like 'an email sent from GitLab'
- it_behaves_like 'it should not have Gmail Actions links'
- it_behaves_like "a user cannot unsubscribe through footer link"
-
- it 'contains all the useful information' do
- to_emails = subject.header[:to].addrs
- expect(to_emails.size).to eq(1)
- expect(to_emails[0].address).to eq(project.members.owners_and_masters.first.user.notification_email)
-
- is_expected.to have_subject "Request to join the #{project.name_with_namespace} project"
- is_expected.to have_html_escaped_body_text project.name_with_namespace
- is_expected.to have_body_text project_project_members_url(project)
- is_expected.to have_body_text project_member.human_access
+ let(:project) do
+ create(:project, :public, :access_requestable) do |project|
+ project.add_master(project.owner)
end
end
- context 'for a project in a group' do
- let(:group_owner) { create(:user) }
- let(:group) { create(:group).tap { |g| g.add_owner(group_owner) } }
- let(:project) { create(:project, :public, :access_requestable, namespace: group) }
- let(:project_member) do
- project.request_access(user)
- project.requesters.find_by(user_id: user.id)
- end
- subject { described_class.member_access_requested_email('project', project_member.id) }
+ let(:project_member) do
+ project.request_access(user)
+ project.requesters.find_by(user_id: user.id)
+ end
+ subject { described_class.member_access_requested_email('project', project_member.id, recipient.notification_email) }
- it_behaves_like 'an email sent from GitLab'
- it_behaves_like 'it should not have Gmail Actions links'
- it_behaves_like "a user cannot unsubscribe through footer link"
+ it_behaves_like 'an email sent from GitLab'
+ it_behaves_like 'it should not have Gmail Actions links'
+ it_behaves_like "a user cannot unsubscribe through footer link"
- it 'contains all the useful information' do
- to_emails = subject.header[:to].addrs
- expect(to_emails.size).to eq(1)
- expect(to_emails[0].address).to eq(group.members.owners_and_masters.first.user.notification_email)
+ it 'contains all the useful information' do
+ to_emails = subject.header[:to].addrs.map(&:address)
+ expect(to_emails).to eq([recipient.notification_email])
- is_expected.to have_subject "Request to join the #{project.name_with_namespace} project"
- is_expected.to have_html_escaped_body_text project.name_with_namespace
- is_expected.to have_body_text project_project_members_url(project)
- is_expected.to have_body_text project_member.human_access
- end
+ is_expected.to have_subject "Request to join the #{project.name_with_namespace} project"
+ is_expected.to have_html_escaped_body_text project.name_with_namespace
+ is_expected.to have_body_text project_project_members_url(project)
+ is_expected.to have_body_text project_member.human_access
end
end
@@ -959,13 +930,16 @@ describe Notify do
group.request_access(user)
group.requesters.find_by(user_id: user.id)
end
- subject { described_class.member_access_requested_email('group', group_member.id) }
+ subject { described_class.member_access_requested_email('group', group_member.id, recipient.notification_email) }
it_behaves_like 'an email sent from GitLab'
it_behaves_like 'it should not have Gmail Actions links'
it_behaves_like "a user cannot unsubscribe through footer link"
it 'contains all the useful information' do
+ to_emails = subject.header[:to].addrs.map(&:address)
+ expect(to_emails).to eq([recipient.notification_email])
+
is_expected.to have_subject "Request to join the #{group.name} group"
is_expected.to have_html_escaped_body_text group.name
is_expected.to have_body_text group_group_members_url(group)
diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb
index 1815696a8a0..3531de244bd 100644
--- a/spec/models/user_spec.rb
+++ b/spec/models/user_spec.rb
@@ -496,6 +496,14 @@ describe User do
user2.update_tracked_fields!(request)
end.to change { user2.reload.current_sign_in_at }
end
+
+ it 'does not write if the DB is in read-only mode' do
+ expect(Gitlab::Database).to receive(:read_only?).and_return(true)
+
+ expect do
+ user.update_tracked_fields!(request)
+ end.not_to change { user.reload.current_sign_in_at }
+ end
end
shared_context 'user keys' do
diff --git a/spec/requests/api/issues_spec.rb b/spec/requests/api/issues_spec.rb
index 13bb3b92085..e6d7b9fde02 100644
--- a/spec/requests/api/issues_spec.rb
+++ b/spec/requests/api/issues_spec.rb
@@ -1,6 +1,6 @@
require 'spec_helper'
-describe API::Issues, :mailer do
+describe API::Issues do
set(:user) { create(:user) }
set(:project) do
create(:project, :public, creator_id: user.id, namespace: user.namespace)
@@ -932,18 +932,6 @@ describe API::Issues, :mailer do
expect(json_response['error']).to eq('confidential is invalid')
end
- it "sends notifications for subscribers of newly added labels" do
- label = project.labels.first
- label.toggle_subscription(user2, project)
-
- perform_enqueued_jobs do
- post api("/projects/#{project.id}/issues", user),
- title: 'new issue', labels: label.title
- end
-
- should_email(user2)
- end
-
it "returns a 400 bad request if title not given" do
post api("/projects/#{project.id}/issues", user), labels: 'label, label2'
expect(response).to have_gitlab_http_status(400)
@@ -1246,18 +1234,6 @@ describe API::Issues, :mailer do
expect(json_response['labels']).to eq([label.title])
end
- it "sends notifications for subscribers of newly added labels when issue is updated" do
- label = create(:label, title: 'foo', color: '#FFAABB', project: project)
- label.toggle_subscription(user2, project)
-
- perform_enqueued_jobs do
- put api("/projects/#{project.id}/issues/#{issue.iid}", user),
- title: 'updated title', labels: label.title
- end
-
- should_email(user2)
- end
-
it 'removes all labels' do
put api("/projects/#{project.id}/issues/#{issue.iid}", user), labels: ''
diff --git a/spec/requests/api/v3/issues_spec.rb b/spec/requests/api/v3/issues_spec.rb
index 25b4c8438e4..0e745c82395 100644
--- a/spec/requests/api/v3/issues_spec.rb
+++ b/spec/requests/api/v3/issues_spec.rb
@@ -1,6 +1,6 @@
require 'spec_helper'
-describe API::V3::Issues, :mailer do
+describe API::V3::Issues do
set(:user) { create(:user) }
set(:user2) { create(:user) }
set(:non_member) { create(:user) }
@@ -780,18 +780,6 @@ describe API::V3::Issues, :mailer do
expect(json_response['error']).to eq('confidential is invalid')
end
- it "sends notifications for subscribers of newly added labels" do
- label = project.labels.first
- label.toggle_subscription(user2, project)
-
- perform_enqueued_jobs do
- post v3_api("/projects/#{project.id}/issues", user),
- title: 'new issue', labels: label.title
- end
-
- should_email(user2)
- end
-
it "returns a 400 bad request if title not given" do
post v3_api("/projects/#{project.id}/issues", user), labels: 'label, label2'
@@ -1045,18 +1033,6 @@ describe API::V3::Issues, :mailer do
expect(json_response['labels']).to eq([label.title])
end
- it "sends notifications for subscribers of newly added labels when issue is updated" do
- label = create(:label, title: 'foo', color: '#FFAABB', project: project)
- label.toggle_subscription(user2, project)
-
- perform_enqueued_jobs do
- put v3_api("/projects/#{project.id}/issues/#{issue.id}", user),
- title: 'updated title', labels: label.title
- end
-
- should_email(user2)
- end
-
it 'removes all labels' do
put v3_api("/projects/#{project.id}/issues/#{issue.id}", user), labels: ''
diff --git a/spec/services/notification_service_spec.rb b/spec/services/notification_service_spec.rb
index 35eb84e5e88..836ffb7cea0 100644
--- a/spec/services/notification_service_spec.rb
+++ b/spec/services/notification_service_spec.rb
@@ -1307,6 +1307,33 @@ describe NotificationService, :mailer do
end
describe 'GroupMember' do
+ let(:added_user) { create(:user) }
+
+ describe '#new_access_request' do
+ let(:master) { create(:user) }
+ let(:owner) { create(:user) }
+ let(:developer) { create(:user) }
+ let!(:group) do
+ create(:group, :public, :access_requestable) do |group|
+ group.add_owner(owner)
+ group.add_master(master)
+ group.add_developer(developer)
+ end
+ end
+
+ before do
+ reset_delivered_emails!
+ end
+
+ it 'sends notification to group owners_and_masters' do
+ group.request_access(added_user)
+
+ should_email(owner)
+ should_email(master)
+ should_not_email(developer)
+ end
+ end
+
describe '#decline_group_invite' do
let(:creator) { create(:user) }
let(:group) { create(:group) }
@@ -1328,18 +1355,9 @@ describe NotificationService, :mailer do
describe '#new_group_member' do
let(:group) { create(:group) }
- let(:added_user) { create(:user) }
-
- def create_member!
- GroupMember.create(
- group: group,
- user: added_user,
- access_level: Gitlab::Access::GUEST
- )
- end
it 'sends a notification' do
- create_member!
+ group.add_guest(added_user)
should_only_email(added_user)
end
@@ -1349,7 +1367,7 @@ describe NotificationService, :mailer do
end
it 'does not send a notification' do
- create_member!
+ group.add_guest(added_user)
should_not_email_anyone
end
end
@@ -1357,8 +1375,42 @@ describe NotificationService, :mailer do
end
describe 'ProjectMember' do
+ let(:project) { create(:project) }
+ set(:added_user) { create(:user) }
+
+ describe '#new_access_request' do
+ context 'for a project in a user namespace' do
+ let(:project) do
+ create(:project, :public, :access_requestable) do |project|
+ project.add_master(project.owner)
+ end
+ end
+
+ it 'sends notification to project owners_and_masters' do
+ project.request_access(added_user)
+
+ should_only_email(project.owner)
+ end
+ end
+
+ context 'for a project in a group' do
+ let(:group_owner) { create(:user) }
+ let(:group) { create(:group).tap { |g| g.add_owner(group_owner) } }
+ let!(:project) { create(:project, :public, :access_requestable, namespace: group) }
+
+ before do
+ reset_delivered_emails!
+ end
+
+ it 'sends notification to group owners_and_masters' do
+ project.request_access(added_user)
+
+ should_only_email(group_owner)
+ end
+ end
+ end
+
describe '#decline_group_invite' do
- let(:project) { create(:project) }
let(:member) { create(:user) }
before do
@@ -1375,19 +1427,12 @@ describe NotificationService, :mailer do
end
describe '#new_project_member' do
- let(:project) { create(:project) }
- let(:added_user) { create(:user) }
-
- def create_member!
- create(:project_member, user: added_user, project: project)
- end
-
it do
create_member!
should_only_email(added_user)
end
- describe 'when notifications are disabled' do
+ context 'when notifications are disabled' do
before do
create_global_setting_for(added_user, :disabled)
end
@@ -1398,6 +1443,10 @@ describe NotificationService, :mailer do
end
end
end
+
+ def create_member!
+ create(:project_member, user: added_user, project: project)
+ end
end
context 'guest user in private project' do
diff --git a/spec/workers/process_commit_worker_spec.rb b/spec/workers/process_commit_worker_spec.rb
index 24f8ca67594..76ef57b6b1e 100644
--- a/spec/workers/process_commit_worker_spec.rb
+++ b/spec/workers/process_commit_worker_spec.rb
@@ -20,6 +20,32 @@ describe ProcessCommitWorker do
worker.perform(project.id, -1, commit.to_hash)
end
+ context 'when commit is a merge request merge commit' do
+ let(:merge_request) do
+ create(:merge_request,
+ description: "Closes #{issue.to_reference}",
+ source_branch: 'feature-merged',
+ target_branch: 'master',
+ source_project: project)
+ end
+
+ let(:commit) do
+ project.repository.create_branch('feature-merged', 'feature')
+
+ sha = project.repository.merge(user,
+ merge_request.diff_head_sha,
+ merge_request,
+ "Closes #{issue.to_reference}")
+ project.repository.commit(sha)
+ end
+
+ it 'it does not close any issues from the commit message' do
+ expect(worker).not_to receive(:close_issues)
+
+ worker.perform(project.id, user.id, commit.to_hash)
+ end
+ end
+
it 'processes the commit message' do
expect(worker).to receive(:process_commit_message).and_call_original
@@ -48,11 +74,9 @@ describe ProcessCommitWorker do
describe '#process_commit_message' do
context 'when pushing to the default branch' do
it 'closes issues that should be closed per the commit message' do
- allow(commit).to receive(:safe_message)
- .and_return("Closes #{issue.to_reference}")
+ allow(commit).to receive(:safe_message).and_return("Closes #{issue.to_reference}")
- expect(worker).to receive(:close_issues)
- .with(project, user, user, commit, [issue])
+ expect(worker).to receive(:close_issues).with(project, user, user, commit, [issue])
worker.process_commit_message(project, commit, user, user, true)
end
@@ -60,8 +84,7 @@ describe ProcessCommitWorker do
context 'when pushing to a non-default branch' do
it 'does not close any issues' do
- allow(commit).to receive(:safe_message)
- .and_return("Closes #{issue.to_reference}")
+ allow(commit).to receive(:safe_message).and_return("Closes #{issue.to_reference}")
expect(worker).not_to receive(:close_issues)
@@ -102,8 +125,7 @@ describe ProcessCommitWorker do
describe '#update_issue_metrics' do
it 'updates any existing issue metrics' do
- allow(commit).to receive(:safe_message)
- .and_return("Closes #{issue.to_reference}")
+ allow(commit).to receive(:safe_message).and_return("Closes #{issue.to_reference}")
worker.update_issue_metrics(commit, user)
@@ -113,10 +135,10 @@ describe ProcessCommitWorker do
end
it "doesn't execute any queries with false conditions" do
- allow(commit).to receive(:safe_message)
- .and_return("Lorem Ipsum")
+ allow(commit).to receive(:safe_message).and_return("Lorem Ipsum")
- expect { worker.update_issue_metrics(commit, user) }.not_to make_queries_matching(/WHERE (?:1=0|0=1)/)
+ expect { worker.update_issue_metrics(commit, user) }
+ .not_to make_queries_matching(/WHERE (?:1=0|0=1)/)
end
end
@@ -128,8 +150,9 @@ describe ProcessCommitWorker do
end
it 'parses date strings into Time instances' do
- commit = worker
- .build_commit(project, id: '123', authored_date: Time.now.to_s)
+ commit = worker.build_commit(project,
+ id: '123',
+ authored_date: Time.now.to_s)
expect(commit.authored_date).to be_an_instance_of(Time)
end
diff --git a/vendor/assets/javascripts/Chart.js b/vendor/assets/javascripts/Chart.js
deleted file mode 100644
index c264262ba73..00000000000
--- a/vendor/assets/javascripts/Chart.js
+++ /dev/null
@@ -1,3477 +0,0 @@
-/*!
- * Chart.js
- * http://chartjs.org/
- * Version: 1.0.2
- *
- * Copyright 2015 Nick Downie
- * Released under the MIT license
- * https://github.com/nnnick/Chart.js/blob/master/LICENSE.md
- */
-
-
-(function(){
-
- "use strict";
-
- //Declare root variable - window in the browser, global on the server
- var root = this,
- previous = root.Chart;
-
- //Occupy the global variable of Chart, and create a simple base class
- var Chart = function(context){
- var chart = this;
- this.canvas = context.canvas;
-
- this.ctx = context;
-
- //Variables global to the chart
- var computeDimension = function(element,dimension)
- {
- if (element['offset'+dimension])
- {
- return element['offset'+dimension];
- }
- else
- {
- return document.defaultView.getComputedStyle(element).getPropertyValue(dimension);
- }
- }
-
- var width = this.width = computeDimension(context.canvas,'Width');
- var height = this.height = computeDimension(context.canvas,'Height');
-
- // Firefox requires this to work correctly
- context.canvas.width = width;
- context.canvas.height = height;
-
- var width = this.width = context.canvas.width;
- var height = this.height = context.canvas.height;
- this.aspectRatio = this.width / this.height;
- //High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale.
- helpers.retinaScale(this);
-
- return this;
- };
- //Globally expose the defaults to allow for user updating/changing
- Chart.defaults = {
- global: {
- // Boolean - Whether to animate the chart
- animation: true,
-
- // Number - Number of animation steps
- animationSteps: 60,
-
- // String - Animation easing effect
- animationEasing: "easeOutQuart",
-
- // Boolean - If we should show the scale at all
- showScale: true,
-
- // Boolean - If we want to override with a hard coded scale
- scaleOverride: false,
-
- // ** Required if scaleOverride is true **
- // Number - The number of steps in a hard coded scale
- scaleSteps: null,
- // Number - The value jump in the hard coded scale
- scaleStepWidth: null,
- // Number - The scale starting value
- scaleStartValue: null,
-
- // String - Colour of the scale line
- scaleLineColor: "rgba(0,0,0,.1)",
-
- // Number - Pixel width of the scale line
- scaleLineWidth: 1,
-
- // Boolean - Whether to show labels on the scale
- scaleShowLabels: true,
-
- // Interpolated JS string - can access value
- scaleLabel: "<%=value%>",
-
- // Boolean - Whether the scale should stick to integers, and not show any floats even if drawing space is there
- scaleIntegersOnly: true,
-
- // Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
- scaleBeginAtZero: false,
-
- // String - Scale label font declaration for the scale label
- scaleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
-
- // Number - Scale label font size in pixels
- scaleFontSize: 12,
-
- // String - Scale label font weight style
- scaleFontStyle: "normal",
-
- // String - Scale label font colour
- scaleFontColor: "#666",
-
- // Boolean - whether or not the chart should be responsive and resize when the browser does.
- responsive: false,
-
- // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
- maintainAspectRatio: true,
-
- // Boolean - Determines whether to draw tooltips on the canvas or not - attaches events to touchmove & mousemove
- showTooltips: true,
-
- // Boolean - Determines whether to draw built-in tooltip or call custom tooltip function
- customTooltips: false,
-
- // Array - Array of string names to attach tooltip events
- tooltipEvents: ["mousemove", "touchstart", "touchmove", "mouseout"],
-
- // String - Tooltip background colour
- tooltipFillColor: "rgba(0,0,0,0.8)",
-
- // String - Tooltip label font declaration for the scale label
- tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
-
- // Number - Tooltip label font size in pixels
- tooltipFontSize: 14,
-
- // String - Tooltip font weight style
- tooltipFontStyle: "normal",
-
- // String - Tooltip label font colour
- tooltipFontColor: "#fff",
-
- // String - Tooltip title font declaration for the scale label
- tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
-
- // Number - Tooltip title font size in pixels
- tooltipTitleFontSize: 14,
-
- // String - Tooltip title font weight style
- tooltipTitleFontStyle: "bold",
-
- // String - Tooltip title font colour
- tooltipTitleFontColor: "#fff",
-
- // Number - pixel width of padding around tooltip text
- tooltipYPadding: 6,
-
- // Number - pixel width of padding around tooltip text
- tooltipXPadding: 6,
-
- // Number - Size of the caret on the tooltip
- tooltipCaretSize: 8,
-
- // Number - Pixel radius of the tooltip border
- tooltipCornerRadius: 6,
-
- // Number - Pixel offset from point x to tooltip edge
- tooltipXOffset: 10,
-
- // String - Template string for single tooltips
- tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
-
- // String - Template string for single tooltips
- multiTooltipTemplate: "<%= value %>",
-
- // String - Colour behind the legend colour block
- multiTooltipKeyBackground: '#fff',
-
- // Function - Will fire on animation progression.
- onAnimationProgress: function(){},
-
- // Function - Will fire on animation completion.
- onAnimationComplete: function(){}
-
- }
- };
-
- //Create a dictionary of chart types, to allow for extension of existing types
- Chart.types = {};
-
- //Global Chart helpers object for utility methods and classes
- var helpers = Chart.helpers = {};
-
- //-- Basic js utility methods
- var each = helpers.each = function(loopable,callback,self){
- var additionalArgs = Array.prototype.slice.call(arguments, 3);
- // Check to see if null or undefined firstly.
- if (loopable){
- if (loopable.length === +loopable.length){
- var i;
- for (i=0; i<loopable.length; i++){
- callback.apply(self,[loopable[i], i].concat(additionalArgs));
- }
- }
- else{
- for (var item in loopable){
- callback.apply(self,[loopable[item],item].concat(additionalArgs));
- }
- }
- }
- },
- clone = helpers.clone = function(obj){
- var objClone = {};
- each(obj,function(value,key){
- if (obj.hasOwnProperty(key)) objClone[key] = value;
- });
- return objClone;
- },
- extend = helpers.extend = function(base){
- each(Array.prototype.slice.call(arguments,1), function(extensionObject) {
- each(extensionObject,function(value,key){
- if (extensionObject.hasOwnProperty(key)) base[key] = value;
- });
- });
- return base;
- },
- merge = helpers.merge = function(base,master){
- //Merge properties in left object over to a shallow clone of object right.
- var args = Array.prototype.slice.call(arguments,0);
- args.unshift({});
- return extend.apply(null, args);
- },
- indexOf = helpers.indexOf = function(arrayToSearch, item){
- if (Array.prototype.indexOf) {
- return arrayToSearch.indexOf(item);
- }
- else{
- for (var i = 0; i < arrayToSearch.length; i++) {
- if (arrayToSearch[i] === item) return i;
- }
- return -1;
- }
- },
- where = helpers.where = function(collection, filterCallback){
- var filtered = [];
-
- helpers.each(collection, function(item){
- if (filterCallback(item)){
- filtered.push(item);
- }
- });
-
- return filtered;
- },
- findNextWhere = helpers.findNextWhere = function(arrayToSearch, filterCallback, startIndex){
- // Default to start of the array
- if (!startIndex){
- startIndex = -1;
- }
- for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
- var currentItem = arrayToSearch[i];
- if (filterCallback(currentItem)){
- return currentItem;
- }
- }
- },
- findPreviousWhere = helpers.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex){
- // Default to end of the array
- if (!startIndex){
- startIndex = arrayToSearch.length;
- }
- for (var i = startIndex - 1; i >= 0; i--) {
- var currentItem = arrayToSearch[i];
- if (filterCallback(currentItem)){
- return currentItem;
- }
- }
- },
- inherits = helpers.inherits = function(extensions){
- //Basic javascript inheritance based on the model created in Backbone.js
- var parent = this;
- var ChartElement = (extensions && extensions.hasOwnProperty("constructor")) ? extensions.constructor : function(){ return parent.apply(this, arguments); };
-
- var Surrogate = function(){ this.constructor = ChartElement;};
- Surrogate.prototype = parent.prototype;
- ChartElement.prototype = new Surrogate();
-
- ChartElement.extend = inherits;
-
- if (extensions) extend(ChartElement.prototype, extensions);
-
- ChartElement.__super__ = parent.prototype;
-
- return ChartElement;
- },
- noop = helpers.noop = function(){},
- uid = helpers.uid = (function(){
- var id=0;
- return function(){
- return "chart-" + id++;
- };
- })(),
- warn = helpers.warn = function(str){
- //Method for warning of errors
- if (window.console && typeof window.console.warn == "function") console.warn(str);
- },
- amd = helpers.amd = (typeof define == 'function' && define.amd),
- //-- Math methods
- isNumber = helpers.isNumber = function(n){
- return !isNaN(parseFloat(n)) && isFinite(n);
- },
- max = helpers.max = function(array){
- return Math.max.apply( Math, array );
- },
- min = helpers.min = function(array){
- return Math.min.apply( Math, array );
- },
- cap = helpers.cap = function(valueToCap,maxValue,minValue){
- if(isNumber(maxValue)) {
- if( valueToCap > maxValue ) {
- return maxValue;
- }
- }
- else if(isNumber(minValue)){
- if ( valueToCap < minValue ){
- return minValue;
- }
- }
- return valueToCap;
- },
- getDecimalPlaces = helpers.getDecimalPlaces = function(num){
- if (num%1!==0 && isNumber(num)){
- return num.toString().split(".")[1].length;
- }
- else {
- return 0;
- }
- },
- toRadians = helpers.radians = function(degrees){
- return degrees * (Math.PI/180);
- },
- // Gets the angle from vertical upright to the point about a centre.
- getAngleFromPoint = helpers.getAngleFromPoint = function(centrePoint, anglePoint){
- var distanceFromXCenter = anglePoint.x - centrePoint.x,
- distanceFromYCenter = anglePoint.y - centrePoint.y,
- radialDistanceFromCenter = Math.sqrt( distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
-
-
- var angle = Math.PI * 2 + Math.atan2(distanceFromYCenter, distanceFromXCenter);
-
- //If the segment is in the top left quadrant, we need to add another rotation to the angle
- if (distanceFromXCenter < 0 && distanceFromYCenter < 0){
- angle += Math.PI*2;
- }
-
- return {
- angle: angle,
- distance: radialDistanceFromCenter
- };
- },
- aliasPixel = helpers.aliasPixel = function(pixelWidth){
- return (pixelWidth % 2 === 0) ? 0 : 0.5;
- },
- splineCurve = helpers.splineCurve = function(FirstPoint,MiddlePoint,AfterPoint,t){
- //Props to Rob Spencer at scaled innovation for his post on splining between points
- //http://scaledinnovation.com/analytics/splines/aboutSplines.html
- var d01=Math.sqrt(Math.pow(MiddlePoint.x-FirstPoint.x,2)+Math.pow(MiddlePoint.y-FirstPoint.y,2)),
- d12=Math.sqrt(Math.pow(AfterPoint.x-MiddlePoint.x,2)+Math.pow(AfterPoint.y-MiddlePoint.y,2)),
- fa=t*d01/(d01+d12),// scaling factor for triangle Ta
- fb=t*d12/(d01+d12);
- return {
- inner : {
- x : MiddlePoint.x-fa*(AfterPoint.x-FirstPoint.x),
- y : MiddlePoint.y-fa*(AfterPoint.y-FirstPoint.y)
- },
- outer : {
- x: MiddlePoint.x+fb*(AfterPoint.x-FirstPoint.x),
- y : MiddlePoint.y+fb*(AfterPoint.y-FirstPoint.y)
- }
- };
- },
- calculateOrderOfMagnitude = helpers.calculateOrderOfMagnitude = function(val){
- return Math.floor(Math.log(val) / Math.LN10);
- },
- calculateScaleRange = helpers.calculateScaleRange = function(valuesArray, drawingSize, textSize, startFromZero, integersOnly){
-
- //Set a minimum step of two - a point at the top of the graph, and a point at the base
- var minSteps = 2,
- maxSteps = Math.floor(drawingSize/(textSize * 1.5)),
- skipFitting = (minSteps >= maxSteps);
-
- var maxValue = max(valuesArray),
- minValue = min(valuesArray);
-
- // We need some degree of seperation here to calculate the scales if all the values are the same
- // Adding/minusing 0.5 will give us a range of 1.
- if (maxValue === minValue){
- maxValue += 0.5;
- // So we don't end up with a graph with a negative start value if we've said always start from zero
- if (minValue >= 0.5 && !startFromZero){
- minValue -= 0.5;
- }
- else{
- // Make up a whole number above the values
- maxValue += 0.5;
- }
- }
-
- var valueRange = Math.abs(maxValue - minValue),
- rangeOrderOfMagnitude = calculateOrderOfMagnitude(valueRange),
- graphMax = Math.ceil(maxValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude),
- graphMin = (startFromZero) ? 0 : Math.floor(minValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude),
- graphRange = graphMax - graphMin,
- stepValue = Math.pow(10, rangeOrderOfMagnitude),
- numberOfSteps = Math.round(graphRange / stepValue);
-
- //If we have more space on the graph we'll use it to give more definition to the data
- while((numberOfSteps > maxSteps || (numberOfSteps * 2) < maxSteps) && !skipFitting) {
- if(numberOfSteps > maxSteps){
- stepValue *=2;
- numberOfSteps = Math.round(graphRange/stepValue);
- // Don't ever deal with a decimal number of steps - cancel fitting and just use the minimum number of steps.
- if (numberOfSteps % 1 !== 0){
- skipFitting = true;
- }
- }
- //We can fit in double the amount of scale points on the scale
- else{
- //If user has declared ints only, and the step value isn't a decimal
- if (integersOnly && rangeOrderOfMagnitude >= 0){
- //If the user has said integers only, we need to check that making the scale more granular wouldn't make it a float
- if(stepValue/2 % 1 === 0){
- stepValue /=2;
- numberOfSteps = Math.round(graphRange/stepValue);
- }
- //If it would make it a float break out of the loop
- else{
- break;
- }
- }
- //If the scale doesn't have to be an int, make the scale more granular anyway.
- else{
- stepValue /=2;
- numberOfSteps = Math.round(graphRange/stepValue);
- }
-
- }
- }
-
- if (skipFitting){
- numberOfSteps = minSteps;
- stepValue = graphRange / numberOfSteps;
- }
-
- return {
- steps : numberOfSteps,
- stepValue : stepValue,
- min : graphMin,
- max : graphMin + (numberOfSteps * stepValue)
- };
-
- },
- /* jshint ignore:start */
- // Blows up jshint errors based on the new Function constructor
- //Templating methods
- //Javascript micro templating by John Resig - source at http://ejohn.org/blog/javascript-micro-templating/
- template = helpers.template = function(templateString, valuesObject){
-
- // If templateString is function rather than string-template - call the function for valuesObject
-
- if(templateString instanceof Function){
- return templateString(valuesObject);
- }
-
- var cache = {};
- function tmpl(str, data){
- // Figure out if we're getting a template, or if we need to
- // load the template - and be sure to cache the result.
- var fn = !/\W/.test(str) ?
- cache[str] = cache[str] :
-
- // Generate a reusable function that will serve as a template
- // generator (and which will be cached).
- new Function("obj",
- "var p=[],print=function(){p.push.apply(p,arguments);};" +
-
- // Introduce the data as local variables using with(){}
- "with(obj){p.push('" +
-
- // Convert the template into pure JavaScript
- str
- .replace(/[\r\t\n]/g, " ")
- .split("<%").join("\t")
- .replace(/((^|%>)[^\t]*)'/g, "$1\r")
- .replace(/\t=(.*?)%>/g, "',$1,'")
- .split("\t").join("');")
- .split("%>").join("p.push('")
- .split("\r").join("\\'") +
- "');}return p.join('');"
- );
-
- // Provide some basic currying to the user
- return data ? fn( data ) : fn;
- }
- return tmpl(templateString,valuesObject);
- },
- /* jshint ignore:end */
- generateLabels = helpers.generateLabels = function(templateString,numberOfSteps,graphMin,stepValue){
- var labelsArray = new Array(numberOfSteps);
- if (labelTemplateString){
- each(labelsArray,function(val,index){
- labelsArray[index] = template(templateString,{value: (graphMin + (stepValue*(index+1)))});
- });
- }
- return labelsArray;
- },
- //--Animation methods
- //Easing functions adapted from Robert Penner's easing equations
- //http://www.robertpenner.com/easing/
- easingEffects = helpers.easingEffects = {
- linear: function (t) {
- return t;
- },
- easeInQuad: function (t) {
- return t * t;
- },
- easeOutQuad: function (t) {
- return -1 * t * (t - 2);
- },
- easeInOutQuad: function (t) {
- if ((t /= 1 / 2) < 1) return 1 / 2 * t * t;
- return -1 / 2 * ((--t) * (t - 2) - 1);
- },
- easeInCubic: function (t) {
- return t * t * t;
- },
- easeOutCubic: function (t) {
- return 1 * ((t = t / 1 - 1) * t * t + 1);
- },
- easeInOutCubic: function (t) {
- if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t;
- return 1 / 2 * ((t -= 2) * t * t + 2);
- },
- easeInQuart: function (t) {
- return t * t * t * t;
- },
- easeOutQuart: function (t) {
- return -1 * ((t = t / 1 - 1) * t * t * t - 1);
- },
- easeInOutQuart: function (t) {
- if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t * t;
- return -1 / 2 * ((t -= 2) * t * t * t - 2);
- },
- easeInQuint: function (t) {
- return 1 * (t /= 1) * t * t * t * t;
- },
- easeOutQuint: function (t) {
- return 1 * ((t = t / 1 - 1) * t * t * t * t + 1);
- },
- easeInOutQuint: function (t) {
- if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t * t * t;
- return 1 / 2 * ((t -= 2) * t * t * t * t + 2);
- },
- easeInSine: function (t) {
- return -1 * Math.cos(t / 1 * (Math.PI / 2)) + 1;
- },
- easeOutSine: function (t) {
- return 1 * Math.sin(t / 1 * (Math.PI / 2));
- },
- easeInOutSine: function (t) {
- return -1 / 2 * (Math.cos(Math.PI * t / 1) - 1);
- },
- easeInExpo: function (t) {
- return (t === 0) ? 1 : 1 * Math.pow(2, 10 * (t / 1 - 1));
- },
- easeOutExpo: function (t) {
- return (t === 1) ? 1 : 1 * (-Math.pow(2, -10 * t / 1) + 1);
- },
- easeInOutExpo: function (t) {
- if (t === 0) return 0;
- if (t === 1) return 1;
- if ((t /= 1 / 2) < 1) return 1 / 2 * Math.pow(2, 10 * (t - 1));
- return 1 / 2 * (-Math.pow(2, -10 * --t) + 2);
- },
- easeInCirc: function (t) {
- if (t >= 1) return t;
- return -1 * (Math.sqrt(1 - (t /= 1) * t) - 1);
- },
- easeOutCirc: function (t) {
- return 1 * Math.sqrt(1 - (t = t / 1 - 1) * t);
- },
- easeInOutCirc: function (t) {
- if ((t /= 1 / 2) < 1) return -1 / 2 * (Math.sqrt(1 - t * t) - 1);
- return 1 / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1);
- },
- easeInElastic: function (t) {
- var s = 1.70158;
- var p = 0;
- var a = 1;
- if (t === 0) return 0;
- if ((t /= 1) == 1) return 1;
- if (!p) p = 1 * 0.3;
- if (a < Math.abs(1)) {
- a = 1;
- s = p / 4;
- } else s = p / (2 * Math.PI) * Math.asin(1 / a);
- return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
- },
- easeOutElastic: function (t) {
- var s = 1.70158;
- var p = 0;
- var a = 1;
- if (t === 0) return 0;
- if ((t /= 1) == 1) return 1;
- if (!p) p = 1 * 0.3;
- if (a < Math.abs(1)) {
- a = 1;
- s = p / 4;
- } else s = p / (2 * Math.PI) * Math.asin(1 / a);
- return a * Math.pow(2, -10 * t) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) + 1;
- },
- easeInOutElastic: function (t) {
- var s = 1.70158;
- var p = 0;
- var a = 1;
- if (t === 0) return 0;
- if ((t /= 1 / 2) == 2) return 1;
- if (!p) p = 1 * (0.3 * 1.5);
- if (a < Math.abs(1)) {
- a = 1;
- s = p / 4;
- } else s = p / (2 * Math.PI) * Math.asin(1 / a);
- if (t < 1) return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
- return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) * 0.5 + 1;
- },
- easeInBack: function (t) {
- var s = 1.70158;
- return 1 * (t /= 1) * t * ((s + 1) * t - s);
- },
- easeOutBack: function (t) {
- var s = 1.70158;
- return 1 * ((t = t / 1 - 1) * t * ((s + 1) * t + s) + 1);
- },
- easeInOutBack: function (t) {
- var s = 1.70158;
- if ((t /= 1 / 2) < 1) return 1 / 2 * (t * t * (((s *= (1.525)) + 1) * t - s));
- return 1 / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
- },
- easeInBounce: function (t) {
- return 1 - easingEffects.easeOutBounce(1 - t);
- },
- easeOutBounce: function (t) {
- if ((t /= 1) < (1 / 2.75)) {
- return 1 * (7.5625 * t * t);
- } else if (t < (2 / 2.75)) {
- return 1 * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75);
- } else if (t < (2.5 / 2.75)) {
- return 1 * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375);
- } else {
- return 1 * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375);
- }
- },
- easeInOutBounce: function (t) {
- if (t < 1 / 2) return easingEffects.easeInBounce(t * 2) * 0.5;
- return easingEffects.easeOutBounce(t * 2 - 1) * 0.5 + 1 * 0.5;
- }
- },
- //Request animation polyfill - http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
- requestAnimFrame = helpers.requestAnimFrame = (function(){
- return window.requestAnimationFrame ||
- window.webkitRequestAnimationFrame ||
- window.mozRequestAnimationFrame ||
- window.oRequestAnimationFrame ||
- window.msRequestAnimationFrame ||
- function(callback) {
- return window.setTimeout(callback, 1000 / 60);
- };
- })(),
- cancelAnimFrame = helpers.cancelAnimFrame = (function(){
- return window.cancelAnimationFrame ||
- window.webkitCancelAnimationFrame ||
- window.mozCancelAnimationFrame ||
- window.oCancelAnimationFrame ||
- window.msCancelAnimationFrame ||
- function(callback) {
- return window.clearTimeout(callback, 1000 / 60);
- };
- })(),
- animationLoop = helpers.animationLoop = function(callback,totalSteps,easingString,onProgress,onComplete,chartInstance){
-
- var currentStep = 0,
- easingFunction = easingEffects[easingString] || easingEffects.linear;
-
- var animationFrame = function(){
- currentStep++;
- var stepDecimal = currentStep/totalSteps;
- var easeDecimal = easingFunction(stepDecimal);
-
- callback.call(chartInstance,easeDecimal,stepDecimal, currentStep);
- onProgress.call(chartInstance,easeDecimal,stepDecimal);
- if (currentStep < totalSteps){
- chartInstance.animationFrame = requestAnimFrame(animationFrame);
- } else{
- onComplete.apply(chartInstance);
- }
- };
- requestAnimFrame(animationFrame);
- },
- //-- DOM methods
- getRelativePosition = helpers.getRelativePosition = function(evt){
- var mouseX, mouseY;
- var e = evt.originalEvent || evt,
- canvas = evt.currentTarget || evt.srcElement,
- boundingRect = canvas.getBoundingClientRect();
-
- if (e.touches){
- mouseX = e.touches[0].clientX - boundingRect.left;
- mouseY = e.touches[0].clientY - boundingRect.top;
-
- }
- else{
- mouseX = e.clientX - boundingRect.left;
- mouseY = e.clientY - boundingRect.top;
- }
-
- return {
- x : mouseX,
- y : mouseY
- };
-
- },
- addEvent = helpers.addEvent = function(node,eventType,method){
- if (node.addEventListener){
- node.addEventListener(eventType,method);
- } else if (node.attachEvent){
- node.attachEvent("on"+eventType, method);
- } else {
- node["on"+eventType] = method;
- }
- },
- removeEvent = helpers.removeEvent = function(node, eventType, handler){
- if (node.removeEventListener){
- node.removeEventListener(eventType, handler, false);
- } else if (node.detachEvent){
- node.detachEvent("on"+eventType,handler);
- } else{
- node["on" + eventType] = noop;
- }
- },
- bindEvents = helpers.bindEvents = function(chartInstance, arrayOfEvents, handler){
- // Create the events object if it's not already present
- if (!chartInstance.events) chartInstance.events = {};
-
- each(arrayOfEvents,function(eventName){
- chartInstance.events[eventName] = function(){
- handler.apply(chartInstance, arguments);
- };
- addEvent(chartInstance.chart.canvas,eventName,chartInstance.events[eventName]);
- });
- },
- unbindEvents = helpers.unbindEvents = function (chartInstance, arrayOfEvents) {
- each(arrayOfEvents, function(handler,eventName){
- removeEvent(chartInstance.chart.canvas, eventName, handler);
- });
- },
- getMaximumWidth = helpers.getMaximumWidth = function(domNode){
- var container = domNode.parentNode;
- // TODO = check cross browser stuff with this.
- return container.clientWidth;
- },
- getMaximumHeight = helpers.getMaximumHeight = function(domNode){
- var container = domNode.parentNode;
- // TODO = check cross browser stuff with this.
- return container.clientHeight;
- },
- getMaximumSize = helpers.getMaximumSize = helpers.getMaximumWidth, // legacy support
- retinaScale = helpers.retinaScale = function(chart){
- var ctx = chart.ctx,
- width = chart.canvas.width,
- height = chart.canvas.height;
-
- if (window.devicePixelRatio) {
- ctx.canvas.style.width = width + "px";
- ctx.canvas.style.height = height + "px";
- ctx.canvas.height = height * window.devicePixelRatio;
- ctx.canvas.width = width * window.devicePixelRatio;
- ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
- }
- },
- //-- Canvas methods
- clear = helpers.clear = function(chart){
- chart.ctx.clearRect(0,0,chart.width,chart.height);
- },
- fontString = helpers.fontString = function(pixelSize,fontStyle,fontFamily){
- return fontStyle + " " + pixelSize+"px " + fontFamily;
- },
- longestText = helpers.longestText = function(ctx,font,arrayOfStrings){
- ctx.font = font;
- var longest = 0;
- each(arrayOfStrings,function(string){
- var textWidth = ctx.measureText(string).width;
- longest = (textWidth > longest) ? textWidth : longest;
- });
- return longest;
- },
- drawRoundedRectangle = helpers.drawRoundedRectangle = function(ctx,x,y,width,height,radius){
- ctx.beginPath();
- ctx.moveTo(x + radius, y);
- ctx.lineTo(x + width - radius, y);
- ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
- ctx.lineTo(x + width, y + height - radius);
- ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
- ctx.lineTo(x + radius, y + height);
- ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
- ctx.lineTo(x, y + radius);
- ctx.quadraticCurveTo(x, y, x + radius, y);
- ctx.closePath();
- };
-
-
- //Store a reference to each instance - allowing us to globally resize chart instances on window resize.
- //Destroy method on the chart will remove the instance of the chart from this reference.
- Chart.instances = {};
-
- Chart.Type = function(data,options,chart){
- this.options = options;
- this.chart = chart;
- this.id = uid();
- //Add the chart instance to the global namespace
- Chart.instances[this.id] = this;
-
- // Initialize is always called when a chart type is created
- // By default it is a no op, but it should be extended
- if (options.responsive){
- this.resize();
- }
- this.initialize.call(this,data);
- };
-
- //Core methods that'll be a part of every chart type
- extend(Chart.Type.prototype,{
- initialize : function(){return this;},
- clear : function(){
- clear(this.chart);
- return this;
- },
- stop : function(){
- // Stops any current animation loop occuring
- cancelAnimFrame(this.animationFrame);
- return this;
- },
- resize : function(callback){
- this.stop();
- var canvas = this.chart.canvas,
- newWidth = getMaximumWidth(this.chart.canvas),
- newHeight = this.options.maintainAspectRatio ? newWidth / this.chart.aspectRatio : getMaximumHeight(this.chart.canvas);
-
- canvas.width = this.chart.width = newWidth;
- canvas.height = this.chart.height = newHeight;
-
- retinaScale(this.chart);
-
- if (typeof callback === "function"){
- callback.apply(this, Array.prototype.slice.call(arguments, 1));
- }
- return this;
- },
- reflow : noop,
- render : function(reflow){
- if (reflow){
- this.reflow();
- }
- if (this.options.animation && !reflow){
- helpers.animationLoop(
- this.draw,
- this.options.animationSteps,
- this.options.animationEasing,
- this.options.onAnimationProgress,
- this.options.onAnimationComplete,
- this
- );
- }
- else{
- this.draw();
- this.options.onAnimationComplete.call(this);
- }
- return this;
- },
- generateLegend : function(){
- return template(this.options.legendTemplate,this);
- },
- destroy : function(){
- this.clear();
- unbindEvents(this, this.events);
- var canvas = this.chart.canvas;
-
- // Reset canvas height/width attributes starts a fresh with the canvas context
- canvas.width = this.chart.width;
- canvas.height = this.chart.height;
-
- // < IE9 doesn't support removeProperty
- if (canvas.style.removeProperty) {
- canvas.style.removeProperty('width');
- canvas.style.removeProperty('height');
- } else {
- canvas.style.removeAttribute('width');
- canvas.style.removeAttribute('height');
- }
-
- delete Chart.instances[this.id];
- },
- showTooltip : function(ChartElements, forceRedraw){
- // Only redraw the chart if we've actually changed what we're hovering on.
- if (typeof this.activeElements === 'undefined') this.activeElements = [];
-
- var isChanged = (function(Elements){
- var changed = false;
-
- if (Elements.length !== this.activeElements.length){
- changed = true;
- return changed;
- }
-
- each(Elements, function(element, index){
- if (element !== this.activeElements[index]){
- changed = true;
- }
- }, this);
- return changed;
- }).call(this, ChartElements);
-
- if (!isChanged && !forceRedraw){
- return;
- }
- else{
- this.activeElements = ChartElements;
- }
- this.draw();
- if(this.options.customTooltips){
- this.options.customTooltips(false);
- }
- if (ChartElements.length > 0){
- // If we have multiple datasets, show a MultiTooltip for all of the data points at that index
- if (this.datasets && this.datasets.length > 1) {
- var dataArray,
- dataIndex;
-
- for (var i = this.datasets.length - 1; i >= 0; i--) {
- dataArray = this.datasets[i].points || this.datasets[i].bars || this.datasets[i].segments;
- dataIndex = indexOf(dataArray, ChartElements[0]);
- if (dataIndex !== -1){
- break;
- }
- }
- var tooltipLabels = [],
- tooltipColors = [],
- medianPosition = (function(index) {
-
- // Get all the points at that particular index
- var Elements = [],
- dataCollection,
- xPositions = [],
- yPositions = [],
- xMax,
- yMax,
- xMin,
- yMin;
- helpers.each(this.datasets, function(dataset){
- dataCollection = dataset.points || dataset.bars || dataset.segments;
- if (dataCollection[dataIndex] && dataCollection[dataIndex].hasValue()){
- Elements.push(dataCollection[dataIndex]);
- }
- });
-
- helpers.each(Elements, function(element) {
- xPositions.push(element.x);
- yPositions.push(element.y);
-
-
- //Include any colour information about the element
- tooltipLabels.push(helpers.template(this.options.multiTooltipTemplate, element));
- tooltipColors.push({
- fill: element._saved.fillColor || element.fillColor,
- stroke: element._saved.strokeColor || element.strokeColor
- });
-
- }, this);
-
- yMin = min(yPositions);
- yMax = max(yPositions);
-
- xMin = min(xPositions);
- xMax = max(xPositions);
-
- return {
- x: (xMin > this.chart.width/2) ? xMin : xMax,
- y: (yMin + yMax)/2
- };
- }).call(this, dataIndex);
-
- new Chart.MultiTooltip({
- x: medianPosition.x,
- y: medianPosition.y,
- xPadding: this.options.tooltipXPadding,
- yPadding: this.options.tooltipYPadding,
- xOffset: this.options.tooltipXOffset,
- fillColor: this.options.tooltipFillColor,
- textColor: this.options.tooltipFontColor,
- fontFamily: this.options.tooltipFontFamily,
- fontStyle: this.options.tooltipFontStyle,
- fontSize: this.options.tooltipFontSize,
- titleTextColor: this.options.tooltipTitleFontColor,
- titleFontFamily: this.options.tooltipTitleFontFamily,
- titleFontStyle: this.options.tooltipTitleFontStyle,
- titleFontSize: this.options.tooltipTitleFontSize,
- cornerRadius: this.options.tooltipCornerRadius,
- labels: tooltipLabels,
- legendColors: tooltipColors,
- legendColorBackground : this.options.multiTooltipKeyBackground,
- title: ChartElements[0].label,
- chart: this.chart,
- ctx: this.chart.ctx,
- custom: this.options.customTooltips
- }).draw();
-
- } else {
- each(ChartElements, function(Element) {
- var tooltipPosition = Element.tooltipPosition();
- new Chart.Tooltip({
- x: Math.round(tooltipPosition.x),
- y: Math.round(tooltipPosition.y),
- xPadding: this.options.tooltipXPadding,
- yPadding: this.options.tooltipYPadding,
- fillColor: this.options.tooltipFillColor,
- textColor: this.options.tooltipFontColor,
- fontFamily: this.options.tooltipFontFamily,
- fontStyle: this.options.tooltipFontStyle,
- fontSize: this.options.tooltipFontSize,
- caretHeight: this.options.tooltipCaretSize,
- cornerRadius: this.options.tooltipCornerRadius,
- text: template(this.options.tooltipTemplate, Element),
- chart: this.chart,
- custom: this.options.customTooltips
- }).draw();
- }, this);
- }
- }
- return this;
- },
- toBase64Image : function(){
- return this.chart.canvas.toDataURL.apply(this.chart.canvas, arguments);
- }
- });
-
- Chart.Type.extend = function(extensions){
-
- var parent = this;
-
- var ChartType = function(){
- return parent.apply(this,arguments);
- };
-
- //Copy the prototype object of the this class
- ChartType.prototype = clone(parent.prototype);
- //Now overwrite some of the properties in the base class with the new extensions
- extend(ChartType.prototype, extensions);
-
- ChartType.extend = Chart.Type.extend;
-
- if (extensions.name || parent.prototype.name){
-
- var chartName = extensions.name || parent.prototype.name;
- //Assign any potential default values of the new chart type
-
- //If none are defined, we'll use a clone of the chart type this is being extended from.
- //I.e. if we extend a line chart, we'll use the defaults from the line chart if our new chart
- //doesn't define some defaults of their own.
-
- var baseDefaults = (Chart.defaults[parent.prototype.name]) ? clone(Chart.defaults[parent.prototype.name]) : {};
-
- Chart.defaults[chartName] = extend(baseDefaults,extensions.defaults);
-
- Chart.types[chartName] = ChartType;
-
- //Register this new chart type in the Chart prototype
- Chart.prototype[chartName] = function(data,options){
- var config = merge(Chart.defaults.global, Chart.defaults[chartName], options || {});
- return new ChartType(data,config,this);
- };
- } else{
- warn("Name not provided for this chart, so it hasn't been registered");
- }
- return parent;
- };
-
- Chart.Element = function(configuration){
- extend(this,configuration);
- this.initialize.apply(this,arguments);
- this.save();
- };
- extend(Chart.Element.prototype,{
- initialize : function(){},
- restore : function(props){
- if (!props){
- extend(this,this._saved);
- } else {
- each(props,function(key){
- this[key] = this._saved[key];
- },this);
- }
- return this;
- },
- save : function(){
- this._saved = clone(this);
- delete this._saved._saved;
- return this;
- },
- update : function(newProps){
- each(newProps,function(value,key){
- this._saved[key] = this[key];
- this[key] = value;
- },this);
- return this;
- },
- transition : function(props,ease){
- each(props,function(value,key){
- this[key] = ((value - this._saved[key]) * ease) + this._saved[key];
- },this);
- return this;
- },
- tooltipPosition : function(){
- return {
- x : this.x,
- y : this.y
- };
- },
- hasValue: function(){
- return isNumber(this.value);
- }
- });
-
- Chart.Element.extend = inherits;
-
-
- Chart.Point = Chart.Element.extend({
- display: true,
- inRange: function(chartX,chartY){
- var hitDetectionRange = this.hitDetectionRadius + this.radius;
- return ((Math.pow(chartX-this.x, 2)+Math.pow(chartY-this.y, 2)) < Math.pow(hitDetectionRange,2));
- },
- draw : function(){
- if (this.display){
- var ctx = this.ctx;
- ctx.beginPath();
-
- ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2);
- ctx.closePath();
-
- ctx.strokeStyle = this.strokeColor;
- ctx.lineWidth = this.strokeWidth;
-
- ctx.fillStyle = this.fillColor;
-
- ctx.fill();
- ctx.stroke();
- }
-
-
- //Quick debug for bezier curve splining
- //Highlights control points and the line between them.
- //Handy for dev - stripped in the min version.
-
- // ctx.save();
- // ctx.fillStyle = "black";
- // ctx.strokeStyle = "black"
- // ctx.beginPath();
- // ctx.arc(this.controlPoints.inner.x,this.controlPoints.inner.y, 2, 0, Math.PI*2);
- // ctx.fill();
-
- // ctx.beginPath();
- // ctx.arc(this.controlPoints.outer.x,this.controlPoints.outer.y, 2, 0, Math.PI*2);
- // ctx.fill();
-
- // ctx.moveTo(this.controlPoints.inner.x,this.controlPoints.inner.y);
- // ctx.lineTo(this.x, this.y);
- // ctx.lineTo(this.controlPoints.outer.x,this.controlPoints.outer.y);
- // ctx.stroke();
-
- // ctx.restore();
-
-
-
- }
- });
-
- Chart.Arc = Chart.Element.extend({
- inRange : function(chartX,chartY){
-
- var pointRelativePosition = helpers.getAngleFromPoint(this, {
- x: chartX,
- y: chartY
- });
-
- //Check if within the range of the open/close angle
- var betweenAngles = (pointRelativePosition.angle >= this.startAngle && pointRelativePosition.angle <= this.endAngle),
- withinRadius = (pointRelativePosition.distance >= this.innerRadius && pointRelativePosition.distance <= this.outerRadius);
-
- return (betweenAngles && withinRadius);
- //Ensure within the outside of the arc centre, but inside arc outer
- },
- tooltipPosition : function(){
- var centreAngle = this.startAngle + ((this.endAngle - this.startAngle) / 2),
- rangeFromCentre = (this.outerRadius - this.innerRadius) / 2 + this.innerRadius;
- return {
- x : this.x + (Math.cos(centreAngle) * rangeFromCentre),
- y : this.y + (Math.sin(centreAngle) * rangeFromCentre)
- };
- },
- draw : function(animationPercent){
-
- var easingDecimal = animationPercent || 1;
-
- var ctx = this.ctx;
-
- ctx.beginPath();
-
- ctx.arc(this.x, this.y, this.outerRadius, this.startAngle, this.endAngle);
-
- ctx.arc(this.x, this.y, this.innerRadius, this.endAngle, this.startAngle, true);
-
- ctx.closePath();
- ctx.strokeStyle = this.strokeColor;
- ctx.lineWidth = this.strokeWidth;
-
- ctx.fillStyle = this.fillColor;
-
- ctx.fill();
- ctx.lineJoin = 'bevel';
-
- if (this.showStroke){
- ctx.stroke();
- }
- }
- });
-
- Chart.Rectangle = Chart.Element.extend({
- draw : function(){
- var ctx = this.ctx,
- halfWidth = this.width/2,
- leftX = this.x - halfWidth,
- rightX = this.x + halfWidth,
- top = this.base - (this.base - this.y),
- halfStroke = this.strokeWidth / 2;
-
- // Canvas doesn't allow us to stroke inside the width so we can
- // adjust the sizes to fit if we're setting a stroke on the line
- if (this.showStroke){
- leftX += halfStroke;
- rightX -= halfStroke;
- top += halfStroke;
- }
-
- ctx.beginPath();
-
- ctx.fillStyle = this.fillColor;
- ctx.strokeStyle = this.strokeColor;
- ctx.lineWidth = this.strokeWidth;
-
- // It'd be nice to keep this class totally generic to any rectangle
- // and simply specify which border to miss out.
- ctx.moveTo(leftX, this.base);
- ctx.lineTo(leftX, top);
- ctx.lineTo(rightX, top);
- ctx.lineTo(rightX, this.base);
- ctx.fill();
- if (this.showStroke){
- ctx.stroke();
- }
- },
- height : function(){
- return this.base - this.y;
- },
- inRange : function(chartX,chartY){
- return (chartX >= this.x - this.width/2 && chartX <= this.x + this.width/2) && (chartY >= this.y && chartY <= this.base);
- }
- });
-
- Chart.Tooltip = Chart.Element.extend({
- draw : function(){
-
- var ctx = this.chart.ctx;
-
- ctx.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
-
- this.xAlign = "center";
- this.yAlign = "above";
-
- //Distance between the actual element.y position and the start of the tooltip caret
- var caretPadding = this.caretPadding = 2;
-
- var tooltipWidth = ctx.measureText(this.text).width + 2*this.xPadding,
- tooltipRectHeight = this.fontSize + 2*this.yPadding,
- tooltipHeight = tooltipRectHeight + this.caretHeight + caretPadding;
-
- if (this.x + tooltipWidth/2 >this.chart.width){
- this.xAlign = "left";
- } else if (this.x - tooltipWidth/2 < 0){
- this.xAlign = "right";
- }
-
- if (this.y - tooltipHeight < 0){
- this.yAlign = "below";
- }
-
-
- var tooltipX = this.x - tooltipWidth/2,
- tooltipY = this.y - tooltipHeight;
-
- ctx.fillStyle = this.fillColor;
-
- // Custom Tooltips
- if(this.custom){
- this.custom(this);
- }
- else{
- switch(this.yAlign)
- {
- case "above":
- //Draw a caret above the x/y
- ctx.beginPath();
- ctx.moveTo(this.x,this.y - caretPadding);
- ctx.lineTo(this.x + this.caretHeight, this.y - (caretPadding + this.caretHeight));
- ctx.lineTo(this.x - this.caretHeight, this.y - (caretPadding + this.caretHeight));
- ctx.closePath();
- ctx.fill();
- break;
- case "below":
- tooltipY = this.y + caretPadding + this.caretHeight;
- //Draw a caret below the x/y
- ctx.beginPath();
- ctx.moveTo(this.x, this.y + caretPadding);
- ctx.lineTo(this.x + this.caretHeight, this.y + caretPadding + this.caretHeight);
- ctx.lineTo(this.x - this.caretHeight, this.y + caretPadding + this.caretHeight);
- ctx.closePath();
- ctx.fill();
- break;
- }
-
- switch(this.xAlign)
- {
- case "left":
- tooltipX = this.x - tooltipWidth + (this.cornerRadius + this.caretHeight);
- break;
- case "right":
- tooltipX = this.x - (this.cornerRadius + this.caretHeight);
- break;
- }
-
- drawRoundedRectangle(ctx,tooltipX,tooltipY,tooltipWidth,tooltipRectHeight,this.cornerRadius);
-
- ctx.fill();
-
- ctx.fillStyle = this.textColor;
- ctx.textAlign = "center";
- ctx.textBaseline = "middle";
- ctx.fillText(this.text, tooltipX + tooltipWidth/2, tooltipY + tooltipRectHeight/2);
- }
- }
- });
-
- Chart.MultiTooltip = Chart.Element.extend({
- initialize : function(){
- this.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
-
- this.titleFont = fontString(this.titleFontSize,this.titleFontStyle,this.titleFontFamily);
-
- this.height = (this.labels.length * this.fontSize) + ((this.labels.length-1) * (this.fontSize/2)) + (this.yPadding*2) + this.titleFontSize *1.5;
-
- this.ctx.font = this.titleFont;
-
- var titleWidth = this.ctx.measureText(this.title).width,
- //Label has a legend square as well so account for this.
- labelWidth = longestText(this.ctx,this.font,this.labels) + this.fontSize + 3,
- longestTextWidth = max([labelWidth,titleWidth]);
-
- this.width = longestTextWidth + (this.xPadding*2);
-
-
- var halfHeight = this.height/2;
-
- //Check to ensure the height will fit on the canvas
- if (this.y - halfHeight < 0 ){
- this.y = halfHeight;
- } else if (this.y + halfHeight > this.chart.height){
- this.y = this.chart.height - halfHeight;
- }
-
- //Decide whether to align left or right based on position on canvas
- if (this.x > this.chart.width/2){
- this.x -= this.xOffset + this.width;
- } else {
- this.x += this.xOffset;
- }
-
-
- },
- getLineHeight : function(index){
- var baseLineHeight = this.y - (this.height/2) + this.yPadding,
- afterTitleIndex = index-1;
-
- //If the index is zero, we're getting the title
- if (index === 0){
- return baseLineHeight + this.titleFontSize/2;
- } else{
- return baseLineHeight + ((this.fontSize*1.5*afterTitleIndex) + this.fontSize/2) + this.titleFontSize * 1.5;
- }
-
- },
- draw : function(){
- // Custom Tooltips
- if(this.custom){
- this.custom(this);
- }
- else{
- drawRoundedRectangle(this.ctx,this.x,this.y - this.height/2,this.width,this.height,this.cornerRadius);
- var ctx = this.ctx;
- ctx.fillStyle = this.fillColor;
- ctx.fill();
- ctx.closePath();
-
- ctx.textAlign = "left";
- ctx.textBaseline = "middle";
- ctx.fillStyle = this.titleTextColor;
- ctx.font = this.titleFont;
-
- ctx.fillText(this.title,this.x + this.xPadding, this.getLineHeight(0));
-
- ctx.font = this.font;
- helpers.each(this.labels,function(label,index){
- ctx.fillStyle = this.textColor;
- ctx.fillText(label,this.x + this.xPadding + this.fontSize + 3, this.getLineHeight(index + 1));
-
- //A bit gnarly, but clearing this rectangle breaks when using explorercanvas (clears whole canvas)
- //ctx.clearRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
- //Instead we'll make a white filled block to put the legendColour palette over.
-
- ctx.fillStyle = this.legendColorBackground;
- ctx.fillRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
-
- ctx.fillStyle = this.legendColors[index].fill;
- ctx.fillRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
-
-
- },this);
- }
- }
- });
-
- Chart.Scale = Chart.Element.extend({
- initialize : function(){
- this.fit();
- },
- buildYLabels : function(){
- this.yLabels = [];
-
- var stepDecimalPlaces = getDecimalPlaces(this.stepValue);
-
- for (var i=0; i<=this.steps; i++){
- this.yLabels.push(template(this.templateString,{value:(this.min + (i * this.stepValue)).toFixed(stepDecimalPlaces)}));
- }
- this.yLabelWidth = (this.display && this.showLabels) ? longestText(this.ctx,this.font,this.yLabels) : 0;
- },
- addXLabel : function(label){
- this.xLabels.push(label);
- this.valuesCount++;
- this.fit();
- },
- removeXLabel : function(){
- this.xLabels.shift();
- this.valuesCount--;
- this.fit();
- },
- // Fitting loop to rotate x Labels and figure out what fits there, and also calculate how many Y steps to use
- fit: function(){
- // First we need the width of the yLabels, assuming the xLabels aren't rotated
-
- // To do that we need the base line at the top and base of the chart, assuming there is no x label rotation
- this.startPoint = (this.display) ? this.fontSize : 0;
- this.endPoint = (this.display) ? this.height - (this.fontSize * 1.5) - 5 : this.height; // -5 to pad labels
-
- // Apply padding settings to the start and end point.
- this.startPoint += this.padding;
- this.endPoint -= this.padding;
-
- // Cache the starting height, so can determine if we need to recalculate the scale yAxis
- var cachedHeight = this.endPoint - this.startPoint,
- cachedYLabelWidth;
-
- // Build the current yLabels so we have an idea of what size they'll be to start
- /*
- * This sets what is returned from calculateScaleRange as static properties of this class:
- *
- this.steps;
- this.stepValue;
- this.min;
- this.max;
- *
- */
- this.calculateYRange(cachedHeight);
-
- // With these properties set we can now build the array of yLabels
- // and also the width of the largest yLabel
- this.buildYLabels();
-
- this.calculateXLabelRotation();
-
- while((cachedHeight > this.endPoint - this.startPoint)){
- cachedHeight = this.endPoint - this.startPoint;
- cachedYLabelWidth = this.yLabelWidth;
-
- this.calculateYRange(cachedHeight);
- this.buildYLabels();
-
- // Only go through the xLabel loop again if the yLabel width has changed
- if (cachedYLabelWidth < this.yLabelWidth){
- this.calculateXLabelRotation();
- }
- }
-
- },
- calculateXLabelRotation : function(){
- //Get the width of each grid by calculating the difference
- //between x offsets between 0 and 1.
-
- this.ctx.font = this.font;
-
- var firstWidth = this.ctx.measureText(this.xLabels[0]).width,
- lastWidth = this.ctx.measureText(this.xLabels[this.xLabels.length - 1]).width,
- firstRotated,
- lastRotated;
-
-
- this.xScalePaddingRight = lastWidth/2 + 3;
- this.xScalePaddingLeft = (firstWidth/2 > this.yLabelWidth + 10) ? firstWidth/2 : this.yLabelWidth + 10;
-
- this.xLabelRotation = 0;
- if (this.display){
- var originalLabelWidth = longestText(this.ctx,this.font,this.xLabels),
- cosRotation,
- firstRotatedWidth;
- this.xLabelWidth = originalLabelWidth;
- //Allow 3 pixels x2 padding either side for label readability
- var xGridWidth = Math.floor(this.calculateX(1) - this.calculateX(0)) - 6;
-
- //Max label rotate should be 90 - also act as a loop counter
- while ((this.xLabelWidth > xGridWidth && this.xLabelRotation === 0) || (this.xLabelWidth > xGridWidth && this.xLabelRotation <= 90 && this.xLabelRotation > 0)){
- cosRotation = Math.cos(toRadians(this.xLabelRotation));
-
- firstRotated = cosRotation * firstWidth;
- lastRotated = cosRotation * lastWidth;
-
- // We're right aligning the text now.
- if (firstRotated + this.fontSize / 2 > this.yLabelWidth + 8){
- this.xScalePaddingLeft = firstRotated + this.fontSize / 2;
- }
- this.xScalePaddingRight = this.fontSize/2;
-
-
- this.xLabelRotation++;
- this.xLabelWidth = cosRotation * originalLabelWidth;
-
- }
- if (this.xLabelRotation > 0){
- this.endPoint -= Math.sin(toRadians(this.xLabelRotation))*originalLabelWidth + 3;
- }
- }
- else{
- this.xLabelWidth = 0;
- this.xScalePaddingRight = this.padding;
- this.xScalePaddingLeft = this.padding;
- }
-
- },
- // Needs to be overidden in each Chart type
- // Otherwise we need to pass all the data into the scale class
- calculateYRange: noop,
- drawingArea: function(){
- return this.startPoint - this.endPoint;
- },
- calculateY : function(value){
- var scalingFactor = this.drawingArea() / (this.min - this.max);
- return this.endPoint - (scalingFactor * (value - this.min));
- },
- calculateX : function(index){
- var isRotated = (this.xLabelRotation > 0),
- // innerWidth = (this.offsetGridLines) ? this.width - offsetLeft - this.padding : this.width - (offsetLeft + halfLabelWidth * 2) - this.padding,
- innerWidth = this.width - (this.xScalePaddingLeft + this.xScalePaddingRight),
- valueWidth = innerWidth/Math.max((this.valuesCount - ((this.offsetGridLines) ? 0 : 1)), 1),
- valueOffset = (valueWidth * index) + this.xScalePaddingLeft;
-
- if (this.offsetGridLines){
- valueOffset += (valueWidth/2);
- }
-
- return Math.round(valueOffset);
- },
- update : function(newProps){
- helpers.extend(this, newProps);
- this.fit();
- },
- draw : function(){
- var ctx = this.ctx,
- yLabelGap = (this.endPoint - this.startPoint) / this.steps,
- xStart = Math.round(this.xScalePaddingLeft);
- if (this.display){
- ctx.fillStyle = this.textColor;
- ctx.font = this.font;
- each(this.yLabels,function(labelString,index){
- var yLabelCenter = this.endPoint - (yLabelGap * index),
- linePositionY = Math.round(yLabelCenter),
- drawHorizontalLine = this.showHorizontalLines;
-
- ctx.textAlign = "right";
- ctx.textBaseline = "middle";
- if (this.showLabels){
- ctx.fillText(labelString,xStart - 10,yLabelCenter);
- }
-
- // This is X axis, so draw it
- if (index === 0 && !drawHorizontalLine){
- drawHorizontalLine = true;
- }
-
- if (drawHorizontalLine){
- ctx.beginPath();
- }
-
- if (index > 0){
- // This is a grid line in the centre, so drop that
- ctx.lineWidth = this.gridLineWidth;
- ctx.strokeStyle = this.gridLineColor;
- } else {
- // This is the first line on the scale
- ctx.lineWidth = this.lineWidth;
- ctx.strokeStyle = this.lineColor;
- }
-
- linePositionY += helpers.aliasPixel(ctx.lineWidth);
-
- if(drawHorizontalLine){
- ctx.moveTo(xStart, linePositionY);
- ctx.lineTo(this.width, linePositionY);
- ctx.stroke();
- ctx.closePath();
- }
-
- ctx.lineWidth = this.lineWidth;
- ctx.strokeStyle = this.lineColor;
- ctx.beginPath();
- ctx.moveTo(xStart - 5, linePositionY);
- ctx.lineTo(xStart, linePositionY);
- ctx.stroke();
- ctx.closePath();
-
- },this);
-
- each(this.xLabels,function(label,index){
- var xPos = this.calculateX(index) + aliasPixel(this.lineWidth),
- // Check to see if line/bar here and decide where to place the line
- linePos = this.calculateX(index - (this.offsetGridLines ? 0.5 : 0)) + aliasPixel(this.lineWidth),
- isRotated = (this.xLabelRotation > 0),
- drawVerticalLine = this.showVerticalLines;
-
- // This is Y axis, so draw it
- if (index === 0 && !drawVerticalLine){
- drawVerticalLine = true;
- }
-
- if (drawVerticalLine){
- ctx.beginPath();
- }
-
- if (index > 0){
- // This is a grid line in the centre, so drop that
- ctx.lineWidth = this.gridLineWidth;
- ctx.strokeStyle = this.gridLineColor;
- } else {
- // This is the first line on the scale
- ctx.lineWidth = this.lineWidth;
- ctx.strokeStyle = this.lineColor;
- }
-
- if (drawVerticalLine){
- ctx.moveTo(linePos,this.endPoint);
- ctx.lineTo(linePos,this.startPoint - 3);
- ctx.stroke();
- ctx.closePath();
- }
-
-
- ctx.lineWidth = this.lineWidth;
- ctx.strokeStyle = this.lineColor;
-
-
- // Small lines at the bottom of the base grid line
- ctx.beginPath();
- ctx.moveTo(linePos,this.endPoint);
- ctx.lineTo(linePos,this.endPoint + 5);
- ctx.stroke();
- ctx.closePath();
-
- ctx.save();
- ctx.translate(xPos,(isRotated) ? this.endPoint + 12 : this.endPoint + 8);
- ctx.rotate(toRadians(this.xLabelRotation)*-1);
- ctx.font = this.font;
- ctx.textAlign = (isRotated) ? "right" : "center";
- ctx.textBaseline = (isRotated) ? "middle" : "top";
- ctx.fillText(label, 0, 0);
- ctx.restore();
- },this);
-
- }
- }
-
- });
-
- Chart.RadialScale = Chart.Element.extend({
- initialize: function(){
- this.size = min([this.height, this.width]);
- this.drawingArea = (this.display) ? (this.size/2) - (this.fontSize/2 + this.backdropPaddingY) : (this.size/2);
- },
- calculateCenterOffset: function(value){
- // Take into account half font size + the yPadding of the top value
- var scalingFactor = this.drawingArea / (this.max - this.min);
-
- return (value - this.min) * scalingFactor;
- },
- update : function(){
- if (!this.lineArc){
- this.setScaleSize();
- } else {
- this.drawingArea = (this.display) ? (this.size/2) - (this.fontSize/2 + this.backdropPaddingY) : (this.size/2);
- }
- this.buildYLabels();
- },
- buildYLabels: function(){
- this.yLabels = [];
-
- var stepDecimalPlaces = getDecimalPlaces(this.stepValue);
-
- for (var i=0; i<=this.steps; i++){
- this.yLabels.push(template(this.templateString,{value:(this.min + (i * this.stepValue)).toFixed(stepDecimalPlaces)}));
- }
- },
- getCircumference : function(){
- return ((Math.PI*2) / this.valuesCount);
- },
- setScaleSize: function(){
- /*
- * Right, this is really confusing and there is a lot of maths going on here
- * The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
- *
- * Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
- *
- * Solution:
- *
- * We assume the radius of the polygon is half the size of the canvas at first
- * at each index we check if the text overlaps.
- *
- * Where it does, we store that angle and that index.
- *
- * After finding the largest index and angle we calculate how much we need to remove
- * from the shape radius to move the point inwards by that x.
- *
- * We average the left and right distances to get the maximum shape radius that can fit in the box
- * along with labels.
- *
- * Once we have that, we can find the centre point for the chart, by taking the x text protrusion
- * on each side, removing that from the size, halving it and adding the left x protrusion width.
- *
- * This will mean we have a shape fitted to the canvas, as large as it can be with the labels
- * and position it in the most space efficient manner
- *
- * https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
- */
-
-
- // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
- // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
- var largestPossibleRadius = min([(this.height/2 - this.pointLabelFontSize - 5), this.width/2]),
- pointPosition,
- i,
- textWidth,
- halfTextWidth,
- furthestRight = this.width,
- furthestRightIndex,
- furthestRightAngle,
- furthestLeft = 0,
- furthestLeftIndex,
- furthestLeftAngle,
- xProtrusionLeft,
- xProtrusionRight,
- radiusReductionRight,
- radiusReductionLeft,
- maxWidthRadius;
- this.ctx.font = fontString(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily);
- for (i=0;i<this.valuesCount;i++){
- // 5px to space the text slightly out - similar to what we do in the draw function.
- pointPosition = this.getPointPosition(i, largestPossibleRadius);
- textWidth = this.ctx.measureText(template(this.templateString, { value: this.labels[i] })).width + 5;
- if (i === 0 || i === this.valuesCount/2){
- // If we're at index zero, or exactly the middle, we're at exactly the top/bottom
- // of the radar chart, so text will be aligned centrally, so we'll half it and compare
- // w/left and right text sizes
- halfTextWidth = textWidth/2;
- if (pointPosition.x + halfTextWidth > furthestRight) {
- furthestRight = pointPosition.x + halfTextWidth;
- furthestRightIndex = i;
- }
- if (pointPosition.x - halfTextWidth < furthestLeft) {
- furthestLeft = pointPosition.x - halfTextWidth;
- furthestLeftIndex = i;
- }
- }
- else if (i < this.valuesCount/2) {
- // Less than half the values means we'll left align the text
- if (pointPosition.x + textWidth > furthestRight) {
- furthestRight = pointPosition.x + textWidth;
- furthestRightIndex = i;
- }
- }
- else if (i > this.valuesCount/2){
- // More than half the values means we'll right align the text
- if (pointPosition.x - textWidth < furthestLeft) {
- furthestLeft = pointPosition.x - textWidth;
- furthestLeftIndex = i;
- }
- }
- }
-
- xProtrusionLeft = furthestLeft;
-
- xProtrusionRight = Math.ceil(furthestRight - this.width);
-
- furthestRightAngle = this.getIndexAngle(furthestRightIndex);
-
- furthestLeftAngle = this.getIndexAngle(furthestLeftIndex);
-
- radiusReductionRight = xProtrusionRight / Math.sin(furthestRightAngle + Math.PI/2);
-
- radiusReductionLeft = xProtrusionLeft / Math.sin(furthestLeftAngle + Math.PI/2);
-
- // Ensure we actually need to reduce the size of the chart
- radiusReductionRight = (isNumber(radiusReductionRight)) ? radiusReductionRight : 0;
- radiusReductionLeft = (isNumber(radiusReductionLeft)) ? radiusReductionLeft : 0;
-
- this.drawingArea = largestPossibleRadius - (radiusReductionLeft + radiusReductionRight)/2;
-
- //this.drawingArea = min([maxWidthRadius, (this.height - (2 * (this.pointLabelFontSize + 5)))/2])
- this.setCenterPoint(radiusReductionLeft, radiusReductionRight);
-
- },
- setCenterPoint: function(leftMovement, rightMovement){
-
- var maxRight = this.width - rightMovement - this.drawingArea,
- maxLeft = leftMovement + this.drawingArea;
-
- this.xCenter = (maxLeft + maxRight)/2;
- // Always vertically in the centre as the text height doesn't change
- this.yCenter = (this.height/2);
- },
-
- getIndexAngle : function(index){
- var angleMultiplier = (Math.PI * 2) / this.valuesCount;
- // Start from the top instead of right, so remove a quarter of the circle
-
- return index * angleMultiplier - (Math.PI/2);
- },
- getPointPosition : function(index, distanceFromCenter){
- var thisAngle = this.getIndexAngle(index);
- return {
- x : (Math.cos(thisAngle) * distanceFromCenter) + this.xCenter,
- y : (Math.sin(thisAngle) * distanceFromCenter) + this.yCenter
- };
- },
- draw: function(){
- if (this.display){
- var ctx = this.ctx;
- each(this.yLabels, function(label, index){
- // Don't draw a centre value
- if (index > 0){
- var yCenterOffset = index * (this.drawingArea/this.steps),
- yHeight = this.yCenter - yCenterOffset,
- pointPosition;
-
- // Draw circular lines around the scale
- if (this.lineWidth > 0){
- ctx.strokeStyle = this.lineColor;
- ctx.lineWidth = this.lineWidth;
-
- if(this.lineArc){
- ctx.beginPath();
- ctx.arc(this.xCenter, this.yCenter, yCenterOffset, 0, Math.PI*2);
- ctx.closePath();
- ctx.stroke();
- } else{
- ctx.beginPath();
- for (var i=0;i<this.valuesCount;i++)
- {
- pointPosition = this.getPointPosition(i, this.calculateCenterOffset(this.min + (index * this.stepValue)));
- if (i === 0){
- ctx.moveTo(pointPosition.x, pointPosition.y);
- } else {
- ctx.lineTo(pointPosition.x, pointPosition.y);
- }
- }
- ctx.closePath();
- ctx.stroke();
- }
- }
- if(this.showLabels){
- ctx.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
- if (this.showLabelBackdrop){
- var labelWidth = ctx.measureText(label).width;
- ctx.fillStyle = this.backdropColor;
- ctx.fillRect(
- this.xCenter - labelWidth/2 - this.backdropPaddingX,
- yHeight - this.fontSize/2 - this.backdropPaddingY,
- labelWidth + this.backdropPaddingX*2,
- this.fontSize + this.backdropPaddingY*2
- );
- }
- ctx.textAlign = 'center';
- ctx.textBaseline = "middle";
- ctx.fillStyle = this.fontColor;
- ctx.fillText(label, this.xCenter, yHeight);
- }
- }
- }, this);
-
- if (!this.lineArc){
- ctx.lineWidth = this.angleLineWidth;
- ctx.strokeStyle = this.angleLineColor;
- for (var i = this.valuesCount - 1; i >= 0; i--) {
- if (this.angleLineWidth > 0){
- var outerPosition = this.getPointPosition(i, this.calculateCenterOffset(this.max));
- ctx.beginPath();
- ctx.moveTo(this.xCenter, this.yCenter);
- ctx.lineTo(outerPosition.x, outerPosition.y);
- ctx.stroke();
- ctx.closePath();
- }
- // Extra 3px out for some label spacing
- var pointLabelPosition = this.getPointPosition(i, this.calculateCenterOffset(this.max) + 5);
- ctx.font = fontString(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily);
- ctx.fillStyle = this.pointLabelFontColor;
-
- var labelsCount = this.labels.length,
- halfLabelsCount = this.labels.length/2,
- quarterLabelsCount = halfLabelsCount/2,
- upperHalf = (i < quarterLabelsCount || i > labelsCount - quarterLabelsCount),
- exactQuarter = (i === quarterLabelsCount || i === labelsCount - quarterLabelsCount);
- if (i === 0){
- ctx.textAlign = 'center';
- } else if(i === halfLabelsCount){
- ctx.textAlign = 'center';
- } else if (i < halfLabelsCount){
- ctx.textAlign = 'left';
- } else {
- ctx.textAlign = 'right';
- }
-
- // Set the correct text baseline based on outer positioning
- if (exactQuarter){
- ctx.textBaseline = 'middle';
- } else if (upperHalf){
- ctx.textBaseline = 'bottom';
- } else {
- ctx.textBaseline = 'top';
- }
-
- ctx.fillText(this.labels[i], pointLabelPosition.x, pointLabelPosition.y);
- }
- }
- }
- }
- });
-
- // Attach global event to resize each chart instance when the browser resizes
- helpers.addEvent(window, "resize", (function(){
- // Basic debounce of resize function so it doesn't hurt performance when resizing browser.
- var timeout;
- return function(){
- clearTimeout(timeout);
- timeout = setTimeout(function(){
- each(Chart.instances,function(instance){
- // If the responsive flag is set in the chart instance config
- // Cascade the resize event down to the chart.
- if (instance.options.responsive){
- instance.resize(instance.render, true);
- }
- });
- }, 50);
- };
- })());
-
-
- if (amd) {
- define(function(){
- return Chart;
- });
- } else if (typeof module === 'object' && module.exports) {
- module.exports = Chart;
- }
-
- root.Chart = Chart;
-
- Chart.noConflict = function(){
- root.Chart = previous;
- return Chart;
- };
-
-}).call(this);
-
-(function(){
- "use strict";
-
- var root = this,
- Chart = root.Chart,
- helpers = Chart.helpers;
-
-
- var defaultConfig = {
- //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
- scaleBeginAtZero : true,
-
- //Boolean - Whether grid lines are shown across the chart
- scaleShowGridLines : true,
-
- //String - Colour of the grid lines
- scaleGridLineColor : "rgba(0,0,0,.05)",
-
- //Number - Width of the grid lines
- scaleGridLineWidth : 1,
-
- //Boolean - Whether to show horizontal lines (except X axis)
- scaleShowHorizontalLines: true,
-
- //Boolean - Whether to show vertical lines (except Y axis)
- scaleShowVerticalLines: true,
-
- //Boolean - If there is a stroke on each bar
- barShowStroke : true,
-
- //Number - Pixel width of the bar stroke
- barStrokeWidth : 2,
-
- //Number - Spacing between each of the X value sets
- barValueSpacing : 5,
-
- //Number - Spacing between data sets within X values
- barDatasetSpacing : 1,
-
- //String - A legend template
- legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
-
- };
-
-
- Chart.Type.extend({
- name: "Bar",
- defaults : defaultConfig,
- initialize: function(data){
-
- //Expose options as a scope variable here so we can access it in the ScaleClass
- var options = this.options;
-
- this.ScaleClass = Chart.Scale.extend({
- offsetGridLines : true,
- calculateBarX : function(datasetCount, datasetIndex, barIndex){
- //Reusable method for calculating the xPosition of a given bar based on datasetIndex & width of the bar
- var xWidth = this.calculateBaseWidth(),
- xAbsolute = this.calculateX(barIndex) - (xWidth/2),
- barWidth = this.calculateBarWidth(datasetCount);
-
- return xAbsolute + (barWidth * datasetIndex) + (datasetIndex * options.barDatasetSpacing) + barWidth/2;
- },
- calculateBaseWidth : function(){
- return (this.calculateX(1) - this.calculateX(0)) - (2*options.barValueSpacing);
- },
- calculateBarWidth : function(datasetCount){
- //The padding between datasets is to the right of each bar, providing that there are more than 1 dataset
- var baseWidth = this.calculateBaseWidth() - ((datasetCount - 1) * options.barDatasetSpacing);
-
- return (baseWidth / datasetCount);
- }
- });
-
- this.datasets = [];
-
- //Set up tooltip events on the chart
- if (this.options.showTooltips){
- helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
- var activeBars = (evt.type !== 'mouseout') ? this.getBarsAtEvent(evt) : [];
-
- this.eachBars(function(bar){
- bar.restore(['fillColor', 'strokeColor']);
- });
- helpers.each(activeBars, function(activeBar){
- activeBar.fillColor = activeBar.highlightFill;
- activeBar.strokeColor = activeBar.highlightStroke;
- });
- this.showTooltip(activeBars);
- });
- }
-
- //Declare the extension of the default point, to cater for the options passed in to the constructor
- this.BarClass = Chart.Rectangle.extend({
- strokeWidth : this.options.barStrokeWidth,
- showStroke : this.options.barShowStroke,
- ctx : this.chart.ctx
- });
-
- //Iterate through each of the datasets, and build this into a property of the chart
- helpers.each(data.datasets,function(dataset,datasetIndex){
-
- var datasetObject = {
- label : dataset.label || null,
- fillColor : dataset.fillColor,
- strokeColor : dataset.strokeColor,
- bars : []
- };
-
- this.datasets.push(datasetObject);
-
- helpers.each(dataset.data,function(dataPoint,index){
- //Add a new point for each piece of data, passing any required data to draw.
- datasetObject.bars.push(new this.BarClass({
- value : dataPoint,
- label : data.labels[index],
- datasetLabel: dataset.label,
- strokeColor : dataset.strokeColor,
- fillColor : dataset.fillColor,
- highlightFill : dataset.highlightFill || dataset.fillColor,
- highlightStroke : dataset.highlightStroke || dataset.strokeColor
- }));
- },this);
-
- },this);
-
- this.buildScale(data.labels);
-
- this.BarClass.prototype.base = this.scale.endPoint;
-
- this.eachBars(function(bar, index, datasetIndex){
- helpers.extend(bar, {
- width : this.scale.calculateBarWidth(this.datasets.length),
- x: this.scale.calculateBarX(this.datasets.length, datasetIndex, index),
- y: this.scale.endPoint
- });
- bar.save();
- }, this);
-
- this.render();
- },
- update : function(){
- this.scale.update();
- // Reset any highlight colours before updating.
- helpers.each(this.activeElements, function(activeElement){
- activeElement.restore(['fillColor', 'strokeColor']);
- });
-
- this.eachBars(function(bar){
- bar.save();
- });
- this.render();
- },
- eachBars : function(callback){
- helpers.each(this.datasets,function(dataset, datasetIndex){
- helpers.each(dataset.bars, callback, this, datasetIndex);
- },this);
- },
- getBarsAtEvent : function(e){
- var barsArray = [],
- eventPosition = helpers.getRelativePosition(e),
- datasetIterator = function(dataset){
- barsArray.push(dataset.bars[barIndex]);
- },
- barIndex;
-
- for (var datasetIndex = 0; datasetIndex < this.datasets.length; datasetIndex++) {
- for (barIndex = 0; barIndex < this.datasets[datasetIndex].bars.length; barIndex++) {
- if (this.datasets[datasetIndex].bars[barIndex].inRange(eventPosition.x,eventPosition.y)){
- helpers.each(this.datasets, datasetIterator);
- return barsArray;
- }
- }
- }
-
- return barsArray;
- },
- buildScale : function(labels){
- var self = this;
-
- var dataTotal = function(){
- var values = [];
- self.eachBars(function(bar){
- values.push(bar.value);
- });
- return values;
- };
-
- var scaleOptions = {
- templateString : this.options.scaleLabel,
- height : this.chart.height,
- width : this.chart.width,
- ctx : this.chart.ctx,
- textColor : this.options.scaleFontColor,
- fontSize : this.options.scaleFontSize,
- fontStyle : this.options.scaleFontStyle,
- fontFamily : this.options.scaleFontFamily,
- valuesCount : labels.length,
- beginAtZero : this.options.scaleBeginAtZero,
- integersOnly : this.options.scaleIntegersOnly,
- calculateYRange: function(currentHeight){
- var updatedRanges = helpers.calculateScaleRange(
- dataTotal(),
- currentHeight,
- this.fontSize,
- this.beginAtZero,
- this.integersOnly
- );
- helpers.extend(this, updatedRanges);
- },
- xLabels : labels,
- font : helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily),
- lineWidth : this.options.scaleLineWidth,
- lineColor : this.options.scaleLineColor,
- showHorizontalLines : this.options.scaleShowHorizontalLines,
- showVerticalLines : this.options.scaleShowVerticalLines,
- gridLineWidth : (this.options.scaleShowGridLines) ? this.options.scaleGridLineWidth : 0,
- gridLineColor : (this.options.scaleShowGridLines) ? this.options.scaleGridLineColor : "rgba(0,0,0,0)",
- padding : (this.options.showScale) ? 0 : (this.options.barShowStroke) ? this.options.barStrokeWidth : 0,
- showLabels : this.options.scaleShowLabels,
- display : this.options.showScale
- };
-
- if (this.options.scaleOverride){
- helpers.extend(scaleOptions, {
- calculateYRange: helpers.noop,
- steps: this.options.scaleSteps,
- stepValue: this.options.scaleStepWidth,
- min: this.options.scaleStartValue,
- max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
- });
- }
-
- this.scale = new this.ScaleClass(scaleOptions);
- },
- addData : function(valuesArray,label){
- //Map the values array for each of the datasets
- helpers.each(valuesArray,function(value,datasetIndex){
- //Add a new point for each piece of data, passing any required data to draw.
- this.datasets[datasetIndex].bars.push(new this.BarClass({
- value : value,
- label : label,
- x: this.scale.calculateBarX(this.datasets.length, datasetIndex, this.scale.valuesCount+1),
- y: this.scale.endPoint,
- width : this.scale.calculateBarWidth(this.datasets.length),
- base : this.scale.endPoint,
- strokeColor : this.datasets[datasetIndex].strokeColor,
- fillColor : this.datasets[datasetIndex].fillColor
- }));
- },this);
-
- this.scale.addXLabel(label);
- //Then re-render the chart.
- this.update();
- },
- removeData : function(){
- this.scale.removeXLabel();
- //Then re-render the chart.
- helpers.each(this.datasets,function(dataset){
- dataset.bars.shift();
- },this);
- this.update();
- },
- reflow : function(){
- helpers.extend(this.BarClass.prototype,{
- y: this.scale.endPoint,
- base : this.scale.endPoint
- });
- var newScaleProps = helpers.extend({
- height : this.chart.height,
- width : this.chart.width
- });
- this.scale.update(newScaleProps);
- },
- draw : function(ease){
- var easingDecimal = ease || 1;
- this.clear();
-
- var ctx = this.chart.ctx;
-
- this.scale.draw(easingDecimal);
-
- //Draw all the bars for each dataset
- helpers.each(this.datasets,function(dataset,datasetIndex){
- helpers.each(dataset.bars,function(bar,index){
- if (bar.hasValue()){
- bar.base = this.scale.endPoint;
- //Transition then draw
- bar.transition({
- x : this.scale.calculateBarX(this.datasets.length, datasetIndex, index),
- y : this.scale.calculateY(bar.value),
- width : this.scale.calculateBarWidth(this.datasets.length)
- }, easingDecimal).draw();
- }
- },this);
-
- },this);
- }
- });
-
-
-}).call(this);
-
-(function(){
- "use strict";
-
- var root = this,
- Chart = root.Chart,
- //Cache a local reference to Chart.helpers
- helpers = Chart.helpers;
-
- var defaultConfig = {
- //Boolean - Whether we should show a stroke on each segment
- segmentShowStroke : true,
-
- //String - The colour of each segment stroke
- segmentStrokeColor : "#fff",
-
- //Number - The width of each segment stroke
- segmentStrokeWidth : 2,
-
- //The percentage of the chart that we cut out of the middle.
- percentageInnerCutout : 50,
-
- //Number - Amount of animation steps
- animationSteps : 100,
-
- //String - Animation easing effect
- animationEasing : "easeOutBounce",
-
- //Boolean - Whether we animate the rotation of the Doughnut
- animateRotate : true,
-
- //Boolean - Whether we animate scaling the Doughnut from the centre
- animateScale : false,
-
- //String - A legend template
- legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
-
- };
-
-
- Chart.Type.extend({
- //Passing in a name registers this chart in the Chart namespace
- name: "Doughnut",
- //Providing a defaults will also register the deafults in the chart namespace
- defaults : defaultConfig,
- //Initialize is fired when the chart is initialized - Data is passed in as a parameter
- //Config is automatically merged by the core of Chart.js, and is available at this.options
- initialize: function(data){
-
- //Declare segments as a static property to prevent inheriting across the Chart type prototype
- this.segments = [];
- this.outerRadius = (helpers.min([this.chart.width,this.chart.height]) - this.options.segmentStrokeWidth/2)/2;
-
- this.SegmentArc = Chart.Arc.extend({
- ctx : this.chart.ctx,
- x : this.chart.width/2,
- y : this.chart.height/2
- });
-
- //Set up tooltip events on the chart
- if (this.options.showTooltips){
- helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
- var activeSegments = (evt.type !== 'mouseout') ? this.getSegmentsAtEvent(evt) : [];
-
- helpers.each(this.segments,function(segment){
- segment.restore(["fillColor"]);
- });
- helpers.each(activeSegments,function(activeSegment){
- activeSegment.fillColor = activeSegment.highlightColor;
- });
- this.showTooltip(activeSegments);
- });
- }
- this.calculateTotal(data);
-
- helpers.each(data,function(datapoint, index){
- this.addData(datapoint, index, true);
- },this);
-
- this.render();
- },
- getSegmentsAtEvent : function(e){
- var segmentsArray = [];
-
- var location = helpers.getRelativePosition(e);
-
- helpers.each(this.segments,function(segment){
- if (segment.inRange(location.x,location.y)) segmentsArray.push(segment);
- },this);
- return segmentsArray;
- },
- addData : function(segment, atIndex, silent){
- var index = atIndex || this.segments.length;
- this.segments.splice(index, 0, new this.SegmentArc({
- value : segment.value,
- outerRadius : (this.options.animateScale) ? 0 : this.outerRadius,
- innerRadius : (this.options.animateScale) ? 0 : (this.outerRadius/100) * this.options.percentageInnerCutout,
- fillColor : segment.color,
- highlightColor : segment.highlight || segment.color,
- showStroke : this.options.segmentShowStroke,
- strokeWidth : this.options.segmentStrokeWidth,
- strokeColor : this.options.segmentStrokeColor,
- startAngle : Math.PI * 1.5,
- circumference : (this.options.animateRotate) ? 0 : this.calculateCircumference(segment.value),
- label : segment.label
- }));
- if (!silent){
- this.reflow();
- this.update();
- }
- },
- calculateCircumference : function(value){
- return (Math.PI*2)*(Math.abs(value) / this.total);
- },
- calculateTotal : function(data){
- this.total = 0;
- helpers.each(data,function(segment){
- this.total += Math.abs(segment.value);
- },this);
- },
- update : function(){
- this.calculateTotal(this.segments);
-
- // Reset any highlight colours before updating.
- helpers.each(this.activeElements, function(activeElement){
- activeElement.restore(['fillColor']);
- });
-
- helpers.each(this.segments,function(segment){
- segment.save();
- });
- this.render();
- },
-
- removeData: function(atIndex){
- var indexToDelete = (helpers.isNumber(atIndex)) ? atIndex : this.segments.length-1;
- this.segments.splice(indexToDelete, 1);
- this.reflow();
- this.update();
- },
-
- reflow : function(){
- helpers.extend(this.SegmentArc.prototype,{
- x : this.chart.width/2,
- y : this.chart.height/2
- });
- this.outerRadius = (helpers.min([this.chart.width,this.chart.height]) - this.options.segmentStrokeWidth/2)/2;
- helpers.each(this.segments, function(segment){
- segment.update({
- outerRadius : this.outerRadius,
- innerRadius : (this.outerRadius/100) * this.options.percentageInnerCutout
- });
- }, this);
- },
- draw : function(easeDecimal){
- var animDecimal = (easeDecimal) ? easeDecimal : 1;
- this.clear();
- helpers.each(this.segments,function(segment,index){
- segment.transition({
- circumference : this.calculateCircumference(segment.value),
- outerRadius : this.outerRadius,
- innerRadius : (this.outerRadius/100) * this.options.percentageInnerCutout
- },animDecimal);
-
- segment.endAngle = segment.startAngle + segment.circumference;
-
- segment.draw();
- if (index === 0){
- segment.startAngle = Math.PI * 1.5;
- }
- //Check to see if it's the last segment, if not get the next and update the start angle
- if (index < this.segments.length-1){
- this.segments[index+1].startAngle = segment.endAngle;
- }
- },this);
-
- }
- });
-
- Chart.types.Doughnut.extend({
- name : "Pie",
- defaults : helpers.merge(defaultConfig,{percentageInnerCutout : 0})
- });
-
-}).call(this);
-(function(){
- "use strict";
-
- var root = this,
- Chart = root.Chart,
- helpers = Chart.helpers;
-
- var defaultConfig = {
-
- ///Boolean - Whether grid lines are shown across the chart
- scaleShowGridLines : true,
-
- //String - Colour of the grid lines
- scaleGridLineColor : "rgba(0,0,0,.05)",
-
- //Number - Width of the grid lines
- scaleGridLineWidth : 1,
-
- //Boolean - Whether to show horizontal lines (except X axis)
- scaleShowHorizontalLines: true,
-
- //Boolean - Whether to show vertical lines (except Y axis)
- scaleShowVerticalLines: true,
-
- //Boolean - Whether the line is curved between points
- bezierCurve : true,
-
- //Number - Tension of the bezier curve between points
- bezierCurveTension : 0.4,
-
- //Boolean - Whether to show a dot for each point
- pointDot : true,
-
- //Number - Radius of each point dot in pixels
- pointDotRadius : 4,
-
- //Number - Pixel width of point dot stroke
- pointDotStrokeWidth : 1,
-
- //Number - amount extra to add to the radius to cater for hit detection outside the drawn point
- pointHitDetectionRadius : 20,
-
- //Boolean - Whether to show a stroke for datasets
- datasetStroke : true,
-
- //Number - Pixel width of dataset stroke
- datasetStrokeWidth : 2,
-
- //Boolean - Whether to fill the dataset with a colour
- datasetFill : true,
-
- //String - A legend template
- legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
-
- };
-
-
- Chart.Type.extend({
- name: "Line",
- defaults : defaultConfig,
- initialize: function(data){
- //Declare the extension of the default point, to cater for the options passed in to the constructor
- this.PointClass = Chart.Point.extend({
- strokeWidth : this.options.pointDotStrokeWidth,
- radius : this.options.pointDotRadius,
- display: this.options.pointDot,
- hitDetectionRadius : this.options.pointHitDetectionRadius,
- ctx : this.chart.ctx,
- inRange : function(mouseX){
- return (Math.pow(mouseX-this.x, 2) < Math.pow(this.radius + this.hitDetectionRadius,2));
- }
- });
-
- this.datasets = [];
-
- //Set up tooltip events on the chart
- if (this.options.showTooltips){
- helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
- var activePoints = (evt.type !== 'mouseout') ? this.getPointsAtEvent(evt) : [];
- this.eachPoints(function(point){
- point.restore(['fillColor', 'strokeColor']);
- });
- helpers.each(activePoints, function(activePoint){
- activePoint.fillColor = activePoint.highlightFill;
- activePoint.strokeColor = activePoint.highlightStroke;
- });
- this.showTooltip(activePoints);
- });
- }
-
- //Iterate through each of the datasets, and build this into a property of the chart
- helpers.each(data.datasets,function(dataset){
-
- var datasetObject = {
- label : dataset.label || null,
- fillColor : dataset.fillColor,
- strokeColor : dataset.strokeColor,
- pointColor : dataset.pointColor,
- pointStrokeColor : dataset.pointStrokeColor,
- points : []
- };
-
- this.datasets.push(datasetObject);
-
-
- helpers.each(dataset.data,function(dataPoint,index){
- //Add a new point for each piece of data, passing any required data to draw.
- datasetObject.points.push(new this.PointClass({
- value : dataPoint,
- label : data.labels[index],
- datasetLabel: dataset.label,
- strokeColor : dataset.pointStrokeColor,
- fillColor : dataset.pointColor,
- highlightFill : dataset.pointHighlightFill || dataset.pointColor,
- highlightStroke : dataset.pointHighlightStroke || dataset.pointStrokeColor
- }));
- },this);
-
- this.buildScale(data.labels);
-
-
- this.eachPoints(function(point, index){
- helpers.extend(point, {
- x: this.scale.calculateX(index),
- y: this.scale.endPoint
- });
- point.save();
- }, this);
-
- },this);
-
-
- this.render();
- },
- update : function(){
- this.scale.update();
- // Reset any highlight colours before updating.
- helpers.each(this.activeElements, function(activeElement){
- activeElement.restore(['fillColor', 'strokeColor']);
- });
- this.eachPoints(function(point){
- point.save();
- });
- this.render();
- },
- eachPoints : function(callback){
- helpers.each(this.datasets,function(dataset){
- helpers.each(dataset.points,callback,this);
- },this);
- },
- getPointsAtEvent : function(e){
- var pointsArray = [],
- eventPosition = helpers.getRelativePosition(e);
- helpers.each(this.datasets,function(dataset){
- helpers.each(dataset.points,function(point){
- if (point.inRange(eventPosition.x,eventPosition.y)) pointsArray.push(point);
- });
- },this);
- return pointsArray;
- },
- buildScale : function(labels){
- var self = this;
-
- var dataTotal = function(){
- var values = [];
- self.eachPoints(function(point){
- values.push(point.value);
- });
-
- return values;
- };
-
- var scaleOptions = {
- templateString : this.options.scaleLabel,
- height : this.chart.height,
- width : this.chart.width,
- ctx : this.chart.ctx,
- textColor : this.options.scaleFontColor,
- fontSize : this.options.scaleFontSize,
- fontStyle : this.options.scaleFontStyle,
- fontFamily : this.options.scaleFontFamily,
- valuesCount : labels.length,
- beginAtZero : this.options.scaleBeginAtZero,
- integersOnly : this.options.scaleIntegersOnly,
- calculateYRange : function(currentHeight){
- var updatedRanges = helpers.calculateScaleRange(
- dataTotal(),
- currentHeight,
- this.fontSize,
- this.beginAtZero,
- this.integersOnly
- );
- helpers.extend(this, updatedRanges);
- },
- xLabels : labels,
- font : helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily),
- lineWidth : this.options.scaleLineWidth,
- lineColor : this.options.scaleLineColor,
- showHorizontalLines : this.options.scaleShowHorizontalLines,
- showVerticalLines : this.options.scaleShowVerticalLines,
- gridLineWidth : (this.options.scaleShowGridLines) ? this.options.scaleGridLineWidth : 0,
- gridLineColor : (this.options.scaleShowGridLines) ? this.options.scaleGridLineColor : "rgba(0,0,0,0)",
- padding: (this.options.showScale) ? 0 : this.options.pointDotRadius + this.options.pointDotStrokeWidth,
- showLabels : this.options.scaleShowLabels,
- display : this.options.showScale
- };
-
- if (this.options.scaleOverride){
- helpers.extend(scaleOptions, {
- calculateYRange: helpers.noop,
- steps: this.options.scaleSteps,
- stepValue: this.options.scaleStepWidth,
- min: this.options.scaleStartValue,
- max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
- });
- }
-
-
- this.scale = new Chart.Scale(scaleOptions);
- },
- addData : function(valuesArray,label){
- //Map the values array for each of the datasets
-
- helpers.each(valuesArray,function(value,datasetIndex){
- //Add a new point for each piece of data, passing any required data to draw.
- this.datasets[datasetIndex].points.push(new this.PointClass({
- value : value,
- label : label,
- x: this.scale.calculateX(this.scale.valuesCount+1),
- y: this.scale.endPoint,
- strokeColor : this.datasets[datasetIndex].pointStrokeColor,
- fillColor : this.datasets[datasetIndex].pointColor
- }));
- },this);
-
- this.scale.addXLabel(label);
- //Then re-render the chart.
- this.update();
- },
- removeData : function(){
- this.scale.removeXLabel();
- //Then re-render the chart.
- helpers.each(this.datasets,function(dataset){
- dataset.points.shift();
- },this);
- this.update();
- },
- reflow : function(){
- var newScaleProps = helpers.extend({
- height : this.chart.height,
- width : this.chart.width
- });
- this.scale.update(newScaleProps);
- },
- draw : function(ease){
- var easingDecimal = ease || 1;
- this.clear();
-
- var ctx = this.chart.ctx;
-
- // Some helper methods for getting the next/prev points
- var hasValue = function(item){
- return item.value !== null;
- },
- nextPoint = function(point, collection, index){
- return helpers.findNextWhere(collection, hasValue, index) || point;
- },
- previousPoint = function(point, collection, index){
- return helpers.findPreviousWhere(collection, hasValue, index) || point;
- };
-
- this.scale.draw(easingDecimal);
-
-
- helpers.each(this.datasets,function(dataset){
- var pointsWithValues = helpers.where(dataset.points, hasValue);
-
- //Transition each point first so that the line and point drawing isn't out of sync
- //We can use this extra loop to calculate the control points of this dataset also in this loop
-
- helpers.each(dataset.points, function(point, index){
- if (point.hasValue()){
- point.transition({
- y : this.scale.calculateY(point.value),
- x : this.scale.calculateX(index)
- }, easingDecimal);
- }
- },this);
-
-
- // Control points need to be calculated in a seperate loop, because we need to know the current x/y of the point
- // This would cause issues when there is no animation, because the y of the next point would be 0, so beziers would be skewed
- if (this.options.bezierCurve){
- helpers.each(pointsWithValues, function(point, index){
- var tension = (index > 0 && index < pointsWithValues.length - 1) ? this.options.bezierCurveTension : 0;
- point.controlPoints = helpers.splineCurve(
- previousPoint(point, pointsWithValues, index),
- point,
- nextPoint(point, pointsWithValues, index),
- tension
- );
-
- // Prevent the bezier going outside of the bounds of the graph
-
- // Cap puter bezier handles to the upper/lower scale bounds
- if (point.controlPoints.outer.y > this.scale.endPoint){
- point.controlPoints.outer.y = this.scale.endPoint;
- }
- else if (point.controlPoints.outer.y < this.scale.startPoint){
- point.controlPoints.outer.y = this.scale.startPoint;
- }
-
- // Cap inner bezier handles to the upper/lower scale bounds
- if (point.controlPoints.inner.y > this.scale.endPoint){
- point.controlPoints.inner.y = this.scale.endPoint;
- }
- else if (point.controlPoints.inner.y < this.scale.startPoint){
- point.controlPoints.inner.y = this.scale.startPoint;
- }
- },this);
- }
-
-
- //Draw the line between all the points
- ctx.lineWidth = this.options.datasetStrokeWidth;
- ctx.strokeStyle = dataset.strokeColor;
- ctx.beginPath();
-
- helpers.each(pointsWithValues, function(point, index){
- if (index === 0){
- ctx.moveTo(point.x, point.y);
- }
- else{
- if(this.options.bezierCurve){
- var previous = previousPoint(point, pointsWithValues, index);
-
- ctx.bezierCurveTo(
- previous.controlPoints.outer.x,
- previous.controlPoints.outer.y,
- point.controlPoints.inner.x,
- point.controlPoints.inner.y,
- point.x,
- point.y
- );
- }
- else{
- ctx.lineTo(point.x,point.y);
- }
- }
- }, this);
-
- ctx.stroke();
-
- if (this.options.datasetFill && pointsWithValues.length > 0){
- //Round off the line by going to the base of the chart, back to the start, then fill.
- ctx.lineTo(pointsWithValues[pointsWithValues.length - 1].x, this.scale.endPoint);
- ctx.lineTo(pointsWithValues[0].x, this.scale.endPoint);
- ctx.fillStyle = dataset.fillColor;
- ctx.closePath();
- ctx.fill();
- }
-
- //Now draw the points over the line
- //A little inefficient double looping, but better than the line
- //lagging behind the point positions
- helpers.each(pointsWithValues,function(point){
- point.draw();
- });
- },this);
- }
- });
-
-
-}).call(this);
-
-(function(){
- "use strict";
-
- var root = this,
- Chart = root.Chart,
- //Cache a local reference to Chart.helpers
- helpers = Chart.helpers;
-
- var defaultConfig = {
- //Boolean - Show a backdrop to the scale label
- scaleShowLabelBackdrop : true,
-
- //String - The colour of the label backdrop
- scaleBackdropColor : "rgba(255,255,255,0.75)",
-
- // Boolean - Whether the scale should begin at zero
- scaleBeginAtZero : true,
-
- //Number - The backdrop padding above & below the label in pixels
- scaleBackdropPaddingY : 2,
-
- //Number - The backdrop padding to the side of the label in pixels
- scaleBackdropPaddingX : 2,
-
- //Boolean - Show line for each value in the scale
- scaleShowLine : true,
-
- //Boolean - Stroke a line around each segment in the chart
- segmentShowStroke : true,
-
- //String - The colour of the stroke on each segement.
- segmentStrokeColor : "#fff",
-
- //Number - The width of the stroke value in pixels
- segmentStrokeWidth : 2,
-
- //Number - Amount of animation steps
- animationSteps : 100,
-
- //String - Animation easing effect.
- animationEasing : "easeOutBounce",
-
- //Boolean - Whether to animate the rotation of the chart
- animateRotate : true,
-
- //Boolean - Whether to animate scaling the chart from the centre
- animateScale : false,
-
- //String - A legend template
- legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
- };
-
-
- Chart.Type.extend({
- //Passing in a name registers this chart in the Chart namespace
- name: "PolarArea",
- //Providing a defaults will also register the deafults in the chart namespace
- defaults : defaultConfig,
- //Initialize is fired when the chart is initialized - Data is passed in as a parameter
- //Config is automatically merged by the core of Chart.js, and is available at this.options
- initialize: function(data){
- this.segments = [];
- //Declare segment class as a chart instance specific class, so it can share props for this instance
- this.SegmentArc = Chart.Arc.extend({
- showStroke : this.options.segmentShowStroke,
- strokeWidth : this.options.segmentStrokeWidth,
- strokeColor : this.options.segmentStrokeColor,
- ctx : this.chart.ctx,
- innerRadius : 0,
- x : this.chart.width/2,
- y : this.chart.height/2
- });
- this.scale = new Chart.RadialScale({
- display: this.options.showScale,
- fontStyle: this.options.scaleFontStyle,
- fontSize: this.options.scaleFontSize,
- fontFamily: this.options.scaleFontFamily,
- fontColor: this.options.scaleFontColor,
- showLabels: this.options.scaleShowLabels,
- showLabelBackdrop: this.options.scaleShowLabelBackdrop,
- backdropColor: this.options.scaleBackdropColor,
- backdropPaddingY : this.options.scaleBackdropPaddingY,
- backdropPaddingX: this.options.scaleBackdropPaddingX,
- lineWidth: (this.options.scaleShowLine) ? this.options.scaleLineWidth : 0,
- lineColor: this.options.scaleLineColor,
- lineArc: true,
- width: this.chart.width,
- height: this.chart.height,
- xCenter: this.chart.width/2,
- yCenter: this.chart.height/2,
- ctx : this.chart.ctx,
- templateString: this.options.scaleLabel,
- valuesCount: data.length
- });
-
- this.updateScaleRange(data);
-
- this.scale.update();
-
- helpers.each(data,function(segment,index){
- this.addData(segment,index,true);
- },this);
-
- //Set up tooltip events on the chart
- if (this.options.showTooltips){
- helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
- var activeSegments = (evt.type !== 'mouseout') ? this.getSegmentsAtEvent(evt) : [];
- helpers.each(this.segments,function(segment){
- segment.restore(["fillColor"]);
- });
- helpers.each(activeSegments,function(activeSegment){
- activeSegment.fillColor = activeSegment.highlightColor;
- });
- this.showTooltip(activeSegments);
- });
- }
-
- this.render();
- },
- getSegmentsAtEvent : function(e){
- var segmentsArray = [];
-
- var location = helpers.getRelativePosition(e);
-
- helpers.each(this.segments,function(segment){
- if (segment.inRange(location.x,location.y)) segmentsArray.push(segment);
- },this);
- return segmentsArray;
- },
- addData : function(segment, atIndex, silent){
- var index = atIndex || this.segments.length;
-
- this.segments.splice(index, 0, new this.SegmentArc({
- fillColor: segment.color,
- highlightColor: segment.highlight || segment.color,
- label: segment.label,
- value: segment.value,
- outerRadius: (this.options.animateScale) ? 0 : this.scale.calculateCenterOffset(segment.value),
- circumference: (this.options.animateRotate) ? 0 : this.scale.getCircumference(),
- startAngle: Math.PI * 1.5
- }));
- if (!silent){
- this.reflow();
- this.update();
- }
- },
- removeData: function(atIndex){
- var indexToDelete = (helpers.isNumber(atIndex)) ? atIndex : this.segments.length-1;
- this.segments.splice(indexToDelete, 1);
- this.reflow();
- this.update();
- },
- calculateTotal: function(data){
- this.total = 0;
- helpers.each(data,function(segment){
- this.total += segment.value;
- },this);
- this.scale.valuesCount = this.segments.length;
- },
- updateScaleRange: function(datapoints){
- var valuesArray = [];
- helpers.each(datapoints,function(segment){
- valuesArray.push(segment.value);
- });
-
- var scaleSizes = (this.options.scaleOverride) ?
- {
- steps: this.options.scaleSteps,
- stepValue: this.options.scaleStepWidth,
- min: this.options.scaleStartValue,
- max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
- } :
- helpers.calculateScaleRange(
- valuesArray,
- helpers.min([this.chart.width, this.chart.height])/2,
- this.options.scaleFontSize,
- this.options.scaleBeginAtZero,
- this.options.scaleIntegersOnly
- );
-
- helpers.extend(
- this.scale,
- scaleSizes,
- {
- size: helpers.min([this.chart.width, this.chart.height]),
- xCenter: this.chart.width/2,
- yCenter: this.chart.height/2
- }
- );
-
- },
- update : function(){
- this.calculateTotal(this.segments);
-
- helpers.each(this.segments,function(segment){
- segment.save();
- });
-
- this.reflow();
- this.render();
- },
- reflow : function(){
- helpers.extend(this.SegmentArc.prototype,{
- x : this.chart.width/2,
- y : this.chart.height/2
- });
- this.updateScaleRange(this.segments);
- this.scale.update();
-
- helpers.extend(this.scale,{
- xCenter: this.chart.width/2,
- yCenter: this.chart.height/2
- });
-
- helpers.each(this.segments, function(segment){
- segment.update({
- outerRadius : this.scale.calculateCenterOffset(segment.value)
- });
- }, this);
-
- },
- draw : function(ease){
- var easingDecimal = ease || 1;
- //Clear & draw the canvas
- this.clear();
- helpers.each(this.segments,function(segment, index){
- segment.transition({
- circumference : this.scale.getCircumference(),
- outerRadius : this.scale.calculateCenterOffset(segment.value)
- },easingDecimal);
-
- segment.endAngle = segment.startAngle + segment.circumference;
-
- // If we've removed the first segment we need to set the first one to
- // start at the top.
- if (index === 0){
- segment.startAngle = Math.PI * 1.5;
- }
-
- //Check to see if it's the last segment, if not get the next and update the start angle
- if (index < this.segments.length - 1){
- this.segments[index+1].startAngle = segment.endAngle;
- }
- segment.draw();
- }, this);
- this.scale.draw();
- }
- });
-
-}).call(this);
-(function(){
- "use strict";
-
- var root = this,
- Chart = root.Chart,
- helpers = Chart.helpers;
-
-
-
- Chart.Type.extend({
- name: "Radar",
- defaults:{
- //Boolean - Whether to show lines for each scale point
- scaleShowLine : true,
-
- //Boolean - Whether we show the angle lines out of the radar
- angleShowLineOut : true,
-
- //Boolean - Whether to show labels on the scale
- scaleShowLabels : false,
-
- // Boolean - Whether the scale should begin at zero
- scaleBeginAtZero : true,
-
- //String - Colour of the angle line
- angleLineColor : "rgba(0,0,0,.1)",
-
- //Number - Pixel width of the angle line
- angleLineWidth : 1,
-
- //String - Point label font declaration
- pointLabelFontFamily : "'Arial'",
-
- //String - Point label font weight
- pointLabelFontStyle : "normal",
-
- //Number - Point label font size in pixels
- pointLabelFontSize : 10,
-
- //String - Point label font colour
- pointLabelFontColor : "#666",
-
- //Boolean - Whether to show a dot for each point
- pointDot : true,
-
- //Number - Radius of each point dot in pixels
- pointDotRadius : 3,
-
- //Number - Pixel width of point dot stroke
- pointDotStrokeWidth : 1,
-
- //Number - amount extra to add to the radius to cater for hit detection outside the drawn point
- pointHitDetectionRadius : 20,
-
- //Boolean - Whether to show a stroke for datasets
- datasetStroke : true,
-
- //Number - Pixel width of dataset stroke
- datasetStrokeWidth : 2,
-
- //Boolean - Whether to fill the dataset with a colour
- datasetFill : true,
-
- //String - A legend template
- legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
-
- },
-
- initialize: function(data){
- this.PointClass = Chart.Point.extend({
- strokeWidth : this.options.pointDotStrokeWidth,
- radius : this.options.pointDotRadius,
- display: this.options.pointDot,
- hitDetectionRadius : this.options.pointHitDetectionRadius,
- ctx : this.chart.ctx
- });
-
- this.datasets = [];
-
- this.buildScale(data);
-
- //Set up tooltip events on the chart
- if (this.options.showTooltips){
- helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
- var activePointsCollection = (evt.type !== 'mouseout') ? this.getPointsAtEvent(evt) : [];
-
- this.eachPoints(function(point){
- point.restore(['fillColor', 'strokeColor']);
- });
- helpers.each(activePointsCollection, function(activePoint){
- activePoint.fillColor = activePoint.highlightFill;
- activePoint.strokeColor = activePoint.highlightStroke;
- });
-
- this.showTooltip(activePointsCollection);
- });
- }
-
- //Iterate through each of the datasets, and build this into a property of the chart
- helpers.each(data.datasets,function(dataset){
-
- var datasetObject = {
- label: dataset.label || null,
- fillColor : dataset.fillColor,
- strokeColor : dataset.strokeColor,
- pointColor : dataset.pointColor,
- pointStrokeColor : dataset.pointStrokeColor,
- points : []
- };
-
- this.datasets.push(datasetObject);
-
- helpers.each(dataset.data,function(dataPoint,index){
- //Add a new point for each piece of data, passing any required data to draw.
- var pointPosition;
- if (!this.scale.animation){
- pointPosition = this.scale.getPointPosition(index, this.scale.calculateCenterOffset(dataPoint));
- }
- datasetObject.points.push(new this.PointClass({
- value : dataPoint,
- label : data.labels[index],
- datasetLabel: dataset.label,
- x: (this.options.animation) ? this.scale.xCenter : pointPosition.x,
- y: (this.options.animation) ? this.scale.yCenter : pointPosition.y,
- strokeColor : dataset.pointStrokeColor,
- fillColor : dataset.pointColor,
- highlightFill : dataset.pointHighlightFill || dataset.pointColor,
- highlightStroke : dataset.pointHighlightStroke || dataset.pointStrokeColor
- }));
- },this);
-
- },this);
-
- this.render();
- },
- eachPoints : function(callback){
- helpers.each(this.datasets,function(dataset){
- helpers.each(dataset.points,callback,this);
- },this);
- },
-
- getPointsAtEvent : function(evt){
- var mousePosition = helpers.getRelativePosition(evt),
- fromCenter = helpers.getAngleFromPoint({
- x: this.scale.xCenter,
- y: this.scale.yCenter
- }, mousePosition);
-
- var anglePerIndex = (Math.PI * 2) /this.scale.valuesCount,
- pointIndex = Math.round((fromCenter.angle - Math.PI * 1.5) / anglePerIndex),
- activePointsCollection = [];
-
- // If we're at the top, make the pointIndex 0 to get the first of the array.
- if (pointIndex >= this.scale.valuesCount || pointIndex < 0){
- pointIndex = 0;
- }
-
- if (fromCenter.distance <= this.scale.drawingArea){
- helpers.each(this.datasets, function(dataset){
- activePointsCollection.push(dataset.points[pointIndex]);
- });
- }
-
- return activePointsCollection;
- },
-
- buildScale : function(data){
- this.scale = new Chart.RadialScale({
- display: this.options.showScale,
- fontStyle: this.options.scaleFontStyle,
- fontSize: this.options.scaleFontSize,
- fontFamily: this.options.scaleFontFamily,
- fontColor: this.options.scaleFontColor,
- showLabels: this.options.scaleShowLabels,
- showLabelBackdrop: this.options.scaleShowLabelBackdrop,
- backdropColor: this.options.scaleBackdropColor,
- backdropPaddingY : this.options.scaleBackdropPaddingY,
- backdropPaddingX: this.options.scaleBackdropPaddingX,
- lineWidth: (this.options.scaleShowLine) ? this.options.scaleLineWidth : 0,
- lineColor: this.options.scaleLineColor,
- angleLineColor : this.options.angleLineColor,
- angleLineWidth : (this.options.angleShowLineOut) ? this.options.angleLineWidth : 0,
- // Point labels at the edge of each line
- pointLabelFontColor : this.options.pointLabelFontColor,
- pointLabelFontSize : this.options.pointLabelFontSize,
- pointLabelFontFamily : this.options.pointLabelFontFamily,
- pointLabelFontStyle : this.options.pointLabelFontStyle,
- height : this.chart.height,
- width: this.chart.width,
- xCenter: this.chart.width/2,
- yCenter: this.chart.height/2,
- ctx : this.chart.ctx,
- templateString: this.options.scaleLabel,
- labels: data.labels,
- valuesCount: data.datasets[0].data.length
- });
-
- this.scale.setScaleSize();
- this.updateScaleRange(data.datasets);
- this.scale.buildYLabels();
- },
- updateScaleRange: function(datasets){
- var valuesArray = (function(){
- var totalDataArray = [];
- helpers.each(datasets,function(dataset){
- if (dataset.data){
- totalDataArray = totalDataArray.concat(dataset.data);
- }
- else {
- helpers.each(dataset.points, function(point){
- totalDataArray.push(point.value);
- });
- }
- });
- return totalDataArray;
- })();
-
-
- var scaleSizes = (this.options.scaleOverride) ?
- {
- steps: this.options.scaleSteps,
- stepValue: this.options.scaleStepWidth,
- min: this.options.scaleStartValue,
- max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
- } :
- helpers.calculateScaleRange(
- valuesArray,
- helpers.min([this.chart.width, this.chart.height])/2,
- this.options.scaleFontSize,
- this.options.scaleBeginAtZero,
- this.options.scaleIntegersOnly
- );
-
- helpers.extend(
- this.scale,
- scaleSizes
- );
-
- },
- addData : function(valuesArray,label){
- //Map the values array for each of the datasets
- this.scale.valuesCount++;
- helpers.each(valuesArray,function(value,datasetIndex){
- var pointPosition = this.scale.getPointPosition(this.scale.valuesCount, this.scale.calculateCenterOffset(value));
- this.datasets[datasetIndex].points.push(new this.PointClass({
- value : value,
- label : label,
- x: pointPosition.x,
- y: pointPosition.y,
- strokeColor : this.datasets[datasetIndex].pointStrokeColor,
- fillColor : this.datasets[datasetIndex].pointColor
- }));
- },this);
-
- this.scale.labels.push(label);
-
- this.reflow();
-
- this.update();
- },
- removeData : function(){
- this.scale.valuesCount--;
- this.scale.labels.shift();
- helpers.each(this.datasets,function(dataset){
- dataset.points.shift();
- },this);
- this.reflow();
- this.update();
- },
- update : function(){
- this.eachPoints(function(point){
- point.save();
- });
- this.reflow();
- this.render();
- },
- reflow: function(){
- helpers.extend(this.scale, {
- width : this.chart.width,
- height: this.chart.height,
- size : helpers.min([this.chart.width, this.chart.height]),
- xCenter: this.chart.width/2,
- yCenter: this.chart.height/2
- });
- this.updateScaleRange(this.datasets);
- this.scale.setScaleSize();
- this.scale.buildYLabels();
- },
- draw : function(ease){
- var easeDecimal = ease || 1,
- ctx = this.chart.ctx;
- this.clear();
- this.scale.draw();
-
- helpers.each(this.datasets,function(dataset){
-
- //Transition each point first so that the line and point drawing isn't out of sync
- helpers.each(dataset.points,function(point,index){
- if (point.hasValue()){
- point.transition(this.scale.getPointPosition(index, this.scale.calculateCenterOffset(point.value)), easeDecimal);
- }
- },this);
-
-
-
- //Draw the line between all the points
- ctx.lineWidth = this.options.datasetStrokeWidth;
- ctx.strokeStyle = dataset.strokeColor;
- ctx.beginPath();
- helpers.each(dataset.points,function(point,index){
- if (index === 0){
- ctx.moveTo(point.x,point.y);
- }
- else{
- ctx.lineTo(point.x,point.y);
- }
- },this);
- ctx.closePath();
- ctx.stroke();
-
- ctx.fillStyle = dataset.fillColor;
- ctx.fill();
-
- //Now draw the points over the line
- //A little inefficient double looping, but better than the line
- //lagging behind the point positions
- helpers.each(dataset.points,function(point){
- if (point.hasValue()){
- point.draw();
- }
- });
-
- },this);
-
- }
-
- });
-
-
-
-
-
-}).call(this); \ No newline at end of file
diff --git a/yarn.lock b/yarn.lock
index 3285fdae331..95f20a4d3e1 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1443,6 +1443,10 @@ chalk@^2.0.0, chalk@^2.0.1, chalk@^2.1.0, chalk@^2.3.0:
escape-string-regexp "^1.0.5"
supports-color "^4.0.0"
+chart.js@1.0.2:
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/chart.js/-/chart.js-1.0.2.tgz#ad57d2229cfd8ccf5955147e8121b4911e69dfe7"
+
chokidar@^1.4.1, chokidar@^1.4.3, chokidar@^1.6.0, chokidar@^1.7.0:
version "1.7.0"
resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-1.7.0.tgz#798e689778151c8076b4b360e5edd28cda2bb468"