rbxl 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,18 +12,28 @@ module Rbxl
12
12
  # * +nil+ — clears the cell's value (children + +t+ attribute removed),
13
13
  # leaving an empty +<c>+ that retains its +s+ (style index)
14
14
  # * +true+ / +false+ — boolean cell (+t="b"+)
15
- # * +Integer+ / +Float+ — number cell (no +t+ attribute)
15
+ # * +Integer+ / +Float+ — number cell (no +t+ attribute); other +Numeric+
16
+ # values are written as +Float+
16
17
  # * +String+ — inline string cell (+t="inlineStr"+); +xl/sharedStrings.xml+
17
18
  # is never mutated, so this round-trips deterministically without a
18
19
  # second pass over the SST
19
- # * +Date+ / +Time+ / +DateTime+ — raises {EditableCellTypeError}; convert
20
- # to a numeric serial yourself if you need a date cell. Date support is
21
- # intentionally deferred so 1.4.0 doesn't ship a half-baked numFmt write
20
+ # * +Date+ / +Time+ / +DateTime+ — Excel serial number (respecting the
21
+ # workbook's 1900/1904 date system). If the cell's current style already
22
+ # has a date/time number format it is kept as-is; otherwise a copy of the
23
+ # current style is derived with the built-in short-date format (+Date+)
24
+ # or date-time format (+Time+ / +DateTime+), so fonts, fills, and borders
25
+ # from the template survive
22
26
  #
23
27
  # When overwriting an existing cell, the +s+ (style index) attribute is
24
28
  # preserved so template formatting (number format, font, fill, alignment)
25
29
  # carries through to the new value. Any +<f>+ (formula) and cached +<v>+
26
30
  # are dropped — assigning a value means the cell is no longer a formula.
31
+ #
32
+ # == Styling
33
+ #
34
+ # {#style} layers changes on top of the cell's current style (only the
35
+ # attributes you pass change); {#style_id=} replaces the style wholesale
36
+ # with an index from {EditableWorkbook#add_style}.
27
37
  class EditableCell
28
38
  # Namespace for the main SpreadsheetML schema.
29
39
  MAIN_NS = "http://schemas.openxmlformats.org/spreadsheetml/2006/main".freeze
@@ -59,19 +69,80 @@ module Rbxl
59
69
  # Sets the cell's value. See the class-level "Type matrix on write"
60
70
  # documentation for accepted Ruby types and how each is serialized.
61
71
  #
62
- # @param new_value [String, Integer, Float, true, false, nil]
72
+ # @param new_value [String, Numeric, true, false, Date, Time, DateTime, nil]
63
73
  # @return [Object] +new_value+
64
- # @raise [Rbxl::EditableCellTypeError] for unsupported types
65
- # (+Date+/+Time+, arbitrary objects)
74
+ # @raise [Rbxl::EditableCellTypeError] for unsupported types, or for
75
+ # dates before the workbook's date epoch
66
76
  def value=(new_value)
67
77
  reject_unsupported_type!(new_value)
78
+ serial = date_serial(new_value) if date_like?(new_value)
68
79
 
69
80
  node = @worksheet.find_or_create_cell_node(@coordinate, create: true)
70
- apply_value(node, new_value)
81
+ @worksheet.note_formula_removed! if node.element_children.any? { |c| c.name == "f" }
82
+
83
+ if serial
84
+ apply_value(node, serial)
85
+ ensure_date_style(node, new_value)
86
+ else
87
+ apply_value(node, new_value)
88
+ end
71
89
  @worksheet.mark_dirty!
72
90
  new_value
73
91
  end
74
92
 
