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

긴 글을 여러 줄로 고치기Edit long text over several lines

칸에는 첫 줄만 보여 주고, 고칠 때는 여러 줄 입력창이 열려요. Enter는 줄바꿈이고, 확정은 Ctrl+Enter나 "확정" 버튼이에요. 전체 내용은 마우스를 올리면 말풍선으로 읽을 수 있어요. 입력창은 칸 아래에 열려요(editorBox).The cell shows only the first line, and editing opens a multi-line box. Enter adds a line; commit with Ctrl+Enter or the "Confirm" button. Hover to read the whole text in a tooltip. The box opens below the cell (editorBox).

활용Intermediate
직접 써 보기Live preview긴 글을 여러 줄로 고치기Edit long text over several lines

코드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="editFirst">첫 줄 내용 편집</button>
  </div>
  <div id="grid" style="height: 230px"></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('editFirst').addEventListener('click', () => actions.editFirst(api));
example.js
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
const rows = [
  {
    id: 1,
    title: '로그인이 느려요',
    body: '아침 9시쯤 로그인이 5초 넘게 걸려요.\n스테이징에서도 같은 증상이 있어요.\n로그 파일은 첨부했어요.',
  },
  { id: 2, title: '내보내기에서 컬럼이 빠져요', body: '컬럼을 고정한 상태에서만 생겨요.' },
  { id: 3, title: '다크 모드 글자가 흐려요', body: '' },
  {
    id: 4,
    title: '모바일에서 표가 잘려요',
    body: '아이폰 SE 크기에서 마지막 컬럼이 안 보여요.\n가로 스크롤은 되는데 안내가 없어요.',
  },
  { id: 5, title: '알림이 두 번 와요', body: '저장 버튼을 한 번만 눌렀는데 알림이 두 번 떠요.' },
];
// 터치 화면(또는 폭이 좁은 화면)에서는 글자를 16px로 키워요. 13px 입력칸은 iOS가 화면을 확대해 버려요.
const touch = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 여러 줄을 쓰는 편집기를 직접 만들었어요. Enter는 줄바꿈이고, Ctrl+Enter 또는 "확정" 버튼이 확정이에요.
// Esc 또는 "취소" 버튼은 고치던 것을 버려요. 키보드가 없는 폰에서는 버튼을 써요.
// 편집기는 mount(만들기), getValue(값 읽기), focus, setError(오류 표시), destroy(치우기)를 갖추면 돼요.
// 색은 그리드의 테마 변수(--mxg-*)를 써서 다크 모드에서도 어울려요.
const textareaEditor = () => {
  let box;
  let area;
  let composing = false; // 한글 조합 중에는 Enter가 확정이 되지 않게 해요.
  return {
    mount(el, ctx) {
      area = document.createElement('textarea');
      area.value = String(ctx.value ?? '');
      area.rows = 3;
      // flex: none — 편집 상자가 좁아도 줄어들지 않아 3줄이 그대로 보여요.
      area.style.cssText = `flex: none; width: 100%; height: ${touch() ? 104 : 84}px; min-height: ${touch() ? 104 : 84}px; box-sizing: border-box; padding: 6px 8px; font: inherit; font-size: ${touch() ? 16 : 13}px; resize: none; background: var(--mxg-bg); color: var(--mxg-fg); border: 1px solid var(--mxg-border); border-radius: 0; outline: none;`; // 바깥 편집 틀이 이미 파란 포커스 선을 그려서 안쪽은 회색 선만 둬요.
      area.addEventListener('compositionstart', () => (composing = true));
      area.addEventListener('compositionend', () => (composing = false));
      area.addEventListener('keydown', (event) => {
        if (event.key === 'Enter' && !event.ctrlKey)
          event.stopPropagation(); // 줄바꿈으로 둬요.
        else if (event.key === 'Enter' && !composing)
          ctx.commit();
      });
      const button = (text, onClick) => {
        const b = document.createElement('button');
        b.type = 'button';
        b.textContent = text;
        b.style.cssText = `font: inherit; font-size: ${touch() ? 16 : 12}px; padding: ${touch() ? '8px 18px' : '2px 10px'}; min-height: ${touch() ? 40 : 0}px; background: var(--mxg-bg); color: var(--mxg-fg); border: 1px solid var(--mxg-border); border-radius: var(--mxg-radius); cursor: pointer;`;
        b.addEventListener('click', onClick);
        return b;
      };
      const row = document.createElement('div');
      row.style.cssText = `display: flex; gap: ${touch() ? 10 : 6}px; justify-content: flex-end; padding-top: 4px;`;
      row.append(button(L('취소', 'Cancel'), () => ctx.cancel()), button(L('확정', 'Confirm'), () => ctx.commit()));
      box = document.createElement('div');
      box.style.cssText =
        'display: flex; flex-direction: column; width: 100%; box-sizing: border-box; padding: 2px;';
      box.append(area, row);
      el.append(box);
    },
    getValue: () => area.value,
    focus: () => area.focus(),
    setError(message) {
      area.setAttribute('aria-invalid', String(message !== null));
      area.title = message ?? '';
    },
    isComposing: () => composing,
    destroy: () => box.remove(),
  };
};
const firstLine = (value) => String(value ?? '').split('\n')[0] ?? '';
export const options = {
  columns: [
    { id: 'title', title: '제목', width: 190 },
    {
      id: 'body',
      title: '내용 (여러 줄)',
      width: 300,
      editable: true,
      cellEditor: textareaEditor,
      // 편집기 상자를 칸 아래에 열고(side) 폭을 칸보다 넓게(minWidth) 정해요. 칸이 가려지지 않고, 자리가 모자라면 위로 뒤집혀요.
      editorBox: { side: 'below', minWidth: 340 },
      formatValue: (value) => firstLine(value), // 칸에는 첫 줄만 보여 줘요.
      tooltip: (row) => row.body || undefined, // 전체 내용은 말풍선으로 읽어요.
      validation: { maxLength: 200 },
    },
  ],
  rows,
  rowKey: 'id',
};
export function setup(api, log) {
  log({
    ko: '"내용" 칸을 더블클릭하세요. Enter는 줄바꿈이에요. 확정은 Ctrl+Enter 또는 "확정" 버튼, 취소는 Esc 또는 "취소" 버튼이에요.',
    en: 'Double-click a "내용" (content) cell. Enter adds a line break. Confirm with Ctrl+Enter or the "확정" (confirm) button; cancel with Esc or the "취소" (cancel) button.',
  });
  const offs = [
    api.on('editCommitted', (e) => log({
      ko: `${e.rowKey}번 문의 내용: ${String(e.newValue).split('\n').length}줄`,
      en: `Inquiry ${e.rowKey} content: ${String(e.newValue).split('\n').length} lines`,
    })),
    api.on('validationFailed', (e) => log({ ko: `확정하지 못했어요: ${e.message}`, en: `Could not confirm: ${e.message}` })),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  editFirst: (api) => api.startEdit(1, 'body'),
};

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="editFirst">Edit first body</button>
  </div>
  <div id="grid" style="height: 230px"></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('editFirst').addEventListener('click', () => actions.editFirst(api));
example.js
const rows = [
  {
    id: 1,
    title: 'Login is slow',
    body: 'Around 9 AM, login takes over 5 seconds.\nThe same happens on staging.\nI attached the log file.',
  },
  { id: 2, title: 'Columns missing from export', body: 'Only happens when columns are pinned.' },
  { id: 3, title: 'Dark mode text is faint', body: '' },
  {
    id: 4,
    title: 'Grid is clipped on mobile',
    body: 'The last column is not visible at iPhone SE size.\nHorizontal scroll works, but there is no hint.',
  },
  {
    id: 5,
    title: 'Notification arrives twice',
    body: 'I pressed Save only once, but two notifications appear.',
  },
];
// On touch screens (or narrow screens) the text grows to 16px. iOS zooms the page for 13px inputs.
const touch = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// A hand-made multi-line editor. Enter adds a line break; Ctrl+Enter or the "Confirm" button commits.
// Esc or the "Cancel" button discards the edit. On phones without a keyboard, use the buttons.
// An editor needs mount, getValue, focus, setError (show an error) and destroy (clean up).
// Colors use the grid theme variables (--mxg-*), so they also fit dark mode.
const textareaEditor = () => {
  let box;
  let area;
  let composing = false; // While an IME is composing, Enter must not commit.
  return {
    mount(el, ctx) {
      area = document.createElement('textarea');
      area.value = String(ctx.value ?? '');
      area.rows = 3;
      // flex: none - the box does not shrink when the edit box is narrow, so 3 lines stay visible.
      area.style.cssText = `flex: none; width: 100%; height: ${touch() ? 104 : 84}px; min-height: ${touch() ? 104 : 84}px; box-sizing: border-box; padding: 6px 8px; font: inherit; font-size: ${touch() ? 16 : 13}px; resize: none; background: var(--mxg-bg); color: var(--mxg-fg); border: 1px solid var(--mxg-border); border-radius: 0; outline: none;`; // The outer edit frame already draws the blue focus outline, so the inside keeps only a gray border.
      area.addEventListener('compositionstart', () => (composing = true));
      area.addEventListener('compositionend', () => (composing = false));
      area.addEventListener('keydown', (event) => {
        if (event.key === 'Enter' && !event.ctrlKey)
          event.stopPropagation(); // Leave it as a line break.
        else if (event.key === 'Enter' && !composing)
          ctx.commit();
      });
      const button = (text, onClick) => {
        const b = document.createElement('button');
        b.type = 'button';
        b.textContent = text;
        b.style.cssText = `font: inherit; font-size: ${touch() ? 16 : 12}px; padding: ${touch() ? '8px 18px' : '2px 10px'}; min-height: ${touch() ? 40 : 0}px; background: var(--mxg-bg); color: var(--mxg-fg); border: 1px solid var(--mxg-border); border-radius: var(--mxg-radius); cursor: pointer;`;
        b.addEventListener('click', onClick);
        return b;
      };
      const row = document.createElement('div');
      row.style.cssText = `display: flex; gap: ${touch() ? 10 : 6}px; justify-content: flex-end; padding-top: 4px;`;
      row.append(button('Cancel', () => ctx.cancel()), button('Confirm', () => ctx.commit()));
      box = document.createElement('div');
      box.style.cssText =
        'display: flex; flex-direction: column; width: 100%; box-sizing: border-box; padding: 2px;';
      box.append(area, row);
      el.append(box);
    },
    getValue: () => area.value,
    focus: () => area.focus(),
    setError(message) {
      area.setAttribute('aria-invalid', String(message !== null));
      area.title = message ?? '';
    },
    isComposing: () => composing,
    destroy: () => box.remove(),
  };
};
const firstLine = (value) => String(value ?? '').split('\n')[0] ?? '';
export const options = {
  columns: [
    { id: 'title', title: 'Title', width: 190 },
    {
      id: 'body',
      title: 'Content (multi-line)',
      width: 300,
      editable: true,
      cellEditor: textareaEditor,
      // Open the editor box below the cell (side) and make it wider than the cell (minWidth). The cell stays visible, and the box flips upward if there is no room.
      editorBox: { side: 'below', minWidth: 340 },
      formatValue: (value) => firstLine(value), // The cell shows only the first line.
      tooltip: (row) => row.body || undefined, // The full content is readable in the tooltip.
      validation: { maxLength: 200 },
    },
  ],
  rows,
  rowKey: 'id',
};
export function setup(api, log) {
  log('Double-click a "Content" cell. Enter adds a line break. Confirm with Ctrl+Enter or the "Confirm" button; cancel with Esc or the "Cancel" button.');
  const offs = [
    api.on('editCommitted', (e) => log(`Inquiry ${e.rowKey} content: ${String(e.newValue).split('\n').length} lines`)),
    api.on('validationFailed', (e) => log(`Could not confirm: ${e.message}`)),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  editFirst: (api) => api.startEdit(1, 'body'),
};