2015-09-25 12:07:36 +05:30
|
|
|
require 'gitlab/markdown'
|
|
|
|
|
2015-09-11 14:41:01 +05:30
|
|
|
module Gitlab
|
|
|
|
module Markdown
|
|
|
|
# HTML filter that replaces snippet references with links. References to
|
|
|
|
# snippets that do not exist are ignored.
|
|
|
|
#
|
|
|
|
# This filter supports cross-project references.
|
|
|
|
class SnippetReferenceFilter < ReferenceFilter
|
|
|
|
include CrossProjectReference
|
|
|
|
|
|
|
|
# Public: Find `$123` snippet references in text
|
|
|
|
#
|
|
|
|
# SnippetReferenceFilter.references_in(text) do |match, snippet|
|
|
|
|
# "<a href=...>$#{snippet}</a>"
|
|
|
|
# end
|
|
|
|
#
|
|
|
|
# text - String text to search.
|
|
|
|
#
|
|
|
|
# Yields the String match, the Integer snippet ID, and an optional String
|
|
|
|
# of the external project reference.
|
|
|
|
#
|
|
|
|
# Returns a String replaced with the return of the block.
|
|
|
|
def self.references_in(text)
|
|
|
|
text.gsub(Snippet.reference_pattern) do |match|
|
|
|
|
yield match, $~[:snippet].to_i, $~[:project]
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2015-10-24 18:46:33 +05:30
|
|
|
def self.referenced_by(node)
|
|
|
|
{ snippet: LazyReference.new(Snippet, node.attr("data-snippet")) }
|
|
|
|
end
|
|
|
|
|
2015-09-11 14:41:01 +05:30
|
|
|
def call
|
|
|
|
replace_text_nodes_matching(Snippet.reference_pattern) do |content|
|
|
|
|
snippet_link_filter(content)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
# Replace `$123` snippet references in text with links to the referenced
|
|
|
|
# snippets's details page.
|
|
|
|
#
|
|
|
|
# text - String text to replace references in.
|
|
|
|
#
|
|
|
|
# Returns a String with `$123` references replaced with links. All links
|
|
|
|
# have `gfm` and `gfm-snippet` class names attached for styling.
|
|
|
|
def snippet_link_filter(text)
|
|
|
|
self.class.references_in(text) do |match, id, project_ref|
|
|
|
|
project = self.project_from_ref(project_ref)
|
|
|
|
|
|
|
|
if project && snippet = project.snippets.find_by(id: id)
|
|
|
|
title = escape_once("Snippet: #{snippet.title}")
|
|
|
|
klass = reference_class(:snippet)
|
2015-10-24 18:46:33 +05:30
|
|
|
data = data_attribute(project: project.id, snippet: snippet.id)
|
2015-09-11 14:41:01 +05:30
|
|
|
|
|
|
|
url = url_for_snippet(snippet, project)
|
|
|
|
|
|
|
|
%(<a href="#{url}" #{data}
|
|
|
|
title="#{title}"
|
|
|
|
class="#{klass}">#{match}</a>)
|
|
|
|
else
|
|
|
|
match
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def url_for_snippet(snippet, project)
|
2015-09-25 12:07:36 +05:30
|
|
|
h = Gitlab::Application.routes.url_helpers
|
2015-09-11 14:41:01 +05:30
|
|
|
h.namespace_project_snippet_url(project.namespace, project, snippet,
|
|
|
|
only_path: context[:only_path])
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|