lostcoords-ui 0.9.3 → 0.11.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 (30) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +164 -4
  3. data/app/assets/tailwind/lostcoords/ui/components/hovercard.css +4 -0
  4. data/app/assets/tailwind/lostcoords/ui/components/shell.css +2 -2
  5. data/app/assets/tailwind/lostcoords/ui/components.css +1 -0
  6. data/app/assets/tailwind/lostcoords/ui/core.css +2 -1
  7. data/app/assets/tailwind/lostcoords/ui/hovercard.css +47 -0
  8. data/app/assets/tailwind/lostcoords/ui/shell.css +66 -9
  9. data/app/assets/tailwind/lostcoords/ui/toggle-group.css +58 -0
  10. data/app/helpers/lostcoords/ui/badge_helper.rb +9 -7
  11. data/app/helpers/lostcoords/ui/description_list_helper.rb +39 -0
  12. data/app/helpers/lostcoords/ui/form_helper.rb +4 -4
  13. data/app/helpers/lostcoords/ui/hovercard_helper.rb +31 -0
  14. data/app/helpers/lostcoords/ui/layout_helper.rb +31 -0
  15. data/app/helpers/lostcoords/ui/navigation_helper.rb +13 -0
  16. data/app/helpers/lostcoords/ui/primitives_helper.rb +20 -2
  17. data/app/helpers/lostcoords/ui/shell_helper.rb +32 -1
  18. data/app/helpers/lostcoords/ui/structures_helper.rb +65 -14
  19. data/app/helpers/lostcoords/ui/typography_helper.rb +30 -0
  20. data/app/javascript/lostcoords/ui/controllers/lc_char_counter_controller.js +63 -0
  21. data/app/javascript/lostcoords/ui/controllers/lc_hovercard_controller.js +104 -0
  22. data/app/javascript/lostcoords/ui/controllers/lc_sidebar_controller.js +48 -0
  23. data/app/javascript/lostcoords/ui/helpers/dismiss_stack.js +1 -1
  24. data/app/javascript/lostcoords/ui/index.js +6 -0
  25. data/config/locales/en.yml +14 -0
  26. data/config/locales/es.yml +14 -0
  27. data/config/locales/ja.yml +14 -0
  28. data/lib/lostcoords/ui/parts.rb +86 -0
  29. data/lib/lostcoords/ui/version.rb +1 -1
  30. metadata +8 -1
@@ -18,6 +18,15 @@ module Lostcoords::Ui
18
18
  form: "max-w-form"
19
19
  }.freeze
20
20
 
21
+ # The aside's width from the lg breakpoint; below it the aside stacks under the main column.
22
+ SPLIT_ASIDES = {
23
+ sm: "lg:grid-cols-[minmax(0,1fr)_16rem]",
24
+ md: "lg:grid-cols-[minmax(0,1fr)_20rem]",
25
+ lg: "lg:grid-cols-[minmax(0,1fr)_24rem]"
26
+ }.freeze
27
+
28
+ COLUMN_COUNTS = { 2 => "lg:columns-2", 3 => "md:columns-2 xl:columns-3" }.freeze
29
+
21
30
  def lc_stack_class(gap: :content, extra: nil)
22
31
  gap = lc_option!(:gap, gap, LAYOUT_GAPS.keys)
23
32
  lc_tw("flex min-w-0 flex-col", LAYOUT_GAPS.fetch(gap), extra)
@@ -33,6 +42,20 @@ module Lostcoords::Ui
33
42
  lc_tw("mx-auto min-w-0 w-full", CONTAINER_SIZES.fetch(size), extra)
34
43
  end
35
44
 
45
+ # A main column and an aside: one column on small screens, and from lg a flexible main beside an
46
+ # aside of fixed width (aside: :sm 16rem, :md 20rem, :lg 24rem). Children align to the top.
47
+ def lc_split_class(aside: :md, extra: nil)
48
+ aside = lc_option!(:aside, aside, SPLIT_ASIDES.keys)
49
+ lc_tw("grid min-w-0 items-start gap-section", SPLIT_ASIDES.fetch(aside), extra)
50
+ end
51
+
52
+ # Groups that flow into balanced columns, as newspaper columns do, without breaking a group across
53
+ # two: count: 2 from lg, or 3 from xl (2 from md). Children keep a section's spacing.
54
+ def lc_columns_class(count: 2, extra: nil)
55
+ count = lc_option!(:count, count, COLUMN_COUNTS.keys)
56
+ lc_tw("min-w-0 gap-section *:break-inside-avoid *:not-last:mb-section", COLUMN_COUNTS.fetch(count), extra)
57
+ end
58
+
36
59
  # The header keeps a control's height, so a section with actions and one without line up.
37
60
  def lc_section_header_class(extra: nil)
