Skip to content

Instantly share code, notes, and snippets.

@deebloo
Last active April 3, 2020 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deebloo/ae722644a5e5256dc2a20f998f3e9920 to your computer and use it in GitHub Desktop.
Save deebloo/ae722644a5e5256dc2a20f998f3e9920 to your computer and use it in GitHub Desktop.
message-parts

Text Chats as Data

Most of the time when we are thinking about sending a chat message as text we just think of sending a string. This work fine in most cases but causes issues when we think about formatting or when needing to define special actions like links. This is a proposal for a potential way of treating messages differently.

Let’s say that you wanted to send this block of text as a message.

“Hello World, this is the BEST! Follow me here.”

How would you interpret the bold text? We could break up the string into distinct tokens that represent a small part of the message.

enum MessageType {
  Bold,
  Link
}

type Text = string;
type Bold { type: MessageType.Bold, value: string }
type Link { type: MessageType.Link, value: string, url: string }

type MessagePart = Text | Bold | Link;

const message: MessagePart[] = [
  'Hello',
  'World,',
  'this',
  'is',
  'the',
  { type: MessageType.Bold, value: 'BEST!' },
  'follow',
  'me',
  { type: MessageType.Link, value: 'here.', url: 'https://www.google.com' }
];

"message" represents the string broken up into distinct parsable tokens. An HTML interpreter for the above message could look something like this.

const interpretMessageToHtml = (message: MessagePart[]): string => {
  return message.map((part: MessagePart) => {
    if('type' in part) {
      switch(part.type) {
        case MessageType.Bold:
          return `<b>${part.value}</b>`;
        
        case MessageType.Link:
          return `<a href="${part.url}">${part.value}</a>`;
      }
    }
    
    return part;
  }).join(' ');
}

interpretMessageToHtml([
  'Hello',
  'World,',
  'this',
  'is',
  'the',
  { type: MessageType.Bold, value: 'BEST.' },
  'Follow',
  'me',
  { type: MessageType.Link, value: 'here', url: 'https://www.google.com' }
]); 
// Hello World this is the <b>BEST</b>. Follow me <a href="https://www.google.com">here</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment