<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>ザワログ</title><description>ザワのブログ</description><link>https://blog.zawa.dev/</link><item><title>【VS Code】Live Previewを最強にする、1ファイル完結型の爆速・軽量「プロジェクトナビゲーター」の構築方法</title><link>https://blog.zawa.dev/blog/dlm-iu3_rtz/</link><guid isPermaLink="true">https://blog.zawa.dev/blog/dlm-iu3_rtz/</guid><content:encoded>VS Codeの拡張機能「Live Preview」を使ってWebサイト制作やドキュメント管理をする際、標準のディレクトリ一覧が少し物足りないと感じたことはありませんか？

外部ライブラリを一切使わず、**HTML、CSS、Node.jsの標準機能だけ**で動く、極限まで無骨でセマンティックな「マイ・プロジェクトナビゲーター」を構築する方法を紹介します。

## 💡 このツールの特徴
* **超軽量＆爆速**: 外部のCSSフレームワークやJavaScriptライブラリは一切不使用。ブラウザ標準の等幅フォント（`monospace`）を活かした無骨なデザイン。
* **1ファイル完結のデータ保持**: 面倒な別ファイルへのデータ書き出しは不要。Node.jsが直接`index.html`の内部変数を上書き同期します。
* **強力なセッション復元**: ページをリロードしたり、ファイルを編集してLive Previewが自動更新されても、**さっきまで開いていたフォルダの展開状態やタブの選択状態がそのまま維持**されます。
* **システム連動テーマ**: OSやブラウザのライトモード/ダークモード設定を自動検知して配色が切り替わります。
* **画面幅に合わせた全幅表示**: スマホサイズや画面分割で幅が狭くなると、自動で左右の余白を削り、エディタのような100%全幅表示になります。

## 🛠️ インストール・設定手順

作業スペース（ワークスペース）のルートディレクトリに、以下の **2つのファイル** を作成するだけで完了します。

### 1. `index.html` の作成
ワークスペースのルートに `index.html` を作成し、以下のコードを貼り付けます。

&lt;details&gt;&lt;summary&gt;index.html&lt;/summary&gt;

