Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
19.0 KB
Raw Blame
<% intro_mode = Current.user&.ui_layout_intro? %>
<% home_path = intro_mode ? chats_path : root_path %>
<%# Assistant type "mcp_only" removes every chat surface. MCP is unaffected. %>
<% assistant_enabled = Current.family.assistant_enabled? %>
<% mobile_nav_items = if intro_mode
  [
    { name: t(".nav.home"), path: chats_path, icon: "home", icon_custom: false, active: page_active?(chats_path) },
    { name: "Intro", path: intro_path, icon: "sparkles", icon_custom: false, active: page_active?(intro_path) }
  ]
else
  [
    { name: t(".nav.home"), path: root_path, icon: "pie-chart", icon_custom: false, active: page_active?(root_path) },
    { name: t(".nav.transactions"), path: transactions_path, icon: "credit-card", icon_custom: false, active: page_active?(transactions_path) },
    bills_nav_item,
    { name: t(".nav.reports"), path: reports_path, icon: "chart-bar", icon_custom: false, active: page_active?(reports_path) },
    plan_nav_item,
    portfolio_nav_item,
    ({ name: t(".nav.assistant"), path: chats_path, icon: "icon-assistant", icon_custom: true, active: page_active?(chats_path), mobile_only: true } if assistant_enabled)
  ].compact
end %>

<% desktop_nav_items = mobile_nav_items.reject { |item| item[:mobile_only] } %>
<% expanded_sidebar_class = "w-full" %>
<% collapsed_sidebar_class = "w-0 overflow-hidden" %>

