simple new blog

This commit is contained in:
2026-01-15 17:19:43 +09:00
parent b344a0a760
commit cf46369cd0
52 changed files with 1590 additions and 3174 deletions

View File

@@ -1,211 +0,0 @@
use anyhow::{Context, Result};
use pulldown_cmark::{html, Parser};
use serde::{Deserialize, Serialize};
use std::fs;
use crate::config::Config;
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct ListRecordsResponse {
records: Vec<Record>,
cursor: Option<String>,
}
#[derive(Debug, Deserialize, Clone)]
#[allow(dead_code)]
struct Record {
uri: String,
cid: String,
value: PostRecord,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
struct PostRecord {
title: String,
content: String,
#[serde(rename = "createdAt")]
created_at: String,
}
pub async fn execute() -> Result<()> {
let mut config = Config::load()?;
// Refresh session before API calls
crate::refresh::refresh_session(&mut config).await?;
println!("Building static site from atproto records...");
let pds_url = format!("https://{}", config.pds);
let client = reqwest::Client::new();
// List records
let list_url = format!(
"{}/xrpc/com.atproto.repo.listRecords?repo={}&collection=ai.syui.log.post&limit=100",
pds_url, config.did
);
let res: ListRecordsResponse = client
.get(&list_url)
.send()
.await
.context("Failed to list records")?
.json()
.await
.context("Failed to parse listRecords response")?;
println!("Found {} posts", res.records.len());
// Create output directory
fs::create_dir_all("./public")?;
fs::create_dir_all("./public/posts")?;
// Generate index.html
let mut index_html = String::from(
r#"<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Blog Posts</title>
<style>
body { font-family: sans-serif; max-width: 800px; margin: 0 auto; padding: 2rem; }
.nav { margin-bottom: 2rem; padding: 1rem; background: #f5f5f5; border-radius: 4px; }
.nav a { margin-right: 1rem; color: #0066cc; text-decoration: none; }
.nav a:hover { text-decoration: underline; }
</style>
</head>
<body>
<div class="nav">
<a href="/pds/">🔍 PDS Browser</a>
</div>
<h1>Posts</h1>
<ul>
"#,
);
for record in &res.records {
let rkey = record.uri.split('/').last().unwrap();
index_html.push_str(&format!(
r#" <li><a href="/posts/{}.html">{}</a></li>
"#,
rkey, record.value.title
));
// Generate individual post page
let parser = Parser::new(&record.value.content);
let mut html_output = String::new();
html::push_html(&mut html_output, parser);
let post_html = format!(
r#"<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{}</title>
</head>
<body>
<h1>{}</h1>
<div>{}</div>
<p><a href="/">← Back to list</a></p>
</body>
</html>"#,
record.value.title, record.value.title, html_output
);
fs::write(format!("./public/posts/{}.html", rkey), post_html)?;
println!(" ✓ Generated: posts/{}.html", rkey);
}
index_html.push_str(
r#" </ul>
</body>
</html>"#,
);
fs::write("./public/index.html", index_html)?;
println!(" ✓ Generated: index.html");
// Build browser app
println!("\nBuilding AT Browser...");
build_browser().await?;
println!("\nDone! Site generated in ./public/");
println!(" - Blog: ./public/index.html");
println!(" - PDS Browser: ./public/pds/index.html");
Ok(())
}
async fn build_browser() -> Result<()> {
use std::process::Command;
let browser_dir = "./pds";
// Check if pds directory exists
if !std::path::Path::new(browser_dir).exists() {
println!(" ⚠ PDS directory not found, skipping");
return Ok(());
}
// Run npm install if node_modules doesn't exist
if !std::path::Path::new(&format!("{}/node_modules", browser_dir)).exists() {
println!(" → Running npm install...");
let status = Command::new("npm")
.arg("install")
.current_dir(browser_dir)
.status()
.context("Failed to run npm install")?;
if !status.success() {
anyhow::bail!("npm install failed");
}
}
// Run npm run build
println!(" → Running npm run build...");
let status = Command::new("npm")
.arg("run")
.arg("build")
.current_dir(browser_dir)
.status()
.context("Failed to run npm run build")?;
if !status.success() {
anyhow::bail!("npm run build failed");
}
// Copy dist to public/pds
let dist_dir = format!("{}/dist", browser_dir);
let target_dir = "./public/pds";
if std::path::Path::new(&dist_dir).exists() {
fs::create_dir_all(target_dir)?;
copy_dir_all(&dist_dir, target_dir)?;
println!(" ✓ PDS browser deployed to ./public/pds/");
} else {
println!(" ⚠ dist directory not found");
}
Ok(())
}
fn copy_dir_all(src: &str, dst: &str) -> Result<()> {
use walkdir::WalkDir;
for entry in WalkDir::new(src) {
let entry = entry?;
let path = entry.path();
let relative = path.strip_prefix(src)?;
let target = std::path::Path::new(dst).join(relative);
if path.is_dir() {
fs::create_dir_all(&target)?;
} else {
if let Some(parent) = target.parent() {
fs::create_dir_all(parent)?;
}
fs::copy(path, &target)?;
}
}
Ok(())
}

140
src/components/atbrowser.ts Normal file
View File

@@ -0,0 +1,140 @@
import { describeRepo, listRecordsRaw, getRecordRaw, fetchLexicon, resolveHandle, getServiceInfo } from '../lib/api.js'
function extractRkey(uri: string): string {
const parts = uri.split('/')
return parts[parts.length - 1]
}
function formatDate(dateStr: string): string {
const date = new Date(dateStr)
return date.toLocaleDateString('ja-JP', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
})
}
function escapeHtml(str: string): string {
return str
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
}
async function renderCollections(did: string, handle: string): Promise<string> {
const collections = await describeRepo(did)
if (collections.length === 0) {
return '<p class="no-data">No collections found</p>'
}
const items = collections.map(col => {
const service = getServiceInfo(col)
const favicon = service ? `<img src="${service.favicon}" class="collection-favicon" alt="" onerror="this.style.display='none'">` : ''
const serviceName = service ? `<span class="collection-service">${service.name}</span>` : ''
return `
<li class="collection-item">
<a href="?mode=browser&handle=${handle}&collection=${encodeURIComponent(col)}" class="collection-link">
${favicon}
<span class="collection-nsid">${col}</span>
${serviceName}
</a>
</li>
`
}).join('')
return `
<div class="collections">
<h3>Collections</h3>
<ul class="collection-list">${items}</ul>
</div>
`
}
async function renderRecordList(did: string, handle: string, collection: string): Promise<string> {
const records = await listRecordsRaw(did, collection)
if (records.length === 0) {
return '<p class="no-data">No records found</p>'
}
const items = records.map(rec => {
const rkey = extractRkey(rec.uri)
const preview = rec.value.title || rec.value.text?.slice(0, 50) || rkey
return `
<li class="record-item">
<a href="?mode=browser&handle=${handle}&collection=${encodeURIComponent(collection)}&rkey=${rkey}" class="record-link">
<span class="record-rkey">${rkey}</span>
<span class="record-preview">${preview}</span>
</a>
</li>
`
}).join('')
return `
<div class="records">
<h3>${collection}</h3>
<p class="record-count">${records.length} records</p>
<ul class="record-list">${items}</ul>
</div>
`
}
async function renderRecordDetail(did: string, handle: string, collection: string, rkey: string): Promise<string> {
const record = await getRecordRaw(did, collection, rkey)
if (!record) {
return '<p class="error">Record not found</p>'
}
const lexicon = await fetchLexicon(collection)
const schemaStatus = lexicon ? 'verified' : 'none'
const schemaLabel = lexicon ? '✓ Schema' : '○ No schema'
const json = JSON.stringify(record, null, 2)
return `
<div class="record-detail">
<div class="record-header">
<h3>${collection}</h3>
<p class="record-uri">${record.uri}</p>
<p class="record-cid">CID: ${record.cid}</p>
<span class="schema-status schema-${schemaStatus}">${schemaLabel}</span>
</div>
<div class="json-view">
<pre><code>${escapeHtml(json)}</code></pre>
</div>
</div>
`
}
export async function mountAtBrowser(
container: HTMLElement,
handle: string,
collection: string | null,
rkey: string | null
): Promise<void> {
container.innerHTML = '<p class="loading">Loading...</p>'
try {
const did = handle.startsWith('did:') ? handle : await resolveHandle(handle)
let content: string
let nav = ''
if (collection && rkey) {
nav = `<a href="?mode=browser&handle=${handle}&collection=${encodeURIComponent(collection)}" class="back-link">← Back</a>`
content = await renderRecordDetail(did, handle, collection, rkey)
} else if (collection) {
nav = `<a href="?mode=browser&handle=${handle}" class="back-link">← Collections</a>`
content = await renderRecordList(did, handle, collection)
} else {
content = await renderCollections(did, handle)
}
container.innerHTML = nav + content
} catch (err) {
container.innerHTML = `<p class="error">Failed to load: ${err}</p>`
}
}

89
src/components/browser.ts Normal file
View File

@@ -0,0 +1,89 @@
export function renderHeader(currentHandle: string, isLoggedIn: boolean, userHandle?: string): string {
const loginBtn = isLoggedIn
? `<button type="button" class="header-btn user-btn" id="user-btn" title="${userHandle}">
<svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z"/>
</svg>
</button>`
: `<button type="button" class="header-btn login-btn" id="login-btn" title="Login">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/>
<polyline points="10 17 15 12 10 7"/>
<line x1="15" y1="12" x2="3" y2="12"/>
</svg>
</button>`
return `
<div class="header">
<form class="header-form" id="header-form">
<input
type="text"
class="header-input"
id="header-input"
placeholder="handle (e.g., syui.ai)"
value="${currentHandle}"
>
<button type="submit" class="header-btn at-btn" title="Browse">@</button>
${loginBtn}
</form>
</div>
`
}
export interface HeaderCallbacks {
onBrowse: (handle: string) => void
onLogin: () => void
onLogout: () => void
}
export function mountHeader(
container: HTMLElement,
currentHandle: string,
isLoggedIn: boolean,
userHandle: string | undefined,
callbacks: HeaderCallbacks
): void {
container.innerHTML = renderHeader(currentHandle, isLoggedIn, userHandle)
const form = document.getElementById('header-form') as HTMLFormElement
const input = document.getElementById('header-input') as HTMLInputElement
form.addEventListener('submit', (e) => {
e.preventDefault()
const handle = input.value.trim()
if (handle) {
callbacks.onBrowse(handle)
}
})
if (isLoggedIn) {
const userBtn = document.getElementById('user-btn')
userBtn?.addEventListener('click', async (e) => {
e.preventDefault()
e.stopPropagation()
if (confirm('Logout?')) {
await callbacks.onLogout()
}
})
} else {
const loginBtn = document.getElementById('login-btn')
loginBtn?.addEventListener('click', (e) => {
e.preventDefault()
e.stopPropagation()
callbacks.onLogin()
})
}
}
// Keep old function for compatibility
export function mountBrowser(
container: HTMLElement,
currentHandle: string,
onSubmit: (handle: string) => void
): void {
mountHeader(container, currentHandle, false, undefined, {
onBrowse: onSubmit,
onLogin: () => {},
onLogout: () => {}
})
}

View File

@@ -0,0 +1,74 @@
import { createPost } from '../lib/auth.js'
export function renderPostForm(collection: string): string {
return `
<div class="post-form-container">
<h3>New Post</h3>
<form class="post-form" id="post-form">
<input
type="text"
class="post-form-title"
id="post-title"
placeholder="Title"
required
>
<textarea
class="post-form-body"
id="post-body"
placeholder="Content"
rows="6"
required
></textarea>
<div class="post-form-footer">
<span class="post-form-collection">${collection}</span>
<button type="submit" class="post-form-btn" id="post-submit">Post</button>
</div>
</form>
<div id="post-status" class="post-status"></div>
</div>
`
}
export function mountPostForm(
container: HTMLElement,
collection: string,
onSuccess: () => void
): void {
container.innerHTML = renderPostForm(collection)
const form = document.getElementById('post-form') as HTMLFormElement
const titleInput = document.getElementById('post-title') as HTMLInputElement
const bodyInput = document.getElementById('post-body') as HTMLTextAreaElement
const submitBtn = document.getElementById('post-submit') as HTMLButtonElement
const statusEl = document.getElementById('post-status') as HTMLDivElement
form.addEventListener('submit', async (e) => {
e.preventDefault()
const title = titleInput.value.trim()
const body = bodyInput.value.trim()
if (!title || !body) return
submitBtn.disabled = true
submitBtn.textContent = 'Posting...'
statusEl.innerHTML = ''
try {
const result = await createPost(collection, title, body)
if (result) {
statusEl.innerHTML = `<span class="post-success">Posted successfully!</span>`
titleInput.value = ''
bodyInput.value = ''
setTimeout(() => {
onSuccess()
}, 1000)
}
} catch (err) {
statusEl.innerHTML = `<span class="post-error">Error: ${err}</span>`
} finally {
submitBtn.disabled = false
submitBtn.textContent = 'Post'
}
})
}

54
src/components/posts.ts Normal file
View File

@@ -0,0 +1,54 @@
import type { BlogPost } from '../types.js'
function formatDate(dateStr: string): string {
const date = new Date(dateStr)
return date.toLocaleDateString('ja-JP', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
})
}
function escapeHtml(str: string): string {
return str
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
}
export function mountPostList(container: HTMLElement, posts: BlogPost[]): void {
if (posts.length === 0) {
container.innerHTML = '<p class="no-posts">No posts yet</p>'
return
}
const html = posts.map(post => {
const rkey = post.uri.split('/').pop()
return `
<li class="post-item">
<a href="?rkey=${rkey}" class="post-link">
<span class="post-title">${escapeHtml(post.title)}</span>
<span class="post-date">${formatDate(post.createdAt)}</span>
</a>
</li>
`
}).join('')
container.innerHTML = `<ul class="post-list">${html}</ul>`
}
export function mountPostDetail(container: HTMLElement, post: BlogPost, handle: string): void {
container.innerHTML = `
<article class="post-detail">
<header class="post-header">
<h1 class="post-title">${escapeHtml(post.title)}</h1>
<time class="post-date">${formatDate(post.createdAt)}</time>
</header>
<div class="post-content">${escapeHtml(post.content)}</div>
<footer class="post-footer">
<a href="?handle=${handle}" class="back-link">← Back to posts</a>
</footer>
</article>
`
}

18
src/components/profile.ts Normal file
View File

@@ -0,0 +1,18 @@
import type { Profile } from '../types.js'
export function renderProfile(profile: Profile): string {
return `
<div class="profile">
${profile.avatar ? `<img src="${profile.avatar}" alt="avatar" class="profile-avatar">` : ''}
<div class="profile-info">
<h1 class="profile-name">${profile.displayName || profile.handle}</h1>
<p class="profile-handle">@${profile.handle}</p>
${profile.description ? `<p class="profile-desc">${profile.description}</p>` : ''}
</div>
</div>
`
}
export function mountProfile(container: HTMLElement, profile: Profile): void {
container.innerHTML = renderProfile(profile)
}

View File

@@ -1,71 +0,0 @@
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
pub pds: String,
pub handle: String,
pub did: String,
pub access_jwt: String,
pub refresh_jwt: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct RecordMapping {
pub rkey: String,
pub uri: String,
pub cid: String,
}
pub type Mapping = HashMap<String, RecordMapping>;
impl Config {
pub fn config_path() -> Result<PathBuf> {
let home = dirs::home_dir().context("Failed to get home directory")?;
let config_dir = home.join(".config/syui/ai/log");
std::fs::create_dir_all(&config_dir)?;
Ok(config_dir.join("config.json"))
}
pub fn mapping_path() -> Result<PathBuf> {
let home = dirs::home_dir().context("Failed to get home directory")?;
let config_dir = home.join(".config/syui/ai/log");
std::fs::create_dir_all(&config_dir)?;
Ok(config_dir.join("mapping.json"))
}
pub fn load() -> Result<Self> {
let path = Self::config_path()?;
let content = std::fs::read_to_string(&path)
.context("Failed to read config file. Please run 'ailog login' first.")?;
let config: Config = serde_json::from_str(&content)?;
Ok(config)
}
pub fn save(&self) -> Result<()> {
let path = Self::config_path()?;
let content = serde_json::to_string_pretty(self)?;
std::fs::write(&path, content)?;
println!("Config saved to: {}", path.display());
Ok(())
}
pub fn load_mapping() -> Result<Mapping> {
let path = Self::mapping_path()?;
if !path.exists() {
return Ok(HashMap::new());
}
let content = std::fs::read_to_string(&path)?;
let mapping: Mapping = serde_json::from_str(&content)?;
Ok(mapping)
}
pub fn save_mapping(mapping: &Mapping) -> Result<()> {
let path = Self::mapping_path()?;
let content = serde_json::to_string_pretty(mapping)?;
std::fs::write(&path, content)?;
Ok(())
}
}

View File

@@ -1,89 +0,0 @@
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use crate::config::Config;
#[derive(Debug, Serialize)]
struct DeleteRecordRequest {
repo: String,
collection: String,
rkey: String,
}
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct ListRecordsResponse {
records: Vec<Record>,
cursor: Option<String>,
}
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct Record {
uri: String,
}
pub async fn execute() -> Result<()> {
let mut config = Config::load()?;
// Refresh session before API calls
crate::refresh::refresh_session(&mut config).await?;
let mut mapping = Config::load_mapping()?;
println!("Deleting all records from ai.syui.log.post...");
let pds_url = format!("https://{}", config.pds);
let client = reqwest::Client::new();
// List all records
let list_url = format!(
"{}/xrpc/com.atproto.repo.listRecords?repo={}&collection=ai.syui.log.post&limit=100",
pds_url, config.did
);
let res: ListRecordsResponse = client
.get(&list_url)
.send()
.await
.context("Failed to list records")?
.json()
.await
.context("Failed to parse listRecords response")?;
if res.records.is_empty() {
println!("No records to delete.");
return Ok(());
}
println!("Found {} records to delete", res.records.len());
// Delete each record
for record in &res.records {
let rkey = record.uri.split('/').last().unwrap();
let delete_req = DeleteRecordRequest {
repo: config.did.clone(),
collection: "ai.syui.log.post".to_string(),
rkey: rkey.to_string(),
};
let delete_url = format!("{}/xrpc/com.atproto.repo.deleteRecord", pds_url);
client
.post(&delete_url)
.header("Authorization", format!("Bearer {}", config.access_jwt))
.json(&delete_req)
.send()
.await
.context("Failed to delete record")?;
println!(" ✓ Deleted: {}", rkey);
}
// Clear mapping (all records deleted)
mapping.clear();
Config::save_mapping(&mapping)?;
println!("Mapping cleared.");
println!("Done! All records deleted.");
Ok(())
}

217
src/lib/api.ts Normal file
View File

@@ -0,0 +1,217 @@
import { AtpAgent } from '@atproto/api'
import type { Profile, BlogPost, NetworkConfig } from '../types.js'
const agents: Map<string, AtpAgent> = new Map()
let networkConfig: NetworkConfig | null = null
export function setNetworkConfig(config: NetworkConfig): void {
networkConfig = config
}
function getPlc(): string {
return networkConfig?.plc || 'https://plc.directory'
}
function getBsky(): string {
return networkConfig?.bsky || 'https://public.api.bsky.app'
}
export function getAgent(service: string): AtpAgent {
if (!agents.has(service)) {
agents.set(service, new AtpAgent({ service }))
}
return agents.get(service)!
}
export async function resolvePds(did: string): Promise<string> {
const res = await fetch(`${getPlc()}/${did}`)
const doc = await res.json()
const service = doc.service?.find((s: any) => s.type === 'AtprotoPersonalDataServer')
return service?.serviceEndpoint || getBsky()
}
export async function resolveHandle(handle: string): Promise<string> {
const agent = getAgent(getBsky())
const res = await agent.resolveHandle({ handle })
return res.data.did
}
export async function getProfile(actor: string): Promise<Profile> {
const agent = getAgent(getBsky())
const res = await agent.getProfile({ actor })
return {
did: res.data.did,
handle: res.data.handle,
displayName: res.data.displayName,
description: res.data.description,
avatar: res.data.avatar,
banner: res.data.banner,
}
}
export async function listRecords(
did: string,
collection: string,
limit = 50
): Promise<BlogPost[]> {
const pds = await resolvePds(did)
const agent = getAgent(pds)
const res = await agent.com.atproto.repo.listRecords({
repo: did,
collection,
limit,
})
return res.data.records.map((record: any) => ({
uri: record.uri,
cid: record.cid,
title: record.value.title || '',
content: record.value.content || '',
createdAt: record.value.createdAt || '',
}))
}
export async function getRecord(
did: string,
collection: string,
rkey: string
): Promise<BlogPost | null> {
const pds = await resolvePds(did)
const agent = getAgent(pds)
try {
const res = await agent.com.atproto.repo.getRecord({
repo: did,
collection,
rkey,
})
return {
uri: res.data.uri,
cid: res.data.cid || '',
title: (res.data.value as any).title || '',
content: (res.data.value as any).content || '',
createdAt: (res.data.value as any).createdAt || '',
}
} catch {
return null
}
}
export async function describeRepo(did: string): Promise<string[]> {
const pds = await resolvePds(did)
const agent = getAgent(pds)
const res = await agent.com.atproto.repo.describeRepo({ repo: did })
return res.data.collections || []
}
export async function listRecordsRaw(
did: string,
collection: string,
limit = 100
): Promise<any[]> {
const pds = await resolvePds(did)
const agent = getAgent(pds)
const res = await agent.com.atproto.repo.listRecords({
repo: did,
collection,
limit,
})
return res.data.records
}
export async function getRecordRaw(
did: string,
collection: string,
rkey: string
): Promise<any | null> {
const pds = await resolvePds(did)
const agent = getAgent(pds)
try {
const res = await agent.com.atproto.repo.getRecord({
repo: did,
collection,
rkey,
})
return res.data
} catch {
return null
}
}
// Known lexicon prefixes that have schemas
const KNOWN_LEXICON_PREFIXES = [
'app.bsky.',
'chat.bsky.',
'com.atproto.',
'sh.tangled.',
'pub.leaflet.',
'blue.linkat.',
'fyi.unravel.frontpage.',
'com.whtwnd.',
'com.shinolabs.pinksea.',
]
export function hasKnownSchema(nsid: string): boolean {
return KNOWN_LEXICON_PREFIXES.some(prefix => nsid.startsWith(prefix))
}
export async function fetchLexicon(nsid: string): Promise<any | null> {
// Check if it's a known lexicon first
if (hasKnownSchema(nsid)) {
return { id: nsid, known: true }
}
// Extract authority from NSID (e.g., "ai.syui.log.post" -> "syui.ai")
const parts = nsid.split('.')
if (parts.length < 3) return null
const authority = parts.slice(0, 2).reverse().join('.')
const url = `https://${authority}/.well-known/lexicon/${nsid}.json`
try {
const res = await fetch(url)
if (!res.ok) return null
return await res.json()
} catch {
return null
}
}
// Known service mappings for collections
const SERVICE_MAP: Record<string, { name: string; domain: string; icon?: string }> = {
'app.bsky': { name: 'Bluesky', domain: 'bsky.app', icon: 'https://bsky.app/static/favicon-32x32.png' },
'ai.syui': { name: 'syui.ai', domain: 'syui.ai' },
'com.whtwnd': { name: 'WhiteWind', domain: 'whtwnd.com' },
'fyi.unravel.frontpage': { name: 'Frontpage', domain: 'frontpage.fyi' },
'com.shinolabs.pinksea': { name: 'PinkSea', domain: 'pinksea.art' },
'blue.linkat': { name: 'Linkat', domain: 'linkat.blue' },
'sh.tangled': { name: 'Tangled', domain: 'tangled.sh' },
'pub.leaflet': { name: 'Leaflet', domain: 'leaflet.pub' },
'chat.bsky': { name: 'Bluesky Chat', domain: 'bsky.app' },
}
export function getServiceInfo(collection: string): { name: string; domain: string; favicon: string } | null {
// Try to find matching service prefix
for (const [prefix, info] of Object.entries(SERVICE_MAP)) {
if (collection.startsWith(prefix)) {
return {
name: info.name,
domain: info.domain,
favicon: info.icon || `https://www.google.com/s2/favicons?domain=${info.domain}&sz=32`
}
}
}
// Fallback: extract domain from first 2 parts of NSID
const parts = collection.split('.')
if (parts.length >= 2) {
const domain = parts.slice(0, 2).reverse().join('.')
return {
name: domain,
domain: domain,
favicon: `https://www.google.com/s2/favicons?domain=${domain}&sz=32`
}
}
return null
}

147
src/lib/auth.ts Normal file
View File

@@ -0,0 +1,147 @@
import { BrowserOAuthClient } from '@atproto/oauth-client-browser'
import { Agent } from '@atproto/api'
import type { NetworkConfig } from '../types.js'
let oauthClient: BrowserOAuthClient | null = null
let agent: Agent | null = null
let currentNetworkConfig: NetworkConfig | null = null
export interface AuthSession {
did: string
handle: string
agent: Agent
}
export function setAuthNetworkConfig(config: NetworkConfig): void {
currentNetworkConfig = config
// Reset client when network changes
oauthClient = null
}
export async function initOAuthClient(): Promise<BrowserOAuthClient> {
if (oauthClient) return oauthClient
const handleResolver = currentNetworkConfig?.bsky || 'https://bsky.social'
const plcDirectoryUrl = currentNetworkConfig?.plc || 'https://plc.directory'
oauthClient = await BrowserOAuthClient.load({
clientId: getClientId(),
handleResolver,
plcDirectoryUrl,
})
return oauthClient
}
function getClientId(): string {
const host = window.location.host
// For localhost development
if (host.includes('localhost') || host.includes('127.0.0.1')) {
// client_id must start with http://localhost, redirect_uri must use 127.0.0.1
const port = window.location.port || '3000'
const redirectUri = `http://127.0.0.1:${port}/`
return `http://localhost?redirect_uri=${encodeURIComponent(redirectUri)}&scope=${encodeURIComponent('atproto transition:generic')}`
}
// For production, use the client-metadata.json
return `${window.location.origin}/client-metadata.json`
}
export async function login(handle: string): Promise<void> {
const client = await initOAuthClient()
await client.signIn(handle, {
scope: 'atproto transition:generic',
})
}
export async function handleOAuthCallback(): Promise<AuthSession | null> {
const params = new URLSearchParams(window.location.search)
if (!params.has('code') && !params.has('state')) {
return null
}
try {
const client = await initOAuthClient()
const result = await client.callback(params)
agent = new Agent(result.session)
// Get profile to get handle
const profile = await agent.getProfile({ actor: result.session.did })
// Clear URL params
window.history.replaceState({}, '', window.location.pathname)
return {
did: result.session.did,
handle: profile.data.handle,
agent,
}
} catch (err) {
console.error('OAuth callback error:', err)
return null
}
}
export async function restoreSession(): Promise<AuthSession | null> {
try {
const client = await initOAuthClient()
const result = await client.init()
if (result?.session) {
agent = new Agent(result.session)
const profile = await agent.getProfile({ actor: result.session.did })
return {
did: result.session.did,
handle: profile.data.handle,
agent,
}
}
} catch (err) {
console.error('Session restore error:', err)
}
return null
}
export async function logout(): Promise<void> {
// Clear all storage
sessionStorage.clear()
localStorage.clear()
// Clear IndexedDB (used by OAuth client)
const databases = await indexedDB.databases()
for (const db of databases) {
if (db.name) {
indexedDB.deleteDatabase(db.name)
}
}
agent = null
oauthClient = null
}
export function getAgent(): Agent | null {
return agent
}
export async function createPost(collection: string, title: string, content: string): Promise<{ uri: string; cid: string } | null> {
if (!agent) return null
try {
const result = await agent.com.atproto.repo.createRecord({
repo: agent.assertDid,
collection,
record: {
$type: collection,
title,
content,
createdAt: new Date().toISOString(),
},
})
return { uri: result.data.uri, cid: result.data.cid }
} catch (err) {
console.error('Create post error:', err)
throw err
}
}

View File

@@ -1,83 +0,0 @@
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use crate::config::Config;
#[derive(Debug, Serialize)]
struct CreateSessionRequest {
identifier: String,
password: String,
}
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct CreateSessionResponse {
#[serde(rename = "accessJwt")]
access_jwt: String,
#[serde(rename = "refreshJwt")]
refresh_jwt: String,
handle: String,
did: String,
}
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct DescribeRepoResponse {
handle: String,
did: String,
}
pub async fn execute(handle: &str, password: &str, pds: &str) -> Result<()> {
println!("Logging in as {} to {}...", handle, pds);
// Resolve handle to DID
let pds_url = format!("https://{}", pds);
let describe_url = format!(
"{}/xrpc/com.atproto.repo.describeRepo?repo={}",
pds_url, handle
);
let client = reqwest::Client::new();
let describe_res: DescribeRepoResponse = client
.get(&describe_url)
.send()
.await
.context("Failed to resolve handle")?
.json()
.await
.context("Failed to parse describeRepo response")?;
println!("Resolved handle to DID: {}", describe_res.did);
// Create session
let session_url = format!("{}/xrpc/com.atproto.server.createSession", pds_url);
let session_req = CreateSessionRequest {
identifier: handle.to_string(),
password: password.to_string(),
};
let session_res: CreateSessionResponse = client
.post(&session_url)
.json(&session_req)
.send()
.await
.context("Failed to create session")?
.json()
.await
.context("Failed to parse createSession response")?;
println!("Successfully authenticated!");
// Save config
let config = Config {
pds: pds.to_string(),
handle: handle.to_string(),
did: session_res.did,
access_jwt: session_res.access_jwt,
refresh_jwt: session_res.refresh_jwt,
};
config.save()?;
Ok(())
}

View File

@@ -1,75 +0,0 @@
use anyhow::Result;
use clap::{Parser, Subcommand};
mod config;
mod login;
mod post;
mod build;
mod delete;
mod refresh;
mod serve;
#[derive(Parser)]
#[command(name = "ailog")]
#[command(about = "A simple static blog generator with atproto integration")]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Login to atproto PDS
#[command(alias = "l")]
Login {
/// Handle (e.g., ai.syui.ai)
handle: String,
/// Password
#[arg(short, long)]
password: String,
/// PDS server (e.g., syu.is, bsky.social)
#[arg(short = 's', long, default_value = "syu.is")]
pds: String,
},
/// Post markdown files to atproto
#[command(alias = "p")]
Post,
/// Build static site from atproto records
#[command(alias = "b")]
Build,
/// Delete all records from atproto
#[command(alias = "d")]
Delete,
/// Start local preview server
#[command(alias = "s")]
Serve {
/// Port number
#[arg(short, long, default_value = "3000")]
port: u16,
},
}
#[tokio::main]
async fn main() -> Result<()> {
let cli = Cli::parse();
match cli.command {
Commands::Login { handle, password, pds } => {
login::execute(&handle, &password, &pds).await?;
}
Commands::Post => {
post::execute().await?;
}
Commands::Build => {
build::execute().await?;
}
Commands::Delete => {
delete::execute().await?;
}
Commands::Serve { port } => {
serve::execute(port).await?;
}
}
Ok(())
}

