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

값이 계속 바뀌는 표: 바뀐 줄 강조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).

심화Advanced
직접 써 보기Live preview값이 계속 바뀌는 표: 바뀐 줄 강조A table whose values keep changing: highlight changed rows

코드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)

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

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

index.html
<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>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('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));
example.js
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` });
  },
};

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

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

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="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>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('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));
example.js
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`);
  },
};