Skip to content

[wip]: legends #880

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
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
95 changes: 95 additions & 0 deletions packages/base/src/dialogs/symbology/hooks/useGetSymbology.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { IJupyterGISModel } from '@jupytergis/schema';
import { useEffect, useState } from 'react';

interface IUseGetSymbologyProps {
layerId?: string;
model: IJupyterGISModel;
}

interface IUseGetSymbologyResult {
symbology: Record<string, any> | null;
isLoading: boolean;
error?: Error;
}

/**
* Extracts symbology information (paint/layout + symbologyState)
* for a given layer from the JupyterGIS model.
* Keeps symbology updated when the layer changes.
*/
export const useGetSymbology = ({
layerId,
model,
}: IUseGetSymbologyProps): IUseGetSymbologyResult => {
const [symbology, setSymbology] = useState<Record<string, any> | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<Error | undefined>();

useEffect(() => {
if (!layerId) {
return;
}

let disposed = false;

const fetchSymbology = () => {
try {
setIsLoading(true);
setError(undefined);

const layer = model.getLayer(layerId);

if (!layer) {
throw new Error(`Layer not found: ${layerId}`);
}

const params = layer.parameters ?? {};
const { symbologyState, color, ...rest } = params;

const result: Record<string, any> = {
...rest,
...(color ? { color } : {}),
...(symbologyState ? { symbologyState } : {}),
};

if (!disposed) {
setSymbology(result);
}
} catch (err) {
if (!disposed) {
setError(err as Error);
setSymbology(null);
}
} finally {
if (!disposed) {
setIsLoading(false);
}
}
};

// initial load
fetchSymbology();

model.sharedLayersChanged.connect(() => {
if (model.getLayer(layerId)) {
fetchSymbology();
} else {
if (!disposed) {
setSymbology(null);
setIsLoading(false);
}
}
});

model.sharedModel.awareness.on('change', () => {
console.log(`Awareness changed for layer ${layerId}`);
fetchSymbology();
});

return () => {
disposed = true;
};
}, [layerId, model]);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should the dependencies include the whole model, or just the piece of the model we care about listening to? Maybe we're firing this hook too much, or not at all because the reference isn't changing but deeply nested values are changing.


return { symbology, isLoading, error };
};
225 changes: 225 additions & 0 deletions packages/base/src/mainview/Legends.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
import { IJupyterGISModel } from '@jupytergis/schema';
import React, { useState } from 'react';
import Draggable from 'react-draggable';

import { useGetSymbology } from '../dialogs/symbology/hooks/useGetSymbology';

interface ILegendsProps {
layerId: string;
model: IJupyterGISModel;
}

