lattice-grid 0.1.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.
Files changed (52) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +21 -0
  3. data/README.md +179 -0
  4. data/lib/lattice/grid/aggregate_sql.rb +98 -0
  5. data/lib/lattice/grid/cells.rb +85 -0
  6. data/lib/lattice/grid/collab/axis.rb +40 -0
  7. data/lib/lattice/grid/collab/channel.rb +31 -0
  8. data/lib/lattice/grid/collab/channel_handler.rb +84 -0
  9. data/lib/lattice/grid/collab/connection.rb +72 -0
  10. data/lib/lattice/grid/collab/doc_model.rb +99 -0
  11. data/lib/lattice/grid/collab/doc_model_apply.rb +105 -0
  12. data/lib/lattice/grid/collab/doc_model_doc.rb +95 -0
  13. data/lib/lattice/grid/collab/doc_model_normalize.rb +120 -0
  14. data/lib/lattice/grid/collab/doc_server.rb +84 -0
  15. data/lib/lattice/grid/collab/doc_server_messages.rb +129 -0
  16. data/lib/lattice/grid/collab/iron_calc.rb +84 -0
  17. data/lib/lattice/grid/collab/iron_calc_ops.rb +118 -0
  18. data/lib/lattice/grid/collab/iron_calc_sheets.rb +69 -0
  19. data/lib/lattice/grid/collab/memory_store.rb +63 -0
  20. data/lib/lattice/grid/collab/refs.rb +131 -0
  21. data/lib/lattice/grid/collab/refs_shrink.rb +56 -0
  22. data/lib/lattice/grid/collab/wasm_book.rb +97 -0
  23. data/lib/lattice/grid/collab/wire.rb +135 -0
  24. data/lib/lattice/grid/collab/wire_model_ops.rb +33 -0
  25. data/lib/lattice/grid/collab/wire_ops.rb +120 -0
  26. data/lib/lattice/grid/collab/wire_style.rb +60 -0
  27. data/lib/lattice/grid/collab.rb +44 -0
  28. data/lib/lattice/grid/context.rb +82 -0
  29. data/lib/lattice/grid/dates.rb +76 -0
  30. data/lib/lattice/grid/filter_sql.rb +87 -0
  31. data/lib/lattice/grid/json.rb +60 -0
  32. data/lib/lattice/grid/keyset.rb +49 -0
  33. data/lib/lattice/grid/kind.rb +58 -0
  34. data/lib/lattice/grid/levels.rb +121 -0
  35. data/lib/lattice/grid/limits.rb +51 -0
  36. data/lib/lattice/grid/pager.rb +118 -0
  37. data/lib/lattice/grid/parser/filter_rules.rb +119 -0
  38. data/lib/lattice/grid/parser/group_rules.rb +105 -0
  39. data/lib/lattice/grid/parser/request_rules.rb +131 -0
  40. data/lib/lattice/grid/parser/tree_rules.rb +68 -0
  41. data/lib/lattice/grid/parser.rb +126 -0
  42. data/lib/lattice/grid/pivot_sql.rb +78 -0
  43. data/lib/lattice/grid/query.rb +76 -0
  44. data/lib/lattice/grid/request.rb +19 -0
  45. data/lib/lattice/grid/respond.rb +60 -0
  46. data/lib/lattice/grid/sql.rb +103 -0
  47. data/lib/lattice/grid/tree_sql.rb +59 -0
  48. data/lib/lattice/grid/values.rb +124 -0
  49. data/lib/lattice/grid/version.rb +7 -0
  50. data/lib/lattice/grid.rb +29 -0
  51. data/wasm/ironcalc_wasi.wasm +0 -0
  52. metadata +110 -0
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ module Collab
6
+ # The formula engine of the server: IronCalc in the WASI module (ADR 0007, ADR 0020). A port
7
+ # of packages/formula-ironcalc/src/engine.ts. The workbook stays loaded: `apply` turns the
8
+ # ops of one submit into one `ic_apply_batch` call, and the module gives the cells that
9
+ # changed. The op handlers are in iron_calc_ops.rb and iron_calc_sheets.rb.
10
+ class IronCalc
11
+ def initialize
12
+ @values = {}
13
+ end
14
+
15
+ # Loads a sheet doc: `{ "sheets" => [{ id, name, rows, cols, cells }], "names" => [...] }`.
16
+ def load(doc)
17
+ @book ? @book.reset : @book = WasmBook.new
18
+ @sheets = []
19
+ @ranges = {}
20
+ @values = {}
21
+ @ctx = nil
22
+ @batch = []
23
+ load_ops(doc)
24
+ run
25
+ nil
26
+ end
27
+
28
+ # The current value of each cell with content, as changes.
29
+ def values = @values.map { |key, value| change(*key, value) }
30
+
31
+ # Applies the ops of one submit in place and gives the computed values that changed.
32
+ # After an EngineError, call `load` again: the ops before the bad op stay applied.
33
+ def apply(ops)
34
+ @batch = []
35
+ ops.each { |operation| add_op(operation) }
36
+ run
37
+ end
38
+
39
+ private
40
+
41
+ def run
42
+ JSON.parse(@book.apply_batch(JSON.generate(@batch))).filter_map do |sheet, row, col, typed|
43
+ key = key_of(sheet, row, col)
44
+ value = read(typed)
45
+ changed = changed?(key, value)
46
+ value.nil? ? @values.delete(key) : @values[key] = value
47
+ change(*key, value) if changed
48
+ end
49
+ end
50
+
51
+ def key_of(sheet, row, col)
52
+ s = @sheets[sheet]
53
+ [s["id"], s["rows"][row - 1], s["cols"][col - 1]]
54
+ end
55
+
56
+ def change(sheet, row, col, value) = { "sheet" => sheet, "row" => row, "col" => col, "value" => value }
57
+
58
+ def changed?(key, value)
59
+ return !value.nil? unless @values.key?(key)
60
+
61
+ prev = @values[key]
62
+ prev.is_a?(Hash) && value.is_a?(Hash) ? prev["error"] != value["error"] : prev != value
63
+ end
64
+
65
+ def read(typed)
66
+ case typed[0, 2]
67
+ when "n:" then number([typed[2..].to_i(16)].pack("Q>").unpack1("G"))
68
+ when "b:" then typed == "b:true"
69
+ when "s:" then typed[2..]
70
+ when "e:" then { "error" => typed[2..] }
71
+ end
72
+ end
73
+
74
+ # 15 significant digits, as the TypeScript engine reads them through a number format.
75
+ def number(raw)
76
+ return raw unless raw.finite?
77
+
78
+ n = Float(format("%.14e", raw))
79
+ n == n.round && n.abs < 1e15 ? n.round : n
80
+ end
81
+ end
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,118 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ module Collab
6
+ # The cell, row and column op handlers of `IronCalc`: `#apply` in engine.ts. Each handler
7
+ # adds the module ops to `@batch` and moves the engine's own row and column IDs, so that each
8
+ # op finds its cells at the positions that the ops before it in the batch made.
9
+ class IronCalc
10
+ HANDLERS = {
11
+ "setCell" => :op_set_cell, "insertRows" => :op_insert, "insertCols" => :op_insert,
12
+ "deleteRows" => :op_delete, "deleteCols" => :op_delete, "setName" => :op_set_name,
13
+ "addSheet" => :op_add_sheet, "removeSheet" => :op_remove_sheet, "renameSheet" => :op_rename_sheet
14
+ }.freeze
15
+
16
+ private
17
+
18
+ # Formats, styles and merges are Lattice state. They do not change a computed value.
19
+ def add_op(operation)
20
+ handler = HANDLERS[operation["type"]]
21
+ send(handler, operation) if handler
22
+ end
23
+
24
+ def op_set_cell(operation) = set_cell(operation.values_at("sheet", "row", "col"), operation)
25
+
26
+ def op_insert(operation)
27
+ sheet = sheet_of(operation["sheet"])
28
+ ids = sheet[axis_of(operation)]
29
+ at = operation["before"] ? ids.index(operation["before"]) : ids.length
30
+ raise EngineError, "no row or column #{operation['before']}" unless at
31
+
32
+ axis_op(operation, sheet, at, operation["ids"].length)
33
+ ids.insert(at, *operation["ids"])
34
+ @ctx = nil
35
+ end
36
+
37
+ def op_delete(operation)
38
+ axis = axis_of(operation)
39
+ sheet = sheet_of(operation["sheet"])
40
+ gone = operation["ids"].to_set
41
+ shrunk = shrink(sheet["id"], axis, gone)
42
+ delete_ids(operation, sheet, axis, gone)
43
+ shrunk.each { |key, formula| set_cell(key, { "formula" => formula }) }
44
+ end
45
+
46
+ def delete_ids(operation, sheet, axis, gone)
47
+ positions = sheet[axis].each_with_index.filter_map { |id, i| i if gone.include?(id) }
48
+ runs(positions).each { |start, count| axis_op(operation, sheet, start, count) }
49
+ sheet[axis] = sheet[axis].reject { |id| gone.include?(id) }
50
+ forget_ids(sheet["id"], axis == "rows" ? 1 : 2, gone)
51
+ end
52
+
53
+ def forget_ids(sheet_id, on_axis, gone) = forget { |key| key[0] == sheet_id && gone.include?(key[on_axis]) }
54
+
55
+ def axis_of(operation) = operation["type"].end_with?("Rows") ? "rows" : "cols"
56
+
57
+ # `at` is 0-based here; the module takes 1-based rows and columns.
58
+ def axis_op(operation, sheet, at, count)
59
+ @batch << { "op" => operation["type"], "sheet" => @sheets.index(sheet), "at" => at + 1, "count" => count }
60
+ end
61
+
62
+ # Sets the value or the formula of `cell` (a doc cell or a setCell op) at `key`.
63
+ def set_cell(key, cell)
64
+ formula = cell["formula"]
65
+ formula && Refs.range?(formula) ? @ranges[key] = formula : @ranges.delete(key)
66
+ input = formula ? Refs.to_a1(formula, key[0], ctx) : input(cell["value"])
67
+ sheet, row, col = position(key)
68
+ @batch << { "op" => "set", "sheet" => sheet, "row" => row, "col" => col, "input" => input }
69
+ end
70
+
71
+ def position(key)
72
+ row = ctx.dig(key[0], :rows, :index, key[1])
73
+ col = ctx.dig(key[0], :cols, :index, key[2])
74
+ raise EngineError, "no cell at #{key.inspect}" unless row && col
75
+
76
+ [@sheets.index { |s| s["id"] == key[0] }, row + 1, col + 1]
77
+ end
78
+
79
+ # IronCalc 0.9.1 turns a range end that a delete removes into #REF!; Excel moves the end
80
+ # inward. Gives the range formulas to set again after the delete (`#shrink` in engine.ts).
81
+ def shrink(sheet_id, axis, gone)
82
+ deletion = { "sheet" => sheet_id, axis => gone.to_a }
83
+ @ranges.filter_map do |key, formula|
84
+ next if skip_shrink?(key, formula, sheet_id, axis, gone)
85
+
86
+ after = Refs.shrink_deleted(formula, key[0], ctx, deletion)
87
+ [key, after] if after != formula || lost?(after, key[0], sheet_id, gone)
88
+ end
89
+ end
90
+
91
+ # True when the delete removes the cell, or when its formula names no deleted ID (then the
92
+ # formula does not change, and the scan is not necessary).
93
+ def skip_shrink?(key, formula, sheet_id, axis, gone)
94
+ (key[0] == sheet_id && gone.include?(axis == "rows" ? key[1] : key[2])) ||
95
+ gone.none? { |id| formula.include?(id) }
96
+ end
97
+
98
+ def lost?(formula, sheet, deleted_sheet, gone)
99
+ Refs.scan(formula).any? do |kind, _, ref|
100
+ kind == :ref && (ref[:sheet] || sheet) == deleted_sheet &&
101
+ [ref[:start], ref[:end]].compact.any? { |p| gone.include?(p[:row]) || gone.include?(p[:col]) }
102
+ end
103
+ end
104
+
105
+ def forget(&gone)
106
+ [@values, @ranges].each { |grid| grid.delete_if { |key, _| gone.call(key) } }
107
+ @ctx = nil
108
+ end
109
+
110
+ # Groups positions into runs of `[start, count]`, from the last run to the first, so the
111
+ # earlier positions stay correct while the module deletes.
112
+ def runs(positions)
113
+ positions.sort.reverse.slice_when { |a, b| a - 1 != b }.map { |run| [run.last, run.length] }
114
+ end
115
+ end
116
+ end
117
+ end
118
+ end
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ module Collab
6
+ # The sheet and name op handlers of `IronCalc`, and the input text of a value.
7
+ class IronCalc
8
+ private
9
+
10
+ def load_ops(doc)
11
+ doc["sheets"].each_with_index { |sheet, i| add_sheet(sheet, i) }
12
+ (doc["names"] || []).each { |name| op_set_name(name) }
13
+ doc["sheets"].each { |sheet| load_cells(sheet) }
14
+ end
15
+
16
+ def load_cells(sheet) = sheet["cells"].each { |c| set_cell([sheet["id"], c["row"], c["col"]], c) }
17
+
18
+ def op_set_name(operation) = @batch << name_op(operation["name"], operation["ref"])
19
+
20
+ def op_add_sheet(operation) = add_sheet(operation, @sheets.length)
21
+
22
+ def op_remove_sheet(operation)
23
+ @batch << { "op" => "removeSheet", "sheet" => @sheets.index(sheet_of(operation["id"])) }
24
+ @sheets.reject! { |s| s["id"] == operation["id"] }
25
+ forget { |key| key[0] == operation["id"] }
26
+ end
27
+
28
+ def op_rename_sheet(operation)
29
+ sheet = sheet_of(operation["id"])
30
+ @batch << { "op" => "renameSheet", "sheet" => @sheets.index(sheet), "name" => operation["name"] }
31
+ sheet["name"] = operation["name"]
32
+ @ctx = nil
33
+ end
34
+
35
+ # `sheet` has the keys id, name, rows and cols. The module starts with one sheet, so the
36
+ # first sheet of a doc is a rename.
37
+ def add_sheet(sheet, index)
38
+ op = index.zero? ? { "op" => "renameSheet", "sheet" => 0 } : { "op" => "addSheet" }
39
+ @batch << op.merge("name" => sheet["name"])
40
+ @sheets << sheet.slice("id", "name").merge("rows" => sheet["rows"].dup, "cols" => sheet["cols"].dup)
41
+ @ctx = nil
42
+ end
43
+
44
+ def name_op(name, ref)
45
+ formula = ref && Refs.to_a1(ref, @sheets.first&.fetch("id"), ctx)
46
+ { "op" => "setName", "name" => name, "formula" => formula }
47
+ end
48
+
49
+ def sheet_of(id) = @sheets.find { |s| s["id"] == id } || raise(EngineError, "no sheet #{id}")
50
+
51
+ def ctx = @ctx ||= Refs.context(@sheets)
52
+
53
+ def input(value)
54
+ case value
55
+ when nil then ""
56
+ when true then "TRUE"
57
+ when false then "FALSE"
58
+ when Numeric then number_input(value)
59
+ when String then value.empty? ? "" : "'#{value}"
60
+ else value["error"]
61
+ end
62
+ end
63
+
64
+ # As JavaScript `String(n)`: no ".0" on a whole number.
65
+ def number_input(value) = value == value.to_i && value.abs < 1e21 ? value.to_i.to_s : value.to_s
66
+ end
67
+ end
68
+ end
69
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ module Collab
6
+ # A store in memory, for tests and for one process. A port of `createMemoryStore` in
7
+ # packages/server/src/collab/store.ts.
8
+ #
9
+ # The store interface (implement these four methods for a database store):
10
+ #
11
+ # - `append(doc_id, entry)`: adds one log entry,
12
+ # `{ "seq", "clientId", "opId", "ops", "changes" }`.
13
+ # - `entries(doc_id, after_seq, up_to_seq = nil)`: the entries with
14
+ # `after_seq < seq <= up_to_seq`, in order.
15
+ # - `save_snapshot(doc_id, snapshot)`: keeps `{ "seq", "doc", "axes" }`.
16
+ # - `snapshot(doc_id, at_or_before = nil)`: the last snapshot with `seq <= at_or_before`
17
+ # (default: the last one), or nil. A doc exists when it has a snapshot.
18
+ #
19
+ # The server calls the store for one doc one call at a time. It can call it for two docs at
20
+ # the same time from two threads.
21
+ class MemoryStore
22
+ def initialize
23
+ @logs = Hash.new { |h, k| h[k] = [] }
24
+ @snapshots = Hash.new { |h, k| h[k] = [] }
25
+ @lock = Mutex.new
26
+ end
27
+
28
+ def append(doc_id, entry)
29
+ @lock.synchronize { @logs[doc_id] << copy(entry) }
30
+ nil
31
+ end
32
+
33
+ def entries(doc_id, after_seq, up_to_seq = nil)
34
+ @lock.synchronize do
35
+ copy(@logs.fetch(doc_id, []).select do |e|
36
+ e["seq"] > after_seq && (up_to_seq.nil? || e["seq"] <= up_to_seq)
37
+ end)
38
+ end
39
+ end
40
+
41
+ def save_snapshot(doc_id, snapshot)
42
+ @lock.synchronize do
43
+ list = @snapshots[doc_id]
44
+ list << copy(snapshot)
45
+ list.sort_by! { |s| s["seq"] }
46
+ end
47
+ nil
48
+ end
49
+
50
+ def snapshot(doc_id, at_or_before = nil)
51
+ @lock.synchronize do
52
+ found = @snapshots.fetch(doc_id, []).select { |s| at_or_before.nil? || s["seq"] <= at_or_before }.last
53
+ found && copy(found)
54
+ end
55
+ end
56
+
57
+ private
58
+
59
+ def copy(value) = Marshal.load(Marshal.dump(value))
60
+ end
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,131 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ module Collab
6
+ # A port of the parts of packages/formula/src/refs.ts, a1.ts and scan.ts that the server
7
+ # uses. A stored formula names rows and columns by ID: `{{c1,r1}}`, `{{s2!c1,r1:c3,r9}}`.
8
+ module Refs
9
+ ID = "[A-Za-z0-9_.-]"
10
+ PART = "(\\$?)(#{ID}*),(\\$?)(#{ID}*)".freeze
11
+ STORED = /\G\{\{(?:(#{ID}+)!)?#{PART}(?::#{PART})?\}\}/
12
+ WORD = /[A-Za-z0-9_.$]/
13
+ REF_ERROR = "#REF!"
14
+
15
+ # The axes of the sheets: `{ id => { name:, rows: {ids:, index:}, cols: {ids:, index:} } }`.
16
+ def self.context(sheets)
17
+ axis = ->(ids) { { ids: ids, index: ids.each_with_index.to_h } }
18
+ sheets.to_h { |s| [s["id"], { name: s["name"], rows: axis.call(s["rows"]), cols: axis.call(s["cols"]) }] }
19
+ end
20
+
21
+ # Splits a stored formula into text and ref tokens that join back to the input. A ref is
22
+ # found only at a token start and never in a string literal.
23
+ def self.scan(formula)
24
+ tokens = []
25
+ pos = 0
26
+ while pos < formula.length
27
+ tokens << token_at(formula, pos)
28
+ pos += tokens.last[1].length
29
+ end
30
+ join_text(tokens)
31
+ end
32
+
33
+ def self.join_text(tokens)
34
+ tokens.chunk_while { |a, b| a[0] == :text && b[0] == :text }
35
+ .map { |run| run[0][0] == :ref ? run[0] : [:text, run.sum("") { |t| t[1] }] }
36
+ end
37
+
38
+ def self.token_at(formula, pos)
39
+ match = ref_at(formula, pos)
40
+ return [:ref, match[0], read(match)] if match
41
+
42
+ [:text, formula[pos...(formula[pos] == '"' ? string_end(formula, pos) : word_end(formula, pos))]]
43
+ end
44
+
45
+ def self.string_end(formula, pos)
46
+ j = pos + 1
47
+ j += formula[j] == '"' ? 2 : 1 while j < formula.length && !(formula[j] == '"' && formula[j + 1] != '"')
48
+ j + 1
49
+ end
50
+
51
+ # Skips the rest of a name, so that `ABCD1` or `Tax2` is never read in part.
52
+ def self.word_end(formula, pos)
53
+ j = pos + 1
54
+ j += 1 while WORD.match?(formula[pos]) && j < formula.length && WORD.match?(formula[j])
55
+ j
56
+ end
57
+
58
+ def self.ref_at(formula, pos)
59
+ prev = pos.zero? ? "" : formula[pos - 1]
60
+ return if WORD.match?(prev) || ["'", "]", "}"].include?(prev)
61
+
62
+ STORED.match(formula, pos)
63
+ end
64
+
65
+ def self.read(match)
66
+ part = lambda { |k|
67
+ { col_abs: match[k] == "$", col: presence(match[k + 1]), row_abs: match[k + 2] == "$",
68
+ row: presence(match[k + 3]) }
69
+ }
70
+ { sheet: match[1], start: part.call(2), end: match[6] && part.call(6) }
71
+ end
72
+
73
+ def self.presence(text) = text.nil? || text.empty? ? nil : text
74
+
75
+ def self.print_stored(ref)
76
+ part = ->(p) { "#{'$' if p[:col_abs] && p[:col]}#{p[:col]},#{'$' if p[:row_abs] && p[:row]}#{p[:row]}" }
77
+ "{{#{"#{ref[:sheet]}!" if ref[:sheet]}#{part.call(ref[:start])}#{":#{part.call(ref[:end])}" if ref[:end]}}}"
78
+ end
79
+
80
+ def self.range?(formula)
81
+ scan(formula).any? { |kind, _, ref| kind == :ref && ref[:end] }
82
+ end
83
+
84
+ # Converts a stored formula on sheet `sheet_id` to A1 text. A lost ref prints as `#REF!`.
85
+ def self.to_a1(formula, sheet_id, ctx)
86
+ scan(formula).map do |kind, text, ref|
87
+ next text if kind == :text
88
+
89
+ resolve(ref, sheet_id, ctx) || REF_ERROR
90
+ end.join
91
+ end
92
+
93
+ def self.resolve(ref, sheet_id, ctx)
94
+ sheet = ctx[ref[:sheet] || sheet_id] or return
95
+ parts = [ref[:start], ref[:end]].compact.map { |part| a1_part(part, sheet) }
96
+ return if parts.include?(nil)
97
+
98
+ "#{"#{quote_sheet(sheet[:name])}!" if ref[:sheet]}#{parts.join(':')}"
99
+ end
100
+
101
+ # One end of a ref in A1 form, or nil when its row or column is gone.
102
+ def self.a1_part(part, sheet)
103
+ row = index_of(sheet[:rows], part[:row])
104
+ col = index_of(sheet[:cols], part[:col])
105
+ return if row == :lost || col == :lost
106
+
107
+ "#{label(part[:col_abs], col && column_label(col))}#{label(part[:row_abs], row && (row + 1))}"
108
+ end
109
+
110
+ def self.index_of(axis, id) = id.nil? ? nil : axis[:index].fetch(id, :lost)
111
+
112
+ def self.label(abs, text) = text.nil? ? "" : "#{'$' if abs}#{text}"
113
+
114
+ def self.column_label(index)
115
+ label = +""
116
+ n = index + 1
117
+ while n.positive?
118
+ label.prepend((65 + ((n - 1) % 26)).chr)
119
+ n = (n - 1) / 26
120
+ end
121
+ label
122
+ end
123
+
124
+ def self.quote_sheet(name)
125
+ plain = /\A[A-Za-z_][A-Za-z0-9_.]*\z/.match?(name) && !/\A[A-Za-z]{1,3}\d+\z|\AR\d*C\d*\z/i.match?(name)
126
+ plain ? name : "'#{name.gsub("'", "''")}'"
127
+ end
128
+ end
129
+ end
130
+ end
131
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ module Collab
6
+ # `shrinkDeleted` in packages/formula/src/refs.ts.
7
+ module Refs
8
+ # Moves each range end that a delete removes to the nearest row or column that stays in
9
+ # the range, as Excel does. Give the context from before the delete. A single-cell ref and
10
+ # a range that loses all its rows stay as they are.
11
+ def self.shrink_deleted(formula, sheet_id, ctx, deletion)
12
+ scan(formula).map do |kind, text, ref|
13
+ next text if kind == :text || (ref[:sheet] || sheet_id) != deletion["sheet"] || !ref[:end]
14
+
15
+ shrink_ref(ref, ctx[deletion["sheet"]], deletion)
16
+ end.join
17
+ end
18
+
19
+ def self.shrink_ref(ref, sheet, deletion)
20
+ out = { sheet: ref[:sheet], start: ref[:start].dup, end: ref[:end].dup }
21
+ { row: "rows", col: "cols" }.each do |key, axis_key|
22
+ ids = deletion[axis_key]
23
+ next if ids.nil? || ids.empty? || sheet.nil?
24
+
25
+ shrink_axis(out, key, sheet[key == :row ? :rows : :cols], ids.to_set)
26
+ end
27
+ print_stored(out)
28
+ end
29
+
30
+ def self.shrink_axis(out, key, axis, gone)
31
+ span = span_of(out, key, axis) or return
32
+ move_end(out[:start], key, pick(axis[:ids], span.each, gone), gone)
33
+ move_end(out[:end], key, pick(axis[:ids], span.reverse_each, gone), gone)
34
+ end
35
+
36
+ # The positions from the start to the end of a ref on one axis (-1 for an unknown ID).
37
+ def self.span_of(out, key, axis)
38
+ ends = [out[:start][key], out[:end][key]]
39
+ Range.new(*ends.map { |id| axis[:index].fetch(id, -1) }) unless ends.include?(nil)
40
+ end
41
+
42
+ def self.move_end(part, key, live, gone)
43
+ part[key] = live if live && gone.include?(part[key])
44
+ end
45
+
46
+ def self.pick(ids, positions, gone)
47
+ positions.each do |i|
48
+ id = i.negative? ? nil : ids[i]
49
+ return id if id && !gone.include?(id)
50
+ end
51
+ nil
52
+ end
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,97 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lattice
4
+ module Grid
5
+ module Collab
6
+ # The IronCalc engine refused an op, a formula or a name.
7
+ class EngineError < StandardError; end
8
+
9
+ # One IronCalc workbook in its own wasmtime instance of the WASI module in
10
+ # wasm/ironcalc-wasi (ADR 0007, ADR 0020). The workbook stays in the instance between calls.
11
+ class WasmBook
12
+ # The module. Set LATTICE_IRONCALC_WASM, or `WasmBook.path =`, to use another file. The gem
13
+ # build puts the file that CI builds at this path.
14
+ DEFAULT_PATH = File.expand_path("../../../../wasm/ironcalc_wasi.wasm", __dir__)
15
+ LOCK = Mutex.new
16
+
17
+ class << self
18
+ attr_writer :path
19
+
20
+ def path = @path || ENV.fetch("LATTICE_IRONCALC_WASM", DEFAULT_PATH)
21
+
22
+ # The compiled module, once for each process: a compile takes 0.7 s to 12 s.
23
+ def compiled
24
+ LOCK.synchronize do
25
+ require "wasmtime"
26
+ @engine ||= Wasmtime::Engine.new
27
+ @compiled ||= Wasmtime::Module.from_file(@engine, path)
28
+ [@engine, @compiled]
29
+ end
30
+ end
31
+ end
32
+
33
+ def initialize
34
+ engine, mod = self.class.compiled
35
+ linker = Wasmtime::Linker.new(engine)
36
+ Wasmtime::WASI::P1.add_to_linker_sync(linker)
37
+ @store = Wasmtime::Store.new(engine, wasi_p1_config: Wasmtime::WasiConfig.new)
38
+ @instance = linker.instantiate(@store, mod)
39
+ @memory = @instance.export("memory").to_memory
40
+ @handle = open
41
+ end
42
+
43
+ # Frees the workbook and starts a new, empty one in the same instance.
44
+ def reset
45
+ close
46
+ @handle = open
47
+ end
48
+
49
+ def close
50
+ call("ic_close", @handle) if @handle
51
+ @handle = nil
52
+ end
53
+
54
+ # Applies a JSON batch of module ops and gives the changed cells as JSON (see book.rs).
55
+ def apply_batch(json)
56
+ packed = with_str(json) { |p, n| call("ic_apply_batch", @handle, p, n) }
57
+ raise EngineError, last_error if packed.zero?
58
+
59
+ take_str(packed)
60
+ end
61
+
62
+ private
63
+
64
+ def open
65
+ handle = call("ic_new")
66
+ raise EngineError, last_error if handle.negative?
67
+
68
+ handle
69
+ end
70
+
71
+ def call(name, *) = @instance.export(name).to_func.call(*)
72
+
73
+ def last_error = take_str(call("ic_last_error"))
74
+
75
+ def with_str(text)
76
+ bytes = text.encode("UTF-8").b
77
+ ptr = call("ic_alloc", bytes.bytesize)
78
+ @memory.write(ptr, bytes)
79
+ yield ptr, bytes.bytesize
80
+ ensure
81
+ call("ic_free", ptr, bytes.bytesize) if ptr
82
+ end
83
+
84
+ def take_str(packed)
85
+ packed &= 0xFFFF_FFFF_FFFF_FFFF
86
+ return "" if packed.zero?
87
+
88
+ ptr = packed >> 32
89
+ len = packed & 0xFFFF_FFFF
90
+ text = @memory.read(ptr, len).force_encoding("UTF-8")
91
+ call("ic_free", ptr, len)
92
+ text
93
+ end
94
+ end
95
+ end
96
+ end
97
+ end