Skip to content
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

Some code cleaning #124

Merged
merged 2 commits into from
Sep 6, 2024
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 packages/base/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@
"@apidevtools/json-schema-ref-parser": "^9.0.9",
"@types/node": "^18.15.11",
"@types/three": "^0.135.0",
"@types/uuid": "^10.0.0",
"rimraf": "^3.0.2",
"typescript": "^5"
},
Expand Down
51 changes: 26 additions & 25 deletions packages/base/src/dialogs/components/color-expression/StopRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,32 +17,32 @@ const StopRow = ({
stopRows: IStopRow[];
setStopRows: any;
}) => {
const [inputZoom, setInputZoom] = useState(10);
const [inputColor, setInputColor] = useState('');
const [, setInputZoom] = useState(10);
const [, setInputColor] = useState('');

const rgbaStringToHex = rgbaStr => {
// Remove the "rgba(" part and close parenthesis
const rgbaParts = rgbaStr.replace('rgba(', '').replace(')', '');
// const rgbaStringToHex = (rgbaStr: any) => {
// // Remove the "rgba(" part and close parenthesis
// const rgbaParts = rgbaStr.replace('rgba(', '').replace(')', '');

// Split the string into individual components
const [r, g, b, a] = rgbaParts
.split(',')
.map(part => parseInt(part.trim()));
// // Split the string into individual components
// const [r, g, b, a] = rgbaParts
// .split(',')
// .map((part: any) => parseInt(part.trim()));

// Convert R, G, B to hexadecimal and ensure they are two digits long
const rHex = r.toString(16).padStart(2, '0');
const gHex = g.toString(16).padStart(2, '0');
const bHex = b.toString(16).padStart(2, '0');
// // Convert R, G, B to hexadecimal and ensure they are two digits long
// const rHex = r.toString(16).padStart(2, '0');
// const gHex = g.toString(16).padStart(2, '0');
// const bHex = b.toString(16).padStart(2, '0');

// Optionally handle alpha channel if needed
// For simplicity, this example ignores the alpha channel
// If you need to include alpha, you could append it after the RGB part, e.g., `return '#' + rHex + gHex + bHex + (a === 1 ? '' : a.toString(16));`
return '#' + rHex + gHex + bHex;
};
// // Optionally handle alpha channel if needed
// // For simplicity, this example ignores the alpha channel
// // If you need to include alpha, you could append it after the RGB part, e.g., `return '#' + rHex + gHex + bHex + (a === 1 ? '' : a.toString(16));`
// return '#' + rHex + gHex + bHex;
// };

const rgbArrToHex = rgbArr => {
const rgbArrToHex = (rgbArr: any) => {
const hex = rgbArr
.map(val => {
.map((val: any) => {
return val.toString(16).padStart(2, '0');
return hex.length === 1 ? '0' + hex : hex;
})
Expand All @@ -51,7 +51,7 @@ const StopRow = ({
return '#' + hex;
};

const hexToRgb = hex => {
const hexToRgb = (hex: any) => {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
const l = result
? [
Expand All @@ -63,14 +63,15 @@ const StopRow = ({
return l;
};

const handleValueChange = event => {
const handleValueChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const newRows = [...stopRows];
stopRows[index].value = event.target.value;
const value = parseFloat(event.target.value);
stopRows[index].value = value;
setStopRows(newRows);
setInputZoom(event.target.value);
setInputZoom(value);
};

const handleColorChange = event => {
const handleColorChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const newRows = [...stopRows];
stopRows[index].color = hexToRgb(event.target.value);
setStopRows(newRows);
Expand Down
2 changes: 1 addition & 1 deletion packages/base/src/dialogs/layerBrowserDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export const LayerBrowserComponent = ({
/**
* Track which layers are currently added to the map
*/
const handleLayerChange = (_, change: IJGISLayerDocChange) => {
const handleLayerChange = (_: any, change: IJGISLayerDocChange) => {
// The split is to get rid of the 'Layer' part of the name to match the names in the gallery
setActiveLayers(
Object.values(context.model.sharedModel.layers).map(
Expand Down
2 changes: 1 addition & 1 deletion packages/base/src/formbuilder/objectform/baseform.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { SchemaForm } from '@deathbeds/jupyterlab-rjsf';
import { MessageLoop } from '@lumino/messaging';
import { Widget } from '@lumino/widgets';
import { IChangeEvent, ISubmitEvent, WidgetProps } from '@rjsf/core';
import { IChangeEvent, ISubmitEvent } from '@rjsf/core';
import * as React from 'react';

import { IJupyterGISModel } from '@jupytergis/schema';
Expand Down
2 changes: 1 addition & 1 deletion packages/base/src/formbuilder/objectform/tilesourceform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export class TileSourcePropertiesForm extends BaseForm {
}

// Dynamically inject url parameters schema based of the url
const propertiesSchema = {};
const propertiesSchema: { [name: string]: any } = {};
schema.properties.urlParameters = {
type: 'object',
required: this._urlParameters,
Expand Down
10 changes: 2 additions & 8 deletions packages/base/src/formbuilder/objectform/vectorlayerform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import { ILayerProps, LayerPropertiesForm } from './layerform';
* The form to modify a vector layer.
*/
export class VectorLayerPropertiesForm extends LayerPropertiesForm {
private sourceLayers: string[] = [];
private currentSourceUrl = '';
protected currentFormData: IVectorLayer;
private sourceLayers: string[] = [];
private currentSourceId: string;

constructor(props: ILayerProps) {
super(props);
Expand Down Expand Up @@ -111,9 +111,6 @@ export class VectorLayerPropertiesForm extends LayerPropertiesForm {
sourceData = currentSource.parameters as IVectorTileSource;
}

// if (this.currentSourceUrl !== sourceData.url) {
this.currentSourceUrl = sourceData.url;

try {
this.sourceLayers = await getSourceLayerNames(
sourceData.url,
Expand All @@ -123,13 +120,10 @@ export class VectorLayerPropertiesForm extends LayerPropertiesForm {
} catch (e) {
console.error(e);
}
// }
} else {
this.currentSourceId = '';
this.sourceLayers = [];
this.forceUpdate();
}
}

private currentSourceId: string;
}
37 changes: 10 additions & 27 deletions packages/base/src/mainview/mainView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { IObservableMap, ObservableMap } from '@jupyterlab/observables';
import { User } from '@jupyterlab/services';
import { JSONValue, UUID } from '@lumino/coreutils';
import { Map as OlMap, View } from 'ol';
import { FeatureLike } from 'ol/Feature';
import { GeoJSON, MVT } from 'ol/format';
import DragAndDrop from 'ol/interaction/DragAndDrop';
import {
Expand Down Expand Up @@ -57,6 +58,7 @@ import { isLightTheme } from '../tools';
interface IProps {
viewModel: MainViewModel;
}

interface IStates {
id: string; // ID of the component, it is used to identify which component
//is the source of awareness updates.
Expand Down Expand Up @@ -141,10 +143,6 @@ export class MainView extends React.Component<IProps, IStates> {
});

dragAndDropInteraction.on('addfeatures', event => {
// const source = new VectorSource({
// features: event.features
// });

const sourceId = UUID.uuid4();

const sourceModel: IJGISSource = {
Expand Down Expand Up @@ -172,10 +170,6 @@ export class MainView extends React.Component<IProps, IStates> {
const layerId = UUID.uuid4();
this.addLayer(layerId, layerModel, this.getLayers().length);
this._model.addLayer(layerId, layerModel);

// this._Map
// .getView()
// .fit(this._sources[layerModel.parameters?.source].getExtent());
});

this._Map.addInteraction(dragAndDropInteraction);
Expand Down Expand Up @@ -572,7 +566,7 @@ export class MainView extends React.Component<IProps, IStates> {
this._Map.getLayers().insertAt(index, newLayer);
}

vectorLayerStyleFunc = (currentFeature, layer) => {
vectorLayerStyleFunc = (currentFeature: FeatureLike, layer: IJGISLayer) => {
const layerParameters = layer.parameters as IVectorLayer;

// const flatStyle = {
Expand All @@ -587,12 +581,12 @@ export class MainView extends React.Component<IProps, IStates> {

// TODO: Need to make a version that works with strings as well
const operators = {
'>': (a, b) => a > b,
'<': (a, b) => a < b,
'>=': (a, b) => a >= b,
'<=': (a, b) => a <= b,
'==': (a, b) => a === b,
'!=': (a, b) => a !== b
'>': (a: number | string, b: number | string) => a > b,
'<': (a: number | string, b: number | string) => a < b,
'>=': (a: number | string, b: number | string) => a >= b,
'<=': (a: number | string, b: number | string) => a <= b,
'==': (a: number | string, b: number | string) => a === b,
'!=': (a: number | string, b: number | string) => a !== b
};

// TODO: I don't think this will work with fancy color expressions
Expand Down Expand Up @@ -668,7 +662,7 @@ export class MainView extends React.Component<IProps, IStates> {
// Other frequently used methods include the Mapbox format
// (red * 256 * 256 + green * 256 + blue) * 0.1 - 10000
//
function elevation(xOffset, yOffset) {
function elevation(xOffset: number, yOffset: number) {
const red = ['band', 1, xOffset, yOffset];
const green = ['band', 2, xOffset, yOffset];
const blue = ['band', 3, xOffset, yOffset];
Expand Down Expand Up @@ -942,17 +936,6 @@ export class MainView extends React.Component<IProps, IStates> {
});
}

private getSource<T>(id: string): T | undefined {
const source = this._model.sharedModel.getSource(id);

if (!source || !source.parameters) {
console.log(`Source id ${id} does not exist`);
return;
}

return source.parameters as T;
}

private _handleThemeChange = (): void => {
const lightTheme = isLightTheme();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ const FilterComponent = (props: IFilterComponentProps) => {
setSelectedLayer(currentLayer);
};

const handleSharedOptionsChanged = (_, keys) => {
const handleSharedOptionsChanged = (_: any, keys: any) => {
// model changes when current widget changes, don't want this to run in that case
if (props.tracker.currentWidget?.id === widgetId && keys.has('zoom')) {
if (!model?.localState?.selected?.value) {
Expand Down
33 changes: 19 additions & 14 deletions packages/base/src/panelview/components/filter-panel/FilterRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ const FilterRow = ({
}) => {
const operators = ['==', '!=', '>', '<', '>=', '<='];

const [sortedFeatures, setSortedFeatures] = useState({});
const [sortedFeatures, setSortedFeatures] = useState<{ [key: string]: any }>(
{}
);
const [selectedFeature, setSelectedFeature] = useState(
filterRows[index].feature || Object.keys(features)[0]
);
Expand All @@ -30,7 +32,7 @@ const FilterRow = ({

useEffect(() => {
const sortedKeys = Object.keys(features).sort();
const sortedResult = {};
const sortedResult: { [key: string]: any } = {};

for (const key of sortedKeys) {
// Convert each Set to a sorted array
Expand All @@ -52,31 +54,34 @@ const FilterRow = ({
}

const currentValue = valueSelect.options[valueSelect.selectedIndex]?.value;
currentValue &&
handleValueChange({
target: { value: currentValue }
});
currentValue && onValueChange(currentValue);
}, [selectedFeature]);

const handleKeyChange = event => {
const onValueChange = (value: string | number) => {
const newFilters = [...filterRows];
const isNum = typeof sortedFeatures[selectedFeature][0] === 'number';

newFilters[index].value = isNum ? +value : value;
setFilterRows(newFilters);
};

const handleKeyChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
const newFilters = [...filterRows];
newFilters[index].feature = event.target.value;
setSelectedFeature(event.target.value);
setFilterRows(newFilters);
};

const handleOperatorChange = event => {
const handleOperatorChange = (
event: React.ChangeEvent<HTMLSelectElement>
) => {
const newFilters = [...filterRows];
newFilters[index].operator = event.target.value;
setFilterRows(newFilters);
};

const handleValueChange = event => {
const newFilters = [...filterRows];
const isNum = typeof sortedFeatures[selectedFeature][0] === 'number';

newFilters[index].value = isNum ? +event.target.value : event.target.value;
setFilterRows(newFilters);
const handleValueChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
onValueChange(event.target.value);
};

return (
Expand Down
7 changes: 4 additions & 3 deletions packages/base/src/panelview/components/layers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
ReactWidget,
caretDownIcon
} from '@jupyterlab/ui-components';
import { ReadonlyPartialJSONValue } from '@lumino/coreutils';
import { Panel } from '@lumino/widgets';
import React, {
MouseEvent as ReactMouseEvent,
Expand Down Expand Up @@ -242,10 +243,10 @@ function LayerGroupComponent(props: ILayerGroupProps): JSX.Element {

useEffect(() => {
setId(DOMUtils.createDomID());

const getExpandedState = async () => {
const groupState = await state.fetch(group.name);
setOpen(groupState ? groupState['expanded'] : false);
const groupState: ReadonlyPartialJSONValue | undefined =
await state.fetch(group.name);
setOpen(groupState ? (groupState as any)['expanded'] ?? false : false);
};

getExpandedState();
Expand Down
8 changes: 4 additions & 4 deletions packages/base/src/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ export const debounce = (
func: CallableFunction,
timeout = 100
): CallableFunction => {
let timeoutId;
return (...args) => {
let timeoutId: number;
return (...args: any[]) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
timeoutId = window.setTimeout(() => {
func(...args);
}, timeout);
};
Expand Down Expand Up @@ -157,7 +157,7 @@ export function createDefaultLayerRegistry(
importAll(context);

for (const entry of Object.keys(RASTER_LAYER_GALLERY)) {
const xyzprovider = RASTER_LAYER_GALLERY[entry];
const xyzprovider: any = (RASTER_LAYER_GALLERY as any)[entry];

if ('url' in xyzprovider) {
const tile = convertToRegistryEntry(entry, xyzprovider);
Expand Down
4 changes: 2 additions & 2 deletions packages/schema/src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -609,15 +609,15 @@ export class JupyterGISModel implements IJupyterGISModel {
};
}

private _onClientStateChanged = changed => {
private _onClientStateChanged = (changed: any) => {
const clients = this.sharedModel.awareness.getStates() as Map<
number,
IJupyterGISClientState
>;

this._clientStateChanged.emit(clients);

this._sharedModel.awareness.on('change', update => {
this._sharedModel.awareness.on('change', (update: any) => {
if (update.added.length || update.removed.length) {
this._userChanged.emit(this.users);
}
Expand Down
2 changes: 1 addition & 1 deletion python/jupytergis_qgis/src/plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ const activate = async (
QGISSharedModelFactory
);

const widgetCreatedCallback = (sender, widget: JupyterGISWidget) => {
const widgetCreatedCallback = (sender: any, widget: JupyterGISWidget) => {
// Notify the instance tracker if restore data needs to update.
widget.context.pathChanged.connect(() => {
tracker.save(widget);
Expand Down
Loading
Loading