1
0
Fork 0
mirror of https://github.com/maybe-finance/maybe.git synced 2025-07-18 20:59:39 +02:00

Add BiomeJS for Linting and Formatting JavaScript relates to #1295 (#1299)

* chore: add formatting and linting for javascript code relates to #1295

* use spaces instaed

* add to recommended extensions

* only enforce lint

* auto save
This commit is contained in:
oxdev03 2024-10-14 23:09:27 +02:00 committed by GitHub
parent fa3b8b078c
commit 4ad28d6eff
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
30 changed files with 740 additions and 377 deletions

View file

@ -17,4 +17,8 @@ RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
RUN gem install bundler RUN gem install bundler
RUN gem install foreman RUN gem install foreman
# Install Node.js 20
RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
&& apt-get install -y nodejs
WORKDIR /workspace WORKDIR /workspace

View file

@ -10,5 +10,13 @@
"remoteEnv": { "remoteEnv": {
"PATH": "/workspace/bin:${containerEnv:PATH}" "PATH": "/workspace/bin:${containerEnv:PATH}"
}, },
"postCreateCommand": "bundle install" "postCreateCommand": "bundle install && npm install",
"customizations": {
"vscode": {
"extensions": [
"biomejs.biome",
"EditorConfig.EditorConfig"
]
}
}
} }

View file

@ -52,6 +52,26 @@ jobs:
- name: Lint code for consistent style - name: Lint code for consistent style
run: bin/rubocop -f github run: bin/rubocop -f github
lint_js:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js environment
uses: actions/setup-node@v4
with:
node-version: "20"
cache: "npm"
- name: Install dependencies
run: npm install
shell: bash
- name: Lint/Format js code
run: npm run lint
test: test:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 10 timeout-minutes: 10

12
.gitignore vendored
View file

@ -43,7 +43,12 @@
.idea .idea
# Ignore VS Code # Ignore VS Code
.vscode .vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Ignore macOS specific files # Ignore macOS specific files
*/.DS_Store */.DS_Store
@ -59,4 +64,7 @@ compose-dev.yaml
gcp-storage-keyfile.json gcp-storage-keyfile.json
coverage coverage
.cursorrules .cursorrules
# Ignore node related files
node_modules

6
.vscode/extensions.json vendored Normal file
View file

@ -0,0 +1,6 @@
{
"recommendations": [
"biomejs.biome",
"EditorConfig.EditorConfig"
]
}

6
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,6 @@
{
"[javascript]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "biomejs.biome",
}
}

View file

@ -1,3 +1,3 @@
// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails // Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails
import "@hotwired/turbo-rails" import "@hotwired/turbo-rails";
import "controllers" import "controllers";

View file

@ -1,51 +1,51 @@
import { Controller } from "@hotwired/stimulus" import { Controller } from "@hotwired/stimulus";
// Connects to data-controller="account-collapse" // Connects to data-controller="account-collapse"
export default class extends Controller { export default class extends Controller {
static values = { type: String } static values = { type: String };
initialToggle = false initialToggle = false;
STORAGE_NAME = "accountCollapseStates" STORAGE_NAME = "accountCollapseStates";
connect() { connect() {
this.element.addEventListener("toggle", this.onToggle) this.element.addEventListener("toggle", this.onToggle);
this.updateFromLocalStorage() this.updateFromLocalStorage();
} }
disconnect() { disconnect() {
this.element.removeEventListener("toggle", this.onToggle) this.element.removeEventListener("toggle", this.onToggle);
} }
onToggle = () => { onToggle = () => {
if (this.initialToggle) { if (this.initialToggle) {
this.initialToggle = false this.initialToggle = false;
return return;
} }
const items = this.getItemsFromLocalStorage() const items = this.getItemsFromLocalStorage();
if (items.has(this.typeValue)) { if (items.has(this.typeValue)) {
items.delete(this.typeValue) items.delete(this.typeValue);
} else { } else {
items.add(this.typeValue) items.add(this.typeValue);
} }
localStorage.setItem(this.STORAGE_NAME, JSON.stringify([...items])) localStorage.setItem(this.STORAGE_NAME, JSON.stringify([...items]));
} };
updateFromLocalStorage() { updateFromLocalStorage() {
const items = this.getItemsFromLocalStorage() const items = this.getItemsFromLocalStorage();
if (items.has(this.typeValue)) { if (items.has(this.typeValue)) {
this.initialToggle = true this.initialToggle = true;
this.element.setAttribute("open", "") this.element.setAttribute("open", "");
} }
} }
getItemsFromLocalStorage() { getItemsFromLocalStorage() {
try { try {
const items = localStorage.getItem(this.STORAGE_NAME) const items = localStorage.getItem(this.STORAGE_NAME);
return new Set(items ? JSON.parse(items) : []) return new Set(items ? JSON.parse(items) : []);
} catch (error) { } catch (error) {
console.error("Error parsing items from localStorage:", error) console.error("Error parsing items from localStorage:", error);
return new Set() return new Set();
} }
} }
} }

View file

