Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
8.1 KB
Raw Blame
import { Controller } from "@hotwired/stimulus";

export default class extends Controller {
  static targets = ["button", "label", "panel", "code", "status"];
  static values = {
    initiateUrl: String,
    pollUrl: String,
    cancelUrl: String,
    returnUrl: String,
    autoPoll: { type: Boolean, default: false },
    loadingText: String,
    instructionText: String,
    successText: String,
    errorText: String,
    interval: { type: Number, default: 1000 },
    timeout: { type: Number, default: 120000 },
    maxRetryDelay: { type: Number, default: 8000 },
    loginText: String,
    cancelText: String,
  };

  connect() {
    this.polling = false;
    this.stopped = false;
    this.pollRequest = null;
    this.retryCount = 0;
    if (this.autoPollValue) {
      this.polling = true;
      this.startedAt = Date.now();
      this.panelTarget.hidden = false;
      this.setButtonLabel(this.cancelTextValue);
      this.statusTarget.textContent = this.instructionTextValue;
      this.poll();
    }
  }

  disconnect() {
    this.stopped = true;
    clearTimeout(this.timer);
    this.pollRequest?.abort();
  }

  async start(event) {
    event.preventDefault();
    if (this.polling) return;

    this.stopped = false;
    this.polling = true;
    this.retryCount = 0;
    this.startedAt = Date.now();
    this.panelTarget.hidden = false;
    this.setButtonLabel(this.cancelTextValue);
    this.codeTarget.replaceChildren();
    this.statusTarget.textContent = this.loadingTextValue;

    let initiation = null;
    try {
      // A cancel waits for this request: sent earlier, it would be overtaken
      // by the login this request stores.
      initiation = fetch(this.initiateUrlValue, {
        method: "POST",
        headers: { ...this.headers(), Accept: "text/vnd.turbo-stream.html" },
        credentials: "same-origin",
        body: this.body(),
      });
      this.initiation = initiation;
      const response = await initiation;
      if (this.stopped) return;
      if (!response.ok)
        throw new Error(`QR login initiation failed: ${response.status}`);

      const result = await response.json();
      if (this.stopped) return;
      this.renderQr(result);

      await this.poll();
    } catch (error) {
      this.showError(error);
    } finally {
      if (this.initiation === initiation) this.initiation = null;
    }
  }

  async poll() {
    if (this.stopped) return;

    try {
      this.pollRequest?.abort();
      this.pollRequest = new AbortController();
      const response = await fetch(this.pollUrlValue, {
        method: "POST",
        headers: { ...this.headers(), Accept: "application/json" },
        credentials: "same-origin",
        body: this.body(),
        signal: this.pollRequest.signal,
      });
      const result = await this.jsonResponse(response);
      if (!response.ok) {
        const error = new Error(result.error || "QR login failed");
        error.retryable =
          result.retryable === true || this.retryableStatus(response.status);
        throw error;
      }

      this.retryCount = 0;
      this.renderQr(result);

      if (result.status !== "pending") {
        this.statusTarget.textContent = this.successTextValue;
        // "replace" forces a fetch; an advance visit to the same path with only
        // a new #anchor is treated as a same-page scroll and never reloads.
        window.Turbo.visit(this.returnUrlValue, { action: "replace" });
        return;
      }

      this.schedulePoll(this.nextPollDelay(result));
    } catch (error) {
      if (this.stopped || error.name === "AbortError") return;

      if (
        this.isRetryableError(error) &&
        Date.now() - this.startedAt < this.timeoutValue
      ) {
        this.retryCount += 1;
        this.schedulePoll(this.retryDelay());
      } else {
        this.showError(error);
      }
    } finally {
      this.pollRequest = null;
    }
  }

  schedulePoll(delay) {
    clearTimeout(this.timer);
    if (this.stopped) return;

    if (Date.now() - this.startedAt >= this.timeoutValue) {
      this.showError(new Error("QR login expired"));
      return;
    }

    this.timer = setTimeout(() => this.poll(), delay);
  }

