Get the Current Directory of Any Selected File in WebShell

Sep 19, 2024 · 1 min read · 178 Words · -Views -Comments · Programming
WebShell 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

While implementing “click to download selected filename” in a WebShell based on xterm.js, I ran into a challenge: how to determine the directory of the selected filename. After some research, here’s the solution.

Approach

  1. First, have the terminal session report the current directory after each command using shell hooks.

    https://static.1991421.cn/2024/2024-09-19-142022.jpeg

  2. Use registerOscHandler to listen for ANSI sequences and extract CurrentDir from the data.

const cwdArr = []; // index 0 unused
term.parser.registerOscHandler(1337, data => {
  const currenDirArr = data?.match?.(/(;CurrentDir=)([^;\u0007]+)/);
  if (currenDirArr?.length >= 3) {
    cwdArr[term.buffer.active.baseY + term.buffer.active.cursorY] = currenDirArr[2];
  }
})
  1. Listen for selection changes. Combine the selection position with cwdArr to compute the CWD of the selected filename.

    term.onSelectionChange(() => {
      const selection = term.getSelection();
      if (!selection) {
        return;
      }
      const selectionPosition = term.getSelectionPosition();
      term.getSelection() && copyToClipboard(term.getSelection());
      let rowNum = selectionPosition.start.y; // row
      while (rowNum < cwdArr.length && !cwdArr[rowNum]) {
        rowNum++;
      }
      const cwd = cwdArr[rowNum];
      console.log('Selected file', pathJoin(cwd, selection));
    });
    

Final Thoughts

This approach lets you infer the working directory that produced any particular section of terminal output and, by extension, the directory of a selected filename.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover