Compare commits

..
Author SHA1 Message Date
lemonknowsall 31b2a1eb4e windows path resolution for electron 2025-12-18 21:40:20 -08:00
31 changed files with 417 additions and 1521 deletions

No files matched your search

+35 -20
View File
@@ -178,9 +178,13 @@ ipcMain.handle('get-platform', () => {
}); });
// Helper function to expand tilde (~) in paths // Helper function to expand tilde (~) in paths
// Handles both Unix (~/) and Windows (~\) style paths
function expandTilde(filepath) { function expandTilde(filepath) {
if (filepath.startsWith('~/') || filepath === '~') { if (filepath === '~') {
return path.join(os.homedir(), filepath.slice(1)); return os.homedir();
}
if (filepath.startsWith('~/') || filepath.startsWith('~\\')) {
return path.join(os.homedir(), filepath.slice(2));
} }
return filepath; return filepath;
} }
@@ -188,10 +192,8 @@ function expandTilde(filepath) {
// Filesystem IPC handlers // Filesystem IPC handlers
ipcMain.handle('fs:readFile', async (event, filePath, encoding) => { ipcMain.handle('fs:readFile', async (event, filePath, encoding) => {
if (!filePath) { if (!filePath) {
const err = new Error('Failed to read file: path is required'); // Return error object instead of throwing to avoid Electron's noisy error logging
err.code = 'EINVAL'; return { __error: true, code: 'EINVAL', message: 'Failed to read file: path is required' };
// Don't log - empty paths are expected from isomorphic-git's ref resolution
throw err;
} }
try { try {
const fullPath = expandTilde(filePath); const fullPath = expandTilde(filePath);
@@ -199,10 +201,13 @@ ipcMain.handle('fs:readFile', async (event, filePath, encoding) => {
// If no encoding, convert Buffer to array for IPC serialization // If no encoding, convert Buffer to array for IPC serialization
return encoding ? data : Array.from(data); return encoding ? data : Array.from(data);
} catch (error) { } catch (error) {
// Re-throw with original error code preserved for ENOENT handling // For ENOENT/EINVAL errors, return error info instead of throwing to avoid Electron's noisy error logging
// Serialize the error code as a regular property so it survives IPC // These are expected during module resolution and git operations
if (error.code === 'ENOENT' || error.code === 'EINVAL') {
return { __error: true, code: error.code, message: `Failed to read file ${filePath}: ${error.message}` };
}
// Re-throw other errors with original error code preserved
const err = new Error(`Failed to read file ${filePath}: ${error.message}`); const err = new Error(`Failed to read file ${filePath}: ${error.message}`);
// Copy enumerable properties including code
if (error.code) { if (error.code) {
Object.defineProperty(err, 'code', { Object.defineProperty(err, 'code', {
value: error.code, value: error.code,
@@ -211,11 +216,7 @@ ipcMain.handle('fs:readFile', async (event, filePath, encoding) => {
configurable: true, configurable: true,
}); });
} }
// Don't log ENOENT errors - these are expected for git packed objects and missing refs console.error(err);
// Only log unexpected errors
if (error.code !== 'ENOENT' && error.code !== 'EINVAL') {
console.error(err);
}
throw err; throw err;
} }
}); });
@@ -263,7 +264,11 @@ ipcMain.handle('fs:readdir', async (event, dirPath, withFileTypes) => {
return entries; return entries;
} catch (error) { } catch (error) {
// Re-throw with original error code preserved for ENOENT handling // Return error object instead of throwing for expected errors to suppress Electron's noisy logging
if (error.code === 'ENOTDIR' || error.code === 'ENOENT') {
return { __error: true, message: error.message, code: error.code };
}
// For other errors, re-throw with original error code preserved
const err = new Error(`Failed to read directory ${dirPath}: ${error.message}`); const err = new Error(`Failed to read directory ${dirPath}: ${error.message}`);
if (error.code) { if (error.code) {
Object.defineProperty(err, 'code', { Object.defineProperty(err, 'code', {
@@ -273,10 +278,6 @@ ipcMain.handle('fs:readdir', async (event, dirPath, withFileTypes) => {
configurable: true, configurable: true,
}); });
} }
// Only log non-ENOTDIR errors (ENOTDIR is expected when checking if a file is a directory)
if (error.code !== 'ENOTDIR') {
console.error(err);
}
throw err; throw err;
} }
}); });
@@ -323,7 +324,12 @@ ipcMain.handle('fs:stat', async (event, filePath) => {
atime: stats.atime?.getTime() ?? now, atime: stats.atime?.getTime() ?? now,
}; };
} catch (error) { } catch (error) {
// Re-throw with original error code preserved for ENOENT handling // For ENOENT errors, return error info instead of throwing to avoid Electron's noisy error logging
// These are expected during module resolution and git operations
if (error.code === 'ENOENT') {
return { __error: true, code: 'ENOENT', message: `Failed to stat ${filePath}: ${error.message}` };
}
// Re-throw other errors with original error code preserved
const err = new Error(`Failed to stat ${filePath}: ${error.message}`); const err = new Error(`Failed to stat ${filePath}: ${error.message}`);
if (error.code) { if (error.code) {
Object.defineProperty(err, 'code', { Object.defineProperty(err, 'code', {
@@ -361,6 +367,10 @@ ipcMain.handle('fs:lstat', async (event, filePath) => {
atime: stats.atime?.getTime() ?? now, atime: stats.atime?.getTime() ?? now,
}; };
} catch (error) { } catch (error) {
// For ENOENT errors, return error info instead of throwing to avoid Electron's noisy error logging
if (error.code === 'ENOENT') {
return { __error: true, code: 'ENOENT', message: `Failed to lstat ${filePath}: ${error.message}` };
}
const err = new Error(`Failed to lstat ${filePath}: ${error.message}`); const err = new Error(`Failed to lstat ${filePath}: ${error.message}`);
if (error.code) { if (error.code) {
Object.defineProperty(err, 'code', { Object.defineProperty(err, 'code', {
@@ -379,6 +389,11 @@ ipcMain.handle('fs:unlink', async (event, filePath) => {
const fullPath = expandTilde(filePath); const fullPath = expandTilde(filePath);
await fs.unlink(fullPath); await fs.unlink(fullPath);
} catch (error) { } catch (error) {
// Return error object instead of throwing for ENOENT to suppress Electron's noisy logging
// This is expected when isomorphic-git tries to delete .git/shallow on non-shallow clones
if (error.code === 'ENOENT') {
return { __error: true, message: error.message, code: error.code };
}
const err = new Error(`Failed to unlink ${filePath}: ${error.message}`); const err = new Error(`Failed to unlink ${filePath}: ${error.message}`);
if (error.code) { if (error.code) {
Object.defineProperty(err, 'code', { Object.defineProperty(err, 'code', {
+33 -11
View File
@@ -196,6 +196,7 @@
"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==", "integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@babel/code-frame": "^7.27.1", "@babel/code-frame": "^7.27.1",
"@babel/generator": "^7.28.5", "@babel/generator": "^7.28.5",
@@ -1831,6 +1832,7 @@
} }
], ],
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=18" "node": ">=18"
}, },
@@ -1854,6 +1856,7 @@
} }
], ],
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=18" "node": ">=18"
} }
@@ -1875,6 +1878,7 @@
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz", "resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==", "integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@dnd-kit/accessibility": "^3.1.1", "@dnd-kit/accessibility": "^3.1.1",
"@dnd-kit/utilities": "^3.2.2", "@dnd-kit/utilities": "^3.2.2",
@@ -5459,8 +5463,7 @@
"resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
"integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==", "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT"
"peer": true
}, },
"node_modules/@types/cacheable-request": { "node_modules/@types/cacheable-request": {
"version": "6.0.3", "version": "6.0.3",
@@ -5702,6 +5705,7 @@
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.20.tgz", "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.20.tgz",
"integrity": "sha512-IPaCZN7PShZK/3t6Q87pfTkRm6oLTd4vztyoj+cbHUF1g3FfVb2tFIL79uCRKEfv16AhqDMBywP2VW3KIZUvcg==", "integrity": "sha512-IPaCZN7PShZK/3t6Q87pfTkRm6oLTd4vztyoj+cbHUF1g3FfVb2tFIL79uCRKEfv16AhqDMBywP2VW3KIZUvcg==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@types/prop-types": "*", "@types/prop-types": "*",
"csstype": "^3.0.2" "csstype": "^3.0.2"
@@ -5713,6 +5717,7 @@
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==", "integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
"devOptional": true, "devOptional": true,
"license": "MIT", "license": "MIT",
"peer": true,
"peerDependencies": { "peerDependencies": {
"@types/react": "^18.0.0" "@types/react": "^18.0.0"
} }
@@ -5817,6 +5822,7 @@
"integrity": "sha512-oU/OtYVydhXnumd0BobL9rkJg7wFJ9bFFPmSmB/bf/XWN85hlViji59ko6bSKBXyseT9V8l+CN1nwmlbiN0G7Q==", "integrity": "sha512-oU/OtYVydhXnumd0BobL9rkJg7wFJ9bFFPmSmB/bf/XWN85hlViji59ko6bSKBXyseT9V8l+CN1nwmlbiN0G7Q==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@typescript-eslint/scope-manager": "8.31.1", "@typescript-eslint/scope-manager": "8.31.1",
"@typescript-eslint/types": "8.31.1", "@typescript-eslint/types": "8.31.1",
@@ -6176,6 +6182,7 @@
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"license": "MIT", "license": "MIT",
"peer": true,
"bin": { "bin": {
"acorn": "bin/acorn" "acorn": "bin/acorn"
}, },
@@ -6679,6 +6686,7 @@
} }
], ],
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"baseline-browser-mapping": "^2.8.19", "baseline-browser-mapping": "^2.8.19",
"caniuse-lite": "^1.0.30001751", "caniuse-lite": "^1.0.30001751",
@@ -6947,6 +6955,7 @@
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
"integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"anymatch": "~3.1.2", "anymatch": "~3.1.2",
"braces": "~3.0.2", "braces": "~3.0.2",
@@ -7747,8 +7756,7 @@
"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",
"integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT"
"peer": true
}, },
"node_modules/dom-helpers": { "node_modules/dom-helpers": {
"version": "5.2.1", "version": "5.2.1",
@@ -7832,7 +7840,8 @@
"version": "8.6.0", "version": "8.6.0",
"resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz", "resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz",
"integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==", "integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==",
"license": "MIT" "license": "MIT",
"peer": true
}, },
"node_modules/embla-carousel-react": { "node_modules/embla-carousel-react": {
"version": "8.6.0", "version": "8.6.0",
@@ -8146,6 +8155,7 @@
"integrity": "sha512-QldCVh/ztyKJJZLr4jXNUByx3gR+TDYZCRXEktiZoUR3PGy4qCmSbkxcIle8GEwGpb5JBZazlaJ/CxLidXdEbQ==", "integrity": "sha512-QldCVh/ztyKJJZLr4jXNUByx3gR+TDYZCRXEktiZoUR3PGy4qCmSbkxcIle8GEwGpb5JBZazlaJ/CxLidXdEbQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/eslint-utils": "^4.2.0",
"@eslint-community/regexpp": "^4.12.1", "@eslint-community/regexpp": "^4.12.1",
@@ -8411,6 +8421,7 @@
"resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz", "resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz",
"integrity": "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==", "integrity": "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"accepts": "^2.0.0", "accepts": "^2.0.0",
"body-parser": "^2.2.0", "body-parser": "^2.2.0",
@@ -9633,6 +9644,7 @@
} }
], ],
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@babel/runtime": "^7.27.6" "@babel/runtime": "^7.27.6"
}, },
@@ -10416,6 +10428,7 @@
"integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"cssstyle": "^4.2.1", "cssstyle": "^4.2.1",
"data-urls": "^5.0.0", "data-urls": "^5.0.0",
@@ -10812,7 +10825,6 @@
"integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"bin": { "bin": {
"lz-string": "bin/bin.js" "lz-string": "bin/bin.js"
} }
@@ -12610,6 +12622,7 @@
} }
], ],
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"nanoid": "^3.3.8", "nanoid": "^3.3.8",
"picocolors": "^1.1.1", "picocolors": "^1.1.1",
@@ -12777,7 +12790,6 @@
"integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"ansi-regex": "^5.0.1", "ansi-regex": "^5.0.1",
"ansi-styles": "^5.0.0", "ansi-styles": "^5.0.0",
@@ -12793,7 +12805,6 @@
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=8" "node": ">=8"
} }
@@ -12804,7 +12815,6 @@
"integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=10" "node": ">=10"
}, },
@@ -12817,8 +12827,7 @@
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT"
"peer": true
}, },
"node_modules/prismjs": { "node_modules/prismjs": {
"version": "1.30.0", "version": "1.30.0",
@@ -13026,6 +13035,7 @@
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"loose-envify": "^1.1.0" "loose-envify": "^1.1.0"
}, },
@@ -13052,6 +13062,7 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"loose-envify": "^1.1.0", "loose-envify": "^1.1.0",
"scheduler": "^0.23.2" "scheduler": "^0.23.2"
@@ -13077,6 +13088,7 @@
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.56.1.tgz", "resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.56.1.tgz",
"integrity": "sha512-qWAVokhSpshhcEuQDSANHx3jiAEFzu2HAaaQIzi/r9FNPm1ioAvuJSD4EuZzWd7Al7nTRKcKPnBKO7sRn+zavQ==", "integrity": "sha512-qWAVokhSpshhcEuQDSANHx3jiAEFzu2HAaaQIzi/r9FNPm1ioAvuJSD4EuZzWd7Al7nTRKcKPnBKO7sRn+zavQ==",
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=18.0.0" "node": ">=18.0.0"
}, },
@@ -13125,6 +13137,7 @@
"resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz", "resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz",
"integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==", "integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@types/hast": "^3.0.0", "@types/hast": "^3.0.0",
"@types/mdast": "^4.0.0", "@types/mdast": "^4.0.0",
@@ -13706,6 +13719,7 @@
"integrity": "sha512-C5VvvgCCyfyotVITIAv+4efVytl5F7wt+/I2i9q9GZcEXW9BP52YYOXC58igUi+LFZVHukErIIqQSWwv/M3WRw==", "integrity": "sha512-C5VvvgCCyfyotVITIAv+4efVytl5F7wt+/I2i9q9GZcEXW9BP52YYOXC58igUi+LFZVHukErIIqQSWwv/M3WRw==",
"devOptional": true, "devOptional": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@types/estree": "1.0.7" "@types/estree": "1.0.7"
}, },
@@ -14820,6 +14834,7 @@
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.17.tgz", "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.17.tgz",
"integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==", "integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@alloc/quick-lru": "^5.2.0", "@alloc/quick-lru": "^5.2.0",
"arg": "^5.0.2", "arg": "^5.0.2",
@@ -15023,6 +15038,7 @@
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==", "integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
}, },
@@ -15318,6 +15334,7 @@
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==", "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
"devOptional": true, "devOptional": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"peer": true,
"bin": { "bin": {
"tsc": "bin/tsc", "tsc": "bin/tsc",
"tsserver": "bin/tsserver" "tsserver": "bin/tsserver"
@@ -15845,6 +15862,7 @@
"integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==", "integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"esbuild": "^0.25.0", "esbuild": "^0.25.0",
"fdir": "^6.4.4", "fdir": "^6.4.4",
@@ -15989,6 +16007,7 @@
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==", "integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
}, },
@@ -16459,6 +16478,7 @@
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"fast-deep-equal": "^3.1.3", "fast-deep-equal": "^3.1.3",
"fast-uri": "^3.0.1", "fast-uri": "^3.0.1",
@@ -16535,6 +16555,7 @@
"integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==", "integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"bin": { "bin": {
"rollup": "dist/bin/rollup" "rollup": "dist/bin/rollup"
}, },
@@ -16994,6 +17015,7 @@
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
"license": "MIT", "license": "MIT",
"peer": true,
"funding": { "funding": {
"url": "https://github.com/sponsors/colinhacks" "url": "https://github.com/sponsors/colinhacks"
} }
-1
View File
@@ -137,7 +137,6 @@ const defaultConfig: AppConfig = {
fsPathTemplates: electronPaths.fsPathTemplates, fsPathTemplates: electronPaths.fsPathTemplates,
sentryDsn: import.meta.env.VITE_SENTRY_DSN || "", sentryDsn: import.meta.env.VITE_SENTRY_DSN || "",
sentryEnabled: true, sentryEnabled: true,
communityFollowPack: "nevent1qvzqqqr4xypzpyexz3t34l966ngh5xg7u2q788hthdqmj0av3lv8s2tz9t43zt6dqy28wumn8ghj7un9d3shjtnyv9kh2uewd9hsz9nhwden5te0wfjkccte9ehx7um5wghxyctwvsq3gamnwvaz7tmwdaehgu3wdau8gu3wv3jhvqgawaehxw309ahx7um5wgkhqatz9emk2mrvdaexgetj9ehx2aqpp4mhxue69uhkummn9ekx7mqpzemhxue69uhhyetvv9ujuurjd9kkzmpwdejhgqgwwaehxw309ahx7uewd3hkctcpz9mhxue69uhkummnw3ezuamfdejj7qghwaehxw309aex2mrp0yhxummnw3ezucnpdejz7qgmwaehxw309aex2mrp0yhxummnw3e8qmr9vfejucm0d5hsz8mhwden5te0dehhxarj94ex2mrp0yhxgetjv44hymmnwvhx6ef0qyt8wumn8ghj7mn0wd68yetvd96x2uewdaexwtcprfmhxue69uhhq7tjv9kkjepwve5kzar2v9nzucm0d5hszfthwden5te0dehhxarj94ex2mrp0yhxgetjv44hymmnwvhx6ef0d9hxymmc9uqzqq6casgsyhj2c29rjlcy3tu3devp3akg7j6zqr296met9gz98np3qkwsg5",
}; };
// Initialize filesystem adapter based on environment // Initialize filesystem adapter based on environment
-2
View File
@@ -5,7 +5,6 @@ import { URLFragmentHandler } from "./components/URLFragmentHandler";
import Index from "./pages/Index"; import Index from "./pages/Index";
import Clone from "./pages/Clone"; import Clone from "./pages/Clone";
import Community from "./pages/Community";
import Settings from "./pages/Settings"; import Settings from "./pages/Settings";
import Preferences from "./pages/Preferences"; import Preferences from "./pages/Preferences";
import NostrSettings from "./pages/NostrSettings"; import NostrSettings from "./pages/NostrSettings";
@@ -37,7 +36,6 @@ export function AppRouter() {
<Route path="/" element={<Index />} /> <Route path="/" element={<Index />} />
<Route path="/giftcard" element={<Index />} /> <Route path="/giftcard" element={<Index />} />
<Route path="/clone" element={<Clone />} /> <Route path="/clone" element={<Clone />} />
<Route path="/community" element={<Community />} />
<Route path="/oauth/github" element={<GitHubOAuth />} /> <Route path="/oauth/github" element={<GitHubOAuth />} />
<Route path="/oauth/netlify" element={<NetlifyOAuth />} /> <Route path="/oauth/netlify" element={<NetlifyOAuth />} />
<Route path="/oauth/vercel" element={<VercelOAuth />} /> <Route path="/oauth/vercel" element={<VercelOAuth />} />
+8 -8
View File
@@ -3,6 +3,7 @@ import { z } from 'zod';
import { useLocalStorage } from '@/hooks/useLocalStorage'; import { useLocalStorage } from '@/hooks/useLocalStorage';
import { AppContext, type AppConfig, type AppContextType, type Theme, type RelayMetadata } from '@/contexts/AppContext'; import { AppContext, type AppConfig, type AppContextType, type Theme, type RelayMetadata } from '@/contexts/AppContext';
import i18n from '@/lib/i18n'; import i18n from '@/lib/i18n';
import { expandTildePath, normalizeToForwardSlashes } from '@/lib/pathUtils';
interface AppProviderProps { interface AppProviderProps {
children: ReactNode; children: ReactNode;
@@ -50,7 +51,6 @@ const AppConfigSchema = z.object({
sentryDsn: z.string(), sentryDsn: z.string(),
sentryEnabled: z.boolean(), sentryEnabled: z.boolean(),
systemPrompt: z.string(), systemPrompt: z.string(),
communityFollowPack: z.string(),
}) satisfies z.ZodType<AppConfig>; }) satisfies z.ZodType<AppConfig>;
export function AppProvider(props: AppProviderProps) { export function AppProvider(props: AppProviderProps) {
@@ -157,16 +157,16 @@ function useApplyLanguage(language?: string): void {
}, [language]); }, [language]);
} }
/** Expand FS paths with the user's home directory, if available. */ /** Expand FS paths with the user's home directory, if available.
* Also normalizes to forward slashes for cross-platform consistency.
*/
function expandPath(path: string): string { function expandPath(path: string): string {
const homedir = window.electron?.homedir; const homedir = window.electron?.homedir;
if (!homedir) { if (!homedir) {
return path; return path;
} else if (path.startsWith('~/')) {
return homedir + path.slice(1);
} else if (path === '~') {
return homedir;
} else {
return path;
} }
// Expand tilde and normalize to forward slashes for consistency
// This ensures paths work correctly on Windows where homedir uses backslashes
const expanded = expandTildePath(path, homedir);
return normalizeToForwardSlashes(expanded);
} }
+2 -1
View File
@@ -3,6 +3,7 @@ import { Dialog, DialogPortal, DialogOverlay } from '@/components/ui/dialog';
import * as DialogPrimitive from '@radix-ui/react-dialog'; import * as DialogPrimitive from '@radix-ui/react-dialog';
import { VFSImage } from '@/components/VFSImage'; import { VFSImage } from '@/components/VFSImage';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { isAbsolutePath } from '@/lib/pathUtils';
interface ImageLightboxProps { interface ImageLightboxProps {
imageUrl: string | null; imageUrl: string | null;
@@ -46,7 +47,7 @@ export function ImageLightbox({ imageUrl, onClose }: ImageLightboxProps) {
className="relative z-[2] flex items-center justify-center w-full h-full pointer-events-none" className="relative z-[2] flex items-center justify-center w-full h-full pointer-events-none"
onClick={(e) => e.stopPropagation()} onClick={(e) => e.stopPropagation()}
> >
{imageUrl.startsWith('/') ? ( {isAbsolutePath(imageUrl) ? (
<VFSImage <VFSImage
path={imageUrl} path={imageUrl}
alt="Expanded image" alt="Expanded image"
+3 -4
View File
@@ -128,10 +128,9 @@ describe('NoteContent', () => {
expect(mention).toHaveClass('text-gray-500'); expect(mention).toHaveClass('text-gray-500');
expect(mention).not.toHaveClass('text-blue-500'); expect(mention).not.toHaveClass('text-blue-500');
// The text should contain @ and a generated name (not a truncated npub) // The text should start with @ and contain a generated name (not a truncated npub)
// Note: textContent includes the avatar fallback initials (e.g., "SW")
const linkText = mention.textContent; const linkText = mention.textContent;
expect(linkText).not.toMatch(/@npub1/); // Should not be a truncated npub expect(linkText).not.toMatch(/^@npub1/); // Should not be a truncated npub
expect(linkText).toContain("@Swift Falcon"); expect(linkText).toEqual("@Swift Falcon");
}); });
}); });
+38 -249
View File
@@ -2,28 +2,19 @@ import { useMemo } from 'react';
import { type NostrEvent } from '@nostrify/nostrify'; import { type NostrEvent } from '@nostrify/nostrify';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { nip19 } from 'nostr-tools'; import { nip19 } from 'nostr-tools';
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import { useAuthor } from '@/hooks/useAuthor'; import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName'; import { genUserName } from '@/lib/genUserName';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
interface NoteContentProps { interface NoteContentProps {
event: NostrEvent; event: NostrEvent;
className?: string; className?: string;
/** When true, renders mentions and hashtags as styled text instead of clickable links */
disableLinks?: boolean;
/** When true, hides embedded note/event previews entirely */
hideEmbeds?: boolean;
} }
/** Parses content of text note events so that URLs and hashtags are linkified. */ /** Parses content of text note events so that URLs and hashtags are linkified. */
export function NoteContent({ export function NoteContent({
event, event,
className, className,
disableLinks = false,
hideEmbeds = false,
}: NoteContentProps) { }: NoteContentProps) {
// Process the content to render mentions, links, etc. // Process the content to render mentions, links, etc.
const content = useMemo(() => { const content = useMemo(() => {
@@ -47,26 +38,18 @@ export function NoteContent({
} }
if (url) { if (url) {
// Handle URLs - always render as links (but prevent click propagation when disableLinks) // Handle URLs
if (disableLinks) { parts.push(
parts.push( <a
<span key={`url-${keyCounter++}`} className="text-blue-500"> key={`url-${keyCounter++}`}
{url} href={url}
</span> target="_blank"
); rel="noopener noreferrer"
} else { className="text-blue-500 hover:underline"
parts.push( >
<a {url}
key={`url-${keyCounter++}`} </a>
href={url} );
target="_blank"
rel="noopener noreferrer"
className="text-blue-500 hover:underline"
>
{url}
</a>
);
}
} else if (nostrPrefix && nostrData) { } else if (nostrPrefix && nostrData) {
// Handle Nostr references // Handle Nostr references
try { try {
@@ -76,56 +59,19 @@ export function NoteContent({
if (decoded.type === 'npub') { if (decoded.type === 'npub') {
const pubkey = decoded.data; const pubkey = decoded.data;
parts.push( parts.push(
<NostrMention key={`mention-${keyCounter++}`} pubkey={pubkey} disableLink={disableLinks} /> <NostrMention key={`mention-${keyCounter++}`} pubkey={pubkey} />
); );
} else if (decoded.type === 'nprofile') {
const pubkey = decoded.data.pubkey;
parts.push(
<NostrMention key={`mention-${keyCounter++}`} pubkey={pubkey} disableLink={disableLinks} />
);
} else if (decoded.type === 'nevent') {
if (hideEmbeds) {
// Skip embedded events entirely when hideEmbeds is true
} else if (disableLinks) {
parts.push(
<NostrEventPreview key={`event-${keyCounter++}`} eventId={decoded.data.id} />
);
} else {
parts.push(
<NostrEventEmbed key={`event-${keyCounter++}`} eventId={decoded.data.id} />
);
}
} else if (decoded.type === 'note') {
if (hideEmbeds) {
// Skip embedded notes entirely when hideEmbeds is true
} else if (disableLinks) {
parts.push(
<NostrEventPreview key={`event-${keyCounter++}`} eventId={decoded.data} />
);
} else {
parts.push(
<NostrEventEmbed key={`event-${keyCounter++}`} eventId={decoded.data} />
);
}
} else { } else {
// For other types, just show as styled text or link // For other types, just show as a link
if (disableLinks) { parts.push(
parts.push( <Link
<span key={`nostr-${keyCounter++}`} className="text-blue-500"> key={`nostr-${keyCounter++}`}
{fullMatch} to={`/${nostrId}`}
</span> className="text-blue-500 hover:underline"
); >
} else { {fullMatch}
parts.push( </Link>
<Link );
key={`nostr-${keyCounter++}`}
to={`/${nostrId}`}
className="text-blue-500 hover:underline"
>
{fullMatch}
</Link>
);
}
} }
} catch { } catch {
// If decoding fails, just render as text // If decoding fails, just render as text
@@ -133,24 +79,16 @@ export function NoteContent({
} }
} else if (hashtag) { } else if (hashtag) {
// Handle hashtags // Handle hashtags
if (disableLinks) { const tag = hashtag.slice(1); // Remove the #
parts.push( parts.push(
<span key={`hashtag-${keyCounter++}`} className="text-blue-500"> <Link
{hashtag} key={`hashtag-${keyCounter++}`}
</span> to={`/t/${tag}`}
); className="text-blue-500 hover:underline"
} else { >
const tag = hashtag.slice(1); // Remove the # {hashtag}
parts.push( </Link>
<Link );
key={`hashtag-${keyCounter++}`}
to={`/t/${tag}`}
className="text-blue-500 hover:underline"
>
{hashtag}
</Link>
);
}
} }
lastIndex = index + fullMatch.length; lastIndex = index + fullMatch.length;
@@ -167,7 +105,7 @@ export function NoteContent({
} }
return parts; return parts;
}, [event, disableLinks, hideEmbeds]); }, [event]);
return ( return (
<div className={cn("whitespace-pre-wrap break-words", className)}> <div className={cn("whitespace-pre-wrap break-words", className)}>
@@ -176,173 +114,24 @@ export function NoteContent({
); );
} }
// Helper component to display user mentions with avatar // Helper component to display user mentions
function NostrMention({ pubkey, disableLink = false }: { pubkey: string; disableLink?: boolean }) { function NostrMention({ pubkey }: { pubkey: string }) {
const author = useAuthor(pubkey); const author = useAuthor(pubkey);
const npub = nip19.npubEncode(pubkey); const npub = nip19.npubEncode(pubkey);
const hasRealName = !!author.data?.metadata?.name; const hasRealName = !!author.data?.metadata?.name;
const displayName = author.data?.metadata?.name ?? genUserName(pubkey); const displayName = author.data?.metadata?.name ?? genUserName(pubkey);
const picture = author.data?.metadata?.picture;
const content = (
<>
<Avatar className="h-4 w-4 inline-block">
<AvatarImage src={picture} alt={displayName} />
<AvatarFallback className="text-[8px]">{displayName.slice(0, 2).toUpperCase()}</AvatarFallback>
</Avatar>
@{displayName}
</>
);
if (disableLink) {
return (
<span
className={cn(
"inline-flex items-center gap-1 font-medium",
hasRealName
? "text-blue-500"
: "text-gray-500"
)}
>
{content}
</span>
);
}
return ( return (
<Link <Link
to={`/${npub}`} to={`/${npub}`}
className={cn( className={cn(
"inline-flex items-center gap-1 font-medium hover:underline", "font-medium hover:underline",
hasRealName hasRealName
? "text-blue-500" ? "text-blue-500"
: "text-gray-500 hover:text-gray-700" : "text-gray-500 hover:text-gray-700"
)} )}
> >
{content} @{displayName}
</Link> </Link>
); );
} }
// Helper component to display embedded events
function NostrEventEmbed({ eventId }: { eventId: string }) {
const { nostr } = useNostr();
const { data: event, isLoading } = useQuery({
queryKey: ['nostr', 'event', eventId],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
const [event] = await nostr.query([{ ids: [eventId], limit: 1 }], { signal });
return event;
},
staleTime: 300000,
});
const author = useAuthor(event?.pubkey);
const note1 = nip19.noteEncode(eventId);
if (isLoading) {
return (
<div className="my-2 p-3 border rounded-lg bg-muted/30 animate-pulse">
<div className="h-4 bg-muted rounded w-1/3 mb-2" />
<div className="h-3 bg-muted rounded w-full" />
</div>
);
}
if (!event) {
return (
<Link
to={`/${note1}`}
className="text-blue-500 hover:underline"
>
nostr:{note1.slice(0, 12)}...
</Link>
);
}
const displayName = author.data?.metadata?.name ?? genUserName(event.pubkey);
const picture = author.data?.metadata?.picture;
const contentPreview = event.content.length > 200
? event.content.slice(0, 200) + '...'
: event.content;
return (
<Link
to={`/${note1}`}
className="block my-2 p-3 border rounded-lg bg-muted/30 hover:bg-muted/50 transition-colors no-underline"
>
<div className="flex items-center gap-2 mb-2">
<Avatar className="h-5 w-5">
<AvatarImage src={picture} alt={displayName} />
<AvatarFallback className="text-[10px]">{displayName.slice(0, 2).toUpperCase()}</AvatarFallback>
</Avatar>
<span className="font-medium text-sm text-foreground">{displayName}</span>
<span className="text-xs text-muted-foreground">
{new Date(event.created_at * 1000).toLocaleDateString()}
</span>
</div>
<p className="text-sm text-muted-foreground whitespace-pre-wrap break-words">
{contentPreview}
</p>
</Link>
);
}
// Helper component to display embedded events without links (for use inside clickable cards)
function NostrEventPreview({ eventId }: { eventId: string }) {
const { nostr } = useNostr();
const { data: event, isLoading } = useQuery({
queryKey: ['nostr', 'event', eventId],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
const [event] = await nostr.query([{ ids: [eventId], limit: 1 }], { signal });
return event;
},
staleTime: 300000,
});
const author = useAuthor(event?.pubkey);
if (isLoading) {
return (
<div className="my-2 p-3 border rounded-lg bg-muted/30 animate-pulse">
<div className="h-4 bg-muted rounded w-1/3 mb-2" />
<div className="h-3 bg-muted rounded w-full" />
</div>
);
}
if (!event) {
return (
<span className="text-blue-500">
[quoted note]
</span>
);
}
const displayName = author.data?.metadata?.name ?? genUserName(event.pubkey);
const picture = author.data?.metadata?.picture;
const contentPreview = event.content.length > 200
? event.content.slice(0, 200) + '...'
: event.content;
return (
<div className="my-2 p-3 border rounded-lg bg-muted/30">
<div className="flex items-center gap-2 mb-2">
<Avatar className="h-5 w-5">
<AvatarImage src={picture} alt={displayName} />
<AvatarFallback className="text-[10px]">{displayName.slice(0, 2).toUpperCase()}</AvatarFallback>
</Avatar>
<span className="font-medium text-sm text-foreground">{displayName}</span>
<span className="text-xs text-muted-foreground">
{new Date(event.created_at * 1000).toLocaleDateString()}
</span>
</div>
<p className="text-sm text-muted-foreground whitespace-pre-wrap break-words">
{contentPreview}
</p>
</div>
);
}
+2 -11
View File
@@ -1,7 +1,7 @@
import React, { useEffect, useState, useMemo } from 'react'; import React, { useEffect, useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Plus, Folder, GitBranch, Loader2, ChevronDown, ChevronRight, Star, Columns2, X, Settings, HelpCircle, Search, Tag, Folders, Users } from 'lucide-react'; import { Plus, Folder, GitBranch, Loader2, ChevronDown, ChevronRight, Star, Columns2, X, Settings, HelpCircle, Search, Tag, Folders } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton'; import { Skeleton } from '@/components/ui/skeleton';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
@@ -511,7 +511,7 @@ export function ProjectSidebar({
</div> </div>
</div> </div>
{/* Settings, Community, and Help at Bottom */} {/* Settings and Help at Bottom */}
<div className="border-t border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5 mt-auto pb-safe"> <div className="border-t border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5 mt-auto pb-safe">
<div className="p-2 flex items-center gap-2"> <div className="p-2 flex items-center gap-2">
<Button <Button
@@ -523,15 +523,6 @@ export function ProjectSidebar({
<Settings className="h-4 w-4 transition-colors duration-200" /> <Settings className="h-4 w-4 transition-colors duration-200" />
{t('settings')} {t('settings')}
</Button> </Button>
<Button
variant="ghost"
size="sm"
className="h-9 w-9 p-0 text-sidebar-foreground dark:hover:text-sidebar-primary hover:bg-primary/10 dark:hover:bg-sidebar-accent/30 transition-all duration-200"
onClick={() => navigateAndClose('/community')}
aria-label={t('community')}
>
<Users className="h-4 w-4 transition-colors duration-200" />
</Button>
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
-4
View File
@@ -40,7 +40,6 @@ describe('SentryProvider', () => {
fsPathTmp: '/tmp', fsPathTmp: '/tmp',
fsPathPlugins: '/plugins', fsPathPlugins: '/plugins',
fsPathTemplates: '/templates', fsPathTemplates: '/templates',
communityFollowPack: '',
}; };
render( render(
@@ -78,7 +77,6 @@ describe('SentryProvider', () => {
fsPathTmp: '/tmp', fsPathTmp: '/tmp',
fsPathPlugins: '/plugins', fsPathPlugins: '/plugins',
fsPathTemplates: '/templates', fsPathTemplates: '/templates',
communityFollowPack: '',
}; };
render( render(
@@ -117,7 +115,6 @@ describe('SentryProvider', () => {
fsPathTmp: '/tmp', fsPathTmp: '/tmp',
fsPathPlugins: '/plugins', fsPathPlugins: '/plugins',
fsPathTemplates: '/templates', fsPathTemplates: '/templates',
communityFollowPack: '',
}; };
render( render(
@@ -159,7 +156,6 @@ describe('SentryProvider', () => {
fsPathTmp: '/tmp', fsPathTmp: '/tmp',
fsPathPlugins: '/plugins', fsPathPlugins: '/plugins',
fsPathTemplates: '/templates', fsPathTemplates: '/templates',
communityFollowPack: '',
}; };
render( render(
+5 -3
View File
@@ -428,11 +428,13 @@ export function ToolCallDisplay({ toolName, toolArgs, state, result }: ToolCallD
// For completed state, we need the result // For completed state, we need the result
if (!result) return null; if (!result) return null;
// Parse "Generated image: /tmp/filename.png" from result // Parse "Generated image: <path>" from result
const match = result.match(/Generated image:\s*(\/tmp\/[^\s\n]+)/); // Path can be VFS style (/tmp/...) or OS path (C:/Users/.../Temp/... on Windows)
const match = result.match(/Generated image:\s*([^\s\n]+)/);
if (match) { if (match) {
const imagePath = match[1]; const imagePath = match[1];
const filename = imagePath.split('/').pop() || imagePath; // Handle both forward and back slashes for getting filename
const filename = imagePath.split(/[/\\]/).pop() || imagePath;
// Hide the image section if there was a load error // Hide the image section if there was a load error
if (imageLoadError) return null; if (imageLoadError) return null;
-2
View File
@@ -57,8 +57,6 @@ export interface AppConfig {
sentryEnabled: boolean; sentryEnabled: boolean;
/** System prompt EJS template */ /** System prompt EJS template */
systemPrompt?: string; systemPrompt?: string;
/** Nostr follow pack naddr for community events (e.g., "naddr1...") */
communityFollowPack: string;
} }
export interface AppContextType { export interface AppContextType {
-359
View File
@@ -1,359 +0,0 @@
import { type NostrEvent, NRelay1 } from '@nostrify/nostrify';
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import { nip19 } from 'nostr-tools';
import { useAppContext } from '@/hooks/useAppContext';
// ShakespeareGitCommits bot npub
// npub1msc06u2v3y3z2awdxlc7k2tnjlc78xg8awvha5rsaphd8py7ussqd0phxu
const COMMITS_BOT_PUBKEY = 'dc30f45e534244455d5ba6fc3b2acfc9ff2a1cd8aa31fb50c70bbfab5294f016';
// Shakespeare group ID for kind 9 chat messages
const SHAKESPEARE_GROUP_ID = '41299083392805314';
// Shakespeare chat relay (NIP-29 group relay)
const SHAKESPEARE_CHAT_RELAY = 'wss://chat.shakespeare.diy/';
// Featured testimonials - curated note IDs
const FEATURED_TESTIMONIAL_IDS: string[] = [
// Add hand-selected note IDs here as they are curated
];
/**
* Hook to fetch #ShakespeareDIY feed (kind 1 notes with the hashtag)
*/
export function useShakespeareFeed(limit = 20) {
const { nostr } = useNostr();
return useQuery<NostrEvent[]>({
queryKey: ['shakespeare-feed', limit],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
const events = await nostr.query(
[{ kinds: [1], '#t': ['shakespearediy', 'ShakespeareDIY'], limit }],
{ signal }
);
return events;
},
staleTime: 60000, // 1 minute
});
}
/**
* Helper to check if an event title contains "shakespeare" (case-insensitive)
*/
function hasShakespeareInTitle(event: NostrEvent): boolean {
const title = event.tags.find(([name]) => name === 'title')?.[1]
|| event.tags.find(([name]) => name === 'name')?.[1]
|| '';
return title.toLowerCase().includes('shakespeare');
}
/**
* Decoded follow pack data - either from naddr or nevent
*/
type FollowPackData = {
/** For naddr: query by author, kind, and d-tag */
type: 'naddr';
pubkey: string;
kind: number;
identifier: string;
} | {
/** For nevent: query by event id */
type: 'nevent';
id: string;
relays?: string[];
};
/**
* Decode a follow pack identifier (naddr or nevent) to get its components
*/
function decodeFollowPackIdentifier(identifier: string): FollowPackData | null {
try {
const decoded = nip19.decode(identifier);
if (decoded.type === 'naddr') {
return {
type: 'naddr',
pubkey: decoded.data.pubkey,
kind: decoded.data.kind,
identifier: decoded.data.identifier,
};
}
if (decoded.type === 'nevent') {
return {
type: 'nevent',
id: decoded.data.id,
relays: decoded.data.relays,
};
}
} catch {
// Invalid identifier
}
return null;
}
/**
* Hook to fetch the community follow pack to get team member pubkeys
* Uses the communityFollowPack setting from the app config
* Supports both naddr and nevent identifiers
*/
export function useCommunityFollowPack() {
const { nostr } = useNostr();
const { config } = useAppContext();
const followPackData = decodeFollowPackIdentifier(config.communityFollowPack);
return useQuery<string[]>({
queryKey: ['community-follow-pack', config.communityFollowPack],
queryFn: async (c) => {
if (!followPackData) {
return [];
}
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
let events: NostrEvent[];
if (followPackData.type === 'naddr') {
// Query by author, kind, and d-tag for addressable events
events = await nostr.query(
[{
kinds: [followPackData.kind],
authors: [followPackData.pubkey],
'#d': [followPackData.identifier],
limit: 1,
}],
{ signal }
);
} else {
// Query by event id for nevent
events = await nostr.query(
[{
ids: [followPackData.id],
limit: 1,
}],
{ signal }
);
}
if (events.length === 0) {
return [];
}
// Extract all pubkeys from p tags
const pubkeys = events[0].tags
.filter(([name]) => name === 'p')
.map(([, pubkey]) => pubkey);
return pubkeys;
},
staleTime: 300000, // 5 minutes
enabled: !!followPackData,
});
}
/**
* Hook to fetch calendar events from community follow pack members (NIP-52)
* Filtered to only show events with "shakespeare" in the title
* Fetches both date-based (31922) and time-based (31923) calendar events
*/
export function useCommunityEvents(limit = 10) {
const { nostr } = useNostr();
const { config } = useAppContext();
const { data: teamPubkeys } = useCommunityFollowPack();
return useQuery<NostrEvent[]>({
queryKey: ['community-events', limit, config.communityFollowPack, teamPubkeys],
queryFn: async (c) => {
if (!teamPubkeys || teamPubkeys.length === 0) {
return [];
}
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
// Query for calendar events created by or mentioning team members
const [createdEvents, attendingEvents] = await Promise.all([
// Events created by team members
nostr.query(
[{
kinds: [31922, 31923],
authors: teamPubkeys,
limit: limit * 2,
}],
{ signal }
),
// Events where team members are tagged as participants
nostr.query(
[{
kinds: [31922, 31923],
'#p': teamPubkeys,
limit: limit * 2,
}],
{ signal }
),
]);
// Combine all events and filter to only include those with "shakespeare" in the title
const allEvents = [
...createdEvents,
...attendingEvents,
].filter(hasShakespeareInTitle);
// Deduplicate events by id
const uniqueEvents = allEvents.filter((event, index, self) =>
index === self.findIndex(e => e.id === event.id)
);
// Filter for future events only
const now = Math.floor(Date.now() / 1000);
return uniqueEvents.filter(event => {
const startTag = event.tags.find(([name]) => name === 'start')?.[1];
if (!startTag) return false;
// For time-based events, start is a unix timestamp
if (event.kind === 31923) {
const startTime = parseInt(startTag, 10);
return !isNaN(startTime) && startTime > now;
}
// For date-based events, start is YYYY-MM-DD
if (event.kind === 31922) {
const today = new Date().toISOString().split('T')[0];
return startTag >= today;
}
return true;
}).sort((a, b) => {
// Sort by start date/time
const aStart = a.tags.find(([name]) => name === 'start')?.[1] || '';
const bStart = b.tags.find(([name]) => name === 'start')?.[1] || '';
return aStart.localeCompare(bStart);
});
},
staleTime: 300000, // 5 minutes
enabled: !!teamPubkeys && teamPubkeys.length > 0,
});
}
/**
* Hook to fetch latest commits from ShakespeareGitCommits bot (NIP-29 kind 9 chat messages)
* Connects directly to the Shakespeare chat relay since kind 9 events are relay-specific
*/
export function useLatestCommits(limit = 5) {
return useQuery<NostrEvent[]>({
queryKey: ['latest-commits', limit],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
// Connect directly to the Shakespeare chat relay for kind 9 events
const relay = new NRelay1(SHAKESPEARE_CHAT_RELAY);
try {
// Query for kind 9 chat messages from the commits bot in the Shakespeare group
const events = await relay.query(
[{
kinds: [9],
authors: [COMMITS_BOT_PUBKEY],
'#h': [SHAKESPEARE_GROUP_ID],
limit
}],
{ signal }
);
return events;
} finally {
relay.close();
}
},
staleTime: 60000, // 1 minute
});
}
/**
* Hook to fetch featured testimonials (hand-picked kind 1 notes)
*/
export function useFeaturedTestimonials() {
const { nostr } = useNostr();
return useQuery<NostrEvent[]>({
queryKey: ['featured-testimonials'],
queryFn: async (c) => {
if (FEATURED_TESTIMONIAL_IDS.length === 0) {
return [];
}
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
const events = await nostr.query(
[{ kinds: [1], ids: FEATURED_TESTIMONIAL_IDS }],
{ signal }
);
return events;
},
staleTime: 300000, // 5 minutes
enabled: FEATURED_TESTIMONIAL_IDS.length > 0,
});
}
/**
* Helper to extract calendar event metadata from a NostrEvent
*/
export function extractCalendarEventData(event: NostrEvent) {
const tags = event.tags;
return {
id: tags.find(([name]) => name === 'd')?.[1] || event.id,
title: tags.find(([name]) => name === 'title')?.[1] || tags.find(([name]) => name === 'name')?.[1] || 'Untitled Event',
summary: tags.find(([name]) => name === 'summary')?.[1] || '',
description: event.content || '',
image: tags.find(([name]) => name === 'image')?.[1],
location: tags.find(([name]) => name === 'location')?.[1],
start: tags.find(([name]) => name === 'start')?.[1] || '',
end: tags.find(([name]) => name === 'end')?.[1],
startTzid: tags.find(([name]) => name === 'start_tzid')?.[1],
endTzid: tags.find(([name]) => name === 'end_tzid')?.[1],
geohash: tags.find(([name]) => name === 'g')?.[1],
hashtags: tags.filter(([name]) => name === 't').map(([, value]) => value),
references: tags.filter(([name]) => name === 'r').map(([, value]) => value),
kind: event.kind,
pubkey: event.pubkey,
created_at: event.created_at,
};
}
/**
* Format a calendar event date for display
*/
export function formatEventDate(start: string, kind: number, startTzid?: string): string {
if (kind === 31923) {
// Time-based event - start is unix timestamp
const timestamp = parseInt(start, 10);
if (isNaN(timestamp)) return 'Invalid date';
const date = new Date(timestamp * 1000);
const options: Intl.DateTimeFormatOptions = {
weekday: 'short',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: '2-digit',
timeZoneName: 'short',
};
if (startTzid) {
options.timeZone = startTzid;
}
return date.toLocaleString(undefined, options);
}
if (kind === 31922) {
// Date-based event - start is YYYY-MM-DD
const date = new Date(start + 'T00:00:00');
return date.toLocaleDateString(undefined, {
weekday: 'long',
month: 'long',
day: 'numeric',
year: 'numeric',
});
}
return start;
}
-2
View File
@@ -75,7 +75,6 @@ describe('useGenerateProjectInfo', () => {
fsPathTemplates: '/templates', fsPathTemplates: '/templates',
sentryDsn: '', sentryDsn: '',
sentryEnabled: false, sentryEnabled: false,
communityFollowPack: '',
}; };
mockUseAppContext.mockReturnValue({ mockUseAppContext.mockReturnValue({
config, config,
@@ -229,7 +228,6 @@ describe('useGenerateProjectInfo', () => {
fsPathTemplates: '/templates', fsPathTemplates: '/templates',
sentryDsn: '', sentryDsn: '',
sentryEnabled: false, sentryEnabled: false,
communityFollowPack: '',
}; };
mockUseAppContext.mockReturnValue({ mockUseAppContext.mockReturnValue({
config, config,
-1
View File
@@ -52,7 +52,6 @@ function createWrapper(corsProxy: string) {
fsPathTemplates: '/templates', fsPathTemplates: '/templates',
sentryDsn: '', sentryDsn: '',
sentryEnabled: false, sentryEnabled: false,
communityFollowPack: 'naddr1qvzqqqr4xgpzpjcswsacvumftxsmcejj3vsxu8mf203p8hkxoklxtgva7rdxzm0qqy88wumn8ghj7mn0wd68yttsw43z7qg4waehxw309aex2mrp0yhx6mmddaehgu339e3k7mf0qythwumn8ghj7cn5vvhxkmr9dejxz7n0xvs8xmmrdejhytnrdakj7q3qdqr8kgh3s5q8ztw0swmvpwz98cse7rw43n4nhrpszgafnuwrxh8hscmhv5m',
}; };
return createElement( return createElement(
+140 -9
View File
@@ -1,4 +1,25 @@
import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime'; import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime';
import { getParentDirectory } from './pathUtils';
/**
* Error object returned from IPC handlers instead of throwing
* to avoid Electron's noisy error logging for expected errors.
*/
interface IPCErrorResult {
__error: true;
code: string;
message: string;
}
/**
* Type guard to check if an IPC result is an error object.
*/
function isIPCError(result: unknown): result is IPCErrorResult {
return result !== null &&
typeof result === 'object' &&
'__error' in result &&
(result as IPCErrorResult).__error === true;
}
/** /**
* Electron filesystem adapter that implements JSRuntimeFS interface * Electron filesystem adapter that implements JSRuntimeFS interface
@@ -7,9 +28,27 @@ import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime';
* *
* Note: This adapter should only be instantiated when running in Electron. * Note: This adapter should only be instantiated when running in Electron.
*/ */
/** Stat result with function methods matching the JSRuntimeFS interface */
interface StatResult {
isDirectory(): boolean;
isFile(): boolean;
isBlockDevice(): boolean;
isCharacterDevice(): boolean;
isSymbolicLink(): boolean;
isFIFO(): boolean;
isSocket(): boolean;
size: number;
mtimeMs: number;
ctimeMs: number;
atimeMs: number;
mtime: Date;
ctime: Date;
atime: Date;
}
export class ElectronFSAdapter implements JSRuntimeFS { export class ElectronFSAdapter implements JSRuntimeFS {
// Cache for stat results to avoid repeated IPC calls // Cache for stat results to avoid repeated IPC calls
private statCache = new Map<string, { result: Awaited<ReturnType<typeof this.electron.fs.stat>>; timestamp: number }>(); private statCache = new Map<string, { result: StatResult; timestamp: number }>();
private readonly STAT_CACHE_TTL = 1000; // 1 second TTL for stat cache private readonly STAT_CACHE_TTL = 1000; // 1 second TTL for stat cache
// Cache for ENOENT results to avoid repeated failed reads (especially for git objects) // Cache for ENOENT results to avoid repeated failed reads (especially for git objects)
@@ -80,6 +119,23 @@ export class ElectronFSAdapter implements JSRuntimeFS {
const encoding = typeof options === 'string' ? options : options?.encoding; const encoding = typeof options === 'string' ? options : options?.encoding;
const result = await this.electron.fs.readFile(path, encoding); const result = await this.electron.fs.readFile(path, encoding);
// Handle error objects returned from IPC (to avoid Electron's noisy error logging)
if (isIPCError(result)) {
const err = new Error(result.message);
(err as NodeJS.ErrnoException).code = result.code;
// Cache ENOENT errors
if (result.code === 'ENOENT') {
this.enoentCache.add(path);
if (this.enoentCache.size > this.ENOENT_CACHE_MAX_SIZE) {
const entries = Array.from(this.enoentCache);
entries.slice(0, 1000).forEach(entry => this.enoentCache.delete(entry));
}
}
throw err;
}
// If no encoding, convert array to Uint8Array // If no encoding, convert array to Uint8Array
if (!encoding && Array.isArray(result)) { if (!encoding && Array.isArray(result)) {
return new Uint8Array(result); return new Uint8Array(result);
@@ -117,7 +173,7 @@ export class ElectronFSAdapter implements JSRuntimeFS {
this.statCache.delete(path); this.statCache.delete(path);
this.statCache.delete(`lstat:${path}`); this.statCache.delete(`lstat:${path}`);
this.enoentCache.delete(path); // File now exists this.enoentCache.delete(path); // File now exists
const parentDir = path.substring(0, path.lastIndexOf('/')); const parentDir = getParentDirectory(path);
if (parentDir) { if (parentDir) {
this.statCache.delete(parentDir); this.statCache.delete(parentDir);
this.statCache.delete(`lstat:${parentDir}`); this.statCache.delete(`lstat:${parentDir}`);
@@ -138,19 +194,71 @@ export class ElectronFSAdapter implements JSRuntimeFS {
// Use cached stat if available to avoid extra IPC call // Use cached stat if available to avoid extra IPC call
const cached = this.statCache.get(path); const cached = this.statCache.get(path);
if (cached && Date.now() - cached.timestamp < this.STAT_CACHE_TTL) { if (cached && Date.now() - cached.timestamp < this.STAT_CACHE_TTL) {
if (cached.result.isFile) { // Note: cached.result has isFile as a function (from statResult), so we must call it
if (cached.result.isFile()) {
// This is a file, not a directory - throw ENOTDIR immediately // This is a file, not a directory - throw ENOTDIR immediately
const err = new Error(`ENOTDIR: not a directory, scandir '${path}'`); const err = new Error(`ENOTDIR: not a directory, scandir '${path}'`);
(err as NodeJS.ErrnoException).code = 'ENOTDIR'; (err as NodeJS.ErrnoException).code = 'ENOTDIR';
throw err; throw err;
} }
} else {
// No cached stat - do a stat check first to avoid unnecessary readdir IPC calls on files
// This is important for performance since FileTree iterates all entries and calls readdir on each
try {
const statResult = await this.stat(path);
if (statResult.isFile()) {
const err = new Error(`ENOTDIR: not a directory, scandir '${path}'`);
(err as NodeJS.ErrnoException).code = 'ENOTDIR';
throw err;
}
} catch (statError) {
// If stat fails with ENOENT, let readdir handle it
if ((statError as NodeJS.ErrnoException).code !== 'ENOENT') {
throw statError;
}
}
} }
const result = await this.electron.fs.readdir(path, options?.withFileTypes); const result = await this.electron.fs.readdir(path, options?.withFileTypes);
// Handle error objects returned from IPC (to avoid Electron's noisy error logging)
if (isIPCError(result)) {
const err = new Error(result.message);
(err as NodeJS.ErrnoException).code = result.code;
throw err;
}
if (options?.withFileTypes) { if (options?.withFileTypes) {
const entries = result as Array<{ name: string; isDirectory: boolean; isFile: boolean }>;
const now = Date.now();
// Cache the file type info for each child entry to speed up subsequent stat/readdir calls
// This is a key optimization - FileTree calls readdir on all children, and we can fast-fail
// files without hitting IPC
for (const entry of entries) {
const childPath = path.endsWith('/') ? `${path}${entry.name}` : `${path}/${entry.name}`;
const nowDate = new Date(now);
const statResult: StatResult = {
isDirectory: () => entry.isDirectory,
isFile: () => entry.isFile,
isBlockDevice: () => false,
isCharacterDevice: () => false,
isSymbolicLink: () => false,
isFIFO: () => false,
isSocket: () => false,
size: 0,
mtimeMs: now,
ctimeMs: now,
atimeMs: now,
mtime: nowDate,
ctime: nowDate,
atime: nowDate,
};
this.statCache.set(childPath, { result: statResult, timestamp: now });
}
// Convert plain objects to DirectoryEntry format // Convert plain objects to DirectoryEntry format
return (result as Array<{ name: string; isDirectory: boolean; isFile: boolean }>).map(entry => ({ return entries.map(entry => ({
name: entry.name, name: entry.name,
isDirectory: () => entry.isDirectory, isDirectory: () => entry.isDirectory,
isFile: () => entry.isFile, isFile: () => entry.isFile,
@@ -173,7 +281,7 @@ export class ElectronFSAdapter implements JSRuntimeFS {
// Invalidate cache for this path and parent // Invalidate cache for this path and parent
this.statCache.delete(path); this.statCache.delete(path);
this.statCache.delete(`lstat:${path}`); this.statCache.delete(`lstat:${path}`);
const parentDir = path.substring(0, path.lastIndexOf('/')); const parentDir = getParentDirectory(path);
if (parentDir) { if (parentDir) {
this.statCache.delete(parentDir); this.statCache.delete(parentDir);
this.statCache.delete(`lstat:${parentDir}`); this.statCache.delete(`lstat:${parentDir}`);
@@ -209,6 +317,14 @@ export class ElectronFSAdapter implements JSRuntimeFS {
} }
const result = await this.electron.fs.stat(path); const result = await this.electron.fs.stat(path);
// Handle error objects returned from IPC (to avoid Electron's noisy error logging)
if (isIPCError(result)) {
const err = new Error(result.message);
(err as NodeJS.ErrnoException).code = result.code;
throw err;
}
const now = Date.now(); const now = Date.now();
const statResult = { const statResult = {
isDirectory: () => result.isDirectory, isDirectory: () => result.isDirectory,
@@ -270,6 +386,14 @@ export class ElectronFSAdapter implements JSRuntimeFS {
} }
const result = await this.electron.fs.lstat(path); const result = await this.electron.fs.lstat(path);
// Handle error objects returned from IPC (to avoid Electron's noisy error logging)
if (isIPCError(result)) {
const err = new Error(result.message);
(err as NodeJS.ErrnoException).code = result.code;
throw err;
}
const now = Date.now(); const now = Date.now();
const statResult = { const statResult = {
isDirectory: () => result.isDirectory, isDirectory: () => result.isDirectory,
@@ -309,10 +433,17 @@ export class ElectronFSAdapter implements JSRuntimeFS {
try { try {
const result = await this.electron.fs.unlink(path); const result = await this.electron.fs.unlink(path);
// Handle error objects returned from IPC (to avoid Electron's noisy error logging)
if (isIPCError(result)) {
const err = new Error(result.message);
(err as NodeJS.ErrnoException).code = result.code;
throw err;
}
// Invalidate cache for this path and parent // Invalidate cache for this path and parent
this.statCache.delete(path); this.statCache.delete(path);
this.statCache.delete(`lstat:${path}`); this.statCache.delete(`lstat:${path}`);
const parentDir = path.substring(0, path.lastIndexOf('/')); const parentDir = getParentDirectory(path);
if (parentDir) { if (parentDir) {
this.statCache.delete(parentDir); this.statCache.delete(parentDir);
this.statCache.delete(`lstat:${parentDir}`); this.statCache.delete(`lstat:${parentDir}`);
@@ -331,7 +462,7 @@ export class ElectronFSAdapter implements JSRuntimeFS {
// Invalidate cache for this path and parent // Invalidate cache for this path and parent
this.statCache.delete(path); this.statCache.delete(path);
this.statCache.delete(`lstat:${path}`); this.statCache.delete(`lstat:${path}`);
const parentDir = path.substring(0, path.lastIndexOf('/')); const parentDir = getParentDirectory(path);
if (parentDir) { if (parentDir) {
this.statCache.delete(parentDir); this.statCache.delete(parentDir);
this.statCache.delete(`lstat:${parentDir}`); this.statCache.delete(`lstat:${parentDir}`);
@@ -353,13 +484,13 @@ export class ElectronFSAdapter implements JSRuntimeFS {
this.statCache.delete(newPath); this.statCache.delete(newPath);
this.statCache.delete(`lstat:${newPath}`); this.statCache.delete(`lstat:${newPath}`);
const oldParent = oldPath.substring(0, oldPath.lastIndexOf('/')); const oldParent = getParentDirectory(oldPath);
if (oldParent) { if (oldParent) {
this.statCache.delete(oldParent); this.statCache.delete(oldParent);
this.statCache.delete(`lstat:${oldParent}`); this.statCache.delete(`lstat:${oldParent}`);
} }
const newParent = newPath.substring(0, newPath.lastIndexOf('/')); const newParent = getParentDirectory(newPath);
if (newParent) { if (newParent) {
this.statCache.delete(newParent); this.statCache.delete(newParent);
this.statCache.delete(`lstat:${newParent}`); this.statCache.delete(`lstat:${newParent}`);
-1
View File
@@ -56,7 +56,6 @@ const testConfig: AppConfig = {
fsPathTemplates: '/templates', fsPathTemplates: '/templates',
sentryDsn: '', sentryDsn: '',
sentryEnabled: false, sentryEnabled: false,
communityFollowPack: 'naddr1qvzqqqr4xgpzpjcswsacvumftxsmcejj3vsxu8mf203p8hkxoklxtgva7rdxzm0qqy88wumn8ghj7mn0wd68yttsw43z7qg4waehxw309aex2mrp0yhx6mmddaehgu339e3k7mf0qythwumn8ghj7cn5vvhxkmr9dejxz7n0xvs8xmmrdejhytnrdakj7q3qdqr8kgh3s5q8ztw0swmvpwz98cse7rw43n4nhrpszgafnuwrxh8hscmhv5m',
}; };
describe('SessionManager', () => { describe('SessionManager', () => {
+20 -4
View File
@@ -2,6 +2,7 @@ import { join, dirname, extname } from "path-browserify";
import type { Loader, Plugin } from "esbuild-wasm"; import type { Loader, Plugin } from "esbuild-wasm";
import type { JSRuntimeFS } from '@/lib/JSRuntime'; import type { JSRuntimeFS } from '@/lib/JSRuntime';
import { isAbsolutePath, normalizeToForwardSlashes } from '@/lib/pathUtils';
interface TsConfig { interface TsConfig {
compilerOptions?: { compilerOptions?: {
@@ -35,21 +36,36 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
return; return;
} }
// Check if this looks like a bare module specifier (npm package)
// Bare specifiers don't start with '.', '..', '/', or '@/' (our alias)
// Examples: 'react', 'react/jsx-runtime', '@tanstack/react-query'
const isBareSpecifier = !args.path.startsWith('.') &&
!args.path.startsWith('/') &&
!args.path.startsWith('@/') &&
!isAbsolutePath(args.path);
let resolved: string; let resolved: string;
if (args.path.startsWith("/")) { // Handle absolute paths (Unix or Windows style)
resolved = args.path; if (isAbsolutePath(args.path)) {
resolved = normalizeToForwardSlashes(args.path);
} else if (args.path.startsWith("@/")) { } else if (args.path.startsWith("@/")) {
resolved = join(cwd, "src", args.path.slice(2)); resolved = join(cwd, "src", args.path.slice(2));
} else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) { } else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
resolved = join(dirname(args.importer), args.path); resolved = join(dirname(args.importer), args.path);
} else if (args.importer && tsconfig?.compilerOptions?.baseUrl) { } else if (args.importer && tsconfig?.compilerOptions?.baseUrl && !isBareSpecifier) {
// Only use baseUrl for non-bare specifiers (local project paths)
// Don't try to resolve npm packages via baseUrl
resolved = join(cwd, tsconfig.compilerOptions.baseUrl, args.path); resolved = join(cwd, tsconfig.compilerOptions.baseUrl, args.path);
} else { } else {
return; return;
} }
// Normalize to forward slashes for consistent comparison
resolved = normalizeToForwardSlashes(resolved);
const normalizedCwd = normalizeToForwardSlashes(cwd);
// Security: prevent accessing files outside the project directory // Security: prevent accessing files outside the project directory
if (resolved.startsWith("/") && !resolved.startsWith(cwd)) { if (isAbsolutePath(resolved) && !resolved.startsWith(normalizedCwd)) {
throw new Error(`Access to files outside the project directory is not allowed: ${resolved}`); throw new Error(`Access to files outside the project directory is not allowed: ${resolved}`);
} }
+120
View File
@@ -0,0 +1,120 @@
/**
* Cross-platform path utilities for handling both Unix and Windows path separators.
* These utilities ensure consistent behavior across different operating systems.
*/
/**
* Get the parent directory of a path, handling both forward and back slashes.
* This is particularly important for Windows paths in Electron.
*
* @param path - The file or directory path
* @returns The parent directory path, or empty string if at root
*/
export function getParentDirectory(path: string): string {
// Find the last occurrence of either separator
const lastForwardSlash = path.lastIndexOf('/');
const lastBackSlash = path.lastIndexOf('\\');
const lastSeparator = Math.max(lastForwardSlash, lastBackSlash);
if (lastSeparator === -1) {
return '';
}
return path.substring(0, lastSeparator);
}
/**
* Normalize a path to use forward slashes consistently.
* This is useful for the VFS which uses Unix-style paths internally.
*
* @param path - The path to normalize
* @returns The path with all backslashes converted to forward slashes
*/
export function normalizeToForwardSlashes(path: string): string {
return path.replace(/\\/g, '/');
}
/**
* Normalize a path to use the native separator for the current platform.
* On Windows, uses backslashes; on Unix-like systems, uses forward slashes.
*
* @param path - The path to normalize
* @returns The path with separators appropriate for the current platform
*/
export function normalizeToNativeSeparator(path: string): string {
const isWindows = typeof navigator !== 'undefined'
? navigator.platform?.toLowerCase().includes('win')
: false;
if (isWindows) {
return path.replace(/\//g, '\\');
}
return path.replace(/\\/g, '/');
}
/**
* Join path segments with forward slashes, regardless of platform.
* This is useful for VFS paths which always use forward slashes.
*
* @param segments - Path segments to join
* @returns The joined path with forward slashes
*/
export function joinWithForwardSlashes(...segments: string[]): string {
return segments
.filter(Boolean)
.map(s => s.replace(/^[/\\]+|[/\\]+$/g, '')) // Trim leading/trailing slashes
.join('/');
}
/**
* Check if a path is absolute on any platform.
* Recognizes:
* - Unix absolute paths starting with /
* - Windows absolute paths starting with \ or drive letter (C:\)
*
* @param path - The path to check
* @returns True if the path is absolute
*/
export function isAbsolutePath(path: string): boolean {
return path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path);
}
/**
* Get the file name from a path, handling both separators.
*
* @param path - The file path
* @returns The file name
*/
export function getBasename(path: string): string {
const lastForwardSlash = path.lastIndexOf('/');
const lastBackSlash = path.lastIndexOf('\\');
const lastSeparator = Math.max(lastForwardSlash, lastBackSlash);
if (lastSeparator === -1) {
return path;
}
return path.substring(lastSeparator + 1);
}
/**
* Expand tilde (~) in paths to the home directory.
* Works with both Unix (~/) and Windows (~\) style paths.
*
* @param path - The path that may contain tilde
* @param homedir - The user's home directory
* @returns The expanded path
*/
export function expandTildePath(path: string, homedir: string): string {
if (path === '~') {
return homedir;
}
if (path.startsWith('~/')) {
return homedir + path.slice(1);
}
if (path.startsWith('~\\')) {
return homedir + path.slice(1);
}
return path;
}
+7 -5
View File
@@ -3,6 +3,7 @@
*/ */
import { normalize } from "path-browserify"; import { normalize } from "path-browserify";
import { normalizeToForwardSlashes } from "./pathUtils";
/** /**
* Check if the given path is an absolute path * Check if the given path is an absolute path
@@ -38,11 +39,12 @@ export function isWriteAllowed(
} }
// For absolute paths, apply restrictions // For absolute paths, apply restrictions
const absolutePath = normalize(path); // Normalize to forward slashes for consistent comparison (handles both Unix and Windows paths)
const absolutePath = normalizeToForwardSlashes(normalize(path));
// Get configured paths with defaults // Get configured paths with defaults and normalize them
const tmpPath = options?.tmpPath || '/tmp'; const tmpPath = normalizeToForwardSlashes(options?.tmpPath || '/tmp');
const projectsPath = options?.projectsPath || '/projects'; const projectsPath = normalizeToForwardSlashes(options?.projectsPath || '/projects');
// Allow writes to tmp directory and its subdirectories // Allow writes to tmp directory and its subdirectories
if (absolutePath.startsWith(tmpPath + '/') || absolutePath === tmpPath) { if (absolutePath.startsWith(tmpPath + '/') || absolutePath === tmpPath) {
@@ -56,7 +58,7 @@ export function isWriteAllowed(
// If we have a current working directory, allow writes within that directory tree // If we have a current working directory, allow writes within that directory tree
if (cwd) { if (cwd) {
const normalizedCwd = normalize(cwd); const normalizedCwd = normalizeToForwardSlashes(normalize(cwd));
if (absolutePath.startsWith(normalizedCwd + '/') || absolutePath === normalizedCwd) { if (absolutePath.startsWith(normalizedCwd + '/') || absolutePath === normalizedCwd) {
return true; return true;
} }
-1
View File
@@ -43,7 +43,6 @@ const testConfig: AppConfig = {
fsPathTemplates: '/templates', fsPathTemplates: '/templates',
sentryDsn: '', sentryDsn: '',
sentryEnabled: false, sentryEnabled: false,
communityFollowPack: 'naddr1qvzqqqr4xgpzpjcswsacvumftxsmcejj3vsxu8mf203p8hkxoklxtgva7rdxzm0qqy88wumn8ghj7mn0wd68yttsw43z7qg4waehxw309aex2mrp0yhx6mmddaehgu339e3k7mf0qythwumn8ghj7cn5vvhxkmr9dejxz7n0xvs8xmmrdejhytnrdakj7q3qdqr8kgh3s5q8ztw0swmvpwz98cse7rw43n4nhrpszgafnuwrxh8hscmhv5m',
}; };
describe('makeSystemPrompt', () => { describe('makeSystemPrompt', () => {
+3 -1
View File
@@ -1,10 +1,12 @@
import { z } from "zod"; import { z } from "zod";
import { join } from "path-browserify";
import type { Tool, ToolResult } from "./Tool"; import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime"; import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand } from "../commands/ShellCommand"; import type { ShellCommand } from "../commands/ShellCommand";
import { Git } from "../git"; import { Git } from "../git";
import { stripAnsiCodes } from "../ansiToHtml"; import { stripAnsiCodes } from "../ansiToHtml";
import type { NostrSigner } from "@nostrify/nostrify"; import type { NostrSigner } from "@nostrify/nostrify";
import { isAbsolutePath } from "../pathUtils";
import { import {
CatCommand, CatCommand,
CdCommand, CdCommand,
@@ -433,7 +435,7 @@ export class ShellTool implements Tool<ShellToolParams> {
*/ */
private async handleRedirection(output: string, redirectType: '>' | '>>', redirectFile: string): Promise<void> { private async handleRedirection(output: string, redirectType: '>' | '>>', redirectFile: string): Promise<void> {
// Resolve the file path relative to current working directory // Resolve the file path relative to current working directory
const filePath = redirectFile.startsWith('/') ? redirectFile : `${this.cwd}/${redirectFile}`; const filePath = isAbsolutePath(redirectFile) ? redirectFile : join(this.cwd, redirectFile);
if (redirectType === '>') { if (redirectType === '>') {
// Overwrite the file // Overwrite the file
-2
View File
@@ -51,8 +51,6 @@
"showcaseEnabledDescription": "Display the app showcase section on the home page", "showcaseEnabledDescription": "Display the app showcase section on the home page",
"showcaseModerator": "Showcase Moderator", "showcaseModerator": "Showcase Moderator",
"showcaseModeratorDescription": "Nostr public key (npub) of the user who can moderate showcase submissions", "showcaseModeratorDescription": "Nostr public key (npub) of the user who can moderate showcase submissions",
"communityFollowPack": "Community",
"communityFollowPackDescription": "Nostr event of the follow pack used for the Community Events section of the Community page",
"filesystemPaths": "Filesystem Paths", "filesystemPaths": "Filesystem Paths",
"projectsDirectory": "Projects Directory", "projectsDirectory": "Projects Directory",
"projectsDirectoryDescription": "Filesystem path where projects are stored", "projectsDirectoryDescription": "Filesystem path where projects are stored",
-2
View File
@@ -51,8 +51,6 @@
"showcaseEnabledDescription": "Nuna sashen nuni na aikace-aikace a shafin gida", "showcaseEnabledDescription": "Nuna sashen nuni na aikace-aikace a shafin gida",
"showcaseModerator": "Mai Kula da Nuni", "showcaseModerator": "Mai Kula da Nuni",
"showcaseModeratorDescription": "Maɓallin jama'a na Nostr (npub) na mai amfani wanda zai iya kula da ƙaddamarwar nuni", "showcaseModeratorDescription": "Maɓallin jama'a na Nostr (npub) na mai amfani wanda zai iya kula da ƙaddamarwar nuni",
"communityFollowPack": "Al'umma",
"communityFollowPackDescription": "Taron Nostr na fakitin bi da ake amfani da shi don sashen Ayyukan Al'umma a shafin Al'umma",
"filesystemPaths": "Hanyoyin Tsarin Fayil", "filesystemPaths": "Hanyoyin Tsarin Fayil",
"projectsDirectory": "Kundin Ayyuka", "projectsDirectory": "Kundin Ayyuka",
"projectsDirectoryDescription": "Hanyar tsarin fayil inda ake adana ayyuka", "projectsDirectoryDescription": "Hanyar tsarin fayil inda ake adana ayyuka",
-2
View File
@@ -51,8 +51,6 @@
"showcaseEnabledDescription": "Gosipụta ngalaba ngosipụta ngwa na ibe ụlọ", "showcaseEnabledDescription": "Gosipụta ngalaba ngosipụta ngwa na ibe ụlọ",
"showcaseModerator": "Onye Nlekọta Ngosipụta", "showcaseModerator": "Onye Nlekọta Ngosipụta",
"showcaseModeratorDescription": "Igodo ọha Nostr (npub) nke onye ọrụ nwere ike ilekọta ntinye ngosipụta", "showcaseModeratorDescription": "Igodo ọha Nostr (npub) nke onye ọrụ nwere ike ilekọta ntinye ngosipụta",
"communityFollowPack": "Obodo",
"communityFollowPackDescription": "Ihe omume Nostr nke ngwugwu eso a na-eji maka ngalaba Mmemme Obodo na ibe Obodo",
"filesystemPaths": "Ụzọ Sistemu Faịlụ", "filesystemPaths": "Ụzọ Sistemu Faịlụ",
"projectsDirectory": "Ndekọ Ọrụ", "projectsDirectory": "Ndekọ Ọrụ",
"projectsDirectoryDescription": "Ụzọ sistemu faịlụ ebe echekwara ọrụ", "projectsDirectoryDescription": "Ụzọ sistemu faịlụ ebe echekwara ọrụ",
-2
View File
@@ -51,8 +51,6 @@
"showcaseEnabledDescription": "Exibir a seção de vitrine de aplicativos na página inicial", "showcaseEnabledDescription": "Exibir a seção de vitrine de aplicativos na página inicial",
"showcaseModerator": "Moderador da Vitrine", "showcaseModerator": "Moderador da Vitrine",
"showcaseModeratorDescription": "Chave pública Nostr (npub) do usuário que pode moderar envios da vitrine", "showcaseModeratorDescription": "Chave pública Nostr (npub) do usuário que pode moderar envios da vitrine",
"communityFollowPack": "Comunidade",
"communityFollowPackDescription": "Evento Nostr do pacote de seguir usado para a seção de Eventos da Comunidade na página da Comunidade",
"filesystemPaths": "Caminhos do Sistema de Arquivos", "filesystemPaths": "Caminhos do Sistema de Arquivos",
"projectsDirectory": "Diretório de Projetos", "projectsDirectory": "Diretório de Projetos",
"projectsDirectoryDescription": "Caminho do sistema de arquivos onde os projetos são armazenados", "projectsDirectoryDescription": "Caminho do sistema de arquivos onde os projetos são armazenados",
-2
View File
@@ -51,8 +51,6 @@
"showcaseEnabledDescription": "Ṣafihan apakan ifihan ohun elo lori oju-iwe ile", "showcaseEnabledDescription": "Ṣafihan apakan ifihan ohun elo lori oju-iwe ile",
"showcaseModerator": "Oluṣakoso Ifihan", "showcaseModerator": "Oluṣakoso Ifihan",
"showcaseModeratorDescription": "Bọtini gbangba Nostr (npub) ti olumulo ti o le ṣakoso awọn ifisilẹ ifihan", "showcaseModeratorDescription": "Bọtini gbangba Nostr (npub) ti olumulo ti o le ṣakoso awọn ifisilẹ ifihan",
"communityFollowPack": "Agbegbe",
"communityFollowPackDescription": "Iṣẹlẹ Nostr ti apo atẹle ti a lo fun apakan Awọn Iṣẹlẹ Agbegbe lori oju-iwe Agbegbe",
"filesystemPaths": "Awọn Ọna Eto Faili", "filesystemPaths": "Awọn Ọna Eto Faili",
"projectsDirectory": "Itọsọna Awọn iṣẹ akanṣe", "projectsDirectory": "Itọsọna Awọn iṣẹ akanṣe",
"projectsDirectoryDescription": "Ọna eto faili nibiti a tọju awọn iṣẹ akanṣe", "projectsDirectoryDescription": "Ọna eto faili nibiti a tọju awọn iṣẹ akanṣe",
-2
View File
@@ -51,8 +51,6 @@
"showcaseEnabledDescription": "在主页上显示应用展示部分", "showcaseEnabledDescription": "在主页上显示应用展示部分",
"showcaseModerator": "展示管理员", "showcaseModerator": "展示管理员",
"showcaseModeratorDescription": "可以审核展示提交的用户的Nostr公钥(npub)", "showcaseModeratorDescription": "可以审核展示提交的用户的Nostr公钥(npub)",
"communityFollowPack": "社区",
"communityFollowPackDescription": "用于社区页面社区活动部分的关注包的Nostr事件",
"filesystemPaths": "文件系统路径", "filesystemPaths": "文件系统路径",
"projectsDirectory": "项目目录", "projectsDirectory": "项目目录",
"projectsDirectoryDescription": "存储项目的文件系统路径", "projectsDirectoryDescription": "存储项目的文件系统路径",
-748
View File
@@ -1,748 +0,0 @@
import { Link } from 'react-router-dom';
import { useSeoMeta } from '@unhead/react';
import {
ArrowLeft,
ExternalLink,
MessageCircle,
Calendar,
Award,
MapPin,
Video,
BookOpen,
Sparkles,
ArrowRight,
HelpCircle,
Megaphone,
MessageSquare,
GitBranch,
Lightbulb,
Image,
LifeBuoy,
Hash,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Skeleton } from '@/components/ui/skeleton';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { NoteContent } from '@/components/NoteContent';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { useAuthor } from '@/hooks/useAuthor';
import {
useShakespeareFeed,
useCommunityEvents,
extractCalendarEventData,
formatEventDate,
} from '@/hooks/useCommunity';
import type { NostrEvent } from '@nostrify/nostrify';
import { nip19 } from 'nostr-tools';
import { genUserName } from '@/lib/genUserName';
// Stock images for cards (to be replaced later)
const STOCK_IMAGES = {
chat: 'https://images.unsplash.com/photo-1522071820081-009f0129c71c?w=800&q=80',
events: 'https://soapbox.pub/assets/blog/shakespeare-workshop-guide/derek-shakespeare-workshop.jpeg',
ambassador: 'https://images.unsplash.com/photo-1517486808906-6ca8b3f04846?w=800&q=80',
workshop: 'https://soapbox.pub/assets/press/satsconf-brazil-2025/alex-workshop.jpeg',
};
// FAQs from soapbox.pub/shakespeare-resources
const FAQS = [
{
question: 'What is Shakespeare and how does it work?',
answer:
'Shakespeare is an AI-powered website builder that lets you create custom websites by chatting with AI. Simply describe what you want to build, and AI will code, design, and deploy your site for you.',
},
{
question: 'Do I need coding experience to use Shakespeare?',
answer:
'No coding experience required! Shakespeare is designed for everyone. Just describe your ideas in plain language and let the AI handle the technical details.',
},
{
question: 'How much does Shakespeare cost?',
answer:
'Shakespeare uses a pay-as-you-go credit system through NSPs (Nostr Service Providers). You only pay for what you use, with no monthly subscriptions required.',
},
{
question: 'Can I download my website\'s source code?',
answer:
'Yes! You can download your complete project source code at any time. You own everything you create.',
},
{
question: 'Where can I get help if I\'m stuck?',
answer:
'Join Shakespeare Chat at chat.shakespeare.diy to connect with other builders, get help from the community, and share what you\'re building!',
},
];
// Featured blog posts
const BLOG_POSTS = [
{
title: 'How to Prompt Better Projects',
url: 'https://soapbox.pub/blog/how-to-prompt-better-projects',
author: 'Derek Ross',
},
{
title: 'Deploying your Shakespeare project',
url: 'https://soapbox.pub/blog/shakespeare-deploying-sharing-projects',
author: 'M.K. Fain',
},
{
title: 'Debugging in Shakespeare',
url: 'https://soapbox.pub/blog/debugging-in-shakespeare',
author: 'Derek Ross',
},
];
export default function Community() {
useSeoMeta({
title: 'Community - Shakespeare',
description: 'Join the Shakespeare community. Connect with builders, attend events, and get help with your projects.',
});
const { data: feedPosts, isLoading: feedLoading } = useShakespeareFeed(6);
const { data: events, isLoading: eventsLoading } = useCommunityEvents(4);
return (
<div className="min-h-screen bg-gradient-to-br from-background via-background to-primary/5">
{/* Topbar */}
<div className="border-b border-border bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10">
<div className="container mx-auto px-4 py-3 max-w-5xl">
<div className="flex items-center justify-between">
<Link to="/" className="flex items-center gap-3 hover:opacity-80 transition-opacity">
<ShakespeareLogo className="w-6 h-6" />
<h1 className="text-xl font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Shakespeare
</h1>
</Link>
<Link to="/">
<Button variant="ghost" size="sm">
<ArrowLeft className="h-4 w-4 mr-2" />
Back to Projects
</Button>
</Link>
</div>
</div>
</div>
<div className="container mx-auto px-4 py-8 max-w-5xl">
<div className="space-y-12">
{/* Hero Section */}
<section className="text-center space-y-4">
<h1 className="text-4xl md:text-5xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Welcome to the Shakespeare Community
</h1>
<p className="text-lg text-muted-foreground max-w-2xl mx-auto">
Connect with builders, get help with your projects, and be part of the future of AI-powered web development.
</p>
<div className="flex flex-wrap justify-center gap-3 pt-4">
<Button asChild size="lg" className="bg-gradient-to-r from-primary to-accent hover:from-primary/90 hover:to-accent/90">
<a href="https://app.flotilla.social/join?r=chat.shakespeare.diy&c=725J9PH4" target="_blank" rel="noopener noreferrer">
<MessageCircle className="h-4 w-4 mr-2" />
Join Shakespeare Chat
</a>
</Button>
<Button asChild variant="outline" size="lg">
<a href="#events">
<Calendar className="h-4 w-4 mr-2" />
Browse Events
</a>
</Button>
</div>
</section>
{/* How to Get Involved - 3 Cards */}
<section className="space-y-6">
<h2 className="text-2xl font-bold text-center">How to Get Involved</h2>
<div className="grid md:grid-cols-3 gap-6">
{/* Join Community Online */}
<Card className="overflow-hidden group hover:shadow-lg transition-shadow flex flex-col">
<div className="aspect-[4/3] overflow-hidden">
<img
src={STOCK_IMAGES.chat}
alt="Community chat"
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
/>
</div>
<CardHeader className="flex-1">
<div className="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center mb-2">
<MessageCircle className="h-5 w-5 text-primary" />
</div>
<CardTitle>Join Community Online</CardTitle>
<CardDescription>
Chat with other Shakespeare builders, get help with your projects, and share what you're creating.
</CardDescription>
</CardHeader>
<CardContent className="mt-auto">
<Button asChild variant="outline" className="w-full">
<a href="https://app.flotilla.social/join?r=chat.shakespeare.diy&c=725J9PH4" target="_blank" rel="noopener noreferrer">
Join Shakespeare Chat
<ExternalLink className="h-4 w-4 ml-2" />
</a>
</Button>
</CardContent>
</Card>
{/* Connect IRL */}
<Card className="overflow-hidden group hover:shadow-lg transition-shadow flex flex-col">
<div className="aspect-[4/3] overflow-hidden">
<img
src={STOCK_IMAGES.events}
alt="Community events"
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
/>
</div>
<CardHeader className="flex-1">
<div className="w-10 h-10 rounded-lg bg-accent/10 flex items-center justify-center mb-2">
<Calendar className="h-5 w-5 text-accent" />
</div>
<CardTitle>Connect IRL</CardTitle>
<CardDescription>
Attend conferences, workshops, and meetups. Learn from experts and network with fellow builders.
</CardDescription>
</CardHeader>
<CardContent className="mt-auto">
<Button asChild variant="outline" className="w-full">
<a href="#events">
View Events
<ArrowRight className="h-4 w-4 ml-2" />
</a>
</Button>
</CardContent>
</Card>
{/* Become an Ambassador */}
<Card className="overflow-hidden group hover:shadow-lg transition-shadow flex flex-col">
<div className="aspect-[4/3] overflow-hidden">
<img
src={STOCK_IMAGES.ambassador}
alt="Ambassador program"
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
style={{ objectPosition: '50% 60%' }}
/>
</div>
<CardHeader className="flex-1">
<div className="w-10 h-10 rounded-lg bg-yellow-500/10 flex items-center justify-center mb-2">
<Award className="h-5 w-5 text-yellow-600" />
</div>
<CardTitle>Become an Ambassador</CardTitle>
<CardDescription>
Host workshops in your city, teach others to build with Shakespeare, and earn recognition.
</CardDescription>
</CardHeader>
<CardContent className="mt-auto">
<Button asChild variant="outline" className="w-full">
<a href="#ambassador">
Learn More
<ArrowRight className="h-4 w-4 ml-2" />
</a>
</Button>
</CardContent>
</Card>
</div>
</section>
{/* #ShakespeareDIY Feed */}
<section className="space-y-6">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
<div>
<h2 className="text-2xl font-bold flex items-center gap-2">
<Sparkles className="h-6 w-6 text-primary" />
#ShakespeareDIY Feed
</h2>
<p className="text-muted-foreground">See what the community is building</p>
</div>
<Badge variant="outline" className="w-fit">Live from Nostr</Badge>
</div>
{feedLoading ? (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{Array.from({ length: 4 }).map((_, i) => (
<Card key={i}>
<CardContent className="pt-4">
<div className="flex items-start gap-3">
<Skeleton className="h-10 w-10 rounded-full flex-shrink-0" />
<div className="flex-1 min-w-0 space-y-2">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-16 w-full" />
</div>
</div>
</CardContent>
</Card>
))}
</div>
) : feedPosts && feedPosts.length > 0 ? (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 auto-rows-fr">
{feedPosts.map((post) => (
<FeedPost key={post.id} event={post} />
))}
</div>
) : (
<Card className="border-dashed">
<CardContent className="py-12 text-center">
<p className="text-muted-foreground">
No posts yet. Be the first to share with #ShakespeareDIY!
</p>
</CardContent>
</Card>
)}
</section>
{/* Events Section */}
<section id="events" className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h2 className="text-2xl font-bold flex items-center gap-2">
<Calendar className="h-6 w-6 text-accent" />
Upcoming Events
</h2>
<p className="text-muted-foreground">Conferences, workshops, and meetups</p>
</div>
</div>
{eventsLoading ? (
<div className="grid md:grid-cols-2 gap-4">
{Array.from({ length: 2 }).map((_, i) => (
<Card key={i}>
<CardContent className="pt-4">
<Skeleton className="h-32 w-full rounded-lg mb-4" />
<Skeleton className="h-6 w-48 mb-2" />
<Skeleton className="h-4 w-32" />
</CardContent>
</Card>
))}
</div>
) : events && events.length > 0 ? (
<div className="grid md:grid-cols-2 gap-4">
{events.map((event) => (
<EventCard key={event.id} event={event} />
))}
</div>
) : (
<Card className="border-dashed">
<CardContent className="py-12 text-center">
<Calendar className="h-12 w-12 mx-auto mb-4 text-muted-foreground/50" />
<p className="text-muted-foreground">
No upcoming events. Check back soon!
</p>
</CardContent>
</Card>
)}
</section>
{/* Ambassador Program */}
<section id="ambassador" className="space-y-6">
<div className="grid md:grid-cols-2 gap-6">
<Card className="bg-gradient-to-br from-primary/5 to-accent/5 border-primary/20">
<CardHeader>
<div className="w-12 h-12 rounded-xl bg-gradient-to-br from-primary to-accent flex items-center justify-center mb-4">
<Award className="h-6 w-6 text-white" />
</div>
<CardTitle className="text-xl">Shakespeare Ambassador Program</CardTitle>
<CardDescription>
Become a community leader by hosting workshops in your city. Teach others how to build with Shakespeare
and help grow the community.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<ul className="space-y-2 text-sm">
<li className="flex items-center gap-2">
<div className="h-1.5 w-1.5 rounded-full bg-primary" />
Host local workshops and meetups
</li>
<li className="flex items-center gap-2">
<div className="h-1.5 w-1.5 rounded-full bg-primary" />
Get exclusive access to new features
</li>
<li className="flex items-center gap-2">
<div className="h-1.5 w-1.5 rounded-full bg-primary" />
Earn free credits for teaching
</li>
<li className="flex items-center gap-2">
<div className="h-1.5 w-1.5 rounded-full bg-primary" />
Be recognized in the community
</li>
</ul>
<Button asChild className="w-full">
<a href="https://app.flotilla.social/join?r=chat.shakespeare.diy&c=725J9PH4" target="_blank" rel="noopener noreferrer">
Apply to Become an Ambassador
<ExternalLink className="h-4 w-4 ml-2" />
</a>
</Button>
</CardContent>
</Card>
<Card className="overflow-hidden">
<div className="aspect-video overflow-hidden">
<img
src={STOCK_IMAGES.workshop}
alt="Workshop"
className="w-full h-full object-cover"
style={{ objectPosition: '50% 10%' }}
/>
</div>
<CardHeader>
<CardTitle>Host a Workshop</CardTitle>
<CardDescription>
Already know Shakespeare well? Host a workshop in your area and teach others how to build amazing
websites with AI.
</CardDescription>
</CardHeader>
<CardContent>
<Button asChild variant="outline" className="w-full">
<a href="https://soapbox.pub/blog/shakespeare-workshop-guide" target="_blank" rel="noopener noreferrer">
View Workshop Guide
<ExternalLink className="h-4 w-4 ml-2" />
</a>
</Button>
</CardContent>
</Card>
</div>
</section>
{/* Chat Channels */}
<section className="space-y-6">
<div>
<h2 className="text-2xl font-bold flex items-center gap-2">
<Hash className="h-6 w-6 text-primary" />
Chat Channels
</h2>
<p className="text-muted-foreground">Explore the different channels in Shakespeare Chat</p>
</div>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
<Card className="hover:shadow-md transition-shadow">
<CardHeader className="pb-2">
<div className="flex items-center gap-2">
<div className="w-8 h-8 rounded-lg bg-blue-500/10 flex items-center justify-center">
<Megaphone className="h-4 w-4 text-blue-500" />
</div>
<CardTitle className="text-base">#announcements</CardTitle>
</div>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
Official updates about Shakespeare features, releases, and important news from the team.
</p>
</CardContent>
</Card>
<Card className="hover:shadow-md transition-shadow">
<CardHeader className="pb-2">
<div className="flex items-center gap-2">
<div className="w-8 h-8 rounded-lg bg-purple-500/10 flex items-center justify-center">
<MessageSquare className="h-4 w-4 text-purple-500" />
</div>
<CardTitle className="text-base">#feedback</CardTitle>
</div>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
Share your ideas, suggestions, and feedback to help improve Shakespeare.
</p>
</CardContent>
</Card>
<Card className="hover:shadow-md transition-shadow">
<CardHeader className="pb-2">
<div className="flex items-center gap-2">
<div className="w-8 h-8 rounded-lg bg-green-500/10 flex items-center justify-center">
<GitBranch className="h-4 w-4 text-green-500" />
</div>
<CardTitle className="text-base">#git</CardTitle>
</div>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
Follow along with the latest commits and development activity on Shakespeare.
</p>
</CardContent>
</Card>
<Card className="hover:shadow-md transition-shadow">
<CardHeader className="pb-2">
<div className="flex items-center gap-2">
<div className="w-8 h-8 rounded-lg bg-yellow-500/10 flex items-center justify-center">
<Lightbulb className="h-4 w-4 text-yellow-500" />
</div>
<CardTitle className="text-base">#prompts</CardTitle>
</div>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
Share and discover effective prompts for building better projects with AI.
</p>
</CardContent>
</Card>
<Card className="hover:shadow-md transition-shadow">
<CardHeader className="pb-2">
<div className="flex items-center gap-2">
<div className="w-8 h-8 rounded-lg bg-pink-500/10 flex items-center justify-center">
<Image className="h-4 w-4 text-pink-500" />
</div>
<CardTitle className="text-base">#showcase</CardTitle>
</div>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
Show off your Shakespeare creations and get inspired by what others have built.
</p>
</CardContent>
</Card>
<Card className="hover:shadow-md transition-shadow">
<CardHeader className="pb-2">
<div className="flex items-center gap-2">
<div className="w-8 h-8 rounded-lg bg-red-500/10 flex items-center justify-center">
<LifeBuoy className="h-4 w-4 text-red-500" />
</div>
<CardTitle className="text-base">#support</CardTitle>
</div>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
Get help from the community when you're stuck or have questions about using Shakespeare.
</p>
</CardContent>
</Card>
</div>
<div className="text-center">
<Button asChild>
<a href="https://app.flotilla.social/join?r=chat.shakespeare.diy&c=725J9PH4" target="_blank" rel="noopener noreferrer">
<MessageCircle className="h-4 w-4 mr-2" />
Join Shakespeare Chat
<ExternalLink className="h-4 w-4 ml-2" />
</a>
</Button>
</div>
</section>
{/* Resources Section */}
<section className="space-y-6">
<h2 className="text-2xl font-bold flex items-center gap-2">
<BookOpen className="h-6 w-6 text-blue-600" />
Resources
</h2>
<div className="grid md:grid-cols-2 gap-6">
{/* Blog Posts */}
<Card>
<CardHeader>
<CardTitle>Featured Guides</CardTitle>
<CardDescription>Learn tips and tricks from the community</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
{BLOG_POSTS.map((post, i) => (
<a
key={i}
href={post.url}
target="_blank"
rel="noopener noreferrer"
className="flex items-center justify-between p-3 rounded-lg hover:bg-muted transition-colors group"
>
<div>
<p className="font-medium group-hover:text-primary transition-colors">
{post.title}
</p>
<p className="text-sm text-muted-foreground">by {post.author}</p>
</div>
<ExternalLink className="h-4 w-4 text-muted-foreground group-hover:text-primary" />
</a>
))}
<Button asChild variant="ghost" className="w-full mt-2">
<a
href="https://soapbox.pub/shakespeare-resources/"
target="_blank"
rel="noopener noreferrer"
>
View All Resources
<ExternalLink className="h-4 w-4 ml-2" />
</a>
</Button>
</CardContent>
</Card>
{/* FAQs */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<HelpCircle className="h-5 w-5" />
Frequently Asked Questions
</CardTitle>
</CardHeader>
<CardContent>
<Accordion type="single" collapsible className="w-full">
{FAQS.map((faq, i) => (
<AccordionItem key={i} value={`faq-${i}`}>
<AccordionTrigger className="text-left text-sm px-3">
{faq.question}
</AccordionTrigger>
<AccordionContent className="text-muted-foreground text-sm px-3">
{faq.answer}
</AccordionContent>
</AccordionItem>
))}
</Accordion>
<Button asChild variant="ghost" className="w-full mt-4">
<a
href="https://soapbox.pub/shakespeare-resources/"
target="_blank"
rel="noopener noreferrer"
>
View All FAQs
<ExternalLink className="h-4 w-4 ml-2" />
</a>
</Button>
</CardContent>
</Card>
</div>
</section>
{/* Final CTA */}
<section className="text-center space-y-4 py-8">
<h2 className="text-2xl font-bold">Ready to Join?</h2>
<p className="text-muted-foreground max-w-xl mx-auto">
Join Shakespeare Chat to connect with the community, get help with your projects, and be part of the
conversation.
</p>
<Button asChild size="lg" className="bg-gradient-to-r from-primary to-accent hover:from-primary/90 hover:to-accent/90">
<a href="https://app.flotilla.social/join?r=chat.shakespeare.diy&c=725J9PH4" target="_blank" rel="noopener noreferrer">
<MessageCircle className="h-4 w-4 mr-2" />
Join Shakespeare Chat
<ExternalLink className="h-4 w-4 ml-2" />
</a>
</Button>
</section>
</div>
</div>
</div>
);
}
// Feed Post Component
function FeedPost({ event }: { event: NostrEvent }) {
const { data: author } = useAuthor(event.pubkey);
const displayName = author?.metadata?.name || genUserName(event.pubkey);
const picture = author?.metadata?.picture;
const timeAgo = getTimeAgo(event.created_at);
const nevent = nip19.neventEncode({ id: event.id, author: event.pubkey });
const njumpUrl = `https://njump.me/${nevent}`;
return (
<a href={njumpUrl} target="_blank" rel="noopener noreferrer" className="block h-full">
<Card className="hover:shadow-md transition-shadow cursor-pointer h-full">
<CardContent className="pt-4 h-full">
<div className="flex items-start gap-3 h-full">
<Avatar className="h-10 w-10 flex-shrink-0">
<AvatarImage src={picture} alt={displayName} />
<AvatarFallback>{displayName.slice(0, 2).toUpperCase()}</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<span className="font-medium text-sm truncate">{displayName}</span>
<span className="text-xs text-muted-foreground">{timeAgo}</span>
</div>
<div className="text-sm">
<NoteContent event={event} className="line-clamp-4" disableLinks hideEmbeds />
</div>
</div>
</div>
</CardContent>
</Card>
</a>
);
}
// Helper to check if a string is a URL
function isUrl(str: string): boolean {
try {
const url = new URL(str);
return url.protocol === 'http:' || url.protocol === 'https:';
} catch {
return false;
}
}
// Event Card Component
function EventCard({ event }: { event: NostrEvent }) {
const eventData = extractCalendarEventData(event);
const formattedDate = formatEventDate(eventData.start, eventData.kind, eventData.startTzid);
const isVirtual = eventData.location && isUrl(eventData.location);
return (
<Card className="hover:shadow-md transition-shadow overflow-hidden">
{eventData.image && (
<div className="aspect-video overflow-hidden">
<img
src={eventData.image}
alt={eventData.title}
className="w-full h-full object-cover"
/>
</div>
)}
<CardHeader>
<div className="flex items-start justify-between gap-2">
<div>
<CardTitle className="text-lg">{eventData.title}</CardTitle>
{eventData.summary && (
<CardDescription className="mt-1">{eventData.summary}</CardDescription>
)}
</div>
</div>
</CardHeader>
<CardContent className="space-y-2">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Calendar className="h-4 w-4" />
<span>{formattedDate}</span>
</div>
{eventData.location && (
isVirtual ? (
<a
href={eventData.location}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-2 text-sm text-primary hover:underline"
>
<Video className="h-4 w-4" />
<span>Virtual</span>
<ExternalLink className="h-3 w-3" />
</a>
) : (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<MapPin className="h-4 w-4" />
<span>{eventData.location}</span>
</div>
)
)}
{eventData.hashtags.length > 0 && (
<div className="flex flex-wrap gap-1 pt-2">
{eventData.hashtags.slice(0, 3).map((tag, i) => (
<Badge key={i} variant="secondary" className="text-xs">
#{tag}
</Badge>
))}
</div>
)}
</CardContent>
</Card>
);
}
// Helper function
function getTimeAgo(timestamp: number): string {
const seconds = Math.floor(Date.now() / 1000 - timestamp);
if (seconds < 60) return 'just now';
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes}m`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h`;
const days = Math.floor(hours / 24);
if (days < 7) return `${days}d`;
const weeks = Math.floor(days / 7);
if (weeks < 4) return `${weeks}w`;
const months = Math.floor(days / 30);
if (months < 12) return `${months}mo`;
return `${Math.floor(months / 12)}y`;
}
+1 -61
View File
@@ -1,4 +1,4 @@
import { Settings, ArrowLeft, RefreshCw, Trash2, XCircle, Loader2, RotateCcw, Cog, Globe, Image, Code, Monitor, Award, Bug, FolderTree, Terminal as TerminalIcon, Users } from "lucide-react"; import { Settings, ArrowLeft, RefreshCw, Trash2, XCircle, Loader2, RotateCcw, Cog, Globe, Image, Code, Monitor, Award, Bug, FolderTree, Terminal as TerminalIcon } from "lucide-react";
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useState, useEffect, useMemo } from "react"; import { useState, useEffect, useMemo } from "react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@@ -26,7 +26,6 @@ export function SystemSettings() {
const [faviconUrlInput, setFaviconUrlInput] = useState(config.faviconUrl); const [faviconUrlInput, setFaviconUrlInput] = useState(config.faviconUrl);
const [previewDomainInput, setPreviewDomainInput] = useState(config.previewDomain); const [previewDomainInput, setPreviewDomainInput] = useState(config.previewDomain);
const [showcaseModeratorInput, setShowcaseModeratorInput] = useState(config.showcaseModerator); const [showcaseModeratorInput, setShowcaseModeratorInput] = useState(config.showcaseModerator);
const [communityFollowPackInput, setCommunityFollowPackInput] = useState(config.communityFollowPack);
const [fsPathProjectsInput, setFsPathProjectsInput] = useState(config.fsPathProjects); const [fsPathProjectsInput, setFsPathProjectsInput] = useState(config.fsPathProjects);
const [fsPathConfigInput, setFsPathConfigInput] = useState(config.fsPathConfig); const [fsPathConfigInput, setFsPathConfigInput] = useState(config.fsPathConfig);
const [fsPathTmpInput, setFsPathTmpInput] = useState(config.fsPathTmp); const [fsPathTmpInput, setFsPathTmpInput] = useState(config.fsPathTmp);
@@ -42,7 +41,6 @@ export function SystemSettings() {
previewDomain: config.previewDomain !== defaultConfig.previewDomain, previewDomain: config.previewDomain !== defaultConfig.previewDomain,
showcaseEnabled: config.showcaseEnabled !== defaultConfig.showcaseEnabled, showcaseEnabled: config.showcaseEnabled !== defaultConfig.showcaseEnabled,
showcaseModerator: config.showcaseModerator !== defaultConfig.showcaseModerator, showcaseModerator: config.showcaseModerator !== defaultConfig.showcaseModerator,
communityFollowPack: config.communityFollowPack !== defaultConfig.communityFollowPack,
fsPathProjects: config.fsPathProjects !== defaultConfig.fsPathProjects, fsPathProjects: config.fsPathProjects !== defaultConfig.fsPathProjects,
fsPathConfig: config.fsPathConfig !== defaultConfig.fsPathConfig, fsPathConfig: config.fsPathConfig !== defaultConfig.fsPathConfig,
fsPathTmp: config.fsPathTmp !== defaultConfig.fsPathTmp, fsPathTmp: config.fsPathTmp !== defaultConfig.fsPathTmp,
@@ -104,15 +102,6 @@ export function SystemSettings() {
}); });
}; };
const restoreCommunityFollowPack = () => {
const defaultValue = defaultConfig.communityFollowPack;
setCommunityFollowPackInput(defaultValue);
updateConfig((current) => {
const { communityFollowPack, ...rest } = current;
return rest;
});
};
const restoreFsPathProjects = () => { const restoreFsPathProjects = () => {
const defaultValue = defaultConfig.fsPathProjects; const defaultValue = defaultConfig.fsPathProjects;
setFsPathProjectsInput(defaultValue); setFsPathProjectsInput(defaultValue);
@@ -691,55 +680,6 @@ export function SystemSettings() {
</AccordionItem> </AccordionItem>
</Accordion> </Accordion>
{/* Community Follow Pack Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="community-follow-pack">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Users className="h-4 w-4 text-muted-foreground" />
<h4 className="text-sm font-medium">{t('communityFollowPack')}</h4>
{isModified.communityFollowPack && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<div className="flex gap-2">
<Input
id="community-follow-pack"
type="text"
placeholder="naddr1..."
value={communityFollowPackInput}
onChange={(e) => {
const value = e.target.value;
setCommunityFollowPackInput(value);
updateConfig((current) => ({
...current,
communityFollowPack: value,
}));
}}
className="flex-1"
/>
{isModified.communityFollowPack && (
<Button
variant="outline"
size="icon"
onClick={restoreCommunityFollowPack}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('communityFollowPackDescription')}
</p>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
{/* Sentry DSN Configuration */} {/* Sentry DSN Configuration */}
<Accordion type="single" collapsible className="w-full"> <Accordion type="single" collapsible className="w-full">
<AccordionItem value="sentry-dsn"> <AccordionItem value="sentry-dsn">
-1
View File
@@ -57,7 +57,6 @@ export function TestApp({ children }: TestAppProps) {
fsPathTemplates: '/templates', fsPathTemplates: '/templates',
sentryDsn: '', sentryDsn: '',
sentryEnabled: false, sentryEnabled: false,
communityFollowPack: 'naddr1qvzqqqr4xgpzpjcswsacvumftxsmcejj3vsxu8mf203p8hkxoklxtgva7rdxzm0qqy88wumn8ghj7mn0wd68yttsw43z7qg4waehxw309aex2mrp0yhx6mmddaehgu339e3k7mf0qythwumn8ghj7cn5vvhxkmr9dejxz7n0xvs8xmmrdejhytnrdakj7q3qdqr8kgh3s5q8ztw0swmvpwz98cse7rw43n4nhrpszgafnuwrxh8hscmhv5m',
}; };
// Initialize LightningFS for testing // Initialize LightningFS for testing