Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

6.9 KB
Raw Blame
// ─── Right-side markdown drawer for the chat view ───
// Hosted next to the main chat history, slides in from the right. Two source
// kinds today (defined by mountMdViewEdit):
//   workspace — a caller explicitly wants a side drawer for a workspace file
//   ephemeral — context-menu "Edit copy" on a chat selection
//
// Single-instance: reopening always closes the previous mount. The drawer's
// own close button (header) goes through the same dirty-check as opening a
// fresh source over an unsaved one.

const _chatMdDrawerLog = createLogger('chat-md-drawer');

let _cmdState = null;   // { controller, source, title, dirty }
let _cmdDiscardConfirmPending = false;

async function openChatMdDrawer({ source, initialMode, title } = {}) {
  if (!source || typeof source.kind !== 'string') {
    _chatMdDrawerLog.warn('openChatMdDrawer called without source.kind');
    return;
  }
  const panel = document.getElementById('chat-md-drawer-panel');
  const titleEl = document.getElementById('chat-md-drawer-title');
  const bodyEl = document.getElementById('chat-md-drawer-body');
  const actionsEl = document.getElementById('chat-md-drawer-actions');
  if (!panel || !bodyEl || !actionsEl) {
    _chatMdDrawerLog.warn('chat-md-drawer DOM missing — drawer container not in index.html');
    return;
  }

  // Replacing an open mount: ask before discarding unsaved edits.
  if (_cmdState && _cmdState.controller && _cmdState.dirty) {
    const proceed = await _confirmDiscardChatMdDrawer();
    if (!proceed) return;
  }
  _teardownCmd();

  const resolvedTitle = title || _defaultTitle(source);
  if (titleEl) titleEl.textContent = resolvedTitle;
  panel.classList.add('is-open');
  panel.hidden = false;

  _cmdState = { controller: null, source, title: resolvedTitle, dirty: false };

  try {
    _cmdState.controller = mountMdViewEdit({
      bodyEl,
      actionsEl,
      source,
      initialMode: source.kind === 'ephemeral' ? 'edit' : (initialMode || 'view'),
      callbacks: {
        onDirtyChange: (dirty) => { if (_cmdState) _cmdState.dirty = !!dirty; },
        onReveal: () => {
          if (source.kind !== 'workspace') return;
          try {
            const payload = { path: source.absPath };
            if (source.cid) payload.cid = source.cid;
            window.orkas.invoke('workspace.revealPath', payload);
          } catch (err) {
            _chatMdDrawerLog.warn('revealPath failed', err);
          }
        },
        // The drawer does not surface a delete action; setting it here would
        // be ignored (capability defaults already skip delete for workspace).
        onSendToChatInput: (text) => {
          const ok = _sendDraftToChatInput(text);
          if (ok) void closeChatMdDrawer({ force: true });
        },
      },
    });
  } catch (err) {
    _chatMdDrawerLog.error('failed to mount markdown drawer', err);
    bodyEl.innerHTML = '';
    actionsEl.innerHTML = '';
    panel.classList.remove('is-open');
    panel.hidden = true;
    _teardownCmd();
    return;
  }

  _bindCloseHandlers();
}

async function closeChatMdDrawer({ force = false } = {}) {
  if (!_cmdState) return;
  if (!force && _cmdState.dirty) {
    const proceed = await _confirmDiscardChatMdDrawer();
    if (!proceed) return;
  }
  const panel = document.getElementById('chat-md-drawer-panel');
  if (panel) {
    panel.classList.remove('is-open');
    panel.hidden = true;
  }
  _teardownCmd();
}

function isChatMdDrawerOpen() {
  return !!_cmdState;
}

function _teardownCmd() {
  if (_cmdState && _cmdState.controller) {
    try { _cmdState.controller.destroy(); }
    catch (err) { _chatMdDrawerLog.warn('controller.destroy threw', err); }
  }
  _cmdState = null;
}

function _defaultTitle(source) {
  if (source.kind === 'workspace' && source.absPath) {
    return source.absPath.split(/[\\/]/).pop() || source.absPath;
  }
  if (source.kind === 'ephemeral') {
    return t('chat.md_drawer.scratch_title');
  }
  return '';
}

async function _confirmDiscardChatMdDrawer() {
  if (_cmdDiscardConfirmPending) return false;
  _cmdDiscardConfirmPending = true;
  const message = t('chat.md_drawer.close_confirm');
  try {
    return typeof uiConfirm === 'function' ? await uiConfirm(message) : false;
  } finally {
    _cmdDiscardConfirmPending = false;
  }
}

// ── Close button / Esc dismisser ────────────────────────────────────────

let _cmdHandlersBound = false;
function _bindCloseHandlers() {
  if (_cmdHandlersBound) return;
  _cmdHandlersBound = true;
  const closeBtn = document.getElementById('chat-md-drawer-close');
  if (closeBtn) closeBtn.addEventListener('click', () => { void closeChatMdDrawer(); });
  document.addEventListener('keydown', (e) => {
    // IME guard (CLAUDE.md §8): don't intercept Escape while the user is
    // committing a composition candidate.
    if (e.isComposing || e.keyCode === 229) return;
    if (e.key !== 'Escape' || !_cmdState) return;
    // If the drawer body has focus and is inside a textarea, let Escape
    // exit the textarea selection rather than close the drawer (matches
    // the behavior of the main chat composer).
    const active = document.activeElement;
    if (active && active.tagName === 'TEXTAREA' && active.closest('#chat-md-drawer-panel')) return;
    void closeChatMdDrawer();
  });
}

// ── Send draft to chat input ────────────────────────────────────────────

function _sendDraftToChatInput(text) {
  const input = document.getElementById('chat-input');
  if (!input) {
    _chatMdDrawerLog.warn('chat-input not found — drawer "send to chat" no-op');
    return false;
  }
  const draft = String(text == null ? '' : text);
  if (!draft.trim()) return false;
  // Prepend a newline when there's already content so the snippet doesn't
  // smash into the existing draft.
  const existing = composerText(input) || '';
  const joiner = existing && !existing.endsWith('\n') ? '\n' : '';
  composerSetText(input, `${existing}${joiner}${draft}`);
  composerNotify(input);
  input.focus();
  // Move caret to end so the user sees the inserted block.
  try {
    const end = composerText(input).length;
    composerSetSelection(input, end, end);
  } catch (_) { /* old jsdom — ignore */ }
  return true;
}

// Expose to the global namespace so cross-module callers can open the drawer
// without ESM imports (per CLAUDE.md §8).
window.openChatMdDrawer  = openChatMdDrawer;
window.closeChatMdDrawer = closeChatMdDrawer;
window.isChatMdDrawerOpen = isChatMdDrawerOpen;

// Focused CommonJS bridge for deterministic renderer tests. The production
// bundle runs this file as a browser script, where `module` is absent.
if (typeof module !== 'undefined' && module.exports) {
  module.exports = {
    openChatMdDrawer,
    closeChatMdDrawer,
    isChatMdDrawerOpen,
    _defaultTitle,
    _sendDraftToChatInput,
  };
}