Class: Textbringer::GhostText::WebSocketServer

Inherits:
Object
  • Object
show all
Defined in:
lib/textbringer/ghost_text/web_socket_server.rb

Instance Method Summary collapse

Instance Method Details

#call(env) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
# File 'lib/textbringer/ghost_text/web_socket_server.rb', line 13

def call(env)
  if Faye::WebSocket.websocket?(env)
    ws = Faye::WebSocket.new(env)

    next_tick do
      buffer = Buffer.new_buffer("*GhostText*")
      switch_to_buffer(buffer)

      remote_text = nil

      buffer.on_modified do
        text = buffer.to_s
        if text != remote_text
          pos = buffer.substring(0, buffer.point).size
          data = {
            "text" => text,
            "selections" => [{ "start" => pos, "end" => pos }]
          }
          ws.send(data.to_json)
          remote_text = text
        end
      end

      ws.on :message do |event|
        data = JSON.parse(event.data)
        next_tick do
          buffer.composite_edit do
            remote_text = data["text"]
            buffer.delete_region(buffer.point_min, buffer.point_max)
            buffer.insert(remote_text)
            pos = data["selections"]&.dig(0, "start")
            if pos
              byte_pos = remote_text[0, pos].bytesize
              buffer.goto_char(byte_pos)
            end
          end
        end
      end

      ws.on :close do |event|
        next_tick do
          kill_buffer(buffer, force: true)
        end
        ws = nil
      end
    end
    ws.rack_response
  else
    json = {
      "WebSocketPort" => 4001,
      "ProtocolVersion" => 1
    }.to_json
    [200, {'Content-Type' => 'application/json'}, [json]]
  end
end