158
src/main.ts Normal file
View File

@@ -0,0 +1,158 @@
import { getProfile, listRecords, getRecord, setNetworkConfig } from './lib/api.js'
import { login, logout, restoreSession, handleOAuthCallback, setAuthNetworkConfig, type AuthSession } from './lib/auth.js'
import { mountProfile } from './components/profile.js'
import { mountPostList, mountPostDetail } from './components/posts.js'
import { mountHeader } from './components/browser.js'
import { mountAtBrowser } from './components/atbrowser.js'
import { mountPostForm } from './components/postform.js'
import type { AppConfig, Networks } from './types.js'
let authSession: AuthSession | null = null
async function loadConfig(): Promise<AppConfig> {
const res = await fetch('/config.json')
return res.json()
}
async function loadNetworks(): Promise<Networks> {
const res = await fetch('/networks.json')
return res.json()
}
function renderFooter(handle: string): string {
const parts = handle.split('.')
const username = parts[0] || handle
return `
<footer class="site-footer">
<p>&copy; ${username}</p>
</footer>
`
}
function renderTabs(handle: string, mode: string | null, isLoggedIn: boolean): string {
const blogActive = !mode || mode === 'blog' ? 'active' : ''
const browserActive = mode === 'browser' ? 'active' : ''
const postActive = mode === 'post' ? 'active' : ''
let tabs = `
<a href="?handle=${handle}" class="tab ${blogActive}">Blog</a>
<a href="?mode=browser&handle=${handle}" class="tab ${browserActive}">Browser</a>
`
if (isLoggedIn) {
tabs += `<a href="?mode=post&handle=${handle}" class="tab ${postActive}">Post</a>`
}
return `<div class="mode-tabs">${tabs}</div>`
}
async function init(): Promise<void> {
const [config, networks] = await Promise.all([loadConfig(), loadNetworks()])
// Set page title
document.title = config.title || 'ailog'
// Set network config
const networkConfig = networks[config.network]
if (networkConfig) {
setNetworkConfig(networkConfig)
setAuthNetworkConfig(networkConfig)
}
// Handle OAuth callback
const callbackSession = await handleOAuthCallback()
if (callbackSession) {
authSession = callbackSession
} else {
// Try to restore existing session
authSession = await restoreSession()
}
const params = new URLSearchParams(window.location.search)
const mode = params.get('mode')
const rkey = params.get('rkey')
const collection = params.get('collection')
const handle = params.get('handle') || config.handle
const profileEl = document.getElementById('profile')
const contentEl = document.getElementById('content')
const headerEl = document.getElementById('header')
const footerEl = document.getElementById('footer')
if (!profileEl || !contentEl || !headerEl) return
// Footer
if (footerEl) {
footerEl.innerHTML = renderFooter(config.handle)
}
const isLoggedIn = !!authSession
// Header with login
mountHeader(headerEl, handle, isLoggedIn, authSession?.handle, {
onBrowse: (newHandle) => {
const currentMode = params.get('mode')
if (currentMode === 'browser') {
window.location.href = `?mode=browser&handle=${newHandle}`
} else {
window.location.href = `?handle=${newHandle}`
}
},
onLogin: async () => {
const inputHandle = (document.getElementById('header-input') as HTMLInputElement)?.value || handle
try {
await login(inputHandle)
} catch (err) {
console.error('Login error:', err)
alert('Login failed: ' + err)
}
},
onLogout: async () => {
await logout()
window.location.reload()
}
})
// Post mode (requires login)
if (mode === 'post' && isLoggedIn) {
profileEl.innerHTML = renderTabs(handle, mode, isLoggedIn)
mountPostForm(contentEl, config.collection, () => {
window.location.href = `?handle=${handle}`
})
return
}
// AT Browser mode
if (mode === 'browser') {
profileEl.innerHTML = renderTabs(handle, mode, isLoggedIn)
await mountAtBrowser(contentEl, handle, collection, rkey)
return
}
// Blog mode (default)
try {
const profile = await getProfile(handle)
profileEl.innerHTML = renderTabs(handle, mode, isLoggedIn)
const profileContentEl = document.createElement('div')
profileEl.appendChild(profileContentEl)
mountProfile(profileContentEl, profile)
if (rkey) {
const post = await getRecord(profile.did, config.collection, rkey)
if (post) {
mountPostDetail(contentEl, post, handle)
} else {
contentEl.innerHTML = '<p>Post not found</p>'
}
} else {
const posts = await listRecords(profile.did, config.collection)
mountPostList(contentEl, posts)
}
} catch (err) {
console.error(err)
contentEl.innerHTML = `<p class="error">Failed to load: ${err}</p>`
}
}
init()

