tiun 0.1.0 → 0.2.0

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.
Files changed (63) hide show
  1. checksums.yaml +4 -4
  2. data/docs/components/images.md +34 -4
  3. data/docs/components/images.ru.md +33 -4
  4. data/docs/components/login.md +2 -0
  5. data/docs/components/login.ru.md +2 -0
  6. data/docs/components/profile.md +3 -1
  7. data/docs/components/profile.ru.md +3 -1
  8. data/docs/components/schema-records.md +2 -0
  9. data/docs/components/schema-records.ru.md +2 -0
  10. data/docs/components/signup.md +3 -1
  11. data/docs/components/signup.ru.md +3 -1
  12. data/docs/components/theme.md +3 -1
  13. data/docs/components/theme.ru.md +3 -1
  14. data/docs/reference.ru.md +6 -6
  15. data/lib/config/locale/ru.yml +0 -3
  16. data/lib/tiun/auth/token_identity.rb +9 -0
  17. data/lib/tiun/controller/auth/identity.rb +78 -19
  18. data/lib/tiun/controller/auth/registration.rb +23 -0
  19. data/lib/tiun/controller/auth.rb +4 -4
  20. data/lib/tiun/controller/base/representation.rb +12 -1
  21. data/lib/tiun/mailer/confirmation.rb +10 -2
  22. data/lib/tiun/model/account.rb +79 -3
  23. data/lib/tiun/model/auth.rb +2 -0
  24. data/lib/tiun/model/me.rb +83 -2
  25. data/lib/tiun/model/settings.rb +7 -0
  26. data/lib/tiun/model/token.rb +2 -2
  27. data/lib/tiun/proceed/schemas/constants.rb +1 -0
  28. data/lib/tiun/proceed/schemas/spans.rb +1 -0
  29. data/lib/tiun/routes/mounts.rb +7 -4
  30. data/lib/tiun/service/email_confirmation.rb +84 -12
  31. data/lib/tiun/version.rb +1 -1
  32. data/package-lock.json +2 -2
  33. data/package.json +1 -1
  34. data/src/components/Component.tsx +4 -1
  35. data/src/components/Image.tsx +36 -25
  36. data/src/components/Index.tsx +193 -24
  37. data/src/components/Loader.tsx +11 -9
  38. data/src/components/Lorem.tsx +7 -1
  39. data/src/components/Modal.tsx +8 -1
  40. data/src/components/Paginator.tsx +9 -3
  41. data/src/components/Records.tsx +45 -18
  42. data/src/components/calendar-browser.scss +14 -4
  43. data/src/components/form/Login.tsx +12 -6
  44. data/src/components/form/auth.scss +44 -130
  45. data/src/components/form/forms.scss +9 -8
  46. data/src/components/form/types.ts +2 -0
  47. data/src/components/image.scss +10 -7
  48. data/src/components/records.scss +4 -0
  49. data/src/components/theme-palettes/dark.scss +1 -0
  50. data/src/concern/application.ts +3 -2
  51. data/src/concern/spansViewProps.tsx +14 -1
  52. data/src/concern/useRecordsResource.ts +2 -0
  53. data/src/decorators/withField.tsx +10 -7
  54. data/src/decorators/withForm.tsx +12 -6
  55. data/src/schema/Schema.ts +10 -0
  56. data/src/services/calendar/daylight.ts +31 -4
  57. data/src/services/methods.ts +1 -1
  58. data/src/services/records/useRecordPages.ts +23 -3
  59. data/src/services/session/renewal.ts +69 -6
  60. data/src/services/useAppearance.ts +22 -11
  61. data/src/services/useSwitch.ts +23 -17
  62. data/src/theme/configuration.ts +21 -7
  63. metadata +2 -2
@@ -2,6 +2,7 @@
2
2
 
3
3
  require 'bigdecimal'
4
4
  require 'tiun/model'
5
+ require 'uri'
5
6
 
6
7
  # Реквизиты учётной записи и опознание пользователя по паролю.
7
8
  module Tiun::Model::Account
@@ -11,12 +12,13 @@ module Tiun::Model::Account
11
12
 