``` html
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;ja&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;title&gt;プロジェクトナビゲーター&lt;/title&gt;
    &lt;style&gt;
        :root {
            --bg-color: #ffffff;
            --text-color: #000000;
            --border-color: #000000;
            --sub-border-color: #cccccc;
            --meta-color: #666666;
            --link-color: #0000ee;
            --hover-bg: #f0f0f0;
            --weblink-hover-bg: #eef2ff;
        }

        @media (prefers-color-scheme: dark) {
            :root {
                --bg-color: #000000;
                --text-color: #ffffff;
                --border-color: #ffffff;
                --sub-border-color: #444444;
                --meta-color: #aaaaaa;
                --link-color: #99ccff;
                --hover-bg: #222222;
                --weblink-hover-bg: #001144;
            }
        }

        body {
            font-family: monospace, sans-serif;
            line-height: 1.5;
            background-color: var(--bg-color);
            color: var(--text-color);
            padding: 2rem;
            max-width: 900px;
            margin: 0 auto;
        }

        @media (max-width: 600px) {
            body {
                padding: 2rem 0;
            }
            header, .tabs {
                padding-left: 0.5rem;
                padding-right: 0.5rem;
            }
        }

        header {
            border-bottom: 1px solid var(--border-color);
            margin-bottom: 0.5rem;
            padding-bottom: 0.5rem;
        }
        h1 {
            font-size: 1.25rem;
            margin: 0;
        }
        .workspace-path {
            font-size: 0.85rem;
            color: var(--meta-color);
            margin: 0 0 0 0;
            word-break: break-all;
        }

        .tabs {
            margin: 1rem 0;
            font-size: 0.9rem;
        }
        .tabs button.tab-btn {
            display: inline;
            width: auto;
            padding: 0.2rem 0.5rem;
            color: var(--meta-color);
        }
        .tabs button.tab-btn.active {
            color: var(--text-color);
            font-weight: bold;
            text-decoration: underline;
        }
        
        ul {
            list-style-type: none;
            padding-left: 0;
            margin: 0;
        }
        li {
            margin: 0;
            padding: 0;
        }
        ul ul {
            padding-left: 1.25rem;
            border-left: 1px dashed var(--sub-border-color); 
            overflow: hidden;
            max-height: 0;
            transition: max-height 0.2s ease-out;
        }
        ul ul.expanded {
            max-height: 2000px; 
            transition: max-height 0.3s ease-in;
        }
        
        .tree-row {
            display: flex;
            align-items: stretch;
            width: 100%;
            margin: 0;
            padding: 0;
        }
        
        button {
            background: none;
            border: none;
            padding: 0.6rem 0.5rem; 
            font-family: inherit;
            font-size: inherit;
            color: var(--text-color);
            cursor: pointer;
            text-align: left;
            flex: 1;
            display: block;
            margin: 0;
        }
        button:hover {
            background-color: var(--hover-bg);
        }
        
        .file-button {
            background: none;
            border: none;
            padding: 0.6rem 0.5rem;
            font-family: inherit;
            font-size: inherit;
            color: var(--text-color);
            text-decoration: none;
            flex: 1;
            display: block;
            margin: 0;
        }
        .file-button:hover {
            background-color: var(--hover-bg);
        }
        .file-link-text {
            color: var(--link-color);
        }
        .file-button:hover .file-link-text {
            text-decoration: underline;
        }
        
        .tree-row a.web-link {
            display: flex;
            align-items: center;
            padding: 0 1rem;
            color: var(--link-color);
            text-decoration: none;
            margin: 0;
        }
        .tree-row a.web-link:hover {
            background-color: var(--weblink-hover-bg);
            text-decoration: underline;
        }

        .meta-info {
            color: var(--meta-color);
            font-size: 0.8rem;
            margin-left: 0.5rem;
            pointer-events: none; 
        }

        #file-tree.mode-web li:not([data-is-web=&quot;true&quot;]) {
            display: none;
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;header&gt;
        &lt;h1 id=&quot;title-display&quot;&gt;&lt;/h1&gt;
        &lt;p class=&quot;workspace-path&quot; id=&quot;workspace-display&quot;&gt;&lt;/p&gt;
    &lt;/header&gt;

    &lt;div class=&quot;tabs&quot; role=&quot;tablist&quot; aria-label=&quot;表示切り替え&quot;&gt;
        &lt;button type=&quot;button&quot; id=&quot;btn-all&quot; class=&quot;tab-btn active&quot; onclick=&quot;switchTab(&apos;all&apos;)&quot;&gt;[All Files]&lt;/button&gt;
        &lt;button type=&quot;button&quot; id=&quot;btn-web&quot; class=&quot;tab-btn&quot; onclick=&quot;switchTab(&apos;web&apos;)&quot;&gt;[Web Sites Only]&lt;/button&gt;
    &lt;/div&gt;

    &lt;main&gt;
        &lt;nav aria-label=&quot;ファイルシステムツリー&quot;&gt;
            &lt;ul id=&quot;file-tree&quot; class=&quot;mode-all&quot;&gt;&lt;/ul&gt;
        &lt;/nav&gt;
    &lt;/main&gt;

    &lt;script&gt;
        const PROJECT_TREE = []; // DATA_PLACEHOLDER
        const WORKSPACE_PATH = &quot;&quot;; // PATH_PLACEHOLDER

        window.addEventListener(&apos;DOMContentLoaded&apos;, () =&gt; {
            document.getElementById(&apos;workspace-display&apos;).textContent = `${WORKSPACE_PATH || &apos;Unknown&apos;}`;

            if (WORKSPACE_PATH) {
                const pathParts = WORKSPACE_PATH.split(&apos;/&apos;);
                const lastDir = pathParts[pathParts.length - 1] || pathParts[pathParts.length - 2];
                if (lastDir) {
                    document.getElementById(&apos;title-display&apos;).textContent = lastDir;
                }
            }

            if (PROJECT_TREE &amp;&amp; PROJECT_TREE.length &gt; 0) {
                calculateCounts(PROJECT_TREE);
                document.getElementById(&apos;file-tree&apos;).innerHTML = renderTree(PROJECT_TREE);
                restoreDirState(); 
                
                const savedTab = sessionStorage.getItem(&apos;active_tab&apos;) || &apos;all&apos;;
                switchTab(savedTab);
            } else {
                document.getElementById(&apos;file-tree&apos;).innerHTML = &apos;&lt;li&gt;プロジェクトが空か、タスクによる初回データ注入を待っています。&lt;/li&gt;&apos;;
            }
        });

        function calculateCounts(nodes) {
            nodes.forEach(node =&gt; {
                if (node.type === &apos;directory&apos;) {
                    calculateCounts(node.children);

                    let totalDirs = 0;
                    let totalFiles = 0;

                    node.children.forEach(child =&gt; {
                        if (child.type === &apos;directory&apos;) {
                            totalDirs += 1 + child.totalDirs;
                            totalFiles += child.totalFiles;
                        } else if (child.type === &apos;file&apos;) {
                            totalFiles += 1;
                        }
                    });

                    node.totalDirs = totalDirs;
                    node.totalFiles = totalFiles;
                }
            });
        }

        function findIndexUrl(node) {
            const directIndex = node.children.find(c =&gt; c.type === &apos;file&apos; &amp;&amp; c.name.toLowerCase() === &apos;index.html&apos;);
            if (directIndex) return &apos;/&apos; + directIndex.path;
            
            for (const child of node.children) {
                if (child.type === &apos;directory&apos; &amp;&amp; child.isWeb) {
                    return findIndexUrl(child);
                }
            }
            return &apos;#&apos;;
        }

        function renderTree(nodes) {
            if (nodes.length === 0) return &apos;&apos;;

            let html = &apos;&apos;;
            nodes.forEach(node =&gt; {
                if (node.type === &apos;directory&apos;) {
                    const uniqueId = &apos;dir-&apos; + btoa(unescape(encodeURIComponent(node.path))).replace(/=/g, &apos;&apos;);
                    const metaHTML = `&lt;span class=&quot;meta-info&quot;&gt;(d:${node.totalDirs}/f:${node.totalFiles})&lt;/span&gt;`;
                    
                    if (node.isWeb) {
                        const destinationUrl = findIndexUrl(node);
                        html += `
                            &lt;li data-is-web=&quot;true&quot;&gt;
                                &lt;div class=&quot;tree-row&quot;&gt;
                                    &lt;button type=&quot;button&quot; onclick=&quot;toggleDir(&apos;${uniqueId}&apos;)&quot;&gt;/${node.name}${metaHTML}&lt;/button&gt;
                                    &lt;a href=&quot;${destinationUrl}&quot; class=&quot;web-link&quot;&gt;[Link]&lt;/a&gt;
                                &lt;/div&gt;
                                &lt;ul id=&quot;${uniqueId}&quot;&gt;
                                    ${renderTree(node.children)}
                                &lt;/ul&gt;
                            &lt;/li&gt;
                        `;
                    } else {
                        html += `
                            &lt;li data-is-web=&quot;false&quot;&gt;
                                &lt;div class=&quot;tree-row&quot;&gt;
                                    &lt;button type=&quot;button&quot; onclick=&quot;toggleDir(&apos;${uniqueId}&apos;)&quot;&gt;/${node.name}${metaHTML}&lt;/button&gt;
                                &lt;/div&gt;
                                &lt;ul id=&quot;${uniqueId}&quot;&gt;
                                    ${renderTree(node.children)}
                                &lt;/ul&gt;
                            &lt;/li&gt;
                        `;
                    }
                } else if (node.type === &apos;file&apos;) {
                    html += `
                        &lt;li data-is-web=&quot;false&quot;&gt;
                            &lt;div class=&quot;tree-row&quot;&gt;
                                &lt;a href=&quot;/${node.path}&quot; class=&quot;button file-button&quot;&gt;&lt;span class=&quot;file-link-text&quot;&gt;${node.name}&lt;/span&gt;&lt;/a&gt;
                            &lt;/div&gt;
                        &lt;/li&gt;
                    `;
                }
            });
            return html;
        }

        function toggleDir(id) {
            const dir = document.getElementById(id);
            if (!dir) return;
            dir.classList.toggle(&apos;expanded&apos;);
            
            const isOpen = dir.classList.contains(&apos;expanded&apos;);
            sessionStorage.setItem(id, isOpen ? &apos;open&apos; : &apos;hidden&apos;);
        }

        function restoreDirState() {
            document.querySelectorAll(&apos;#file-tree ul[id^=&quot;dir-&quot;]&apos;).forEach(dir =&gt; {
                if (sessionStorage.getItem(dir.id) === &apos;open&apos;) {
                    dir.classList.add(&apos;expanded&apos;);
                }
            });
        }

        function switchTab(mode) {
            const tree = document.getElementById(&apos;file-tree&apos;);
            const btnAll = document.getElementById(&apos;btn-all&apos;);
            const btnWeb = document.getElementById(&apos;btn-web&apos;);

            if (mode === &apos;web&apos;) {
                tree.className = &apos;mode-web&apos;;
                btnAll.classList.remove(&apos;active&apos;);
                btnWeb.classList.add(&apos;active&apos;);
            } else {
                tree.className = &apos;mode-all&apos;;
                btnWeb.classList.remove(&apos;active&apos;);
                btnAll.classList.add(&apos;active&apos;);
            }
            sessionStorage.setItem(&apos;active_tab&apos;, mode);
        }
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

```
&lt;/details&gt;