View File

@@ -1,172 +0,0 @@
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use walkdir::WalkDir;
use crate::config::{Config, RecordMapping};
#[derive(Debug, Serialize)]
struct PutRecordRequest {
repo: String,
collection: String,
#[serde(skip_serializing_if = "Option::is_none")]
rkey: Option<String>,
record: PostRecord,
}
#[derive(Debug, Serialize, Clone)]
struct PostRecord {
#[serde(rename = "$type")]
schema_type: String,
title: String,
content: String,
#[serde(rename = "createdAt")]
created_at: String,
}
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct PutRecordResponse {
uri: String,
cid: String,
#[serde(default)]
commit: Option<serde_json::Value>,
#[serde(rename = "validationStatus", default)]
validation_status: Option<String>,
}
pub async fn execute() -> Result<()> {
let mut config = Config::load()?;
// Refresh session before API calls
crate::refresh::refresh_session(&mut config).await?;
let mut mapping = Config::load_mapping()?;
println!("Posting markdown files from ./content/post/...");
let pds_url = format!("https://{}", config.pds);
let client = reqwest::Client::new();
// Walk through ./content/post/
for entry in WalkDir::new("./content/post")
.into_iter()
.filter_map(|e| e.ok())
.filter(|e| e.path().extension().and_then(|s| s.to_str()) == Some("md"))
{
let path = entry.path();
let filename = path
.file_name()
.and_then(|s| s.to_str())
.context("Invalid filename")?
.to_string();
println!("Processing: {}", filename);
let content = std::fs::read_to_string(path)?;
// Use filename as title (simplified)
let title = path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("Untitled");
// Check if this file already has a mapping
let existing_rkey = mapping.get(&filename).map(|m| m.rkey.clone());
// Create record
let record = PostRecord {
schema_type: "ai.syui.log.post".to_string(),
title: title.to_string(),
content,
created_at: chrono::Utc::now().to_rfc3339(),
};
let res: PutRecordResponse = if let Some(rkey) = existing_rkey.clone() {
// Update existing record with putRecord
let put_req = PutRecordRequest {
repo: config.did.clone(),
collection: "ai.syui.log.post".to_string(),
rkey: Some(rkey),
record: record.clone(),
};
let put_url = format!("{}/xrpc/com.atproto.repo.putRecord", pds_url);
let response = client
.post(&put_url)
.header("Authorization", format!("Bearer {}", config.access_jwt))
.json(&put_req)
.send()
.await
.context("Failed to put record")?;
let status = response.status();
let body_text = response.text().await?;
if !status.is_success() {
eprintln!("Error response ({}): {}", status, body_text);
anyhow::bail!("API returned error: {}", body_text);
}
serde_json::from_str(&body_text)
.context(format!("Failed to parse putRecord response. Body: {}", body_text))?
} else {
// Create new record with createRecord (auto-generates TID)
#[derive(Serialize)]
struct CreateRecordRequest {
repo: String,
collection: String,
record: PostRecord,
}
let create_req = CreateRecordRequest {
repo: config.did.clone(),
collection: "ai.syui.log.post".to_string(),
record,
};
let create_url = format!("{}/xrpc/com.atproto.repo.createRecord", pds_url);
let response = client
.post(&create_url)
.header("Authorization", format!("Bearer {}", config.access_jwt))
.json(&create_req)
.send()
.await
.context("Failed to create record")?;
let status = response.status();
let body_text = response.text().await?;
if !status.is_success() {
eprintln!("Error response ({}): {}", status, body_text);
anyhow::bail!("API returned error: {}", body_text);
}
serde_json::from_str(&body_text)
.context(format!("Failed to parse createRecord response. Body: {}", body_text))?
};
// Extract rkey from URI
let rkey = res.uri.split('/').last().unwrap().to_string();
// Update mapping
mapping.insert(
filename.clone(),
RecordMapping {
rkey: rkey.clone(),
uri: res.uri.clone(),
cid: res.cid.clone(),
},
);
if existing_rkey.is_some() {
println!(" ✓ Updated: {} ({})", title, rkey);
} else {
println!(" ✓ Created: {} ({})", title, rkey);
}
}
// Save mapping
Config::save_mapping(&mapping)?;
println!("Mapping saved to: {}", Config::mapping_path()?.display());
println!("Done!");
Ok(())
}