93
+ # @return [Integer] the cell's style index (+s+ attribute); +0+ when the
94
+ # cell has none or does not exist
95
+ def style_id
96
+ node = @worksheet.find_or_create_cell_node(@coordinate, create: false)
97
+ node ? node["s"].to_i : 0
98
+ end
99
+
100
+ # Replaces the cell's style with +id+, typically a value returned by
101
+ # {EditableWorkbook#add_style}. The cell's value is left untouched; the
102
+ # cell is created (empty) if it does not exist yet.
103
+ #
104
+ # @param id [Integer] a +cellXfs+ index valid for this workbook
105
+ # @return [Integer] +id+
106
+ # @raise [ArgumentError] if +id+ is not an existing style index
107
+ def style_id=(id)
108
+ count = @worksheet.styles.xf_count
109
+ unless id.is_a?(Integer) && id >= 0 && id < count
110
+ raise ArgumentError, "style_id must be an Integer in 0...#{count}, got #{id.inspect}"
111
+ end
112
+
113
+ node = @worksheet.find_or_create_cell_node(@coordinate, create: true)
114
+ if id.zero?
115
+ node.delete("s")
116
+ else
117
+ node["s"] = id.to_s
118
+ end
119
+ @worksheet.mark_dirty!
120
+ id
121
+ end
122
+
123
+ # Changes part of the cell's formatting while keeping the rest of its
124
+ # current style (typically the template's). Accepts the same keywords as
125
+ # {EditableWorkbook#add_style}, with merge semantics:
126
+ #
127
+ # * +font:+ — only the given attributes change (e.g. <tt>{ color: "C00000" }</tt>
128
+ # keeps the template's font face and size); +false+ turns +bold+ /
129
+ # +italic+ / +underline+ off
130
+ # * +border:+ — only the given sides change; <tt>{ bottom: nil }</tt>
131
+ # removes the bottom line
132
+ # * +alignment:+ — only the given attributes change
133
+ # * +fill:+, +number_format:+ — replaced
134
+ #
135
+ # Identical changes on cells sharing a style reuse one derived style.
136
+ #
137
+ # sheet["F20"].style(font: { color: "C00000", bold: true })
138
+ #
139
+ # @return [Rbxl::EditableCell] +self+
140
+ def style(font: nil, fill: nil, border: nil, alignment: nil, number_format: nil)
141
+ patch = Style.new(font: font, fill: fill, border: border, alignment: alignment, number_format: number_format)
142
+ self.style_id = @worksheet.styles.patch(style_id, patch)
143
+ self
144
+ end
145
+
75
146
  private
76
147
 
77
148
  WHITESPACE_BYTES = [" ".ord, "\t".ord, "\n".ord, "\r".ord].freeze
@@ -79,20 +150,33 @@ module Rbxl
79
150
 
80
151
  def reject_unsupported_type!(value)
81
152
  case value
82
- when nil, true, false, Integer, Float, String
83
- # supported
84
- when Date, Time, DateTime
85
- raise EditableCellTypeError,
86
- "Date/Time/DateTime are not supported by EditableCell in 1.4.0; " \
87
- "convert to a numeric Excel serial yourself if you need a date cell"
88
- when Numeric
89
- # other Numerics (Rational, BigDecimal) — coerce to Float on apply
153
+ when nil, true, false, Numeric, String, Date, Time
154
+ # supported (DateTime is a Date)
90
155
  else
91
156
  raise EditableCellTypeError,
92
157
  "unsupported cell value type: #{value.class}"
93
158
  end
94
159
  end
95
160
 
161
+ def date_like?(value)
162
+ value.is_a?(Date) || value.is_a?(Time)
163
+ end
164
+
165
+ def date_serial(value)
166
+ DateFormat.to_serial(value, date_1904: @worksheet.date_1904?)
167
+ rescue ArgumentError => e
168
+ raise EditableCellTypeError, "#{@coordinate}: #{e.message}"
169
+ end
170
+
171
+ def ensure_date_style(node, value)
172
+ current = node["s"].to_i
173
+ styles = @worksheet.styles
174
+ return if styles.date_style?(current)
175
+
176
+ fmt = value.is_a?(Time) || value.is_a?(DateTime) ? DateFormat::BUILTIN_DATETIME_ID : DateFormat::BUILTIN_DATE_ID
177
+ node["s"] = styles.patch(current, Style.new, numfmt_id: fmt).to_s
178
+ end
179
+
96
180
  def apply_value(node, value)
