값이 계속 바뀌는 표: 바뀐 줄 강조A table whose values keep changing: highlight changed rows
서버에서 새 값이 계속 들어오는 상황을 흉내 내요. 바뀐 줄은 주황빛으로 잠깐 칠해졌다가 서서히 사라져요. 서버가 보낸 값은 직접 고친 값(칸 모서리 표시)과 달리 '고친 곳'으로 쌓이지 않아요.Simulates new values arriving from a server. Changed rows flash orange and fade out. Values pushed by the server are not counted as your own edits (the corner mark).
코드Code
탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.
이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft' (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft' (without them in your code you get the default look)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<div id="app">
<div class="toolbar">
<button type="button" id="pause">멈추기</button>
<button type="button" id="resume">다시 시작</button>
<select aria-label="갱신 간격" id="speed">
<option value="300">0.3초</option>
<option value="1000" selected>1초 (기본)</option>
<option value="2000">2초</option>
</select>
</div>
<div id="grid" style="height: 320px"></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('pause').addEventListener('click', () => actions.pause(api));
document.getElementById('resume').addEventListener('click', () => actions.resume(api));
document.getElementById('speed').addEventListener('change', (event) => actions.speed(api, event.target.value));const signed = (value) => `${Number(value) > 0 ? '+' : ''}${Number(value)}`;
const flashing = new Set();
const SYMBOLS = ['한빛전자', '푸른제약', '북극성화학', '다온건설', '새벽식품', '모아패션'];
export const options = {
columns: [
{ id: 'symbol', title: '종목', width: 130, editable: true },
{
id: 'price',
title: '현재가',
kind: 'number',
width: 110,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
{
id: 'change',
title: '등락',
kind: 'number',
width: 100,
align: 'end',
getValue: (row) => row.price - row.prev,
formatValue: signed,
},
],
rows: SYMBOLS.map((symbol, i) => ({
id: i + 1,
symbol,
price: 10000 + i * 1500,
prev: 10000 + i * 1500,
})),
rowKey: 'id',
rowClass: (row) => (flashing.has(row.id) ? 'lu-flash' : undefined),
};
let timer;
let periodMs = 1000;
let tick = 0;
let say = () => { };
// 멈추기는 돌아가는 중에만, 다시 시작은 멈춘 뒤에만 누를 수 있게 버튼을 맞춰요.
function syncButtons() {
const pause = document.getElementById('pause');
const resume = document.getElementById('resume');
if (pause instanceof HTMLButtonElement)
pause.disabled = timer === undefined;
if (resume instanceof HTMLButtonElement)
resume.disabled = timer !== undefined;
}
function stop() {
clearInterval(timer);
timer = undefined;
syncButtons();
}
function start(api) {
stop();
timer = setInterval(() => {
if (api.isDestroyed())
return stop();
tick += 1;
// 난수 대신 정해진 규칙으로 두 줄을 골라서, 언제 열어도 같은 모습이에요.
const picks = [(tick * 3) % 6, (tick * 5 + 1) % 6];
const changed = picks.flatMap((index) => {
const row = api.getRows()[index];
if (!row)
return [];
const delta = ((tick + index) % 2 === 0 ? 1 : -1) * (100 + ((tick * 7) % 40) * 10);
return [{ ...row, prev: row.price, price: row.price + delta }];
});
// 서버가 보낸 값은 mergeRows로 합쳐요. 사용자가 직접 고친 값(칸 모서리 표시)과 달리 '고친 곳'으로 쌓이지 않아요.
api.mergeRows(changed);
for (const row of changed)
flashing.add(row.id);
api.refresh();
setTimeout(() => {
if (api.isDestroyed())
return;
for (const row of changed)
flashing.delete(row.id);
api.refresh();
}, 600);
}, periodMs);
syncButtons();
}
// 방금 바뀐 줄은 주황빛으로 칠했다가 서서히 사라져요(배경 색에 0.6초 전환을 주고, 타이머가 클래스를 지워요).
const CSS = `
.mxg-row { transition: background-color 0.6s ease; }
.mxg-row.lu-flash { background: color-mix(in srgb, #f5a524 38%, transparent); }
@media (prefers-reduced-motion: reduce) { .mxg-row { transition: none; } }
`;
export function setup(api, log) {
say = log;
const style = document.createElement('style');
style.textContent = CSS;
document.head.append(style);
tick = 0;
periodMs = 1000;
start(api);
log({
ko: '1초마다 두 종목의 값이 바뀌어요. 종목 이름을 두 번 눌러 직접 고쳐 보세요',
en: 'The values of two stocks change every second. Double-click a stock name to edit it yourself',
});
return () => {
stop();
flashing.clear();
style.remove();
};
}
export const actions = {
pause: () => {
stop();
say({ ko: '멈췄어요', en: 'Paused' });
},
resume: (api) => {
start(api);
say({ ko: '다시 시작했어요', en: 'Resumed' });
},
speed: (api, value) => {
periodMs = Number(value) || 1000;
if (timer !== undefined)
start(api);
say({ ko: `${periodMs / 1000}초마다 바꿔요`, en: `Changes every ${periodMs / 1000} s` });
},
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>값이 계속 바뀌는 표: 바뀐 줄 강조</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="pause">멈추기</button>
<button type="button" id="resume">다시 시작</button>
<select aria-label="갱신 간격" id="speed">
<option value="300">0.3초</option>
<option value="1000" selected>1초 (기본)</option>
<option value="2000">2초</option>
</select>
</div>
<div id="grid" style="height: 320px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const signed = (value) => `${Number(value) > 0 ? '+' : ''}${Number(value)}`;
const flashing = new Set();
const SYMBOLS = ['한빛전자', '푸른제약', '북극성화학', '다온건설', '새벽식품', '모아패션'];
const options = {
columns: [
{ id: 'symbol', title: '종목', width: 130, editable: true },
{
id: 'price',
title: '현재가',
kind: 'number',
width: 110,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
{
id: 'change',
title: '등락',
kind: 'number',
width: 100,
align: 'end',
getValue: (row) => row.price - row.prev,
formatValue: signed,
},
],
rows: SYMBOLS.map((symbol, i) => ({
id: i + 1,
symbol,
price: 10000 + i * 1500,
prev: 10000 + i * 1500,
})),
rowKey: 'id',
rowClass: (row) => (flashing.has(row.id) ? 'lu-flash' : undefined),
};
let timer;
let periodMs = 1000;
let tick = 0;
let say = () => { };
// 멈추기는 돌아가는 중에만, 다시 시작은 멈춘 뒤에만 누를 수 있게 버튼을 맞춰요.
function syncButtons() {
const pause = document.getElementById('pause');
const resume = document.getElementById('resume');
if (pause instanceof HTMLButtonElement)
pause.disabled = timer === undefined;
if (resume instanceof HTMLButtonElement)
resume.disabled = timer !== undefined;
}
function stop() {
clearInterval(timer);
timer = undefined;
syncButtons();
}
function start(api) {
stop();
timer = setInterval(() => {
if (api.isDestroyed())
return stop();
tick += 1;
// 난수 대신 정해진 규칙으로 두 줄을 골라서, 언제 열어도 같은 모습이에요.
const picks = [(tick * 3) % 6, (tick * 5 + 1) % 6];
const changed = picks.flatMap((index) => {
const row = api.getRows()[index];
if (!row)
return [];
const delta = ((tick + index) % 2 === 0 ? 1 : -1) * (100 + ((tick * 7) % 40) * 10);
return [{ ...row, prev: row.price, price: row.price + delta }];
});
// 서버가 보낸 값은 mergeRows로 합쳐요. 사용자가 직접 고친 값(칸 모서리 표시)과 달리 '고친 곳'으로 쌓이지 않아요.
api.mergeRows(changed);
for (const row of changed)
flashing.add(row.id);
api.refresh();
setTimeout(() => {
if (api.isDestroyed())
return;
for (const row of changed)
flashing.delete(row.id);
api.refresh();
}, 600);
}, periodMs);
syncButtons();
}
// 방금 바뀐 줄은 주황빛으로 칠했다가 서서히 사라져요(배경 색에 0.6초 전환을 주고, 타이머가 클래스를 지워요).
const CSS = `
.mxg-row { transition: background-color 0.6s ease; }
.mxg-row.lu-flash { background: color-mix(in srgb, #f5a524 38%, transparent); }
@media (prefers-reduced-motion: reduce) { .mxg-row { transition: none; } }
`;
function setup(api, log) {
say = log;
const style = document.createElement('style');
style.textContent = CSS;
document.head.append(style);
tick = 0;
periodMs = 1000;
start(api);
log({
ko: '1초마다 두 종목의 값이 바뀌어요. 종목 이름을 두 번 눌러 직접 고쳐 보세요',
en: 'The values of two stocks change every second. Double-click a stock name to edit it yourself',
});
return () => {
stop();
flashing.clear();
style.remove();
};
}
const actions = {
pause: () => {
stop();
say({ ko: '멈췄어요', en: 'Paused' });
},
resume: (api) => {
start(api);
say({ ko: '다시 시작했어요', en: 'Resumed' });
},
speed: (api, value) => {
periodMs = Number(value) || 1000;
if (timer !== undefined)
start(api);
say({ ko: `${periodMs / 1000}초마다 바꿔요`, en: `Changes every ${periodMs / 1000} s` });
},
};
options.ariaLabel = "값이 계속 바뀌는 표: 바뀐 줄 강조";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('pause').addEventListener('click', () => actions.pause(api));
document.getElementById('resume').addEventListener('click', () => actions.resume(api));
document.getElementById('speed').addEventListener('change', (event) => actions.speed(api, event.target.value));
</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.pause(api)}
>멈추기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.resume(api)}
>다시 시작</button>
<select
aria-label="갱신 간격"
disabled={!api}
onChange={(event) => api && actions.speed(api, event.target.value)}
>
<option value="300">0.3초</option>
<option value="1000">1초 (기본)</option>
<option value="2000">2초</option>
</select>
</div>
<Grid style={{ height: 320 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
symbol: string;
price: number;
prev: number;
}
const signed = (value: unknown): string => `${Number(value) > 0 ? '+' : ''}${Number(value)}`;
const flashing = new Set<number>();
const SYMBOLS = ['한빛전자', '푸른제약', '북극성화학', '다온건설', '새벽식품', '모아패션'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'symbol', title: '종목', width: 130, editable: true },
{
id: 'price',
title: '현재가',
kind: 'number',
width: 110,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
{
id: 'change',
title: '등락',
kind: 'number',
width: 100,
align: 'end',
getValue: (row) => row.price - row.prev,
formatValue: signed,
},
],
rows: SYMBOLS.map((symbol, i) => ({
id: i + 1,
symbol,
price: 10000 + i * 1500,
prev: 10000 + i * 1500,
})),
rowKey: 'id',
rowClass: (row) => (flashing.has(row.id) ? 'lu-flash' : undefined),
};
let timer: ReturnType<typeof setInterval> | undefined;
let periodMs = 1000;
let tick = 0;
let say: (message: LogText) => void = () => {};
// 멈추기는 돌아가는 중에만, 다시 시작은 멈춘 뒤에만 누를 수 있게 버튼을 맞춰요.
function syncButtons(): void {
const pause = document.getElementById('pause');
const resume = document.getElementById('resume');
if (pause instanceof HTMLButtonElement) pause.disabled = timer === undefined;
if (resume instanceof HTMLButtonElement) resume.disabled = timer !== undefined;
}
function stop(): void {
clearInterval(timer);
timer = undefined;
syncButtons();
}
function start(api: GridApi<Row>): void {
stop();
timer = setInterval(() => {
if (api.isDestroyed()) return stop();
tick += 1;
// 난수 대신 정해진 규칙으로 두 줄을 골라서, 언제 열어도 같은 모습이에요.
const picks = [(tick * 3) % 6, (tick * 5 + 1) % 6];
const changed = picks.flatMap((index) => {
const row = api.getRows()[index];
if (!row) return [];
const delta = ((tick + index) % 2 === 0 ? 1 : -1) * (100 + ((tick * 7) % 40) * 10);
return [{ ...row, prev: row.price, price: row.price + delta }];
});
// 서버가 보낸 값은 mergeRows로 합쳐요. 사용자가 직접 고친 값(칸 모서리 표시)과 달리 '고친 곳'으로 쌓이지 않아요.
api.mergeRows(changed);
for (const row of changed) flashing.add(row.id);
api.refresh();
setTimeout(() => {
if (api.isDestroyed()) return;
for (const row of changed) flashing.delete(row.id);
api.refresh();
}, 600);
}, periodMs);
syncButtons();
}
// 방금 바뀐 줄은 주황빛으로 칠했다가 서서히 사라져요(배경 색에 0.6초 전환을 주고, 타이머가 클래스를 지워요).
const CSS = `
.mxg-row { transition: background-color 0.6s ease; }
.mxg-row.lu-flash { background: color-mix(in srgb, #f5a524 38%, transparent); }
@media (prefers-reduced-motion: reduce) { .mxg-row { transition: none; } }
`;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const style = document.createElement('style');
style.textContent = CSS;
document.head.append(style);
tick = 0;
periodMs = 1000;
start(api);
log({
ko: '1초마다 두 종목의 값이 바뀌어요. 종목 이름을 두 번 눌러 직접 고쳐 보세요',
en: 'The values of two stocks change every second. Double-click a stock name to edit it yourself',
});
return () => {
stop();
flashing.clear();
style.remove();
};
}
export const actions = {
pause: () => {
stop();
say({ ko: '멈췄어요', en: 'Paused' });
},
resume: (api: GridApi<Row>) => {
start(api);
say({ ko: '다시 시작했어요', en: 'Resumed' });
},
speed: (api: GridApi<Row>, value?: string) => {
periodMs = Number(value) || 1000;
if (timer !== undefined) start(api);
say({ ko: `${periodMs / 1000}초마다 바꿔요`, en: `Changes every ${periodMs / 1000} s` });
},
};버튼을 누르면 이 예제의 코드가 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.pause(api)">멈추기</button>
<button type="button" :disabled="!api" @click="api && actions.resume(api)">다시 시작</button>
<select
aria-label="갱신 간격"
:disabled="!api"
@change="api && actions.speed(api, ($event.target as HTMLSelectElement).value)"
>
<option value="300">0.3초</option>
<option value="1000" selected>1초 (기본)</option>
<option value="2000">2초</option>
</select>
</div>
<Grid style="height: 320px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
symbol: string;
price: number;
prev: number;
}
const signed = (value: unknown): string => `${Number(value) > 0 ? '+' : ''}${Number(value)}`;
const flashing = new Set<number>();
const SYMBOLS = ['한빛전자', '푸른제약', '북극성화학', '다온건설', '새벽식품', '모아패션'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'symbol', title: '종목', width: 130, editable: true },
{
id: 'price',
title: '현재가',
kind: 'number',
width: 110,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
{
id: 'change',
title: '등락',
kind: 'number',
width: 100,
align: 'end',
getValue: (row) => row.price - row.prev,
formatValue: signed,
},
],
rows: SYMBOLS.map((symbol, i) => ({
id: i + 1,
symbol,
price: 10000 + i * 1500,
prev: 10000 + i * 1500,
})),
rowKey: 'id',
rowClass: (row) => (flashing.has(row.id) ? 'lu-flash' : undefined),
};
let timer: ReturnType<typeof setInterval> | undefined;
let periodMs = 1000;
let tick = 0;
let say: (message: LogText) => void = () => {};
// 멈추기는 돌아가는 중에만, 다시 시작은 멈춘 뒤에만 누를 수 있게 버튼을 맞춰요.
function syncButtons(): void {
const pause = document.getElementById('pause');
const resume = document.getElementById('resume');
if (pause instanceof HTMLButtonElement) pause.disabled = timer === undefined;
if (resume instanceof HTMLButtonElement) resume.disabled = timer !== undefined;
}
function stop(): void {
clearInterval(timer);
timer = undefined;
syncButtons();
}
function start(api: GridApi<Row>): void {
stop();
timer = setInterval(() => {
if (api.isDestroyed()) return stop();
tick += 1;
// 난수 대신 정해진 규칙으로 두 줄을 골라서, 언제 열어도 같은 모습이에요.
const picks = [(tick * 3) % 6, (tick * 5 + 1) % 6];
const changed = picks.flatMap((index) => {
const row = api.getRows()[index];
if (!row) return [];
const delta = ((tick + index) % 2 === 0 ? 1 : -1) * (100 + ((tick * 7) % 40) * 10);
return [{ ...row, prev: row.price, price: row.price + delta }];
});
// 서버가 보낸 값은 mergeRows로 합쳐요. 사용자가 직접 고친 값(칸 모서리 표시)과 달리 '고친 곳'으로 쌓이지 않아요.
api.mergeRows(changed);
for (const row of changed) flashing.add(row.id);
api.refresh();
setTimeout(() => {
if (api.isDestroyed()) return;
for (const row of changed) flashing.delete(row.id);
api.refresh();
}, 600);
}, periodMs);
syncButtons();
}
// 방금 바뀐 줄은 주황빛으로 칠했다가 서서히 사라져요(배경 색에 0.6초 전환을 주고, 타이머가 클래스를 지워요).
const CSS = `
.mxg-row { transition: background-color 0.6s ease; }
.mxg-row.lu-flash { background: color-mix(in srgb, #f5a524 38%, transparent); }
@media (prefers-reduced-motion: reduce) { .mxg-row { transition: none; } }
`;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const style = document.createElement('style');
style.textContent = CSS;
document.head.append(style);
tick = 0;
periodMs = 1000;
start(api);
log({
ko: '1초마다 두 종목의 값이 바뀌어요. 종목 이름을 두 번 눌러 직접 고쳐 보세요',
en: 'The values of two stocks change every second. Double-click a stock name to edit it yourself',
});
return () => {
stop();
flashing.clear();
style.remove();
};
}
export const actions = {
pause: () => {
stop();
say({ ko: '멈췄어요', en: 'Paused' });
},
resume: (api: GridApi<Row>) => {
start(api);
say({ ko: '다시 시작했어요', en: 'Resumed' });
},
speed: (api: GridApi<Row>, value?: string) => {
periodMs = Number(value) || 1000;
if (timer !== undefined) start(api);
say({ ko: `${periodMs / 1000}초마다 바꿔요`, en: `Changes every ${periodMs / 1000} s` });
},
};버튼을 누르면 이 예제의 코드가 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.pause(api)"
>멈추기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.resume(api)"
>다시 시작</button>
<select
aria-label="갱신 간격"
[disabled]="!api"
(change)="api && actions.speed(api, $any($event.target).value)"
>
<option value="300">0.3초</option>
<option value="1000" selected>1초 (기본)</option>
<option value="2000">2초</option>
</select>
</div>
<mx-grid style="height: 320px" [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 { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
symbol: string;
price: number;
prev: number;
}
const signed = (value: unknown): string => `${Number(value) > 0 ? '+' : ''}${Number(value)}`;
const flashing = new Set<number>();
const SYMBOLS = ['한빛전자', '푸른제약', '북극성화학', '다온건설', '새벽식품', '모아패션'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'symbol', title: '종목', width: 130, editable: true },
{
id: 'price',
title: '현재가',
kind: 'number',
width: 110,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
{
id: 'change',
title: '등락',
kind: 'number',
width: 100,
align: 'end',
getValue: (row) => row.price - row.prev,
formatValue: signed,
},
],
rows: SYMBOLS.map((symbol, i) => ({
id: i + 1,
symbol,
price: 10000 + i * 1500,
prev: 10000 + i * 1500,
})),
rowKey: 'id',
rowClass: (row) => (flashing.has(row.id) ? 'lu-flash' : undefined),
};
let timer: ReturnType<typeof setInterval> | undefined;
let periodMs = 1000;
let tick = 0;
let say: (message: LogText) => void = () => {};
// 멈추기는 돌아가는 중에만, 다시 시작은 멈춘 뒤에만 누를 수 있게 버튼을 맞춰요.
function syncButtons(): void {
const pause = document.getElementById('pause');
const resume = document.getElementById('resume');
if (pause instanceof HTMLButtonElement) pause.disabled = timer === undefined;
if (resume instanceof HTMLButtonElement) resume.disabled = timer !== undefined;
}
function stop(): void {
clearInterval(timer);
timer = undefined;
syncButtons();
}
function start(api: GridApi<Row>): void {
stop();
timer = setInterval(() => {
if (api.isDestroyed()) return stop();
tick += 1;
// 난수 대신 정해진 규칙으로 두 줄을 골라서, 언제 열어도 같은 모습이에요.
const picks = [(tick * 3) % 6, (tick * 5 + 1) % 6];
const changed = picks.flatMap((index) => {
const row = api.getRows()[index];
if (!row) return [];
const delta = ((tick + index) % 2 === 0 ? 1 : -1) * (100 + ((tick * 7) % 40) * 10);
return [{ ...row, prev: row.price, price: row.price + delta }];
});
// 서버가 보낸 값은 mergeRows로 합쳐요. 사용자가 직접 고친 값(칸 모서리 표시)과 달리 '고친 곳'으로 쌓이지 않아요.
api.mergeRows(changed);
for (const row of changed) flashing.add(row.id);
api.refresh();
setTimeout(() => {
if (api.isDestroyed()) return;
for (const row of changed) flashing.delete(row.id);
api.refresh();
}, 600);
}, periodMs);
syncButtons();
}
// 방금 바뀐 줄은 주황빛으로 칠했다가 서서히 사라져요(배경 색에 0.6초 전환을 주고, 타이머가 클래스를 지워요).
const CSS = `
.mxg-row { transition: background-color 0.6s ease; }
.mxg-row.lu-flash { background: color-mix(in srgb, #f5a524 38%, transparent); }
@media (prefers-reduced-motion: reduce) { .mxg-row { transition: none; } }
`;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const style = document.createElement('style');
style.textContent = CSS;
document.head.append(style);
tick = 0;
periodMs = 1000;
start(api);
log({
ko: '1초마다 두 종목의 값이 바뀌어요. 종목 이름을 두 번 눌러 직접 고쳐 보세요',
en: 'The values of two stocks change every second. Double-click a stock name to edit it yourself',
});
return () => {
stop();
flashing.clear();
style.remove();
};
}
export const actions = {
pause: () => {
stop();
say({ ko: '멈췄어요', en: 'Paused' });
},
resume: (api: GridApi<Row>) => {
start(api);
say({ ko: '다시 시작했어요', en: 'Resumed' });
},
speed: (api: GridApi<Row>, value?: string) => {
periodMs = Number(value) || 1000;
if (timer !== undefined) start(api);
say({ ko: `${periodMs / 1000}초마다 바꿔요`, en: `Changes every ${periodMs / 1000} s` });
},
};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="pause">Pause</button>
<button type="button" id="resume">Resume</button>
<select aria-label="Interval" id="speed">
<option value="300">0.3 s</option>
<option value="1000" selected>1 s (default)</option>
<option value="2000">2 s</option>
</select>
</div>
<div id="grid" style="height: 320px"></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('pause').addEventListener('click', () => actions.pause(api));
document.getElementById('resume').addEventListener('click', () => actions.resume(api));
document.getElementById('speed').addEventListener('change', (event) => actions.speed(api, event.target.value));const signed = (value) => `${Number(value) > 0 ? '+' : ''}${Number(value)}`;
const flashing = new Set();
const SYMBOLS = [
'Northwind Tech',
'Bluesky Pharma',
'Polaris Chemical',
'Harmony Build',
'Dawn Foods',
'Mode Fashion',
];
export const options = {
columns: [
{ id: 'symbol', title: 'Stock', width: 150, editable: true },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 110,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
{
id: 'change',
title: 'Change',
kind: 'number',
width: 100,
align: 'end',
getValue: (row) => row.price - row.prev,
formatValue: signed,
},
],
rows: SYMBOLS.map((symbol, i) => ({
id: i + 1,
symbol,
price: 10000 + i * 1500,
prev: 10000 + i * 1500,
})),
rowKey: 'id',
rowClass: (row) => (flashing.has(row.id) ? 'lu-flash' : undefined),
};
let timer;
let periodMs = 1000;
let tick = 0;
let say = () => { };
// Keep the buttons in step: Pause can be pressed only while running, and Resume only after pausing.
function syncButtons() {
const pause = document.getElementById('pause');
const resume = document.getElementById('resume');
if (pause instanceof HTMLButtonElement)
pause.disabled = timer === undefined;
if (resume instanceof HTMLButtonElement)
resume.disabled = timer !== undefined;
}
function stop() {
clearInterval(timer);
timer = undefined;
syncButtons();
}
function start(api) {
stop();
timer = setInterval(() => {
if (api.isDestroyed())
return stop();
tick += 1;
// Pick two rows by a fixed rule instead of random numbers, so it looks the same whenever you open it.
const picks = [(tick * 3) % 6, (tick * 5 + 1) % 6];
const changed = picks.flatMap((index) => {
const row = api.getRows()[index];
if (!row)
return [];
const delta = ((tick + index) % 2 === 0 ? 1 : -1) * (100 + ((tick * 7) % 40) * 10);
return [{ ...row, prev: row.price, price: row.price + delta }];
});
// Values sent by the server are merged with mergeRows. Unlike values the user edits by hand (the cell corner mark), they do not pile up as 'edited'.
api.mergeRows(changed);
for (const row of changed)
flashing.add(row.id);
api.refresh();
setTimeout(() => {
if (api.isDestroyed())
return;
for (const row of changed)
flashing.delete(row.id);
api.refresh();
}, 600);
}, periodMs);
syncButtons();
}
// A row that just changed is painted orange and fades away (the background color gets a 0.6 s transition and a timer removes the class).
const CSS = `
.mxg-row { transition: background-color 0.6s ease; }
.mxg-row.lu-flash { background: color-mix(in srgb, #f5a524 38%, transparent); }
@media (prefers-reduced-motion: reduce) { .mxg-row { transition: none; } }
`;
export function setup(api, log) {
say = log;
const style = document.createElement('style');
style.textContent = CSS;
document.head.append(style);
tick = 0;
periodMs = 1000;
start(api);
log('The values of two stocks change every second. Double-click a stock name to edit it yourself');
return () => {
stop();
flashing.clear();
style.remove();
};
}
export const actions = {
pause: () => {
stop();
say('Paused');
},
resume: (api) => {
start(api);
say('Resumed');
},
speed: (api, value) => {
periodMs = Number(value) || 1000;
if (timer !== undefined)
start(api);
say(`Changes every ${periodMs / 1000} s`);
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>A table whose values keep changing: highlight changed rows</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="pause">Pause</button>
<button type="button" id="resume">Resume</button>
<select aria-label="Interval" id="speed">
<option value="300">0.3 s</option>
<option value="1000" selected>1 s (default)</option>
<option value="2000">2 s</option>
</select>
</div>
<div id="grid" style="height: 320px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const signed = (value) => `${Number(value) > 0 ? '+' : ''}${Number(value)}`;
const flashing = new Set();
const SYMBOLS = [
'Northwind Tech',
'Bluesky Pharma',
'Polaris Chemical',
'Harmony Build',
'Dawn Foods',
'Mode Fashion',
];
const options = {
columns: [
{ id: 'symbol', title: 'Stock', width: 150, editable: true },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 110,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
{
id: 'change',
title: 'Change',
kind: 'number',
width: 100,
align: 'end',
getValue: (row) => row.price - row.prev,
formatValue: signed,
},
],
rows: SYMBOLS.map((symbol, i) => ({
id: i + 1,
symbol,
price: 10000 + i * 1500,
prev: 10000 + i * 1500,
})),
rowKey: 'id',
rowClass: (row) => (flashing.has(row.id) ? 'lu-flash' : undefined),
};
let timer;
let periodMs = 1000;
let tick = 0;
let say = () => { };
// Keep the buttons in step: Pause can be pressed only while running, and Resume only after pausing.
function syncButtons() {
const pause = document.getElementById('pause');
const resume = document.getElementById('resume');
if (pause instanceof HTMLButtonElement)
pause.disabled = timer === undefined;
if (resume instanceof HTMLButtonElement)
resume.disabled = timer !== undefined;
}
function stop() {
clearInterval(timer);
timer = undefined;
syncButtons();
}
function start(api) {
stop();
timer = setInterval(() => {
if (api.isDestroyed())
return stop();
tick += 1;
// Pick two rows by a fixed rule instead of random numbers, so it looks the same whenever you open it.
const picks = [(tick * 3) % 6, (tick * 5 + 1) % 6];
const changed = picks.flatMap((index) => {
const row = api.getRows()[index];
if (!row)
return [];
const delta = ((tick + index) % 2 === 0 ? 1 : -1) * (100 + ((tick * 7) % 40) * 10);
return [{ ...row, prev: row.price, price: row.price + delta }];
});
// Values sent by the server are merged with mergeRows. Unlike values the user edits by hand (the cell corner mark), they do not pile up as 'edited'.
api.mergeRows(changed);
for (const row of changed)
flashing.add(row.id);
api.refresh();
setTimeout(() => {
if (api.isDestroyed())
return;
for (const row of changed)
flashing.delete(row.id);
api.refresh();
}, 600);
}, periodMs);
syncButtons();
}
// A row that just changed is painted orange and fades away (the background color gets a 0.6 s transition and a timer removes the class).
const CSS = `
.mxg-row { transition: background-color 0.6s ease; }
.mxg-row.lu-flash { background: color-mix(in srgb, #f5a524 38%, transparent); }
@media (prefers-reduced-motion: reduce) { .mxg-row { transition: none; } }
`;
function setup(api, log) {
say = log;
const style = document.createElement('style');
style.textContent = CSS;
document.head.append(style);
tick = 0;
periodMs = 1000;
start(api);
log('The values of two stocks change every second. Double-click a stock name to edit it yourself');
return () => {
stop();
flashing.clear();
style.remove();
};
}
const actions = {
pause: () => {
stop();
say('Paused');
},
resume: (api) => {
start(api);
say('Resumed');
},
speed: (api, value) => {
periodMs = Number(value) || 1000;
if (timer !== undefined)
start(api);
say(`Changes every ${periodMs / 1000} s`);
},
};
options.ariaLabel = "A table whose values keep changing: highlight changed rows";
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('pause').addEventListener('click', () => actions.pause(api));
document.getElementById('resume').addEventListener('click', () => actions.resume(api));
document.getElementById('speed').addEventListener('change', (event) => actions.speed(api, event.target.value));
</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.pause(api)}
>Pause</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.resume(api)}
>Resume</button>
<select
aria-label="Interval"
disabled={!api}
onChange={(event) => api && actions.speed(api, event.target.value)}
>
<option value="300">0.3 s</option>
<option value="1000">1 s (default)</option>
<option value="2000">2 s</option>
</select>
</div>
<Grid style={{ height: 320 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
symbol: string;
price: number;
prev: number;
}
const signed = (value: unknown): string => `${Number(value) > 0 ? '+' : ''}${Number(value)}`;
const flashing = new Set<number>();
const SYMBOLS = [
'Northwind Tech',
'Bluesky Pharma',
'Polaris Chemical',
'Harmony Build',
'Dawn Foods',
'Mode Fashion',
];
export const options: GridOptions<Row> = {
columns: [
{ id: 'symbol', title: 'Stock', width: 150, editable: true },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 110,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
{
id: 'change',
title: 'Change',
kind: 'number',
width: 100,
align: 'end',
getValue: (row) => row.price - row.prev,
formatValue: signed,
},
],
rows: SYMBOLS.map((symbol, i) => ({
id: i + 1,
symbol,
price: 10000 + i * 1500,
prev: 10000 + i * 1500,
})),
rowKey: 'id',
rowClass: (row) => (flashing.has(row.id) ? 'lu-flash' : undefined),
};
let timer: ReturnType<typeof setInterval> | undefined;
let periodMs = 1000;
let tick = 0;
let say: (message: LogText) => void = () => {};
// Keep the buttons in step: Pause can be pressed only while running, and Resume only after pausing.
function syncButtons(): void {
const pause = document.getElementById('pause');
const resume = document.getElementById('resume');
if (pause instanceof HTMLButtonElement) pause.disabled = timer === undefined;
if (resume instanceof HTMLButtonElement) resume.disabled = timer !== undefined;
}
function stop(): void {
clearInterval(timer);
timer = undefined;
syncButtons();
}
function start(api: GridApi<Row>): void {
stop();
timer = setInterval(() => {
if (api.isDestroyed()) return stop();
tick += 1;
// Pick two rows by a fixed rule instead of random numbers, so it looks the same whenever you open it.
const picks = [(tick * 3) % 6, (tick * 5 + 1) % 6];
const changed = picks.flatMap((index) => {
const row = api.getRows()[index];
if (!row) return [];
const delta = ((tick + index) % 2 === 0 ? 1 : -1) * (100 + ((tick * 7) % 40) * 10);
return [{ ...row, prev: row.price, price: row.price + delta }];
});
// Values sent by the server are merged with mergeRows. Unlike values the user edits by hand (the cell corner mark), they do not pile up as 'edited'.
api.mergeRows(changed);
for (const row of changed) flashing.add(row.id);
api.refresh();
setTimeout(() => {
if (api.isDestroyed()) return;
for (const row of changed) flashing.delete(row.id);
api.refresh();
}, 600);
}, periodMs);
syncButtons();
}
// A row that just changed is painted orange and fades away (the background color gets a 0.6 s transition and a timer removes the class).
const CSS = `
.mxg-row { transition: background-color 0.6s ease; }
.mxg-row.lu-flash { background: color-mix(in srgb, #f5a524 38%, transparent); }
@media (prefers-reduced-motion: reduce) { .mxg-row { transition: none; } }
`;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const style = document.createElement('style');
style.textContent = CSS;
document.head.append(style);
tick = 0;
periodMs = 1000;
start(api);
log(
'The values of two stocks change every second. Double-click a stock name to edit it yourself',
);
return () => {
stop();
flashing.clear();
style.remove();
};
}
export const actions = {
pause: () => {
stop();
say('Paused');
},
resume: (api: GridApi<Row>) => {
start(api);
say('Resumed');
},
speed: (api: GridApi<Row>, value?: string) => {
periodMs = Number(value) || 1000;
if (timer !== undefined) start(api);
say(`Changes every ${periodMs / 1000} s`);
},
};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.pause(api)">Pause</button>
<button type="button" :disabled="!api" @click="api && actions.resume(api)">Resume</button>
<select
aria-label="Interval"
:disabled="!api"
@change="api && actions.speed(api, ($event.target as HTMLSelectElement).value)"
>
<option value="300">0.3 s</option>
<option value="1000" selected>1 s (default)</option>
<option value="2000">2 s</option>
</select>
</div>
<Grid style="height: 320px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
symbol: string;
price: number;
prev: number;
}
const signed = (value: unknown): string => `${Number(value) > 0 ? '+' : ''}${Number(value)}`;
const flashing = new Set<number>();
const SYMBOLS = [
'Northwind Tech',
'Bluesky Pharma',
'Polaris Chemical',
'Harmony Build',
'Dawn Foods',
'Mode Fashion',
];
export const options: GridOptions<Row> = {
columns: [
{ id: 'symbol', title: 'Stock', width: 150, editable: true },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 110,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
{
id: 'change',
title: 'Change',
kind: 'number',
width: 100,
align: 'end',
getValue: (row) => row.price - row.prev,
formatValue: signed,
},
],
rows: SYMBOLS.map((symbol, i) => ({
id: i + 1,
symbol,
price: 10000 + i * 1500,
prev: 10000 + i * 1500,
})),
rowKey: 'id',
rowClass: (row) => (flashing.has(row.id) ? 'lu-flash' : undefined),
};
let timer: ReturnType<typeof setInterval> | undefined;
let periodMs = 1000;
let tick = 0;
let say: (message: LogText) => void = () => {};
// Keep the buttons in step: Pause can be pressed only while running, and Resume only after pausing.
function syncButtons(): void {
const pause = document.getElementById('pause');
const resume = document.getElementById('resume');
if (pause instanceof HTMLButtonElement) pause.disabled = timer === undefined;
if (resume instanceof HTMLButtonElement) resume.disabled = timer !== undefined;
}
function stop(): void {
clearInterval(timer);
timer = undefined;
syncButtons();
}
function start(api: GridApi<Row>): void {
stop();
timer = setInterval(() => {
if (api.isDestroyed()) return stop();
tick += 1;
// Pick two rows by a fixed rule instead of random numbers, so it looks the same whenever you open it.
const picks = [(tick * 3) % 6, (tick * 5 + 1) % 6];
const changed = picks.flatMap((index) => {
const row = api.getRows()[index];
if (!row) return [];
const delta = ((tick + index) % 2 === 0 ? 1 : -1) * (100 + ((tick * 7) % 40) * 10);
return [{ ...row, prev: row.price, price: row.price + delta }];
});
// Values sent by the server are merged with mergeRows. Unlike values the user edits by hand (the cell corner mark), they do not pile up as 'edited'.
api.mergeRows(changed);
for (const row of changed) flashing.add(row.id);
api.refresh();
setTimeout(() => {
if (api.isDestroyed()) return;
for (const row of changed) flashing.delete(row.id);
api.refresh();
}, 600);
}, periodMs);
syncButtons();
}
// A row that just changed is painted orange and fades away (the background color gets a 0.6 s transition and a timer removes the class).
const CSS = `
.mxg-row { transition: background-color 0.6s ease; }
.mxg-row.lu-flash { background: color-mix(in srgb, #f5a524 38%, transparent); }
@media (prefers-reduced-motion: reduce) { .mxg-row { transition: none; } }
`;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const style = document.createElement('style');
style.textContent = CSS;
document.head.append(style);
tick = 0;
periodMs = 1000;
start(api);
log(
'The values of two stocks change every second. Double-click a stock name to edit it yourself',
);
return () => {
stop();
flashing.clear();
style.remove();
};
}
export const actions = {
pause: () => {
stop();
say('Paused');
},
resume: (api: GridApi<Row>) => {
start(api);
say('Resumed');
},
speed: (api: GridApi<Row>, value?: string) => {
periodMs = Number(value) || 1000;
if (timer !== undefined) start(api);
say(`Changes every ${periodMs / 1000} s`);
},
};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.pause(api)"
>Pause</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.resume(api)"
>Resume</button>
<select
aria-label="Interval"
[disabled]="!api"
(change)="api && actions.speed(api, $any($event.target).value)"
>
<option value="300">0.3 s</option>
<option value="1000" selected>1 s (default)</option>
<option value="2000">2 s</option>
</select>
</div>
<mx-grid style="height: 320px" [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 { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
symbol: string;
price: number;
prev: number;
}
const signed = (value: unknown): string => `${Number(value) > 0 ? '+' : ''}${Number(value)}`;
const flashing = new Set<number>();
const SYMBOLS = [
'Northwind Tech',
'Bluesky Pharma',
'Polaris Chemical',
'Harmony Build',
'Dawn Foods',
'Mode Fashion',
];
export const options: GridOptions<Row> = {
columns: [
{ id: 'symbol', title: 'Stock', width: 150, editable: true },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 110,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
{
id: 'change',
title: 'Change',
kind: 'number',
width: 100,
align: 'end',
getValue: (row) => row.price - row.prev,
formatValue: signed,
},
],
rows: SYMBOLS.map((symbol, i) => ({
id: i + 1,
symbol,
price: 10000 + i * 1500,
prev: 10000 + i * 1500,
})),
rowKey: 'id',
rowClass: (row) => (flashing.has(row.id) ? 'lu-flash' : undefined),
};
let timer: ReturnType<typeof setInterval> | undefined;
let periodMs = 1000;
let tick = 0;
let say: (message: LogText) => void = () => {};
// Keep the buttons in step: Pause can be pressed only while running, and Resume only after pausing.
function syncButtons(): void {
const pause = document.getElementById('pause');
const resume = document.getElementById('resume');
if (pause instanceof HTMLButtonElement) pause.disabled = timer === undefined;
if (resume instanceof HTMLButtonElement) resume.disabled = timer !== undefined;
}
function stop(): void {
clearInterval(timer);
timer = undefined;
syncButtons();
}
function start(api: GridApi<Row>): void {
stop();
timer = setInterval(() => {
if (api.isDestroyed()) return stop();
tick += 1;
// Pick two rows by a fixed rule instead of random numbers, so it looks the same whenever you open it.
const picks = [(tick * 3) % 6, (tick * 5 + 1) % 6];
const changed = picks.flatMap((index) => {
const row = api.getRows()[index];
if (!row) return [];
const delta = ((tick + index) % 2 === 0 ? 1 : -1) * (100 + ((tick * 7) % 40) * 10);
return [{ ...row, prev: row.price, price: row.price + delta }];
});
// Values sent by the server are merged with mergeRows. Unlike values the user edits by hand (the cell corner mark), they do not pile up as 'edited'.
api.mergeRows(changed);
for (const row of changed) flashing.add(row.id);
api.refresh();
setTimeout(() => {
if (api.isDestroyed()) return;
for (const row of changed) flashing.delete(row.id);
api.refresh();
}, 600);
}, periodMs);
syncButtons();
}
// A row that just changed is painted orange and fades away (the background color gets a 0.6 s transition and a timer removes the class).
const CSS = `
.mxg-row { transition: background-color 0.6s ease; }
.mxg-row.lu-flash { background: color-mix(in srgb, #f5a524 38%, transparent); }
@media (prefers-reduced-motion: reduce) { .mxg-row { transition: none; } }
`;
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
const style = document.createElement('style');
style.textContent = CSS;
document.head.append(style);
tick = 0;
periodMs = 1000;
start(api);
log(
'The values of two stocks change every second. Double-click a stock name to edit it yourself',
);
return () => {
stop();
flashing.clear();
style.remove();
};
}
export const actions = {
pause: () => {
stop();
say('Paused');
},
resume: (api: GridApi<Row>) => {
start(api);
say('Resumed');
},
speed: (api: GridApi<Row>, value?: string) => {
periodMs = Number(value) || 1000;
if (timer !== undefined) start(api);
say(`Changes every ${periodMs / 1000} s`);
},
};