폴더를 열 때 안쪽을 가져오기Fetch a folder's contents when it opens
처음에는 맨 위 줄만 보여 주고, 폴더를 처음 열 때 그 폴더의 내용만 서버에서 받아 와요. 비어 있는 폴더나 응답이 실패한 폴더도 알맞게 보여 줘요.Only the top rows load at first; a folder's contents are fetched the first time it opens. Empty folders and failed requests are handled too.
코드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="openDocs">"문서" 열기</button>
<button type="button" id="openPhotos">"사진" 열기</button>
<button type="button" id="openEmpty">"빈 폴더" 열기</button>
<button type="button" id="openFlaky">"불안정한 폴더" 열기</button>
<button type="button" id="closeFlaky">"불안정한 폴더" 닫기</button>
<button type="button" id="collapseAll">모두 닫기</button>
</div>
<div id="grid" style="height: 362px"></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('openDocs').addEventListener('click', () => actions.openDocs(api));
document.getElementById('openPhotos').addEventListener('click', () => actions.openPhotos(api));
document.getElementById('openEmpty').addEventListener('click', () => actions.openEmpty(api));
document.getElementById('openFlaky').addEventListener('click', () => actions.openFlaky(api));
document.getElementById('closeFlaky').addEventListener('click', () => actions.closeFlaky(api));
document.getElementById('collapseAll').addEventListener('click', () => actions.collapseAll(api));// 처음에는 맨 위 줄만 있어요. 폴더를 처음 열 때 loadChildren이 불려서 그 폴더의 내용만 가져와요.
const topRows = [
{ id: 'docs', parentId: null, name: '문서', folder: true, type: '폴더' },
{ id: 'photos', parentId: null, name: '사진', folder: true, type: '폴더' },
{ id: 'empty', parentId: null, name: '빈 폴더', folder: true, type: '폴더' },
{ id: 'flaky', parentId: null, name: '불안정한 폴더', folder: true, type: '폴더' },
{ id: 'memo', parentId: null, name: '메모.txt', folder: false, type: '파일' },
];
// 서버가 폴더마다 돌려줄 내용이에요. 실제로는 fetch(...)로 받는 자리예요.
const folders = {
docs: [
['보고서', true],
['계약서.pdf', false],
['회의록.docx', false],
],
reports: [
['월간 보고.xlsx', false],
['분기 보고.pptx', false],
],
photos: [
['여행 1.jpg', false],
['여행 2.jpg', false],
['가족.png', false],
['로고.svg', false],
],
flaky: [['복구된 파일.txt', false]],
};
let flakyTries = 0;
export const options = {
columns: [
{ id: 'name', title: '이름', width: 220 },
{ id: 'type', title: '종류', width: 80 },
],
rows: topRows,
rowKey: 'id',
tree: {
parentKey: 'parentId',
column: 'name',
hasChildren: (row) => row.folder, // 폴더만 화살표가 생겨요.
loadChildren: async (row, { key, signal }) => {
await new Promise((resolve) => setTimeout(resolve, 700)); // 서버 응답을 기다리는 시간
if (signal.aborted)
return []; // 기다리다 접으면 이 응답은 그리드가 버려요.
if (row.id === 'flaky' && flakyTries++ === 0)
throw new Error('서버가 응답하지 않아요');
const id = row.name === '보고서' ? 'reports' : String(key);
return (folders[id] ?? []).map(([name, folder], i) => ({
id: `${row.id}-${i}`,
parentId: String(key),
name,
folder,
type: folder ? '폴더' : '파일',
}));
},
},
};
const says = {
loading: ['불러오는 중이에요…', 'Loading…'],
loaded: ['불러왔어요', 'Loaded'],
error: [
'불러오지 못했어요. 접었다가 다시 열면 한 번 더 시도해요.',
'Could not load. Collapse and open it again to retry once more.',
],
cancelled: [
'기다리다 접어서 응답을 버렸어요',
'Collapsed while waiting, so the response was dropped',
],
};
export function setup(api, log) {
return api.on('childrenLoadChanged', ({ rowKey, state, count }) => {
const name = api.getRowByKey(rowKey)?.name ?? String(rowKey);
log({
ko: `${name}: ${says[state]?.[0] ?? state}${count === undefined ? '' : ` (${count}개)`}`,
en: `${name}: ${says[state]?.[1] ?? state}${count === undefined ? '' : ` (${count})`}`,
});
});
}
export const actions = {
openDocs: (api) => api.expandRow('docs'),
openPhotos: (api) => api.expandRow('photos'),
// 이미 불러와 보니 비어 있던 폴더는 다시 펼칠 수 없어서 오류가 나요. 처음 한 번의 결과는 기록에 나와요.
openEmpty: (api) => {
try {
api.expandRow('empty');
}
catch {
// 이미 "불러옴 (0개)"로 기록에 나왔어요. 펼칠 것이 없어요.
}
},
openFlaky: (api) => api.expandRow('flaky'),
closeFlaky: (api) => api.collapseRow('flaky'),
collapseAll: (api) => api.collapseAll(),
};<!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="openDocs">"문서" 열기</button>
<button type="button" id="openPhotos">"사진" 열기</button>
<button type="button" id="openEmpty">"빈 폴더" 열기</button>
<button type="button" id="openFlaky">"불안정한 폴더" 열기</button>
<button type="button" id="closeFlaky">"불안정한 폴더" 닫기</button>
<button type="button" id="collapseAll">모두 닫기</button>
</div>
<div id="grid" style="height: 362px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 처음에는 맨 위 줄만 있어요. 폴더를 처음 열 때 loadChildren이 불려서 그 폴더의 내용만 가져와요.
const topRows = [
{ id: 'docs', parentId: null, name: '문서', folder: true, type: '폴더' },
{ id: 'photos', parentId: null, name: '사진', folder: true, type: '폴더' },
{ id: 'empty', parentId: null, name: '빈 폴더', folder: true, type: '폴더' },
{ id: 'flaky', parentId: null, name: '불안정한 폴더', folder: true, type: '폴더' },
{ id: 'memo', parentId: null, name: '메모.txt', folder: false, type: '파일' },
];
// 서버가 폴더마다 돌려줄 내용이에요. 실제로는 fetch(...)로 받는 자리예요.
const folders = {
docs: [
['보고서', true],
['계약서.pdf', false],
['회의록.docx', false],
],
reports: [
['월간 보고.xlsx', false],
['분기 보고.pptx', false],
],
photos: [
['여행 1.jpg', false],
['여행 2.jpg', false],
['가족.png', false],
['로고.svg', false],
],
flaky: [['복구된 파일.txt', false]],
};
let flakyTries = 0;
const options = {
columns: [
{ id: 'name', title: '이름', width: 220 },
{ id: 'type', title: '종류', width: 80 },
],
rows: topRows,
rowKey: 'id',
tree: {
parentKey: 'parentId',
column: 'name',
hasChildren: (row) => row.folder, // 폴더만 화살표가 생겨요.
loadChildren: async (row, { key, signal }) => {
await new Promise((resolve) => setTimeout(resolve, 700)); // 서버 응답을 기다리는 시간
if (signal.aborted)
return []; // 기다리다 접으면 이 응답은 그리드가 버려요.
if (row.id === 'flaky' && flakyTries++ === 0)
throw new Error('서버가 응답하지 않아요');
const id = row.name === '보고서' ? 'reports' : String(key);
return (folders[id] ?? []).map(([name, folder], i) => ({
id: `${row.id}-${i}`,
parentId: String(key),
name,
folder,
type: folder ? '폴더' : '파일',
}));
},
},
};
const says = {
loading: ['불러오는 중이에요…', 'Loading…'],
loaded: ['불러왔어요', 'Loaded'],
error: [
'불러오지 못했어요. 접었다가 다시 열면 한 번 더 시도해요.',
'Could not load. Collapse and open it again to retry once more.',
],
cancelled: [
'기다리다 접어서 응답을 버렸어요',
'Collapsed while waiting, so the response was dropped',
],
};
function setup(api, log) {
return api.on('childrenLoadChanged', ({ rowKey, state, count }) => {
const name = api.getRowByKey(rowKey)?.name ?? String(rowKey);
log({
ko: `${name}: ${says[state]?.[0] ?? state}${count === undefined ? '' : ` (${count}개)`}`,
en: `${name}: ${says[state]?.[1] ?? state}${count === undefined ? '' : ` (${count})`}`,
});
});
}
const actions = {
openDocs: (api) => api.expandRow('docs'),
openPhotos: (api) => api.expandRow('photos'),
// 이미 불러와 보니 비어 있던 폴더는 다시 펼칠 수 없어서 오류가 나요. 처음 한 번의 결과는 기록에 나와요.
openEmpty: (api) => {
try {
api.expandRow('empty');
}
catch {
// 이미 "불러옴 (0개)"로 기록에 나왔어요. 펼칠 것이 없어요.
}
},
openFlaky: (api) => api.expandRow('flaky'),
closeFlaky: (api) => api.collapseRow('flaky'),
collapseAll: (api) => api.collapseAll(),
};
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('openDocs').addEventListener('click', () => actions.openDocs(api));
document.getElementById('openPhotos').addEventListener('click', () => actions.openPhotos(api));
document.getElementById('openEmpty').addEventListener('click', () => actions.openEmpty(api));
document.getElementById('openFlaky').addEventListener('click', () => actions.openFlaky(api));
document.getElementById('closeFlaky').addEventListener('click', () => actions.closeFlaky(api));
document.getElementById('collapseAll').addEventListener('click', () => actions.collapseAll(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.openDocs(api)}
>"문서" 열기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.openPhotos(api)}
>"사진" 열기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.openEmpty(api)}
>"빈 폴더" 열기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.openFlaky(api)}
>"불안정한 폴더" 열기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.closeFlaky(api)}
>"불안정한 폴더" 닫기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.collapseAll(api)}
>모두 닫기</button>
</div>
<Grid style={{ height: 362 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: string;
parentId: string | null;
name: string;
folder: boolean;
type: string;
}
// 처음에는 맨 위 줄만 있어요. 폴더를 처음 열 때 loadChildren이 불려서 그 폴더의 내용만 가져와요.
const topRows: Row[] = [
{ id: 'docs', parentId: null, name: '문서', folder: true, type: '폴더' },
{ id: 'photos', parentId: null, name: '사진', folder: true, type: '폴더' },
{ id: 'empty', parentId: null, name: '빈 폴더', folder: true, type: '폴더' },
{ id: 'flaky', parentId: null, name: '불안정한 폴더', folder: true, type: '폴더' },
{ id: 'memo', parentId: null, name: '메모.txt', folder: false, type: '파일' },
];
// 서버가 폴더마다 돌려줄 내용이에요. 실제로는 fetch(...)로 받는 자리예요.
const folders: Record<string, [string, boolean][]> = {
docs: [
['보고서', true],
['계약서.pdf', false],
['회의록.docx', false],
],
reports: [
['월간 보고.xlsx', false],
['분기 보고.pptx', false],
],
photos: [
['여행 1.jpg', false],
['여행 2.jpg', false],
['가족.png', false],
['로고.svg', false],
],
flaky: [['복구된 파일.txt', false]],
};
let flakyTries = 0;
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 220 },
{ id: 'type', title: '종류', width: 80 },
],
rows: topRows,
rowKey: 'id',
tree: {
parentKey: 'parentId',
column: 'name',
hasChildren: (row) => row.folder, // 폴더만 화살표가 생겨요.
loadChildren: async (row, { key, signal }) => {
await new Promise((resolve) => setTimeout(resolve, 700)); // 서버 응답을 기다리는 시간
if (signal.aborted) return []; // 기다리다 접으면 이 응답은 그리드가 버려요.
if (row.id === 'flaky' && flakyTries++ === 0) throw new Error('서버가 응답하지 않아요');
const id = row.name === '보고서' ? 'reports' : String(key);
return (folders[id] ?? []).map(([name, folder], i) => ({
id: `${row.id}-${i}`,
parentId: String(key),
name,
folder,
type: folder ? '폴더' : '파일',
}));
},
},
};
const says: Record<string, [string, string]> = {
loading: ['불러오는 중이에요…', 'Loading…'],
loaded: ['불러왔어요', 'Loaded'],
error: [
'불러오지 못했어요. 접었다가 다시 열면 한 번 더 시도해요.',
'Could not load. Collapse and open it again to retry once more.',
],
cancelled: [
'기다리다 접어서 응답을 버렸어요',
'Collapsed while waiting, so the response was dropped',
],
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
return api.on('childrenLoadChanged', ({ rowKey, state, count }) => {
const name = api.getRowByKey(rowKey)?.name ?? String(rowKey);
log({
ko: `${name}: ${says[state]?.[0] ?? state}${count === undefined ? '' : ` (${count}개)`}`,
en: `${name}: ${says[state]?.[1] ?? state}${count === undefined ? '' : ` (${count})`}`,
});
});
}
export const actions = {
openDocs: (api: GridApi<Row>) => api.expandRow('docs'),
openPhotos: (api: GridApi<Row>) => api.expandRow('photos'),
// 이미 불러와 보니 비어 있던 폴더는 다시 펼칠 수 없어서 오류가 나요. 처음 한 번의 결과는 기록에 나와요.
openEmpty: (api: GridApi<Row>) => {
try {
api.expandRow('empty');
} catch {
// 이미 "불러옴 (0개)"로 기록에 나왔어요. 펼칠 것이 없어요.
}
},
openFlaky: (api: GridApi<Row>) => api.expandRow('flaky'),
closeFlaky: (api: GridApi<Row>) => api.collapseRow('flaky'),
collapseAll: (api: GridApi<Row>) => api.collapseAll(),
};버튼을 누르면 이 예제의 코드가 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.openDocs(api)"
>"문서" 열기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.openPhotos(api)"
>"사진" 열기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.openEmpty(api)"
>"빈 폴더" 열기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.openFlaky(api)"
>"불안정한 폴더" 열기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.closeFlaky(api)"
>"불안정한 폴더" 닫기</button>
<button
type="button"
:disabled="!api"
@click="api && actions.collapseAll(api)"
>모두 닫기</button>
</div>
<Grid style="height: 362px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: string;
parentId: string | null;
name: string;
folder: boolean;
type: string;
}
// 처음에는 맨 위 줄만 있어요. 폴더를 처음 열 때 loadChildren이 불려서 그 폴더의 내용만 가져와요.
const topRows: Row[] = [
{ id: 'docs', parentId: null, name: '문서', folder: true, type: '폴더' },
{ id: 'photos', parentId: null, name: '사진', folder: true, type: '폴더' },
{ id: 'empty', parentId: null, name: '빈 폴더', folder: true, type: '폴더' },
{ id: 'flaky', parentId: null, name: '불안정한 폴더', folder: true, type: '폴더' },
{ id: 'memo', parentId: null, name: '메모.txt', folder: false, type: '파일' },
];
// 서버가 폴더마다 돌려줄 내용이에요. 실제로는 fetch(...)로 받는 자리예요.
const folders: Record<string, [string, boolean][]> = {
docs: [
['보고서', true],
['계약서.pdf', false],
['회의록.docx', false],
],
reports: [
['월간 보고.xlsx', false],
['분기 보고.pptx', false],
],
photos: [
['여행 1.jpg', false],
['여행 2.jpg', false],
['가족.png', false],
['로고.svg', false],
],
flaky: [['복구된 파일.txt', false]],
};
let flakyTries = 0;
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 220 },
{ id: 'type', title: '종류', width: 80 },
],
rows: topRows,
rowKey: 'id',
tree: {
parentKey: 'parentId',
column: 'name',
hasChildren: (row) => row.folder, // 폴더만 화살표가 생겨요.
loadChildren: async (row, { key, signal }) => {
await new Promise((resolve) => setTimeout(resolve, 700)); // 서버 응답을 기다리는 시간
if (signal.aborted) return []; // 기다리다 접으면 이 응답은 그리드가 버려요.
if (row.id === 'flaky' && flakyTries++ === 0) throw new Error('서버가 응답하지 않아요');
const id = row.name === '보고서' ? 'reports' : String(key);
return (folders[id] ?? []).map(([name, folder], i) => ({
id: `${row.id}-${i}`,
parentId: String(key),
name,
folder,
type: folder ? '폴더' : '파일',
}));
},
},
};
const says: Record<string, [string, string]> = {
loading: ['불러오는 중이에요…', 'Loading…'],
loaded: ['불러왔어요', 'Loaded'],
error: [
'불러오지 못했어요. 접었다가 다시 열면 한 번 더 시도해요.',
'Could not load. Collapse and open it again to retry once more.',
],
cancelled: [
'기다리다 접어서 응답을 버렸어요',
'Collapsed while waiting, so the response was dropped',
],
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
return api.on('childrenLoadChanged', ({ rowKey, state, count }) => {
const name = api.getRowByKey(rowKey)?.name ?? String(rowKey);
log({
ko: `${name}: ${says[state]?.[0] ?? state}${count === undefined ? '' : ` (${count}개)`}`,
en: `${name}: ${says[state]?.[1] ?? state}${count === undefined ? '' : ` (${count})`}`,
});
});
}
export const actions = {
openDocs: (api: GridApi<Row>) => api.expandRow('docs'),
openPhotos: (api: GridApi<Row>) => api.expandRow('photos'),
// 이미 불러와 보니 비어 있던 폴더는 다시 펼칠 수 없어서 오류가 나요. 처음 한 번의 결과는 기록에 나와요.
openEmpty: (api: GridApi<Row>) => {
try {
api.expandRow('empty');
} catch {
// 이미 "불러옴 (0개)"로 기록에 나왔어요. 펼칠 것이 없어요.
}
},
openFlaky: (api: GridApi<Row>) => api.expandRow('flaky'),
closeFlaky: (api: GridApi<Row>) => api.collapseRow('flaky'),
collapseAll: (api: GridApi<Row>) => api.collapseAll(),
};버튼을 누르면 이 예제의 코드가 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.openDocs(api)"
>"문서" 열기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.openPhotos(api)"
>"사진" 열기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.openEmpty(api)"
>"빈 폴더" 열기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.openFlaky(api)"
>"불안정한 폴더" 열기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.closeFlaky(api)"
>"불안정한 폴더" 닫기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.collapseAll(api)"
>모두 닫기</button>
</div>
<mx-grid style="height: 362px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: string;
parentId: string | null;
name: string;
folder: boolean;
type: string;
}
// 처음에는 맨 위 줄만 있어요. 폴더를 처음 열 때 loadChildren이 불려서 그 폴더의 내용만 가져와요.
const topRows: Row[] = [
{ id: 'docs', parentId: null, name: '문서', folder: true, type: '폴더' },
{ id: 'photos', parentId: null, name: '사진', folder: true, type: '폴더' },
{ id: 'empty', parentId: null, name: '빈 폴더', folder: true, type: '폴더' },
{ id: 'flaky', parentId: null, name: '불안정한 폴더', folder: true, type: '폴더' },
{ id: 'memo', parentId: null, name: '메모.txt', folder: false, type: '파일' },
];
// 서버가 폴더마다 돌려줄 내용이에요. 실제로는 fetch(...)로 받는 자리예요.
const folders: Record<string, [string, boolean][]> = {
docs: [
['보고서', true],
['계약서.pdf', false],
['회의록.docx', false],
],
reports: [
['월간 보고.xlsx', false],
['분기 보고.pptx', false],
],
photos: [
['여행 1.jpg', false],
['여행 2.jpg', false],
['가족.png', false],
['로고.svg', false],
],
flaky: [['복구된 파일.txt', false]],
};
let flakyTries = 0;
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 220 },
{ id: 'type', title: '종류', width: 80 },
],
rows: topRows,
rowKey: 'id',
tree: {
parentKey: 'parentId',
column: 'name',
hasChildren: (row) => row.folder, // 폴더만 화살표가 생겨요.
loadChildren: async (row, { key, signal }) => {
await new Promise((resolve) => setTimeout(resolve, 700)); // 서버 응답을 기다리는 시간
if (signal.aborted) return []; // 기다리다 접으면 이 응답은 그리드가 버려요.
if (row.id === 'flaky' && flakyTries++ === 0) throw new Error('서버가 응답하지 않아요');
const id = row.name === '보고서' ? 'reports' : String(key);
return (folders[id] ?? []).map(([name, folder], i) => ({
id: `${row.id}-${i}`,
parentId: String(key),
name,
folder,
type: folder ? '폴더' : '파일',
}));
},
},
};
const says: Record<string, [string, string]> = {
loading: ['불러오는 중이에요…', 'Loading…'],
loaded: ['불러왔어요', 'Loaded'],
error: [
'불러오지 못했어요. 접었다가 다시 열면 한 번 더 시도해요.',
'Could not load. Collapse and open it again to retry once more.',
],
cancelled: [
'기다리다 접어서 응답을 버렸어요',
'Collapsed while waiting, so the response was dropped',
],
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
return api.on('childrenLoadChanged', ({ rowKey, state, count }) => {
const name = api.getRowByKey(rowKey)?.name ?? String(rowKey);
log({
ko: `${name}: ${says[state]?.[0] ?? state}${count === undefined ? '' : ` (${count}개)`}`,
en: `${name}: ${says[state]?.[1] ?? state}${count === undefined ? '' : ` (${count})`}`,
});
});
}
export const actions = {
openDocs: (api: GridApi<Row>) => api.expandRow('docs'),
openPhotos: (api: GridApi<Row>) => api.expandRow('photos'),
// 이미 불러와 보니 비어 있던 폴더는 다시 펼칠 수 없어서 오류가 나요. 처음 한 번의 결과는 기록에 나와요.
openEmpty: (api: GridApi<Row>) => {
try {
api.expandRow('empty');
} catch {
// 이미 "불러옴 (0개)"로 기록에 나왔어요. 펼칠 것이 없어요.
}
},
openFlaky: (api: GridApi<Row>) => api.expandRow('flaky'),
closeFlaky: (api: GridApi<Row>) => api.collapseRow('flaky'),
collapseAll: (api: GridApi<Row>) => api.collapseAll(),
};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="openDocs">Open "Documents"</button>
<button type="button" id="openPhotos">Open "Photos"</button>
<button type="button" id="openEmpty">Open "Empty folder"</button>
<button type="button" id="openFlaky">Open "Flaky folder"</button>
<button type="button" id="closeFlaky">Close "Flaky folder"</button>
<button type="button" id="collapseAll">Collapse all</button>
</div>
<div id="grid" style="height: 362px"></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('openDocs').addEventListener('click', () => actions.openDocs(api));
document.getElementById('openPhotos').addEventListener('click', () => actions.openPhotos(api));
document.getElementById('openEmpty').addEventListener('click', () => actions.openEmpty(api));
document.getElementById('openFlaky').addEventListener('click', () => actions.openFlaky(api));
document.getElementById('closeFlaky').addEventListener('click', () => actions.closeFlaky(api));
document.getElementById('collapseAll').addEventListener('click', () => actions.collapseAll(api));// At first there are only the top rows. The first time a folder opens, loadChildren is called and fetches only that folder's contents.
const topRows = [
{ id: 'docs', parentId: null, name: 'Documents', folder: true, type: 'Folder' },
{ id: 'photos', parentId: null, name: 'Photos', folder: true, type: 'Folder' },
{ id: 'empty', parentId: null, name: 'Empty folder', folder: true, type: 'Folder' },
{ id: 'flaky', parentId: null, name: 'Flaky folder', folder: true, type: 'Folder' },
{ id: 'memo', parentId: null, name: 'memo.txt', folder: false, type: 'File' },
];
// The contents the server would return for each folder. In real code this is where fetch(...) goes.
const folders = {
docs: [
['Reports', true],
['contract.pdf', false],
['minutes.docx', false],
],
reports: [
['monthly-report.xlsx', false],
['quarterly-report.pptx', false],
],
photos: [
['trip-1.jpg', false],
['trip-2.jpg', false],
['family.png', false],
['logo.svg', false],
],
flaky: [['recovered-file.txt', false]],
};
let flakyTries = 0;
export const options = {
columns: [
{ id: 'name', title: 'Name', width: 220 },
{ id: 'type', title: 'Type', width: 80 },
],
rows: topRows,
rowKey: 'id',
tree: {
parentKey: 'parentId',
column: 'name',
hasChildren: (row) => row.folder, // Only folders get an arrow.
loadChildren: async (row, { key, signal }) => {
await new Promise((resolve) => setTimeout(resolve, 700)); // Time spent waiting for the server
if (signal.aborted)
return []; // If it was collapsed while waiting, the grid drops this response.
if (row.id === 'flaky' && flakyTries++ === 0)
throw new Error('The server is not responding');
const id = row.name === 'Reports' ? 'reports' : String(key);
return (folders[id] ?? []).map(([name, folder], i) => ({
id: `${row.id}-${i}`,
parentId: String(key),
name,
folder,
type: folder ? 'Folder' : 'File',
}));
},
},
};
const says = {
loading: 'Loading…',
loaded: 'Loaded',
error: 'Could not load. Collapse and open it again to retry once more.',
cancelled: 'Collapsed while waiting, so the response was dropped',
};
export function setup(api, log) {
return api.on('childrenLoadChanged', ({ rowKey, state, count }) => {
const name = api.getRowByKey(rowKey)?.name ?? String(rowKey);
log(`${name}: ${says[state] ?? state}${count === undefined ? '' : ` (${count})`}`);
});
}
export const actions = {
openDocs: (api) => api.expandRow('docs'),
openPhotos: (api) => api.expandRow('photos'),
// A folder that turned out empty when loaded cannot be expanded again, so this throws. The result of the first attempt appears in the log.
openEmpty: (api) => {
try {
api.expandRow('empty');
}
catch {
// Already logged as "Loaded (0)". There is nothing to expand.
}
},
openFlaky: (api) => api.expandRow('flaky'),
closeFlaky: (api) => api.collapseRow('flaky'),
collapseAll: (api) => api.collapseAll(),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Fetch a folder's contents when it opens</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="openDocs">Open "Documents"</button>
<button type="button" id="openPhotos">Open "Photos"</button>
<button type="button" id="openEmpty">Open "Empty folder"</button>
<button type="button" id="openFlaky">Open "Flaky folder"</button>
<button type="button" id="closeFlaky">Close "Flaky folder"</button>
<button type="button" id="collapseAll">Collapse all</button>
</div>
<div id="grid" style="height: 362px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// At first there are only the top rows. The first time a folder opens, loadChildren is called and fetches only that folder's contents.
const topRows = [
{ id: 'docs', parentId: null, name: 'Documents', folder: true, type: 'Folder' },
{ id: 'photos', parentId: null, name: 'Photos', folder: true, type: 'Folder' },
{ id: 'empty', parentId: null, name: 'Empty folder', folder: true, type: 'Folder' },
{ id: 'flaky', parentId: null, name: 'Flaky folder', folder: true, type: 'Folder' },
{ id: 'memo', parentId: null, name: 'memo.txt', folder: false, type: 'File' },
];
// The contents the server would return for each folder. In real code this is where fetch(...) goes.
const folders = {
docs: [
['Reports', true],
['contract.pdf', false],
['minutes.docx', false],
],
reports: [
['monthly-report.xlsx', false],
['quarterly-report.pptx', false],
],
photos: [
['trip-1.jpg', false],
['trip-2.jpg', false],
['family.png', false],
['logo.svg', false],
],
flaky: [['recovered-file.txt', false]],
};
let flakyTries = 0;
const options = {
columns: [
{ id: 'name', title: 'Name', width: 220 },
{ id: 'type', title: 'Type', width: 80 },
],
rows: topRows,
rowKey: 'id',
tree: {
parentKey: 'parentId',
column: 'name',
hasChildren: (row) => row.folder, // Only folders get an arrow.
loadChildren: async (row, { key, signal }) => {
await new Promise((resolve) => setTimeout(resolve, 700)); // Time spent waiting for the server
if (signal.aborted)
return []; // If it was collapsed while waiting, the grid drops this response.
if (row.id === 'flaky' && flakyTries++ === 0)
throw new Error('The server is not responding');
const id = row.name === 'Reports' ? 'reports' : String(key);
return (folders[id] ?? []).map(([name, folder], i) => ({
id: `${row.id}-${i}`,
parentId: String(key),
name,
folder,
type: folder ? 'Folder' : 'File',
}));
},
},
};
const says = {
loading: 'Loading…',
loaded: 'Loaded',
error: 'Could not load. Collapse and open it again to retry once more.',
cancelled: 'Collapsed while waiting, so the response was dropped',
};
function setup(api, log) {
return api.on('childrenLoadChanged', ({ rowKey, state, count }) => {
const name = api.getRowByKey(rowKey)?.name ?? String(rowKey);
log(`${name}: ${says[state] ?? state}${count === undefined ? '' : ` (${count})`}`);
});
}
const actions = {
openDocs: (api) => api.expandRow('docs'),
openPhotos: (api) => api.expandRow('photos'),
// A folder that turned out empty when loaded cannot be expanded again, so this throws. The result of the first attempt appears in the log.
openEmpty: (api) => {
try {
api.expandRow('empty');
}
catch {
// Already logged as "Loaded (0)". There is nothing to expand.
}
},
openFlaky: (api) => api.expandRow('flaky'),
closeFlaky: (api) => api.collapseRow('flaky'),
collapseAll: (api) => api.collapseAll(),
};
options.ariaLabel = "Fetch a folder's contents when it opens";
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('openDocs').addEventListener('click', () => actions.openDocs(api));
document.getElementById('openPhotos').addEventListener('click', () => actions.openPhotos(api));
document.getElementById('openEmpty').addEventListener('click', () => actions.openEmpty(api));
document.getElementById('openFlaky').addEventListener('click', () => actions.openFlaky(api));
document.getElementById('closeFlaky').addEventListener('click', () => actions.closeFlaky(api));
document.getElementById('collapseAll').addEventListener('click', () => actions.collapseAll(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.openDocs(api)}
>Open "Documents"</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.openPhotos(api)}
>Open "Photos"</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.openEmpty(api)}
>Open "Empty folder"</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.openFlaky(api)}
>Open "Flaky folder"</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.closeFlaky(api)}
>Close "Flaky folder"</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.collapseAll(api)}
>Collapse all</button>
</div>
<Grid style={{ height: 362 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: string;
parentId: string | null;
name: string;
folder: boolean;
type: string;
}
// At first there are only the top rows. The first time a folder opens, loadChildren is called and fetches only that folder's contents.
const topRows: Row[] = [
{ id: 'docs', parentId: null, name: 'Documents', folder: true, type: 'Folder' },
{ id: 'photos', parentId: null, name: 'Photos', folder: true, type: 'Folder' },
{ id: 'empty', parentId: null, name: 'Empty folder', folder: true, type: 'Folder' },
{ id: 'flaky', parentId: null, name: 'Flaky folder', folder: true, type: 'Folder' },
{ id: 'memo', parentId: null, name: 'memo.txt', folder: false, type: 'File' },
];
// The contents the server would return for each folder. In real code this is where fetch(...) goes.
const folders: Record<string, [string, boolean][]> = {
docs: [
['Reports', true],
['contract.pdf', false],
['minutes.docx', false],
],
reports: [
['monthly-report.xlsx', false],
['quarterly-report.pptx', false],
],
photos: [
['trip-1.jpg', false],
['trip-2.jpg', false],
['family.png', false],
['logo.svg', false],
],
flaky: [['recovered-file.txt', false]],
};
let flakyTries = 0;
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 220 },
{ id: 'type', title: 'Type', width: 80 },
],
rows: topRows,
rowKey: 'id',
tree: {
parentKey: 'parentId',
column: 'name',
hasChildren: (row) => row.folder, // Only folders get an arrow.
loadChildren: async (row, { key, signal }) => {
await new Promise((resolve) => setTimeout(resolve, 700)); // Time spent waiting for the server
if (signal.aborted) return []; // If it was collapsed while waiting, the grid drops this response.
if (row.id === 'flaky' && flakyTries++ === 0) throw new Error('The server is not responding');
const id = row.name === 'Reports' ? 'reports' : String(key);
return (folders[id] ?? []).map(([name, folder], i) => ({
id: `${row.id}-${i}`,
parentId: String(key),
name,
folder,
type: folder ? 'Folder' : 'File',
}));
},
},
};
const says: Record<string, string> = {
loading: 'Loading…',
loaded: 'Loaded',
error: 'Could not load. Collapse and open it again to retry once more.',
cancelled: 'Collapsed while waiting, so the response was dropped',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
return api.on('childrenLoadChanged', ({ rowKey, state, count }) => {
const name = api.getRowByKey(rowKey)?.name ?? String(rowKey);
log(`${name}: ${says[state] ?? state}${count === undefined ? '' : ` (${count})`}`);
});
}
export const actions = {
openDocs: (api: GridApi<Row>) => api.expandRow('docs'),
openPhotos: (api: GridApi<Row>) => api.expandRow('photos'),
// A folder that turned out empty when loaded cannot be expanded again, so this throws. The result of the first attempt appears in the log.
openEmpty: (api: GridApi<Row>) => {
try {
api.expandRow('empty');
} catch {
// Already logged as "Loaded (0)". There is nothing to expand.
}
},
openFlaky: (api: GridApi<Row>) => api.expandRow('flaky'),
closeFlaky: (api: GridApi<Row>) => api.collapseRow('flaky'),
collapseAll: (api: GridApi<Row>) => api.collapseAll(),
};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.openDocs(api)"
>Open "Documents"</button>
<button
type="button"
:disabled="!api"
@click="api && actions.openPhotos(api)"
>Open "Photos"</button>
<button
type="button"
:disabled="!api"
@click="api && actions.openEmpty(api)"
>Open "Empty folder"</button>
<button
type="button"
:disabled="!api"
@click="api && actions.openFlaky(api)"
>Open "Flaky folder"</button>
<button
type="button"
:disabled="!api"
@click="api && actions.closeFlaky(api)"
>Close "Flaky folder"</button>
<button
type="button"
:disabled="!api"
@click="api && actions.collapseAll(api)"
>Collapse all</button>
</div>
<Grid style="height: 362px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: string;
parentId: string | null;
name: string;
folder: boolean;
type: string;
}
// At first there are only the top rows. The first time a folder opens, loadChildren is called and fetches only that folder's contents.
const topRows: Row[] = [
{ id: 'docs', parentId: null, name: 'Documents', folder: true, type: 'Folder' },
{ id: 'photos', parentId: null, name: 'Photos', folder: true, type: 'Folder' },
{ id: 'empty', parentId: null, name: 'Empty folder', folder: true, type: 'Folder' },
{ id: 'flaky', parentId: null, name: 'Flaky folder', folder: true, type: 'Folder' },
{ id: 'memo', parentId: null, name: 'memo.txt', folder: false, type: 'File' },
];
// The contents the server would return for each folder. In real code this is where fetch(...) goes.
const folders: Record<string, [string, boolean][]> = {
docs: [
['Reports', true],
['contract.pdf', false],
['minutes.docx', false],
],
reports: [
['monthly-report.xlsx', false],
['quarterly-report.pptx', false],
],
photos: [
['trip-1.jpg', false],
['trip-2.jpg', false],
['family.png', false],
['logo.svg', false],
],
flaky: [['recovered-file.txt', false]],
};
let flakyTries = 0;
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 220 },
{ id: 'type', title: 'Type', width: 80 },
],
rows: topRows,
rowKey: 'id',
tree: {
parentKey: 'parentId',
column: 'name',
hasChildren: (row) => row.folder, // Only folders get an arrow.
loadChildren: async (row, { key, signal }) => {
await new Promise((resolve) => setTimeout(resolve, 700)); // Time spent waiting for the server
if (signal.aborted) return []; // If it was collapsed while waiting, the grid drops this response.
if (row.id === 'flaky' && flakyTries++ === 0) throw new Error('The server is not responding');
const id = row.name === 'Reports' ? 'reports' : String(key);
return (folders[id] ?? []).map(([name, folder], i) => ({
id: `${row.id}-${i}`,
parentId: String(key),
name,
folder,
type: folder ? 'Folder' : 'File',
}));
},
},
};
const says: Record<string, string> = {
loading: 'Loading…',
loaded: 'Loaded',
error: 'Could not load. Collapse and open it again to retry once more.',
cancelled: 'Collapsed while waiting, so the response was dropped',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
return api.on('childrenLoadChanged', ({ rowKey, state, count }) => {
const name = api.getRowByKey(rowKey)?.name ?? String(rowKey);
log(`${name}: ${says[state] ?? state}${count === undefined ? '' : ` (${count})`}`);
});
}
export const actions = {
openDocs: (api: GridApi<Row>) => api.expandRow('docs'),
openPhotos: (api: GridApi<Row>) => api.expandRow('photos'),
// A folder that turned out empty when loaded cannot be expanded again, so this throws. The result of the first attempt appears in the log.
openEmpty: (api: GridApi<Row>) => {
try {
api.expandRow('empty');
} catch {
// Already logged as "Loaded (0)". There is nothing to expand.
}
},
openFlaky: (api: GridApi<Row>) => api.expandRow('flaky'),
closeFlaky: (api: GridApi<Row>) => api.collapseRow('flaky'),
collapseAll: (api: GridApi<Row>) => api.collapseAll(),
};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.openDocs(api)"
>Open "Documents"</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.openPhotos(api)"
>Open "Photos"</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.openEmpty(api)"
>Open "Empty folder"</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.openFlaky(api)"
>Open "Flaky folder"</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.closeFlaky(api)"
>Close "Flaky folder"</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.collapseAll(api)"
>Collapse all</button>
</div>
<mx-grid style="height: 362px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: string;
parentId: string | null;
name: string;
folder: boolean;
type: string;
}
// At first there are only the top rows. The first time a folder opens, loadChildren is called and fetches only that folder's contents.
const topRows: Row[] = [
{ id: 'docs', parentId: null, name: 'Documents', folder: true, type: 'Folder' },
{ id: 'photos', parentId: null, name: 'Photos', folder: true, type: 'Folder' },
{ id: 'empty', parentId: null, name: 'Empty folder', folder: true, type: 'Folder' },
{ id: 'flaky', parentId: null, name: 'Flaky folder', folder: true, type: 'Folder' },
{ id: 'memo', parentId: null, name: 'memo.txt', folder: false, type: 'File' },
];
// The contents the server would return for each folder. In real code this is where fetch(...) goes.
const folders: Record<string, [string, boolean][]> = {
docs: [
['Reports', true],
['contract.pdf', false],
['minutes.docx', false],
],
reports: [
['monthly-report.xlsx', false],
['quarterly-report.pptx', false],
],
photos: [
['trip-1.jpg', false],
['trip-2.jpg', false],
['family.png', false],
['logo.svg', false],
],
flaky: [['recovered-file.txt', false]],
};
let flakyTries = 0;
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 220 },
{ id: 'type', title: 'Type', width: 80 },
],
rows: topRows,
rowKey: 'id',
tree: {
parentKey: 'parentId',
column: 'name',
hasChildren: (row) => row.folder, // Only folders get an arrow.
loadChildren: async (row, { key, signal }) => {
await new Promise((resolve) => setTimeout(resolve, 700)); // Time spent waiting for the server
if (signal.aborted) return []; // If it was collapsed while waiting, the grid drops this response.
if (row.id === 'flaky' && flakyTries++ === 0) throw new Error('The server is not responding');
const id = row.name === 'Reports' ? 'reports' : String(key);
return (folders[id] ?? []).map(([name, folder], i) => ({
id: `${row.id}-${i}`,
parentId: String(key),
name,
folder,
type: folder ? 'Folder' : 'File',
}));
},
},
};
const says: Record<string, string> = {
loading: 'Loading…',
loaded: 'Loaded',
error: 'Could not load. Collapse and open it again to retry once more.',
cancelled: 'Collapsed while waiting, so the response was dropped',
};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
return api.on('childrenLoadChanged', ({ rowKey, state, count }) => {
const name = api.getRowByKey(rowKey)?.name ?? String(rowKey);
log(`${name}: ${says[state] ?? state}${count === undefined ? '' : ` (${count})`}`);
});
}
export const actions = {
openDocs: (api: GridApi<Row>) => api.expandRow('docs'),
openPhotos: (api: GridApi<Row>) => api.expandRow('photos'),
// A folder that turned out empty when loaded cannot be expanded again, so this throws. The result of the first attempt appears in the log.
openEmpty: (api: GridApi<Row>) => {
try {
api.expandRow('empty');
} catch {
// Already logged as "Loaded (0)". There is nothing to expand.
}
},
openFlaky: (api: GridApi<Row>) => api.expandRow('flaky'),
closeFlaky: (api: GridApi<Row>) => api.collapseRow('flaky'),
collapseAll: (api: GridApi<Row>) => api.collapseAll(),
};