View File

@@ -1,50 +0,0 @@
use anyhow::{Context, Result};
use serde::Deserialize;
use crate::config::Config;
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct RefreshSessionResponse {
#[serde(rename = "accessJwt")]
access_jwt: String,
#[serde(rename = "refreshJwt")]
refresh_jwt: String,
handle: String,
did: String,
}
pub async fn refresh_session(config: &mut Config) -> Result<()> {
let pds_url = format!("https://{}", config.pds);
let refresh_url = format!("{}/xrpc/com.atproto.server.refreshSession", pds_url);
let client = reqwest::Client::new();
let response = client
.post(&refresh_url)
.header("Authorization", format!("Bearer {}", config.refresh_jwt))
.send()
.await
.context("Failed to refresh session")?;
let status = response.status();
let body_text = response.text().await?;
if !status.is_success() {
eprintln!("Refresh session failed ({}): {}", status, body_text);
anyhow::bail!("Failed to refresh session. Please run 'ailog login' again.");
}
let res: RefreshSessionResponse = serde_json::from_str(&body_text)
.context(format!("Failed to parse refreshSession response. Body: {}", body_text))?;
// Update config with new tokens
config.access_jwt = res.access_jwt;
config.refresh_jwt = res.refresh_jwt;
// Save updated config (silent)
let path = Config::config_path()?;
let content = serde_json::to_string_pretty(config)?;
std::fs::write(&path, content)?;
Ok(())
}

