polis-client-ts example

by patcon

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Polis Demo</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <h1>Polis Conversation Viewer</h1>

  <div id="conversation-meta">
    Loading conversation details...
  </div>

  <h2>Comments</h2>
  <div id="comments-container">Loading comments...</div>

  <!-- Load your script as an ES module -->
  <script type="module" src="script.js"></script>
</body>
</html>

CSS

body {
  font-family: Arial, sans-serif;
  margin: 2rem;
  background-color: #f9f9f9;
  color: #333;
}

h1 {
  font-size: 1.8rem;
  margin-bottom: 1rem;
}

h2 {
  margin-top: 2rem;
  margin-bottom: 1rem;
}

#conversation-meta {
  padding: 1rem;
  background-color: #eef;
  border-radius: 6px;
  margin-bottom: 1rem;
}

#comments-container {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.comment {
  padding: 0.5rem 1rem;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

JavaScript

// Load ESM build from CDN
import { PolisClient } from "https://cdn.jsdelivr.net/gh/patcon/polis-client@latest/typescript/dist/index.js";

const metaContainer = document.getElementById("conversation-meta");
const commentsContainer = document.getElementById("comments-container");

async function loadConversation() {
  try {
    const polis = new PolisClient({
      baseUrl: "https://corsproxy.io/?url=https://pol.is"
    });

    const convoId = "2demo";

    // Fetch conversation metadata
    const convo = await polis.getConversation(convoId);
    metaContainer.innerHTML = `
      <strong>Topic:</strong> ${convo.topic || "N/A"}<br>
      <strong>Description:</strong> ${convo.description || "No description"}<br>
      <strong>Participants:</strong> ${convo.participant_count || 0}<br>
      <strong>Owner:</strong> ${convo.ownername || "N/A"}
    `;

    // Fetch comments
    const comments = await polis.getComments(convoId);
    commentsContainer.innerHTML = ""; // clear loading text

    if (!comments || comments.length === 0) {
      commentsContainer.textContent = "No comments found.";
      return;
    }

    comments.forEach(comment => {
      const div = document.createElement("div");
      div.className = "comment";
      div.textContent = comment.txt || comment.text || JSON.stringify(comment);
      commentsContainer.appendChild(div);
    });

  } catch (err) {
    console.error(err);
    metaContainer.textContent = "Failed to load conversation.";
    commentsContainer.textContent = "Failed to load comments.";
  }
}

loadConversation();