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.
@@ -0,0 +1,203 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/concern"
4
+ require "base64"
5
+ require "json"
6
+ require "y/collaborative"
7
+
8
+ module Y
9
+ module Forms
10
+ # Adds a set of collaborative form fields to a model. The fields share one
11
+ # collaborative document, which the model declares the same way
12
+ # has_collaborative_document does. With column: the document is a column
13
+ # of the model's own table instead, and forms need no connection.
14
+ module CollaborativeFields
15
+ extend ActiveSupport::Concern
16
+ include Y::Collaborative
17
+
18
+ module ClassMethods
19
+ # Declares which attributes collaborate and resolves a tier for each:
20
+ # :text (a Y.Text share, character merge) or :lww (an entry in the
21
+ # shared map, last write wins per field). Rails enums are LWW; string
22
+ # and text columns are text tier; every other type is LWW. The text:
23
+ # and lww: kwargs force a tier and win over detection.
24
+ #
25
+ # column: names a string or text column that holds the document as
26
+ # Base64. The form posts the document with the fields, and each save
27
+ # merges it into the stored one (see Column).
28
+ def has_collaborative_fields(*names, text: [], lww: [], encrypted: false, column: nil) # rubocop:disable Naming/PredicatePrefix
29
+ include Model unless include?(Model)
30
+
31
+ tiers = names.map(&:to_sym).to_h do |name|
32
+ [name, forced_collaborative_tiers(names, text, lww)[name] || detect_collaborative_tier(name)]
33
+ end
34
+ self.collaborative_field_tiers = collaborative_field_tiers.merge(tiers).freeze
35
+ return collaborative_fields_in(column, encrypted:) if column
36
+
37
+ # encrypted: true stores the document through Y::EncryptedDocument.
38
+ # To encrypt the columns the values are written to, use the model's
39
+ # own +encrypts+.
40
+ has_collaborative_document Y::Forms::DOCUMENT_NAME, encrypted:, channel: Y::Forms::CHANNEL_NAME
41
+
42
+ # The document's row, or nil before the first edit. The association
43
+ # is here so that destroying the record destroys its document.
44
+ has_one :collaborative_fields_document, -> { where(name: Y::Forms::DOCUMENT_NAME) },
45
+ class_name: encrypted ? "Y::EncryptedDocument" : "Y::Document",
46
+ as: :record, inverse_of: :record, dependent: :destroy
47
+ end
48
+
49
+ private
50
+
51
+ def collaborative_fields_in(column, encrypted:)
52
+ unless attribute_types.key?(column.to_s)
53
+ raise ArgumentError, "#{column.inspect} is not an attribute of #{name}"
54
+ end
55
+ raise ArgumentError, "encrypted: has no effect with column:, use encrypts #{column.inspect}" if encrypted
56
+
57
+ include Column unless include?(Column)
58
+ self.collaborative_fields_column = column.to_sym
59
+ end
60
+
61
+ def forced_collaborative_tiers(names, text, lww)
62
+ forced = Array(text).to_h { |name| [name.to_sym, :text] }
63
+ Array(lww).each do |name|
64
+ raise ArgumentError, "#{name.inspect} is forced both text: and lww:" if forced.key?(name.to_sym)
65
+
66
+ forced[name.to_sym] = :lww
67
+ end
68
+ unknown = forced.keys - names.map(&:to_sym)
69
+ raise ArgumentError, "#{unknown.map(&:inspect).join(", ")} not declared collaborative" if unknown.any?
70
+
71
+ forced
72
+ end
73
+
74
+ def detect_collaborative_tier(name)
75
+ unless attribute_types.key?(name.to_s)
76
+ raise ArgumentError, "#{name.inspect} is not an attribute of #{self.name}"
77
+ end
78
+ return :lww if defined_enums.key?(name.to_s)
79
+
80
+ %i[string text].include?(type_for_attribute(name).type) ? :text : :lww
81
+ end
82
+ end
83
+
84
+ # The instance API, present only on models that declared fields.
85
+ module Model
86
+ extend ActiveSupport::Concern
87
+
88
+ included do
89
+ class_attribute :collaborative_field_tiers, instance_writer: false, default: {}.freeze
90
+ end
91
+
92
+ def collaborative_fields? = collaborative_field_tiers.any?
93
+
94
+ def collaborative_field?(name) = collaborative_field_tiers.key?(name.to_sym)
95
+
96
+ # The column holding the document, or nil when it is a Y::Document.
97
+ def collaborative_fields_column = nil
98
+
99
+ # Reads the document and writes the declared fields' current values
100
+ # into their columns while holding the record lock. Returns false
101
+ # before the document's first edit.
102
+ def refresh_collaborative_fields
103
+ with_lock do
104
+ state = collaborative_document(Y::Forms::DOCUMENT_NAME).load_state
105
+ break false if state.nil?
106
+
107
+ doc = Y::Doc.new
108
+ doc.apply_update(state)
109
+ assign_collaborative_fields(doc)
110
+ save!(validate: false) # collaboration updates should not run unrelated model validations
111
+ true
112
+ end
113
+ end
114
+
115
+ private
116
+
117
+ def collaborative_text_name(name) = "#{Y::Forms::DOCUMENT_NAME}/#{name}"
118
+
119
+ # Assign declared fields only, each read through its declared tier.
120
+ # The map is client-written, so any key a client invents — another
121
+ # column's name included — is dropped here; nothing outside the
122
+ # declared set is ever mass-assigned. LWW values cast through the
123
+ # attribute types on assignment.
124
+ def assign_collaborative_fields(doc)
125
+ entries = JSON.parse(doc.read_map(Y::Forms::DOCUMENT_NAME) || "{}")
126
+ collaborative_field_tiers.each do |name, tier|
127
+ if tier == :text
128
+ value = doc.read_text(collaborative_text_name(name))
129
+ assign_attributes(name => value) unless value.nil?
130
+ elsif entries.key?(name.to_s)
131
+ assign_attributes(name => entries[name.to_s])
132
+ end
133
+ end
134
+ end
135
+ end
136
+
137
+ # The document in a column of the model's own table, as Base64. A form
138
+ # posts the document it edited in that column's param, next to the
139
+ # fields. Each save merges the posted document into the stored one and
140
+ # reads the declared fields from the result, so two people who submit
141
+ # the same form both keep their edits.
142
+ #
143
+ # The document owns the declared fields: a value assigned to one in Ruby
144
+ # is replaced by the document's on save. A text field the document does
145
+ # not hold yet is added to it from its column, which is how a record
146
+ # created in Ruby, or one saved before the macro was declared, gets its
147
+ # document.
148
+ module Column
149
+ extend ActiveSupport::Concern
150
+
151
+ included do
152
+ class_attribute :collaborative_fields_column, instance_writer: false
153
+ before_save :merge_collaborative_fields
154
+ end
155
+
156
+ # The document a form starts from: the stored one, or before the first
157
+ # save one built from the text columns.
158
+ def collaborative_fields_state
159
+ self[collaborative_fields_column].presence || encode_collaborative_fields(seed_collaborative_fields(Y::Doc.new))
160
+ end
161
+
162
+ private
163
+
164
+ def merge_collaborative_fields
165
+ column = collaborative_fields_column
166
+ watched = [column, *collaborative_field_tiers.keys]
167
+ return if self[column].present? && watched.none? { |name| will_save_change_to_attribute?(name) }
168
+
169
+ doc = load_collaborative_fields(stored_collaborative_fields, self[column])
170
+ assign_collaborative_fields(seed_collaborative_fields(doc))
171
+ self[column] = encode_collaborative_fields(doc)
172
+ end
173
+
174
+ # Read under a row lock, so two saves at once merge one after the other.
175
+ def stored_collaborative_fields
176
+ return unless persisted?
177
+
178
+ self.class.unscoped.lock.where(self.class.primary_key => id_in_database).pick(collaborative_fields_column)
179
+ end
180
+
181
+ def load_collaborative_fields(*states)
182
+ states.compact_blank.each_with_object(Y::Doc.new) do |state, doc|
183
+ doc.apply_update(Base64.strict_decode64(state))
184
+ end
185
+ rescue ArgumentError, Y::Error
186
+ errors.add(collaborative_fields_column, :invalid)
187
+ throw :abort
188
+ end
189
+
190
+ def seed_collaborative_fields(doc)
191
+ collaborative_field_tiers.each do |name, tier|
192
+ next unless tier == :text && self[name].present? && doc.read_text(collaborative_text_name(name)).nil?
193
+
194
+ doc.get_text(collaborative_text_name(name)).insert(0, self[name].to_s)
195
+ end
196
+ doc
197
+ end
198
+
199
+ def encode_collaborative_fields(doc) = Base64.strict_encode64(doc.encode_state_as_update)
200
+ end
201
+ end
202
+ end
203
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/engine"
4
+ require "action_dispatch" # Engine::Configuration references it at subclass definition
5
+
6
+ # Require the engine dependencies explicitly so their initializers run
7
+ # during boot.
8
+ require "y"
9
+ require "yrby-rails" # the sync concern, Y::Document storage, and yrby's engine
10
+ # The channels are eager loaded with the app. An app whose fields all live in
11
+ # a column may not load Action Cable, and the channels still need its classes.
12
+ require "action_cable"
13
+
14
+ module Y
15
+ module Forms
16
+ class Engine < ::Rails::Engine
17
+ initializer "y_forms.active_record" do
18
+ ActiveSupport.on_load(:active_record) { include Y::Forms::CollaborativeFields }
19
+ end
20
+
21
+ initializer "y_forms.form_builder" do |app|
22
+ app.config.to_prepare { ActionView::Helpers::FormBuilder.prepend(Y::Forms::FormBuilder) }
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Y
4
+ module Forms
5
+ # form.collaborative_fields wraps a block of inputs in the element that
6
+ # holds the record's field set: <yrby-document>, or <collaborative-fields>
7
+ # when the document is a column. form.collaborative_field wraps one input
8
+ # in <collaborative-field>.
9
+ module FormBuilder
10
+ # Renders collaborative_document_tag for the field set, with the presence
11
+ # name and color from Y::Forms.identity as data attributes. Options go
12
+ # through to the tag, so expires_in: and refresh: work as they do there.
13
+ #
14
+ # When the document is a column, renders <collaborative-fields> with the
15
+ # document in its value attribute. Options become attributes, so
16
+ # autosave: true posts the form after each edit.
17
+ def collaborative_fields(**options, &)
18
+ record = collaborative_record!
19
+ if (column = record.collaborative_fields_column)
20
+ return @template.content_tag("collaborative-fields", @template.capture(&), **options,
21
+ name: field_name(column), value: record.collaborative_fields_state)
22
+ end
23
+ raise ArgumentError, "#{record.class.name} must be persisted to collaborate on it" unless record.persisted?
24
+
25
+ identity = Y::Forms.identity.call(@template)
26
+ name = identity[:name]
27
+ user = { user_name: name, user_color: identity[:color] || Y::Forms.collaborator_color(name) }
28
+ @template.collaborative_document_tag(record, Y::Forms::DOCUMENT_NAME,
29
+ **options, data: user.merge(options.fetch(:data, {})), &)
30
+ end
31
+
32
+ # Renders the stock input for the attribute's type inside the wrapper.
33
+ # Pass a block to render your own input instead.
34
+ def collaborative_field(method, &block)
35
+ record = collaborative_record!
36
+ tier = record.collaborative_field_tiers[method.to_sym]
37
+ unless tier
38
+ raise ArgumentError,
39
+ "#{record.class.name}##{method} is not collaborative (declare has_collaborative_fields :#{method})"
40
+ end
41
+
42
+ input = block ? @template.capture(&block) : default_collaborative_input(method)
43
+ @template.content_tag("collaborative-field", input, "name" => method, "tier" => tier)
44
+ end
45
+
46
+ private
47
+
48
+ def collaborative_record!
49
+ record = object
50
+ unless record.respond_to?(:collaborative_fields?) && record.collaborative_fields?
51
+ raise ArgumentError, "#{record.class.name} has no collaborative fields (declare has_collaborative_fields)"
52
+ end
53
+
54
+ record
55
+ end
56
+
57
+ def default_collaborative_input(method)
58
+ enums = object.class.defined_enums
59
+ return select(method, enums[method.to_s].keys) if enums.key?(method.to_s)
60
+
61
+ case object.class.type_for_attribute(method).type
62
+ when :text then text_area(method)
63
+ when :boolean then check_box(method)
64
+ when :date then date_field(method)
65
+ when :datetime, :time then datetime_field(method)
66
+ when :integer, :decimal, :float then number_field(method)
67
+ else text_field(method)
68
+ end
69
+ end
70
+ end
71
+ end
72
+ end
data/lib/y/forms.rb ADDED
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "y"
4
+
5
+ module Y
6
+ # Collaborative form fields over yrby: a model macro
7
+ # (has_collaborative_fields), form helpers that render <yrby-document> and
8
+ # <collaborative-field>, and the channel that serves them. One document per
9
+ # record, named "fields", holds the whole field set: LWW fields in a
10
+ # "fields" map share, and each text-tier field in its own "fields/<name>"
11
+ # text share.
12
+ module Forms
13
+ # The collaborative document every field set lives in, one per record.
14
+ DOCUMENT_NAME = "fields"
15
+
16
+ # The channel has_collaborative_fields declares for that document.
17
+ CHANNEL_NAME = "Y::Forms::FieldsChannel"
18
+
19
+ class << self
20
+ # Presence identity, called with the view context; returns { name:, color: }
21
+ # (a nil color gets a stable one derived from the name).
22
+ attr_writer :identity
23
+
24
+ def identity
25
+ @identity ||= lambda do |view|
26
+ user = view.respond_to?(:current_user) ? view.current_user : nil
27
+ # Use Anonymous when no display name is available.
28
+ name = user && %i[name username handle].lazy.filter_map { |a| user.try(a).presence }.first
29
+ { name: name || "Anonymous", color: nil }
30
+ end
31
+ end
32
+
33
+ # A stable, readable presence color per collaborator name.
34
+ def collaborator_color(name)
35
+ "hsl(#{name.to_s.each_byte.reduce(0) { |acc, b| ((acc * 31) + b) % 360 }}, 70%, 45%)"
36
+ end
37
+ end
38
+ end
39
+ end
40
+
41
+ require "y/forms/collaborative_fields"
42
+ require "y/forms/form_builder"
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yrby
4
+ module Forms
5
+ VERSION = "0.1.0.alpha1"
6
+ end
7
+ end
data/lib/yrby-forms.rb ADDED
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Entry point matching the gem name, so `Bundler.require` loads it automatically.
4
+ require "yrby/forms/version"
5
+ require "y/forms"
6
+ require "y/forms/engine" if defined?(Rails::Engine)
metadata ADDED
@@ -0,0 +1,176 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: yrby-forms
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0.alpha1
5
+ platform: ruby
6
+ authors:
7
+ - JP Camara
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: yrby
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: 0.9.0
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: 0.9.0
26
+ - !ruby/object:Gem::Dependency
27
+ name: yrby-rails
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '0.9'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '0.9'
40
+ - !ruby/object:Gem::Dependency
41
+ name: actionview
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: '7.1'
47
+ type: :runtime
48
+ prerelease: false
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: '7.1'
54
+ - !ruby/object:Gem::Dependency
55
+ name: activerecord
56
+ requirement: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: '7.1'
61
+ type: :runtime
62
+ prerelease: false
63
+ version_requirements: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: '7.1'
68
+ - !ruby/object:Gem::Dependency
69
+ name: activesupport
70
+ requirement: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: '7.1'
75
+ type: :runtime
76
+ prerelease: false
77
+ version_requirements: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - ">="
80
+ - !ruby/object:Gem::Version
81
+ version: '7.1'
82
+ - !ruby/object:Gem::Dependency
83
+ name: railties
84
+ requirement: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ - - ">="
87
+ - !ruby/object:Gem::Version
88
+ version: '7.1'
89
+ type: :runtime
90
+ prerelease: false
91
+ version_requirements: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - ">="
94
+ - !ruby/object:Gem::Version
95
+ version: '7.1'
96
+ - !ruby/object:Gem::Dependency
97
+ name: minitest
98
+ requirement: !ruby/object:Gem::Requirement
99
+ requirements:
100
+ - - "~>"
101
+ - !ruby/object:Gem::Version
102
+ version: '5.0'
103
+ type: :development
104
+ prerelease: false
105
+ version_requirements: !ruby/object:Gem::Requirement
106
+ requirements:
107
+ - - "~>"
108
+ - !ruby/object:Gem::Version
109
+ version: '5.0'
110
+ - !ruby/object:Gem::Dependency
111
+ name: rake
112
+ requirement: !ruby/object:Gem::Requirement
113
+ requirements:
114
+ - - "~>"
115
+ - !ruby/object:Gem::Version
116
+ version: '13.0'
117
+ type: :development
118
+ prerelease: false
119
+ version_requirements: !ruby/object:Gem::Requirement
120
+ requirements:
121
+ - - "~>"
122
+ - !ruby/object:Gem::Version
123
+ version: '13.0'
124
+ description: Declare attributes with has_collaborative_fields and every open form
125
+ for a record edits one yrby document. Selects, checkboxes, numbers, and dates are
126
+ last-write-wins map entries. Text fields merge concurrent typing through Y.Text.
127
+ The form helpers render yrby's <yrby-document> element and the yrby-forms npm package's
128
+ <collaborative-field>, and the gem's channel writes each change to the record's
129
+ columns.
130
+ email:
131
+ - johnpcamara@gmail.com
132
+ executables: []
133
+ extensions: []
134
+ extra_rdoc_files: []
135
+ files:
136
+ - CHANGELOG-forms.md
137
+ - LICENSE
138
+ - README-forms.md
139
+ - app/assets/javascript/yrby-forms/column.js
140
+ - app/assets/javascript/yrby-forms/column.js.map
141
+ - app/assets/javascript/yrby-forms/yrby-forms.js
142
+ - app/assets/javascript/yrby-forms/yrby-forms.js.map
143
+ - app/channels/y/forms/fields_channel.rb
144
+ - lib/y/forms.rb
145
+ - lib/y/forms/collaborative_fields.rb
146
+ - lib/y/forms/engine.rb
147
+ - lib/y/forms/form_builder.rb
148
+ - lib/yrby-forms.rb
149
+ - lib/yrby/forms/version.rb
150
+ homepage: https://github.com/jpcamara/yrby
151
+ licenses:
152
+ - MIT
153
+ metadata:
154
+ source_code_uri: https://github.com/jpcamara/yrby
155
+ changelog_uri: https://github.com/jpcamara/yrby/blob/main/CHANGELOG-forms.md
156
+ documentation_uri: https://github.com/jpcamara/yrby/blob/main/README-forms.md
157
+ bug_tracker_uri: https://github.com/jpcamara/yrby/issues
158
+ rubygems_mfa_required: 'true'
159
+ rdoc_options: []
160
+ require_paths:
161
+ - lib
162
+ required_ruby_version: !ruby/object:Gem::Requirement
163
+ requirements:
164
+ - - ">="
165
+ - !ruby/object:Gem::Version
166
+ version: 3.4.0
167
+ required_rubygems_version: !ruby/object:Gem::Requirement
168
+ requirements:
169
+ - - ">="
170
+ - !ruby/object:Gem::Version
171
+ version: '0'
172
+ requirements: []
173
+ rubygems_version: 3.6.9
174
+ specification_version: 4
175
+ summary: Collaborative form fields for Rails over yrby
176
+ test_files: []