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

Refactoring sqPath #2986

Merged
merged 22 commits into from
Jan 23, 2024
Merged
Show file tree
Hide file tree
Changes from 19 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 @@ -18,7 +18,7 @@ import {
viewSettingsSchema,
} from "../PlaygroundSettings.js";
import { PlaygroundContext } from "../SquigglePlayground/index.js";
import { pathAsString } from "./utils.js";
import { pathToDisplayString } from "./utils.js";
import {
useHasLocalSettings,
useMergedSettings,
Expand Down Expand Up @@ -74,15 +74,15 @@ const ItemSettingsModal: FC<Props> = ({
<Modal container={getLeftPanelElement()} close={close}>
<Modal.Header>
Chart settings
{path.items.length ? (
{path.edges.length ? (
<>
{" for "}
<span
title="Scroll to item"
className="cursor-pointer"
onClick={resetScroll}
>
{pathAsString(path)}
{pathToDisplayString(path)}
</span>
</>
) : (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { SqValueWithContext } from "../../lib/utility.js";
import { widgetRegistry } from "../../widgets/registry.js";
import { valueToHeadingString } from "../../widgets/utils.js";
import { CollapsedIcon, ExpandedIcon } from "./icons.js";
import { getChildrenValues, pathAsString } from "./utils.js";
import { getChildrenValues } from "./utils.js";
import {
useFocus,
useHasLocalSettings,
Expand Down Expand Up @@ -88,7 +88,7 @@ const LogToConsoleItem: FC<{ value: SqValueWithContext }> = ({ value }) => {
onClick={() => {
// eslint-disable-next-line no-console
console.log({
variable: pathAsString(value.context.path),
variable: value.context.path.uid(),
value: value._value,
context: value.context,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,14 +175,14 @@ export const ValueWithContextViewer: FC<Props> = ({
const name = pathToShortName(path);

// We want to show colons after the keys, for dicts/arrays.
const showColon = header !== "large" && path.items.length > 1;
const showColon = header !== "large" && path.edges.length > 1;

const getHeaderColor = () => {
let color = "text-orange-900";
const parentTag = parentValue?.tag;
if (parentTag === "Array" && !taggedName) {
color = "text-stone-400";
} else if (path.items.length > 1) {
} else if (path.edges.length > 1) {
color = "text-teal-700";
}
return color;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,7 @@ import {
PartialPlaygroundSettings,
PlaygroundSettings,
} from "../PlaygroundSettings.js";
import {
getChildrenValues,
pathAsString,
shouldBeginCollapsed,
} from "./utils.js";
import { getChildrenValues, shouldBeginCollapsed } from "./utils.js";

type ViewerType = "normal" | "tooltip";

Expand Down Expand Up @@ -70,19 +66,19 @@ class ItemStore {
path: SqValuePath,
fn: (localItemState: LocalItemState) => LocalItemState
): void {
const pathString = pathAsString(path);
const pathString = path.uid();
const newSettings = fn(this.state[pathString] || defaultLocalItemState);
this.state[pathString] = newSettings;
}

getState(path: SqValuePath): LocalItemState {
return this.state[pathAsString(path)] || defaultLocalItemState;
return this.state[path.uid()] || defaultLocalItemState;
}

getStateOrInitialize(value: SqValueWithContext): LocalItemState {
const path = value.context.path;
const pathString = pathAsString(path);
const existingState = this.state[pathString];
const pathString = path.uid();
const existingState = this.state[path.uid()];
if (existingState) {
return existingState;
}
Expand All @@ -96,7 +92,7 @@ class ItemStore {
if (!child.context) {
continue; // shouldn't happen
}
const childPathString = pathAsString(child.context.path);
const childPathString = child.context.path.uid();
if (this.state[childPathString]) {
continue; // shouldn't happen, if parent state is not initialized, child state won't be initialized either
}
Expand Down Expand Up @@ -126,15 +122,15 @@ class ItemStore {
}

forceUpdate(path: SqValuePath) {
this.handles[pathAsString(path)]?.forceUpdate();
this.handles[path.uid()]?.forceUpdate();
}

registerItemHandle(path: SqValuePath, handle: ItemHandle) {
this.handles[pathAsString(path)] = handle;
this.handles[path.uid()] = handle;
}

unregisterItemHandle(path: SqValuePath) {
delete this.handles[pathAsString(path)];
delete this.handles[path.uid()];
}

updateCalculatorState(path: SqValuePath, calculator: CalculatorState) {
Expand All @@ -152,7 +148,7 @@ class ItemStore {
}

scrollToPath(path: SqValuePath) {
this.handles[pathAsString(path)]?.element.scrollIntoView({
this.handles[path.uid()]?.element.scrollIntoView({
behavior: "smooth",
});
}
Expand Down Expand Up @@ -274,7 +270,7 @@ export function useHasLocalSettings(path: SqValuePath) {
export function useFocus() {
const { focused, setFocused } = useViewerContext();
return (path: SqValuePath) => {
if (focused && pathAsString(focused) === pathAsString(path)) {
if (focused && focused.isEqual(path)) {
return; // nothing to do
}
if (path.isRoot()) {
Expand All @@ -292,7 +288,7 @@ export function useUnfocus() {

export function useIsFocused(path: SqValuePath) {
const { focused } = useViewerContext();
return focused && pathAsString(focused) === pathAsString(path);
return focused && focused.isEqual(path);
}

export function useMergedSettings(path: SqValuePath) {
Expand Down
14 changes: 7 additions & 7 deletions packages/components/src/components/SquiggleViewer/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { ChevronRightIcon } from "@quri/ui";
import { MessageAlert } from "../Alert.js";
import { CodeEditorHandle } from "../CodeEditor/index.js";
import { PartialPlaygroundSettings } from "../PlaygroundSettings.js";
import { pathIsEqual, pathItemFormat, useGetSubvalueByPath } from "./utils.js";
import { useGetSubvalueByPath } from "./utils.js";
import { ValueViewer } from "./ValueViewer.js";
import {
SquiggleViewerHandle,
Expand Down Expand Up @@ -38,31 +38,31 @@ const FocusedNavigation: FC<{
const unfocus = useUnfocus();
const focus = useFocus();

const isFocusedOnRootPath = rootPath && pathIsEqual(focusedPath, rootPath);
const isFocusedOnRootPath = rootPath && rootPath.isEqual(focusedPath);

if (isFocusedOnRootPath) {
return null;
}

// If we're focused on the root path override, we need to adjust the focused path accordingly when presenting the navigation, so that it begins with the root path intead. This is a bit confusing.
const rootPathFocusedAdjustment = rootPath?.items.length
? rootPath.items.length - 1
const rootPathFocusedAdjustment = rootPath?.edges.length
? rootPath.edges.length - 1
: 0;

return (
<div className="flex items-center">
{!rootPath?.items.length && (
{!rootPath?.edges.length && (
<FocusedNavigationItem onClick={unfocus} text="Home" />
)}

{focusedPath
.itemsAsValuePaths({ includeRoot: false })
.allPrefixPaths({ includeRoot: false })
.slice(rootPathFocusedAdjustment, -1)
.map((path, i) => (
<FocusedNavigationItem
key={i}
onClick={() => focus(path)}
text={pathItemFormat(path.items[i + rootPathFocusedAdjustment])}
text={path.edges[i + rootPathFocusedAdjustment].toDisplayString()}
/>
))}
</div>
Expand Down
119 changes: 19 additions & 100 deletions packages/components/src/components/SquiggleViewer/utils.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,9 @@
import isEqual from "lodash/isEqual.js";

import { PathItem, SqDict, SqValue, SqValuePath } from "@quri/squiggle-lang";
import { SqDict, SqValue, SqValuePath } from "@quri/squiggle-lang";

import { SHORT_STRING_LENGTH } from "../../lib/constants.js";
import { SqValueWithContext } from "../../lib/utility.js";
import { useViewerContext } from "./ViewerProvider.js";

export const pathItemFormat = (item: PathItem): string => {
if (item.type === "cellAddress") {
return `Cell (${item.value.row},${item.value.column})`;
} else if (item.type === "calculator") {
return `calculator`;
} else {
return String(item.value);
}
};

function isTopLevel(path: SqValuePath): boolean {
return path.items.length === 0;
}

function topLevelName(path: SqValuePath): string {
return {
result: "Result",
Expand All @@ -29,25 +13,16 @@ function topLevelName(path: SqValuePath): string {
}[path.root];
}

export function pathAsString(path: SqValuePath) {
if (isTopLevel(path)) {
return topLevelName(path);
} else {
return [topLevelName(path), ...path.items.map(pathItemFormat)].join(".");
}
}

export function pathIsEqual(path1: SqValuePath, path2: SqValuePath) {
return pathAsString(path1) === pathAsString(path2);
export function pathToDisplayString(path: SqValuePath) {
return [
Copy link
Collaborator

Choose a reason for hiding this comment

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

Could be path.toDisplayString()
(or path.toString(), see my other comment)

Copy link
Contributor Author

@OAGr OAGr Jan 20, 2024

Choose a reason for hiding this comment

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

The annoying thing here is that in utils, we use different names for the root elements than in squiggle-lang. I could do a regex to replace, but that seemed hacky.

Maybe we could rename them in squiggle-lang to match Squiggle-viewer? "Bindings" -> "Variables", capitalize all of them?

Copy link
Collaborator

Choose a reason for hiding this comment

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

Hmm. Yeah, I missed that this depends on topLevelName.

The problem with renaming is that roots also match keys in SqOutput dicts, and it's nice even if we don't rely on it anywhere.

In export type ValuePathRoot = "result" | "bindings" | "imports" | "exports", I thought about suggesting export type ValuePathRoot = keyof SqOutput, but they might diverge at some point (output could include other, non-value things), so I'm not sure if that's a good idea.

Using public names in SqOutput is too much (and problematic re: versioned-components), so... I dunno. Maybe just leave it here for now.

topLevelName(path),
...path.edges.map((p) => p.toDisplayString()),
].join(".");
}

export function pathToShortName(path: SqValuePath): string {
if (isTopLevel(path)) {
return topLevelName(path);
} else {
const lastPathItem = path.items[path.items.length - 1];
return pathItemFormat(lastPathItem);
}
//topLevelName is used if its the root path
return path.lastItem()?.toDisplayString() || topLevelName(path);
}

export function getChildrenValues(value: SqValue): SqValue[] {
Expand All @@ -66,73 +41,17 @@ export function getChildrenValues(value: SqValue): SqValue[] {
export function useGetSubvalueByPath() {
const { itemStore } = useViewerContext();

return (value: SqValue, path: SqValuePath): SqValue | undefined => {
const { context } = value;
if (!context) {
return;
}
if (context.path.root !== path.root) {
return;
}
if (context.path.items.length > path.items.length) {
return;
}

for (let i = 0; i < path.items.length; i++) {
if (i < context.path.items.length) {
// check that `path` is a subpath of `context.path`
if (!isEqual(context.path.items[i], path.items[i])) {
return;
}
continue;
return (topValue: SqValue, subValuePath: SqValuePath): SqValue | undefined =>
topValue.getSubvalueByPath(
subValuePath,
(calculatorSubPath: SqValuePath) => {
// The previous path item is the one that is the parent of the calculator result.
// This is the one that we use in the ViewerContext to store information about the calculator.
const calculatorState = itemStore.getCalculator(calculatorSubPath);
const result = calculatorState?.calculatorResult;
return result?.ok ? result.value : undefined;
}

const pathItem = path.items[i];
{
let nextValue: SqValue | undefined;
if (pathItem.type === "number" && value.tag === "Array") {
nextValue = value.value.getValues()[pathItem.value];
} else if (pathItem.type === "string" && value.tag === "Dict") {
nextValue = value.value.get(pathItem.value);
} else if (
pathItem.type === "cellAddress" &&
value.tag === "TableChart"
) {
// Maybe it would be better to get the environment in a different way.
const environment = context.project.getEnvironment();
const item = value.value.item(
pathItem.value.row,
pathItem.value.column,
environment
);
if (item.ok) {
nextValue = item.value;
} else {
return;
}
} else if (pathItem.type === "calculator") {
// The previous path item is the one that is the parent of the calculator result.
// This is the one that we use in the ViewerContext to store information about the calculator.
const calculatorPath = new SqValuePath({
root: path.root,
items: path.items.slice(0, i),
});
const calculatorState = itemStore.getCalculator(calculatorPath);
const result = calculatorState?.calculatorResult;
if (!result?.ok) {
return;
}
nextValue = result.value;
}

if (!nextValue) {
return;
}
value = nextValue;
}
}
return value;
};
);
}

export function getValueComment(value: SqValueWithContext): string | undefined {
Expand Down Expand Up @@ -176,7 +95,7 @@ export const shouldBeginCollapsed = (
function isHidden(value: SqValue): boolean {
const isHidden = value.tags.hidden();
const path = value.context?.path;
return Boolean(isHidden === true && path && path.items.length === 1);
return Boolean(isHidden === true && path && path.edges.length === 1);
}

export function nonHiddenDictEntries(value: SqDict): [string, SqValue][] {
Expand Down
4 changes: 2 additions & 2 deletions packages/components/src/stories/SquiggleChart.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Meta, StoryObj } from "@storybook/react";

import { SqValuePath } from "@quri/squiggle-lang";
import { SqValuePath, SqValuePathEdge } from "@quri/squiggle-lang";

import { SquiggleChart } from "../components/SquiggleChart.js";

Expand Down Expand Up @@ -50,7 +50,7 @@ export const RootPathOverride: Story = {
code: "{foo: 35 to 50, bar: [1,2,3]}",
rootPathOverride: new SqValuePath({
root: "result",
items: [{ type: "string", value: "bar" }],
edges: [SqValuePathEdge.fromKey("bar")],
}),
},
};
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Meta, StoryObj } from "@storybook/react";

import { SqValuePath } from "@quri/squiggle-lang";
import { SqValuePath, SqValuePathEdge } from "@quri/squiggle-lang";

import { SquiggleChart } from "../../components/SquiggleChart.js";

Expand Down Expand Up @@ -43,10 +43,7 @@ export const WithPathOverride: Story = {
`,
rootPathOverride: new SqValuePath({
root: "bindings",
items: [
{ type: "string", value: "foo" },
{ type: "string", value: "bar" },
],
edges: [SqValuePathEdge.fromKey("foo"), SqValuePathEdge.fromKey("bar")],
}),
},
};
Loading
Loading