@ -1,10 +1,10 @@
import { Application } from "@hotwired/stimulus" import { Application } from "@hotwired/stimulus";
const application = Application.start() const application = Application.start();
// Configure Stimulus development experience // Configure Stimulus development experience
application.debug = false application.debug = false;
window.Stimulus = application window.Stimulus = application;
Turbo.setConfirmMethod((message) => { Turbo.setConfirmMethod((message) => {
const dialog = document.getElementById("turbo-confirm"); const dialog = document.getElementById("turbo-confirm");
@ -34,10 +34,14 @@ Turbo.setConfirmMethod((message) => {
dialog.showModal(); dialog.showModal();
return new Promise((resolve) => { return new Promise((resolve) => {
dialog.addEventListener("close", () => { dialog.addEventListener(
resolve(dialog.returnValue == "confirm") "close",
}, { once: true }) () => {
}) resolve(dialog.returnValue === "confirm");
}) },
{ once: true },
);
});
});
export { application } export { application };

View file

@ -1,81 +1,95 @@
import { Controller } from "@hotwired/stimulus" import { Controller } from "@hotwired/stimulus";
// Connects to data-controller="bulk-select" // Connects to data-controller="bulk-select"
export default class extends Controller { export default class extends Controller {
static targets = ["row", "group", "selectionBar", "selectionBarText", "bulkEditDrawerTitle"] static targets = [
"row",
"group",
"selectionBar",
"selectionBarText",
"bulkEditDrawerTitle",
];
static values = { static values = {
resource: String, resource: String,
selectedIds: { type: Array, default: [] } selectedIds: { type: Array, default: [] },
} };
connect() { connect() {
document.addEventListener("turbo:load", this._updateView) document.addEventListener("turbo:load", this._updateView);
this._updateView() this._updateView();
} }
disconnect() { disconnect() {
document.removeEventListener("turbo:load", this._updateView) document.removeEventListener("turbo:load", this._updateView);
} }
bulkEditDrawerTitleTargetConnected(element) { bulkEditDrawerTitleTargetConnected(element) {
element.innerText = `Edit ${this.selectedIdsValue.length} ${this._pluralizedResourceName()}` element.innerText = `Edit ${
this.selectedIdsValue.length
} ${this._pluralizedResourceName()}`;
} }
submitBulkRequest(e) { submitBulkRequest(e) {
const form = e.target.closest("form"); const form = e.target.closest("form");
const scope = e.params.scope const scope = e.params.scope;
this._addHiddenFormInputsForSelectedIds(form, `${scope}[entry_ids][]`, this.selectedIdsValue) this._addHiddenFormInputsForSelectedIds(
form.requestSubmit() form,
`${scope}[entry_ids][]`,
this.selectedIdsValue,
);
form.requestSubmit();
} }
togglePageSelection(e) { togglePageSelection(e) {
if (e.target.checked) { if (e.target.checked) {
this._selectAll() this._selectAll();
} else { } else {
this.deselectAll() this.deselectAll();
} }
} }
toggleGroupSelection(e) { toggleGroupSelection(e) {
const group = this.groupTargets.find(group => group.contains(e.target)) const group = this.groupTargets.find((group) => group.contains(e.target));
this._rowsForGroup(group).forEach(row => { this._rowsForGroup(group).forEach((row) => {
if (e.target.checked) { if (e.target.checked) {
this._addToSelection(row.dataset.id) this._addToSelection(row.dataset.id);
} else { } else {
this._removeFromSelection(row.dataset.id) this._removeFromSelection(row.dataset.id);
} }
}) });
} }
toggleRowSelection(e) { toggleRowSelection(e) {
if (e.target.checked) { if (e.target.checked) {
this._addToSelection(e.target.dataset.id) this._addToSelection(e.target.dataset.id);
} else { } else {
this._removeFromSelection(e.target.dataset.id) this._removeFromSelection(e.target.dataset.id);
} }
} }
deselectAll() { deselectAll() {
this.selectedIdsValue = [] this.selectedIdsValue = [];
this.element.querySelectorAll('input[type="checkbox"]').forEach(el => el.checked = false) this.element.querySelectorAll('input[type="checkbox"]').forEach((el) => {
el.checked = false;
});
} }
selectedIdsValueChanged() { selectedIdsValueChanged() {
this._updateView() this._updateView();
} }
_addHiddenFormInputsForSelectedIds(form, paramName, transactionIds) { _addHiddenFormInputsForSelectedIds(form, paramName, transactionIds) {
this._resetFormInputs(form, paramName); this._resetFormInputs(form, paramName);
transactionIds.forEach(id => { transactionIds.forEach((id) => {
const input = document.createElement("input"); const input = document.createElement("input");
input.type = 'hidden' input.type = "hidden";
input.name = paramName input.name = paramName;
input.value = id input.value = id;
form.appendChild(input) form.appendChild(input);
}) });
} }
_resetFormInputs(form, paramName) { _resetFormInputs(form, paramName) {
@ -84,51 +98,58 @@ export default class extends Controller {
} }
_rowsForGroup(group) { _rowsForGroup(group) {
return this.rowTargets.filter(row => group.contains(row)) return this.rowTargets.filter((row) => group.contains(row));
} }
_addToSelection(idToAdd) { _addToSelection(idToAdd) {
this.selectedIdsValue = Array.from( this.selectedIdsValue = Array.from(
new Set([...this.selectedIdsValue, idToAdd]) new Set([...this.selectedIdsValue, idToAdd]),
) );
} }
_removeFromSelection(idToRemove) { _removeFromSelection(idToRemove) {
this.selectedIdsValue = this.selectedIdsValue.filter(id => id !== idToRemove) this.selectedIdsValue = this.selectedIdsValue.filter(
(id) => id !== idToRemove,
);
} }
_selectAll() { _selectAll() {
this.selectedIdsValue = this.rowTargets.map(t => t.dataset.id) this.selectedIdsValue = this.rowTargets.map((t) => t.dataset.id);
} }
_updateView = () => { _updateView = () => {
this._updateSelectionBar() this._updateSelectionBar();
this._updateGroups() this._updateGroups();
this._updateRows() this._updateRows();
} };
_updateSelectionBar() { _updateSelectionBar() {
const count = this.selectedIdsValue.length const count = this.selectedIdsValue.length;
this.selectionBarTextTarget.innerText = `${count} ${this._pluralizedResourceName()} selected` this.selectionBarTextTarget.innerText = `${count} ${this._pluralizedResourceName()} selected`;
this.selectionBarTarget.hidden = count === 0 this.selectionBarTarget.hidden = count === 0;
this.selectionBarTarget.querySelector("input[type='checkbox']").checked = count > 0 this.selectionBarTarget.querySelector("input[type='checkbox']").checked =
count > 0;
} }
_pluralizedResourceName() { _pluralizedResourceName() {
return `${this.resourceValue}${this.selectedIdsValue.length === 1 ? "" : "s"}` return `${this.resourceValue}${
this.selectedIdsValue.length === 1 ? "" : "s"
}`;
} }
_updateGroups() { _updateGroups() {
this.groupTargets.forEach(group => { this.groupTargets.forEach((group) => {
const rows = this.rowTargets.filter(row => group.contains(row)) const rows = this.rowTargets.filter((row) => group.contains(row));
const groupSelected = rows.length > 0 && rows.every(row => this.selectedIdsValue.includes(row.dataset.id)) const groupSelected =
group.querySelector("input[type='checkbox']").checked = groupSelected rows.length > 0 &&
}) rows.every((row) => this.selectedIdsValue.includes(row.dataset.id));
group.querySelector("input[type='checkbox']").checked = groupSelected;
});
} }
_updateRows() { _updateRows() {
this.rowTargets.forEach(row => { this.rowTargets.forEach((row) => {
row.checked = this.selectedIdsValue.includes(row.dataset.id) row.checked = this.selectedIdsValue.includes(row.dataset.id);
}) });
} }
} }

View file

@ -1,28 +1,28 @@
import { Controller } from "@hotwired/stimulus" import { Controller } from "@hotwired/stimulus";
export default class extends Controller { export default class extends Controller {
static targets = ["source", "iconDefault", "iconSuccess"] static targets = ["source", "iconDefault", "iconSuccess"];
copy(event) { copy(event) {
event.preventDefault(); event.preventDefault();
if (this.sourceTarget && this.sourceTarget.textContent) { if (this.sourceTarget?.textContent) {
navigator.clipboard.writeText(this.sourceTarget.textContent) navigator.clipboard
.writeText(this.sourceTarget.textContent)
.then(() => { .then(() => {
this.showSuccess(); this.showSuccess();
}) })
.catch((error) => { .catch((error) => {
console.error('Failed to copy text: ', error); console.error("Failed to copy text: ", error);
}); });
} }
} }
showSuccess() { showSuccess() {
this.iconDefaultTarget.classList.add('hidden'); this.iconDefaultTarget.classList.add("hidden");
this.iconSuccessTarget.classList.remove('hidden'); this.iconSuccessTarget.classList.remove("hidden");
setTimeout(() => { setTimeout(() => {
this.iconDefaultTarget.classList.remove('hidden'); this.iconDefaultTarget.classList.remove("hidden");
this.iconSuccessTarget.classList.add('hidden'); this.iconSuccessTarget.classList.add("hidden");
}, 3000); }, 3000);
} }
} }

View file

@ -3,10 +3,7 @@ import { Controller } from "@hotwired/stimulus";
// Connects to data-controller="color-avatar" // Connects to data-controller="color-avatar"
// Used by the transaction merchant form to show a preview of what the avatar will look like // Used by the transaction merchant form to show a preview of what the avatar will look like
export default class extends Controller { export default class extends Controller {
static targets = [ static targets = ["name", "avatar"];
"name",
"avatar"
];
connect() { connect() {
this.nameTarget.addEventListener("input", this.handleNameChange); this.nameTarget.addEventListener("input", this.handleNameChange);
@ -17,8 +14,10 @@ export default class extends Controller {
} }
handleNameChange = (e) => { handleNameChange = (e) => {
this.avatarTarget.textContent = (e.currentTarget.value?.[0] || "?").toUpperCase(); this.avatarTarget.textContent = (
} e.currentTarget.value?.[0] || "?"
).toUpperCase();
};
handleColorChange(e) { handleColorChange(e) {
const color = e.currentTarget.value; const color = e.currentTarget.value;
@ -26,4 +25,4 @@ export default class extends Controller {
this.avatarTarget.style.borderColor = `color-mix(in srgb, ${color} 10%, white)`; this.avatarTarget.style.borderColor = `color-mix(in srgb, ${color} 10%, white)`;
this.avatarTarget.style.color = color; this.avatarTarget.style.color = color;
} }
} }

View file

@ -1,59 +1,65 @@
import { Controller } from "@hotwired/stimulus"; import { Controller } from "@hotwired/stimulus";
export default class extends Controller { export default class extends Controller {
static targets = [ "input", "decoration" ] static targets = ["input", "decoration"];
static values = { selection: String } static values = { selection: String };
connect() { connect() {
this.#renderOptions() this.#renderOptions();
} }
select({ target }) { select({ target }) {
this.selectionValue = target.dataset.value this.selectionValue = target.dataset.value;
} }
selectionValueChanged() { selectionValueChanged() {
this.#options.forEach(option => { this.#options.forEach((option) => {
if (option.dataset.value === this.selectionValue) { if (option.dataset.value === this.selectionValue) {
this.#check(option) this.#check(option);
this.inputTarget.value = this.selectionValue this.inputTarget.value = this.selectionValue;
} else { } else {
this.#uncheck(option) this.#uncheck(option);
} }
}) });
} }
#renderOptions() { #renderOptions() {
this.#options.forEach(option => option.style.backgroundColor = option.dataset.value) this.#options.forEach((option) => {
option.style.backgroundColor = option.dataset.value;
});
} }
#check(option) { #check(option) {
option.setAttribute("aria-checked", "true") option.setAttribute("aria-checked", "true");
option.style.boxShadow = `0px 0px 0px 4px ${hexToRGBA(option.dataset.value, 0.2)}` option.style.boxShadow = `0px 0px 0px 4px ${hexToRGBA(
this.decorationTarget.style.backgroundColor = option.dataset.value option.dataset.value,
0.2,
)}`;
this.decorationTarget.style.backgroundColor = option.dataset.value;
} }
#uncheck(option) { #uncheck(option) {
option.setAttribute("aria-checked", "false") option.setAttribute("aria-checked", "false");
option.style.boxShadow = "none" option.style.boxShadow = "none";
} }
get #options() { get #options() {
return Array.from(this.element.querySelectorAll("[role='radio']")) return Array.from(this.element.querySelectorAll("[role='radio']"));
} }
} }
function hexToRGBA(hex, alpha = 1) { function hexToRGBA(hex, alpha = 1) {
hex = hex.replace(/^#/, ''); let hexCode = hex.replace(/^#/, "");
let calculatedAlpha = alpha;
if (hex.length === 8) { if (hexCode.length === 8) {
alpha = parseInt(hex.slice(6, 8), 16) / 255; calculatedAlpha = Number.parseInt(hexCode.slice(6, 8), 16) / 255;
hex = hex.slice(0, 6); hexCode = hexCode.slice(0, 6);
} }
let r = parseInt(hex.slice(0, 2), 16); const r = Number.parseInt(hexCode.slice(0, 2), 16);
let g = parseInt(hex.slice(2, 4), 16); const g = Number.parseInt(hexCode.slice(2, 4), 16);
let b = parseInt(hex.slice(4, 6), 16); const b = Number.parseInt(hexCode.slice(4, 6), 16);
return `rgba(${r}, ${g}, ${b}, ${alpha})`; return `rgba(${r}, ${g}, ${b}, ${calculatedAlpha})`;
} }

View file

@ -1,30 +1,30 @@
import { Controller } from "@hotwired/stimulus"; import { Controller } from "@hotwired/stimulus";
export default class extends Controller { export default class extends Controller {
static targets = ["replacementField", "submitButton"] static targets = ["replacementField", "submitButton"];
static classes = [ "dangerousAction", "safeAction" ] static classes = ["dangerousAction", "safeAction"];
static values = { static values = {
submitTextWhenReplacing: String, submitTextWhenReplacing: String,
submitTextWhenNotReplacing: String submitTextWhenNotReplacing: String,
} };
updateSubmitButton() { updateSubmitButton() {
if (this.replacementFieldTarget.value) { if (this.replacementFieldTarget.value) {
this.submitButtonTarget.value = this.submitTextWhenReplacingValue this.submitButtonTarget.value = this.submitTextWhenReplacingValue;
this.#markSafe() this.#markSafe();
} else { } else {
this.submitButtonTarget.value = this.submitTextWhenNotReplacingValue this.submitButtonTarget.value = this.submitTextWhenNotReplacingValue;
this.#markDangerous() this.#markDangerous();
} }
} }
#markSafe() { #markSafe() {
this.submitButtonTarget.classList.remove(...this.dangerousActionClasses) this.submitButtonTarget.classList.remove(...this.dangerousActionClasses);
this.submitButtonTarget.classList.add(...this.safeActionClasses) this.submitButtonTarget.classList.add(...this.safeActionClasses);
} }
#markDangerous() { #markDangerous() {
this.submitButtonTarget.classList.remove(...this.safeActionClasses) this.submitButtonTarget.classList.remove(...this.safeActionClasses);
this.submitButtonTarget.classList.add(...this.dangerousActionClasses) this.submitButtonTarget.classList.add(...this.dangerousActionClasses);
} }
} }

