Personal Telegram developer console for GitHub

feat/studio-g0-foundation
audit/commit-drilldown audit/finalize-workspace-menu-security audit/ops-actionability audit/pr-menu-consolidation audit/status-menu-consolidation audit/telegram-menu-e2e audit/telegram-menu-e2e-wave2 chore/actions-node24-runtime cleanup/remove-diag design/cloudflare-ops-read docs/control-plane-2-7-design docs/guide-v2-1-sync docs/menu-audit-final-sync docs/phase2-acceptance-closeout docs/phase2-multifile-design feat/bootstrap-worker feat/cloudflare-ops-read feat/cp2-multifile-final feat/cp2-multifile-workspace feat/cp3-github-write-final feat/cp4-cloudflare-ops-final feat/cp5-cicd-control-plane feat/cp6-incident-manager feat/cp7-automation-engine feat/deep-file-browser feat/final-delivery-16-20 feat/github-advanced-read feat/in-app-guide-v2 feat/navigation-recovery-ux-v2 feat/ops-console-v2-1 feat/persistent-menu-code-input feat/phase2-multifile-workspace feat/phase2-multifile-workspace-v2 feat/plugin-foundation-v1 feat/safe-github-ops feat/self-register-webhook feat/studio-g0-foundation feat/telegram-main-inline-menu feat/telegram-pr-merge feat/ux-platform-8-12 feat/v3a-readonly-copilot feat/workspace-file-upload feature/mobile-repo-browser feature/multi-file-change-set fix/approval-expiry-feedback fix/callback-resilience-and-docs fix/ci-actions-pagination fix/cloudflare-fetch-binding fix/editor-request-body-cap fix/editor-safe-file-options fix/issues-permission-release-empty-ux fix/main-menu-callback-fallback fix/phase2-file-editor-selection fix/phase2-final-ux fix/phase2-workspace-ref-persistence fix/production-auto-deploy fix/provider-write-error-feedback fix/repository-id-navigation-fallback fix/repository-pr-navigation fix/telegram-callback-updates fix/telegram-runtime-diagnostics fix/workspace-editor-flow-v2 fix/workspace-recovery-validation hardening/ci-zero-test-telegram-token hardening/pr1-destructive-totp hardening/pr2-kill-switch main multifile-workspace nexa/edit-BwJEIIY3PW nexa/edit-IPHT8irO7b nexa/edit-b4Od3BIMYd p2-multifile phase2-20261005 phase2-20261005-a phase2-20261005-b phase2-20261005-c phase2-20261005-d phase2-20261005-e phase2-20261005-f phase2-20261005-g phase2-20261005-h phase2-20261005-i phase2-20261005-j phase2-20261005-k phase2-20261005-l phase2-20261005-m phase2-20261005-n phase2-20261005-o phase2-20261005-p phase2-20261005-q phase2-20261005-r phase2-20261005-s phase2-20261005-t phase2-20261005-u phase2-20261005-v phase2-20261005-w phase2-20261005-x phase2-20261005-y phase2-20261005-z phase2-acceptance-closeout phase2-add-file-hotfix phase2-change-set phase2-design-20261005 phase2-design-final phase2-implementation phase2-multifile-implementation phase2-multifile-spec phase2-spec-final phase2-workspace phase2/multifile-workspace plan/nexa-studio-v2-reviewed security/remove-telegram-setup spec/repository-workspace-editor v3a/multifile work/multifile
tsx 1,415 lines 52.6 KB
Raw
1 import { useEffect, useMemo, useState } from 'react';
2 import { ApiError, createApi } from './api.js';
3 import { CodeEditor, searchEditor } from './CodeEditor.js';
4 import type {
5 Approval,
6 Diff,
7 Limits,
8 Repository,
9 ReviewSnapshot,
10 TreeItem,
11 Workspace,
12 WorkspaceResponse
13 } from './types.js';
14
15 type Page = 'home' | 'tree' | 'editor' | 'review' | 'approval';
16 type Failure = { message: string; retry?: () => void };
17 const encoder = new TextEncoder();
18 const number = (value: number) => value.toLocaleString('fa-IR');
19 const bytes = (value: string) => encoder.encode(value).length;
20 const chars = (value: string) => Array.from(value).length;
21 const fileName = (path: string) => path.split('/').pop() || path;
22 const workspaceStorageKey = 'nexa.studio.workspace';
23 const workspaceIdPattern = /^[A-Za-z0-9]{10}$/;
24 function rememberWorkspace(id: string | null) {
25 try {
26 if (id && workspaceIdPattern.test(id))
27 window.localStorage.setItem(workspaceStorageKey, id);
28 else window.localStorage.removeItem(workspaceStorageKey);
29 } catch {
30 // Storage is optional; signed launch data and draft contents stay in memory.
31 }
32 }
33 function rememberedWorkspace() {
34 try {
35 const id = window.localStorage.getItem(workspaceStorageKey);
36 if (!id || workspaceIdPattern.test(id)) return id;
37 rememberWorkspace(null);
38 } catch {
39 // Telegram browsers may disable local storage.
40 }
41 return null;
42 }
43 const unavailableWorkspace = (error: unknown) =>
44 error instanceof ApiError && [400, 401, 403, 404, 410].includes(error.status);
45
46 function Icon({
47 name,
48 className = ''
49 }: {
50 name:
51 | 'code'
52 | 'repo'
53 | 'folder'
54 | 'file'
55 | 'arrow'
56 | 'check'
57 | 'lock'
58 | 'search'
59 | 'plus';
60 className?: string;
61 }) {
62 const paths = {
63 code: (
64 <>
65 <path d="m8 7-5 5 5 5M16 7l5 5-5 5M14 4l-4 16" />
66 </>
67 ),
68 repo: (
69 <>
70 <path d="M4 4a2 2 0 0 1 2-2h14v20H6a2 2 0 0 1-2-2Zm0 13h16M8 6h7" />
71 </>
72 ),
73 folder: <path d="M3 7V4h7l2 3h9v13H3Z" />,
74 file: (
75 <>
76 <path d="M5 2h9l5 5v15H5ZM14 2v6h5M8 12h8M8 16h6" />
77 </>
78 ),
79 arrow: <path d="m9 5 7 7-7 7M16 12H3" />,
80 check: <path d="m5 12 4 4L19 6" />,
81 lock: (
82 <>
83 <rect x="5" y="10" width="14" height="11" rx="2" />
84 <path d="M8 10V7a4 4 0 0 1 8 0v3M12 14v3" />
85 </>
86 ),
87 search: (
88 <>
89 <circle cx="10" cy="10" r="6" />
90 <path d="m15 15 6 6" />
91 </>
92 ),
93 plus: <path d="M12 4v16M4 12h16" />
94 };
95 return (
96 <svg
97 className={className}
98 width="20"
99 height="20"
100 viewBox="0 0 24 24"
101 fill="none"
102 stroke="currentColor"
103 strokeWidth="1.7"
104 strokeLinecap="round"
105 strokeLinejoin="round"
106 aria-hidden="true"
107 >
108 {paths[name]}
109 </svg>
110 );
111 }
112
113 export function App({ fetcher = fetch }: { fetcher?: typeof fetch }) {
114 const [telegram] = useState(() => window.Telegram?.WebApp);
115 const [initData] = useState(() => telegram?.initData || '');
116 const api = useMemo(() => createApi(initData, fetcher), [initData, fetcher]);
117 const [page, setPage] = useState<Page>('home');
118 const [userName, setUserName] = useState('');
119 const [repositories, setRepositories] = useState<Repository[]>([]);
120 const [limits, setLimits] = useState<Limits | null>(null);
121 const [repository, setRepository] = useState<Repository | null>(null);
122 const [treePath, setTreePath] = useState('');
123 const [items, setItems] = useState<TreeItem[]>([]);
124 const [addingFile, setAddingFile] = useState(false);
125 const [workspace, setWorkspace] = useState<Workspace | null>(null);
126 const [resumableWorkspace, setResumableWorkspace] =
127 useState<Workspace | null>(null);
128 const [drafts, setDrafts] = useState<Record<string, string>>({});
129 const [activePath, setActivePath] = useState('');
130 const [message, setMessage] = useState('');
131 const [diff, setDiff] = useState<Diff | null>(null);
132 const [reviewSnapshot, setReviewSnapshot] = useState<ReviewSnapshot | null>(
133 null
134 );
135 const [approval, setApproval] = useState<Approval | null>(null);
136 const [fontSize, setFontSize] = useState(14);
137 const [busy, setBusy] = useState('');
138 const [failure, setFailure] = useState<Failure | null>(null);
139 const [status, setStatus] = useState('');
140 const [conflict, setConflict] = useState<{
141 latest: WorkspaceResponse;
142 path: string;
143 } | null>(null);
144 const [discardAction, setDiscardAction] = useState<(() => void) | null>(null);
145 const activeFile = workspace?.files.find((file) => file.path === activePath);
146 const text = drafts[activePath] ?? '';
147 const dirtyPaths =
148 workspace?.files
149 .filter(
150 (file) => (drafts[file.path] ?? file.draftText) !== file.draftText
151 )
152 .map((file) => file.path) || [];
153 const hasUnsaved = dirtyPaths.length > 0;
154 const aggregateBytes =
155 workspace?.files.reduce(
156 (total, file) => total + bytes(drafts[file.path] ?? file.draftText),
157 0
158 ) || 0;
159 const overLimit =
160 !!limits &&
161 (bytes(text) > limits.maxBytes ||
162 chars(text) > limits.maxChars ||
163 aggregateBytes > limits.maxAggregateBytes);
164 const editable = workspace?.state === 'DRAFT' && !busy && !conflict;
165
166 function showError(error: unknown, retry?: () => void) {
167 setFailure({
168 message:
169 error instanceof ApiError
170 ? error.message
171 : 'ارتباط با سرویس برقرار نشد. اتصال را بررسی و دوباره تلاش کن.',
172 retry
173 });
174 }
175 async function perform(
176 label: string,
177 action: () => Promise<void>,
178 retry?: () => void
179 ) {
180 setBusy(label);
181 setFailure(null);
182 try {
183 await action();
184 } catch (error) {
185 showError(error, retry);
186 } finally {
187 setBusy('');
188 }
189 }
190 function acceptWorkspace(
191 response: WorkspaceResponse,
192 preserve = false,
193 acceptedPath?: string
194 ) {
195 setReviewSnapshot(null);
196 rememberWorkspace(response.workspace.id);
197 setResumableWorkspace(response.workspace);
198 setWorkspace((current) => ({
199 ...response.workspace,
200 files: response.workspace.files.map((file) => {
201 const previous = current?.files.find(
202 (entry) => entry.path === file.path
203 );
204 // An unrelated response must never authorize overwriting an unseen edit.
205 return preserve && previous && file.path !== acceptedPath
206 ? previous
207 : file;
208 })
209 }));
210 if (response.limits) setLimits(response.limits);
211 setDrafts((current) =>
212 Object.fromEntries(
213 response.workspace.files.map((file) => [
214 file.path,
215 preserve && current[file.path] !== undefined
216 ? current[file.path]
217 : file.draftText
218 ])
219 )
220 );
221 }
222 async function getRememberedWorkspace(id: string) {
223 try {
224 const result = await api<WorkspaceResponse>(`/workspaces/${id}`);
225 if (
226 result.workspace.id !== id ||
227 !['DRAFT', 'READY', 'COMMITTED', 'COMMITTING'].includes(
228 result.workspace.state
229 )
230 ) {
231 rememberWorkspace(null);
232 setResumableWorkspace(null);
233 return null;
234 }
235 setResumableWorkspace(result.workspace);
236 return result;
237 } catch (error) {
238 if (!unavailableWorkspace(error)) throw error;
239 rememberWorkspace(null);
240 setResumableWorkspace(null);
241 return null;
242 }
243 }
244 async function loadHome() {
245 await perform(
246 'در حال دریافت مخازن…',
247 async () => {
248 let session;
249 try {
250 session = await api<{ user: { name: string }; limits: Limits }>('');
251 } catch (error) {
252 if (unavailableWorkspace(error)) {
253 rememberWorkspace(null);
254 setResumableWorkspace(null);
255 }
256 throw error;
257 }
258 setUserName(session.user.name);
259 setLimits(session.limits);
260 const savedId = rememberedWorkspace();
261 const [repos] = await Promise.all([
262 api<{ repositories: Repository[] }>('/repos'),
263 savedId ? getRememberedWorkspace(savedId) : Promise.resolve(null)
264 ]);
265 setRepositories(repos.repositories);
266 setPage('home');
267 },
268 () => void loadHome()
269 );
270 }
271 async function continueWorkspace() {
272 if (!resumableWorkspace) return;
273 await perform(
274 'در حال دریافت فضای کاری…',
275 async () => {
276 const result = await getRememberedWorkspace(resumableWorkspace.id);
277 if (!result) return;
278 const restored = result.workspace;
279 acceptWorkspace(result);
280 setRepository(
281 repositories.find(
282 (repo) => String(repo.id) === String(restored.repoId)
283 ) || null
284 );
285 setActivePath(restored.path || restored.files[0]?.path || '');
286 setMessage(restored.commitMessage || '');
287 setApproval(null);
288 setDiff(null);
289 setConflict(null);
290 setStatus('');
291 if (restored.state === 'READY') {
292 const reviewed = await api<{ diff: Diff; review: ReviewSnapshot }>(
293 `/workspaces/${restored.id}/diff`
294 );
295 if (!reviewed.review) throw new Error('Review snapshot unavailable');
296 setDiff(reviewed.diff);
297 setReviewSnapshot(reviewed.review);
298 setPage('review');
299 } else if (
300 restored.state === 'COMMITTED' ||
301 restored.state === 'COMMITTING'
302 ) {
303 setPage('approval');
304 } else setPage('editor');
305 },
306 () => void continueWorkspace()
307 );
308 }
309 useEffect(() => {
310 if (!initData) return;
311 telegram?.ready?.();
312 telegram?.expand?.();
313 void loadHome();
314 // The signed Telegram launch data stays in memory for this mount only.
315 }, [api]);
316 useEffect(() => {
317 const beforeUnload = (event: BeforeUnloadEvent) => {
318 if (hasUnsaved) {
319 event.preventDefault();
320 event.returnValue = '';
321 }
322 };
323 window.addEventListener('beforeunload', beforeUnload);
324 if (hasUnsaved) telegram?.enableClosingConfirmation?.();
325 else telegram?.disableClosingConfirmation?.();
326 return () => window.removeEventListener('beforeunload', beforeUnload);
327 }, [hasUnsaved, telegram]);
328 function guard(action: () => void) {
329 if (hasUnsaved) setDiscardAction(() => action);
330 else action();
331 }
332 function backToFiles() {
333 guard(() => {
334 if (!repository) {
335 setPage('home');
336 return;
337 }
338 setDrafts(
339 Object.fromEntries(
340 workspace?.files.map((file) => [file.path, file.draftText]) || []
341 )
342 );
343 setAddingFile(false);
344 setConflict(null);
345 setStatus('');
346 void loadTree(repository, '');
347 });
348 }
349 useEffect(() => {
350 const button = telegram?.BackButton;
351 if (!button) return;
352 const back = () => {
353 if (busy) return;
354 if (page === 'review' || (page === 'tree' && addingFile))
355 setPage('editor');
356 else if (page === 'editor') backToFiles();
357 else if (page === 'tree') setPage('home');
358 else if (page === 'approval') guard(() => telegram?.close?.());
359 };
360 if (page === 'home') button.hide();
361 else button.show();
362 button.onClick(back);
363 return () => button.offClick(back);
364 }, [page, busy, hasUnsaved, addingFile, repository]);
365
366 async function loadTree(repo: Repository, path: string, adding = false) {
367 await perform(
368 'در حال دریافت فایل‌ها…',
369 async () => {
370 const query = new URLSearchParams({ repoId: String(repo.id), path });
371 if (adding && workspace) query.set('workspaceId', workspace.id);
372 const result = await api<{ items: TreeItem[]; path: string }>(
373 `/tree?${query}`
374 );
375 setRepository(repo);
376 setTreePath(result.path);
377 setItems(result.items);
378 setAddingFile(adding);
379 setPage('tree');
380 },
381 () => void loadTree(repo, path, adding)
382 );
383 }
384 async function openFile(item: TreeItem) {
385 if (item.type === 'dir' || item.type === 'directory') {
386 if (repository) await loadTree(repository, item.path, addingFile);
387 return;
388 }
389 await perform(
390 'در حال باز کردن فایل…',
391 async () => {
392 if (addingFile && workspace) {
393 const result = await api<WorkspaceResponse>(
394 `/workspaces/${workspace.id}/files`,
395 { method: 'POST', body: JSON.stringify({ refId: item.refId }) }
396 );
397 acceptWorkspace(result, true);
398 setActivePath(item.path);
399 } else {
400 const result = await api<WorkspaceResponse>('/workspaces', {
401 method: 'POST',
402 body: JSON.stringify({ refId: item.refId })
403 });
404 acceptWorkspace(result);
405 setActivePath(
406 result.workspace.path || result.workspace.files[0].path
407 );
408 setMessage(result.workspace.commitMessage || '');
409 setApproval(null);
410 setDiff(null);
411 }
412 setAddingFile(false);
413 setStatus('');
414 setPage('editor');
415 },
416 () => void openFile(item)
417 );
418 }
419 async function saveFile() {
420 if (
421 !workspace ||
422 !activeFile ||
423 overLimit ||
424 !editable ||
425 !dirtyPaths.includes(activePath)
426 )
427 return;
428 const selectedPath = activePath;
429 const savedText = text;
430 await perform(
431 'در حال ذخیره…',
432 async () => {
433 try {
434 const result = await api<WorkspaceResponse>(
435 `/workspaces/${workspace.id}/files`,
436 {
437 method: 'PUT',
438 headers: { 'if-match': String(activeFile.revision) },
439 body: JSON.stringify({ path: selectedPath, text: savedText })
440 }
441 );
442 acceptWorkspace(result, true, selectedPath);
443 setDrafts((current) => ({
444 ...current,
445 [selectedPath]:
446 result.workspace.files.find((file) => file.path === selectedPath)
447 ?.draftText ?? savedText
448 }));
449 setStatus(
450 'تغییرات در فضای کاری ذخیره شد. هنوز چیزی در GitHub ثبت نشده است.'
451 );
452 } catch (error) {
453 if (!(error instanceof ApiError) || error.status !== 409) throw error;
454 const latest = await api<WorkspaceResponse>(
455 `/workspaces/${workspace.id}`
456 );
457 setConflict({ latest, path: selectedPath });
458 setStatus('');
459 }
460 },
461 () => void saveFile()
462 );
463 }
464 function resolveConflict(keepMine: boolean) {
465 if (!conflict) return;
466 acceptWorkspace(conflict.latest, true, conflict.path);
467 if (!keepMine) {
468 const latest = conflict.latest.workspace.files.find(
469 (file) => file.path === conflict.path
470 );
471 if (latest)
472 setDrafts((current) => ({
473 ...current,
474 [conflict.path]: latest.draftText
475 }));
476 }
477 setConflict(null);
478 setStatus(
479 keepMine
480 ? 'نسخه تو نگه داشته شد. برای جایگزینی نسخه سرور، دوباره «ذخیره تغییرات» را بزن.'
481 : 'نسخه جدید بارگیری شد. می‌توانی ویرایش را ادامه بدهی.'
482 );
483 }
484 async function review(refresh = false) {
485 if (!workspace || hasUnsaved || conflict) return;
486 setReviewSnapshot(null);
487 await perform(
488 'در حال آماده‌سازی Diff…',
489 async () => {
490 if (refresh) {
491 const latest = await api<WorkspaceResponse>(
492 `/workspaces/${workspace.id}`
493 );
494 acceptWorkspace(latest);
495 }
496 const result = await api<{ diff: Diff; review: ReviewSnapshot }>(
497 `/workspaces/${workspace.id}/diff`
498 );
499 if (!result.review) throw new Error('Review snapshot unavailable');
500 setDiff(result.diff);
501 setReviewSnapshot(result.review);
502 setPage('review');
503 setStatus('');
504 },
505 () => void review(refresh)
506 );
507 }
508 async function requestApproval() {
509 if (
510 !workspace ||
511 !reviewSnapshot ||
512 !message.trim() ||
513 chars(message.trim()) > 120 ||
514 hasUnsaved ||
515 diff?.truncated
516 )
517 return;
518 const reviewed = reviewSnapshot;
519 const expectedMessage = message.trim();
520 await perform(
521 'در حال ارسال درخواست تأیید…',
522 async () => {
523 try {
524 await api<WorkspaceResponse>(`/workspaces/${workspace.id}/message`, {
525 method: 'PUT',
526 body: JSON.stringify({ message: expectedMessage })
527 });
528 // A message response may contain a concurrent edit. Keep the displayed review fixed.
529 setWorkspace((current) =>
530 current ? { ...current, commitMessage: expectedMessage } : current
531 );
532 const requested = await api<Approval>(
533 `/workspaces/${workspace.id}/approval`,
534 {
535 method: 'POST',
536 body: JSON.stringify({
537 review: reviewed,
538 message: expectedMessage
539 })
540 }
541 );
542 if (!requested.approvalRequested)
543 throw new Error('Approval was not requested');
544 setApproval(requested);
545 setPage('approval');
546 } catch (error) {
547 if (!(error instanceof ApiError) || error.status !== 409) throw error;
548 setReviewSnapshot(null);
549 showError(error);
550 }
551 },
552 () => void requestApproval()
553 );
554 }
555 async function refreshWorkspace() {
556 if (!workspace) return;
557 await perform(
558 'در حال بررسی نتیجه…',
559 async () => {
560 const result = await api<WorkspaceResponse>(
561 `/workspaces/${workspace.id}`
562 );
563 acceptWorkspace(result);
564 setStatus(
565 result.workspace.state === 'COMMITTED'
566 ? ''
567 : 'هنوز نتیجه ثبت Commit دریافت نشده است. وضعیت تأیید را در تلگرام بررسی کن.'
568 );
569 },
570 () => void refreshWorkspace()
571 );
572 }
573 async function cancelWorkspace() {
574 if (!workspace) return;
575 await perform(
576 'در حال لغو فضای کاری…',
577 async () => {
578 await api(`/workspaces/${workspace.id}`, { method: 'DELETE' });
579 rememberWorkspace(null);
580 setResumableWorkspace(null);
581 setWorkspace(null);
582 setDrafts({});
583 setApproval(null);
584 setStatus('فضای کاری لغو شد.');
585 setPage('home');
586 },
587 () => void cancelWorkspace()
588 );
589 }
590
591 useEffect(() => {
592 if (!discardAction) return;
593 const previousFocus =
594 document.activeElement instanceof HTMLElement
595 ? document.activeElement
596 : null;
597 const dialog = document.querySelector<HTMLElement>('[role="dialog"]');
598 const focusable = () =>
599 Array.from(
600 dialog?.querySelectorAll<HTMLElement>(
601 'button:not(:disabled), a[href], input:not(:disabled), select:not(:disabled), [tabindex="0"]'
602 ) || []
603 );
604 focusable()[0]?.focus();
605 const keydown = (event: KeyboardEvent) => {
606 if (event.key === 'Escape') {
607 event.preventDefault();
608 setDiscardAction(null);
609 }
610 if (event.key === 'Tab') {
611 const controls = focusable();
612 const first = controls[0];
613 const last = controls[controls.length - 1];
614 if (event.shiftKey && document.activeElement === first) {
615 event.preventDefault();
616 last?.focus();
617 } else if (!event.shiftKey && document.activeElement === last) {
618 event.preventDefault();
619 first?.focus();
620 }
621 }
622 };
623 document.addEventListener('keydown', keydown);
624 return () => {
625 document.removeEventListener('keydown', keydown);
626 if (previousFocus?.isConnected) previousFocus.focus();
627 };
628 }, [discardAction]);
629
630 const repoLabel = (
631 <span dir="ltr">{repository?.fullName || workspace?.repoFullName}</span>
632 );
633 const workspaceHeader = workspace && (
634 <div className="workspace-header">
635 <div>
636 <p className="eyebrow">فضای کاری</p>
637 <h1 className="workspace-title" dir="ltr">
638 {workspace.repoFullName}
639 </h1>
640 <div className="workspace-meta">
641 <span>
642 مبنای تغییر <bdi>{workspace.baseBranch}</bdi>
643 </span>
644 <span className="inline-code" dir="ltr">
645 {workspace.baseHeadSha.slice(0, 10)}
646 </span>
647 <span>{number(workspace.files.length)} فایل</span>
648 </div>
649 </div>
650 <span className="badge">
651 {workspace.state === 'COMMITTED' ? 'ثبت‌شده' : 'پیش‌نویس امن'}
652 </span>
653 </div>
654 );
655
656 return (
657 <div className="app-shell" dir="rtl">
658 <header className="topbar">
659 <div className="brand">
660 <span className="brand-mark">
661 <Icon name="code" />
662 </span>
663 <span>
664 <span className="brand-name">
665 Nexa <strong>Studio</strong>
666 </span>
667 <span className="brand-subtitle">
668 از ایده تا تغییر، داخل تلگرام
669 </span>
670 </span>
671 </div>
672 {userName && <span className="user-pill">{userName}</span>}
673 </header>
674 <main className="app-main" aria-busy={!!busy}>
675 {!initData ? (
676 <section className="empty-state">
677 <span className="brand-mark">
678 <Icon name="lock" />
679 </span>
680 <h1>استودیوی تو، داخل تلگرام</h1>
681 <p>
682 برای دسترسی امن به مخازن، Nexa Studio را از دکمه داخل ربات تلگرام
683 باز کن.
684 </p>
685 <button
686 className="button secondary"
687 type="button"
688 onClick={() => window.location.reload()}
689 >
690 بررسی دوباره
691 </button>
692 </section>
693 ) : (
694 <>
695 {failure && (
696 <div className="notice error" role="alert">
697 <div>
698 <strong className="notice-title">درخواست انجام نشد</strong>
699 <p>{failure.message}</p>
700 </div>
701 {failure.retry && (
702 <button
703 className="button secondary"
704 type="button"
705 disabled={!!busy}
706 onClick={failure.retry}
707 >
708 تلاش دوباره
709 </button>
710 )}
711 </div>
712 )}
713 {status && (
714 <div className="notice info" role="status">
715 <Icon name="check" />
716 <p>{status}</p>
717 </div>
718 )}
719 {busy && (
720 <div className="loading-state" role="status">
721 <span className="spinner" />
722 {busy}
723 </div>
724 )}
725 {page === 'home' && (
726 <section>
727 <div className="screen-heading">
728 <p className="eyebrow">میز کار تو</p>
729 <h1 className="screen-title">
730 {userName
731 ? `${userName}، از کجا شروع کنیم؟`
732 : 'یک تغییر کوچک، یک قدم جلوتر.'}
733 </h1>
734 <p className="screen-description">
735 مخزنت را باز کن، فایل‌ها را ویرایش کن و تغییرات را پیش از
736 تأیید ببین.
737 </p>
738 </div>
739 {resumableWorkspace && (
740 <div className="notice info">
741 <div>
742 <strong>فضای کاری قبلی</strong>
743 <p dir="ltr">{resumableWorkspace.repoFullName}</p>
744 </div>
745 <button
746 className="button secondary"
747 type="button"
748 disabled={!!busy}
749 onClick={() => guard(() => void continueWorkspace())}
750 >
751 ادامه فضای کاری
752 </button>
753 </div>
754 )}
755 <div className="panel-heading">
756 <h2>مخازن GitHub</h2>
757 <button
758 className="button quiet small"
759 type="button"
760 disabled={!!busy}
761 onClick={() => void loadHome()}
762 >
763 تازه‌سازی
764 </button>
765 </div>
766 {!busy && !failure && repositories.length === 0 ? (
767 <div className="empty-state">
768 <Icon name="repo" />
769 <h2>مخزنی برای نمایش نیست</h2>
770 <p>
771 دسترسی حساب متصل به مخازن را در GitHub بررسی کن، سپس
772 دوباره دریافت کن.
773 </p>
774 <button
775 className="button secondary"
776 type="button"
777 onClick={() => void loadHome()}
778 >
779 دریافت دوباره مخازن
780 </button>
781 </div>
782 ) : (
783 <div className="repo-list">
784 {repositories.map((repo) => (
785 <button
786 key={repo.id}
787 className="repo-card"
788 type="button"
789 disabled={!!busy}
790 onClick={() => void loadTree(repo, '')}
791 >
792 <span className="repo-icon">
793 <Icon name="repo" />
794 </span>
795 <span className="repo-copy">
796 <span className="repo-name" dir="ltr">
797 {repo.name}
798 </span>
799 <span className="repo-description">
800 {repo.description || repo.fullName}
801 </span>
802 <span className="repo-meta">
803 <span>{repo.private ? 'خصوصی' : 'عمومی'}</span>
804 <bdi>{repo.defaultBranch}</bdi>
805 </span>
806 </span>
807 <Icon name="arrow" />
808 </button>
809 ))}
810 </div>
811 )}
812 <p className="screen-footer">
813 <Icon name="lock" />
814 هیچ تغییری بدون تأیید امن تو در تلگرام ثبت نمی‌شود.
815 </p>
816 </section>
817 )}
818 {page === 'tree' && repository && (
819 <section>
820 <button
821 className="button quiet back-button"
822 type="button"
823 disabled={!!busy}
824 onClick={() => {
825 if (addingFile) setPage('editor');
826 else setPage('home');
827 }}
828 >
829 <Icon name="arrow" />
830 {addingFile ? 'بازگشت به ویرایشگر' : 'همه مخازن'}
831 </button>
832 <div className="screen-heading">
833 <p className="eyebrow">
834 {addingFile ? 'افزودن به فضای کاری' : 'مرور مخزن'}
835 </p>
836 <h1 className="screen-title" dir="ltr">
837 {repository.name}
838 </h1>
839 <p className="screen-description">
840 {addingFile
841 ? 'فایل بعدی را برای ویرایش کنار فایل‌های فعلی انتخاب کن.'
842 : 'یک فایل متنی را انتخاب کن تا فضای کاری‌ات باز شود.'}
843 </p>
844 </div>
845 <div className="browser-panel">
846 <nav className="breadcrumb" aria-label="مسیر مخزن">
847 <button
848 className="button quiet small"
849 type="button"
850 disabled={!!busy}
851 onClick={() => void loadTree(repository, '', addingFile)}
852 >
853 {repoLabel}
854 </button>
855 {treePath
856 .split('/')
857 .filter(Boolean)
858 .map((part, index, parts) => (
859 <button
860 key={index}
861 className="button quiet small"
862 type="button"
863 disabled={!!busy}
864 onClick={() =>
865 void loadTree(
866 repository,
867 parts.slice(0, index + 1).join('/'),
868 addingFile
869 )
870 }
871 >
872 <bdi>{part}</bdi>
873 </button>
874 ))}
875 </nav>
876 {items.length ? (
877 <div className="tree-list">
878 {items.map((item) => {
879 const directory =
880 item.type === 'dir' || item.type === 'directory';
881 const exists =
882 addingFile &&
883 workspace?.files.some(
884 (file) => file.path === item.path
885 );
886 return (
887 <button
888 key={item.refId}
889 className="tree-row"
890 type="button"
891 disabled={!!busy || !!exists}
892 onClick={() => void openFile(item)}
893 >
894 <span className="tree-icon">
895 <Icon name={directory ? 'folder' : 'file'} />
896 </span>
897 <span className="tree-name" dir="ltr">
898 {item.name}
899 </span>
900 <span className="tree-detail">
901 {exists
902 ? 'در فضای کاری'
903 : directory
904 ? 'پوشه'
905 : `${number(item.size || 0)} بایت`}
906 </span>
907 </button>
908 );
909 })}
910 </div>
911 ) : (
912 <div className="empty-state">
913 <Icon name="folder" />
914 <h2>این پوشه خالی است</h2>
915 <p>به ریشه مخزن برگرد و پوشه دیگری را باز کن.</p>
916 <button
917 className="button secondary"
918 type="button"
919 disabled={!!busy}
920 onClick={() =>
921 void loadTree(repository, '', addingFile)
922 }
923 >
924 ریشه مخزن
925 </button>
926 </div>
927 )}
928 </div>
929 {addingFile && limits && (
930 <p className="field-help">
931 تا {number(limits.maxFiles)} فایل و مجموع{' '}
932 {number(limits.maxAggregateBytes)} بایت در هر فضای کاری.
933 </p>
934 )}
935 </section>
936 )}
937 {page === 'editor' && workspace && activeFile && limits && (
938 <section>
939 <button
940 className="button quiet back-button"
941 type="button"
942 disabled={!!busy}
943 onClick={backToFiles}
944 >
945 <Icon name="arrow" />
946 بازگشت به فایل‌ها
947 </button>
948 {workspaceHeader}
949 {conflict && (
950 <div className="conflict-panel" role="alert">
951 <strong>نسخه این فایل تغییر کرده است</strong>
952 <p>
953 یک نسخه تازه روی سرور وجود دارد. نسخه تو هنوز اینجاست؛
954 خودت انتخاب کن کدام را ادامه بدهی.
955 </p>
956 <div className="action-row">
957 <button
958 className="button primary"
959 type="button"
960 onClick={() => resolveConflict(true)}
961 >
962 نگه‌داشتن نسخه من
963 </button>
964 <button
965 className="button secondary"
966 type="button"
967 onClick={() => resolveConflict(false)}
968 >
969 بارگیری نسخه جدید
970 </button>
971 </div>
972 </div>
973 )}
974 <div className="workspace-layout">
975 <div className="editor-panel">
976 <div className="editor-toolbar">
977 <div
978 className="file-tabs"
979 role="tablist"
980 aria-label="فایل‌های فضای کاری"
981 >
982 {workspace.files.map((file) => (
983 <button
984 key={file.path}
985 type="button"
986 role="tab"
987 title={file.path}
988 aria-selected={file.path === activePath}
989 disabled={!!busy || !!conflict}
990 className={`file-tab${file.path === activePath ? ' active' : ''}${dirtyPaths.includes(file.path) ? ' dirty' : ''}`}
991 onClick={() => {
992 setActivePath(file.path);
993 setStatus('');
994 }}
995 >
996 <Icon name="file" />
997 <bdi>{fileName(file.path)}</bdi>
998 {dirtyPaths.includes(file.path) && (
999 <span aria-label="ذخیره نشده">●</span>
1000 )}
1001 </button>
1002 ))}
1003 </div>
1004 <div className="editor-settings">
1005 <button
1006 className="icon-button"
1007 type="button"
1008 title="جست‌وجو در فایل"
1009 aria-label="جست‌وجو در فایل"
1010 onClick={searchEditor}
1011 >
1012 <Icon name="search" />
1013 </button>
1014 <label className="font-control">
1015 اندازه کد
1016 <select
1017 className="select-control"
1018 aria-label="اندازه قلم کد"
1019 value={fontSize}
1020 onChange={(event) =>
1021 setFontSize(Number(event.target.value))
1022 }
1023 >
1024 {[12, 14, 16, 18, 20].map((size) => (
1025 <option key={size} value={size}>
1026 {number(size)}
1027 </option>
1028 ))}
1029 </select>
1030 </label>
1031 </div>
1032 </div>
1033 <CodeEditor
1034 value={text}
1035 path={activePath}
1036 readOnly={!editable}
1037 fontSize={fontSize}
1038 onChange={(value) => {
1039 setReviewSnapshot(null);
1040 setDrafts((current) => ({
1041 ...current,
1042 [activePath]: value
1043 }));
1044 setStatus('');
1045 }}
1046 />
1047 <div className="editor-status">
1048 <span>
1049 <span
1050 className={`status-dot ${dirtyPaths.includes(activePath) ? 'dirty' : 'saved'}`}
1051 />
1052 {dirtyPaths.includes(activePath)
1053 ? 'تغییرات ذخیره نشده'
1054 : 'ذخیره‌شده در فضای کاری'}
1055 </span>
1056 <span
1057 className={`count-limit${overLimit ? ' over-limit' : ''}`}
1058 >
1059 {number(bytes(text))} / {number(limits.maxBytes)} بایت ·{' '}
1060 {number(chars(text))} / {number(limits.maxChars)} نویسه
1061 </span>
1062 </div>
1063 </div>
1064 </div>
1065 {overLimit && (
1066 <div className="notice warning" role="alert">
1067 سقف مجاز فایل یا مجموع فضای کاری رد شده است. پیش از ذخیره،
1068 حجم متن را کم کن.
1069 </div>
1070 )}
1071 <div className="editor-actions">
1072 <button
1073 className="button primary"
1074 type="button"
1075 disabled={
1076 !editable || overLimit || !dirtyPaths.includes(activePath)
1077 }
1078 onClick={() => void saveFile()}
1079 >
1080 <Icon name="check" />
1081 ذخیره تغییرات
1082 </button>
1083 <button
1084 className="button secondary"
1085 type="button"
1086 disabled={
1087 !!busy ||
1088 !!conflict ||
1089 hasUnsaved ||
1090 !['DRAFT', 'READY'].includes(workspace.state)
1091 }
1092 onClick={() => void review()}
1093 >
1094 بازبینی تغییرات
1095 </button>
1096 <button
1097 className="button quiet"
1098 type="button"
1099 disabled={
1100 !!busy ||
1101 !!conflict ||
1102 !repository ||
1103 workspace.files.length >= limits.maxFiles ||
1104 workspace.state !== 'DRAFT'
1105 }
1106 onClick={() =>
1107 repository && void loadTree(repository, '', true)
1108 }
1109 >
1110 <Icon name="plus" />
1111 افزودن فایل
1112 </button>
1113 </div>
1114 <p className="field-help">
1115 {hasUnsaved
1116 ? 'هر فایل تغییرکرده را ذخیره کن تا Diff و درخواست تأیید در دسترس باشد.'
1117 : 'ذخیره، فقط پیش‌نویس فضای کاری را به‌روز می‌کند. ثبت در GitHub به تأیید جداگانه نیاز دارد.'}
1118 </p>
1119 <div className="screen-footer">
1120 <span>
1121 مجموع فضای کاری: {number(aggregateBytes)} /{' '}
1122 {number(limits.maxAggregateBytes)} بایت
1123 </span>
1124 <button
1125 className="button quiet small danger"
1126 type="button"
1127 disabled={!!busy}
1128 onClick={() =>
1129 setDiscardAction(() => () => void cancelWorkspace())
1130 }
1131 >
1132 لغو فضای کاری
1133 </button>
1134 </div>
1135 </section>
1136 )}
1137 {page === 'review' && workspace && diff && (
1138 <section>
1139 <button
1140 className="button quiet back-button"
1141 type="button"
1142 disabled={!!busy}
1143 onClick={() => setPage('editor')}
1144 >
1145 <Icon name="arrow" />
1146 بازگشت به ویرایشگر
1147 </button>
1148 {workspaceHeader}
1149 <div className="screen-heading">
1150 <p className="eyebrow">قبل از ثبت</p>
1151 <h2 className="screen-title">یک بار دیگر، با دقت.</h2>
1152 <p className="screen-description">
1153 فایل‌ها، تفاوت‌ها و پیام Commit را بررسی کن. تأیید نهایی در
1154 تلگرام انجام می‌شود.
1155 </p>
1156 </div>
1157 <div className="review-panel">
1158 <div className="review-summary">
1159 <div className="review-facts">
1160 <div className="review-fact">
1161 <span>مخزن</span>
1162 <strong dir="ltr">{workspace.repoFullName}</strong>
1163 </div>
1164 <div className="review-fact">
1165 <span>شاخه مبنا</span>
1166 <strong dir="ltr">{workspace.baseBranch}</strong>
1167 </div>
1168 <div className="review-fact">
1169 <span>شاخه جدید</span>
1170 <strong dir="ltr">nexa/edit-{workspace.id}</strong>
1171 </div>
1172 <div className="review-fact">
1173 <span>نسخه مبنا</span>
1174 <strong dir="ltr">
1175 {workspace.baseHeadSha.slice(0, 10)}
1176 </strong>
1177 </div>
1178 </div>
1179 <ul className="review-files">
1180 {workspace.files.map((file) => (
1181 <li key={file.path}>
1182 <Icon name="file" />
1183 <bdi>{file.path}</bdi>
1184 <span className="badge">ویرایش</span>
1185 </li>
1186 ))}
1187 </ul>
1188 </div>
1189 <div className="diff-toolbar">
1190 <strong>تفاوت تغییرات · Diff</strong>
1191 <span>
1192 <bdi>+{number(diff.additions)}</bdi> /{' '}
1193 <bdi>−{number(diff.deletions)}</bdi>
1194 </span>
1195 </div>
1196 <pre
1197 className="diff-view"
1198 dir="ltr"
1199 tabIndex={0}
1200 aria-label="تفاوت تغییرات"
1201 >
1202 {diff.text
1203 ? diff.text.split('\n').map((line, index) => (
1204 <span
1205 key={index}
1206 className={`diff-line ${line.startsWith('+++') || line.startsWith('---') || line.startsWith('@@') ? 'hunk' : line.startsWith('+') ? 'addition' : line.startsWith('-') ? 'deletion' : 'context'}`}
1207 >
1208 {line}
1209 {'\n'}
1210 </span>
1211 ))
1212 : 'تغییری برای ثبت وجود ندارد.'}
1213 </pre>
1214 </div>
1215 {!reviewSnapshot && (
1216 <div className="notice warning" role="alert">
1217 <p>
1218 تغییرات از زمان بازبینی عوض شده‌اند. آخرین نسخه را دریافت
1219 و Diff تازه را بررسی کن.
1220 </p>
1221 <button
1222 className="button secondary"
1223 type="button"
1224 disabled={!!busy}
1225 onClick={() => void review(true)}
1226 >
1227 بارگیری و بازبینی تازه
1228 </button>
1229 </div>
1230 )}
1231 {diff.truncated && (
1232 <div className="notice warning" role="alert">
1233 Diff کامل نیست. برای بازبینی امن، تغییرات را کوچک‌تر کن.
1234 </div>
1235 )}
1236 <label className="field">
1237 <span>پیام Commit</span>
1238 <input
1239 className="text-input"
1240 dir="auto"
1241 aria-label="پیام Commit"
1242 value={message}
1243 disabled={!!busy}
1244 autoComplete="off"
1245 placeholder="مثلاً: اصلاح عنوان صفحه اصلی"
1246 onChange={(event) => setMessage(event.target.value)}
1247 />
1248 <span className="field-help">
1249 در یک جمله توضیح بده چه چیزی تغییر کرده است. حداکثر ۱۲۰
1250 نویسه.
1251 </span>
1252 </label>
1253 {chars(message.trim()) > 120 && (
1254 <p className="notice warning" role="alert">
1255 پیام را به ۱۲۰ نویسه یا کمتر کوتاه کن.
1256 </p>
1257 )}
1258 <div className="sticky-actions">
1259 <button
1260 className="button primary"
1261 type="button"
1262 disabled={
1263 !!busy ||
1264 !message.trim() ||
1265 chars(message.trim()) > 120 ||
1266 !reviewSnapshot ||
1267 diff.truncated ||
1268 diff.additions + diff.deletions === 0
1269 }
1270 onClick={() => void requestApproval()}
1271 >
1272 <Icon name="lock" />
1273 درخواست تأیید امن
1274 </button>
1275 <span className="field-help">
1276 این دکمه درخواست تأیید می‌فرستد؛ Commit پس از تأیید تو در
1277 تلگرام ثبت می‌شود.
1278 </span>
1279 </div>
1280 </section>
1281 )}
1282 {page === 'approval' &&
1283 workspace &&
1284 (approval ||
1285 ['COMMITTED', 'COMMITTING'].includes(workspace.state)) && (
1286 <section className="approval-panel">
1287 <span className="brand-mark">
1288 <Icon
1289 name={workspace.state === 'COMMITTED' ? 'check' : 'lock'}
1290 />
1291 </span>
1292 <p className="eyebrow">
1293 {workspace.state === 'COMMITTED'
1294 ? 'نتیجه دریافت‌شده از سرور'
1295 : approval
1296 ? 'یک گام تا ثبت تغییرات'
1297 : 'وضعیت دریافت‌شده از سرور'}
1298 </p>
1299 <h1 className="screen-title">
1300 {workspace.state === 'COMMITTED'
1301 ? 'Commit ثبت شد'
1302 : approval
1303 ? 'درخواست تأیید به تلگرام فرستاده شد'
1304 : 'ثبت تغییرات در حال بررسی است'}
1305 </h1>
1306 <p className="screen-description">
1307 {workspace.state === 'COMMITTED'
1308 ? 'نتیجه فضای کاری تأیید می‌کند که تغییرات روی شاخه جدید ثبت شده‌اند.'
1309 : approval
1310 ? 'به گفت‌وگو با ربات برگرد و درخواست امضاشده را بررسی و تأیید کن. تا آن زمان، تغییری در GitHub ثبت نمی‌شود.'
1311 : 'نتیجه نهایی هنوز دریافت نشده است. وضعیت را دوباره از سرور بررسی کن.'}
1312 </p>
1313 <div className="approval-target">
1314 <strong dir="ltr">{workspace.repoFullName}</strong>
1315 <span dir="ltr">
1316 {workspace.result?.branch ||
1317 approval?.targetBranch ||
1318 `nexa/edit-${workspace.id}`}
1319 </span>
1320 {workspace.result?.commitSha && (
1321 <code>{workspace.result.commitSha.slice(0, 12)}</code>
1322 )}
1323 </div>
1324 {workspace.state === 'COMMITTED' &&
1325 workspace.result?.commitSha && (
1326 <a
1327 className="button primary result-link"
1328 href={`https://github.com/${workspace.repoFullName.split('/').map(encodeURIComponent).join('/')}/commit/${encodeURIComponent(workspace.result.commitSha)}`}
1329 target="_blank"
1330 rel="noopener noreferrer"
1331 >
1332 مشاهده Commit در GitHub
1333 </a>
1334 )}
1335 <div className="action-row">
1336 <button
1337 className="button primary close-action"
1338 type="button"
1339 disabled={!!busy}
1340 onClick={() => telegram?.close?.()}
1341 >
1342 بستن و رفتن به تلگرام
1343 </button>
1344 <button
1345 className="button secondary"
1346 type="button"
1347 disabled={!!busy}
1348 onClick={() => void refreshWorkspace()}
1349 >
1350 بررسی نتیجه
1351 </button>
1352 </div>
1353 {workspace.state !== 'COMMITTED' && (
1354 <button
1355 className="button quiet small danger"
1356 type="button"
1357 disabled={!!busy}
1358 onClick={() =>
1359 setDiscardAction(() => () => void cancelWorkspace())
1360 }
1361 >
1362 لغو فضای کاری
1363 </button>
1364 )}
1365 </section>
1366 )}
1367 </>
1368 )}
1369 </main>
1370 <footer className="app-footer">
1371 <span>Nexa Studio</span>
1372 <span>تغییر با اختیار تو.</span>
1373 </footer>
1374 {discardAction && (
1375 <div className="modal-backdrop">
1376 <section
1377 className="dialog"
1378 role="dialog"
1379 aria-modal="true"
1380 aria-labelledby="discard-title"
1381 aria-describedby="discard-description"
1382 >
1383 <h2 id="discard-title">ادامه می‌دهی؟</h2>
1384 <p id="discard-description">
1385 {hasUnsaved
1386 ? 'بخشی از تغییرات هنوز ذخیره نشده است. با ادامه، این تغییرات از ویرایشگر کنار گذاشته می‌شوند.'
1387 : 'با لغو فضای کاری، این پیش‌نویس دیگر قابل ادامه نیست.'}
1388 </p>
1389 <div className="dialog-actions">
1390 <button
1391 className="button secondary"
1392 type="button"
1393 autoFocus
1394 onClick={() => setDiscardAction(null)}
1395 >
1396 ادامه ویرایش
1397 </button>
1398 <button
1399 className="button danger"
1400 type="button"
1401 onClick={() => {
1402 const action = discardAction;
1403 setDiscardAction(null);
1404 action();
1405 }}
1406 >
1407 کنار گذاشتن و ادامه
1408 </button>
1409 </div>
1410 </section>
1411 </div>
1412 )}
1413 </div>
1414 );
1415 }