97
181
  node.children.unlink
98
182
  node.delete("t")
@@ -102,23 +186,23 @@ module Rbxl
102
186
  # empty cell — preserve <c r="..." s="..."/>
103
187
  when true
104
188
  node["t"] = "b"
105
- node.add_child("<v>1</v>")
189
+ XmlEdit.append(node, "<v>1</v>")
106
190
  when false
107
191
  node["t"] = "b"
108
- node.add_child("<v>0</v>")
192
+ XmlEdit.append(node, "<v>0</v>")
109
193
  when Integer
110
- node.add_child("<v>#{value}</v>")
194
+ XmlEdit.append(node, "<v>#{value}</v>")
111
195
  when Float
112
196
  # Ruby's Float#to_s gives the shortest round-trippable form. Excel
113
197
  # accepts standard decimal and scientific notation as <v> text.
114
- node.add_child("<v>#{value}</v>")
198
+ XmlEdit.append(node, "<v>#{value}</v>")
115
199
  when String
116
200
  node["t"] = "inlineStr"
117
201
  text = CGI.escapeHTML(value)
118
202
  space_attr = preserve_whitespace?(value) ? ' xml:space="preserve"' : ""
119
- node.add_child("<is><t#{space_attr}>#{text}</t></is>")
203
+ XmlEdit.append(node, "<is><t#{space_attr}>#{text}</t></is>")
120
204
  when Numeric
121
- node.add_child("<v>#{value.to_f}</v>")
205
+ XmlEdit.append(node, "<v>#{value.to_f}</v>")
122
206
  end
123
207
  end
124
208
 
@@ -0,0 +1,273 @@
1
+ module Rbxl
2
+ # @api private
3
+ #
4
+ # Append-only view of an existing workbook's +xl/styles.xml+, used by edit
5
+ # mode to register new cell styles without disturbing the template's own.
6
+ #
7
+ # Every operation only <em>appends</em> entries to +numFmts+ / +fonts+ /
8
+ # +fills+ / +borders+ / +cellXfs+ and bumps their +count+ attributes, so the
9
+ # indices that existing cells reference never change. The part is
10
+ # re-serialized only when something was actually appended; otherwise it is
11
+ # copied from the source ZIP byte-for-byte like any other untouched part.
12
+ #
13
+ # Two ways to obtain a new +cellXfs+ index:
14
+ #
15
+ # * {#register} — a style built from scratch, exactly like
16
+ # {WriteOnlyWorkbook#add_style}; unspecified components use entry 0
17
+ # * {#patch} — a copy of an existing xf with only the given components
18
+ # overridden (font attributes merged, border sides merged, alignment
19
+ # attributes merged, fill and number format replaced)
20
+ class EditableStyles
21
+ # Child-element sequence of +<styleSheet>+ (ECMA-376 part 1 §18.8.39).
22
+ STYLESHEET_ORDER = %w[numFmts fonts fills borders cellStyleXfs cellXfs
23
+ cellStyles dxfs tableStyles colors extLst].freeze
24
+
25
+ # Conventional element order inside +<font>+, as written by Excel.
26
+ FONT_ORDER = %w[b i strike condense extend outline shadow u vertAlign
27
+ sz color name family charset scheme].freeze
28
+
29
+ # Child-element sequence of +<border>+.
30
+ BORDER_ORDER = %w[start left end right top bottom diagonal vertical horizontal].freeze
31
+
32
+ # Child-element sequence of +<xf>+.
33
+ XF_ORDER = %w[alignment protection extLst].freeze
34
+
35
+ # Locale-independent built-in number formats a +number_format+ string is
36
+ # mapped to before a custom +<numFmt>+ is allocated. Date formats are
37
+ # deliberately absent: built-in ids 14–22 render per the viewer's locale,
38
+ # so mapping a literal code onto them would change what the user asked for.
39
+ BUILTIN_NUMFMTS = {
40
+ "General" => 0, "0" => 1, "0.00" => 2, "#,##0" => 3, "#,##0.00" => 4,
41
+ "0%" => 9, "0.00%" => 10, "0.00E+00" => 11, "@" => 49
42
+ }.freeze
43
+
44
+ # First id available for custom number formats.
45
+ NUMFMT_CUSTOM_BASE = 164
46
+
47
+ # Minimal stylesheet used when a workbook ships without a styles part.
48
+ MINIMAL_XML = <<~XML.freeze
49
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
50
+ <styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><fonts count="1"><font><sz val="11"/><name val="Calibri"/></font></fonts><fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills><borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs><cellXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/></cellXfs><cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles></styleSheet>
51
+ XML
52
+
53
+ # @return [String] ZIP entry path of the styles part
54
+ attr_reader :part_name
55
+
56
+ # @param xml [String] source +styles.xml+
57
+ # @param part_name [String] ZIP entry path of the styles part
58
+ # @param workbook_path [String] used in error messages
59
+ def initialize(xml, part_name:, workbook_path:)
60
+ @part_name = part_name
61
+ @doc = Nokogiri::XML(xml)
62
+ unless @doc.errors.empty? && @doc.root&.name == "styleSheet"
63
+ detail = @doc.errors.first || "root element is not <styleSheet>"
64
+ raise WorkbookFormatError, "#{workbook_path}: #{part_name}: #{detail}"
65
+ end
66
+
67
+ @root = @doc.root
68
+ @modified = false
69
+ @entry_cache = {}
70
+ @patch_cache = {}
71
+ @font_patch_cache = {}
72
+ @border_patch_cache = {}
73
+ end
74
+
75
+ # @return [Boolean] whether any entry has been appended since load
76
+ def modified?
77
+ @modified
78
+ end
79
+
80
+ # @return [String] the stylesheet XML including appended entries
81
+ def to_xml
82
+ XmlEdit.serialize(@doc)
83
+ end
84
+
85
+ # @return [Integer] number of +cellXfs+ entries (valid style ids are
86
+ # +0...xf_count+)
87
+ def xf_count
88
+ entries("cellXfs", "xf").length
89
+ end
90
+
91
+ # Registers a style from scratch. Like {StyleRegistry#register}, each
92
+ # call appends a new xf (no deduplication at the xf level), while
93
+ # identical fonts / fills / borders appended in this session are shared.
94
+ #
95
+ # @param style [Rbxl::Style]
96
+ # @return [Integer] the new +cellXfs+ index
97
+ def register(style)
98
+ xf = {
99
+ font_id: style.font ? append_shared("fonts", "font", StyleXml.render_font(style.font)) : 0,
100
+ fill_id: style.fill ? append_shared("fills", "fill", StyleXml.render_fill(style.fill)) : 0,
101
+ border_id: style.border ? append_shared("borders", "border", StyleXml.render_border(style.border)) : 0,
102
+ numfmt_id: style.number_format ? numfmt_id_for(style.number_format) : 0,
103
+ alignment: style.alignment
104
+ }
105
+ append_entry("cellXfs", "xf", StyleXml.render_xf(xf))
106
+ end
107
+
108
+ # Derives a new xf from +base_index+ with the components of +style+
109
+ # layered on top. Identical (base, style) pairs return the same index.
110
+ #
111
+ # @param base_index [Integer] existing +cellXfs+ index to start from
112
+ # @param style [Rbxl::Style]
113
+ # @param numfmt_id [Integer, nil] internal override for the number format
114
+ # id (used for date writes), taking precedence over +style.number_format+
115
+ # @return [Integer] the derived +cellXfs+ index
116
+ def patch(base_index, style, numfmt_id: nil)
117
+ key = [base_index, style.font, style.fill, style.border, style.alignment, style.number_format, numfmt_id]
118
+ @patch_cache[key] ||= build_patched_xf(base_index, style, numfmt_id)
119
+ end
120
+
121
+ # @param index [Integer] +cellXfs+ index
122
+ # @return [Boolean] whether that xf renders numbers as a date/time
123
+ def date_style?(index)
124
+ xf = entries("cellXfs", "xf")[index]
125
+ fmt_id = xf ? xf["numFmtId"].to_i : 0
126
+ return true if DateFormat::BUILTIN_IDS.include?(fmt_id)
127
+
128
+ code = entries("numFmts", "numFmt").find { |n| n["numFmtId"].to_i == fmt_id }&.[]("formatCode")
129
+ code ? DateFormat.date_format_code?(code) : false
130
+ end
131
+
132
+ private
133
+
134
+ def build_patched_xf(base_index, style, numfmt_id)
135
+ base = entries("cellXfs", "xf")[base_index]
136
+ source = base ? XmlEdit.serialize(base) : '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>'
137
+
138
+ # Resolve sub-entries first so the xf appended below is the last one.
139
+ font_id = style.font ? patched_font(base&.[]("fontId").to_i, style.font) : nil
140
+ fill_id = style.fill ? append_shared("fills", "fill", StyleXml.render_fill(style.fill)) : nil
141
+ border_id = style.border ? patched_border(base&.[]("borderId").to_i, style.border) : nil
142
+ fmt_id = numfmt_id || (style.number_format && numfmt_id_for(style.number_format))
143
+
144
+ index = append_entry("cellXfs", "xf", source)
145
+ xf = entries("cellXfs", "xf")[index]
146
+
147
+ set_component(xf, "fontId", "applyFont", font_id)
148
+ set_component(xf, "fillId", "applyFill", fill_id)
149
+ set_component(xf, "borderId", "applyBorder", border_id)
150
+ set_component(xf, "numFmtId", "applyNumberFormat", fmt_id)
151
+ merge_alignment(xf, style.alignment) if style.alignment
152
+ index
153
+ end
154
+
155
+ def set_component(xf, id_attr, apply_attr, value)
156
+ return if value.nil?
157
+
158
+ xf[id_attr] = value.to_s
159
+ xf[apply_attr] = "1"
160
+ end
161
+
162
+ def merge_alignment(xf, alignment)
163
+ node = XmlEdit.child(xf, "alignment") ||
164
+ XmlEdit.insert_in_order(xf, "alignment", "<alignment/>", XF_ORDER)
165
+ StyleXml.alignment_attributes(alignment).each { |name, value| node[name] = value }
166
+ node.delete("wrapText") if alignment.key?(:wrap_text) && !alignment[:wrap_text]
167
+ xf["applyAlignment"] = "1"
168
+ end
169
+
170
+ def patched_font(base_id, font)
171
+ @font_patch_cache[[base_id, font]] ||= begin
172
+ base = entries("fonts", "font")[base_id]
173
+ index = append_entry("fonts", "font", base ? XmlEdit.serialize(base) : "<font/>")
174
+ node = entries("fonts", "font")[index]
175
+ apply_font_attributes(node, font)
176
+ index
177
+ end
178
+ end
179
+
180
+ def apply_font_attributes(node, font)
181
+ set_flag(node, "b", font[:bold]) if font.key?(:bold)
182
+ set_flag(node, "i", font[:italic]) if font.key?(:italic)
183
+ if font.key?(:underline)
184
+ u = font[:underline]
185
+ set_valued(node, "u", u.is_a?(String) || u.is_a?(Symbol) ? u.to_s : nil, present: !!u)
186
+ end
187
+ set_valued(node, "sz", font[:size].to_s, present: true) if font[:size]
188
+ if font[:color]
189
+ replace_child(node, "color", %(<color rgb="#{StyleXml.escape_attr(StyleXml.argb(font[:color]))}"/>), FONT_ORDER)
190
+ end
191
+ return unless font[:name]
192
+
193
+ set_valued(node, "name", font[:name].to_s, present: true)
194
+ # A <scheme> (major/minor) makes Excel substitute the theme font and
195
+ # ignore <name>, so an explicit name must drop it.
196
+ XmlEdit.children(node, "scheme").each(&:unlink)
197
+ end
198
+
199
+ def set_flag(node, name, on)
200
+ XmlEdit.children(node, name).each(&:unlink)
201
+ XmlEdit.insert_in_order(node, name, "<#{name}/>", FONT_ORDER) if on
202
+ end
203
+
204
+ def set_valued(node, name, val, present:)
205
+ XmlEdit.children(node, name).each(&:unlink)
206
+ return unless present
207
+
208
+ xml = val ? %(<#{name} val="#{StyleXml.escape_attr(val)}"/>) : "<#{name}/>"
209
+ XmlEdit.insert_in_order(node, name, xml, FONT_ORDER)
210
+ end
211
+
212
+ def replace_child(node, name, xml, order)
213
+ existing = XmlEdit.children(node, name)
214
+ if existing.empty?
215
+ XmlEdit.insert_in_order(node, name, xml, order)
216
+ else
217
+ XmlEdit.insert_before(existing.first, xml)
218
+ existing.each(&:unlink)
219
+ end
220
+ end
221
+
222
+ def patched_border(base_id, border)
223
+ @border_patch_cache[[base_id, border]] ||= begin
224
+ base = entries("borders", "border")[base_id]
225
+ index = append_entry("borders", "border", base ? XmlEdit.serialize(base) : "<border/>")
226
+ node = entries("borders", "border")[index]
227
+ border.each do |side, spec|
228
+ replace_child(node, side.to_s, StyleXml.render_border_side(side, spec), BORDER_ORDER)
229
+ end
230
+ index
231
+ end
232
+ end
233
+
234
+ def numfmt_id_for(code)
235
+ code = code.to_s
236
+ builtin = BUILTIN_NUMFMTS[code]
237
+ return builtin if builtin
238
+
239
+ existing = entries("numFmts", "numFmt").find { |n| n["formatCode"] == code }
240
+ return existing["numFmtId"].to_i if existing
241
+
242
+ used = entries("numFmts", "numFmt").map { |n| n["numFmtId"].to_i }
243
+ id = [used.max || 0, NUMFMT_CUSTOM_BASE - 1].max + 1
244
+ append_entry("numFmts", "numFmt", %(<numFmt numFmtId="#{id}" formatCode="#{StyleXml.escape_attr(code)}"/>))
245
+ id
246
+ end
247
+
248
+ # Appends +xml+ to +container+ unless the identical markup was already
249
+ # appended in this session, in which case the earlier index is reused.
250
+ def append_shared(container, entry, xml)
251
+ @entry_cache[[container, xml]] ||= append_entry(container, entry, xml)
252
+ end
253
+
254
+ def append_entry(container_name, entry_name, xml)
255
+ container = container(container_name)
256
+ index = XmlEdit.children(container, entry_name).length
257
+ XmlEdit.append(container, xml)
258
+ container["count"] = (index + 1).to_s
259
+ @modified = true
260
+ index
261
+ end
262
+
263
+ def container(name)
264
+ XmlEdit.child(@root, name) ||
265
+ XmlEdit.insert_in_order(@root, name, %(<#{name} count="0"/>), STYLESHEET_ORDER)
266
+ end
267
+
268
+ def entries(container_name, entry_name)
269
+ container = XmlEdit.child(@root, container_name)
270
+ container ? XmlEdit.children(container, entry_name) : []
271
+ end
272
+ end
273
+ end