Skip to content

armgit / ODS

Public Imported from GitHub
0

ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.

10.3 KB
Raw Blame
import { useEffect, useRef, useState } from 'react'
import { Archive, Folder, Plus } from 'lucide-react'
import {groupProjectConversations} from '../lib/conversationProjects'
import {EXAMPLE_OPEN_EVENT, EXAMPLE_REFRESH_EVENT, exampleProjectRows, readExampleProjects} from '../lib/exampleProjects'
import { CHAT_KEY, LIBRARY_EVENT, SELECT_EVENT, DELETE_EVENT, readConversations, conversationTitle } from '../lib/pixelConversations'
import { conversationLabels } from '../lib/pixelConversationLabels'
import { useNewTaskBlocked } from '../lib/portalTaskState'
import PixelConversationRow, {ConversationTitle} from './PixelConversationRow'

import { exportConversation } from '../lib/pixelConversationExport'

function LimitedList({items,children,label}) {
  const [expanded,setExpanded]=useState(false)
  return <>{children(expanded?items:items.slice(0,5))}{items.length>5 && <button type="button" className="rail-show-more" aria-label={`${expanded?'Show fewer':'Show more'} ${label}`} aria-expanded={expanded} onClick={()=>setExpanded(value=>!value)}>{expanded?'Show fewer':`Show more (${items.length-5})`}</button>}</>
}

