@viamrobotics/test-widgets 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -91,9 +91,12 @@
91
91
  })
92
92
  </script>
93
93
 
94
- <div class="text-default flex flex-wrap gap-2 text-xs">
94
+ <div class="text-default flex text-xs">
95
95
  <div class="w-50 max-w-full">
96
- <Select on:change={onChange}>
96
+ <Select
97
+ on:change={onChange}
98
+ cx="border-r-0"
99
+ >
97
100
  {#each refetchOptions as option (option)}
98
101
  <option selected={selectedOption === option}>{option}</option>
99
102
  {/each}
@@ -14,5 +14,5 @@ export declare const RefetchIntervals: {
14
14
  };
15
15
  export type RefetchRate = ValueOf<typeof RefetchRates>;
16
16
  export type RefetchInterval = ValueOf<typeof RefetchIntervals>;
17
- export declare const RefetchRateToInterval: ["Live" | "Refresh every second" | "Refresh every 5 seconds" | "Manual refresh", false | 1000 | 33.3333 | 5000][];
17
+ export declare const RefetchRateToInterval: ["Live" | "Refresh every second" | "Refresh every 5 seconds" | "Manual refresh", false | 1000 | 5000 | 33.3333][];
18
18
  export declare const createRefetchIntervalStore: (partID: () => string, resourceName: () => string, scope: string, defaultInterval?: RefetchInterval) => PersistedState<RefetchInterval>;
@@ -38,8 +38,8 @@
38
38
  const moveToJointPosMutation = createResourceMutation(client, 'moveToJointPositions')
39
39
  const stopMutation = createResourceMutation(client, 'stop')
40
40
 
41
- const moveToJointPositions = (jointPositionsList: number[]) => {
42
- moveToJointPosMutation.mutate([jointPositionsList], {})
41
+ const moveToJointPositions = async (jointPositionsList: number[]) => {
42
+ await moveToJointPosMutation.mutateAsync([jointPositionsList])
43
43
  }
44
44
 
45
45
  const jointLimitsDegrees = $derived(
@@ -11,7 +11,8 @@
11
11
  positions: number[]
12
12
  jointLimitsDegrees: JointLimit[]
13
13
  useRadians: boolean
14
- moveToJointPositions: (jointPositions: number[]) => void
14
+ /** Sends the move. Rejects when it fails. */
15
+ moveToJointPositions: (jointPositions: number[]) => Promise<void>
15
16
  }
16
17
 
17
18
  let {
@@ -25,8 +26,12 @@
25
26
  const getSliderMin = (index: number): number => jointLimitsDegrees[index]?.minDegrees ?? -180
26
27
  const getSliderMax = (index: number): number => jointLimitsDegrees[index]?.maxDegrees ?? 180
27
28
 
28
- const execute = () => {
29
- moveToJointPositions([...desiredPositions])
29
+ const execute = async () => {
30
+ try {
31
+ await moveToJointPositions([...desiredPositions])
32
+ } catch {
33
+ // The parent renders the failure from the mutation's error state.
34
+ }
30
35
  }
31
36
 
32
37
  const resetToZero = () => {
@@ -4,7 +4,8 @@ interface Props {
4
4
  positions: number[];
5
5
  jointLimitsDegrees: JointLimit[];
6
6
  useRadians: boolean;
7
- moveToJointPositions: (jointPositions: number[]) => void;
7
+ /** Sends the move. Rejects when it fails. */
8
+ moveToJointPositions: (jointPositions: number[]) => Promise<void>;
8
9
  }
9
10
  declare const JointPositionEditor: import("svelte").Component<Props, {}, "desiredPositions">;
10
11
  type JointPositionEditor = ReturnType<typeof JointPositionEditor>;
@@ -0,0 +1,216 @@
1
+ <script lang="ts">
2
+ import {
3
+ Badge,
4
+ Button,
5
+ Icon,
6
+ type IconName,
7
+ Label,
8
+ Select,
9
+ Tooltip,
10
+ } from '@viamrobotics/prime-core'
11
+
12
+ import { degreesToRadians, formatNumeric } from '../../../format'
13
+
14
+ import type { JointLimit } from './joint-position-limits'
15
+
16
+ import {
17
+ type JogJointRange,
18
+ type JogQueueEntry,
19
+ type JogQueueStatus,
20
+ jogTargetDegrees,
21
+ useJogQueue,
22
+ } from './useJogQueue.svelte'
23
+
24
+ const JOG_STEP_OPTIONS_DEGREES = [1, 5, 10, 15] as const
25
+ type JogStepDegrees = (typeof JOG_STEP_OPTIONS_DEGREES)[number]
26
+ const DEFAULT_JOG_STEP_DEGREES: JogStepDegrees = 5
27
+
28
+ type JogDirection = 'decrease' | 'increase'
29
+
30
+ interface StatusBadge {
31
+ variant: 'pending' | 'progress' | 'success' | 'danger'
32
+ icon?: IconName
33
+ }
34
+
35
+ const STATUS_BADGES: Record<JogQueueStatus, StatusBadge> = {
36
+ queuing: { variant: 'pending' },
37
+ sending: { variant: 'progress' },
38
+ sent: { variant: 'success' },
39
+ failed: { variant: 'danger' },
40
+ }
41
+
42
+ interface Props {
43
+ positions: number[]
44
+ /** Per-joint limits a jog target is clamped to. A joint with no entry is not clamped. */
45
+ jointLimitsDegrees: JointLimit[]
46
+ useRadians: boolean
47
+ isMoving: boolean
48
+ /** Sends the move. Rejects when it fails. */
49
+ moveToJointPositions: (jointPositions: number[]) => Promise<void>
50
+ }
51
+
52
+ const { positions, jointLimitsDegrees, useRadians, isMoving, moveToJointPositions }: Props =
53
+ $props()
54
+
55
+ let jogStepDegrees = $state<JogStepDegrees>(DEFAULT_JOG_STEP_DEGREES)
56
+
57
+ const queue = useJogQueue({
58
+ send: (targetsByJoint) =>
59
+ moveToJointPositions(
60
+ positions.map((position, index) => targetsByJoint.get(index) ?? position)
61
+ ),
62
+ })
63
+
64
+ $effect(() => queue.dispose)
65
+
66
+ const isJointDisabled = (jointIndex: number) =>
67
+ isMoving || queue.entryFor(jointIndex)?.status === 'sending'
68
+
69
+ const formatAngle = (degrees: number) =>
70
+ useRadians ? `${formatNumeric(degreesToRadians(degrees))} rad` : `${formatNumeric(degrees)}°`
71
+
72
+ const rangeFor = (jointIndex: number): JogJointRange => ({
73
+ startDegrees: positions[jointIndex] ?? 0,
74
+ minDegrees: jointLimitsDegrees[jointIndex]?.minDegrees ?? Number.NEGATIVE_INFINITY,
75
+ maxDegrees: jointLimitsDegrees[jointIndex]?.maxDegrees ?? Number.POSITIVE_INFINITY,
76
+ })
77
+
78
+ const stepFor = (direction: JogDirection) =>
79
+ direction === 'decrease' ? -jogStepDegrees : jogStepDegrees
80
+
81
+ const handleStepChange = (event: Event) => {
82
+ if (!(event.target instanceof HTMLSelectElement)) return
83
+
84
+ const selected = Number(event.target.value)
85
+ const step = JOG_STEP_OPTIONS_DEGREES.find((option) => option === selected)
86
+ if (step !== undefined) jogStepDegrees = step
87
+ }
88
+
89
+ const handlePointerDown = (event: PointerEvent, jointIndex: number, direction: JogDirection) => {
90
+ if (isJointDisabled(jointIndex) || event.button !== 0) return
91
+
92
+ queue.beginHold(jointIndex, stepFor(direction), rangeFor(jointIndex))
93
+ }
94
+
95
+ // Keyboard and assistive-technology activation arrive as a click with `detail` 0. Pointer
96
+ // clicks are already counted by the pointer handlers, so they are skipped here.
97
+ const handleClick = (event: MouseEvent, jointIndex: number, direction: JogDirection) => {
98
+ if (isJointDisabled(jointIndex) || event.detail !== 0) return
99
+
100
+ queue.tap(jointIndex, stepFor(direction), rangeFor(jointIndex))
101
+ }
102
+
103
+ const formatTarget = (entry: JogQueueEntry) => formatAngle(jogTargetDegrees(entry))
104
+
105
+ const describeEntry = (entry: JogQueueEntry) => {
106
+ const target = formatTarget(entry)
107
+ switch (entry.status) {
108
+ case 'queuing': {
109
+ return `Joint ${entry.jointIndex} will move to ${target}`
110
+ }
111
+ case 'sending': {
112
+ return `Moving joint ${entry.jointIndex} to ${target}`
113
+ }
114
+ case 'sent': {
115
+ return `Joint ${entry.jointIndex} moved to ${target}`
116
+ }
117
+ case 'failed': {
118
+ return `Move of joint ${entry.jointIndex} to ${target} failed`
119
+ }
120
+ default: {
121
+ const exhaustive: never = entry.status
122
+ return exhaustive
123
+ }
124
+ }
125
+ }
126
+ </script>
127
+
128
+ {#snippet jogButton(jointIndex: number, direction: JogDirection)}
129
+ <Tooltip
130
+ hoverDelayMS={400}
131
+ targetClass="inline-flex"
132
+ >
133
+ <Button
134
+ aria-label="{direction === 'decrease'
135
+ ? 'Decrease'
136
+ : 'Increase'} joint {jointIndex} by {jogStepDegrees} degrees"
137
+ disabled={isJointDisabled(jointIndex)}
138
+ onpointerdown={(event) => handlePointerDown(event, jointIndex, direction)}
139
+ onpointerup={queue.endHold}
140
+ onpointerleave={queue.endHold}
141
+ onpointercancel={queue.endHold}
142
+ onclick={(event) => handleClick(event, jointIndex, direction)}
143
+ >
144
+ {direction === 'decrease' ? '−' : '+'}{jogStepDegrees}°
145
+ </Button>
146
+ <span slot="description">
147
+ Tap or hold to {direction === 'decrease' ? 'subtract' : 'add'}
148
+ {jogStepDegrees}°
149
+ </span>
150
+ </Tooltip>
151
+ {/snippet}
152
+
153
+ <div class="flex flex-col gap-x-4 gap-y-2">
154
+ <Label position="left">
155
+ <span class="w-12"> Jog step</span>
156
+ <Select
157
+ slot="input"
158
+ value={String(jogStepDegrees)}
159
+ on:change={handleStepChange}
160
+ >
161
+ {#each JOG_STEP_OPTIONS_DEGREES as step (step)}
162
+ <option value={String(step)}>{step}°</option>
163
+ {/each}
164
+ </Select>
165
+ </Label>
166
+ <Tooltip>
167
+ <span class="flex items-center gap-1 text-xs text-amber-600">
168
+ <Icon
169
+ name="alert"
170
+ size="sm"
171
+ cx="text-amber-600"
172
+ />
173
+ Jogging executes immediately on release
174
+ </span>
175
+ <span slot="description">
176
+ Jog buttons send a move to the arm as soon as you release them. There is no confirm step.
177
+ Buttons are disabled while the arm is moving.
178
+ </span>
179
+ </Tooltip>
180
+ </div>
181
+
182
+ <ul class="flex flex-col divide-y">
183
+ {#each positions as position, index (index)}
184
+ {@const entry = queue.entryFor(index)}
185
+ <!-- flex-wrap with a stepper that keeps its min-content width: it drops under the label only when the row is too narrow for both. -->
186
+ <li class="flex flex-wrap items-center gap-x-3 gap-y-1.5 py-1.5">
187
+ <span class="font-roboto-mono text-subtle-1 w-14 shrink-0 text-xs">Joint {index}</span>
188
+ <div class="flex flex-1 items-center gap-1.5">
189
+ {@render jogButton(index, 'decrease')}
190
+ <!-- The badge overlays the readout so the row keeps one width in the narrow three-column card. -->
191
+ <span class="grid min-w-20 flex-1 items-center justify-center">
192
+ {#if entry}
193
+ <span
194
+ role="status"
195
+ class="row-start-1l col-start-1"
196
+ >
197
+ <span aria-hidden="true">
198
+ <Badge
199
+ label={formatTarget(entry)}
200
+ cx="font-roboto-mono tabular-nums"
201
+ {...STATUS_BADGES[entry.status]}
202
+ />
203
+ </span>
204
+ <span class="sr-only">{describeEntry(entry)}</span>
205
+ </span>
206
+ {:else}
207
+ <span class="font-roboto-mono col-start-1 row-start-1 text-xs tabular-nums">
208
+ {formatAngle(position)}
209
+ </span>
210
+ {/if}
211
+ </span>
212
+ {@render jogButton(index, 'increase')}
213
+ </div>
214
+ </li>
215
+ {/each}
216
+ </ul>
@@ -0,0 +1,13 @@
1
+ import type { JointLimit } from './joint-position-limits';
2
+ interface Props {
3
+ positions: number[];
4
+ /** Per-joint limits a jog target is clamped to. A joint with no entry is not clamped. */
5
+ jointLimitsDegrees: JointLimit[];
6
+ useRadians: boolean;
7
+ isMoving: boolean;
8
+ /** Sends the move. Rejects when it fails. */
9
+ moveToJointPositions: (jointPositions: number[]) => Promise<void>;
10
+ }
11
+ declare const JointPositionJogging: import("svelte").Component<Props, {}, "">;
12
+ type JointPositionJogging = ReturnType<typeof JointPositionJogging>;
13
+ export default JointPositionJogging;
@@ -1,10 +1,14 @@
1
+ import { type FrameConfigEntry } from '../motion/frame-system-config';
1
2
  /** How the arm MoveToPosition widget executes a move. */
2
3
  export type MoveControlMode = 'motion' | 'direct';
3
4
  /**
4
- * The mode the widget starts in: motion planning whenever the machine has a
5
- * motion service, direct arm control only when it has none.
5
+ * Whether the widget can offer motion planning for `resourceName`.
6
+ *
7
+ * The machine needs a motion service, and the arm needs a frame in the machine's frame system.
8
+ * rdk leaves a component configured without a `frame` out of the frame system entirely, and
9
+ * neither `GetPose` nor a motion `Move` can resolve an arm it cannot find there.
6
10
  */
7
- export declare const defaultMoveControlMode: (motionServiceNames: string[]) => MoveControlMode;
11
+ export declare const canPlanMotion: (motionServiceNames: string[], frameSystem: FrameConfigEntry[], resourceName: string) => boolean;
8
12
  /**
9
13
  * The motion service a `Move` call targets: `builtin` when present, otherwise
10
14
  * the first discovered service.
@@ -1,8 +1,12 @@
1
+ import { movableFrameNames } from '../motion/frame-system-config';
1
2
  /**
2
- * The mode the widget starts in: motion planning whenever the machine has a
3
- * motion service, direct arm control only when it has none.
3
+ * Whether the widget can offer motion planning for `resourceName`.
4
+ *
5
+ * The machine needs a motion service, and the arm needs a frame in the machine's frame system.
6
+ * rdk leaves a component configured without a `frame` out of the frame system entirely, and
7
+ * neither `GetPose` nor a motion `Move` can resolve an arm it cannot find there.
4
8
  */
5
- export const defaultMoveControlMode = (motionServiceNames) => motionServiceNames.length > 0 ? 'motion' : 'direct';
9
+ export const canPlanMotion = (motionServiceNames, frameSystem, resourceName) => motionServiceNames.length > 0 && movableFrameNames(frameSystem).includes(resourceName);
6
10
  /**
7
11
  * The motion service a `Move` call targets: `builtin` when present, otherwise
8
12
  * the first discovered service.
@@ -33,8 +33,8 @@
33
33
 
34
34
  const moveToJointPosMutation = createResourceMutation(client, 'moveToJointPositions')
35
35
 
36
- const moveToJointPositions = (jointPositionsList: number[]) => {
37
- moveToJointPosMutation.mutate([jointPositionsList], {})
36
+ const moveToJointPositions = async (jointPositionsList: number[]) => {
37
+ await moveToJointPosMutation.mutateAsync([jointPositionsList])
38
38
  }
39
39
 
40
40
  const jointLimitsDegrees = $derived(
@@ -8,16 +8,17 @@
8
8
  import { degreesToRadians, formatNumeric, radiansToDegrees } from '../../../format'
9
9
 
10
10
  import JointPositionEditor from './joint-position-editor.svelte'
11
+ import JointPositionJogging from './joint-position-jogging.svelte'
11
12
  import { type JointLimit } from './joint-position-limits'
12
- import JointPositionQuickMove from './joint-position-quick-move.svelte'
13
13
 
14
- type ControlMode = 'Joint Positions' | 'Quick Move'
14
+ type ControlMode = 'Jogging' | 'Joint Positions'
15
15
 
16
- const CONTROL_MODES: ControlMode[] = ['Joint Positions', 'Quick Move']
16
+ const CONTROL_MODES: ControlMode[] = ['Jogging', 'Joint Positions']
17
17
 
18
18
  interface Props {
19
19
  positions: number[]
20
- moveToJointPositions: (jointPositions: number[]) => void
20
+ /** Sends the move. Rejects when it fails. */
21
+ moveToJointPositions: (jointPositions: number[]) => Promise<void>
21
22
  lastError: Error | null
22
23
  jointLimitsDegrees: JointLimit[]
23
24
  isMoving?: boolean
@@ -34,9 +35,9 @@
34
35
  // svelte-ignore state_referenced_locally
35
36
  let desiredPositions = $state([...positions]) // in degrees
36
37
  let useRadians = $state(false)
37
- let controlMode = $state<ControlMode>('Joint Positions')
38
+ let controlMode = $state<ControlMode>('Jogging')
38
39
 
39
- const isQuickMoveMode = $derived(controlMode === 'Quick Move')
40
+ const isJoggingMode = $derived(controlMode === 'Jogging')
40
41
 
41
42
  const getJointMin = (index: number): number => jointLimitsDegrees[index]?.minDegrees ?? -180
42
43
  const getJointMax = (index: number): number => jointLimitsDegrees[index]?.maxDegrees ?? 180
@@ -77,7 +78,7 @@
77
78
  on:input={handleModeChange}
78
79
  />
79
80
  <div class="flex items-center gap-1">
80
- {#if !isQuickMoveMode}
81
+ {#if !isJoggingMode}
81
82
  <Tooltip>
82
83
  <Icon
83
84
  name="information-outline"
@@ -100,10 +101,11 @@
100
101
  </div>
101
102
  </div>
102
103
 
103
- {#if isQuickMoveMode}
104
- <JointPositionQuickMove
104
+ {#if isJoggingMode}
105
+ <JointPositionJogging
105
106
  {positions}
106
107
  {moveToJointPositions}
108
+ {jointLimitsDegrees}
107
109
  {useRadians}
108
110
  {isMoving}
109
111
  />
@@ -1,7 +1,8 @@
1
1
  import { type JointLimit } from './joint-position-limits';
2
2
  interface Props {
3
3
  positions: number[];
4
- moveToJointPositions: (jointPositions: number[]) => void;
4
+ /** Sends the move. Rejects when it fails. */
5
+ moveToJointPositions: (jointPositions: number[]) => Promise<void>;
5
6
  lastError: Error | null;
6
7
  jointLimitsDegrees: JointLimit[];
7
8
  isMoving?: boolean;
@@ -10,10 +10,10 @@
10
10
  useRobotClient,
11
11
  } from '@viamrobotics/svelte-sdk'
12
12
 
13
- import Query from '../../query.svelte'
13
+ import Queries from '../../queries.svelte'
14
14
 
15
15
  import {
16
- defaultMoveControlMode,
16
+ canPlanMotion,
17
17
  motionServiceOptions,
18
18
  type MoveControlMode,
19
19
  moveMotionServiceName,
@@ -27,16 +27,29 @@
27
27
 
28
28
  const { partID, resourceName }: Props = $props()
29
29
 
30
+ // Both modes read the live pose back at this rate, so `Current position` is never stale.
31
+ const POSE_REFETCH_INTERVAL_MS = 500
32
+ const FRAME_SYSTEM_REFETCH_INTERVAL_MS = 5000
33
+
30
34
  const motionServices = useResourceStatuses(() => partID, 'motion')
31
35
  const motionServiceNames = $derived(
32
36
  motionServices.current
33
37
  .map((service) => service.name?.name)
34
38
  .filter((name): name is string => name !== undefined)
35
39
  )
40
+
41
+ const robotClient = useRobotClient(() => partID)
42
+ const frameSystemQuery = createRobotQuery(robotClient, 'frameSystemConfig', () => ({
43
+ refetchInterval: FRAME_SYSTEM_REFETCH_INTERVAL_MS,
44
+ }))
45
+ const frameSystem = $derived(frameSystemQuery.data)
36
46
  const hasMotionService = $derived(motionServiceNames.length > 0)
47
+ const motionAvailable = $derived(
48
+ frameSystem !== undefined && canPlanMotion(motionServiceNames, frameSystem, resourceName)
49
+ )
37
50
 
38
51
  let userChoice = $state<MoveControlMode>()
39
- const mode = $derived(userChoice ?? defaultMoveControlMode(motionServiceNames))
52
+ const mode = $derived<MoveControlMode>(motionAvailable ? (userChoice ?? 'motion') : 'direct')
40
53
 
41
54
  let userServiceChoice = $state<string>()
42
55
  const activeMotionServiceName = $derived(
@@ -45,7 +58,6 @@
45
58
  const serviceOptions = $derived(motionServiceOptions(motionServiceNames))
46
59
  const showServiceSelect = $derived(mode === 'motion' && serviceOptions.length > 1)
47
60
 
48
- const robotClient = useRobotClient(() => partID)
49
61
  const armClient = createResourceClient(
50
62
  ArmClient,
51
63
  () => partID,
@@ -63,10 +75,10 @@
63
75
  robotClient,
64
76
  'getPose',
65
77
  () => poseArgs,
66
- () => ({ enabled: mode === 'motion' })
78
+ () => ({ refetchInterval: POSE_REFETCH_INTERVAL_MS, enabled: mode === 'motion' })
67
79
  )
68
80
  const endPositionQuery = createResourceQuery(armClient, 'getEndPosition', () => ({
69
- refetchInterval: 500,
81
+ refetchInterval: POSE_REFETCH_INTERVAL_MS,
70
82
  enabled: mode === 'direct',
71
83
  }))
72
84
 
@@ -103,7 +115,7 @@
103
115
  </script>
104
116
 
105
117
  <div class="flex flex-col gap-4">
106
- {#if hasMotionService}
118
+ {#if motionAvailable}
107
119
  <Label position="top">
108
120
  <span class="flex items-center gap-1 text-xs">
109
121
  Control mode
@@ -142,23 +154,31 @@
142
154
  </Select>
143
155
  </Label>
144
156
  {/if}
145
- <Banner variant={mode === 'motion' ? 'info' : 'danger'}>
146
- {#snippet subtitle()}
147
- {#if mode === 'motion'}
148
- Movement goes through motion planning and attempts to avoid obstacles.
149
- {:else}
150
- The arm will not avoid obstacles when moving. Use with caution.
157
+ {#if frameSystem !== undefined}
158
+ <Banner variant={mode === 'motion' ? 'info' : 'danger'}>
159
+ {#snippet subtitle()}
160
+ {#if mode === 'motion'}
161
+ Movement goes through motion planning and attempts to avoid obstacles.
162
+ {:else if hasMotionService && !motionAvailable}
163
+ {resourceName} has no frame, so the motion service cannot plan for it. The arm will not avoid
164
+ obstacles when moving. Use with caution.
165
+ {:else}
166
+ The arm will not avoid obstacles when moving. Use with caution.
167
+ {/if}
168
+ {/snippet}
169
+ </Banner>
170
+ {/if}
171
+ <Queries queries={[frameSystemQuery, activeQuery]}>
172
+ <!-- Re-seed the editor on a mode change: the two modes report the pose in different frames. -->
173
+ {#key mode}
174
+ {#if endPosition}
175
+ <MoveToPosition
176
+ {endPosition}
177
+ {moveToPosition}
178
+ {lastError}
179
+ {description}
180
+ />
151
181
  {/if}
152
- {/snippet}
153
- </Banner>
154
- <Query query={activeQuery}>
155
- {#if endPosition}
156
- <MoveToPosition
157
- {endPosition}
158
- {moveToPosition}
159
- {lastError}
160
- {description}
161
- />
162
- {/if}
163
- </Query>
182
+ {/key}
183
+ </Queries>
164
184
  </div>
@@ -0,0 +1,51 @@
1
+ export type JogQueueStatus = 'queuing' | 'sending' | 'sent' | 'failed';
2
+ /** The joint's position when an entry starts, and the limits its target is clamped to, in degrees. */
3
+ export interface JogJointRange {
4
+ startDegrees: number;
5
+ minDegrees: number;
6
+ maxDegrees: number;
7
+ }
8
+ export interface JogQueueEntry extends JogJointRange {
9
+ jointIndex: number;
10
+ /** Sum of every queued step in degrees, clamped so the target stays inside the limits. */
11
+ deltaDegrees: number;
12
+ status: JogQueueStatus;
13
+ }
14
+ export interface JogQueueTiming {
15
+ /** Quiet time after the last press or repeat before the queued total is sent. */
16
+ sendDebounceMs: number;
17
+ /** How long a button is held before it starts repeating. */
18
+ holdRepeatDelayMs: number;
19
+ /** Time between repeats while the button stays held. */
20
+ holdRepeatIntervalMs: number;
21
+ /** How long the sent or failed result stays visible. */
22
+ resultDisplayMs: number;
23
+ }
24
+ export declare const DEFAULT_JOG_QUEUE_TIMING: JogQueueTiming;
25
+ interface JogQueueOptions {
26
+ timing?: JogQueueTiming;
27
+ /**
28
+ * Moves every joint in `targetsByJoint` to its target, in degrees. The map
29
+ * holds the joint being sent plus any joint whose earlier move is still in
30
+ * flight or just finished, so a new move never drags those joints back to a
31
+ * stale polled position. Rejects when the move fails.
32
+ */
33
+ send: (targetsByJoint: ReadonlyMap<number, number>) => Promise<void>;
34
+ }
35
+ /** The position the entry moves its joint to, in degrees. */
36
+ export declare const jogTargetDegrees: (entry: JogQueueEntry) => number;
37
+ /**
38
+ * Collects jog presses into one move per joint. Presses within the debounce
39
+ * window, and repeats while a button is held, add to that joint's entry. The
40
+ * total is sent once the joint's input goes quiet. Each joint has its own
41
+ * entry and timers, so jogging a second joint leaves the first joint's badge
42
+ * to run through sending, its result, and clearing on its own.
43
+ */
44
+ export declare const useJogQueue: ({ send, timing }: JogQueueOptions) => {
45
+ entryFor: (jointIndex: number) => JogQueueEntry | undefined;
46
+ tap: (jointIndex: number, stepDegrees: number, range: JogJointRange) => void;
47
+ beginHold: (jointIndex: number, stepDegrees: number, range: JogJointRange) => void;
48
+ endHold: () => void;
49
+ dispose: () => void;
50
+ };
51
+ export {};
@@ -0,0 +1,143 @@
1
+ export const DEFAULT_JOG_QUEUE_TIMING = {
2
+ sendDebounceMs: 300,
3
+ holdRepeatDelayMs: 400,
4
+ holdRepeatIntervalMs: 150,
5
+ resultDisplayMs: 1200,
6
+ };
7
+ /** The position the entry moves its joint to, in degrees. */
8
+ export const jogTargetDegrees = (entry) => entry.startDegrees + entry.deltaDegrees;
9
+ // A step that would cross a joint limit is cut at the limit, so 350° jogged by 15° toward a 360° limit moves the remaining 10°.
10
+ const clampDelta = (range, deltaDegrees) => Math.min(Math.max(range.startDegrees + deltaDegrees, range.minDegrees), range.maxDegrees) -
11
+ range.startDegrees;
12
+ /**
13
+ * Collects jog presses into one move per joint. Presses within the debounce
14
+ * window, and repeats while a button is held, add to that joint's entry. The
15
+ * total is sent once the joint's input goes quiet. Each joint has its own
16
+ * entry and timers, so jogging a second joint leaves the first joint's badge
17
+ * to run through sending, its result, and clearing on its own.
18
+ */
19
+ export const useJogQueue = ({ send, timing = DEFAULT_JOG_QUEUE_TIMING }) => {
20
+ // $state.raw: the map is replaced wholesale on every change so readers re-run without deep proxies.
21
+ let entries = $state.raw(new Map());
22
+ const debounceTimers = new Map();
23
+ const resultTimers = new Map();
24
+ let holdDelayTimer;
25
+ let holdRepeatTimer;
26
+ let heldJointIndex;
27
+ const setEntry = (jointIndex, entry) => {
28
+ const next = new Map(entries);
29
+ if (entry) {
30
+ next.set(jointIndex, entry);
31
+ }
32
+ else {
33
+ next.delete(jointIndex);
34
+ }
35
+ entries = next;
36
+ };
37
+ const clearHoldTimers = () => {
38
+ clearTimeout(holdDelayTimer);
39
+ clearInterval(holdRepeatTimer);
40
+ };
41
+ const committedTargets = () => {
42
+ const targets = new Map();
43
+ for (const entry of entries.values()) {
44
+ if (entry.status === 'sending' || entry.status === 'sent') {
45
+ targets.set(entry.jointIndex, jogTargetDegrees(entry));
46
+ }
47
+ }
48
+ return targets;
49
+ };
50
+ const flush = async (jointIndex) => {
51
+ clearTimeout(debounceTimers.get(jointIndex));
52
+ const entry = entries.get(jointIndex);
53
+ if (entry?.status !== 'queuing')
54
+ return;
55
+ if (entry.deltaDegrees === 0) {
56
+ setEntry(jointIndex, undefined);
57
+ return;
58
+ }
59
+ const sending = { ...entry, status: 'sending' };
60
+ setEntry(jointIndex, sending);
61
+ let status = 'sent';
62
+ try {
63
+ await send(committedTargets());
64
+ }
65
+ catch {
66
+ status = 'failed';
67
+ }
68
+ setEntry(jointIndex, { ...sending, status });
69
+ resultTimers.set(jointIndex, setTimeout(() => {
70
+ setEntry(jointIndex, undefined);
71
+ }, timing.resultDisplayMs));
72
+ };
73
+ const add = (jointIndex, stepDegrees, range) => {
74
+ clearTimeout(debounceTimers.get(jointIndex));
75
+ const current = entries.get(jointIndex);
76
+ if (current?.status === 'sending')
77
+ return;
78
+ clearTimeout(resultTimers.get(jointIndex));
79
+ if (current?.status === 'queuing') {
80
+ setEntry(jointIndex, {
81
+ ...current,
82
+ deltaDegrees: clampDelta(current, current.deltaDegrees + stepDegrees),
83
+ });
84
+ return;
85
+ }
86
+ setEntry(jointIndex, {
87
+ jointIndex,
88
+ ...range,
89
+ deltaDegrees: clampDelta(range, stepDegrees),
90
+ status: 'queuing',
91
+ });
92
+ };
93
+ const scheduleSend = (jointIndex) => {
94
+ clearTimeout(debounceTimers.get(jointIndex));
95
+ if (entries.get(jointIndex)?.status !== 'queuing')
96
+ return;
97
+ debounceTimers.set(jointIndex, setTimeout(() => {
98
+ void flush(jointIndex);
99
+ }, timing.sendDebounceMs));
100
+ };
101
+ /**
102
+ * One discrete press, such as a keyboard or assistive-technology activation.
103
+ * `range` is the joint's current position and limits and is only read when the
104
+ * press starts a new entry.
105
+ */
106
+ const tap = (jointIndex, stepDegrees, range) => {
107
+ add(jointIndex, stepDegrees, range);
108
+ scheduleSend(jointIndex);
109
+ };
110
+ /** A pointer press. Queues one step now and keeps adding while held. */
111
+ const beginHold = (jointIndex, stepDegrees, range) => {
112
+ clearHoldTimers();
113
+ heldJointIndex = jointIndex;
114
+ add(jointIndex, stepDegrees, range);
115
+ holdDelayTimer = setTimeout(() => {
116
+ holdRepeatTimer = setInterval(() => {
117
+ add(jointIndex, stepDegrees, range);
118
+ }, timing.holdRepeatIntervalMs);
119
+ }, timing.holdRepeatDelayMs);
120
+ };
121
+ /** A pointer release. Stops repeating and schedules the held joint's send. */
122
+ const endHold = () => {
123
+ clearHoldTimers();
124
+ if (heldJointIndex === undefined)
125
+ return;
126
+ scheduleSend(heldJointIndex);
127
+ heldJointIndex = undefined;
128
+ };
129
+ const dispose = () => {
130
+ clearHoldTimers();
131
+ for (const timer of debounceTimers.values())
132
+ clearTimeout(timer);
133
+ for (const timer of resultTimers.values())
134
+ clearTimeout(timer);
135
+ };
136
+ return {
137
+ entryFor: (jointIndex) => entries.get(jointIndex),
138
+ tap,
139
+ beginHold,
140
+ endHold,
141
+ dispose,
142
+ };
143
+ };
@@ -167,59 +167,10 @@
167
167
  headingId={getImagesHeadingID}
168
168
  />
169
169
  </div>
170
- <div class="flex gap-4 px-4 pt-3">
171
- <Label position="left">
172
- Wait to start feed
173
- <Switch
174
- slot="input"
175
- annotated
176
- on={waitToStartFeed.current}
177
- on:change={(event) => {
178
- waitToStartFeed.current = event.detail
179
- }}
180
- />
181
- </Label>
182
- </div>
183
- {#if isPlaying}
184
- <div class="flex flex-wrap gap-4 p-4 pb-3">
185
- <RefetchController
186
- {refetchInterval}
187
- allowLive
188
- queries={[imageQuery, pointcloudQuery]}
189
- />
190
- {#if sourceNames.length > 0 && refetchInterval.current !== RefetchIntervals.LIVE}
191
- <Label position="left">
192
- Source
193
- <Select
194
- value={selectedSource}
195
- on:change={onSourceSelect}
196
- slot="input"
197
- >
198
- {#each sourceNames as name (name)}
199
- <option value={name}>{name}</option>
200
- {/each}
201
- </Select>
202
- </Label>
203
- {/if}
204
- {#if panoCoverage}
205
- <Label>
206
- {panoToggleLabel}
207
- <ToggleButtons
208
- slot="input"
209
- options={['On', 'Off']}
210
- selected={displayAs360 ? 'On' : 'Off'}
211
- on:input={(event) => {
212
- displayAs360 = event.detail === 'On'
213
- }}
214
- />
215
- </Label>
216
- {/if}
217
- </div>
218
- {/if}
219
- <div class="flex h-full w-full flex-wrap gap-4 p-4">
220
- <div class="min-w-0 grow basis-80">
221
- {#if isPlaying}
222
- {#if displayAs360}
170
+ <div class="p-4">
171
+ {#if isPlaying}
172
+ {#if displayAs360}
173
+ <div class="h-80 w-full">
223
174
  {#if isLive}
224
175
  <!-- renderMode="always" keeps the live VideoTexture advancing each frame -->
225
176
  <Canvas renderMode="always">
@@ -237,84 +188,131 @@
237
188
  />
238
189
  </Canvas>
239
190
  {/if}
240
- {:else}
241
- <LiveOrPollingVideo
242
- {partID}
243
- {resourceName}
244
- showResolutionOptions
245
- videoClass="h-auto max-w-full"
246
- {isLive}
247
- data={imageQuery.data}
248
- error={imageQuery.error}
249
- isLoading={imageQuery.isLoading}
250
- refetch={imageQuery.refetch}
251
- showMousePositionTooltip={mousePostionTooltip === 'On'}
252
- sourceName={selectedSource}
253
- />
254
- {/if}
255
- {:else}
256
- <div class="bg-medium flex h-64 w-full max-w-80 items-center justify-center">
257
- <Button
258
- icon="play-circle-outline"
259
- variant="dark"
260
- onclick={() => {
261
- isPlaying = true
262
- }}
263
- >
264
- Start feed
265
- </Button>
266
191
  </div>
267
- {/if}
268
- </div>
269
- {#if isPlaying}
270
- <div class="flex shrink-0 flex-col items-start gap-2">
271
- <ExportScreenshot
272
- name={client.current?.name ?? ''}
192
+ {:else}
193
+ <LiveOrPollingVideo
194
+ {partID}
195
+ {resourceName}
196
+ showResolutionOptions
197
+ videoClass="h-auto max-w-full"
198
+ {isLive}
199
+ data={imageQuery.data}
200
+ error={imageQuery.error}
201
+ isLoading={imageQuery.isLoading}
202
+ refetch={imageQuery.refetch}
203
+ showMousePositionTooltip={mousePostionTooltip === 'On'}
273
204
  sourceName={selectedSource}
274
- getImage={exportScreenshotQuery.refetch}
275
205
  />
276
- {#if addImageToDataset}
277
- <Button
278
- icon="layers-triple-outline"
279
- onclick={async () => {
280
- let imgData
281
- if (refetchInterval.current === RefetchIntervals.LIVE) {
282
- const { isSuccess, data } = await imageQuery.refetch()
283
- if (!isSuccess) return
284
- imgData = data
285
- } else {
286
- imgData = imageQuery.data
287
- }
206
+ {/if}
207
+ {:else}
208
+ <div class="bg-medium flex h-64 w-full items-center justify-center">
209
+ <Button
210
+ icon="play-circle-outline"
211
+ variant="dark"
212
+ onclick={() => {
213
+ isPlaying = true
214
+ }}
215
+ >
216
+ Start feed
217
+ </Button>
218
+ </div>
219
+ {/if}
220
+
221
+ <div class="mt-3 flex flex-wrap items-start gap-2">
222
+ <RefetchController
223
+ {refetchInterval}
224
+ allowLive
225
+ queries={[imageQuery, pointcloudQuery]}
226
+ />
227
+ <ExportScreenshot
228
+ name={client.current?.name ?? ''}
229
+ sourceName={selectedSource}
230
+ getImage={exportScreenshotQuery.refetch}
231
+ />
232
+ {#if addImageToDataset}
233
+ <Button
234
+ icon="layers-triple-outline"
235
+ onclick={async () => {
236
+ let imgData
237
+ if (refetchInterval.current === RefetchIntervals.LIVE) {
238
+ const { isSuccess, data } = await imageQuery.refetch()
239
+ if (!isSuccess) return
240
+ imgData = data
241
+ } else {
242
+ imgData = imageQuery.data
243
+ }
288
244
 
289
- const matchingImage = pickImageForSource(imgData?.images, selectedSource)
290
- const image = matchingImage?.image
291
- const mimeType = matchingImage?.mimeType
245
+ const matchingImage = pickImageForSource(imgData?.images, selectedSource)
246
+ const image = matchingImage?.image
247
+ const mimeType = matchingImage?.mimeType
292
248
 
293
- if (image) {
294
- addImageToDataset({
295
- binaryData: new Uint8Array(image),
296
- partID,
297
- componentType: 'camera',
298
- componentName: resourceName,
299
- methodName: 'captureAllFromCamera',
300
- mimeType: mimeType ?? 'image/png',
301
- dataRequestTimes: [new Date(), new Date()],
302
- })
303
- }
304
- }}
305
- >
306
- Add current image to dataset
307
- </Button>
249
+ if (image) {
250
+ addImageToDataset({
251
+ binaryData: new Uint8Array(image),
252
+ partID,
253
+ componentType: 'camera',
254
+ componentName: resourceName,
255
+ methodName: 'captureAllFromCamera',
256
+ mimeType: mimeType ?? 'image/png',
257
+ dataRequestTimes: [new Date(), new Date()],
258
+ })
259
+ }
260
+ }}
261
+ >
262
+ Add to dataset
263
+ </Button>
264
+ {/if}
265
+ {#if !isFirefox}
266
+ <PictureInPictureButton
267
+ {resourceName}
268
+ rate={refetchInterval.current}
269
+ />
270
+ {/if}
271
+ </div>
272
+ <div class="flex flex-col gap-4">
273
+ <div class="flex w-full max-w-80 items-start gap-4">
274
+ {#if sourceNames.length > 0 && refetchInterval.current !== RefetchIntervals.LIVE}
275
+ <Label>
276
+ Source
277
+ <Select
278
+ value={selectedSource}
279
+ on:change={onSourceSelect}
280
+ slot="input"
281
+ >
282
+ {#each sourceNames as name (name)}
283
+ <option value={name}>{name}</option>
284
+ {/each}
285
+ </Select>
286
+ </Label>
308
287
  {/if}
309
- {#if !isFirefox}
310
- <PictureInPictureButton
311
- {resourceName}
312
- rate={refetchInterval.current}
313
- />
288
+ {#if panoCoverage}
289
+ <Label>
290
+ {panoToggleLabel}
291
+ <ToggleButtons
292
+ slot="input"
293
+ options={['On', 'Off']}
294
+ selected={displayAs360 ? 'On' : 'Off'}
295
+ on:input={(event) => {
296
+ displayAs360 = event.detail === 'On'
297
+ }}
298
+ />
299
+ </Label>
314
300
  {/if}
301
+ </div>
302
+ <div class="flex w-full max-w-80 items-start gap-4">
315
303
  <Label>
316
- Mouse Position Tooltip
317
-
304
+ Start feed automatically
305
+ <ToggleButtons
306
+ slot="input"
307
+ options={['Yes', 'No']}
308
+ selected={waitToStartFeed.current ? 'No' : 'Yes'}
309
+ on:input={(event) => {
310
+ waitToStartFeed.current = event.detail === 'No'
311
+ }}
312
+ />
313
+ </Label>
314
+ <Label>
315
+ Mouse position tooltip
318
316
  <ToggleButtons
319
317
  slot="input"
320
318
  options={['On', 'Off']}
@@ -323,7 +321,7 @@
323
321
  />
324
322
  </Label>
325
323
  </div>
326
- {/if}
324
+ </div>
327
325
  </div>
328
326
  </section>
329
327
 
@@ -79,11 +79,15 @@
79
79
  }
80
80
  </script>
81
81
 
82
- <Button
83
- icon="camera-outline"
84
- onclick={handleExport}>Export screenshot</Button
85
- >
86
- <ErrorDisplay
87
- class="max-w-50"
88
- {lastError}
89
- />
82
+ <div class="flex flex-col items-start gap-1">
83
+ <Button
84
+ icon="camera-outline"
85
+ onclick={handleExport}
86
+ >
87
+ Screenshot
88
+ </Button>
89
+ <ErrorDisplay
90
+ class="max-w-50"
91
+ {lastError}
92
+ />
93
+ </div>
@@ -21,15 +21,16 @@
21
21
  })
22
22
  </script>
23
23
 
24
- <Button
25
- icon="picture-in-picture-top-right"
26
- onclick={() => pip.toggle(resourceName)}
27
- progress={pip.readyState === 'loading' ? 'indeterminate' : undefined}
28
- >
29
- Toggle picture-in-picture
30
- </Button>
31
-
32
- <ErrorDisplay
33
- class="max-w-50"
34
- lastError={pip.error}
35
- />
24
+ <div class="flex flex-col items-start gap-1">
25
+ <Button
26
+ icon="picture-in-picture-top-right"
27
+ onclick={() => pip.toggle(resourceName)}
28
+ progress={pip.readyState === 'loading' ? 'indeterminate' : undefined}
29
+ >
30
+ Picture-in-picture
31
+ </Button>
32
+ <ErrorDisplay
33
+ class="max-w-50"
34
+ lastError={pip.error}
35
+ />
36
+ </div>
package/dist/registry.js CHANGED
@@ -17,7 +17,7 @@ const resourceWidgetRegistry = {
17
17
  widgets: [ArmMoveToJointPositionsWidget],
18
18
  },
19
19
  { id: 'move-to-position', label: 'MoveToPosition', widgets: [ArmMoveToPositionWidget] },
20
- { id: 'quick-move', label: 'Quick move', widgets: [ArmQuickMoveWidget] },
20
+ { id: 'quick-move', label: 'Jogging', widgets: [ArmQuickMoveWidget] },
21
21
  {
22
22
  id: 'get-joint-positions',
23
23
  label: 'GetJointPositions',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@viamrobotics/test-widgets",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "wireit": {
@@ -1,85 +0,0 @@
1
- <script lang="ts">
2
- import { Button, Icon, Tooltip } from '@viamrobotics/prime-core'
3
-
4
- import Table from '../../table.svelte'
5
- import { degreesToRadians, formatNumeric } from '../../../format'
6
-
7
- const INCREMENT_DEGREES = 5
8
-
9
- interface Props {
10
- positions: number[]
11
- moveToJointPositions: (jointPositions: number[]) => void
12
- useRadians: boolean
13
- isMoving: boolean
14
- }
15
-
16
- const { positions, moveToJointPositions, useRadians, isMoving }: Props = $props()
17
-
18
- const toDisplayAngle = (degrees: number) => (useRadians ? degreesToRadians(degrees) : degrees)
19
-
20
- const currentDisplayPositions = $derived(positions.map((degrees) => toDisplayAngle(degrees)))
21
-
22
- const quickMove = (index: number, increment: number) => {
23
- if (isMoving) {
24
- return
25
- }
26
- const clonedPositions = positions.map((position, positionIndex) =>
27
- positionIndex === index ? position + increment : position
28
- )
29
- moveToJointPositions(clonedPositions)
30
- }
31
- </script>
32
-
33
- <Tooltip>
34
- <span class="flex items-center gap-1 text-xs text-amber-600">
35
- <Icon
36
- name="alert"
37
- size="sm"
38
- cx="text-amber-600"
39
- />
40
- Quick move executes immediately
41
- </span>
42
- <span slot="description">
43
- Each ±5° button sends a move command as soon as it is pressed. Buttons are disabled while the
44
- arm is moving.
45
- </span>
46
- </Tooltip>
47
-
48
- <Table>
49
- <thead>
50
- <tr>
51
- <th>Joint</th>
52
- <th>Move (degrees)</th>
53
- </tr>
54
- </thead>
55
- <tbody>
56
- {#each positions as position, index (index)}
57
- {@const currentValue = currentDisplayPositions[index] ?? position}
58
- {@const unit = useRadians ? ' rad' : '°'}
59
- <tr>
60
- <th scope="row">{index}</th>
61
- <th>
62
- <div class="flex h-full max-h-6.5 w-full items-center justify-center gap-1.5">
63
- <Button
64
- aria-label="Decrease joint {index} by 5 degrees"
65
- disabled={isMoving}
66
- onclick={() => quickMove(index, -INCREMENT_DEGREES)}
67
- >
68
- −5°
69
- </Button>
70
- <span class="min-w-16 grow text-center text-xs text-gray-700 tabular-nums">
71
- {formatNumeric(currentValue)}{unit}
72
- </span>
73
- <Button
74
- aria-label="Increase joint {index} by 5 degrees"
75
- disabled={isMoving}
76
- onclick={() => quickMove(index, INCREMENT_DEGREES)}
77
- >
78
- +5°
79
- </Button>
80
- </div>
81
- </th>
82
- </tr>
83
- {/each}
84
- </tbody>
85
- </Table>
@@ -1,9 +0,0 @@
1
- interface Props {
2
- positions: number[];
3
- moveToJointPositions: (jointPositions: number[]) => void;
4
- useRadians: boolean;
5
- isMoving: boolean;
6
- }
7
- declare const JointPositionQuickMove: import("svelte").Component<Props, {}, "">;
8
- type JointPositionQuickMove = ReturnType<typeof JointPositionQuickMove>;
9
- export default JointPositionQuickMove;