Profile Stack
The profile stack shows the list of users currently accessing the Document. Try adding and deleting users to see how the profile stack changes.
main.js
1import yorkie from '@yorkie-js/sdk';2import { getRandomName, getPeerColor } from './util.js';34const API_ADDR = import.meta.env.VITE_YORKIE_API_ADDR;56const client = new yorkie.Client({7 rpcAddr: API_ADDR,8 apiKey: import.meta.env.VITE_YORKIE_API_KEY,9});1011// Everyone who opens this page attaches to the same document, so the stack12// lists every client that is currently on it.13const doc = new yorkie.Document('profile-stack', {14 enableDevtools: import.meta.env.DEV,15});1617// Show yourself and up to this many peers; the rest collapse into "+N".18const MAX_PEERS_SHOWN = 3;1920const $status = document.getElementById('status');21const $stage = document.getElementById('stage');22const $stack = document.getElementById('stack');23const $caption = document.getElementById('caption');24const $dialog = document.getElementById('nameDialog');25const $nameForm = document.getElementById('nameForm');26const $nameInput = document.getElementById('nameInput');27const $nameError = document.getElementById('nameError');2829let me = null;30let peers = [];31// Which bubble is open: a peer's client ID, 'more', or null.32let openBubble = null;3334async function main() {35 await client.activate();3637 // `presence` fires whenever someone joins, leaves or changes their name.38 doc.subscribe('presence', () => {39 // Presences are keyed by the client's actor ID, so "me" is the entry40 // whose `clientID` matches `client.getActorID()`.41 const myID = client.getActorID();42 const presences = doc.getPresences();43 me = presences.find(({ clientID }) => clientID === myID);44 peers = presences.filter(({ clientID }) => clientID !== myID);45 render();46 });4748 // `connection` reports whether the watch stream to the server is alive.49 doc.subscribe('connection', (event) => {50 setStatus(event.value === 'connected' ? 'connected' : 'offline');51 });5253 await client.attach(doc, {54 initialPresence: { name: getRandomName() },55 });56 setStatus('connected');57}5859const STATUS_LABELS = {60 connecting: 'Connecting…',61 connected: 'Connected',62 offline: 'Offline',63 error: 'Error',64};65const setStatus = (state) => {66 $status.dataset.state = state;67 $status.querySelector('.status-label').textContent = STATUS_LABELS[state];68};6970// Names are typed by peers, so they only ever go in through `textContent`.71// A peer may also send no name at all, which must not break the stack.72const nameOf = (presence) => String(presence.name ?? '');7374const createAvatar = ({ clientID, presence }) => {75 const $avatar = document.createElement('span');76 $avatar.className = 'avatar';77 $avatar.style.setProperty('--peer', getPeerColor(clientID));78 $avatar.textContent = nameOf(presence).charAt(0).toUpperCase() || '?';79 return $avatar;80};8182const render = () => {83 // The stack is rebuilt on every change; remember which button had focus so84 // keyboard users don't lose their place.85 const focusedKey = document.activeElement?.dataset.key;86 $stack.replaceChildren();87 if (!me) return;8889 // Your own entry: avatar plus name. Clicking it opens the name dialog.90 const $meItem = document.createElement('li');91 $meItem.className = 'me';92 const $meButton = document.createElement('button');93 $meButton.className = 'me-button';94 $meButton.dataset.key = 'me';95 $meButton.title = 'You';96 $meButton.setAttribute(97 'aria-label',98 `${nameOf(me.presence)} (you), change name`,99 );100 const $meName = document.createElement('span');101 $meName.className = 'me-name';102 $meName.textContent = nameOf(me.presence);103 const $meTag = document.createElement('span');104 $meTag.className = 'me-tag';105 $meTag.textContent = 'you';106 $meButton.append(createAvatar(me), $meName, $meTag);107 $meButton.addEventListener('click', openNameDialog);108 $meItem.append($meButton);109 $stack.append($meItem);110111 // Peers: avatars that show the name in a bubble when clicked.112 peers.slice(0, MAX_PEERS_SHOWN).forEach((peer) => {113 const $item = document.createElement('li');114 $item.className = 'peer';115 const $button = document.createElement('button');116 $button.className = 'peer-button';117 $button.dataset.key = peer.clientID;118 $button.title = nameOf(peer.presence);119 $button.setAttribute('aria-label', nameOf(peer.presence));120 $button.append(createAvatar(peer));121 $button.addEventListener('click', () => toggleBubble(peer.clientID));122 $item.append($button);123 if (openBubble === peer.clientID) {124 $item.append(createBubble([peer]));125 }126 $stack.append($item);127 });128129 const rest = peers.slice(MAX_PEERS_SHOWN);130 if (rest.length > 0) {131 const $item = document.createElement('li');132 $item.className = 'peer';133 const $button = document.createElement('button');134 $button.className = 'peer-button more';135 $button.dataset.key = 'more';136 $button.setAttribute('aria-label', `${rest.length} more people`);137 $button.textContent = `+${rest.length}`;138 $button.addEventListener('click', () => toggleBubble('more'));139 $item.append($button);140 if (openBubble === 'more') {141 $item.append(createBubble(rest));142 }143 $stack.append($item);144 }145146 const others = peers.length === 1 ? 'other' : 'others';147 $caption.textContent =148 peers.length === 0149 ? 'Only you are here · click your avatar to change your name'150 : `You and ${peers.length} ${others} are here · ` +151 'click your avatar to change your name';152153 keepBubbleOnScreen();154 if (focusedKey) {155 $stack.querySelector(`[data-key="${focusedKey}"]`)?.focus();156 }157};158159// bubble160const createBubble = (people) => {161 const $bubble = document.createElement('ul');162 $bubble.className = 'bubble';163 people.forEach((person) => {164 const $row = document.createElement('li');165 $row.className = 'bubble-row';166 const $name = document.createElement('span');167 $name.textContent = nameOf(person.presence);168 $row.append(createAvatar(person), $name);169 $bubble.append($row);170 });171 return $bubble;172};173174const toggleBubble = (key) => {175 openBubble = openBubble === key ? null : key;176 render();177};178179// On narrow screens a bubble under the last avatar would stick out of the180// viewport, so nudge it back in.181const keepBubbleOnScreen = () => {182 const $bubble = $stack.querySelector('.bubble');183 if (!$bubble) return;184 const { left, right } = $bubble.getBoundingClientRect();185 const margin = 16;186 const shift =187 Math.max(0, margin - left) -188 Math.max(0, right - (window.innerWidth - margin));189 $bubble.style.translate = `${shift}px 0`;190};191192window.addEventListener('click', (event) => {193 if (openBubble !== null && !event.target.closest('.peer')) {194 toggleBubble(null);195 }196});197window.addEventListener('keydown', (event) => {198 if (event.key === 'Escape' && openBubble !== null) {199 toggleBubble(null);200 }201});202203// name dialog: a native <dialog> traps focus and closes on Escape. It returns204// focus to the button that opened it, but a render while it was open may have205// replaced that button, so focus your avatar again once it closes.206$dialog.addEventListener('close', () => {207 $stack.querySelector('[data-key="me"]')?.focus();208});209210const openNameDialog = () => {211 $nameInput.value = nameOf(me.presence);212 $nameError.hidden = true;213 $nameInput.removeAttribute('aria-invalid');214 $dialog.showModal();215 $nameInput.select();216};217218$nameForm.addEventListener('submit', (event) => {219 event.preventDefault();220 const name = $nameInput.value.trim();221 if (!name) {222 $nameError.hidden = false;223 $nameInput.setAttribute('aria-invalid', 'true');224 $nameInput.focus();225 return;226 }227 // Close first so focus is back on your avatar before the stack re-renders.228 $dialog.close();229 // Presence changes are sent to every peer, which re-renders their stack.230 doc.update((_, presence) => {231 presence.set({ name });232 });233});234document235 .getElementById('nameCancel')236 .addEventListener('click', () => $dialog.close());237238main().catch(() => {239 setStatus('error');240 const $error = document.createElement('p');241 $error.className = 'error';242 $error.textContent =243 `Couldn't reach the Yorkie server at ${API_ADDR}. ` +244 "Check that it's running, then reload.";245 $stage.replaceChildren($error);246});
Two clients on the same document. Edit in one and watch the other.This is one client. Open the example in another tab or on another device to watch edits sync.
- User 1