Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

frontend: always calculate the snippet indexes from the beginning #113

Merged
merged 2 commits into from
Mar 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions frontend/src/app/contribute_events.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
[lambdaisland.fetch :as fetch]
[app.helpers :refer
[current-path
remove-trailing-slash]]
remove-trailing-slash
previous-siblings]]
[app.editor.core :refer [active-file]]
[app.contribute-logic :refer
[file-id
Expand Down Expand Up @@ -43,7 +44,7 @@
(rename-keys {:comment :user_comment
:start-index :start_index
:end-index :end_index})
(dissoc :text :file)))
(dissoc :file)))
;; Only snippets for this file
(filter
(fn [snippet]
Expand Down Expand Up @@ -88,8 +89,26 @@

(let [selection (.getSelection js/window)
content (.toString selection)

;; The position is calculated from the end of the last node
;; This can be be either a previous snippet span or if the text
;; longer than 65536 characters than it is implictily split into
;; multiple sibling text nodes
start (.-anchorOffset selection)

;; Calculate the real starting index from the beginning of the log
offset (->> selection
.-anchorNode
previous-siblings
(map #(.-textContent %))
(map #(count %))
(reduce +))
start (+ start offset)

;; Index of the last snippet character. When parsing in python, don't
;; forget to do text[start:end+1]
end (+ start (count content) -1)

snippet
{:text content
:start-index start
Expand Down
6 changes: 6 additions & 0 deletions frontend/src/app/helpers.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,9 @@

(defn remove-trailing-slash [text]
(clojure.string/replace text #"/$" ""))

(defn previous-siblings [node]
(let [sibling (.-previousSibling node)]
(if-not sibling
[]
(conj (previous-siblings sibling) sibling))))
Loading