작은 추세 그래프를 칸 안에 넣기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.
코드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)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<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>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));// 예제 틀이 알려 주는 페이지 언어(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.' });
},
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>작은 추세 그래프를 칸 안에 넣기</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="next">새 값 더하기</button>
<button type="button" id="reset">처음 값으로</button>
</div>
<div id="grid" style="height: 280px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 예제 틀이 알려 주는 페이지 언어(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: [] },
];
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;
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.',
});
}
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.' });
},
};
options.ariaLabel = "작은 추세 그래프를 칸 안에 넣기";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('next').addEventListener('click', () => actions.next(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.next(api)}
>새 값 더하기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.reset(api)}
>처음 값으로</button>
</div>
<Grid style={{ height: 280 }} ref={gridRef} options={options} />
</>
);
}import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/react';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
last: number;
trend: number[];
}
// 칸 안의 내용은 기본으로 세로 가운데가 아니에요. .mxg-cell-center 상자에 넣으면 가운데에 와요.
const centered = (el: HTMLElement): HTMLElement => {
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 = (): CellRendererAdapter<Row> => {
let svg: SVGSVGElement;
let line: SVGPathElement;
let dot: SVGCircleElement;
let empty: HTMLSpanElement;
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: unknown = ctx.row.trend;
const points = Array.isArray(raw)
? raw.filter((n): n is number => 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: Row[] = [
{
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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let tick = 0;
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => {
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: GridApi<Row>) => {
tick = 0;
api.updateRows(base.map((row) => ({ ...row, trend: [...row.trend] })));
say({ ko: '처음 값으로 되돌렸어요.', en: 'Back to the first values.' });
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button type="button" :disabled="!api" @click="api && actions.next(api)">새 값 더하기</button>
<button type="button" :disabled="!api" @click="api && actions.reset(api)">처음 값으로</button>
</div>
<Grid style="height: 280px" :options="options" @ready="onReady" />
</template>import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/vue';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
last: number;
trend: number[];
}
// 칸 안의 내용은 기본으로 세로 가운데가 아니에요. .mxg-cell-center 상자에 넣으면 가운데에 와요.
const centered = (el: HTMLElement): HTMLElement => {
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 = (): CellRendererAdapter<Row> => {
let svg: SVGSVGElement;
let line: SVGPathElement;
let dot: SVGCircleElement;
let empty: HTMLSpanElement;
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: unknown = ctx.row.trend;
const points = Array.isArray(raw)
? raw.filter((n): n is number => 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: Row[] = [
{
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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let tick = 0;
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => {
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: GridApi<Row>) => {
tick = 0;
api.updateRows(base.map((row) => ({ ...row, trend: [...row.trend] })));
say({ ko: '처음 값으로 되돌렸어요.', en: 'Back to the first values.' });
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.next(api)"
>새 값 더하기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.reset(api)"
>처음 값으로</button>
</div>
<mx-grid style="height: 280px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/angular';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
last: number;
trend: number[];
}
// 칸 안의 내용은 기본으로 세로 가운데가 아니에요. .mxg-cell-center 상자에 넣으면 가운데에 와요.
const centered = (el: HTMLElement): HTMLElement => {
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 = (): CellRendererAdapter<Row> => {
let svg: SVGSVGElement;
let line: SVGPathElement;
let dot: SVGCircleElement;
let empty: HTMLSpanElement;
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: unknown = ctx.row.trend;
const points = Array.isArray(raw)
? raw.filter((n): n is number => 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: Row[] = [
{
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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let tick = 0;
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => {
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: GridApi<Row>) => {
tick = 0;
api.updateRows(base.map((row) => ({ ...row, trend: [...row.trend] })));
say({ ko: '처음 값으로 되돌렸어요.', en: 'Back to the first values.' });
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<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>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));// 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.');
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>A tiny trend chart inside a cell</title>
</head>
<body>
<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>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 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: [] },
];
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;
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.');
}
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.');
},
};
options.ariaLabel = "A tiny trend chart inside a cell";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('next').addEventListener('click', () => actions.next(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.next(api)}
>Add a new value</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.reset(api)}
>Back to start</button>
</div>
<Grid style={{ height: 280 }} ref={gridRef} options={options} />
</>
);
}import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
last: number;
trend: number[];
}
// Cell content is not vertically centered by default. Putting it in a .mxg-cell-center box centers it.
const centered = (el: HTMLElement): HTMLElement => {
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 = (): CellRendererAdapter<Row> => {
let svg: SVGSVGElement;
let line: SVGPathElement;
let dot: SVGCircleElement;
let empty: HTMLSpanElement;
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: unknown = ctx.row.trend;
const points = Array.isArray(raw)
? raw.filter((n): n is number => 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: Row[] = [
{
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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let tick = 0;
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => {
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: GridApi<Row>) => {
tick = 0;
api.updateRows(base.map((row) => ({ ...row, trend: [...row.trend] })));
say('Back to the first values.');
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button type="button" :disabled="!api" @click="api && actions.next(api)">Add a new value</button>
<button type="button" :disabled="!api" @click="api && actions.reset(api)">Back to start</button>
</div>
<Grid style="height: 280px" :options="options" @ready="onReady" />
</template>import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
last: number;
trend: number[];
}
// Cell content is not vertically centered by default. Putting it in a .mxg-cell-center box centers it.
const centered = (el: HTMLElement): HTMLElement => {
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 = (): CellRendererAdapter<Row> => {
let svg: SVGSVGElement;
let line: SVGPathElement;
let dot: SVGCircleElement;
let empty: HTMLSpanElement;
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: unknown = ctx.row.trend;
const points = Array.isArray(raw)
? raw.filter((n): n is number => 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: Row[] = [
{
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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let tick = 0;
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => {
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: GridApi<Row>) => {
tick = 0;
api.updateRows(base.map((row) => ({ ...row, trend: [...row.trend] })));
say('Back to the first values.');
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.next(api)"
>Add a new value</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.reset(api)"
>Back to start</button>
</div>
<mx-grid style="height: 280px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
last: number;
trend: number[];
}
// Cell content is not vertically centered by default. Putting it in a .mxg-cell-center box centers it.
const centered = (el: HTMLElement): HTMLElement => {
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 = (): CellRendererAdapter<Row> => {
let svg: SVGSVGElement;
let line: SVGPathElement;
let dot: SVGCircleElement;
let empty: HTMLSpanElement;
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: unknown = ctx.row.trend;
const points = Array.isArray(raw)
? raw.filter((n): n is number => 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: Row[] = [
{
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: GridOptions<Row> = {
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: (message: LogText) => void = () => {};
let tick = 0;
export function setup(_api: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => {
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: GridApi<Row>) => {
tick = 0;
api.updateRows(base.map((row) => ({ ...row, trend: [...row.trend] })));
say('Back to the first values.');
},
};