본문으로 건너뛰기Skip to content
예제 첫화면Examples home

작은 추세 그래프를 칸 안에 넣기A tiny trend chart inside a cell

숫자 목록을 칸 안의 작은 꺾은선 그래프로 보여 줘요. 처음보다 오르면 초록, 내리면 빨강이고, 새 값이 들어오면 바로 다시 그려요.Show a list of numbers as a small line chart in the cell. Green when it rose from the start, red when it fell; it redraws when new values arrive.

활용Intermediate
직접 써 보기Live preview작은 추세 그래프를 칸 안에 넣기A tiny trend chart inside a cell

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="next">새 값 더하기</button>
    <button type="button" id="reset">처음 값으로</button>
  </div>
  <div id="grid" style="height: 280px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('next').addEventListener('click', () => actions.next(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
example.js
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
// 칸 안의 내용은 기본으로 세로 가운데가 아니에요. .mxg-cell-center 상자에 넣으면 가운데에 와요.
const centered = (el) => {
  const box = document.createElement('div');
  box.className = 'mxg-cell-center';
  el.append(box);
  return box;
};
const NS = 'http://www.w3.org/2000/svg';
const W = 100;
const H = 22;
// 작은 꺾은선 그래프를 SVG 선 하나로 그려요. 요소는 처음에 한 번만 만들고, update()에서는 선의 좌표와 끝점 색만 바꿔서
// 스크롤해도 가벼워요. 처음보다 끝이 높으면 초록, 낮으면 빨강이에요.
const sparkline = () => {
  let svg;
  let line;
  let dot;
  let empty;
  return {
    mount(el, ctx) {
      svg = document.createElementNS(NS, 'svg');
      svg.setAttribute('viewBox', `0 0 ${W} ${H}`);
      svg.setAttribute('width', String(W));
      svg.setAttribute('height', String(H));
      svg.setAttribute('role', 'img');
      line = document.createElementNS(NS, 'path');
      line.setAttribute('fill', 'none');
      line.setAttribute('stroke-width', '1.5');
      dot = document.createElementNS(NS, 'circle');
      svg.append(line, dot);
      empty = document.createElement('span');
      empty.textContent = '—';
      empty.style.color = 'var(--mxg-fg-muted)';
      centered(el).append(svg, empty);
      this.update(ctx);
    },
    update(ctx) {
      const raw = ctx.row.trend;
      const points = Array.isArray(raw)
        ? raw.filter((n) => typeof n === 'number')
        : [];
      if (points.length < 2) {
        line.setAttribute('d', '');
        dot.setAttribute('r', '0');
        svg.setAttribute('aria-label', L('추세 자료 없음', 'No trend data'));
        svg.style.display = 'none';
        empty.style.display = '';
        return;
      }
      svg.style.display = '';
      empty.style.display = 'none';
      const min = Math.min(...points);
      const span = Math.max(...points) - min || 1;
      const coords = points.map((p, i) => ({
        x: (i / (points.length - 1)) * (W - 6) + 3,
        y: H - 3 - ((p - min) / span) * (H - 6),
      }));
      line.setAttribute('d', coords.map((c, i) => `${i === 0 ? 'M' : 'L'}${c.x.toFixed(1)} ${c.y.toFixed(1)}`).join(' '));
      const last = points[points.length - 1] ?? 0;
      const up = last >= (points[0] ?? 0);
      const color = up ? '#16a34a' : '#e5484d';
      line.setAttribute('stroke', color);
      const end = coords[coords.length - 1] ?? { x: 0, y: 0 };
      dot.setAttribute('fill', color);
      dot.setAttribute('r', '2.5');
      dot.setAttribute('cx', String(end.x));
      dot.setAttribute('cy', String(end.y));
      svg.setAttribute('aria-label', L(`${up ? '오르는' : '내리는'} 추세, 마지막 값 ${last.toLocaleString('ko-KR')}원`, `${up ? 'Rising' : 'Falling'} trend, last value ${last.toLocaleString('en-US')} KRW`));
    },
    destroy() { },
  };
};
// 그래프의 값은 모두 원(현재가와 같은 단위)이고, 현재가는 그래프의 마지막 값이에요.
const base = [
  {
    id: 1,
    name: '한빛전자',
    last: 74000,
    trend: [68000, 69000, 67000, 70000, 72000, 71000, 74000],
  },
  {
    id: 2,
    name: '파란에너지',
    last: 38000,
    trend: [44000, 43000, 45000, 41000, 40000, 39000, 38000],
  },
  {
    id: 3,
    name: '단풍제약',
    last: 125000,
    trend: [110000, 112000, 118000, 117000, 121000, 123000, 125000],
  },
  {
    id: 4,
    name: '바다물류',
    last: 20000,
    trend: [20000, 21000, 20000, 22000, 21000, 20000, 20000],
  },
  { id: 5, name: '새 상장 종목', last: 9800, trend: [] },
];
export const options = {
  columns: [
    { id: 'name', title: '종목', width: 130 },
    {
      id: 'last',
      title: '현재가(원)',
      kind: 'number',
      width: 110,
      align: 'end',
      formatValue: (v) => Number(v).toLocaleString('ko-KR'),
    },
    {
      id: 'trend',
      title: '최근 7일',
      width: 130,
      getValue: (row) => row.trend.length,
      cellRenderer: sparkline,
    },
  ],
  rows: base.map((row) => ({ ...row, trend: [...row.trend] })),
  rowKey: 'id',
  saveMode: 'none',
};
let say = () => { };
let tick = 0;
export function setup(_api, log) {
  say = log;
  tick = 0;
  log({
    ko: '처음보다 끝이 높으면 초록, 낮으면 빨강이에요. 자료가 없으면 아무것도 그리지 않아요.',
    en: 'Green if the end is higher than the start, red if lower. With no data, nothing is drawn.',
  });
}
export const actions = {
  next: (api) => {
    tick += 1;
    const changed = api.getRows().map((row) => {
      const prev = row.trend[row.trend.length - 1] ?? row.last;
      const nextValue = Math.max(1000, Math.round((prev + (((tick * 7 + row.id * 3) % 7) - 3) * 500) / 100) * 100);
      return { ...row, last: nextValue, trend: [...row.trend.slice(-6), nextValue] };
    });
    api.updateRows(changed);
    say({
      ko: `새 값을 하나씩 더했어요. (${tick}번째) 현재가도 그래프의 마지막 값으로 바뀌어요.`,
      en: `Added one new value. (#${tick}) The current price also becomes the last value of the graph.`,
    });
  },
  reset: (api) => {
    tick = 0;
    api.updateRows(base.map((row) => ({ ...row, trend: [...row.trend] })));
    say({ ko: '처음 값으로 되돌렸어요.', en: 'Back to the first values.' });
  },
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="next">Add a new value</button>
    <button type="button" id="reset">Back to start</button>
  </div>
  <div id="grid" style="height: 280px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('next').addEventListener('click', () => actions.next(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
example.js
// Cell content is not vertically centered by default. Putting it in a .mxg-cell-center box centers it.
const centered = (el) => {
  const box = document.createElement('div');
  box.className = 'mxg-cell-center';
  el.append(box);
  return box;
};
const NS = 'http://www.w3.org/2000/svg';
const W = 100;
const H = 22;
// Draws a small line chart as one SVG path. The elements are created once; update() only changes the path
// coordinates and the end dot color, so scrolling stays light. Green if the end is higher than the start, red if lower.
const sparkline = () => {
  let svg;
  let line;
  let dot;
  let empty;
  return {
    mount(el, ctx) {
      svg = document.createElementNS(NS, 'svg');
      svg.setAttribute('viewBox', `0 0 ${W} ${H}`);
      svg.setAttribute('width', String(W));
      svg.setAttribute('height', String(H));
      svg.setAttribute('role', 'img');
      line = document.createElementNS(NS, 'path');
      line.setAttribute('fill', 'none');
      line.setAttribute('stroke-width', '1.5');
      dot = document.createElementNS(NS, 'circle');
      svg.append(line, dot);
      empty = document.createElement('span');
      empty.textContent = '—';
      empty.style.color = 'var(--mxg-fg-muted)';
      centered(el).append(svg, empty);
      this.update(ctx);
    },
    update(ctx) {
      const raw = ctx.row.trend;
      const points = Array.isArray(raw)
        ? raw.filter((n) => typeof n === 'number')
        : [];
      if (points.length < 2) {
        line.setAttribute('d', '');
        dot.setAttribute('r', '0');
        svg.setAttribute('aria-label', 'No trend data');
        svg.style.display = 'none';
        empty.style.display = '';
        return;
      }
      svg.style.display = '';
      empty.style.display = 'none';
      const min = Math.min(...points);
      const span = Math.max(...points) - min || 1;
      const coords = points.map((p, i) => ({
        x: (i / (points.length - 1)) * (W - 6) + 3,
        y: H - 3 - ((p - min) / span) * (H - 6),
      }));
      line.setAttribute('d', coords.map((c, i) => `${i === 0 ? 'M' : 'L'}${c.x.toFixed(1)} ${c.y.toFixed(1)}`).join(' '));
      const last = points[points.length - 1] ?? 0;
      const up = last >= (points[0] ?? 0);
      const color = up ? '#16a34a' : '#e5484d';
      line.setAttribute('stroke', color);
      const end = coords[coords.length - 1] ?? { x: 0, y: 0 };
      dot.setAttribute('fill', color);
      dot.setAttribute('r', '2.5');
      dot.setAttribute('cx', String(end.x));
      dot.setAttribute('cy', String(end.y));
      svg.setAttribute('aria-label', `${up ? 'Rising' : 'Falling'} trend, last value $${last.toLocaleString('en-US')}`);
    },
    destroy() { },
  };
};
// All chart values are in dollars (the same unit as the price), and the price is the last value of the chart.
const base = [
  {
    id: 1,
    name: 'Bright Electronics',
    last: 74,
    trend: [68, 69, 67, 70, 72, 71, 74],
  },
  {
    id: 2,
    name: 'Blue Energy',
    last: 38,
    trend: [44, 43, 45, 41, 40, 39, 38],
  },
  {
    id: 3,
    name: 'Maple Pharma',
    last: 125,
    trend: [110, 112, 118, 117, 121, 123, 125],
  },
  {
    id: 4,
    name: 'Ocean Logistics',
    last: 20,
    trend: [20, 21, 20, 22, 21, 20, 20],
  },
  { id: 5, name: 'New Listing', last: 10, trend: [] },
];
export const options = {
  columns: [
    { id: 'name', title: 'Stock', width: 130 },
    {
      id: 'last',
      title: 'Price ($)',
      kind: 'number',
      width: 110,
      align: 'end',
      formatValue: (v) => Number(v).toLocaleString('en-US'),
    },
    {
      id: 'trend',
      title: 'Last 7 days',
      width: 130,
      getValue: (row) => row.trend.length,
      cellRenderer: sparkline,
    },
  ],
  rows: base.map((row) => ({ ...row, trend: [...row.trend] })),
  rowKey: 'id',
  saveMode: 'none',
};
let say = () => { };
let tick = 0;
export function setup(_api, log) {
  say = log;
  tick = 0;
  log('Green if the end is higher than the start, red if lower. With no data, nothing is drawn.');
}
export const actions = {
  next: (api) => {
    tick += 1;
    const changed = api.getRows().map((row) => {
      const prev = row.trend[row.trend.length - 1] ?? row.last;
      const nextValue = Math.max(1, Math.round(prev + (((tick * 7 + row.id * 3) % 7) - 3)));
      return { ...row, last: nextValue, trend: [...row.trend.slice(-6), nextValue] };
    });
    api.updateRows(changed);
    say(`Added one new value. (#${tick}) The current price also becomes the last value of the graph.`);
  },
  reset: (api) => {
    tick = 0;
    api.updateRows(base.map((row) => ({ ...row, trend: [...row.trend] })));
    say('Back to the first values.');
  },
};