Skip to content

AI-native design editor. Open-source Figma alternative.

refactor: use es-toolkit for set, clamp, sum, and object helpers (#1086)

Danila Poyarkov34c3bc5e103f
diff --git a/packages/cli/src/commands/analyze/clusters.ts b/packages/cli/src/commands/analyze/clusters.ts
index aa8cf5559..80ace835d 100644
--- a/packages/cli/src/commands/analyze/clusters.ts
+++ b/packages/cli/src/commands/analyze/clusters.ts
@@ -1,4 +1,5 @@
import { defineCommand } from 'citty'
+import { mean, sumBy } from 'es-toolkit'
import type { AnalyzeClustersResult } from '@open-pencil/core/rpc'
import { calcClusterConfidence } from '@open-pencil/core/tools'
@@ -72,8 +73,8 @@ export default defineCommand({
const heights = c.nodes.map((n) => n.height)
const wRange = Math.max(...widths) - Math.min(...widths)
const hRange = Math.max(...heights) - Math.min(...heights)
- const avgW = Math.round(widths.reduce((a, b) => a + b, 0) / widths.length)
- const avgH = Math.round(heights.reduce((a, b) => a + b, 0) / heights.length)
+ const avgW = Math.round(mean(widths))
+ const avgH = Math.round(mean(heights))
const sizeStr =
wRange <= 4 && hRange <= 4
@@ -95,7 +96,7 @@ export default defineCommand({
console.log(fmtList(items, { numbered: true }))
- const clusteredNodes = data.clusters.reduce((sum, c) => sum + c.nodes.length, 0)
+ const clusteredNodes = sumBy(data.clusters, (c) => c.nodes.length)
console.log('')
console.log(
fmtSummary({
diff --git a/packages/cli/src/commands/export/storybook/index.ts b/packages/cli/src/commands/export/storybook/index.ts
index 1e8b6b6c5..fb8a2e644 100644
--- a/packages/cli/src/commands/export/storybook/index.ts
+++ b/packages/cli/src/commands/export/storybook/index.ts
@@ -12,6 +12,8 @@ import {
sep
} from 'node:path'
+import { uniq } from 'es-toolkit'
+
import { BUILTIN_IO_FORMATS, IORegistry, vectorElement } from '@open-pencil/core/io'
import {
exportStorybook,
@@ -263,7 +265,7 @@ async function resolveDocuments(args: StorybookArgs): Promise<string[]> {
if (matches.length === 0) throw new Error(`No documents match ${pattern}.`)
documents.push(...matches.sort())
}
- return [...new Set(documents)]
+ return uniq(documents)
}
function outputFor(args: StorybookArgs, file: string): string {
diff --git a/packages/cli/src/format.ts b/packages/cli/src/format.ts
index fbab2732a..2e2690b09 100644
--- a/packages/cli/src/format.ts
+++ b/packages/cli/src/format.ts
@@ -17,6 +17,7 @@ import {
summary as fmtSummary
} from 'agentfmt'
import type { TreeNode, ListItem, NodeData } from 'agentfmt'
+import { isEmptyObject } from 'es-toolkit'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
@@ -209,7 +210,7 @@ export function nodeToListItem(node: SceneNode): ListItem {
const details = nodeDetails(node)
return {
header: entity(formatType(node.type), node.name, node.id),
- details: Object.keys(details).length > 0 ? details : undefined
+ details: isEmptyObject(details) ? undefined : details
}
}
diff --git a/packages/core/src/editor/alignment.ts b/packages/core/src/editor/alignment.ts
index b55013f35..d4a807802 100644
--- a/packages/core/src/editor/alignment.ts
+++ b/packages/core/src/editor/alignment.ts
@@ -1,3 +1,5 @@
+import { sumBy } from 'es-toolkit'
+
import type { SceneNode } from '@open-pencil/scene-graph'
import { getAbsolutePositionFull, getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
import { computeAbsoluteBounds } from '@open-pencil/scene-graph/geometry'
@@ -101,7 +103,7 @@ function distributeMultipleNodes(
const start = bounds.get(first.id)?.[coordinate] ?? 0
const end = (bounds.get(last.id)?.[coordinate] ?? 0) + (bounds.get(last.id)?.[size] ?? 0)
- const totalSize = sorted.reduce((sum, node) => sum + (bounds.get(node.id)?.[size] ?? 0), 0)
+ const totalSize = sumBy(sorted, (node) => bounds.get(node.id)?.[size] ?? 0)
const gap = (end - start - totalSize) / (sorted.length - 1)
let cursor = start
diff --git a/packages/core/src/editor/clipboard/assets.ts b/packages/core/src/editor/clipboard/assets.ts
index 5193cc21b..652594377 100644
--- a/packages/core/src/editor/clipboard/assets.ts
+++ b/packages/core/src/editor/clipboard/assets.ts
@@ -1,3 +1,5 @@
+import { sumBy } from 'es-toolkit'
+
import type { Fill } from '@open-pencil/scene-graph'
import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
import Matrix from '@open-pencil/scene-graph/matrix'
@@ -140,8 +142,7 @@ export function createClipboardAssetActions(
const previousSelection = new Set(ctx.state.selectedIds)
const parentId = resolvePasteTarget(ctx)
const center = parentLocalPoint(parentId, cx, cy)
- const totalWidth =
- prepared.reduce((total, asset) => total + asset.width, 0) + ASSET_GAP * (prepared.length - 1)
+ const totalWidth = sumBy(prepared, (asset) => asset.width) + ASSET_GAP * (prepared.length - 1)
const maxHeight = Math.max(...prepared.map((asset) => asset.height))
let x = center.x - totalWidth / 2
const y = center.y - maxHeight / 2
diff --git a/packages/core/src/editor/text/path-edit.ts b/packages/core/src/editor/text/path-edit.ts
index 81bc7cff1..4450a5a45 100644
--- a/packages/core/src/editor/text/path-edit.ts
+++ b/packages/core/src/editor/text/path-edit.ts
@@ -1,3 +1,5 @@
+import { mean } from 'es-toolkit'
+
import { encodePathCommandsBlob } from '@open-pencil/fig/node-change'
import type { SceneNode } from '@open-pencil/scene-graph'
@@ -48,7 +50,7 @@ export function pathTextEditChanges(
const layout = calibratePathTextLayout(node.derivedTextGlyphs, data, node.textPathBox)
if (!layout) return {}
- const offset = layout.offsets.reduce((sum, o) => sum + o, 0) / layout.offsets.length
+ const offset = mean(layout.offsets)
const glyphs = layoutPathTextFromAdvances(
data,
diff --git a/packages/core/src/io/formats/design-tokens/apply.ts b/packages/core/src/io/formats/design-tokens/apply.ts
index 07b06ffe7..040255e0b 100644
--- a/packages/core/src/io/formats/design-tokens/apply.ts
+++ b/packages/core/src/io/formats/design-tokens/apply.ts
@@ -155,7 +155,7 @@ function applyVariables(target: TokenImportTarget, plan: TokenImportPlan) {
hiddenFromPublishing: variable.hiddenFromPublishing ?? false,
description: variable.description ?? made.description
}
- if (Object.keys(expressions).length > 0) fields.expressions = expressions
+ if (!isEmptyObject(expressions)) fields.expressions = expressions
target.setTokenFields(made.id, fields)
})
})
diff --git a/packages/core/src/io/formats/pptx/style.ts b/packages/core/src/io/formats/pptx/style.ts
index 3515286f0..2d6f457d9 100644
--- a/packages/core/src/io/formats/pptx/style.ts
+++ b/packages/core/src/io/formats/pptx/style.ts
@@ -1,3 +1,4 @@
+import { clamp } from 'es-toolkit'
import type PptxGenJS from 'pptxgenjs'
import type { Color, Fill, SceneNode, Stroke } from '@open-pencil/scene-graph'
@@ -51,7 +52,7 @@ export function mapShadow(node: SceneNode, opacity: number): PptxGenJS.ShadowPro
type: e.type === 'INNER_SHADOW' ? 'inner' : 'outer',
color: hex(e.color),
opacity: clamp01(e.color.a * opacity),
- blur: Math.min(Math.max(e.radius, 0), 100),
+ blur: clamp(e.radius, 0, 100),
offset: Math.min(Math.hypot(e.offset.x, e.offset.y), 200),
angle: angleRaw < 0 ? angleRaw + 360 : angleRaw
}
@@ -84,15 +85,15 @@ export function hex(color: Color): string {
}
export function transparency(alpha: number): number {
- return Math.min(Math.max(Math.round((1 - clamp01(alpha)) * 100), 0), 100)
+ return clamp(Math.round((1 - clamp01(alpha)) * 100), 0, 100)
}
export function clamp01(v: number): number {
- return Math.min(Math.max(v, 0), 1)
+ return clamp(v, 0, 1)
}
export function clampRot(deg: number): number {
- return Math.min(Math.max(deg, -360), 360)
+ return clamp(deg, -360, 360)
}
export function round2(v: number): number {
diff --git a/packages/core/src/lint/fixes.ts b/packages/core/src/lint/fixes.ts
index 45297ad08..29e6c9eae 100644
--- a/packages/core/src/lint/fixes.ts
+++ b/packages/core/src/lint/fixes.ts
@@ -1,3 +1,5 @@
+import { isEmptyObject } from 'es-toolkit'
+
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { colorToHex } from '@open-pencil/scene-graph/color'
@@ -104,7 +106,7 @@ export function applyLintFixes(target: LintFixTarget, requests: readonly LintFix
const changes = Object.fromEntries(
Object.entries(fix.changes).filter(([key, value]) => Reflect.get(node, key) !== value)
)
- if (Object.keys(changes).length === 0) continue
+ if (isEmptyObject(changes)) continue
updates.set(nodeId, { ...updates.get(nodeId), ...changes })
break
}
diff --git a/packages/core/src/rpc/read-commands.ts b/packages/core/src/rpc/read-commands.ts
index 9b20f244d..29195a5b9 100644
--- a/packages/core/src/rpc/read-commands.ts
+++ b/packages/core/src/rpc/read-commands.ts
@@ -1,3 +1,5 @@
+import { sumBy } from 'es-toolkit'
+
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import type { DocumentFontStatus } from '#core/text/font/status'
@@ -28,7 +30,7 @@ function countDescendants(graph: SceneGraph, rootId: string): number {
function countNodes(graph: SceneGraph, pageId: string): number {
const page = graph.getNode(pageId)
- return page?.childIds.reduce((count, id) => count + countDescendants(graph, id), 0) ?? 0
+ return page ? sumBy(page.childIds, (id) => countDescendants(graph, id)) : 0
}
function nodeFrame(node: SceneNode) {
diff --git a/packages/core/src/text/web-fonts.ts b/packages/core/src/text/web-fonts.ts
index b3c49e379..8347c1f96 100644
--- a/packages/core/src/text/web-fonts.ts
+++ b/packages/core/src/text/web-fonts.ts
@@ -1,3 +1,4 @@
+import { uniq } from 'es-toolkit'
import type { FontFaceData, RemoteFontSource, ResolveFontResult } from 'unifont'
import { IS_BROWSER } from '#core/constants'
@@ -319,9 +320,7 @@ export class WebFontResolver {
try {
const unifont = await this.unifont(provider)
const listedFamilies = await this.withFetchProxy(() => unifont.listFonts())
- const families = listedFamilies
- ? [...new Set(listedFamilies)].sort((a, b) => a.localeCompare(b))
- : []
+ const families = listedFamilies ? uniq(listedFamilies).sort((a, b) => a.localeCompare(b)) : []
this.familiesCache.set(provider, families)
return families
} catch {
diff --git a/packages/core/src/tools/ai-adapter.ts b/packages/core/src/tools/ai-adapter.ts
index 024cd515f..8e50dde24 100644
--- a/packages/core/src/tools/ai-adapter.ts
+++ b/packages/core/src/tools/ai-adapter.ts
@@ -7,6 +7,7 @@
// eslint-disable-next-line open-pencil/no-mixed-case-acronym-identifiers -- Upstream export spelling.
import { toStandardJsonSchema as toStandardJSONSchema } from '@valibot/to-json-schema'
import type { JSONValue, ToolResultPart, ToolSet, tool as createTool } from 'ai'
+import { isEmptyObject } from 'es-toolkit'
import type { FigmaAPI } from '#core/figma-api'
@@ -232,7 +233,7 @@ export function toolsToAI(
mediaType: mimeType,
data: { type: 'data' as const, data: base64 }
}
- return Object.keys(metadata).length > 0
+ return !isEmptyObject(metadata)
? {
type: 'content',
value: [{ type: 'text', text: JSON.stringify(metadata) }, image]
diff --git a/packages/core/src/tools/describe/issues.ts b/packages/core/src/tools/describe/issues.ts
index a37c6ef4e..9c47d8d1b 100644
--- a/packages/core/src/tools/describe/issues.ts
+++ b/packages/core/src/tools/describe/issues.ts
@@ -1,3 +1,5 @@
+import { uniq } from 'es-toolkit'
+
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { colorDistance, colorToHex } from '@open-pencil/scene-graph/color'
@@ -382,7 +384,7 @@ function detectSpacingIssues(
const gaps = flexChildren.map((c) => c.itemSpacing)
if (new Set(paddings).size > 2) {
issues.push({
- message: `Inconsistent padding across siblings in "${node.name}" (${[...new Set(paddings)].join(', ')})`,
+ message: `Inconsistent padding across siblings in "${node.name}" (${uniq(paddings).join(', ')})`,
suggestion: 'Use same padding for similar containers'
})
}
diff --git a/packages/scene-graph/src/behaviours/model.ts b/packages/scene-graph/src/behaviours/model.ts
index 560cde38f..725d95ae4 100644
--- a/packages/scene-graph/src/behaviours/model.ts
+++ b/packages/scene-graph/src/behaviours/model.ts
@@ -1,3 +1,5 @@
+import { mapValues } from 'es-toolkit'
+
import type { SceneGraph } from '../index'
import { readPluginData, withPluginData } from '../plugin-data/field'
import { OPEN_PENCIL_PLUGIN_DATA } from '../plugin-data/fields'
@@ -175,8 +177,6 @@ export function renameBehaviourProperties(
behaviour: Behaviour,
rename: (propertyId: string) => string
): Behaviour {
- const mapValues = <T>(record: Record<string, T>, change: (value: T) => T) =>
- Object.fromEntries(Object.entries(record).map(([key, value]) => [key, change(value)]))
return {
...behaviour,
booleans: mapValues(behaviour.booleans, (binding) => ({
diff --git a/src/app/ai/chat/tool-calls/display.ts b/src/app/ai/chat/tool-calls/display.ts
index fd37ff57f..0198082d0 100644
--- a/src/app/ai/chat/tool-calls/display.ts
+++ b/src/app/ai/chat/tool-calls/display.ts
@@ -1,5 +1,6 @@
import { getToolName, isToolUIPart } from 'ai'
import type { UIDataTypes, UIMessagePart, UITools } from 'ai'
+import { isEmptyObject } from 'es-toolkit'
import { isValid } from 'js-base64'
export type ChatMessagePart = UIMessagePart<UIDataTypes, UITools>
@@ -123,7 +124,7 @@ export function toolSource(
/** Whether a call has input worth showing: source, or at least one argument. */
export function toolHasInput(part: ToolCallPart): boolean {
- return toolSource(part) !== null || (isRecord(part.input) && Object.keys(part.input).length > 0)
+ return toolSource(part) !== null || (isRecord(part.input) && !isEmptyObject(part.input))
}
export type MessagePartGroup =
diff --git a/src/app/ai/models/settings/onboarding/plan.ts b/src/app/ai/models/settings/onboarding/plan.ts
index 411a6f63a..dc6f25dc9 100644
--- a/src/app/ai/models/settings/onboarding/plan.ts
+++ b/src/app/ai/models/settings/onboarding/plan.ts
@@ -1,3 +1,5 @@
+import { uniq } from 'es-toolkit'
+
import { AI_PROVIDERS, type AIProviderID, type ModelOption } from '@open-pencil/core/constants'
import { modelProviderName } from '@/app/ai/models/provider-name'
@@ -286,7 +288,7 @@ export function planConnections(roles: Omit<OnboardingPlan, 'connections'>): Onb
.filter((model) => !model.profileId)
.map((model) => model.providerID)
.filter(isOnboardingAccess)
- return [...new Set(providers)]
+ return uniq(providers)
}
/** Whether every role the person asked about has a model. */
diff --git a/src/app/ai/models/settings/onboarding/use.ts b/src/app/ai/models/settings/onboarding/use.ts
index 4eb7f8beb..931ed1317 100644
--- a/src/app/ai/models/settings/onboarding/use.ts
+++ b/src/app/ai/models/settings/onboarding/use.ts
@@ -1,3 +1,4 @@
+import { uniq } from 'es-toolkit'
import { computed, reactive, ref, watch } from 'vue'
import { IS_TAURI } from '@open-pencil/core/constants'
@@ -39,7 +40,7 @@ function initialAnswers(): OnboardingAnswers {
.filter((providerID) => existingOnboardingConnection(providerID))
return {
goals: aiModelSettings.value.assignments.vision === null ? ['design'] : ['design', 'vision'],
- access: [...new Set(access)],
+ access: uniq(access),
spending: 'existing'
}
}
diff --git a/src/app/ai/models/store.ts b/src/app/ai/models/store.ts
index 72529b2a8..3aa629f70 100644
--- a/src/app/ai/models/store.ts
+++ b/src/app/ai/models/store.ts
@@ -143,7 +143,7 @@ function hydrateCuratedCapabilities(
const connection = connections.find((candidate) => candidate.id === profile.connectionId)
if (!connection) continue
const capabilities = curatedModelCapabilities(connection.providerID, profile.modelID)
- if (capabilities) profile.capabilities = [...new Set(capabilities)]
+ if (capabilities) profile.capabilities = uniq(capabilities)
}
}
@@ -406,7 +406,7 @@ export function saveModelProfileDraft(draft: AIModelProfileDraft): AIModelProfil
thinkingLevel: draft.thinkingLevel,
harnessPermissionMode:
draft.providerID === 'harness:pi' ? draft.harnessPermissionMode : undefined,
- capabilities: [...new Set(draft.capabilities)]
+ capabilities: uniq(draft.capabilities)
}
const index = aiModelSettings.value.models.findIndex((model) => model.id === profile.id)
if (index === -1) aiModelSettings.value.models.push(profile)
diff --git a/src/app/automation/bridge/vite-plugin.ts b/src/app/automation/bridge/vite-plugin.ts
index 8319aa066..a7ac0bd56 100644
--- a/src/app/automation/bridge/vite-plugin.ts
+++ b/src/app/automation/bridge/vite-plugin.ts
@@ -5,6 +5,7 @@ import type { IncomingMessage } from 'node:http'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
+import { delay } from 'es-toolkit'
import type { Plugin } from 'vite'
import { serializeDisabledTools } from '@open-pencil/mcp/tools'
@@ -121,9 +122,7 @@ export async function waitForAutomationHealth(
}
options.assertRunning?.()
if (healthy) return
- await new Promise<void>((resolve) => {
- setTimeout(resolve, CHILD_HEALTH_DELAY_MS)
- })
+ await delay(CHILD_HEALTH_DELAY_MS)
}
throw new Error(`MCP server did not become healthy at ${healthURL}`)
}
diff --git a/src/app/code/sandbox/convert.ts b/src/app/code/sandbox/convert.ts
index d37877df1..492ac0284 100644
--- a/src/app/code/sandbox/convert.ts
+++ b/src/app/code/sandbox/convert.ts
@@ -1,3 +1,5 @@
+import { mapValues } from 'es-toolkit'
+
import {
angularGradient,
backgroundBlur,
@@ -87,8 +89,7 @@ function convertValue(value: unknown): unknown {
return helper(...value.args.map(convertValue))
}
if (Array.isArray(value)) return value.map(convertValue)
- if (isRecord(value))
- return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, convertValue(v)]))
+ if (isRecord(value)) return mapValues(value, (entry) => convertValue(entry))
return value
}
diff --git a/src/app/collab/shared-tree/migration.ts b/src/app/collab/shared-tree/migration.ts
index 8a274edff..36d9e440f 100644
--- a/src/app/collab/shared-tree/migration.ts
+++ b/src/app/collab/shared-tree/migration.ts
@@ -1,3 +1,4 @@
+import { orderBy, uniq } from 'es-toolkit'
import * as v from 'valibot'
import * as Y from 'yjs'
@@ -55,7 +56,7 @@ export function migrateLegacyLayers(
meta: YMeta,
layerIds: Iterable<string>
): string[] {
- const legacy = [...new Set(layerIds)].filter((id) => {
+ const legacy = uniq(Array.from(layerIds)).filter((id) => {
const ynode = ynodes.get(id)
return ynode !== undefined && isLegacyLayer(ynode)
})
@@ -89,7 +90,7 @@ export function migrateLegacyLayers(
const listed = legacyChildIdsOf(ynodes.get(parentId)).filter(
(id) => ynodes.get(id) && (migrating.has(id) || legacyParentOrEntry(ynodes, id, parentId))
)
- const order = [...new Set(listed)]
+ const order = uniq(listed)
const unlisted = [...migrating].filter((id) => !order.includes(id)).sort()
order.push(...unlisted)
const keys = siblingOrderKeys(
@@ -147,11 +148,11 @@ function legacyPageOf(ynodes: YNodes, id: string): string | undefined {
*/
function claimLegacyRoot(ynodes: YNodes, meta: YMeta, roots: ReadonlySet<string>): void {
if (readRoot(meta) !== undefined) return
- // Sorting is stable, so roots with as many children stay in id order.
- const ranked = [...roots]
- .sort()
- .map((id) => ({ id, children: legacyChildIdsOf(ynodes.get(id)).length }))
- .sort((a, b) => b.children - a.children)
+ const ranked = orderBy(
+ [...roots].map((id) => ({ id, children: legacyChildIdsOf(ynodes.get(id)).length })),
+ ['children', 'id'],
+ ['desc', 'asc']
+ )
const root = ranked.at(0)
if (root) claimRoot(meta, root.id)
}
diff --git a/src/app/diagnostics/settings.ts b/src/app/diagnostics/settings.ts
index 1d9a07547..afe43f55f 100644
--- a/src/app/diagnostics/settings.ts
+++ b/src/app/diagnostics/settings.ts
@@ -1,4 +1,5 @@
import { useLocalStorage } from '@vueuse/core'
+import { clamp } from 'es-toolkit'
import { computed, ref } from 'vue'
/**
@@ -24,7 +25,7 @@ export function resolveDiagnosticsRetention(value: unknown): DiagnosticsRetentio
return DIAGNOSTICS_RETENTION_DEFAULT
}
const whole = Math.round(parsed)
- return Math.min(Math.max(whole, DIAGNOSTICS_RETENTION_MIN), DIAGNOSTICS_RETENTION_MAX)
+ return clamp(whole, DIAGNOSTICS_RETENTION_MIN, DIAGNOSTICS_RETENTION_MAX)
}
const diagnosticsEnabled = useLocalStorage('open-pencil:diagnostics-enabled', true)
diff --git a/src/app/editor/clipboard/figma-images.ts b/src/app/editor/clipboard/figma-images.ts
index 17337a7b7..d6f2a38ee 100644
--- a/src/app/editor/clipboard/figma-images.ts
+++ b/src/app/editor/clipboard/figma-images.ts
@@ -1,3 +1,4 @@
+import { uniq } from 'es-toolkit'
import * as v from 'valibot'
import { computeImageHash } from '@open-pencil/scene-graph/images'
@@ -37,7 +38,7 @@ export async function resolveFigmaClipboardImages(
fetcher: ClipboardImageFetch = tauriFetch,
timeoutMs = IMAGE_FETCH_TIMEOUT_MS
): Promise<ReadonlyMap<string, Uint8Array>> {
- const uniqueHashes = [...new Set(hashes)]
+ const uniqueHashes = uniq(hashes)
if (uniqueHashes.length === 0) return new Map()
const batchResponse = await fetcher(
diff --git a/src/app/editor/fonts/cache.ts b/src/app/editor/fonts/cache.ts
index 9813cf1be..85b2e1ccc 100644
--- a/src/app/editor/fonts/cache.ts
+++ b/src/app/editor/fonts/cache.ts
@@ -1,3 +1,4 @@
+import { sumBy } from 'es-toolkit'
import * as v from 'valibot'
import type { DownloadedFontCache } from '@open-pencil/core/text'
@@ -84,7 +85,7 @@ export async function downloadedFontCacheSummary(): Promise<DownloadedFontCacheS
)
return {
count: entries.length,
- byteLength: entries.reduce((sum, entry) => sum + entry.byteLength, 0),
+ byteLength: sumBy(entries, (entry) => entry.byteLength),
updatedAt: entries.length > 0 ? Math.max(...entries.map((entry) => entry.updatedAt)) : null
}
}
diff --git a/src/app/editor/panes/split-tree.ts b/src/app/editor/panes/split-tree.ts
index 09f1f3320..fef26a9a6 100644
--- a/src/app/editor/panes/split-tree.ts
+++ b/src/app/editor/panes/split-tree.ts
@@ -1,3 +1,4 @@
+import { sum, sumBy } from 'es-toolkit'
export const MAX_VISIBLE_CANVAS_PANES = 4
export type SplitDirection = 'horizontal' | 'vertical'
@@ -13,9 +14,7 @@ export type CanvasSplitNode =
}
export function paneCount(node: CanvasSplitNode): number {
- return node.type === 'pane'
- ? 1
- : node.children.reduce((count, child) => count + paneCount(child), 0)
+ return node.type === 'pane' ? 1 : sumBy(node.children, paneCount)
}
export function leafPaneIds(node: CanvasSplitNode): string[] {
@@ -37,7 +36,7 @@ export function normalizeSplitSizes(length: number, sizes?: number[]): number[]
) {
return Array.from({ length }, () => 100 / length)
}
- const total = sizes.reduce((sum, size) => sum + size, 0)
+ const total = sum(sizes)
return sizes.map((size) => (size / total) * 100)
}
diff --git a/src/app/integrations/storage/s3/adapter.ts b/src/app/integrations/storage/s3/adapter.ts
index 007049b44..c352c4ea4 100644
--- a/src/app/integrations/storage/s3/adapter.ts
+++ b/src/app/integrations/storage/s3/adapter.ts
@@ -1,3 +1,4 @@
+import { sumBy } from 'es-toolkit'
import * as v from 'valibot'
import { extractFigThumbnailFromReader } from '@open-pencil/fig'
@@ -258,7 +259,7 @@ export function createS3StorageAdapter(runtime: StorageProviderRuntime): S3Stora
const config = await resolveConfig(runtime)
const objects = await listObjects(config, `${STORAGE_NAMESPACE}/`)
return {
- bytesUsed: objects.reduce((total, object) => total + (object.size ?? 0), 0),
+ bytesUsed: sumBy(objects, (object) => object.size ?? 0),
objectCount: objects.length,
documentCount: objects.filter((object) => documentIdFromFigKey(object.key)).length
}
diff --git a/src/app/settings/automation.ts b/src/app/settings/automation.ts
index e9da39476..384656d38 100644
--- a/src/app/settings/automation.ts
+++ b/src/app/settings/automation.ts
@@ -1,3 +1,4 @@
+import { isEmptyObject } from 'es-toolkit'
import * as v from 'valibot'
import { allRules } from '@open-pencil/core/lint'
@@ -126,7 +127,7 @@ export function updateAutomationSettings(input: unknown): AutomationSettings {
}
if (patch.editing?.snapping) applySnappingPreferences(patch.editing.snapping)
const { showOnCanvas, ...designCheck } = patch.designCheck ?? {}
- if (Object.keys(designCheck).length > 0) updateDesignCheckPreferences(designCheck)
+ if (!isEmptyObject(designCheck)) updateDesignCheckPreferences(designCheck)
// Through the menu's setter, so the native View menu checkmark follows.
if (showOnCanvas !== undefined) setDesignIssuesOnCanvas(showOnCanvas)
diff --git a/src/app/usage/summarize.ts b/src/app/usage/summarize.ts
index 2dd024c86..43975b22d 100644
--- a/src/app/usage/summarize.ts
+++ b/src/app/usage/summarize.ts
@@ -1,3 +1,5 @@
+import { sum } from 'es-toolkit'
+
import type { DiagnosticEvent } from '@/app/diagnostics/types'
export type UsageModelSummary = {
@@ -22,7 +24,7 @@ function sumAttribute(events: DiagnosticEvent[], name: string): number | null {
const values = events
.map((event) => event.attributes[name])
.filter((value): value is number => typeof value === 'number')
- return values.length === 0 ? null : values.reduce((sum, value) => sum + value, 0)
+ return values.length === 0 ? null : sum(values)
}
export function summarizeUsage(events: DiagnosticEvent[]): UsageSummary {
diff --git a/src/components/ui/select/AppPicker.vue b/src/components/ui/select/AppPicker.vue
index abed9c85f..0e0257f3b 100644
--- a/src/components/ui/select/AppPicker.vue
+++ b/src/components/ui/select/AppPicker.vue
@@ -1,4 +1,5 @@
<script lang="ts">
+import { clamp } from 'es-toolkit'
import type { VNode } from 'vue'
import type { ComponentUI } from '@/components/ui/types'
@@ -151,7 +152,7 @@ function moveRow(event: KeyboardEvent) {
const current = highlighted.value?.value
const index = matches.value.findIndex((item) => item.value === current)
const target = index === -1 ? 0 : index + rows * APP_PICKER_GRID_COLUMNS
- const next = matches.value[Math.min(Math.max(target, 0), matches.value.length - 1)]
+ const next = matches.value[clamp(target, 0, matches.value.length - 1)]
if (next) listbox.value?.highlightItem(next.value)
}
diff --git a/src/components/variables/TokenInspector.vue b/src/components/variables/TokenInspector.vue
index ccf710eec..05f886bc2 100644
--- a/src/components/variables/TokenInspector.vue
+++ b/src/components/variables/TokenInspector.vue
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { computedAsync } from '@vueuse/core'
-import { omit } from 'es-toolkit'
+import { isEmptyObject, omit } from 'es-toolkit'
import { tv } from 'tailwind-variants'
import { computed, reactive, useId, watch } from 'vue'
@@ -205,7 +205,7 @@ function commitExpression(modeId: string) {
const expressions: Record<string, TokenExpression> =
css && typeof resolved === 'number' ? { ...others, [modeId]: { css, resolved } } : others
emit('updateToken', {
- expressions: Object.keys(expressions).length > 0 ? expressions : undefined
+ expressions: isEmptyObject(expressions) ? undefined : expressions
})
}