목록에서 고르거나 직접 쓰는 콤보박스A combo box: pick from a list or type your own
제안 목록에서 고를 수도 있고, 목록에 없는 값을 직접 쓸 수도 있는 편집기예요. 입력한 값을 기억해 두었다가 다음 제안에 넣는 방식도 고를 수 있어요.An editor that offers suggestions but also accepts values that are not in the list. You can also make it remember what people typed and offer it next time.
코드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="mode">
<option value="fixed" selected>고정 목록</option>
<option value="history">입력한 값도 기억</option>
</select>
</div>
<div id="grid" style="height: 310px"></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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));const base = ['서울', '부산', '인천', '대구', '대전', '광주', '울산', '수원'];
const employees = ['김서연', '이준호', '박민지', '최도윤', '정하은', '강지후'];
const cities = ['서울', '부산', '제주', '대구', '세종', '광주']; // 제주·세종은 제안 목록에 없는 도시예요.
const rows = employees.map((employee, i) => ({ id: i + 1, employee, city: cities[i] }));
let mode = 'fixed';
let history = []; // 직접 입력해서 확정한 값을 기억해 두는 곳
const suggestions = () => mode === 'history' ? [...base, ...history.filter((c) => !base.includes(c))] : base;
// 터치 화면(또는 폭이 좁은 화면)에서는 글자를 16px로 키워요. 13px 입력칸은 iOS가 화면을 확대해 버려요.
const touch = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 입력칸 + 제안 목록(<datalist>)으로 만든 콤보박스 편집기예요. 목록에서 고를 수도 있고, 목록에 없는 값을 직접 쓸 수도 있어요.
// 엄격한 드롭다운(select)과 달라서, 목록에 없는 도시도 그대로 받아요.
const cityEditor = () => {
let input;
let list;
let composing = false;
return {
mount(el, ctx) {
input = document.createElement('input');
list = document.createElement('datalist');
list.id = `cities-${String(ctx.rowKey)}`;
for (const city of suggestions())
list.append(new Option(city));
input.setAttribute('list', list.id);
input.value = String(ctx.value ?? '');
input.style.cssText = `width: 100%; height: 100%; box-sizing: border-box; border: 0; padding: 0 8px; font: inherit; font-size: ${touch() ? 16 : 13}px; background: var(--mxg-bg); color: var(--mxg-fg);`;
input.addEventListener('compositionstart', () => (composing = true));
input.addEventListener('compositionend', () => (composing = false));
// 목록에서 고르면 키 입력 없이 input 이벤트가 와요. 그때는 바로 확정해요.
input.addEventListener('input', (event) => {
if (!event.inputType && suggestions().includes(input.value))
ctx.commit();
});
el.append(input, list);
},
getValue: () => input.value.trim(),
focus() {
input.focus();
input.select();
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
input.title = message ?? '';
},
isComposing: () => composing,
destroy() {
input.remove();
list.remove();
},
};
};
// 이 콤보박스는 직접 만든 편집기(cellEditor)라서, 한 번 누르면 열리는 singleClickEdit은 적용되지 않고 다른 칸처럼 더블클릭이나 키로 열어요.
export const options = {
columns: [
{ id: 'employee', title: '직원', width: 120 },
{
id: 'city',
title: '근무 도시 (콤보박스)',
width: 200,
editable: true,
cellEditor: cityEditor,
validation: { required: true },
},
],
rows,
rowKey: 'id',
};
export function setup(api, log) {
log({
ko: '"근무 도시" 칸을 더블클릭하면 제안 목록이 나와요. 목록에 없는 도시도 쓸 수 있어요.',
en: 'Double-click a "근무 도시" (work city) cell to see suggestions. You can also type a city that is not in the list.',
});
return api.on('editCommitted', (e) => {
const city = String(e.newValue);
const known = suggestions().includes(city);
if (mode === 'history' && !base.includes(city) && !history.includes(city))
history = [...history, city];
log({
ko: `${e.rowKey}번 줄 도시: ${city}${known ? '' : mode === 'history' ? ' (새 값, 이제부터 제안에 나와요)' : ' (제안에 없는 값)'}`,
en: `Row ${e.rowKey} city: ${city}${known ? '' : mode === 'history' ? ' (new value, will appear in suggestions from now on)' : ' (not in the suggestions)'}`,
});
});
}
export const actions = {
mode: (_api, value) => {
mode = value === 'history' ? 'history' : 'fixed';
if (mode === 'fixed')
history = [];
},
};<!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="mode">
<option value="fixed" selected>고정 목록</option>
<option value="history">입력한 값도 기억</option>
</select>
</div>
<div id="grid" style="height: 310px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const base = ['서울', '부산', '인천', '대구', '대전', '광주', '울산', '수원'];
const employees = ['김서연', '이준호', '박민지', '최도윤', '정하은', '강지후'];
const cities = ['서울', '부산', '제주', '대구', '세종', '광주']; // 제주·세종은 제안 목록에 없는 도시예요.
const rows = employees.map((employee, i) => ({ id: i + 1, employee, city: cities[i] }));
let mode = 'fixed';
let history = []; // 직접 입력해서 확정한 값을 기억해 두는 곳
const suggestions = () => mode === 'history' ? [...base, ...history.filter((c) => !base.includes(c))] : base;
// 터치 화면(또는 폭이 좁은 화면)에서는 글자를 16px로 키워요. 13px 입력칸은 iOS가 화면을 확대해 버려요.
const touch = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 입력칸 + 제안 목록(<datalist>)으로 만든 콤보박스 편집기예요. 목록에서 고를 수도 있고, 목록에 없는 값을 직접 쓸 수도 있어요.
// 엄격한 드롭다운(select)과 달라서, 목록에 없는 도시도 그대로 받아요.
const cityEditor = () => {
let input;
let list;
let composing = false;
return {
mount(el, ctx) {
input = document.createElement('input');
list = document.createElement('datalist');
list.id = `cities-${String(ctx.rowKey)}`;
for (const city of suggestions())
list.append(new Option(city));
input.setAttribute('list', list.id);
input.value = String(ctx.value ?? '');
input.style.cssText = `width: 100%; height: 100%; box-sizing: border-box; border: 0; padding: 0 8px; font: inherit; font-size: ${touch() ? 16 : 13}px; background: var(--mxg-bg); color: var(--mxg-fg);`;
input.addEventListener('compositionstart', () => (composing = true));
input.addEventListener('compositionend', () => (composing = false));
// 목록에서 고르면 키 입력 없이 input 이벤트가 와요. 그때는 바로 확정해요.
input.addEventListener('input', (event) => {
if (!event.inputType && suggestions().includes(input.value))
ctx.commit();
});
el.append(input, list);
},
getValue: () => input.value.trim(),
focus() {
input.focus();
input.select();
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
input.title = message ?? '';
},
isComposing: () => composing,
destroy() {
input.remove();
list.remove();
},
};
};
// 이 콤보박스는 직접 만든 편집기(cellEditor)라서, 한 번 누르면 열리는 singleClickEdit은 적용되지 않고 다른 칸처럼 더블클릭이나 키로 열어요.
const options = {
columns: [
{ id: 'employee', title: '직원', width: 120 },
{
id: 'city',
title: '근무 도시 (콤보박스)',
width: 200,
editable: true,
cellEditor: cityEditor,
validation: { required: true },
},
],
rows,
rowKey: 'id',
};
function setup(api, log) {
log({
ko: '"근무 도시" 칸을 더블클릭하면 제안 목록이 나와요. 목록에 없는 도시도 쓸 수 있어요.',
en: 'Double-click a "근무 도시" (work city) cell to see suggestions. You can also type a city that is not in the list.',
});
return api.on('editCommitted', (e) => {
const city = String(e.newValue);
const known = suggestions().includes(city);
if (mode === 'history' && !base.includes(city) && !history.includes(city))
history = [...history, city];
log({
ko: `${e.rowKey}번 줄 도시: ${city}${known ? '' : mode === 'history' ? ' (새 값, 이제부터 제안에 나와요)' : ' (제안에 없는 값)'}`,
en: `Row ${e.rowKey} city: ${city}${known ? '' : mode === 'history' ? ' (new value, will appear in suggestions from now on)' : ' (not in the suggestions)'}`,
});
});
}
const actions = {
mode: (_api, value) => {
mode = value === 'history' ? 'history' : 'fixed';
if (mode === 'fixed')
history = [];
},
};
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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
</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.mode(api, event.target.value)}
>
<option value="fixed">고정 목록</option>
<option value="history">입력한 값도 기억</option>
</select>
</div>
<Grid style={{ height: 310 }} ref={gridRef} options={options} />
</>
);
}import type { CellEditorAdapter, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
employee: string;
city: string;
}
const base = ['서울', '부산', '인천', '대구', '대전', '광주', '울산', '수원'];
const employees = ['김서연', '이준호', '박민지', '최도윤', '정하은', '강지후'];
const cities = ['서울', '부산', '제주', '대구', '세종', '광주']; // 제주·세종은 제안 목록에 없는 도시예요.
const rows: Row[] = employees.map((employee, i) => ({ id: i + 1, employee, city: cities[i] }));
type Mode = 'fixed' | 'history';
let mode: Mode = 'fixed';
let history: string[] = []; // 직접 입력해서 확정한 값을 기억해 두는 곳
const suggestions = () =>
mode === 'history' ? [...base, ...history.filter((c) => !base.includes(c))] : base;
// 터치 화면(또는 폭이 좁은 화면)에서는 글자를 16px로 키워요. 13px 입력칸은 iOS가 화면을 확대해 버려요.
const touch = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 입력칸 + 제안 목록(<datalist>)으로 만든 콤보박스 편집기예요. 목록에서 고를 수도 있고, 목록에 없는 값을 직접 쓸 수도 있어요.
// 엄격한 드롭다운(select)과 달라서, 목록에 없는 도시도 그대로 받아요.
const cityEditor = (): CellEditorAdapter<Row> => {
let input: HTMLInputElement;
let list: HTMLDataListElement;
let composing = false;
return {
mount(el, ctx) {
input = document.createElement('input');
list = document.createElement('datalist');
list.id = `cities-${String(ctx.rowKey)}`;
for (const city of suggestions()) list.append(new Option(city));
input.setAttribute('list', list.id);
input.value = String(ctx.value ?? '');
input.style.cssText = `width: 100%; height: 100%; box-sizing: border-box; border: 0; padding: 0 8px; font: inherit; font-size: ${touch() ? 16 : 13}px; background: var(--mxg-bg); color: var(--mxg-fg);`;
input.addEventListener('compositionstart', () => (composing = true));
input.addEventListener('compositionend', () => (composing = false));
// 목록에서 고르면 키 입력 없이 input 이벤트가 와요. 그때는 바로 확정해요.
input.addEventListener('input', (event) => {
if (!(event as InputEvent).inputType && suggestions().includes(input.value)) ctx.commit();
});
el.append(input, list);
},
getValue: () => input.value.trim(),
focus() {
input.focus();
input.select();
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
input.title = message ?? '';
},
isComposing: () => composing,
destroy() {
input.remove();
list.remove();
},
};
};
// 이 콤보박스는 직접 만든 편집기(cellEditor)라서, 한 번 누르면 열리는 singleClickEdit은 적용되지 않고 다른 칸처럼 더블클릭이나 키로 열어요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'employee', title: '직원', width: 120 },
{
id: 'city',
title: '근무 도시 (콤보박스)',
width: 200,
editable: true,
cellEditor: cityEditor,
validation: { required: true },
},
],
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log({
ko: '"근무 도시" 칸을 더블클릭하면 제안 목록이 나와요. 목록에 없는 도시도 쓸 수 있어요.',
en: 'Double-click a "근무 도시" (work city) cell to see suggestions. You can also type a city that is not in the list.',
});
return api.on('editCommitted', (e) => {
const city = String(e.newValue);
const known = suggestions().includes(city);
if (mode === 'history' && !base.includes(city) && !history.includes(city))
history = [...history, city];
log({
ko: `${e.rowKey}번 줄 도시: ${city}${known ? '' : mode === 'history' ? ' (새 값, 이제부터 제안에 나와요)' : ' (제안에 없는 값)'}`,
en: `Row ${e.rowKey} city: ${city}${known ? '' : mode === 'history' ? ' (new value, will appear in suggestions from now on)' : ' (not in the suggestions)'}`,
});
});
}
export const actions = {
mode: (_api: GridApi<Row>, value?: string) => {
mode = value === 'history' ? 'history' : 'fixed';
if (mode === 'fixed') history = [];
},
};버튼을 누르면 이 예제의 코드가 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.mode(api, ($event.target as HTMLSelectElement).value)"
>
<option value="fixed" selected>고정 목록</option>
<option value="history">입력한 값도 기억</option>
</select>
</div>
<Grid style="height: 310px" :options="options" @ready="onReady" />
</template>import type { CellEditorAdapter, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
employee: string;
city: string;
}
const base = ['서울', '부산', '인천', '대구', '대전', '광주', '울산', '수원'];
const employees = ['김서연', '이준호', '박민지', '최도윤', '정하은', '강지후'];
const cities = ['서울', '부산', '제주', '대구', '세종', '광주']; // 제주·세종은 제안 목록에 없는 도시예요.
const rows: Row[] = employees.map((employee, i) => ({ id: i + 1, employee, city: cities[i] }));
type Mode = 'fixed' | 'history';
let mode: Mode = 'fixed';
let history: string[] = []; // 직접 입력해서 확정한 값을 기억해 두는 곳
const suggestions = () =>
mode === 'history' ? [...base, ...history.filter((c) => !base.includes(c))] : base;
// 터치 화면(또는 폭이 좁은 화면)에서는 글자를 16px로 키워요. 13px 입력칸은 iOS가 화면을 확대해 버려요.
const touch = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 입력칸 + 제안 목록(<datalist>)으로 만든 콤보박스 편집기예요. 목록에서 고를 수도 있고, 목록에 없는 값을 직접 쓸 수도 있어요.
// 엄격한 드롭다운(select)과 달라서, 목록에 없는 도시도 그대로 받아요.
const cityEditor = (): CellEditorAdapter<Row> => {
let input: HTMLInputElement;
let list: HTMLDataListElement;
let composing = false;
return {
mount(el, ctx) {
input = document.createElement('input');
list = document.createElement('datalist');
list.id = `cities-${String(ctx.rowKey)}`;
for (const city of suggestions()) list.append(new Option(city));
input.setAttribute('list', list.id);
input.value = String(ctx.value ?? '');
input.style.cssText = `width: 100%; height: 100%; box-sizing: border-box; border: 0; padding: 0 8px; font: inherit; font-size: ${touch() ? 16 : 13}px; background: var(--mxg-bg); color: var(--mxg-fg);`;
input.addEventListener('compositionstart', () => (composing = true));
input.addEventListener('compositionend', () => (composing = false));
// 목록에서 고르면 키 입력 없이 input 이벤트가 와요. 그때는 바로 확정해요.
input.addEventListener('input', (event) => {
if (!(event as InputEvent).inputType && suggestions().includes(input.value)) ctx.commit();
});
el.append(input, list);
},
getValue: () => input.value.trim(),
focus() {
input.focus();
input.select();
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
input.title = message ?? '';
},
isComposing: () => composing,
destroy() {
input.remove();
list.remove();
},
};
};
// 이 콤보박스는 직접 만든 편집기(cellEditor)라서, 한 번 누르면 열리는 singleClickEdit은 적용되지 않고 다른 칸처럼 더블클릭이나 키로 열어요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'employee', title: '직원', width: 120 },
{
id: 'city',
title: '근무 도시 (콤보박스)',
width: 200,
editable: true,
cellEditor: cityEditor,
validation: { required: true },
},
],
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log({
ko: '"근무 도시" 칸을 더블클릭하면 제안 목록이 나와요. 목록에 없는 도시도 쓸 수 있어요.',
en: 'Double-click a "근무 도시" (work city) cell to see suggestions. You can also type a city that is not in the list.',
});
return api.on('editCommitted', (e) => {
const city = String(e.newValue);
const known = suggestions().includes(city);
if (mode === 'history' && !base.includes(city) && !history.includes(city))
history = [...history, city];
log({
ko: `${e.rowKey}번 줄 도시: ${city}${known ? '' : mode === 'history' ? ' (새 값, 이제부터 제안에 나와요)' : ' (제안에 없는 값)'}`,
en: `Row ${e.rowKey} city: ${city}${known ? '' : mode === 'history' ? ' (new value, will appear in suggestions from now on)' : ' (not in the suggestions)'}`,
});
});
}
export const actions = {
mode: (_api: GridApi<Row>, value?: string) => {
mode = value === 'history' ? 'history' : 'fixed';
if (mode === 'fixed') history = [];
},
};버튼을 누르면 이 예제의 코드가 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.mode(api, $any($event.target).value)"
>
<option value="fixed" selected>고정 목록</option>
<option value="history">입력한 값도 기억</option>
</select>
</div>
<mx-grid style="height: 310px" [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 { CellEditorAdapter, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
employee: string;
city: string;
}
const base = ['서울', '부산', '인천', '대구', '대전', '광주', '울산', '수원'];
const employees = ['김서연', '이준호', '박민지', '최도윤', '정하은', '강지후'];
const cities = ['서울', '부산', '제주', '대구', '세종', '광주']; // 제주·세종은 제안 목록에 없는 도시예요.
const rows: Row[] = employees.map((employee, i) => ({ id: i + 1, employee, city: cities[i] }));
type Mode = 'fixed' | 'history';
let mode: Mode = 'fixed';
let history: string[] = []; // 직접 입력해서 확정한 값을 기억해 두는 곳
const suggestions = () =>
mode === 'history' ? [...base, ...history.filter((c) => !base.includes(c))] : base;
// 터치 화면(또는 폭이 좁은 화면)에서는 글자를 16px로 키워요. 13px 입력칸은 iOS가 화면을 확대해 버려요.
const touch = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// 입력칸 + 제안 목록(<datalist>)으로 만든 콤보박스 편집기예요. 목록에서 고를 수도 있고, 목록에 없는 값을 직접 쓸 수도 있어요.
// 엄격한 드롭다운(select)과 달라서, 목록에 없는 도시도 그대로 받아요.
const cityEditor = (): CellEditorAdapter<Row> => {
let input: HTMLInputElement;
let list: HTMLDataListElement;
let composing = false;
return {
mount(el, ctx) {
input = document.createElement('input');
list = document.createElement('datalist');
list.id = `cities-${String(ctx.rowKey)}`;
for (const city of suggestions()) list.append(new Option(city));
input.setAttribute('list', list.id);
input.value = String(ctx.value ?? '');
input.style.cssText = `width: 100%; height: 100%; box-sizing: border-box; border: 0; padding: 0 8px; font: inherit; font-size: ${touch() ? 16 : 13}px; background: var(--mxg-bg); color: var(--mxg-fg);`;
input.addEventListener('compositionstart', () => (composing = true));
input.addEventListener('compositionend', () => (composing = false));
// 목록에서 고르면 키 입력 없이 input 이벤트가 와요. 그때는 바로 확정해요.
input.addEventListener('input', (event) => {
if (!(event as InputEvent).inputType && suggestions().includes(input.value)) ctx.commit();
});
el.append(input, list);
},
getValue: () => input.value.trim(),
focus() {
input.focus();
input.select();
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
input.title = message ?? '';
},
isComposing: () => composing,
destroy() {
input.remove();
list.remove();
},
};
};
// 이 콤보박스는 직접 만든 편집기(cellEditor)라서, 한 번 누르면 열리는 singleClickEdit은 적용되지 않고 다른 칸처럼 더블클릭이나 키로 열어요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'employee', title: '직원', width: 120 },
{
id: 'city',
title: '근무 도시 (콤보박스)',
width: 200,
editable: true,
cellEditor: cityEditor,
validation: { required: true },
},
],
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log({
ko: '"근무 도시" 칸을 더블클릭하면 제안 목록이 나와요. 목록에 없는 도시도 쓸 수 있어요.',
en: 'Double-click a "근무 도시" (work city) cell to see suggestions. You can also type a city that is not in the list.',
});
return api.on('editCommitted', (e) => {
const city = String(e.newValue);
const known = suggestions().includes(city);
if (mode === 'history' && !base.includes(city) && !history.includes(city))
history = [...history, city];
log({
ko: `${e.rowKey}번 줄 도시: ${city}${known ? '' : mode === 'history' ? ' (새 값, 이제부터 제안에 나와요)' : ' (제안에 없는 값)'}`,
en: `Row ${e.rowKey} city: ${city}${known ? '' : mode === 'history' ? ' (new value, will appear in suggestions from now on)' : ' (not in the suggestions)'}`,
});
});
}
export const actions = {
mode: (_api: GridApi<Row>, value?: string) => {
mode = value === 'history' ? 'history' : 'fixed';
if (mode === 'fixed') history = [];
},
};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="Suggestions" id="mode">
<option value="fixed" selected>Fixed list</option>
<option value="history">Remember typed values</option>
</select>
</div>
<div id="grid" style="height: 310px"></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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));const base = [
'New York',
'Los Angeles',
'Chicago',
'Houston',
'Seattle',
'Boston',
'Austin',
'Denver',
];
const employees = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brooks',
'Ava Morgan',
];
const cities = ['New York', 'Los Angeles', 'Miami', 'Houston', 'Portland', 'Boston']; // Miami and Portland are not in the suggestion list.
const rows = employees.map((employee, i) => ({ id: i + 1, employee, city: cities[i] }));
let mode = 'fixed';
let history = []; // Remembers values that were typed in and committed
const suggestions = () => mode === 'history' ? [...base, ...history.filter((c) => !base.includes(c))] : base;
// On a touch screen (or a narrow screen) the text grows to 16px. iOS zooms the page for a 13px input.
const touch = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// A combobox editor built from an input plus a suggestion list (<datalist>). You can pick from the list or type a value that is not in it.
// Unlike a strict dropdown (select), cities that are not in the list are accepted as they are.
const cityEditor = () => {
let input;
let list;
let composing = false;
return {
mount(el, ctx) {
input = document.createElement('input');
list = document.createElement('datalist');
list.id = `cities-${String(ctx.rowKey)}`;
for (const city of suggestions())
list.append(new Option(city));
input.setAttribute('list', list.id);
input.value = String(ctx.value ?? '');
input.style.cssText = `width: 100%; height: 100%; box-sizing: border-box; border: 0; padding: 0 8px; font: inherit; font-size: ${touch() ? 16 : 13}px; background: var(--mxg-bg); color: var(--mxg-fg);`;
input.addEventListener('compositionstart', () => (composing = true));
input.addEventListener('compositionend', () => (composing = false));
// Picking from the list fires an input event without a key press. Commit right away in that case.
input.addEventListener('input', (event) => {
if (!event.inputType && suggestions().includes(input.value))
ctx.commit();
});
el.append(input, list);
},
getValue: () => input.value.trim(),
focus() {
input.focus();
input.select();
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
input.title = message ?? '';
},
isComposing: () => composing,
destroy() {
input.remove();
list.remove();
},
};
};
// This combobox is a hand-made editor (cellEditor), so singleClickEdit (open on one click) does not apply. Like other cells it opens with a double-click or a key.
export const options = {
columns: [
{ id: 'employee', title: 'Employee', width: 140 },
{
id: 'city',
title: 'Work city (combobox)',
width: 210,
editable: true,
cellEditor: cityEditor,
validation: { required: true },
},
],
rows,
rowKey: 'id',
};
export function setup(api, log) {
log('Double-click a "Work city" cell to see suggestions. You can also type a city that is not in the list.');
return api.on('editCommitted', (e) => {
const city = String(e.newValue);
const known = suggestions().includes(city);
if (mode === 'history' && !base.includes(city) && !history.includes(city))
history = [...history, city];
log(`Row ${e.rowKey} city: ${city}${known ? '' : mode === 'history' ? ' (new value, will appear in suggestions from now on)' : ' (not in the suggestions)'}`);
});
}
export const actions = {
mode: (_api, value) => {
mode = value === 'history' ? 'history' : 'fixed';
if (mode === 'fixed')
history = [];
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>A combo box: pick from a list or type your own</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Suggestions" id="mode">
<option value="fixed" selected>Fixed list</option>
<option value="history">Remember typed values</option>
</select>
</div>
<div id="grid" style="height: 310px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const base = [
'New York',
'Los Angeles',
'Chicago',
'Houston',
'Seattle',
'Boston',
'Austin',
'Denver',
];
const employees = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brooks',
'Ava Morgan',
];
const cities = ['New York', 'Los Angeles', 'Miami', 'Houston', 'Portland', 'Boston']; // Miami and Portland are not in the suggestion list.
const rows = employees.map((employee, i) => ({ id: i + 1, employee, city: cities[i] }));
let mode = 'fixed';
let history = []; // Remembers values that were typed in and committed
const suggestions = () => mode === 'history' ? [...base, ...history.filter((c) => !base.includes(c))] : base;
// On a touch screen (or a narrow screen) the text grows to 16px. iOS zooms the page for a 13px input.
const touch = () => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// A combobox editor built from an input plus a suggestion list (<datalist>). You can pick from the list or type a value that is not in it.
// Unlike a strict dropdown (select), cities that are not in the list are accepted as they are.
const cityEditor = () => {
let input;
let list;
let composing = false;
return {
mount(el, ctx) {
input = document.createElement('input');
list = document.createElement('datalist');
list.id = `cities-${String(ctx.rowKey)}`;
for (const city of suggestions())
list.append(new Option(city));
input.setAttribute('list', list.id);
input.value = String(ctx.value ?? '');
input.style.cssText = `width: 100%; height: 100%; box-sizing: border-box; border: 0; padding: 0 8px; font: inherit; font-size: ${touch() ? 16 : 13}px; background: var(--mxg-bg); color: var(--mxg-fg);`;
input.addEventListener('compositionstart', () => (composing = true));
input.addEventListener('compositionend', () => (composing = false));
// Picking from the list fires an input event without a key press. Commit right away in that case.
input.addEventListener('input', (event) => {
if (!event.inputType && suggestions().includes(input.value))
ctx.commit();
});
el.append(input, list);
},
getValue: () => input.value.trim(),
focus() {
input.focus();
input.select();
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
input.title = message ?? '';
},
isComposing: () => composing,
destroy() {
input.remove();
list.remove();
},
};
};
// This combobox is a hand-made editor (cellEditor), so singleClickEdit (open on one click) does not apply. Like other cells it opens with a double-click or a key.
const options = {
columns: [
{ id: 'employee', title: 'Employee', width: 140 },
{
id: 'city',
title: 'Work city (combobox)',
width: 210,
editable: true,
cellEditor: cityEditor,
validation: { required: true },
},
],
rows,
rowKey: 'id',
};
function setup(api, log) {
log('Double-click a "Work city" cell to see suggestions. You can also type a city that is not in the list.');
return api.on('editCommitted', (e) => {
const city = String(e.newValue);
const known = suggestions().includes(city);
if (mode === 'history' && !base.includes(city) && !history.includes(city))
history = [...history, city];
log(`Row ${e.rowKey} city: ${city}${known ? '' : mode === 'history' ? ' (new value, will appear in suggestions from now on)' : ' (not in the suggestions)'}`);
});
}
const actions = {
mode: (_api, value) => {
mode = value === 'history' ? 'history' : 'fixed';
if (mode === 'fixed')
history = [];
},
};
options.ariaLabel = "A combo box: pick from a list or type your own";
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('mode').addEventListener('change', (event) => actions.mode(api, event.target.value));
</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="Suggestions"
disabled={!api}
onChange={(event) => api && actions.mode(api, event.target.value)}
>
<option value="fixed">Fixed list</option>
<option value="history">Remember typed values</option>
</select>
</div>
<Grid style={{ height: 310 }} ref={gridRef} options={options} />
</>
);
}import type { CellEditorAdapter, GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
employee: string;
city: string;
}
const base = [
'New York',
'Los Angeles',
'Chicago',
'Houston',
'Seattle',
'Boston',
'Austin',
'Denver',
];
const employees = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brooks',
'Ava Morgan',
];
const cities = ['New York', 'Los Angeles', 'Miami', 'Houston', 'Portland', 'Boston']; // Miami and Portland are not in the suggestion list.
const rows: Row[] = employees.map((employee, i) => ({ id: i + 1, employee, city: cities[i] }));
type Mode = 'fixed' | 'history';
let mode: Mode = 'fixed';
let history: string[] = []; // Remembers values that were typed in and committed
const suggestions = () =>
mode === 'history' ? [...base, ...history.filter((c) => !base.includes(c))] : base;
// On a touch screen (or a narrow screen) the text grows to 16px. iOS zooms the page for a 13px input.
const touch = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// A combobox editor built from an input plus a suggestion list (<datalist>). You can pick from the list or type a value that is not in it.
// Unlike a strict dropdown (select), cities that are not in the list are accepted as they are.
const cityEditor = (): CellEditorAdapter<Row> => {
let input: HTMLInputElement;
let list: HTMLDataListElement;
let composing = false;
return {
mount(el, ctx) {
input = document.createElement('input');
list = document.createElement('datalist');
list.id = `cities-${String(ctx.rowKey)}`;
for (const city of suggestions()) list.append(new Option(city));
input.setAttribute('list', list.id);
input.value = String(ctx.value ?? '');
input.style.cssText = `width: 100%; height: 100%; box-sizing: border-box; border: 0; padding: 0 8px; font: inherit; font-size: ${touch() ? 16 : 13}px; background: var(--mxg-bg); color: var(--mxg-fg);`;
input.addEventListener('compositionstart', () => (composing = true));
input.addEventListener('compositionend', () => (composing = false));
// Picking from the list fires an input event without a key press. Commit right away in that case.
input.addEventListener('input', (event) => {
if (!(event as InputEvent).inputType && suggestions().includes(input.value)) ctx.commit();
});
el.append(input, list);
},
getValue: () => input.value.trim(),
focus() {
input.focus();
input.select();
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
input.title = message ?? '';
},
isComposing: () => composing,
destroy() {
input.remove();
list.remove();
},
};
};
// This combobox is a hand-made editor (cellEditor), so singleClickEdit (open on one click) does not apply. Like other cells it opens with a double-click or a key.
export const options: GridOptions<Row> = {
columns: [
{ id: 'employee', title: 'Employee', width: 140 },
{
id: 'city',
title: 'Work city (combobox)',
width: 210,
editable: true,
cellEditor: cityEditor,
validation: { required: true },
},
],
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log(
'Double-click a "Work city" cell to see suggestions. You can also type a city that is not in the list.',
);
return api.on('editCommitted', (e) => {
const city = String(e.newValue);
const known = suggestions().includes(city);
if (mode === 'history' && !base.includes(city) && !history.includes(city))
history = [...history, city];
log(
`Row ${e.rowKey} city: ${city}${known ? '' : mode === 'history' ? ' (new value, will appear in suggestions from now on)' : ' (not in the suggestions)'}`,
);
});
}
export const actions = {
mode: (_api: GridApi<Row>, value?: string) => {
mode = value === 'history' ? 'history' : 'fixed';
if (mode === 'fixed') history = [];
},
};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="Suggestions"
:disabled="!api"
@change="api && actions.mode(api, ($event.target as HTMLSelectElement).value)"
>
<option value="fixed" selected>Fixed list</option>
<option value="history">Remember typed values</option>
</select>
</div>
<Grid style="height: 310px" :options="options" @ready="onReady" />
</template>import type { CellEditorAdapter, GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
employee: string;
city: string;
}
const base = [
'New York',
'Los Angeles',
'Chicago',
'Houston',
'Seattle',
'Boston',
'Austin',
'Denver',
];
const employees = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brooks',
'Ava Morgan',
];
const cities = ['New York', 'Los Angeles', 'Miami', 'Houston', 'Portland', 'Boston']; // Miami and Portland are not in the suggestion list.
const rows: Row[] = employees.map((employee, i) => ({ id: i + 1, employee, city: cities[i] }));
type Mode = 'fixed' | 'history';
let mode: Mode = 'fixed';
let history: string[] = []; // Remembers values that were typed in and committed
const suggestions = () =>
mode === 'history' ? [...base, ...history.filter((c) => !base.includes(c))] : base;
// On a touch screen (or a narrow screen) the text grows to 16px. iOS zooms the page for a 13px input.
const touch = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// A combobox editor built from an input plus a suggestion list (<datalist>). You can pick from the list or type a value that is not in it.
// Unlike a strict dropdown (select), cities that are not in the list are accepted as they are.
const cityEditor = (): CellEditorAdapter<Row> => {
let input: HTMLInputElement;
let list: HTMLDataListElement;
let composing = false;
return {
mount(el, ctx) {
input = document.createElement('input');
list = document.createElement('datalist');
list.id = `cities-${String(ctx.rowKey)}`;
for (const city of suggestions()) list.append(new Option(city));
input.setAttribute('list', list.id);
input.value = String(ctx.value ?? '');
input.style.cssText = `width: 100%; height: 100%; box-sizing: border-box; border: 0; padding: 0 8px; font: inherit; font-size: ${touch() ? 16 : 13}px; background: var(--mxg-bg); color: var(--mxg-fg);`;
input.addEventListener('compositionstart', () => (composing = true));
input.addEventListener('compositionend', () => (composing = false));
// Picking from the list fires an input event without a key press. Commit right away in that case.
input.addEventListener('input', (event) => {
if (!(event as InputEvent).inputType && suggestions().includes(input.value)) ctx.commit();
});
el.append(input, list);
},
getValue: () => input.value.trim(),
focus() {
input.focus();
input.select();
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
input.title = message ?? '';
},
isComposing: () => composing,
destroy() {
input.remove();
list.remove();
},
};
};
// This combobox is a hand-made editor (cellEditor), so singleClickEdit (open on one click) does not apply. Like other cells it opens with a double-click or a key.
export const options: GridOptions<Row> = {
columns: [
{ id: 'employee', title: 'Employee', width: 140 },
{
id: 'city',
title: 'Work city (combobox)',
width: 210,
editable: true,
cellEditor: cityEditor,
validation: { required: true },
},
],
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log(
'Double-click a "Work city" cell to see suggestions. You can also type a city that is not in the list.',
);
return api.on('editCommitted', (e) => {
const city = String(e.newValue);
const known = suggestions().includes(city);
if (mode === 'history' && !base.includes(city) && !history.includes(city))
history = [...history, city];
log(
`Row ${e.rowKey} city: ${city}${known ? '' : mode === 'history' ? ' (new value, will appear in suggestions from now on)' : ' (not in the suggestions)'}`,
);
});
}
export const actions = {
mode: (_api: GridApi<Row>, value?: string) => {
mode = value === 'history' ? 'history' : 'fixed';
if (mode === 'fixed') history = [];
},
};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="Suggestions"
[disabled]="!api"
(change)="api && actions.mode(api, $any($event.target).value)"
>
<option value="fixed" selected>Fixed list</option>
<option value="history">Remember typed values</option>
</select>
</div>
<mx-grid style="height: 310px" [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 { CellEditorAdapter, GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
employee: string;
city: string;
}
const base = [
'New York',
'Los Angeles',
'Chicago',
'Houston',
'Seattle',
'Boston',
'Austin',
'Denver',
];
const employees = [
'Liam Carter',
'Emma Stone',
'Noah Kim',
'Olivia Park',
'Ethan Brooks',
'Ava Morgan',
];
const cities = ['New York', 'Los Angeles', 'Miami', 'Houston', 'Portland', 'Boston']; // Miami and Portland are not in the suggestion list.
const rows: Row[] = employees.map((employee, i) => ({ id: i + 1, employee, city: cities[i] }));
type Mode = 'fixed' | 'history';
let mode: Mode = 'fixed';
let history: string[] = []; // Remembers values that were typed in and committed
const suggestions = () =>
mode === 'history' ? [...base, ...history.filter((c) => !base.includes(c))] : base;
// On a touch screen (or a narrow screen) the text grows to 16px. iOS zooms the page for a 13px input.
const touch = (): boolean => window.matchMedia('(pointer: coarse), (max-width: 480px)').matches;
// A combobox editor built from an input plus a suggestion list (<datalist>). You can pick from the list or type a value that is not in it.
// Unlike a strict dropdown (select), cities that are not in the list are accepted as they are.
const cityEditor = (): CellEditorAdapter<Row> => {
let input: HTMLInputElement;
let list: HTMLDataListElement;
let composing = false;
return {
mount(el, ctx) {
input = document.createElement('input');
list = document.createElement('datalist');
list.id = `cities-${String(ctx.rowKey)}`;
for (const city of suggestions()) list.append(new Option(city));
input.setAttribute('list', list.id);
input.value = String(ctx.value ?? '');
input.style.cssText = `width: 100%; height: 100%; box-sizing: border-box; border: 0; padding: 0 8px; font: inherit; font-size: ${touch() ? 16 : 13}px; background: var(--mxg-bg); color: var(--mxg-fg);`;
input.addEventListener('compositionstart', () => (composing = true));
input.addEventListener('compositionend', () => (composing = false));
// Picking from the list fires an input event without a key press. Commit right away in that case.
input.addEventListener('input', (event) => {
if (!(event as InputEvent).inputType && suggestions().includes(input.value)) ctx.commit();
});
el.append(input, list);
},
getValue: () => input.value.trim(),
focus() {
input.focus();
input.select();
},
setError(message) {
input.setAttribute('aria-invalid', String(message !== null));
input.title = message ?? '';
},
isComposing: () => composing,
destroy() {
input.remove();
list.remove();
},
};
};
// This combobox is a hand-made editor (cellEditor), so singleClickEdit (open on one click) does not apply. Like other cells it opens with a double-click or a key.
export const options: GridOptions<Row> = {
columns: [
{ id: 'employee', title: 'Employee', width: 140 },
{
id: 'city',
title: 'Work city (combobox)',
width: 210,
editable: true,
cellEditor: cityEditor,
validation: { required: true },
},
],
rows,
rowKey: 'id',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
log(
'Double-click a "Work city" cell to see suggestions. You can also type a city that is not in the list.',
);
return api.on('editCommitted', (e) => {
const city = String(e.newValue);
const known = suggestions().includes(city);
if (mode === 'history' && !base.includes(city) && !history.includes(city))
history = [...history, city];
log(
`Row ${e.rowKey} city: ${city}${known ? '' : mode === 'history' ? ' (new value, will appear in suggestions from now on)' : ' (not in the suggestions)'}`,
);
});
}
export const actions = {
mode: (_api: GridApi<Row>, value?: string) => {
mode = value === 'history' ? 'history' : 'fixed';
if (mode === 'fixed') history = [];
},
};