별점: 보기만 하는 별과 눌러서 바꾸는 별Ratings: read-only stars and clickable stars
내장 별점으로 평점을 보여 주고, 직접 만든 칸으로 별을 눌러 내 평점을 바꿔요. 같은 별을 다시 누르면 지워져요.Show ratings with the built-in stars and let people change their own rating by clicking stars in a custom cell. Clicking the same star again clears it.
코드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">
<button type="button" id="clear">내 평점 모두 지우기</button>
</div>
<div id="grid" style="height: 260px"></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('clear').addEventListener('click', () => actions.clear(api));// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
// 손가락으로 쓰는 화면(폰)인지 알려 줘요. 이런 화면에서는 누를 곳을 40px 이상으로 키워요.
const coarse = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 칸 안의 내용은 기본으로 세로 가운데가 아니에요. .mxg-cell-center 상자에 넣으면 가운데에 와요.
const centered = (el) => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// 왼쪽 "고객 평점"은 내장 별점이라 보기만 해요(반올림하고 0~별 개수로 맞춰요). "내 평점"은 별을 누르면 바뀌는
// 직접 만든 칸이에요. 별은 버튼이라 Tab으로 이동해 Enter·Space로 고를 수 있고, 별 사이는 좌우 화살표로 옮겨요.
// 그리기만 하고, 누름은 setup에서 한 번만 받아서 값을 바꿔요.
const MAX = 5;
const stars = () => {
let root;
let marks = [];
return {
mount(el, ctx) {
root = centered(el);
root.setAttribute('role', 'radiogroup');
marks = Array.from({ length: MAX }, (_, i) => {
const star = document.createElement('button');
star.type = 'button';
star.dataset.star = String(i + 1);
star.setAttribute('role', 'radio');
const size = coarse() ? 40 : 24;
star.style.cssText = `cursor: pointer; font: inherit; font-size: 18px; min-width: ${size}px; height: ${size}px; padding: 0; border: 0; background: transparent;`;
star.addEventListener('keydown', (event) => {
if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft')
return;
event.preventDefault();
// 양 끝에서는 더 가지 않고 멈춰요(처음으로 돌아가지 않아요).
marks[Math.max(0, Math.min(MAX - 1, i + (event.key === 'ArrowRight' ? 1 : -1)))]?.focus();
});
root.append(star);
return star;
});
this.update(ctx);
},
update(ctx) {
const value = Math.round(Number(ctx.value) || 0);
root.setAttribute('aria-label', L(`${ctx.row.product} 내 평점`, `${ctx.row.product} my rating`));
marks.forEach((star, i) => {
star.textContent = i < value ? '★' : '☆';
star.setAttribute('aria-label', L(`별 ${i + 1}개`, `${i + 1} ${i === 0 ? 'star' : 'stars'}`));
star.setAttribute('aria-checked', String(i + 1 === value));
// 칸에 들어가면 지금 점수의 별(0점이면 첫 별)에서 시작하도록, 그 별만 Tab으로 닿게 해요.
star.tabIndex = i === Math.max(0, value - 1) ? 0 : -1;
star.style.color = i < value ? 'var(--mxg-accent)' : 'var(--mxg-fg-muted)';
});
},
destroy() {
marks = [];
},
};
};
const review = {
id: 'review',
title: '고객 평점(보기만)',
kind: 'number',
width: 150,
cellRenderer: 'rating',
};
const mine = {
id: 'mine',
title: '내 평점(눌러서 바꾸기)',
kind: 'number',
width: coarse() ? 230 : 190,
cellRenderer: stars,
};
export const options = {
// 폰에서는 눌러서 바꾸는 칸을 먼저 보여요.
columns: [
{ id: 'product', title: '상품', width: 150 },
...(coarse() ? [mine, review] : [review, mine]),
],
rows: [
{ id: 1, product: '높이 조절 책상', review: 5, mine: 5 },
{ id: 2, product: '메쉬 의자', review: 4, mine: 4 },
{ id: 3, product: '모니터 받침대', review: 3.6, mine: 3 },
{ id: 4, product: '스탠드 조명', review: 2, mine: 2 },
{ id: 5, product: '케이블 정리함', review: null, mine: 0 },
],
rowKey: 'id',
saveMode: 'none', // 이 예제는 저장 흐름이 아니라서 "저장 안 한 변경" 표시를 쓰지 않아요
...(coarse() ? { rowHeight: 44 } : {}),
};
export function setup(api, log) {
log({
ko: '고객 평점 3.6은 4개로 반올림해서 그려요. 비어 있으면 아무것도 그리지 않아요.',
en: 'The customer rating 3.6 is drawn rounded to 4. An empty value draws nothing.',
});
return api.on('cellClicked', (e) => {
const star = e.event.target?.closest('[data-star]');
if (e.columnId !== 'mine' || !star)
return;
const next = Number(star.dataset.star);
// 지금 점수와 같은 별을 다시 누르면 0점으로 지워요.
const value = next === e.row.mine ? 0 : next;
api.updateRows([{ ...e.row, mine: value }]);
log({ ko: `${e.row.product}: 내 평점 ${value}점`, en: `${e.row.product}: my rating ${value}` });
});
}
export const actions = {
clear: (api) => {
api.updateRows(api.getRows().map((row) => ({ ...row, mine: 0 })));
},
};<!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="clear">내 평점 모두 지우기</button>
</div>
<div id="grid" style="height: 260px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
// 손가락으로 쓰는 화면(폰)인지 알려 줘요. 이런 화면에서는 누를 곳을 40px 이상으로 키워요.
const coarse = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 칸 안의 내용은 기본으로 세로 가운데가 아니에요. .mxg-cell-center 상자에 넣으면 가운데에 와요.
const centered = (el) => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// 왼쪽 "고객 평점"은 내장 별점이라 보기만 해요(반올림하고 0~별 개수로 맞춰요). "내 평점"은 별을 누르면 바뀌는
// 직접 만든 칸이에요. 별은 버튼이라 Tab으로 이동해 Enter·Space로 고를 수 있고, 별 사이는 좌우 화살표로 옮겨요.
// 그리기만 하고, 누름은 setup에서 한 번만 받아서 값을 바꿔요.
const MAX = 5;
const stars = () => {
let root;
let marks = [];
return {
mount(el, ctx) {
root = centered(el);
root.setAttribute('role', 'radiogroup');
marks = Array.from({ length: MAX }, (_, i) => {
const star = document.createElement('button');
star.type = 'button';
star.dataset.star = String(i + 1);
star.setAttribute('role', 'radio');
const size = coarse() ? 40 : 24;
star.style.cssText = `cursor: pointer; font: inherit; font-size: 18px; min-width: ${size}px; height: ${size}px; padding: 0; border: 0; background: transparent;`;
star.addEventListener('keydown', (event) => {
if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft')
return;
event.preventDefault();
// 양 끝에서는 더 가지 않고 멈춰요(처음으로 돌아가지 않아요).
marks[Math.max(0, Math.min(MAX - 1, i + (event.key === 'ArrowRight' ? 1 : -1)))]?.focus();
});
root.append(star);
return star;
});
this.update(ctx);
},
update(ctx) {
const value = Math.round(Number(ctx.value) || 0);
root.setAttribute('aria-label', L(`${ctx.row.product} 내 평점`, `${ctx.row.product} my rating`));
marks.forEach((star, i) => {
star.textContent = i < value ? '★' : '☆';
star.setAttribute('aria-label', L(`별 ${i + 1}개`, `${i + 1} ${i === 0 ? 'star' : 'stars'}`));
star.setAttribute('aria-checked', String(i + 1 === value));
// 칸에 들어가면 지금 점수의 별(0점이면 첫 별)에서 시작하도록, 그 별만 Tab으로 닿게 해요.
star.tabIndex = i === Math.max(0, value - 1) ? 0 : -1;
star.style.color = i < value ? 'var(--mxg-accent)' : 'var(--mxg-fg-muted)';
});
},
destroy() {
marks = [];
},
};
};
const review = {
id: 'review',
title: '고객 평점(보기만)',
kind: 'number',
width: 150,
cellRenderer: 'rating',
};
const mine = {
id: 'mine',
title: '내 평점(눌러서 바꾸기)',
kind: 'number',
width: coarse() ? 230 : 190,
cellRenderer: stars,
};
const options = {
// 폰에서는 눌러서 바꾸는 칸을 먼저 보여요.
columns: [
{ id: 'product', title: '상품', width: 150 },
...(coarse() ? [mine, review] : [review, mine]),
],
rows: [
{ id: 1, product: '높이 조절 책상', review: 5, mine: 5 },
{ id: 2, product: '메쉬 의자', review: 4, mine: 4 },
{ id: 3, product: '모니터 받침대', review: 3.6, mine: 3 },
{ id: 4, product: '스탠드 조명', review: 2, mine: 2 },
{ id: 5, product: '케이블 정리함', review: null, mine: 0 },
],
rowKey: 'id',
saveMode: 'none', // 이 예제는 저장 흐름이 아니라서 "저장 안 한 변경" 표시를 쓰지 않아요
...(coarse() ? { rowHeight: 44 } : {}),
};
function setup(api, log) {
log({
ko: '고객 평점 3.6은 4개로 반올림해서 그려요. 비어 있으면 아무것도 그리지 않아요.',
en: 'The customer rating 3.6 is drawn rounded to 4. An empty value draws nothing.',
});
return api.on('cellClicked', (e) => {
const star = e.event.target?.closest('[data-star]');
if (e.columnId !== 'mine' || !star)
return;
const next = Number(star.dataset.star);
// 지금 점수와 같은 별을 다시 누르면 0점으로 지워요.
const value = next === e.row.mine ? 0 : next;
api.updateRows([{ ...e.row, mine: value }]);
log({ ko: `${e.row.product}: 내 평점 ${value}점`, en: `${e.row.product}: my rating ${value}` });
});
}
const actions = {
clear: (api) => {
api.updateRows(api.getRows().map((row) => ({ ...row, mine: 0 })));
},
};
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('clear').addEventListener('click', () => actions.clear(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">
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>내 평점 모두 지우기</button>
</div>
<Grid style={{ height: 260 }} ref={gridRef} options={options} />
</>
);
}import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/react';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
product: string;
review: number | null;
mine: number;
}
// 손가락으로 쓰는 화면(폰)인지 알려 줘요. 이런 화면에서는 누를 곳을 40px 이상으로 키워요.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 칸 안의 내용은 기본으로 세로 가운데가 아니에요. .mxg-cell-center 상자에 넣으면 가운데에 와요.
const centered = (el: HTMLElement): HTMLElement => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// 왼쪽 "고객 평점"은 내장 별점이라 보기만 해요(반올림하고 0~별 개수로 맞춰요). "내 평점"은 별을 누르면 바뀌는
// 직접 만든 칸이에요. 별은 버튼이라 Tab으로 이동해 Enter·Space로 고를 수 있고, 별 사이는 좌우 화살표로 옮겨요.
// 그리기만 하고, 누름은 setup에서 한 번만 받아서 값을 바꿔요.
const MAX = 5;
const stars = (): CellRendererAdapter<Row> => {
let root: HTMLElement;
let marks: HTMLButtonElement[] = [];
return {
mount(el, ctx) {
root = centered(el);
root.setAttribute('role', 'radiogroup');
marks = Array.from({ length: MAX }, (_, i) => {
const star = document.createElement('button');
star.type = 'button';
star.dataset.star = String(i + 1);
star.setAttribute('role', 'radio');
const size = coarse() ? 40 : 24;
star.style.cssText = `cursor: pointer; font: inherit; font-size: 18px; min-width: ${size}px; height: ${size}px; padding: 0; border: 0; background: transparent;`;
star.addEventListener('keydown', (event) => {
if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft') return;
event.preventDefault();
// 양 끝에서는 더 가지 않고 멈춰요(처음으로 돌아가지 않아요).
marks[Math.max(0, Math.min(MAX - 1, i + (event.key === 'ArrowRight' ? 1 : -1)))]?.focus();
});
root.append(star);
return star;
});
this.update(ctx);
},
update(ctx) {
const value = Math.round(Number(ctx.value) || 0);
root.setAttribute(
'aria-label',
L(`${ctx.row.product} 내 평점`, `${ctx.row.product} my rating`),
);
marks.forEach((star, i) => {
star.textContent = i < value ? '★' : '☆';
star.setAttribute(
'aria-label',
L(`별 ${i + 1}개`, `${i + 1} ${i === 0 ? 'star' : 'stars'}`),
);
star.setAttribute('aria-checked', String(i + 1 === value));
// 칸에 들어가면 지금 점수의 별(0점이면 첫 별)에서 시작하도록, 그 별만 Tab으로 닿게 해요.
star.tabIndex = i === Math.max(0, value - 1) ? 0 : -1;
star.style.color = i < value ? 'var(--mxg-accent)' : 'var(--mxg-fg-muted)';
});
},
destroy() {
marks = [];
},
};
};
const review = {
id: 'review',
title: '고객 평점(보기만)',
kind: 'number',
width: 150,
cellRenderer: 'rating',
} as const;
const mine = {
id: 'mine',
title: '내 평점(눌러서 바꾸기)',
kind: 'number',
width: coarse() ? 230 : 190,
cellRenderer: stars,
} as const;
export const options: GridOptions<Row> = {
// 폰에서는 눌러서 바꾸는 칸을 먼저 보여요.
columns: [
{ id: 'product', title: '상품', width: 150 },
...(coarse() ? [mine, review] : [review, mine]),
],
rows: [
{ id: 1, product: '높이 조절 책상', review: 5, mine: 5 },
{ id: 2, product: '메쉬 의자', review: 4, mine: 4 },
{ id: 3, product: '모니터 받침대', review: 3.6, mine: 3 },
{ id: 4, product: '스탠드 조명', review: 2, mine: 2 },
{ id: 5, product: '케이블 정리함', review: null, mine: 0 },
],
rowKey: 'id',
saveMode: 'none', // 이 예제는 저장 흐름이 아니라서 "저장 안 한 변경" 표시를 쓰지 않아요
...(coarse() ? { rowHeight: 44 } : {}),
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log({
ko: '고객 평점 3.6은 4개로 반올림해서 그려요. 비어 있으면 아무것도 그리지 않아요.',
en: 'The customer rating 3.6 is drawn rounded to 4. An empty value draws nothing.',
});
return api.on('cellClicked', (e) => {
const star = (e.event.target as HTMLElement | null)?.closest<HTMLElement>('[data-star]');
if (e.columnId !== 'mine' || !star) return;
const next = Number(star.dataset.star);
// 지금 점수와 같은 별을 다시 누르면 0점으로 지워요.
const value = next === e.row.mine ? 0 : next;
api.updateRows([{ ...e.row, mine: value }]);
log({ ko: `${e.row.product}: 내 평점 ${value}점`, en: `${e.row.product}: my rating ${value}` });
});
}
export const actions = {
clear: (api: GridApi<Row>) => {
api.updateRows(api.getRows().map((row) => ({ ...row, mine: 0 })));
},
};버튼을 누르면 이 예제의 코드가 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.clear(api)">내 평점 모두 지우기</button>
</div>
<Grid style="height: 260px" :options="options" @ready="onReady" />
</template>import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/vue';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
product: string;
review: number | null;
mine: number;
}
// 손가락으로 쓰는 화면(폰)인지 알려 줘요. 이런 화면에서는 누를 곳을 40px 이상으로 키워요.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 칸 안의 내용은 기본으로 세로 가운데가 아니에요. .mxg-cell-center 상자에 넣으면 가운데에 와요.
const centered = (el: HTMLElement): HTMLElement => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// 왼쪽 "고객 평점"은 내장 별점이라 보기만 해요(반올림하고 0~별 개수로 맞춰요). "내 평점"은 별을 누르면 바뀌는
// 직접 만든 칸이에요. 별은 버튼이라 Tab으로 이동해 Enter·Space로 고를 수 있고, 별 사이는 좌우 화살표로 옮겨요.
// 그리기만 하고, 누름은 setup에서 한 번만 받아서 값을 바꿔요.
const MAX = 5;
const stars = (): CellRendererAdapter<Row> => {
let root: HTMLElement;
let marks: HTMLButtonElement[] = [];
return {
mount(el, ctx) {
root = centered(el);
root.setAttribute('role', 'radiogroup');
marks = Array.from({ length: MAX }, (_, i) => {
const star = document.createElement('button');
star.type = 'button';
star.dataset.star = String(i + 1);
star.setAttribute('role', 'radio');
const size = coarse() ? 40 : 24;
star.style.cssText = `cursor: pointer; font: inherit; font-size: 18px; min-width: ${size}px; height: ${size}px; padding: 0; border: 0; background: transparent;`;
star.addEventListener('keydown', (event) => {
if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft') return;
event.preventDefault();
// 양 끝에서는 더 가지 않고 멈춰요(처음으로 돌아가지 않아요).
marks[Math.max(0, Math.min(MAX - 1, i + (event.key === 'ArrowRight' ? 1 : -1)))]?.focus();
});
root.append(star);
return star;
});
this.update(ctx);
},
update(ctx) {
const value = Math.round(Number(ctx.value) || 0);
root.setAttribute(
'aria-label',
L(`${ctx.row.product} 내 평점`, `${ctx.row.product} my rating`),
);
marks.forEach((star, i) => {
star.textContent = i < value ? '★' : '☆';
star.setAttribute(
'aria-label',
L(`별 ${i + 1}개`, `${i + 1} ${i === 0 ? 'star' : 'stars'}`),
);
star.setAttribute('aria-checked', String(i + 1 === value));
// 칸에 들어가면 지금 점수의 별(0점이면 첫 별)에서 시작하도록, 그 별만 Tab으로 닿게 해요.
star.tabIndex = i === Math.max(0, value - 1) ? 0 : -1;
star.style.color = i < value ? 'var(--mxg-accent)' : 'var(--mxg-fg-muted)';
});
},
destroy() {
marks = [];
},
};
};
const review = {
id: 'review',
title: '고객 평점(보기만)',
kind: 'number',
width: 150,
cellRenderer: 'rating',
} as const;
const mine = {
id: 'mine',
title: '내 평점(눌러서 바꾸기)',
kind: 'number',
width: coarse() ? 230 : 190,
cellRenderer: stars,
} as const;
export const options: GridOptions<Row> = {
// 폰에서는 눌러서 바꾸는 칸을 먼저 보여요.
columns: [
{ id: 'product', title: '상품', width: 150 },
...(coarse() ? [mine, review] : [review, mine]),
],
rows: [
{ id: 1, product: '높이 조절 책상', review: 5, mine: 5 },
{ id: 2, product: '메쉬 의자', review: 4, mine: 4 },
{ id: 3, product: '모니터 받침대', review: 3.6, mine: 3 },
{ id: 4, product: '스탠드 조명', review: 2, mine: 2 },
{ id: 5, product: '케이블 정리함', review: null, mine: 0 },
],
rowKey: 'id',
saveMode: 'none', // 이 예제는 저장 흐름이 아니라서 "저장 안 한 변경" 표시를 쓰지 않아요
...(coarse() ? { rowHeight: 44 } : {}),
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log({
ko: '고객 평점 3.6은 4개로 반올림해서 그려요. 비어 있으면 아무것도 그리지 않아요.',
en: 'The customer rating 3.6 is drawn rounded to 4. An empty value draws nothing.',
});
return api.on('cellClicked', (e) => {
const star = (e.event.target as HTMLElement | null)?.closest<HTMLElement>('[data-star]');
if (e.columnId !== 'mine' || !star) return;
const next = Number(star.dataset.star);
// 지금 점수와 같은 별을 다시 누르면 0점으로 지워요.
const value = next === e.row.mine ? 0 : next;
api.updateRows([{ ...e.row, mine: value }]);
log({ ko: `${e.row.product}: 내 평점 ${value}점`, en: `${e.row.product}: my rating ${value}` });
});
}
export const actions = {
clear: (api: GridApi<Row>) => {
api.updateRows(api.getRows().map((row) => ({ ...row, mine: 0 })));
},
};버튼을 누르면 이 예제의 코드가 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.clear(api)"
>내 평점 모두 지우기</button>
</div>
<mx-grid style="height: 260px" [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 { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/angular';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
product: string;
review: number | null;
mine: number;
}
// 손가락으로 쓰는 화면(폰)인지 알려 줘요. 이런 화면에서는 누를 곳을 40px 이상으로 키워요.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 칸 안의 내용은 기본으로 세로 가운데가 아니에요. .mxg-cell-center 상자에 넣으면 가운데에 와요.
const centered = (el: HTMLElement): HTMLElement => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// 왼쪽 "고객 평점"은 내장 별점이라 보기만 해요(반올림하고 0~별 개수로 맞춰요). "내 평점"은 별을 누르면 바뀌는
// 직접 만든 칸이에요. 별은 버튼이라 Tab으로 이동해 Enter·Space로 고를 수 있고, 별 사이는 좌우 화살표로 옮겨요.
// 그리기만 하고, 누름은 setup에서 한 번만 받아서 값을 바꿔요.
const MAX = 5;
const stars = (): CellRendererAdapter<Row> => {
let root: HTMLElement;
let marks: HTMLButtonElement[] = [];
return {
mount(el, ctx) {
root = centered(el);
root.setAttribute('role', 'radiogroup');
marks = Array.from({ length: MAX }, (_, i) => {
const star = document.createElement('button');
star.type = 'button';
star.dataset.star = String(i + 1);
star.setAttribute('role', 'radio');
const size = coarse() ? 40 : 24;
star.style.cssText = `cursor: pointer; font: inherit; font-size: 18px; min-width: ${size}px; height: ${size}px; padding: 0; border: 0; background: transparent;`;
star.addEventListener('keydown', (event) => {
if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft') return;
event.preventDefault();
// 양 끝에서는 더 가지 않고 멈춰요(처음으로 돌아가지 않아요).
marks[Math.max(0, Math.min(MAX - 1, i + (event.key === 'ArrowRight' ? 1 : -1)))]?.focus();
});
root.append(star);
return star;
});
this.update(ctx);
},
update(ctx) {
const value = Math.round(Number(ctx.value) || 0);
root.setAttribute(
'aria-label',
L(`${ctx.row.product} 내 평점`, `${ctx.row.product} my rating`),
);
marks.forEach((star, i) => {
star.textContent = i < value ? '★' : '☆';
star.setAttribute(
'aria-label',
L(`별 ${i + 1}개`, `${i + 1} ${i === 0 ? 'star' : 'stars'}`),
);
star.setAttribute('aria-checked', String(i + 1 === value));
// 칸에 들어가면 지금 점수의 별(0점이면 첫 별)에서 시작하도록, 그 별만 Tab으로 닿게 해요.
star.tabIndex = i === Math.max(0, value - 1) ? 0 : -1;
star.style.color = i < value ? 'var(--mxg-accent)' : 'var(--mxg-fg-muted)';
});
},
destroy() {
marks = [];
},
};
};
const review = {
id: 'review',
title: '고객 평점(보기만)',
kind: 'number',
width: 150,
cellRenderer: 'rating',
} as const;
const mine = {
id: 'mine',
title: '내 평점(눌러서 바꾸기)',
kind: 'number',
width: coarse() ? 230 : 190,
cellRenderer: stars,
} as const;
export const options: GridOptions<Row> = {
// 폰에서는 눌러서 바꾸는 칸을 먼저 보여요.
columns: [
{ id: 'product', title: '상품', width: 150 },
...(coarse() ? [mine, review] : [review, mine]),
],
rows: [
{ id: 1, product: '높이 조절 책상', review: 5, mine: 5 },
{ id: 2, product: '메쉬 의자', review: 4, mine: 4 },
{ id: 3, product: '모니터 받침대', review: 3.6, mine: 3 },
{ id: 4, product: '스탠드 조명', review: 2, mine: 2 },
{ id: 5, product: '케이블 정리함', review: null, mine: 0 },
],
rowKey: 'id',
saveMode: 'none', // 이 예제는 저장 흐름이 아니라서 "저장 안 한 변경" 표시를 쓰지 않아요
...(coarse() ? { rowHeight: 44 } : {}),
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log({
ko: '고객 평점 3.6은 4개로 반올림해서 그려요. 비어 있으면 아무것도 그리지 않아요.',
en: 'The customer rating 3.6 is drawn rounded to 4. An empty value draws nothing.',
});
return api.on('cellClicked', (e) => {
const star = (e.event.target as HTMLElement | null)?.closest<HTMLElement>('[data-star]');
if (e.columnId !== 'mine' || !star) return;
const next = Number(star.dataset.star);
// 지금 점수와 같은 별을 다시 누르면 0점으로 지워요.
const value = next === e.row.mine ? 0 : next;
api.updateRows([{ ...e.row, mine: value }]);
log({ ko: `${e.row.product}: 내 평점 ${value}점`, en: `${e.row.product}: my rating ${value}` });
});
}
export const actions = {
clear: (api: GridApi<Row>) => {
api.updateRows(api.getRows().map((row) => ({ ...row, mine: 0 })));
},
};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="clear">Clear all my ratings</button>
</div>
<div id="grid" style="height: 260px"></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('clear').addEventListener('click', () => actions.clear(api));// Tells whether this is a touch screen (phone). On such screens the tap target grows to at least 40px.
const coarse = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// Cell content is not vertically centered by default. Putting it in a .mxg-cell-center box centers it.
const centered = (el) => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// The left "Customer rating" is the built-in star rating and is read-only (rounded and clamped to 0..star count). "My rating" is
// a custom cell that changes when you click a star. Stars are buttons, so Tab moves to them and Enter/Space picks one; left/right arrows move between stars.
// It only draws; clicks are handled once in setup, which changes the value.
const MAX = 5;
const stars = () => {
let root;
let marks = [];
return {
mount(el, ctx) {
root = centered(el);
root.setAttribute('role', 'radiogroup');
marks = Array.from({ length: MAX }, (_, i) => {
const star = document.createElement('button');
star.type = 'button';
star.dataset.star = String(i + 1);
star.setAttribute('role', 'radio');
const size = coarse() ? 40 : 24;
star.style.cssText = `cursor: pointer; font: inherit; font-size: 18px; min-width: ${size}px; height: ${size}px; padding: 0; border: 0; background: transparent;`;
star.addEventListener('keydown', (event) => {
if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft')
return;
event.preventDefault();
// Stop at either end instead of wrapping around to the start.
marks[Math.max(0, Math.min(MAX - 1, i + (event.key === 'ArrowRight' ? 1 : -1)))]?.focus();
});
root.append(star);
return star;
});
this.update(ctx);
},
update(ctx) {
const value = Math.round(Number(ctx.value) || 0);
root.setAttribute('aria-label', `${ctx.row.product} my rating`);
marks.forEach((star, i) => {
star.textContent = i < value ? '★' : '☆';
star.setAttribute('aria-label', `${i + 1} ${i === 0 ? 'star' : 'stars'}`);
star.setAttribute('aria-checked', String(i + 1 === value));
// Only the star for the current score (the first star at 0) is reachable by Tab, so entering the cell starts there.
star.tabIndex = i === Math.max(0, value - 1) ? 0 : -1;
star.style.color = i < value ? 'var(--mxg-accent)' : 'var(--mxg-fg-muted)';
});
},
destroy() {
marks = [];
},
};
};
const review = {
id: 'review',
title: 'Customer rating (read-only)',
kind: 'number',
width: 190,
cellRenderer: 'rating',
};
const mine = {
id: 'mine',
title: 'My rating (click to change)',
kind: 'number',
width: coarse() ? 240 : 210,
cellRenderer: stars,
};
export const options = {
// On a phone, the clickable cell comes first.
columns: [
{ id: 'product', title: 'Product', width: 150 },
...(coarse() ? [mine, review] : [review, mine]),
],
rows: [
{ id: 1, product: 'Height-adjustable desk', review: 5, mine: 5 },
{ id: 2, product: 'Mesh chair', review: 4, mine: 4 },
{ id: 3, product: 'Monitor stand', review: 3.6, mine: 3 },
{ id: 4, product: 'Desk lamp', review: 2, mine: 2 },
{ id: 5, product: 'Cable organizer', review: null, mine: 0 },
],
rowKey: 'id',
saveMode: 'none', // This example is not a save flow, so it does not use the "unsaved changes" marker
...(coarse() ? { rowHeight: 44 } : {}),
};
export function setup(api, log) {
log('The customer rating 3.6 is drawn rounded to 4. An empty value draws nothing.');
return api.on('cellClicked', (e) => {
const star = e.event.target?.closest('[data-star]');
if (e.columnId !== 'mine' || !star)
return;
const next = Number(star.dataset.star);
// Clicking the star equal to the current score again clears it to 0.
const value = next === e.row.mine ? 0 : next;
api.updateRows([{ ...e.row, mine: value }]);
log(`${e.row.product}: my rating ${value}`);
});
}
export const actions = {
clear: (api) => {
api.updateRows(api.getRows().map((row) => ({ ...row, mine: 0 })));
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Ratings: read-only stars and clickable stars</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="clear">Clear all my ratings</button>
</div>
<div id="grid" style="height: 260px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// Tells whether this is a touch screen (phone). On such screens the tap target grows to at least 40px.
const coarse = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// Cell content is not vertically centered by default. Putting it in a .mxg-cell-center box centers it.
const centered = (el) => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// The left "Customer rating" is the built-in star rating and is read-only (rounded and clamped to 0..star count). "My rating" is
// a custom cell that changes when you click a star. Stars are buttons, so Tab moves to them and Enter/Space picks one; left/right arrows move between stars.
// It only draws; clicks are handled once in setup, which changes the value.
const MAX = 5;
const stars = () => {
let root;
let marks = [];
return {
mount(el, ctx) {
root = centered(el);
root.setAttribute('role', 'radiogroup');
marks = Array.from({ length: MAX }, (_, i) => {
const star = document.createElement('button');
star.type = 'button';
star.dataset.star = String(i + 1);
star.setAttribute('role', 'radio');
const size = coarse() ? 40 : 24;
star.style.cssText = `cursor: pointer; font: inherit; font-size: 18px; min-width: ${size}px; height: ${size}px; padding: 0; border: 0; background: transparent;`;
star.addEventListener('keydown', (event) => {
if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft')
return;
event.preventDefault();
// Stop at either end instead of wrapping around to the start.
marks[Math.max(0, Math.min(MAX - 1, i + (event.key === 'ArrowRight' ? 1 : -1)))]?.focus();
});
root.append(star);
return star;
});
this.update(ctx);
},
update(ctx) {
const value = Math.round(Number(ctx.value) || 0);
root.setAttribute('aria-label', `${ctx.row.product} my rating`);
marks.forEach((star, i) => {
star.textContent = i < value ? '★' : '☆';
star.setAttribute('aria-label', `${i + 1} ${i === 0 ? 'star' : 'stars'}`);
star.setAttribute('aria-checked', String(i + 1 === value));
// Only the star for the current score (the first star at 0) is reachable by Tab, so entering the cell starts there.
star.tabIndex = i === Math.max(0, value - 1) ? 0 : -1;
star.style.color = i < value ? 'var(--mxg-accent)' : 'var(--mxg-fg-muted)';
});
},
destroy() {
marks = [];
},
};
};
const review = {
id: 'review',
title: 'Customer rating (read-only)',
kind: 'number',
width: 190,
cellRenderer: 'rating',
};
const mine = {
id: 'mine',
title: 'My rating (click to change)',
kind: 'number',
width: coarse() ? 240 : 210,
cellRenderer: stars,
};
const options = {
// On a phone, the clickable cell comes first.
columns: [
{ id: 'product', title: 'Product', width: 150 },
...(coarse() ? [mine, review] : [review, mine]),
],
rows: [
{ id: 1, product: 'Height-adjustable desk', review: 5, mine: 5 },
{ id: 2, product: 'Mesh chair', review: 4, mine: 4 },
{ id: 3, product: 'Monitor stand', review: 3.6, mine: 3 },
{ id: 4, product: 'Desk lamp', review: 2, mine: 2 },
{ id: 5, product: 'Cable organizer', review: null, mine: 0 },
],
rowKey: 'id',
saveMode: 'none', // This example is not a save flow, so it does not use the "unsaved changes" marker
...(coarse() ? { rowHeight: 44 } : {}),
};
function setup(api, log) {
log('The customer rating 3.6 is drawn rounded to 4. An empty value draws nothing.');
return api.on('cellClicked', (e) => {
const star = e.event.target?.closest('[data-star]');
if (e.columnId !== 'mine' || !star)
return;
const next = Number(star.dataset.star);
// Clicking the star equal to the current score again clears it to 0.
const value = next === e.row.mine ? 0 : next;
api.updateRows([{ ...e.row, mine: value }]);
log(`${e.row.product}: my rating ${value}`);
});
}
const actions = {
clear: (api) => {
api.updateRows(api.getRows().map((row) => ({ ...row, mine: 0 })));
},
};
options.ariaLabel = "Ratings: read-only stars and clickable stars";
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('clear').addEventListener('click', () => actions.clear(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">
<button
type="button"
disabled={!api}
onClick={() => api && actions.clear(api)}
>Clear all my ratings</button>
</div>
<Grid style={{ height: 260 }} ref={gridRef} options={options} />
</>
);
}import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
product: string;
review: number | null;
mine: number;
}
// Tells whether this is a touch screen (phone). On such screens the tap target grows to at least 40px.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// Cell content is not vertically centered by default. Putting it in a .mxg-cell-center box centers it.
const centered = (el: HTMLElement): HTMLElement => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// The left "Customer rating" is the built-in star rating and is read-only (rounded and clamped to 0..star count). "My rating" is
// a custom cell that changes when you click a star. Stars are buttons, so Tab moves to them and Enter/Space picks one; left/right arrows move between stars.
// It only draws; clicks are handled once in setup, which changes the value.
const MAX = 5;
const stars = (): CellRendererAdapter<Row> => {
let root: HTMLElement;
let marks: HTMLButtonElement[] = [];
return {
mount(el, ctx) {
root = centered(el);
root.setAttribute('role', 'radiogroup');
marks = Array.from({ length: MAX }, (_, i) => {
const star = document.createElement('button');
star.type = 'button';
star.dataset.star = String(i + 1);
star.setAttribute('role', 'radio');
const size = coarse() ? 40 : 24;
star.style.cssText = `cursor: pointer; font: inherit; font-size: 18px; min-width: ${size}px; height: ${size}px; padding: 0; border: 0; background: transparent;`;
star.addEventListener('keydown', (event) => {
if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft') return;
event.preventDefault();
// Stop at either end instead of wrapping around to the start.
marks[Math.max(0, Math.min(MAX - 1, i + (event.key === 'ArrowRight' ? 1 : -1)))]?.focus();
});
root.append(star);
return star;
});
this.update(ctx);
},
update(ctx) {
const value = Math.round(Number(ctx.value) || 0);
root.setAttribute('aria-label', `${ctx.row.product} my rating`);
marks.forEach((star, i) => {
star.textContent = i < value ? '★' : '☆';
star.setAttribute('aria-label', `${i + 1} ${i === 0 ? 'star' : 'stars'}`);
star.setAttribute('aria-checked', String(i + 1 === value));
// Only the star for the current score (the first star at 0) is reachable by Tab, so entering the cell starts there.
star.tabIndex = i === Math.max(0, value - 1) ? 0 : -1;
star.style.color = i < value ? 'var(--mxg-accent)' : 'var(--mxg-fg-muted)';
});
},
destroy() {
marks = [];
},
};
};
const review = {
id: 'review',
title: 'Customer rating (read-only)',
kind: 'number',
width: 190,
cellRenderer: 'rating',
} as const;
const mine = {
id: 'mine',
title: 'My rating (click to change)',
kind: 'number',
width: coarse() ? 240 : 210,
cellRenderer: stars,
} as const;
export const options: GridOptions<Row> = {
// On a phone, the clickable cell comes first.
columns: [
{ id: 'product', title: 'Product', width: 150 },
...(coarse() ? [mine, review] : [review, mine]),
],
rows: [
{ id: 1, product: 'Height-adjustable desk', review: 5, mine: 5 },
{ id: 2, product: 'Mesh chair', review: 4, mine: 4 },
{ id: 3, product: 'Monitor stand', review: 3.6, mine: 3 },
{ id: 4, product: 'Desk lamp', review: 2, mine: 2 },
{ id: 5, product: 'Cable organizer', review: null, mine: 0 },
],
rowKey: 'id',
saveMode: 'none', // This example is not a save flow, so it does not use the "unsaved changes" marker
...(coarse() ? { rowHeight: 44 } : {}),
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log('The customer rating 3.6 is drawn rounded to 4. An empty value draws nothing.');
return api.on('cellClicked', (e) => {
const star = (e.event.target as HTMLElement | null)?.closest<HTMLElement>('[data-star]');
if (e.columnId !== 'mine' || !star) return;
const next = Number(star.dataset.star);
// Clicking the star equal to the current score again clears it to 0.
const value = next === e.row.mine ? 0 : next;
api.updateRows([{ ...e.row, mine: value }]);
log(`${e.row.product}: my rating ${value}`);
});
}
export const actions = {
clear: (api: GridApi<Row>) => {
api.updateRows(api.getRows().map((row) => ({ ...row, mine: 0 })));
},
};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.clear(api)">Clear all my ratings</button>
</div>
<Grid style="height: 260px" :options="options" @ready="onReady" />
</template>import type { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
product: string;
review: number | null;
mine: number;
}
// Tells whether this is a touch screen (phone). On such screens the tap target grows to at least 40px.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// Cell content is not vertically centered by default. Putting it in a .mxg-cell-center box centers it.
const centered = (el: HTMLElement): HTMLElement => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// The left "Customer rating" is the built-in star rating and is read-only (rounded and clamped to 0..star count). "My rating" is
// a custom cell that changes when you click a star. Stars are buttons, so Tab moves to them and Enter/Space picks one; left/right arrows move between stars.
// It only draws; clicks are handled once in setup, which changes the value.
const MAX = 5;
const stars = (): CellRendererAdapter<Row> => {
let root: HTMLElement;
let marks: HTMLButtonElement[] = [];
return {
mount(el, ctx) {
root = centered(el);
root.setAttribute('role', 'radiogroup');
marks = Array.from({ length: MAX }, (_, i) => {
const star = document.createElement('button');
star.type = 'button';
star.dataset.star = String(i + 1);
star.setAttribute('role', 'radio');
const size = coarse() ? 40 : 24;
star.style.cssText = `cursor: pointer; font: inherit; font-size: 18px; min-width: ${size}px; height: ${size}px; padding: 0; border: 0; background: transparent;`;
star.addEventListener('keydown', (event) => {
if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft') return;
event.preventDefault();
// Stop at either end instead of wrapping around to the start.
marks[Math.max(0, Math.min(MAX - 1, i + (event.key === 'ArrowRight' ? 1 : -1)))]?.focus();
});
root.append(star);
return star;
});
this.update(ctx);
},
update(ctx) {
const value = Math.round(Number(ctx.value) || 0);
root.setAttribute('aria-label', `${ctx.row.product} my rating`);
marks.forEach((star, i) => {
star.textContent = i < value ? '★' : '☆';
star.setAttribute('aria-label', `${i + 1} ${i === 0 ? 'star' : 'stars'}`);
star.setAttribute('aria-checked', String(i + 1 === value));
// Only the star for the current score (the first star at 0) is reachable by Tab, so entering the cell starts there.
star.tabIndex = i === Math.max(0, value - 1) ? 0 : -1;
star.style.color = i < value ? 'var(--mxg-accent)' : 'var(--mxg-fg-muted)';
});
},
destroy() {
marks = [];
},
};
};
const review = {
id: 'review',
title: 'Customer rating (read-only)',
kind: 'number',
width: 190,
cellRenderer: 'rating',
} as const;
const mine = {
id: 'mine',
title: 'My rating (click to change)',
kind: 'number',
width: coarse() ? 240 : 210,
cellRenderer: stars,
} as const;
export const options: GridOptions<Row> = {
// On a phone, the clickable cell comes first.
columns: [
{ id: 'product', title: 'Product', width: 150 },
...(coarse() ? [mine, review] : [review, mine]),
],
rows: [
{ id: 1, product: 'Height-adjustable desk', review: 5, mine: 5 },
{ id: 2, product: 'Mesh chair', review: 4, mine: 4 },
{ id: 3, product: 'Monitor stand', review: 3.6, mine: 3 },
{ id: 4, product: 'Desk lamp', review: 2, mine: 2 },
{ id: 5, product: 'Cable organizer', review: null, mine: 0 },
],
rowKey: 'id',
saveMode: 'none', // This example is not a save flow, so it does not use the "unsaved changes" marker
...(coarse() ? { rowHeight: 44 } : {}),
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log('The customer rating 3.6 is drawn rounded to 4. An empty value draws nothing.');
return api.on('cellClicked', (e) => {
const star = (e.event.target as HTMLElement | null)?.closest<HTMLElement>('[data-star]');
if (e.columnId !== 'mine' || !star) return;
const next = Number(star.dataset.star);
// Clicking the star equal to the current score again clears it to 0.
const value = next === e.row.mine ? 0 : next;
api.updateRows([{ ...e.row, mine: value }]);
log(`${e.row.product}: my rating ${value}`);
});
}
export const actions = {
clear: (api: GridApi<Row>) => {
api.updateRows(api.getRows().map((row) => ({ ...row, mine: 0 })));
},
};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.clear(api)"
>Clear all my ratings</button>
</div>
<mx-grid style="height: 260px" [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 { CellRendererAdapter, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
product: string;
review: number | null;
mine: number;
}
// Tells whether this is a touch screen (phone). On such screens the tap target grows to at least 40px.
const coarse = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// Cell content is not vertically centered by default. Putting it in a .mxg-cell-center box centers it.
const centered = (el: HTMLElement): HTMLElement => {
const box = document.createElement('div');
box.className = 'mxg-cell-center';
el.append(box);
return box;
};
// The left "Customer rating" is the built-in star rating and is read-only (rounded and clamped to 0..star count). "My rating" is
// a custom cell that changes when you click a star. Stars are buttons, so Tab moves to them and Enter/Space picks one; left/right arrows move between stars.
// It only draws; clicks are handled once in setup, which changes the value.
const MAX = 5;
const stars = (): CellRendererAdapter<Row> => {
let root: HTMLElement;
let marks: HTMLButtonElement[] = [];
return {
mount(el, ctx) {
root = centered(el);
root.setAttribute('role', 'radiogroup');
marks = Array.from({ length: MAX }, (_, i) => {
const star = document.createElement('button');
star.type = 'button';
star.dataset.star = String(i + 1);
star.setAttribute('role', 'radio');
const size = coarse() ? 40 : 24;
star.style.cssText = `cursor: pointer; font: inherit; font-size: 18px; min-width: ${size}px; height: ${size}px; padding: 0; border: 0; background: transparent;`;
star.addEventListener('keydown', (event) => {
if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft') return;
event.preventDefault();
// Stop at either end instead of wrapping around to the start.
marks[Math.max(0, Math.min(MAX - 1, i + (event.key === 'ArrowRight' ? 1 : -1)))]?.focus();
});
root.append(star);
return star;
});
this.update(ctx);
},
update(ctx) {
const value = Math.round(Number(ctx.value) || 0);
root.setAttribute('aria-label', `${ctx.row.product} my rating`);
marks.forEach((star, i) => {
star.textContent = i < value ? '★' : '☆';
star.setAttribute('aria-label', `${i + 1} ${i === 0 ? 'star' : 'stars'}`);
star.setAttribute('aria-checked', String(i + 1 === value));
// Only the star for the current score (the first star at 0) is reachable by Tab, so entering the cell starts there.
star.tabIndex = i === Math.max(0, value - 1) ? 0 : -1;
star.style.color = i < value ? 'var(--mxg-accent)' : 'var(--mxg-fg-muted)';
});
},
destroy() {
marks = [];
},
};
};
const review = {
id: 'review',
title: 'Customer rating (read-only)',
kind: 'number',
width: 190,
cellRenderer: 'rating',
} as const;
const mine = {
id: 'mine',
title: 'My rating (click to change)',
kind: 'number',
width: coarse() ? 240 : 210,
cellRenderer: stars,
} as const;
export const options: GridOptions<Row> = {
// On a phone, the clickable cell comes first.
columns: [
{ id: 'product', title: 'Product', width: 150 },
...(coarse() ? [mine, review] : [review, mine]),
],
rows: [
{ id: 1, product: 'Height-adjustable desk', review: 5, mine: 5 },
{ id: 2, product: 'Mesh chair', review: 4, mine: 4 },
{ id: 3, product: 'Monitor stand', review: 3.6, mine: 3 },
{ id: 4, product: 'Desk lamp', review: 2, mine: 2 },
{ id: 5, product: 'Cable organizer', review: null, mine: 0 },
],
rowKey: 'id',
saveMode: 'none', // This example is not a save flow, so it does not use the "unsaved changes" marker
...(coarse() ? { rowHeight: 44 } : {}),
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log('The customer rating 3.6 is drawn rounded to 4. An empty value draws nothing.');
return api.on('cellClicked', (e) => {
const star = (e.event.target as HTMLElement | null)?.closest<HTMLElement>('[data-star]');
if (e.columnId !== 'mine' || !star) return;
const next = Number(star.dataset.star);
// Clicking the star equal to the current score again clears it to 0.
const value = next === e.row.mine ? 0 : next;
api.updateRows([{ ...e.row, mine: value }]);
log(`${e.row.product}: my rating ${value}`);
});
}
export const actions = {
clear: (api: GridApi<Row>) => {
api.updateRows(api.getRows().map((row) => ({ ...row, mine: 0 })));
},
};