1 Commits
Author SHA1 Message Date
Anya Tokugawa 96065d1e89 fix(revisions): connect safe restore UI and readable change history
Release container images / release (push) Successful in 19s
Build and publish container images / images (push) Successful in 9m28s
2026-11-10 11:34:28 +09:00
11 changed files with 166 additions and 96 deletions

No files matched your search

+4
View File
@@ -330,6 +330,8 @@ var translations = map[string]map[string]string{
"viewer.metadata_unavailable": "The metadata queue is unavailable. Download is still available.",
"viewer.archive_truncated": "The listing limit was reached. Download the archive for the complete contents.",
"history.title": "Revision History",
"history.message": "Change message",
"history.message_optional": "Optional summary of changes",
"history.older": "Older revisions",
"history.newest": "Newest revisions",
"history.view": "View",
@@ -1120,6 +1122,8 @@ var translations = map[string]map[string]string{
"viewer.metadata_unavailable": "メタデータの待ち行列を利用できません。ダウンロードは利用できます。",
"viewer.archive_truncated": "表示件数の上限に達しました。全内容はダウンロードして確認してください。",
"history.title": "リビジョン履歴",
"history.message": "更新メッセージ",
"history.message_optional": "変更内容(任意)",
"history.older": "以前のリビジョン",
"history.newest": "最新のリビジョン",
"history.view": "表示",
+20 -6
View File
@@ -50,6 +50,18 @@ func (s *Server) handleRevisionBrowser(
}
next := ""
heads := map[string]string{}
canRestore := s.authorizeObjectForRequest(r, "write", objectUUID) == nil
if canRestore {
for _, revision := range page.Items {
if _, ok := heads[revision.Language]; ok {
continue
}
if head, e := s.store.GetRevisionMetadataForExactLanguage(objectUUID, revision.Language); e == nil {
heads[revision.Language] = head.UUID
}
}
}
if page.Next != "" {
next = revisionPageURL(r, page.Next)
}
@@ -62,12 +74,14 @@ func (s *Server) handleRevisionBrowser(
s.getSystemNavItems(s.domainUUIDForRequest(r)),
NavContext{},
),
"Title": "Revision History",
"ObjectUUID": objectUUID,
"Revisions": page.Items,
"NextURL": next,
"NewestURL": revisionPageURL(r, ""),
"HasPrevious": before != "",
"Title": "Revision History",
"ObjectUUID": objectUUID,
"CanRestore": canRestore,
"RevisionHeads": heads,
"Revisions": page.Items,
"NextURL": next,
"NewestURL": revisionPageURL(r, ""),
"HasPrevious": before != "",
},
)
}
+39 -41
View File
@@ -1,63 +1,61 @@
package server
import (
"errors"
"net/http"
"pageswiki/internal/store"
"strings"
)
func (s *Server) handleRestoreRevisionAPI(
w http.ResponseWriter,
r *http.Request,
) {
func (s *Server) handleRestoreRevisionAPI(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.Header().Set("Allow", "POST")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
http.Error(w, "method not allowed", 405)
return
}
revisionUUID :=
r.URL.Query().Get("revision")
metadata, err :=
s.store.GetRevisionMetadata(
revisionUUID,
)
var input struct {
Revision string `json:"revision_uuid"`
Expected string `json:"base_revision_uuid"`
Message string `json:"message"`
}
if !taskJSON(w, r, &input) {
return
}
if input.Expected == "" {
http.Error(w, "base revision required", 428)
return
}
if len(input.Message) > 4096 {
http.Error(w, "message too long", 422)
return
}
metadata, err := s.store.GetRevisionMetadata(input.Revision)
if err != nil {
http.Error(
w,
err.Error(),
500,
)
http.NotFound(w, r)
return
}
if s.authorizeObjectForRequest(r, "write", metadata.ObjectUUID) != nil {
http.Error(w, "forbidden", http.StatusForbidden)
if s.authorizeObjectForRequest(r, "read", metadata.ObjectUUID) != nil || s.authorizeObjectForRequest(r, "write", metadata.ObjectUUID) != nil {
http.Error(w, "forbidden", 403)
return
}
// Authorize metadata before hydrating the potentially large source body.
revision, err := s.store.GetRevision(revisionUUID)
revision, err := s.store.GetRevision(input.Revision)
if err != nil {
http.Error(w, "revision unavailable", http.StatusInternalServerError)
http.Error(w, "revision unavailable", 500)
return
}
message := strings.TrimSpace(input.Message)
if message == "" {
message = "Restore revision " + revision.UUID
}
saved, err := s.store.SaveRevisionContentIfHead(revision.ObjectUUID, []byte(revision.Body), message, revision.Language, revision.ContentType, revision.Filename, input.Expected)
if errors.Is(err, store.ErrRevisionConflict) {
http.Error(w, "revision changed; reload history", 412)
return
}
_, err = s.store.SaveRevisionContent(
revision.ObjectUUID,
[]byte(revision.Body),
"restore revision",
revision.Language,
revision.ContentType,
revision.Filename,
)
if err != nil {
http.Error(
w,
err.Error(),
500,
)
http.Error(w, "restore failed", 500)
return
}
_, _ = w.Write([]byte("ok"))
w.Header().Set("Cache-Control", "no-store")
writeEventJSON(w, 200, map[string]string{"revision_uuid": saved.UUID, "object_uuid": revision.ObjectUUID})
}
+61
View File
@@ -0,0 +1,61 @@
package server
import (
"bytes"
"encoding/json"
"net/http/httptest"
"strings"
"testing"
)
func TestRevisionRestoreAppendAndConflict(t *testing.T) {
s, token, domain := configFixture(t)
object, err := s.store.CreatePageAtPathInDomain(domain, "/restore-ui")
if err != nil {
t.Fatal(err)
}
old, err := s.store.SaveRevisionContent(object, []byte("<p>Old</p>"), "first", "ja", "text/html", "note.html")
if err != nil {
t.Fatal(err)
}
head, err := s.store.SaveRevisionContent(object, []byte("<p>New</p>"), "second", "ja", "text/html", "note.html")
if err != nil {
t.Fatal(err)
}
s.mux.HandleFunc("/_/api/v1/revisions/restore", s.handleRestoreRevisionAPI)
s.mux.HandleFunc("/r/history/", s.handleRevisionBrowser)
post := func(payload map[string]string) *httptest.ResponseRecorder {
body, _ := json.Marshal(payload)
r := httptest.NewRequest("POST", "http://localhost/_/api/v1/revisions/restore", bytes.NewReader(body))
r.Header.Set("Authorization", "Bearer "+token)
r.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
s.withAuthorization(s.mux).ServeHTTP(w, r)
return w
}
page := configRequest(s, token, "GET", "/r/history/"+object, nil)
if page.Code != 200 || !strings.Contains(page.Body.String(), `data-restore-revision="`+old.UUID+`"`) || !strings.Contains(page.Body.String(), "data-revision-time") {
t.Fatal(page.Code, page.Body)
}
payload := map[string]string{"revision_uuid": old.UUID, "base_revision_uuid": head.UUID, "message": "元の内容へ復元"}
w := post(payload)
if w.Code != 200 {
t.Fatal(w.Code, w.Body)
}
restored, err := s.store.GetRevisionForExactLanguage(object, "ja")
if err != nil || restored.UUID == old.UUID || restored.UUID == head.UUID || restored.Body != old.Body || restored.Message != payload["message"] {
t.Fatal(restored, err)
}
if _, err = s.store.GetRevision(head.UUID); err != nil {
t.Fatal("previous head lost", err)
}
w = post(payload)
if w.Code != 412 {
t.Fatal("stale restore", w.Code, w.Body)
}
delete(payload, "base_revision_uuid")
w = post(payload)
if w.Code != 428 {
t.Fatal("missing precondition", w.Code, w.Body)
}
}
+3
View File
@@ -5,3 +5,6 @@ body.mode-editor .page-html {
body.mode-view textarea.editor {
display: none;
}
.editor-change-message { display:flex; align-items:center; gap:.35rem; min-width:0; font-size:.8rem; }
.editor-change-message input { width:clamp(8rem,16vw,16rem); min-width:0; padding:.3rem .5rem; color:var(--fg); background:var(--bg); border:1px solid var(--border); border-radius:.3rem; }
@media(max-width:760px) { .editor-change-message span { display:none; } .editor-change-message input { width:8rem; } }
+6 -1
View File
@@ -252,6 +252,10 @@ window.PagesEditor = {
if (this.saving) return false
if (!this.dirty) return !this.paused
if (!manual && this.paused) return false
const messageField=document.getElementById('revision-message')
const changeMessage=messageField?.value.trim()||''
// A supplied message belongs to the next explicit save, not autosave.
if (!manual && changeMessage) return false
if (manual) this.mergeAttempts=0
this.persist()
this.saving = true
@@ -261,11 +265,12 @@ window.PagesEditor = {
try {
body = await this.canonical(text,format)
const data = await this.post('/_/api/v1/revisions/save',{
object_uuid:this.value('object-uuid'),body,message:manual?'manual-save':'autosave',
object_uuid:this.value('object-uuid'),body,message:manual?(changeMessage||'manual-save'):'autosave',
lang:this.value('page-language')||'und',content_type:this.value('page-content-type'),filename:this.value('page-filename'),
base_revision_uuid:this.baseRevision,editor_principal_uuid:this.owner,
})
if (!data.revision_uuid) throw {kind:'failed'}
if (manual && messageField?.value.trim()===changeMessage) messageField.value=''
this.baseRevision = data.revision_uuid
this.baseBody = typeof data.body==='string' ? data.body : body
this.initialText = text; this.initialFormat = format
+20 -44
View File
@@ -1,44 +1,20 @@
console.log("revisions.js loaded")
async function restoreRevision(
revisionUUID,
) {
if (
!confirm(
"restore revision?"
)
) {
return
}
const res = await fetch(
"/_/api/v1/revisions/restore",
{
method: "POST",
headers: {
"Content-Type":
"application/json",
},
body: JSON.stringify({
revision_uuid:
revisionUUID,
}),
},
)
if (!res.ok) {
alert(
"restore failed",
)
return
}
alert(
"revision restored",
)
location.reload()
}
(() => {
'use strict';
const ja=document.documentElement.lang.startsWith('ja'),t=(en,jp)=>ja?jp:en;
for(const node of document.querySelectorAll('[data-revision-time]')){
const date=new Date(Number(node.dataset.revisionTime)*1000);
if(!Number.isNaN(date.valueOf())){node.dateTime=date.toISOString();node.textContent=date.toLocaleString(undefined,{year:'numeric',month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit',second:'2-digit',timeZoneName:'short'});node.title=date.toISOString();}
}
let busy=false;
document.addEventListener('click',async event=>{
const button=event.target.closest('[data-restore-revision]');if(!button||busy)return;
const message=prompt(t('Restore as a new revision. Enter a change message:','新しいリビジョンとして復元します。更新メッセージを入力してください。'),t('Restore revision ','リビジョンを復元: ')+button.dataset.restoreRevision);
if(message===null)return;
busy=true;button.disabled=true;
try{
const response=await fetch('/_/api/v1/revisions/restore',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},body:JSON.stringify({revision_uuid:button.dataset.restoreRevision,base_revision_uuid:button.dataset.baseRevision,message}),signal:AbortSignal.timeout(30000)});
if(response.redirected||!response.ok)throw Error(response.status===412?t('Changed elsewhere. Reload history before restoring.','別の画面で更新されました。履歴を再読み込みしてから復元してください。'):t('Restore failed. Check your login and permissions.','復元できませんでした。ログイン状態と権限を確認してください。'));
location.reload();
}catch(error){alert(error.message);}finally{busy=false;button.disabled=false;}
});
})();
+2 -1
View File
@@ -53,6 +53,7 @@
<div class="editor-head-left">
<label class="editor-change-message"><span>{{ T "history.message" }}</span><input id="revision-message" type="text" maxlength="1000" placeholder="{{ T "history.message_optional" }}"></label>
<button type="button" class="editor-action-icon" data-editor-action="tools" title="{{ T "editor.tools" }}" aria-label="{{ T "editor.tools" }}">+</button>
<button type="button" class="editor-action-icon" data-editor-action="language" title="{{ T "editor.language" }}" aria-label="{{ T "editor.language" }}">文</button>
<button type="button" class="editor-action-icon" data-editor-action="restore" title="{{ T "editor.restore" }}" aria-label="{{ T "editor.restore" }}">↶</button>
@@ -277,7 +278,7 @@ Ln 1, Col 1
<script src="/static/js/editor-core.js?v=priority-ux-1"></script>
{{ if .CSVEditor }}<script>window.PagesCSVSource = {{ .Body }};</script><script src="/static/js/csv-core.js?v=2"></script><script src="/static/js/csv-editor.js?v=2"></script>{{ end }}
<script src="/static/js/editor.js?v=slides-1"></script>
<script src="/static/js/editor.js?v=revision-message-1"></script>
<script src="/static/js/path-actions.js"></script>
+1
View File
@@ -80,6 +80,7 @@
</div>
{{ if .ObjectUUID }}
<a class="breadcrumb-action-icon" href="/r/history/{{ .ObjectUUID }}" title="{{ T "history.title" }}" aria-label="{{ T "history.title" }}"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 5v5h5M5.5 9a8 8 0 1 1-.5 6M12 7v5l3 2"/></svg></a>
{{ if and .SlidesEnabled (eq .ContentView.Kind "html") }}<a class="breadcrumb-action-icon" href="/v/slides{{ .Path }}" title="{{ T "slides.title" }}" aria-label="{{ T "slides.title" }}"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 4h18v12H3zM12 16v5m-5 0 5-5 5 5M8 8h8m-8 4h5"/></svg></a>{{ end }}
<a class="breadcrumb-action-icon" href="/_/view/print/uuid:{{ .ObjectUUID }}" title="{{ T "viewer.print" }}" aria-label="{{ T "viewer.print" }}">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 9V4h10v5M7 17H5a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-2M7 14h10v6H7z"></path></svg>
+4 -1
View File
@@ -38,7 +38,7 @@
<a
href="/r/history/{{ .Revision.ObjectUUID }}"
>
History
{{ T "history.title" }}
</a>
</nav>
@@ -52,6 +52,8 @@ History
<h1>Revision View</h1>
<div class="revision-meta">
<div><time data-revision-time="{{ .Revision.CreatedAt }}">{{ .Revision.CreatedAt }}</time> · {{ .Revision.Language }}</div>
<div>{{ T "history.message" }}: {{ if .Revision.Message }}{{ .Revision.Message }}{{ else }}—{{ end }}</div>
<div>
Revision UUID:
@@ -166,6 +168,7 @@ Raw HTML Source
</main>
<script src="/static/js/revisions.js?v=2" defer></script>
</body>
</html>
{{ end }}
+6 -2
View File
@@ -66,17 +66,20 @@ Object UUID:
</div>
<div>
{{ $r.CreatedAt }}
<time data-revision-time="{{ $r.CreatedAt }}">{{ $r.CreatedAt }}</time>
· {{ $r.Language }}
</div>
</div>
<div class="revision-message">
{{ $r.Message }}
{{ if $r.Message }}{{ $r.Message }}{{ else }}—{{ end }}
</div>
<div class="revision-actions">
{{ if $.CanRestore }}{{ $head := index $.RevisionHeads $r.Language }}{{ if $head }}{{ if ne $head $r.UUID }}
<button type="button" data-restore-revision="{{ $r.UUID }}" data-base-revision="{{ $head }}">{{ T "editor.restore" }}</button>
{{ end }}{{ end }}{{ end }}
<a
class="button"
@@ -112,6 +115,7 @@ Object UUID:
</nav>
</main>
<script src="/static/js/revisions.js?v=2" defer></script>
</body>
</html>
{{ end }}