38
61
  lc_inline_class(extra: lc_tw("min-h-control-md justify-between", extra))
@@ -47,6 +70,14 @@ module Lostcoords::Ui
47
70
  tag.public_send(lc_option!(:as, as, LAYOUT_ELEMENTS), **lc_attributes({ class: lc_inline_class(gap: gap) }, attributes), &block)
48
71
  end
49
72
 
73
+ def lc_split(aside: :md, as: :div, **attributes, &block)
74
+ tag.public_send(lc_option!(:as, as, LAYOUT_ELEMENTS), **lc_attributes({ class: lc_split_class(aside: aside) }, attributes), &block)
75
+ end
76
+
77
+ def lc_columns(count: 2, as: :div, **attributes, &block)
78
+ tag.public_send(lc_option!(:as, as, LAYOUT_ELEMENTS), **lc_attributes({ class: lc_columns_class(count: count) }, attributes), &block)
79
+ end
80
+
50
81
  def lc_container(size: :page, **attributes, &block)
51
82
  tag.div(**lc_attributes({ class: lc_container_class(size: size) }, attributes), &block)
52
83
  end
@@ -84,6 +84,19 @@ module Lostcoords::Ui
84
84
  end
85
85
  end
86
86
 
87
+ # Links styled as a row of tabs over a rule, each page of a view behind one. Unlike lc_tabs, every
88
+ # tab is a link to its own URL. Yields a builder: `bar.link "Replies", replies_path, current: true, count: 12`.
89
+ # fill: true stretches the tabs to share the row; a row too long for its container scrolls sideways.
90
+ def lc_tab_bar(label:, fill: false, **attributes, &block)
91
+ lc_label!(label, :label)
92
+ raise ArgumentError, "lc_tab_bar needs a block" unless block
93
+
94
+ data = { slot: "tab-bar", fill: (true if fill) }.compact
95
+ tag.nav(**lc_attributes({ class: "min-w-0 border-b border-border", aria: { label: label }, data: data }, attributes)) do
96
+ tag.ul(capture(Parts::TabBar.new(self, fill), &block), class: "m-0 flex min-w-0 list-none overflow-x-auto p-0 [scrollbar-width:none] lc-scroll-fade-x [&::-webkit-scrollbar]:hidden")
97
+ end
98
+ end
99
+
87
100
  TOC_INDICATOR = "pointer-events-none absolute -start-px top-0 h-0 w-0.5 rounded-pill bg-primary opacity-0 " \
88
101
  "transition-[translate,height,opacity] duration-300 ease-(--lc-ease-out-expo) motion-reduce:transition-none"
89
102
 
@@ -154,8 +154,26 @@ module Lostcoords::Ui
154
154
  end
155
155
  end
156
156
 
157
- def lc_empty_state(**attributes, &block)
158
- tag.div(**lc_attributes({ class: lc_empty_state_class, data: { slot: "empty-state" } }, attributes), &block)
157
+ # title:, text: and icon: lay out the usual empty state: a round icon badge, a heading and a line
158
+ # of muted text, then the block, such as an action. Without them the block is the whole content.
159
+ # level: sets the heading level, and card: true puts the empty state on an lc_card.
160
+ def lc_empty_state(title: nil, text: nil, icon: nil, level: 2, card: false, **attributes, &block)
161
+ extra = capture(&block) if block
162
+ content = if title.present? || text.present? || icon
163
+ heading = [
164
+ (lc_heading(title, level: level, size: :subheading, data: { slot: "empty-state-title" }) if title.present?),
165
+ (lc_text(text, size: :small, tone: :muted, data: { slot: "empty-state-description" }) if text.present?)
166
+ ].compact
167
+ safe_join([
168
+ (lc_icon_badge(icon: icon, shape: :circle, size: :lg, data: { slot: "empty-state-icon" }) if icon),
169
+ (lc_stack(gap: :tight, class: "max-w-md") { safe_join(heading) } if heading.any?),
170
+ extra
171
+ ].compact)
172
+ else
173
+ extra
174
+ end
175
+ state = tag.div(content, **lc_attributes({ class: lc_empty_state_class, data: { slot: "empty-state" } }, attributes))
176
+ card ? lc_card { state } : state
159
177
  end
160
178
 
161
179
  def lc_spinner(size: :md, label: lc_t("lostcoords.ui.spinner.label"), **attributes)
@@ -1,5 +1,5 @@
1
1
  module Lostcoords::Ui
2
- # Page chrome: the sticky application header, the documentation layout and the phone dock.
2
+ # Page chrome: the sticky application header, the app sidebar, the documentation layout and the phone dock.
3
3
  module ShellHelper
