Kanban Board
A Vue board whose lists and cards are Yorkie Arrays. Add, move and delete cards in one pane and watch the same Array operations arrive in the other.
App.vue
1<script setup>2import { computed, onBeforeUnmount, onMounted, ref, shallowRef } from 'vue';3import yorkie from '@yorkie-js/sdk';45const rpcAddr = import.meta.env.VITE_YORKIE_API_ADDR;6const names = ['Otter', 'Fox', 'Panda', 'Koala', 'Heron', 'Lynx', 'Robin'];7const peerColors = [8 '#fc8539',9 '#fdc433',10 '#23c176',11 '#3c9af1',12 '#f44954',13 '#855cf9',14];15const maxAvatars = 4;16const pageURL = window.location.href;1718const initialRoot = {19 lists: [20 {21 title: 'To do',22 cards: [23 { title: 'Draft the launch announcement' },24 { title: 'Pick a date for the team offsite' },25 ],26 },27 {28 title: 'In progress',29 cards: [{ title: 'Redesign the pricing page' }],30 },31 {32 title: 'Done',33 cards: [34 { title: 'Set up the project board' },35 { title: 'Invite the team' },36 ],37 },38 ],39};4041const client = new yorkie.Client({42 rpcAddr,43 apiKey: import.meta.env.VITE_YORKIE_API_KEY,44});45// A new board starts every day (the key ends in YYYYMMDD), so the public46// demo resets to the seed cards instead of collecting edits forever.47const doc = new yorkie.Document(48 `vuejs-kanban-${new Date().toISOString().substring(0, 10).replace(/-/g, '')}`,49 { enableDevtools: import.meta.env.DEV },50);5152// `lists` holds the Yorkie proxy. A shallowRef keeps Vue from wrapping it;53// we assign a fresh root after every change to re-render.54const lists = shallowRef(null);55const presences = shallowRef([]);56const status = ref('connecting'); // connecting, connected, offline, error57const opened = ref(null); // the list whose form is open, or 'list'58const title = ref('');59const dragging = shallowRef(null);60const unsubscribers = [];6162const idOf = (element) => element.getID().toIDString();63const statusLabels = {64 connecting: 'Connecting…',65 connected: 'Connected',66 offline: 'Offline',67 error: 'Error',68};6970// `peerColor` derives a colour from the client ID, so every tab agrees.71function peerColor(clientID) {72 let hash = 0;73 for (const ch of clientID) hash = (hash * 31 + ch.charCodeAt(0)) | 0;74 return peerColors[Math.abs(hash) % peerColors.length];75}7677const peers = computed(() => {78 const myID = client.getActorID();79 return presences.value80 .map(({ clientID, presence }) => ({81 clientID,82 name: presence.name,83 color: peerColor(clientID),84 isMe: clientID === myID,85 }))86 .sort((a, b) => b.isMe - a.isMe);87});8889onMounted(async () => {90 try {91 await client.activate();92 unsubscribers.push(93 doc.subscribe(() => (lists.value = doc.getRoot().lists)),94 doc.subscribe('presence', () => (presences.value = doc.getPresences())),95 doc.subscribe('connection', (event) => {96 status.value = event.value === 'connected' ? 'connected' : 'offline';97 }),98 );99 await client.attach(doc, {100 initialRoot,101 initialPresence: {102 name: names[Math.floor(Math.random() * names.length)],103 },104 });105 lists.value = doc.getRoot().lists;106 presences.value = doc.getPresences();107 } catch {108 status.value = 'error';109 }110});111112onBeforeUnmount(async () => {113 unsubscribers.forEach((unsubscribe) => unsubscribe());114 if (client.has(doc.getKey())) await client.detach(doc);115 if (client.isActive()) await client.deactivate();116});117118function openForm(target) {119 opened.value = target;120 title.value = '';121}122123function closeForm() {124 opened.value = null;125}126127// Focus the title input as soon as a form opens.128const vFocus = { mounted: (el) => el.focus() };129130function addCard(list) {131 const cardTitle = title.value.trim();132 if (!cardTitle) return;133 doc.update((root) => {134 root.lists.getElementByID(list.getID())?.cards.push({ title: cardTitle });135 }, 'add a card');136 title.value = '';137}138139function addList() {140 const listTitle = title.value.trim();141 if (!listTitle) return;142 doc.update((root) => {143 root.lists.push({ title: listTitle, cards: [] });144 }, 'add a list');145 title.value = '';146}147148function deleteCard(list, card) {149 doc.update((root) => {150 root.lists.getElementByID(list.getID())?.cards.deleteByID(card.getID());151 }, 'delete a card');152}153154function deleteList(list) {155 doc.update((root) => {156 root.lists.deleteByID(list.getID());157 }, 'delete a list');158}159160// `moveCard` moves a card before `beforeCard`, or to the end of `toList`.161// moveBefore/moveLast reorder elements inside one array. An element can't162// move between arrays, so a card that changes lists is deleted from one163// and re-created in the other. Doing both in one update keeps a single164// move atomic, but it is still delete + insert: if two peers move the165// same card to other lists at the same time, both copies survive, and a166// move made at the same time as a peer's delete brings the card back.167function moveCard(card, fromList, toList, beforeCard) {168 if (beforeCard && idOf(beforeCard) === idOf(card)) return;169 doc.update((root) => {170 // A peer may have deleted the card or either list since this view171 // rendered. Re-read them here and skip the move if any is gone, so a172 // deleted card is not re-created. If only `beforeCard` is gone, the173 // card goes to the end of the list instead.174 const from = root.lists.getElementByID(fromList.getID())?.cards;175 const to = root.lists.getElementByID(toList.getID())?.cards;176 if (!from || !to || !from.getElementByID(card.getID())) return;177 const beforeID =178 beforeCard && to.getElementByID(beforeCard.getID())179 ? beforeCard.getID()180 : undefined;181 if (idOf(fromList) === idOf(toList)) {182 if (beforeID) to.moveBefore(beforeID, card.getID());183 else to.moveLast(card.getID());184 return;185 }186 from.deleteByID(card.getID());187 if (beforeID) to.insertBefore(beforeID, { title: card.title });188 else to.push({ title: card.title });189 }, 'move a card');190}191192function onMoveSelect(card, fromList, event) {193 const toList = [...lists.value].find((l) => idOf(l) === event.target.value);194 event.target.value = '';195 if (toList) moveCard(card, fromList, toList);196}197198function onDragStart(event, card, list) {199 // Firefox only starts a drag when some data is set.200 event.dataTransfer.setData('text/plain', card.title);201 dragging.value = { card, list };202}203204function onDrop(toList, beforeCard) {205 if (!dragging.value) return;206 const { card, list } = dragging.value;207 dragging.value = null;208 moveCard(card, list, toList, beforeCard);209}210</script>211212<template>213 <header class="header">214 <div class="header-text">215 <h1 class="header-title">Vue Kanban</h1>216 <p class="header-hint">217 Add, move and delete cards together:218 <a :href="pageURL" target="_blank">open this board in another tab</a>219 to see changes sync.220 </p>221 </div>222 <div class="header-meta">223 <span class="status" :data-status="status">224 <span class="status-dot" aria-hidden="true" />225 {{ statusLabels[status] }}226 </span>227 <ul228 v-if="peers.length"229 class="avatars"230 :aria-label="`${peers.length} online`"231 >232 <li233 v-for="peer in peers.slice(0, maxAvatars)"234 :key="peer.clientID"235 class="avatar"236 :data-me="peer.isMe"237 :style="{ background: peer.color }"238 :title="peer.isMe ? 'You' : peer.name"239 >240 {{ peer.name?.[0] }}241 </li>242 <li243 v-if="peers.length > maxAvatars"244 class="avatar avatar-more"245 :title="`${peers.length - maxAvatars} more`"246 >247 +{{ peers.length - maxAvatars }}248 </li>249 </ul>250 </div>251 </header>252253 <main class="board">254 <p v-if="status === 'error'" class="message" role="alert">255 Couldn’t reach the Yorkie server at {{ rpcAddr }}. Check that it’s256 running, then reload.257 </p>258 <p v-else-if="!lists" class="message">Loading the board…</p>259 <template v-else>260 <section261 v-for="list in lists"262 :key="idOf(list)"263 class="list"264 :aria-label="list.title"265 @dragover.prevent266 @drop.prevent="onDrop(list)"267 >268 <div class="list-header">269 <h2 class="list-title">{{ list.title }}</h2>270 <button271 type="button"272 class="icon-button"273 :aria-label="`Delete list ${list.title}`"274 title="Delete list"275 @click="deleteList(list)"276 >277 <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true">278 <path279 d="M4 4l8 8M12 4l-8 8"280 stroke="currentColor"281 stroke-width="1.5"282 stroke-linecap="round"283 />284 </svg>285 </button>286 </div>287288 <ul class="cards">289 <li290 v-for="card in list.cards"291 :key="idOf(card)"292 class="card"293 draggable="true"294 @dragstart="onDragStart($event, card, list)"295 @dragend="dragging = null"296 @dragover.prevent297 @drop.prevent.stop="onDrop(list, card)"298 >299 <span class="card-title">{{ card.title }}</span>300 <div class="card-actions">301 <select302 v-if="lists.length > 1"303 class="move-select"304 :aria-label="`Move ${card.title} to another list`"305 @change="onMoveSelect(card, list, $event)"306 >307 <option value="">Move to…</option>308 <template v-for="target in lists" :key="idOf(target)">309 <option310 v-if="idOf(target) !== idOf(list)"311 :value="idOf(target)"312 >313 {{ target.title }}314 </option>315 </template>316 </select>317 <button318 type="button"319 class="icon-button"320 :aria-label="`Delete card ${card.title}`"321 title="Delete card"322 @click="deleteCard(list, card)"323 >324 <svg325 width="16"326 height="16"327 viewBox="0 0 16 16"328 aria-hidden="true"329 >330 <path331 d="M4 4l8 8M12 4l-8 8"332 stroke="currentColor"333 stroke-width="1.5"334 stroke-linecap="round"335 />336 </svg>337 </button>338 </div>339 </li>340 <li v-if="list.cards.length === 0" class="empty">341 No cards yet. Add one, or drop a card here.342 </li>343 </ul>344345 <form346 v-if="opened === idOf(list)"347 class="add-form"348 @submit.prevent="addCard(list)"349 >350 <input351 v-model="title"352 v-focus353 type="text"354 placeholder="Card title"355 :aria-label="`New card in ${list.title}`"356 @keyup.esc="closeForm"357 />358 <div class="form-buttons">359 <button360 type="submit"361 class="button-primary"362 :disabled="!title.trim()"363 >364 Add card365 </button>366 <button type="button" class="button" @click="closeForm">367 Cancel368 </button>369 </div>370 </form>371 <button372 v-else373 type="button"374 class="add-opener"375 @click="openForm(idOf(list))"376 >377 <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true">378 <path379 d="M8 3v10M3 8h10"380 stroke="currentColor"381 stroke-width="1.5"382 stroke-linecap="round"383 />384 </svg>385 Add a card386 </button>387 </section>388389 <section class="list list-new" aria-label="New list">390 <form391 v-if="opened === 'list'"392 class="add-form"393 @submit.prevent="addList"394 >395 <input396 v-model="title"397 v-focus398 type="text"399 placeholder="List title"400 aria-label="New list title"401 @keyup.esc="closeForm"402 />403 <div class="form-buttons">404 <button405 type="submit"406 class="button-primary"407 :disabled="!title.trim()"408 >409 Add list410 </button>411 <button type="button" class="button" @click="closeForm">412 Cancel413 </button>414 </div>415 </form>416 <button417 v-else418 type="button"419 class="add-opener"420 @click="openForm('list')"421 >422 <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true">423 <path424 d="M8 3v10M3 8h10"425 stroke="currentColor"426 stroke-width="1.5"427 stroke-linecap="round"428 />429 </svg>430 Add another list431 </button>432 </section>433 </template>434 </main>435</template>
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