### 2. バックグラウンドタスク `generate-tree.js` の作成

同じくルートディレクトリに `generate-tree.js` を作成し、以下のコードを貼り付けます。

&lt;details&gt;&lt;summary&gt;generate-tree.js&lt;/summary&gt;


``` js
const fs = require(&apos;fs&apos;);
const path = require(&apos;path&apos;);

// 自身のスクリプトや不要なシステムファイルを除外リストに登録
const IGNORE_LIST = [&apos;.git&apos;, &apos;node_modules&apos;, &apos;.vscode&apos;, &apos;generate-tree.js&apos;];
let lastTreeString = &quot;&quot;;

function scanDirectory(dirPath, baseDir = dirPath) {
    const result = [];
    let files = [];
    try { files = fs.readdirSync(dirPath); } catch (e) { return result; }

    files.forEach(file =&gt; {
        if (IGNORE_LIST.includes(file)) return;
        const fullPath = path.join(dirPath, file);
        const relativePath = path.relative(baseDir, fullPath).replace(/\\/g, &apos;/&apos;);
        
        try {
            if (fs.statSync(fullPath).isDirectory()) {
                const children = scanDirectory(fullPath, baseDir);
                const hasLocalIndex = children.some(c =&gt; c.type === &apos;file&apos; &amp;&amp; c.name.toLowerCase() === &apos;index.html&apos;);
                const hasChildIndex = children.some(c =&gt; c.type === &apos;directory&apos; &amp;&amp; c.isWeb);
                const isWeb = hasLocalIndex || hasChildIndex;

                result.push({ 
                    type: &apos;directory&apos;, 
                    name: file, 
                    path: relativePath, 
                    isWeb: isWeb, 
                    children: children 
                });
            } else {
                result.push({ 
                    type: &apos;file&apos;, 
                    name: file, 
                    path: relativePath, 
                    ext: path.extname(file).toLowerCase() 
                });
            }
        } catch (e) {}
    });
    
    return result.sort((a, b) =&gt; (b.type === &apos;directory&apos;) - (a.type === &apos;directory&apos;));
}

function updateIndexHtml() {
    const treeData = scanDirectory(__dirname);
    const currentTreeString = JSON.stringify(treeData);
    const absoluteWorkspacePath = __dirname.replace(/\\/g, &apos;/&apos;);
    
    const indexPath = path.join(__dirname, &apos;index.html&apos;);
    if (!fs.existsSync(indexPath)) return;
    
    let indexContent = fs.readFileSync(indexPath, &apos;utf8&apos;);
    let isChanged = false;
    
    // 1. ツリーデータの正規表現書き換え
    const treeRegex = /(const PROJECT_TREE = )([\s\S]*?)(; \/\/ DATA_PLACEHOLDER)/;
    if (treeRegex.test(indexContent)) {
        const matchedTree = indexContent.match(treeRegex)[2];
        if (matchedTree !== currentTreeString) {
            indexContent = indexContent.replace(treeRegex, `$1${currentTreeString}$3`);
            isChanged = true;
        }
    }
    
    // 2. ワークスペース絶対パスの正規表現書き換え
    const pathRegex = /(const WORKSPACE_PATH = &quot;)(.*?)(&quot;; \/\/ PATH_PLACEHOLDER)/;
    if (pathRegex.test(indexContent)) {
        const matchedPath = indexContent.match(pathRegex)[2];
        if (matchedPath !== absoluteWorkspacePath) {
            indexContent = indexContent.replace(pathRegex, `$1${absoluteWorkspacePath}$3`);
            isChanged = true;
        }
    }
    
    if (isChanged) {
        fs.writeFileSync(indexPath, indexContent, &apos;utf8&apos;);
        console.log(`[${new Date().toLocaleTimeString()}] 📝 index.html へのデータ同期が完了しました`);
    }
}

updateIndexHtml();

// フォルダ内を監視し、変更があれば100msウェイトでインデックスを自動同期
fs.watch(__dirname, { recursive: true }, (eventType, filename) =&gt; {
    if (filename &amp;&amp; !IGNORE_LIST.some(item =&gt; filename.includes(item)) &amp;&amp; filename !== &apos;index.html&apos;) {
        clearTimeout(global.watchTimeout);
        global.watchTimeout = setTimeout(updateIndexHtml, 100);
    }
});

```

