Skip to content

Commit

Permalink
Merges adjacent strings in notebooks
Browse files Browse the repository at this point in the history
  • Loading branch information
OAGr committed Nov 13, 2024
1 parent ac326ab commit 07de163
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,9 @@ Here is more text.",
" ### This is an opening section
Here is more text.
",
"- bullet 1",
"- bullet 2",
"- bullet 3",
]
notebook = notNotebook -> Tag.notebook
Expand Down
30 changes: 29 additions & 1 deletion packages/components/src/widgets/ArrayWidget.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { useMemo } from "react";

import { SqStringValue, SqValue } from "@quri/squiggle-lang";
import { DocumentTextIcon } from "@quri/ui";

import { vString } from "../../../squiggle-lang/src/value/VString.js";
import { ValueViewer } from "../components/SquiggleViewer/ValueViewer/index.js";
import { SqValueWithContext } from "../lib/utility.js";
import { widgetRegistry } from "./registry.js";
Expand All @@ -11,6 +13,26 @@ function isNotebook(value: SqValueWithContext) {
return Boolean(value.tags.notebook());
}

// Combines adjacent string values into a single string value. Helps with rendering in notebooks, so that there aren't unecessary breaks between strings.
const compressStringValues = (values: SqValue[]): SqValue[] => {
return values.reduce((acc: SqValue[], curr) => {
// If current and previous are strings, combine them
if (
curr.tag === "String" &&
acc.length > 0 &&
acc[acc.length - 1].tag === "String"
) {
acc[acc.length - 1] = new SqStringValue(
vString(acc[acc.length - 1].value + "\n" + curr.value),
acc[acc.length - 1].context
);
return acc;
}
// Otherwise add the current value as is
return [...acc, curr];
}, []);
};

widgetRegistry.register("Array", {
heading: (value) => `List(${value.value.getValues().length})`,

Expand All @@ -23,9 +45,15 @@ widgetRegistry.register("Array", {
},
Chart: (value) => {
const values = useMemo(() => value.value.getValues(), [value]);

const compressedValues = useMemo(() => {
if (!isNotebook(value)) return values;
return compressStringValues(values);
}, [values, value]);

return (
<div className="mt-0.5 space-y-1 pt-0.5">
{values.map((r, i) => (
{compressedValues.map((r, i) => (
<ValueViewer
parentValue={value}
key={i}
Expand Down

0 comments on commit 07de163

Please sign in to comment.