View File

@@ -1,29 +0,0 @@
use anyhow::Result;
use axum::Router;
use std::net::SocketAddr;
use tower_http::services::ServeDir;
pub async fn execute(port: u16) -> Result<()> {
let public_dir = "./public";
// Check if public directory exists
if !std::path::Path::new(public_dir).exists() {
anyhow::bail!("Public directory not found. Run 'ailog build' first.");
}
println!("Starting server...");
println!(" → Serving: {}", public_dir);
println!(" → Address: http://localhost:{}", port);
println!(" → Blog: http://localhost:{}/", port);
println!(" → AT Browser: http://localhost:{}/at/", port);
println!("\nPress Ctrl+C to stop");
let app = Router::new().nest_service("/", ServeDir::new(public_dir));
let addr = SocketAddr::from(([127, 0, 0, 1], port));
let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(listener, app).await?;
Ok(())
}

557
src/styles/main.css Normal file
View File

@@ -0,0 +1,557 @@
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
line-height: 1.6;
color: #1a1a1a;
background: #fff;
}
#app {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
/* Dark mode */
@media (prefers-color-scheme: dark) {
body {
background: #0a0a0a;
color: #e0e0e0;
}
.profile {
background: #1a1a1a;
}
.post-item {
border-color: #333;
}
.post-link:hover {
background: #1a1a1a;
}
.browser-input {
background: #1a1a1a;
border-color: #333;
color: #e0e0e0;
}
}
/* Header */
#header {
margin-bottom: 24px;
}
.header-form {
display: flex;
gap: 8px;
align-items: center;
}
.header-input {
flex: 1;
padding: 8px 12px;
border: 1px solid #ddd;
border-radius: 6px;
font-size: 14px;
}
.header-btn {
width: 36px;
height: 36px;
display: flex;
align-items: center;
justify-content: center;
background: #f0f0f0;
color: #333;
border: 1px solid #ddd;
border-radius: 6px;
cursor: pointer;
font-size: 16px;
font-weight: bold;
}
.header-btn:hover {
background: #e0e0e0;
}
.header-btn.at-btn {
background: #0066cc;
color: #fff;
border-color: #0066cc;
}
.header-btn.at-btn:hover {
background: #0052a3;
}
.header-btn.login-btn {
color: #666;
}
.header-btn.user-btn {
background: #0066cc;
color: #fff;
border-color: #0066cc;
}
/* Post Form */
.post-form-container {
padding: 20px 0;
}
.post-form-container h3 {
font-size: 18px;
margin-bottom: 16px;
}
.post-form {
display: flex;
flex-direction: column;
gap: 12px;
}
.post-form-title {
padding: 10px 12px;
border: 1px solid #ddd;
border-radius: 6px;
font-size: 16px;
}
.post-form-body {
padding: 10px 12px;
border: 1px solid #ddd;
border-radius: 6px;
font-size: 14px;
resize: vertical;
min-height: 120px;
font-family: inherit;
}
.post-form-footer {
display: flex;
justify-content: space-between;
align-items: center;
}
.post-form-collection {
font-size: 12px;
color: #888;
font-family: monospace;
}
.post-form-btn {
padding: 10px 24px;
background: #0066cc;
color: #fff;
border: none;
border-radius: 6px;
font-size: 14px;
cursor: pointer;
}
.post-form-btn:hover {
background: #0052a3;
}
.post-form-btn:disabled {
background: #ccc;
cursor: not-allowed;
}
.post-status {
margin-top: 12px;
}
.post-success {
color: #155724;
}
.post-error {
color: #dc3545;
}
/* Profile */
.profile {
display: flex;
gap: 16px;
padding: 20px;
background: #f5f5f5;
border-radius: 12px;
margin-bottom: 24px;
}
.profile-avatar {
width: 80px;
height: 80px;
border-radius: 50%;
object-fit: cover;
}
.profile-info {
flex: 1;
}
.profile-name {
font-size: 20px;
font-weight: 600;
margin-bottom: 4px;
}
.profile-handle {
font-size: 14px;
color: #666;
margin-bottom: 8px;
}
.profile-desc {
font-size: 14px;
color: #444;
}
/* Post List */
.post-list {
list-style: none;
}
.post-item {
border-bottom: 1px solid #eee;
}
.post-link {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px 8px;
text-decoration: none;
color: inherit;
}
.post-link:hover {
background: #f9f9f9;
}
.post-title {
font-weight: 500;
}
.post-date {
font-size: 13px;
color: #888;
}
/* Post Detail */
.post-detail {
padding: 20px 0;
}
.post-header {
margin-bottom: 24px;
padding-bottom: 16px;
border-bottom: 1px solid #eee;
}
.post-header .post-title {
font-size: 28px;
font-weight: 600;
margin-bottom: 8px;
}
.post-meta {
display: flex;
align-items: center;
gap: 12px;
}
.post-header .post-date {
font-size: 14px;
color: #888;
}
.json-btn {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 4px 8px;
background: #f0f0f0;
color: #666;
border-radius: 4px;
text-decoration: none;
font-family: monospace;
font-size: 12px;
}
.json-btn:hover {
background: #e0e0e0;
color: #333;
}
.post-content {
font-size: 16px;
line-height: 1.8;
white-space: pre-wrap;
}
.post-footer {
margin-top: 32px;
padding-top: 16px;
border-top: 1px solid #eee;
}
.back-link {
color: #0066cc;
text-decoration: none;
}
.back-link:hover {
text-decoration: underline;
}
/* Utility */
.no-posts,
.no-data,
.error {
padding: 40px;
text-align: center;
color: #888;
}
.loading {
padding: 40px;
text-align: center;
color: #666;
}
/* Footer */
.site-footer {
margin-top: 60px;
padding: 20px 0;
text-align: center;
font-size: 13px;
color: #888;
}
.site-footer p {
margin: 4px 0;
}
/* Mode Tabs */
.mode-tabs {
display: flex;
gap: 4px;
margin-bottom: 16px;
}
.tab {
padding: 8px 16px;
text-decoration: none;
color: #666;
border-radius: 6px;
font-size: 14px;
}
.tab:hover {
background: #f0f0f0;
}
.tab.active {
background: #0066cc;
color: #fff;
}
/* AT Browser */
.collections,
.records,
.record-detail {
padding: 16px 0;
}
.collections h3,
.records h3,
.record-detail h3 {
font-size: 18px;
margin-bottom: 12px;
}
.collection-list,
.record-list {
list-style: none;
}
.collection-item,
.record-item {
border-bottom: 1px solid #eee;
}
.collection-link,
.record-link {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 8px;
text-decoration: none;
color: inherit;
font-family: monospace;
font-size: 14px;
}
.collection-link:hover,
.record-link:hover {
background: #f9f9f9;
}
.collection-favicon {
width: 20px;
height: 20px;
flex-shrink: 0;
}
.collection-nsid {
flex: 1;
}
.collection-service {
font-size: 12px;
color: #888;
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
}
.record-link {
display: flex;
gap: 16px;
}
.record-rkey {
color: #0066cc;
min-width: 120px;
}
.record-preview {
color: #666;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.record-count {
font-size: 13px;
color: #888;
margin-bottom: 12px;
}
/* Record Detail */
.record-header {
margin-bottom: 16px;
padding-bottom: 16px;
border-bottom: 1px solid #eee;
}
.record-uri,
.record-cid {
font-family: monospace;
font-size: 12px;
color: #666;
margin: 4px 0;
word-break: break-all;
}
.schema-status {
display: inline-block;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
margin-top: 8px;
}
.schema-verified {
background: #d4edda;
color: #155724;
}
.schema-none {
background: #f0f0f0;
color: #666;
}
/* JSON View */
.json-view {
background: #f5f5f5;
border-radius: 8px;
padding: 16px;
overflow-x: auto;
}
.json-view pre {
margin: 0;
}
.json-view code {
font-family: 'SF Mono', Monaco, 'Cascadia Code', monospace;
font-size: 13px;
line-height: 1.5;
}
/* Dark mode additions */
@media (prefers-color-scheme: dark) {
.header-input {
background: #1a1a1a;
border-color: #333;
color: #e0e0e0;
}
.header-btn {
background: #2a2a2a;
border-color: #333;
color: #e0e0e0;
}
.header-btn:hover {
background: #333;
}
.header-btn.at-btn,
.header-btn.user-btn {
background: #0066cc;
border-color: #0066cc;
color: #fff;
}
.post-form-title,
.post-form-body {
background: #1a1a1a;
border-color: #333;
color: #e0e0e0;
}
.json-btn {
background: #2a2a2a;
color: #888;
}
.json-btn:hover {
background: #333;
color: #e0e0e0;
}
.tab:hover {
background: #333;
}
.tab.active {
background: #0066cc;
}
.collection-link:hover,
.record-link:hover {
background: #1a1a1a;
}
.collection-item,
.record-item,
.record-header {
border-color: #333;
}
.json-view {
background: #1a1a1a;
}
.schema-verified {
background: #1e3a29;
color: #75b798;
}
.schema-none {
background: #2a2a2a;
color: #888;
}
}

30
src/types.ts Normal file
View File

@@ -0,0 +1,30 @@
export interface Profile {
did: string
handle: string
displayName?: string
description?: string
avatar?: string
banner?: string
}
export interface BlogPost {
uri: string
cid: string
title: string
content: string
createdAt: string
}
export interface NetworkConfig {
plc: string
bsky: string
}
export interface AppConfig {
title: string
handle: string
collection: string
network: string
}
export type Networks = Record<string, NetworkConfig>