tipasa 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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: bb1e74e3129ed6d4165cf34f0890285b3d5984a4b659469753bbf654e50fe104
4
+ data.tar.gz: 8e0b016c6b796212502352293c2aa61ac7fca727534e4f2e9888922ec593b243
5
+ SHA512:
6
+ metadata.gz: f80a72da16ab30d151538cc5ca32accaeb60e91e99562ae2cebb37fd9f5acfa0f742a9ea91efa3e8d4f2db36d51609436ecfafbec62dfee48be690f3e1d313f2
7
+ data.tar.gz: f045c9c4b9168c2b320f82032f1e357b133b95fcb5c07e7fea055bf8a1c8fca64d74bbe4f46ede2c7fdd98263e825f1ad7e72566065fcbb05b10f4f8ab1b1c0b
data/CHANGELOG.md ADDED
@@ -0,0 +1,8 @@
1
+ # Changelog
2
+
3
+ ## [0.2.0](https://github.com/ACR1209/tipasa/compare/tipasa-v0.1.0...tipasa/v0.2.0) (2026-11-16)
4
+
5
+
6
+ ### Features
7
+
8
+ * initial tipasa engine and Stimulus controller ([3a89582](https://github.com/ACR1209/tipasa/commit/3a895822cda89cac8c4a3b1f4d72ae93fc124f3b))
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright ACR1209
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,160 @@
1
+ # Tipasa
2
+
3
+ > In the midst of winter, I found there was, within me, an invincible summer.
4
+ > - Albert Camus on _Return to Tipasa_
5
+
6
+ Guided product tours for Rails, written in YAML.
7
+
8
+ Tipasa is a Rails engine plus a Stimulus controller. You describe each tour in `config/tours/<slug>.yml`; the engine serves it, records who completed it, and the controller walks the user through it with [driver.js](https://driverjs.com) (MIT).
9
+
10
+
11
+ ## Installation
12
+
13
+ ```ruby
14
+ # Gemfile
15
+ gem "tipasa"
16
+ ```
17
+
18
+ ```bash
19
+ bundle install
20
+ bin/rails g tipasa:install # initializer, config/tours/, route, migration
21
+ bin/rails db:migrate
22
+ yarn add tipasa # or npm install tipasa
23
+ ```
24
+
25
+ Register the controller (esbuild, Vite, webpack...):
26
+
27
+ ```js
28
+ // app/javascript/controllers/index.js
29
+ import TipasaController from "tipasa";
30
+ application.register("tipasa", TipasaController);
31
+ ```
32
+
33
+ Load the styles in your CSS build (Tailwind CLI, cssbundling, PostCSS):
34
+
35
+ ```css
36
+ @import "tipasa/tipasa.css";
37
+ ```
38
+
39
+ Importmap apps aren't supported yet.
40
+
41
+ ## Writing a tour
42
+
43
+ The file name is the slug: `config/tours/agenda.yml` is the `agenda` tour.
44
+
45
+ ```yaml
46
+ name: "Agenda"
47
+ description: "The agenda in four steps"
48
+ active: true # default true; false hides the tour
49
+ for: [User] # optional: only these owner classes see it (see below)
50
+ steps:
51
+ - id: "welcome"
52
+ title: "Welcome!"
53
+ text: "A step without element_selector is centered. <b>HTML</b> is allowed."
54
+ - id: "calendar"
55
+ title: "Calendar"
56
+ text: "Move between dates here."
57
+ element_selector: "#calendar"
58
+ ```
59
+
60
+ Step keys:
61
+
62
+ | Key | What it does |
63
+ |---|---|
64
+ | `id`, `title`, `text` | Identity and content. `text` is rendered as HTML, so only put trusted content in it. |
65
+ | `element_selector` | What the step points at. Without it the step is centered. |
66
+ | `attach_to` | `top`, `right`, `bottom` (default) or `left`. Left/right fall back to bottom on phones. |
67
+ | `optional` | Skip the step when `element_selector` isn't on the page. |
68
+ | `wait_for` | Selector to wait for (up to 3s) before showing the step. |
69
+ | `padding`, `radius` | Pixels around the highlighted element, and its corner radius. |
70
+ | `highlight_class` | Class added to the element. Steps that wait for the user pulse (`tipasa-pulse`) by default. |
71
+ | `extra_highlights` | More selectors kept visible and clickable. |
72
+ | `advance_on` | Event on the element (e.g. `click`) that moves on. The step has no Next button. |
73
+ | `await_more` | Selector: the tour hides while the user works in a modal and moves on when more elements match it (e.g. one more row). |
74
+ | `await_modal` | `true`: the tour hides until the modal the element opens is closed. |
75
+ | `button` | Text for this step's Next button. |
76
+ | `ping_url` | POSTed (with the CSRF token) when the user presses Next. |
77
+ | `next_url` | Completes the tour and visits this URL (Turbo if present), e.g. `/people?tour=people`. |
78
+ | `finish_url` | Completes the tour and submits a POST form to this URL. |
79
+
80
+ ## Showing a tour
81
+
82
+ ```erb
83
+ <%# In the layout: starts the tour named in ?tour=, e.g. /agenda?tour=agenda %>
84
+ <%= tipasa_autostart %>
85
+
86
+ <%# A help button that replays the tour. Unstyled: bring your own classes and icon. %>
87
+ <%= tipasa_button "agenda", class: "help-button" do %>
88
+ <%= lucide_icon "circle-help" %>
89
+ <% end %>
90
+ ```
91
+
92
+ A tour started with `?tour=` plays even if it was completed. Add `&resume=1` to reopen it at the step where the user closed it.
93
+
94
+ Closing a tour (with the ×, Escape, or by replaying another one) counts as completing it, the same as finishing it. Leaving the page doesn't.
95
+
96
+ ## Configuration
97
+
98
+ ```ruby
99
+ # config/initializers/tipasa.rb
100
+ Tipasa.configure do |config|
101
+ # Who takes the tour on this request; nil when nobody is signed in.
102
+ config.current_owner = ->(c) { c.current_user || c.current_admin_user }
103
+
104
+ # Defaults to ActionController::Base, so your before_actions don't run on the tour endpoints.
105
+ # config.parent_controller = "ApplicationController"
106
+
107
+ # Button and hint language (en and es ship with the gem); nil follows I18n.locale.
108
+ # config.locale = :es
109
+
110
+ # config.tours_path = Rails.root.join("config/tours")
111
+ end
112
+ ```
113
+
114
+ To change the text, override the `tipasa.*` keys in your locale files. See [config/locales/en.yml](config/locales/en.yml).
115
+
116
+ ## Owners and completions
117
+
118
+ Owners are polymorphic: any model can take tours.
119
+
120
+ ```ruby
121
+ class User < ApplicationRecord
122
+ include Tipasa::Owner
123
+ end
124
+
125
+ user.completed_tour?("agenda") # => true / false
126
+ user.pending_tours # active tours this user may see and hasn't completed
127
+ user.tipasa_completions # Tipasa::Completion records (owner, tour_slug, timestamps)
128
+ ```
129
+
130
+ `for: [AdminUser]` limits a tour to those classes. Everyone else, including anonymous visitors, gets a 404 for it, and it's left out of `pending_tours`. A tour without `for:` is visible to everyone, signed in or not. Only signed-in owners can complete one.
131
+
132
+ Completions are keyed by slug, so renaming a tour's file resets who has completed it.
133
+
134
+ ## Endpoints
135
+
136
+ Mounted where the installer put it (`/tours` by default):
137
+
138
+ - `GET /tours/:slug`: the tour as JSON, plus `completed` for the current owner.
139
+ - `POST /tours/:slug/complete`: records the completion (401 without an owner).
140
+
141
+ ## Styling
142
+
143
+ `tipasa.css` imports driver.js's styles and adds the step counter, the "waiting" hint and the pulse. Theme it with `--tipasa-accent` and the `--driver-*` variables, or target `.tipasa-popover`.
144
+
145
+ ## Development
146
+
147
+ ```bash
148
+ bundle install
149
+ bundle exec rspec
150
+ bin/rubocop
151
+ RAILS_VERSION="~> 7.2.0" bundle update && bundle exec rspec # other Rails versions
152
+ ```
153
+
154
+ ## Releasing
155
+
156
+ Releases are managed by [release-please](https://github.com/googleapis/release-please). PR titles must follow [Conventional Commits](https://www.conventionalcommits.org) (`feat:`, `fix:`, `feat!:`). Merging the release PR tags the version and publishes the gem and the npm package with the same version number, using trusted publishing on rubygems.org and npmjs.com.
157
+
158
+ ## License
159
+
160
+ MIT. driver.js is MIT too, so commercial apps need no extra license.
@@ -0,0 +1,66 @@
1
+ /* Tipasa: driver.js base styles plus the step counter, the "waiting" hint and the pulse.
2
+ Theme it with --tipasa-accent (pulse and hint dot) and the --driver-* variables. */
3
+ @import "driver.js/dist/driver.css";
4
+
5
+ .tipasa-popover.driver-popover {
6
+ border-radius: 12px;
7
+ padding: 20px;
8
+ max-width: 340px;
9
+ box-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1);
10
+ }
11
+
12
+ .tipasa-popover .driver-popover-footer {
13
+ gap: 8px;
14
+ }
15
+
16
+ .tipasa-popover .driver-popover-description :is(img, video) {
17
+ display: block;
18
+ max-width: 100%;
19
+ height: auto;
20
+ margin-top: 12px;
21
+ border-radius: 8px;
22
+ }
23
+
24
+ .tipasa-popover .tipasa-progress,
25
+ .tipasa-popover .tipasa-waiting {
26
+ margin-right: auto;
27
+ align-self: center;
28
+ font-size: 12px;
29
+ font-weight: 600;
30
+ color: #6b7280;
31
+ }
32
+
33
+ .tipasa-popover .tipasa-waiting {
34
+ display: inline-flex;
35
+ align-items: center;
36
+ gap: 6px;
37
+ }
38
+
39
+ .tipasa-popover .tipasa-waiting-dot {
40
+ width: 8px;
41
+ height: 8px;
42
+ border-radius: 9999px;
43
+ background: var(--tipasa-accent, #2563eb);
44
+ animation: tipasa-blink 1.4s ease-in-out infinite;
45
+ }
46
+
47
+ @keyframes tipasa-blink {
48
+ 50% { opacity: 0.3; }
49
+ }
50
+
51
+ @keyframes tipasa-pulse {
52
+ 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--tipasa-accent, #2563eb) 70%, transparent); }
53
+ 70%, 100% { box-shadow: 0 0 0 14px transparent; }
54
+ }
55
+
56
+ .tipasa-pulse {
57
+ outline: 2px solid var(--tipasa-accent, #2563eb);
58
+ animation: tipasa-pulse 1.4s ease-out infinite;
59
+ }
60
+
61
+ @media (prefers-reduced-motion: reduce) {
62
+ .tipasa-pulse,
63
+ .tipasa-popover .tipasa-waiting-dot {
64
+ animation: none;
65
+ }
66
+ }
@@ -0,0 +1,5 @@
1
+ module Tipasa
2
+ class ApplicationController < Tipasa.parent_controller.constantize
3
+ protect_from_forgery with: :exception
4
+ end
5
+ end
@@ -0,0 +1,35 @@
1
+ module Tipasa
2
+ class ToursController < ApplicationController
3
+ before_action :set_tour
4
+
5
+ def show
6
+ completed = owner.present? && Completion.exists?(owner:, tour_slug: @tour.slug)
7
+ render json: @tour.as_json.merge(completed:)
8
+ end
9
+
10
+ def complete
11
+ return head :unauthorized unless owner
12
+
13
+ begin
14
+ Completion.find_or_create_by!(owner:, tour_slug: @tour.slug)
15
+ rescue ActiveRecord::RecordNotUnique
16
+ # A double request raced us to it; the tour is completed either way.
17
+ end
18
+
19
+ render json: { success: true }
20
+ end
21
+
22
+ private
23
+
24
+ def set_tour
25
+ @tour = Tour.find(params[:slug])
26
+ head :not_found unless @tour&.active? && @tour.visible_to?(owner)
27
+ end
28
+
29
+ def owner
30
+ return @owner if defined?(@owner)
31
+
32
+ @owner = Tipasa.current_owner.call(self)
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,344 @@
1
+ import { Controller } from "@hotwired/stimulus";
2
+ import { driver } from "driver.js";
3
+
4
+ // The controller whose tour is on screen, so a replay elsewhere can close it first.
5
+ let active = null;
6
+
7
+ // Register as "tipasa": application.register("tipasa", TipasaController)
8
+ // The tipasa_button and tipasa_autostart helpers render the element and its values.
9
+ export default class TipasaController extends Controller {
10
+ static values = {
11
+ slug: String,
12
+ url: String,
13
+ completeUrl: String,
14
+ labels: Object,
15
+ replay: Boolean,
16
+ resume: Boolean,
17
+ manual: Boolean
18
+ };
19
+
20
+ // A manual tour (a help button) waits for a click on replay instead of starting on load.
21
+ connect() {
22
+ if (!this.manualValue) this.load();
23
+ }
24
+
25
+ // Starts the tour again even if it was completed, closing whichever tour is open.
26
+ // Clicks while the tour loads are ignored, so a double click doesn't start it twice.
27
+ async replay() {
28
+ if (this.loading) return;
29
+ this.loading = true;
30
+ try {
31
+ active?.stop();
32
+ this.replayValue = true;
33
+ await this.load();
34
+ } finally {
35
+ this.loading = false;
36
+ }
37
+ }
38
+
39
+ // Leaving the page isn't finishing the tour, so nothing is recorded.
40
+ disconnect() {
41
+ this.end({ record: false });
42
+ }
43
+
44
+ async load() {
45
+ const response = await fetch(this.urlValue, { credentials: "same-origin", headers: { Accept: "application/json" } });
46
+ if (!response.ok) return;
47
+
48
+ const tour = await response.json();
49
+ if (tour.completed && !this.replayValue) return;
50
+
51
+ this.steps = tour.steps;
52
+ // Fixed when the tour starts, so skipped steps don't make the counter jump around.
53
+ this.progressIds = this.steps.filter((step) => this.present(step)).map((step) => step.id);
54
+
55
+ // Remembers the step on screen, so a tour closed with the x (or left) can be reopened there
56
+ // with ?resume=1. Any other start begins at the first step.
57
+ const resumeAt = this.resumeValue ? this.steps.findIndex((step) => step.id === this.savedStep()) : -1;
58
+ this.go(resumeAt >= 0 ? resumeAt : this.nextIndex(-1));
59
+ }
60
+
61
+ // Shows step `index`, building the driver if it isn't on screen (first step, or back from a pause).
62
+ async go(index) {
63
+ if (index < 0) return this.finish();
64
+
65
+ const step = this.steps[index];
66
+ if (step.wait_for) await this.waitFor(step.wait_for);
67
+ if (!this.element.isConnected) return;
68
+
69
+ if (this.driver?.isActive()) {
70
+ this.driver.moveTo(index);
71
+ } else {
72
+ this.build();
73
+ this.driver.drive(index);
74
+ }
75
+ }
76
+
77
+ build() {
78
+ active = this;
79
+ const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
80
+ this.driver = driver({
81
+ steps: this.steps.map((step, index) => this.driveStep(step, index)),
82
+ animate: !reduceMotion,
83
+ smoothScroll: !reduceMotion,
84
+ overlayClickBehavior: "none",
85
+ // The arrow keys would move the driver past our own next/back (ping_url, next_url, optional steps).
86
+ allowKeyboardControl: false,
87
+ popoverClass: "tipasa-popover"
88
+ });
89
+ this.onKeydown ||= (event) => event.key === "Escape" && this.stop();
90
+ document.addEventListener("keydown", this.onKeydown);
91
+ }
92
+
93
+ // Takes the tour off screen without ending it (the user is acting in a modal); go() builds it again.
94
+ pause() {
95
+ document.removeEventListener("keydown", this.onKeydown);
96
+ this.driver?.destroy();
97
+ }
98
+
99
+ driveStep(step, index) {
100
+ const labels = this.labelsValue;
101
+ const last = index === this.steps.length - 1;
102
+ // A step that waits for the user (await_more, await_modal, advance_on) has no Next: doing the action moves the tour on.
103
+ const buttons = ["close", ...(index > 0 ? ["previous"] : []), ...(this.waitsForUser(step) ? [] : ["next"])];
104
+ const nextText = step.button || (last ? labels.done : labels.next);
105
+
106
+ return {
107
+ element: step.element_selector || undefined,
108
+ allowedElements: step.extra_highlights,
109
+ popover: {
110
+ title: step.title,
111
+ description: step.text,
112
+ side: this.placement(step),
113
+ align: "center",
114
+ showButtons: buttons,
115
+ nextBtnText: nextText,
116
+ doneBtnText: nextText,
117
+ prevBtnText: labels.back,
118
+ closeBtnLabel: labels.close,
119
+ onNextClick: () => this.advance(step),
120
+ onPrevClick: () => this.go(this.previousIndex(index)),
121
+ onCloseClick: () => this.stop(),
122
+ onPopoverRender: (popover) => this.decorate(popover, step)
123
+ },
124
+ onHighlightStarted: (element) => {
125
+ // Padding and radius are driver-wide settings, so each step sets its own before it's drawn.
126
+ this.driver.setConfig({ ...this.driver.getConfig(), stagePadding: this.padding(step), stageRadius: step.radius ?? 8 });
127
+ element?.classList.add(...this.highlightClasses(step));
128
+ this.savedStep(step.id);
129
+ },
130
+ onHighlighted: () => {
131
+ if (step.advance_on) this.advanceOnEvent(step);
132
+ if (step.await_more || step.await_modal) this.awaitMore(step, index);
133
+ },
134
+ onDeselected: (element) => element?.classList.remove(...this.highlightClasses(step))
135
+ };
136
+ }
137
+
138
+ advance(step) {
139
+ if (step.ping_url) this.ping(step.ping_url);
140
+ if (step.next_url) {
141
+ this.finish();
142
+ window.Turbo ? window.Turbo.visit(step.next_url) : window.location.assign(step.next_url);
143
+ } else if (step.finish_url) {
144
+ this.finish();
145
+ this.post(step.finish_url);
146
+ } else {
147
+ this.go(this.nextIndex(this.steps.indexOf(step)));
148
+ }
149
+ }
150
+
151
+ // The user went through the whole tour.
152
+ finish() {
153
+ this.savedStep(null);
154
+ this.end({ record: true });
155
+ }
156
+
157
+ // The user closed the tour (x, Escape, or another tour's replay). It counts as completed,
158
+ // but keeps the step for ?resume=1.
159
+ stop() {
160
+ this.end({ record: true });
161
+ }
162
+
163
+ end({ record }) {
164
+ this.observer?.disconnect();
165
+ this.advanceAbort?.abort();
166
+ this.cancelWait?.();
167
+ clearTimeout(this.reshowTimer);
168
+ document.removeEventListener("keydown", this.onKeydown);
169
+ this.driver?.destroy();
170
+ this.driver = null;
171
+ if (active === this) active = null;
172
+ if (record && this.element.isConnected) this.complete();
173
+ }
174
+
175
+ // keepalive: the request survives a next_url visit right after.
176
+ complete() {
177
+ fetch(this.completeUrlValue, {
178
+ method: "POST",
179
+ headers: { "X-CSRF-Token": this.csrfToken(), "Content-Type": "application/json", Accept: "application/json" },
180
+ credentials: "same-origin",
181
+ body: "{}",
182
+ keepalive: true
183
+ });
184
+ }
185
+
186
+ // An optional step is skipped when its element isn't on the page (e.g. an empty list).
187
+ present(step) {
188
+ return !step.optional || Boolean(document.querySelector(step.element_selector));
189
+ }
190
+
191
+ nextIndex(from) {
192
+ for (let i = from + 1; i < this.steps.length; i++) if (this.present(this.steps[i])) return i;
193
+ return -1;
194
+ }
195
+
196
+ previousIndex(from) {
197
+ for (let i = from - 1; i >= 0; i--) if (this.present(this.steps[i])) return i;
198
+ return from;
199
+ }
200
+
201
+ // On a phone there is no room beside an element, so a left/right step gets pushed over it.
202
+ // It goes below instead.
203
+ placement(step) {
204
+ const side = step.attach_to || "bottom";
205
+ const sideways = side === "left" || side === "right";
206
+ return sideways && window.matchMedia("(max-width: 767px)").matches ? "bottom" : side;
207
+ }
208
+
209
+ waitsForUser(step) {
210
+ return Boolean(step.await_more || step.await_modal || step.advance_on);
211
+ }
212
+
213
+ // Steps that ask the user to act get a wider cut-out, so the pulse around the element isn't dimmed.
214
+ padding(step) {
215
+ return step.padding ?? (this.waitsForUser(step) ? 16 : 6);
216
+ }
217
+
218
+ highlightClasses(step) {
219
+ const name = step.highlight_class || (this.waitsForUser(step) ? "tipasa-pulse" : null);
220
+ return name ? name.split(" ") : [];
221
+ }
222
+
223
+ // Adds the step counter and, on a step with no Next, what it's waiting for (otherwise it looks stuck).
224
+ decorate(popover, step) {
225
+ popover.footer.querySelectorAll(".tipasa-progress, .tipasa-waiting").forEach((extra) => extra.remove());
226
+ const position = this.progressIds.indexOf(step.id) + 1;
227
+ const extras = [];
228
+ if (position && this.progressIds.length > 1) {
229
+ extras.push(this.span("tipasa-progress", this.labelsValue.progress.replace("%{current}", position).replace("%{total}", this.progressIds.length)));
230
+ }
231
+ if (this.waitsForUser(step)) {
232
+ const hint = this.span("tipasa-waiting", this.labelsValue.waiting);
233
+ hint.prepend(this.span("tipasa-waiting-dot", ""));
234
+ extras.push(hint);
235
+ }
236
+ if (extras.length === 0) return;
237
+
238
+ popover.progress.style.display = "none";
239
+ popover.footer.style.display = "flex";
240
+ popover.footer.prepend(...extras);
241
+ }
242
+
243
+ span(className, text) {
244
+ const span = document.createElement("span");
245
+ span.className = className;
246
+ span.textContent = text;
247
+ return span;
248
+ }
249
+
250
+ // Holds the step until its element renders (e.g. a Turbo frame still loading). After 3s it shows anyway.
251
+ // Closing or leaving the tour cancels the wait, so the step never shows up on another page.
252
+ waitFor(selector) {
253
+ if (document.querySelector(selector)) return Promise.resolve();
254
+
255
+ this.cancelWait?.();
256
+ return new Promise((resolve) => {
257
+ const cancel = () => { observer.disconnect(); clearTimeout(timer); };
258
+ const done = () => { cancel(); resolve(); };
259
+ const observer = new MutationObserver(() => document.querySelector(selector) && done());
260
+ const timer = setTimeout(done, 3000);
261
+ this.cancelWait = () => { cancel(); resolve(); };
262
+ observer.observe(document.body, { childList: true, subtree: true });
263
+ });
264
+ }
265
+
266
+ // Not driver.js's advanceOn, which moves to the next step and would skip ping_url, next_url and finish_url.
267
+ advanceOnEvent(step) {
268
+ this.advanceAbort?.abort();
269
+ this.advanceAbort = new AbortController();
270
+ document.querySelector(step.element_selector)?.addEventListener(step.advance_on, () => {
271
+ this.advanceAbort.abort();
272
+ if (this.driver?.getActiveStep() && this.steps[this.driver.getActiveIndex()] === step) this.advance(step);
273
+ }, { signal: this.advanceAbort.signal });
274
+ }
275
+
276
+ // Hides the tour while the user does the step in a modal and moves on once more elements match
277
+ // await_more (e.g. one more paid row). If the modal closes without that, the step comes back,
278
+ // after a pause because the page can refresh a moment after the modal closes.
279
+ // await_modal (no selector) only waits out the modal, which can run its own tour.
280
+ awaitMore(step, index) {
281
+ const selector = typeof step.await_more === "string" ? step.await_more : null;
282
+ const count = () => (selector ? document.querySelectorAll(selector).length : 0);
283
+ const before = count();
284
+ document.querySelector(step.element_selector)?.addEventListener("click", () => this.pause(), { once: true });
285
+
286
+ let modalOpened = false;
287
+ this.observer?.disconnect();
288
+ clearTimeout(this.reshowTimer);
289
+ this.observer = new MutationObserver(() => {
290
+ const modalOpen = Boolean(document.querySelector("dialog:modal"));
291
+ modalOpened ||= modalOpen;
292
+ if (modalOpen) return;
293
+
294
+ if (count() > before) {
295
+ clearTimeout(this.reshowTimer);
296
+ this.observer.disconnect();
297
+ this.go(this.nextIndex(index));
298
+ } else if (modalOpened && !this.driver?.isActive()) {
299
+ clearTimeout(this.reshowTimer);
300
+ this.reshowTimer = setTimeout(() => {
301
+ if (count() > before) return;
302
+ this.observer.disconnect();
303
+ this.go(index);
304
+ }, 1500);
305
+ }
306
+ });
307
+ this.observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ["open"] });
308
+ }
309
+
310
+ // sessionStorage can be unavailable (private mode, blocked storage); the tour then starts over.
311
+ savedStep(id) {
312
+ const key = `tipasa-step:${this.slugValue}`;
313
+ try {
314
+ if (id === undefined) return sessionStorage.getItem(key);
315
+ if (id) sessionStorage.setItem(key, id);
316
+ else sessionStorage.removeItem(key);
317
+ } catch {
318
+ return null;
319
+ }
320
+ }
321
+
322
+ csrfToken() {
323
+ return document.querySelector("meta[name=csrf-token]")?.content;
324
+ }
325
+
326
+ // keepalive: the request survives a page change right after.
327
+ ping(url) {
328
+ fetch(url, { method: "POST", headers: { "X-CSRF-Token": this.csrfToken() }, credentials: "same-origin", keepalive: true });
329
+ }
330
+
331
+ post(url) {
332
+ const form = document.createElement("form");
333
+ form.method = "post";
334
+ form.action = url;
335
+ form.dataset.turbo = "false";
336
+ const token = document.createElement("input");
337
+ token.type = "hidden";
338
+ token.name = "authenticity_token";
339
+ token.value = this.csrfToken() || "";
340
+ form.append(token);
341
+ document.body.append(form);
342
+ form.submit();
343
+ }
344
+ }
@@ -0,0 +1,20 @@
1
+ module Tipasa
2
+ # Include in every model that takes tours (User, AdminUser...).
3
+ module Owner
4
+ extend ActiveSupport::Concern
5
+
6
+ included do
7
+ has_many :tipasa_completions, class_name: "Tipasa::Completion", as: :owner, dependent: :delete_all
8
+ end
9
+
10
+ def completed_tour?(slug)
11
+ tipasa_completions.exists?(tour_slug: slug.to_s)
12
+ end
13
+
14
+ # Active tours this owner may see and hasn't completed.
15
+ def pending_tours
16
+ done = tipasa_completions.pluck(:tour_slug)
17
+ Tipasa::Tour.all.select { |tour| tour.active? && tour.visible_to?(self) && done.exclude?(tour.slug) }
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,5 @@
1
+ module Tipasa
2
+ class ApplicationRecord < ActiveRecord::Base
3
+ self.abstract_class = true
4
+ end
5
+ end
@@ -0,0 +1,7 @@
1
+ module Tipasa
2
+ class Completion < ApplicationRecord
3
+ belongs_to :owner, polymorphic: true
4
+
5
+ validates :tour_slug, presence: true, uniqueness: { scope: %i[owner_type owner_id] }
6
+ end
7
+ end
@@ -0,0 +1,40 @@
1
+ module Tipasa
2
+ # A tour is one YAML file in Tipasa.tours_path; its slug is the file name.
3
+ class Tour
4
+ SLUG = /\A[\w-]+\z/
5
+
6
+ attr_reader :slug
7
+
8
+ def self.all
9
+ Dir[File.join(Tipasa.tours_path, "*.yml")].sort.map { |path| new(File.basename(path, ".yml"), path) }
10
+ end
11
+
12
+ # The slug comes from the URL, so anything that isn't a plain file name is rejected before touching the disk.
13
+ def self.find(slug)
14
+ path = File.join(Tipasa.tours_path, "#{slug}.yml")
15
+ new(slug, path) if slug.to_s.match?(SLUG) && File.file?(path)
16
+ end
17
+
18
+ def initialize(slug, path)
19
+ @slug = slug
20
+ @data = YAML.safe_load_file(path) || {}
21
+ end
22
+
23
+ def name = @data["name"]
24
+ def description = @data["description"]
25
+ def steps = @data["steps"] || []
26
+ def active? = @data.fetch("active", true)
27
+
28
+ # Without `for:` everyone sees the tour, signed in or not. With it, only those owner classes do.
29
+ def visible_to?(owner)
30
+ audience = Array(@data["for"])
31
+ return true if audience.empty?
32
+
33
+ audience.any? { |name| (klass = name.to_s.safe_constantize) && owner.is_a?(klass) }
34
+ end
35
+
36
+ def as_json(*)
37
+ { slug:, name:, description:, steps: }
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,9 @@
1
+ en:
2
+ tipasa:
3
+ next: "Next"
4
+ back: "Back"
5
+ done: "Finish"
6
+ close: "Close tour"
7
+ replay: "Show the tour"
8
+ waiting: "Click the highlighted element to continue"
9
+ progress: "Step %{current} of %{total}"
@@ -0,0 +1,9 @@
1
+ es:
2
+ tipasa:
3
+ next: "Siguiente"
4
+ back: "Atrás"
5
+ done: "Finalizar"
6
+ close: "Cerrar recorrido"
7
+ replay: "Ver el recorrido"
8
+ waiting: "Haz clic en lo resaltado para continuar"
9
+ progress: "Paso %{current} de %{total}"
data/config/routes.rb ADDED
@@ -0,0 +1,4 @@
1
+ Tipasa::Engine.routes.draw do
2
+ get ":slug", to: "tours#show", as: :tour
3
+ post ":slug/complete", to: "tours#complete", as: :complete_tour
4
+ end
@@ -0,0 +1,10 @@
1
+ class CreateTipasaCompletions < ActiveRecord::Migration[7.1]
2
+ def change
3
+ create_table :tipasa_completions do |t|
4
+ t.references :owner, polymorphic: true, null: false, index: false
5
+ t.string :tour_slug, null: false
6
+ t.timestamps
7
+ end
8
+ add_index :tipasa_completions, %i[owner_type owner_id tour_slug], unique: true, name: "index_tipasa_completions_uniqueness"
9
+ end
10
+ end
@@ -0,0 +1,26 @@
1
+ require "rails/generators"
2
+
3
+ module Tipasa
4
+ module Generators
5
+ # rails g tipasa:install
6
+ class InstallGenerator < Rails::Generators::Base
7
+ source_root File.expand_path("templates", __dir__)
8
+
9
+ def copy_initializer
10
+ template "initializer.rb", "config/initializers/tipasa.rb"
11
+ end
12
+
13
+ def create_tours_folder
14
+ empty_directory "config/tours"
15
+ end
16
+
17
+ def mount_engine
18
+ route 'mount Tipasa::Engine, at: "/tours"'
19
+ end
20
+
21
+ def copy_migrations
22
+ rake "tipasa:install:migrations"
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,13 @@
1
+ Tipasa.configure do |config|
2
+ # Who takes the tour on this request; nil when nobody is signed in.
3
+ # Several account models? config.current_owner = ->(c) { c.current_user || c.current_admin_user }
4
+ config.current_owner = ->(controller) { controller.try(:current_user) }
5
+
6
+ # Inherit from your ApplicationController to run its filters (auth, locale, paper_trail...) on the tour endpoints.
7
+ # config.parent_controller = "ApplicationController"
8
+
9
+ # Locale for the buttons and hints (en and es ship with the gem); nil follows I18n.locale.
10
+ # config.locale = :es
11
+
12
+ # config.tours_path = Rails.root.join("config/tours")
13
+ end
@@ -0,0 +1,11 @@
1
+ require "tipasa/helper"
2
+
3
+ module Tipasa
4
+ class Engine < ::Rails::Engine
5
+ isolate_namespace Tipasa
6
+
7
+ initializer "tipasa.helper" do
8
+ ActiveSupport.on_load(:action_view) { include Tipasa::Helper }
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,31 @@
1
+ module Tipasa
2
+ module Helper
3
+ LABELS = %i[next back done close waiting progress].freeze
4
+
5
+ def tipasa_button(slug, **options, &block)
6
+ label = I18n.t("tipasa.replay", locale: Tipasa.locale)
7
+ data = tipasa_data(slug, manual: true).merge(action: "tipasa#replay").merge(options.delete(:data) || {})
8
+ content = block ? capture(&block) : "?"
9
+ tag.button(content, type: "button", title: label, aria: { label: }, data:, **options)
10
+ end
11
+
12
+ def tipasa_autostart
13
+ return if params[:tour].blank?
14
+
15
+ tag.div(data: tipasa_data(params[:tour], replay: true, resume: params[:resume].present?))
16
+ end
17
+
18
+ private
19
+
20
+ def tipasa_data(slug, **values)
21
+ labels = LABELS.to_h { |key| [ key, I18n.t("tipasa.#{key}", locale: Tipasa.locale) ] }
22
+ {
23
+ controller: "tipasa",
24
+ tipasa_slug_value: slug,
25
+ tipasa_url_value: tipasa.tour_path(slug),
26
+ tipasa_complete_url_value: tipasa.complete_tour_path(slug),
27
+ tipasa_labels_value: labels.to_json
28
+ }.merge(values.transform_keys { |key| :"tipasa_#{key}_value" })
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,3 @@
1
+ module Tipasa
2
+ VERSION = "0.2.0"
3
+ end
data/lib/tipasa.rb ADDED
@@ -0,0 +1,20 @@
1
+ require "tipasa/version"
2
+ require "tipasa/engine"
3
+
4
+ module Tipasa
5
+ mattr_accessor :current_owner, default: ->(controller) { controller.try(:current_user) }
6
+
7
+ mattr_accessor :parent_controller, default: "ActionController::Base"
8
+
9
+ mattr_accessor :locale
10
+
11
+ mattr_writer :tours_path
12
+
13
+ def self.tours_path
14
+ @@tours_path || Rails.root.join("config/tours")
15
+ end
16
+
17
+ def self.configure
18
+ yield self
19
+ end
20
+ end
metadata ADDED
@@ -0,0 +1,82 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: tipasa
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - ACR1209
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-11-16 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rails
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '7.1'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '7.1'
27
+ description: A Rails engine that serves product tours defined in config/tours/*.yml,
28
+ records who completed them, and ships a Stimulus controller built on driver.js.
29
+ email:
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - CHANGELOG.md
35
+ - MIT-LICENSE
36
+ - README.md
37
+ - app/assets/stylesheets/tipasa.css
38
+ - app/controllers/tipasa/application_controller.rb
39
+ - app/controllers/tipasa/tours_controller.rb
40
+ - app/javascript/tipasa/index.js
41
+ - app/models/concerns/tipasa/owner.rb
42
+ - app/models/tipasa/application_record.rb
43
+ - app/models/tipasa/completion.rb
44
+ - app/models/tipasa/tour.rb
45
+ - config/locales/en.yml
46
+ - config/locales/es.yml
47
+ - config/routes.rb
48
+ - db/migrate/20261115000000_create_tipasa_completions.rb
49
+ - lib/generators/tipasa/install/install_generator.rb
50
+ - lib/generators/tipasa/install/templates/initializer.rb
51
+ - lib/tipasa.rb
52
+ - lib/tipasa/engine.rb
53
+ - lib/tipasa/helper.rb
54
+ - lib/tipasa/version.rb
55
+ homepage: https://github.com/ACR1209/tipasa
56
+ licenses:
57
+ - MIT
58
+ metadata:
59
+ homepage_uri: https://github.com/ACR1209/tipasa
60
+ source_code_uri: https://github.com/ACR1209/tipasa
61
+ changelog_uri: https://github.com/ACR1209/tipasa/blob/main/CHANGELOG.md
62
+ rubygems_mfa_required: 'true'
63
+ post_install_message:
64
+ rdoc_options: []
65
+ require_paths:
66
+ - lib
67
+ required_ruby_version: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ version: '3.1'
72
+ required_rubygems_version: !ruby/object:Gem::Requirement
73
+ requirements:
74
+ - - ">="
75
+ - !ruby/object:Gem::Version
76
+ version: '0'
77
+ requirements: []
78
+ rubygems_version: 3.5.11
79
+ signing_key:
80
+ specification_version: 4
81
+ summary: Guided product tours for Rails apps, written in YAML.
82
+ test_files: []