chat.nim 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import
  2. ../server_api/api,
  3. asyncdispatch,
  4. httpclient,
  5. nodesnim,
  6. json
  7. var
  8. thr: Thread[tuple[scene: ptr SceneRef, username: ptr string, timed_chat: ptr seq[JsonNode]]]
  9. gradient = GradientDrawable()
  10. gradient.setCornerColors(Color("#C9D6FF"), Color("#C9D6FF"), Color("#E2E2E2"), Color("#E2E2E2"))
  11. Input.addKeyAction("send", 13) # Enter
  12. build:
  13. - Scene (chat_scene):
  14. call rename("Chat")
  15. - Control background:
  16. call rename("background")
  17. call setBackground(gradient)
  18. call setSizeAnchor(1, 1)
  19. - Label chat:
  20. call rename("chat")
  21. call setSizeAnchor(1, 1)
  22. - EditText message:
  23. call setSizeAnchor(0.95, 0.15)
  24. call setAnchor(0.5, 1, 0.5, 1.2)
  25. call setStyle(style({
  26. border-radius: 8,
  27. border-detail: 8,
  28. background-color: rgba(50, 60, 70, 0.5)
  29. }))
  30. proc listenChat(arg: tuple[scene: ptr SceneRef, username: ptr string, timed_chat: ptr seq[JsonNode]]) {.thread.} =
  31. var client = newAsyncHttpClient()
  32. while true:
  33. var
  34. response = waitFor client.get("http://127.0.0.1:5000/getchat")
  35. text = stext""
  36. arg.timed_chat[] = parseJson(waitFor response.body())["data"].getElems
  37. var i = 0
  38. while i < arg.timed_chat[].len:
  39. text &= (stext arg.timed_chat[][i].str & stext": " & stext arg.timed_chat[][i+1].str & stext("\n\n"))
  40. inc i, 2
  41. text.setColor(Color("#123"))
  42. arg.scene[].getNode("background/chat").LabelRef.text = text
  43. waitFor sleepAsync(100)
  44. background@onEnter(self):
  45. createThread(thr, listenChat, (chat_scene.addr, username.addr, timed_chat.addr))
  46. background@onInput(self, event):
  47. if Input.isActionJustPressed("send"):
  48. if message.getText().len > 0:
  49. sendMessage(message.getText())
  50. message.setText("")