first commit

This commit is contained in:
2025-07-08 21:49:27 +02:00
commit bc374cad73
21 changed files with 5865 additions and 0 deletions

97
.gitignore vendored Normal file
View File

@ -0,0 +1,97 @@
# Dependencies
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Build outputs
dist/
build/
*.tsbuildinfo
# Environment files
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# IDEs and editors
.vscode/
.idea/
*.swp
*.swo
*~
# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Temporary files
*.tmp
*.temp
# Logs
logs/
*.log
# Runtime data
pids/
*.pid
*.seed
*.pid.lock
# Coverage directory used by tools like istanbul
coverage/
*.lcov
# Dependency directories
jspm_packages/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
# Storybook build outputs
.out
.storybook-out
# Temporary folders
tmp/
temp/

11
.prettierrc Normal file
View File

@ -0,0 +1,11 @@
{
"semi": true,
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"bracketSpacing": true,
"arrowParens": "avoid",
"endOfLine": "lf"
}

12
README.md Normal file
View File

@ -0,0 +1,12 @@
# React + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## Expanding the ESLint configuration
If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and [`typescript-eslint`](https://typescript-eslint.io) in your project.

49
eslint.config.js Normal file
View File

@ -0,0 +1,49 @@
import js from '@eslint/js';
import globals from 'globals';
import reactHooks from 'eslint-plugin-react-hooks';
import reactRefresh from 'eslint-plugin-react-refresh';
import tseslint from '@typescript-eslint/eslint-plugin';
import tsParser from '@typescript-eslint/parser';
import prettier from 'eslint-plugin-prettier';
import prettierConfig from 'eslint-config-prettier';
export default [
{
ignores: ['dist', 'node_modules'],
},
{
files: ['**/*.{js,jsx,ts,tsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
parser: tsParser,
parserOptions: {
ecmaVersion: 'latest',
ecmaFeatures: { jsx: true },
sourceType: 'module',
},
},
plugins: {
'@typescript-eslint': tseslint,
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
prettier,
},
rules: {
...js.configs.recommended.rules,
...tseslint.configs.recommended.rules,
...reactHooks.configs['recommended-latest'].rules,
...prettierConfig.rules,
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': [
'error',
{ varsIgnorePattern: '^[A-Z_]' },
],
'prettier/prettier': 'error',
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
},
];

13
index.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Rayon Cosmique</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

3487
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

44
package.json Normal file
View File

@ -0,0 +1,44 @@
{
"name": "rayon-cosmique",
"private": true,
"version": "0.0.0",
"type": "module",
"description": "A hex editor for corrupting image files with cosmic randomness",
"author": {
"name": "Raphaël Forment",
"email": "raphael.forment@gmail.com"
},
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"format": "prettier --write .",
"format:check": "prettier --check .",
"typecheck": "tsc --noEmit",
"preview": "vite preview"
},
"dependencies": {
"@nanostores/react": "^1.0.0",
"nanostores": "^1.0.1",
"react": "^19.1.0",
"react-dom": "^19.1.0"
},
"devDependencies": {
"@eslint/js": "^9.30.1",
"@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6",
"@typescript-eslint/eslint-plugin": "^8.36.0",
"@typescript-eslint/parser": "^8.36.0",
"@vitejs/plugin-react": "^4.6.0",
"eslint": "^9.30.1",
"eslint-config-prettier": "^10.1.5",
"eslint-plugin-prettier": "^5.5.1",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.20",
"globals": "^16.3.0",
"prettier": "^3.6.2",
"typescript": "^5.8.3",
"vite": "^7.0.3"
}
}

1
public/vite.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

622
src/App.css Normal file
View File

