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

Create a widget to query ECSQL strings #213

Draft
wants to merge 8 commits into
base: master
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
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ import {
} from "@itwin/web-viewer-react";
import React, { useCallback, useEffect, useMemo, useState } from "react";

import { EcsqlWidgetProvider } from "../../providers/EcsqlWidgetProvider";
import { history } from "../routing";

/**
* Test a viewer that uses auth configuration provided at startup
* @returns
Expand Down Expand Up @@ -140,6 +142,7 @@ const ViewerHome: React.FC = () => {
enableCopyingPropertyText: true,
}),
new MeasureToolsUiItemsProvider(),
new EcsqlWidgetProvider(),
]}
extensions={[
new LocalExtensionProvider({
Expand Down
149 changes: 149 additions & 0 deletions packages/apps/web-viewer-test/src/providers/EcsqlWidget.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/

import { useActiveIModelConnection } from "@itwin/appui-react";
import { QueryRowFormat } from "@itwin/core-common";
import {
Button,
ExpandableBlock,
LabeledTextarea,
Table,
} from "@itwin/itwinui-react";
import React, { useState } from "react";

export default function EcsqlWidget() {
const [input, setInput] = useState("");
const [data, setData] = useState<Record<string, string | React.ReactNode>[]>(
[]
);
const [headers, setHeaders] = useState<string[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState("");
const iModelConnection = useActiveIModelConnection();

const getData = async () => {
if (!iModelConnection) {
return;
}
try {
setData([]);
setHeaders([]);
setIsLoading(true);
const results = iModelConnection.query(input, undefined, {
aruniverse marked this conversation as resolved.
Show resolved Hide resolved
rowFormat: QueryRowFormat.UseJsPropertyNames,
});
const rows: Record<string, string | React.ReactNode>[] = [];
const columnHeaders: string[] = [];

for await (const obj of results) {
const row = { ...obj };
// Case 1: Need to convert booleans to strings to display them in the table
Object.keys(row)
.filter((key) => typeof row[key] === "boolean")
.forEach((key) => {
row[key] = obj[key].toString();
});
// Case 2: Need to stringify objects to display them in the table
Object.keys(row)
.filter((key) => typeof row[key] === "object")
.forEach((key) => {
row[key] = JSON.stringify(obj[key]);
});
// Case 3: If the cell content is too long, put it inside an ExpandableBlock
Object.keys(row)
.filter(
(key) => typeof row[key] === "string" && row[key].length > 500
)
.forEach((key) => {
row[key] = (
<ExpandableBlock title="..." size="small" styleType="borderless">
{row[key]}
</ExpandableBlock>
);
});

rows.push(row);
for (const key of Object.keys(row)) {
if (!columnHeaders.includes(key)) {
Copy link
Member

Choose a reason for hiding this comment

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

well wouldnt they always all not be in columnheaders to begin with?
re-read this block of code here

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Hmm, I'm pretty sure this is right. I wanted columnHeaders to be the superset of all keys in each row, because sometimes each row might have different keys. So every time columnHeaders encounters a new unique key, it should append the new key. columnHeaders is instantiated before we start iterating through each row.

columnHeaders.push(key);
}
}
}
setData(rows);
setHeaders(columnHeaders);
setError("");
} catch (err: any) {
setError(err.message);
} finally {
setIsLoading(false);
}
aruniverse marked this conversation as resolved.
Show resolved Hide resolved
};

const columns = React.useMemo(
() => [
{
Header: "Header name",
columns: headers.map((str) => ({
id: str,
Header: str,
accessor: str,
width: 300,
minWidth: 100,
})),
},
],
[headers]
);

return (
<div style={{ height: "100%", display: "flex", flexFlow: "column" }}>
<div
style={{
display: "flex",
flexDirection: "row",
justifyContent: "center",
alignItems: "baseline",
flex: "0 1 auto",
}}
>
<LabeledTextarea
label=""
message={
isLoading
? "Loading..."
: error || data.length.toString() + " results"
}
value={input}
onChange={(e) => setInput(e.target.value)}
status={error && !isLoading ? "negative" : undefined}
rows={1}
style={{ flexGrow: 1 }}
/>
<Button
as="button"
styleType="high-visibility"
disabled={!input}
onClick={getData}
>
Execute
</Button>
</div>
<Table
columns={columns}
data={data}
isSortable={true}
isResizable={true}
density="extra-condensed"
emptyTableContent="No data."
isLoading={isLoading}
style={{
flex: "1 1 auto",
height: "0em",
width: "100%",
}}
/>
</div>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/

import type {
AbstractWidgetProps,
UiItemsProvider,
} from "@itwin/appui-abstract";
import {
StagePanelLocation,
StagePanelSection,
StageUsage,
} from "@itwin/appui-abstract";
import React from "react";

import EcsqlWidget from "./EcsqlWidget";

export class EcsqlWidgetProvider implements UiItemsProvider {
public readonly id = "EcsqlWidgetProvider";

public provideWidgets(
_stageId: string,
stageUsage: string,
location: StagePanelLocation,
section?: StagePanelSection
): ReadonlyArray<AbstractWidgetProps> {
const widgets: AbstractWidgetProps[] = [];

if (
stageUsage === StageUsage.General &&
location === StagePanelLocation.Bottom &&
section === StagePanelSection.Start
) {
const ecsqlWidget: AbstractWidgetProps = {
id: "EcsqlWidget",
label: "ECSQL",
getWidgetContent() {
return <EcsqlWidget />;
},
};
widgets.push(ecsqlWidget);
}

return widgets;
}
}