View file

@ -1,9 +1,8 @@
import { Controller } from '@hotwired/stimulus' import { Controller } from "@hotwired/stimulus";
// Connects to data-controller="element-removal" // Connects to data-controller="element-removal"
export default class extends Controller { export default class extends Controller {
remove() { remove() {
this.element.remove() this.element.remove();
} }
} }

View file

@ -1,5 +1,5 @@
import { Controller } from "@hotwired/stimulus";
import { install, uninstall } from "@github/hotkey"; import { install, uninstall } from "@github/hotkey";
import { Controller } from "@hotwired/stimulus";
// Connects to data-controller="hotkey" // Connects to data-controller="hotkey"
export default class extends Controller { export default class extends Controller {

View file

@ -1,10 +1,10 @@
// Import and register all your controllers from the importmap under controllers/* // Import and register all your controllers from the importmap under controllers/*
import { application } from "controllers/application" import { application } from "controllers/application";
// Eager load all controllers defined in the import map under controllers/**/*_controller // Eager load all controllers defined in the import map under controllers/**/*_controller
import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading" import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading";
eagerLoadControllersFrom("controllers", application) eagerLoadControllersFrom("controllers", application);
// Lazy load controllers as they appear in the DOM (remember not to preload controllers in import map!) // Lazy load controllers as they appear in the DOM (remember not to preload controllers in import map!)
// import { lazyLoadControllersFrom } from "@hotwired/stimulus-loading" // import { lazyLoadControllersFrom } from "@hotwired/stimulus-loading"

View file

@ -1,39 +1,40 @@
import { Controller } from "@hotwired/stimulus" import { Controller } from "@hotwired/stimulus";
// Connects to data-controller="list-keyboard-navigation" // Connects to data-controller="list-keyboard-navigation"
export default class extends Controller { export default class extends Controller {
focusPrevious() { focusPrevious() {
this.focusLinkTargetInDirection(-1) this.focusLinkTargetInDirection(-1);
} }
focusNext() { focusNext() {
this.focusLinkTargetInDirection(1) this.focusLinkTargetInDirection(1);
} }
focusLinkTargetInDirection(direction) { focusLinkTargetInDirection(direction) {
const element = this.getLinkTargetInDirection(direction) const element = this.getLinkTargetInDirection(direction);
element?.focus() element?.focus();
} }
getLinkTargetInDirection(direction) { getLinkTargetInDirection(direction) {
const indexOfLastFocus = this.indexOfLastFocus() const indexOfLastFocus = this.indexOfLastFocus();
let nextIndex = (indexOfLastFocus + direction) % this.focusableLinks.length let nextIndex = (indexOfLastFocus + direction) % this.focusableLinks.length;
if (nextIndex < 0) nextIndex = this.focusableLinks.length - 1 if (nextIndex < 0) nextIndex = this.focusableLinks.length - 1;
return this.focusableLinks[nextIndex] return this.focusableLinks[nextIndex];
} }
indexOfLastFocus(targets = this.focusableLinks) { indexOfLastFocus(targets = this.focusableLinks) {
const indexOfActiveElement = targets.indexOf(document.activeElement) const indexOfActiveElement = targets.indexOf(document.activeElement);
if (indexOfActiveElement !== -1) { if (indexOfActiveElement !== -1) {
return indexOfActiveElement return indexOfActiveElement;
} else {
return targets.findIndex(target => target.getAttribute("tabindex") === "0")
} }
return targets.findIndex(
(target) => target.getAttribute("tabindex") === "0",
);
} }
get focusableLinks() { get focusableLinks() {
return Array.from(this.element.querySelectorAll("a[href]")) return Array.from(this.element.querySelectorAll("a[href]"));
} }
} }

View file

@ -1,5 +1,11 @@
import {
autoUpdate,
computePosition,
flip,
offset,
shift,
} from "@floating-ui/dom";
import { Controller } from "@hotwired/stimulus"; import { Controller } from "@hotwired/stimulus";
import { computePosition, flip, shift, offset, autoUpdate } from '@floating-ui/dom';
/** /**
* A "menu" can contain arbitrary content including non-clickable items, links, buttons, and forms. * A "menu" can contain arbitrary content including non-clickable items, links, buttons, and forms.
@ -70,8 +76,10 @@ export default class extends Controller {
} }
focusFirstElement() { focusFirstElement() {
const focusableElements = 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'; const focusableElements =
const firstFocusableElement = this.contentTarget.querySelectorAll(focusableElements)[0]; 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
const firstFocusableElement =
this.contentTarget.querySelectorAll(focusableElements)[0];
if (firstFocusableElement) { if (firstFocusableElement) {
firstFocusableElement.focus(); firstFocusableElement.focus();
} }
@ -79,7 +87,11 @@ export default class extends Controller {
startAutoUpdate() { startAutoUpdate() {
if (!this._cleanup) { if (!this._cleanup) {
this._cleanup = autoUpdate(this.buttonTarget, this.contentTarget, this.boundUpdate); this._cleanup = autoUpdate(
this.buttonTarget,
this.contentTarget,
this.boundUpdate,
);
} }
} }
@ -93,14 +105,10 @@ export default class extends Controller {
update() { update() {
computePosition(this.buttonTarget, this.contentTarget, { computePosition(this.buttonTarget, this.contentTarget, {
placement: this.placementValue, placement: this.placementValue,
middleware: [ middleware: [offset(this.offsetValue), flip(), shift({ padding: 5 })],
offset(this.offsetValue),
flip(),
shift({ padding: 5 })
],
}).then(({ x, y }) => { }).then(({ x, y }) => {
Object.assign(this.contentTarget.style, { Object.assign(this.contentTarget.style, {
position: 'fixed', position: "fixed",
left: `${x}px`, left: `${x}px`,
top: `${y}px`, top: `${y}px`,
}); });

View file

@ -1,10 +1,10 @@
import { Controller } from "@hotwired/stimulus" import { Controller } from "@hotwired/stimulus";
// Connects to data-controller="modal" // Connects to data-controller="modal"
export default class extends Controller { export default class extends Controller {
connect() { connect() {
if (this.element.open) return if (this.element.open) return;
else this.element.showModal() this.element.showModal();
} }
// Hide the dialog when the user clicks outside of it // Hide the dialog when the user clicks outside of it

View file

@ -12,14 +12,16 @@ export default class extends Controller {
} }
updateAmount(currency) { updateAmount(currency) {
(new CurrenciesService).get(currency).then((currency) => { new CurrenciesService().get(currency).then((currency) => {
this.amountTarget.step = currency.step; this.amountTarget.step = currency.step;
if (isFinite(this.amountTarget.value)) { if (Number.isFinite(this.amountTarget.value)) {
this.amountTarget.value = parseFloat(this.amountTarget.value).toFixed(currency.default_precision) this.amountTarget.value = Number.parseFloat(
this.amountTarget.value,
).toFixed(currency.default_precision);
} }
this.symbolTarget.innerText = currency.symbol; this.symbolTarget.innerText = currency.symbol;
}); });
} }
} }

View file

@ -104,27 +104,25 @@ export default class extends Controller {
} }
get #d3Svg() { get #d3Svg() {
if (this.#d3SvgMemo) { if (!this.#d3SvgMemo) {
return this.#d3SvgMemo; this.#d3SvgMemo = this.#createMainSvg();
} else {
return (this.#d3SvgMemo = this.#createMainSvg());
} }
return this.#d3SvgMemo;
} }
get #d3Group() { get #d3Group() {
if (this.#d3GroupMemo) { if (!this.#d3GroupMemo) {
return this.#d3GroupMemo; this.#d3GroupMemo = this.#createMainGroup();
} else {
return (this.#d3GroupMemo = this.#createMainGroup());
} }
return this.#d3ContentMemo;
} }
get #d3Content() { get #d3Content() {
if (this.#d3ContentMemo) { if (!this.#d3ContentMemo) {
return this.#d3ContentMemo; this.#d3ContentMemo = this.#createContent();
} else {
return (this.#d3ContentMemo = this.#createContent());
} }
return this.#d3ContentMemo;
} }
#createMainSvg() { #createMainSvg() {

View file

@ -1,7 +1,13 @@
import { Controller } from "@hotwired/stimulus" import { Controller } from "@hotwired/stimulus";
export default class extends Controller { export default class extends Controller {
static targets = ["imagePreview", "fileField", "deleteField", "clearBtn", "template"] static targets = [
"imagePreview",
"fileField",
"deleteField",
"clearBtn",
"template",
];
preview(event) { preview(event) {
const file = event.target.files[0]; const file = event.target.files[0];

View file

@ -28,7 +28,7 @@ export default class extends Controller {
updateClasses = (selectedId) => { updateClasses = (selectedId) => {
this.btnTargets.forEach((btn) => this.btnTargets.forEach((btn) =>
btn.classList.remove(...this.activeClasses) btn.classList.remove(...this.activeClasses),
); );
this.tabTargets.forEach((tab) => tab.classList.add("hidden")); this.tabTargets.forEach((tab) => tab.classList.add("hidden"));

View file

@ -1,6 +1,6 @@
import { Controller } from "@hotwired/stimulus" import { Controller } from "@hotwired/stimulus";
import tailwindColors from "@maybe/tailwindcolors" import tailwindColors from "@maybe/tailwindcolors";
import * as d3 from "d3" import * as d3 from "d3";
export default class extends Controller { export default class extends Controller {
static values = { static values = {
@ -8,8 +8,8 @@ export default class extends Controller {
strokeWidth: { type: Number, default: 2 }, strokeWidth: { type: Number, default: 2 },
useLabels: { type: Boolean, default: true }, useLabels: { type: Boolean, default: true },
useTooltip: { type: Boolean, default: true }, useTooltip: { type: Boolean, default: true },
usePercentSign: Boolean usePercentSign: Boolean,
} };
_d3SvgMemo = null; _d3SvgMemo = null;
_d3GroupMemo = null; _d3GroupMemo = null;
@ -19,68 +19,63 @@ export default class extends Controller {
_normalDataPoints = []; _normalDataPoints = [];
connect() { connect() {
this._install() this._install();
document.addEventListener("turbo:load", this._reinstall) document.addEventListener("turbo:load", this._reinstall);
} }
disconnect() { disconnect() {
this._teardown() this._teardown();
document.removeEventListener("turbo:load", this._reinstall) document.removeEventListener("turbo:load", this._reinstall);
} }
_reinstall = () => { _reinstall = () => {
this._teardown() this._teardown();
this._install() this._install();
} };
_teardown() { _teardown() {
this._d3SvgMemo = null this._d3SvgMemo = null;
this._d3GroupMemo = null this._d3GroupMemo = null;
this._d3Tooltip = null this._d3Tooltip = null;
this._normalDataPoints = [] this._normalDataPoints = [];
this._d3Container.selectAll("*").remove() this._d3Container.selectAll("*").remove();
} }
_install() { _install() {
this._normalizeDataPoints() this._normalizeDataPoints();
this._rememberInitialContainerSize() this._rememberInitialContainerSize();
this._draw() this._draw();
} }
_normalizeDataPoints() { _normalizeDataPoints() {
this._normalDataPoints = (this.dataValue.values || []).map((d) => ({ this._normalDataPoints = (this.dataValue.values || []).map((d) => ({
...d, ...d,
date: new Date(d.date), date: new Date(d.date),
value: d.value.amount ? +d.value.amount : +d.value, value: d.value.amount ? +d.value.amount : +d.value,
currency: d.value.currency currency: d.value.currency,
})) }));
} }
_rememberInitialContainerSize() { _rememberInitialContainerSize() {
this._d3InitialContainerWidth = this._d3Container.node().clientWidth this._d3InitialContainerWidth = this._d3Container.node().clientWidth;
this._d3InitialContainerHeight = this._d3Container.node().clientHeight this._d3InitialContainerHeight = this._d3Container.node().clientHeight;
} }
_draw() { _draw() {
if (this._normalDataPoints.length < 2) { if (this._normalDataPoints.length < 2) {
this._drawEmpty() this._drawEmpty();
} else { } else {
this._drawChart() this._drawChart();
} }
} }
_drawEmpty() { _drawEmpty() {
this._d3Svg.selectAll(".tick").remove() this._d3Svg.selectAll(".tick").remove();
this._d3Svg.selectAll(".domain").remove() this._d3Svg.selectAll(".domain").remove();
this._drawDashedLineEmptyState() this._drawDashedLineEmptyState();
this._drawCenteredCircleEmptyState() this._drawCenteredCircleEmptyState();
} }
_drawDashedLineEmptyState() { _drawDashedLineEmptyState() {
@ -91,7 +86,7 @@ export default class extends Controller {
.attr("x2", this._d3InitialContainerWidth / 2) .attr("x2", this._d3InitialContainerWidth / 2)
.attr("y2", this._d3InitialContainerHeight) .attr("y2", this._d3InitialContainerHeight)
.attr("stroke", tailwindColors.gray[300]) .attr("stroke", tailwindColors.gray[300])
.attr("stroke-dasharray", "4, 4") .attr("stroke-dasharray", "4, 4");
} }
_drawCenteredCircleEmptyState() { _drawCenteredCircleEmptyState() {
@ -100,26 +95,25 @@ export default class extends Controller {
.attr("cx", this._d3InitialContainerWidth / 2) .attr("cx", this._d3InitialContainerWidth / 2)
.attr("cy", this._d3InitialContainerHeight / 2) .attr("cy", this._d3InitialContainerHeight / 2)
.attr("r", 4) .attr("r", 4)
.style("fill", tailwindColors.gray[400]) .style("fill", tailwindColors.gray[400]);
} }
_drawChart() { _drawChart() {
this._drawTrendline() this._drawTrendline();
if (this.useLabelsValue) { if (this.useLabelsValue) {
this._drawXAxisLabels() this._drawXAxisLabels();
this._drawGradientBelowTrendline() this._drawGradientBelowTrendline();
} }
if (this.useTooltipValue) { if (this.useTooltipValue) {
this._drawTooltip() this._drawTooltip();
this._trackMouseForShowingTooltip() this._trackMouseForShowingTooltip();
} }
} }
_drawTrendline() { _drawTrendline() {
this._installTrendlineSplit() this._installTrendlineSplit();
this._d3Group this._d3Group
.append("path") .append("path")
@ -129,7 +123,7 @@ export default class extends Controller {
.attr("d", this._d3Line) .attr("d", this._d3Line)
.attr("stroke-linejoin", "round") .attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round") .attr("stroke-linecap", "round")
.attr("stroke-width", this.strokeWidthValue) .attr("stroke-width", this.strokeWidthValue);
} }
_installTrendlineSplit() { _installTrendlineSplit() {
@ -139,38 +133,41 @@ export default class extends Controller {
.attr("id", `${this.element.id}-split-gradient`) .attr("id", `${this.element.id}-split-gradient`)
.attr("gradientUnits", "userSpaceOnUse") .attr("gradientUnits", "userSpaceOnUse")
.attr("x1", this._d3XScale.range()[0]) .attr("x1", this._d3XScale.range()[0])
.attr("x2", this._d3XScale.range()[1]) .attr("x2", this._d3XScale.range()[1]);
gradient.append("stop") gradient
.append("stop")
.attr("class", "start-color") .attr("class", "start-color")
.attr("offset", "0%") .attr("offset", "0%")
.attr("stop-color", this._trendColor) .attr("stop-color", this._trendColor);
gradient.append("stop") gradient
.append("stop")
.attr("class", "middle-color") .attr("class", "middle-color")
.attr("offset", "100%") .attr("offset", "100%")
.attr("stop-color", this._trendColor) .attr("stop-color", this._trendColor);
gradient.append("stop") gradient
.append("stop")
.attr("class", "end-color") .attr("class", "end-color")
.attr("offset", "100%") .attr("offset", "100%")
.attr("stop-color", tailwindColors.gray[300]) .attr("stop-color", tailwindColors.gray[300]);
} }
_setTrendlineSplitAt(percent) { _setTrendlineSplitAt(percent) {
this._d3Svg this._d3Svg
.select(`#${this.element.id}-split-gradient`) .select(`#${this.element.id}-split-gradient`)
.select(".middle-color") .select(".middle-color")
.attr("offset", `${percent * 100}%`) .attr("offset", `${percent * 100}%`);
this._d3Svg this._d3Svg
.select(`#${this.element.id}-split-gradient`) .select(`#${this.element.id}-split-gradient`)
.select(".end-color") .select(".end-color")
.attr("offset", `${percent * 100}%`) .attr("offset", `${percent * 100}%`);
this._d3Svg this._d3Svg
.select(`#${this.element.id}-trendline-gradient-rect`) .select(`#${this.element.id}-trendline-gradient-rect`)
.attr("width", this._d3ContainerWidth * percent) .attr("width", this._d3ContainerWidth * percent);
} }
_drawXAxisLabels() { _drawXAxisLabels() {
@ -181,24 +178,28 @@ export default class extends Controller {
.call( .call(
d3 d3
.axisBottom(this._d3XScale) .axisBottom(this._d3XScale)
.tickValues([this._normalDataPoints[0].date, this._normalDataPoints[this._normalDataPoints.length - 1].date]) .tickValues([
this._normalDataPoints[0].date,
this._normalDataPoints[this._normalDataPoints.length - 1].date,
])
.tickSize(0) .tickSize(0)
.tickFormat(d3.timeFormat("%d %b %Y")) .tickFormat(d3.timeFormat("%d %b %Y")),
) )
.select(".domain") .select(".domain")
.remove() .remove();
// Style ticks // Style ticks
this._d3Group.selectAll(".tick text") this._d3Group
.selectAll(".tick text")
.style("fill", tailwindColors.gray[500]) .style("fill", tailwindColors.gray[500])
.style("font-size", "12px") .style("font-size", "12px")
.style("font-weight", "500") .style("font-weight", "500")
.attr("text-anchor", "middle") .attr("text-anchor", "middle")
.attr("dx", (_d, i) => { .attr("dx", (_d, i) => {
// We know we only have 2 values // We know we only have 2 values
return i === 0 ? "5em" : "-5em" return i === 0 ? "5em" : "-5em";
}) })
.attr("dy", "0em") .attr("dy", "0em");
} }
_drawGradientBelowTrendline() { _drawGradientBelowTrendline() {
@ -210,20 +211,23 @@ export default class extends Controller {
.attr("gradientUnits", "userSpaceOnUse") .attr("gradientUnits", "userSpaceOnUse")
.attr("x1", 0) .attr("x1", 0)
.attr("x2", 0) .attr("x2", 0)
.attr("y1", this._d3YScale(d3.max(this._normalDataPoints, d => d.value))) .attr(
.attr("y2", this._d3ContainerHeight) "y1",
this._d3YScale(d3.max(this._normalDataPoints, (d) => d.value)),
)
.attr("y2", this._d3ContainerHeight);
gradient gradient
.append("stop") .append("stop")
.attr("offset", 0) .attr("offset", 0)
.attr("stop-color", this._trendColor) .attr("stop-color", this._trendColor)
.attr("stop-opacity", 0.06) .attr("stop-opacity", 0.06);
gradient gradient
.append("stop") .append("stop")
.attr("offset", 0.5) .attr("offset", 0.5)
.attr("stop-color", this._trendColor) .attr("stop-color", this._trendColor)
.attr("stop-opacity", 0) .attr("stop-opacity", 0);
// Clip path makes gradient start at the trendline // Clip path makes gradient start at the trendline
this._d3Group this._d3Group
@ -231,11 +235,14 @@ export default class extends Controller {
.attr("id", `${this.element.id}-clip-below-trendline`) .attr("id", `${this.element.id}-clip-below-trendline`)
.append("path") .append("path")
.datum(this._normalDataPoints) .datum(this._normalDataPoints)
.attr("d", d3.area() .attr(
.x(d => this._d3XScale(d.date)) "d",
.y0(this._d3ContainerHeight) d3
.y1(d => this._d3YScale(d.value)) .area()
) .x((d) => this._d3XScale(d.date))
.y0(this._d3ContainerHeight)
.y1((d) => this._d3YScale(d.value)),
);
// Apply the gradient + clip path // Apply the gradient + clip path
this._d3Group this._d3Group
@ -244,7 +251,7 @@ export default class extends Controller {
.attr("width", this._d3ContainerWidth) .attr("width", this._d3ContainerWidth)
.attr("height", this._d3ContainerHeight) .attr("height", this._d3ContainerHeight)
.attr("clip-path", `url(#${this.element.id}-clip-below-trendline)`) .attr("clip-path", `url(#${this.element.id}-clip-below-trendline)`)
.style("fill", `url(#${this.element.id}-trendline-gradient)`) .style("fill", `url(#${this.element.id}-trendline-gradient)`);
} }
_drawTooltip() { _drawTooltip() {
@ -258,11 +265,11 @@ export default class extends Controller {
.style("border", `1px solid ${tailwindColors["alpha-black"][100]}`) .style("border", `1px solid ${tailwindColors["alpha-black"][100]}`)
.style("border-radius", "10px") .style("border-radius", "10px")
.style("pointer-events", "none") .style("pointer-events", "none")
.style("opacity", 0) // Starts as hidden .style("opacity", 0); // Starts as hidden
} }
_trackMouseForShowingTooltip() { _trackMouseForShowingTooltip() {
const bisectDate = d3.bisector(d => d.date).left const bisectDate = d3.bisector((d) => d.date).left;
this._d3Group this._d3Group
.append("rect") .append("rect")
@ -271,24 +278,32 @@ export default class extends Controller {
.attr("fill", "none") .attr("fill", "none")
.attr("pointer-events", "all") .attr("pointer-events", "all")
.on("mousemove", (event) => { .on("mousemove", (event) => {
const estimatedTooltipWidth = 250 const estimatedTooltipWidth = 250;
const pageWidth = document.body.clientWidth const pageWidth = document.body.clientWidth;
const tooltipX = event.pageX + 10 const tooltipX = event.pageX + 10;
const overflowX = tooltipX + estimatedTooltipWidth - pageWidth const overflowX = tooltipX + estimatedTooltipWidth - pageWidth;
const adjustedX = overflowX > 0 ? event.pageX - overflowX - 20 : tooltipX const adjustedX =
overflowX > 0 ? event.pageX - overflowX - 20 : tooltipX;
const [xPos] = d3.pointer(event) const [xPos] = d3.pointer(event);
const x0 = bisectDate(this._normalDataPoints, this._d3XScale.invert(xPos), 1) const x0 = bisectDate(
const d0 = this._normalDataPoints[x0 - 1] this._normalDataPoints,
const d1 = this._normalDataPoints[x0] this._d3XScale.invert(xPos),
const d = xPos - this._d3XScale(d0.date) > this._d3XScale(d1.date) - xPos ? d1 : d0 1,
const xPercent = this._d3XScale(d.date) / this._d3ContainerWidth );
const d0 = this._normalDataPoints[x0 - 1];
const d1 = this._normalDataPoints[x0];
const d =
xPos - this._d3XScale(d0.date) > this._d3XScale(d1.date) - xPos
? d1
: d0;
const xPercent = this._d3XScale(d.date) / this._d3ContainerWidth;
this._setTrendlineSplitAt(xPercent) this._setTrendlineSplitAt(xPercent);
// Reset // Reset
this._d3Group.selectAll(".data-point-circle").remove() this._d3Group.selectAll(".data-point-circle").remove();
this._d3Group.selectAll(".guideline").remove() this._d3Group.selectAll(".guideline").remove();
// Guideline // Guideline
this._d3Group this._d3Group
@ -299,7 +314,7 @@ export default class extends Controller {
.attr("x2", this._d3XScale(d.date)) .attr("x2", this._d3XScale(d.date))
.attr("y2", this._d3ContainerHeight) .attr("y2", this._d3ContainerHeight)
.attr("stroke", tailwindColors.gray[300]) .attr("stroke", tailwindColors.gray[300])
.attr("stroke-dasharray", "4, 4") .attr("stroke-dasharray", "4, 4");
// Big circle // Big circle
this._d3Group this._d3Group
@ -310,7 +325,7 @@ export default class extends Controller {
.attr("r", 8) .attr("r", 8)
.attr("fill", this._trendColor) .attr("fill", this._trendColor)
.attr("fill-opacity", "0.1") .attr("fill-opacity", "0.1")
.attr("pointer-events", "none") .attr("pointer-events", "none");
// Small circle // Small circle
this._d3Group this._d3Group
@ -320,31 +335,32 @@ export default class extends Controller {
.attr("cy", this._d3YScale(d.value)) .attr("cy", this._d3YScale(d.value))
.attr("r", 3) .attr("r", 3)
.attr("fill", this._trendColor) .attr("fill", this._trendColor)
.attr("pointer-events", "none") .attr("pointer-events", "none");
// Render tooltip // Render tooltip
this._d3Tooltip this._d3Tooltip
.html(this._tooltipTemplate(d)) .html(this._tooltipTemplate(d))
.style("opacity", 1) .style("opacity", 1)
.style("z-index", 999) .style("z-index", 999)
.style("left", adjustedX + "px") .style("left", `${adjustedX}px`)
.style("top", event.pageY - 10 + "px") .style("top", `${event.pageY - 10}px`);
}) })
.on("mouseout", (event) => { .on("mouseout", (event) => {
const hoveringOnGuideline = event.toElement?.classList.contains("guideline") const hoveringOnGuideline =
event.toElement?.classList.contains("guideline");
if (!hoveringOnGuideline) { if (!hoveringOnGuideline) {
this._d3Group.selectAll(".guideline").remove() this._d3Group.selectAll(".guideline").remove();
this._d3Group.selectAll(".data-point-circle").remove() this._d3Group.selectAll(".data-point-circle").remove();
this._d3Tooltip.style("opacity", 0) this._d3Tooltip.style("opacity", 0);
this._setTrendlineSplitAt(1) this._setTrendlineSplitAt(1);
} }
}) });
} }
_tooltipTemplate(datum) { _tooltipTemplate(datum) {
return (` return `
<div style="margin-bottom: 4px; color: ${tailwindColors.gray[500]};"> <div style="margin-bottom: 4px; color: ${tailwindColors.gray[500]};">
${d3.timeFormat("%b %d, %Y")(datum.date)} ${d3.timeFormat("%b %d, %Y")(datum.date)}
</div> </div>
@ -364,15 +380,21 @@ export default class extends Controller {
${this._tooltipValue(datum)}${this.usePercentSignValue ? "%" : ""} ${this._tooltipValue(datum)}${this.usePercentSignValue ? "%" : ""}
</div> </div>
${this.usePercentSignValue || datum.trend.value === 0 || datum.trend.value.amount === 0 ? ` ${
this.usePercentSignValue ||
datum.trend.value === 0 ||
datum.trend.value.amount === 0
? `
<span style="width: 80px;"></span> <span style="width: 80px;"></span>
` : ` `
: `
<span style="color: ${this._tooltipTrendColor(datum)};"> <span style="color: ${this._tooltipTrendColor(datum)};">
${this._tooltipChange(datum)} (${datum.trend.percent}%) ${this._tooltipChange(datum)} (${datum.trend.percent}%)
</span> </span>
`} `
}
</div> </div>
`) `;
} }
_tooltipTrendColor(datum) { _tooltipTrendColor(datum) {
@ -380,30 +402,28 @@ export default class extends Controller {
up: tailwindColors.success, up: tailwindColors.success,
down: tailwindColors.error, down: tailwindColors.error,
flat: tailwindColors.gray[500], flat: tailwindColors.gray[500],
}[datum.trend.direction] }[datum.trend.direction];
} }
_tooltipValue(datum) { _tooltipValue(datum) {
if (datum.currency) { if (datum.currency) {
return this._currencyValue(datum) return this._currencyValue(datum);
} else {
return datum.value
} }
return datum.value;
} }
_tooltipChange(datum) { _tooltipChange(datum) {
if (datum.currency) { if (datum.currency) {
return this._currencyChange(datum) return this._currencyChange(datum);
} else {
return this._decimalChange(datum)
} }
return this._decimalChange(datum);
} }
_currencyValue(datum) { _currencyValue(datum) {
return Intl.NumberFormat(undefined, { return Intl.NumberFormat(undefined, {
style: "currency", style: "currency",
currency: datum.currency, currency: datum.currency,
}).format(datum.value) }).format(datum.value);
} }
_currencyChange(datum) { _currencyChange(datum) {
@ -411,109 +431,113 @@ export default class extends Controller {
style: "currency", style: "currency",
currency: datum.currency, currency: datum.currency,
signDisplay: "always", signDisplay: "always",
}).format(datum.trend.value.amount) }).format(datum.trend.value.amount);
} }
_decimalChange(datum) { _decimalChange(datum) {
return Intl.NumberFormat(undefined, { return Intl.NumberFormat(undefined, {
style: "decimal", style: "decimal",
signDisplay: "always", signDisplay: "always",
}).format(datum.trend.value) }).format(datum.trend.value);
} }
_createMainSvg() { _createMainSvg() {
return this._d3Container return this._d3Container
.append("svg") .append("svg")
.attr("width", this._d3InitialContainerWidth) .attr("width", this._d3InitialContainerWidth)
.attr("height", this._d3InitialContainerHeight) .attr("height", this._d3InitialContainerHeight)
.attr("viewBox", [0, 0, this._d3InitialContainerWidth, this._d3InitialContainerHeight]) .attr("viewBox", [
0,
0,
this._d3InitialContainerWidth,
this._d3InitialContainerHeight,
]);
} }
_createMainGroup() { _createMainGroup() {
return this._d3Svg return this._d3Svg
.append("g") .append("g")
.attr("transform", `translate(${this._margin.left},${this._margin.top})`) .attr("transform", `translate(${this._margin.left},${this._margin.top})`);
} }
get _d3Svg() { get _d3Svg() {
if (this._d3SvgMemo) { if (!this._d3SvgMemo) {
return this._d3SvgMemo this._d3SvgMemo = this._createMainSvg();
} else {
return this._d3SvgMemo = this._createMainSvg()
} }
return this._d3SvgMemo;
} }
get _d3Group() { get _d3Group() {
if (this._d3GroupMemo) { if (!this._d3GroupMemo) {
return this._d3GroupMemo this._d3GroupMemo = this._createMainGroup();
} else {
return this._d3GroupMemo = this._createMainGroup()
} }
return this._d3GroupMemo;
} }
get _margin() { get _margin() {
if (this.useLabelsValue) { if (this.useLabelsValue) {
return { top: 20, right: 0, bottom: 30, left: 0 } return { top: 20, right: 0, bottom: 30, left: 0 };
} else {
return { top: 0, right: 0, bottom: 0, left: 0 }
} }
return { top: 0, right: 0, bottom: 0, left: 0 };
} }
get _d3ContainerWidth() { get _d3ContainerWidth() {
return this._d3InitialContainerWidth - this._margin.left - this._margin.right return (
this._d3InitialContainerWidth - this._margin.left - this._margin.right
);
} }
get _d3ContainerHeight() { get _d3ContainerHeight() {
return this._d3InitialContainerHeight - this._margin.top - this._margin.bottom return (
this._d3InitialContainerHeight - this._margin.top - this._margin.bottom
);
} }
get _d3Container() { get _d3Container() {
return d3.select(this.element) return d3.select(this.element);
} }
get _trendColor() { get _trendColor() {
if (this._trendDirection === "flat") { if (this._trendDirection === "flat") {
return tailwindColors.gray[500] return tailwindColors.gray[500];
} else if (this._trendDirection === this._favorableDirection) {
return tailwindColors.green[500]
} else {
return tailwindColors.error
} }
if (this._trendDirection === this._favorableDirection) {
return tailwindColors.green[500];
}
return tailwindColors.error;
} }
get _trendDirection() { get _trendDirection() {
return this.dataValue.trend.direction return this.dataValue.trend.direction;
} }
get _favorableDirection() { get _favorableDirection() {
return this.dataValue.trend.favorable_direction return this.dataValue.trend.favorable_direction;
} }
get _d3Line() { get _d3Line() {
return d3 return d3
.line() .line()
.x(d => this._d3XScale(d.date)) .x((d) => this._d3XScale(d.date))
.y(d => this._d3YScale(d.value)) .y((d) => this._d3YScale(d.value));
} }
get _d3XScale() { get _d3XScale() {
return d3 return d3
.scaleTime() .scaleTime()
.rangeRound([0, this._d3ContainerWidth]) .rangeRound([0, this._d3ContainerWidth])
.domain(d3.extent(this._normalDataPoints, d => d.date)) .domain(d3.extent(this._normalDataPoints, (d) => d.date));
} }
get _d3YScale() { get _d3YScale() {
const reductionPercent = this.useLabelsValue ? 0.15 : 0.05 const reductionPercent = this.useLabelsValue ? 0.15 : 0.05;
const dataMin = d3.min(this._normalDataPoints, d => d.value) const dataMin = d3.min(this._normalDataPoints, (d) => d.value);
const dataMax = d3.max(this._normalDataPoints, d => d.value) const dataMax = d3.max(this._normalDataPoints, (d) => d.value);
const padding = (dataMax - dataMin) * reductionPercent const padding = (dataMax - dataMin) * reductionPercent;
return d3 return d3
.scaleLinear() .scaleLinear()
.rangeRound([this._d3ContainerHeight, 0]) .rangeRound([this._d3ContainerHeight, 0])
.domain([dataMin - padding, dataMax + padding]) .domain([dataMin - padding, dataMax + padding]);
} }
} }

View file

@ -1,11 +1,11 @@
import { Controller } from '@hotwired/stimulus'
import { import {
autoUpdate,
computePosition, computePosition,
flip, flip,
shift,
offset, offset,
autoUpdate shift,
} from '@floating-ui/dom'; } from "@floating-ui/dom";
import { Controller } from "@hotwired/stimulus";
export default class extends Controller { export default class extends Controller {
static targets = ["tooltip"]; static targets = ["tooltip"];
@ -39,20 +39,20 @@ export default class extends Controller {
} }
show = () => { show = () => {
this.tooltipTarget.style.display = 'block'; this.tooltipTarget.style.display = "block";
this.update(); // Ensure immediate update when shown this.update(); // Ensure immediate update when shown
} };
hide = () => { hide = () => {
this.tooltipTarget.style.display = 'none'; this.tooltipTarget.style.display = "none";
} };
startAutoUpdate() { startAutoUpdate() {
if (!this._cleanup) { if (!this._cleanup) {
this._cleanup = autoUpdate( this._cleanup = autoUpdate(
this.element, this.element,
this.tooltipTarget, this.tooltipTarget,
this.boundUpdate this.boundUpdate,
); );
} }
} }
@ -69,9 +69,13 @@ export default class extends Controller {
computePosition(this.element, this.tooltipTarget, { computePosition(this.element, this.tooltipTarget, {
placement: this.placementValue, placement: this.placementValue,
middleware: [ middleware: [
offset({ mainAxis: this.offsetValue, crossAxis: this.crossAxisValue, alignmentAxis: this.alignmentAxisValue }), offset({
mainAxis: this.offsetValue,
crossAxis: this.crossAxisValue,
alignmentAxis: this.alignmentAxisValue,
}),
flip(), flip(),
shift({ padding: 5 }) shift({ padding: 5 }),
], ],
}).then(({ x, y, placement, middlewareData }) => { }).then(({ x, y, placement, middlewareData }) => {
Object.assign(this.tooltipTarget.style, { Object.assign(this.tooltipTarget.style, {
@ -80,4 +84,4 @@ export default class extends Controller {
}); });
}); });
} }
} }

View file

@ -1,55 +1,62 @@
import {Controller} from "@hotwired/stimulus" import { Controller } from "@hotwired/stimulus";
const TRADE_TYPES = { const TRADE_TYPES = {
BUY: "buy", BUY: "buy",
SELL: "sell", SELL: "sell",
TRANSFER_IN: "transfer_in", TRANSFER_IN: "transfer_in",
TRANSFER_OUT: "transfer_out", TRANSFER_OUT: "transfer_out",
INTEREST: "interest" INTEREST: "interest",
} };
const FIELD_VISIBILITY = { const FIELD_VISIBILITY = {
[TRADE_TYPES.BUY]: {ticker: true, qty: true, price: true}, [TRADE_TYPES.BUY]: { ticker: true, qty: true, price: true },
[TRADE_TYPES.SELL]: {ticker: true, qty: true, price: true}, [TRADE_TYPES.SELL]: { ticker: true, qty: true, price: true },
[TRADE_TYPES.TRANSFER_IN]: {amount: true, transferAccount: true}, [TRADE_TYPES.TRANSFER_IN]: { amount: true, transferAccount: true },
[TRADE_TYPES.TRANSFER_OUT]: {amount: true, transferAccount: true}, [TRADE_TYPES.TRANSFER_OUT]: { amount: true, transferAccount: true },
[TRADE_TYPES.INTEREST]: {amount: true} [TRADE_TYPES.INTEREST]: { amount: true },
} };
// Connects to data-controller="trade-form" // Connects to data-controller="trade-form"
export default class extends Controller { export default class extends Controller {
static targets = ["typeInput", "tickerInput", "amountInput", "transferAccountInput", "qtyInput", "priceInput"] static targets = [
"typeInput",
"tickerInput",
"amountInput",
"transferAccountInput",
"qtyInput",
"priceInput",
];
connect() { connect() {
this.handleTypeChange = this.handleTypeChange.bind(this) this.handleTypeChange = this.handleTypeChange.bind(this);
this.typeInputTarget.addEventListener("change", this.handleTypeChange) this.typeInputTarget.addEventListener("change", this.handleTypeChange);
this.updateFields(this.typeInputTarget.value || TRADE_TYPES.BUY) this.updateFields(this.typeInputTarget.value || TRADE_TYPES.BUY);
} }
disconnect() { disconnect() {
this.typeInputTarget.removeEventListener("change", this.handleTypeChange) this.typeInputTarget.removeEventListener("change", this.handleTypeChange);
} }
handleTypeChange(event) { handleTypeChange(event) {
this.updateFields(event.target.value) this.updateFields(event.target.value);
} }
updateFields(type) { updateFields(type) {
const visibleFields = FIELD_VISIBILITY[type] || {} const visibleFields = FIELD_VISIBILITY[type] || {};
Object.entries(this.fieldTargets).forEach(([field, target]) => { Object.entries(this.fieldTargets).forEach(([field, target]) => {
const isVisible = visibleFields[field] || false const isVisible = visibleFields[field] || false;
// Update visibility // Update visibility
target.hidden = !isVisible target.hidden = !isVisible;
// Update required status based on visibility // Update required status based on visibility
if (isVisible) { if (isVisible) {
target.setAttribute('required', '') target.setAttribute("required", "");
} else { } else {
target.removeAttribute('required') target.removeAttribute("required");
} }
}) });
} }
get fieldTargets() { get fieldTargets() {
@ -58,7 +65,7 @@ export default class extends Controller {
amount: this.amountInputTarget, amount: this.amountInputTarget,
transferAccount: this.transferAccountInputTarget, transferAccount: this.transferAccountInputTarget,
qty: this.qtyInputTarget, qty: this.qtyInputTarget,
price: this.priceInputTarget price: this.priceInputTarget,
} };
} }
} }

34
biome.json Normal file
View file

@ -0,0 +1,34 @@
{
"$schema": "https://biomejs.dev/schemas/1.9.3/schema.json",
"vcs": {
"enabled": false,
"clientKind": "git",
"useIgnoreFile": true
},
"files": {
"ignoreUnknown": false,
"ignore": [],
"include": ["./app/javascript/**/*.js"]
},
"formatter": {
"enabled": true,
"useEditorconfig": true
},
"organizeImports": {
"enabled": true
},
"linter": {
"enabled": true,
"rules": {
"recommended": true,
"complexity": {
"noForEach": "off"
}
}
},
"javascript": {
"formatter": {
"quoteStyle": "double"
}
}
}

