Skip to content

Commit

Permalink
chat demo finished
Browse files Browse the repository at this point in the history
  • Loading branch information
zodman committed Nov 29, 2020
1 parent 493d576 commit 1b46d44
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 6 deletions.
1 change: 1 addition & 0 deletions core/javascript/controllers/chat_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export default class extends ApplicationController {
}

post (event) {
console.log("post");
Rails.stopEverything(event)
lastMessageId = Math.random()
this.stimulate(
Expand Down
19 changes: 17 additions & 2 deletions core/reflexes/chat_reflex.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
from sockpuppet.reflex import Reflex
from sockpuppet.channel import Channel
from django.core.cache import cache
from django.utils import timezone


class ChatReflex(Reflex):
def increment(self, step=1):
self.count = int(self.element.dataset['count']) + step
def post(self, color, message, message_id):
chats = cache.get("chats", [])
chats.append({
'message': message,
'message_id': message_id,
'created_at': timezone.now()
})
cache.set("chats", chats)
channel = Channel("chat")
channel.dispatch_event({
'name': 'chats:added',
'detail': {'messagre_id': message_id}
})
channel.broadcast()
8 changes: 5 additions & 3 deletions core/templates/_chat_demo.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,18 @@
data-action="chats:added@document->chat#reload cable-ready:after-morph@document->chat#scroll">
<span data-target="chat.list">
{% for chat in chats %}
<aside class="message" style="min-height:auto;">
<aside class="message" style="min-height:auto; margin-top: 15px;">
<p>
{{chat.message}}
{{chat.message}} <sup>{{chat.created_at|timesince}} ago </sup>
</p>
</aside>
{% endfor %}
</span>
<form>
<textarea data-target="chat.input" placeholder="Type your message.."></textarea>
<button data-action="click->chat#post" type="submit"> Send </button>

<div>
<small>Message storage on <a href="https://docs.djangoproject.com/en/3.1/topics/cache/#local-memory-caching">LocMemCache</a></small>
</div>
</form>
</article>
3 changes: 2 additions & 1 deletion core/views/chat.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django.views.generic.base import TemplateView
from django.core.cache import cache
from .mixins import MixinBase

class ChatView(MixinBase, TemplateView):
Expand All @@ -13,7 +14,7 @@ class ChatView(MixinBase, TemplateView):

def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['chats'] = [dict(message='message1')]
context['chats'] = cache.get("chats", [])
return context

chat = ChatView.as_view()
Expand Down

0 comments on commit 1b46d44

Please sign in to comment.