This commit is contained in:
2026-11-23 18:42:15 +01:00
parent 978217b3be
commit 74f9a09098
24 changed files with 445 additions and 10 deletions
+7
View File
@@ -85,3 +85,10 @@ whenever a change is considered, to avoid regressions.
* assuming that user input with _precision > DIG_ is as rare as in * 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 range _(0, MIN)_, the decision is to choose input which requires
the least/simplest additional code. 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.
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" id="icon" viewBox="0 0 24 24"><path d="M6.5 10C7.3 10 8 9.3 8 8.5S7.3 7 6.5 7 5 7.7 5 8.5 5.7 10 6.5 10M9 6L16 13L11 18L4 11V6H9M9 4H4C2.9 4 2 4.9 2 6V11C2 11.6 2.2 12.1 2.6 12.4L9.6 19.4C9.9 19.8 10.4 20 11 20S12.1 19.8 12.4 19.4L17.4 14.4C17.8 14 18 13.5 18 13C18 12.4 17.8 11.9 17.4 11.6L10.4 4.6C10.1 4.2 9.6 4 9 4M13.5 5.7L14.5 4.7L21.4 11.6C21.8 12 22 12.5 22 13S21.8 14.1 21.4 14.4L16 19.8L15 18.8L20.7 13L13.5 5.7Z" /></svg>

After

Width:  |  Height:  |  Size: 473 B

