1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// OverType hardcodes `min-height: 60px !important` on `.overtype-wrapper`
// and runs auto-resize during construction — before callers can intervene —
// locking in an inflated height. The app's global textarea styles (padding,
// border) further inflate `scrollHeight`, which auto-resize reads.
//
// This function corrects both problems after `new OverType(el, ...)`:
//
//  1. Zeros the wrapper's min-height (inline `!important` beats the
//     stylesheet's `!important` at equal specificity).
//  2. Strips the textarea padding and border that inflate scrollHeight.
//  3. On the next frame — once the style overrides have taken effect —
//     collapses the textarea to height 0, reads scrollHeight for the true
//     content height, and sets that height on the wrapper, textarea, and
//     preview so all three layers agree.
//  4. Hooks the textarea's `input` event to repeat step 3, because
//     OverType's own auto-resize fires on every keystroke and re-inflates
//     the height.
//
// The element must be visible (participating in layout) by the time the
// next animation frame fires, or scrollHeight will read as 0. If the
// container is hidden at creation time — for example behind an Alpine
// x-show that hasn't toggled yet — defer the call with
// requestAnimationFrame so the browser lays it out first.
//
// Returns a resize function for manual re-measurement (e.g. after toggling
// readOnly or pointer-events), or null if the expected DOM isn't found.
function compactOverType(el) {
  const wrapper = el.querySelector(".overtype-wrapper")
  const textarea = el.querySelector("textarea")
  const preview = el.querySelector(".overtype-preview")
  if (!wrapper || !textarea) return null

  wrapper.style.setProperty("min-height", "0", "important")
  textarea.style.setProperty("padding", "0 4px", "important")
  textarea.style.setProperty("border", "none", "important")

  const resize = () => {
    textarea.style.setProperty("height", "0", "important")
    const h = textarea.scrollHeight + "px"
    textarea.style.setProperty("height", h, "important")
    wrapper.style.setProperty("height", h, "important")
    if (preview) preview.style.setProperty("height", h, "important")
  }

  requestAnimationFrame(resize)
  textarea.addEventListener("input", () => requestAnimationFrame(resize))

  return resize
}

OverType.setTheme({
  name: "ketchup",
  colors: {
    bgPrimary: "transparent",
    bgSecondary: "transparent",
    text: "#1a1a1a",
    textPrimary: "#1a1a1a",
    textSecondary: "#888",
    h1: "#c00",
    h2: "#c00",
    h3: "#c00",
    strong: "#1a1a1a",
    em: "#666",
    link: "#c00",
    code: "#888",
    codeBg: "rgba(0, 0, 0, 0.05)",
    blockquote: "#666",
    hr: "#ddd",
    syntaxMarker: "rgba(0, 0, 0, 0.3)",
    syntax: "#999",
    cursor: "#c00",
    selection: "rgba(204, 0, 0, 0.15)",
    listMarker: "#c00",
    border: "#ddd",
  },
})

function initPanelEditors(container) {
  const noteDetail = container.querySelector("#series-note-detail")
  if (noteDetail) {
    const initialNote = noteDetail.dataset.value || ""

    const [editor] = new OverType(noteDetail, {
      value: initialNote,
      placeholder: "Series note...",
      autoResize: true,
      minHeight: 14,
      padding: "0 4px",
    })

    const resizeNote = compactOverType(noteDetail)

    noteDetail._overtype = editor
    noteDetail._initialNote = initialNote

    const ta = noteDetail.querySelector("textarea")
    if (ta) {
      ta.style.pointerEvents = "none"
      ta.readOnly = true

      container.addEventListener("start-editing", () => {
        ta.style.pointerEvents = ""
        ta.readOnly = false
        ta.focus()
        if (resizeNote) requestAnimationFrame(resizeNote)
      })

      container.addEventListener("stop-editing", () => {
        ta.style.pointerEvents = "none"
        ta.readOnly = true
        if (resizeNote) requestAnimationFrame(resizeNote)
      })
    }
  }
}

