Skip to content

Commit

Permalink
Fix AcroForm Javascript actions to gracefully handle Infinity/NaN
Browse files Browse the repository at this point in the history
  • Loading branch information
gettalong committed Jan 14, 2025
1 parent 1557e60 commit 530fb0e
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
## Unreleased

### Fixed

* AcroForm Javascript actions to gracefully handle the special values infinity
and NaN


## 1.1.1 - 2025-01-08

### Fixed
Expand Down
10 changes: 8 additions & 2 deletions lib/hexapdf/type/acro_form/java_script_actions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,7 @@ def calculate(form, calculate_action)
else
nil
end
result && (result == result.truncate ? result.to_i.to_s : result.to_s)
result && (result.finite? && result == result.truncate ? result.to_i.to_s : result.to_s)
end

AF_SIMPLE_CALCULATE_MAPPING = { #:nodoc:
Expand Down Expand Up @@ -613,7 +613,13 @@ def run_simplified_field_notation(form, action_string)

# Returns the numeric value of the string, interpreting comma as point.
def af_make_number(value)
value.to_s.tr(',', '.').to_f
if value.match?(/(?:[+-])?Inf(?:inity)?/i)
value.start_with?('-') ? -Float::INFINITY : Float::INFINITY
elsif value.match?(/NaN/i)
Float::NAN
else
value.to_s.tr(',', '.').to_f
end
end

# Formats the numeric value according to the format string and separator style.
Expand Down
16 changes: 16 additions & 0 deletions test/hexapdf/type/acro_form/test_java_script_actions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,15 @@ def assert_format(arg_string, result_value, result_color)
assert_equal('1.234,57', value)
end

it "works with the special Infinity and NaN values" do
@value = 'Infinity'
assert_format('2, 2, 0, 0, "", false', "Inf", "black")
@value = '-Infinity'
assert_format('2, 2, 0, 0, "", false', "-Inf", "black")
@value = 'Nan'
assert_format('2, 2, 0, 0, "", false', "NaN", "black")
end

it "does nothing to the value if the JavaScript method could not be determined " do
assert_format('2, 3, 0, 0, " E", false, a', "1234567.898765", nil)
end
Expand Down Expand Up @@ -244,6 +253,13 @@ def assert_calculation(function, fields, value)
assert_calculation('SUM', [@field1, @field2], "30.54")
end

it "works with the special values Infinity and NaN" do
@field1.field_value = "Infinity"
assert_calculation('SUM', [@field1, @field2], "Infinity")
@field1.field_value = "NaN"
assert_calculation('SUM', [@field1, @field2], "NaN")
end

it "returns nil if a field cannot be resolved" do
@action[:JS] = 'AFSimple_Calculate("SUM", ["unknown"]);'
assert_nil(@klass.calculate(@form, @action))
Expand Down

0 comments on commit 530fb0e

Please sign in to comment.