180
package-lock.json generated Normal file
View file

@ -0,0 +1,180 @@
{
"name": "maybe",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "maybe",
"version": "1.0.0",
"license": "ISC",
"devDependencies": {
"@biomejs/biome": "1.9.3"
}
},
"node_modules/@biomejs/biome": {
"version": "1.9.3",
"resolved": "https://registry.npmjs.org/@biomejs/biome/-/biome-1.9.3.tgz",
"integrity": "sha512-POjAPz0APAmX33WOQFGQrwLvlu7WLV4CFJMlB12b6ZSg+2q6fYu9kZwLCOA+x83zXfcPd1RpuWOKJW0GbBwLIQ==",
"dev": true,
"hasInstallScript": true,
"license": "MIT OR Apache-2.0",
"bin": {
"biome": "bin/biome"
},
"engines": {
"node": ">=14.21.3"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/biome"
},
"optionalDependencies": {
"@biomejs/cli-darwin-arm64": "1.9.3",
"@biomejs/cli-darwin-x64": "1.9.3",
"@biomejs/cli-linux-arm64": "1.9.3",
"@biomejs/cli-linux-arm64-musl": "1.9.3",
"@biomejs/cli-linux-x64": "1.9.3",
"@biomejs/cli-linux-x64-musl": "1.9.3",
"@biomejs/cli-win32-arm64": "1.9.3",
"@biomejs/cli-win32-x64": "1.9.3"
}
},
"node_modules/@biomejs/cli-darwin-arm64": {
"version": "1.9.3",
"resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-1.9.3.tgz",
"integrity": "sha512-QZzD2XrjJDUyIZK+aR2i5DDxCJfdwiYbUKu9GzkCUJpL78uSelAHAPy7m0GuPMVtF/Uo+OKv97W3P9nuWZangQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@biomejs/cli-darwin-x64": {
"version": "1.9.3",
"resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-1.9.3.tgz",
"integrity": "sha512-vSCoIBJE0BN3SWDFuAY/tRavpUtNoqiceJ5PrU3xDfsLcm/U6N93JSM0M9OAiC/X7mPPfejtr6Yc9vSgWlEgVw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@biomejs/cli-linux-arm64": {
"version": "1.9.3",
"resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-1.9.3.tgz",
"integrity": "sha512-vJkAimD2+sVviNTbaWOGqEBy31cW0ZB52KtpVIbkuma7PlfII3tsLhFa+cwbRAcRBkobBBhqZ06hXoZAN8NODQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@biomejs/cli-linux-arm64-musl": {
"version": "1.9.3",
"resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-1.9.3.tgz",
"integrity": "sha512-VBzyhaqqqwP3bAkkBrhVq50i3Uj9+RWuj+pYmXrMDgjS5+SKYGE56BwNw4l8hR3SmYbLSbEo15GcV043CDSk+Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@biomejs/cli-linux-x64": {
"version": "1.9.3",
"resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-1.9.3.tgz",
"integrity": "sha512-x220V4c+romd26Mu1ptU+EudMXVS4xmzKxPVb9mgnfYlN4Yx9vD5NZraSx/onJnd3Gh/y8iPUdU5CDZJKg9COA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@biomejs/cli-linux-x64-musl": {
"version": "1.9.3",
"resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-1.9.3.tgz",
"integrity": "sha512-TJmnOG2+NOGM72mlczEsNki9UT+XAsMFAOo8J0me/N47EJ/vkLXxf481evfHLlxMejTY6IN8SdRSiPVLv6AHlA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@biomejs/cli-win32-arm64": {
"version": "1.9.3",
"resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-1.9.3.tgz",
"integrity": "sha512-lg/yZis2HdQGsycUvHWSzo9kOvnGgvtrYRgoCEwPBwwAL8/6crOp3+f47tPwI/LI1dZrhSji7PNsGKGHbwyAhw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=14.21.3"
}
},
"node_modules/@biomejs/cli-win32-x64": {
"version": "1.9.3",
"resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-1.9.3.tgz",
"integrity": "sha512-cQMy2zanBkVLpmmxXdK6YePzmZx0s5Z7KEnwmrW54rcXK3myCNbQa09SwGZ8i/8sLw0H9F3X7K4rxVNGU8/D4Q==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=14.21.3"
}
}
}
}

18
package.json Normal file
View file

@ -0,0 +1,18 @@
{
"devDependencies": {
"@biomejs/biome": "1.9.3"
},
"name": "maybe",
"version": "1.0.0",
"description": "The OS for your personal finances",
"scripts": {
"style:check": "biome check",
"style:fix":"biome check --write",
"lint": "biome lint",
"lint:fix" : "biome lint --write",
"format:check" : "biome format",
"format" : "biome format --write"
},
"author": "",
"license": "ISC"
}