diff --git a/DESIGN.md b/DESIGN.md index 4f21d8d..fb4d76b 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -85,3 +85,10 @@ whenever a change is considered, to avoid regressions. * assuming that user input with _precision > DIG_ is as rare as in the range _(0, MIN)_, the decision is to choose input which requires the least/simplest additional code. + +### Other + +* Arel usage inside models should be avoided in favor of direct query fragments. + They have similar portability and are much more readable. Anything more + complex, e.g. named functions not available in Rails should be extracted into + extensions. diff --git a/app/assets/images/tag-multiple-outline.svg b/app/assets/images/tag-multiple-outline.svg new file mode 100644 index 0000000..51d320d --- /dev/null +++ b/app/assets/images/tag-multiple-outline.svg @@ -0,0 +1 @@ + diff --git a/app/controllers/tags_controller.rb b/app/controllers/tags_controller.rb new file mode 100644 index 0000000..3ab2718 --- /dev/null +++ b/app/controllers/tags_controller.rb @@ -0,0 +1,64 @@ +class TagsController < ApplicationController + before_action ->{ @tag = current_user.tags.find_by!(id: params[:id]) }, + only: [:new, :edit, :update, :reposition, :destroy], + unless: ->{ action_name == "new" && params[:id].nil? } + + before_action except: :index do + raise AccessForbidden unless current_user.at_least(:active) + end + + def index + @tags = current_user.tags.ordered.includes(:supertag, :subtags) + end + + def new + @tag = current_user.tags.new(supertag: @tag) + end + + def create + @tag = current_user.tags.new(params.expect(Tag::ATTRIBUTES)) + if @tag.save + @before = @tag.succeeding + @ancestors = @tag.ancestors + flash.now.notice = t('.success', tag: @tag) + else + render_errors @tag + end + end + + def edit + end + + def update + if @tag.update(params.except(:supertag_id).expect(Tag::ATTRIBUTES)) + @ancestors = @tag.ancestors + flash.now.notice = t('.success', tag: @tag) + else + render_errors @tag + end + end + + def reposition + tag_params = params.expect(tag: :supertag_id) + + @prev_supertag_id = @tag.supertag_id + if @tag.update(tag_params) + @ancestors = Tag.ancestors([@prev_supertag_id, @tag.supertag_id]) + .includes(:subtags) + @tags = @tag.with_progenies.includes(:subtags) + @before = @tag.succeeding(true) + else + # Until UI blocks all disallowed repositions, render error messages if present. + flash.now.alert = @tag.errors.full_messages + render :nothing + end + end + + def destroy + @tag.destroy! + @ancestors = @tag.ancestors + flash.now.notice = t('.success', tag: @tag) + end + + private +end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 97fa6c1..6087d4c 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -161,8 +161,10 @@ module ApplicationHelper menu_tabs = [ ['measurements', 'scale-bathroom', :restricted], ['quantities', 'axis-arrow', :restricted, 'right'], + ['tags', 'tag-multiple-outline', :restricted], ['units', 'weight-gram', :restricted], - # TODO: display users tab only if >1 user present; sole_user?/sole_admin? + # TODO: display users tab only if >1 user present; sole_user?/sole_admin?; + # change status field to proc? ['users', 'account-multiple-outline', :admin], ] diff --git a/app/models/tag.rb b/app/models/tag.rb new file mode 100644 index 0000000..9f6638c --- /dev/null +++ b/app/models/tag.rb @@ -0,0 +1,113 @@ +class Tag < ApplicationRecord + ATTRIBUTES = {tag: [:label, :description, :supertag_id]} + attr_cached :depth + + belongs_to :user + belongs_to :supertag, optional: true, class_name: "Tag" + alias_method :parent, :supertag + has_many :subtags, ->{ order(:label) }, class_name: "Tag", inverse_of: :supertag, + # Database allows cascade deletion, this is application level safety net. + dependent: :restrict_with_error + #has_many :quantities, dependent: :restrict_with_error + + # TODO: try to remove validations and replace them with db constraints. + # All :supertag checks may be performed on record instead of :supertag_id, as + # record is loaded anyway by presence validator. + # Disallow #blank? (i.e. non-nil, non-existent ID) record association. + # TODO: use version below after bug fixed, https://github.com/rails/rails/issues/59879 + # validates :supertag, allow_nil: true, presence: true, comparison: {...} + validates :supertag, if: :supertag_id, presence: true, + # TODO: add check constraint + comparison: {other_than: :itself, message: :self_reference} + # TODO: add foreign key constraint tag.user == supertag.user + validates :user_id, if: :supertag_id, + comparison: {equal_to: ->(tag){ tag.supertag.user_id }, message: :user_mismatch} + validate on: :update, if: :supertag_changed? do + errors.add(:supertag, :descendant_reference) if ancestor_of?(supertag) + end + validates :label, presence: true, uniqueness: {scope: :user_id}, + length: {maximum: type_for_attribute(:label).limit} + validates :description, length: {maximum: type_for_attribute(:description).limit} + + after_initialize :update_depth, if: :new_record? + before_save :update_depth, if: :supertag_changed? + + after_update if: :depth_previously_changed? do + Tag.with_recursive(updated: [ + Tag.reselect(id: :tag_id).select(depth: :tag_depth).where(id: id), + Tag.reselect(:id, 'tag_depth + 1').joins('JOIN updated ON tag_id = supertag_id') + # JOIN could be replaced with 'FROM updated WHERE id = tag_id' if Rails + # supported UPDATE FROM, https://sqlite.org/lang_update.html#update_from + ]).joins(:updated).update_all('depth = tag_depth') + end + + def to_s + tag.pre label + end + + def to_s_with_depth + # em space, U+2003 + ' ' * depth + label + end + + def destroyable? + subtags.empty? + end + + # TODO: move to ApplicationRecord? + default_scope { select(arel_table[Arel.star]) } + + # Return: ordered [sub]hierarchy. + scope :ordered, ->(root: nil, include_root: true) { + Tag.with_recursive(ordered: [ + where(root && include_root ? :id : :supertag_id => root), + Tag.joins('JOIN ordered ON tags.supertag_id = ordered.id') + .order(depth: :desc, label: :asc) + ]).from('ordered AS tags') + } + + # Return: ancestors of `leaf(s)`, inclusive. + scope :ancestors, ->(leafs) { + return none if leafs.nil? + Tag.with_recursive(ancestors: [ + Tag.where(id: leafs), + Tag.joins('JOIN ancestors ON tags.id = ancestors.supertag_id') + ]).from('ancestors AS tags') + } + + # Return: succeeding record in order of appearance. Used for partial view reload. + def succeeding(subtree = false) + # Recursive SELECT cannot use window functions. WHERE is evaluated before + # window function in SELECT - requires use of subquery. + # This is more compact, but probably less efficient version. Also it doesn't + # support `subtree` option. May be freely removed, or replace longer version. + #Tag.from(user.tags.ordered.select.lag(:id), :tags).where(lag_id: id).take + + Tag.from( + # NULL default causes children of self to be skipped (label comparison fails). + Tag.ancestors(id).select.lag(:label, default: subtree ? nil : ''), :left + ).joins(' + JOIN tags ON (left.id = tags.supertag_id AND left.lag_label < tags.label) OR + (left.supertag_id IS NULL AND tags.supertag_id IS NULL AND left.label < tags.label) + ').order(depth: :desc, label: :asc).take + end + + # Return: ancestors of (possibly destroyed) self. + def ancestors + Tag.ancestors(supertag_id).order(:depth) + end + + def with_progenies + user.tags.ordered(root: id) + end + + def ancestor_of?(progeny) + Tag.ancestors(progeny.respond_to?(:id) ? progeny.id : progeny).exists?(id) + end + + private + + def update_depth + self[:depth] = supertag&.depth&.succ || 0 + end +end diff --git a/app/models/user.rb b/app/models/user.rb index 0de9460..480d046 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -15,6 +15,7 @@ class User < ApplicationRecord has_many :readouts, dependent: :delete_all accepts_nested_attributes_for :readouts has_many :quantities, dependent: :delete_all + has_many :tags, dependent: :delete_all has_many :units, dependent: :delete_all validates :email, presence: true, uniqueness: true, diff --git a/app/views/tags/_form.html.erb b/app/views/tags/_form.html.erb new file mode 100644 index 0000000..1061f5d --- /dev/null +++ b/app/views/tags/_form.html.erb @@ -0,0 +1,15 @@ +<%# locals: (record: Tag.new, **attrs) %> +<%= tabular_fields_for record, form: attrs.dig(:data, :form) do |form| %> + <%- tag.tr class: "form", onkeydown: "formProcessKey(event)", **attrs do %> + + + <%= form.text_field :label, autofocus: true, class: 'hstretch', required: true %> + <%= form.text_area :description, class: 'hstretch', escape: false, rows: 1 %> + + <%= form.button %> + + <%= image_link_to t(:discard), "close-outline", tags_path, class: 'dangerous', + name: :discard, onclick: render_turbo_stream('form_close', {id: attrs[:id]}) %> + + <% end %> +<% end %> diff --git a/app/views/tags/_form_close.html.erb b/app/views/tags/_form_close.html.erb new file mode 100644 index 0000000..1754e10 --- /dev/null +++ b/app/views/tags/_form_close.html.erb @@ -0,0 +1,2 @@ +<%= turbo_stream.close_form id %> +<%= turbo_stream.update :flashes %> diff --git a/app/views/tags/_tag.html.erb b/app/views/tags/_tag.html.erb new file mode 100644 index 0000000..4ab2ceb --- /dev/null +++ b/app/views/tags/_tag.html.erb @@ -0,0 +1,24 @@ + + + + <%= link_to tag, edit_tag_path(tag), class: 'link', onclick: 'this.blur();', + data: {turbo_stream: true} %> + <%= tag.description %> + + <% if current_user.at_least(:active) %> + + <%= image_link_to t('.new_subtag'), 'plus-outline', new_tag_path(tag), + id: dom_target(:new, tag, :link), onclick: 'this.blur();', + data: {turbo_stream: true} %> + + <%= image_button_to_if tag.destroyable?, t('.destroy'), 'delete-outline', + tag_path(tag), method: :delete %> + + ⠿ + <% end %> diff --git a/app/views/tags/create.turbo_stream.erb b/app/views/tags/create.turbo_stream.erb new file mode 100644 index 0000000..d50c04a --- /dev/null +++ b/app/views/tags/create.turbo_stream.erb @@ -0,0 +1,5 @@ +<%= turbo_stream.close_form dom_target(:new, @tag.supertag || :tag) %> +<% @ancestors.each do |ancestor| %> + <%= turbo_stream.replace ancestor %> +<% end %> +<%= turbo_stream.before @before || :endmark, @tag %> diff --git a/app/views/tags/destroy.turbo_stream.erb b/app/views/tags/destroy.turbo_stream.erb new file mode 100644 index 0000000..9da5cb6 --- /dev/null +++ b/app/views/tags/destroy.turbo_stream.erb @@ -0,0 +1,4 @@ +<% @ancestors.each do |ancestor| %> + <%= turbo_stream.replace ancestor %> +<% end %> +<%= turbo_stream.remove @tag %> diff --git a/app/views/tags/edit.turbo_stream.erb b/app/views/tags/edit.turbo_stream.erb new file mode 100644 index 0000000..8fef174 --- /dev/null +++ b/app/views/tags/edit.turbo_stream.erb @@ -0,0 +1,13 @@ +<% attrs = {record: @tag, + id: dom_target(:edit, @tag), + data: {form: dom_target(:edit, @tag, :form), + hidden_row: dom_target(@tag), + link: nil}} %> + +<%= turbo_stream.append_all 'body' do %> + <%- tabular_form_with model: @tag, html: {id: attrs[:data][:form]} do %> + <% end %> +<% end %> + +<%= turbo_stream.hide attrs[:data][:hidden_row] %> +<%= turbo_stream.after @tag, partial: 'form', locals: attrs -%> diff --git a/app/views/tags/index.html.erb b/app/views/tags/index.html.erb new file mode 100644 index 0000000..d836833 --- /dev/null +++ b/app/views/tags/index.html.erb @@ -0,0 +1,35 @@ +
+ <% if current_user.at_least(:active) %> + <%= image_link_to t('.new_tag'), 'plus-outline', new_tag_path, id: :new_tag_link, + onclick: 'this.blur();', data: {turbo_stream: true} %> + <% end %> + <%#= image_link_to t('.import_tags'), 'download-outline', default_tags_path, + class: 'tools-area' %> +
+ + + + + + + + + + + <%= render partial: 'form', locals: {hidden: true} %> + <% end %> +
<%= t '.no_items' %>
<%= Tag.human_attribute_name(:label) %> + <%= Tag.human_attribute_name(:description) %> + <% if current_user.at_least(:active) %> + <%= t :actions %> + +
diff --git a/app/views/tags/new.turbo_stream.erb b/app/views/tags/new.turbo_stream.erb new file mode 100644 index 0000000..fd752d8 --- /dev/null +++ b/app/views/tags/new.turbo_stream.erb @@ -0,0 +1,16 @@ +<% target_id = dom_target(:new, @tag.supertag || :tag) %> +<% attrs = {record: @tag, + id: target_id, + data: {form: dom_target(target_id, :form), + hidden_row: nil, + link: dom_target(target_id, :link)}} %> + +<%= turbo_stream.disable attrs[:data][:link] -%> + +<%= turbo_stream.append_all 'body' do %> + <%- tabular_form_with model: @tag, html: {id: attrs[:data][:form]} do |form| %> + <%= form.hidden_field :supertag_id if @tag.supertag_id? %> + <% end %> +<% end %> + +<%= turbo_stream.after @tag.supertag || :tag_, partial: 'form', locals: attrs %> diff --git a/app/views/tags/reposition.turbo_stream.erb b/app/views/tags/reposition.turbo_stream.erb new file mode 100644 index 0000000..c3655fd --- /dev/null +++ b/app/views/tags/reposition.turbo_stream.erb @@ -0,0 +1,7 @@ +<% @ancestors.each do |ancestor| %> + <%= turbo_stream.replace ancestor %> +<% end %> +<% @tags.each do |tag| %> + <%= turbo_stream.remove tag %> + <%= turbo_stream.before @before || :endmark, tag %> +<% end %> diff --git a/app/views/tags/update.turbo_stream.erb b/app/views/tags/update.turbo_stream.erb new file mode 100644 index 0000000..0193b77 --- /dev/null +++ b/app/views/tags/update.turbo_stream.erb @@ -0,0 +1,4 @@ +<%= turbo_stream.close_form dom_target(:edit, @tag) %> +<% @ancestors.push(@tag).each do |ancestor| %> + <%= turbo_stream.replace ancestor %> +<% end %> diff --git a/config/initializers/core_ext.rb b/config/initializers/core_ext.rb index 4752387..73c829f 100644 --- a/config/initializers/core_ext.rb +++ b/config/initializers/core_ext.rb @@ -16,6 +16,9 @@ ActiveSupport.on_load :active_record do ActiveModel::Validations::NumericalityValidator .prepend CoreExt::ActiveModel::Validations::NumericalityValidator + # SELECT using window functions through SelectChain. + ActiveRecord::Relation.include CoreExt::ActiveRecord::QueryMethods + # Temporary patch for https://github.com/rails/rails/pull/54658. ActiveRecord::Relation.include CoreExt::ActiveRecord::Relation Arel::Crud.prepend CoreExt::Arel::Crud diff --git a/config/locales/en.yml b/config/locales/en.yml index abe8396..630667a 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -8,6 +8,9 @@ en: out_of_range: exceeds range of double precision floating-point format activerecord: attributes: + tag: + description: Description + label: Label quantity: description: Description name: Name @@ -23,6 +26,14 @@ en: status: Status errors: models: + tag: + attributes: + name: + taken: has to be unique + supertag: + descendant_reference: cannot be changed to any of descendants + self_reference: of the tag cannot be the tag itself + user_mismatch: has to belong to the same user as tag unit: attributes: base: @@ -104,6 +115,19 @@ en: taken_at_html: Measurement taken at  index: new_measurement: Add measurement + tags: + navigation: Tags + tag: + new_subtag: Subtag + index: + new_tag: Add tag + no_items: There are no configured tags. You can Add some or Import from defaults. + create: + success: Created new tag "%{tag}" + update: + success: Updated tag "%{tag}" + destroy: + success: Deleted tag "%{tag}" quantities: navigation: Quantities quantity: diff --git a/config/routes.rb b/config/routes.rb index 9a1b623..16f4542 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -9,6 +9,10 @@ Rails.application.routes.draw do member { post :reparent } end + resources :tags, except: [:show], path_names: {new: '(/:id)/new'} do + member { post :reposition } + end + resources :units, except: [:show], path_names: {new: '(/:id)/new'} do member { post :rebase } end diff --git a/db/migrate/20261107214900_create_tags.rb b/db/migrate/20261107214900_create_tags.rb new file mode 100644 index 0000000..4971f05 --- /dev/null +++ b/db/migrate/20261107214900_create_tags.rb @@ -0,0 +1,24 @@ +class CreateTags < ActiveRecord::Migration[8.1] + def change + create_table :tags do |t| + t.references :user, null: false, foreign_key: {on_delete: :cascade} + t.string :label, null: false, limit: 2**5 + t.text :description, limit: 2**16 + t.references :supertag, foreign_key: {to_table: :tags, on_delete: :cascade} + t.timestamps + # Cached, computed from other attributes. NULL default to ensure value + # has been properly initialized. + t.integer :depth, null: false + + # Constraints: + # * label has to be unique + t.index [:user_id, :label], unique: true + # * supertag cannot reference self + t.check_constraint 'id != supertag_id', name: :self_reference + # * supertag has to belong to the same user as tag + t.index [:id, :user_id], unique: true + t.foreign_key :tags, primary_key: [:id, :user_id], + column: [:supertag_id, :user_id], name: :user_mismatch + end + end +end diff --git a/db/schema.rb b/db/schema.rb index 0d1533a..afedf4d 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -57,6 +57,23 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_07_214900) do t.index ["user_id"], name: "index_readouts_on_user_id" end + create_table "tags", force: :cascade do |t| + t.integer "user_id", null: false + t.string "label", limit: 32, null: false + t.text "description", limit: 65536 + t.integer "supertag_id" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.integer "depth", null: false + t.index ["id", "user_id"], name: "index_tags_on_id_and_user_id", unique: true + t.index ["supertag_id"], name: "index_tags_on_supertag_id" + t.index ["user_id", "label"], name: "index_tags_on_user_id_and_label", unique: true + t.index ["user_id"], name: "index_tags_on_user_id" + t.check_constraint "id != supertag_id", name: "self_reference" + t.check_constraint "length(description) <= 65536", name: "description_length" + t.check_constraint "length(label) <= 32", name: "label_length" + end + create_table "units", force: :cascade do |t| t.integer "user_id" t.string "symbol", limit: 15, null: false @@ -98,6 +115,9 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_07_214900) do add_foreign_key "readouts", "units", column: ["unit_id", "user_id"], primary_key: ["id", "user_id"] add_foreign_key "readouts", "units", on_delete: :cascade add_foreign_key "readouts", "users", on_delete: :cascade + add_foreign_key "tags", "tags", column: "supertag_id", on_delete: :cascade + add_foreign_key "tags", "tags", column: ["supertag_id", "user_id"], primary_key: ["id", "user_id"] + add_foreign_key "tags", "users", on_delete: :cascade add_foreign_key "units", "units", column: "base_id", on_delete: :cascade add_foreign_key "units", "users", on_delete: :cascade end diff --git a/lib/core_ext/active_record/query_methods.rb b/lib/core_ext/active_record/query_methods.rb new file mode 100644 index 0000000..a510b71 --- /dev/null +++ b/lib/core_ext/active_record/query_methods.rb @@ -0,0 +1,39 @@ +module CoreExt::ActiveRecord::QueryMethods + class SelectChain + def initialize(scope) + @scope = scope + end + + def lag(expr, offset: 1, default: nil) + case expr + when Hash + when Symbol + expr = {expr => "lag_#{expr}"} + else + raise ArgumentError, "Unsupported expression argument type: #{expr.class.name}." + end + + expr.each do |column, column_alias| + @scope._select!( + Arel::Nodes::NamedFunction.new( + 'LAG', + [@scope.table[column], offset, Arel::Nodes.build_quoted(default)] + ).over().as(column_alias) + ) + end + + @scope + end + end + + def self.included(base) + base.prepend SelectWithSelectChain + end +end + +module SelectWithSelectChain + def select(*fields) + return super if !fields.empty? || block_given? + ActiveRecord::Relation::SelectChain.new(spawn) + end +end diff --git a/lib/core_ext/active_record/relation.rb b/lib/core_ext/active_record/relation.rb index 012bd6c..0f14bf4 100644 --- a/lib/core_ext/active_record/relation.rb +++ b/lib/core_ext/active_record/relation.rb @@ -1,3 +1,6 @@ module CoreExt::ActiveRecord::Relation - INVALID_METHODS_FOR_UPDATE_AND_DELETE_ALL = [:distinct] + ActiveRecord::Relation.class_eval do + remove_const :INVALID_METHODS_FOR_UPDATE_AND_DELETE_ALL + INVALID_METHODS_FOR_UPDATE_AND_DELETE_ALL = [:distinct] + end end diff --git a/lib/default_settings_strategy.rb b/lib/default_settings_strategy.rb index df80bf1..67308c5 100644 --- a/lib/default_settings_strategy.rb +++ b/lib/default_settings_strategy.rb @@ -4,14 +4,6 @@ class DefaultSettingsStrategy < ActiveRecord::Migration::DefaultStrategy # TODO: references `foreign_key: {on_delete: :cascade}` ? # `timestamps` - Rails defaults to `null: false, precision: true`, which is # expected. - # `limit:` for `text` - `text` can be theoretically up to 1GB or - # longer, so roughly unlimited for practical purposes. But: - # * the actual usable length depends on additional factors, like compile - # time limits (`SQLITE_MAX_LENGTH` in SQLite) and probably other, - # * Rails does not report limit for `text` column types, unless it is - # explicitly set. - # The decision is to always set safe limit and enforce it by validations, to - # avoid surprises (e.g. text truncation) when saving to dabatase. text: {limit: 2**16 - 1} } COLUMN_DEFAULTS.default = {} @@ -20,6 +12,19 @@ class DefaultSettingsStrategy < ActiveRecord::Migration::DefaultStrategy module ColumnSettingsStrategy def column(name, type, **options) super(name, type, **COLUMN_DEFAULTS[type].merge(options)) + # SQLite does not enforce `limit` on string/text columns by default. + # `text` can be theoretically up to 1GB or longer, so roughly unlimited + # for practical purposes. But the actual usable length depends on + # additional factors, like compile time limits (`SQLITE_MAX_LENGTH` in + # SQLite) and probably other. + # Limit is explicitly set to: + # a) be used by views/UI (Rails does not report limit for `text` column + # types, unless it is explicitly set) and + # b) be enforced by database constraint (below). + # Length constraint is measured in codepoints (not bytes). + if options[:limit] && [:string, :text].include?(type) + check_constraint("length(#{name}) <= #{options[:limit]}", name: "#{name}_length") + end end end ActiveRecord::ConnectionAdapters::TableDefinition.prepend ColumnSettingsStrategy