4
4
  DOCS_SHELL = "lc-docs-shell mx-auto flex w-full max-w-360 gap-10 px-5 sm:px-8 lg:px-10"
5
5
  DOCS_SHELL_ASIDE = "sticky top-(--lc-sticky-offset,0rem) hidden h-[calc(100dvh-var(--lc-sticky-offset,0rem))] shrink-0 overflow-y-auto"
@@ -48,6 +48,37 @@ module Lostcoords::Ui
48
48
  end
49
49
  end
50
50
 
51
+ SIDEBAR = "lc-sidebar sticky top-0 flex h-dvh w-(--lc-sidebar-width,15rem) shrink-0 flex-col gap-content overflow-y-auto px-related py-inset " \
52
+ "lc-rail:w-(--lc-sidebar-rail-width,4rem)"
53
+ SIDEBAR_RAIL_BELOW = %i[md lg xl 2xl].freeze
54
+ SIDEBAR_STATES = %w[collapsed expanded].freeze
55
+
56
+ # A sticky, full-height app sidebar that folds to an icon rail. Yields a builder: sidebar.header
57
+ # (a wordmark and the toggle), sidebar.body (usually lc_nav_list), sidebar.footer and
58
+ # sidebar.account. The toggle stores the choice in the cookie named cookie:, which the helper
59
+ # reads back, so the server renders the next page the same way; state: "collapsed" or "expanded"
60
+ # overrides it. Below rail_below: (a breakpoint, or false for never) it starts as a rail unless
61
+ # the reader expanded it. Style your own content for the rail with the lc-rail: variant.
62
+ def lc_sidebar(label: lc_t("lostcoords.ui.sidebar.label"), cookie: "lc_sidebar", rail_below: :xl, state: nil, **attributes, &block)
63
+ lc_label!(label, :label)
64
+ lc_label!(cookie, :cookie)
65
+ raise ArgumentError, "lc_sidebar needs a block" unless block
66
+
67
+ rail_below = lc_option!(:rail_below, rail_below, SIDEBAR_RAIL_BELOW) unless rail_below == false
68
+ # cookies is a controller helper_method that respond_to? can't see from the view, so read the request's.
69
+ state = (state || (request.cookies[cookie] if respond_to?(:request) && request)).to_s
70
+ state = nil unless SIDEBAR_STATES.include?(state)
71
+ collapse_label = lc_t("lostcoords.ui.sidebar.collapse")
72
+ expand_label = lc_t("lostcoords.ui.sidebar.expand")
73
+
74
+ content = capture(Parts::Sidebar.new(self, state == "collapsed" ? expand_label : collapse_label, state != "collapsed"), &block)
75
+ data = { slot: "sidebar", controller: "lc-sidebar lc-scroll-keeper", rail_below: rail_below || nil,
76
+ collapsed: (true if state == "collapsed"), expanded: (true if state == "expanded"),
77
+ lc_sidebar_cookie_value: cookie, lc_sidebar_collapse_label_value: collapse_label, lc_sidebar_expand_label_value: expand_label,
78
+ lc_scroll_keeper_key_value: cookie }.compact
79
+ tag.aside(content, **lc_attributes({ class: SIDEBAR, aria: { label: label }, data: data }, attributes))
80
+ end
81
+
51
82
  # A floating bar at the bottom of a phone screen: dock.nav for primary destinations and dock.menu
52
83
  # for a button whose actions fan out above it. It reserves its height at the end of the page, so
53
84
  # render it last, and it hides while the on-screen keyboard is open.
@@ -13,6 +13,43 @@ module Lostcoords::Ui
13
13
  tag.textarea(block ? capture(&block) : content, **lc_attributes({ name: name, class: lc_textarea_class, data: { slot: "textarea" } }, attributes))
14
14
  end
15
15
 