@ -0,0 +1,622 @@
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html, body {
height: 100%;
width: 100%;
}
#root {
height: 100%;
width: 100%;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
background: #1a1a1a;
color: #fff;
}
.app {
height: 100vh;
width: 100vw;
display: flex;
flex-direction: column;
}
.top-bar {
height: 40px;
background: #2a2a2a;
border-bottom: 1px solid #444;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 16px;
}
.app-info {
display: flex;
align-items: center;
gap: 12px;
}
.app-title {
font-size: 16px;
font-weight: 600;
color: #fff;
margin: 0;
}
.app-author {
font-size: 11px;
color: #888;
font-style: italic;
}
.main-content {
flex: 1;
display: flex;
flex-direction: row;
}
.image-section {
flex: 1;
display: flex;
flex-direction: column;
}
.editor-section {
width: 700px;
min-width: 600px;
max-width: 800px;
background: #2a2a2a;
border-left: 1px solid #444;
display: flex;
flex-direction: column;
}
.image-panel {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
background: #111;
position: relative;
overflow: hidden;
}
.image-panel.modified {
border-bottom: 1px solid #444;
}
.image-container {
width: 100%;
height: 100%;
position: relative;
overflow: hidden;
cursor: grab;
}
.image-container:active {
cursor: grabbing;
}
.image-container img {
position: absolute;
user-select: none;
pointer-events: none;
}
.image-panel::before {
content: attr(data-label);
position: absolute;
top: 8px;
left: 8px;
font-size: 12px;
color: #888;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.image-panel.modified::before {
content: 'Modified';
}
.image-panel.original::before {
content: 'Original';
}
.load-button {
background: #007acc;
color: white;
border: none;
padding: 6px 12px;
border-radius: 0;
cursor: pointer;
font-size: 13px;
font-weight: 500;
}
.load-button:hover {
background: #0066aa;
}
.load-button:disabled {
background: #444;
cursor: not-allowed;
opacity: 0.5;
}
.export-button {
background: #198754;
color: #fff;
border: 1px solid #198754;
padding: 6px 12px;
border-radius: 0;
cursor: pointer;
font-size: 13px;
font-weight: 500;
transition: all 0.2s;
margin-left: 8px;
}
.export-button:hover:not(:disabled) {
background: #157347;
border-color: #157347;
}
.export-button:disabled {
background: #444;
cursor: not-allowed;
opacity: 0.5;
}
.hidden-input {
display: none;
}
.empty-state {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
color: #666;
font-style: italic;
font-size: 14px;
}
/* Hex Editor Styles */
.hex-editor {
background: #2a2a2a;
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
max-height: 100vh;
}
.hex-editor-header {
padding: 8px 12px;
background: #333;
border-bottom: 1px solid #444;
user-select: none;
display: flex;
align-items: center;
justify-content: space-between;
flex-shrink: 0;
}
.hex-editor-title {
font-size: 13px;
font-weight: 500;
color: #fff;
}
.hex-editor-content {
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
max-height: calc(100vh - 100px);
overflow: hidden;
}
.hex-controls {
padding: 8px;
background: #333;
border-bottom: 1px solid #444;
display: flex;
flex-direction: column;
gap: 8px;
}
.control-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.chunk-nav {
display: flex;
align-items: center;
gap: 8px;
}
.nav-button {
background: #444;
color: #fff;
border: 1px solid #666;
padding: 4px 8px;
border-radius: 4px;
cursor: pointer;
font-size: 12px;
}
.nav-button:hover:not(:disabled) {
background: #555;
}
.nav-button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.jump-form {
display: flex;
align-items: center;
}
.jump-input {
background: #1a1a1a;
color: #fff;
border: 1px solid #444;
padding: 4px 8px;
border-radius: 0;
width: 80px;
font-size: 12px;
}
.jump-input.address-input {
width: 120px;
}
.jump-input:focus {
outline: none;
border-color: #007acc;
}
.chunk-info {
color: #888;
font-size: 11px;
}
.action-buttons {
display: flex;
gap: 8px;
}
.action-button {
background: #444;
color: #fff;
border: 1px solid #666;
padding: 0;
border-radius: 0;
cursor: pointer;
font-size: 12px;
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
}
.action-button:hover:not(:disabled) {
background: #555;
}
.action-button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.action-button.apply {
background: #28a745;
border-color: #28a745;
}
.action-button.apply:hover:not(:disabled) {
background: #218838;
}
.action-button.compile {
background: #007acc;
border-color: #007acc;
}
.action-button.compile:hover:not(:disabled) {
background: #0066aa;
}
.action-button.reset {
background: #dc3545;
border-color: #dc3545;
}
.action-button.reset:hover:not(:disabled) {
background: #c82333;
}
.action-button.random {
background: #fd7e14;
border-color: #fd7e14;
}
.action-button.random:hover:not(:disabled) {
background: #e8690b;
}
.action-button.export {
background: #198754;
border-color: #198754;
}
.action-button.export:hover:not(:disabled) {
background: #157347;
}
.action-button.undo {
background: #6c757d;
border-color: #6c757d;
}
.action-button.undo:hover:not(:disabled) {
background: #5a6268;
}
.action-button.global-random {
background: #6f42c1;
border-color: #6f42c1;
}
.action-button.global-random:hover:not(:disabled) {
background: #5a359a;
}
/* Hex View */
.hex-view-container {
flex: 1;
min-height: 0;
max-height: 450px;
background: #1a1a1a;
border-radius: 0 0 4px 4px;
}
.hex-view {
height: 100%;
display: flex;
flex-direction: column;
}
.hex-header {
display: flex;
background: #333;
border-bottom: 1px solid #444;
padding: 4px 8px;
font-size: 11px;
font-weight: 600;
color: #aaa;
font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', monospace;
}
.hex-address-header {
width: 80px;
flex-shrink: 0;
}
.hex-data-header {
width: 380px;
flex-shrink: 0;
text-align: center;
}
.hex-ascii-header {
width: 120px;
flex-shrink: 0;
text-align: center;
}
.hex-content {
flex: 1;
overflow-y: auto;
padding: 4px 8px;
font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', monospace;
font-size: 12px;
line-height: 1.4;
}
.hex-content-scroll {
flex: 1;
overflow-y: auto;
padding: 4px 8px;
font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', monospace;
font-size: 12px;
line-height: 1.4;
scrollbar-width: thin;
scrollbar-color: #444 #1a1a1a;
max-height: 400px;
height: 400px;
min-height: 200px;
}
.hex-content-scroll::-webkit-scrollbar {
width: 8px;
}
.hex-content-scroll::-webkit-scrollbar-track {
background: #1a1a1a;
}
.hex-content-scroll::-webkit-scrollbar-thumb {
background: #444;
border-radius: 4px;
}
.hex-content-scroll::-webkit-scrollbar-thumb:hover {
background: #555;
}
.hex-content-virtual {
position: relative;
}
.hex-content-viewport {
position: absolute;
}
.hex-row {
display: flex;
padding: 1px 0;
border-radius: 2px;
}
.hex-row:hover {
background: #333;
}
.hex-address {
width: 80px;
flex-shrink: 0;
color: #888;
user-select: none;
}
.hex-data {
width: 380px;
flex-shrink: 0;
color: #fff;
letter-spacing: 0.5px;
display: flex;
align-items: center;
}
.hex-byte {
cursor: pointer;
padding: 1px 2px;
border-radius: 2px;
transition: background-color 0.15s;
}
.hex-byte:hover {
background: #444;
}
.hex-byte-empty {
cursor: default;
opacity: 0.3;
}
.hex-byte-empty:hover {
background: transparent;
}
.hex-space {
user-select: none;
}
.hex-byte-input {
width: 20px;
background: #007acc;
color: #fff;
border: 1px solid #0099ff;
border-radius: 0;
text-align: center;
font-family: inherit;
font-size: inherit;
padding: 1px;
outline: none;
}
.hex-ascii {
width: 120px;
flex-shrink: 0;
color: #aaa;
padding-left: 8px;
border-left: 1px solid #444;
display: flex;
align-items: center;
}
.ascii-char {
cursor: pointer;
padding: 1px 1px;
border-radius: 2px;
transition: background-color 0.15s;
min-width: 7px;
text-align: center;
}
.ascii-char:hover {
background: #444;
}
.ascii-char-empty {
cursor: default;
opacity: 0.3;
}
.ascii-char-empty:hover {
background: transparent;
}
.ascii-char-input {
width: 8px;
background: #007acc;
color: #fff;
border: 1px solid #0099ff;
border-radius: 0;
text-align: center;
font-family: inherit;
font-size: inherit;
padding: 1px;
outline: none;
}
/* Hex Input Section */
.hex-input-section {
padding: 8px;
background: #333;
border-top: 1px solid #444;
max-height: 250px;
flex-shrink: 0;
}
.hex-input-section label {
display: block;
margin-bottom: 4px;
font-size: 12px;
color: #aaa;
}
.hex-input {
width: 100%;
background: #1a1a1a;
color: #fff;
border: 1px solid #444;
border-radius: 0;
padding: 8px;
font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', monospace;
font-size: 12px;
line-height: 1.4;
resize: vertical;
outline: none;
}
.hex-input:focus {
border-color: #007acc;
}