<%= render "layouts/shared/htmldoc", sidebar_aware: true do %>
  <div
    class="flex flex-col lg:flex-row h-full bg-surface"
    data-controller="app-layout privacy-mode sidebar-resize"
    data-app-layout-expanded-sidebar-class="<%= expanded_sidebar_class %>"
    data-app-layout-collapsed-sidebar-class="<%= collapsed_sidebar_class %>"
    data-app-layout-user-id-value="<%= Current.user.id %>">
    <%= link_to t("layouts.application.skip_to_main"), "#main",
        class: "sr-only focus:not-sr-only focus:fixed focus:top-2 focus:left-2 focus:z-50 focus:px-3 focus:py-2 focus:rounded-lg focus:bg-container focus:text-primary focus:shadow-border-xs" %>

    <div
      class="hidden fixed inset-0 bg-surface z-20 h-full w-full pt-[calc(env(safe-area-inset-top)+0.75rem)] pr-3 pb-[calc(env(safe-area-inset-bottom)+0.75rem)] pl-3 overflow-y-auto transition-all duration-300"
      data-app-layout-target="mobileSidebar">
      <% unless intro_mode %>
        <div class="mb-2">
          <%= icon("x", as_button: true, data: { action: "app-layout#closeMobileSidebar" }) %>
        </div>
      <% end %>

      <%= render(
        "accounts/account_sidebar_tabs",
        family: Current.family,
        active_tab: @account_group_tab,
        mobile: true
      ) %>
    </div>

    <%# MOBILE - Top nav %>
    <nav class="lg:hidden relative flex justify-between items-center p-3 pt-[calc(env(safe-area-inset-top)+0.75rem)]">
      <% if intro_mode %>
      <% else %>
        <div class="flex items-center gap-1">
          <%= icon("panel-left", as_button: true, data: { action: "app-layout#openMobileSidebar"}) %>
          <%= render "layouts/shared/insights_button" %>
        </div>
      <% end %>

      <%= link_to home_path, class: "absolute left-1/2 -translate-x-1/2" do %>
        <%= image_tag "logomark-color.svg", class: "w-9 h-9 mx-auto" %>
      <% end %>

      <div class="flex items-center gap-1">
        <button type="button"
                class="inline-flex items-center justify-center w-9 h-9 pointer-coarse:w-11 pointer-coarse:h-11 rounded-lg text-secondary hover:text-primary hover:bg-container-inset-hover transition-colors focus-ring"
                data-action="click->privacy-mode#toggle"
                data-privacy-mode-target="toggle"
                title="<%= t("layouts.application.privacy_mode") %>"
                aria-label="<%= t("layouts.application.privacy_mode") %>"
                aria-pressed="false">
          <%= icon("eye-off", size: "sm", data: { privacy_mode_target: "iconOff" }) %>
          <%= icon("eye", size: "sm", class: "hidden", data: { privacy_mode_target: "iconOn" }) %>
        </button>
        <%= render "users/user_menu", user: Current.user, placement: "bottom-end", offset: 12, intro_mode: intro_mode %>
      </div>
    </nav>

    <%# DESKTOP - Left navbar %>
    <div class="hidden lg:block border-r border-divider">
      <nav class="h-full flex flex-col shrink-0 w-[84px] py-4">
        <div class="pl-2 mb-3">
          <%= link_to home_path, class: "block" do %>
            <%= image_tag "logomark-color.svg", class: "w-9 h-9 mx-auto" %>
          <% end %>
        </div>

        <ul class="space-y-0.5">
          <% desktop_nav_items.reject { |item| item[:mobile_only] }.each do |nav_item| %>
            <li>
              <%= render "layouts/shared/nav_item", **nav_item %>
            </li>
          <% end %>
        </ul>

        <div class="pl-2 mt-auto mx-auto flex flex-col gap-2">
          <%= render DS::Link.new(
            variant: "icon",
            icon: "message-circle-question",
            href: "https://discord.gg/36ZGBsxYEK",
            target: "_blank"
          ) %>

          <%= render "users/user_menu", user: Current.user, intro_mode: intro_mode %>
        </div>
      </nav>
    </div>

    <%# DESKTOP - Left sidebar %>
    <%= tag.div class: class_names(
        "hidden lg:block relative py-4 shrink-0 transition-[width] duration-300 border-divider",
        Current.user.show_sidebar? ? [expanded_sidebar_class, "border-r"] : [collapsed_sidebar_class, "border-r-0"],
       ),
       style: "max-width: var(--left-sidebar-width, 320px)",
       inert: !Current.user.show_sidebar?,
       data: { app_layout_target: "leftSidebar", sidebar_resize_target: "leftSidebar" } do %>
      <%= render "layouts/shared/sidebar_resize_handle", side: "left" %>
      <%# The scrollbar's space is kept even while the list fits, so opening or
          closing account groups doesn't narrow and widen the sidebar. %>
      <div id="sidebar-scroll" data-controller="preserve-scroll" class="px-4 h-full flex flex-col overflow-y-auto [scrollbar-gutter:stable]">
        <% if content_for?(:sidebar) %>
          <%= yield :sidebar %>
        <% else %>
          <div class="grow">
            <%= render "accounts/account_sidebar_tabs", family: Current.family, active_tab: @account_group_tab %>
          </div>

          <% if Current.family.trialing? && !self_hosted? %>
            <div class="px-4 py-3 space-y-4 bg-container shadow-border-xs rounded-xl">
              <div class="flex items-start justify-between">
                <div>
                  <p class="text-sm font-medium text-primary"><%= t("layouts.trial.open_demo") %></p>
                  <p class="text-sm text-secondary"><%= t("layouts.trial.data_deleted_in_days", days: Current.family.days_left_in_trial) %></p>
                </div>

                <%= render DS::Link.new(
                  text: t("layouts.trial.contribute"),
                  href: upgrade_subscription_path,
                ) %>
              </div>

              <div class="flex items-center gap-0.5 h-1.5">
                <div class="h-full bg-warning rounded-full" style="width: <%= Current.family.percentage_of_trial_completed %>%"></div>
                <div class="h-full bg-surface-inset rounded-full" style="width: <%= Current.family.percentage_of_trial_remaining %>%"></div>
              </div>
            </div>
          <% end %>
        <% end %>
      </div>
    <% end %>

    <%# SHARED - Main content %>
    <%# On phones the bottom padding keeps the page, full-height pages too,
        above the bottom nav. Safari can leave a scroll container's bottom
        padding out of how far it scrolls, so an empty ::after spacer reaches
        down to the padding's end (its negative margin takes nothing from the
        layout) and keeps the end of the page reachable. %>
    <%= tag.main id: "main", class: class_names("grow overflow-y-auto px-3 lg:px-10 w-full mx-auto pb-[calc(5rem+env(safe-area-inset-bottom))] lg:pb-0 after:block after:content-[''] after:h-[calc(5rem+env(safe-area-inset-bottom))] after:-mb-[calc(5rem+env(safe-area-inset-bottom))] lg:after:hidden"), data: { app_layout_target: "content", viewport_target: "content", notification_tray_target: "main" } do %>
      <% unless intro_mode %>
        <div class="hidden lg:flex gap-2 items-center justify-between mb-6 sticky top-0 z-10 -mx-3 lg:-mx-10 px-3 lg:px-10 py-4 bg-surface border-b border-tertiary">
          <div class="flex items-center gap-2">
            <%= icon("panel-left", as_button: true, data: { action: "app-layout#toggleLeftSidebar" }) %>

            <% if content_for?(:breadcrumbs) %>
              <%= yield :breadcrumbs %>
            <% else %>
              <%= render "layouts/shared/breadcrumbs", breadcrumbs: breadcrumbs %>
            <% end %>
          </div>

          <div class="flex items-center gap-2">
            <%= render "layouts/shared/insights_button" %>

            <button type="button"
                    class="inline-flex items-center justify-center w-9 h-9 pointer-coarse:w-11 pointer-coarse:h-11 rounded-lg text-secondary hover:text-primary hover:bg-container-inset-hover transition-colors focus-ring"
                    data-action="click->privacy-mode#toggle"
                    data-privacy-mode-target="toggle"
                    title="<%= t("layouts.application.privacy_mode") %>"
                    aria-label="<%= t("layouts.application.privacy_mode") %>"
                    aria-pressed="false">
              <%= icon("eye-off", size: "sm", data: { privacy_mode_target: "iconOff" }) %>
              <%= icon("eye", size: "sm", class: "hidden", data: { privacy_mode_target: "iconOn" }) %>
            </button>

            <% if assistant_enabled %>
              <%= icon("panel-right", as_button: true, data: { action: "app-layout#toggleRightSidebar" }) %>
            <% end %>
          </div>
        </div>
      <% end %>

      <%= yield :system_alerts %>

      <% if content_for?(:page_header) %>
        <%= yield :page_header %>
      <% end %>

      <%= yield %>
    <% end %>

    <% if assistant_enabled %>
      <%# DESKTOP - Right sidebar %>
      <%= tag.div class: class_names(
            "hidden lg:block relative h-full shrink-0 transition-[width] duration-300 border-divider",
            Current.user.show_ai_sidebar? ? [expanded_sidebar_class, "border-l"] : [collapsed_sidebar_class, "border-l-0"],
          ),
          style: "max-width: var(--right-sidebar-width, 400px)",
          inert: !Current.user.show_ai_sidebar?,
          data: { app_layout_target: "rightSidebar", sidebar_resize_target: "rightSidebar" } do %>
        <%= render "layouts/shared/sidebar_resize_handle", side: "right" %>
        <%= tag.div id: "chat-container", class: "relative h-full px-4 overflow-y-auto", data: { controller: "chat hotkey", chat_response_timeout_value: Chat.response_timeout_ms, turbo_permanent: true } do %>
          <div class="flex flex-col h-full justify-between shrink-0">
            <%= turbo_frame_tag chat_frame, src: chat_view_path(@chat), loading: "lazy", class: "h-full" do %>
              <div class="flex justify-center items-center h-full">
                <%= icon("loader-circle", class: "animate-spin") %>
              </div>
            <% end %>
          </div>

          <% unless Current.user.ai_enabled? %>
            <div class="absolute backdrop-blur-lg inset-0 h-full w-full flex flex-col justify-center items-center px-4">
              <%= render "chats/ai_consent" %>
            </div>
          <% end %>
        <% end %>
      <% end %>
    <% end %>

    <%# MOBILE - Bottom Nav %>
    <%= tag.nav class: "lg:hidden fixed bottom-0 left-0 right-0 bg-surface z-10 border-t border-tertiary flex justify-around pb-[env(safe-area-inset-bottom)]",
      data: { viewport_target: "bottomNav" } do %>
      <% mobile_nav_items.reject { |item| item[:desktop_only] }.each do |nav_item| %>
        <%= render "layouts/shared/nav_item", **nav_item %>
      <% end %>
    <% end %>
    <%# "What's new" release highlight: one dialog per deployed release,
        shown on first interaction and tracked per account. %>
    <% unless intro_mode %>
      <% if (tag = pending_release_tag) %>
        <%= render "layouts/shared/release_highlight", tag: tag %>
      <% end %>
    <% end %>