16
+ CHAR_COUNTER = "inline-flex items-center gap-related text-small tabular-nums text-primary data-[state=near]:text-warning data-[state=over]:text-destructive"
17
+ CHAR_COUNTER_RADIUS = 9
18
+
19
+ # A ring that fills as a field nears max: characters, as on X. It hides while the field is empty,
20
+ # turns to the warning tone and shows the characters left once warn: or fewer remain, and to the
21
+ # destructive tone with a negative number past the limit. for: is the field's id; without it the
22
+ # nearest field around the counter is counted. To count another way, such as weighted characters,
23
+ # set data-lc-char-counter-count-value or send an event with detail.count to lc-char-counter#update.
24
+ # count: renders that count before JavaScript runs.
25
+ def lc_char_counter(max:, for: nil, warn: 20, count: nil, **attributes)
26
+ field = binding.local_variable_get(:for)
27
+ raise ArgumentError, "max: must be a positive integer" unless max.is_a?(Integer) && max.positive?
28
+ raise ArgumentError, "warn: must be a non-negative integer" unless warn.is_a?(Integer) && !warn.negative?
29
+ raise ArgumentError, "count: must be an integer" unless count.nil? || count.is_a?(Integer)
30
+
31
+ shown = count || 0
32
+ left = max - shown
33
+ circumference = 2 * Math::PI * CHAR_COUNTER_RADIUS
34
+ data = { slot: "char-counter", state: (left.negative? ? "over" : (left <= warn ? "near" : "ok")), controller: "lc-char-counter",
35
+ lc_char_counter_max_value: max, lc_char_counter_warn_value: warn, lc_char_counter_for_value: field.presence,
36
+ lc_char_counter_label_value: lc_t("lostcoords.ui.char_counter.label"), lc_char_counter_count_value: count }.compact
37
+ defaults = { class: CHAR_COUNTER, role: "img", hidden: shown.zero?, aria: { label: lc_t("lostcoords.ui.char_counter.label", count: shown, max: max) }, data: data }
38
+ circle = { cx: 10, cy: 10, r: CHAR_COUNTER_RADIUS, fill: "none", stroke: "currentColor", "stroke-width": 2 }
39
+ tag.span(**lc_attributes(defaults, attributes)) do
40
+ safe_join([
41
+ tag.span((left if left <= warn), data: { slot: "char-counter-remaining", lc_char_counter_target: "remaining" }),
42
+ tag.svg(viewBox: "0 0 20 20", class: "size-6 shrink-0 -rotate-90", aria: { hidden: true }) do
43
+ safe_join([
44
+ tag.circle(**circle, class: "opacity-20"),
45
+ tag.circle(**circle, "stroke-linecap": "round", "stroke-dasharray": "#{([ shown.fdiv(max), 1 ].min * circumference).round(2)} #{circumference.round(2)}",
46
+ data: { lc_char_counter_target: "progress" })
47
+ ])
48
+ end
49
+ ])
50
+ end
51
+ end
52
+
16
53
  def lc_select(options = nil, name: nil, selected: nil, size: :md, **attributes, &block)
17
54
  size = lc_option!(:size, size, TailwindHelper::CONTROL_SIZES.keys)
18
55
  content = block ? capture(&block) : options_for_select(options || [], selected)
@@ -108,27 +145,41 @@ module Lostcoords::Ui
108
145
  tag.button(content, **lc_attributes(defaults.merge(aria: { checked: selected || false }), attributes, required))
109
146
  end
110
147
 
148
+ TOGGLE_ICON_ONLY = "aspect-square px-0"
149
+
111
150
  # A button that flips its own aria-pressed. href: renders a link marked current when active, and
112
151
  # name: a label around a radio checked when active. A caller that sets aria-pressed or
113
152
  # aria-expanded owns the state, so the toggle drops its own controller.
114
- def lc_toggle(label = nil, active: false, ghost: false, size: :md, href: nil, name: nil, value: nil, input: {}, **attributes, &block)
115
- content = block ? capture(&block) : label
116
- defaults = { class: lc_toggle_class(ghost: ghost, size: size), data: { slot: "toggle" } }
117
- return lc_toggle_link(content, href, active, defaults, attributes) if href
153
+ # icon: adds a leading icon; with icon_only: true the toggle is a square of just the icon and
154
+ # the label stays as its accessible name. tooltip: true shows the label on hover and focus, and
155
+ # tooltip: "text" describes the toggle with other text, as on lc_icon_button.
156
+ def lc_toggle(label = nil, active: false, ghost: false, size: :md, href: nil, name: nil, value: nil, input: {}, icon: nil, icon_only: false, tooltip: nil, **attributes, &block)
157
+ raise ArgumentError, "icon_only: true needs icon: and a label, not a block" if icon_only && (icon.nil? || label.blank? || block)
118
158
 
119
- if name
120
- value ||= label
121
- lc_label!(value, :value)
122
- return lc_toggle_radio(content, name, value, active, input, defaults, attributes)
159
+ content = block ? capture(&block) : label
160
+ if icon
161
+ glyph = lc_icon(icon, options: { "aria-hidden": true, "data-icon": ("inline-start" unless icon_only) }.compact)
162
+ content = safe_join([ glyph, (icon_only ? tag.span(label, class: "sr-only") : content) ])
123
163
  end
164
+ defaults = { class: lc_toggle_class(ghost: ghost, size: size, extra: (TOGGLE_ICON_ONLY if icon_only)), data: { slot: "toggle", icon_only: (true if icon_only) }.compact }
165
+ lc_icon_button_tooltip(label, tooltip, attributes) do |tip|
166
+ attributes = lc_attributes(attributes, tip)
167
+ next lc_toggle_link(content, href, active, defaults, attributes) if href
168
+
169
+ if name
170
+ value ||= label
171
+ lc_label!(value, :value)
172
+ next lc_toggle_radio(content, name, value, active, input, defaults, attributes)
173
+ end
124
174
 