33
src/App.tsx Normal file
View File

@ -0,0 +1,33 @@
import './App.css';
import ImageUpload from './components/ImageUpload';
import BinaryEditor from './components/BinaryEditor';
import ImagePreview from './components/ImagePreview';
function App() {
return (
<div className="app">
<div className="top-bar">
<div className="app-info">
<h1 className="app-title">Rayon Cosmique</h1>
<span className="app-author">by Raphaël Forment (BuboBubo)</span>
</div>
<ImageUpload />
</div>
<div className="main-content">
<div className="image-section">
<div className="image-panel modified">
<ImagePreview type="modified" />
</div>
<div className="image-panel original">
<ImagePreview type="original" />
</div>
</div>
<div className="editor-section">
<BinaryEditor />
</div>
</div>
</div>
);
}
export default App;

1
src/assets/react.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

@ -0,0 +1,714 @@
import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react';
import { useStore } from '@nanostores/react';
import {
fileMetadata,
isCompiling,
hasModifications,
totalHexChunks,
compileImage,
resetToOriginal,
byteToChar,
originalFileData,
modifiedFileData,
hexChunkSize,
pushToUndoStack,
undo,
canUndo,
} from '../stores/imageStore';
export default function BinaryEditor() {
const metadata = useStore(fileMetadata);
const compiling = useStore(isCompiling);
const modified = useStore(hasModifications);
const totalChunks = useStore(totalHexChunks);
const originalData = useStore(originalFileData);
const modifiedData = useStore(modifiedFileData);
const chunkSize = useStore(hexChunkSize);
const canUndoState = useStore(canUndo);
const [jumpToChunk, setJumpToChunk] = useState('');
const [jumpToAddress, setJumpToAddress] = useState('');
const [hexInput, setHexInput] = useState('');
const [editingByte, setEditingByte] = useState<{ row: number; col: number; value: string; globalOffset: number } | null>(null);
const [editingAscii, setEditingAscii] = useState<{ row: number; col: number; value: string; globalOffset: number } | null>(null);
const [scrollTop, setScrollTop] = useState(0);
const editorRef = useRef<HTMLDivElement>(null);
const scrollContainerRef = useRef<HTMLDivElement>(null);
// Virtual scrolling configuration
const ROW_HEIGHT = 20; // Height of each hex row in pixels
const BYTES_PER_ROW = 16;
const BUFFER_SIZE = 10; // Extra rows to render above/below viewport for smooth scrolling
// Calculate virtual scrolling parameters
const virtualScrollData = useMemo(() => {
if (!metadata || !originalData) return null;
const totalRows = Math.ceil(metadata.fileSize / BYTES_PER_ROW);
const containerHeight = 400; // Fixed height for hex container
const visibleRows = Math.ceil(containerHeight / ROW_HEIGHT);
const startRow = Math.floor(scrollTop / ROW_HEIGHT);
const endRow = Math.min(startRow + visibleRows + BUFFER_SIZE * 2, totalRows);
const actualStartRow = Math.max(0, startRow - BUFFER_SIZE);
const startByte = actualStartRow * BYTES_PER_ROW;
const endByte = Math.min(endRow * BYTES_PER_ROW, metadata.fileSize);
return {
totalRows,
visibleRows,
startRow: actualStartRow,
endRow,
startByte,
endByte,
totalHeight: Math.max(totalRows * ROW_HEIGHT, containerHeight),
offsetY: actualStartRow * ROW_HEIGHT,
};
}, [metadata, originalData, scrollTop]);
// Get data for virtual scrolling viewport
const viewportData = useMemo(() => {
if (!virtualScrollData || !originalData) return null;
const dataToUse = modifiedData || originalData;
const viewportBytes = dataToUse.slice(virtualScrollData.startByte, virtualScrollData.endByte);
return viewportBytes;
}, [virtualScrollData, originalData, modifiedData]);
// Update hex input when viewport data changes
useEffect(() => {
if (viewportData) {
const hexString = Array.from(viewportData)
.map(byte => byte.toString(16).padStart(2, '0'))
.join('');
setHexInput(hexString);
}
}, [viewportData]);
// Handle scroll events
const handleScroll = useCallback((e: React.UIEvent<HTMLDivElement>) => {
setScrollTop(e.currentTarget.scrollTop);
}, []);
// Random button functionality
const handleRandomize = useCallback((count: number = 1) => {
if (!originalData || !virtualScrollData) return;
// Push current state to undo stack
const currentData = modifiedData || new Uint8Array(originalData);
pushToUndoStack(currentData);
const newData = new Uint8Array(currentData);
// Get visible range
const visibleStart = virtualScrollData.startByte;
const visibleEnd = virtualScrollData.endByte;
// Make multiple random changes
for (let i = 0; i < count; i++) {
const randomIndex = Math.floor(Math.random() * (visibleEnd - visibleStart)) + visibleStart;
const randomValue = Math.floor(Math.random() * 256);
newData[randomIndex] = randomValue;
}
modifiedFileData.set(newData);
// Auto-update image after random change
setTimeout(() => compileImage(), 100);
}, [originalData, modifiedData, virtualScrollData]);
// Undo functionality
const handleUndo = useCallback(() => {
undo();
setTimeout(() => compileImage(), 100);
}, []);
// Global random button functionality (affects entire file)
const handleGlobalRandomize = useCallback((count: number = 1) => {
if (!originalData || !metadata) return;
// Push current state to undo stack
const currentData = modifiedData || new Uint8Array(originalData);
pushToUndoStack(currentData);
const newData = new Uint8Array(currentData);
// Make random changes across the entire file
for (let i = 0; i < count; i++) {
const randomIndex = Math.floor(Math.random() * metadata.fileSize);
const randomValue = Math.floor(Math.random() * 256);
newData[randomIndex] = randomValue;
}
modifiedFileData.set(newData);
// Auto-update image after random change
setTimeout(() => compileImage(), 100);
}, [originalData, modifiedData, metadata]);
const handleHexInputChange = (
event: React.ChangeEvent<HTMLTextAreaElement>
) => {
const value = event.target.value.replace(/[^0-9a-fA-F]/gi, '');
setHexInput(value);
};
// Auto-updates happen immediately now
const handleByteClick = (row: number, col: number, currentValue: number, globalOffset: number) => {
setEditingByte({
row,
col,
value: currentValue.toString(16).padStart(2, '0').toUpperCase(),
globalOffset
});
};
const handleByteEdit = (e: React.ChangeEvent<HTMLInputElement>) => {
if (!editingByte) return;
const value = e.target.value.replace(/[^0-9a-fA-F]/gi, '').slice(0, 2);
setEditingByte({ ...editingByte, value });
};
const handleByteSubmit = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && editingByte) {
applyByteEdit();
} else if (e.key === 'Escape') {
setEditingByte(null);
}
};
const applyByteEdit = () => {
if (!editingByte || !originalData) return;
const newValue = parseInt(editingByte.value, 16);
if (isNaN(newValue)) {
setEditingByte(null);
return;
}
// Push current state to undo stack
const currentData = modifiedData || new Uint8Array(originalData);
pushToUndoStack(currentData);
// Update the full modified data directly
const newData = new Uint8Array(currentData);
newData[editingByte.globalOffset] = newValue;
// Update store with new modified data
modifiedFileData.set(newData);
setEditingByte(null);
// Auto-update image after byte edit
setTimeout(() => compileImage(), 100);
};
const handleAsciiClick = (row: number, col: number, currentValue: number, globalOffset: number) => {
const char = currentValue >= 32 && currentValue <= 126 ? String.fromCharCode(currentValue) : '.';
setEditingAscii({
row,
col,
value: char,
globalOffset
});
};
const handleAsciiEdit = (e: React.ChangeEvent<HTMLInputElement>) => {
if (!editingAscii) return;
const value = e.target.value.slice(0, 1); // Only allow single character
setEditingAscii({ ...editingAscii, value });
};
const handleAsciiSubmit = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && editingAscii) {
applyAsciiEdit();
} else if (e.key === 'Escape') {
setEditingAscii(null);
}
};
const applyAsciiEdit = () => {
if (!editingAscii || !originalData) return;
const char = editingAscii.value;
if (char.length !== 1) {
setEditingAscii(null);
return;
}
const newValue = char.charCodeAt(0);
// Push current state to undo stack
const currentData = modifiedData || new Uint8Array(originalData);
pushToUndoStack(currentData);
// Update the full modified data directly
const newData = new Uint8Array(currentData);
newData[editingAscii.globalOffset] = newValue;
// Update store with new modified data
modifiedFileData.set(newData);
setEditingAscii(null);
// Auto-update image after ASCII edit
setTimeout(() => compileImage(), 100);
};
const renderFallbackHexView = (data: Uint8Array) => {
const rows = [];
const bytesPerRow = BYTES_PER_ROW;
for (let i = 0; i < data.length; i += bytesPerRow) {
const rowData = data.slice(i, i + bytesPerRow);
const address = i;
// Address column
const addressStr = address.toString(16).toUpperCase().padStart(8, '0');
// Hex column
const hexBytes = Array.from(rowData).map((byte, colIndex) => {
const globalOffset = address + colIndex;
return (
<span
key={colIndex}
className="hex-byte"
onClick={() => handleByteClick(Math.floor(i / bytesPerRow), colIndex, byte, globalOffset)}
title={`Click to edit byte at offset ${globalOffset.toString(16).toUpperCase()}`}
>
{byte.toString(16).padStart(2, '0').toUpperCase()}
</span>
);
});
// Pad remaining columns if row is incomplete
while (hexBytes.length < bytesPerRow) {
hexBytes.push(
<span key={hexBytes.length} className="hex-byte hex-byte-empty">
{' '}
</span>
);
}
// ASCII column
const asciiChars = Array.from(rowData).map((byte, colIndex) => {
const globalOffset = address + colIndex;
const char = byteToChar(byte);
return (
<span
key={colIndex}
className="ascii-char"
onClick={() => handleAsciiClick(Math.floor(i / bytesPerRow), colIndex, byte, globalOffset)}
title={`Click to edit ASCII char at offset ${globalOffset.toString(16).toUpperCase()} (byte value: ${byte})`}
>
{char}
</span>
);
});
// Pad remaining columns if row is incomplete
while (asciiChars.length < bytesPerRow) {
asciiChars.push(
<span key={asciiChars.length} className="ascii-char ascii-char-empty">
{' '}
</span>
);
}
rows.push(
<div key={address} className="hex-row" style={{ height: ROW_HEIGHT }}>
<span className="hex-address">{addressStr}</span>
<div className="hex-data">
{hexBytes.map((byte, idx) => (
<React.Fragment key={idx}>
{byte}
{idx < bytesPerRow - 1 && <span className="hex-space"> </span>}
</React.Fragment>
))}
</div>
<div className="hex-ascii">
{asciiChars}
</div>
</div>
);
}
return rows;
};
const renderVirtualizedHexView = () => {
if (!virtualScrollData || !viewportData) {
// Fallback: render first chunk if virtual scrolling data not available
if (!originalData) return null;
const fallbackData = originalData.slice(0, Math.min(512, originalData.length));
return renderFallbackHexView(fallbackData);
}
const rows = [];
const bytesPerRow = BYTES_PER_ROW;
for (let i = 0; i < viewportData.length; i += bytesPerRow) {
const rowData = viewportData.slice(i, i + bytesPerRow);
const globalRowIndex = virtualScrollData.startRow + Math.floor(i / bytesPerRow);
const address = globalRowIndex * bytesPerRow;
// Address column
const addressStr = address.toString(16).toUpperCase().padStart(8, '0');
// Hex column with editable bytes
const hexBytes = Array.from(rowData).map((byte, colIndex) => {
const globalOffset = address + colIndex;
const isEditing = editingByte?.globalOffset === globalOffset;
if (isEditing) {
return (
<input
key={colIndex}
type="text"
value={editingByte.value}
onChange={handleByteEdit}
onKeyDown={handleByteSubmit}
onBlur={applyByteEdit}
className="hex-byte-input"
autoFocus
maxLength={2}
/>
);
}
return (
<span
key={colIndex}
className="hex-byte"
onClick={() => handleByteClick(globalRowIndex, colIndex, byte, globalOffset)}
title={`Click to edit byte at offset ${globalOffset.toString(16).toUpperCase()}`}
>
{byte.toString(16).padStart(2, '0').toUpperCase()}
</span>
);
});
// Pad remaining columns if row is incomplete
while (hexBytes.length < bytesPerRow) {
hexBytes.push(
<span key={hexBytes.length} className="hex-byte hex-byte-empty">
{' '}
</span>
);
}
// ASCII column with editable characters
const asciiChars = Array.from(rowData).map((byte, colIndex) => {
const globalOffset = address + colIndex;
const isEditingAsciiChar = editingAscii?.globalOffset === globalOffset;
if (isEditingAsciiChar) {
return (
<input
key={colIndex}
type="text"
value={editingAscii.value}
onChange={handleAsciiEdit}
onKeyDown={handleAsciiSubmit}
onBlur={applyAsciiEdit}
className="ascii-char-input"
autoFocus
maxLength={1}
/>
);
}
const char = byteToChar(byte);
return (
<span
key={colIndex}
className="ascii-char"
onClick={() => handleAsciiClick(globalRowIndex, colIndex, byte, globalOffset)}
title={`Click to edit ASCII char at offset ${globalOffset.toString(16).toUpperCase()} (byte value: ${byte})`}
>
{char}
</span>
);
});
// Pad remaining columns if row is incomplete
while (asciiChars.length < bytesPerRow) {
asciiChars.push(
<span key={asciiChars.length} className="ascii-char ascii-char-empty">
{' '}
</span>
);
}
rows.push(
<div key={address} className="hex-row" style={{ height: ROW_HEIGHT }}>
<span className="hex-address">{addressStr}</span>
<div className="hex-data">
{hexBytes.map((byte, idx) => (
<React.Fragment key={idx}>
{byte}
{idx < bytesPerRow - 1 && <span className="hex-space"> </span>}
</React.Fragment>
))}
</div>
<div className="hex-ascii">
{asciiChars}
</div>
</div>
);
}
return rows;
};
const handleJumpToChunk = (e: React.FormEvent) => {
e.preventDefault();
const chunkIndex = parseInt(jumpToChunk) - 1;
if (!isNaN(chunkIndex) && chunkIndex >= 0 && chunkIndex < totalChunks) {
// Calculate the address of the chunk and scroll to it
const chunkAddress = chunkIndex * chunkSize;
const targetRow = Math.floor(chunkAddress / BYTES_PER_ROW);
const targetScrollTop = targetRow * ROW_HEIGHT;
if (scrollContainerRef.current) {
scrollContainerRef.current.scrollTop = targetScrollTop;
}
setScrollTop(targetScrollTop);
setJumpToChunk('');
}
};
const handleJumpToAddress = (e: React.FormEvent) => {
e.preventDefault();
const address = parseInt(jumpToAddress, 16);
if (!isNaN(address) && metadata) {
if (address >= 0 && address < metadata.fileSize) {
// For virtual scrolling, calculate the row and scroll to it
const targetRow = Math.floor(address / BYTES_PER_ROW);
const targetScrollTop = targetRow * ROW_HEIGHT;
if (scrollContainerRef.current) {
scrollContainerRef.current.scrollTop = targetScrollTop;
}
setScrollTop(targetScrollTop);
}
setJumpToAddress('');
}
};
if (!metadata) {
return (
<div className="hex-editor">
<div className="hex-editor-header">
<span className="hex-editor-title">
Hex Editor - No file loaded
</span>
</div>
<div className="hex-editor-content">
<div style={{ padding: '20px', textAlign: 'center', color: '#888' }}>
Upload an image to start editing
</div>
</div>
</div>
);
}
if (!originalData) {
return (
<div className="hex-editor">
<div className="hex-editor-header">
<span className="hex-editor-title">
Hex Editor - {metadata.fileName} ({metadata.fileSize} bytes)
</span>
</div>
<div className="hex-editor-content">
<div style={{ padding: '20px', textAlign: 'center' }}>
Loading file data...
</div>
</div>
</div>
);
}
return (
<div
ref={editorRef}
className="hex-editor"
>
<div className="hex-editor-header">
<span className="hex-editor-title">
Hex Editor - {metadata.fileName} ({metadata.fileSize} bytes)
</span>
</div>
<div className="hex-editor-content">
<div className="hex-controls">
<div className="control-row">
<form onSubmit={handleJumpToChunk} className="jump-form">
<input
type="number"
value={jumpToChunk}
onChange={e => setJumpToChunk(e.target.value)}
placeholder="Jump to chunk..."
className="jump-input"
min="1"
max={totalChunks}
/>
</form>
<form onSubmit={handleJumpToAddress} className="jump-form">
<input
type="text"
value={jumpToAddress}
onChange={e => setJumpToAddress(e.target.value)}
placeholder="Go to address (hex)"
className="jump-input address-input"
/>
</form>
</div>
<div className="chunk-info">
<small>
File: {metadata.fileSize} bytes Scroll position: {Math.floor(scrollTop / ROW_HEIGHT * BYTES_PER_ROW).toString(16).toUpperCase()}
{modified && ' • Modified'}
</small>
</div>
<div className="action-buttons">
<button
onClick={compileImage}
className="action-button compile"
disabled={compiling}
title="Update Image"
>
</button>
<button
onClick={() => handleRandomize(1)}
className="action-button random"
disabled={compiling || !originalData}
title="Random (Visible)"
>
1
</button>
<button
onClick={() => handleRandomize(10)}
className="action-button random"
disabled={compiling || !originalData}
title="Random × 10 (Visible)"
>
10
</button>
<button
onClick={() => handleRandomize(100)}
className="action-button random"
disabled={compiling || !originalData}
title="Random × 100 (Visible)"
>
100
</button>
<button
onClick={() => handleGlobalRandomize(1)}
className="action-button global-random"
disabled={compiling || !originalData}
title="Global Random"
>
1
</button>
<button
onClick={() => handleGlobalRandomize(10)}
className="action-button global-random"
disabled={compiling || !originalData}
title="Global Random × 10"
>
10
</button>
<button
onClick={() => handleGlobalRandomize(100)}
className="action-button global-random"
disabled={compiling || !originalData}
title="Global Random × 100"
>
100
</button>
<button
onClick={handleUndo}
className="action-button undo"
disabled={compiling || !canUndoState}
title="Undo"
>
</button>
<button
onClick={resetToOriginal}
className="action-button reset"
disabled={compiling}
title="Reset"
>
</button>
</div>
</div>
<div className="hex-view-container">
<div className="hex-view">
<div className="hex-header">
<span className="hex-address-header">Address</span>
<span className="hex-data-header">Hex Data</span>
<span className="hex-ascii-header">ASCII</span>
</div>
<div
ref={scrollContainerRef}
className="hex-content-scroll"
style={{
height: '400px',
overflow: 'auto',
position: 'relative'
}}
onScroll={handleScroll}
>
<div
className="hex-content-virtual"
style={{
height: virtualScrollData?.totalHeight || 0,
position: 'relative'
}}
>
<div
className="hex-content-viewport"
style={{
transform: `translateY(${virtualScrollData?.offsetY || 0}px)`,
position: 'absolute',
top: 0,
left: 0,
right: 0
}}
>
{renderVirtualizedHexView()}
</div>
</div>
</div>
</div>
</div>
<div className="hex-input-section">
<label>Raw Hex Input (Current View):</label>
<textarea
className="hex-input"
value={hexInput}
onChange={handleHexInputChange}
placeholder="Enter hex values..."
rows={8}
style={{ minHeight: '120px', maxHeight: '200px' }}
/>
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,161 @@
import React, { useState, useRef, useEffect } from 'react';
import { useStore } from '@nanostores/react';
import {
originalImageUrl,
compiledImageUrl,
fileMetadata,
imagePan,
imageSize,
} from '../stores/imageStore';
interface ImagePreviewProps {
type: 'original' | 'modified';
}
export default function ImagePreview({ type }: ImagePreviewProps) {
const originalUrl = useStore(originalImageUrl);
const compiledUrl = useStore(compiledImageUrl);
const metadata = useStore(fileMetadata);
const pan = useStore(imagePan);
const size = useStore(imageSize);
const [isDragging, setIsDragging] = useState(false);
const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
const containerRef = useRef<HTMLDivElement>(null);
const imgRef = useRef<HTMLImageElement>(null);
const imageUrl = type === 'original' ? originalUrl : compiledUrl;
const handleImageLoad = () => {
if (imgRef.current && containerRef.current) {
const img = imgRef.current;
const container = containerRef.current;
// Get natural image dimensions
const imgAspect = img.naturalWidth / img.naturalHeight;
const containerAspect = container.clientWidth / container.clientHeight;
let displayWidth, displayHeight;
// Scale image to fit container (letterbox if necessary)
if (imgAspect > containerAspect) {
// Image is wider - fit width, letterbox height
displayWidth = container.clientWidth;
displayHeight = displayWidth / imgAspect;
} else {
// Image is taller - fit height, letterbox width
displayHeight = container.clientHeight;
displayWidth = displayHeight * imgAspect;
}
imageSize.set({ width: displayWidth, height: displayHeight });
// Center the image initially
const initialX = Math.max(0, (container.clientWidth - displayWidth) / 2);
const initialY = Math.max(0, (container.clientHeight - displayHeight) / 2);
imagePan.set({
x: initialX,
y: initialY
});
}
};
const handleMouseDown = (e: React.MouseEvent) => {
setIsDragging(true);
setDragStart({ x: e.clientX - pan.x, y: e.clientY - pan.y });
};
const handleMouseMove = (e: React.MouseEvent) => {
if (isDragging && containerRef.current) {
const container = containerRef.current;
const newX = e.clientX - dragStart.x;
const newY = e.clientY - dragStart.y;
// Constrain panning to keep image properly positioned
const maxX = Math.max(0, (container.clientWidth - size.width) / 2);
const minX = Math.min(0, container.clientWidth - size.width + maxX);
const maxY = Math.max(0, (container.clientHeight - size.height) / 2);
const minY = Math.min(0, container.clientHeight - size.height + maxY);
imagePan.set({
x: Math.max(minX, Math.min(maxX, newX)),
y: Math.max(minY, Math.min(maxY, newY))
});
}
};
const handleMouseUp = () => {
setIsDragging(false);
};
useEffect(() => {
if (isDragging) {
const handleGlobalMouseMove = (e: MouseEvent) => {
if (containerRef.current) {
const container = containerRef.current;
const newX = e.clientX - dragStart.x;
const newY = e.clientY - dragStart.y;
const maxX = Math.max(0, (container.clientWidth - size.width) / 2);
const minX = Math.min(0, container.clientWidth - size.width + maxX);
const maxY = Math.max(0, (container.clientHeight - size.height) / 2);
const minY = Math.min(0, container.clientHeight - size.height + maxY);
imagePan.set({
x: Math.max(minX, Math.min(maxX, newX)),
y: Math.max(minY, Math.min(maxY, newY))
});
}
};
const handleGlobalMouseUp = () => {
setIsDragging(false);
};
document.addEventListener('mousemove', handleGlobalMouseMove);
document.addEventListener('mouseup', handleGlobalMouseUp);
return () => {
document.removeEventListener('mousemove', handleGlobalMouseMove);
document.removeEventListener('mouseup', handleGlobalMouseUp);
};
}
}, [isDragging, dragStart, size]);
if (!imageUrl) {
return (
<div className="empty-state">
{type === 'original'
? 'Load an image to start hex editing'
: 'Click "Update Image" to see corrupted result'}
</div>
);
}
return (
<div
ref={containerRef}
className="image-container"
onMouseDown={handleMouseDown}
onMouseMove={handleMouseMove}
onMouseUp={handleMouseUp}
>
<img
ref={imgRef}
src={imageUrl}
alt={type}
onLoad={handleImageLoad}
style={{
left: pan.x,
top: pan.y,
width: size.width,
height: size.height
}}
title={
metadata ? `${metadata.fileName} (${metadata.fileSize} bytes)` : type
}
/>
</div>
);
}

View File

@ -0,0 +1,119 @@
import React, { useCallback } from 'react';
import { useStore } from '@nanostores/react';
import { initializeHexEditor, isCompiling, modifiedFileData, fileMetadata, compiledImageUrl } from '../stores/imageStore';
export default function ImageUpload() {
const compiling = useStore(isCompiling);
const modifiedData = useStore(modifiedFileData);
const metadata = useStore(fileMetadata);
const compiledUrl = useStore(compiledImageUrl);
const handleFileUpload = async (
event: React.ChangeEvent<HTMLInputElement>
) => {
const file = event.target.files?.[0];
if (!file) return;
try {
await initializeHexEditor(file);
console.log(`Loaded ${file.name} (${file.size} bytes) for hex editing`);
} catch (error) {
console.error('Failed to load file:', error);
}
};
// Export functionality - creates a proper image file from what's displayed
const handleExport = useCallback(async () => {
if (!metadata || !compiledUrl) return;
try {
// Generate filename
const originalName = metadata.fileName;
const lastDotIndex = originalName.lastIndexOf('.');
const nameWithoutExt = lastDotIndex > 0 ? originalName.substring(0, lastDotIndex) : originalName;
// Create an image from the compiled URL (what you see on screen)
const img = new Image();
img.crossOrigin = 'anonymous';
await new Promise((resolve, reject) => {
img.onload = resolve;
img.onerror = reject;
img.src = compiledUrl;
});
// Create canvas and draw the image
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) return;
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
ctx.drawImage(img, 0, 0);
// Convert canvas to blob and download as PNG (always valid)
canvas.toBlob((canvasBlob) => {
if (canvasBlob) {
const canvasUrl = URL.createObjectURL(canvasBlob);
const link = document.createElement('a');
link.href = canvasUrl;
link.download = `${nameWithoutExt}_modified.png`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(canvasUrl);
}
}, 'image/png', 1.0); // High quality PNG
} catch (error) {
console.error('Failed to export image:', error);
// Fallback to raw binary data export
if (modifiedData) {
const blob = new Blob([modifiedData], { type: 'application/octet-stream' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
const originalName = metadata.fileName;
const lastDotIndex = originalName.lastIndexOf('.');
const nameWithoutExt = lastDotIndex > 0 ? originalName.substring(0, lastDotIndex) : originalName;
const extension = lastDotIndex > 0 ? originalName.substring(lastDotIndex) : '';
const newFilename = `${nameWithoutExt}_modified${extension}`;
link.download = newFilename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
}
}, [compiledUrl, modifiedData, metadata]);
return (
<>
<input
type="file"
accept="image/*"
onChange={handleFileUpload}
id="imageUpload"
className="hidden-input"
disabled={compiling}
/>
<label htmlFor="imageUpload" className="load-button">
{compiling ? 'Compiling...' : 'Load Image'}
</label>
<button
onClick={handleExport}
className="export-button"
disabled={compiling || (!compiledUrl && !modifiedData)}
>
Export
</button>
</>
);
}

68
src/index.css Normal file
View File

@ -0,0 +1,68 @@
:root {
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}

10
src/main.tsx Normal file
View File

@ -0,0 +1,10 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import './index.css';
import App from './App.tsx';
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>
);

362
src/stores/imageStore.ts Normal file
View File

@ -0,0 +1,362 @@
import { atom, computed } from 'nanostores';
// Core image data - now handling raw file binary
export const originalImageFile = atom<File | null>(null);
export const originalFileData = atom<Uint8Array | null>(null);
export const modifiedFileData = atom<Uint8Array | null>(null);
export const compiledImageBlob = atom<Blob | null>(null);
// Hex editor state - proper chunking for large files
export const hexChunkSize = atom<number>(512); // 512 bytes = 32 rows of 16 bytes
export const currentHexChunk = atom<number>(0);
export const totalHexChunks = atom<number>(0);
export const currentChunkData = atom<Uint8Array | null>(null);
export const isCompiling = atom<boolean>(false);
export const hasModifications = atom<boolean>(false);
// Undo system
export const undoStack = atom<Uint8Array[]>([]);
export const canUndo = atom<boolean>(false);
// File metadata
export const fileMetadata = atom<{
fileName: string;
fileSize: number;
fileType: string;
} | null>(null);
// Shared pan state for synchronized image viewing
export const imagePan = atom<{ x: number; y: number }>({ x: 0, y: 0 });
export const imageSize = atom<{ width: number; height: number }>({ width: 0, height: 0 });
// Computed values
export const originalImageUrl = computed([originalImageFile], file => {
if (!file) return null;
return URL.createObjectURL(file);
});
export const compiledImageUrl = computed([compiledImageBlob], blob => {
if (!blob) return null;
return URL.createObjectURL(blob);
});
export const chunkInfo = computed(
[currentHexChunk, totalHexChunks, hexChunkSize, fileMetadata],
(chunk, total, size, metadata) => {
if (!metadata) return null;
const startByte = chunk * size;
const endByte = Math.min(startByte + size, metadata.fileSize);
return {
chunkIndex: chunk,
totalChunks: total,
startByte,
endByte,
chunkSize: endByte - startByte,
startAddress: startByte.toString(16).toUpperCase().padStart(8, '0'),
endAddress: (endByte - 1).toString(16).toUpperCase().padStart(8, '0'),
};
}
);
// Helper functions for hex conversion
export const bytesToHex = (data: Uint8Array): string => {
return Array.from(data)
.map(byte => byte.toString(16).padStart(2, '0'))
.join('');
};
export const hexToBytes = (hex: string): Uint8Array => {
const cleanHex = hex.replace(/[^0-9a-fA-F]/gi, '');
const bytes = new Uint8Array(cleanHex.length / 2);
for (let i = 0; i < cleanHex.length; i += 2) {
bytes[i / 2] = parseInt(cleanHex.substr(i, 2), 16);
}
return bytes;
};
export const byteToChar = (byte: number): string => {
// Show printable ASCII characters, others as dots
return byte >= 32 && byte <= 126 ? String.fromCharCode(byte) : '.';
};
// Chunk management
export const getChunkData = (
fullData: Uint8Array,
chunkIndex: number,
chunkSize: number
): Uint8Array => {
const start = chunkIndex * chunkSize;
const end = Math.min(start + chunkSize, fullData.length);
return fullData.slice(start, end);
};
export const updateChunkInFullData = (
fullData: Uint8Array,
chunkIndex: number,
chunkSize: number,
newChunkData: Uint8Array
): Uint8Array => {
const result = new Uint8Array(fullData);
const start = chunkIndex * chunkSize;
for (let i = 0; i < newChunkData.length; i++) {
if (start + i < result.length) {
result[start + i] = newChunkData[i];
}
}
return result;
};
// File loading
export const loadFileData = async (file: File): Promise<Uint8Array> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = e => {
const arrayBuffer = e.target!.result as ArrayBuffer;
const uint8Array = new Uint8Array(arrayBuffer);
resolve(uint8Array);
};
reader.onerror = () => reject(new Error('Failed to read file'));
reader.readAsArrayBuffer(file);
});
};
// Navigation functions
export const goToNextChunk = () => {
const current = currentHexChunk.get();
const total = totalHexChunks.get();
if (current < total - 1) {
currentHexChunk.set(current + 1);
loadCurrentChunk();
}
};
export const goToPreviousChunk = () => {
const current = currentHexChunk.get();
if (current > 0) {
currentHexChunk.set(current - 1);
loadCurrentChunk();
}
};
export const goToChunk = (chunkIndex: number) => {
const total = totalHexChunks.get();
if (chunkIndex >= 0 && chunkIndex < total) {
currentHexChunk.set(chunkIndex);
loadCurrentChunk();
}
};
export const goToAddress = (address: number) => {
const chunkSize = hexChunkSize.get();
const chunkIndex = Math.floor(address / chunkSize);
goToChunk(chunkIndex);
};
export const loadCurrentChunk = () => {
const fullData = modifiedFileData.get();
const chunkIndex = currentHexChunk.get();
const chunkSize = hexChunkSize.get();
if (!fullData) return;
const chunkData = getChunkData(fullData, chunkIndex, chunkSize);
currentChunkData.set(chunkData);
};
// Initialize hex editor
export const initializeHexEditor = async (file: File) => {
const fileData = await loadFileData(file);
const chunkSize = hexChunkSize.get();
const totalChunks = Math.ceil(fileData.length / chunkSize);
// Store file data
originalImageFile.set(file);
originalFileData.set(fileData);
modifiedFileData.set(new Uint8Array(fileData)); // Copy for modifications
// Reset state
totalHexChunks.set(totalChunks);
currentHexChunk.set(0);
hasModifications.set(false);
compiledImageBlob.set(null);
// Clear undo stack
undoStack.set([]);
canUndo.set(false);
// Set metadata
fileMetadata.set({
fileName: file.name,
fileSize: fileData.length,
fileType: file.type,
});
// Load first chunk
loadCurrentChunk();
};
// Update chunk data from hex editor
export const updateCurrentChunk = (newData: Uint8Array) => {
const fullData = modifiedFileData.get();
const chunkIndex = currentHexChunk.get();
const chunkSize = hexChunkSize.get();
if (!fullData) return;
const updatedFullData = updateChunkInFullData(
fullData,
chunkIndex,
chunkSize,
newData
);
modifiedFileData.set(updatedFullData);
currentChunkData.set(newData);
hasModifications.set(true);
};
// Undo system functions
export const pushToUndoStack = (data: Uint8Array) => {
const stack = undoStack.get();
const newStack = [...stack, new Uint8Array(data)];
// Limit undo stack to 50 items
if (newStack.length > 50) {
newStack.shift();
}
undoStack.set(newStack);
canUndo.set(true);
};
export const undo = () => {
const stack = undoStack.get();
if (stack.length === 0) return;
const previousState = stack[stack.length - 1];
const newStack = stack.slice(0, -1);
undoStack.set(newStack);
canUndo.set(newStack.length > 0);
modifiedFileData.set(new Uint8Array(previousState));
hasModifications.set(true);
};
// Create fault-tolerant image decoder
const decodeCorruptedImage = (data: Uint8Array): ImageData | null => {
try {
// For now, try to interpret raw data as RGBA pixels
// This is a simplified approach - we'll build a proper JPEG decoder later
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) return null;
// Estimate dimensions based on file size
const totalPixels = Math.floor(data.length / 3); // Assume RGB for now
const width = Math.floor(Math.sqrt(totalPixels));
const height = Math.ceil(totalPixels / width);
canvas.width = width;
canvas.height = height;
const imageData = ctx.createImageData(width, height);
const pixels = imageData.data;
// Convert raw bytes to RGBA pixels
for (let i = 0; i < Math.min(data.length, pixels.length / 4 * 3); i += 3) {
const pixelIndex = Math.floor(i / 3) * 4;
if (pixelIndex + 3 < pixels.length) {
pixels[pixelIndex] = data[i] || 0; // R
pixels[pixelIndex + 1] = data[i + 1] || 0; // G
pixels[pixelIndex + 2] = data[i + 2] || 0; // B
pixels[pixelIndex + 3] = 255; // A
}
}
return imageData;
} catch (error) {
console.error('Failed to decode corrupted image:', error);
return null;
}
};
const drawImageDataToCanvas = (imageData: ImageData): string => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) return '';
canvas.width = imageData.width;
canvas.height = imageData.height;
ctx.putImageData(imageData, 0, 0);
return canvas.toDataURL();
};
// Compile modified data into image
export const compileImage = async () => {
const modifiedData = modifiedFileData.get();
const metadata = fileMetadata.get();
if (!modifiedData || !metadata) return;
isCompiling.set(true);
try {
// First try standard blob approach
const blob = new Blob([modifiedData], { type: metadata.fileType });
const url = URL.createObjectURL(blob);
// Test if the blob creates a valid image
const img = new Image();
const loadPromise = new Promise<boolean>((resolve) => {
img.onload = () => resolve(true);
img.onerror = () => resolve(false);
img.src = url;
});
const isValid = await loadPromise;
if (isValid) {
// Standard approach worked
compiledImageBlob.set(blob);
} else {
// Blob is corrupted, use fault-tolerant decoder
URL.revokeObjectURL(url);
const imageData = decodeCorruptedImage(modifiedData);
if (imageData) {
const dataUrl = drawImageDataToCanvas(imageData);
const response = await fetch(dataUrl);
const corruptedBlob = await response.blob();
compiledImageBlob.set(corruptedBlob);
} else {
// Even fault-tolerant decoder failed
compiledImageBlob.set(null);
}
}
} catch (error) {
console.error('Failed to compile image:', error);
compiledImageBlob.set(null);
} finally {
isCompiling.set(false);
}
};
// Reset to original
export const resetToOriginal = () => {
const originalData = originalFileData.get();
if (!originalData) return;
modifiedFileData.set(new Uint8Array(originalData));
hasModifications.set(false);
compiledImageBlob.set(null);
loadCurrentChunk();
};

19
src/utils/debounce.ts Normal file
View File

@ -0,0 +1,19 @@
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function debounce<T extends (...args: any[]) => any>(
func: T,
wait: number
): (...args: Parameters<T>) => void {
let timeout: number | null = null;
return function executedFunction(...args: Parameters<T>) {
const later = () => {
timeout = null;
func(...args);
};
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(later, wait);
};
}

24
tsconfig.json Normal file
View File

@ -0,0 +1,24 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"references": [{ "path": "./tsconfig.node.json" }]
}

11
tsconfig.node.json Normal file
View File

@ -0,0 +1,11 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true,
"strict": true
},
"include": ["vite.config.js", "eslint.config.js"]
}

7
vite.config.js Normal file
View File

@ -0,0 +1,7 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
});