yrby-forms 0.1.0.alpha1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: befbd86cf6f6e5affdec95b841406ce40790d33af4b59b4345e35d66998029d8
4
+ data.tar.gz: a23eb0997253f791bb80c09ae100cd1ca3bfe1f5f7114729f8d279c070a8903d
5
+ SHA512:
6
+ metadata.gz: 32917cfeb6599d555a85b9a5d96d017d3c2b5588870c744f7bae12f0b62fef74f7f148e22fdf8ea582fe955c37f58f578d1a360f9380f32e5768a8fc50960800
7
+ data.tar.gz: f144fef11f932046f5465f785a7a6be9c3e121e2d708203372a7c2835738f48469942810f5edc3723ab11eafcdf1e133a19d20aa8fb3bb901c2d153d9d58eccc
@@ -0,0 +1,57 @@
1
+ # Changelog: yrby-forms
2
+
3
+ All notable changes to the `yrby-forms` gem are documented here. The
4
+ format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
5
+ this project aims to follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ The first release.
10
+
11
+ ### Added
12
+
13
+ - `has_collaborative_fields :status, :summary` declares which attributes of a
14
+ model collaborate. Enums are last-write-wins. String and text columns merge
15
+ concurrent typing through a Y.Text. Every other type is last-write-wins.
16
+ `text:` and `lww:` force a tier. A name that isn't an attribute raises when
17
+ the class loads.
18
+ - The fields share one collaborative document per record, declared as
19
+ `has_collaborative_document "fields"` with `Y::Forms::FieldsChannel` as its
20
+ channel. Last-write-wins values are entries in a `fields` map, and each
21
+ text field is a Y.Text named `fields/<name>`. `encrypted: true` stores the
22
+ document through `Y::EncryptedDocument`. Destroying the record destroys
23
+ its document.
24
+ - `Y::Forms::FieldsChannel` ships with the gem and subclasses
25
+ `Y::DocumentChannel`. It saves each change and then writes the record's
26
+ columns. It accepts a grant only for the `fields` document of a model with
27
+ collaborative fields, and `authorize_document` adds a check of the current
28
+ user. A failed column write is logged and the change is still acknowledged.
29
+ - `refresh_collaborative_fields` writes the document's values to the declared
30
+ columns under the record lock, with `save!(validate: false)`. Values are
31
+ cast by the attribute types. Map keys outside the declared set are ignored,
32
+ so a client can't write another column.
33
+ - `form.collaborative_fields` renders `<yrby-document>` with the record's
34
+ grant, and takes `collaborative_document_tag`'s options. The presence name
35
+ and color come from `Y::Forms.identity` and render as `data-user-name` and
36
+ `data-user-color`.
37
+ - `form.collaborative_field :status` wraps the usual input for the attribute,
38
+ or one from a block, in `<collaborative-field name tier>`.
39
+ - The `yrby-forms` npm package has the `<collaborative-field>` element.
40
+ - `has_collaborative_fields :title, :body, column: :fields_ydoc` keeps the
41
+ document in a column of the model's own table, as Base64, with no channel
42
+ and no connection. The form posts the document with the fields. A
43
+ `before_save` callback merges it into the stored document under a row lock
44
+ and reads the declared fields from the result. A record's first save builds
45
+ the document from its text columns. A column that is not a document fails
46
+ the save with an `:invalid` error.
47
+ - With `column:`, `form.collaborative_fields` renders `<collaborative-fields>`
48
+ with the document in its `value` attribute, for new records too.
49
+ `autosave: true` posts the form after each edit and merges the answer.
50
+ - The npm package has the `<collaborative-fields>` element, and a
51
+ `yrby-forms/column` entry that registers both elements without yrby-client.
52
+ - The gem ships the JavaScript as import-map assets:
53
+ `yrby-forms/yrby-forms.js` and `yrby-forms/column.js`.
54
+ - The engine requires Action Cable's classes, so an app that keeps every
55
+ document in a column loads without the cable.
56
+
57
+ Requires yrby-rails 0.9.0 or later.
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README-forms.md ADDED
@@ -0,0 +1,280 @@
1
+ # yrby-forms
2
+
3
+ Collaborative form fields for Rails over [yrby](README.md). You declare which
4
+ attributes of a model collaborate and render them with two form helpers.
5
+ Every open form for that record then edits one shared document. Selects,
6
+ checkboxes, numbers, and dates are last-write-wins per field. Text fields
7
+ merge concurrent typing per character. The server writes the values to the
8
+ record's columns after every change.
9
+
10
+ It is two packages, versioned in this repo:
11
+
12
+ - **`yrby-forms` (gem)** has the model macro, the form helpers, and the
13
+ channel.
14
+ - **[`yrby-forms` (npm)](packages/forms)** has the `<collaborative-field>`
15
+ element. The connection is yrby-client's `<yrby-document>`.
16
+
17
+ A model can also keep the document in one of its own columns. Then the form
18
+ posts the document like any other field and needs no connection. See
19
+ [A document in a column](#a-document-in-a-column).
20
+
21
+ ## Install
22
+
23
+ ```ruby
24
+ # Gemfile
25
+ gem "yrby-forms"
26
+ ```
27
+
28
+ ```sh
29
+ bin/rails generate yrby:install
30
+ bin/rails db:migrate
31
+ npm install yrby-forms yjs y-protocols @rails/actioncable
32
+ ```
33
+
34
+ `yrby:install` is yrby-rails' generator. It creates the migration for the
35
+ `y_documents` and `y_document_updates` tables. Skip it if the app already
36
+ has them.
37
+
38
+ Import the npm package once from your JavaScript entry point. Importing
39
+ registers the elements:
40
+
41
+ ```js
42
+ import "yrby-forms"
43
+ ```
44
+
45
+ An import-map app needs no npm. The gem ships the same module as an asset.
46
+ Pin it next to the pins `yrby:install` added:
47
+
48
+ ```ruby
49
+ # config/importmap.rb
50
+ pin "yrby-forms", to: "yrby-forms/yrby-forms.js"
51
+ ```
52
+
53
+ ## Declare and render
54
+
55
+ ```ruby
56
+ class Ticket < ApplicationRecord
57
+ enum :status, { triage: "triage", active: "active", done: "done" }
58
+
59
+ has_collaborative_fields :status, :priority, :summary, :description
60
+ end
61
+ ```
62
+
63
+ Declare enums before the macro, because it reads them to pick each
64
+ attribute's tier:
65
+
66
+ | Attribute | Tier |
67
+ |---|---|
68
+ | Rails enum | `lww` |
69
+ | `:string` or `:text` column | `text` (a Y.Text, merged per character) |
70
+ | anything else (integer, boolean, date, datetime, decimal) | `lww` |
71
+
72
+ `text:` and `lww:` force a tier:
73
+
74
+ ```ruby
75
+ has_collaborative_fields :summary, :notes, lww: [:summary]
76
+ ```
77
+
78
+ A name that isn't an attribute raises when the class loads. `encrypted: true`
79
+ stores the document through `Y::EncryptedDocument`. To encrypt the columns,
80
+ use the model's own `encrypts`.
81
+
82
+ Render the fields inside any form:
83
+
84
+ ```erb
85
+ <%= form_with(model: @ticket) do |form| %>
86
+ <%= form.collaborative_fields do %>
87
+ <%= form.collaborative_field :status %>
88
+ <%= form.collaborative_field :priority %>
89
+ <%= form.collaborative_field :description %>
90
+ <% end %>
91
+ <% end %>
92
+ ```
93
+
94
+ `collaborative_field` renders the usual input for the attribute's type: a
95
+ select for an enum, a checkbox for a boolean, a date field for a date. Pass a
96
+ block to render your own:
97
+
98
+ ```erb
99
+ <%= form.collaborative_field :status do %>
100
+ <%= form.select :status, Ticket.statuses.keys %>
101
+ <% end %>
102
+ ```
103
+
104
+ `collaborative_fields` renders yrby's `<yrby-document>` with
105
+ `collaborative_document_tag`, and takes the same options, such as
106
+ `expires_in:` and `refresh:`.
107
+
108
+ ## How it works
109
+
110
+ The macro declares one collaborative document on the model, as
111
+ `has_collaborative_document "fields", channel: "Y::Forms::FieldsChannel"`
112
+ would. The document holds the whole field set:
113
+
114
+ - A `fields` map has one entry per `lww` field. Each write replaces the
115
+ value, and the last write wins.
116
+ - Each `text` field has its own Y.Text named `fields/<name>`.
117
+
118
+ `Y::Forms::FieldsChannel` ships with the gem and subclasses
119
+ `Y::DocumentChannel`. It saves each change and then calls
120
+ `refresh_collaborative_fields` on the record. That method locks the record,
121
+ reads the document, assigns the declared fields, and saves with
122
+ `save!(validate: false)`. Values are cast by the attribute types, so `"7"`
123
+ becomes `7` in an integer column and `"2026-09-01"` becomes a date.
124
+
125
+ Only declared fields are assigned. Clients write the map, so a client can put
126
+ any key in it, including another column's name. Keys outside the declared set
127
+ are dropped before `assign_attributes`.
128
+
129
+ A change is acknowledged once it is saved. If the column write then fails,
130
+ for example on an enum value the model rejects, the channel logs the error.
131
+ The columns catch up on the next change that can be written.
132
+
133
+ Destroying the record destroys its document.
134
+
135
+ ## Authorization and identity
136
+
137
+ The form helper renders a grant signed for this record's `fields` document.
138
+ The channel accepts only that. A grant for another attribute, or for a model
139
+ without collaborative fields, is rejected.
140
+
141
+ A valid grant is enough by default, so the view that renders the form must
142
+ require edit permission. To also check the current user when a client
143
+ subscribes, give the channel an `authorize_document` block, as you would for
144
+ `Y::DocumentChannel`:
145
+
146
+ ```ruby
147
+ # config/initializers/yrby_forms.rb
148
+ Rails.application.config.to_prepare do
149
+ Y::Forms::FieldsChannel.authorize_document do |record, _name|
150
+ current_user.present? && record.editable_by?(current_user)
151
+ end
152
+ end
153
+ ```
154
+
155
+ A block set on `Y::DocumentChannel` applies to forms too, until
156
+ `Y::Forms::FieldsChannel` has its own.
157
+
158
+ Presence names and colors come from `Y::Forms.identity`, which is called with
159
+ the view context. The default reads `current_user`'s `name`, `username`, or
160
+ `handle`, and uses `"Anonymous"` when there is none. A `nil` color becomes a
161
+ color derived from the name:
162
+
163
+ ```ruby
164
+ Y::Forms.identity = ->(view) { { name: view.current_user.handle, color: nil } }
165
+ ```
166
+
167
+ The helper renders the name and color as `data-user-name` and
168
+ `data-user-color` on `<yrby-document>`, and the browser sends them as
169
+ presence. A tampered client can show any name, so treat the name on a field
170
+ as a label. The grant and your `authorize_document` block decide who can read
171
+ and write.
172
+
173
+ ## A document in a column
174
+
175
+ With `column:` the document is a column of the model's own table, stored as
176
+ Base64. There is no `y_documents` table, no channel, and no connection:
177
+
178
+ ```ruby
179
+ class Draft < ApplicationRecord
180
+ has_collaborative_fields :title, :body, column: :fields_ydoc
181
+ end
182
+ ```
183
+
184
+ ```ruby
185
+ add_column :drafts, :fields_ydoc, :text
186
+ ```
187
+
188
+ The form is the same, and the controller is a plain one that permits the
189
+ column with the fields:
190
+
191
+ ```erb
192
+ <%= form_with(model: @draft) do |form| %>
193
+ <%= form.collaborative_fields do %>
194
+ <%= form.collaborative_field :title %>
195
+ <%= form.collaborative_field :body %>
196
+ <% end %>
197
+ <% end %>
198
+ ```
199
+
200
+ ```ruby
201
+ def update
202
+ @draft.update!(params.expect(draft: [:title, :body, :fields_ydoc]))
203
+ redirect_to @draft
204
+ end
205
+ ```
206
+
207
+ `collaborative_fields` renders `<collaborative-fields>` with the document in
208
+ its `value` attribute. The element adds the edited document to the form's
209
+ data under the column's name, so every submit carries it. A `before_save`
210
+ callback merges the posted document into the stored one and reads the
211
+ declared fields from the result. Two people who submit the same form both
212
+ keep their edits, and nobody gets a `StaleObjectError`.
213
+
214
+ Pass `autosave: true` to post the form 300 ms after each edit, without a
215
+ page load. The page that answers holds the merged document, and the element
216
+ merges it into the open form:
217
+
218
+ ```erb
219
+ <%= form.collaborative_fields autosave: true do %>
220
+ ```
221
+
222
+ A new document also reaches an open form when the `value` attribute changes,
223
+ which is what a Turbo morph of the page does. A bound control is left out of
224
+ the morph, so the person typing keeps their cursor.
225
+
226
+ This mode needs only `<collaborative-fields>` and `<collaborative-field>`.
227
+ An app with no connection can import them without yrby-client:
228
+
229
+ ```js
230
+ import "yrby-forms/column"
231
+ ```
232
+
233
+ ```ruby
234
+ # config/importmap.rb
235
+ pin "yjs", to: "yrby/yjs.js"
236
+ pin "yrby-forms/column", to: "yrby-forms/column.js"
237
+ ```
238
+
239
+ What to know about the column:
240
+
241
+ - The document owns the declared fields. On every save they are read from
242
+ it, so a value assigned to a declared field in Ruby is replaced.
243
+ - A record gets its document on the first save, built from its text
244
+ columns. For records that exist already, run `Draft.find_each(&:save!)`.
245
+ - A column that is not a valid document fails the save with an `:invalid`
246
+ error on the column.
247
+ - The stored document is read under a row lock, so two saves at the same
248
+ moment merge one after the other.
249
+ - There is no presence, because there is no connection.
250
+ - `encrypted:` is rejected. Use the model's own `encrypts :fields_ydoc`.
251
+
252
+ Anything that saves the record through Active Record merges the same way, so
253
+ a sync layer that writes the column works as the transport. Offline edits
254
+ then merge when they arrive.
255
+
256
+ ## Limitations
257
+
258
+ - Values go from the document to the columns, and not the other way. An
259
+ attribute assigned in Ruby is not written to the document. With a
260
+ `Y::Document`, a record's existing column values do not fill a new
261
+ document. With `column:`, the text columns do.
262
+ - A change made to the document from Ruby does not reach the columns until
263
+ you call `refresh_collaborative_fields` or a browser makes the next change.
264
+ - Presence is per field. There are no carets inside a field.
265
+ - Nothing is stored in the browser, so a change that has not reached the
266
+ server is lost on reload.
267
+ - Nested attributes and `fields_for` are not supported.
268
+ - Rich text belongs to
269
+ [lexxy-realtime](https://github.com/jpcamara/lexxy-realtime).
270
+
271
+ ## The element
272
+
273
+ The [npm package README](packages/forms/README.md) covers the markup, the
274
+ presence state, using another consumer such as AnyCable's, and styling.
275
+
276
+ ## Demo
277
+
278
+ The [actioncable-demo](examples/actioncable-demo)'s `/tickets/:id` page runs
279
+ all of it. `frontend/form_fields_e2e.mjs` drives the page with two browsers
280
+ in CI.
@@ -0,0 +1,309 @@
1
+ // src/bindings.ts
2
+ var FIELDS_MAP = "fields";
3
+ function diffSplice(oldValue, newValue) {
4
+ if (oldValue === newValue)
5
+ return null;
6
+ let start = 0;
7
+ while (start < oldValue.length && start < newValue.length && oldValue[start] === newValue[start])
8
+ start++;
9
+ let oldEnd = oldValue.length;
10
+ let newEnd = newValue.length;
11
+ while (oldEnd > start && newEnd > start && oldValue[oldEnd - 1] === newValue[newEnd - 1]) {
12
+ oldEnd--;
13
+ newEnd--;
14
+ }
15
+ return { index: start, deleteCount: oldEnd - start, insert: newValue.slice(start, newEnd) };
16
+ }
17
+ var isCheckbox = (control) => control instanceof HTMLInputElement && control.type === "checkbox";
18
+ function bindLww(doc, name, control) {
19
+ const map = doc.getMap(FIELDS_MAP);
20
+ const origin = {};
21
+ const read = () => isCheckbox(control) ? control.checked : control.value;
22
+ const write = (value) => {
23
+ if (isCheckbox(control))
24
+ control.checked = value === true;
25
+ else {
26
+ const text = value == null ? "" : String(value);
27
+ if (control.value !== text)
28
+ control.value = text;
29
+ }
30
+ };
31
+ const onInput = () => {
32
+ if (map.get(name) === read())
33
+ return;
34
+ doc.transact(() => map.set(name, read()), origin);
35
+ };
36
+ control.addEventListener("input", onInput);
37
+ control.addEventListener("change", onInput);
38
+ const observer = (event, transaction) => {
39
+ if (transaction.origin === origin || !event.keysChanged.has(name))
40
+ return;
41
+ write(map.get(name));
42
+ };
43
+ map.observe(observer);
44
+ if (map.has(name))
45
+ write(map.get(name));
46
+ return () => {
47
+ control.removeEventListener("input", onInput);
48
+ control.removeEventListener("change", onInput);
49
+ map.unobserve(observer);
50
+ };
51
+ }
52
+ function bindText(doc, name, control) {
53
+ const text = doc.getText(`${FIELDS_MAP}/${name}`);
54
+ const origin = {};
55
+ let shadow = control.value;
56
+ if (text.length > 0)
57
+ shadow = control.value = text.toString();
58
+ const onInput = () => {
59
+ const change = diffSplice(shadow, control.value);
60
+ shadow = control.value;
61
+ if (!change)
62
+ return;
63
+ doc.transact(() => {
64
+ if (change.deleteCount > 0)
65
+ text.delete(change.index, change.deleteCount);
66
+ if (change.insert)
67
+ text.insert(change.index, change.insert);
68
+ }, origin);
69
+ };
70
+ control.addEventListener("input", onInput);
71
+ const observer = (_event, transaction) => {
72
+ if (transaction.origin === origin)
73
+ return;
74
+ const value = text.toString();
75
+ if (control.value === value) {
76
+ shadow = value;
77
+ return;
78
+ }
79
+ const change = diffSplice(control.value, value);
80
+ const caret = control.selectionStart;
81
+ const focused = control.ownerDocument.activeElement === control;
82
+ control.value = value;
83
+ shadow = value;
84
+ if (focused && change && caret != null) {
85
+ const position = change.index <= caret ? Math.max(change.index, caret + change.insert.length - change.deleteCount) : caret;
86
+ control.setSelectionRange(position, position);
87
+ }
88
+ };
89
+ text.observe(observer);
90
+ return () => {
91
+ control.removeEventListener("input", onInput);
92
+ text.unobserve(observer);
93
+ };
94
+ }
95
+
96
+ // src/styles.ts
97
+ var STYLE_ID = "yrby-forms-styles";
98
+ function ensureStyles(doc) {
99
+ if (doc.getElementById(STYLE_ID))
100
+ return;
101
+ const style = doc.createElement("style");
102
+ style.id = STYLE_ID;
103
+ style.textContent = `
104
+ collaborative-field { display: block; position: relative; }
105
+ collaborative-field[data-remote] :is(input, textarea, select) {
106
+ outline: 2px solid var(--collaborative-field-color, #958DF1);
107
+ outline-offset: 1px;
108
+ }
109
+ .collaborative-field-chip {
110
+ position: absolute;
111
+ top: 0;
112
+ right: 0;
113
+ transform: translateY(-100%);
114
+ color: #fff;
115
+ padding: 1px 6px;
116
+ border-radius: 999px;
117
+ font: 11px system-ui, sans-serif;
118
+ pointer-events: none;
119
+ }
120
+ `;
121
+ doc.head.appendChild(style);
122
+ }
123
+
124
+ // src/collaborative_field.ts
125
+ var FALLBACK_COLOR = "#958DF1";
126
+
127
+ class CollaborativeField extends HTMLElement {
128
+ #host = null;
129
+ #unbind = null;
130
+ connectedCallback() {
131
+ ensureStyles(this.ownerDocument);
132
+ const host = this.closest("yrby-document, collaborative-fields");
133
+ if (!host) {
134
+ console.error("<collaborative-field> needs a <yrby-document> or <collaborative-fields> around it.");
135
+ return;
136
+ }
137
+ this.#host = host;
138
+ host.addEventListener("yrby:synced", this.#onSynced);
139
+ if (host.current)
140
+ this.#bind(host.current);
141
+ }
142
+ disconnectedCallback() {
143
+ this.#host?.removeEventListener("yrby:synced", this.#onSynced);
144
+ this.#host = null;
145
+ this.#unbind?.();
146
+ }
147
+ #onSynced = (event) => {
148
+ if (event.target === this.#host)
149
+ this.#bind(event.detail);
150
+ };
151
+ #bind({ doc, lease, signal }) {
152
+ this.#unbind?.();
153
+ const control = this.querySelector("input:not([type=hidden]), textarea, select");
154
+ const name = this.getAttribute("name");
155
+ if (!control || !name) {
156
+ console.error("<collaborative-field> needs a name and a form control.");
157
+ return;
158
+ }
159
+ const unbindControl = this.getAttribute("tier") === "text" ? bindText(doc, name, control) : bindLww(doc, name, control);
160
+ const keep = (event) => {
161
+ if (event.target === control)
162
+ event.preventDefault();
163
+ };
164
+ this.addEventListener("turbo:before-morph-element", keep);
165
+ const unbindPresence = lease ? this.#bindPresence(name, lease) : () => {};
166
+ const unbind = () => {
167
+ if (this.#unbind !== unbind)
168
+ return;
169
+ this.#unbind = null;
170
+ unbindControl();
171
+ this.removeEventListener("turbo:before-morph-element", keep);
172
+ unbindPresence();
173
+ };
174
+ this.#unbind = unbind;
175
+ signal.addEventListener("abort", unbind, { once: true });
176
+ }
177
+ #bindPresence(name, lease) {
178
+ const { userName, userColor } = this.#host.dataset;
179
+ const user = { name: userName || "Anonymous", color: userColor || FALLBACK_COLOR };
180
+ const onFocusin = () => lease.setPresence({ user, field: name });
181
+ const onFocusout = () => lease.setPresence({ user, field: null });
182
+ this.addEventListener("focusin", onFocusin);
183
+ this.addEventListener("focusout", onFocusout);
184
+ const awareness = lease.session.provider.awareness;
185
+ const renderPresence = () => {
186
+ const peers = [...awareness.getStates()].filter(([id, state]) => id !== awareness.clientID && state?.field === name).map(([, state]) => state.user ?? {});
187
+ this.#renderPresence(peers);
188
+ };
189
+ awareness.on("update", renderPresence);
190
+ renderPresence();
191
+ return () => {
192
+ this.removeEventListener("focusin", onFocusin);
193
+ this.removeEventListener("focusout", onFocusout);
194
+ awareness.off("update", renderPresence);
195
+ this.#renderPresence([]);
196
+ };
197
+ }
198
+ #renderPresence(peers) {
199
+ for (const chip of this.querySelectorAll(".collaborative-field-chip"))
200
+ chip.remove();
201
+ if (peers.length === 0) {
202
+ this.removeAttribute("data-remote");
203
+ this.style.removeProperty("--collaborative-field-color");
204
+ return;
205
+ }
206
+ this.setAttribute("data-remote", "");
207
+ this.style.setProperty("--collaborative-field-color", String(peers[0].color ?? FALLBACK_COLOR));
208
+ for (const peer of peers) {
209
+ const chip = this.ownerDocument.createElement("span");
210
+ chip.className = "collaborative-field-chip";
211
+ chip.textContent = String(peer.name ?? "Anonymous");
212
+ chip.style.background = String(peer.color ?? FALLBACK_COLOR);
213
+ this.appendChild(chip);
214
+ }
215
+ }
216
+ }
217
+
218
+ // src/collaborative_fields.ts
219
+ import * as Y from "yjs";
220
+ var SAVE_DELAY = 300;
221
+ var REMOTE = "remote";
222
+
223
+ class CollaborativeFields extends HTMLElement {
224
+ static observedAttributes = ["value"];
225
+ current;
226
+ #form = null;
227
+ #abort = null;
228
+ #timer;
229
+ connectedCallback() {
230
+ const doc = new Y.Doc;
231
+ this.#abort = new AbortController;
232
+ const { signal } = this.#abort;
233
+ this.current = { doc, signal };
234
+ this.#merge(this.getAttribute("value"));
235
+ this.#form = this.closest("form");
236
+ this.#form?.addEventListener("formdata", this.#onFormData, { signal });
237
+ doc.on("update", (_update, origin) => {
238
+ if (origin !== REMOTE && this.hasAttribute("autosave"))
239
+ this.#schedule();
240
+ });
241
+ this.dispatchEvent(new CustomEvent("yrby:synced", { detail: this.current, bubbles: true }));
242
+ }
243
+ disconnectedCallback() {
244
+ if (this.#timer !== undefined)
245
+ this.#save();
246
+ this.#abort?.abort();
247
+ this.current = undefined;
248
+ }
249
+ attributeChangedCallback(_name, _old, value) {
250
+ this.#merge(value);
251
+ }
252
+ #merge(state) {
253
+ if (this.current && state)
254
+ Y.applyUpdate(this.current.doc, fromBase64(state), REMOTE);
255
+ }
256
+ #onFormData = ({ formData }) => {
257
+ const name = this.getAttribute("name");
258
+ if (name && this.current)
259
+ formData.set(name, toBase64(Y.encodeStateAsUpdate(this.current.doc)));
260
+ };
261
+ #schedule() {
262
+ clearTimeout(this.#timer);
263
+ this.#timer = setTimeout(() => void this.#save(), SAVE_DELAY);
264
+ }
265
+ async#save() {
266
+ clearTimeout(this.#timer);
267
+ this.#timer = undefined;
268
+ const form = this.#form;
269
+ const doc = this.current?.doc;
270
+ if (!form || !doc)
271
+ return;
272
+ const body = new URLSearchParams(new FormData(form));
273
+ const response = await fetch(form.getAttribute("action") || location.href, {
274
+ method: "POST",
275
+ body,
276
+ headers: { Accept: "text/html" }
277
+ });
278
+ if (!response.ok || this.current?.doc !== doc)
279
+ return;
280
+ const page = new DOMParser().parseFromString(await response.text(), "text/html");
281
+ for (const fields of page.querySelectorAll("collaborative-fields")) {
282
+ if (fields.getAttribute("name") === this.getAttribute("name"))
283
+ this.#merge(fields.getAttribute("value"));
284
+ }
285
+ }
286
+ }
287
+ var toBase64 = (bytes) => {
288
+ let binary = "";
289
+ for (const byte of bytes)
290
+ binary += String.fromCharCode(byte);
291
+ return btoa(binary);
292
+ };
293
+ var fromBase64 = (text) => Uint8Array.from(atob(text), (char) => char.charCodeAt(0));
294
+
295
+ // src/elements.ts
296
+ for (const [name, element] of [
297
+ ["collaborative-field", CollaborativeField],
298
+ ["collaborative-fields", CollaborativeFields]
299
+ ]) {
300
+ if (!customElements.get(name))
301
+ customElements.define(name, element);
302
+ }
303
+ export {
304
+ CollaborativeField,
305
+ CollaborativeFields
306
+ };
307
+
308
+ //# debugId=9C20B4CD31EB089964756E2164756E21
309
+ //# sourceMappingURL=column.js.map