@celljs/ta-workspace 0.0.0-stage → 4.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,388 @@
1
+ import { Action, copyText, Empty, Glyph, type MenuItem, Section, useContextMenu, ViewHeader } from './common';
2
+ import { openDiff, openFile } from './editors';
3
+ import { RevealRequests } from './explorer';
4
+ import { FileIcon } from './file-icon';
5
+ import { FilesChanged, Host, MAC, PACKAGE, pi, useFilesChanged, useLoad } from './host';
6
+ import { gitLabel, t } from './i18n';
7
+ import { React } from './react';
8
+ import { type GitStatus, GitUtil } from './util/git';
9
+ import { type GitGroup, type GitRow, WorkspaceUtil } from './util/workspace';
10
+ import { WorkspaceClient } from './workspace-client';
11
+
12
+ const REFRESH_MS = 10000;
13
+ const GROUPS: GitGroup[] = ['merge', 'staged', 'changes'];
14
+
15
+ /** What is typed for the next commit, by directory, while the view comes and goes. */
16
+ const messages = new Map<string, string>();
17
+
18
+ /** The changes of git in the conversation's directory, as source control in an IDE: stage, unstage, discard, commit, pull and push. */
19
+ export function ScmView() {
20
+ const cwd = pi.ui.useCwd();
21
+ const changed = useFilesChanged();
22
+ const status = useLoad<GitStatus>(() => WorkspaceClient.status(cwd), [cwd, changed]);
23
+ const { reload } = status;
24
+ const [message, setMessageState] = React.useState(() => messages.get(cwd) ?? '');
25
+ const [busy, setBusy] = React.useState<string>();
26
+ const [closed, setClosed] = React.useState<GitGroup[]>([]);
27
+ const [tree, setTree] = React.useState(false);
28
+ const [menu, openMenu] = useContextMenu();
29
+ const box = React.useRef<HTMLTextAreaElement>(null);
30
+ React.useEffect(() => setMessageState(messages.get(cwd) ?? ''), [cwd]);
31
+ const setMessage = (value: string) => {
32
+ messages.set(cwd, value);
33
+ setMessageState(value);
34
+ };
35
+ React.useEffect(() => {
36
+ const timer = setInterval(() => document.visibilityState === 'visible' && reload(), REFRESH_MS);
37
+ return () => clearInterval(timer);
38
+ }, [reload]);
39
+ // The box grows with the message, as the one of an IDE, up to a few lines.
40
+ React.useLayoutEffect(() => {
41
+ const element = box.current;
42
+ if (element) {
43
+ element.style.height = 'auto';
44
+ element.style.height = `${Math.min(element.scrollHeight, 200)}px`;
45
+ }
46
+ }, [message]);
47
+
48
+ const value = status.value;
49
+ const rows = React.useMemo(() => (value ? WorkspaceUtil.gitRows(value) : []), [value]);
50
+ const groups = GROUPS.map(group => [group, rows.filter(row => row.group === group)] as const);
51
+ const staged = rows.filter(row => row.group === 'staged');
52
+ const initial = !!value?.initial;
53
+
54
+ /** Runs git, then reads the status again; a failure is a notice. */
55
+ const run = async (label: string, work: () => Promise<unknown>) => {
56
+ setBusy(label);
57
+ try {
58
+ await work();
59
+ } catch (error) {
60
+ pi.ui.notify(Host.message(error), 'error');
61
+ } finally {
62
+ setBusy(undefined);
63
+ FilesChanged.notify();
64
+ reload();
65
+ }
66
+ };
67
+
68
+ const stage = (paths: string[]) => run('stage', () => WorkspaceClient.git(cwd, GitUtil.stage(paths)));
69
+ const unstage = (paths: string[]) => run('unstage', () => WorkspaceClient.git(cwd, GitUtil.unstage(paths, initial)));
70
+
71
+ /** Back to the index for tracked files; untracked ones are deleted, which says so. */
72
+ const discard = async (list: GitRow[]) => {
73
+ const untracked = list.filter(row => row.file.unstaged === '?').map(row => row.file.path);
74
+ const tracked = list.filter(row => row.file.unstaged !== '?').map(row => row.file.path);
75
+ const single = list.length === 1 ? WorkspaceUtil.basename(list[0].file.path) : undefined;
76
+ const title =
77
+ untracked.length && !tracked.length
78
+ ? single
79
+ ? t('deleteUntracked', { name: single })
80
+ : t('deleteUntrackedMany', { count: untracked.length })
81
+ : single
82
+ ? t('discardOne', { name: single })
83
+ : t('discardMany', { count: list.length });
84
+ const confirmed = await pi.ui.confirm(title, t('irreversible'), {
85
+ confirmLabel: untracked.length && !tracked.length ? t('delete') : t('discard'),
86
+ danger: true,
87
+ });
88
+ if (confirmed) {
89
+ await run('discard', async () => {
90
+ if (tracked.length) {
91
+ await WorkspaceClient.git(cwd, GitUtil.discard(tracked));
92
+ }
93
+ if (untracked.length) {
94
+ await WorkspaceClient.git(cwd, GitUtil.clean(untracked));
95
+ }
96
+ });
97
+ }
98
+ };
99
+
100
+ const commit = async () => {
101
+ if (!message.trim()) {
102
+ box.current?.focus();
103
+ pi.ui.notify(t('commitMessageMissing'), 'warning');
104
+ return;
105
+ }
106
+ // As VS Code with nothing staged: commit all the changes (after asking once).
107
+ if (staged.length === 0) {
108
+ if (rows.length === 0) {
109
+ pi.ui.notify(t('nothingToCommit'), 'info');
110
+ return;
111
+ }
112
+ const confirmed = await pi.ui.confirm(t('stageAllTitle'), t('stageAllMessage'), { confirmLabel: t('stageAllCommit') });
113
+ if (!confirmed) {
114
+ return;
115
+ }
116
+ }
117
+ await run('commit', async () => {
118
+ if (staged.length === 0) {
119
+ await WorkspaceClient.git(cwd, GitUtil.stage(['.']));
120
+ }
121
+ await WorkspaceClient.commit(cwd, message);
122
+ setMessage('');
123
+ });
124
+ };
125
+
126
+ const remote = (command: 'pull' | 'push' | 'fetch') =>
127
+ run(command, async () => {
128
+ await WorkspaceClient.remote(cwd, command);
129
+ pi.ui.notify(t(`${command}Done`));
130
+ });
131
+
132
+ const open = (row: GitRow, pin: boolean) => {
133
+ if (row.letter === 'D' && row.group === 'changes') {
134
+ openDiff(cwd, row.file.path, false, { preview: !pin });
135
+ } else {
136
+ openDiff(cwd, row.file.path, row.group === 'staged', { preview: !pin });
137
+ }
138
+ };
139
+
140
+ const reveal = (path: string) => {
141
+ RevealRequests.send({ cwd, path });
142
+ pi.ui.showView(`${PACKAGE}/explorer`);
143
+ };
144
+
145
+ const rowMenu = (row: GitRow): MenuItem[] => [
146
+ { label: t('openChanges'), run: () => open(row, true) },
147
+ ...(row.letter !== 'D' ? [{ label: t('openFile'), run: () => openFile(cwd, row.file.path) }] : []),
148
+ '-',
149
+ ...(row.group === 'staged'
150
+ ? [{ label: t('unstage'), run: () => void unstage([row.file.path]) }]
151
+ : [
152
+ { label: t('stage'), run: () => void stage([row.file.path]) },
153
+ ...(row.group === 'changes' ? [{ label: t(row.letter === 'U' ? 'delete' : 'discard'), run: () => void discard([row]) }] : []),
154
+ ]),
155
+ '-',
156
+ ...(row.letter !== 'D' ? [{ label: t('revealInExplorer'), run: () => reveal(row.file.path) }] : []),
157
+ { label: t('copyRelativePath'), run: () => copyText(row.file.path, t('copied')) },
158
+ ];
159
+
160
+ const commitKeys = MAC ? '⌘↵' : 'Ctrl+Enter';
161
+ const branch = value?.branch;
162
+ const placeholder = branch ? t('commitPlaceholderBranch', { keys: commitKeys, branch }) : t('commitPlaceholder', { keys: commitKeys });
163
+
164
+ return (
165
+ <div className="taw-view">
166
+ <ViewHeader
167
+ title={
168
+ <span className="taw-scm-title">
169
+ <span>{WorkspaceUtil.basename(cwd) || t('scm')}</span>
170
+ {branch && (
171
+ <span className="taw-branch-title">
172
+ <Glyph name="GitBranch" size={12} />
173
+ {branch}
174
+ {!!value?.ahead && <span className="taw-sync">{value.ahead}↑</span>}
175
+ {!!value?.behind && <span className="taw-sync">{value.behind}↓</span>}
176
+ </span>
177
+ )}
178
+ </span>
179
+ }
180
+ hint={[cwd, branch, value?.ahead || value?.behind ? t('aheadBehind', { ahead: value.ahead ?? 0, behind: value.behind ?? 0 }) : '']
181
+ .filter(Boolean)
182
+ .join(' · ')}
183
+ >
184
+ {value?.repository && (
185
+ <React.Fragment>
186
+ <Action icon={tree ? 'List' : 'ListTree'} label={t(tree ? 'viewAsList' : 'viewAsTree')} onClick={() => setTree(!tree)} />
187
+ <Action icon="ArrowDown" label={t('pull')} disabled={!!busy} onClick={() => void remote('pull')} />
188
+ <Action icon="ArrowUp" label={t('push')} disabled={!!busy} onClick={() => void remote('push')} />
189
+ </React.Fragment>
190
+ )}
191
+ <Action icon="RefreshCw" label={t('refresh')} onClick={reload} />
192
+ {value?.repository && (
193
+ <Action
194
+ icon="Ellipsis"
195
+ label={t('moreActions')}
196
+ onClick={event =>
197
+ openMenu(event, [
198
+ { label: t('pull'), run: () => void remote('pull') },
199
+ { label: t('push'), run: () => void remote('push') },
200
+ { label: t('fetch'), run: () => void remote('fetch') },
201
+ '-',
202
+ { label: t('stageAll'), run: () => void stage(['.']), disabled: rows.every(row => row.group === 'staged') },
203
+ { label: t('unstageAll'), run: () => void unstage(staged.map(row => row.file.path)), disabled: staged.length === 0 },
204
+ {
205
+ label: t('discardAll'),
206
+ run: () => void discard(rows.filter(row => row.group === 'changes')),
207
+ disabled: !rows.some(row => row.group === 'changes'),
208
+ },
209
+ ])
210
+ }
211
+ />
212
+ )}
213
+ </ViewHeader>
214
+ {busy && <div className="taw-progress-bar" role="progressbar" aria-label={t('loading')} />}
215
+ {value?.repository && (
216
+ <div className="taw-commit">
217
+ <textarea
218
+ ref={box}
219
+ rows={1}
220
+ className="taw-input taw-commit-input"
221
+ value={message}
222
+ placeholder={placeholder}
223
+ aria-label={t('commitMessage')}
224
+ spellCheck={false}
225
+ onChange={event => setMessage(event.target.value)}
226
+ onKeyDown={event => {
227
+ if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {
228
+ event.preventDefault();
229
+ void commit();
230
+ }
231
+ }}
232
+ />
233
+ <button
234
+ type="button"
235
+ className={`taw-button taw-commit-button ${message.trim() ? 'taw-ready' : ''}`}
236
+ disabled={!!busy}
237
+ onClick={() => void commit()}
238
+ >
239
+ <Glyph name="Check" size={14} />
240
+ {t('commit')}
241
+ </button>
242
+ </div>
243
+ )}
244
+ <div className="taw-list taw-scm-list">
245
+ {status.error && <Empty tone="error">{t('failed', { message: status.error })}</Empty>}
246
+ {!status.error && !value && <Empty>{t('loading')}</Empty>}
247
+ {value && !value.repository && <Empty>{t('notRepository')}</Empty>}
248
+ {value?.repository && rows.length === 0 && <Empty>{t('noChanges')}</Empty>}
249
+ {groups.map(([group, list]) => {
250
+ if (list.length === 0) {
251
+ return null;
252
+ }
253
+ const expanded = !closed.includes(group);
254
+ const paths = list.map(row => row.file.path);
255
+ const actions =
256
+ group === 'staged' ? (
257
+ <Action icon="Minus" label={t('unstageAll')} onClick={() => void unstage(paths)} />
258
+ ) : (
259
+ <React.Fragment>
260
+ {group === 'changes' && <Action icon="Undo2" label={t('discardAll')} onClick={() => void discard(list)} />}
261
+ <Action icon="Plus" label={t('stageAll')} onClick={() => void stage(paths)} />
262
+ </React.Fragment>
263
+ );
264
+ return (
265
+ <Section
266
+ key={group}
267
+ title={t(group === 'merge' ? 'mergeChanges' : group)}
268
+ count={list.length}
269
+ open={expanded}
270
+ onToggle={() => setClosed(expanded ? [...closed, group] : closed.filter(other => other !== group))}
271
+ actions={actions}
272
+ >
273
+ {(tree ? treeRows(list) : list.map(row => ({ row, depth: 0 }))).map(item =>
274
+ 'folder' in item ? (
275
+ <div key={`${group}:dir:${item.folder}`} className="taw-row taw-scm-row" style={{ paddingLeft: 20 + item.depth * 12 }}>
276
+ <Glyph name="Folder" />
277
+ <span className="taw-name">{WorkspaceUtil.basename(item.folder)}</span>
278
+ </div>
279
+ ) : (
280
+ <ScmRow
281
+ key={`${group}:${item.row.file.path}`}
282
+ row={item.row}
283
+ depth={item.depth}
284
+ tree={tree}
285
+ onOpen={pin => open(item.row, pin)}
286
+ onMenu={event => openMenu(event, rowMenu(item.row))}
287
+ actions={
288
+ <React.Fragment>
289
+ {item.row.letter !== 'D' && (
290
+ <Action icon="File" label={t('openFile')} onClick={() => openFile(cwd, item.row.file.path)} />
291
+ )}
292
+ {item.row.group === 'changes' && (
293
+ <Action
294
+ icon="Undo2"
295
+ label={t(item.row.letter === 'U' ? 'delete' : 'discard')}
296
+ onClick={() => void discard([item.row])}
297
+ />
298
+ )}
299
+ {item.row.group === 'staged' ? (
300
+ <Action icon="Minus" label={t('unstage')} onClick={() => void unstage([item.row.file.path])} />
301
+ ) : (
302
+ <Action icon="Plus" label={t('stage')} onClick={() => void stage([item.row.file.path])} />
303
+ )}
304
+ </React.Fragment>
305
+ }
306
+ />
307
+ ),
308
+ )}
309
+ </Section>
310
+ );
311
+ })}
312
+ </div>
313
+ {menu}
314
+ </div>
315
+ );
316
+ }
317
+
318
+ /** The rows of a group as a tree: each folder once, before its files. */
319
+ function treeRows(list: readonly GitRow[]): ({ row: GitRow; depth: number } | { folder: string; depth: number })[] {
320
+ const out: ({ row: GitRow; depth: number } | { folder: string; depth: number })[] = [];
321
+ const seen = new Set<string>();
322
+ const sorted = [...list].sort((a, b) => {
323
+ const [da, db] = [WorkspaceUtil.dirname(a.file.path), WorkspaceUtil.dirname(b.file.path)];
324
+ return da === db ? WorkspaceUtil.compareNames(a.file.path, b.file.path) : WorkspaceUtil.compareNames(da, db);
325
+ });
326
+ for (const row of sorted) {
327
+ const parts = row.file.path.split('/');
328
+ for (let depth = 0; depth < parts.length - 1; depth++) {
329
+ const folder = parts.slice(0, depth + 1).join('/');
330
+ if (!seen.has(folder)) {
331
+ seen.add(folder);
332
+ out.push({ folder, depth });
333
+ }
334
+ }
335
+ out.push({ row, depth: parts.length - 1 });
336
+ }
337
+ return out;
338
+ }
339
+
340
+ function ScmRow({
341
+ row,
342
+ depth,
343
+ tree,
344
+ onOpen,
345
+ onMenu,
346
+ actions,
347
+ }: {
348
+ row: GitRow;
349
+ depth: number;
350
+ tree: boolean;
351
+ onOpen(pin: boolean): void;
352
+ onMenu(event: React.MouseEvent | React.KeyboardEvent): void;
353
+ actions: React.ReactNode;
354
+ }) {
355
+ const color = WorkspaceUtil.gitColor(row.letter);
356
+ const path = row.file.path;
357
+ const from = row.file.from && row.group === 'staged' ? row.file.from : undefined;
358
+ return (
359
+ <div
360
+ role="treeitem"
361
+ tabIndex={0}
362
+ className={`taw-row taw-scm-row ${row.letter === 'D' ? 'taw-deleted' : ''}`}
363
+ style={{ paddingLeft: 20 + depth * 12 }}
364
+ title={`${from ? `${from} → ` : ''}${path} • ${gitLabel(row.letter)}`}
365
+ onClick={() => onOpen(false)}
366
+ onDoubleClick={() => onOpen(true)}
367
+ onKeyDown={event => {
368
+ if (event.key === 'Enter') {
369
+ onOpen(true);
370
+ } else if (event.key === 'ContextMenu' || (event.key === 'F10' && event.shiftKey)) {
371
+ onMenu(event);
372
+ }
373
+ }}
374
+ onContextMenu={onMenu}
375
+ >
376
+ <FileIcon path={path} />
377
+ <span className="taw-name" style={{ color }}>
378
+ {WorkspaceUtil.basename(path)}
379
+ </span>
380
+ {!tree && <span className="taw-detail">{from ? `${from} → ${WorkspaceUtil.dirname(path)}` : WorkspaceUtil.dirname(path)}</span>}
381
+ {tree && <span className="taw-detail" />}
382
+ <span className="taw-row-actions">{actions}</span>
383
+ <span className="taw-letter" style={{ color }}>
384
+ {row.letter}
385
+ </span>
386
+ </div>
387
+ );
388
+ }