125
- if lc_normalize_attributes(attributes).fetch(:aria, {}).slice(:pressed, :expanded).any?
126
- raise ArgumentError, "pass active: or aria: { pressed: }, not both" if active
127
- else
128
- defaults[:aria] = { pressed: active }
129
- defaults[:data].merge!(controller: "lc-toggle", action: "click->lc-toggle#toggle")
175
+ if lc_normalize_attributes(attributes).fetch(:aria, {}).slice(:pressed, :expanded).any?
176
+ raise ArgumentError, "pass active: or aria: { pressed: }, not both" if active
177
+ else
178
+ defaults[:aria] = { pressed: active }
179
+ defaults[:data].merge!(controller: "lc-toggle", action: "click->lc-toggle#toggle")
180
+ end
181
+ tag.button(content, **lc_attributes(defaults, attributes).merge(type: "button"))
130
182
  end
131
- tag.button(content, **lc_attributes(defaults, attributes).merge(type: "button"))
132
183
  end
133
184
 
134
185
  private
@@ -42,6 +42,28 @@ module Lostcoords::Ui
42
42
  tag.public_send(lc_option!(:as, as, TEXT_ELEMENTS), content, **lc_attributes({ class: lc_text_class(size: size, tone: tone, trim: trim) }, attributes), &block)
43
43
  end
44
44
 
45
+ # A <time> with the short text X shows: "now", "12m" and "4h" within a day, then "4 Nov", and
46
+ # "4 Nov 2025" in another year; a Date shows its day. The full date and time is its title, and
47
+ # detail: adds to it. now: is the moment to count from. Texts and formats are lostcoords.ui.time.*.
48
+ def lc_time(time, now: Time.current, detail: nil, **attributes)
49
+ raise ArgumentError, "lc_time needs a Time, DateTime or Date" unless time.is_a?(Time) || time.is_a?(Date)
50
+
51
+ date = time.instance_of?(Date)
52
+ time = time.in_time_zone
53
+ elapsed = now - time
54
+ text = if date || elapsed.negative? || elapsed >= 1.day
55
+ lc_localize_time(time, time.year == now.year ? :date : :date_with_year)
56
+ elsif elapsed < 1.minute
57
+ lc_t("lostcoords.ui.time.now")
58
+ elsif elapsed < 1.hour
59
+ lc_t("lostcoords.ui.time.minutes", count: (elapsed / 1.minute).floor)
60
+ else
61
+ lc_t("lostcoords.ui.time.hours", count: (elapsed / 1.hour).floor)
62
+ end
63
+ title = [ lc_localize_time(time, date ? :date_with_year : :full), detail.presence ].compact.join(" · ")
64
+ tag.time(text, **lc_attributes({ datetime: (date ? time.to_date.iso8601 : time.iso8601), title: title, data: { slot: "time" } }, attributes))
65
+ end
66
+
45
67
  # A key hint, such as lc_kbd("mod+k"). "mod" renders Ctrl and reads ⌘ on Apple platforms once JS runs.
46
68
  def lc_kbd(keys, **attributes)
47
69
  lc_label!(keys, :keys)
@@ -63,5 +85,13 @@ module Lostcoords::Ui
63
85
  data = data.to_h.symbolize_keys
64
86
  data.merge(controller: [ data[:controller], "lc-shortcut" ].compact.join(" "), lc_shortcut_keys_value: keys)
65
87
  end
88
+
89
+ private
90
+ # Month names come from the host's locale, as rails-i18n provides them; without them, English ones.
91
+ def lc_localize_time(time, format)
92
+ pattern = lc_t("lostcoords.ui.time.formats.#{format}")
93
+ named = I18n.exists?(:"date.month_names") && I18n.exists?(:"date.abbr_month_names")
94
+ named ? I18n.l(time, format: pattern) : time.strftime(pattern)
95
+ end
66
96
  end
67
97
  end
