lostcoords-ui 0.9.1 → 0.10.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.
@@ -1,5 +1,14 @@
1
1
  module Lostcoords::Ui
2
2
  module DescriptionListHelper
3
+ STAT_TONES = { default: "text-foreground", primary: "text-primary", success: "text-success", warning: "text-warning", destructive: "text-destructive" }.freeze
4
+ STATS_COLUMNS = { nil => "grid-cols-[repeat(auto-fit,minmax(min(100%,9rem),1fr))]", 2 => "grid-cols-2", 3 => "grid-cols-3", 4 => "grid-cols-2 sm:grid-cols-4" }.freeze
5
+ STATS_LAYOUTS = {
6
+ inline: "flex flex-wrap items-baseline gap-x-section gap-y-tight",
7
+ grid: "grid gap-related"
8
+ }.freeze
9
+ STAT = "flex min-w-0 items-baseline gap-tight group-data-[layout=grid]/stats:flex-col group-data-[layout=grid]/stats:items-stretch " \
10
+ "group-data-[layout=grid]/stats:rounded-2xl group-data-[layout=grid]/stats:lc-squircle group-data-[layout=grid]/stats:bg-tile group-data-[layout=grid]/stats:p-content"
11
+
3
12
  # Yields a builder; `list.item "Owner", "Ada"` or `list.item("Owner") { … }` adds a row.
4
13
  # Rows stack on phones and sit in two columns from the sm breakpoint.
5
14
  def lc_description_list(**attributes, &block)
@@ -8,5 +17,35 @@ module Lostcoords::Ui
8
17
  capture(Parts::DescriptionList.new(self), &block) if block
9
18
  end
10
19
  end
20
+
21
+ # Headline numbers as a description list of lc_stat items. layout: :inline runs them along a line,
22
+ # each value followed by its label; :grid gives each a tile, the label under the value, in
23
+ # columns: (2, 3 or 4; nil fits as many as the width allows).
24
+ def lc_stats(layout: :inline, columns: nil, **attributes, &block)
25
+ layout = lc_option!(:layout, layout, STATS_LAYOUTS.keys)
26
+ raise ArgumentError, "columns: lays out a grid; pass layout: :grid" if columns && layout != :grid
27
+
28
+ columns = lc_option!(:columns, columns, STATS_COLUMNS.keys.compact) if columns
29
+ classes = lc_tw("group/stats m-0 min-w-0", STATS_LAYOUTS.fetch(layout), (STATS_COLUMNS.fetch(columns) if layout == :grid))
30
+ tag.dl(**lc_attributes({ class: classes, data: { slot: "stats", layout: layout } }, attributes)) do
31
+ capture(&block) if block
32
+ end
33
+ end
34
+
35
+ # One number in lc_stats: the value in bold tabular figures and its label in muted text. tone:
36
+ # colours the value with a status tone. A block replaces the value, such as a link around it.
37
+ def lc_stat(value = nil, label:, tone: :default, **attributes, &block)
38
+ lc_label!(label, :label)
39
+ tone = lc_option!(:tone, tone, STAT_TONES.keys)
40
+ value = capture(&block) if block
41
+ raise ArgumentError, "lc_stat needs a value or a block" if value.nil?
42
+
43
+ tag.div(**lc_attributes({ class: STAT, data: { slot: "stat", tone: (tone unless tone == :default) }.compact }, attributes)) do
44
+ safe_join([
45
+ tag.dt(label, class: "order-last text-small text-muted-foreground group-data-[layout=grid]/stats:text-caption", data: { slot: "stat-label" }),
46
+ tag.dd(value, class: lc_tw("m-0 text-heading font-semibold tabular-nums", STAT_TONES.fetch(tone)), data: { slot: "stat-value" })
47
+ ])
48
+ end
49
+ end
11
50
  end
12
51
  end
@@ -1,11 +1,11 @@
1
1
  module Lostcoords::Ui
2
2
  module FormHelper
3
3
  TOGGLE_GROUP_BASE =
4
- "inline-flex items-center gap-1 rounded-2xl bg-track p-1 lc-squircle"
4
+ "lc-toggle-group inline-flex items-center gap-1 rounded-2xl bg-track p-1 lc-squircle *:grow"
5
5
 
6
6
  TOGGLE_GROUP_ITEM_BASE =
7
- "lc-press inline-flex items-center justify-center gap-1.5 whitespace-nowrap " \
8
- "h-control-sm rounded-xl border-0 bg-transparent " \
7
+ "lc-toggle-group-item lc-press inline-flex items-center justify-center gap-1.5 whitespace-nowrap " \
8
+ "h-control-sm rounded-(--lc-toggle-item-radius,var(--radius-xl)) lc-squircle border-0 bg-transparent " \
9
9
  "px-3 font-sans text-label cursor-pointer no-underline " \