  retryDelay() {
    return Math.min(
      this.intervalValue * 2 ** Math.min(this.retryCount - 1, 4),
      this.maxRetryDelayValue,
    );
  }

  retryableStatus(status) {
    return status === 408 || status === 425 || status === 429 || status >= 500;
  }

  isRetryableError(error) {
    return error.retryable === true || error.name === "TypeError";
  }

  async jsonResponse(response) {
    try {
      return await response.json();
    } catch {
      const error = new Error(
        `QR login returned invalid JSON: ${response.status}`,
      );
      error.retryable = this.retryableStatus(response.status);
      throw error;
    }
  }

  showError(error) {
    if (this.stopped) return;
    console.warn("[Trade Republic] QR login failed", error);
    this.polling = false;
    this.setButtonLabel(this.loginTextValue);
    this.buttonTarget.disabled = false;
    this.statusTarget.textContent = this.errorTextValue;
  }

  toggle(event) {
    event.preventDefault();
    if (this.polling) {
      this.hideQr();
    } else {
      this.start(event);
    }
  }

  async hideQr() {
    this.stopped = true;
    clearTimeout(this.timer);
    this.pollRequest?.abort();
    this.polling = false;
    this.panelTarget.hidden = true;
    this.codeTarget.replaceChildren();
    // A login started before the server confirms the cancellation would be
    // cleared by it, so the button stays disabled until then.
    this.buttonTarget.disabled = true;
    this.setButtonLabel(this.loginTextValue);

    try {
      await this.initiation?.catch(() => {});
      const response = await fetch(this.cancelUrlValue, {
        method: "POST",
        headers: { ...this.headers(), Accept: "text/vnd.turbo-stream.html" },
        credentials: "same-origin",
        body: this.body(),
      });
      if (!response.ok)
        throw new Error(`QR login cancellation failed: ${response.status}`);

      const stream = await response.text();
      if (!this.element.isConnected) return;

      // In Settings this replaces the connection card, which brings back the
      // credentials form hidden while the login was pending. Turbo replaces
      // it on the next repaint, so the old button stays disabled until the
      // new card brings an enabled one. The Accounts page has no such card.
      const replacesCard = this.streamReplacesElement(stream);
      Turbo.renderStreamMessage(stream);
      if (!replacesCard) this.buttonTarget.disabled = false;
    } catch (error) {
      this.stopped = false;
      this.buttonTarget.disabled = false;
      console.warn("[Trade Republic] QR login cancellation failed", error);
    }
  }

  streamReplacesElement(stream) {
    const template = document.createElement("template");
    template.innerHTML = stream;
    const targetId = template.content
      .querySelector("turbo-stream")
      ?.getAttribute("target");
    const target = targetId && document.getElementById(targetId);
    return Boolean(target?.contains(this.element));
  }

  renderQr(result) {
    if (!result.qr_code_svg) return;
    this.codeTarget.innerHTML = result.qr_code_svg;
    this.statusTarget.textContent = this.instructionTextValue;
  }

  nextPollDelay(result) {
    const expiresAt = result.qr_code_token_expires_at;
    if (!expiresAt) return this.intervalValue;

    const remaining = Date.parse(expiresAt) - Date.now();
    return remaining > 0 && remaining <= 1500 ? 100 : this.intervalValue;
  }

  setButtonLabel(label) {
    // DS::Button renders its text in a span, so without a label target the
    // button's own text is updated.
    const target = this.hasLabelTarget
      ? this.labelTarget
      : this.buttonTarget.querySelector("span");
    if (target) target.textContent = label;
  }

  headers() {
    return {
      Accept: "application/json",
      "X-CSRF-Token":
        document.querySelector("meta[name='csrf-token']")?.content || "",
      "X-Requested-With": "XMLHttpRequest",
    };
  }

  body() {
    const csrfToken =
      document.querySelector("meta[name='csrf-token']")?.content || "";
    return new URLSearchParams({ authenticity_token: csrfToken });
  }
}