number_flow 0.1.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 3f31e242cb8f5c29ef2c788129623d60d4cdd3bf5ce65ea92060fde290c51ae5
4
+ data.tar.gz: 87473cf2e807ab5779e983130a99012063a8bde1d8507ef341a61e17dfdbb883
5
+ SHA512:
6
+ metadata.gz: 517de85f88f290d45cd4037d6230f999512c42039fc65f71de607df1065698b17754b1bd82cafbbf5990818792809275ffc893d5c33460fda394a51a6dec72f0
7
+ data.tar.gz: 07ef80244873796464a53b19074a07606cc5b78a67b90df4756f3e50385ad575e8839953d3cc4da66de381c81086a736f4d72950cb8bbf7c3c1365862e72ba82
data/CHANGELOG.md ADDED
@@ -0,0 +1,18 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/)
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [0.1.0] - 2026-02-23
11
+
12
+ ### Added
13
+ - Initial release of `number_flow`.
14
+ - Rails helper API: `number_flow_tag`.
15
+ - Rails engine integration for helper and assets.
16
+ - Stimulus controller and CSS assets shipped inside the gem.
17
+ - Minitest suite for helper and integration contracts.
18
+
data/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 David
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
data/README.md ADDED
@@ -0,0 +1,124 @@
1
+ # NumberFlow
2
+
3
+ Rails helper + Stimulus controller for smooth integer digit transitions inspired by [number-flow](https://github.com/barvian/number-flow).
4
+
5
+ [![Gem Version](https://badge.fury.io/rb/number_flow.svg)](https://badge.fury.io/rb/number_flow)
6
+
7
+ `number_flow` ships both CSS and JavaScript assets inside the gem, so you do not need a separate npm package.
8
+
9
+ ## Original Project
10
+
11
+ This gem is inspired by and references the original Number Flow project by Barvian:
12
+ - https://github.com/barvian/number-flow
13
+
14
+ `number_flow` is a Ruby/Rails adaptation and is not an official package from the original project maintainers.
15
+
16
+ ## Installation
17
+
18
+ ```sh
19
+ bundle add number_flow
20
+ ```
21
+
22
+ Or:
23
+
24
+ ```sh
25
+ gem install number_flow
26
+ ```
27
+
28
+ ## Rails Setup
29
+
30
+ ### 1) Ensure the gem stylesheet is loaded
31
+
32
+ Add this in your layout (or import into your main stylesheet):
33
+
34
+ ```erb
35
+ <%= stylesheet_link_tag "number_flow", "data-turbo-track": "reload" %>
36
+ ```
37
+
38
+ ### 2) Register the Stimulus controller
39
+
40
+ With importmap (`config/importmap.rb`):
41
+
42
+ ```ruby
43
+ pin "number_flow/controller", to: "number_flow/controller.js"
44
+ ```
45
+
46
+ Then register in `app/javascript/controllers/index.js`:
47
+
48
+ ```js
49
+ import { application } from "./application"
50
+ import NumberFlowController from "number_flow/controller"
51
+
52
+ application.register("number-flow", NumberFlowController)
53
+ ```
54
+
55
+ ## Usage
56
+
57
+ Render a value:
58
+
59
+ ```erb
60
+ <%= number_flow_tag(12_345) %>
61
+ ```
62
+
63
+ Render with options:
64
+
65
+ ```erb
66
+ <%= number_flow_tag(
67
+ 12_345,
68
+ class: "kpi-value",
69
+ duration: 550,
70
+ easing: "ease-out",
71
+ stagger: 30,
72
+ grouping: true,
73
+ aria_label: "Current total users"
74
+ ) %>
75
+ ```
76
+
77
+ Update from JavaScript:
78
+
79
+ ```js
80
+ const element = document.querySelector("[data-controller='number-flow']")
81
+ element.dispatchEvent(
82
+ new CustomEvent("number-flow:update", {
83
+ detail: { value: 12987 }
84
+ })
85
+ )
86
+ ```
87
+
88
+ ## API
89
+
90
+ ### `number_flow_tag(value, **options)`
91
+
92
+ Options:
93
+ - `id:` DOM id
94
+ - `class:` extra CSS classes
95
+ - `duration:` animation duration in milliseconds (default: `400`)
96
+ - `easing:` CSS easing function (default: `cubic-bezier(0.2, 0, 0, 1)`)
97
+ - `stagger:` per-digit delay in milliseconds (default: `20`)
98
+ - `grouping:` show thousands separators (default: `false`)
99
+ - `aria_label:` explicit `aria-label`
100
+ - `data:` additional data attributes merged into the root element
101
+
102
+ ## Accessibility
103
+
104
+ - Root element uses `role="status"` and `aria-live="polite"`.
105
+ - `prefers-reduced-motion: reduce` disables animated transitions while still updating values.
106
+
107
+ ## Error Handling
108
+
109
+ `number_flow_tag` raises `ArgumentError` when `value` cannot be coerced into an integer.
110
+
111
+ ## Development
112
+
113
+ ```sh
114
+ bundle exec rake test
115
+ bundle exec rubocop
116
+ ```
117
+
118
+ ## Contributing
119
+
120
+ Bug reports and pull requests are welcome on [GitHub](https://github.com/dpaluy/number_flow/issues).
121
+
122
+ ## License
123
+
124
+ MIT. See `LICENSE.txt`.
@@ -0,0 +1,184 @@
1
+ import { Controller } from "@hotwired/stimulus"
2
+
3
+ const UPDATE_EVENT = "number-flow:update"
4
+
5
+ export default class extends Controller {
6
+ static values = {
7
+ value: Number,
8
+ duration: Number,
9
+ easing: String,
10
+ stagger: Number,
11
+ grouping: Boolean
12
+ }
13
+
14
+ connect() {
15
+ this.handleUpdate = this.handleUpdate.bind(this)
16
+ this.reducedMotionMedia = window.matchMedia("(prefers-reduced-motion: reduce)")
17
+ this.element.addEventListener(UPDATE_EVENT, this.handleUpdate)
18
+
19
+ this.applyTimingVariables()
20
+ this.currentValue = this.initialValue()
21
+ this.currentParts = []
22
+ this.render(this.currentValue, false)
23
+ }
24
+
25
+ disconnect() {
26
+ this.element.removeEventListener(UPDATE_EVENT, this.handleUpdate)
27
+ }
28
+
29
+ valueValueChanged(nextValue, previousValue) {
30
+ if (previousValue === undefined) return
31
+
32
+ this.updateTo(nextValue)
33
+ }
34
+
35
+ handleUpdate(event) {
36
+ const nextValue = Number(event?.detail?.value)
37
+ if (!Number.isFinite(nextValue)) {
38
+ if (this.isDevelopmentEnv()) {
39
+ console.warn("[number_flow] Ignoring non-numeric number-flow:update payload.")
40
+ }
41
+ return
42
+ }
43
+
44
+ this.updateTo(Math.trunc(nextValue))
45
+ }
46
+
47
+ updateTo(nextValue) {
48
+ const normalized = Math.trunc(nextValue)
49
+ if (normalized === this.currentValue) return
50
+
51
+ this.applyTimingVariables()
52
+ this.render(normalized, !this.prefersReducedMotion())
53
+ this.currentValue = normalized
54
+ this.valueValue = normalized
55
+ }
56
+
57
+ render(value, animate) {
58
+ const previousDigits = this.currentParts.filter((part) => part.kind === "digit").map((part) => part.value)
59
+ const nextParts = this.partsFor(value)
60
+ const nextDigits = nextParts.filter((part) => part.kind === "digit").map((part) => part.value)
61
+
62
+ let digitIndex = 0
63
+ const totalDigits = nextDigits.length
64
+ const fragment = document.createDocumentFragment()
65
+
66
+ nextParts.forEach((part) => {
67
+ if (part.kind === "separator") {
68
+ fragment.appendChild(this.buildSeparatorNode(part.value))
69
+ return
70
+ }
71
+
72
+ const remaining = totalDigits - digitIndex
73
+ const previousIndex = previousDigits.length - remaining
74
+ const fromDigit = previousIndex >= 0 ? previousDigits[previousIndex] : 0
75
+ const toDigit = part.value
76
+ const indexFromRight = totalDigits - digitIndex - 1
77
+ fragment.appendChild(this.buildDigitNode(fromDigit, toDigit, indexFromRight, animate))
78
+ digitIndex += 1
79
+ })
80
+
81
+ this.element.replaceChildren(fragment)
82
+ this.element.setAttribute("aria-label", this.formattedString(value))
83
+
84
+ if (animate && !this.prefersReducedMotion()) {
85
+ requestAnimationFrame(() => {
86
+ this.element.querySelectorAll(".nf__track--animated").forEach((track) => {
87
+ track.style.setProperty("--nf-current-digit", track.dataset.toDigit)
88
+ })
89
+ })
90
+ }
91
+
92
+ this.currentParts = nextParts
93
+ }
94
+
95
+ partsFor(value) {
96
+ return this.formattedString(value).split("").map((char) => {
97
+ if (/\d/.test(char)) {
98
+ return { kind: "digit", value: Number(char) }
99
+ }
100
+
101
+ return { kind: "separator", value: char }
102
+ })
103
+ }
104
+
105
+ formattedString(value) {
106
+ const sign = value < 0 ? "-" : ""
107
+ const digits = Math.abs(value).toString()
108
+ const groupedDigits = this.groupingValue ? digits.replace(/\B(?=(\d{3})+(?!\d))/g, ",") : digits
109
+ return `${sign}${groupedDigits}`
110
+ }
111
+
112
+ buildDigitNode(fromDigit, toDigit, indexFromRight, animate) {
113
+ const digit = document.createElement("span")
114
+ digit.className = "nf__digit"
115
+ digit.dataset.digit = String(toDigit)
116
+ digit.style.setProperty("--nf-index-from-right", String(indexFromRight))
117
+
118
+ const track = document.createElement("span")
119
+ track.className = animate ? "nf__track nf__track--animated" : "nf__track"
120
+ track.dataset.toDigit = String(toDigit)
121
+ track.style.setProperty("--nf-from-digit", String(fromDigit))
122
+ track.style.setProperty("--nf-to-digit", String(toDigit))
123
+ track.style.setProperty("--nf-current-digit", String(animate ? fromDigit : toDigit))
124
+
125
+ for (let value = 0; value <= 9; value += 1) {
126
+ const cell = document.createElement("span")
127
+ cell.className = "nf__cell"
128
+ cell.setAttribute("aria-hidden", "true")
129
+ cell.textContent = String(value)
130
+ track.appendChild(cell)
131
+ }
132
+
133
+ digit.appendChild(track)
134
+ return digit
135
+ }
136
+
137
+ buildSeparatorNode(value) {
138
+ const separator = document.createElement("span")
139
+ separator.className = "nf__separator"
140
+ separator.setAttribute("aria-hidden", "true")
141
+ separator.textContent = value
142
+ return separator
143
+ }
144
+
145
+ applyTimingVariables() {
146
+ this.element.style.setProperty("--nf-duration", `${this.durationOrDefault()}ms`)
147
+ this.element.style.setProperty("--nf-easing", this.easingOrDefault())
148
+ this.element.style.setProperty("--nf-stagger", `${this.staggerOrDefault()}ms`)
149
+ }
150
+
151
+ initialValue() {
152
+ if (this.hasValueValue && Number.isFinite(this.valueValue)) {
153
+ return Math.trunc(this.valueValue)
154
+ }
155
+
156
+ const inlineValue = Number(this.element.getAttribute("data-number-flow-value-value"))
157
+ if (Number.isFinite(inlineValue)) {
158
+ return Math.trunc(inlineValue)
159
+ }
160
+
161
+ return 0
162
+ }
163
+
164
+ prefersReducedMotion() {
165
+ return this.reducedMotionMedia.matches
166
+ }
167
+
168
+ durationOrDefault() {
169
+ return this.hasDurationValue ? this.durationValue : 400
170
+ }
171
+
172
+ easingOrDefault() {
173
+ return this.hasEasingValue ? this.easingValue : "cubic-bezier(0.2, 0, 0, 1)"
174
+ }
175
+
176
+ staggerOrDefault() {
177
+ return this.hasStaggerValue ? this.staggerValue : 20
178
+ }
179
+
180
+ isDevelopmentEnv() {
181
+ return typeof document !== "undefined" && document.location?.hostname === "localhost"
182
+ }
183
+ }
184
+
@@ -0,0 +1,56 @@
1
+ .nf {
2
+ --nf-duration: 400ms;
3
+ --nf-easing: cubic-bezier(0.2, 0, 0, 1);
4
+ --nf-stagger: 20ms;
5
+ --nf-digit-height: 1em;
6
+ --nf-gap: 0.04em;
7
+
8
+ display: inline-flex;
9
+ align-items: flex-end;
10
+ gap: var(--nf-gap);
11
+ line-height: 1;
12
+ white-space: nowrap;
13
+ font-variant-numeric: tabular-nums;
14
+ }
15
+
16
+ .nf__digit,
17
+ .nf__separator {
18
+ display: inline-flex;
19
+ align-items: center;
20
+ justify-content: center;
21
+ height: var(--nf-digit-height);
22
+ }
23
+
24
+ .nf__digit {
25
+ position: relative;
26
+ width: 0.68em;
27
+ overflow: hidden;
28
+ }
29
+
30
+ .nf__track {
31
+ display: flex;
32
+ flex-direction: column;
33
+ transform: translateY(calc(var(--nf-current-digit, 0) * var(--nf-digit-height) * -1));
34
+ will-change: transform;
35
+ }
36
+
37
+ .nf__track--animated {
38
+ transition-property: transform;
39
+ transition-duration: var(--nf-duration);
40
+ transition-timing-function: var(--nf-easing);
41
+ transition-delay: calc(var(--nf-stagger) * var(--nf-index-from-right, 0));
42
+ }
43
+
44
+ .nf__cell {
45
+ display: inline-flex;
46
+ align-items: center;
47
+ justify-content: center;
48
+ height: var(--nf-digit-height);
49
+ }
50
+
51
+ @media (prefers-reduced-motion: reduce) {
52
+ .nf__track--animated {
53
+ transition: none;
54
+ }
55
+ }
56
+
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ begin
4
+ require 'active_support/core_ext/module/delegation'
5
+ require 'rails/engine'
6
+ rescue LoadError
7
+ # Rails is not available in this runtime.
8
+ end
9
+
10
+ module NumberFlow
11
+ if defined?(Rails)
12
+ class Engine < ::Rails::Engine
13
+ initializer 'number_flow.action_view' do
14
+ ActiveSupport.on_load(:action_view) do
15
+ include NumberFlow::Helper
16
+ end
17
+ end
18
+
19
+ initializer 'number_flow.assets.precompile' do |app|
20
+ next unless app.config.respond_to?(:assets)
21
+
22
+ app.config.assets.precompile += %w[number_flow.css number_flow/controller.js]
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,104 @@
1
+ # frozen_string_literal: true
2
+
3
+ module NumberFlow
4
+ # View helper that renders number-flow compatible markup.
5
+ module Helper
6
+ DEFAULT_DURATION = 400
7
+ DEFAULT_EASING = 'cubic-bezier(0.2, 0, 0, 1)'
8
+ DEFAULT_STAGGER = 20
9
+
10
+ def number_flow_tag(
11
+ value,
12
+ id: nil,
13
+ duration: DEFAULT_DURATION,
14
+ easing: DEFAULT_EASING,
15
+ stagger: DEFAULT_STAGGER,
16
+ grouping: false,
17
+ aria_label: nil,
18
+ data: {},
19
+ **html_options
20
+ )
21
+ normalized_value = Integer(value)
22
+ formatted_value = format_integer(normalized_value, grouping: grouping)
23
+ css_class = html_options.delete(:class)
24
+ extra_data = html_options.delete(:data)
25
+
26
+ root_options = {
27
+ id: id,
28
+ role: 'status',
29
+ class: ['nf', css_class].compact.join(' '),
30
+ aria: {
31
+ live: 'polite',
32
+ label: aria_label || formatted_value
33
+ },
34
+ data: merged_data_attributes(
35
+ {
36
+ controller: 'number-flow',
37
+ number_flow_value_value: normalized_value,
38
+ number_flow_duration_value: Integer(duration),
39
+ number_flow_easing_value: easing.to_s,
40
+ number_flow_stagger_value: Integer(stagger),
41
+ number_flow_grouping_value: grouping == true
42
+ },
43
+ normalize_data_hash(data),
44
+ normalize_data_hash(extra_data)
45
+ )
46
+ }.merge(html_options.compact)
47
+
48
+ content_tag(:span, **root_options) do
49
+ safe_join(formatted_value.chars.map { |char| build_character_fragment(char) })
50
+ end
51
+ rescue ArgumentError, TypeError
52
+ raise ArgumentError, 'number_flow_tag expects an integer-compatible value'
53
+ end
54
+
55
+ private
56
+
57
+ def build_character_fragment(char)
58
+ if char.match?(/\d/)
59
+ build_digit_fragment(char.to_i)
60
+ else
61
+ content_tag(:span, char, class: 'nf__separator', 'aria-hidden': 'true')
62
+ end
63
+ end
64
+
65
+ def build_digit_fragment(digit)
66
+ cells = safe_join(
67
+ (0..9).map do |value|
68
+ content_tag(:span, value.to_s, class: 'nf__cell', 'aria-hidden': 'true')
69
+ end
70
+ )
71
+
72
+ content_tag(:span, class: 'nf__digit', data: { digit: digit }) do
73
+ content_tag(
74
+ :span,
75
+ cells,
76
+ class: 'nf__track',
77
+ data: { to_digit: digit },
78
+ style: "--nf-current-digit: #{digit}; --nf-from-digit: #{digit}; --nf-to-digit: #{digit};"
79
+ )
80
+ end
81
+ end
82
+
83
+ def format_integer(value, grouping:)
84
+ sign = value.negative? ? '-' : ''
85
+ digits = value.abs.to_s
86
+ grouped = grouping ? digits.reverse.scan(/.{1,3}/).join(',').reverse : digits
87
+ "#{sign}#{grouped}"
88
+ end
89
+
90
+ def merged_data_attributes(*hashes)
91
+ hashes.each_with_object({}) do |hash, merged|
92
+ hash.each { |key, value| merged[key.to_sym] = value unless value.nil? }
93
+ end
94
+ end
95
+
96
+ def normalize_data_hash(data)
97
+ return {} unless data.respond_to?(:each)
98
+
99
+ data.transform_keys do |key|
100
+ key.to_s.tr('-', '_').to_sym
101
+ end
102
+ end
103
+ end
104
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module NumberFlow
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'number_flow/version'
4
+ require_relative 'number_flow/helper'
5
+ require_relative 'number_flow/engine'
6
+
7
+ module NumberFlow
8
+ class Error < StandardError; end
9
+ end
metadata ADDED
@@ -0,0 +1,87 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: number_flow
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - dpaluy
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: actionview
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: 8.1.0
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: 8.1.0
26
+ - !ruby/object:Gem::Dependency
27
+ name: railties
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: 8.1.0
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: 8.1.0
40
+ description: NumberFlow provides a Rails helper and Stimulus controller for smooth
41
+ integer digit transitions using gem-shipped CSS and JavaScript assets.
42
+ email:
43
+ - dpaluy@users.noreply.github.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files:
47
+ - CHANGELOG.md
48
+ - LICENSE.txt
49
+ - README.md
50
+ files:
51
+ - CHANGELOG.md
52
+ - LICENSE.txt
53
+ - README.md
54
+ - app/assets/javascripts/number_flow/controller.js
55
+ - app/assets/stylesheets/number_flow.css
56
+ - lib/number_flow.rb
57
+ - lib/number_flow/engine.rb
58
+ - lib/number_flow/helper.rb
59
+ - lib/number_flow/version.rb
60
+ homepage: https://github.com/dpaluy/number_flow#readme
61
+ licenses:
62
+ - MIT
63
+ metadata:
64
+ rubygems_mfa_required: 'true'
65
+ homepage_uri: https://github.com/dpaluy/number_flow#readme
66
+ documentation_uri: https://rubydoc.info/gems/number_flow
67
+ source_code_uri: https://github.com/dpaluy/number_flow
68
+ changelog_uri: https://github.com/dpaluy/number_flow/blob/main/CHANGELOG.md
69
+ bug_tracker_uri: https://github.com/dpaluy/number_flow/issues
70
+ rdoc_options: []
71
+ require_paths:
72
+ - lib
73
+ required_ruby_version: !ruby/object:Gem::Requirement
74
+ requirements:
75
+ - - ">="
76
+ - !ruby/object:Gem::Version
77
+ version: 3.4.0
78
+ required_rubygems_version: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ requirements: []
84
+ rubygems_version: 4.0.3
85
+ specification_version: 4
86
+ summary: Rails helper + Stimulus digit flow transitions for integers.
87
+ test_files: []