Method: Collab::Models::Document#apply_commit

Defined in:
lib/collab/models/document.rb

#apply_commit(data) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/collab/models/document.rb', line 31

def apply_commit(data)
  base_version = data["v"]&.to_i
  steps = data["steps"]

  return false unless base_version
  return false unless steps.is_a?(Array) && !steps.empty?

  self.with_lock do
    return false unless self.possibly_saved_version? base_version

    self.document_version += 1

    original_positions = self.tracked_positions.current.distinct.pluck(:pos, :assoc).map { |(pos, assoc)| {pos: pos, assoc: assoc} }
    
    result = ::Collab::JS.apply_commit content,
                                      {steps: steps},
                                       map_steps_through: self.commits.where("document_version > ?", base_version).steps,
                                       pos: original_positions,
                                       schema_name: schema_name

    self.content = result["doc"]

    commits.create!({
      steps: result["steps"],
      ref: data["ref"],
      document_version: self.document_version
    })

    self.save!

    original_positions.lazy.zip(result["pos"]) do |original, res|
      if res["deleted"]
        tracked_positions.current.where(original).update_all deleted_at_version: self.document_version
      elsif original[:pos] != res["pos"]
        tracked_positions.current.where(original).update_all pos: res["pos"]
      end
    end
  end

end