Diffdown is a real-time collaborative Markdown editor/previewer built on the AT Protocol diffdown.com

feat: add simplified OT engine

+53
+53
internal/collaboration/ot.go
··· 1 + package collaboration 2 + 3 + import "sync" 4 + 5 + type OTEngine struct { 6 + mu sync.Mutex 7 + documentText string 8 + version int 9 + } 10 + 11 + func NewOTEngine(initialText string) *OTEngine { 12 + return &OTEngine{ 13 + documentText: initialText, 14 + version: 0, 15 + } 16 + } 17 + 18 + type Operation struct { 19 + From int `json:"from"` 20 + To int `json:"to"` 21 + Insert string `json:"insert"` 22 + Author string `json:"author"` 23 + } 24 + 25 + func (ot *OTEngine) Apply(op Operation) string { 26 + ot.mu.Lock() 27 + defer ot.mu.Unlock() 28 + 29 + if op.To > len(ot.documentText) { 30 + op.To = len(ot.documentText) 31 + } 32 + if op.From > len(ot.documentText) { 33 + op.From = len(ot.documentText) 34 + } 35 + 36 + newText := ot.documentText[:op.From] + op.Insert + ot.documentText[op.To:] 37 + ot.documentText = newText 38 + ot.version++ 39 + 40 + return ot.documentText 41 + } 42 + 43 + func (ot *OTEngine) GetText() string { 44 + ot.mu.Lock() 45 + defer ot.mu.Unlock() 46 + return ot.documentText 47 + } 48 + 49 + func (ot *OTEngine) GetVersion() int { 50 + ot.mu.Lock() 51 + defer ot.mu.Unlock() 52 + return ot.version 53 + }