Class: JsDuck::DocFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/jsduck/doc_formatter.rb

Overview

Formats doc-comments

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(relations = {}, opts = {}) ⇒ DocFormatter

Returns a new instance of DocFormatter.



58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/jsduck/doc_formatter.rb', line 58

def initialize(relations={}, opts={})
  @class_context = ""
  @doc_context = {}
  @max_length = 120
  @relations = relations
  @images = []
  @link_tpl = opts[:link_tpl] || '<a href="%c%#%m">%a</a>'
  @img_tpl = opts[:img_tpl] || '<img src="%u" alt="%a"/>'
  @link_re = /\{@link\s+(\S*?)(?:\s+(.+?))?\}/m
  @img_re = /\{@img\s+(\S*?)(?:\s+(.+?))?\}/m
  @example_annotation_re = /<pre><code>\s*@example( +[^\n]*)?\s+/m
end

Instance Attribute Details

#class_contextObject

Sets up instance to work in context of particular class, so that when #blah is encountered it knows that Context#blah is meant.



42
43
44
# File 'lib/jsduck/doc_formatter.rb', line 42

def class_context
  @class_context
end

#doc_contextObject

Sets up instance to work in context of particular doc object. Used for error reporting.



46
47
48
# File 'lib/jsduck/doc_formatter.rb', line 46

def doc_context
  @doc_context
end

#imagesObject

This will hold list of all image paths gathered from @img tags.



33
34
35
# File 'lib/jsduck/doc_formatter.rb', line 33

def images
  @images
end

#img_pathObject

Base path to prefix images from @img tags. Defaults to no prefix.



37
38
39
# File 'lib/jsduck/doc_formatter.rb', line 37

def img_path
  @img_path
end

#img_tplObject

Template HTML that replaces URL alt text Can contain placeholders:

%u - URL from @img tag (e.g. “some/path.png”) %a - alt text for image

Default value: ‘<img src=“%u” alt=“%a”/>’



30
31
32
# File 'lib/jsduck/doc_formatter.rb', line 30

def img_tpl
  @img_tpl
end

Template HTML that replaces Class#member anchor text. Can contain placeholders:

%c - full class name (e.g. “Ext.Panel”) %m - class member name prefixed with member type (e.g. “method-urlEncode”) %# - inserts “#” if member name present %- - inserts “-” if member name present %a - anchor text for link

Default value: ‘<a href=“%c%M”>%a</a>’



21
22
23
# File 'lib/jsduck/doc_formatter.rb', line 21

def link_tpl
  @link_tpl
end

#max_lengthObject

Maximum length for text that doesn’t get shortened, defaults to 120



49
50
51
# File 'lib/jsduck/doc_formatter.rb', line 49

def max_length
  @max_length
end

#relationsObject

JsDuck::Relations for looking up class names.

When auto-creating class links from CamelCased names found from text, we check the relations object to see if a class with that name actually exists.



56
57
58
# File 'lib/jsduck/doc_formatter.rb', line 56

def relations
  @relations
end

Instance Method Details

Looks input text for patterns like:

My.ClassName
MyClass#method
#someProperty

and converts them to links, as if they were surrounded with @link tag. One notable exception is that Foo is not created to link, even when Foo class exists, but Foo.Bar is. This is to avoid turning normal words into links. For example:

Math involves a lot of numbers. Ext JS is a JavaScript framework.

In these sentences we don’t want to link “Math” and “Ext” to the corresponding JS classes. And that’s why we auto-link only class names containing a dot “.”



209
210
211
212
213
214
215
216
# File 'lib/jsduck/doc_formatter.rb', line 209

