SaaS-дашборд

Дашборд подписочного сервиса на четыре страницы в одном HTML-файле. Страницы выезжают в сторону вашего движения, число MRR перелетает на страницу выручки, график идёт за пальцем и превращается в столбцы, а тема расходится кругом от нажатого переключателя.

Нажмите MRR на Overview и смотрите, как число перелетает в Revenue. Проведите по графику, переключите Line на Bars, введите no в поиске Customers, потом смените тему в Settings.

Скачать

Что можно поменять

Поменяйте число, сохраните файл и обновите страницу, разница будет видна сразу.

BRAND'Acme'

Название продукта в углу боковой панели.

DATAmonths, revenue, plans, customers

Все числа на всех страницах. Подставьте свои, и графики, показатели и таблица пойдут за ними.

--accent#3A4CF0 / #6C7CFF

Один цвет, которым окрашен весь дашборд, в светлой и тёмной теме.

EASEcubic-bezier(.23, 1, .32, 1)

Кривая, которую используют все плавные переходы и превращения в скрипте.

300ms::view-transition-new(page)

Сколько выезжает новая страница. Держите меньше 400ms, это используется часто.

Как поставить на свой сайт

Используйте как целую страницу админки или личного кабинета либо как скриншот на обложке лендинга вашего сервиса.

Комментарии в коде на английском, так файл понятен любому разработчику.

  1. CSS

    Вставьте в свой файл стилей или в тег <style> внутри <head>.

    /* SaaS Dashboard by @codinvisual · t.me/CodinVisual · free for your own site, don't resell this file */
    :root {
    --bg: #EDEFF3; --panel: #FFFFFF; --ink: #10141B; --muted: #6B7380; --line: #DDE1E8;
    --accent: #3A4CF0; --up: #0FA36B; --down: #E5553A; --soft: #F4F6F9;
    }
    :root[data-theme="dark"] {
    --bg: #0B0E13; --panel: #131821; --ink: #E8ECF2; --muted: #8A93A3; --line: #232A36;
    --accent: #6C7CFF; --up: #18A874; --down: #E8604A; --soft: #182030;
    }
    .app { display: grid; grid-template-columns: 220px 1fr; min-height: 100%; }
    .side { position: relative; view-transition-name: nav; padding: 22px 14px; border-right: 1px solid var(--line); display: flex; flex-direction: column; gap: 4px; }
    .pill-bg { position: absolute; border-radius: 10px; background: var(--panel); box-shadow: 0 1px 0 var(--line), 0 6px 16px -10px rgba(16,20,27,.35); transform-origin: 0 0; }
    .brand { display: flex; align-items: center; gap: 10px; padding: 4px 10px 22px; font-weight: 800; font-size: 17px; letter-spacing: -.01em; }
    .brand i { width: 22px; height: 22px; border-radius: 7px; background: var(--accent); box-shadow: inset -6px -6px 0 rgba(255,255,255,.25); }
    .tab { position: relative; z-index: 1; display: flex; align-items: center; gap: 12px; height: 40px; padding: 0 12px; border: 0; border-radius: 10px;
    background: none; color: var(--muted); font: 600 14px system-ui, sans-serif; text-align: left; cursor: pointer; }
    .tab svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
    .tab[aria-selected="true"] { color: var(--ink); }
    .tab:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
    @media (hover: hover) and (pointer: fine) { .tab:hover { color: var(--ink); } }
    
    main { padding: 26px 32px 40px; min-width: 0; view-transition-name: page; }
    .head { display: flex; align-items: flex-end; justify-content: space-between; gap: 16px; margin-bottom: 22px; }
    .head h1 { margin: 0; font-size: 26px; letter-spacing: -.02em; }
    .head p { margin: 2px 0 0; color: var(--muted); }
    .icon { width: 38px; height: 38px; border: 1px solid var(--line); border-radius: 10px; background: var(--panel); color: var(--ink); display: grid; place-items: center; cursor: pointer; flex: none; }
    .icon svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; }
    .icon:active { transform: scale(.96); }
    .tools { display: flex; align-items: center; gap: 8px; }
    .range { display: flex; padding: 3px; border-radius: 10px; background: var(--soft); border: 1px solid var(--line); }
    .range button { border: 0; background: none; padding: 6px 12px; border-radius: 8px; color: var(--muted); font: 600 13px system-ui, sans-serif; cursor: pointer; }
    .range button[aria-pressed="true"] { background: var(--panel); color: var(--ink); box-shadow: 0 1px 2px rgba(16,20,27,.12); }
    
    /* the numbers read like a ledger: one row, hairlines between, no card per number */
    .kpis { display: grid; grid-template-columns: repeat(4, 1fr); background: var(--panel); border: 1px solid var(--line); border-radius: 16px; overflow: hidden; view-transition-name: kpis; }
    .kpi { padding: 16px 18px 14px; border: 0; border-left: 1px solid var(--line); background: none; color: inherit; font: inherit; text-align: left; }
    button.kpi { cursor: pointer; }
    button.kpi > span::after { content: " ↗"; opacity: .5; }
    button.kpi:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
    @media (hover: hover) and (pointer: fine) { button.kpi:hover { background: var(--soft); } }
    .odo { display: inline-block; height: 1em; overflow: hidden; vertical-align: top; }
    .odo span { display: block; white-space: pre; text-align: center; }
    .heroline { display: flex; align-items: baseline; gap: 12px; margin: -8px 0 18px; }
    .hero { display: block; font: 650 48px/1 system-ui, sans-serif; letter-spacing: -.03em; view-transition-name: mrr; }
    .heroline small { color: var(--muted); font-size: 13px; }
    .kpi:first-child { border-left: 0; }
    .kpi > span { color: var(--muted); font-size: 12.5px; font-weight: 600; }
    .kpi b { display: block; margin: 6px 0 4px; font: 650 30px/1 system-ui, sans-serif; letter-spacing: -.02em; }
    .delta { display: inline-flex; align-items: center; gap: 4px; font-style: normal; font-size: 12.5px; font-weight: 600; color: var(--muted); }
    .delta svg { width: 12px; height: 12px; }
    .delta.up svg { fill: var(--up); } .delta.down svg { fill: var(--down); }
    
    .section { margin-top: 18px; background: var(--panel); border: 1px solid var(--line); border-radius: 16px; padding: 16px 18px; }
    .section h2 { display: flex; align-items: center; justify-content: space-between; margin: 0 0 10px; font-size: 14px; }
    .plot { position: relative; view-transition-name: chart; }
    .chart { width: 100%; height: auto; display: block; overflow: visible; outline: 0; }
    .chart .grid { stroke: var(--line); stroke-width: 1; }
    .chart .lbl { fill: var(--muted); font: 500 10.5px system-ui, sans-serif; font-variant-numeric: tabular-nums; }
    .chart .end { fill: var(--ink); font: 650 12px system-ui, sans-serif; }
    .chart .ln { fill: none; stroke: var(--accent); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
    .chart .ar { fill: var(--accent); fill-opacity: .1; }
    .chart .dot { fill: var(--accent); stroke: var(--panel); stroke-width: 2; }
    .chart .hair { stroke: var(--muted); stroke-width: 1; opacity: 0; }
    .chart .bar.lift { fill-opacity: .8; }
    .chart .veil { fill: var(--panel); opacity: 0; }
    .chart .pulse { fill: none; stroke: var(--accent); stroke-width: 1.5; transform-box: fill-box; transform-origin: center; animation: pulse 1.6s cubic-bezier(.23, 1, .32, 1) infinite; }
    @keyframes pulse { from { transform: scale(1); opacity: .7; } to { transform: scale(3.2); opacity: 0; } }
    ::highlight(match) { background-color: color-mix(in srgb, var(--accent) 24%, transparent); color: var(--ink); }
    .chart:focus-visible { outline: 2px solid var(--accent); outline-offset: 4px; border-radius: 4px; }
    .tip { position: absolute; top: 0; left: 0; padding: 7px 10px; border-radius: 8px; background: var(--ink); color: var(--panel); pointer-events: none; opacity: 0;
    transform: translate(-50%, -110%); transition: opacity .12s ease-out; white-space: nowrap; font-size: 12px; }
    .tip b { display: block; font-size: 14px; } .tip span { opacity: .7; }
    .sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
    .chart .bar { fill: var(--accent); }
    .chart .ln { stroke-dasharray: 1; stroke-dashoffset: 1; animation: draw .9s cubic-bezier(.23, 1, .32, 1) forwards; }
    .chart .ar { animation: fade .6s ease-out .25s both; }
    @keyframes draw { to { stroke-dashoffset: 0; } }
    @keyframes fade { from { opacity: 0; } }
    
    .pay { display: grid; grid-template-columns: 28px 1fr auto auto; align-items: center; gap: 12px; padding: 9px 0; border-top: 1px solid var(--line); }
    .pay:first-of-type { border-top: 0; }
    .av { width: 28px; height: 28px; border-radius: 50%; display: grid; place-items: center; font-size: 11px; font-weight: 800; color: #fff; }
    .pay small { display: block; color: var(--muted); font-size: 12px; }
    .amt { font: 600 15px/1 system-ui, sans-serif; font-variant-numeric: tabular-nums; }
    .pill { display: inline-flex; align-items: center; gap: 5px; padding: 3px 8px 3px 7px; border-radius: 999px; font-size: 11.5px; font-weight: 600; background: var(--soft); color: var(--ink); }
    .pill::before { content: ""; width: 6px; height: 6px; border-radius: 50%; background: var(--muted); }
    .pill.ok::before { background: var(--up); } .pill.late::before { background: var(--down); }
    
    .plans { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0; }
    .plan { padding: 6px 16px; border-left: 1px solid var(--line); }
    .plan:first-child { border-left: 0; padding-left: 0; }
    .plan b { display: block; font: 650 24px/1 system-ui, sans-serif; letter-spacing: -.02em; margin: 6px 0 10px; }
    .meter { height: 6px; border-radius: 3px; background: color-mix(in srgb, var(--accent) 14%, var(--panel)); overflow: hidden; }
    .meter i { display: block; height: 100%; border-radius: 3px; background: var(--accent); }
    
    .search { width: 100%; height: 40px; padding: 0 14px 0 38px; border: 1px solid var(--line); border-radius: 10px; background: var(--panel) no-repeat 12px 50% / 16px;
    color: var(--ink); font: 500 14px system-ui, sans-serif; outline: 0;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%236B7380' stroke-width='2' stroke-linecap='round'%3E%3Ccircle cx='11' cy='11' r='7'/%3E%3Cpath d='M20 20l-3.5-3.5'/%3E%3C/svg%3E"); }
    .search:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 18%, transparent); }
    .row { display: grid; grid-template-columns: 28px 1.4fr 1fr .8fr .8fr; align-items: center; gap: 12px; padding: 10px 0; border-top: 1px solid var(--line); }
    .row .who small { display: block; color: var(--muted); font-size: 12px; }
    .row .num { font: 600 15px/1 system-ui, sans-serif; font-variant-numeric: tabular-nums; text-align: right; }
    .empty { padding: 26px 0 8px; color: var(--muted); text-align: center; }
    
    .set { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 14px 0; border-top: 1px solid var(--line); }
    .set:first-of-type { border-top: 0; }
    .set small { display: block; color: var(--muted); }
    .switch { position: relative; width: 44px; height: 26px; border: 0; border-radius: 13px; background: var(--line); cursor: pointer; flex: none; transition: background .2s ease-out; }
    .switch::after { content: ""; position: absolute; left: 3px; top: 3px; width: 20px; height: 20px; border-radius: 50%; background: #fff; box-shadow: 0 1px 3px rgba(0,0,0,.25); transition: transform .2s cubic-bezier(.23, 1, .32, 1); }
    .switch[aria-checked="true"] { background: var(--accent); }
    .switch[aria-checked="true"]::after { transform: translateX(18px); }
    .switch:active::after { width: 24px; }
    
    /* page changes: the page slides a little and fades, the pill glides to the new tab */
    ::view-transition-old(page) { animation: 130ms ease-out both page-out; }
    ::view-transition-new(page) { animation: 300ms cubic-bezier(.23, 1, .32, 1) 70ms both page-in; }
    /* a number, a chart or a row that lives on one page only leaves and arrives with that page */
    ::view-transition-old(*):only-child { animation: 130ms ease-out both page-out; }
    ::view-transition-new(*):only-child { animation: 300ms cubic-bezier(.23, 1, .32, 1) 70ms both page-in; }
    html:active-view-transition-type(fwd)::view-transition-old(page), html:active-view-transition-type(fwd)::view-transition-old(*):only-child { animation-name: out-left; }
    html:active-view-transition-type(fwd)::view-transition-new(page), html:active-view-transition-type(fwd)::view-transition-new(*):only-child { animation-name: in-right; }
    html:active-view-transition-type(back)::view-transition-old(page), html:active-view-transition-type(back)::view-transition-old(*):only-child { animation-name: out-right; }
    html:active-view-transition-type(back)::view-transition-new(page), html:active-view-transition-type(back)::view-transition-new(*):only-child { animation-name: in-left; }
    /* typing in search: the page holds still, matching rows slide into place, the rest fade out */
    #list { view-transition-name: list; }
    ::view-transition-old(list), ::view-transition-new(list) { height: 100%; }
    html:active-view-transition-type(filter)::view-transition-old(page) { display: none; }
    html:active-view-transition-type(filter)::view-transition-new(page) { animation: none; }
    html:active-view-transition-type(filter)::view-transition-group(*) { animation-duration: 260ms; animation-timing-function: cubic-bezier(.23, 1, .32, 1); }
    html:active-view-transition-type(filter)::view-transition-old(*):only-child { animation: 120ms ease-out both row-out; }
    html:active-view-transition-type(filter)::view-transition-new(*):only-child { animation: 220ms cubic-bezier(.23, 1, .32, 1) 60ms both row-in; }
    @keyframes row-out { to { opacity: 0; transform: scale(.97); } }
    @keyframes row-in { from { opacity: 0; transform: scale(.97); } }
    @keyframes page-out { to { opacity: 0; transform: translateY(-8px); } }
    @keyframes page-in { from { opacity: 0; transform: translateY(14px); } }
    @keyframes out-left { to { opacity: 0; transform: translateX(-28px); } }
    @keyframes out-right { to { opacity: 0; transform: translateX(28px); } }
    @keyframes in-right { from { opacity: 0; transform: translateX(44px); } }
    @keyframes in-left { from { opacity: 0; transform: translateX(-44px); } }
    ::view-transition-group(mrr) { animation-duration: 420ms; animation-timing-function: cubic-bezier(.23, 1, .32, 1); }
    ::view-transition-old(mrr), ::view-transition-new(mrr) { height: 100%; object-fit: contain; }
    ::view-transition-old(kpis), ::view-transition-new(kpis) { animation-duration: 140ms; }
    /* the tab bar stays live during the change, so the pill can glide under the labels */
    ::view-transition-old(nav) { display: none; }
    ::view-transition-group(nav) { z-index: 1; }
    ::view-transition-new(nav) { animation: none; }
    /* the theme spreads out as a circle from the switch you pressed */
    .theme-flip::view-transition-old(root), .theme-flip::view-transition-new(root) { animation: none; mix-blend-mode: normal; }
    .theme-flip::view-transition-group(*) { animation: none; }
    .theme-flip *, .theme-flip main { view-transition-name: none !important; }
    @media (prefers-reduced-motion: reduce) {
    .chart .ln, .chart .ar, .chart .pulse { animation: none; }
    ::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; }
    }
    
    @media (max-width: 760px) {
    .app { grid-template-columns: 1fr; }
    .side { position: fixed; left: 0; right: 0; bottom: 0; z-index: 5; flex-direction: row; justify-content: space-around; padding: 8px 8px calc(8px + env(safe-area-inset-bottom));
      border-right: 0; border-top: 1px solid var(--line); background: color-mix(in srgb, var(--bg) 88%, transparent); backdrop-filter: blur(14px); }
    .brand { display: none; }
    .tab { flex-direction: column; justify-content: center; gap: 3px; height: 54px; padding: 0 10px; font-size: 11px; }
    main { padding: 18px 16px 96px; }
    .head h1 { font-size: 24px; }
    .kpis { grid-template-columns: 1fr 1fr; }
    .kpi:nth-child(3) { border-left: 0; }
    .kpi:nth-child(n+3) { border-top: 1px solid var(--line); }
    .kpi b { font-size: 28px; }
    .plans { grid-template-columns: 1fr; }
    .plan { border-left: 0; padding: 10px 0; border-top: 1px solid var(--line); }
    .plan:first-child { border-top: 0; }
    .row { grid-template-columns: 28px 1fr auto; }
    .row .hide { display: none; }
    .range button { padding: 6px 9px; }
    }
  2. HTML

    Поставьте в то место страницы, где должен быть эффект.

    <div class="app">
      <nav class="side" aria-label="Pages">
        <span class="pill-bg" aria-hidden="true"></span>
        <div class="brand"><i></i><span id="brand"></span></div>
        <button class="tab" data-page="overview" aria-selected="true"><svg viewBox="0 0 24 24"><rect x="3" y="3" width="7" height="9" rx="2"/><rect x="14" y="3" width="7" height="5" rx="2"/><rect x="14" y="12" width="7" height="9" rx="2"/><rect x="3" y="16" width="7" height="5" rx="2"/></svg>Overview</button>
        <button class="tab" data-page="revenue" aria-selected="false"><svg viewBox="0 0 24 24"><path d="M4 19V9M10 19V5M16 19v-7M22 19H2"/></svg>Revenue</button>
        <button class="tab" data-page="customers" aria-selected="false"><svg viewBox="0 0 24 24"><circle cx="9" cy="8" r="3.5"/><path d="M2.5 20c.8-3.6 3.4-5.5 6.5-5.5s5.7 1.9 6.5 5.5M16 4.8a3.5 3.5 0 0 1 0 6.4M18.5 14.8c1.6.8 2.6 2.5 3 5.2"/></svg>Customers</button>
        <button class="tab" data-page="settings" aria-selected="false"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg>Settings</button>
      </nav>
      <main id="page"></main>
    </div>
  3. JavaScript

    Вставьте перед закрывающим тегом </body>, внутри <script></script>.

    // SaaS Dashboard by @codinvisual · t.me/CodinVisual · free for your own site, don't resell this file
    const BRAND = 'Acme';
    // put your own numbers here, or fetch them and call render() again
    const DATA = {
    months: ['Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep'],
    revenue: [18.2, 19.6, 21.1, 20.4, 23.8, 25.9, 27.1, 29.6, 31.2, 33.9, 36.4, 39.8],
    plans: [['Starter', 1840, 9], ['Pro', 1215, 29], ['Team', 214, 99]],
    customers: [
      ['Maya Chen', 'maya@example.com', 'Team', 99, 'ok'], ['Lucas Moreau', 'lucas@example.com', 'Pro', 29, 'ok'],
      ['Aiko Tanaka', 'aiko@example.com', 'Pro', 29, 'late'], ['Omar Haddad', 'omar@example.com', 'Starter', 9, 'ok'],
      ['Sofia Rossi', 'sofia@example.com', 'Team', 99, 'ok'], ['Noah Becker', 'noah@example.com', 'Starter', 9, 'ok'],
      ['Priya Nair', 'priya@example.com', 'Pro', 29, 'ok'], ['Leo Novak', 'leo@example.com', 'Starter', 9, 'late'],
    ],
    };
    const TINTS = ['#3A4CF0', '#0FA36B', '#E5553A', '#8B5CF6', '#F59E0B', '#0EA5E9', '#EC4899', '#14B8A6'];
    const ORDER = ['overview', 'revenue', 'customers', 'settings'];
    const REDUCED = '(prefers-reduced-motion: reduce)';
    const EASE = 'cubic-bezier(.23, 1, .32, 1)';
    const root = document.documentElement;
    const page = document.getElementById('page');
    const state = { page: 'overview', chart: 'line', q: '' };
    document.getElementById('brand').textContent = BRAND;
    
    const money = n => '$' + n.toLocaleString('en-US');
    const initials = n => n.split(' ').map(w => w[0]).join('');
    const sum = a => a.reduce((s, x) => s + x, 0);
    const esc = v => String(v).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
    const still = () => matchMedia(REDUCED).matches;
    const mrr = () => DATA.revenue[DATA.revenue.length - 1];
    const UP = '<svg viewBox="0 0 12 12"><path d="M6 2l4 6H2z"/></svg>';
    
    // digits roll in like an odometer, each one on its own column, sized to its final digit
    const measure = document.createElement('canvas').getContext('2d');
    function odometer(el) {
    const text = el.dataset.text;
    el.textContent = '';
    const said = Object.assign(document.createElement('span'), { className: 'sr', textContent: text });
    const shown = document.createElement('span');
    shown.setAttribute('aria-hidden', 'true');
    el.append(said, shown);
    if (still()) { shown.textContent = text; return; }
    const cs = getComputedStyle(el);
    measure.font = `${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`;
    let n = 0;
    for (const ch of text) {
      if (!/\d/.test(ch)) { shown.append(ch); continue; }
      const col = document.createElement('span'), strip = document.createElement('span');
      col.className = 'odo';
      col.style.width = measure.measureText(ch).width + 'px';
      strip.textContent = '0\n1\n2\n3\n4\n5\n6\n7\n8\n9';
      col.append(strip); shown.append(col);
      strip.animate([{ transform: 'translateY(0)' }, { transform: `translateY(${-ch}em)` }],
        { duration: 700 + n * 60, easing: EASE, fill: 'both' });
      n++;
    }
    }
    
    // one series, one colour: a line with a light wash, or capped bars from the baseline
    function geometry() {
    const W = Math.max(300, Math.round(page.clientWidth - 40)), H = 200, L = 34, R = 44, T = 12, B = 24;
    const v = DATA.revenue, n = v.length, top = Math.ceil(Math.max(...v) * 1.1 / 10) * 10;
    const x = i => L + (i + .5) * (W - L - R) / n, y = val => T + (1 - val / top) * (H - T - B);
    return { W, H, L, R, T, B, v, n, top, x, y, bw: Math.min(24, (W - L - R) / n - 6) };
    }
    // a bar that can shrink into a dot sitting on the line, k = 0 dot, k = 1 bar
    function barD(g, i, k) {
    const w = 8 + (g.bw - 8) * k, x0 = g.x(i) - w / 2, y0 = g.y(g.v[i]), y1 = y0 + 8 + (g.y(0) - y0 - 8) * k;
    return `M${x0.toFixed(1)} ${y1.toFixed(1)}V${(y0 + 4).toFixed(1)}q0 -4 4 -4h${(w - 8).toFixed(1)}q4 0 4 4V${y1.toFixed(1)}Z`;
    }
    function chart(kind) {
    const g = geometry(), bars = kind === 'bars', last = [g.x(g.n - 1), g.y(g.v[g.n - 1])];
    const line = g.v.map((val, i) => (i ? 'L' : 'M') + g.x(i).toFixed(1) + ' ' + g.y(val).toFixed(1)).join(' ');
    const ticks = [0, g.top / 2, g.top].map(t => `<line class="grid" x1="${g.L}" x2="${g.W - g.R}" y1="${g.y(t)}" y2="${g.y(t)}"/><text class="lbl" x="${g.L - 8}" y="${g.y(t) + 3.5}" text-anchor="end">$${t}k</text>`).join('');
    const months = DATA.months.map((m, i) => i % 2 ? '' : `<text class="lbl" x="${g.x(i)}" y="${g.H - 6}" text-anchor="middle">${esc(m)}</text>`).join('');
    const table = `<table class="sr"><caption>Monthly revenue, thousands of dollars</caption>${DATA.months.map((m, i) => `<tr><th>${esc(m)}</th><td>${g.v[i]}</td></tr>`).join('')}</table>`;
    return `<div class="plot" data-kind="${kind}"><svg class="chart" viewBox="0 0 ${g.W} ${g.H}" role="img" tabindex="0" aria-label="Monthly revenue, use the arrow keys to read each month">
      ${ticks}<path class="ar" d="${line} L${g.x(g.n - 1)} ${g.y(0)} L${g.x(0)} ${g.y(0)} Z" style="opacity:${bars ? 0 : 1}"/>
      ${g.v.map((val, i) => `<path class="bar" d="${barD(g, i, bars ? 1 : 0)}" style="opacity:${bars ? 1 : 0}"/>`).join('')}
      <path class="ln" d="${line}" pathLength="1" style="${bars ? 'animation:none;stroke-dashoffset:1' : ''}"/>
      <rect class="veil" x="${g.W}" y="0" width="${g.W}" height="${g.y(0)}"/>
      <g class="tip-end" style="opacity:${bars ? 0 : 1}"><circle class="pulse" cx="${last[0]}" cy="${last[1]}" r="4"/><circle class="dot" cx="${last[0]}" cy="${last[1]}" r="4"/>
      <text class="end" x="${last[0] + 8}" y="${last[1] + 4}">$${g.v[g.n - 1]}k</text></g>
      ${months}<line class="hair" x1="0" x2="0" y1="${g.T}" y2="${g.y(0)}"/></svg><div class="tip" aria-hidden="true"></div>${table}</div>`;
    }
    
    // line to bars: every bar grows out of the dot on its own point, the line wipes away;
    // bars to line: the bars sink back into their dots and the line draws through them
    function morph(plot, to) {
    const g = geometry(), svg = plot.querySelector('svg'), bars = [...svg.querySelectorAll('.bar')];
    const ln = svg.querySelector('.ln'), ar = svg.querySelector('.ar'), end = svg.querySelector('.tip-end');
    plot.dataset.kind = to;
    const fade = (el, a, b, delay = 0) => el.animate([{ opacity: a }, { opacity: b }], { duration: 260, delay, easing: EASE, fill: 'both' });
    bars.forEach((b, i) => {
      const [k0, k1] = to === 'bars' ? [0, 1] : [1, 0];
      const run = b.animate([{ d: `path("${barD(g, i, k0)}")`, opacity: to === 'bars' ? 1 : 1 }, { d: `path("${barD(g, i, k1)}")`, opacity: 1 }],
        { duration: 480, delay: (to === 'bars' ? 120 : 0) + i * 28, easing: EASE, fill: 'both' });
      run.onfinish = () => { b.setAttribute('d', barD(g, i, k1)); b.style.opacity = to === 'bars' ? 1 : 0; run.cancel(); };
    });
    ln.style.animation = 'none';
    ln.animate([{ strokeDashoffset: to === 'bars' ? 0 : 1 }, { strokeDashoffset: to === 'bars' ? 1 : 0 }],
      { duration: to === 'bars' ? 360 : 620, delay: to === 'bars' ? 0 : 380, easing: EASE, fill: 'both' });
    fade(ar, to === 'bars' ? 1 : 0, to === 'bars' ? 0 : 1, to === 'bars' ? 0 : 600);
    fade(end, to === 'bars' ? 1 : 0, to === 'bars' ? 0 : 1, to === 'bars' ? 0 : 700);
    }
    
    // the crosshair snaps to the nearest month, the big number follows the finger,
    // and everything right of the finger dims until it lets go
    function hover(plot, i) {
    const svg = plot.querySelector('svg'), tip = plot.querySelector('.tip'), hair = svg.querySelector('.hair'), veil = svg.querySelector('.veil');
    const g = geometry(), hero = page.querySelector('.hero'), note = page.querySelector('.heroline small');
    svg.querySelectorAll('.bar').forEach((b, k) => b.classList.toggle('lift', k === i));
    if (i < 0) {
      tip.style.opacity = 0; hair.style.opacity = 0; veil.style.opacity = 0;
      if (hero) { hero.dataset.text = '$' + mrr() + 'k'; hero.lastChild.textContent = hero.dataset.text; note.textContent = 'MRR, September'; }
      return;
    }
    const vb = svg.viewBox.baseVal, k = svg.clientWidth / vb.width, px = g.x(i), py = g.y(g.v[i]);
    const line = plot.dataset.kind !== 'bars';
    hair.setAttribute('x1', px); hair.setAttribute('x2', px); hair.style.opacity = line ? .5 : 0;
    veil.setAttribute('x', px + 2); veil.style.opacity = line ? .55 : 0;
    tip.replaceChildren(Object.assign(document.createElement('b'), { textContent: '$' + g.v[i] + 'k' }),
      Object.assign(document.createElement('span'), { textContent: DATA.months[i] + ' revenue' }));
    const flip = px * k > svg.clientWidth - 90;
    tip.style.transform = flip ? 'translate(-108%, -110%)' : 'translate(-50%, -110%)';
    tip.style.left = px * k + 'px'; tip.style.top = py * k + 'px'; tip.style.opacity = 1;
    if (hero) { hero.lastChild.textContent = '$' + g.v[i] + 'k'; note.textContent = 'MRR, ' + DATA.months[i]; }
    }
    
    const PAGES = {
    overview: () => {
      const subs = sum(DATA.plans.map(p => p[1]));
      return `<div class="head"><div><h1>Overview</h1><p>September, all plans</p></div>${themeButton()}</div>
      <div class="kpis">
        <button class="kpi" data-go="revenue"><span>MRR</span><b data-text="$${mrr()}k" style="view-transition-name:mrr"></b><em class="delta up">${UP}9.3% vs Aug</em></button>
        <div class="kpi"><span>Subscribers</span><b data-text="${subs.toLocaleString('en-US')}"></b><em class="delta up">${UP}214 vs Aug</em></div>
        <div class="kpi"><span>Churn</span><b data-text="2.1%"></b><em class="delta down">${UP}0.3 pts vs Aug</em></div>
        <div class="kpi"><span>ARPU</span><b data-text="$${(mrr() * 1000 / subs).toFixed(2)}"></b><em class="delta up">${UP}$0.41 vs Aug</em></div>
      </div>
      <div class="section"><h2>Revenue, last 12 months</h2>${chart('line')}</div>
      <div class="section"><h2>Latest payments</h2>${DATA.customers.slice(0, 4).map((c, i) => `
        <div class="pay"><div class="av" style="background:${TINTS[i]}">${initials(c[0])}</div><div>${esc(c[0])}<small>${esc(c[2])} plan</small></div>
        <span class="pill ${c[4]}">${c[4] === 'ok' ? 'Paid' : 'Late'}</span><span class="amt">${money(c[3])}</span></div>`).join('')}</div>`;
    },
    revenue: () => `<div class="head"><div><h1>Revenue</h1><p>Monthly recurring revenue</p></div>
        <div class="tools"><div class="range" role="group" aria-label="Chart type"><button data-chart="line" aria-pressed="${state.chart === 'line'}">Line</button><button data-chart="bars" aria-pressed="${state.chart === 'bars'}">Bars</button></div>${themeButton()}</div></div>
      <div class="heroline"><b class="hero" data-text="$${mrr()}k"></b><small>MRR, September</small></div>
      <div class="section">${chart(state.chart)}</div>
      <div class="section"><h2>By plan</h2><div class="plans">${DATA.plans.map(p => `
        <div class="plan"><span>${esc(p[0])} · ${money(p[2])}/mo</span><b data-text="${money(p[1] * p[2])}"></b>
        <div class="meter"><i style="width:${Math.round(p[1] * p[2] / sum(DATA.plans.map(q => q[1] * q[2])) * 100)}%"></i></div></div>`).join('')}</div></div>`,
    customers: () => `<div class="head"><div><h1>Customers</h1><p>${DATA.customers.length} most recent</p></div>${themeButton()}</div>
      <input class="search" type="search" placeholder="Search by name or plan" value="${esc(state.q)}" aria-label="Search customers">
      <div class="section" id="list">${rows()}</div>`,
    settings: () => `<div class="head"><div><h1>Settings</h1><p>Workspace and appearance</p></div></div>
      <div class="section">
        <div class="set"><div>Dark theme<small>Easier on the eyes at night</small></div><button class="switch" id="theme" role="switch" aria-checked="${root.dataset.theme === 'dark'}" aria-label="Dark theme"></button></div>
        <div class="set"><div>Weekly report<small>A summary every Monday morning</small></div><button class="switch" role="switch" aria-checked="true" aria-label="Weekly report"></button></div>
        <div class="set"><div>Payment alerts<small>When a card fails or a plan changes</small></div><button class="switch" role="switch" aria-checked="false" aria-label="Payment alerts"></button></div>
      </div>`,
    };
    
    function themeButton() {
    const dark = root.dataset.theme === 'dark';
    return `<button class="icon" id="themeBtn" aria-label="${dark ? 'Light' : 'Dark'} theme"><svg viewBox="0 0 24 24">${dark
      ? '<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/>'
      : '<path d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z"/>'}</svg></button>`;
    }
    
    function rows() {
    const q = state.q.trim().toLowerCase();
    const list = DATA.customers.map((c, i) => [c, i]).filter(([c]) => !q || (c[0] + ' ' + c[2]).toLowerCase().includes(q));
    if (!list.length) return '<div class="empty">No customers match that search</div>';
    return list.map(([c, i]) => `<div class="row" style="view-transition-name:c${i}"><div class="av" style="background:${TINTS[i % TINTS.length]}">${initials(c[0])}</div>
      <div class="who">${esc(c[0])}<small>${esc(c[1])}</small></div><span class="hide">${esc(c[2])}</span><span class="pill ${c[4]} hide">${c[4] === 'ok' ? 'Active' : 'Past due'}</span><span class="num">${money(c[3])}</span></div>`).join('');
    }
    
    // the letters you typed light up in every name that matches
    function mark() {
    if (!window.CSS || !CSS.highlights) return;
    const q = state.q.trim().toLowerCase(), ranges = [];
    if (q) for (const el of page.querySelectorAll('.row .who')) {
      const node = el.firstChild, at = node.textContent.toLowerCase().indexOf(q);
      if (at < 0) continue;
      const r = new Range(); r.setStart(node, at); r.setEnd(node, at + q.length); ranges.push(r);
    }
    CSS.highlights.set('match', new Highlight(...ranges));
    }
    
    // one line does the animation: the browser morphs the old page into the new one
    function go(update, extra, types = []) {
    if (!document.startViewTransition || still()) return update();
    if (extra) root.classList.add(extra);
    let vt;
    try {
      vt = document.startViewTransition({ update, types });
    } catch {
      vt = document.startViewTransition(update);
    }
    if (extra) vt.finished.finally(() => root.classList.remove(extra));
    return vt;
    }
    
    function switchTo(name) {
    if (name === state.page) return;
    const from = ORDER.indexOf(state.page);
    const ahead = ORDER.indexOf(name) > from;
    go(() => {
      state.page = name;
      render();
    }, null, [ahead ? 'fwd' : 'back']);
    }
    
    function render() {
    page.innerHTML = PAGES[state.page]();
    page.querySelectorAll('[data-text]').forEach(odometer);
    document.querySelectorAll('.tab').forEach(t => t.setAttribute('aria-selected', t.dataset.page === state.page));
    placePill(true);
    mark();
    }
    
    // the light pill behind the current tab glides to the next one, from where it was
    function placePill(glide) {
    const t = document.querySelector('.tab[aria-selected="true"]'), pill = document.querySelector('.pill-bg');
    const from = pill.getBoundingClientRect();
    pill.style.cssText = `left:${t.offsetLeft}px;top:${t.offsetTop}px;width:${t.offsetWidth}px;height:${t.offsetHeight}px`;
    const to = pill.getBoundingClientRect();
    if (!glide || !from.width || still()) return;
    const dx = from.left - to.left, dy = from.top - to.top;
    if (!dx && !dy) return;
    pill.animate([{ transform: `translate(${dx}px, ${dy}px) scale(${from.width / to.width}, ${from.height / to.height})` }, { transform: 'none' }],
      { duration: 360, easing: EASE });
    }
    addEventListener('resize', () => placePill(false));
    
    for (const tab of document.querySelectorAll('.tab')) {
    tab.addEventListener('click', () => switchTo(tab.dataset.page));
    }
    page.addEventListener('click', e => {
    const card = e.target.closest('[data-go]');
    if (card) { switchTo(card.dataset.go); return; }
    const b = e.target.closest('[data-chart]');
    if (b && b.dataset.chart !== state.chart) {
      state.chart = b.dataset.chart;
      page.querySelectorAll('[data-chart]').forEach(x => x.setAttribute('aria-pressed', x === b));
      if (still()) render(); else morph(page.querySelector('.plot'), state.chart);
      return;
    }
    const icon = e.target.closest('#themeBtn');
    if (icon) { flipTheme(e.clientX, e.clientY); return; }
    const s = e.target.closest('.switch');
    if (!s) return;
    if (s.id === 'theme') flipTheme(e.clientX, e.clientY);
    else s.setAttribute('aria-checked', s.getAttribute('aria-checked') !== 'true');
    });
    page.addEventListener('pointermove', e => {
    const plot = e.target.closest('.plot');
    if (!plot) return;
    const svg = plot.querySelector('svg'), r = svg.getBoundingClientRect(), g = geometry();
    const fx = (e.clientX - r.left) / r.width * g.W;
    hover(plot, Math.max(0, Math.min(g.n - 1, Math.floor((fx - g.L) / ((g.W - g.L - g.R) / g.n)))));
    });
    page.addEventListener('pointerout', e => { const plot = e.target.closest('.plot'); if (plot && !plot.contains(e.relatedTarget)) hover(plot, -1); });
    page.addEventListener('keydown', e => {
    const plot = e.target.closest('.plot');
    if (!plot || !/Arrow(Left|Right)/.test(e.key)) return;
    e.preventDefault();
    plot.dataset.at = Math.max(0, Math.min(DATA.revenue.length - 1, (+plot.dataset.at || DATA.revenue.length) + (e.key === 'ArrowLeft' ? -1 : 1)));
    hover(plot, +plot.dataset.at);
    });
    page.addEventListener('focusout', e => { const plot = e.target.closest('.plot'); if (plot) hover(plot, -1); });
    page.addEventListener('input', e => {
    if (!e.target.matches('.search')) return;
    state.q = e.target.value;
    go(() => { document.getElementById('list').innerHTML = rows(); mark(); }, null, ['filter']);
    });
    
    // the new theme grows out of whatever you pressed, as a circle
    function flipTheme(x, y) {
    const dark = root.dataset.theme !== 'dark';
    const vt = go(() => { root.dataset.theme = dark ? 'dark' : 'light'; render(); }, 'theme-flip');
    if (!vt) return;
    const r = Math.hypot(Math.max(x, innerWidth - x), Math.max(y, innerHeight - y));
    const spread = [`circle(0 at ${x}px ${y}px)`, `circle(${r}px at ${x}px ${y}px)`];
    vt.ready.then(() => root.animate({ clipPath: spread },
      { duration: 520, easing: 'cubic-bezier(.77, 0, .175, 1)', pseudoElement: '::view-transition-new(root)' }));
    }
    
    // to load real numbers: fetch your JSON, copy it into DATA and call render()
    render();

Подключение к серверу

Найдите в конце скрипта to load real numbers. Загрузите там свой JSON, скопируйте в DATA и вызовите render(), и каждая страница перерисуется из DATA.

Полезно знать

Tilda, Webflow, WordPress

Нажмите «Скопировать весь код» вверху и вставьте его в один HTML-блок.

Tilda

Добавить блок, Другое, T123 HTML-код. Вставьте и сохраните. Проверяйте на опубликованной странице, в редакторе скрипты не запускаются.

Webflow

Панель Add, Embed. Вставьте и нажмите Save & Close. Свой код работает на опубликованном сайте.

WordPress

Добавить блок, Произвольный HTML. Вставьте и нажмите «Обновить».

Другие эффекты

Все
Скопировано