Class: Rich::Span

Inherits:
Object
  • Object
show all
Defined in:
lib/rich/text.rb

Overview

A span of styled text within a Text object

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(start_pos, end_pos, style) ⇒ Span

Returns a new instance of Span.



19
20
21
22
23
24
# File 'lib/rich/text.rb', line 19

def initialize(start_pos, end_pos, style)
  @start = start_pos
  @end = end_pos
  @style = style.is_a?(String) ? Style.parse(style) : style
  freeze
end

Instance Attribute Details

#endInteger (readonly)

Returns End position (exclusive).

Returns:

  • (Integer)

    End position (exclusive)



14
15
16
# File 'lib/rich/text.rb', line 14

def end
  @end
end

#startInteger (readonly)

Returns Start position (inclusive).

Returns:

  • (Integer)

    Start position (inclusive)



11
12
13
# File 'lib/rich/text.rb', line 11

def start
  @start
end

#styleStyle (readonly)

Returns Style for this span.

Returns:

  • (Style)

    Style for this span



17
18
19
# File 'lib/rich/text.rb', line 17

def style
  @style
end

Instance Method Details

#adjust_delete(position, length) ⇒ Object

Adjust span after deletion at position



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/rich/text.rb', line 48

def adjust_delete(position, length)
  delete_end = position + length

  if delete_end <= @start
    Span.new(@start - length, @end - length, @style)
  elsif position >= @end
    self
  elsif position <= @start && delete_end >= @end
    nil # Span completely deleted
  elsif position <= @start
    Span.new(position, @end - length, @style)
  elsif delete_end >= @end
    Span.new(@start, position, @style)
  else
    Span.new(@start, @end - length, @style)
  end
end

#adjust_insert(position, length) ⇒ Object

Adjust span after insertion at position



37
38
39
40
41
42
43
44
45
# File 'lib/rich/text.rb', line 37

def adjust_insert(position, length)
  if position <= @start
    Span.new(@start + length, @end + length, @style)
  elsif position < @end
    Span.new(@start, @end + length, @style)
  else
    self
  end
end

#inspectObject



66
67
68
# File 'lib/rich/text.rb', line 66

def inspect
  "#<Rich::Span [#{@start}:#{@end}] #{@style}>"
end

#lengthInteger

Returns Length of the span.

Returns:

  • (Integer)

    Length of the span



27
28
29
# File 'lib/rich/text.rb', line 27

def length
  @end - @start
end

#overlaps?(start_pos, end_pos) ⇒ Boolean

Check if span overlaps with a range

Returns:

  • (Boolean)


32
33
34
# File 'lib/rich/text.rb', line 32

def overlaps?(start_pos, end_pos)
  @start < end_pos && @end > start_pos
end