<%# Preserve the account sidebar's group open/closed state across Turbo Drive navigations so the sidebar height stays stable and the scroll position is not clamped to the top. See the inline script below for details. %>
<script nonce="<%= content_security_policy_nonce %>">
  // Preserves the account sidebar's group open/closed state across Turbo Drive
  // navigations so the sidebar height stays stable and the scroll position
  // (restored by the `preserve-scroll` controller) is not clamped to the top.
  //
  // Each account group is a <details> whose open state is decided server-side:
  // a group is open when it holds the active account or is in the user's
  // "always expanded" preference. Navigating between accounts re-renders a
  // different set of open groups, which changes the sidebar's scrollHeight.
  // If the new sidebar is shorter than the saved offset, the browser clamps
  // the restored scrollTop to the new maximum and the user sees the sidebar
  // jump back up. This script records the open/closed state of every group
  // before the navigation and re-applies it after the render (so a group the
  // user collapsed stays collapsed, even one the server would re-open from the
  // "always expanded" preference), keeps the group holding the active account
  // open, forces a synchronous layout pass, and re-applies the saved scrollTop
  // so the offset is valid again.
  //
  // groupKeyOf() derives a tab-independent group key from either markup shape:
  //   (a) the NEW sidebar partial / balance sheet, which carry
  //       data-group-key on the <details> or its wrapper, or
  //   (b) the OLD sidebar partial, whose wrapper id is <tab>_<group>
  //       (all_/asset_/liability_, plus the mobile_ variant) with no
  //       data-group-key. A key is only accepted if it is a known account
  //       category, so unrelated <details> widgets are never treated as
  //       account groups. This makes the fix tolerant of a mixed deployment
  //       where the sidebar partial and the balance sheet differ.
  //
  // State lives on a window global so it survives Turbo Drive visits (the
  // window is not replaced, only the body). The listeners are bound once;
  // the trailing restore() also covers a full (non-Turbo) page load, where
  // the global is fresh and the call is a no-op.
  (function () {
    var state = window.__sidebarScrollPreserve ||
      (window.__sidebarScrollPreserve = { groupStates: null, scrollTop: null });

    var PREFIX_RE = /^(mobile_)?(all|asset|liability)_/;
    // Accepted group keys, derived from Accountable::TYPES at render time
    // so the set stays in sync with the source of truth: adding a new
    // accountable type cannot silently recreate the "open group not
    // re-opened after navigation" gap. `to_json` escapes <>& as unicode
    // (safe inside a <script> tag); `raw` keeps ERB from double-escaping.
    var GROUP_KEYS = new Set(<%= raw(Accountable::TYPES.map(&:underscore).to_json) %>);

    function container() { return document.getElementById("sidebar-scroll"); }

    function validKey(value) {
      return value && GROUP_KEYS.has(value) ? value : null;
    }

    // Derive a tab-independent group key from a <details>, or null if it is
    // not an account group.
    function groupKeyOf(details) {
      var root = container();
      if (!root || !root.contains(details)) return null;
      // 1. data-group-key on the <details> or its nearest wrapper.
      for (var node = details; node && node !== root; node = node.parentElement) {
        if (node.hasAttribute("data-group-key")) {
          return validKey(node.getAttribute("data-group-key"));
        }
      }
      // 2. Wrapper id with the tab prefix stripped (old partial).
      for (var w = details.parentElement; w && w !== root; w = w.parentElement) {
        if (w.id && PREFIX_RE.test(w.id)) {
          return validKey(w.id.replace(PREFIX_RE, ""));
        }
      }
      return null;
    }

    function groupDetails() {
      var root = container();
      if (!root) return [];
      return Array.prototype.slice.call(root.querySelectorAll("details"));
    }

    // Prototype-free map of group key -> open/closed for every account group,
    // or null when there are no account groups at all. Storing the explicit
    // boolean (not just the open keys) lets restore() keep a group the user
    // collapsed closed, including groups the server re-opens from the
    // "always expanded" preference.
    function groupStates() {
      var states = null;
      groupDetails().forEach(function (d) {
        var k = groupKeyOf(d);
        if (k) {
          if (!states) states = Object.create(null);
          states[k] = d.open;
        }
      });
      return states;
    }

    // Key of the group holding the active account, or null. The active account
    // link is marked data-active-account in the sidebar partial; every copy of
    // the account (per tab panel, desktop + mobile) shares the same group key,
    // so the first match resolves to the right group.
    function activeGroupKey() {
      var root = container();
      if (!root) return null;
      var active = root.querySelector("[data-active-account]");
      if (!active) return null;
      var d = active.closest("details");
      return d ? groupKeyOf(d) : null;
    }

    function capture() {
      var el = container();
      if (!el) return;
      state.groupStates = groupStates();
      // Always save the scroll offset, even when every group is collapsed:
      // the sidebar can still be scrolled (headers, "New" buttons, the bottom
      // of a long list), so coupling the save to "any group open" would drop
      // the offset in that case.
      state.scrollTop = el.scrollTop;
    }

    function restore() {
      var el = container();
      if (!el || !state.groupStates) return;
      var activeKey = activeGroupKey();
      // Re-apply the user's pre-navigation open/closed state to every group we
      // captured. A group the user collapsed stays closed even if the server
      // re-opens it (active account or "always expanded" preference); the group
      // holding the active account is forced open so it is never hidden.
      // Groups not in state.groupStates (new since capture) are left as the
      // server rendered them.
      groupDetails().forEach(function (d) {
        var k = groupKeyOf(d);
        if (!k || !Object.prototype.hasOwnProperty.call(state.groupStates, k)) return;
        d.open = (k === activeKey) ? true : state.groupStates[k];
      });
      // Force a synchronous layout pass so scrollHeight reflects the re-opened
      // groups before we write scrollTop; otherwise the browser clamps the
      // restored offset to the (still-short) container.
      void el.offsetHeight;
      if (typeof state.scrollTop === "number") el.scrollTop = state.scrollTop;
    }

    if (!window.__sidebarScrollPreserveBound) {
      window.__sidebarScrollPreserveBound = true;
      window.addEventListener("turbo:before-cache", capture);
      window.addEventListener("turbo:render", restore);
    }
    restore();
  })();

</script>
  </div>
<% end %>