feat: add hide/show all geometry actions and implement geometry cache optimization for map rendering
Build and Release / release (push) Successful in 1m2s

This commit is contained in:
taDuc
2026-06-17 15:17:02 +07:00
parent 99c3efe678
commit 59de951edd
8 changed files with 171 additions and 46 deletions
@@ -201,7 +201,7 @@ const narrativeActionDefinitions: NarrativeActionDefinitionMap = {
text: string;
image_url?: string;
} = {
text: asString(values.text),
text: asString(values.text).replace(/ /g, " ").replace(/\u00a0/g, " "),
};
if (values.image_url) {
data.image_url = asString(values.image_url);
@@ -882,6 +882,26 @@ function GeoFunctionShortcutPanel({
)
}
/>
<ShortcutButton
label="Ẩn Toàn Bộ"
tone="slate"
onClick={() =>
onAppendActions(
[{ function_name: "hide_all_geometries", params: [] }],
"Geo: ẩn toàn bộ"
)
}
/>
<ShortcutButton
label="Hiện Toàn Bộ"
tone="green"
onClick={() =>
onAppendActions(
[{ function_name: "show_all_geometries", params: [] }],
"Geo: hiện toàn bộ"
)
}
/>
<ShortcutButton
label="Đặt làm BG"
tone="teal"
@@ -1410,7 +1430,7 @@ function FieldInput({
if (field.kind === "rich-text") {
return (
<label style={{ display: "grid", gap: 6 }}>
<div style={{ display: "grid", gap: 6 }}>
{baseLabel}
<div style={{ background: "#0b1220", borderRadius: 6, border: "1px solid #334155" }} className="dark">
<ReactQuillEditor
@@ -1420,7 +1440,7 @@ function FieldInput({
modules={quillModules}
/>
</div>
</label>
</div>
);
}
@@ -1717,7 +1737,12 @@ function replaceUiActionsByGroup(
const nextGroupActions = groupOptions
.filter((option) => {
if (option === "timeline" || option === "layer_panel" || option === "zoom_panel") {
if (
option === "timeline" ||
option === "layer_panel" ||
option === "zoom_panel" ||
option === "wiki"
) {
return true;
}
return draft.selected[option];
@@ -1734,7 +1759,12 @@ function buildUiEffectsApplyLabel(
) {
const activeLabels = groupOptions
.filter((option) => {
if (option === "timeline" || option === "layer_panel" || option === "zoom_panel") {
if (
option === "timeline" ||
option === "layer_panel" ||
option === "zoom_panel" ||
option === "wiki"
) {
return true;
}
return draft.selected[option];
@@ -1744,6 +1774,9 @@ function buildUiEffectsApplyLabel(
if (option === "timeline" || option === "layer_panel" || option === "zoom_panel") {
return draft.selected[option] ? `Show ${label}` : `Hide ${label}`;
}
if (option === "wiki") {
return draft.wiki_id ? `Open ${label}: ${draft.wiki_id}` : `Close ${label}`;
}
return label;
});
@@ -240,17 +240,12 @@ function getBackgroundGeometryIdsFromReplay(replay: BattleReplay | null): Set<st
? Math.max(...stages.map((stage) => stage.id)) + 1
: 0;
const bgIds = getBackgroundGeometryIdsFromReplay(replay);
const geometriesToHide = (replay.target_geometry_ids || []).filter(
(id: string) => !bgIds.has(String(id))
);
const initialGeoFunctions = [];
if (geometriesToHide.length > 0) {
initialGeoFunctions.push({
function_name: "set_geometry_visibility" as const,
params: [geometriesToHide, false],
});
}
const initialGeoFunctions = [
{
function_name: "hide_all_geometries" as const,
params: [],
},
];
const nextStage: ReplayStage = {
id: nextId,
@@ -583,22 +578,13 @@ function getBackgroundGeometryIdsFromReplay(replay: BattleReplay | null): Set<st
<button
type="button"
onClick={onPlayPreviewFromSelection}
disabled={!replay || selectedStage == null || selectedStepIndex == null}
disabled={true /* Tạm thời khóa nút này */}
style={{
...buttonStyle,
background:
!replay || selectedStage == null || selectedStepIndex == null
? "#1e293b"
: "#0f766e",
background: "#1e293b",
border: "none",
cursor:
!replay || selectedStage == null || selectedStepIndex == null
? "not-allowed"
: "pointer",
opacity:
!replay || selectedStage == null || selectedStepIndex == null
? 0.7
: 1,
cursor: "not-allowed",
opacity: 0.7,
}}
>
Play từ step
@@ -1435,6 +1421,8 @@ const geoFunctionLabels: Record<GeoFunctionName, string> = {
orbit_camera_around_geometry: "Orbit quanh geo",
set_as_background_geometries: "Đặt làm background",
remove_from_background_geometries: "Loại khỏi background",
hide_all_geometries: "Ẩn toàn bộ geo",
show_all_geometries: "Hiện toàn bộ geo",
};
function buildStepActionEntries(step: ReplayStep): StepActionEntry[] {
@@ -1591,6 +1579,12 @@ function buildGeoActionEntry(
case "remove_from_background_geometries":
summary = `geometry=${summarizeGeometryIdsValue(params[0])}`;
break;
case "hide_all_geometries":
summary = "Ẩn toàn bộ geo ngoại trừ background";
break;
case "show_all_geometries":
summary = "Hiện toàn bộ geo";
break;
}
return {
+60 -2
View File
@@ -338,7 +338,7 @@ export function buildPolygonLabelFeatureCollection(
continue;
}
const labelPoint = getPolygonLabelPoint(feature.geometry);
const labelPoint = getPolygonLabelPoint(feature.geometry, feature.properties.id);
if (!labelPoint) continue;
const labelFeature: Feature = {
@@ -485,6 +485,32 @@ export function getGeometryRepresentativePoint(geometry: Geometry): Coordinate |
}
const pathArrowGeometriesCache = new WeakMap<Geometry, Geometry[]>();
const pathArrowGeometriesL2Cache = new Map<string, Geometry[]>();
const polygonLabelPointL2Cache = new Map<string, Coordinate | null>();
const MAX_L2_CACHE_SIZE = 1000;
export function clearGeometryCaches() {
pathArrowGeometriesL2Cache.clear();
polygonLabelPointL2Cache.clear();
}
function getGeometryFingerprint(geometry: Geometry): string {
const coords = geometry.coordinates;
if (!Array.isArray(coords)) return geometry.type;
if (typeof coords[0] === "number") {
return `${geometry.type}:${coords[0]},${coords[1]}`;
}
const flat = coords.flat(4) as number[];
if (flat.length === 0) return geometry.type;
const len = flat.length;
const first = flat[0];
const last = flat[len - 1];
const mid = flat[Math.floor(len / 2)];
return `${geometry.type}:${len}:${first}:${mid}:${last}`;
}
export function buildPathArrowFeatureCollection(fc: FeatureCollection): FeatureCollection {
const features: Feature[] = [];
@@ -494,6 +520,14 @@ export function buildPathArrowFeatureCollection(fc: FeatureCollection): FeatureC
let arrowGeometries = pathArrowGeometriesCache.get(feature.geometry);
if (!arrowGeometries) {
const featureId = feature.properties?.id;
const fingerprint = getGeometryFingerprint(feature.geometry);
const cacheKey = featureId ? `${featureId}:${fingerprint}` : null;
if (cacheKey && pathArrowGeometriesL2Cache.has(cacheKey)) {
arrowGeometries = pathArrowGeometriesL2Cache.get(cacheKey)!;
pathArrowGeometriesCache.set(feature.geometry, arrowGeometries);
} else {
arrowGeometries = [];
const coordinateGroups = getLineCoordinateGroups(feature.geometry);
const featureType = getFeatureSemanticType(feature);
@@ -503,6 +537,13 @@ export function buildPathArrowFeatureCollection(fc: FeatureCollection): FeatureC
if (geometry) arrowGeometries.push(geometry);
}
pathArrowGeometriesCache.set(feature.geometry, arrowGeometries);
if (cacheKey) {
if (pathArrowGeometriesL2Cache.size >= MAX_L2_CACHE_SIZE) {
pathArrowGeometriesL2Cache.clear();
}
pathArrowGeometriesL2Cache.set(cacheKey, arrowGeometries);
}
}
}
for (const geometry of arrowGeometries) {
@@ -1163,10 +1204,20 @@ function getLineCoordinateGroups(geometry: Geometry): Coordinate[][] {
const polygonLabelPointCache = new WeakMap<Geometry, Coordinate | null>();
function getPolygonLabelPoint(geometry: Geometry): Coordinate | null {
function getPolygonLabelPoint(geometry: Geometry, featureId?: string | number): Coordinate | null {
if (polygonLabelPointCache.has(geometry)) {
return polygonLabelPointCache.get(geometry)!;
}
const fingerprint = getGeometryFingerprint(geometry);
const cacheKey = featureId ? `${featureId}:${fingerprint}` : null;
if (cacheKey && polygonLabelPointL2Cache.has(cacheKey)) {
const result = polygonLabelPointL2Cache.get(cacheKey)!;
polygonLabelPointCache.set(geometry, result);
return result;
}
let result: Coordinate | null = null;
if (geometry.type === "Polygon") {
result = getPolygonLabelCandidate(geometry.coordinates)?.point || null;
@@ -1181,7 +1232,14 @@ function getPolygonLabelPoint(geometry: Geometry): Coordinate | null {
}
result = best?.point || null;
}
polygonLabelPointCache.set(geometry, result);
if (cacheKey) {
if (polygonLabelPointL2Cache.size >= MAX_L2_CACHE_SIZE) {
polygonLabelPointL2Cache.clear();
}
polygonLabelPointL2Cache.set(cacheKey, result);
}
return result;
}
+5 -1
View File
@@ -169,7 +169,9 @@ export type GeoFunctionName =
| "set_geometry_style"
| "orbit_camera_around_geometry"
| "set_as_background_geometries"
| "remove_from_background_geometries";
| "remove_from_background_geometries"
| "hide_all_geometries"
| "show_all_geometries";
export type NarrativeFunctionName =
| "set_dialog";
@@ -283,6 +285,8 @@ export type ReplayGeoFunctionParamTupleDocs = {
remove_from_background_geometries: [
geometry_ids: string[],
];
hide_all_geometries: [];
show_all_geometries: [];
};
export type ReplayNarrativeParamTupleDocs = {
@@ -1193,6 +1193,18 @@ function normalizeReplayMapAndGeoActions(
params,
});
break;
case "hide_all_geometries":
normalizedGeoActions.push({
function_name: "hide_all_geometries",
params: [],
});
break;
case "show_all_geometries":
normalizedGeoActions.push({
function_name: "show_all_geometries",
params: [],
});
break;
default:
break;
}
+10 -1
View File
@@ -36,6 +36,7 @@ export interface ReplayControllers {
hideGeometries: (ids: string[]) => void;
showOnlyGeometries: (ids: string[]) => void;
showAllGeometries: () => void;
hideAllGeometries: () => void;
setAsBackgroundGeometries: (ids: string[]) => void;
removeFromBackgroundGeometries: (ids: string[]) => void;
@@ -98,6 +99,12 @@ export const dispatchReplayAction = (
case "hide_others_geometries":
controllers.showOnlyGeometries(toStringValues(params[0]));
return;
case "hide_all_geometries":
controllers.hideAllGeometries();
return;
case "show_all_geometries":
controllers.showAllGeometries();
return;
case "pulse_geometry":
controllers.effects.pulseGeometry(
map,
@@ -247,8 +254,10 @@ function normalizeSingleAction(action: unknown): ReplayAction<ReplayFunctionName
case "reset_camera_north":
return { function_name: "set_camera_view", params: [{ bearing: 0 }] };
case "set_time_filter":
case "show_all_geometries":
return null;
case "hide_all_geometries":
case "show_all_geometries":
return { function_name, params: [] };
// Geo Functions
case "fly_to_geometries":
+16 -3
View File
@@ -6,6 +6,7 @@ import type { BattleReplay, ReplayStage, ReplayStep, DialogState } from "@/uhm/t
import { dispatchReplayAction } from "./replayDispatcher";
import { mapActions } from "./mapActions";
import { createReplayMapEffects } from "./replayMapEffects";
import { clearGeometryCaches } from "@/uhm/components/map/mapUtils";
export type ReplayPreviewToast = {
id: number;
@@ -205,11 +206,13 @@ export function useReplayPreview({
});
}
}
clearGeometryCaches();
}, [getMapInstance, resetPresentation, setMapProjection]);
const resetPreview = useCallback(() => {
runIdRef.current += 1;
restorePreviewState();
clearGeometryCaches();
}, [restorePreviewState]);
const stopPreview = useCallback(() => {
@@ -217,6 +220,7 @@ export function useReplayPreview({
isPlayingRef.current = false;
setIsPlaying(false);
getMapInstance()?.stop();
clearGeometryCaches();
}, [getMapInstance]);
useEffect(() => {
@@ -224,7 +228,10 @@ export function useReplayPreview({
const timeoutId = window.setTimeout(() => {
restorePreviewState();
}, 0);
return () => window.clearTimeout(timeoutId);
return () => {
window.clearTimeout(timeoutId);
clearGeometryCaches();
};
}, [replay?.id, restorePreviewState]);
const controllers = useMemo<Parameters<typeof dispatchReplayAction>[0]>(() => ({
@@ -290,6 +297,13 @@ export function useReplayPreview({
showAllGeometries: () => {
setHiddenGeometryIds([]);
},
hideAllGeometries: () => {
setHiddenGeometryIds(
draft.features
.map((feature) => String(feature.properties.id))
.filter((id) => !backgroundIdsRef.current.has(id))
);
},
setDialog: setDialogWithRef,
getDialog: () => dialogRef.current,
}), [
@@ -301,13 +315,12 @@ export function useReplayPreview({
]);
const controllersRef = useRef<Parameters<typeof dispatchReplayAction>[0] | null>(null);
useEffect(() => {
controllersRef.current = controllers;
}, [controllers]);
const playFromIndex = useCallback(async (startIndex: number) => {
if (!flatSteps.length) return;
clearGeometryCaches();
const map = getMapInstance();
if (map) {
map.stop(); // Stop ongoing camera animations/transitions immediately
+3 -1
View File
@@ -113,7 +113,9 @@ export type GeoFunctionName =
| "set_geometry_style" // Đổi style trực tiếp của geometry
| "orbit_camera_around_geometry" // Quay camera quanh một geometry
| "set_as_background_geometries" // Đặt các geometry làm background (luôn hiện)
| "remove_from_background_geometries"; // Loại các geometry khỏi background
| "remove_from_background_geometries" // Loại các geometry khỏi background
| "hide_all_geometries" // Ẩn toàn bộ geometry (ngoại trừ background)
| "show_all_geometries"; // Hiện toàn bộ geometry
export type NarrativeFunctionName =
| "set_dialog"; // Đặt kịch bản đối thoại/hình ảnh dẫn chuyện mới (hoặc null để xóa)