10
10
  "text-muted-foreground not-disabled:hover:text-foreground " \
11
11
  "aria-selected:bg-background aria-selected:text-foreground " \
@@ -18,7 +18,7 @@ module Lostcoords::Ui
18
18
  "has-disabled:cursor-not-allowed has-disabled:text-[color-mix(in_oklab,var(--foreground)_38%,transparent)] " \
19
19
  "[&_svg]:size-[1.1em] [&_svg]:shrink-0"
20
20
 
21
- TOGGLE_GROUP_ITEM_ACTIVE = "bg-background text-foreground hover:text-foreground"
21
+ TOGGLE_GROUP_ITEM_ACTIVE = "lc-toggle-group-item-active bg-background text-foreground hover:text-foreground"
22
22
 
23
23
  INPUT_BASE =
24
24
  "w-full max-w-full min-w-0 " \
@@ -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
@@ -5,6 +5,15 @@ module Lostcoords::Ui
5
5
  LIST_ROW_PADDING = "px-content py-heading sm:px-inset"
6
6
  LIST_ICON = "grid size-10 shrink-0 place-items-center rounded-full bg-tile [&>svg:not([class*='size-'])]:size-4.5"
7
7
  LIST_ROW_TAGS = %i[div li label details a].freeze
8
+ LIST_ROW_HOVER = "transition-colors duration-(--lc-motion-quick) hover:bg-accent"
9
+ # A linked li or div row: the title's link covers the row, the row's own controls sit above it,
10
+ # and the row shows the link's focus ring.
11
+ LIST_ROW_LINKED =
12
+ "relative has-[[data-slot=list-link]:focus-visible]:outline-2 has-[[data-slot=list-link]:focus-visible]:outline-offset-2 " \
13
+ "has-[[data-slot=list-link]:focus-visible]:outline-(--ring,color-mix(in_oklab,var(--primary)_50%,transparent)) " \
14
+ "[&_:is(a[href],button,input,select,textarea,summary,[tabindex]):not([data-slot=list-link])]:relative " \
15
+ "[&_:is(a[href],button,input,select,textarea,summary,[tabindex]):not([data-slot=list-link])]:z-raised"
16
+ LIST_LINK = "text-inherit no-underline focus-visible:outline-none after:absolute after:inset-0 after:rounded-[inherit] after:content-['']"
8
17
  LIST_FIELD_TAGS = %i[div fieldset span].freeze
9
18
  LIST_FIELD = "@container px-content py-2.5 transition-colors duration-(--lc-motion-quick) has-[[data-plain]:focus]:bg-accent"
10
19
  LIST_FIELD_GRID = "grid min-h-9 grid-cols-[1.25rem_minmax(0,1fr)] items-center gap-x-heading gap-y-related @md:grid-cols-[8rem_minmax(0,1fr)]"
@@ -37,14 +46,18 @@ module Lostcoords::Ui
37
46
 
38
47
  # With a title, the row lays out icon:, the title and subtitle, then the block as its trailing
39
48
  # content. Without one, the block is the whole row; padded: false drops the row's padding for
40
- # content that pads itself, such as an lc_list_item button. href: makes the row a link.
49
+ # content that pads itself, such as an lc_list_item button. href: makes the row a link. On an li
50
+ # or div row, the title is the link and covers the row, so the block can hold buttons and links
51
+ # of its own; a click elsewhere in the row follows the title.
41
52
  def lc_list_row(title = nil, subtitle: nil, icon: nil, href: nil, tag: nil, padded: true, **attributes, &block)
42
53
  tag = lc_option!(:tag, tag || (href ? :a : :div), LIST_ROW_TAGS)
43
- raise ArgumentError, "href: needs tag: :a" if href && tag != :a
54
+ titled = href && tag != :a
55
+ raise ArgumentError, "href: needs tag: :a, :li or :div" if titled && !%i[li div].include?(tag)
56
+ raise ArgumentError, "href: on an li or div row links its title, so it needs one" if titled && title.blank?
44
57
 