export default function PixelConversationNavigation({ collapsed }) {
  const [chats, setChats] = useState(readConversations)
  const [active, setActive] = useState('')
  const [pending, setPending] = useState(null)
  const [deleteError, setDeleteError] = useState('')
  const [deleting,setDeleting]=useState(false)
  const [exportError, setExportError] = useState('')
  const [showArchived, setShowArchived] = useState(false)
  const [examples, setExamples] = useState([])
  // While Portal finishes a task, New task is disabled and says why.
  const newTaskBlocked = useNewTaskBlocked()
  const archiveToggle = useRef(null)

  const dialog = useRef(null)
  const trigger = useRef(null)
  const newTask = useRef(null)
  const deletionAttempt=useRef(null)
  useEffect(()=>()=>{if(deletionAttempt.current)clearTimeout(deletionAttempt.current.timer);deletionAttempt.current=null},[])
  useEffect(() => {
    if (pending) dialog.current?.showModal()
    else if (trigger.current) {
      // Restore after React removes the deleted row. Focusing its opener
      // before that commit would leave keyboard users on the document body.
      const target = trigger.current.isConnected ? trigger.current : newTask.current
      trigger.current = null
      target?.focus()
    }
  }, [pending])
  function closeDelete() { if(deleting)return;dialog.current?.close(); setPending(null); setDeleteError('') }
  function confirmDelete() {
    if(deletionAttempt.current)return
    setDeleting(true)
    const attempt={chatId:pending.chatId,timer:null};deletionAttempt.current=attempt
    attempt.timer=setTimeout(()=>{
      if(deletionAttempt.current!==attempt)return
      deletionAttempt.current=null;setDeleting(false)
      setDeleteError('Deletion was not confirmed. Your history has not been hidden. Open this conversation and retry deletion.')
    },35000)
    window.dispatchEvent(new CustomEvent(DELETE_EVENT, {detail:{chatId:pending.chatId, complete:error => {
      if(deletionAttempt.current!==attempt)return
      clearTimeout(attempt.timer);deletionAttempt.current=null
      setDeleting(false)
      if (error) setDeleteError(error)
      else {dialog.current?.close();setPending(null);setDeleteError('')}
    }}}))
  }
  useEffect(() => {
    const refresh = () => {
      setChats(readConversations())
      try { setActive(JSON.parse(localStorage.getItem(CHAT_KEY) || 'null')?.chatId || '') } catch { setActive('') }
    }
    refresh()
    window.addEventListener(LIBRARY_EVENT, refresh)
    window.addEventListener('storage', refresh)
    return () => { window.removeEventListener(LIBRARY_EVENT, refresh); window.removeEventListener('storage', refresh) }
  }, [])
  useEffect(() => {
    // Shipped example projects whose folder is in the owner's workspace.
    // Checked again when the window regains focus and when Portal becomes
    // available (Pixel sends the refresh event then), so a deleted or renamed
    // folder quietly leaves the list. A failed check keeps the last answer.
    let controller = null
    const load = () => {
      controller?.abort()
      const current = controller = new AbortController()
      readExampleProjects(current.signal)
        .then(names => { if (!current.signal.aborted) setExamples(names) })
        .catch(() => { /* Portal is not answering yet; a later check decides. */ })
    }
    load()
    window.addEventListener('focus', load)
    window.addEventListener(EXAMPLE_REFRESH_EVENT, load)
    return () => { controller?.abort(); window.removeEventListener('focus', load); window.removeEventListener(EXAMPLE_REFRESH_EVENT, load) }
  }, [])
  // aria-disabled, not disabled: a click or tap still reaches Portal, which
  // shows the reason beside the composer instead of doing nothing.
  if (collapsed) return <button ref={newTask} className="pixel-nav-item rail-new-task" aria-label="New task" title={newTaskBlocked || 'New task'} aria-disabled={newTaskBlocked ? 'true' : undefined} onClick={() => window.dispatchEvent(new Event('ods:pixel-new-task'))}><Plus size={16}/></button>
  const labeled = chats.map(chat => ({chat, labels:conversationLabels(chat.chatId)}))
  const visible = labeled.filter(item => item.labels.archived === showArchived)
  const pinned = visible.filter(item => item.labels.pinned).map(item => item.chat)
  const regular = visible.filter(item => !item.labels.pinned).map(item => item.chat)
  const {projects,recent}=groupProjectConversations(regular)
  const shipped=showArchived?[]:exampleProjectRows(examples,projects)
  const playground=[...projects.filter(project=>project.root==='Playground'),...shipped]
  const legacy=projects.filter(project=>!project.root)
  const chevron = <svg className="rail-chevron" viewBox="0 0 16 16" aria-hidden="true"><path d="m5 6 3 3 3-3"/></svg>
  function rows(items, empty) {
    return <div className="rail-conversations">{items.length ? items.map(chat => <PixelConversationRow key={chat.chatId} chat={chat} title={conversationTitle(chat)} onSaved={() => archiveToggle.current?.focus()} onDelete={event => {trigger.current=event.currentTarget;setDeleteError('');setPending(chat)}} onExport={() => {
      try { exportConversation(chat.chatId); setExportError('') }
      catch { setExportError('This conversation could not be exported. Your saved history is unchanged.') }
    }}><button className={`conversation-link ${chat.chatId === active ? 'active' : ''}`} title={conversationTitle(chat)} aria-current={chat.chatId === active ? 'page' : undefined} onClick={() => window.dispatchEvent(new CustomEvent(SELECT_EVENT, { detail: chat.chatId }))}><ConversationTitle title={conversationTitle(chat)}/>{chat.inFlight && <span className="rail-task-running" role="status" aria-label="Working"/>}</button></PixelConversationRow>) : <span className="rail-empty">{empty}</span>}</div>

  }
  function projectRows(items) {
    // A shipped example with no conversations yet opens its game on click,
    // exactly where the folder sits; otherwise it is the same project row.
    // Assistive tech hears a button, since this row opens rather than unfolds.
    return items.map(project=>project.example ? <details className="rail-project" key={project.path}>
      <summary role="button" title={project.path} onClick={event=>{event.preventDefault();window.dispatchEvent(new CustomEvent(EXAMPLE_OPEN_EVENT,{detail:{name:project.name}}))}}><Folder size={16}/><span>{project.name}</span>{chevron}</summary>
    </details> : <details className="rail-project" key={project.path} open={project.chats.some(chat=>chat.chatId===active) || undefined}>
      <summary title={project.path}><Folder size={16}/><span>{project.name}</span>{chevron}</summary>
      <LimitedList items={project.chats} label={`conversations in ${project.path}`}>{items=>rows(items,'')}</LimitedList>
    </details>)
  }
  return <div className="pixel-conversation-navigation">
    {exportError && <p role="alert">{exportError}</p>}
    <dialog ref={dialog} className="chat-delete-dialog" aria-labelledby="delete-chat-title" onCancel={event => { event.preventDefault(); closeDelete() }}>
      <h3 id="delete-chat-title">Delete this chat?</h3>
      <p>{pending && conversationTitle(pending)}</p>
      <p>This removes this browser's conversation and its private Portal image copies, including registered native transcripts. Workspace files, published previews and external backups are kept. This cannot be undone.</p>
      {deleteError && <p role="alert">{deleteError}</p>}
      <footer><button autoFocus disabled={deleting} onClick={closeDelete}>Cancel</button><button disabled={deleting} onClick={confirmDelete}>{deleting?'Deleting…':'Delete chat'}</button></footer>
    </dialog>
    <button ref={newTask} className="pixel-nav-item rail-new-task" aria-disabled={newTaskBlocked ? 'true' : undefined} aria-describedby={newTaskBlocked ? 'pixel-new-task-reason' : undefined} onClick={() => window.dispatchEvent(new Event('ods:pixel-new-task'))}><Plus size={16}/><span>New task</span></button>
    {/* Described, not announced: the header already announces that Portal is working. */}
    {newTaskBlocked && <p id="pixel-new-task-reason" className="rail-new-task-reason">{newTaskBlocked}</p>}
    <div className="pixel-original-sections">
      {pinned.length > 0 && <details className="rail-section" open><summary>Pinned{chevron}</summary>{rows(pinned, '')}</details>}
      {projects.length+shipped.length>0 && <details className="rail-section" open>
        <summary>Projects{chevron}</summary>
        {playground.length>0 && <details className="rail-project rail-playground" open>
          <summary><Folder size={16}/><span>Playground</span>{chevron}</summary>
          <LimitedList items={playground} label="Playground projects">{projectRows}</LimitedList>
        </details>}
        {legacy.length>0 && <LimitedList items={legacy} label="projects">{projectRows}</LimitedList>}
      </details>}
      <details className="rail-section" open><summary>{showArchived?'Archived conversations':'Recent'}{chevron}</summary>{rows(recent,showArchived?'No archived conversations':'No conversations yet')}</details>
    </div>
    <button ref={archiveToggle} className="pixel-nav-item rail-archive-toggle" type="button" aria-pressed={showArchived} onClick={() => setShowArchived(value => !value)}><Archive size={16}/><span>{showArchived ? 'Show active conversations' : `Archived (${labeled.filter(item => item.labels.archived).length})`}</span></button>
  </div>
}