+64
View File
@@ -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
+3 -1
View File
@@ -161,8 +161,10 @@ module ApplicationHelper
menu_tabs = [ menu_tabs = [
['measurements', 'scale-bathroom', :restricted], ['measurements', 'scale-bathroom', :restricted],
['quantities', 'axis-arrow', :restricted, 'right'], ['quantities', 'axis-arrow', :restricted, 'right'],
['tags', 'tag-multiple-outline', :restricted],
['units', 'weight-gram', :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], ['users', 'account-multiple-outline', :admin],
] ]
+113
View File
@@ -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
+1
View File
@@ -15,6 +15,7 @@ class User < ApplicationRecord
has_many :readouts, dependent: :delete_all has_many :readouts, dependent: :delete_all
accepts_nested_attributes_for :readouts accepts_nested_attributes_for :readouts
has_many :quantities, dependent: :delete_all has_many :quantities, dependent: :delete_all
has_many :tags, dependent: :delete_all
has_many :units, dependent: :delete_all has_many :units, dependent: :delete_all
validates :email, presence: true, uniqueness: true, validates :email, presence: true, uniqueness: true,
+15
View File
@@ -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 %>
<td style="--depth:<%= form.object.depth %>">
<%= form.text_field :label, autofocus: true, class: 'hstretch', required: true %>
<td><%= form.text_area :description, class: 'hstretch', escape: false, rows: 1 %>
<td><%= form.button %>
<td>
<%= image_link_to t(:discard), "close-outline", tags_path, class: 'dangerous',
name: :discard, onclick: render_turbo_stream('form_close', {id: attrs[:id]}) %>
<td><!-- TODO: add aria-disabled drag handle with proper vertical alignment? -->
<% end %>
<% end %>
+2
View File
@@ -0,0 +1,2 @@
<%= turbo_stream.close_form id %>
<%= turbo_stream.update :flashes %>
+24
View File
@@ -0,0 +1,24 @@
<tr id="<%= dom_target(tag) %>"
ondragstart="dragStart(event)" ondragend="dragEnd(event)"
ondragover="dragOver(event)" ondrop="drop(event)"
ondragenter="dragEnter(event)" ondragleave="dragLeave(event)"
data-drag-path="<%= reposition_tag_path(tag) %>"
data-drop-id="<%= dom_target(tag) %>"
data-drop-id-param="<%= field_name(:tag, :supertag_id) %>">
<td style="--depth:<%= tag.depth %>">
<%= link_to tag, edit_tag_path(tag), class: 'link', onclick: 'this.blur();',
data: {turbo_stream: true} %>
<td><%= tag.description %>
<% if current_user.at_least(:active) %>
<td>
<%= 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} %>
<td>
<%= image_button_to_if tag.destroyable?, t('.destroy'), 'delete-outline',
tag_path(tag), method: :delete %>
<td class="handle" draggable="true">&#x283F
<% end %>
+5
View File
@@ -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 %>
+4
View File
@@ -0,0 +1,4 @@
<% @ancestors.each do |ancestor| %>
<%= turbo_stream.replace ancestor %>
<% end %>
<%= turbo_stream.remove @tag %>
+13
View File
@@ -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 -%>
+35
View File
@@ -0,0 +1,35 @@
<div class="rightside-area buttongrid">
<% 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' %>
</div>
<table class="main-area items-table">
<caption class="hint"><%= t '.no_items' %></caption>
<tbody>
<tr>
<th class="hmintext"><%= Tag.human_attribute_name(:label) %>
<th class="hexpand"><%= Tag.human_attribute_name(:description) %>
<% if current_user.at_least(:active) %>
<th colspan="3"><%= t :actions %>
<tr id="tag_" hidden
ondragover="dragOver(event)" ondrop="drop(event)"
ondragenter="dragEnter(event)" ondragleave="dragLeave(event)"
data-drop-id="tag_" data-drop-id-param="<%= field_name(:tag, :supertag_id) %>">
<th colspan="5"><%= t '.top_level_drop' %>
<% end %>
<%= render @tags %>
<% if current_user.at_least(:active) %>
<tr id="endmark" hidden>
<tfoot>
<%= render partial: 'form', locals: {hidden: true} %>
<% end %>
</table>
+16
View File
@@ -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 %>
@@ -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 %>
+4
View File
@@ -0,0 +1,4 @@
<%= turbo_stream.close_form dom_target(:edit, @tag) %>
<% @ancestors.push(@tag).each do |ancestor| %>
<%= turbo_stream.replace ancestor %>
<% end %>
+3
View File
@@ -16,6 +16,9 @@ ActiveSupport.on_load :active_record do
ActiveModel::Validations::NumericalityValidator ActiveModel::Validations::NumericalityValidator
.prepend CoreExt::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. # Temporary patch for https://github.com/rails/rails/pull/54658.
ActiveRecord::Relation.include CoreExt::ActiveRecord::Relation ActiveRecord::Relation.include CoreExt::ActiveRecord::Relation
Arel::Crud.prepend CoreExt::Arel::Crud Arel::Crud.prepend CoreExt::Arel::Crud
+24
View File
@@ -8,6 +8,9 @@ en:
out_of_range: exceeds range of double precision floating-point format out_of_range: exceeds range of double precision floating-point format
activerecord: activerecord:
attributes: attributes:
tag:
description: Description
label: Label
quantity: quantity:
description: Description description: Description
name: Name name: Name
@@ -23,6 +26,14 @@ en:
status: Status status: Status
errors: errors:
models: 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: unit:
attributes: attributes:
base: base:
@@ -104,6 +115,19 @@ en:
taken_at_html: Measurement taken at&emsp; taken_at_html: Measurement taken at&emsp;
index: index:
new_measurement: Add measurement 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: quantities:
navigation: Quantities navigation: Quantities
quantity: quantity:
+4
View File
@@ -9,6 +9,10 @@ Rails.application.routes.draw do
member { post :reparent } member { post :reparent }
end 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 resources :units, except: [:show], path_names: {new: '(/:id)/new'} do
member { post :rebase } member { post :rebase }
end end
+24
View File
@@ -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
+20
View File
@@ -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" t.index ["user_id"], name: "index_readouts_on_user_id"
end 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| create_table "units", force: :cascade do |t|
t.integer "user_id" t.integer "user_id"
t.string "symbol", limit: 15, null: false 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", column: ["unit_id", "user_id"], primary_key: ["id", "user_id"]
add_foreign_key "readouts", "units", on_delete: :cascade add_foreign_key "readouts", "units", on_delete: :cascade
add_foreign_key "readouts", "users", 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", "units", column: "base_id", on_delete: :cascade
add_foreign_key "units", "users", on_delete: :cascade add_foreign_key "units", "users", on_delete: :cascade
end end
@@ -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
+3
View File
@@ -1,3 +1,6 @@
module CoreExt::ActiveRecord::Relation module CoreExt::ActiveRecord::Relation
ActiveRecord::Relation.class_eval do
remove_const :INVALID_METHODS_FOR_UPDATE_AND_DELETE_ALL
INVALID_METHODS_FOR_UPDATE_AND_DELETE_ALL = [:distinct] INVALID_METHODS_FOR_UPDATE_AND_DELETE_ALL = [:distinct]
end
end end
+13 -8
View File
@@ -4,14 +4,6 @@ class DefaultSettingsStrategy < ActiveRecord::Migration::DefaultStrategy
# TODO: references `foreign_key: {on_delete: :cascade}` ? # TODO: references `foreign_key: {on_delete: :cascade}` ?
# `timestamps` - Rails defaults to `null: false, precision: true`, which is # `timestamps` - Rails defaults to `null: false, precision: true`, which is
# expected. # 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} text: {limit: 2**16 - 1}
} }
COLUMN_DEFAULTS.default = {} COLUMN_DEFAULTS.default = {}
@@ -20,6 +12,19 @@ class DefaultSettingsStrategy < ActiveRecord::Migration::DefaultStrategy
module ColumnSettingsStrategy module ColumnSettingsStrategy
def column(name, type, **options) def column(name, type, **options)
super(name, type, **COLUMN_DEFAULTS[type].merge(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
end end
ActiveRecord::ConnectionAdapters::TableDefinition.prepend ColumnSettingsStrategy ActiveRecord::ConnectionAdapters::TableDefinition.prepend ColumnSettingsStrategy