12
13
  TEXT_IDENTITIES = %w[Email Uid].freeze
13
14
  PHONE_IDENTITIES = %w[Phone Telegram].freeze
15
+ EMAIL_APPROVAL_PERIOD = 3.days
14
16
 
15
17
  # Опознаёт пользователя по обычному или одноразовому паролю этой учётной записи.
16
18
  # @param password [String] Пароль из запроса входа.
17
19
  # @return [Object] Опознанный пользователь.
18
20
  def authenticated_user! password
19
- if !is_email_confirmation_pending? && password.is_a?(String)
21
+ if !is_obsoleted? && !is_email_confirmation_pending? && password.is_a?(String)
20
22
  return user if user.match_password?(password)
21
23
 
22
24
  recovered = Token::PasswordRecovery.consume_password(password, self)
@@ -30,6 +32,7 @@ module Tiun::Model::Account
30
32
  # Отправляет временный пароль либо повторное подтверждение почтовой учётки.
31
33
  # @return [Boolean] true после отправки письма либо false без адреса или при отключённой доставке.
32
34
  def recover_password!
35
+ return false if is_obsoleted?
33
36
  return resend_email_confirmation! if is_email_confirmation_pending?
34
37
 
35
38
  address = recovery_email
@@ -55,7 +58,57 @@ module Tiun::Model::Account
55
58
  # @param owner [Object] Пользователь, которому выдан сеанс.
56
59
  # @return [Boolean, nil] Результат записи либо nil при отсутствии подтверждения.
57
60
  def confirm_email_for! owner
58
- update!(email_confirmation_pending: false) if user_id == owner.id && is_email_confirmation_pending?
61
+ with_lock do
62
+ update!(email_confirmation_pending: false) if user_id == owner.id && is_email_confirmation_pending?
63
+ end
64
+ end
65
+
66
+ # Проверяет, подтверждена ли учётка, заменившая текущую.
67
+ # Параметров нет; учитывает существование столбца в приложении.
68
+ # @return [Boolean] true, если старые реквизиты уже отключены.
69
+ def is_obsoleted?
70
+ return false unless has_attribute?(:obsoleted_by_id) && obsoleted_by_id
71
+
72
+ obsoleted_by&.email_confirmation_pending == false
73
+ end
74
+
75
+ # Создаёт новую почтовую учётку взамен текущей, сохраняя старую до подтверждения.
76
+ # - Повторный запрос того же адреса возвращает существующий токен.
77
+ # @param address [String] Новый почтовый адрес.
78
+ # @return [Token::Validate, nil] Токен подтверждения или nil при отсутствии изменения.
79
+ def begin_email_replacement! address
80
+ address = address.to_s.strip
81
+ return if no == address
82
+
83
+ with_lock do
84
+ if is_email_confirmation_pending? || is_obsoleted? || !address.match?(URI::MailTo::EMAIL_REGEXP)
85
+ errors.add(:no, :invalid)
86
+ raise ActiveRecord::RecordInvalid.new(self)
87
+ end
88
+
89
+ replacement = obsoleted_by
90
+ if replacement
91
+ token = replacement.validate_token
92
+ return token if replacement.no == address && token&.expires_at&.future?
93
+
94
+ errors.add(:no, :invalid)
95
+ raise ActiveRecord::RecordInvalid.new(self)
96
+ end
97
+
98
+ replacement = self.class.create!(user: user, no: address, email_confirmation_pending: true)
99
+ update!(obsoleted_by: replacement)
100
+ replacement.limit_email_confirmation!
101
+ end
102
+ rescue ActiveRecord::RecordNotUnique
103
+ errors.add(:no, :taken)
104
+ raise ActiveRecord::RecordInvalid.new(self)
105
+ end
106
+
107
+ # Ограничивает действие токена новой почтовой учётки тремя днями.
108
+ # Параметров нет; использует токен, выпущенный при создании учётки.
109
+ # @return [Token::Validate] Обновлённый токен подтверждения.
110
+ def limit_email_confirmation!
111
+ validate_token.tap {|token| token.update!(expires_at: EMAIL_APPROVAL_PERIOD.from_now) }
59
112
  end
60
113
 
61
114
  def validate_token
@@ -81,6 +134,12 @@ module Tiun::Model::Account
81
134
  token =
82
135
  with_lock do
83
136
  if is_email_confirmation_pending?
137
+ issued = validate_token
138
+ if issued&.expires_at&.past? && has_attribute?(:obsoleted_by_id) &&
139
+ self.class.base_class.exists?(obsoleted_by_id: id)
140
+ return false
141
+ end
142
+
84
143
  Token::Validate.actual.find_by(tokenable: self,
85
144
  obsoleted_at: nil) || Token::Validate.create!(tokenable: self)
86
145
  end
@@ -98,7 +157,9 @@ module Tiun::Model::Account
98
157
  def recovery_email
99
158
  address_type = Tiun::Model::Account.email_type_for(self.class)
100
159
 
101
- type == address_type ? no : user.accounts.find_by(type: address_type)&.no
160
+ return no if type == address_type
161
+
162
+ user.accounts.where(type: address_type).find {|account| !account.is_obsoleted? && !account.is_email_confirmation_pending? }&.no
102
163
  end
103
164
 
104
165
  class << self
@@ -179,10 +240,25 @@ module Tiun::Model::Account
179
240
  def included kls
180
241
  kls.module_eval do
181
242
  belongs_to(:user)
243
+ belongs_to(:obsoleted_by, class_name: kls.name, optional: true)
182
244
  has_many(:tokina, as: :tokenable)
183
245
  has_many(:session_tokina, class_name: 'Token::Session', as: :tokenable)
184
246
  has_many(:refresh_tokina, class_name: 'Token::Refresh', as: :tokenable)
185
247
 
248
+ # Выбирает подтверждённые почтовые учётки, действующие у пользователя.
249
+ # Параметров нет.
250
+ # @return [ActiveRecord::Relation] Действующие адреса для правки.
251
+ scope :current_addresses, lambda {
252
+ kind = Tiun::Model::Account.email_type_for(klass)
253
+ emails = where(type: kind)
254
+ emails = emails.where(email_confirmation_pending: [false, nil]) if
255
+ klass.attribute_names.include?('email_confirmation_pending')
256
+ return emails unless klass.attribute_names.include?('obsoleted_by_id')
257
+
258
+ pending = klass.unscoped.where(email_confirmation_pending: true).select(:id)
259
+ emails.where(obsoleted_by_id: nil).or(emails.where(obsoleted_by_id: pending))
260
+ }
261
+
186
262
  after_create(:create_validate_token)
187
263
  end
188
264
  end
@@ -9,6 +9,8 @@ module Tiun::Model::Auth
9
9
  class InvalidTokenError < StandardError; end
10
10
 
11
11
  attr_reader :password, :password_confirmation
12
+ # Локальный адрес возврата для письма этой регистрации. В базу не записывается.
13
+ attr_accessor :registration_return_path
12
14
 
13
15
  def password_confirmation= value
14
16
  @password_confirmation = value
data/lib/tiun/model/me.rb CHANGED
@@ -5,9 +5,16 @@ module Tiun::Model::Me
5
5
  extend ActiveSupport::Concern
6
6
 
7
7
  included do
8
- has_one(:email, class_name: 'Account::Email')
8
+ has_one(:email, -> { current_addresses }, class_name: 'Account::Email')
9
+ has_many(:email_changes, -> { current_addresses }, class_name: 'Account', foreign_key: :user_id)
10
+ accepts_nested_attributes_for(:email_changes)
9
11
  before_validation(:fill_in_account)
10
12
 
13
+ # Запоминает разрешённые поля почтовых строк до выполнения PATCH.
14
+ # @param rows [Array<Hash>, Hash] Новые адреса и идентификаторы заменяемых учёток.
15
+ # @return [Array<Hash>, Hash] Переданные строки.
16
+ define_method(:email_changes_attributes=) {|rows| @requested_email_changes = rows }
17
+
11
18
  scope :by_uno, lambda {|identifier|
12
19
  if /\A\d+\z/.match?(identifier.to_s)
13
20
  where(primary_key => identifier)
@@ -78,8 +85,15 @@ module Tiun::Model::Me
78
85
  def account_projection_fields account, only, table
79
86
  fields = only ? only.map(&:to_s) & account.attribute_names : account.attribute_names
80
87
  columns = fields.map {|field| "#{table}.#{connection.quote_column_name(field)}" }
88
+ validated =
89
+ if account.attribute_names.include?('email_confirmation_pending')
90
+ email_type = connection.quote(Tiun::Model::Account.email_type_for(account))
91
+ "#{table}.type = #{email_type} AND #{table}.email_confirmation_pending IS NOT TRUE AS validated"
92
+ else
93
+ 'FALSE AS validated'
94
+ end
81
95
 
82
- (columns + ['FALSE AS validated']).join(', ')
96
+ (columns + [validated]).join(', ')
83
97
  end
84
98
  end
85
99
 
@@ -130,4 +144,71 @@ module Tiun::Model::Me
130
144
  accounts.build(attributes)
131
145
  end
132
146
  end
147
+
148
+ # Выдаёт идентификаторы токенов для почтовой службы после успешного сохранения.
149
+ # Параметров нет.
150
+ # @return [Array<Integer>, nil] Снимок изменений адресов текущего запроса.
151
+ attr_reader :email_change_token_ids
152
+
153
+ # Учитывает назначенные строки почты при проверке вложенных изменений профиля.
154
+ # - Строки сохраняются в PATCH, поэтому до него не изменяют столбцы пользователя.
155
+ # Параметров нет.
156
+ # @return [Boolean] Есть ли изменения, которые запрос ещё должен сохранить.
157
+ def changed_for_autosave?
158
+ @requested_email_changes.present? || super
159
+ end
160
+
161
+ # Сохраняет почтовые изменения одного пользователя под блокировкой строки.
162
+ # - Остальные PATCH передаёт модели приложения.
163
+ # Параметров нет; использует назначенные строки почтовой формы.
164
+ # @return [User] Пользователь после проверки и сохранения изменений.
165
+ def patch!
166
+ return super if @requested_email_changes.nil? && defined?(super)
167
+
168
+ unless @requested_email_changes
169
+ errors.add(:base, :invalid)
170
+ raise ActiveRecord::RecordInvalid.new(self)
171
+ end
172
+
173
+ rows = @requested_email_changes
174
+ rows = rows.values if rows.is_a?(Hash)
175
+ with_lock do
176
+ @email_change_token_ids = rows.filter_map {|row| change_email(row)&.id }
177
+ end
178
+ @requested_email_changes = nil
179
+ self
180
+ end
181
+
182
+ private
183
+
184
+ # Добавляет адрес либо меняет текущую собственную почтовую запись.
185
+ # @param row [Hash] Идентификатор старой записи и новый адрес.
186
+ # @return [Token::Validate, nil] Подтверждение нового адреса или nil при отсутствии правки.
187
+ def change_email row
188
+ address = row.fetch('no', '').to_s.strip
189
+ if row['id'].present?
190
+ return email_changes.find(row['id']).begin_email_replacement!(address)
191
+ end
192
+ return if address.empty?
193
+
194
+ unless address.match?(URI::MailTo::EMAIL_REGEXP)
195
+ errors.add(:email_changes, :invalid)
196
+ raise ActiveRecord::RecordInvalid.new(self)
197
+ end
198
+
199
+ kind = Tiun::Model::Account.email_type_for(accounts.klass)
200
+ if (existing = accounts.find_by(type: kind, no: address))
201
+ token = existing.validate_token
202
+ return token if existing.email_confirmation_pending == true && token&.expires_at&.future?
203
+ return unless existing.is_obsoleted?
204
+
205
+ errors.add(:email_changes, :taken)
206
+ raise ActiveRecord::RecordInvalid.new(self)
207
+ end
208
+
209
+ accounts.create!(type: kind, no: address, email_confirmation_pending: true).limit_email_confirmation!
210
+ rescue ActiveRecord::RecordNotUnique
211
+ errors.add(:email_changes, :taken)
212
+ raise ActiveRecord::RecordInvalid.new(self)
213
+ end
133
214
  end
@@ -54,6 +54,13 @@ module Tiun::Model::Settings
54
54
  end
55
55
  end
56
56
 
57
+ # Возвращает поля оформления для ответа текущего пользователя.
58
+ # Параметров нет. Каждое поле использует штатную проверку и значение по умолчанию.
59
+ # @return [Hash] Объявленные настройки оформления текущего пользователя.
60
+ def appearance
61
+ tiun_appearance_rules.keys.to_h {|key| [key, appearance_value(key)] }
62
+ end
63
+
57
64
  # Сохраняет заданные поля оформления независимо от валидации прочего профиля.
58
65
  # Параметров нет. Строка блокируется перед слиянием с имеющимися настройками.
59
66
  # @return [ActiveRecord::Base] Перезагруженная запись.
@@ -7,8 +7,8 @@ module Tiun::Model::Token
7
7
  autoload :Recovery, 'tiun/model/token/recovery'
8
8
 
9
9
  DEFAULT_LIFETIMES = {
10
- session: { days: 1 }.freeze,
11
- refresh: { months: 6 }.freeze,
10
+ session: { months: 6 }.freeze,
11
+ refresh: { months: 18 }.freeze,
12
12
  validate: { days: 1 }.freeze
13
13
  }.freeze
14
14
 
@@ -15,6 +15,7 @@ module Tiun::Proceed::Schemas::Constants
15
15
  IMAGE_VIEW_CHECKS = {
16
16
  native: ->(value) { BOOLEAN_VALUES.include?(value) },
17
17
  view_as: ->(value) { %w[plain card].include?(value) },
18
+ reserve_space: ->(value) { value == true || value == false },
18
19
  description: ->(value) { value.is_a?(String) },
19
20
  on_click: ->(value) { value.is_a?(String) },
20
21
  **%i[width height].to_h do |key|
@@ -16,6 +16,7 @@ module Tiun::Proceed::Schemas::Spans
16
16
  range_unit: ->(value) { %w[pages records].include?(value) },
17
17
  button_style: ->(value) { %w[text circle].include?(value) },
18
18
  kind: ->(value) { %w[hidden button].include?(value) },
19
+ show_loading: ->(value) { BOOLEAN_VALUES.include?(value) },
19
20
  autoload_upto: ->(value) { value.is_a?(Integer) && value.positive? },
20
21
  per: ->(value) { value.is_a?(Integer) && value.positive? && value <= 1000 }
21
22
  }.freeze
@@ -71,10 +71,13 @@ module Tiun::Routes::Mounts
71
71
  false
72
72
  end
73
73
 
74
- # Отдаёт отказ вместо вызова обработчика защищённого вида.
75
- # @param _environment [Hash] Окружение запроса Rack.
76
- # @return [Array] Ответ HTTP 403 с переводом причины.
77
- def forbidden_mount _environment
74
+ # Возвращает браузер на корень при отказе в доступе к HTML-виду.
75
+ # Если защищён сам корень, возвращает HTTP 403 без перенаправления.
76
+ # @param environment [Hash] Окружение запроса Rack.
77
+ # @return [Array] Переход на корень либо ответ с переводом причины отказа.
78
+ def forbidden_mount environment
79
+ return [302, { 'location' => '/' }, []] unless environment['PATH_INFO'] == '/'
80
+
78
81
  [403, { 'content-type' => 'text/plain; charset=utf-8' }, [I18n.t('tiun.defaults.errors.403.name')]]
79
82
  end
80
83
 
@@ -4,33 +4,105 @@
4
4
  class Tiun::Service::EmailConfirmation
5
5
  include Tiun::Service
6
6
 
7
- # Оставляет в событии регистрации только идентификатор и класс записи.
8
- # @param _record [ActiveRecord::Base] Запись пользователя.
9
- # @return [nil] Снимок не нужен для отправки письма.
10
- def self.post_action_snapshot _record
11
- nil
7
+ class << self
8
+ # Передаёт адрес возврата из регистрации в задание отправки письма.
9
+ # @param record [ActiveRecord::Base] Запись пользователя.
10
+ # @return [Hash, nil] Адрес возврата или отсутствие снимка.
11
+ def post_action_snapshot record
12
+ path = record.try(:registration_return_path)
13
+ token_ids = record.try(:email_change_token_ids)
14
+
15
+ return { 'token_ids' => token_ids } if token_ids.present?
16
+
17
+ { 'return_path' => path } if path
18
+ end
12
19
  end
13
20
 
14
21
  # Загружает почтовую учётку и отправляет письмо через настроенный транспорт приложения.
15
22
  # @param event [Hash] Событие post со строковыми ключами.
16
23
  # @return [void]
17
24
  def perform event
18
- return unless event.fetch('action') == 'create'
25
+ case event.fetch('action')
26
+ when 'update', 'patch'
27
+ Array(event.dig('after', 'token_ids')).each {|id| send_changed_email(id) }
28
+ when 'expire_email'
29
+ expire_email(event.fetch('token_id'))
30
+ when 'create'
31
+ accounts = event.fetch('model').constantize.find(event.fetch('id')).accounts
32
+ email_type = Tiun::Model::Account.email_type_for(accounts.klass)
33
+ return_path = event['after']&.[]('return_path')
19
34
 
20
- accounts = event.fetch('model').constantize.find(event.fetch('id')).accounts
21
- email_type = Tiun::Model::Account.email_type_for(accounts.klass)
22
-
23
- accounts.where(type: email_type).find_each {|account| deliver_confirmation(account) }
35
+ accounts.where(type: email_type).find_each {|account| deliver_confirmation(account, return_path) }
36
+ end
24
37
  end
25
38
 
26
39
  private
27
40
 
41
+ # Ставит очистку после смены почты в Sidekiq и отправляет письмо.
42
+ # @param id [Integer] Идентификатор токена нового адреса.
43
+ # @return [Mail::Message, nil] Отправленное письмо либо nil при недоступном токене.
44
+ def send_changed_email id
45
+ token = Token::Validate.find_by(id: id)
46
+ return unless token&.expires_at
47
+
48
+ Tiun::Service::Job.set(queue: 'mailers').perform_at(token.expires_at, self.class.name,
49
+ { 'action' => 'expire_email', 'token_id' => id })
50
+ account = token.tokenable
51
+ deliver_confirmation(account, '/me') if account
52
+ end
53
+
54
+ # Удаляет лишнюю почтовую учётку после окончания срока подтверждения.
55
+ # - Блокирует токен до учётки в том же порядке, что и обработчик подтверждения.
56
+ # - При подтверждении удаляет прежнюю учётку. По истечении срока без подтверждения удаляет новую.
57
+ # @param id [Integer] Идентификатор токена нового адреса.
58
+ # @return [void]
59
+ def expire_email id
60
+ token = Token::Validate.find_by(id: id)
61
+ return unless token
62
+
63
+ token.with_lock do
64
+ account = token.tokenable
65
+ return unless account && token.expires_at && token.expires_at <= Time.current
66
+
67
+ account.with_lock do
68
+ case account.email_confirmation_pending
69
+ when true
70
+ destroy_email(account)
71
+ when false
72
+ destroy_previous_emails(account)
73
+ end
74
+ end
75
+ end
76
+ end
77
+
78
+ # Удаляет предыдущие адреса для подтверждённой почтовой учётки.
79
+ # - Обходит всю цепочку замен на случай, если задания Sidekiq выполняются в обратном порядке.
80
+ # @param account [Account] Заблокированная учётка, заменившая прежние адреса.
81
+ # @return [void]
82
+ def destroy_previous_emails account
83
+ account.user.accounts.where(obsoleted_by_id: account.id).find_each do |previous|
84
+ previous.with_lock do
85
+ destroy_previous_emails(previous)
86
+ destroy_email(previous)
87
+ end
88
+ end
89
+ end
90
+
91
+ # Удаляет почтовую учётку вместе с токенами, выпущенными на неё.
92
+ # @param account [Account] Заблокированная почтовая учётка.
93
+ # @return [Account] Удалённая учётка.
94
+ def destroy_email account
95
+ account.tokina.find_each(&:destroy!)
96
+ account.destroy!
97
+ end
98
+
28
99
  # Отправляет письмо, если подтверждение почтовой учётки ещё доступно.
29
100
  # @param account [Account] Почтовая учётка.
101
+ # @param return_path [String, nil] Локальный адрес страницы регистрации.
30
102
  # @return [Mail::Message, nil] Письмо либо nil без действующего токена.
31
- def deliver_confirmation account
103
+ def deliver_confirmation account, return_path
32
104
  token = Token::Validate.actual.find_by(tokenable: account, obsoleted_at: nil)
33
105
 
34
- Tiun::Mailer::Confirmation.email_confirmation(account.no, token.code).deliver_now if token
106
+ Tiun::Mailer::Confirmation.email_confirmation(account.no, token.code, return_path).deliver_now if token
35
107
  end
36
108
  end
data/lib/tiun/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Tiun
4
- VERSION = '0.1.0'
4
+ VERSION = '0.2.0'
5
5
  end
data/package-lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "tiun",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "tiun",
9
- "version": "0.1.0",
9
+ "version": "0.2.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "axios": "^1.6.3",
data/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tiun",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "TypeScript package for Tiun.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -718,7 +718,8 @@ function renderComponent(
718
718
  return path ? (
719
719
  <Avatar href={path} src={text("url") ?? null} alt={text("alt") ?? text("caption") ?? ""} />
720
720
  ) : null;
721
- case "image":
721
+ case "image": {
722
+ const reserveSpace = value("reserveSpace");
722
723
  return (
723
724
  <Image
724
725
  src={text("url")}
@@ -729,11 +730,13 @@ function renderComponent(
729
730
  alt={tooltip.text ?? text("caption") ?? text("title")}
730
731
  title={text("title")}
731
732
  description={text("description")}
733
+ reserveSpace={typeof reserveSpace === "boolean" ? reserveSpace : undefined}
732
734
  variant={node.viewAs === "card" ? "card" : "plain"}
733
735
  tooltip={tooltip.content}
734
736
  {...imageEvents(incoming)}
735
737
  />
736
738
  );
739
+ }
737
740
  case "pressee": {
738
741
  const caption = text("caption");
739
742
  const view = text("view");
@@ -21,6 +21,7 @@ export interface ImageProps {
21
21
  readonly width?: number | string | undefined;
22
22
  readonly height?: number | string | undefined;
23
23
  readonly minHeight?: number | undefined;
24
+ readonly reserveSpace?: boolean | undefined;
24
25
  readonly loading?: "lazy" | "eager" | undefined;
25
26
  readonly fallback?: ReactNode;
26
27
  readonly onLoad?: ((event: SyntheticEvent<HTMLImageElement>) => void) | undefined;
@@ -44,10 +45,14 @@ export function imageEvents(
44
45
  };
45
46
  }
46
47
 
47
- function ImageCore(props: ImageProps): ReactElement {
48
+ /**
49
+ * Displays an image after it loads and applies its configured layout while unavailable.
50
+ * @param props Source, dimensions, display options and event handlers.
51
+ * @returns The image figure, an explicit fallback, or null.
52
+ */
53
+ function ImageCore(props: ImageProps): ReactElement | null {
48
54
  const { t } = useI18n(),
49
55
  [status, setStatus] = useState<"loading" | "loaded" | "error">(props.src ? "loading" : "error"),
50
- [attempt, setAttempt] = useState(0),
51
56
  live = useRef(true);
52
57
 
53
58
  useEffect(() => {
@@ -65,6 +70,11 @@ function ImageCore(props: ImageProps): ReactElement {
65
70
  }
66
71
  }
67
72
 
73
+ /**
74
+ * Records whether the loaded source is usable and notifies the caller.
75
+ * @param event The load or error event from the current image.
76
+ * @returns Nothing. Updates the figure state.
77
+ */
68
78
  function completed(event: SyntheticEvent<HTMLImageElement>): void {
69
79
  if (!live.current) {
70
80
  return;
@@ -78,15 +88,28 @@ function ImageCore(props: ImageProps): ReactElement {
78
88
  }
79
89
  }
80
90
 
91
+ if (status === "error" && props.reserveSpace !== true) {
92
+ return props.reserveSpace === undefined && props.fallback != null ? <>{props.fallback}</> : null;
93
+ }
94
+
95
+ const width = Number(props.width),
96
+ height = Number(props.height),
97
+ sized = width > 0 && height > 0 && Number.isFinite(width) && Number.isFinite(height),
98
+ slot =
99
+ props.reserveSpace === true && status !== "loaded"
100
+ ? { aspectRatio: sized ? `${width} / ${height}` : "1", maxWidth: "100%", width: sized ? width : undefined }
101
+ : undefined;
102
+
81
103
  const image = (
82
104
  <>
83
- {status === "loading" && <Loader label={t("tiun.components.image.loading")} />}
105
+ {status === "loading" && props.reserveSpace === undefined && (
106
+ <Loader label={t("tiun.components.image.loading")} />
107
+ )}
84
108
  {status !== "error" && props.src && (
85
109
  <img
86
- key={attempt}
87
110
  src={props.src}
88
111
  alt={alt}
89
- loading={props.loading ?? "eager"}
112
+ loading={props.reserveSpace === false ? "eager" : (props.loading ?? "eager")}
90
113
  className={props.imageClassName}
91
114
  width={props.width}
92
115
  height={props.height}
@@ -94,11 +117,6 @@ function ImageCore(props: ImageProps): ReactElement {
94
117
  onError={completed}
95
118
  />
96
119
  )}
97
- {status === "error" && (
98
- <span className="tiun-image-error" role="status">
99
- {props.fallback ?? t("tiun.components.image.errors.load")}
100
- </span>
101
- )}
102
120
  </>
103
121
  ),
104
122
  target = props.path ?? props.url,
@@ -130,8 +148,9 @@ function ImageCore(props: ImageProps): ReactElement {
130
148
  <Figure
131
149
  className={`tiun-image tiun-image-${props.variant ?? "plain"} ${props.className ?? ""}`}
132
150
  data-image-state={status}
151
+ data-image-reserve={props.reserveSpace}
133
152
  >
134
- <div className="tiun-image-frame">
153
+ <div className="tiun-image-frame" style={slot}>
135
154
  {props.tooltip ? (
136
155
  <Tooltip content={props.tooltip}>
137
156
  <div>{wrappedImage}</div>
@@ -140,19 +159,7 @@ function ImageCore(props: ImageProps): ReactElement {
140
159
  wrappedImage
141
160
  )}
142
161
  </div>
143
- {status === "error" && props.src && (
144
- <button
145
- type="button"
146
- className="tiun-image-retry"
147
- onClick={() => {
148
- setAttempt((value) => value + 1);
149
- setStatus("loading");
150
- }}
151
- >
152
- {t("tiun.components.image.retry")}
153
- </button>
154
- )}
155
- {(props.title || props.description) && (
162
+ {status !== "error" && (props.title || props.description) && (
156
163
  <figcaption>
157
164
  {props.title && <div className="tiun-image-title">{props.title}</div>}
158
165
  {props.description && <div className="tiun-image-description">{props.description}</div>}
@@ -162,7 +169,11 @@ function ImageCore(props: ImageProps): ReactElement {
162
169
  );
163
170
  }
164
171
 
165
- /** Plain image and card share loading/error/retry. Source identity resets every transient state. */
172
+ /**
173
+ * Renders a plain image or card and resets loading state when its source changes.
174
+ * @param props Source, layout, caption and event handlers for the image.
175
+ * @returns The keyed image renderer for the supplied source.
176
+ */
166
177
  export function Image(props: ImageProps): ReactElement {
167
178
  return <ImageCore key={props.src ?? ""} {...props} />;
168
179
  }