Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ API between minor releases.
tour both use the saved state.
- Keyboard navigation and visible focus in the model tree and context menu.
- Select multiple elements in the model tree and open the viewer context menu from its rows.
- Filter the model tree by source model, level and category, and optionally isolate the matches in 3D.

### Fixed

Expand Down
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ fails when it differs from the committed file. The end-to-end tests need the
.NET SDK and a Chromium for Playwright (`npx playwright install chromium`).
Fixtures are in `tests/fixtures/viewer`.

CI also runs the smoke, selection, section, keyboard-accessibility and model-tree selection tests in Firefox.
CI also runs the smoke, selection, section, keyboard-accessibility and model-tree tests in Firefox.
It builds `tests/fixtures/viewer/generate-fixtures.cs` and `tools/SyntheticModel/SyntheticModel.cs`.
To run the Firefox project locally, build the viewer, install Firefox
with `npx playwright install firefox` and run `npx playwright test --project=firefox`. On Linux, install browser
Expand Down
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ Built clean-room under the [IOExtend](https://github.com/IOExtend) organization.
- Shifts coordinates relative to the model centre (RTC), so georeferenced models with coordinates around 10⁶ m do not jitter.
- Draws large models with few draw calls: geometry is merged into spatial chunks per material (very large models draw their repeated shapes as instanced copies instead), and hiding, selection and colouring are per-object data, so they never rebuild geometry.
- Viewer interface in Russian or English, chosen from the browser language:
- model tree by category with search, a properties panel and a selected/total counter;
- model tree with search and filters by source model, level and category, a properties panel and a selected/total counter;
- toolbar with labelled groups: navigation, sections, measure, display and view;
- context menu: properties, hide, isolate, show all, zoom to object, section box around the object, copy Id;
- view cube that follows the camera exactly, with face clicks, 90° arrows and a home button;
Expand Down Expand Up @@ -57,6 +57,10 @@ Built clean-room under the [IOExtend](https://github.com/IOExtend) organization.

The model's up axis is +Z.

In the model tree, open **Filters** to combine source model, level and category with the text search. Use
**Isolate matches** to apply the results to 3D visibility. Clearing the filters keeps the current visibility.
Use **Show all** to reset the hide and isolate actions.

## Install

Install the command line tool:
Expand Down
13 changes: 13 additions & 0 deletions src/IOViewer/Exporters/ViewerPayloadWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -716,6 +716,16 @@ public void WriteMeta(Stream output)
var levels = new Dictionary<int, string>();
foreach (var level in _scene.Levels) levels.TryAdd(level.Id, level.Name);

w.WriteStartArray("models");
foreach (var model in _scene.Models)
{
w.WriteStartObject();
w.WriteNumber("id", model.Id);
w.WriteString("name", model.Name ?? string.Empty);
w.WriteEndObject();
}
w.WriteEndArray();

w.WriteStartArray("elements");
foreach (var el in _scene.Elements)
{
Expand All @@ -726,6 +736,9 @@ public void WriteMeta(Stream output)
w.WriteString("category", string.IsNullOrEmpty(el.Category) ? "General" : el.Category);
w.WriteString("type", el.TypeName);
w.WriteString("level", el.LevelId is int level ? levels.GetValueOrDefault(level, string.Empty) : string.Empty);
if (el.LevelId is int levelId) w.WriteNumber("levelId", levelId);
// The first model is the default so single-source files do not repeat its ID on every element.
if (el.ModelId != host?.Id) w.WriteNumber("modelId", el.ModelId);
if (host is null || el.ModelId == host.Id || links.GetValueOrDefault(el.ModelId) is not { Length: > 0 } link) w.WriteNull("link");
else w.WriteString("link", link);
if (!string.IsNullOrEmpty(el.SourceId)) w.WriteString("sourceId", el.SourceId);
Expand Down
348 changes: 174 additions & 174 deletions src/IOViewer/Viewer/dist/viewer.js

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion src/IOViewer/Viewer/playwright.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ export default defineConfig({
{ name: 'chromium', use: { browserName: 'chromium' } },
{
name: 'firefox',
testMatch: ['**/smoke.spec.js', '**/selection.spec.js', '**/sections.spec.js', '**/accessibility.spec.js', '**/tree-selection.spec.js'],
testMatch: ['**/smoke.spec.js', '**/selection.spec.js', '**/sections.spec.js', '**/accessibility.spec.js',
'**/tree-selection.spec.js', '**/tree-filters.spec.js'],
use: {
browserName: 'firefox',
// Under Linux, Xvfb supplies the display Firefox uses to create a WebGL context in CI.
Expand Down
7 changes: 6 additions & 1 deletion src/IOViewer/Viewer/src/data.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,14 @@ function validateMeta(meta) {
throw new ModelDataError('Invalid META geometry.');
}
}
for (const name of ['textures', 'grids', 'viewpoints', 'clashTests', 'linkedFiles']) {
for (const name of ['textures', 'grids', 'viewpoints', 'clashTests', 'linkedFiles', 'models']) {
if (meta[name] != null && !records(meta[name])) throw new ModelDataError(`Invalid META ${name} list.`);
}
if (meta.models?.some(({ id, name }) => !Number.isSafeInteger(id) || typeof name !== 'string')
|| meta.elements.some(({ modelId, levelId }) => (modelId != null && !Number.isSafeInteger(modelId))
|| (levelId != null && !Number.isSafeInteger(levelId)))) {
throw new ModelDataError('Invalid META model or level identity.');
}
for (const material of meta.materials) {
const index = material.texture;
if (!vector(material.color) || typeof material.opacity !== 'number'
Expand Down
12 changes: 12 additions & 0 deletions src/IOViewer/Viewer/src/i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@ const dictionaries = {
searchPlaceholder: 'Поиск по имени, типу, Id…',
noCategory: 'Без категории',
noMatches: 'Ничего не найдено',
'filters.title': 'Фильтры',
'filters.model': 'Модель-источник',
'filters.noLevel': 'Без уровня',
'filters.all': 'Все',
'filters.clear': 'Сбросить',
'filters.isolate': 'Изолировать совпадения',
idCopied: 'Id скопирован',
copyFailed: 'Не удалось скопировать Id',
fullscreenUnavailable: 'Полноэкранный режим недоступен',
Expand Down Expand Up @@ -164,6 +170,12 @@ const dictionaries = {
searchPlaceholder: 'Search by name, type, Id…',
noCategory: 'No category',
noMatches: 'No matches',
'filters.title': 'Filters',
'filters.model': 'Source model',
'filters.noLevel': 'No level',
'filters.all': 'All',
'filters.clear': 'Clear',
'filters.isolate': 'Isolate matches',
idCopied: 'Id copied',
copyFailed: 'Could not copy Id',
fullscreenUnavailable: 'Fullscreen is not available',
Expand Down
1 change: 1 addition & 0 deletions src/IOViewer/Viewer/src/ui/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export function mountUI({ root, data, scene, controls, picker, selection, measur
render: (body) =>
mountTree(body, {
elements: meta.elements,
models: meta.models ?? [],
selection,
scene,
openContextMenu,
Expand Down
42 changes: 28 additions & 14 deletions src/IOViewer/Viewer/src/ui/tree.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { t } from '../i18n.js';
import { icons } from './icons.js';
import { el } from './dom.js';
import { isContextMenuKey } from './hotkeys.js';
import { createTreeFilters } from './treeFilters.js';

export const ROW_HEIGHT = 24; // px, every row; the list is virtualized on this fixed height
const OVERSCAN = 8;
Expand Down Expand Up @@ -37,11 +38,11 @@ export function groupByCategory(elements) {
}

/**
* Model tree in `container`: collapsed categories with counts, then elements (name, muted type); a search flattens
* Model tree in `container`: collapsed categories with counts, then elements (name, muted type); search and filters flatten
* matches. Rows in view and the focused row exist in the DOM. Activating an element selects and zooms to it;
* selecting elsewhere scrolls to and highlights the last selected row, expanding its category. Hidden elements are dimmed.
*/
export function mountTree(container, { elements, selection, scene, zoomToElement, openContextMenu }) {
export function mountTree(container, { elements, models, selection, scene, zoomToElement, openContextMenu }) {
const groups = groupByCategory(elements);
const categoryOf = new Int32Array(elements.length);
groups.forEach((group, c) => group.indices.forEach((i) => (categoryOf[i] = c)));
Expand All @@ -50,6 +51,7 @@ export function mountTree(container, { elements, selection, scene, zoomToElement
const selectedCounts = new Uint32Array(groups.length);
const search = createSearch(elements);
let query = '';
let flat = false;
let rows = new Int32Array(0); // element index, or -(category + 1) for a category header
let tabRow = 0;
let pendingRow = -1; // row to scroll to once the tree has a size (it is laid out only while its panel is open)
Expand All @@ -69,12 +71,22 @@ export function mountTree(container, { elements, selection, scene, zoomToElement
spacer.setAttribute('role', 'presentation');
viewport.append(spacer);
const empty = el('div', 'ioviewer-tree-empty', t('noMatches'));
container.append(input, viewport, empty);
const filters = createTreeFilters(elements, models, input, refilter, () => scene.isolate(rows));
container.append(filters.element, input, viewport, empty);

function rebuild() {
const previous = rows[tabRow];
if (query) {
rows = Int32Array.from(search(query));
const matches = filters.predicate();
flat = Boolean(query || matches);
if (flat) {
const candidates = query ? search(query) : elements.keys();
if (matches) {
const found = [];
for (const index of candidates) if (matches(elements[index])) found.push(index);
rows = Int32Array.from(found);
} else {
rows = Int32Array.from(candidates);
}
} else {
let count = groups.length;
groups.forEach((group, c) => expanded[c] && (count += group.indices.length));
Expand All @@ -89,7 +101,8 @@ export function mountTree(container, { elements, selection, scene, zoomToElement
const next = rows.indexOf(previous);
tabRow = next >= 0 ? next : 0;
spacer.style.height = `${rows.length * ROW_HEIGHT}px`;
empty.hidden = rows.length > 0 || !query;
empty.hidden = rows.length > 0 || !flat;
filters.update(query, flat && rows.some((index) => scene.instancesOf(index).length > 0));
render();
}

Expand Down Expand Up @@ -136,10 +149,10 @@ export function mountTree(container, { elements, selection, scene, zoomToElement
} else {
const element = elements[value];
node.classList.add('tree-element');
node.setAttribute('aria-level', query ? '1' : '2');
node.setAttribute('aria-posinset', String(query ? r + 1 : r - groupRows[c]));
node.setAttribute('aria-setsize', String(query ? rows.length : groups[c].indices.length));
node.classList.toggle('tree-child', !query);
node.setAttribute('aria-level', flat ? '1' : '2');
node.setAttribute('aria-posinset', String(flat ? r + 1 : r - groupRows[c]));
node.setAttribute('aria-setsize', String(flat ? rows.length : groups[c].indices.length));
node.classList.toggle('tree-child', !flat);
node.classList.toggle('tree-hidden', !scene.isVisible(value));
node.append(el('span', 'tree-name', element.name || `#${element.id}`), el('span', 'tree-type', element.type ?? ''));
}
Expand All @@ -165,7 +178,7 @@ export function mountTree(container, { elements, selection, scene, zoomToElement

function reveal(index) {
const c = categoryOf[index];
if (!query && !expanded[c]) {
if (!flat && !expanded[c]) {
expanded[c] = 1;
rebuild();
}
Expand Down Expand Up @@ -226,13 +239,14 @@ export function mountTree(container, { elements, selection, scene, zoomToElement
input.addEventListener('focus', () => {
if (!spacer.firstElementChild) syncLayout();
});
input.addEventListener('input', () => {
function refilter() {
query = input.value.trim();
viewport.scrollTop = 0;
pendingRow = -1;
tabRow = -1;
rebuild();
});
}
input.addEventListener('input', refilter);
viewport.addEventListener('scroll', () => render());
viewport.addEventListener('focusin', (e) => {
const node = e.target.closest('.tree-row');
Expand Down Expand Up @@ -287,7 +301,7 @@ export function mountTree(container, { elements, selection, scene, zoomToElement
}
break;
case 'ArrowLeft':
if (value >= 0 && !query) next = groupRows[categoryOf[value]];
if (value >= 0 && !flat) next = groupRows[categoryOf[value]];
else if (value < 0 && expanded[-value - 1]) {
expanded[-value - 1] = 0;
rebuild();
Expand Down
86 changes: 86 additions & 0 deletions src/IOViewer/Viewer/src/ui/treeFilters.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { t } from '../i18n.js';
import { el } from './dom.js';

// The select values are option positions. Model and level keys keep their original types for exact matching.
export function createTreeFilters(elements, models, search, onChange, onIsolate) {
const details = el('details', 'ioviewer-tree-filters');
details.hidden = elements.length === 0;
const summary = el('summary', '', t('filters.title'));
const body = el('div', 'ioviewer-filter-fields');
const names = new Map(models.map(({ id, name }) => [id, name || `#${id}`]));
const modelOf = (element) => element.modelId ?? models[0]?.id ?? null;
const levelOf = (element) => element.levelId ?? (element.level || null);
const categoryOf = (element) => element.category ?? '';
const fields = [
{ name: t('filters.model'), key: modelOf, labels: new Map() },
{ name: t('level'), key: levelOf, labels: new Map() },
{ name: t('category'), key: categoryOf, labels: new Map() },
];
const [model, level, category] = fields;
const actions = el('div', 'ioviewer-filter-actions');
const clear = el('button', 'ioviewer-text-button', t('filters.clear'));
clear.type = 'button';
clear.addEventListener('click', () => {
for (const field of fields) if (field.select) field.select.selectedIndex = 0;
search.value = '';
onChange();
search.focus();
});
const isolate = el('button', 'ioviewer-text-button', t('filters.isolate'));
isolate.type = 'button';
isolate.addEventListener('click', onIsolate);
actions.append(clear, isolate);
details.append(summary, body, actions);

// Build the option lists only when a user opens the filters, even for very large models.
function populate() {
if (!details.open) return;
details.removeEventListener('toggle', populate);
for (const element of elements) {
const id = modelOf(element);
const modelName = names.get(id) ?? (id == null ? '' : `#${id}`);
if (id != null) model.labels.set(id, modelName);
const key = levelOf(element);
if (!level.labels.has(key)) {
const name = element.level || (key == null ? t('filters.noLevel') : `#${key}`);
level.labels.set(key, key != null && models.length > 1 && modelName ? `${name} · ${modelName}` : name);
}
const group = categoryOf(element);
category.labels.set(group, group || t('noCategory'));
}
for (const field of fields) {
if (!field.labels.size) continue;
const counts = new Map();
for (const label of field.labels.values()) counts.set(label, (counts.get(label) ?? 0) + 1);
const options = [...field.labels].map(([key, label]) => [key, counts.get(label) > 1 ? `${label} (#${key})` : label]);
options.sort((a, b) => a[1].localeCompare(b[1]));
field.keys = options.map(([key]) => key);
const select = field.select = el('select');
select.append(new Option(t('filters.all'), ''));
for (const [index, [, label]] of options.entries()) select.append(new Option(label, String(index + 1)));
select.addEventListener('change', onChange);
const row = el('label', 'ioviewer-filter-field');
row.append(el('span', '', field.name), select);
body.append(row);
}
}
details.addEventListener('toggle', populate);

function activeFields() {
return fields.filter((field) => field.select?.selectedIndex > 0);
}

return {
element: details,
predicate() {
const rules = activeFields().map(({ select, keys, key }) => ({ key, value: keys[select.selectedIndex - 1] }));
return rules.length ? (element) => rules.every(({ key, value }) => key(element) === value) : null;
},
update(query, canIsolate) {
const count = activeFields().length;
summary.textContent = count ? `${t('filters.title')} (${count})` : t('filters.title');
clear.disabled = !count && !query;
isolate.disabled = !canIsolate;
},
};
}
59 changes: 59 additions & 0 deletions src/IOViewer/Viewer/styles/viewer.css
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,65 @@ input:focus-visible {
font: inherit;
}

.ioviewer-tree-filters {
margin-bottom: 6px;
}

.ioviewer-tree-filters summary {
width: fit-content;
padding: 4px 6px;
border-radius: 4px;
cursor: pointer;
}

.ioviewer-tree-filters summary:hover {
background: var(--button);
}

.ioviewer-tree-filters :is(summary, select):focus-visible {
outline: 2px solid var(--accent-text);
outline-offset: -2px;
}

.ioviewer-filter-fields {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 4px 8px;
margin-top: 4px;
}

.ioviewer-filter-field {
display: grid;
grid-column: 1 / -1;
grid-template-columns: subgrid;
align-items: center;
}

.ioviewer-filter-field select {
min-width: 0;
width: 100%;
min-height: 28px;
padding: 3px 5px;
border: 1px solid var(--border);
border-radius: 4px;
background: var(--button);
color: var(--text);
font: inherit;
}

.ioviewer-filter-actions {
display: flex;
flex-wrap: wrap;
gap: 4px;
margin-top: 6px;
}

@media (max-width: 640px) {
.ioviewer-side-panel:has(.ioviewer-tree-filters[open]) {
z-index: 1;
}
}

.ioviewer-tree {
position: relative;
flex: 1 1 auto;
Expand Down
Loading
Loading