From d31a5053cf88d4c61a86ce07f02684e000a50e14 Mon Sep 17 00:00:00 2001 From: Stephen Searles Date: Mon, 12 Jun 2017 23:44:50 -0700 Subject: [PATCH] fixes and cleanups --- acedoc.go | 5 +++-- client.go | 10 +++++++++- delta.go | 43 ++++++++++++++++++++++++++++++++++++++----- 3 files changed, 50 insertions(+), 8 deletions(-) diff --git a/acedoc.go b/acedoc.go index 299383c..3de1da1 100644 --- a/acedoc.go +++ b/acedoc.go @@ -74,7 +74,7 @@ func (d Delta) rows() uint { } func (d Delta) cols() uint { - r := d.End.Column + r := d.End.Column - d.Start.Column return r } @@ -86,7 +86,8 @@ func (d *Document) Contents() string { } type Position struct { - Row, Column uint + Row uint `json:"row"` + Column uint `json:"column"` } func (d *Document) InDocument(pos Position) bool { diff --git a/client.go b/client.go index 3b40e2a..e886e29 100644 --- a/client.go +++ b/client.go @@ -96,7 +96,12 @@ func (c *Client) Error() error { // PushDeltas pushes deltas into the document. func (c *Client) PushDeltas(d ...Delta) error { - return c.doc.Apply(d...) + ds := make([]Delta, len(d)) + for i := range d { + ds[i] = d[i] + ds[i].source = c + } + return c.doc.Apply(ds...) } func (c *Client) pullDeltas() []Delta { @@ -125,6 +130,9 @@ func (c *Client) pullDeltas() []Delta { if d.Equal(Delta{}) { continue } + if d.source == c { + continue + } ds = append(ds, d) if len(ds) == maxSize { diff --git a/delta.go b/delta.go index bc34c1e..b15b8fb 100644 --- a/delta.go +++ b/delta.go @@ -45,10 +45,40 @@ const ( DeltaRemove DeltaAction = false ) +func (d DeltaAction) String() string { + if d == DeltaInsert { + return "insert" + } + return "remove" +} + +func (d DeltaAction) MarshalJSON() ([]byte, error) { + if d == DeltaInsert { + return []byte(`"insert"`), nil + } + return []byte(`"remove"`), nil +} + +func (d *DeltaAction) UnmarshalJSON(b []byte) error { + fmt.Println(string(b)) + if string(b) == "null" { + return nil + } + + if string(b) == `"insert"` { + *d = DeltaInsert + } + + return nil +} + type Delta struct { - Action DeltaAction - Lines []string - Start, End Position + Action DeltaAction `json:"action"` + Lines []string `json:"lines"` + Start Position `json:"start"` + End Position `json:"end"` + + source *Client } func (d Delta) Equal(other Delta) bool { @@ -162,6 +192,9 @@ func (d *Document) Apply(dls ...Delta) error { d.deltas = append(d.deltas, dl) for _, c := range d.clients { + if dl.source == c { + continue + } c.ch <- dl } } @@ -184,8 +217,8 @@ func (d *Document) validate(dl Delta) error { lastDlLine := dl.line(dl.nRows() - 1) - if uint(len(lastDlLine)) != dl.cols() { - return fmt.Errorf("delta has %d chars on the final line, but positions show range of %d chars", len(lastDlLine), dl.cols()) + if uint(len(lastDlLine)) != dl.End.Column { + return fmt.Errorf("delta has %d chars on the final line, but positions show range of %d chars", len(lastDlLine), dl.End.Column) } return nil