칸을 우클릭해서 복사·붙여넣기·메모 쓰기Right-click a cell to copy, paste and add notes
칸에서 마우스 오른쪽 버튼을 누르면 잘라내기·복사·붙여넣기·메모 메뉴가 떠요. 복사한 글은 엑셀에 그대로 붙고, 엑셀에서 복사한 칸도 바로 붙여넣을 수 있어요.Right-click a cell for cut, copy, paste and note commands. Copied text pastes straight into Excel, and cells copied from Excel paste right back in.
코드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">
<select aria-label="우클릭 메뉴" id="menu">
<option value="on" selected>켜기 (기본)</option>
<option value="custom">항목 직접 정하기</option>
<option value="off">끄기 (브라우저 기본 메뉴)</option>
</select>
<button type="button" id="copyCode">고른 칸을 글자로 받기</button>
<button type="button" id="pasteCode">코드로 붙여넣기</button>
<button type="button" id="noteCode">코드로 메모 달기</button>
</div>
<div id="grid" style="height: 360px"></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('menu').addEventListener('change', (event) => actions.menu(api, event.target.value));
document.getElementById('copyCode').addEventListener('click', () => actions.copyCode(api));
document.getElementById('pasteCode').addEventListener('click', () => actions.pasteCode(api));
document.getElementById('noteCode').addEventListener('click', () => actions.noteCode(api));// 카페 주문표. 이름·수량·단가·완료는 직접 고칠 수 있어서 잘라내기·붙여넣기가 값을 바꿔요.
const menus = [
'아메리카노',
'카페라떼',
'바닐라라떼',
'콜드브루',
'카푸치노',
'녹차라떼',
'딸기스무디',
'레몬에이드',
];
const rows = menus.map((menu, i) => ({
id: i + 1,
menu,
qty: 3 + ((i * 7) % 9),
price: 4000 + i * 300,
done: i % 3 === 0,
}));
// cellMenu는 기본으로 켜져 있어요(false로 끄면 브라우저 기본 메뉴가 떠요).
// cellNotes로 처음부터 달아 둘 메모를 줄 수 있고, getCellNotes()로 저장할 메모를 꺼내요.
export const options = {
columns: [
{ id: 'menu', title: '메뉴', width: 150, editable: true },
{ id: 'qty', title: '수량', kind: 'number', width: 100, editable: true },
{
id: 'price',
title: '단가',
kind: 'number',
width: 120,
editable: true,
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
{
id: 'done',
title: '완료',
kind: 'boolean',
width: 90,
editable: true,
formatValue: (value) => (value ? '✓' : ''),
},
],
rows,
rowKey: 'id',
cellSelection: 'multiple',
cellNotes: [{ rowKey: 2, columnId: 'qty', text: '단체 주문이라 미리 만들어 두기' }],
};
// 버튼(actions)도 알림을 남길 수 있게 setup에서 받은 log를 보관해요.
let say = () => { };
export function setup(api, log) {
say = log;
log({
ko: '칸을 오른쪽 버튼으로 눌러 보세요. 메모와 붙여넣기 결과가 여기에 남아요.',
en: 'Right-click a cell. Notes and paste results appear here.',
});
const offs = [
api.on('cellNoteChanged', ({ rowKey, columnId, text }) => {
const name = api.getRowByKey(rowKey)?.menu ?? rowKey;
log({
ko: text === null ? `${name} 메모를 지웠어요 (${columnId})` : `${name} 메모: ${text}`,
en: text === null ? `${name} note removed (${columnId})` : `${name} note: ${text}`,
});
}),
api.on('cellsPasted', ({ pasted, skipped }) => log({
ko: `붙여넣기: ${pasted}칸 바꿨고 ${skipped}칸은 건너뛰었어요`,
en: `Paste: ${pasted} cells changed, ${skipped} skipped`,
})),
];
return () => offs.forEach((off) => off());
}
export const actions = {
// 메뉴를 켜거나, 항목을 직접 정하거나(예: '복사'만 남기기), 끄는 방법이에요.
menu: (api, value) => {
if (value === 'off')
return api.setOptions({ cellMenu: false });
if (value === 'custom')
return api.setOptions({
cellMenu: {
items: (defaults) => defaults.filter((item) => ['copy', 'note-add', 'note-edit', 'note-remove'].includes(item.id) ||
item.separator),
},
});
api.setOptions({ cellMenu: true });
},
// copyCells()는 고른 칸을 엑셀에 그대로 붙는 글자로 돌려줘요. header: 'columns'면 컬럼 제목이 맨 위에 붙어요.
copyCode: (api) => {
const text = api.copyCells({ header: 'columns' });
say({
ko: text === ''
? '고른 칸이 없어요. 먼저 칸을 끌어 보세요'
: text.replaceAll('\t', ' | ').replaceAll('\r\n', ' / '),
en: text === ''
? 'No cells selected. Drag across some cells first'
: text.replaceAll('\t', ' | ').replaceAll('\r\n', ' / '),
});
},
// pasteCells()는 탭·줄바꿈으로 나뉜 글자를 고른 칸(없으면 포커스 칸)부터 채워요. 편집과 같은 검증을 거쳐요.
pasteCode: (api) => {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'menu' });
api.pasteCells('샘플 음료\t12\t5500\ttrue');
},
noteCode: (api) => api.setCellNote(1, 'menu', '대표 메뉴예요'),
};<!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">
<select aria-label="우클릭 메뉴" id="menu">
<option value="on" selected>켜기 (기본)</option>
<option value="custom">항목 직접 정하기</option>
<option value="off">끄기 (브라우저 기본 메뉴)</option>
</select>
<button type="button" id="copyCode">고른 칸을 글자로 받기</button>
<button type="button" id="pasteCode">코드로 붙여넣기</button>
<button type="button" id="noteCode">코드로 메모 달기</button>
</div>
<div id="grid" style="height: 360px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 카페 주문표. 이름·수량·단가·완료는 직접 고칠 수 있어서 잘라내기·붙여넣기가 값을 바꿔요.
const menus = [
'아메리카노',
'카페라떼',
'바닐라라떼',
'콜드브루',
'카푸치노',
'녹차라떼',
'딸기스무디',
'레몬에이드',
];
const rows = menus.map((menu, i) => ({
id: i + 1,
menu,
qty: 3 + ((i * 7) % 9),
price: 4000 + i * 300,
done: i % 3 === 0,
}));
// cellMenu는 기본으로 켜져 있어요(false로 끄면 브라우저 기본 메뉴가 떠요).
// cellNotes로 처음부터 달아 둘 메모를 줄 수 있고, getCellNotes()로 저장할 메모를 꺼내요.
const options = {
columns: [
{ id: 'menu', title: '메뉴', width: 150, editable: true },
{ id: 'qty', title: '수량', kind: 'number', width: 100, editable: true },
{
id: 'price',
title: '단가',
kind: 'number',
width: 120,
editable: true,
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
{
id: 'done',
title: '완료',
kind: 'boolean',
width: 90,
editable: true,
formatValue: (value) => (value ? '✓' : ''),
},
],
rows,
rowKey: 'id',
cellSelection: 'multiple',
cellNotes: [{ rowKey: 2, columnId: 'qty', text: '단체 주문이라 미리 만들어 두기' }],
};
// 버튼(actions)도 알림을 남길 수 있게 setup에서 받은 log를 보관해요.
let say = () => { };
function setup(api, log) {
say = log;
log({
ko: '칸을 오른쪽 버튼으로 눌러 보세요. 메모와 붙여넣기 결과가 여기에 남아요.',
en: 'Right-click a cell. Notes and paste results appear here.',
});
const offs = [
api.on('cellNoteChanged', ({ rowKey, columnId, text }) => {
const name = api.getRowByKey(rowKey)?.menu ?? rowKey;
log({
ko: text === null ? `${name} 메모를 지웠어요 (${columnId})` : `${name} 메모: ${text}`,
en: text === null ? `${name} note removed (${columnId})` : `${name} note: ${text}`,
});
}),
api.on('cellsPasted', ({ pasted, skipped }) => log({
ko: `붙여넣기: ${pasted}칸 바꿨고 ${skipped}칸은 건너뛰었어요`,
en: `Paste: ${pasted} cells changed, ${skipped} skipped`,
})),
];
return () => offs.forEach((off) => off());
}
const actions = {
// 메뉴를 켜거나, 항목을 직접 정하거나(예: '복사'만 남기기), 끄는 방법이에요.
menu: (api, value) => {
if (value === 'off')
return api.setOptions({ cellMenu: false });
if (value === 'custom')
return api.setOptions({
cellMenu: {
items: (defaults) => defaults.filter((item) => ['copy', 'note-add', 'note-edit', 'note-remove'].includes(item.id) ||
item.separator),
},
});
api.setOptions({ cellMenu: true });
},
// copyCells()는 고른 칸을 엑셀에 그대로 붙는 글자로 돌려줘요. header: 'columns'면 컬럼 제목이 맨 위에 붙어요.
copyCode: (api) => {
const text = api.copyCells({ header: 'columns' });
say({
ko: text === ''
? '고른 칸이 없어요. 먼저 칸을 끌어 보세요'
: text.replaceAll('\t', ' | ').replaceAll('\r\n', ' / '),
en: text === ''
? 'No cells selected. Drag across some cells first'
: text.replaceAll('\t', ' | ').replaceAll('\r\n', ' / '),
});
},
// pasteCells()는 탭·줄바꿈으로 나뉜 글자를 고른 칸(없으면 포커스 칸)부터 채워요. 편집과 같은 검증을 거쳐요.
pasteCode: (api) => {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'menu' });
api.pasteCells('샘플 음료\t12\t5500\ttrue');
},
noteCode: (api) => api.setCellNote(1, 'menu', '대표 메뉴예요'),
};
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('menu').addEventListener('change', (event) => actions.menu(api, event.target.value));
document.getElementById('copyCode').addEventListener('click', () => actions.copyCode(api));
document.getElementById('pasteCode').addEventListener('click', () => actions.pasteCode(api));
document.getElementById('noteCode').addEventListener('click', () => actions.noteCode(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">
<select
aria-label="우클릭 메뉴"
disabled={!api}
onChange={(event) => api && actions.menu(api, event.target.value)}
>
<option value="on">켜기 (기본)</option>
<option value="custom">항목 직접 정하기</option>
<option value="off">끄기 (브라우저 기본 메뉴)</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.copyCode(api)}
>고른 칸을 글자로 받기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.pasteCode(api)}
>코드로 붙여넣기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.noteCode(api)}
>코드로 메모 달기</button>
</div>
<Grid style={{ height: 360 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
menu: string;
qty: number;
price: number;
done: boolean;
}
// 카페 주문표. 이름·수량·단가·완료는 직접 고칠 수 있어서 잘라내기·붙여넣기가 값을 바꿔요.
const menus = [
'아메리카노',
'카페라떼',
'바닐라라떼',
'콜드브루',
'카푸치노',
'녹차라떼',
'딸기스무디',
'레몬에이드',
];
const rows: Row[] = menus.map((menu, i) => ({
id: i + 1,
menu,
qty: 3 + ((i * 7) % 9),
price: 4000 + i * 300,
done: i % 3 === 0,
}));
// cellMenu는 기본으로 켜져 있어요(false로 끄면 브라우저 기본 메뉴가 떠요).
// cellNotes로 처음부터 달아 둘 메모를 줄 수 있고, getCellNotes()로 저장할 메모를 꺼내요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'menu', title: '메뉴', width: 150, editable: true },
{ id: 'qty', title: '수량', kind: 'number', width: 100, editable: true },
{
id: 'price',
title: '단가',
kind: 'number',
width: 120,
editable: true,
formatValue: (value: unknown) => Number(value).toLocaleString('ko-KR'),
},
{
id: 'done',
title: '완료',
kind: 'boolean',
width: 90,
editable: true,
formatValue: (value: unknown) => (value ? '✓' : ''),
},
],
rows,
rowKey: 'id',
cellSelection: 'multiple',
cellNotes: [{ rowKey: 2, columnId: 'qty', text: '단체 주문이라 미리 만들어 두기' }],
};
// 버튼(actions)도 알림을 남길 수 있게 setup에서 받은 log를 보관해요.
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '칸을 오른쪽 버튼으로 눌러 보세요. 메모와 붙여넣기 결과가 여기에 남아요.',
en: 'Right-click a cell. Notes and paste results appear here.',
});
const offs = [
api.on('cellNoteChanged', ({ rowKey, columnId, text }) => {
const name = api.getRowByKey(rowKey)?.menu ?? rowKey;
log({
ko: text === null ? `${name} 메모를 지웠어요 (${columnId})` : `${name} 메모: ${text}`,
en: text === null ? `${name} note removed (${columnId})` : `${name} note: ${text}`,
});
}),
api.on('cellsPasted', ({ pasted, skipped }) =>
log({
ko: `붙여넣기: ${pasted}칸 바꿨고 ${skipped}칸은 건너뛰었어요`,
en: `Paste: ${pasted} cells changed, ${skipped} skipped`,
}),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
// 메뉴를 켜거나, 항목을 직접 정하거나(예: '복사'만 남기기), 끄는 방법이에요.
menu: (api: GridApi<Row>, value?: string) => {
if (value === 'off') return api.setOptions({ cellMenu: false });
if (value === 'custom')
return api.setOptions({
cellMenu: {
items: (defaults) =>
defaults.filter(
(item) =>
['copy', 'note-add', 'note-edit', 'note-remove'].includes(item.id) ||
item.separator,
),
},
});
api.setOptions({ cellMenu: true });
},
// copyCells()는 고른 칸을 엑셀에 그대로 붙는 글자로 돌려줘요. header: 'columns'면 컬럼 제목이 맨 위에 붙어요.
copyCode: (api: GridApi<Row>) => {
const text = api.copyCells({ header: 'columns' });
say({
ko:
text === ''
? '고른 칸이 없어요. 먼저 칸을 끌어 보세요'
: text.replaceAll('\t', ' | ').replaceAll('\r\n', ' / '),
en:
text === ''
? 'No cells selected. Drag across some cells first'
: text.replaceAll('\t', ' | ').replaceAll('\r\n', ' / '),
});
},
// pasteCells()는 탭·줄바꿈으로 나뉜 글자를 고른 칸(없으면 포커스 칸)부터 채워요. 편집과 같은 검증을 거쳐요.
pasteCode: (api: GridApi<Row>) => {
if (api.getSelectedCells().length === 0) api.selectCells({ rowKey: 1, columnId: 'menu' });
api.pasteCells('샘플 음료\t12\t5500\ttrue');
},
noteCode: (api: GridApi<Row>) => api.setCellNote(1, 'menu', '대표 메뉴예요'),
};버튼을 누르면 이 예제의 코드가 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">
<select
aria-label="우클릭 메뉴"
:disabled="!api"
@change="api && actions.menu(api, ($event.target as HTMLSelectElement).value)"
>
<option value="on" selected>켜기 (기본)</option>
<option value="custom">항목 직접 정하기</option>
<option value="off">끄기 (브라우저 기본 메뉴)</option>
</select>
<button
type="button"
:disabled="!api"
@click="api && actions.copyCode(api)"
>고른 칸을 글자로 받기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.pasteCode(api)"
>코드로 붙여넣기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.noteCode(api)"
>코드로 메모 달기</button>
</div>
<Grid style="height: 360px" :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;
menu: string;
qty: number;
price: number;
done: boolean;
}
// 카페 주문표. 이름·수량·단가·완료는 직접 고칠 수 있어서 잘라내기·붙여넣기가 값을 바꿔요.
const menus = [
'아메리카노',
'카페라떼',
'바닐라라떼',
'콜드브루',
'카푸치노',
'녹차라떼',
'딸기스무디',
'레몬에이드',
];
const rows: Row[] = menus.map((menu, i) => ({
id: i + 1,
menu,
qty: 3 + ((i * 7) % 9),
price: 4000 + i * 300,
done: i % 3 === 0,
}));
// cellMenu는 기본으로 켜져 있어요(false로 끄면 브라우저 기본 메뉴가 떠요).
// cellNotes로 처음부터 달아 둘 메모를 줄 수 있고, getCellNotes()로 저장할 메모를 꺼내요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'menu', title: '메뉴', width: 150, editable: true },
{ id: 'qty', title: '수량', kind: 'number', width: 100, editable: true },
{
id: 'price',
title: '단가',
kind: 'number',
width: 120,
editable: true,
formatValue: (value: unknown) => Number(value).toLocaleString('ko-KR'),
},
{
id: 'done',
title: '완료',
kind: 'boolean',
width: 90,
editable: true,
formatValue: (value: unknown) => (value ? '✓' : ''),
},
],
rows,
rowKey: 'id',
cellSelection: 'multiple',
cellNotes: [{ rowKey: 2, columnId: 'qty', text: '단체 주문이라 미리 만들어 두기' }],
};
// 버튼(actions)도 알림을 남길 수 있게 setup에서 받은 log를 보관해요.
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '칸을 오른쪽 버튼으로 눌러 보세요. 메모와 붙여넣기 결과가 여기에 남아요.',
en: 'Right-click a cell. Notes and paste results appear here.',
});
const offs = [
api.on('cellNoteChanged', ({ rowKey, columnId, text }) => {
const name = api.getRowByKey(rowKey)?.menu ?? rowKey;
log({
ko: text === null ? `${name} 메모를 지웠어요 (${columnId})` : `${name} 메모: ${text}`,
en: text === null ? `${name} note removed (${columnId})` : `${name} note: ${text}`,
});
}),
api.on('cellsPasted', ({ pasted, skipped }) =>
log({
ko: `붙여넣기: ${pasted}칸 바꿨고 ${skipped}칸은 건너뛰었어요`,
en: `Paste: ${pasted} cells changed, ${skipped} skipped`,
}),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
// 메뉴를 켜거나, 항목을 직접 정하거나(예: '복사'만 남기기), 끄는 방법이에요.
menu: (api: GridApi<Row>, value?: string) => {
if (value === 'off') return api.setOptions({ cellMenu: false });
if (value === 'custom')
return api.setOptions({
cellMenu: {
items: (defaults) =>
defaults.filter(
(item) =>
['copy', 'note-add', 'note-edit', 'note-remove'].includes(item.id) ||
item.separator,
),
},
});
api.setOptions({ cellMenu: true });
},
// copyCells()는 고른 칸을 엑셀에 그대로 붙는 글자로 돌려줘요. header: 'columns'면 컬럼 제목이 맨 위에 붙어요.
copyCode: (api: GridApi<Row>) => {
const text = api.copyCells({ header: 'columns' });
say({
ko:
text === ''
? '고른 칸이 없어요. 먼저 칸을 끌어 보세요'
: text.replaceAll('\t', ' | ').replaceAll('\r\n', ' / '),
en:
text === ''
? 'No cells selected. Drag across some cells first'
: text.replaceAll('\t', ' | ').replaceAll('\r\n', ' / '),
});
},
// pasteCells()는 탭·줄바꿈으로 나뉜 글자를 고른 칸(없으면 포커스 칸)부터 채워요. 편집과 같은 검증을 거쳐요.
pasteCode: (api: GridApi<Row>) => {
if (api.getSelectedCells().length === 0) api.selectCells({ rowKey: 1, columnId: 'menu' });
api.pasteCells('샘플 음료\t12\t5500\ttrue');
},
noteCode: (api: GridApi<Row>) => api.setCellNote(1, 'menu', '대표 메뉴예요'),
};버튼을 누르면 이 예제의 코드가 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">
<select
aria-label="우클릭 메뉴"
[disabled]="!api"
(change)="api && actions.menu(api, $any($event.target).value)"
>
<option value="on" selected>켜기 (기본)</option>
<option value="custom">항목 직접 정하기</option>
<option value="off">끄기 (브라우저 기본 메뉴)</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.copyCode(api)"
>고른 칸을 글자로 받기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.pasteCode(api)"
>코드로 붙여넣기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.noteCode(api)"
>코드로 메모 달기</button>
</div>
<mx-grid style="height: 360px" [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;
menu: string;
qty: number;
price: number;
done: boolean;
}
// 카페 주문표. 이름·수량·단가·완료는 직접 고칠 수 있어서 잘라내기·붙여넣기가 값을 바꿔요.
const menus = [
'아메리카노',
'카페라떼',
'바닐라라떼',
'콜드브루',
'카푸치노',
'녹차라떼',
'딸기스무디',
'레몬에이드',
];
const rows: Row[] = menus.map((menu, i) => ({
id: i + 1,
menu,
qty: 3 + ((i * 7) % 9),
price: 4000 + i * 300,
done: i % 3 === 0,
}));
// cellMenu는 기본으로 켜져 있어요(false로 끄면 브라우저 기본 메뉴가 떠요).
// cellNotes로 처음부터 달아 둘 메모를 줄 수 있고, getCellNotes()로 저장할 메모를 꺼내요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'menu', title: '메뉴', width: 150, editable: true },
{ id: 'qty', title: '수량', kind: 'number', width: 100, editable: true },
{
id: 'price',
title: '단가',
kind: 'number',
width: 120,
editable: true,
formatValue: (value: unknown) => Number(value).toLocaleString('ko-KR'),
},
{
id: 'done',
title: '완료',
kind: 'boolean',
width: 90,
editable: true,
formatValue: (value: unknown) => (value ? '✓' : ''),
},
],
rows,
rowKey: 'id',
cellSelection: 'multiple',
cellNotes: [{ rowKey: 2, columnId: 'qty', text: '단체 주문이라 미리 만들어 두기' }],
};
// 버튼(actions)도 알림을 남길 수 있게 setup에서 받은 log를 보관해요.
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log({
ko: '칸을 오른쪽 버튼으로 눌러 보세요. 메모와 붙여넣기 결과가 여기에 남아요.',
en: 'Right-click a cell. Notes and paste results appear here.',
});
const offs = [
api.on('cellNoteChanged', ({ rowKey, columnId, text }) => {
const name = api.getRowByKey(rowKey)?.menu ?? rowKey;
log({
ko: text === null ? `${name} 메모를 지웠어요 (${columnId})` : `${name} 메모: ${text}`,
en: text === null ? `${name} note removed (${columnId})` : `${name} note: ${text}`,
});
}),
api.on('cellsPasted', ({ pasted, skipped }) =>
log({
ko: `붙여넣기: ${pasted}칸 바꿨고 ${skipped}칸은 건너뛰었어요`,
en: `Paste: ${pasted} cells changed, ${skipped} skipped`,
}),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
// 메뉴를 켜거나, 항목을 직접 정하거나(예: '복사'만 남기기), 끄는 방법이에요.
menu: (api: GridApi<Row>, value?: string) => {
if (value === 'off') return api.setOptions({ cellMenu: false });
if (value === 'custom')
return api.setOptions({
cellMenu: {
items: (defaults) =>
defaults.filter(
(item) =>
['copy', 'note-add', 'note-edit', 'note-remove'].includes(item.id) ||
item.separator,
),
},
});
api.setOptions({ cellMenu: true });
},
// copyCells()는 고른 칸을 엑셀에 그대로 붙는 글자로 돌려줘요. header: 'columns'면 컬럼 제목이 맨 위에 붙어요.
copyCode: (api: GridApi<Row>) => {
const text = api.copyCells({ header: 'columns' });
say({
ko:
text === ''
? '고른 칸이 없어요. 먼저 칸을 끌어 보세요'
: text.replaceAll('\t', ' | ').replaceAll('\r\n', ' / '),
en:
text === ''
? 'No cells selected. Drag across some cells first'
: text.replaceAll('\t', ' | ').replaceAll('\r\n', ' / '),
});
},
// pasteCells()는 탭·줄바꿈으로 나뉜 글자를 고른 칸(없으면 포커스 칸)부터 채워요. 편집과 같은 검증을 거쳐요.
pasteCode: (api: GridApi<Row>) => {
if (api.getSelectedCells().length === 0) api.selectCells({ rowKey: 1, columnId: 'menu' });
api.pasteCells('샘플 음료\t12\t5500\ttrue');
},
noteCode: (api: GridApi<Row>) => api.setCellNote(1, 'menu', '대표 메뉴예요'),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<select aria-label="Right-click menu" id="menu">
<option value="on" selected>On (default)</option>
<option value="custom">Custom items</option>
<option value="off">Off (browser menu)</option>
</select>
<button type="button" id="copyCode">Get picked cells as text</button>
<button type="button" id="pasteCode">Paste in code</button>
<button type="button" id="noteCode">Add a note in code</button>
</div>
<div id="grid" style="height: 360px"></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('menu').addEventListener('change', (event) => actions.menu(api, event.target.value));
document.getElementById('copyCode').addEventListener('click', () => actions.copyCode(api));
document.getElementById('pasteCode').addEventListener('click', () => actions.pasteCode(api));
document.getElementById('noteCode').addEventListener('click', () => actions.noteCode(api));// A cafe order sheet. Name, quantity, price and done can be edited, so cut and paste change values.
const menus = [
'Americano',
'Cafe Latte',
'Vanilla Latte',
'Cold Brew',
'Cappuccino',
'Green Tea Latte',
'Strawberry Smoothie',
'Lemonade',
];
const rows = menus.map((menu, i) => ({
id: i + 1,
menu,
qty: 3 + ((i * 7) % 9),
price: (4000 + i * 300) / 1000,
done: i % 3 === 0,
}));
// cellMenu is on by default (set it to false to get the browser's own menu).
// cellNotes can attach notes from the start, and getCellNotes() returns the notes to save.
export const options = {
columns: [
{ id: 'menu', title: 'Menu', width: 170, editable: true },
{ id: 'qty', title: 'Qty', kind: 'number', width: 100, editable: true },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 120,
editable: true,
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
{
id: 'done',
title: 'Done',
kind: 'boolean',
width: 90,
editable: true,
formatValue: (value) => (value ? '✓' : ''),
},
],
rows,
rowKey: 'id',
cellSelection: 'multiple',
cellNotes: [{ rowKey: 2, columnId: 'qty', text: 'Group order, prepare in advance' }],
};
// Keep the log received in setup so the buttons (actions) can leave messages too.
let say = () => { };
export function setup(api, log) {
say = log;
log('Right-click a cell. Notes and paste results appear here.');
const offs = [
api.on('cellNoteChanged', ({ rowKey, columnId, text }) => {
const name = api.getRowByKey(rowKey)?.menu ?? rowKey;
log(text === null ? `${name} note removed (${columnId})` : `${name} note: ${text}`);
}),
api.on('cellsPasted', ({ pasted, skipped }) => log(`Paste: ${pasted} cells changed, ${skipped} skipped`)),
];
return () => offs.forEach((off) => off());
}
export const actions = {
// Turn the menu on, choose its items yourself (for example keep only 'copy'), or turn it off.
menu: (api, value) => {
if (value === 'off')
return api.setOptions({ cellMenu: false });
if (value === 'custom')
return api.setOptions({
cellMenu: {
items: (defaults) => defaults.filter((item) => ['copy', 'note-add', 'note-edit', 'note-remove'].includes(item.id) ||
item.separator),
},
});
api.setOptions({ cellMenu: true });
},
// copyCells() returns the selected cells as text that pastes straight into a spreadsheet. With header: 'columns', the column titles go on top.
copyCode: (api) => {
const text = api.copyCells({ header: 'columns' });
say(text === ''
? 'No cells selected. Drag across some cells first'
: text.replaceAll('\t', ' | ').replaceAll('\r\n', ' / '));
},
// pasteCells() fills from the selected cells (or the focused cell) with text split by tabs and line breaks. It goes through the same validation as editing.
pasteCode: (api) => {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'menu' });
api.pasteCells('Sample drink\t12\t5.5\ttrue');
},
noteCode: (api) => api.setCellNote(1, 'menu', 'Signature item'),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Right-click a cell to copy, paste and add notes</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Right-click menu" id="menu">
<option value="on" selected>On (default)</option>
<option value="custom">Custom items</option>
<option value="off">Off (browser menu)</option>
</select>
<button type="button" id="copyCode">Get picked cells as text</button>
<button type="button" id="pasteCode">Paste in code</button>
<button type="button" id="noteCode">Add a note in code</button>
</div>
<div id="grid" style="height: 360px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// A cafe order sheet. Name, quantity, price and done can be edited, so cut and paste change values.
const menus = [
'Americano',
'Cafe Latte',
'Vanilla Latte',
'Cold Brew',
'Cappuccino',
'Green Tea Latte',
'Strawberry Smoothie',
'Lemonade',
];
const rows = menus.map((menu, i) => ({
id: i + 1,
menu,
qty: 3 + ((i * 7) % 9),
price: (4000 + i * 300) / 1000,
done: i % 3 === 0,
}));
// cellMenu is on by default (set it to false to get the browser's own menu).
// cellNotes can attach notes from the start, and getCellNotes() returns the notes to save.
const options = {
columns: [
{ id: 'menu', title: 'Menu', width: 170, editable: true },
{ id: 'qty', title: 'Qty', kind: 'number', width: 100, editable: true },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 120,
editable: true,
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
{
id: 'done',
title: 'Done',
kind: 'boolean',
width: 90,
editable: true,
formatValue: (value) => (value ? '✓' : ''),
},
],
rows,
rowKey: 'id',
cellSelection: 'multiple',
cellNotes: [{ rowKey: 2, columnId: 'qty', text: 'Group order, prepare in advance' }],
};
// Keep the log received in setup so the buttons (actions) can leave messages too.
let say = () => { };
function setup(api, log) {
say = log;
log('Right-click a cell. Notes and paste results appear here.');
const offs = [
api.on('cellNoteChanged', ({ rowKey, columnId, text }) => {
const name = api.getRowByKey(rowKey)?.menu ?? rowKey;
log(text === null ? `${name} note removed (${columnId})` : `${name} note: ${text}`);
}),
api.on('cellsPasted', ({ pasted, skipped }) => log(`Paste: ${pasted} cells changed, ${skipped} skipped`)),
];
return () => offs.forEach((off) => off());
}
const actions = {
// Turn the menu on, choose its items yourself (for example keep only 'copy'), or turn it off.
menu: (api, value) => {
if (value === 'off')
return api.setOptions({ cellMenu: false });
if (value === 'custom')
return api.setOptions({
cellMenu: {
items: (defaults) => defaults.filter((item) => ['copy', 'note-add', 'note-edit', 'note-remove'].includes(item.id) ||
item.separator),
},
});
api.setOptions({ cellMenu: true });
},
// copyCells() returns the selected cells as text that pastes straight into a spreadsheet. With header: 'columns', the column titles go on top.
copyCode: (api) => {
const text = api.copyCells({ header: 'columns' });
say(text === ''
? 'No cells selected. Drag across some cells first'
: text.replaceAll('\t', ' | ').replaceAll('\r\n', ' / '));
},
// pasteCells() fills from the selected cells (or the focused cell) with text split by tabs and line breaks. It goes through the same validation as editing.
pasteCode: (api) => {
if (api.getSelectedCells().length === 0)
api.selectCells({ rowKey: 1, columnId: 'menu' });
api.pasteCells('Sample drink\t12\t5.5\ttrue');
},
noteCode: (api) => api.setCellNote(1, 'menu', 'Signature item'),
};
options.ariaLabel = "Right-click a cell to copy, paste and add notes";
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('menu').addEventListener('change', (event) => actions.menu(api, event.target.value));
document.getElementById('copyCode').addEventListener('click', () => actions.copyCode(api));
document.getElementById('pasteCode').addEventListener('click', () => actions.pasteCode(api));
document.getElementById('noteCode').addEventListener('click', () => actions.noteCode(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">
<select
aria-label="Right-click menu"
disabled={!api}
onChange={(event) => api && actions.menu(api, event.target.value)}
>
<option value="on">On (default)</option>
<option value="custom">Custom items</option>
<option value="off">Off (browser menu)</option>
</select>
<button
type="button"
disabled={!api}
onClick={() => api && actions.copyCode(api)}
>Get picked cells as text</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.pasteCode(api)}
>Paste in code</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.noteCode(api)}
>Add a note in code</button>
</div>
<Grid style={{ height: 360 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
menu: string;
qty: number;
price: number;
done: boolean;
}
// A cafe order sheet. Name, quantity, price and done can be edited, so cut and paste change values.
const menus = [
'Americano',
'Cafe Latte',
'Vanilla Latte',
'Cold Brew',
'Cappuccino',
'Green Tea Latte',
'Strawberry Smoothie',
'Lemonade',
];
const rows: Row[] = menus.map((menu, i) => ({
id: i + 1,
menu,
qty: 3 + ((i * 7) % 9),
price: (4000 + i * 300) / 1000,
done: i % 3 === 0,
}));
// cellMenu is on by default (set it to false to get the browser's own menu).
// cellNotes can attach notes from the start, and getCellNotes() returns the notes to save.
export const options: GridOptions<Row> = {
columns: [
{ id: 'menu', title: 'Menu', width: 170, editable: true },
{ id: 'qty', title: 'Qty', kind: 'number', width: 100, editable: true },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 120,
editable: true,
formatValue: (value: unknown) => Number(value).toLocaleString('en-US'),
},
{
id: 'done',
title: 'Done',
kind: 'boolean',
width: 90,
editable: true,
formatValue: (value: unknown) => (value ? '✓' : ''),
},
],
rows,
rowKey: 'id',
cellSelection: 'multiple',
cellNotes: [{ rowKey: 2, columnId: 'qty', text: 'Group order, prepare in advance' }],
};
// Keep the log received in setup so the buttons (actions) can leave messages too.
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log('Right-click a cell. Notes and paste results appear here.');
const offs = [
api.on('cellNoteChanged', ({ rowKey, columnId, text }) => {
const name = api.getRowByKey(rowKey)?.menu ?? rowKey;
log(text === null ? `${name} note removed (${columnId})` : `${name} note: ${text}`);
}),
api.on('cellsPasted', ({ pasted, skipped }) =>
log(`Paste: ${pasted} cells changed, ${skipped} skipped`),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
// Turn the menu on, choose its items yourself (for example keep only 'copy'), or turn it off.
menu: (api: GridApi<Row>, value?: string) => {
if (value === 'off') return api.setOptions({ cellMenu: false });
if (value === 'custom')
return api.setOptions({
cellMenu: {
items: (defaults) =>
defaults.filter(
(item) =>
['copy', 'note-add', 'note-edit', 'note-remove'].includes(item.id) ||
item.separator,
),
},
});
api.setOptions({ cellMenu: true });
},
// copyCells() returns the selected cells as text that pastes straight into a spreadsheet. With header: 'columns', the column titles go on top.
copyCode: (api: GridApi<Row>) => {
const text = api.copyCells({ header: 'columns' });
say(
text === ''
? 'No cells selected. Drag across some cells first'
: text.replaceAll('\t', ' | ').replaceAll('\r\n', ' / '),
);
},
// pasteCells() fills from the selected cells (or the focused cell) with text split by tabs and line breaks. It goes through the same validation as editing.
pasteCode: (api: GridApi<Row>) => {
if (api.getSelectedCells().length === 0) api.selectCells({ rowKey: 1, columnId: 'menu' });
api.pasteCells('Sample drink\t12\t5.5\ttrue');
},
noteCode: (api: GridApi<Row>) => api.setCellNote(1, 'menu', 'Signature item'),
};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">
<select
aria-label="Right-click menu"
:disabled="!api"
@change="api && actions.menu(api, ($event.target as HTMLSelectElement).value)"
>
<option value="on" selected>On (default)</option>
<option value="custom">Custom items</option>
<option value="off">Off (browser menu)</option>
</select>
<button
type="button"
:disabled="!api"
@click="api && actions.copyCode(api)"
>Get picked cells as text</button>
<button
type="button"
:disabled="!api"
@click="api && actions.pasteCode(api)"
>Paste in code</button>
<button
type="button"
:disabled="!api"
@click="api && actions.noteCode(api)"
>Add a note in code</button>
</div>
<Grid style="height: 360px" :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;
menu: string;
qty: number;
price: number;
done: boolean;
}
// A cafe order sheet. Name, quantity, price and done can be edited, so cut and paste change values.
const menus = [
'Americano',
'Cafe Latte',
'Vanilla Latte',
'Cold Brew',
'Cappuccino',
'Green Tea Latte',
'Strawberry Smoothie',
'Lemonade',
];
const rows: Row[] = menus.map((menu, i) => ({
id: i + 1,
menu,
qty: 3 + ((i * 7) % 9),
price: (4000 + i * 300) / 1000,
done: i % 3 === 0,
}));
// cellMenu is on by default (set it to false to get the browser's own menu).
// cellNotes can attach notes from the start, and getCellNotes() returns the notes to save.
export const options: GridOptions<Row> = {
columns: [
{ id: 'menu', title: 'Menu', width: 170, editable: true },
{ id: 'qty', title: 'Qty', kind: 'number', width: 100, editable: true },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 120,
editable: true,
formatValue: (value: unknown) => Number(value).toLocaleString('en-US'),
},
{
id: 'done',
title: 'Done',
kind: 'boolean',
width: 90,
editable: true,
formatValue: (value: unknown) => (value ? '✓' : ''),
},
],
rows,
rowKey: 'id',
cellSelection: 'multiple',
cellNotes: [{ rowKey: 2, columnId: 'qty', text: 'Group order, prepare in advance' }],
};
// Keep the log received in setup so the buttons (actions) can leave messages too.
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log('Right-click a cell. Notes and paste results appear here.');
const offs = [
api.on('cellNoteChanged', ({ rowKey, columnId, text }) => {
const name = api.getRowByKey(rowKey)?.menu ?? rowKey;
log(text === null ? `${name} note removed (${columnId})` : `${name} note: ${text}`);
}),
api.on('cellsPasted', ({ pasted, skipped }) =>
log(`Paste: ${pasted} cells changed, ${skipped} skipped`),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
// Turn the menu on, choose its items yourself (for example keep only 'copy'), or turn it off.
menu: (api: GridApi<Row>, value?: string) => {
if (value === 'off') return api.setOptions({ cellMenu: false });
if (value === 'custom')
return api.setOptions({
cellMenu: {
items: (defaults) =>
defaults.filter(
(item) =>
['copy', 'note-add', 'note-edit', 'note-remove'].includes(item.id) ||
item.separator,
),
},
});
api.setOptions({ cellMenu: true });
},
// copyCells() returns the selected cells as text that pastes straight into a spreadsheet. With header: 'columns', the column titles go on top.
copyCode: (api: GridApi<Row>) => {
const text = api.copyCells({ header: 'columns' });
say(
text === ''
? 'No cells selected. Drag across some cells first'
: text.replaceAll('\t', ' | ').replaceAll('\r\n', ' / '),
);
},
// pasteCells() fills from the selected cells (or the focused cell) with text split by tabs and line breaks. It goes through the same validation as editing.
pasteCode: (api: GridApi<Row>) => {
if (api.getSelectedCells().length === 0) api.selectCells({ rowKey: 1, columnId: 'menu' });
api.pasteCells('Sample drink\t12\t5.5\ttrue');
},
noteCode: (api: GridApi<Row>) => api.setCellNote(1, 'menu', 'Signature item'),
};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">
<select
aria-label="Right-click menu"
[disabled]="!api"
(change)="api && actions.menu(api, $any($event.target).value)"
>
<option value="on" selected>On (default)</option>
<option value="custom">Custom items</option>
<option value="off">Off (browser menu)</option>
</select>
<button
type="button"
[disabled]="!api"
(click)="api && actions.copyCode(api)"
>Get picked cells as text</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.pasteCode(api)"
>Paste in code</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.noteCode(api)"
>Add a note in code</button>
</div>
<mx-grid style="height: 360px" [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;
menu: string;
qty: number;
price: number;
done: boolean;
}
// A cafe order sheet. Name, quantity, price and done can be edited, so cut and paste change values.
const menus = [
'Americano',
'Cafe Latte',
'Vanilla Latte',
'Cold Brew',
'Cappuccino',
'Green Tea Latte',
'Strawberry Smoothie',
'Lemonade',
];
const rows: Row[] = menus.map((menu, i) => ({
id: i + 1,
menu,
qty: 3 + ((i * 7) % 9),
price: (4000 + i * 300) / 1000,
done: i % 3 === 0,
}));
// cellMenu is on by default (set it to false to get the browser's own menu).
// cellNotes can attach notes from the start, and getCellNotes() returns the notes to save.
export const options: GridOptions<Row> = {
columns: [
{ id: 'menu', title: 'Menu', width: 170, editable: true },
{ id: 'qty', title: 'Qty', kind: 'number', width: 100, editable: true },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 120,
editable: true,
formatValue: (value: unknown) => Number(value).toLocaleString('en-US'),
},
{
id: 'done',
title: 'Done',
kind: 'boolean',
width: 90,
editable: true,
formatValue: (value: unknown) => (value ? '✓' : ''),
},
],
rows,
rowKey: 'id',
cellSelection: 'multiple',
cellNotes: [{ rowKey: 2, columnId: 'qty', text: 'Group order, prepare in advance' }],
};
// Keep the log received in setup so the buttons (actions) can leave messages too.
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
log('Right-click a cell. Notes and paste results appear here.');
const offs = [
api.on('cellNoteChanged', ({ rowKey, columnId, text }) => {
const name = api.getRowByKey(rowKey)?.menu ?? rowKey;
log(text === null ? `${name} note removed (${columnId})` : `${name} note: ${text}`);
}),
api.on('cellsPasted', ({ pasted, skipped }) =>
log(`Paste: ${pasted} cells changed, ${skipped} skipped`),
),
];
return () => offs.forEach((off) => off());
}
export const actions = {
// Turn the menu on, choose its items yourself (for example keep only 'copy'), or turn it off.
menu: (api: GridApi<Row>, value?: string) => {
if (value === 'off') return api.setOptions({ cellMenu: false });
if (value === 'custom')
return api.setOptions({
cellMenu: {
items: (defaults) =>
defaults.filter(
(item) =>
['copy', 'note-add', 'note-edit', 'note-remove'].includes(item.id) ||
item.separator,
),
},
});
api.setOptions({ cellMenu: true });
},
// copyCells() returns the selected cells as text that pastes straight into a spreadsheet. With header: 'columns', the column titles go on top.
copyCode: (api: GridApi<Row>) => {
const text = api.copyCells({ header: 'columns' });
say(
text === ''
? 'No cells selected. Drag across some cells first'
: text.replaceAll('\t', ' | ').replaceAll('\r\n', ' / '),
);
},
// pasteCells() fills from the selected cells (or the focused cell) with text split by tabs and line breaks. It goes through the same validation as editing.
pasteCode: (api: GridApi<Row>) => {
if (api.getSelectedCells().length === 0) api.selectCells({ rowKey: 1, columnId: 'menu' });
api.pasteCells('Sample drink\t12\t5.5\ttrue');
},
noteCode: (api: GridApi<Row>) => api.setCellNote(1, 'menu', 'Signature item'),
};