Real-time Chat Example

Built with Now.js Framework

Example Implementation

// Define Chat Component
Now.component('chat-app', {
  // Component state
  state: {
    messages: [],
    users: [],
    currentUser: null,
    isConnected: false,
    newMessage: ''
  },

  // Lifecycle hook when component is created
  created() {
    // Initialize WebSocket connection
    this.initWebSocket();

    // Load message history
    this.loadHistory();
  },

  // Component methods
  methods: {
    // Initialize WebSocket
    initWebSocket() {
      const ws = new WebSocket('wss://example.com/chat');

      ws.onopen = () => {
        this.state.isConnected = true;
        this.notify('Connected to chat server');
      };

      ws.onmessage = (event) => {
        const message = JSON.parse(event.data);
        this.addMessage(message);
      };

      ws.onclose = () => {
        this.state.isConnected = false;
        this.notify('Disconnected from server', 'error');
      };

      this.ws = ws;
    },

    // Load chat history
    async loadHistory() {
      try {
        const response = await fetch('/api/chat/history');
        const history = await response.json();
        this.state.messages = history;
      } catch (error) {
        this.notify('Failed to load chat history', 'error');
      }
    },

    // Send new message
    sendMessage() {
      if (!this.state.newMessage.trim()) return;

      const message = {
        id: Date.now(),
        user: this.state.currentUser,
        text: this.state.newMessage,
        timestamp: new Date().toISOString()
      };

      this.ws.send(JSON.stringify(message));
      this.state.newMessage = '';
    },

    // Add message to chat
    addMessage(message) {
      this.state.messages.push(message);
      this.scrollToBottom();
    },

    // Scroll chat to bottom
    scrollToBottom() {
      const chat = this.element.querySelector('.chat-messages');
      chat.scrollTop = chat.scrollHeight;
    },

    // Show notification
    notify(message, type = 'info') {
      NotificationManager[type](message);
    }
  },

  // Component template
  template: `
    
{{isConnected ? 'Connected' : 'Disconnected'}}
{{#each messages}}
{{user.name}} {{formatTime(timestamp)}}
{{text}}
{{/each}}
` });

HTML Usage

<div data-component="chat-app"></div>

CSS Styles

.chat-container {
  display: flex;
  flex-direction: column;
  height: 500px;
  border: 1px solid var(--color-border);
  border-radius: var(--border-radius-lg);
  background: var(--color-surface);
}

.chat-header {
  padding: var(--spacing-4);
  border-bottom: 1px solid var(--color-border);
}

.online-status {
  padding: var(--spacing-2) var(--spacing-4);
  border-radius: var(--border-radius-full);
  background: var(--color-error);
  color: white;
  font-size: var(--font-size-sm);
  display: inline-block;
}

.online-status.online {
  background: var(--color-success);
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: var(--spacing-4);
}

.message {
  margin-bottom: var(--spacing-4);
  max-width: 80%;
}

.message.own {
  margin-left: auto;
}

.message-info {
  margin-bottom: var(--spacing-2);
  font-size: var(--font-size-sm);
}

.username {
  font-weight: var(--font-weight-bold);
  color: var(--color-primary);
}

.timestamp {
  color: var(--color-text-light);
  margin-left: var(--spacing-2);
}

.message-content {
  background: var(--color-surface-light);
  padding: var(--spacing-3);
  border-radius: var(--border-radius-lg);
}

.message.own .message-content {
  background: var(--color-primary);
  color: white;
}

.chat-input {
  padding: var(--spacing-4);
  border-top: 1px solid var(--color-border);
  display: flex;
  gap: var(--spacing-2);
}

.chat-input input {
  flex: 1;
  padding: var(--spacing-2) var(--spacing-3);
  border: 1px solid var(--color-border);
  border-radius: var(--border-radius);
  background: var(--color-background);
}

.chat-input button {
  padding: var(--spacing-2) var(--spacing-4);
  background: var(--color-primary);
  color: white;
  border-radius: var(--border-radius);
  cursor: pointer;
}

Live Demo

Features Demonstrated

Real-time Communication

WebSocket integration for instant messaging

State Management

Component state handling and updates

Event Handling

User input and WebSocket events

Template System

Dynamic content rendering

Additional Resources