def create_magic_links(input)
  cls_re = "([A-Z][A-Za-z0-9.]*[A-Za-z0-9])"
  member_re = "(?:#([A-Za-z0-9]+))"

  input.gsub(/\b#{cls_re}#{member_re}?\b|#{member_re}\b/m) do
    replace_magic_link($1, $2 || $3)
  end
end

#first_sentence(str) ⇒ Object



355
356
357
# File 'lib/jsduck/doc_formatter.rb', line 355

def first_sentence(str)
  str.sub(/\A(.+?\.)\s.*\Z/m, "\\1")
end

#format(input) ⇒ Object

Formats doc-comment for placement into HTML. Renders it with Markdown-formatter and replaces @link-s.



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/jsduck/doc_formatter.rb', line 317

def format(input)
  # In ExtJS source "<pre>" is often at the end of paragraph, not
  # on its own line.  But in that case RDiscount doesn't recognize
  # it as the beginning of <pre>-block and goes on parsing it as
  # normal Markdown, which often causes nested <pre>-blocks.
  #
  # To prevent this, we always add extra newline before <pre>.
  input.gsub!(/([^\n])<pre>/, "\\1\n<pre>")

  # But we remove trailing newline after <pre> to prevent
  # code-blocks beginning with empty line.
  input.gsub!(/<pre>(<code>)?\n?/, "<pre>\\1")

  replace(RDiscount.new(input).to_html)
end

#get_matching_member(cls, member, type = nil, static = false) ⇒ Object



301
302
303
304
305
306
307
308
309
# File 'lib/jsduck/doc_formatter.rb', line 301

def get_matching_member(cls, member, type=nil, static=false)
  ms = get_members(cls, member, type, static).find_all {|m| !m[:private] }
  if ms.length > 1
    instance_ms = ms.find_all {|m| !m[:meta][:static] }
    instance_ms.length > 0 ? instance_ms[0] : ms.find_all {|m| m[:meta][:static] }[0]
  else
    ms[0]
  end
end

#get_members(cls, member, type = nil, static = false) ⇒ Object



311
312
313
# File 'lib/jsduck/doc_formatter.rb', line 311

def get_members(cls, member, type=nil, static=false)
  @relations[cls] ? @relations[cls].get_members(member, type, static) : []
end

#img(url, alt_text) ⇒ Object

applies the image template



262
263
264
265
266
267
268
269
270
271
272
273
274
# File 'lib/jsduck/doc_formatter.rb', line 262

def img(url, alt_text)
  @images << url
  @img_tpl.gsub(/(%\w)/) do
    case $1
    when '%u'
      @img_path ? (@img_path + "/" + url) : url
    when '%a'
      CGI.escapeHTML(alt_text||"")
    else
      $1
    end
  end
end

applies the link template



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/jsduck/doc_formatter.rb', line 277

def link(cls, member, anchor_text, type=nil, static=false)
  # Use the canonical class name for link (not some alternateClassName)
  cls = @relations[cls].full_name
  # prepend type name to member name
  member = member && get_matching_member(cls, member, type, static)

  @link_tpl.gsub(/(%[\w#-])/) do
    case $1
    when '%c'
      cls
    when '%m'
      member ? member[:id] : ""
    when '%#'
      member ? "#" : ""
    when '%-'
      member ? "-" : ""
    when '%a'
      CGI.escapeHTML(anchor_text||"")
    else
      $1
    end
  end
end

#replace(input) ⇒ Object

Replaces @link and @img tags, auto-generates links for recognized classnames.

Replaces Class#member link text in given string with HTML from @link_tpl.

Replaces path/to/image.jpg Alt text with HTML from @img_tpl.

Adds ‘inline-example’ class to code examples beginning with @example.

Additionally replaces strings recognized as ClassNames or #members with links to these classes or members. So one doesn’t even need to use the @link tag to create a link.



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/jsduck/doc_formatter.rb', line 84

def replace(input)
  s = StringScanner.new(input)
  out = ""

  # Keep track of the nesting level of <a> tags. We're not
  # auto-detecting class names when inside <a>. Normally links
  # shouldn't be nested, but just to be extra safe.
  open_a_tags = 0

  while !s.eos? do
    if s.check(@link_re)
      out += replace_link_tag(s.scan(@link_re))
    elsif s.check(@img_re)
      out += replace_img_tag(s.scan(@img_re))
    elsif s.check(/[{]/)
      # There might still be "{" that doesn't begin {@link} or {@img} - ignore it
      out += s.scan(/[{]/)
    elsif s.check(@example_annotation_re)
      # Match possible classnames following @example and add them
      # as CSS classes inside <pre> element.
      s.scan(@example_annotation_re) =~ @example_annotation_re
      css_classes = ($1 || "").strip
      out += "<pre class='inline-example #{css_classes}'><code>"
    elsif s.check(/<a\b/)
      # Increment number of open <a> tags.
      open_a_tags += 1
      out += s.scan_until(/>|\Z/)
    elsif s.check(/<\/a>/)
      # <a> closed, auto-detection may continue when no more <a> tags open.
      open_a_tags -= 1
      out += s.scan(/<\/a>/)
    elsif s.check(/</)
      # Ignore all other HTML tags
      out += s.scan_until(/>|\Z/)
    else
      # Replace class names in the following text up to next "<" or "{"
      # but only when we're not inside <a>...</a>
      text = s.scan(/[^{<]+/)
      out += open_a_tags > 0 ? text : create_magic_links(text)
    end
  end
  out
end

#replace_img_tag(input) ⇒ Object



188
189
190
# File 'lib/jsduck/doc_formatter.rb', line 188

def replace_img_tag(input)
  input.sub(@img_re) { img($1, $2) }
end


128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/jsduck/doc_formatter.rb', line 128

def replace_link_tag(input)
  input.sub(@link_re) do
    target = $1
    text = $2
    if target =~ /^(.*)#(static-)?(?:(cfg|property|method|event|css_var|css_mixin)-)?(.*)$/
      cls = $1.empty? ? @class_context : $1
      static = !!$2
      type = $3 ? $3.intern : nil
      member = $4
    else
      cls = target
      static = false
      type = false
      member = false
    end

    # Construct link text
    if text
      text = text
    elsif member
      text = (cls == @class_context) ? member : (cls + "." + member)
    else
      text = cls
    end

    file = @doc_context[:filename]
    line = @doc_context[:linenr]
    if !@relations[cls]
      Logger.instance.warn(:link, "#{input} links to non-existing class", file, line)
      return text
    elsif member
      ms = get_members(cls, member, type, static)
      if ms.length == 0
        Logger.instance.warn(:link, "#{input} links to non-existing member", file, line)
        return text
      end

      if ms.length > 1
        # When multiple public members, see if there remains just
        # one when we ignore the static members. If there's more,
        # report ambiguity. If there's only static members, also
        # report ambiguity.
        instance_ms = ms.find_all {|m| !m[:meta][:static] }
        if instance_ms.length > 1
          alternatives = instance_ms.map {|m| m[:tagname].to_s }.join(", ")
          Logger.instance.warn(:link_ambiguous, "#{input} is ambiguous: "+alternatives, file, line)
        elsif instance_ms.length == 0
          static_ms = ms.find_all {|m| m[:meta][:static] }
          alternatives = static_ms.map {|m| "static " + m[:tagname].to_s }.join(", ")
          Logger.instance.warn(:link_ambiguous, "#{input} is ambiguous: "+alternatives, file, line)
        end
      end

      return link(cls, member, text, type, static)
    else
      return link(cls, false, text)
    end
  end
end


218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/jsduck/doc_formatter.rb', line 218

def replace_magic_link(cls, member)
  if cls && member
    if @relations[cls] && get_matching_member(cls, member)
      return link(cls, member, cls+"."+member)
    else
      warn_magic_link("#{cls}##{member} links to non-existing " + (@relations[cls] ? "member" : "class"))
    end
  elsif cls && cls =~ /\./
    if @relations[cls]
      return link(cls, nil, cls)
    else
      cls2, member2 = split_to_cls_and_member(cls)
      if @relations[cls2] && get_matching_member(cls2, member2)
        return link(cls2, member2, cls2+"."+member2)
      elsif cls =~ /\.(js|css|html|php)\Z/
        # Ignore common filenames
      else
        warn_magic_link("#{cls} links to non-existing class")
      end
    end
  elsif !cls && member
    if get_matching_member(@class_context, member)
      return link(@class_context, member, member)
    elsif member =~ /\A([A-F0-9]{3}|[A-F0-9]{6})\Z/i || member =~ /\A[0-9]/
      # Ignore HEX color codes and
      # member names beginning with number
    else
      warn_magic_link("##{member} links to non-existing member")
    end
  end

  return "#{cls}#{member ? '#' : ''}#{member}"
end

#shorten(input) ⇒ Object

Shortens text

116 chars is also where ext-doc makes its cut, but unlike ext-doc we only make the cut when there’s more than 120 chars.

This way we don’t get stupid expansions like:

Blah blah blah some text...

expanding to:

Blah blah blah some text.


346
347
348
349
350
351
352
353
# File 'lib/jsduck/doc_formatter.rb', line 346

def shorten(input)
  sent = first_sentence(strip_tags(input))
  if sent.length > @max_length
    sent[0..(@max_length-4)] + "..."
  else
    sent + " ..."
  end
end

#split_to_cls_and_member(str) ⇒ Object



252
253
254
255
# File 'lib/jsduck/doc_formatter.rb', line 252

def split_to_cls_and_member(str)
  parts = str.split(/\./)
  return [parts.slice(0, parts.length-1).join("."), parts.last]
end

#strip_tags(str) ⇒ Object



365
366
367
# File 'lib/jsduck/doc_formatter.rb', line 365

def strip_tags(str)
  str.gsub(/<.*?>/, "").strip
end

#too_long?(input) ⇒ Boolean

Returns true when input should get shortened.

Returns:

  • (Boolean)


360
361
362
363
# File 'lib/jsduck/doc_formatter.rb', line 360

def too_long?(input)
  stripped = strip_tags(input)
  first_sentence(stripped).length < stripped.length || stripped.length > @max_length
end


257
258
259
# File 'lib/jsduck/doc_formatter.rb', line 257

def warn_magic_link(msg)
  Logger.instance.warn(:link_auto, msg, @doc_context[:filename], @doc_context[:linenr])
end