@@ -0,0 +1,63 @@
1
+ import { Controller } from "@hotwired/stimulus"
2
+
3
+ const FIELDS =
4
+ "textarea, input:not([type=hidden], [type=checkbox], [type=radio], [type=submit], [type=button], [type=reset])"
5
+
6
+ // Fills lc_char_counter's ring from a field's characters, or from a count you supply: set the count value,
7
+ // or send an event whose detail.count is the count to update.
8
+ export default class extends Controller {
9
+ static targets = ["remaining", "progress"]
10
+ static values = {
11
+ max: Number,
12
+ warn: { type: Number, default: 20 },
13
+ for: String,
14
+ label: String,
15
+ count: Number,
16
+ }
17
+
18
+ connect() {
19
+ this.field = this.forValue ? document.getElementById(this.forValue) : this.nearestField()
20
+ this.input = () => this.render()
21
+ this.field?.addEventListener("input", this.input)
22
+ this.render()
23
+ }
24
+
25
+ disconnect() {
26
+ this.field?.removeEventListener("input", this.input)
27
+ }
28
+
29
+ update({ detail }) {
30
+ this.countValue = detail.count
31
+ }
32
+
33
+ countValueChanged() {
34
+ if (this.field !== undefined) this.render()
35
+ }
36
+
37
+ get count() {
38
+ if (this.hasCountValue) return this.countValue
39
+ return Array.from(this.field?.value ?? "").length
40
+ }
41
+
42
+ render() {
43
+ const count = this.count
44
+ const left = this.maxValue - count
45
+ const circumference = 2 * Math.PI * Number(this.progressTarget.getAttribute("r"))
46
+ this.progressTarget.style.strokeDasharray = `${Math.min(count / this.maxValue, 1) * circumference} ${circumference}`
47
+ this.element.dataset.state = left < 0 ? "over" : left <= this.warnValue ? "near" : "ok"
48
+ this.element.hidden = count === 0
49
+ this.remainingTarget.textContent = left <= this.warnValue ? String(left) : ""
50
+ this.element.setAttribute(
51
+ "aria-label",
52
+ this.labelValue.replace("%{count}", count).replace("%{max}", this.maxValue),
53
+ )
54
+ }
55
+
56
+ nearestField() {
57
+ for (let node = this.element.parentElement; node; node = node.parentElement) {
58
+ const field = node.querySelector(FIELDS)
59
+ if (field) return field
60
+ }
61
+ return null
62
+ }
63
+ }
@@ -0,0 +1,104 @@
1
+ import { Controller } from "@hotwired/stimulus"
2
+ import { registerDismissable } from "lostcoords/ui/helpers/dismiss_stack"
3
+ import { liftToTopLayer, onPageLeave } from "lostcoords/ui/helpers/top_layer"
4
+
5
+ const OPEN_DELAY = 450
6
+ const CLOSE_DELAY = 200
7
+
8
+ // Opens a preview card after a short hover, or at once on keyboard focus, in
9
+ // the top layer beside its trigger. With a src it loads the card's HTML the
10
+ // first time it opens. The pointer can cross the gap to the card and stay on
11
+ // it; leaving both closes it after a moment, and Escape closes it at once.
12
+ // Touch screens never open it: a tap follows the link.
13
+ export default class extends Controller {
14
+ static targets = ["trigger", "content"]
15
+ static values = { src: String }
16
+
17
+ connect() {
18
+ this.stopPageLeave = onPageLeave(() => this.close({ immediate: true }))
19
+ this.untab()
20
+ }
21
+
22
+ disconnect() {
23
+ this.stopPageLeave?.()
24
+ this.cancelTimers()
25
+ this.close({ immediate: true })
26
+ }
27
+
28
+ enter(event) {
29
+ if (event.type === "focusin" && !event.target.matches(":focus-visible")) return
30
+ if (event.type === "mouseenter" && !matchMedia("(hover: hover)").matches) return
31
+ clearTimeout(this.closing)
32
+ if (this.release || this.opening) return
33
+ this.opening = setTimeout(() => this.open(), event.type === "focusin" ? 0 : OPEN_DELAY)
34
+ }
35
+
36
+ leave() {
37
+ clearTimeout(this.opening)
38
+ this.opening = null
39
+ this.closing = setTimeout(() => {
40
+ if (this.element.matches(":hover") || this.element.querySelector(":focus-visible")) return
41
+ this.close()
42
+ }, CLOSE_DELAY)
43
+ }
44
+
45
+ async open() {
46
+ this.opening = null
47
+ if (this.release || !this.element.isConnected) return
48
+ if (!this.contentTarget.hasAttribute("data-loaded") && this.hasSrcValue && this.srcValue) {
49
+ this.loading ??= this.load().finally(() => (this.loading = null))
50
+ if (!(await this.loading) || this.release) return
51
+ if (!this.element.matches(":hover") && !this.element.querySelector(":focus-visible")) return
52
+ }
53
+ this.element.toggleAttribute("data-open", true)
54
+ this.release = liftToTopLayer(this.contentTarget, this.triggerTarget)
55
+ this.unregister = registerDismissable({
56
+ type: "hovercard",
57
+ element: this.element,
58
+ isOpen: () => this.element.hasAttribute("data-open"),
59
+ close: () => this.close({ immediate: true }),
60
+ })
61
+ }
62
+
63
+ // Only the page's own origin can fill the card.
64
+ async load() {
65
+ const url = new URL(this.srcValue, window.location.href)
66
+ if (url.origin !== window.location.origin) return false
67
+ try {
68
+ const response = await fetch(url, {
69
+ headers: { Accept: "text/html", "X-Requested-With": "XMLHttpRequest" },
70
+ credentials: "same-origin",
71
+ })
72
+ if (!response.ok) return false
73
+ this.contentTarget.innerHTML = await response.text()
74
+ this.untab()
75
+ this.contentTarget.toggleAttribute("data-loaded", true)
76
+ return true
77
+ } catch {
78
+ return false
79
+ }
80
+ }
81
+
82
+ // The card is a preview: its links stay clickable but out of the tab order.
83
+ untab() {
84
+ for (const element of this.contentTarget.querySelectorAll(
85
+ "a, button, input, select, textarea, [tabindex]",
86
+ )) {
87
+ element.setAttribute("tabindex", "-1")
88
+ }
89
+ }
90
+
91
+ close({ immediate = false } = {}) {
92
+ this.element.toggleAttribute("data-open", false)
93
+ this.release?.({ immediate })
94
+ this.release = null
95
+ this.unregister?.()
96
+ this.unregister = null
97
+ }
98
+
99
+ cancelTimers() {
100
+ clearTimeout(this.opening)
101
+ clearTimeout(this.closing)
102
+ this.opening = null
103
+ }
104
+ }
@@ -0,0 +1,48 @@
1
+ import { Controller } from "@hotwired/stimulus"
2
+
3
+ const BREAKPOINTS = { md: "48rem", lg: "64rem", xl: "80rem", "2xl": "96rem" }
4
+
5
+ // Folds lc_sidebar to an icon rail and back, and keeps the choice in a cookie so the server renders the
6
+ // next page the same way. Below its data-rail-below breakpoint it is a rail unless the reader expanded it.
7
+ export default class extends Controller {
8
+ static targets = ["toggle"]
9
+ static values = { cookie: String, collapseLabel: String, expandLabel: String }
10
+
11
+ connect() {
12
+ const width = BREAKPOINTS[this.element.dataset.railBelow]
13
+ this.query = width ? matchMedia(`(width < ${width})`) : null
14
+ this.sync = () => this.label()
15
+ this.query?.addEventListener("change", this.sync)
16
+ this.label()
17
+ }
18
+
19
+ disconnect() {
20
+ this.query?.removeEventListener("change", this.sync)
21
+ }
22
+
23
+ toggle() {
24
+ const collapse = !this.rail
25
+ this.element.toggleAttribute("data-collapsed", collapse)
26
+ this.element.toggleAttribute("data-expanded", !collapse)
27
+ // biome-ignore lint/suspicious/noDocumentCookie: the server reads this cookie to render the next page the same way
28
+ document.cookie = `${encodeURIComponent(this.cookieValue)}=${collapse ? "collapsed" : "expanded"}; path=/; max-age=31536000; samesite=lax`
29
+ this.label()
30
+ this.dispatch("toggle", { detail: { collapsed: collapse } })
31
+ }
32
+
33
+ get rail() {
34
+ if (this.element.hasAttribute("data-collapsed")) return true
35
+ if (this.element.hasAttribute("data-expanded")) return false
36
+ return Boolean(this.query?.matches)
37
+ }
38
+
39
+ label() {
40
+ const rail = this.rail
41
+ const label = rail ? this.expandLabelValue : this.collapseLabelValue
42
+ for (const toggle of this.toggleTargets) {
43
+ toggle.setAttribute("aria-label", label)
44
+ toggle.setAttribute("title", label)
45
+ toggle.setAttribute("aria-expanded", String(!rail))
46
+ }
47
+ }
48
+ }
@@ -130,7 +130,7 @@ function defaultIsOpen() {
130
130
  }
