ECharts 차트 종류 바꾸기Switch ECharts chart types
같은 ECharts 어댑터로 막대·가로 막대·꺾은선·영역·원을 바꿔 가며 그려요. ECharts는 단추를 누를 때만 jsDelivr CDN에서 불러와요.The same ECharts adapter draws column, bar, line, area and pie charts. ECharts loads from the jsDelivr CDN only when you press the button.
코드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="load">ECharts 불러오기</button>
<select aria-label="종류" id="chartType">
<option value="column" selected>막대</option>
<option value="bar">가로 막대</option>
<option value="line">꺾은선</option>
<option value="area">영역</option>
<option value="pie">원</option>
</select>
<button type="button" id="clear">지우기</button>
</div>
<div id="grid" style="height: 520px"></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('load').addEventListener('click', () => actions.load(api));
document.getElementById('chartType').addEventListener('change', (event) => actions.chartType(api, event.target.value));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));const rows = [
{ id: 1, region: '서울', q1: 120, q2: 150, q3: 180, q4: 210, note: '본사' },
{ id: 2, region: '부산', q1: 90, q2: 110, q3: 140, q4: 130, note: '항만' },
{ id: 3, region: '대구', q1: 70, q2: 85, q3: 95, q4: 120, note: '내륙' },
{ id: 4, region: '인천', q1: 100, q2: 130, q3: 125, q4: 160, note: '공항' },
{ id: 5, region: '광주', q1: 60, q2: 75, q3: 90, q4: 80, note: '호남' },
{ id: 6, region: '대전', q1: 80, q2: 95, q3: 110, q4: 140, note: '충청' },
{ id: 7, region: '울산', q1: 110, q2: 105, q3: 150, q4: 170, note: '공단' },
{ id: 8, region: '제주', q1: 50, q2: 65, q3: 70, q4: 95, note: '관광' },
];
const columns = [
{ id: 'region', title: '지역', width: 110 },
{ id: 'q1', title: '1분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q2', title: '2분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q3', title: '3분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q4', title: '4분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'note', title: '메모', editable: true, width: 110 },
];
const EC_VERSION = '6.1.0';
const EC_URL = `https://cdn.jsdelivr.net/npm/echarts@${EC_VERSION}/dist/echarts.min.js`;
const EC_SRI = 'sha384-C2iskrW/uPW46KzOjrvJIQo4YkV8lkD+QS0CrDN18IIPIpT/g2USu8bTP3nvmIAD';
const ec = () => window.echarts;
/** Reads the grid theme from its CSS variables (falls back to light/dark defaults). */
function themeOptions(el, dark, type) {
const css = getComputedStyle(el);
const read = (name, fallback) => css.getPropertyValue(name).trim() || fallback;
const bg = read('--mxg-bg', dark ? '#151a21' : '#ffffff');
const fg = read('--mxg-fg', dark ? '#e6e9ee' : '#1f2933');
const line = read('--mxg-border', dark ? '#323b47' : '#d9dee5');
const axis = {
axisLabel: { color: fg },
axisLine: { lineStyle: { color: line } },
axisTick: { lineStyle: { color: line } },
splitLine: { lineStyle: { color: line } },
};
return {
backgroundColor: bg,
textStyle: { color: fg },
title: { textStyle: { color: fg } },
legend: { textStyle: { color: fg } },
tooltip: { backgroundColor: bg, borderColor: line, textStyle: { color: fg } },
// a pie chart has no axes: do not add any
...(type === 'pie' ? {} : { xAxis: axis, yAxis: axis }),
};
}
/** Our ChartData -> ECharts series. Pie uses the first series; null values stay gaps. */
function seriesOf(type, data) {
if (type === 'pie') {
const first = data.series[0];
return [
{
type: 'pie',
name: first?.name ?? '',
radius: '65%',
data: data.categories.map((name, i) => ({ name, value: first?.values[i] ?? null })),
},
];
}
return data.series.map((s) => ({
type: type === 'column' || type === 'bar' ? 'bar' : 'line',
name: s.name,
data: s.values,
...(type === 'area' ? { areaStyle: {} } : {}),
}));
}
/** Axes: a horizontal bar chart swaps the category and value axis. Pie has none. */
function axesOf(type, data) {
if (type === 'pie')
return {};
const category = { type: 'category', data: data.categories };
const value = { type: 'value' };
return type === 'bar' ? { xAxis: value, yAxis: category } : { xAxis: category, yAxis: value };
}
function loadECharts(onReady, onError) {
if (ec() !== undefined)
return onReady();
let script = document.querySelector('script[data-echarts]');
if (script === null) {
script = document.createElement('script');
script.src = EC_URL;
script.integrity = EC_SRI; // the pinned file must match, or the browser refuses it
script.crossOrigin = 'anonymous';
script.dataset.echarts = '1';
document.head.append(script);
}
script.addEventListener('load', onReady, { once: true });
script.addEventListener('error', () => {
script?.remove(); // allow another try
onError();
}, { once: true });
}
const echartsAdapter = {
create(ctx) {
const echarts = ec();
if (echarts === undefined) {
ctx.container.textContent = 'ECharts를 아직 불러오지 않았어요.';
return { update() { }, destroy: () => ctx.container.replaceChildren() };
}
const opts = (ctx.options ?? {});
const dark = ctx.theme === 'dark';
const label = (d) => `${opts.title ?? '차트'}: ${d.categories.length} 분류, ${d.series.length} 계열`;
ctx.container.setAttribute('role', 'img');
ctx.container.setAttribute('aria-label', label(ctx.getData()));
const fmt = opts.valueFormat;
const base = (d) => ({
title: { text: opts.title ?? '' },
tooltip: {
trigger: ctx.type === 'pie' ? 'item' : 'axis',
...(fmt
? { valueFormatter: (v) => fmt.replace('{value}', Number(v).toLocaleString()) }
: {}),
},
legend: {},
series: seriesOf(ctx.type, d),
...axesOf(ctx.type, d),
});
const chart = echarts.init(ctx.container, null, { renderer: 'svg' });
chart.setOption(merge(base(ctx.getData()), themeOptions(ctx.container, dark, ctx.type), opts.echarts));
// Follow the grid theme when it changes later.
const retheme = () => chart.setOption(themeOptions(ctx.container, document.documentElement.dataset.mxgTheme === 'dark', ctx.type));
const watcher = new MutationObserver(retheme);
watcher.observe(document.documentElement, {
attributes: true,
subtree: true,
attributeFilter: ['data-mxg-theme'],
});
return {
update(d) {
ctx.container.setAttribute('aria-label', label(d));
chart.setOption({ ...axesOf(ctx.type, d), series: seriesOf(ctx.type, d) }, { replaceMerge: ['series'] });
},
destroy() {
watcher.disconnect();
chart.dispose();
ctx.container.removeAttribute('role');
ctx.container.removeAttribute('aria-label');
},
resize: () => chart.resize(),
};
},
};
/** Small deep merge for plain option objects. */
function merge(...parts) {
const out = {};
for (const part of parts) {
for (const [key, value] of Object.entries(part ?? {})) {
const prev = out[key];
const plain = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
out[key] = plain(prev) && plain(value) ? merge(prev, value) : value;
}
}
return out;
}
export const options = {
rowKey: 'id',
columns,
rows,
cellSelection: 'multiple',
selection: 'multiple',
ariaLabel: '지역별 분기 매출',
chartAdapter: echartsAdapter,
};
let host = null;
let notice = null;
let status = null;
let chart = null;
let loaded = false;
function ensureHost() {
if (host !== null)
return host;
const first = document.getElementById('grid');
notice = document.createElement('div');
notice.style.cssText =
'margin-top:10px;padding:8px 10px;border:1px solid var(--mxg-border, #d9dee5);border-radius:6px;font-size:13px;color:var(--mxg-fg, #1f2933)';
const text = document.createElement('p');
text.style.margin = '0 0 6px';
text.textContent =
'ECharts는 Apache Software Foundation의 별도 오픈소스 라이브러리예요(Apache License 2.0). 맥스그리드에는 들어 있지 않고, 아래 단추를 누르면 jsDelivr CDN(cdn.jsdelivr.net)에서 불러와요.';
status = document.createElement('p');
status.style.margin = '0';
status.setAttribute('role', 'status');
status.textContent =
'아직 불러오지 않았어요. 단추를 누르기 전에는 외부로 아무것도 요청하지 않아요.';
notice.append(text, status);
host = document.createElement('div');
host.id = 'chart-host';
host.style.cssText = 'height:260px;margin-top:10px';
if (first !== null)
first.after(notice, host);
else
document.body.append(notice, host);
return host;
}
function cleanup() {
chart?.destroy();
chart = null;
}
function showStatus(message) {
ensureHost();
if (status !== null)
status.textContent = message;
}
// 고른 칸이 없으면 앞의 네 행(지역~3분기)을 골라서 차트가 바로 나오게 해요.
function fromSelection(api, type) {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
return api.createChart(ensureHost(), { source: 'selection', type, options: chartOptions });
}
const chartOptions = { title: '지역별 분기 매출', valueFormat: '{value}' };
/** Nothing is requested from the network until this runs (the button next to the notice). */
function load(log, then) {
ensureHost();
if (loaded || window.echarts !== undefined) {
loaded = true;
showStatus('ECharts를 불러왔어요.');
then?.();
return;
}
showStatus('ECharts를 불러오는 중이에요…');
loadECharts(() => {
loaded = true;
showStatus('ECharts를 불러왔어요.');
log({ ko: 'ECharts 6.1.0을 불러왔어요.', en: 'ECharts 6.1.0 loaded.' });
then?.();
}, () => {
showStatus('ECharts를 불러오지 못했어요. 인터넷 연결이나 보안 정책(CSP)을 확인하고 다시 눌러 보세요.');
log({
ko: 'ECharts를 불러오지 못했어요(오프라인이거나 막혔어요).',
en: 'Could not load ECharts (offline or blocked).',
});
});
}
const needLoad = (log) => {
if (loaded)
return false;
showStatus('먼저 "ECharts 불러오기"를 눌러 주세요.');
log({ ko: '먼저 "ECharts 불러오기"를 눌러 주세요.', en: 'Press "Load ECharts" first.' });
return true;
};
let say = () => { };
let currentType = 'column';
function rebuild(api) {
if (needLoad(say))
return;
cleanup();
chart = fromSelection(api, currentType);
}
export function setup(api, log) {
say = log;
loaded = false;
currentType = 'column';
ensureHost();
const offCreated = api.on('chartCreated', ({ type }) => {
log({ ko: `차트를 만들었어요: ${type}`, en: `Chart created: ${type}` });
});
log({
ko: '먼저 "ECharts 불러오기"를 누르고, 종류를 바꿔 보세요.',
en: 'Press "Load ECharts", then switch the type.',
});
return () => {
offCreated();
cleanup();
notice?.remove();
host?.remove();
notice = null;
status = null;
host = null;
};
}
export const actions = {
load: (api) => load(say, () => rebuild(api)),
chartType: (api, value) => {
currentType = value ?? 'column';
rebuild(api);
},
clear: () => {
cleanup();
},
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>ECharts 차트 종류 바꾸기</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="load">ECharts 불러오기</button>
<select aria-label="종류" id="chartType">
<option value="column" selected>막대</option>
<option value="bar">가로 막대</option>
<option value="line">꺾은선</option>
<option value="area">영역</option>
<option value="pie">원</option>
</select>
<button type="button" id="clear">지우기</button>
</div>
<div id="grid" style="height: 520px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const rows = [
{ id: 1, region: '서울', q1: 120, q2: 150, q3: 180, q4: 210, note: '본사' },
{ id: 2, region: '부산', q1: 90, q2: 110, q3: 140, q4: 130, note: '항만' },
{ id: 3, region: '대구', q1: 70, q2: 85, q3: 95, q4: 120, note: '내륙' },
{ id: 4, region: '인천', q1: 100, q2: 130, q3: 125, q4: 160, note: '공항' },
{ id: 5, region: '광주', q1: 60, q2: 75, q3: 90, q4: 80, note: '호남' },
{ id: 6, region: '대전', q1: 80, q2: 95, q3: 110, q4: 140, note: '충청' },
{ id: 7, region: '울산', q1: 110, q2: 105, q3: 150, q4: 170, note: '공단' },
{ id: 8, region: '제주', q1: 50, q2: 65, q3: 70, q4: 95, note: '관광' },
];
const columns = [
{ id: 'region', title: '지역', width: 110 },
{ id: 'q1', title: '1분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q2', title: '2분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q3', title: '3분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q4', title: '4분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'note', title: '메모', editable: true, width: 110 },
];
const EC_VERSION = '6.1.0';
const EC_URL = `https://cdn.jsdelivr.net/npm/echarts@${EC_VERSION}/dist/echarts.min.js`;
const EC_SRI = 'sha384-C2iskrW/uPW46KzOjrvJIQo4YkV8lkD+QS0CrDN18IIPIpT/g2USu8bTP3nvmIAD';
const ec = () => window.echarts;
/** Reads the grid theme from its CSS variables (falls back to light/dark defaults). */
function themeOptions(el, dark, type) {
const css = getComputedStyle(el);
const read = (name, fallback) => css.getPropertyValue(name).trim() || fallback;
const bg = read('--mxg-bg', dark ? '#151a21' : '#ffffff');
const fg = read('--mxg-fg', dark ? '#e6e9ee' : '#1f2933');
const line = read('--mxg-border', dark ? '#323b47' : '#d9dee5');
const axis = {
axisLabel: { color: fg },
axisLine: { lineStyle: { color: line } },
axisTick: { lineStyle: { color: line } },
splitLine: { lineStyle: { color: line } },
};
return {
backgroundColor: bg,
textStyle: { color: fg },
title: { textStyle: { color: fg } },
legend: { textStyle: { color: fg } },
tooltip: { backgroundColor: bg, borderColor: line, textStyle: { color: fg } },
// a pie chart has no axes: do not add any
...(type === 'pie' ? {} : { xAxis: axis, yAxis: axis }),
};
}
/** Our ChartData -> ECharts series. Pie uses the first series; null values stay gaps. */
function seriesOf(type, data) {
if (type === 'pie') {
const first = data.series[0];
return [
{
type: 'pie',
name: first?.name ?? '',
radius: '65%',
data: data.categories.map((name, i) => ({ name, value: first?.values[i] ?? null })),
},
];
}
return data.series.map((s) => ({
type: type === 'column' || type === 'bar' ? 'bar' : 'line',
name: s.name,
data: s.values,
...(type === 'area' ? { areaStyle: {} } : {}),
}));
}
/** Axes: a horizontal bar chart swaps the category and value axis. Pie has none. */
function axesOf(type, data) {
if (type === 'pie')
return {};
const category = { type: 'category', data: data.categories };
const value = { type: 'value' };
return type === 'bar' ? { xAxis: value, yAxis: category } : { xAxis: category, yAxis: value };
}
function loadECharts(onReady, onError) {
if (ec() !== undefined)
return onReady();
let script = document.querySelector('script[data-echarts]');
if (script === null) {
script = document.createElement('script');
script.src = EC_URL;
script.integrity = EC_SRI; // the pinned file must match, or the browser refuses it
script.crossOrigin = 'anonymous';
script.dataset.echarts = '1';
document.head.append(script);
}
script.addEventListener('load', onReady, { once: true });
script.addEventListener('error', () => {
script?.remove(); // allow another try
onError();
}, { once: true });
}
const echartsAdapter = {
create(ctx) {
const echarts = ec();
if (echarts === undefined) {
ctx.container.textContent = 'ECharts를 아직 불러오지 않았어요.';
return { update() { }, destroy: () => ctx.container.replaceChildren() };
}
const opts = (ctx.options ?? {});
const dark = ctx.theme === 'dark';
const label = (d) => `${opts.title ?? '차트'}: ${d.categories.length} 분류, ${d.series.length} 계열`;
ctx.container.setAttribute('role', 'img');
ctx.container.setAttribute('aria-label', label(ctx.getData()));
const fmt = opts.valueFormat;
const base = (d) => ({
title: { text: opts.title ?? '' },
tooltip: {
trigger: ctx.type === 'pie' ? 'item' : 'axis',
...(fmt
? { valueFormatter: (v) => fmt.replace('{value}', Number(v).toLocaleString()) }
: {}),
},
legend: {},
series: seriesOf(ctx.type, d),
...axesOf(ctx.type, d),
});
const chart = echarts.init(ctx.container, null, { renderer: 'svg' });
chart.setOption(merge(base(ctx.getData()), themeOptions(ctx.container, dark, ctx.type), opts.echarts));
// Follow the grid theme when it changes later.
const retheme = () => chart.setOption(themeOptions(ctx.container, document.documentElement.dataset.mxgTheme === 'dark', ctx.type));
const watcher = new MutationObserver(retheme);
watcher.observe(document.documentElement, {
attributes: true,
subtree: true,
attributeFilter: ['data-mxg-theme'],
});
return {
update(d) {
ctx.container.setAttribute('aria-label', label(d));
chart.setOption({ ...axesOf(ctx.type, d), series: seriesOf(ctx.type, d) }, { replaceMerge: ['series'] });
},
destroy() {
watcher.disconnect();
chart.dispose();
ctx.container.removeAttribute('role');
ctx.container.removeAttribute('aria-label');
},
resize: () => chart.resize(),
};
},
};
/** Small deep merge for plain option objects. */
function merge(...parts) {
const out = {};
for (const part of parts) {
for (const [key, value] of Object.entries(part ?? {})) {
const prev = out[key];
const plain = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
out[key] = plain(prev) && plain(value) ? merge(prev, value) : value;
}
}
return out;
}
const options = {
rowKey: 'id',
columns,
rows,
cellSelection: 'multiple',
selection: 'multiple',
ariaLabel: '지역별 분기 매출',
chartAdapter: echartsAdapter,
};
let host = null;
let notice = null;
let status = null;
let chart = null;
let loaded = false;
function ensureHost() {
if (host !== null)
return host;
const first = document.getElementById('grid');
notice = document.createElement('div');
notice.style.cssText =
'margin-top:10px;padding:8px 10px;border:1px solid var(--mxg-border, #d9dee5);border-radius:6px;font-size:13px;color:var(--mxg-fg, #1f2933)';
const text = document.createElement('p');
text.style.margin = '0 0 6px';
text.textContent =
'ECharts는 Apache Software Foundation의 별도 오픈소스 라이브러리예요(Apache License 2.0). 맥스그리드에는 들어 있지 않고, 아래 단추를 누르면 jsDelivr CDN(cdn.jsdelivr.net)에서 불러와요.';
status = document.createElement('p');
status.style.margin = '0';
status.setAttribute('role', 'status');
status.textContent =
'아직 불러오지 않았어요. 단추를 누르기 전에는 외부로 아무것도 요청하지 않아요.';
notice.append(text, status);
host = document.createElement('div');
host.id = 'chart-host';
host.style.cssText = 'height:260px;margin-top:10px';
if (first !== null)
first.after(notice, host);
else
document.body.append(notice, host);
return host;
}
function cleanup() {
chart?.destroy();
chart = null;
}
function showStatus(message) {
ensureHost();
if (status !== null)
status.textContent = message;
}
// 고른 칸이 없으면 앞의 네 행(지역~3분기)을 골라서 차트가 바로 나오게 해요.
function fromSelection(api, type) {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
return api.createChart(ensureHost(), { source: 'selection', type, options: chartOptions });
}
const chartOptions = { title: '지역별 분기 매출', valueFormat: '{value}' };
/** Nothing is requested from the network until this runs (the button next to the notice). */
function load(log, then) {
ensureHost();
if (loaded || window.echarts !== undefined) {
loaded = true;
showStatus('ECharts를 불러왔어요.');
then?.();
return;
}
showStatus('ECharts를 불러오는 중이에요…');
loadECharts(() => {
loaded = true;
showStatus('ECharts를 불러왔어요.');
log({ ko: 'ECharts 6.1.0을 불러왔어요.', en: 'ECharts 6.1.0 loaded.' });
then?.();
}, () => {
showStatus('ECharts를 불러오지 못했어요. 인터넷 연결이나 보안 정책(CSP)을 확인하고 다시 눌러 보세요.');
log({
ko: 'ECharts를 불러오지 못했어요(오프라인이거나 막혔어요).',
en: 'Could not load ECharts (offline or blocked).',
});
});
}
const needLoad = (log) => {
if (loaded)
return false;
showStatus('먼저 "ECharts 불러오기"를 눌러 주세요.');
log({ ko: '먼저 "ECharts 불러오기"를 눌러 주세요.', en: 'Press "Load ECharts" first.' });
return true;
};
let say = () => { };
let currentType = 'column';
function rebuild(api) {
if (needLoad(say))
return;
cleanup();
chart = fromSelection(api, currentType);
}
function setup(api, log) {
say = log;
loaded = false;
currentType = 'column';
ensureHost();
const offCreated = api.on('chartCreated', ({ type }) => {
log({ ko: `차트를 만들었어요: ${type}`, en: `Chart created: ${type}` });
});
log({
ko: '먼저 "ECharts 불러오기"를 누르고, 종류를 바꿔 보세요.',
en: 'Press "Load ECharts", then switch the type.',
});
return () => {
offCreated();
cleanup();
notice?.remove();
host?.remove();
notice = null;
status = null;
host = null;
};
}
const actions = {
load: (api) => load(say, () => rebuild(api)),
chartType: (api, value) => {
currentType = value ?? 'column';
rebuild(api);
},
clear: () => {
cleanup();
},
};
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('load').addEventListener('click', () => actions.load(api));
document.getElementById('chartType').addEventListener('change', (event) => actions.chartType(api, event.target.value));
document.getElementById('clear').addEventListener('click', () => actions.clear(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.load(api)}
>ECharts 불러오기</button>
<select
aria-label="종류"
disabled={!api}
onChange={(event) => api && actions.chartType(api, event.target.value)}
>
<option value="column">막대</option>
<option value="bar">가로 막대</option>
<option value="line">꺾은선</option>
<option value="area">영역</option>
<option value="pie">원</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>지우기</button>
</div>
<Grid style={{ height: 520 }} ref={gridRef} options={options} />
</>
);
}import type {
ChartAdapter,
ChartData,
ChartType,
GridApi,
GridChart,
GridOptions,
} from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
region: string;
q1: number;
q2: number;
q3: number;
q4: number;
note: string;
}
const rows: Row[] = [
{ id: 1, region: '서울', q1: 120, q2: 150, q3: 180, q4: 210, note: '본사' },
{ id: 2, region: '부산', q1: 90, q2: 110, q3: 140, q4: 130, note: '항만' },
{ id: 3, region: '대구', q1: 70, q2: 85, q3: 95, q4: 120, note: '내륙' },
{ id: 4, region: '인천', q1: 100, q2: 130, q3: 125, q4: 160, note: '공항' },
{ id: 5, region: '광주', q1: 60, q2: 75, q3: 90, q4: 80, note: '호남' },
{ id: 6, region: '대전', q1: 80, q2: 95, q3: 110, q4: 140, note: '충청' },
{ id: 7, region: '울산', q1: 110, q2: 105, q3: 150, q4: 170, note: '공단' },
{ id: 8, region: '제주', q1: 50, q2: 65, q3: 70, q4: 95, note: '관광' },
];
const columns: NonNullable<GridOptions<Row>['columns']> = [
{ id: 'region', title: '지역', width: 110 },
{ id: 'q1', title: '1분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q2', title: '2분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q3', title: '3분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q4', title: '4분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'note', title: '메모', editable: true, width: 110 },
];
// ── ECharts adapter recipe ───────────────────────────────────────────────────
// MaxGrid ships no chart library. This adapter maps ChartContext -> ECharts and back.
type EcChart = {
setOption(option: object, opts?: { replaceMerge?: string[] }): void;
dispose(): void;
resize(): void;
};
type EcStatic = {
init(el: HTMLElement, theme?: null, opts?: { renderer: 'svg' | 'canvas' }): EcChart;
};
type EcOptions = { title?: string; valueFormat?: string; echarts?: object };
const EC_VERSION = '6.1.0';
const EC_URL = `https://cdn.jsdelivr.net/npm/echarts@${EC_VERSION}/dist/echarts.min.js`;
const EC_SRI = 'sha384-C2iskrW/uPW46KzOjrvJIQo4YkV8lkD+QS0CrDN18IIPIpT/g2USu8bTP3nvmIAD';
const ec = (): EcStatic | undefined => (window as unknown as { echarts?: EcStatic }).echarts;
/** Reads the grid theme from its CSS variables (falls back to light/dark defaults). */
function themeOptions(el: HTMLElement, dark: boolean, type: ChartType): object {
const css = getComputedStyle(el);
const read = (name: string, fallback: string): string =>
css.getPropertyValue(name).trim() || fallback;
const bg = read('--mxg-bg', dark ? '#151a21' : '#ffffff');
const fg = read('--mxg-fg', dark ? '#e6e9ee' : '#1f2933');
const line = read('--mxg-border', dark ? '#323b47' : '#d9dee5');
const axis = {
axisLabel: { color: fg },
axisLine: { lineStyle: { color: line } },
axisTick: { lineStyle: { color: line } },
splitLine: { lineStyle: { color: line } },
};
return {
backgroundColor: bg,
textStyle: { color: fg },
title: { textStyle: { color: fg } },
legend: { textStyle: { color: fg } },
tooltip: { backgroundColor: bg, borderColor: line, textStyle: { color: fg } },
// a pie chart has no axes: do not add any
...(type === 'pie' ? {} : { xAxis: axis, yAxis: axis }),
};
}
/** Our ChartData -> ECharts series. Pie uses the first series; null values stay gaps. */
function seriesOf(type: ChartType, data: ChartData): object[] {
if (type === 'pie') {
const first = data.series[0];
return [
{
type: 'pie',
name: first?.name ?? '',
radius: '65%',
data: data.categories.map((name, i) => ({ name, value: first?.values[i] ?? null })),
},
];
}
return data.series.map((s) => ({
type: type === 'column' || type === 'bar' ? 'bar' : 'line',
name: s.name,
data: s.values,
...(type === 'area' ? { areaStyle: {} } : {}),
}));
}
/** Axes: a horizontal bar chart swaps the category and value axis. Pie has none. */
function axesOf(type: ChartType, data: ChartData): object {
if (type === 'pie') return {};
const category = { type: 'category', data: data.categories };
const value = { type: 'value' };
return type === 'bar' ? { xAxis: value, yAxis: category } : { xAxis: category, yAxis: value };
}
function loadECharts(onReady: () => void, onError: () => void): void {
if (ec() !== undefined) return onReady();
let script = document.querySelector<HTMLScriptElement>('script[data-echarts]');
if (script === null) {
script = document.createElement('script');
script.src = EC_URL;
script.integrity = EC_SRI; // the pinned file must match, or the browser refuses it
script.crossOrigin = 'anonymous';
script.dataset.echarts = '1';
document.head.append(script);
}
script.addEventListener('load', onReady, { once: true });
script.addEventListener(
'error',
() => {
script?.remove(); // allow another try
onError();
},
{ once: true },
);
}
const echartsAdapter: ChartAdapter = {
create(ctx) {
const echarts = ec();
if (echarts === undefined) {
ctx.container.textContent = 'ECharts를 아직 불러오지 않았어요.';
return { update() {}, destroy: () => ctx.container.replaceChildren() };
}
const opts = (ctx.options ?? {}) as EcOptions;
const dark = ctx.theme === 'dark';
const label = (d: ChartData): string =>
`${opts.title ?? '차트'}: ${d.categories.length} 분류, ${d.series.length} 계열`;
ctx.container.setAttribute('role', 'img');
ctx.container.setAttribute('aria-label', label(ctx.getData()));
const fmt = opts.valueFormat;
const base = (d: ChartData): object => ({
title: { text: opts.title ?? '' },
tooltip: {
trigger: ctx.type === 'pie' ? 'item' : 'axis',
...(fmt
? { valueFormatter: (v: unknown) => fmt.replace('{value}', Number(v).toLocaleString()) }
: {}),
},
legend: {},
series: seriesOf(ctx.type, d),
...axesOf(ctx.type, d),
});
const chart = echarts.init(ctx.container, null, { renderer: 'svg' });
chart.setOption(
merge(base(ctx.getData()), themeOptions(ctx.container, dark, ctx.type), opts.echarts),
);
// Follow the grid theme when it changes later.
const retheme = (): void =>
chart.setOption(
themeOptions(ctx.container, document.documentElement.dataset.mxgTheme === 'dark', ctx.type),
);
const watcher = new MutationObserver(retheme);
watcher.observe(document.documentElement, {
attributes: true,
subtree: true,
attributeFilter: ['data-mxg-theme'],
});
return {
update(d) {
ctx.container.setAttribute('aria-label', label(d));
chart.setOption(
{ ...axesOf(ctx.type, d), series: seriesOf(ctx.type, d) },
{ replaceMerge: ['series'] },
);
},
destroy() {
watcher.disconnect();
chart.dispose();
ctx.container.removeAttribute('role');
ctx.container.removeAttribute('aria-label');
},
resize: () => chart.resize(),
};
},
};
/** Small deep merge for plain option objects. */
function merge(...parts: Array<object | undefined>): object {
const out: Record<string, unknown> = {};
for (const part of parts) {
for (const [key, value] of Object.entries(part ?? {})) {
const prev = out[key];
const plain = (v: unknown): v is object =>
typeof v === 'object' && v !== null && !Array.isArray(v);
out[key] = plain(prev) && plain(value) ? merge(prev, value) : value;
}
}
return out;
}
export const options: GridOptions<Row> = {
rowKey: 'id',
columns,
rows,
cellSelection: 'multiple',
selection: 'multiple',
ariaLabel: '지역별 분기 매출',
chartAdapter: echartsAdapter,
};
let host: HTMLElement | null = null;
let notice: HTMLElement | null = null;
let status: HTMLElement | null = null;
let chart: GridChart | null = null;
let loaded = false;
function ensureHost(): HTMLElement {
if (host !== null) return host;
const first = document.getElementById('grid');
notice = document.createElement('div');
notice.style.cssText =
'margin-top:10px;padding:8px 10px;border:1px solid var(--mxg-border, #d9dee5);border-radius:6px;font-size:13px;color:var(--mxg-fg, #1f2933)';
const text = document.createElement('p');
text.style.margin = '0 0 6px';
text.textContent =
'ECharts는 Apache Software Foundation의 별도 오픈소스 라이브러리예요(Apache License 2.0). 맥스그리드에는 들어 있지 않고, 아래 단추를 누르면 jsDelivr CDN(cdn.jsdelivr.net)에서 불러와요.';
status = document.createElement('p');
status.style.margin = '0';
status.setAttribute('role', 'status');
status.textContent =
'아직 불러오지 않았어요. 단추를 누르기 전에는 외부로 아무것도 요청하지 않아요.';
notice.append(text, status);
host = document.createElement('div');
host.id = 'chart-host';
host.style.cssText = 'height:260px;margin-top:10px';
if (first !== null) first.after(notice, host);
else document.body.append(notice, host);
return host;
}
function cleanup(): void {
chart?.destroy();
chart = null;
}
function showStatus(message: string): void {
ensureHost();
if (status !== null) status.textContent = message;
}
// 고른 칸이 없으면 앞의 네 행(지역~3분기)을 골라서 차트가 바로 나오게 해요.
function fromSelection(api: GridApi<Row>, type: ChartType): GridChart | null {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
return api.createChart(ensureHost(), { source: 'selection', type, options: chartOptions });
}
const chartOptions = { title: '지역별 분기 매출', valueFormat: '{value}' };
/** Nothing is requested from the network until this runs (the button next to the notice). */
function load(log: (message: LogText) => void, then?: () => void): void {
ensureHost();
if (loaded || (window as unknown as { echarts?: unknown }).echarts !== undefined) {
loaded = true;
showStatus('ECharts를 불러왔어요.');
then?.();
return;
}
showStatus('ECharts를 불러오는 중이에요…');
loadECharts(
() => {
loaded = true;
showStatus('ECharts를 불러왔어요.');
log({ ko: 'ECharts 6.1.0을 불러왔어요.', en: 'ECharts 6.1.0 loaded.' });
then?.();
},
() => {
showStatus(
'ECharts를 불러오지 못했어요. 인터넷 연결이나 보안 정책(CSP)을 확인하고 다시 눌러 보세요.',
);
log({
ko: 'ECharts를 불러오지 못했어요(오프라인이거나 막혔어요).',
en: 'Could not load ECharts (offline or blocked).',
});
},
);
}
const needLoad = (log: (message: LogText) => void): boolean => {
if (loaded) return false;
showStatus('먼저 "ECharts 불러오기"를 눌러 주세요.');
log({ ko: '먼저 "ECharts 불러오기"를 눌러 주세요.', en: 'Press "Load ECharts" first.' });
return true;
};
let say: (message: LogText) => void = () => {};
let currentType: ChartType = 'column';
function rebuild(api: GridApi<Row>): void {
if (needLoad(say)) return;
cleanup();
chart = fromSelection(api, currentType);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
loaded = false;
currentType = 'column';
ensureHost();
const offCreated = api.on('chartCreated', ({ type }) => {
log({ ko: `차트를 만들었어요: ${type}`, en: `Chart created: ${type}` });
});
log({
ko: '먼저 "ECharts 불러오기"를 누르고, 종류를 바꿔 보세요.',
en: 'Press "Load ECharts", then switch the type.',
});
return () => {
offCreated();
cleanup();
notice?.remove();
host?.remove();
notice = null;
status = null;
host = null;
};
}
export const actions = {
load: (api: GridApi<Row>) => load(say, () => rebuild(api)),
chartType: (api: GridApi<Row>, value?: string) => {
currentType = (value as ChartType | undefined) ?? 'column';
rebuild(api);
},
clear: () => {
cleanup();
},
};버튼을 누르면 이 예제의 코드가 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.load(api)">ECharts 불러오기</button>
<select
aria-label="종류"
:disabled="!api"
@change="api && actions.chartType(api, ($event.target as HTMLSelectElement).value)"
>
<option value="column" selected>막대</option>
<option value="bar">가로 막대</option>
<option value="line">꺾은선</option>
<option value="area">영역</option>
<option value="pie">원</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">지우기</button>
</div>
<Grid style="height: 520px" :options="options" @ready="onReady" />
</template>import type {
ChartAdapter,
ChartData,
ChartType,
GridApi,
GridChart,
GridOptions,
} from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
region: string;
q1: number;
q2: number;
q3: number;
q4: number;
note: string;
}
const rows: Row[] = [
{ id: 1, region: '서울', q1: 120, q2: 150, q3: 180, q4: 210, note: '본사' },
{ id: 2, region: '부산', q1: 90, q2: 110, q3: 140, q4: 130, note: '항만' },
{ id: 3, region: '대구', q1: 70, q2: 85, q3: 95, q4: 120, note: '내륙' },
{ id: 4, region: '인천', q1: 100, q2: 130, q3: 125, q4: 160, note: '공항' },
{ id: 5, region: '광주', q1: 60, q2: 75, q3: 90, q4: 80, note: '호남' },
{ id: 6, region: '대전', q1: 80, q2: 95, q3: 110, q4: 140, note: '충청' },
{ id: 7, region: '울산', q1: 110, q2: 105, q3: 150, q4: 170, note: '공단' },
{ id: 8, region: '제주', q1: 50, q2: 65, q3: 70, q4: 95, note: '관광' },
];
const columns: NonNullable<GridOptions<Row>['columns']> = [
{ id: 'region', title: '지역', width: 110 },
{ id: 'q1', title: '1분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q2', title: '2분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q3', title: '3분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q4', title: '4분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'note', title: '메모', editable: true, width: 110 },
];
// ── ECharts adapter recipe ───────────────────────────────────────────────────
// MaxGrid ships no chart library. This adapter maps ChartContext -> ECharts and back.
type EcChart = {
setOption(option: object, opts?: { replaceMerge?: string[] }): void;
dispose(): void;
resize(): void;
};
type EcStatic = {
init(el: HTMLElement, theme?: null, opts?: { renderer: 'svg' | 'canvas' }): EcChart;
};
type EcOptions = { title?: string; valueFormat?: string; echarts?: object };
const EC_VERSION = '6.1.0';
const EC_URL = `https://cdn.jsdelivr.net/npm/echarts@${EC_VERSION}/dist/echarts.min.js`;
const EC_SRI = 'sha384-C2iskrW/uPW46KzOjrvJIQo4YkV8lkD+QS0CrDN18IIPIpT/g2USu8bTP3nvmIAD';
const ec = (): EcStatic | undefined => (window as unknown as { echarts?: EcStatic }).echarts;
/** Reads the grid theme from its CSS variables (falls back to light/dark defaults). */
function themeOptions(el: HTMLElement, dark: boolean, type: ChartType): object {
const css = getComputedStyle(el);
const read = (name: string, fallback: string): string =>
css.getPropertyValue(name).trim() || fallback;
const bg = read('--mxg-bg', dark ? '#151a21' : '#ffffff');
const fg = read('--mxg-fg', dark ? '#e6e9ee' : '#1f2933');
const line = read('--mxg-border', dark ? '#323b47' : '#d9dee5');
const axis = {
axisLabel: { color: fg },
axisLine: { lineStyle: { color: line } },
axisTick: { lineStyle: { color: line } },
splitLine: { lineStyle: { color: line } },
};
return {
backgroundColor: bg,
textStyle: { color: fg },
title: { textStyle: { color: fg } },
legend: { textStyle: { color: fg } },
tooltip: { backgroundColor: bg, borderColor: line, textStyle: { color: fg } },
// a pie chart has no axes: do not add any
...(type === 'pie' ? {} : { xAxis: axis, yAxis: axis }),
};
}
/** Our ChartData -> ECharts series. Pie uses the first series; null values stay gaps. */
function seriesOf(type: ChartType, data: ChartData): object[] {
if (type === 'pie') {
const first = data.series[0];
return [
{
type: 'pie',
name: first?.name ?? '',
radius: '65%',
data: data.categories.map((name, i) => ({ name, value: first?.values[i] ?? null })),
},
];
}
return data.series.map((s) => ({
type: type === 'column' || type === 'bar' ? 'bar' : 'line',
name: s.name,
data: s.values,
...(type === 'area' ? { areaStyle: {} } : {}),
}));
}
/** Axes: a horizontal bar chart swaps the category and value axis. Pie has none. */
function axesOf(type: ChartType, data: ChartData): object {
if (type === 'pie') return {};
const category = { type: 'category', data: data.categories };
const value = { type: 'value' };
return type === 'bar' ? { xAxis: value, yAxis: category } : { xAxis: category, yAxis: value };
}
function loadECharts(onReady: () => void, onError: () => void): void {
if (ec() !== undefined) return onReady();
let script = document.querySelector<HTMLScriptElement>('script[data-echarts]');
if (script === null) {
script = document.createElement('script');
script.src = EC_URL;
script.integrity = EC_SRI; // the pinned file must match, or the browser refuses it
script.crossOrigin = 'anonymous';
script.dataset.echarts = '1';
document.head.append(script);
}
script.addEventListener('load', onReady, { once: true });
script.addEventListener(
'error',
() => {
script?.remove(); // allow another try
onError();
},
{ once: true },
);
}
const echartsAdapter: ChartAdapter = {
create(ctx) {
const echarts = ec();
if (echarts === undefined) {
ctx.container.textContent = 'ECharts를 아직 불러오지 않았어요.';
return { update() {}, destroy: () => ctx.container.replaceChildren() };
}
const opts = (ctx.options ?? {}) as EcOptions;
const dark = ctx.theme === 'dark';
const label = (d: ChartData): string =>
`${opts.title ?? '차트'}: ${d.categories.length} 분류, ${d.series.length} 계열`;
ctx.container.setAttribute('role', 'img');
ctx.container.setAttribute('aria-label', label(ctx.getData()));
const fmt = opts.valueFormat;
const base = (d: ChartData): object => ({
title: { text: opts.title ?? '' },
tooltip: {
trigger: ctx.type === 'pie' ? 'item' : 'axis',
...(fmt
? { valueFormatter: (v: unknown) => fmt.replace('{value}', Number(v).toLocaleString()) }
: {}),
},
legend: {},
series: seriesOf(ctx.type, d),
...axesOf(ctx.type, d),
});
const chart = echarts.init(ctx.container, null, { renderer: 'svg' });
chart.setOption(
merge(base(ctx.getData()), themeOptions(ctx.container, dark, ctx.type), opts.echarts),
);
// Follow the grid theme when it changes later.
const retheme = (): void =>
chart.setOption(
themeOptions(ctx.container, document.documentElement.dataset.mxgTheme === 'dark', ctx.type),
);
const watcher = new MutationObserver(retheme);
watcher.observe(document.documentElement, {
attributes: true,
subtree: true,
attributeFilter: ['data-mxg-theme'],
});
return {
update(d) {
ctx.container.setAttribute('aria-label', label(d));
chart.setOption(
{ ...axesOf(ctx.type, d), series: seriesOf(ctx.type, d) },
{ replaceMerge: ['series'] },
);
},
destroy() {
watcher.disconnect();
chart.dispose();
ctx.container.removeAttribute('role');
ctx.container.removeAttribute('aria-label');
},
resize: () => chart.resize(),
};
},
};
/** Small deep merge for plain option objects. */
function merge(...parts: Array<object | undefined>): object {
const out: Record<string, unknown> = {};
for (const part of parts) {
for (const [key, value] of Object.entries(part ?? {})) {
const prev = out[key];
const plain = (v: unknown): v is object =>
typeof v === 'object' && v !== null && !Array.isArray(v);
out[key] = plain(prev) && plain(value) ? merge(prev, value) : value;
}
}
return out;
}
export const options: GridOptions<Row> = {
rowKey: 'id',
columns,
rows,
cellSelection: 'multiple',
selection: 'multiple',
ariaLabel: '지역별 분기 매출',
chartAdapter: echartsAdapter,
};
let host: HTMLElement | null = null;
let notice: HTMLElement | null = null;
let status: HTMLElement | null = null;
let chart: GridChart | null = null;
let loaded = false;
function ensureHost(): HTMLElement {
if (host !== null) return host;
const first = document.getElementById('grid');
notice = document.createElement('div');
notice.style.cssText =
'margin-top:10px;padding:8px 10px;border:1px solid var(--mxg-border, #d9dee5);border-radius:6px;font-size:13px;color:var(--mxg-fg, #1f2933)';
const text = document.createElement('p');
text.style.margin = '0 0 6px';
text.textContent =
'ECharts는 Apache Software Foundation의 별도 오픈소스 라이브러리예요(Apache License 2.0). 맥스그리드에는 들어 있지 않고, 아래 단추를 누르면 jsDelivr CDN(cdn.jsdelivr.net)에서 불러와요.';
status = document.createElement('p');
status.style.margin = '0';
status.setAttribute('role', 'status');
status.textContent =
'아직 불러오지 않았어요. 단추를 누르기 전에는 외부로 아무것도 요청하지 않아요.';
notice.append(text, status);
host = document.createElement('div');
host.id = 'chart-host';
host.style.cssText = 'height:260px;margin-top:10px';
if (first !== null) first.after(notice, host);
else document.body.append(notice, host);
return host;
}
function cleanup(): void {
chart?.destroy();
chart = null;
}
function showStatus(message: string): void {
ensureHost();
if (status !== null) status.textContent = message;
}
// 고른 칸이 없으면 앞의 네 행(지역~3분기)을 골라서 차트가 바로 나오게 해요.
function fromSelection(api: GridApi<Row>, type: ChartType): GridChart | null {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
return api.createChart(ensureHost(), { source: 'selection', type, options: chartOptions });
}
const chartOptions = { title: '지역별 분기 매출', valueFormat: '{value}' };
/** Nothing is requested from the network until this runs (the button next to the notice). */
function load(log: (message: LogText) => void, then?: () => void): void {
ensureHost();
if (loaded || (window as unknown as { echarts?: unknown }).echarts !== undefined) {
loaded = true;
showStatus('ECharts를 불러왔어요.');
then?.();
return;
}
showStatus('ECharts를 불러오는 중이에요…');
loadECharts(
() => {
loaded = true;
showStatus('ECharts를 불러왔어요.');
log({ ko: 'ECharts 6.1.0을 불러왔어요.', en: 'ECharts 6.1.0 loaded.' });
then?.();
},
() => {
showStatus(
'ECharts를 불러오지 못했어요. 인터넷 연결이나 보안 정책(CSP)을 확인하고 다시 눌러 보세요.',
);
log({
ko: 'ECharts를 불러오지 못했어요(오프라인이거나 막혔어요).',
en: 'Could not load ECharts (offline or blocked).',
});
},
);
}
const needLoad = (log: (message: LogText) => void): boolean => {
if (loaded) return false;
showStatus('먼저 "ECharts 불러오기"를 눌러 주세요.');
log({ ko: '먼저 "ECharts 불러오기"를 눌러 주세요.', en: 'Press "Load ECharts" first.' });
return true;
};
let say: (message: LogText) => void = () => {};
let currentType: ChartType = 'column';
function rebuild(api: GridApi<Row>): void {
if (needLoad(say)) return;
cleanup();
chart = fromSelection(api, currentType);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
loaded = false;
currentType = 'column';
ensureHost();
const offCreated = api.on('chartCreated', ({ type }) => {
log({ ko: `차트를 만들었어요: ${type}`, en: `Chart created: ${type}` });
});
log({
ko: '먼저 "ECharts 불러오기"를 누르고, 종류를 바꿔 보세요.',
en: 'Press "Load ECharts", then switch the type.',
});
return () => {
offCreated();
cleanup();
notice?.remove();
host?.remove();
notice = null;
status = null;
host = null;
};
}
export const actions = {
load: (api: GridApi<Row>) => load(say, () => rebuild(api)),
chartType: (api: GridApi<Row>, value?: string) => {
currentType = (value as ChartType | undefined) ?? 'column';
rebuild(api);
},
clear: () => {
cleanup();
},
};버튼을 누르면 이 예제의 코드가 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.load(api)"
>ECharts 불러오기</button>
<select
aria-label="종류"
[disabled]="!api"
(change)="api && actions.chartType(api, $any($event.target).value)"
>
<option value="column" selected>막대</option>
<option value="bar">가로 막대</option>
<option value="line">꺾은선</option>
<option value="area">영역</option>
<option value="pie">원</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>지우기</button>
</div>
<mx-grid style="height: 520px" [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 {
ChartAdapter,
ChartData,
ChartType,
GridApi,
GridChart,
GridOptions,
} from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
region: string;
q1: number;
q2: number;
q3: number;
q4: number;
note: string;
}
const rows: Row[] = [
{ id: 1, region: '서울', q1: 120, q2: 150, q3: 180, q4: 210, note: '본사' },
{ id: 2, region: '부산', q1: 90, q2: 110, q3: 140, q4: 130, note: '항만' },
{ id: 3, region: '대구', q1: 70, q2: 85, q3: 95, q4: 120, note: '내륙' },
{ id: 4, region: '인천', q1: 100, q2: 130, q3: 125, q4: 160, note: '공항' },
{ id: 5, region: '광주', q1: 60, q2: 75, q3: 90, q4: 80, note: '호남' },
{ id: 6, region: '대전', q1: 80, q2: 95, q3: 110, q4: 140, note: '충청' },
{ id: 7, region: '울산', q1: 110, q2: 105, q3: 150, q4: 170, note: '공단' },
{ id: 8, region: '제주', q1: 50, q2: 65, q3: 70, q4: 95, note: '관광' },
];
const columns: NonNullable<GridOptions<Row>['columns']> = [
{ id: 'region', title: '지역', width: 110 },
{ id: 'q1', title: '1분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q2', title: '2분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q3', title: '3분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'q4', title: '4분기(백만원)', kind: 'number', editable: true, width: 120 },
{ id: 'note', title: '메모', editable: true, width: 110 },
];
// ── ECharts adapter recipe ───────────────────────────────────────────────────
// MaxGrid ships no chart library. This adapter maps ChartContext -> ECharts and back.
type EcChart = {
setOption(option: object, opts?: { replaceMerge?: string[] }): void;
dispose(): void;
resize(): void;
};
type EcStatic = {
init(el: HTMLElement, theme?: null, opts?: { renderer: 'svg' | 'canvas' }): EcChart;
};
type EcOptions = { title?: string; valueFormat?: string; echarts?: object };
const EC_VERSION = '6.1.0';
const EC_URL = `https://cdn.jsdelivr.net/npm/echarts@${EC_VERSION}/dist/echarts.min.js`;
const EC_SRI = 'sha384-C2iskrW/uPW46KzOjrvJIQo4YkV8lkD+QS0CrDN18IIPIpT/g2USu8bTP3nvmIAD';
const ec = (): EcStatic | undefined => (window as unknown as { echarts?: EcStatic }).echarts;
/** Reads the grid theme from its CSS variables (falls back to light/dark defaults). */
function themeOptions(el: HTMLElement, dark: boolean, type: ChartType): object {
const css = getComputedStyle(el);
const read = (name: string, fallback: string): string =>
css.getPropertyValue(name).trim() || fallback;
const bg = read('--mxg-bg', dark ? '#151a21' : '#ffffff');
const fg = read('--mxg-fg', dark ? '#e6e9ee' : '#1f2933');
const line = read('--mxg-border', dark ? '#323b47' : '#d9dee5');
const axis = {
axisLabel: { color: fg },
axisLine: { lineStyle: { color: line } },
axisTick: { lineStyle: { color: line } },
splitLine: { lineStyle: { color: line } },
};
return {
backgroundColor: bg,
textStyle: { color: fg },
title: { textStyle: { color: fg } },
legend: { textStyle: { color: fg } },
tooltip: { backgroundColor: bg, borderColor: line, textStyle: { color: fg } },
// a pie chart has no axes: do not add any
...(type === 'pie' ? {} : { xAxis: axis, yAxis: axis }),
};
}
/** Our ChartData -> ECharts series. Pie uses the first series; null values stay gaps. */
function seriesOf(type: ChartType, data: ChartData): object[] {
if (type === 'pie') {
const first = data.series[0];
return [
{
type: 'pie',
name: first?.name ?? '',
radius: '65%',
data: data.categories.map((name, i) => ({ name, value: first?.values[i] ?? null })),
},
];
}
return data.series.map((s) => ({
type: type === 'column' || type === 'bar' ? 'bar' : 'line',
name: s.name,
data: s.values,
...(type === 'area' ? { areaStyle: {} } : {}),
}));
}
/** Axes: a horizontal bar chart swaps the category and value axis. Pie has none. */
function axesOf(type: ChartType, data: ChartData): object {
if (type === 'pie') return {};
const category = { type: 'category', data: data.categories };
const value = { type: 'value' };
return type === 'bar' ? { xAxis: value, yAxis: category } : { xAxis: category, yAxis: value };
}
function loadECharts(onReady: () => void, onError: () => void): void {
if (ec() !== undefined) return onReady();
let script = document.querySelector<HTMLScriptElement>('script[data-echarts]');
if (script === null) {
script = document.createElement('script');
script.src = EC_URL;
script.integrity = EC_SRI; // the pinned file must match, or the browser refuses it
script.crossOrigin = 'anonymous';
script.dataset.echarts = '1';
document.head.append(script);
}
script.addEventListener('load', onReady, { once: true });
script.addEventListener(
'error',
() => {
script?.remove(); // allow another try
onError();
},
{ once: true },
);
}
const echartsAdapter: ChartAdapter = {
create(ctx) {
const echarts = ec();
if (echarts === undefined) {
ctx.container.textContent = 'ECharts를 아직 불러오지 않았어요.';
return { update() {}, destroy: () => ctx.container.replaceChildren() };
}
const opts = (ctx.options ?? {}) as EcOptions;
const dark = ctx.theme === 'dark';
const label = (d: ChartData): string =>
`${opts.title ?? '차트'}: ${d.categories.length} 분류, ${d.series.length} 계열`;
ctx.container.setAttribute('role', 'img');
ctx.container.setAttribute('aria-label', label(ctx.getData()));
const fmt = opts.valueFormat;
const base = (d: ChartData): object => ({
title: { text: opts.title ?? '' },
tooltip: {
trigger: ctx.type === 'pie' ? 'item' : 'axis',
...(fmt
? { valueFormatter: (v: unknown) => fmt.replace('{value}', Number(v).toLocaleString()) }
: {}),
},
legend: {},
series: seriesOf(ctx.type, d),
...axesOf(ctx.type, d),
});
const chart = echarts.init(ctx.container, null, { renderer: 'svg' });
chart.setOption(
merge(base(ctx.getData()), themeOptions(ctx.container, dark, ctx.type), opts.echarts),
);
// Follow the grid theme when it changes later.
const retheme = (): void =>
chart.setOption(
themeOptions(ctx.container, document.documentElement.dataset.mxgTheme === 'dark', ctx.type),
);
const watcher = new MutationObserver(retheme);
watcher.observe(document.documentElement, {
attributes: true,
subtree: true,
attributeFilter: ['data-mxg-theme'],
});
return {
update(d) {
ctx.container.setAttribute('aria-label', label(d));
chart.setOption(
{ ...axesOf(ctx.type, d), series: seriesOf(ctx.type, d) },
{ replaceMerge: ['series'] },
);
},
destroy() {
watcher.disconnect();
chart.dispose();
ctx.container.removeAttribute('role');
ctx.container.removeAttribute('aria-label');
},
resize: () => chart.resize(),
};
},
};
/** Small deep merge for plain option objects. */
function merge(...parts: Array<object | undefined>): object {
const out: Record<string, unknown> = {};
for (const part of parts) {
for (const [key, value] of Object.entries(part ?? {})) {
const prev = out[key];
const plain = (v: unknown): v is object =>
typeof v === 'object' && v !== null && !Array.isArray(v);
out[key] = plain(prev) && plain(value) ? merge(prev, value) : value;
}
}
return out;
}
export const options: GridOptions<Row> = {
rowKey: 'id',
columns,
rows,
cellSelection: 'multiple',
selection: 'multiple',
ariaLabel: '지역별 분기 매출',
chartAdapter: echartsAdapter,
};
let host: HTMLElement | null = null;
let notice: HTMLElement | null = null;
let status: HTMLElement | null = null;
let chart: GridChart | null = null;
let loaded = false;
function ensureHost(): HTMLElement {
if (host !== null) return host;
const first = document.getElementById('grid');
notice = document.createElement('div');
notice.style.cssText =
'margin-top:10px;padding:8px 10px;border:1px solid var(--mxg-border, #d9dee5);border-radius:6px;font-size:13px;color:var(--mxg-fg, #1f2933)';
const text = document.createElement('p');
text.style.margin = '0 0 6px';
text.textContent =
'ECharts는 Apache Software Foundation의 별도 오픈소스 라이브러리예요(Apache License 2.0). 맥스그리드에는 들어 있지 않고, 아래 단추를 누르면 jsDelivr CDN(cdn.jsdelivr.net)에서 불러와요.';
status = document.createElement('p');
status.style.margin = '0';
status.setAttribute('role', 'status');
status.textContent =
'아직 불러오지 않았어요. 단추를 누르기 전에는 외부로 아무것도 요청하지 않아요.';
notice.append(text, status);
host = document.createElement('div');
host.id = 'chart-host';
host.style.cssText = 'height:260px;margin-top:10px';
if (first !== null) first.after(notice, host);
else document.body.append(notice, host);
return host;
}
function cleanup(): void {
chart?.destroy();
chart = null;
}
function showStatus(message: string): void {
ensureHost();
if (status !== null) status.textContent = message;
}
// 고른 칸이 없으면 앞의 네 행(지역~3분기)을 골라서 차트가 바로 나오게 해요.
function fromSelection(api: GridApi<Row>, type: ChartType): GridChart | null {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
return api.createChart(ensureHost(), { source: 'selection', type, options: chartOptions });
}
const chartOptions = { title: '지역별 분기 매출', valueFormat: '{value}' };
/** Nothing is requested from the network until this runs (the button next to the notice). */
function load(log: (message: LogText) => void, then?: () => void): void {
ensureHost();
if (loaded || (window as unknown as { echarts?: unknown }).echarts !== undefined) {
loaded = true;
showStatus('ECharts를 불러왔어요.');
then?.();
return;
}
showStatus('ECharts를 불러오는 중이에요…');
loadECharts(
() => {
loaded = true;
showStatus('ECharts를 불러왔어요.');
log({ ko: 'ECharts 6.1.0을 불러왔어요.', en: 'ECharts 6.1.0 loaded.' });
then?.();
},
() => {
showStatus(
'ECharts를 불러오지 못했어요. 인터넷 연결이나 보안 정책(CSP)을 확인하고 다시 눌러 보세요.',
);
log({
ko: 'ECharts를 불러오지 못했어요(오프라인이거나 막혔어요).',
en: 'Could not load ECharts (offline or blocked).',
});
},
);
}
const needLoad = (log: (message: LogText) => void): boolean => {
if (loaded) return false;
showStatus('먼저 "ECharts 불러오기"를 눌러 주세요.');
log({ ko: '먼저 "ECharts 불러오기"를 눌러 주세요.', en: 'Press "Load ECharts" first.' });
return true;
};
let say: (message: LogText) => void = () => {};
let currentType: ChartType = 'column';
function rebuild(api: GridApi<Row>): void {
if (needLoad(say)) return;
cleanup();
chart = fromSelection(api, currentType);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
loaded = false;
currentType = 'column';
ensureHost();
const offCreated = api.on('chartCreated', ({ type }) => {
log({ ko: `차트를 만들었어요: ${type}`, en: `Chart created: ${type}` });
});
log({
ko: '먼저 "ECharts 불러오기"를 누르고, 종류를 바꿔 보세요.',
en: 'Press "Load ECharts", then switch the type.',
});
return () => {
offCreated();
cleanup();
notice?.remove();
host?.remove();
notice = null;
status = null;
host = null;
};
}
export const actions = {
load: (api: GridApi<Row>) => load(say, () => rebuild(api)),
chartType: (api: GridApi<Row>, value?: string) => {
currentType = (value as ChartType | undefined) ?? 'column';
rebuild(api);
},
clear: () => {
cleanup();
},
};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="load">Load ECharts</button>
<select aria-label="Type" id="chartType">
<option value="column" selected>Column</option>
<option value="bar">Bar</option>
<option value="line">Line</option>
<option value="area">Area</option>
<option value="pie">Pie</option>
</select>
<button type="button" id="clear">Clear</button>
</div>
<div id="grid" style="height: 520px"></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('load').addEventListener('click', () => actions.load(api));
document.getElementById('chartType').addEventListener('change', (event) => actions.chartType(api, event.target.value));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));const rows = [
{ id: 1, region: 'Seoul', q1: 120, q2: 150, q3: 180, q4: 210, note: 'HQ' },
{ id: 2, region: 'Busan', q1: 90, q2: 110, q3: 140, q4: 130, note: 'Port' },
{ id: 3, region: 'Daegu', q1: 70, q2: 85, q3: 95, q4: 120, note: 'Inland' },
{ id: 4, region: 'Incheon', q1: 100, q2: 130, q3: 125, q4: 160, note: 'Airport' },
{ id: 5, region: 'Gwangju', q1: 60, q2: 75, q3: 90, q4: 80, note: 'Southwest' },
{ id: 6, region: 'Daejeon', q1: 80, q2: 95, q3: 110, q4: 140, note: 'Central' },
{ id: 7, region: 'Ulsan', q1: 110, q2: 105, q3: 150, q4: 170, note: 'Industrial' },
{ id: 8, region: 'Jeju', q1: 50, q2: 65, q3: 70, q4: 95, note: 'Tourism' },
];
const columns = [
{ id: 'region', title: 'Region', width: 110 },
{ id: 'q1', title: 'Q1 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q2', title: 'Q2 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q3', title: 'Q3 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q4', title: 'Q4 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'note', title: 'Note', editable: true, width: 110 },
];
const EC_VERSION = '6.1.0';
const EC_URL = `https://cdn.jsdelivr.net/npm/echarts@${EC_VERSION}/dist/echarts.min.js`;
const EC_SRI = 'sha384-C2iskrW/uPW46KzOjrvJIQo4YkV8lkD+QS0CrDN18IIPIpT/g2USu8bTP3nvmIAD';
const ec = () => window.echarts;
/** Reads the grid theme from its CSS variables (falls back to light/dark defaults). */
function themeOptions(el, dark, type) {
const css = getComputedStyle(el);
const read = (name, fallback) => css.getPropertyValue(name).trim() || fallback;
const bg = read('--mxg-bg', dark ? '#151a21' : '#ffffff');
const fg = read('--mxg-fg', dark ? '#e6e9ee' : '#1f2933');
const line = read('--mxg-border', dark ? '#323b47' : '#d9dee5');
const axis = {
axisLabel: { color: fg },
axisLine: { lineStyle: { color: line } },
axisTick: { lineStyle: { color: line } },
splitLine: { lineStyle: { color: line } },
};
return {
backgroundColor: bg,
textStyle: { color: fg },
title: { textStyle: { color: fg } },
legend: { textStyle: { color: fg } },
tooltip: { backgroundColor: bg, borderColor: line, textStyle: { color: fg } },
// a pie chart has no axes: do not add any
...(type === 'pie' ? {} : { xAxis: axis, yAxis: axis }),
};
}
/** Our ChartData -> ECharts series. Pie uses the first series; null values stay gaps. */
function seriesOf(type, data) {
if (type === 'pie') {
const first = data.series[0];
return [
{
type: 'pie',
name: first?.name ?? '',
radius: '65%',
data: data.categories.map((name, i) => ({ name, value: first?.values[i] ?? null })),
},
];
}
return data.series.map((s) => ({
type: type === 'column' || type === 'bar' ? 'bar' : 'line',
name: s.name,
data: s.values,
...(type === 'area' ? { areaStyle: {} } : {}),
}));
}
/** Axes: a horizontal bar chart swaps the category and value axis. Pie has none. */
function axesOf(type, data) {
if (type === 'pie')
return {};
const category = { type: 'category', data: data.categories };
const value = { type: 'value' };
return type === 'bar' ? { xAxis: value, yAxis: category } : { xAxis: category, yAxis: value };
}
function loadECharts(onReady, onError) {
if (ec() !== undefined)
return onReady();
let script = document.querySelector('script[data-echarts]');
if (script === null) {
script = document.createElement('script');
script.src = EC_URL;
script.integrity = EC_SRI; // the pinned file must match, or the browser refuses it
script.crossOrigin = 'anonymous';
script.dataset.echarts = '1';
document.head.append(script);
}
script.addEventListener('load', onReady, { once: true });
script.addEventListener('error', () => {
script?.remove(); // allow another try
onError();
}, { once: true });
}
const echartsAdapter = {
create(ctx) {
const echarts = ec();
if (echarts === undefined) {
ctx.container.textContent = 'ECharts is not loaded yet.';
return { update() { }, destroy: () => ctx.container.replaceChildren() };
}
const opts = (ctx.options ?? {});
const dark = ctx.theme === 'dark';
const label = (d) => `${opts.title ?? 'Chart'}: ${d.categories.length} categories, ${d.series.length} series`;
ctx.container.setAttribute('role', 'img');
ctx.container.setAttribute('aria-label', label(ctx.getData()));
const fmt = opts.valueFormat;
const base = (d) => ({
title: { text: opts.title ?? '' },
tooltip: {
trigger: ctx.type === 'pie' ? 'item' : 'axis',
...(fmt
? { valueFormatter: (v) => fmt.replace('{value}', Number(v).toLocaleString()) }
: {}),
},
legend: {},
series: seriesOf(ctx.type, d),
...axesOf(ctx.type, d),
});
const chart = echarts.init(ctx.container, null, { renderer: 'svg' });
chart.setOption(merge(base(ctx.getData()), themeOptions(ctx.container, dark, ctx.type), opts.echarts));
// Follow the grid theme when it changes later.
const retheme = () => chart.setOption(themeOptions(ctx.container, document.documentElement.dataset.mxgTheme === 'dark', ctx.type));
const watcher = new MutationObserver(retheme);
watcher.observe(document.documentElement, {
attributes: true,
subtree: true,
attributeFilter: ['data-mxg-theme'],
});
return {
update(d) {
ctx.container.setAttribute('aria-label', label(d));
chart.setOption({ ...axesOf(ctx.type, d), series: seriesOf(ctx.type, d) }, { replaceMerge: ['series'] });
},
destroy() {
watcher.disconnect();
chart.dispose();
ctx.container.removeAttribute('role');
ctx.container.removeAttribute('aria-label');
},
resize: () => chart.resize(),
};
},
};
/** Small deep merge for plain option objects. */
function merge(...parts) {
const out = {};
for (const part of parts) {
for (const [key, value] of Object.entries(part ?? {})) {
const prev = out[key];
const plain = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
out[key] = plain(prev) && plain(value) ? merge(prev, value) : value;
}
}
return out;
}
export const options = {
rowKey: 'id',
columns,
rows,
cellSelection: 'multiple',
selection: 'multiple',
ariaLabel: 'Regional sales by quarter',
chartAdapter: echartsAdapter,
};
let host = null;
let notice = null;
let status = null;
let chart = null;
let loaded = false;
function ensureHost() {
if (host !== null)
return host;
const first = document.getElementById('grid');
notice = document.createElement('div');
notice.style.cssText =
'margin-top:10px;padding:8px 10px;border:1px solid var(--mxg-border, #d9dee5);border-radius:6px;font-size:13px;color:var(--mxg-fg, #1f2933)';
const text = document.createElement('p');
text.style.margin = '0 0 6px';
text.textContent =
'ECharts is a separate open-source library from the Apache Software Foundation (Apache License 2.0); MaxGrid does not include it. The button below loads it from the jsDelivr CDN (cdn.jsdelivr.net).';
status = document.createElement('p');
status.style.margin = '0';
status.setAttribute('role', 'status');
status.textContent =
'Not loaded yet. Nothing is requested from the network until you press the button.';
notice.append(text, status);
host = document.createElement('div');
host.id = 'chart-host';
host.style.cssText = 'height:260px;margin-top:10px';
if (first !== null)
first.after(notice, host);
else
document.body.append(notice, host);
return host;
}
function cleanup() {
chart?.destroy();
chart = null;
}
function showStatus(message) {
ensureHost();
if (status !== null)
status.textContent = message;
}
// If nothing is selected, select the first four rows (region to Q3) so a chart appears at once.
function fromSelection(api, type) {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
return api.createChart(ensureHost(), { source: 'selection', type, options: chartOptions });
}
const chartOptions = { title: 'Regional sales by quarter', valueFormat: '{value}' };
/** Nothing is requested from the network until this runs (the button next to the notice). */
function load(log, then) {
ensureHost();
if (loaded || window.echarts !== undefined) {
loaded = true;
showStatus('ECharts is loaded.');
then?.();
return;
}
showStatus('Loading ECharts…');
loadECharts(() => {
loaded = true;
showStatus('ECharts is loaded.');
log('ECharts 6.1.0 loaded.');
then?.();
}, () => {
showStatus('Could not load ECharts. Check your connection or Content Security Policy and press the button again.');
log('Could not load ECharts (offline or blocked).');
});
}
const needLoad = (log) => {
if (loaded)
return false;
showStatus('Press "Load ECharts" first.');
log('Press "Load ECharts" first.');
return true;
};
let say = () => { };
let currentType = 'column';
function rebuild(api) {
if (needLoad(say))
return;
cleanup();
chart = fromSelection(api, currentType);
}
export function setup(api, log) {
say = log;
loaded = false;
currentType = 'column';
ensureHost();
const offCreated = api.on('chartCreated', ({ type }) => {
log(`Chart created: ${type}`);
});
log('Press "Load ECharts", then switch the type.');
return () => {
offCreated();
cleanup();
notice?.remove();
host?.remove();
notice = null;
status = null;
host = null;
};
}
export const actions = {
load: (api) => load(say, () => rebuild(api)),
chartType: (api, value) => {
currentType = value ?? 'column';
rebuild(api);
},
clear: () => {
cleanup();
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Switch ECharts chart types</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="load">Load ECharts</button>
<select aria-label="Type" id="chartType">
<option value="column" selected>Column</option>
<option value="bar">Bar</option>
<option value="line">Line</option>
<option value="area">Area</option>
<option value="pie">Pie</option>
</select>
<button type="button" id="clear">Clear</button>
</div>
<div id="grid" style="height: 520px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const rows = [
{ id: 1, region: 'Seoul', q1: 120, q2: 150, q3: 180, q4: 210, note: 'HQ' },
{ id: 2, region: 'Busan', q1: 90, q2: 110, q3: 140, q4: 130, note: 'Port' },
{ id: 3, region: 'Daegu', q1: 70, q2: 85, q3: 95, q4: 120, note: 'Inland' },
{ id: 4, region: 'Incheon', q1: 100, q2: 130, q3: 125, q4: 160, note: 'Airport' },
{ id: 5, region: 'Gwangju', q1: 60, q2: 75, q3: 90, q4: 80, note: 'Southwest' },
{ id: 6, region: 'Daejeon', q1: 80, q2: 95, q3: 110, q4: 140, note: 'Central' },
{ id: 7, region: 'Ulsan', q1: 110, q2: 105, q3: 150, q4: 170, note: 'Industrial' },
{ id: 8, region: 'Jeju', q1: 50, q2: 65, q3: 70, q4: 95, note: 'Tourism' },
];
const columns = [
{ id: 'region', title: 'Region', width: 110 },
{ id: 'q1', title: 'Q1 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q2', title: 'Q2 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q3', title: 'Q3 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q4', title: 'Q4 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'note', title: 'Note', editable: true, width: 110 },
];
const EC_VERSION = '6.1.0';
const EC_URL = `https://cdn.jsdelivr.net/npm/echarts@${EC_VERSION}/dist/echarts.min.js`;
const EC_SRI = 'sha384-C2iskrW/uPW46KzOjrvJIQo4YkV8lkD+QS0CrDN18IIPIpT/g2USu8bTP3nvmIAD';
const ec = () => window.echarts;
/** Reads the grid theme from its CSS variables (falls back to light/dark defaults). */
function themeOptions(el, dark, type) {
const css = getComputedStyle(el);
const read = (name, fallback) => css.getPropertyValue(name).trim() || fallback;
const bg = read('--mxg-bg', dark ? '#151a21' : '#ffffff');
const fg = read('--mxg-fg', dark ? '#e6e9ee' : '#1f2933');
const line = read('--mxg-border', dark ? '#323b47' : '#d9dee5');
const axis = {
axisLabel: { color: fg },
axisLine: { lineStyle: { color: line } },
axisTick: { lineStyle: { color: line } },
splitLine: { lineStyle: { color: line } },
};
return {
backgroundColor: bg,
textStyle: { color: fg },
title: { textStyle: { color: fg } },
legend: { textStyle: { color: fg } },
tooltip: { backgroundColor: bg, borderColor: line, textStyle: { color: fg } },
// a pie chart has no axes: do not add any
...(type === 'pie' ? {} : { xAxis: axis, yAxis: axis }),
};
}
/** Our ChartData -> ECharts series. Pie uses the first series; null values stay gaps. */
function seriesOf(type, data) {
if (type === 'pie') {
const first = data.series[0];
return [
{
type: 'pie',
name: first?.name ?? '',
radius: '65%',
data: data.categories.map((name, i) => ({ name, value: first?.values[i] ?? null })),
},
];
}
return data.series.map((s) => ({
type: type === 'column' || type === 'bar' ? 'bar' : 'line',
name: s.name,
data: s.values,
...(type === 'area' ? { areaStyle: {} } : {}),
}));
}
/** Axes: a horizontal bar chart swaps the category and value axis. Pie has none. */
function axesOf(type, data) {
if (type === 'pie')
return {};
const category = { type: 'category', data: data.categories };
const value = { type: 'value' };
return type === 'bar' ? { xAxis: value, yAxis: category } : { xAxis: category, yAxis: value };
}
function loadECharts(onReady, onError) {
if (ec() !== undefined)
return onReady();
let script = document.querySelector('script[data-echarts]');
if (script === null) {
script = document.createElement('script');
script.src = EC_URL;
script.integrity = EC_SRI; // the pinned file must match, or the browser refuses it
script.crossOrigin = 'anonymous';
script.dataset.echarts = '1';
document.head.append(script);
}
script.addEventListener('load', onReady, { once: true });
script.addEventListener('error', () => {
script?.remove(); // allow another try
onError();
}, { once: true });
}
const echartsAdapter = {
create(ctx) {
const echarts = ec();
if (echarts === undefined) {
ctx.container.textContent = 'ECharts is not loaded yet.';
return { update() { }, destroy: () => ctx.container.replaceChildren() };
}
const opts = (ctx.options ?? {});
const dark = ctx.theme === 'dark';
const label = (d) => `${opts.title ?? 'Chart'}: ${d.categories.length} categories, ${d.series.length} series`;
ctx.container.setAttribute('role', 'img');
ctx.container.setAttribute('aria-label', label(ctx.getData()));
const fmt = opts.valueFormat;
const base = (d) => ({
title: { text: opts.title ?? '' },
tooltip: {
trigger: ctx.type === 'pie' ? 'item' : 'axis',
...(fmt
? { valueFormatter: (v) => fmt.replace('{value}', Number(v).toLocaleString()) }
: {}),
},
legend: {},
series: seriesOf(ctx.type, d),
...axesOf(ctx.type, d),
});
const chart = echarts.init(ctx.container, null, { renderer: 'svg' });
chart.setOption(merge(base(ctx.getData()), themeOptions(ctx.container, dark, ctx.type), opts.echarts));
// Follow the grid theme when it changes later.
const retheme = () => chart.setOption(themeOptions(ctx.container, document.documentElement.dataset.mxgTheme === 'dark', ctx.type));
const watcher = new MutationObserver(retheme);
watcher.observe(document.documentElement, {
attributes: true,
subtree: true,
attributeFilter: ['data-mxg-theme'],
});
return {
update(d) {
ctx.container.setAttribute('aria-label', label(d));
chart.setOption({ ...axesOf(ctx.type, d), series: seriesOf(ctx.type, d) }, { replaceMerge: ['series'] });
},
destroy() {
watcher.disconnect();
chart.dispose();
ctx.container.removeAttribute('role');
ctx.container.removeAttribute('aria-label');
},
resize: () => chart.resize(),
};
},
};
/** Small deep merge for plain option objects. */
function merge(...parts) {
const out = {};
for (const part of parts) {
for (const [key, value] of Object.entries(part ?? {})) {
const prev = out[key];
const plain = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
out[key] = plain(prev) && plain(value) ? merge(prev, value) : value;
}
}
return out;
}
const options = {
rowKey: 'id',
columns,
rows,
cellSelection: 'multiple',
selection: 'multiple',
ariaLabel: 'Regional sales by quarter',
chartAdapter: echartsAdapter,
};
let host = null;
let notice = null;
let status = null;
let chart = null;
let loaded = false;
function ensureHost() {
if (host !== null)
return host;
const first = document.getElementById('grid');
notice = document.createElement('div');
notice.style.cssText =
'margin-top:10px;padding:8px 10px;border:1px solid var(--mxg-border, #d9dee5);border-radius:6px;font-size:13px;color:var(--mxg-fg, #1f2933)';
const text = document.createElement('p');
text.style.margin = '0 0 6px';
text.textContent =
'ECharts is a separate open-source library from the Apache Software Foundation (Apache License 2.0); MaxGrid does not include it. The button below loads it from the jsDelivr CDN (cdn.jsdelivr.net).';
status = document.createElement('p');
status.style.margin = '0';
status.setAttribute('role', 'status');
status.textContent =
'Not loaded yet. Nothing is requested from the network until you press the button.';
notice.append(text, status);
host = document.createElement('div');
host.id = 'chart-host';
host.style.cssText = 'height:260px;margin-top:10px';
if (first !== null)
first.after(notice, host);
else
document.body.append(notice, host);
return host;
}
function cleanup() {
chart?.destroy();
chart = null;
}
function showStatus(message) {
ensureHost();
if (status !== null)
status.textContent = message;
}
// If nothing is selected, select the first four rows (region to Q3) so a chart appears at once.
function fromSelection(api, type) {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
return api.createChart(ensureHost(), { source: 'selection', type, options: chartOptions });
}
const chartOptions = { title: 'Regional sales by quarter', valueFormat: '{value}' };
/** Nothing is requested from the network until this runs (the button next to the notice). */
function load(log, then) {
ensureHost();
if (loaded || window.echarts !== undefined) {
loaded = true;
showStatus('ECharts is loaded.');
then?.();
return;
}
showStatus('Loading ECharts…');
loadECharts(() => {
loaded = true;
showStatus('ECharts is loaded.');
log('ECharts 6.1.0 loaded.');
then?.();
}, () => {
showStatus('Could not load ECharts. Check your connection or Content Security Policy and press the button again.');
log('Could not load ECharts (offline or blocked).');
});
}
const needLoad = (log) => {
if (loaded)
return false;
showStatus('Press "Load ECharts" first.');
log('Press "Load ECharts" first.');
return true;
};
let say = () => { };
let currentType = 'column';
function rebuild(api) {
if (needLoad(say))
return;
cleanup();
chart = fromSelection(api, currentType);
}
function setup(api, log) {
say = log;
loaded = false;
currentType = 'column';
ensureHost();
const offCreated = api.on('chartCreated', ({ type }) => {
log(`Chart created: ${type}`);
});
log('Press "Load ECharts", then switch the type.');
return () => {
offCreated();
cleanup();
notice?.remove();
host?.remove();
notice = null;
status = null;
host = null;
};
}
const actions = {
load: (api) => load(say, () => rebuild(api)),
chartType: (api, value) => {
currentType = value ?? 'column';
rebuild(api);
},
clear: () => {
cleanup();
},
};
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('load').addEventListener('click', () => actions.load(api));
document.getElementById('chartType').addEventListener('change', (event) => actions.chartType(api, event.target.value));
document.getElementById('clear').addEventListener('click', () => actions.clear(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.load(api)}
>Load ECharts</button>
<select
aria-label="Type"
disabled={!api}
onChange={(event) => api && actions.chartType(api, event.target.value)}
>
<option value="column">Column</option>
<option value="bar">Bar</option>
<option value="line">Line</option>
<option value="area">Area</option>
<option value="pie">Pie</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>Clear</button>
</div>
<Grid style={{ height: 520 }} ref={gridRef} options={options} />
</>
);
}import type {
ChartAdapter,
ChartData,
ChartType,
GridApi,
GridChart,
GridOptions,
} from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
region: string;
q1: number;
q2: number;
q3: number;
q4: number;
note: string;
}
const rows: Row[] = [
{ id: 1, region: 'Seoul', q1: 120, q2: 150, q3: 180, q4: 210, note: 'HQ' },
{ id: 2, region: 'Busan', q1: 90, q2: 110, q3: 140, q4: 130, note: 'Port' },
{ id: 3, region: 'Daegu', q1: 70, q2: 85, q3: 95, q4: 120, note: 'Inland' },
{ id: 4, region: 'Incheon', q1: 100, q2: 130, q3: 125, q4: 160, note: 'Airport' },
{ id: 5, region: 'Gwangju', q1: 60, q2: 75, q3: 90, q4: 80, note: 'Southwest' },
{ id: 6, region: 'Daejeon', q1: 80, q2: 95, q3: 110, q4: 140, note: 'Central' },
{ id: 7, region: 'Ulsan', q1: 110, q2: 105, q3: 150, q4: 170, note: 'Industrial' },
{ id: 8, region: 'Jeju', q1: 50, q2: 65, q3: 70, q4: 95, note: 'Tourism' },
];
const columns: NonNullable<GridOptions<Row>['columns']> = [
{ id: 'region', title: 'Region', width: 110 },
{ id: 'q1', title: 'Q1 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q2', title: 'Q2 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q3', title: 'Q3 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q4', title: 'Q4 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'note', title: 'Note', editable: true, width: 110 },
];
// ── ECharts adapter recipe ───────────────────────────────────────────────────
// MaxGrid ships no chart library. This adapter maps ChartContext -> ECharts and back.
type EcChart = {
setOption(option: object, opts?: { replaceMerge?: string[] }): void;
dispose(): void;
resize(): void;
};
type EcStatic = {
init(el: HTMLElement, theme?: null, opts?: { renderer: 'svg' | 'canvas' }): EcChart;
};
type EcOptions = { title?: string; valueFormat?: string; echarts?: object };
const EC_VERSION = '6.1.0';
const EC_URL = `https://cdn.jsdelivr.net/npm/echarts@${EC_VERSION}/dist/echarts.min.js`;
const EC_SRI = 'sha384-C2iskrW/uPW46KzOjrvJIQo4YkV8lkD+QS0CrDN18IIPIpT/g2USu8bTP3nvmIAD';
const ec = (): EcStatic | undefined => (window as unknown as { echarts?: EcStatic }).echarts;
/** Reads the grid theme from its CSS variables (falls back to light/dark defaults). */
function themeOptions(el: HTMLElement, dark: boolean, type: ChartType): object {
const css = getComputedStyle(el);
const read = (name: string, fallback: string): string =>
css.getPropertyValue(name).trim() || fallback;
const bg = read('--mxg-bg', dark ? '#151a21' : '#ffffff');
const fg = read('--mxg-fg', dark ? '#e6e9ee' : '#1f2933');
const line = read('--mxg-border', dark ? '#323b47' : '#d9dee5');
const axis = {
axisLabel: { color: fg },
axisLine: { lineStyle: { color: line } },
axisTick: { lineStyle: { color: line } },
splitLine: { lineStyle: { color: line } },
};
return {
backgroundColor: bg,
textStyle: { color: fg },
title: { textStyle: { color: fg } },
legend: { textStyle: { color: fg } },
tooltip: { backgroundColor: bg, borderColor: line, textStyle: { color: fg } },
// a pie chart has no axes: do not add any
...(type === 'pie' ? {} : { xAxis: axis, yAxis: axis }),
};
}
/** Our ChartData -> ECharts series. Pie uses the first series; null values stay gaps. */
function seriesOf(type: ChartType, data: ChartData): object[] {
if (type === 'pie') {
const first = data.series[0];
return [
{
type: 'pie',
name: first?.name ?? '',
radius: '65%',
data: data.categories.map((name, i) => ({ name, value: first?.values[i] ?? null })),
},
];
}
return data.series.map((s) => ({
type: type === 'column' || type === 'bar' ? 'bar' : 'line',
name: s.name,
data: s.values,
...(type === 'area' ? { areaStyle: {} } : {}),
}));
}
/** Axes: a horizontal bar chart swaps the category and value axis. Pie has none. */
function axesOf(type: ChartType, data: ChartData): object {
if (type === 'pie') return {};
const category = { type: 'category', data: data.categories };
const value = { type: 'value' };
return type === 'bar' ? { xAxis: value, yAxis: category } : { xAxis: category, yAxis: value };
}
function loadECharts(onReady: () => void, onError: () => void): void {
if (ec() !== undefined) return onReady();
let script = document.querySelector<HTMLScriptElement>('script[data-echarts]');
if (script === null) {
script = document.createElement('script');
script.src = EC_URL;
script.integrity = EC_SRI; // the pinned file must match, or the browser refuses it
script.crossOrigin = 'anonymous';
script.dataset.echarts = '1';
document.head.append(script);
}
script.addEventListener('load', onReady, { once: true });
script.addEventListener(
'error',
() => {
script?.remove(); // allow another try
onError();
},
{ once: true },
);
}
const echartsAdapter: ChartAdapter = {
create(ctx) {
const echarts = ec();
if (echarts === undefined) {
ctx.container.textContent = 'ECharts is not loaded yet.';
return { update() {}, destroy: () => ctx.container.replaceChildren() };
}
const opts = (ctx.options ?? {}) as EcOptions;
const dark = ctx.theme === 'dark';
const label = (d: ChartData): string =>
`${opts.title ?? 'Chart'}: ${d.categories.length} categories, ${d.series.length} series`;
ctx.container.setAttribute('role', 'img');
ctx.container.setAttribute('aria-label', label(ctx.getData()));
const fmt = opts.valueFormat;
const base = (d: ChartData): object => ({
title: { text: opts.title ?? '' },
tooltip: {
trigger: ctx.type === 'pie' ? 'item' : 'axis',
...(fmt
? { valueFormatter: (v: unknown) => fmt.replace('{value}', Number(v).toLocaleString()) }
: {}),
},
legend: {},
series: seriesOf(ctx.type, d),
...axesOf(ctx.type, d),
});
const chart = echarts.init(ctx.container, null, { renderer: 'svg' });
chart.setOption(
merge(base(ctx.getData()), themeOptions(ctx.container, dark, ctx.type), opts.echarts),
);
// Follow the grid theme when it changes later.
const retheme = (): void =>
chart.setOption(
themeOptions(ctx.container, document.documentElement.dataset.mxgTheme === 'dark', ctx.type),
);
const watcher = new MutationObserver(retheme);
watcher.observe(document.documentElement, {
attributes: true,
subtree: true,
attributeFilter: ['data-mxg-theme'],
});
return {
update(d) {
ctx.container.setAttribute('aria-label', label(d));
chart.setOption(
{ ...axesOf(ctx.type, d), series: seriesOf(ctx.type, d) },
{ replaceMerge: ['series'] },
);
},
destroy() {
watcher.disconnect();
chart.dispose();
ctx.container.removeAttribute('role');
ctx.container.removeAttribute('aria-label');
},
resize: () => chart.resize(),
};
},
};
/** Small deep merge for plain option objects. */
function merge(...parts: Array<object | undefined>): object {
const out: Record<string, unknown> = {};
for (const part of parts) {
for (const [key, value] of Object.entries(part ?? {})) {
const prev = out[key];
const plain = (v: unknown): v is object =>
typeof v === 'object' && v !== null && !Array.isArray(v);
out[key] = plain(prev) && plain(value) ? merge(prev, value) : value;
}
}
return out;
}
export const options: GridOptions<Row> = {
rowKey: 'id',
columns,
rows,
cellSelection: 'multiple',
selection: 'multiple',
ariaLabel: 'Regional sales by quarter',
chartAdapter: echartsAdapter,
};
let host: HTMLElement | null = null;
let notice: HTMLElement | null = null;
let status: HTMLElement | null = null;
let chart: GridChart | null = null;
let loaded = false;
function ensureHost(): HTMLElement {
if (host !== null) return host;
const first = document.getElementById('grid');
notice = document.createElement('div');
notice.style.cssText =
'margin-top:10px;padding:8px 10px;border:1px solid var(--mxg-border, #d9dee5);border-radius:6px;font-size:13px;color:var(--mxg-fg, #1f2933)';
const text = document.createElement('p');
text.style.margin = '0 0 6px';
text.textContent =
'ECharts is a separate open-source library from the Apache Software Foundation (Apache License 2.0); MaxGrid does not include it. The button below loads it from the jsDelivr CDN (cdn.jsdelivr.net).';
status = document.createElement('p');
status.style.margin = '0';
status.setAttribute('role', 'status');
status.textContent =
'Not loaded yet. Nothing is requested from the network until you press the button.';
notice.append(text, status);
host = document.createElement('div');
host.id = 'chart-host';
host.style.cssText = 'height:260px;margin-top:10px';
if (first !== null) first.after(notice, host);
else document.body.append(notice, host);
return host;
}
function cleanup(): void {
chart?.destroy();
chart = null;
}
function showStatus(message: string): void {
ensureHost();
if (status !== null) status.textContent = message;
}
// If nothing is selected, select the first four rows (region to Q3) so a chart appears at once.
function fromSelection(api: GridApi<Row>, type: ChartType): GridChart | null {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
return api.createChart(ensureHost(), { source: 'selection', type, options: chartOptions });
}
const chartOptions = { title: 'Regional sales by quarter', valueFormat: '{value}' };
/** Nothing is requested from the network until this runs (the button next to the notice). */
function load(log: (message: LogText) => void, then?: () => void): void {
ensureHost();
if (loaded || (window as unknown as { echarts?: unknown }).echarts !== undefined) {
loaded = true;
showStatus('ECharts is loaded.');
then?.();
return;
}
showStatus('Loading ECharts…');
loadECharts(
() => {
loaded = true;
showStatus('ECharts is loaded.');
log('ECharts 6.1.0 loaded.');
then?.();
},
() => {
showStatus(
'Could not load ECharts. Check your connection or Content Security Policy and press the button again.',
);
log('Could not load ECharts (offline or blocked).');
},
);
}
const needLoad = (log: (message: LogText) => void): boolean => {
if (loaded) return false;
showStatus('Press "Load ECharts" first.');
log('Press "Load ECharts" first.');
return true;
};
let say: (message: LogText) => void = () => {};
let currentType: ChartType = 'column';
function rebuild(api: GridApi<Row>): void {
if (needLoad(say)) return;
cleanup();
chart = fromSelection(api, currentType);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
loaded = false;
currentType = 'column';
ensureHost();
const offCreated = api.on('chartCreated', ({ type }) => {
log(`Chart created: ${type}`);
});
log('Press "Load ECharts", then switch the type.');
return () => {
offCreated();
cleanup();
notice?.remove();
host?.remove();
notice = null;
status = null;
host = null;
};
}
export const actions = {
load: (api: GridApi<Row>) => load(say, () => rebuild(api)),
chartType: (api: GridApi<Row>, value?: string) => {
currentType = (value as ChartType | undefined) ?? 'column';
rebuild(api);
},
clear: () => {
cleanup();
},
};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.load(api)">Load ECharts</button>
<select
aria-label="Type"
:disabled="!api"
@change="api && actions.chartType(api, ($event.target as HTMLSelectElement).value)"
>
<option value="column" selected>Column</option>
<option value="bar">Bar</option>
<option value="line">Line</option>
<option value="area">Area</option>
<option value="pie">Pie</option>
</select>
<button type="button" :disabled="!api" @click="api && actions.clear(api)">Clear</button>
</div>
<Grid style="height: 520px" :options="options" @ready="onReady" />
</template>import type {
ChartAdapter,
ChartData,
ChartType,
GridApi,
GridChart,
GridOptions,
} from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
region: string;
q1: number;
q2: number;
q3: number;
q4: number;
note: string;
}
const rows: Row[] = [
{ id: 1, region: 'Seoul', q1: 120, q2: 150, q3: 180, q4: 210, note: 'HQ' },
{ id: 2, region: 'Busan', q1: 90, q2: 110, q3: 140, q4: 130, note: 'Port' },
{ id: 3, region: 'Daegu', q1: 70, q2: 85, q3: 95, q4: 120, note: 'Inland' },
{ id: 4, region: 'Incheon', q1: 100, q2: 130, q3: 125, q4: 160, note: 'Airport' },
{ id: 5, region: 'Gwangju', q1: 60, q2: 75, q3: 90, q4: 80, note: 'Southwest' },
{ id: 6, region: 'Daejeon', q1: 80, q2: 95, q3: 110, q4: 140, note: 'Central' },
{ id: 7, region: 'Ulsan', q1: 110, q2: 105, q3: 150, q4: 170, note: 'Industrial' },
{ id: 8, region: 'Jeju', q1: 50, q2: 65, q3: 70, q4: 95, note: 'Tourism' },
];
const columns: NonNullable<GridOptions<Row>['columns']> = [
{ id: 'region', title: 'Region', width: 110 },
{ id: 'q1', title: 'Q1 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q2', title: 'Q2 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q3', title: 'Q3 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q4', title: 'Q4 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'note', title: 'Note', editable: true, width: 110 },
];
// ── ECharts adapter recipe ───────────────────────────────────────────────────
// MaxGrid ships no chart library. This adapter maps ChartContext -> ECharts and back.
type EcChart = {
setOption(option: object, opts?: { replaceMerge?: string[] }): void;
dispose(): void;
resize(): void;
};
type EcStatic = {
init(el: HTMLElement, theme?: null, opts?: { renderer: 'svg' | 'canvas' }): EcChart;
};
type EcOptions = { title?: string; valueFormat?: string; echarts?: object };
const EC_VERSION = '6.1.0';
const EC_URL = `https://cdn.jsdelivr.net/npm/echarts@${EC_VERSION}/dist/echarts.min.js`;
const EC_SRI = 'sha384-C2iskrW/uPW46KzOjrvJIQo4YkV8lkD+QS0CrDN18IIPIpT/g2USu8bTP3nvmIAD';
const ec = (): EcStatic | undefined => (window as unknown as { echarts?: EcStatic }).echarts;
/** Reads the grid theme from its CSS variables (falls back to light/dark defaults). */
function themeOptions(el: HTMLElement, dark: boolean, type: ChartType): object {
const css = getComputedStyle(el);
const read = (name: string, fallback: string): string =>
css.getPropertyValue(name).trim() || fallback;
const bg = read('--mxg-bg', dark ? '#151a21' : '#ffffff');
const fg = read('--mxg-fg', dark ? '#e6e9ee' : '#1f2933');
const line = read('--mxg-border', dark ? '#323b47' : '#d9dee5');
const axis = {
axisLabel: { color: fg },
axisLine: { lineStyle: { color: line } },
axisTick: { lineStyle: { color: line } },
splitLine: { lineStyle: { color: line } },
};
return {
backgroundColor: bg,
textStyle: { color: fg },
title: { textStyle: { color: fg } },
legend: { textStyle: { color: fg } },
tooltip: { backgroundColor: bg, borderColor: line, textStyle: { color: fg } },
// a pie chart has no axes: do not add any
...(type === 'pie' ? {} : { xAxis: axis, yAxis: axis }),
};
}
/** Our ChartData -> ECharts series. Pie uses the first series; null values stay gaps. */
function seriesOf(type: ChartType, data: ChartData): object[] {
if (type === 'pie') {
const first = data.series[0];
return [
{
type: 'pie',
name: first?.name ?? '',
radius: '65%',
data: data.categories.map((name, i) => ({ name, value: first?.values[i] ?? null })),
},
];
}
return data.series.map((s) => ({
type: type === 'column' || type === 'bar' ? 'bar' : 'line',
name: s.name,
data: s.values,
...(type === 'area' ? { areaStyle: {} } : {}),
}));
}
/** Axes: a horizontal bar chart swaps the category and value axis. Pie has none. */
function axesOf(type: ChartType, data: ChartData): object {
if (type === 'pie') return {};
const category = { type: 'category', data: data.categories };
const value = { type: 'value' };
return type === 'bar' ? { xAxis: value, yAxis: category } : { xAxis: category, yAxis: value };
}
function loadECharts(onReady: () => void, onError: () => void): void {
if (ec() !== undefined) return onReady();
let script = document.querySelector<HTMLScriptElement>('script[data-echarts]');
if (script === null) {
script = document.createElement('script');
script.src = EC_URL;
script.integrity = EC_SRI; // the pinned file must match, or the browser refuses it
script.crossOrigin = 'anonymous';
script.dataset.echarts = '1';
document.head.append(script);
}
script.addEventListener('load', onReady, { once: true });
script.addEventListener(
'error',
() => {
script?.remove(); // allow another try
onError();
},
{ once: true },
);
}
const echartsAdapter: ChartAdapter = {
create(ctx) {
const echarts = ec();
if (echarts === undefined) {
ctx.container.textContent = 'ECharts is not loaded yet.';
return { update() {}, destroy: () => ctx.container.replaceChildren() };
}
const opts = (ctx.options ?? {}) as EcOptions;
const dark = ctx.theme === 'dark';
const label = (d: ChartData): string =>
`${opts.title ?? 'Chart'}: ${d.categories.length} categories, ${d.series.length} series`;
ctx.container.setAttribute('role', 'img');
ctx.container.setAttribute('aria-label', label(ctx.getData()));
const fmt = opts.valueFormat;
const base = (d: ChartData): object => ({
title: { text: opts.title ?? '' },
tooltip: {
trigger: ctx.type === 'pie' ? 'item' : 'axis',
...(fmt
? { valueFormatter: (v: unknown) => fmt.replace('{value}', Number(v).toLocaleString()) }
: {}),
},
legend: {},
series: seriesOf(ctx.type, d),
...axesOf(ctx.type, d),
});
const chart = echarts.init(ctx.container, null, { renderer: 'svg' });
chart.setOption(
merge(base(ctx.getData()), themeOptions(ctx.container, dark, ctx.type), opts.echarts),
);
// Follow the grid theme when it changes later.
const retheme = (): void =>
chart.setOption(
themeOptions(ctx.container, document.documentElement.dataset.mxgTheme === 'dark', ctx.type),
);
const watcher = new MutationObserver(retheme);
watcher.observe(document.documentElement, {
attributes: true,
subtree: true,
attributeFilter: ['data-mxg-theme'],
});
return {
update(d) {
ctx.container.setAttribute('aria-label', label(d));
chart.setOption(
{ ...axesOf(ctx.type, d), series: seriesOf(ctx.type, d) },
{ replaceMerge: ['series'] },
);
},
destroy() {
watcher.disconnect();
chart.dispose();
ctx.container.removeAttribute('role');
ctx.container.removeAttribute('aria-label');
},
resize: () => chart.resize(),
};
},
};
/** Small deep merge for plain option objects. */
function merge(...parts: Array<object | undefined>): object {
const out: Record<string, unknown> = {};
for (const part of parts) {
for (const [key, value] of Object.entries(part ?? {})) {
const prev = out[key];
const plain = (v: unknown): v is object =>
typeof v === 'object' && v !== null && !Array.isArray(v);
out[key] = plain(prev) && plain(value) ? merge(prev, value) : value;
}
}
return out;
}
export const options: GridOptions<Row> = {
rowKey: 'id',
columns,
rows,
cellSelection: 'multiple',
selection: 'multiple',
ariaLabel: 'Regional sales by quarter',
chartAdapter: echartsAdapter,
};
let host: HTMLElement | null = null;
let notice: HTMLElement | null = null;
let status: HTMLElement | null = null;
let chart: GridChart | null = null;
let loaded = false;
function ensureHost(): HTMLElement {
if (host !== null) return host;
const first = document.getElementById('grid');
notice = document.createElement('div');
notice.style.cssText =
'margin-top:10px;padding:8px 10px;border:1px solid var(--mxg-border, #d9dee5);border-radius:6px;font-size:13px;color:var(--mxg-fg, #1f2933)';
const text = document.createElement('p');
text.style.margin = '0 0 6px';
text.textContent =
'ECharts is a separate open-source library from the Apache Software Foundation (Apache License 2.0); MaxGrid does not include it. The button below loads it from the jsDelivr CDN (cdn.jsdelivr.net).';
status = document.createElement('p');
status.style.margin = '0';
status.setAttribute('role', 'status');
status.textContent =
'Not loaded yet. Nothing is requested from the network until you press the button.';
notice.append(text, status);
host = document.createElement('div');
host.id = 'chart-host';
host.style.cssText = 'height:260px;margin-top:10px';
if (first !== null) first.after(notice, host);
else document.body.append(notice, host);
return host;
}
function cleanup(): void {
chart?.destroy();
chart = null;
}
function showStatus(message: string): void {
ensureHost();
if (status !== null) status.textContent = message;
}
// If nothing is selected, select the first four rows (region to Q3) so a chart appears at once.
function fromSelection(api: GridApi<Row>, type: ChartType): GridChart | null {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
return api.createChart(ensureHost(), { source: 'selection', type, options: chartOptions });
}
const chartOptions = { title: 'Regional sales by quarter', valueFormat: '{value}' };
/** Nothing is requested from the network until this runs (the button next to the notice). */
function load(log: (message: LogText) => void, then?: () => void): void {
ensureHost();
if (loaded || (window as unknown as { echarts?: unknown }).echarts !== undefined) {
loaded = true;
showStatus('ECharts is loaded.');
then?.();
return;
}
showStatus('Loading ECharts…');
loadECharts(
() => {
loaded = true;
showStatus('ECharts is loaded.');
log('ECharts 6.1.0 loaded.');
then?.();
},
() => {
showStatus(
'Could not load ECharts. Check your connection or Content Security Policy and press the button again.',
);
log('Could not load ECharts (offline or blocked).');
},
);
}
const needLoad = (log: (message: LogText) => void): boolean => {
if (loaded) return false;
showStatus('Press "Load ECharts" first.');
log('Press "Load ECharts" first.');
return true;
};
let say: (message: LogText) => void = () => {};
let currentType: ChartType = 'column';
function rebuild(api: GridApi<Row>): void {
if (needLoad(say)) return;
cleanup();
chart = fromSelection(api, currentType);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
loaded = false;
currentType = 'column';
ensureHost();
const offCreated = api.on('chartCreated', ({ type }) => {
log(`Chart created: ${type}`);
});
log('Press "Load ECharts", then switch the type.');
return () => {
offCreated();
cleanup();
notice?.remove();
host?.remove();
notice = null;
status = null;
host = null;
};
}
export const actions = {
load: (api: GridApi<Row>) => load(say, () => rebuild(api)),
chartType: (api: GridApi<Row>, value?: string) => {
currentType = (value as ChartType | undefined) ?? 'column';
rebuild(api);
},
clear: () => {
cleanup();
},
};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.load(api)"
>Load ECharts</button>
<select
aria-label="Type"
[disabled]="!api"
(change)="api && actions.chartType(api, $any($event.target).value)"
>
<option value="column" selected>Column</option>
<option value="bar">Bar</option>
<option value="line">Line</option>
<option value="area">Area</option>
<option value="pie">Pie</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.clear(api)"
>Clear</button>
</div>
<mx-grid style="height: 520px" [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 {
ChartAdapter,
ChartData,
ChartType,
GridApi,
GridChart,
GridOptions,
} from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
region: string;
q1: number;
q2: number;
q3: number;
q4: number;
note: string;
}
const rows: Row[] = [
{ id: 1, region: 'Seoul', q1: 120, q2: 150, q3: 180, q4: 210, note: 'HQ' },
{ id: 2, region: 'Busan', q1: 90, q2: 110, q3: 140, q4: 130, note: 'Port' },
{ id: 3, region: 'Daegu', q1: 70, q2: 85, q3: 95, q4: 120, note: 'Inland' },
{ id: 4, region: 'Incheon', q1: 100, q2: 130, q3: 125, q4: 160, note: 'Airport' },
{ id: 5, region: 'Gwangju', q1: 60, q2: 75, q3: 90, q4: 80, note: 'Southwest' },
{ id: 6, region: 'Daejeon', q1: 80, q2: 95, q3: 110, q4: 140, note: 'Central' },
{ id: 7, region: 'Ulsan', q1: 110, q2: 105, q3: 150, q4: 170, note: 'Industrial' },
{ id: 8, region: 'Jeju', q1: 50, q2: 65, q3: 70, q4: 95, note: 'Tourism' },
];
const columns: NonNullable<GridOptions<Row>['columns']> = [
{ id: 'region', title: 'Region', width: 110 },
{ id: 'q1', title: 'Q1 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q2', title: 'Q2 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q3', title: 'Q3 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'q4', title: 'Q4 ($K)', kind: 'number', editable: true, width: 120 },
{ id: 'note', title: 'Note', editable: true, width: 110 },
];
// ── ECharts adapter recipe ───────────────────────────────────────────────────
// MaxGrid ships no chart library. This adapter maps ChartContext -> ECharts and back.
type EcChart = {
setOption(option: object, opts?: { replaceMerge?: string[] }): void;
dispose(): void;
resize(): void;
};
type EcStatic = {
init(el: HTMLElement, theme?: null, opts?: { renderer: 'svg' | 'canvas' }): EcChart;
};
type EcOptions = { title?: string; valueFormat?: string; echarts?: object };
const EC_VERSION = '6.1.0';
const EC_URL = `https://cdn.jsdelivr.net/npm/echarts@${EC_VERSION}/dist/echarts.min.js`;
const EC_SRI = 'sha384-C2iskrW/uPW46KzOjrvJIQo4YkV8lkD+QS0CrDN18IIPIpT/g2USu8bTP3nvmIAD';
const ec = (): EcStatic | undefined => (window as unknown as { echarts?: EcStatic }).echarts;
/** Reads the grid theme from its CSS variables (falls back to light/dark defaults). */
function themeOptions(el: HTMLElement, dark: boolean, type: ChartType): object {
const css = getComputedStyle(el);
const read = (name: string, fallback: string): string =>
css.getPropertyValue(name).trim() || fallback;
const bg = read('--mxg-bg', dark ? '#151a21' : '#ffffff');
const fg = read('--mxg-fg', dark ? '#e6e9ee' : '#1f2933');
const line = read('--mxg-border', dark ? '#323b47' : '#d9dee5');
const axis = {
axisLabel: { color: fg },
axisLine: { lineStyle: { color: line } },
axisTick: { lineStyle: { color: line } },
splitLine: { lineStyle: { color: line } },
};
return {
backgroundColor: bg,
textStyle: { color: fg },
title: { textStyle: { color: fg } },
legend: { textStyle: { color: fg } },
tooltip: { backgroundColor: bg, borderColor: line, textStyle: { color: fg } },
// a pie chart has no axes: do not add any
...(type === 'pie' ? {} : { xAxis: axis, yAxis: axis }),
};
}
/** Our ChartData -> ECharts series. Pie uses the first series; null values stay gaps. */
function seriesOf(type: ChartType, data: ChartData): object[] {
if (type === 'pie') {
const first = data.series[0];
return [
{
type: 'pie',
name: first?.name ?? '',
radius: '65%',
data: data.categories.map((name, i) => ({ name, value: first?.values[i] ?? null })),
},
];
}
return data.series.map((s) => ({
type: type === 'column' || type === 'bar' ? 'bar' : 'line',
name: s.name,
data: s.values,
...(type === 'area' ? { areaStyle: {} } : {}),
}));
}
/** Axes: a horizontal bar chart swaps the category and value axis. Pie has none. */
function axesOf(type: ChartType, data: ChartData): object {
if (type === 'pie') return {};
const category = { type: 'category', data: data.categories };
const value = { type: 'value' };
return type === 'bar' ? { xAxis: value, yAxis: category } : { xAxis: category, yAxis: value };
}
function loadECharts(onReady: () => void, onError: () => void): void {
if (ec() !== undefined) return onReady();
let script = document.querySelector<HTMLScriptElement>('script[data-echarts]');
if (script === null) {
script = document.createElement('script');
script.src = EC_URL;
script.integrity = EC_SRI; // the pinned file must match, or the browser refuses it
script.crossOrigin = 'anonymous';
script.dataset.echarts = '1';
document.head.append(script);
}
script.addEventListener('load', onReady, { once: true });
script.addEventListener(
'error',
() => {
script?.remove(); // allow another try
onError();
},
{ once: true },
);
}
const echartsAdapter: ChartAdapter = {
create(ctx) {
const echarts = ec();
if (echarts === undefined) {
ctx.container.textContent = 'ECharts is not loaded yet.';
return { update() {}, destroy: () => ctx.container.replaceChildren() };
}
const opts = (ctx.options ?? {}) as EcOptions;
const dark = ctx.theme === 'dark';
const label = (d: ChartData): string =>
`${opts.title ?? 'Chart'}: ${d.categories.length} categories, ${d.series.length} series`;
ctx.container.setAttribute('role', 'img');
ctx.container.setAttribute('aria-label', label(ctx.getData()));
const fmt = opts.valueFormat;
const base = (d: ChartData): object => ({
title: { text: opts.title ?? '' },
tooltip: {
trigger: ctx.type === 'pie' ? 'item' : 'axis',
...(fmt
? { valueFormatter: (v: unknown) => fmt.replace('{value}', Number(v).toLocaleString()) }
: {}),
},
legend: {},
series: seriesOf(ctx.type, d),
...axesOf(ctx.type, d),
});
const chart = echarts.init(ctx.container, null, { renderer: 'svg' });
chart.setOption(
merge(base(ctx.getData()), themeOptions(ctx.container, dark, ctx.type), opts.echarts),
);
// Follow the grid theme when it changes later.
const retheme = (): void =>
chart.setOption(
themeOptions(ctx.container, document.documentElement.dataset.mxgTheme === 'dark', ctx.type),
);
const watcher = new MutationObserver(retheme);
watcher.observe(document.documentElement, {
attributes: true,
subtree: true,
attributeFilter: ['data-mxg-theme'],
});
return {
update(d) {
ctx.container.setAttribute('aria-label', label(d));
chart.setOption(
{ ...axesOf(ctx.type, d), series: seriesOf(ctx.type, d) },
{ replaceMerge: ['series'] },
);
},
destroy() {
watcher.disconnect();
chart.dispose();
ctx.container.removeAttribute('role');
ctx.container.removeAttribute('aria-label');
},
resize: () => chart.resize(),
};
},
};
/** Small deep merge for plain option objects. */
function merge(...parts: Array<object | undefined>): object {
const out: Record<string, unknown> = {};
for (const part of parts) {
for (const [key, value] of Object.entries(part ?? {})) {
const prev = out[key];
const plain = (v: unknown): v is object =>
typeof v === 'object' && v !== null && !Array.isArray(v);
out[key] = plain(prev) && plain(value) ? merge(prev, value) : value;
}
}
return out;
}
export const options: GridOptions<Row> = {
rowKey: 'id',
columns,
rows,
cellSelection: 'multiple',
selection: 'multiple',
ariaLabel: 'Regional sales by quarter',
chartAdapter: echartsAdapter,
};
let host: HTMLElement | null = null;
let notice: HTMLElement | null = null;
let status: HTMLElement | null = null;
let chart: GridChart | null = null;
let loaded = false;
function ensureHost(): HTMLElement {
if (host !== null) return host;
const first = document.getElementById('grid');
notice = document.createElement('div');
notice.style.cssText =
'margin-top:10px;padding:8px 10px;border:1px solid var(--mxg-border, #d9dee5);border-radius:6px;font-size:13px;color:var(--mxg-fg, #1f2933)';
const text = document.createElement('p');
text.style.margin = '0 0 6px';
text.textContent =
'ECharts is a separate open-source library from the Apache Software Foundation (Apache License 2.0); MaxGrid does not include it. The button below loads it from the jsDelivr CDN (cdn.jsdelivr.net).';
status = document.createElement('p');
status.style.margin = '0';
status.setAttribute('role', 'status');
status.textContent =
'Not loaded yet. Nothing is requested from the network until you press the button.';
notice.append(text, status);
host = document.createElement('div');
host.id = 'chart-host';
host.style.cssText = 'height:260px;margin-top:10px';
if (first !== null) first.after(notice, host);
else document.body.append(notice, host);
return host;
}
function cleanup(): void {
chart?.destroy();
chart = null;
}
function showStatus(message: string): void {
ensureHost();
if (status !== null) status.textContent = message;
}
// If nothing is selected, select the first four rows (region to Q3) so a chart appears at once.
function fromSelection(api: GridApi<Row>, type: ChartType): GridChart | null {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
return api.createChart(ensureHost(), { source: 'selection', type, options: chartOptions });
}
const chartOptions = { title: 'Regional sales by quarter', valueFormat: '{value}' };
/** Nothing is requested from the network until this runs (the button next to the notice). */
function load(log: (message: LogText) => void, then?: () => void): void {
ensureHost();
if (loaded || (window as unknown as { echarts?: unknown }).echarts !== undefined) {
loaded = true;
showStatus('ECharts is loaded.');
then?.();
return;
}
showStatus('Loading ECharts…');
loadECharts(
() => {
loaded = true;
showStatus('ECharts is loaded.');
log('ECharts 6.1.0 loaded.');
then?.();
},
() => {
showStatus(
'Could not load ECharts. Check your connection or Content Security Policy and press the button again.',
);
log('Could not load ECharts (offline or blocked).');
},
);
}
const needLoad = (log: (message: LogText) => void): boolean => {
if (loaded) return false;
showStatus('Press "Load ECharts" first.');
log('Press "Load ECharts" first.');
return true;
};
let say: (message: LogText) => void = () => {};
let currentType: ChartType = 'column';
function rebuild(api: GridApi<Row>): void {
if (needLoad(say)) return;
cleanup();
chart = fromSelection(api, currentType);
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
loaded = false;
currentType = 'column';
ensureHost();
const offCreated = api.on('chartCreated', ({ type }) => {
log(`Chart created: ${type}`);
});
log('Press "Load ECharts", then switch the type.');
return () => {
offCreated();
cleanup();
notice?.remove();
host?.remove();
notice = null;
status = null;
host = null;
};
}
export const actions = {
load: (api: GridApi<Row>) => load(say, () => rebuild(api)),
chartType: (api: GridApi<Row>, value?: string) => {
currentType = (value as ChartType | undefined) ?? 'column';
rebuild(api);
},
clear: () => {
cleanup();
},
};