Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Pubky
https://pubky.org/llms.txt
Admin
Pubky is a platform that aims to unlock the web by realizing a vision for a key-based,
...
Tokens:
47,665
Snippets:
346
Trust Score:
6.4
Update:
1 week ago
Context
Chat
Benchmark
52.28
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Clone Vite starter template and install Pubky SDK Source: https://pubky.org/developer-guide Initializes a new Pubky app from the Vite starter template and installs the @synonymdev/pubky package. Requires the Homeserver to be running. ```bash npx tiged pubky/pubky-app-templates/vite-starter pubky-hello-world cd pubky-hello-world npm install && npm install @synonymdev/pubky ``` -------------------------------- ### Install Pubky SDK with Yarn Source: https://pubky.org/developer-guide Alternative installation for Yarn users. ```bash yarn add @synonymdev/pubky ``` -------------------------------- ### Install Pubky SDK with Cargo (Rust) Source: https://pubky.org/developer-guide Alternative installation for Rust users. ```bash cargo add pubky ``` -------------------------------- ### Start Colima Docker runtime Source: https://pubky.org/developer-guide Starts the Colima Docker runtime, required when using Colima instead of Docker Desktop or a native daemon. Ensure your Docker engine is running before proceeding. ```bash colima start ``` -------------------------------- ### Install Pubky SDK for React Native Source: https://pubky.org/developer-guide Alternative installation for React Native, including iOS pod install. ```bash npm install @synonymdev/react-native-pubky cd ios && pod install # iOS only ``` -------------------------------- ### Sign in Source: https://pubky.org/developer-guide Creates a Homeserver session for the demo user. ```js const session = await signer.signin("myapp.example"); ``` -------------------------------- ### Run basic Pubky app with VITE_PUBKY_TESTNET=true Source: https://pubky.org/developer-guide Starts the development server with the testnet flag enabled, which is required for local development with the Pubky Ring Simulator. ```bash VITE_PUBKY_TESTNET=true npm run dev ``` -------------------------------- ### Fetch posts from Pubky Nexus API Source: https://pubky.org/developer-guide Use this to retrieve a stream of posts from the Pubky Nexus API. The example fetches the latest 10 posts and parses the JSON response. ```javascript const response = await fetch( "https://nexus.pubky.app/v0/stream/posts?limit=10", ); const posts = await response.json(); ``` -------------------------------- ### Connect to local testnet Source: https://pubky.org/developer-guide Creates a Pubky instance configured to use the local testnet services started by Pubky Docker instead of the production network. ```js const pubky = Pubky.testnet(); ``` -------------------------------- ### Sign up on the local Homeserver Source: https://pubky.org/developer-guide Creates an account on the local Homeserver and publishes the user's Homeserver mapping (PKARR). Passes null as the signup token because local signup is set to 'open'. A 404 during first signup may be normal. ```js const homeserver = PublicKey.from( "pubky8pinxxgqs41n4aididenw5apqp1urfmzdztr8jt4abrkdn435ewo", ); await signer.signup(homeserver, null); ``` -------------------------------- ### Import Pubky SDK and enable info logs Source: https://pubky.org/developer-guide Loads the Pubky SDK and sets log level to 'info'. The log level must be set only once, before creating the client; errors are caught and warned. ```js import { Keypair, Pubky, PublicKey, setLogLevel } from "@synonymdev/pubky"; try { setLogLevel("info"); } catch (error) { console.warn( "Pubky log level must be set only once, before creating the client.", error, ); } ``` -------------------------------- ### Clone basic Pubky app template with npx tiged Source: https://pubky.org/developer-guide Clones the basic Pubky app template into a new directory and installs dependencies. Set a stable app ID in src/config.ts; it determines the storage path. ```bash npx tiged pubky/pubky-app-templates/basic-pubky-app my-pubky-app cd my-pubky-app npm install ``` -------------------------------- ### Pubky.testnet Source: https://pubky.org/developer-guide Creates a Pubky client instance configured to use the local testnet services started by Pubky Docker instead of the production Pubky network. ```APIDOC ## Pubky.testnet ### Description Creates a Pubky client instance configured to use the local testnet services started by Pubky Docker instead of the production Pubky network. ### Method Static method ### Returns - **Pubky** - A Pubky client instance. ### Example ```js const pubky = Pubky.testnet(); ``` ``` -------------------------------- ### PublicKey.from Source: https://pubky.org/developer-guide Parses a public key string into a PublicKey object. ```APIDOC ## PublicKey.from ### Description Parses a public key string into a PublicKey object. ### Method Static method ### Parameters - **publicKey** (string) - Required - The public key string to parse. ### Returns - **PublicKey** - A PublicKey object. ### Example ```js const homeserver = PublicKey.from( "pubky8pinxxgqs41n4aididenw5apqp1urfmzdztr8jt4abrkdn435ewo", ); ``` ``` -------------------------------- ### Create a new user identity Source: https://pubky.org/developer-guide Generates a random keypair and creates a signer, logging the public key in z32 format to the browser console. ```js const keypair = Keypair.random(); const signer = pubky.signer(keypair); console.log("Your pubky:", signer.publicKey.z32()); ``` -------------------------------- ### Read JSON from Homeserver storage with session.storage.getJson Source: https://pubky.org/developer-guide Fetches the same JSON file from Homeserver storage and renders it in the template's #app element, proving that signup, signin, write, and read all worked. Run npm run dev again and open the page to see the data displayed. ```javascript const data = await session.storage.getJson(path); document.querySelector<HTMLDivElement>("#app")!.textContent = JSON.stringify( data, null, 2, ); ``` -------------------------------- ### Run homeserver and testnet via Docker Compose Source: https://pubky.org/developer-guide Starts the homeserver and testnet containers in detached mode. After running, verify the PKARR relay at http://localhost:15411/ and the Homeserver admin at http://localhost:6288/ respond. The testnet Homeserver's pubky is always 8pinxxgqs41n4aididenw5apqp1urfmzdztr8jt4abrkdn435ewo. ```bash docker compose up homeserver -d ``` -------------------------------- ### Keypair.random Source: https://pubky.org/developer-guide Generates a random keypair for a new user identity. ```APIDOC ## Keypair.random ### Description Generates a random keypair for a new user identity. ### Method Static method ### Returns - **Keypair** - A randomly generated keypair. ### Example ```js const keypair = Keypair.random(); ``` ``` -------------------------------- ### Clone and configure Pubky Docker Source: https://pubky.org/developer-guide Clones the pubky-docker repository, enters the directory, and copies the sample environment file to .env. Requires Docker and npm. The default NETWORK=testnet exposes ports 15411, 15412, 6286, 6287, and 6288. ```bash git clone https://github.com/pubky/pubky-docker.git && cd pubky-docker && cp .env-sample .env ``` -------------------------------- ### Starter prompt for exploring Pubky Source: https://pubky.org/ A prompt to start exploring Pubky with an LLM, directing it to the documentation and asking for citations and verification. ```text Help me explore Pubky. Start at https://pubky.org/llms.txt and use the linked index or full documentation as needed. Ask what I’d like to know or do. Follow my interests. Cite sources and flag anything you cannot verify or access. If we write code, confirm my language or framework and SDK version, then check the corresponding SDK documentation. ``` -------------------------------- ### Install Pubky SDK via npm Source: https://pubky.org/ Install the Pubky JavaScript SDK using npm. ```bash $ npm install @synonymdev/pubky ``` -------------------------------- ### setLogLevel Source: https://pubky.org/developer-guide Sets the log level for the Pubky SDK. Must be called only once, before creating the client. ```APIDOC ## setLogLevel ### Description Sets the log level for the Pubky SDK. Must be called only once, before creating the client. ### Method Function ### Parameters - **level** (string) - Required - The log level to set (e.g., "info"). ### Example ```js setLogLevel("info"); ``` ``` -------------------------------- ### Switch from testnet to production Pubky client Source: https://pubky.org/developer-guide Replace the testnet client with the production client to connect to the live Pubky network. This stops using local endpoints and resolves PKARR records from the Mainline DHT. ```diff - const pubky = Pubky.testnet(); + const pubky = new Pubky(); ``` -------------------------------- ### pubky.signer Source: https://pubky.org/developer-guide Creates a signer for the given keypair, which can be used to sign operations and access the public key. ```APIDOC ## pubky.signer ### Description Creates a signer for the given keypair, which can be used to sign operations and access the public key. ### Method Method ### Parameters - **keypair** (Keypair) - Required - The keypair to create a signer for. ### Returns - **Signer** - A signer object with a `publicKey` property. ### Example ```js const signer = pubky.signer(keypair); console.log("Your pubky:", signer.publicKey.z32()); ``` ``` -------------------------------- ### Configure custom PKARR relays Source: https://pubky.org/developer-guide Use this to specify custom PKARR relays for the Pubky client. Browsers cannot query the UDP-based Mainline DHT directly, so HTTPS gateways are required. ```javascript const client = new Client({ pkarr: { relays: ["https://pkarr.pubky.org"], }, }); const pubky = Pubky.withClient(client); ``` -------------------------------- ### Write JSON to Homeserver storage with session.storage.putJson Source: https://pubky.org/developer-guide Writes a JSON file to the signed-in user's Homeserver public storage. Store each independently edited record in its own file to enable smaller updates, load records as needed, and reduce write conflicts. ```javascript const path = "/pub/hello-world/data.json"; await session.storage.putJson(path, { message: "Hello Pubkyverse!" }); ``` -------------------------------- ### Install Pubky React Native SDK via npm Source: https://pubky.org/ Install the Pubky React Native SDK using npm. ```bash $ npm install @synonymdev/react-native-pubky ``` -------------------------------- ### Configure custom HTTP relay for authentication Source: https://pubky.org/developer-guide Use this to set a custom HTTP relay for Pubky Ring authentication. The relay transfers encrypted authentication messages and is separate from PKARR relays. ```javascript import { AuthFlowKind } from "@synonymdev/pubky"; const relay = "https://httprelay.example.com/inbox/"; const flow = await pubky.startGrantAuthFlow( "/pub/myapp/:rw", AuthFlowKind.signin(), { clientId: "myapp.example", relay, }, ); ``` -------------------------------- ### Define Pubky post, profile, tag, and collection objects Source: https://playground.pubky.org/ Defines canonical JavaScript objects for a Pubky post, user profile, tag, and collection. These are used as the data models for the PubkyApp examples on this page. ```javascript const POST_CANONICAL = { content: POST.content, kind: POST.kind, attachments: [ 'pubky://pk:gx9m.../pub/pubky.app/blobs/X9F2K3M0N1P2' ] }; const POST_PROFILE = { name: POST.author.name, bio: 'My ghost, my shell, my keys.', image: 'pubky://pk:gx9m.../pub/pubky.app/blobs/AVATAR', links: [{ title: 'Section 9', url: 'https://example.net' }] }; const TAG_EXAMPLE = { uri: 'pubky://pk:gx9m.../pub/pubky.app/posts/ID', label: '❤️', created_at: 1711234567 }; const COLLECTION_CANONICAL = { name: COLLECTION.name, description: COLLECTION.description, tags: COLLECTION.tags, cover: 'pubky://pk:gx9m.../pub/pubky.app/blobs/COV3R0B4NN3R', is_public: true, items: [ 'pubky://pk:gx9m.../pub/pubky.app/posts/0034A0M4R04SG', 'pubky://pk:gx9m.../pub/pubky.app/posts/0034B0M4R04SG', 'pubky://pk:gx9m.../pub/pubky.app/posts/0035C0M4R16SG', 'pubky://pk:gx9m.../pub/pubky.app/posts/0036D0M4R20SG', 'pubky://pk:gx9m.../pub/pubky.app/posts/0037E0M4R24SG', 'pubky://pk:gx9m.../pub/pubky.app/posts/0038F0M4R30SG' ] }; ``` -------------------------------- ### syntaxJSON: highlight JSON keys and values Source: https://playground.pubky.org/ Helper function that pretty-prints a JSON object and wraps keys, strings, numbers, and booleans in HTML span classes for syntax highlighting. Used to render the JSON examples on this page. ```javascript function syntaxJSON(obj) { return JSON.stringify(obj, null, 2) .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>') .replace(/"([^"]+)"(\s*:)/g, '<span class="json-key">"$1"</span>$2') .replace(/:\s*"([^"]*)"/g, ': <span class="json-str">"$1"</span>') .replace(/:\s*(\d+)/g, ': <span class="json-num">$1</span>') .replace(/:\s*(true|false|null)/g, ': <span class="json-bool">$1</span>'); } ``` -------------------------------- ### Starlight tabs custom element implementation Source: https://pubky.org/ This JavaScript code defines a custom element 'starlight-tabs' that implements accessible tabbed panels with keyboard navigation and synchronized tab state across multiple instances using localStorage. It is used by the documentation site to display tabbed code examples. ```javascript class r extends HTMLElement{static#e=new Map;#t;#n="starlight-synced-tabs__";constructor(){super();const t=this.querySelector('[role="tablist"]');if(this.tabs=[...t.querySelectorAll('[role="tab"]')],this.panels=[...this.querySelectorAll(':scope > [role="tabpanel"]')],this.#t=this.dataset.syncKey,this.#t){const i=r.#e.get(this.#t)??[];i.push(this),r.#e.set(this.#t,i)}this.tabs.forEach((i,c)=>{i.addEventListener("click",e=>{e.preventDefault();const n=t.querySelector('[aria-selected="true"]');e.currentTarget!==n&&this.switchTab(e.currentTarget,c)}),i.addEventListener("keydown",e=>{const n=this.tabs.indexOf(e.currentTarget),s=e.key==="ArrowLeft"?n-1:e.key==="ArrowRight"?n+1:e.key==="Home"?0:e.key==="End"?this.tabs.length-1:null;s!==null&&this.tabs[s]&&(e.preventDefault(),this.switchTab(this.tabs[s],s))})})}switchTab(t,i,c=!0){if(!t)return;const e=c?this.getBoundingClientRect().top:0;this.tabs.forEach(s=>{s.setAttribute("aria-selected","false"),s.setAttribute("tabindex","-1")}),this.panels.forEach(s=>{s.hidden=!0});const n=this.panels[i];n&&(n.hidden=!1),t.removeAttribute("tabindex"),t.setAttribute("aria-selected","true"),c&&(t.focus(),r.#r(this,t),window.scrollTo({top:window.scrollY+(this.getBoundingClientRect().top-e),behavior:"instant"}))}#i(t){!this.#t||typeof localStorage>"u"||localStorage.setItem(this.#n+this.#t,t)}static#r(t,i){const c=t.#t,e=r.#s(i);if(!c||!e)return;const n=r.#e.get(c);if(n){for(const s of n){if(s===t)continue;const a=s.tabs.findIndex(o=>r.#s(o)===e);a!==-1&&s.switchTab(s.tabs[a],a,!1)}t.#i(e)}}static#s(t){return t.textContent?.trim()}}customElements.define("starlight-tabs",r); ``` -------------------------------- ### Create and read a Pubky collection with putJson and getJson Source: https://playground.pubky.org/ Shows how to create a collection with a name and items (URIs), store it via session.storage.putJson, read it with pubky.publicStorage.getJson, and resolve items to full post objects. The comment notes the same data can power any layout such as Podcast, Channel, Album, Board, Blog, or Photo Album. ```javascript const collection = { name: "My Collection", items: [ "pubky://pk:gx9m.../posts/0034A", "pubky://pk:gx9m.../posts/0034B" // posts from any user by URI ] }; await session.storage.putJson( "/pub/pubky.app/collections/HASH_ID", collection ); // Read anyone's collection const col = await pubky.publicStorage.getJson( `pubky${pk}/pub/pubky.app/collections/ID` ); // Resolve items → full post objects const posts = await Promise.all( col.items.map(uri => pubky.publicStorage.getJson(uri) ) ); // Same data powers any layout: // Podcast, Channel, Album, Board, // Blog, or Photo Album. ``` -------------------------------- ### Initialize post and collection layout switchers Source: https://playground.pubky.org/ Initializes the post and collection switchers, attaching click handlers that call switchLayout with the appropriate layout and data. It also scrolls the tab bar into view on each switch. ```javascript const postPillUpdate = initSwitcherPill('post-switcher-track', 'post-pill', 4); const colPillUpdate = initSwitcherPill('col-switcher-track', 'col-pill', 6); const postBtns = document.querySelectorAll('#post-switcher-track .switcher-btn'); const colBtns = document.querySelectorAll('#col-switcher-track .switcher-btn'); postBtns.forEach(btn => { btn.addEventListener('click', () => { if (btn.classList.contains('active')) return; const layout = btn.dataset.layout; switchLayout('post-frame', postLayouts[layout], POST, layout, postPillUpdate, parseInt(btn.dataset.index), postBtns); document.querySelector('.tab-bar').scrollIntoView({ behavior: 'smooth', block: 'start' }); }); }); colBtns.forEach(btn => { btn.addEventListener('click', () => { if (btn.classList.contains('active')) return; const layout = btn.dataset.layout; switchLayout('col-frame', colLayouts[layout], COLLECTION, layout, colPillUpdate, parseInt(btn.dataset.index), colBtns); document.querySelector('.tab-bar').scrollIntoView({ behavior: 'smooth', block: 'start' }); }); }); ``` -------------------------------- ### Collection renderers for podcast, channel, album, board, blog, and photos Source: https://playground.pubky.org/ Defines a set of renderer functions for different collection types (podcast, channel, album, board, blog, photos). Each function takes a data object and returns an HTML template string using template literals and the icon() helper. The code is incomplete at the end, cutting off in the photos renderer. ```javascript const colLayouts = { podcast(d) { return ` <div class="collection-frame"> <div class="pod-layout"> <div class="pod-top"> <div class="pod-cover" style="background:url(${d.cover}) center/cover"> <span class="cover-title">${d.name}</span> </div> <div class="pod-info"> <div class="pod-type">Podcast</div> <div class="pod-title">${d.name}</div> <div class="pod-creator">${d.creator.name}</div> <div class="pod-desc">${d.description}</div> <div class="pod-stats">${d.followers.toLocaleString()} followers · ${d.items.length} episodes</div> </div> </div> <div class="pod-divider"></div> <div class="pod-section-label">Episodes</div> <div class="pod-episodes"> ${d.items.map(it => ` <div class="pod-ep"> <div class="ep-play">${icon('play', 14)}</div> <div class="ep-info"> <div class="ep-title">${it.title}</div> <div class="ep-meta">${it.date}${it.duration ? ' · ' + it.duration : ''}</div> </div> <div class="ep-dur">${it.duration || '—'}</div> </div>`).join('')} </div> </div> </div>`; }, channel(d) { return ` <div class="collection-frame"> <div class="yt-layout"> <div class="yt-banner" style="background:url(${d.cover}) center/cover"> <span class="banner-title">${d.name}</span> </div> <div class="yt-channel-row"> ${av(d.creator, 44)} <div class="yt-channel-info"> <div class="ch-name">${d.creator.name}</div> <div class="ch-subs">${(d.followers / 1000).toFixed(1)}K subscribers</div> </div> <button class="yt-subscribe">Subscribe</button> </div> <div class="yt-tabs"> <div class="yt-tab active">Videos</div> <div class="yt-tab">About</div> </div> <div class="yt-grid"> ${d.items.map(it => ` <div class="yt-video"> <div class="yt-thumb" style="background:url(${it.image}) center/cover"> <span class="play-icon">${icon('play', 20)}</span> ${it.duration ? `<span class="dur-badge">${it.duration}</span>` : ''} </div> <div class="yt-vid-title">${it.title}</div> <div class="yt-vid-meta">${d.creator.name} · ${it.date}</div> </div>`).join('')} </div> </div> </div>`; }, album(d) { return ` <div class="collection-frame"> <div class="sp-layout"> <div class="sp-top"> <div class="sp-cover" style="background:url(${d.cover}) center/cover"> <span class="cover-title">${d.name}</span> </div> <div class="sp-info"> <div class="sp-type">Collection</div> <div class="sp-title">${d.name}</div> <div class="sp-creator-row"> ${av(d.creator, 22)} <span class="cr-name">${d.creator.name}</span> </div> <div class="sp-meta">2024 · ${d.items.length} tracks · ${d.followers.toLocaleString()} saves</div> <div class="sp-actions"> <button class="sp-play-btn">${icon('play', 20)}</button> <span class="sp-icon">${icon('heart', 22)}</span> <span class="sp-icon">···</span> </div> </div> </div> <div class="sp-divider"></div> <div class="sp-tracks"> ${d.items.map((it, i) => ` <div class="sp-track"> <span class="tr-num">${i + 1}</span> <div class="tr-info"> <div class="tr-title">${it.title}</div> <div class="tr-sub">${d.creator.name}</div> </div> <span class="tr-dur">${it.duration || '—'}</span> </div>`).join('')} </div> </div> </div>`; }, board(d) { return ` <div class="collection-frame"> <div class="pin-layout"> <div class="pin-header"> <div class="pin-title">${d.name}</div> <div class="pin-meta">${d.creator.name} · ${d.items.length} Pins · ${d.followers.toLocaleString()} followers</div> <div class="pin-desc">${d.description}</div> <div class="pin-tags-row">${d.tags.map(t => `<span class="tag-pill">${t}</span>`).join('')}</div> </div> <div class="pin-grid"> ${d.items.map(it => ` <div class="pin-card"> <div class="pin-img"> <img src="${it.image}" alt="${it.title}"> <span class="pin-label">${it.title}</span> <span class="pin-save">Save</span> </div> </div>`).join('')} </div> </div> </div>`; }, blog(d) { return ` <div class="collection-frame"> <div class="med-layout"> <div class="med-header"> <div class="med-title">${d.name}</div> <div class="med-desc">${d.description}</div> <div class="med-byline"> ${av(d.creator, 28)} <span class="by-name">${d.creator.name}</span> <span class="by-sep">·</span> <span class="by-follow">Follow</span> </div> </div> <div class="med-articles"> ${d.items.map(it => ` <div class="med-article"> <div class="art-title">${it.title}</div> <div class="art-preview">${it.desc}</div> <div class="art-meta"> <span>${it.date}</span> <span>·</span> <span>${it.duration || '3 min read'}</span> <span class="art-tag">${it.tag || d.tags[0]}</span> </div> </div>`).join('')} </div> </div> </div>`; }, photos(d) { return ` <div class="collection-frame"> <div class="gp-layout"> <div ``` -------------------------------- ### Lightbox and initial render for post/collection layouts Source: https://playground.pubky.org/ JavaScript for a lightbox modal: openLightbox sets the image source and adds an 'open' class while hiding body scroll; closeLightbox reverses it. An Escape key listener closes the lightbox. The second block renders post and collection layouts into frames and triggers code rendering functions. ```javascript window.openLightbox = function(src) { const lb = document.getElementById('lightbox'); document.getElementById('lightbox-img').src = src; lb.classList.add('open'); document.body.style.overflow = 'hidden'; }; window.closeLightbox = function() { const lb = document.getElementById('lightbox'); lb.classList.remove('open'); document.body.style.overflow = ''; }; document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeLightbox(); }); ``` ```javascript document.getElementById('post-frame').innerHTML = postLayouts.instagram(POST); document.getElementById('col-frame').innerHTML = colLayouts.podcast(COLLECTION); renderPostCode(); renderColCode(); ``` -------------------------------- ### Pubky post sample data (POST) Source: https://playground.pubky.org/ Sample post data object used to render a Pubky post in the demo UI. ```javascript const POST = { author: { name: 'Motoko Kusanagi', shortPk: 'gx9m...k4re', avatar: 'avatar.png', gradient: 'linear-gradient(135deg, #6366F1, #06B6D4)', initial: 'MK' }, content: 'If a technological feat is possible, man will do it. Almost as if it\'s wired into the core of our being.', title: 'Are you ready to unlock the web?', kind: 'short', media: { src: 'post-image.png', alt: 'Green glowing keyhole with crown' }, tags: [ { label: 'pubky', count: 17, color: '#34D399' }, { label: '💯', count: 7, color: '#60A5FA' }, { label: '❤️', count: 5, color: '#FF4D6A' }, { label: '🔥', count: 3, color: '#FF9500' }, ], timestamp: '2h', replies: 47, reposts: 3, community: 'Decentralized Systems' }; ``` -------------------------------- ### Pinterest board layout styles Source: https://playground.pubky.org/ CSS for a Pinterest-style board layout with a header, tag row, and responsive grid of cards. Cards scale on hover and reveal a save button. ```css /* ── Pinterest Board ── */ .pin-layout {} .pin-header { padding: 20px 20px 14px; text-align: center; } .pin-header .pin-title { font-family: var(--font-display); font-size: 1.5rem; font-weight: 700; margin-bottom: 4px; } .pin-header .pin-meta { font-size: 0.8rem; color: var(--text-3); margin-bottom: 6px; } .pin-header .pin-desc { font-size: 0.82rem; color: var(--text-2); margin-bottom: 8px; } .pin-tags-row { display: flex; gap: 6px; justify-content: center; } .pin-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px; padding: 10px 12px 16px; } .pin-card { border-radius: 12px; overflow: hidden; cursor: pointer; transition: transform 0.15s; } .pin-card:hover { transform: scale(1.02); } .pin-img { width: 100%; aspect-ratio: 3/4; display: flex; align-items: flex-end; padding: 10px; position: relative; overflow: hidden; background: var(--surface-2); } .pin-img img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; object-position: center; } .pin-img .pin-label { position: relative; z-index: 1; font-size: 0.75rem; font-weight: 600; color: #fff; text-shadow: 0 1px 6px rgba(0,0,0,0.6); line-height: 1.3; } .pin-save { z-index: 1; position: absolute; top: 8px; right: 8px; background: var(--red); color: #fff; padding: 4px 10px; border-radius: 16px; font-size: 0.7rem; font-weight: 700; opacity: 0; transition: opacity 0.15s; } .pin-card:hover .pin-save { opacity: 1; } ``` -------------------------------- ### Pubky UI helper functions: icon, isTextTag, av, renderTag Source: https://playground.pubky.org/ Utility functions for rendering SVG icons, detecting text tags, displaying author avatars, and rendering reaction tags in the Pubky demo UI. ```javascript function icon(name, size = 18) { const s = `<svg style="width:${size}px;height:${size}px;flex-shrink:0;vertical-align:middle" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`; const f = `<svg style="width:${size}px;height:${size}px;flex-shrink:0;vertical-align:middle" viewBox="0 0 24 24" fill="currentColor" stroke="none">`; const icons = { heart: s + '<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>', comment: s + '<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>', share: s + '<path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"/><polyline points="16 6 12 2 8 6"/><line x1="12" y1="2" x2="12" y2="15"/></svg>', bookmark: s + '<path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></svg>', repost: s + '<polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><polyline points="7 23 3 19 7 15"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>', tag: s + '<path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/></svg>', upvote: f + '<path d="M12 4l-7 7h4v9h6v-9h4z"/></svg>', downvote: f + '<path d="M12 20l7-7h-4V4H9v9H5z"/></svg>', music: f + '<path d="M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"/></svg>', play: f + '<polygon points="5 3 19 12 5 21 5 3"/></svg>', }; return icons[name] || ''; } ``` ```javascript const isTextTag = (t) => /^[a-z0-9-]+$/i.test(t.label); ``` ```javascript function av(author, size = 32) { if (author.avatar) { return `<div class="av" style="width:${size}px;height:${size}px"><img src="${author.avatar}" alt="${author.name}"></div>`; } return `<div class="av" style="width:${size}px;height:${size}px;background:${author.gradient}">${author.initial}</div>`; } ``` ```javascript function renderTag(tag) { return `<span class="reaction-tag" style="background:${tag.color}18;border-color:${tag.color}35;color:${tag.color}">${tag.label} <span class="tag-count">${tag.count}</span></span>`; } ``` -------------------------------- ### Medium blog layout styles Source: https://playground.pubky.org/ CSS for a Medium-style blog layout with a serif header, byline, and article list. Article previews are clamped to two lines. ```css /* ── Medium Blog ── */ .med-layout { padding: 32px 28px; } .med-header { margin-bottom: 24px; } .med-header .med-title { font-family: var(--font-serif); font-size: 1.9rem; font-weight: 700; line-height: 1.25; margin-bottom: 8px; } .med-header .med-desc { font-family: var(--font-serif); font-size: 1rem; color: var(--text-2); line-height: 1.5; font-style: italic; margin-bottom: 10px; } .med-byline { display: flex; align-items: center; gap: 10px; font-size: 0.82rem; } .med-byline .av { width: 28px; height: 28px; font-size: 0.55rem; } .med-byline .by-name { font-weight: 600; } .med-byline .by-sep { color: var(--text-3); } .med-byline .by-follow { color: var(--green); font-weight: 500; } .med-articles {} .med-article { padding: 20px 0; border-top: 1px solid var(--border); } .med-article .art-title { font-family: var(--font-serif); font-size: 1.2rem; font-weight: 600; margin-bottom: 6px; line-height: 1.3; } .med-article .art-preview { font-size: 0.88rem; color: var(--text-2); line-height: 1.5; margin-bottom: 8px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } .med-article .art-meta { display: flex; align-items: center; gap: 8px; font-size: 0.75rem; color: var(--text-3); } .med-article .art-tag { background: var(--surface-3); padding: 2px 8px; border-radius: 12px; font-size: 0.7rem; } ``` -------------------------------- ### Pubky collection sample data (COLLECTION) Source: https://playground.pubky.org/ Sample collection data object used to render a Pubky collection in the demo UI. ```javascript const COLLECTION = { name: 'The Atomic Economy', description: 'Rebuilding coordination from first principles — identity, markets, social intelligence, and the end of platform dependency.', creator: { name: 'Motoko Kusanagi', shortPk: 'gx9m...k4re', avatar: 'avatar.png', gradient: 'linear-gradient(135deg, #6366F1, #06B6D4)', initial: 'MK' }, cover: 'col-banner.png', followers: 2847, tags: ['sovereignty', 'coordination', 'pubky'], items: [ { title: 'The Atomic Economy Doctrine', kind: 'long', desc: 'Human society is a coordination system. When coordination is monopolized, violence fills the gap. ``` -------------------------------- ### Google Photos layout styles Source: https://playground.pubky.org/ CSS for a Google Photos-style grid layout with a header, date label, and a three-column photo grid. Photos are square and clickable. ```css /* ── Google Photos ── */ .gp-layout { padding: 0; } .gp-header { padding: 20px 20px 8px; } .gp-title { font-size: 1.3rem; font-weight: 600; margin-bottom: 2px; } .gp-meta { font-size: 0.8rem; color: var(--text-3); } .gp-date-label { padding: 10px 20px 8px; font-size: 0.78rem; font-weight: 600; color: var(--text-2); } .gp-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 2px; padding: 0 2px 2px; } .gp-photo { aspect-ratio: 1; cursor: pointer; transition: opacity 0.15s; } ``` -------------------------------- ### Subtitle and track duration styles Source: https://playground.pubky.org/ Styles for subtitle text and track duration in a music player interface. ```css .tr-sub { font-size: 0.75rem; color: var(--text-3); } .sp-track .tr-dur { font-size: 0.8rem; color: var(--text-3); } ``` -------------------------------- ### Switch layout with fade transition Source: https://playground.pubky.org/ Switches the content of a frame to a new layout by calling the provided render function. It adds a fading class, updates the active button and pill, then after 220ms replaces the innerHTML and removes the fading class. ```javascript function switchLayout(frameId, renderFn, data, layout, pillUpdater, btnIndex, btns) { const frame = document.getElementById(frameId); frame.classList.add('fading'); btns.forEach(b => b.classList.remove('active')); btns[btnIndex].classList.add('active'); pillUpdater(btnIndex); setTimeout(() => { frame.innerHTML = renderFn(data); requestAnimationFrame(() => { frame.classList.remove('fading'); }); }, 220); } ``` -------------------------------- ### renderColCode: display collection JSON and store code Source: https://playground.pubky.org/ Renders the JSON for a PubkyAppCollection and the beginning of code to store a collection on a homeserver using `@synonymdev/pubky`. The snippet is truncated in the source at `is_public: <span`. ```javascript function renderColCode() { const jsonBlock = `<span class="code-cm">// PubkyAppCollection (proposed spec)</span> <span class="code-cm">// /pub/pubky.app/collections/BLAKE3_HASH</span> ${syntaxJSON(COLLECTION_CANONICAL)} <span class="code-cm">// Items are post URIs (pubky:// addresses).</span> <span class="code-cm">// Posts are PubkyAppPost objects stored at</span> <span class="code-cm">// /pub/pubky.app/posts/TIMESTAMP_ID</span> <span class="code-cm">// Any user's posts can be in any collection.</span>`; const codeBlock = `<span class="code-kw">import</span> { Pubky } <span class="code-kw">from</span> <span class="code-str">"@synonymdev/pubky"</span>; <span class="code-cm">// Store a collection on your homeserver</span> <span class="code-kw">const</span> collection = { name: <span class="code-str">"${COLLECTION.name}"</span>, description: <span class="code-str">"Rebuilding coordination..."</span>, tags: [<span class="code-str">"sovereignty"</span>, <span class="code-str">"coordination"</span>], cover: <span class="code-str">"pubky://pk:gx9m.../blobs/COV3R"</span>, is_public: <span ``` -------------------------------- ### Tab switching and embed mode handling Source: https://playground.pubky.org/ Handles tab switching and embed mode. If the URL has ?embed=1, it activates the collection tab and adds an embed-mode class. Clicking a tab toggles the active panel and scrolls the tab bar into view; for the collection tab it also updates the pill after a short delay. ```javascript const tabBtns = document.querySelectorAll('.tab-btn'); const panels = document.querySelectorAll('.tab-panel'); const EMBED_MODE = new URLSearchParams(window.location.search).get('embed') === '1'; if (EMBED_MODE) { document.body.classList.add('embed-mode'); tabBtns.forEach(b => b.classList.remove('active')); panels.forEach(p => p.classList.remove('active')); const collectionTabBtn = document.querySelector('.tab-btn[data-tab="collection"]'); const collectionPanel = document.getElementById('panel-collection'); if (collectionTabBtn && collectionPanel) { collectionTabBtn.classList.add('active'); collectionPanel.classList.add('active'); } } // Tab switching tabBtns.forEach(btn => { btn.addEventListener('click', () => { const tab = btn.dataset.tab; tabBtns.forEach(b => b.classList.remove('active')); btn.classList.add('active'); panels.forEach(p => { p.classList.toggle('active', p.id === 'panel-' + tab); }); document.querySelector('.tab-bar').scrollIntoView({ behavior: 'smooth', block: 'start' }); if (tab === 'collection') { setTimeout(() => { const activeColBtn = document.querySelector('#col-switcher-track .switcher-btn.active'); if (activeColBtn) colPillUpdate(parseInt(activeColBtn.dataset.index)); }, 50); } }); }); ``` -------------------------------- ### Add pubky dependency with cargo add Source: https://pubky.org/ Use this command to add the pubky crate as a dependency to your Rust project. It is the first step in building applications for user sovereignty with Pubky. ```bash $ cargo add pubky ``` -------------------------------- ### Toggle expandable element Source: https://playground.pubky.org/ Defines a global toggleExpand function that toggles the 'open' class on the element with the given id, used for expandable sections. ```javascript window.toggleExpand = function(id) { document.getElementById(id).classList.toggle('open'); }; ```