45
- link = ("no-underline transition-colors duration-(--lc-motion-quick) hover:bg-accent" if href)
46
- defaults = { href: href, data: { slot: "list-row" } }
47
- return lc_list_item(title, subtitle: subtitle, icon: icon, tag: tag, **lc_attributes(defaults.merge(class: lc_tw(LIST_ROW, link)), attributes), &block) if title.present?
58
+ link = (titled ? lc_tw(LIST_ROW_HOVER, LIST_ROW_LINKED) : lc_tw("no-underline", LIST_ROW_HOVER)) if href
59
+ defaults = { href: (href unless titled), data: { slot: "list-row" } }
60
+ return lc_list_item(title, subtitle: subtitle, icon: icon, link: (href if titled), tag: tag, **lc_attributes(defaults.merge(class: lc_tw(LIST_ROW, link)), attributes), &block) if title.present?
48
61
 
49
62
  classes = lc_tw(LIST_ROW, (LIST_ROW_PADDING if padded), link)
50
63
  content_tag(tag, (capture(&block) if block), **lc_attributes(defaults.merge(class: classes), attributes))
@@ -76,9 +89,11 @@ module Lostcoords::Ui
76
89
 
77
90
  # The row layout without the row's surface, for an element inside a free-form row: a summary, a
78
91
  # button that opens an editor. icon: takes an icon name or your own markup, such as a logo.
79
- def lc_list_item(title, subtitle: nil, icon: nil, tag: :div, **attributes, &block)
92
+ # link: links the title to that URL and stretches the link over the nearest positioned ancestor.
93
+ def lc_list_item(title, subtitle: nil, icon: nil, link: nil, tag: :div, **attributes, &block)
80
94
  lc_label!(title, :title)
81
95
  glyph = icon.is_a?(ActiveSupport::SafeBuffer) ? icon : lc_icon(icon) if icon.present?
96
+ title = link_to(title, link, class: LIST_LINK, data: { slot: "list-link" }) if link
82
97
  content_tag(tag, **lc_attributes({ class: LIST_ITEM, data: { slot: "list-item" } }, attributes)) do