&lt;/details&gt;

## 🚀 動かし方

1. ターミナルでワークスペースのルートに移動し、同期スクリプトを常駐起動させます。
``` bash
node generate-tree.js
```


2. スクリプトが起動すると、自動的に `index.html` 内部の変数に現在のPCの絶対パスとツリー構造データが注入されます。
3. VS Codeの「Live Preview」で `index.html` を開きます。

これで、無骨で超軽量なあなただけのプロジェクトツリー環境が爆速で立ち上がります！

## 🛠️ おすすめ：VS Code起動時にタスクを自動化する

毎回コマンドを叩くのが面倒な場合は、`.vscode/tasks.json` を作成して以下のように設定すると、**VS Codeでこのフォルダを開いた瞬間に裏で勝手にスクリプトが常駐動作**してくれます。

``` json
{
    &quot;version&quot;: &quot;2.0.0&quot;,
    &quot;tasks&quot;: [
        {
            &quot;label&quot;: &quot;Auto Project Tracker&quot;,
            &quot;type&quot;: &quot;shell&quot;,
            &quot;command&quot;: &quot;node generate-tree.js&quot;,
            &quot;isBackground&quot;: true,
            &quot;problemMatcher&quot;: [],
            &quot;runOptions&quot;: {
                &quot;runOn&quot;: &quot;folderOpen&quot;
            }
        }
    ]
}

```

## 📝 終わりに

無駄なアセットや重いフレームワークを削ぎ落とし、CSSセレクタによるフィルタリングを主軸にすることで、数百ファイル規模の環境でも一瞬で切り替わる最高にプレーンなツリーに仕上がりました。Live Previewライフのお供にぜひ役立ててください。
</content:encoded></item></channel></rss>