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

내가 맞춘 컬럼 배치를 저장하고 불러오기Save and restore your column layout

폭을 바꾸고, 순서를 옮기고, 숨기고, 고정한 컬럼 배치를 JSON 하나로 저장했다가 나중에 한 번에 되돌려요. 처음 상태로 초기화하는 것도 한 줄이에요. 저장하는 곳은 브라우저 저장소여도, 서버나 파일이어도 돼요.Save the widths, order, hidden and pinned state of your columns as one JSON and restore it later in one step. Resetting to the defaults is one call. Store it in browser storage, a server or a file.

활용Intermediate
직접 써 보기Live preview내가 맞춘 컬럼 배치를 저장하고 불러오기Save and restore your column layout

코드Code

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

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

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

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

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="save">배치 저장</button>
    <button type="button" id="scramble">일부러 어지럽히기</button>
    <button type="button" id="restore">저장한 배치 불러오기</button>
    <button type="button" id="reset">처음 상태로</button>
    <button type="button" id="forget">저장값 지우기</button>
  </div>
  <div id="grid" style="height: 340px"></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('save').addEventListener('click', () => actions.save(api));
document.getElementById('scramble').addEventListener('click', () => actions.scramble(api));
document.getElementById('restore').addEventListener('click', () => actions.restore(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
document.getElementById('forget').addEventListener('click', () => actions.forget(api));
example.js
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희'];
const teams = ['개발팀', '디자인팀', '영업팀', '인사팀'];
const levels = ['사원', '대리', '과장', '차장'];
const cities = ['서울', '부산', '대구', '제주'];
// 컬럼 배치(폭·순서·숨김·고정)는 그냥 JSON 데이터라서 브라우저 저장소나 서버, 파일 어디든 보관할 수 있어요.
export const options = {
  columnMenu: true,
  columns: [
    { id: 'id', title: '번호', width: 70, align: 'end' },
    { id: 'name', title: '이름', width: 120 },
    { id: 'team', title: '팀', width: 110, pinned: 'start' },
    { id: 'level', title: '직급', width: 90 },
    { id: 'salary', title: '연봉(만원)', kind: 'number', width: 120, align: 'end' },
    { id: 'city', title: '근무지', width: 100 },
  ],
  rows: Array.from({ length: 8 }, (_, i) => ({
    id: i + 1,
    name: names[i % 6],
    team: teams[(i * 3) % 4],
    level: levels[i % 4],
    salary: 3800 + ((i * 530) % 4200),
    city: cities[i % 4],
  })),
  rowKey: 'id',
};
const KEY = 'gallery-column-state-save-restore';
let say = () => { };
const read = () => {
  try {
    return localStorage.getItem(KEY);
  }
  catch {
    return null;
  }
};
// 레이아웃 JSON인지 확인하고 적용해요. 없는 컬럼 id가 들어 있으면 setColumnState가 거절해요.
const valid = (value) => Array.isArray(value) &&
  value.every((s) => typeof s === 'object' &&
    s !== null &&
    typeof s.id === 'string' &&
    typeof s.width === 'number' &&
    typeof s.hidden === 'boolean');
export function setup(api, log) {
  say = log;
  const offs = ['columnMoved', 'columnResized', 'columnPinned', 'columnVisibilityChanged'].map((name) => api.on(name, (e) => log({
    ko: `${e.columnId} 바뀜 (${e.source === 'api' ? '코드' : '직접'})`,
    en: `${e.columnId} changed (${e.source === 'api' ? 'code' : 'direct'})`,
  })));
  return () => offs.forEach((off) => off());
}
export const actions = {
  save: (api) => {
    try {
      localStorage.setItem(KEY, JSON.stringify(api.getColumnState()));
      say({ ko: '지금 배치를 저장했어요', en: 'Saved the current layout' });
    }
    catch {
      say({ ko: '이 브라우저에서는 저장할 수 없어요', en: 'Cannot save in this browser' });
    }
  },
  restore: (api) => {
    const raw = read();
    if (raw === null)
      return say({
        ko: '저장된 배치가 없어요. 컬럼을 바꾼 뒤 저장해 보세요',
        en: 'No saved layout. Change the columns, then save.',
      });
    try {
      const parsed = JSON.parse(raw);
      if (!valid(parsed))
        return say({
          ko: '저장된 값이 컬럼 배치 모양이 아니에요',
          en: 'The saved value is not a column layout',
        });
      api.setColumnState(parsed);
      say({
        ko: `저장한 배치를 불러왔어요 (${parsed.length}개 컬럼)`,
        en: `Loaded the saved layout (${parsed.length} columns)`,
      });
    }
    catch (error) {
      say({
        ko: `불러오지 못했어요: ${error instanceof Error ? error.message : '알 수 없는 오류'}`,
        en: `Could not load: ${error instanceof Error ? error.message : 'unknown error'}`,
      });
    }
  },
  // 정의된 처음 상태로 되돌려요(팀은 정의대로 왼쪽 고정).
  reset: (api) => {
    api.resetColumnState();
    say({ ko: '처음 상태로 되돌렸어요', en: 'Back to the starting state' });
  },
  // 컬럼을 일부러 어지럽혀 봐요.
  scramble: (api) => {
    api.resizeColumn('name', 220);
    api.moveColumn('salary', 0);
    api.setColumnVisible('city', false);
    api.pinColumn('team', null);
  },
  forget: () => {
    try {
      localStorage.removeItem(KEY);
      say({ ko: '저장된 배치를 지웠어요', en: 'Deleted the saved layout' });
    }
    catch {
      say({
        ko: '이 브라우저에서는 저장 공간을 쓸 수 없어요',
        en: 'Storage is not available in this browser',
      });
    }
  },
};

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="save">Save layout</button>
    <button type="button" id="scramble">Scramble columns</button>
    <button type="button" id="restore">Restore saved layout</button>
    <button type="button" id="reset">Reset to defaults</button>
    <button type="button" id="forget">Delete saved value</button>
  </div>
  <div id="grid" style="height: 340px"></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('save').addEventListener('click', () => actions.save(api));
document.getElementById('scramble').addEventListener('click', () => actions.scramble(api));
document.getElementById('restore').addEventListener('click', () => actions.restore(api));
document.getElementById('reset').addEventListener('click', () => actions.reset(api));
document.getElementById('forget').addEventListener('click', () => actions.forget(api));
example.js
const names = [
  'Liam Carter',
  'Emma Stone',
  'Noah Parker',
  'Olivia Reed',
  'Ethan Clark',
  'Mia Turner',
];
const teams = ['Dev', 'Design', 'Sales', 'HR'];
const levels = ['Junior', 'Associate', 'Senior', 'Lead'];
const cities = ['Seoul', 'Busan', 'Daegu', 'Jeju'];
// The column layout (width, order, hidden, pinned) is plain JSON, so you can keep it in browser storage, on a server or in a file.
export const options = {
  columnMenu: true,
  columns: [
    { id: 'id', title: 'No.', width: 70, align: 'end' },
    { id: 'name', title: 'Name', width: 130 },
    { id: 'team', title: 'Team', width: 110, pinned: 'start' },
    { id: 'level', title: 'Level', width: 90 },
    { id: 'salary', title: 'Salary ($)', kind: 'number', width: 120, align: 'end' },
    { id: 'city', title: 'Office', width: 100 },
  ],
  rows: Array.from({ length: 8 }, (_, i) => ({
    id: i + 1,
    name: names[i % 6],
    team: teams[(i * 3) % 4],
    level: levels[i % 4],
    salary: (3800 + ((i * 530) % 4200)) * 10,
    city: cities[i % 4],
  })),
  rowKey: 'id',
};
const KEY = 'gallery-column-state-save-restore';
let say = () => { };
const read = () => {
  try {
    return localStorage.getItem(KEY);
  }
  catch {
    return null;
  }
};
// Check that this is layout JSON before applying it. setColumnState rejects unknown column ids.
const valid = (value) => Array.isArray(value) &&
  value.every((s) => typeof s === 'object' &&
    s !== null &&
    typeof s.id === 'string' &&
    typeof s.width === 'number' &&
    typeof s.hidden === 'boolean');
export function setup(api, log) {
  say = log;
  const offs = ['columnMoved', 'columnResized', 'columnPinned', 'columnVisibilityChanged'].map((name) => api.on(name, (e) => log(`${e.columnId} changed (${e.source === 'api' ? 'code' : 'direct'})`)));
  return () => offs.forEach((off) => off());
}
export const actions = {
  save: (api) => {
    try {
      localStorage.setItem(KEY, JSON.stringify(api.getColumnState()));
      say('Saved the current layout');
    }
    catch {
      say('Cannot save in this browser');
    }
  },
  restore: (api) => {
    const raw = read();
    if (raw === null)
      return say('No saved layout. Change the columns, then save.');
    try {
      const parsed = JSON.parse(raw);
      if (!valid(parsed))
        return say('The saved value is not a column layout');
      api.setColumnState(parsed);
      say(`Loaded the saved layout (${parsed.length} columns)`);
    }
    catch (error) {
      say(`Could not load: ${error instanceof Error ? error.message : 'unknown error'}`);
    }
  },
  // Go back to the defined starting state (Team pinned left, as defined).
  reset: (api) => {
    api.resetColumnState();
    say('Back to the starting state');
  },
  // Scramble the columns on purpose.
  scramble: (api) => {
    api.resizeColumn('name', 220);
    api.moveColumn('salary', 0);
    api.setColumnVisible('city', false);
    api.pinColumn('team', null);
  },
  forget: () => {
    try {
      localStorage.removeItem(KEY);
      say('Deleted the saved layout');
    }
    catch {
      say('Storage is not available in this browser');
    }
  },
};