const Legends: React.FC<ILegendsProps> = ({ layerId, model }) => {
const [collapsed, setCollapsed] = useState(false);
const { symbology, isLoading, error } = useGetSymbology({ layerId, model });
console.log('symbology', symbology);

const parseColorStops = (expr: any): { value: number; color: string }[] => {
if (!Array.isArray(expr) || expr[0] !== 'interpolate') {
return [];
}
const stops: { value: number; color: string }[] = [];
for (let i = 3; i < expr.length; i += 2) {
const value = expr[i] as number;
const rgba = expr[i + 1] as [number, number, number, number];
const color = Array.isArray(rgba)
? `rgba(${rgba[0]},${rgba[1]},${rgba[2]},${rgba[3]})`
: String(rgba);
stops.push({ value, color });
}
return stops;
};

const parseCaseCategories = (
expr: any,
): { category: string | number; color: string }[] => {
if (!Array.isArray(expr) || expr[0] !== 'case') {
return [];
}

const categories: { category: string | number; color: string }[] = [];

for (let i = 1; i < expr.length - 1; i += 2) {
const condition = expr[i];
const colorExpr = expr[i + 1];

let category;
if (
Array.isArray(condition) &&
condition[0] === '==' &&
Array.isArray(condition[2])
) {
category = condition[2];
} else if (Array.isArray(condition) && condition[0] === '==') {
category = condition[2];
}

let color = '';
if (Array.isArray(colorExpr)) {
color = `rgba(${colorExpr[0]},${colorExpr[1]},${colorExpr[2]},${colorExpr[3]})`;
} else if (typeof colorExpr === 'string') {
color = colorExpr;
}

categories.push({ category, color });
}

return categories;
};

const renderLegend = () => {
if (!symbology) {
return <p>No symbology available</p>;
}

const state = symbology.symbologyState?.renderType;

if (state === 'Single Symbol') {
const color =
symbology.color?.['fill-color'] || symbology.color?.['stroke-color'];
return (
<div
className="legend-item"
style={{ display: 'flex', alignItems: 'center' }}
>
<span
className="legend-color"
style={{
display: 'inline-block',
width: '20px',
height: '20px',
marginRight: '8px',
backgroundColor: color,
border: '1px solid #000',
}}
/>
<span>Layer</span>
</div>
);
}

if (state === 'Graduated') {
const stops = parseColorStops(
symbology.color?.['fill-color'] || symbology.color?.['stroke-color'],
);
if (stops.length === 0) {
return <p>No graduated symbology</p>;
}

return (
<>
{stops.map((stop, idx) => (
<div
key={idx}
className="legend-item"
style={{
display: 'flex',
alignItems: 'center',
marginBottom: '4px',
}}
>
<span
className="legend-color"
style={{
display: 'inline-block',
width: '16px',
height: '16px',
marginRight: '8px',
backgroundColor: stop.color,
border: '1px solid #000',
}}
/>
<span className="legend-label">{stop.value.toFixed(2)}</span>
</div>
))}
</>
);
}

if (state === 'Categorized') {
const categories = parseCaseCategories(
symbology.color?.['fill-color'] || symbology.color?.['stroke-color'],
);
if (categories.length === 0) {
return <p>No categorized symbology</p>;
}

return (
<div style={{ padding: '4px 0' }}>
{categories.map((c, idx) => (
<div
key={idx}
className="legend-item"
style={{
display: 'flex',
alignItems: 'center',
marginBottom: '4px',
}}
>
<span
className="legend-color"
style={{
display: 'inline-block',
width: '16px',
height: '16px',
marginRight: '8px',
backgroundColor: c.color,
border: '1px solid #000',
}}
/>
<span className="legend-label">{String(c.category)}</span>
</div>
))}
</div>
);
}

return <p>Unsupported render type: {state}</p>;
};

return (
<Draggable handle=".legends-header">
<div
className={`legends-container ${collapsed ? 'collapsed' : ''}`}
style={{
position: 'absolute',
top: '100px',
left: '100px',
background: 'white',
border: '1px solid #ccc',
padding: '8px',
minWidth: '180px',
}}
>
{/* Header */}
<div
className="legends-header"
style={{
display: 'flex',
justifyContent: 'space-between',
cursor: 'move',
}}
>
<span className="legends-title">Legends</span>
<button
onClick={() => setCollapsed(!collapsed)}
className="legends-toggle"
>
{collapsed ? '▾' : '▴'}
</button>
</div>

{/* Body */}
{!collapsed && (
<div className="legends-body">
{isLoading && <p>Loading...</p>}
{error && <p style={{ color: 'red' }}>{error.message}</p>}
{!isLoading && renderLegend()}
</div>
)}
</div>
</Draggable>
);
};

export default Legends;
11 changes: 11 additions & 0 deletions packages/base/src/mainview/mainView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ import { FollowIndicator } from './FollowIndicator';
import TemporalSlider from './TemporalSlider';
import { MainViewModel } from './mainviewmodel';
import { LeftPanel, RightPanel } from '../panelview';
import Legends from './Legends';

type OlLayerTypes =
| TileLayer
Expand Down Expand Up @@ -2299,6 +2300,16 @@ export class MainView extends React.Component<IProps, IStates> {
/>
</div>

<Legends
model={this._model}
layerId={
Object.keys(
this._model?.sharedModel.awareness.getLocalState()?.selected
?.value || {},
)[0]
}
/>

{this._state && (
<LeftPanel
model={this._model}
Expand Down
43 changes: 43 additions & 0 deletions python/jupytergis_lab/style/base.css
Original file line number Diff line number Diff line change
Expand Up @@ -840,3 +840,46 @@ div.jGIS-toolbar-widget > div.jp-Toolbar-item:last-child {
.jp-toolbar-users-item > .lm-MenuBar-itemIcon.selected {
border-color: var(--jp-brand-color1);
}

.legends-container {
width: 250px;
height: 200px;
background: white;
border: 1px solid #ccc;
border-radius: 6px;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
overflow: hidden;
z-index: 1000;
}

.legends-container.collapsed {
width: 200px;
height: 40px;
}

.legends-header {
background: #f4f4f4;
padding: 6px;
cursor: move;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid #ddd;
}

.legends-title {
font-weight: bold;
}

.legends-toggle {
border: none;
background: transparent;
cursor: pointer;
font-size: 14px;
}

.legends-body {
padding: 10px;
max-height: 150px;
overflow: auto;
}
Loading