83
98
  text = safe_join([
84
99
  content_tag(:span, title, class: "font-semibold", data: { slot: "list-title" }),
@@ -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
 
@@ -86,20 +86,21 @@ module Lostcoords::Ui
86
86
  tag.div(safe_join([ primary, toggle, popover ]), **lc_attributes(defaults, attributes))
87
87
  end
88
88
 
89
- def lc_icon_button(label, icon: nil, size: :md, shape: :circle, variant: :ghost, tone: :default, **attributes, &content)
89
+ def lc_icon_button(label, icon: nil, size: :md, shape: :circle, variant: :ghost, tone: :default, tooltip: nil, **attributes, &content)
90
90
  attributes = lc_icon_button_attributes(label, size, shape, variant, tone, { type: "button" }, attributes)
91
- tag.button(lc_icon_button_content(icon, &content), **attributes)
91
+ lc_icon_button_tooltip(label, tooltip, attributes) { |tip| tag.button(lc_icon_button_content(icon, &content), **lc_attributes(attributes, tip)) }
92
92
  end
93
93
 
94
- def lc_icon_button_link_to(label, url, icon: nil, size: :md, shape: :circle, variant: :ghost, tone: :default, **attributes, &content)
94
+ def lc_icon_button_link_to(label, url, icon: nil, size: :md, shape: :circle, variant: :ghost, tone: :default, tooltip: nil, **attributes, &content)
95
95
  attributes = lc_icon_button_attributes(label, size, shape, variant, tone, {}, attributes)
96
96
  raise ArgumentError, "Links cannot be disabled; use lc_icon_button for a disabled control" if attributes[:disabled]
97
97
 
98
- link_to(lc_icon_button_content(icon, &content), url, attributes)
98
+ lc_icon_button_tooltip(label, tooltip, attributes) { |tip| link_to(lc_icon_button_content(icon, &content), url, lc_attributes(attributes, tip)) }
99
99
  end
100
100
 
101
- def lc_icon_button_to(label, url, icon: nil, size: :md, shape: :circle, variant: :ghost, tone: :default, **attributes, &content)
102
- button_to(lc_icon_button_content(icon, &content), url, lc_icon_button_attributes(label, size, shape, variant, tone, {}, attributes))
101
+ def lc_icon_button_to(label, url, icon: nil, size: :md, shape: :circle, variant: :ghost, tone: :default, tooltip: nil, **attributes, &content)
102
+ attributes = lc_icon_button_attributes(label, size, shape, variant, tone, {}, attributes)
103
+ lc_icon_button_tooltip(label, tooltip, attributes) { |tip| button_to(lc_icon_button_content(icon, &content), url, lc_attributes(attributes, tip)) }
103
104
  end
104
105
 
105
106
  def lc_badge(content = nil, tone: :neutral, shape: :rounded, **attributes, &block)
@@ -153,8 +154,26 @@ module Lostcoords::Ui
153
154
  end
154
155
  end
155
156
 
156
- def lc_empty_state(**attributes, &block)
157
- 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
158
177
  end
159
178
 
160
179
  def lc_spinner(size: :md, label: lc_t("lostcoords.ui.spinner.label"), **attributes)
@@ -215,6 +234,16 @@ module Lostcoords::Ui
215
234
  attributes
216
235
  end
217
236
 
237
+ # tooltip: true shows the label on hover and keyboard focus; a string shows that text instead,
238
+ # and describes the button with it.
239
+ def lc_icon_button_tooltip(label, tooltip, attributes)
240
+ return yield({}) if tooltip.nil? || tooltip == false
241
+
242
+ text = tooltip == true ? label : tooltip
243
+ id = ("#{attributes[:id] || "lc-icon-button-#{@lc_tooltip_count = (@lc_tooltip_count || 0) + 1}"}-tooltip" unless text == label)
244
+ lc_tooltip(text, id: id) { |tip| yield(tip) }
245
+ end
246
+
218
247
  def lc_icon_button_content(icon, &content)
219
248
  raise ArgumentError, "Pass icon: or a block" unless icon || content
220
249
 
@@ -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
@@ -3,14 +3,15 @@ module Lostcoords::Ui
3
3
  TOOLTIP_SIDES = %i[top bottom].freeze
4
4
 
5
5
  # Yields attributes for the trigger; splat them with `**tip` so the trigger is described by the tooltip.
6
+ # Leave out id: when the tooltip repeats the trigger's own label, so it is not read twice.
6
7
  # The tooltip shows on hover and keyboard focus, and Escape hides it. It is a hint: keep essential information visible.
7
- def lc_tooltip(text, id:, side: :top, **attributes, &block)
8
+ def lc_tooltip(text, id: nil, side: :top, **attributes, &block)
8
9
  lc_label!(text, :text)
9
- lc_label!(id, :id)
10
+ lc_label!(id, :id) unless id.nil?
10
11
  side = lc_option!(:side, side, TOOLTIP_SIDES)
11
- trigger = capture({ aria: { describedby: id } }, &block) if block
12
+ trigger = capture(id ? { aria: { describedby: id } } : {}, &block) if block
12
13
  tag.span(**lc_attributes({ class: "lc-tooltip relative inline-flex", data: { slot: "tooltip", side: side, controller: "lc-tooltip", action: "mouseenter->lc-tooltip#show focusin->lc-tooltip#show mouseleave->lc-tooltip#hide focusout->lc-tooltip#hide" } }, attributes)) do
13
- safe_join([ trigger, tag.span(text, id: id, role: "tooltip", class: "lc-tooltip__content", data: { slot: "tooltip-content", lc_tooltip_target: "content" }) ].compact)
14
+ safe_join([ trigger, tag.span(text, id: id, role: ("tooltip" if id), aria: { hidden: ("true" unless id) }, class: "lc-tooltip__content", data: { slot: "tooltip-content", lc_tooltip_target: "content" }) ].compact)
14
15
  end
15
16
  end
16
17
  end
@@ -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,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
+ }
@@ -1,4 +1,5 @@
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"
@@ -14,6 +15,7 @@ import Search from "lostcoords/ui/controllers/lc_search_controller"
14
15
  import Selection from "lostcoords/ui/controllers/lc_selection_controller"
15
16
  import Sheet from "lostcoords/ui/controllers/lc_sheet_controller"
16
17
  import Shortcut from "lostcoords/ui/controllers/lc_shortcut_controller"
18
+ import Sidebar from "lostcoords/ui/controllers/lc_sidebar_controller"
17
19
  import Tabs from "lostcoords/ui/controllers/lc_tabs_controller"
18
20
  import Toast from "lostcoords/ui/controllers/lc_toast_controller"
19
21
  import ToastRegion from "lostcoords/ui/controllers/lc_toast_region_controller"
@@ -23,6 +25,7 @@ import Tooltip from "lostcoords/ui/controllers/lc_tooltip_controller"
23
25
 
24
26
  const controllers = {
25
27
  "lc-app-header": AppHeader,
28
+ "lc-char-counter": CharCounter,
26
29
  "lc-collapsible": Collapsible,
27
30
  "lc-code-block": CodeBlock,
28
31
  "lc-copy": Copy,
@@ -38,6 +41,7 @@ const controllers = {
38
41
  "lc-selection": Selection,
39
42
  "lc-sheet": Sheet,
40
43
  "lc-shortcut": Shortcut,
44
+ "lc-sidebar": Sidebar,
41
45
  "lc-tabs": Tabs,
42
46
  "lc-toc": Toc,
43
47
  "lc-toast": Toast,