131
131
 
132
132
  function priorityFor(type) {
133
- if (type === "tooltip") return 40
133
+ if (type === "tooltip" || type === "hovercard") return 40
134
134
  if (type === "popover") return 30
135
135
  if (type === "panel") return 20
136
136
  return 10
@@ -1,10 +1,12 @@
1
1
  import AppHeader from "lostcoords/ui/controllers/lc_app_header_controller"
2
+ import CharCounter from "lostcoords/ui/controllers/lc_char_counter_controller"
2
3
  import CodeBlock from "lostcoords/ui/controllers/lc_code_block_controller"
3
4
  import Collapsible from "lostcoords/ui/controllers/lc_collapsible_controller"
4
5
  import Copy from "lostcoords/ui/controllers/lc_copy_controller"
5
6
  import Dialog from "lostcoords/ui/controllers/lc_dialog_controller"
6
7
  import Dock from "lostcoords/ui/controllers/lc_dock_controller"
7
8
  import EmojiPicker from "lostcoords/ui/controllers/lc_emoji_picker_controller"
9
+ import Hovercard from "lostcoords/ui/controllers/lc_hovercard_controller"
8
10
  import Kbd from "lostcoords/ui/controllers/lc_kbd_controller"
9
11
  import Menu from "lostcoords/ui/controllers/lc_menu_controller"
10
12
  import Nav from "lostcoords/ui/controllers/lc_nav_controller"
@@ -14,6 +16,7 @@ import Search from "lostcoords/ui/controllers/lc_search_controller"
14
16
  import Selection from "lostcoords/ui/controllers/lc_selection_controller"
15
17
  import Sheet from "lostcoords/ui/controllers/lc_sheet_controller"
16
18
  import Shortcut from "lostcoords/ui/controllers/lc_shortcut_controller"
19
+ import Sidebar from "lostcoords/ui/controllers/lc_sidebar_controller"
17
20
  import Tabs from "lostcoords/ui/controllers/lc_tabs_controller"
18
21
  import Toast from "lostcoords/ui/controllers/lc_toast_controller"
19
22
  import ToastRegion from "lostcoords/ui/controllers/lc_toast_region_controller"
@@ -23,12 +26,14 @@ import Tooltip from "lostcoords/ui/controllers/lc_tooltip_controller"
23
26
 
24
27
  const controllers = {
25
28
  "lc-app-header": AppHeader,
29
+ "lc-char-counter": CharCounter,
26
30
  "lc-collapsible": Collapsible,
27
31
  "lc-code-block": CodeBlock,
28
32
  "lc-copy": Copy,
29
33
  "lc-dialog": Dialog,
30
34
  "lc-dock": Dock,
31
35
  "lc-emoji-picker": EmojiPicker,
36
+ "lc-hovercard": Hovercard,
32
37
  "lc-kbd": Kbd,
33
38
  "lc-menu": Menu,
34
39
  "lc-nav": Nav,
@@ -38,6 +43,7 @@ const controllers = {
38
43
  "lc-selection": Selection,
39
44
  "lc-sheet": Sheet,
40
45
  "lc-shortcut": Shortcut,
46
+ "lc-sidebar": Sidebar,
41
47
  "lc-tabs": Tabs,
42
48
  "lc-toc": Toc,
43
49
  "lc-toast": Toast,
@@ -29,6 +29,20 @@ en:
29
29
  navigation: "Main"
30
30
  dock:
31
31
  close: "Close %{label}"
32
+ sidebar:
33
+ label: "Sidebar"
34
+ collapse: "Collapse sidebar"
35
+ expand: "Expand sidebar"
36
+ char_counter:
37
+ label: "%{count} of %{max} characters"
38
+ time:
39
+ now: "now"
40
+ minutes: "%{count}m"
41
+ hours: "%{count}h"
42
+ formats:
43
+ date: "%-d %b"
44
+ date_with_year: "%-d %b %Y"
45
+ full: "%-d %B %Y, %H:%M"
32
46
  breadcrumb:
33
47
  label: "Breadcrumb"
34
48
  code_block:
@@ -29,6 +29,20 @@ es:
29
29
  navigation: "Principal"
30
30
  dock:
31
31
  close: "Cerrar %{label}"
32
+ sidebar:
33
+ label: "Barra lateral"
34
+ collapse: "Contraer la barra lateral"
35
+ expand: "Expandir la barra lateral"
36
+ char_counter:
37
+ label: "%{count} de %{max} caracteres"
38
+ time:
39
+ now: "ahora"
40
+ minutes: "%{count} min"
41
+ hours: "%{count} h"
42
+ formats:
43
+ date: "%-d %b"
44
+ date_with_year: "%-d %b %Y"
45
+ full: "%-d de %B de %Y, %H:%M"
32
46
  breadcrumb:
33
47
  label: "Ruta de navegación"
34
48
  code_block:
@@ -29,6 +29,20 @@ ja:
29
29
  navigation: "メイン"
30
30
  dock:
31
31
  close: "%{label}を閉じる"
32
+ sidebar:
33
+ label: "サイドバー"
34
+ collapse: "サイドバーを折りたたむ"
35
+ expand: "サイドバーを展開する"
36
+ char_counter:
37
+ label: "%{max}文字中%{count}文字"
38
+ time:
39
+ now: "たった今"
40
+ minutes: "%{count}分"
41
+ hours: "%{count}時間"
42
+ formats:
43
+ date: "%-m月%-d日"
44
+ date_with_year: "%Y年%-m月%-d日"
45
+ full: "%Y年%-m月%-d日 %H:%M"
32
46
  breadcrumb:
33
47
  label: "パンくずリスト"
34
48
  code_block: