1
0

initial commit

This commit is contained in:
2025-05-23 10:15:53 +02:00
commit c75a4df5dc
12 changed files with 777 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
node_modules
package-lock.json

36
LICENSE Normal file
View File

@@ -0,0 +1,36 @@
CC0 1.0 Universal
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER.
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others.
For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights.
A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following:
the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work;
moral rights retained by the original author(s) and/or performer(s);
publicity and privacy rights pertaining to a person's image or likeness depicted in a Work;
rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below;
rights protecting the extraction, dissemination, use and reuse of data in a Work;
database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and
other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof.
2. Waiver.
To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback.
Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose.
4. Limitations and Disclaimers.
No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document.
Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law.
Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work.
Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work.

1
README.md Normal file
View File

@@ -0,0 +1 @@
# Projekt in auto-git-gui-initial

158
animeCat.js Normal file
View File

@@ -0,0 +1,158 @@
// animeCat.js
export class AnimeCat {
/**
* @param {HTMLElement} container
* @param {Object} [options]
*/
constructor(container, options = {}) {
this.container = container;
this.images = Object.assign({
default: 'default.png',
eyesClosed: 'eyes_closed.png',
mouthOpen: 'mouth_open.png'
}, options.images);
this.blinkMin = options.blinkMin ?? 5000;
this.blinkMax = options.blinkMax ?? 15000;
this.blinkDuration = options.blinkDuration?? 175;
this.talkInterval = options.talkInterval ?? 300;
this._isSpeaking = false;
this._blinkTimeout = null;
this._talkIntervalId = null;
this._speechTimeout = null;
this._mouthOpen = false;
this._createElements();
this._bindMouseHold();
this._startBlinking();
}
_createElements() {
this.wrapper = document.createElement('div');
this.wrapper.style.position = 'relative';
this.wrapper.style.display = 'inline-block';
// cat image
this.img = document.createElement('img');
this.img.src = this.images.default;
// disable drag & selection
this.img.draggable = false;
this.img.style.userSelect = 'none';
this.img.style.webkitUserSelect = 'none';
this.img.style.MozUserSelect = 'none';
this.img.style.msUserSelect = 'none';
// some browsers need this to stop the default drag ghost
this.img.style.webkitUserDrag = 'none';
this.wrapper.appendChild(this.img);
// speech bubble
this.bubble = document.createElement('div');
Object.assign(this.bubble.style, {
position: 'absolute',
bottom: '100%',
left: '50%',
transform: 'translateX(-50%)',
padding: '8px 12px',
background: 'white',
border: '1px solid #ccc',
borderRadius: '4px',
boxShadow: '0 2px 6px rgba(0,0,0,0.2)',
opacity: '0',
transition: 'opacity 0.3s',
maxWidth: '200px',
wordWrap: 'break-word',
fontFamily: 'sans-serif',
fontSize: '14px',
color: '#333',
pointerEvents: 'none'
});
this.wrapper.appendChild(this.bubble);
this.container.appendChild(this.wrapper);
}
_startBlinking() {
const delay = this.blinkMin + Math.random() * (this.blinkMax - this.blinkMin);
this._blinkTimeout = setTimeout(() => {
if (!this._isSpeaking) {
this.img.src = this.images.eyesClosed;
setTimeout(() => {
this.img.src = this.images.default;
this._startBlinking();
}, this.blinkDuration);
} else {
this._startBlinking();
}
}, delay);
}
_bindMouseHold() {
let holdTimer = null;
const closeEyes = () => {
clearTimeout(holdTimer);
this.img.src = this.images.eyesClosed;
};
const reopenEyes = () => {
clearTimeout(holdTimer);
if (!this._isSpeaking) {
this.img.src = this.images.default;
}
};
this.img.addEventListener('mousedown', () => {
// if currently talking, ignore hold-to-close
if (this._isSpeaking) return;
closeEyes();
// force reopen after max 5s
holdTimer = setTimeout(reopenEyes, 4000);
});
['mouseup', 'mouseleave'].forEach(evt =>
this.img.addEventListener(evt, reopenEyes)
);
}
/** Call when streaming text begins */
beginSpeech() {
clearTimeout(this._speechTimeout);
clearInterval(this._talkIntervalId);
this._isSpeaking = true;
this._mouthOpen = false;
this.img.src = this.images.default;
this.bubble.style.opacity = '1';
this.bubble.textContent = '';
this._talkIntervalId = setInterval(() => {
this._mouthOpen = !this._mouthOpen;
this.img.src = this._mouthOpen
? this.images.mouthOpen
: this.images.default;
}, this.talkInterval / 2);
}
/** Append a chunk of streamed text */
appendSpeech(chunk) {
this.bubble.textContent += chunk;
}
/** Call when the stream ends */
endSpeech() {
clearInterval(this._talkIntervalId);
this.img.src = this.images.default;
this._speechTimeout = setTimeout(() => {
this.bubble.style.opacity = '0';
this._isSpeaking = false;
}, 3000);
}
/** Clean up timers & DOM */
destroy() {
clearTimeout(this._blinkTimeout);
clearInterval(this._talkIntervalId);
clearTimeout(this._speechTimeout);
this.wrapper.remove();
}
}

BIN
assets/cat/default.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

BIN
assets/cat/eyes_closed.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

BIN
assets/cat/mouth_open.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

121
index.html Normal file
View File

@@ -0,0 +1,121 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>auto-git</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
#catSlot img {
width: 120px;
height: 120px;
}
/* Außenschale für den Diff: overflow + max-height */
.diff-container {
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease;
}
/* Pfeil-Icon: 90°-Rotation */
.rotate {
transition: transform 0.3s ease;
}
.rotate.open {
transform: rotate(90deg);
}
/* Diff-Zeilen hervorheben */
.diff-line {
white-space: pre-wrap;
font-family: monospace;
}
.diff-line.addition {
background-color: #dafbe1; /* GitHub-grün */
}
.diff-line.deletion {
background-color: #ffeef0; /* GitHub-rot */
}
/* Deaktivierter Button */
.disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* verhindert den Hover-Effekt, wenn disabled */
button.disabled {
opacity: 0.5;
cursor: not-allowed;
pointer-events: none;
}
button.disabled:hover {
background-color: transparent;
}
@keyframes glow {
0%, 100% { box-shadow: 0 0 4px gold; }
50% { box-shadow: 0 0 12px gold; }
}
/* Klasse für den aktuellen Commit */
.current-commit {
animation: glow 4s infinite ease-in-out;
/* stell sicher, dass Du überhaupt eine sichtbare Border hast: */
border-width: 1px !important;
border-style: solid !important;
border-color: gold !important;
}
</style>
</head>
<body class="flex h-screen bg-white">
<!-- Sidebar -->
<aside class="w-64 bg-[#fff1f2] border-r border-[#ffe4e6] flex flex-col">
<h2 class="px-4 py-3 text-lg font-semibold text-gray-900">Monitored Folders</h2>
<ul id="folderList" class="flex-1 px-2 space-y-2 overflow-y-auto"></ul>
<button id="addFolderBtn" class="mx-4 mb-4 flex items-center justify-center space-x-2 px-3 py-2 bg-[#ffe4e6] rounded hover:bg-[#fecdd3]">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-[#9f1239]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
</svg>
<span class="text-sm font-medium text-[#9f1239]">Add Folder</span>
</button>
</aside>
<!-- Main panel -->
<main class="relative flex flex-col flex-1 bg-white">
<div class="flex-1 p-4 overflow-y-auto">
<h3 id="currentTitle" class="text-xl font-semibold mb-2">No folder selected</h3>
<div class="border-t border-[#ffe4e6] mb-4"></div>
<ul id="contentList" class="space-y-1"></ul>
</div>
<div id="catSlot" class="absolute bottom-10 right-4"></div>
<div class="w-full flex items-center p-4 bg-[#fff1f2] border-t border-[#ffe4e6]"></div>
<script src="renderer.js"></script>
<script type="module">
import { AnimeCat } from './animeCat.js';
document.addEventListener('DOMContentLoaded', () => {
const slot = document.getElementById('catSlot');
const cat = new AnimeCat(slot, {
images: {
default: 'assets/cat/default.png',
eyesClosed: 'assets/cat/eyes_closed.png',
mouthOpen: 'assets/cat/mouth_open.png'
}
});
async function simulateStream(text) {
cat.beginSpeech();
for (let ch of text) {
cat.appendSpeech(ch);
await new Promise(r => setTimeout(r, 50));
}
cat.endSpeech();
}
simulateStream("Hi there! I'm your friendly assistant 👋");
});
</script>
</main>
</body>
</html>

194
main.js Normal file
View File

@@ -0,0 +1,194 @@
const { app, BrowserWindow, ipcMain, dialog } = require('electron');
const { exec } = require('child_process');
const path = require('path');
const fs = require('fs');
const Store = require('electron-store');
const simpleGit = require('simple-git');
const chokidar = require('chokidar');
const store = new Store({
defaults: {
folders: [],
selected: null
}
});
// Map zum Speichern der Watcher pro Ordner
const repoWatchers = new Map();
/**
* Erstellt das BrowserWindow und lädt index.html.
* Gibt das Window-Objekt zurück.
*/
function createWindow() {
const win = new BrowserWindow({
width: 900,
height: 600,
title: 'auto-git',
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true
}
});
win.loadFile('index.html');
return win;
}
/**
* Startet einen File-Watcher auf .git/refs/heads/master,
* sendet bei Änderungen 'repo-updated' an den Renderer.
*/
function watchRepo(folder, win) {
const gitHead = path.join(folder, '.git', 'refs', 'heads', 'master');
const watcher = chokidar.watch(gitHead, { ignoreInitial: true });
watcher.on('change', () => {
win.webContents.send('repo-updated', folder);
});
repoWatchers.set(folder, watcher);
}
/**
* Initiiert ein Git-Repo in `folder`, falls noch nicht vorhanden,
* und erzeugt einen Initial-Commit mit Timestamp.
*/
async function initGitRepo(folder) {
const git = simpleGit(folder);
const gitDir = path.join(folder, '.git');
if (!fs.existsSync(gitDir)) {
await git.init();
const message = `Initial commit: ${new Date().toISOString()}`;
const readmePath = path.join(folder, 'README.md');
fs.writeFileSync(readmePath, `# Projekt in ${path.basename(folder)}\n`);
await git.add('./*');
await git.commit(message);
}
}
app.whenReady().then(() => {
const win = createWindow();
// 1) Beim Start bereits gespeicherte Ordner überwachen
const folders = store.get('folders');
folders.forEach(folder => {
// nur watchen, wenn .git existiert
if (fs.existsSync(path.join(folder, '.git', 'refs', 'heads', 'master'))) {
watchRepo(folder, win);
}
});
// 2) IPC-Handler
// Liste aller Folders
ipcMain.handle('get-folders', () => store.get('folders'));
// Ordner hinzufügen: Open-Dialog, init, Store-Update, watchen
ipcMain.handle('add-folder', async () => {
const { canceled, filePaths } = await dialog.showOpenDialog({
properties: ['openDirectory']
});
if (canceled || !filePaths[0]) {
return store.get('folders');
}
const newFolder = filePaths[0];
// Repo initialisieren
await initGitRepo(newFolder);
// Im Store ablegen
const current = store.get('folders');
if (!current.includes(newFolder)) {
store.set('folders', [...current, newFolder]);
}
store.set('selected', newFolder);
// und watchen
watchRepo(newFolder, win);
return store.get('folders');
});
// Ordner entfernen: Watcher schließen, Store-Update
ipcMain.handle('remove-folder', (_e, folder) => {
const watcher = repoWatchers.get(folder);
if (watcher) {
watcher.close();
repoWatchers.delete(folder);
}
const updated = store.get('folders').filter(f => f !== folder);
store.set('folders', updated);
if (store.get('selected') === folder) {
store.set('selected', null);
}
return updated;
});
// Selected
ipcMain.handle('get-selected', () => store.get('selected'));
ipcMain.handle('set-selected', (_e, folder) => {
store.set('selected', folder);
return folder;
});
// Commits holen
ipcMain.handle('get-commits', async (_e, folder) => {
const git = simpleGit(folder);
// alle Commits holen
const log = await git.log(['--all']);
// aktuellen HEADHash ermitteln
const fullHead = (await git.revparse(['--verify', 'HEAD'])).trim();
const head = fullHead.substring(0, 7);
return {
head,
commits: log.all.map(c => ({
hash: c.hash.substring(0, 7),
date: c.date,
message: c.message
}))
};
});
// Diff
ipcMain.handle('diff-commit', async (_e, folder, hash) => {
const git = simpleGit(folder);
return git.diff([`${hash}^!`]);
});
// Revert
ipcMain.handle('revert-commit', async (_e, folder, hash) => {
const git = simpleGit(folder);
await git.revert(hash, ['--no-edit']);
});
/**
* Checkt das Arbeitsverzeichnis auf exakt den Zustand von `hash` aus.
*/
ipcMain.handle('checkout-commit', async (_e, folder, hash) => {
const git = simpleGit(folder);
// clean mode: alle lokalen Veränderungen verwerfen
await git.checkout([hash, '--force']);
});
// Snapshot
ipcMain.handle('snapshot-commit', async (_e, folder, hash) => {
const { canceled, filePaths } = await dialog.showOpenDialog({
title: 'Ordner auswählen zum Speichern des Snapshots',
properties: ['openDirectory']
});
if (canceled || !filePaths[0]) return;
const outDir = filePaths[0];
const baseName = path.basename(folder);
const filePath = path.join(outDir, `${baseName}-${hash}.zip`);
return new Promise((resolve, reject) => {
exec(
`git -C "${folder}" archive --format zip --output "${filePath}" ${hash}`,
err => err ? reject(err) : resolve(filePath)
);
});
});
});
// clean up on exit
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});

16
package.json Normal file
View File

@@ -0,0 +1,16 @@
{
"name": "auto-git",
"version": "1.0.0",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"dependencies": {
"chokidar": "^4.0.3",
"electron-store": "^8.2.0",
"simple-git": "^3.20.0"
},
"devDependencies": {
"electron": "^25.0.0"
}
}

19
preload.js Normal file
View File

@@ -0,0 +1,19 @@
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('electronAPI', {
getFolders: () => ipcRenderer.invoke('get-folders'),
addFolder: () => ipcRenderer.invoke('add-folder'),
removeFolder: folder => ipcRenderer.invoke('remove-folder', folder),
getSelected: () => ipcRenderer.invoke('get-selected'),
setSelected: folder => ipcRenderer.invoke('set-selected', folder),
listFolder: folder => ipcRenderer.invoke('list-folder', folder),
getCommits: folder => ipcRenderer.invoke('get-commits', folder),
diffCommit: (folder, hash) => ipcRenderer.invoke('diff-commit', folder, hash),
revertCommit: (folder, hash) => ipcRenderer.invoke('revert-commit', folder, hash),
snapshotCommit: (folder, hash) => ipcRenderer.invoke('snapshot-commit', folder, hash),
checkoutCommit: (folder, hash) => ipcRenderer.invoke('checkout-commit', folder, hash),
});
ipcRenderer.on('repo-updated', (_e, folder) => {
window.dispatchEvent(new CustomEvent('repo-updated', { detail: folder }));
});

230
renderer.js Normal file
View File

@@ -0,0 +1,230 @@
// renderer.jsx
window.addEventListener('DOMContentLoaded', async () => {
const folderList = document.getElementById('folderList');
const addBtn = document.getElementById('addFolderBtn');
const titleEl = document.getElementById('currentTitle');
const contentList = document.getElementById('contentList');
window.addEventListener('repo-updated', e => {
const updatedFolder = e.detail;
const current = titleEl.textContent;
if (current === updatedFolder) {
renderContent(current);
}
});
function basename(fullPath) {
return fullPath.replace(/.*[\\/]/, '');
}
async function renderSidebar() {
const folders = await window.electronAPI.getFolders();
const selected = await window.electronAPI.getSelected();
folderList.innerHTML = '';
folders.forEach(folder => {
const li = document.createElement('li');
li.className = [
'flex items-center justify-between px-3 py-2 rounded cursor-pointer text-[#9f1239]',
folder === selected ? 'bg-[#fecdd3]' : ''
].join(' ');
li.innerHTML = `
<span class="flex items-center space-x-2 truncate">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-[#9f1239]" fill="none"
viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M3 7a2 2 0 012-2h4l2 2h6a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V7"/>
</svg>
<span class="truncate">${basename(folder)}</span>
</span>
<button class="text-[#9f1239] hover:text-opacity-80 remove-btn">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none"
viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M6 18L18 6M6 6l12 12"/>
</svg>
</button>
`;
li.addEventListener('click', async e => {
if (e.target.closest('.remove-btn')) return;
await window.electronAPI.setSelected(folder);
await renderSidebar();
await renderContent(folder);
});
li.querySelector('.remove-btn').addEventListener('click', async () => {
await window.electronAPI.removeFolder(folder);
await renderSidebar();
titleEl.textContent = 'No folder selected';
contentList.innerHTML = '';
});
folderList.appendChild(li);
});
}
async function renderContent(folder) {
const currentFolder = folder;
titleEl.textContent = folder;
const { head, commits } = await window.electronAPI.getCommits(folder);
contentList.innerHTML = commits.map(c => `
<li class="w-full p-3 mb-2 bg-white border border-gray-200 rounded shadow-sm
${c.hash === head ? 'current-commit' : ''}">
<div class="flex justify-between text-sm text-gray-600 mb-1">
<span>${c.hash}</span>
<span>${new Date(c.date).toLocaleString()}</span>
</div>
<div class="text-gray-800 mb-2">${c.message}</div>
<div class="flex space-x-2 mb-2">
<!-- Changes-Button -->
<button class="diff-btn flex items-center px-2 py-1 text-xs border rounded hover:bg-gray-100" data-hash="${c.hash}">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1 rotate" viewBox="0 0 24 24"
stroke="currentColor" fill="none">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M9 5l7 7-7 7"/>
</svg>
Changes
</button>
<!-- Snapshot-Button -->
<button class="snapshot-btn flex items-center px-2 py-1 text-xs border rounded hover:bg-gray-100" data-hash="${c.hash}">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0l-4 4m4-4v12"/>
</svg>
Snapshot
</button>
<!-- Checkout-Button -->
<button
class="checkout-btn flex items-center px-2 py-1 text-xs border rounded ${c.hash === head ? 'disabled' : 'hover:bg-gray-100'}"
data-hash="${c.hash}"
${c.hash === head ? 'disabled' : ''}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M15 12H3m12 0l-4-4m4 4l-4 4"/>
</svg>
Jump Here
</button>
<!-- Revert-Button -->
<!--<button class="revert-btn flex items-center px-2 py-1 text-xs border rounded hover:bg-gray-100" data-hash="${c.hash}">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none"
viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M15 12H3m12 0l-4-4m4 4l-4 4"/>
</svg>
Revert
</button>-->
</div>
<div class="diff-container">
<pre class="m-0"></pre>
</div>
</li>
`).join('');
// Erst mal alle Diff-Buttons prüfen und ggf. deaktivieren
contentList.querySelectorAll('.diff-btn').forEach(async btn => {
const hash = btn.dataset.hash;
const diffText = await window.electronAPI.diffCommit(folder, hash);
if (!diffText.trim()) {
btn.disabled = true;
btn.classList.add('disabled');
}
});
// Diff-Toggle & Highlighting
contentList.querySelectorAll('.diff-btn').forEach(btn => {
btn.addEventListener('click', async () => {
const li = btn.closest('li');
const hash = btn.dataset.hash;
const svg = btn.querySelector('svg');
const container = li.querySelector('.diff-container');
const pre = container.querySelector('pre');
if (!pre.innerHTML.trim()) {
// fetch und HTML-Snippet bauen
const diff = await window.electronAPI.diffCommit(folder, hash);
const escaped = diff
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
pre.innerHTML = escaped
.split('\n')
.map(line => {
const cls = line.startsWith('+')
? 'diff-line addition'
: line.startsWith('-')
? 'diff-line deletion'
: 'diff-line';
return `<div class="${cls}">${line}</div>`;
})
.join('');
}
const isOpen = container.classList.toggle('open');
if (isOpen) {
container.style.maxHeight = container.scrollHeight + 'px';
} else {
container.style.maxHeight = '0';
}
svg.classList.toggle('open', isOpen);
});
});
// Snapshot-Button
contentList.querySelectorAll('.snapshot-btn').forEach(btn => {
btn.addEventListener('click', async () => {
const hash = btn.dataset.hash;
try {
// verwende jetzt currentFolder statt einer undefinierten Variable
const savedPath = await window.electronAPI.snapshotCommit(currentFolder, hash);
if (savedPath) {
alert(`Snapshot gespeichert unter:\n${savedPath}`);
}
} catch (err) {
console.error(err);
alert('Snapshot fehlgeschlagen');
}
});
});
// Revert-Button
contentList.querySelectorAll('.revert-btn').forEach(btn => {
btn.addEventListener('click', async () => {
const hash = btn.dataset.hash;
if (confirm(`Commit ${hash} wirklich revertieren?`)) {
await window.electronAPI.revertCommit(folder, hash);
await renderContent(folder);
}
});
});
// Checkout-Button
contentList.querySelectorAll('.checkout-btn').forEach(btn => {
btn.addEventListener('click', async () => {
const hash = btn.dataset.hash;
//if (!confirm(`Jump here? Ungestagte Änderungen werden verworfen.`)) return;
// currentFolder hast du oben in renderContent gespeichert
await window.electronAPI.checkoutCommit(currentFolder, hash);
await renderContent(currentFolder);
});
});
const currentEl = contentList.querySelector('li.current-commit');
if (currentEl) {
// weich scrollen und zentriert in den Viewport bringen
currentEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}
// initial
await renderSidebar();
const initial = await window.electronAPI.getSelected();
if (initial) await renderContent(initial);
// Add-Folder
addBtn.addEventListener('click', async () => {
await window.electronAPI.addFolder();
await renderSidebar();
const sel = await window.electronAPI.getSelected();
if (sel) await renderContent(sel);
});
});