document.addEventListener("alpine:init", () => {
  Alpine.data("seriesEditor", (seriesId, initialCount, initialUnit, initialShared) => ({
    editing: false,
    count: initialCount,
    unit: initialUnit,
    shared: initialShared,

    startEditing() {
      this.editing = true
      this.$dispatch("start-editing")
    },

    cancel() {
      this.editing = false
      location.reload()
    },

    save() {
      const params = new URLSearchParams()
      if (this.count !== initialCount) params.set("interval_count", this.count)
      if (this.unit !== initialUnit) params.set("interval_unit", this.unit)
      if (this.shared !== initialShared) params.set("shared", this.shared ? "1" : "0")

      const noteEl = document.querySelector("#series-note-detail")
      if (noteEl?._overtype) {
        const note = noteEl._overtype.getValue().trim()
        if (note && note !== (noteEl._initialNote || "").trim()) {
          params.set("note", note)
        }
      }

      this.editing = false
      this.$dispatch("stop-editing")

      if (params.toString() === "") return

      fetch(`/series/${seriesId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: params.toString(),
      }).then((r) => { if (r.ok) location.reload() })
    },
  }))

  Alpine.data("dueDateEditor", (seriesId, taskId, initialDate) => ({
    editingDate: false,
    dueDate: initialDate,

    save() {
      if (this.dueDate === initialDate) {
        this.editingDate = false
        return
      }
      fetch(`/series/${seriesId}/tasks/${taskId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ due_date: this.dueDate }),
      }).then((r) => { if (r.ok) location.reload() })
    },
  }))

  Alpine.data("historyNote", (seriesId, taskId, hasNote) => ({
    hasNote,
    editing: false,
    _editor: null,

    init() {
      if (this.hasNote) this._initEditor()
    },

    destroy() {
      if (this._editor) {
        this._editor.destroy()
        this._editor = null
      }
    },

    edit() {
      this.editing = true
      this.$nextTick(() => this._initEditor())
    },

    _patchTask(data) {
      return fetch(`/series/${seriesId}/tasks/${taskId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      })
    },

    _initEditor() {
      const el = this.$refs.editor
      if (!el || this._editor) return

      const initialNote = el.dataset.value || ""
      const [editor] = new OverType(el, {
        value: initialNote,
        placeholder: "Add a note...",
        autoResize: true,
        minHeight: 14,
        fontSize: "14px",
        padding: "0 4px",
      })

      this._editor = editor
      compactOverType(el)

      const textarea = el.querySelector("textarea")
      if (textarea) {
        if (!initialNote) textarea.focus()
        textarea.addEventListener("blur", () => {
          const note = editor.getValue().trim()
          if (note === initialNote.trim()) {
            if (!note) this.editing = false
            return
          }

          this._patchTask({ note }).then((r) => {
            if (!r.ok) return
            el.dataset.value = note
            this.hasNote = !!note
            this.editing = false
          })
        })
      }
    },
  }))

  Alpine.data("completedDateEditor", (seriesId, taskId, initialDate) => ({
    editingDate: false,
    completedDate: initialDate,

    cancel() {
      this.completedDate = initialDate
      this.editingDate = false
    },

    save() {
      if (this.completedDate === initialDate) {
        this.editingDate = false
        return
      }
      fetch(`/series/${seriesId}/tasks/${taskId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ completed_at: this.completedDate }),
      }).then((r) => { if (r.ok) location.reload() })
    },
  }))

  // Series detail page editor
  initPanelEditors(document)

  // New series form editor
  const newNoteEl = document.getElementById("series-note-editor")
  if (newNoteEl) {
    const [editor] = new OverType("#series-note-editor", {
      placeholder: "What needs doing...",
      textareaProps: { name: "note", required: true },
      autoResize: true,
    })
    const createBtn = document.getElementById("create-series-btn")
    const newForm = document.getElementById("new-series-form")
    if (createBtn && newForm) {
      newNoteEl.addEventListener("input", () => {
        createBtn.disabled = !editor.getValue().trim()
      })
      createBtn.addEventListener("click", () => {
        newForm.requestSubmit()
      })
    }
  }
})