// Вкладка «Git»: изменения + diff, коммит, история с графом, ветки.import{Fragment}from'preact';import{ useEffect, useMemo, useRef, useState, useCallback }from'preact/hooks';import{
html, rpc, act, toast, useRes, invalidate, mutateRes, peekRes, humanError, svc, saveSettings, saveUi, relTime, fmtDateTime,
copyText, shortId, plural, initials, colorFor,STATUS_LABEL,}from'./core.js';import{Icon}from
text
rows
a
b
line text
line
m line
rows m m line
line
m line
m a m b m
rows line
line
rows line
line
rows b line
line
rows a line
line
rows line
rows
rows a b line line line
rows rowsrows rowsrows rows
rows
rows diff diff
diff rows html
shown rows maxRows
html
i p
i p pi p i
st app svc
stworkspace stidecwd
r err method params okMsg
r err
open setOpen
custom setCustom
ref
st svc
recent st stcwd st
label dir dir
html
name dir path
letter group group status
html
open setOpen initOpen
count
html
open setOpen
q setQ
ref
tasks boardtasks t q tq tq
html
msg setMsg svcuicommitDraft
amend setAmend
busy setBusy
ta
subject msg
staged gitlength
can busy msg staged amend
t msg t msg
msg ta
staged amend
r err dir msg amend push
err
html push rpushed
tag t
el ta
msg
pos elselectionEnd msg
next msg pos msgpos msgpos msgpos tag msgpos
next
el
html
sel setSel
diff sel dir sel sel
gitKey g g
set files
moved g setx g setp p
g g setx g setp g setx moved
dir files
set files
moved g setx
g g setx g moved x g moved x x
dir files
files untracked
dir files
sel filessel
dir
total gitlength gitlength gitlength gitlength
html
refs
list refs refs refs x
out
r list
r out out r
r out
r out r
r out r
out r
out
pages setPages
items setItems
more setMore
loadingMore setLoadingMore
open setOpen
sentinel
first dir
first first first first
loadMore
loadingMore more items
next dir items
x next x y c
next
e e
items more loadingMore dir
el sentinel
el
io e el
ioel
io
loadMore
items html
items html
html
div ref$sentinel stylediv
$loadingMore html more html
$ dir$dir hash$open onClose$
div$dir$h$ open$hash onClose$onClose wide label
title$html
headExtra$html
$c html html
map
s mapch ch
br dir
creating setCreating
name setName
taskId setTaskId
tasks boardtasks t
taskId
t tasks x taskId
t
taskId
dirty gitlength gitlength
dirty
dir b
n name
n
err dir n
err
html html
$br html html
div$dir Опубликовать ветку $gitbranchdiv style
div
div $ dir$gitcwd dir onPick$pick div
$gitisRepo html
div
$git g html
html
git html
sub html
sub html
html
div`
`<div><divclass="git-sec-h"><buttontype="button"class="collapse-btn"aria-expanded=${String(open)}onClick=${()=>setOpen((o)=>!o)}style="font-weight:600"><spanstyle=${{display:'grid',transform: open ?'none':'rotate(-90deg)',transition:'transform .2s cubic-bezier(.22,1,.36,1)'}}><${Icon}name="chevron"size=${13}/></span>${title}</button><spanclass="badge">${count}</span><spanclass="grow"></span>${actions}</div>${open ? children :null}</div>`
;
}
function
TaskLinkPicker
(
{ board, onPick }
)
{
const
[
,
]
=
useState
(
false
)
;
const
[
,
]
=
useState
(
''
)
;
const
=
useRef
(
null
)
;
const
=
(
.
data
?.
??
[
]
)
.
filter
(
(
t
)
=>
.
status
!==
'done'
&&
(
!
||
.
title
.
toLowerCase
(
)
.
includes
(
.
toLowerCase
(
)
)
||
shortId
(
.
id
)
.
startsWith
(
.
replace
(
'#'
,
''
)
)
)
)
;
return
`<${Fragment}><buttontype="button"class="btn sm"ref=${ref}onClick=${()=>setOpen((o)=>!o)}aria-haspopup="menu"aria-expanded=${String(open)}><${Icon}name="hash"size=${13}/>Привязать задачу</button>${open ? html`<${Popover} anchor=${ref.current} onClose=${()=>setOpen(false)} width=${300}><div style="padding:4px"><input class="inp sm" value=${q} placeholder="Найти задачу…" aria-label="Поиск задачи" onInput=${(e)=>setQ(e.currentTarget.value)}/div
div style
$tasks html${!tasks.length? html`<divclass="mi faint"style="cursor:default">${board.data?'Ничего не найдено':'Команда не выбрана'}</div>`:null}</div>
<//>`
:
null
}
<
//>`;
}
function
CommitBox
(
{ dir, git, board }
)
{
const
[
,
]
=
useState
(
.
state
?.
?.
||
''
)
;
const
[
,
]
=
useState
(
false
)
;
const
[
,
]
=
useState
(
false
)
;
const
=
useRef
(
null
)
;
const
=
.
split
(
'\n'
)
[
0
]
;
const
=
.
staged
?.
||
0
;
const
=
!
&&
.
trim
(
)
&&
(
>
0
||
)
;
useEffect
(
(
)
=>
{
const
=
setTimeout
(
(
)
=>
saveUi
(
{
commitDraft
:
}
)
,
500
)
;
return
(
)
=>
clearTimeout
(
)
;
}
,
[
]
)
;
const
commit
=
async
(
push
)
=>
{
if
(
!
.
trim
(
)
)
{
toast
(
'Введите сообщение коммита'
,
{
kind
:
'err'
}
)
;
.
current
?.
focus
(
)
;
return
;
}
if
(
!
&&
!
)
{
toast
(
'Нет подготовленных изменений'
,
{
kind
:
'err'
}
)
;
return
;
}
setBusy
(
true
)
;
const
[
,
]
=
await
act
(
'gitCommit'
,
{
,
message
:
.
trim
(
)
,
amend
:
||
undefined
,
push
:
||
undefined
}
)
;
setBusy
(
false
)
;
invalidate
(
'git'
,
'gitLog'
,
'gitBranches'
)
;
if
(
)
return
;
setMsg
(
''
)
;
setAmend
(
false
)
;
saveUi
(
{
commitDraft
:
''
}
)
;
toast
(
`Коммит <spanclass="mono">${String(r?.hash ||'').slice(0,7)}</span>${push ?(r?.pushed ?'создан и отправлен':'создан, push не удался'):'создан'}`
,
{
kind
:
&&
!
?.
?
'err'
:
'ok'
}
)
;
}
;
const
insertTask
=
(
t
)
=>
{
const
=
'#'
+
shortId
(
.
id
)
;
const
=
.
current
;
if
(
!
.
trim
(
)
)
{
setMsg
(
`${t.title}${tag}`
)
;
return
;
}
const
=
?.
??
.
length
;
const
=
.
slice
(
0
,
)
+
(
[
-
1
]
&&
[
-
1
]
!==
' '
&&
[
-
1
]
!==
'\n'
?
' '
:
''
)
+
+
.
slice
(
)
;
setMsg
(
)
;
requestAnimationFrame
(
(
)
=>
?.
focus
(
)
)
;
}
;
return
`<divclass="commit-box"><divstyle="position:relative"><textarearef=${ta}class="ta"value=${msg}placeholder=${staged ?`Сообщение коммита (${staged}${plural(staged,'файл','файла','файлов')}) · Ctrl+Enter`:'Сообщение коммита · Ctrl+Enter'}aria-label="Сообщение коммита"onInput=${(e)=>setMsg(e.currentTarget.value)}onKeyDown=${(e)=>{if(e.key==='Enter'&&(e.ctrlKey|| e.metaKey)){ e.preventDefault();commit(false);}}}></textarea><spanclass=${'cnt72'+(subject.length>72?' over':'')}style="position:absolute;right:8px;bottom:6px"title="Длина первой строки">${subject.length}/72</span></div><divclass="row wrap"style="gap:6px"><${TaskLinkPicker}board=${board}onPick=${insertTask}/><labelclass="chk-row small muted"><inputtype="checkbox"class="chk"checked=${amend}onChange=${(e)=>setAmend(e.currentTarget.checked)}/>Amend</label></div><divclass="row"style="gap:6px;justify-content:flex-end"><buttontype="button"class="btn"disabled=${!can}onClick=${()=>commit(true)}><${Icon}name="arrow-up-line"size=${13}/>Коммит и Push</button><buttontype="button"class="btn primary"disabled=${!can}onClick=${()=>commit(false)}>${busy ? html`<spanclass="spin"></span>`: html`<${Icon}name="check"size=${14}/>`}Коммит</button></div></div>`
;
}
function
ChangesView
(
{ dir, gitKey, git, board, readOnly }
)
{
const
[
,
]
=
useState
(
null
)
;
// {path, staged}
const
=
useRes
(
?
`gitDiff:${dir}:${sel.path}:${sel.staged?1:0}`
:
null
,
(
)
=>
rpc
(
'gitDiff'
,
{
,
file
:
.
path
,
staged
:
.
staged
||
undefined
}
)
)
;
const
optimistic
=
(
fn
)
=>
mutateRes
(
,
(
g
)
=>
&&
fn
(
)
)
;
const
stage
=
async
(
files
)
=>
{
optimistic
(
(
g
)
=>
{
const
=
new
Set
(
)
;
const
=
[
...
.
unstaged
.
filter
(
(
x
)
=>
.
has
(
.
path
)
)
,
...
.
untracked
.
filter
(
(
p
)
=>
.
has
(
)
)
.
map
(
(
p
)
=>
(
{
path
:
,
status
:
'A'
}
)
)
]
;
return
{
...
,
unstaged
:
.
unstaged
.
filter
(
(
x
)
=>
!
.
has
(
.
path
)
)
,
untracked
:
.
untracked
.
filter
(
(
p
)
=>
!
.
has
(
)
)
,
staged
:
[
...
.
staged
.
filter
(
(
x
)
=>
!
.
has
(
.
path
)
)
,
...
]
}
;
}
)
;
await
gitAct
(
'gitStage'
,
{
,
}
)
;
}
;
const
unstage
=
async
(
files
)
=>
{
optimistic
(
(
g
)
=>
{
const
=
new
Set
(
)
;
const
=
.
staged
.
filter
(
(
x
)
=>
.
has
(
.
path
)
)
;
return
{
...
,
staged
:
.
staged
.
filter
(
(
x
)
=>
!
.
has
(
.
path
)
)
,
unstaged
:
[
...
.
unstaged
,
...
.
filter
(
(
x
)
=>
.
status
!==
'A'
)
]
,
untracked
:
[
...
.
untracked
,
...
.
filter
(
(
x
)
=>
.
status
===
'A'
)
.
map
(
(
x
)
=>
.
path
)
]
}
;
}
)
;
await
gitAct
(
'gitUnstage'
,
{
,
}
)
;
}
;
const
discard
=
async
(
files, untracked
)
=>
{
if
(
!
(
await
confirmDialog
(
{
title
:
.
length
===
1
?
`Отменить изменения в ${splitPath(files[0]).name}?`
:
`Отменить изменения в ${files.length}${plural(files.length,'файле','файлах','файлах')}?`
,
text
:
?
'Новые файлы будут удалены с диска. Это нельзя отменить.'
:
'Несохранённые в коммите правки будут потеряны. Это нельзя отменить.'
,
ok
:
'Отменить изменения'
}
)
)
)
return
;
await
gitAct
(
'gitDiscard'
,
{
,
}
,
'Изменения отменены'
)
;
if
(
&&
.
includes
(
.
path
)
)
setSel
(
null
)
;
}
;
const
stageAll
=
(
)
=>
gitAct
(
'gitStageAll'
,
{
}
)
;
const
=
(
.
staged
?.
||
0
)
+
(
.
unstaged
?.
||
0
)
+
(
.
untracked
?.
||
0
)
+
(
.
conflicts
?.
||
0
)
;
return
`<divstyle="display:flex;flex-direction:column;min-height:100%"><divclass="grow"style="padding:4px08px">${!total ? html`<${Empty}icon="check"title="Рабочее дерево чистое"text="Изменений нет — можно переключать ветки и тянуть обновления."/>`:null}<${GitSection}title="Конфликты"count=${git.conflicts?.length}>${git.conflicts?.map((p)=> html`<${FileRowGit}key=${'c'+ p}path=${p}group="conflicts"readOnly=${readOnly}selected=${sel?.path === p}
<//>
<${GitSection}title="Подготовлено"count=${git.staged?.length}actions=${readOnly ?null: html`<buttontype="button"class="ibtn sm"title="Убрать всё"aria-label="Убрать все из подготовленных"onClick${git.staged?.map((f)=> html`<${FileRowGit}key=${'s'+ f.path}path=${f.path}status=${f.status}group="staged"readOnly=readOnly
<//>
<${GitSection}title="Изменено"count=${git.unstaged?.length}actions=${readOnly ?null: html`<buttontype="button"class="ibtn sm danger"title="Отменить все"aria-label="Отменить все изменения"onClick${git.unstaged?.map((f)=> html`<${FileRowGit}key=${'u'+ f.path}path=${f.path}status=${f.status}group="unstaged"readOnly=readOnly
<//>
<${GitSection}title="Новые"count=${git.untracked?.length}actions=${readOnly ?null: html`<buttontype="button"class="ibtn sm"title="Подготовить все"aria-label="Подготовить все новые"onClick${git.untracked?.map((p)=> html`<${FileRowGit}key=${'n'+ p}path=${p}group="untracked"readOnly=${readOnly}selected=${sel?.path === p}
<//>
${total &&!readOnly &&(git.unstaged?.length || git.untracked?.length)? html`<divstyle="padding:8px12px"><${AsyncButton}class="btn sm"onClick=${stageAll}><Подготовить всё<//></div><${CommitBox}dir=${dir}git=${git}board=${board}/><${Layer}open=${!!sel}onClose=${()=>setSel(null)}widetitle=${sel ? html`<spanclass="row"style="gap:6px">${diff.loading&&!diff.data? html`<divclass="stack-s">${[80,60,90,40,70].map((w, i)=> html`<${Skel}key=${i}
html
<//>
</div>`
;
}
// ---------------------------------------------------------------- история
`В рабочем дереве ${dirty}${plural(dirty,'изменённый файл','изменённых файла','изменённых файлов')}. Git может отказать, если они конфликтуют.`
,
ok
:
'Переключить'
,
danger
:
false
}
)
)
)
return
;
await
gitAct
(
'gitCheckout'
,
{
,
branch
:
.
name
}
,
`Ветка ${b.name}`
)
;
}
;
const
create
=
async
(
)
=>
{
const
=
.
trim
(
)
;
if
(
!
)
return
;
const
[
,
]
=
await
gitAct
(
'gitCheckout'
,
{
,
branch
:
,
create
:
true
}
,
`Создана ветка ${n}`
)
;
if
(
!
)
{
setCreating
(
false
)
;
setName
(
''
)
;
setTaskId
(
''
)
;
}
}
;
return
`<divclass="pad stack-s">${readOnly ?null: creating ? html`<div class="card pad stack-s reveal"><${Field} label="Из задачи (необязательно)"><${Select} sm value=${taskId} label="Задача" onChange=${setTaskId}
options=${[{id:'',label:'— без задачи —'},...tasks.map((t)=>({id: t.id,label:`#${shortId(t.id)}${t.title}`}))]} /><//>
<${Field}label="Имя ветки"><inputclass="inp sm mono"value=${name}placeholder="feat/…"data-autofocusref=${(el)=> el &&!name &&requestAnimationFrame(()=> el.focus())}onInput=${(e)=>setName(e.currentTarget.<//>
<divclass="row"style="justify-content:flex-end"><buttontype="button"class="btn"onClick=${()=>setCreating(false)}>Отмена</button><${AsyncButton}class="btn primary"onClick=${create}disabled=${!name.trim()}>Создать и переключиться<//></div></div>`
`<divclass="pad stack"style="padding-top:24px"><${Empty}icon="git-branch"title="Здесь нет git-репозитория"text=${(git.cwd|| dir ||'Папка не выбрана')+' — выберите другую папку выше или откройте проект в ZCode.'}/></div>`