1341
src/components/WaveformChart.test.ts
Normal file
1341
src/components/WaveformChart.test.ts
Normal file
File diff suppressed because it is too large
Load Diff
1046
src/components/WaveformChart.vue
Normal file
1046
src/components/WaveformChart.vue
Normal file
File diff suppressed because it is too large
Load Diff
59
src/components/annotation/WaveformAnnotationContextMenu.vue
Normal file
59
src/components/annotation/WaveformAnnotationContextMenu.vue
Normal file
@@ -0,0 +1,59 @@
|
||||
<script setup lang="ts">
|
||||
interface Props {
|
||||
visible: boolean
|
||||
x: number
|
||||
y: number
|
||||
canEdit: boolean
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
const emit = defineEmits<{
|
||||
(event: 'edit'): void
|
||||
(event: 'delete'): void
|
||||
(event: 'close'): void
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="props.visible && props.canEdit"
|
||||
class="waveform-annotation-context-menu"
|
||||
:style="{ left: `${props.x}px`, top: `${props.y}px` }"
|
||||
role="menu"
|
||||
@contextmenu.prevent
|
||||
>
|
||||
<button type="button" role="menuitem" @click="emit('edit')">编辑标注</button>
|
||||
<button type="button" role="menuitem" @click="emit('delete')">删除标注</button>
|
||||
<button type="button" role="menuitem" @click="emit('close')">取消</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.waveform-annotation-context-menu {
|
||||
position: absolute;
|
||||
z-index: 30;
|
||||
display: grid;
|
||||
min-width: 112px;
|
||||
padding: 4px;
|
||||
background: #fff;
|
||||
border: 1px solid #dfe5ef;
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 4px 14px rgb(16 24 40 / 16%);
|
||||
}
|
||||
|
||||
.waveform-annotation-context-menu button {
|
||||
padding: 7px 10px;
|
||||
color: #344054;
|
||||
font-size: 12px;
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
border-radius: 3px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.waveform-annotation-context-menu button:hover {
|
||||
background: #f2f4f7;
|
||||
}
|
||||
</style>
|
||||
519
src/components/annotation/WaveformAnnotationEditor.vue
Normal file
519
src/components/annotation/WaveformAnnotationEditor.vue
Normal file
@@ -0,0 +1,519 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, defineAsyncComponent, nextTick, ref, useId, watch } from 'vue'
|
||||
|
||||
import type { WaveformAnnotation } from '../../types'
|
||||
import { formatAnnotationTime, formatPlainNumber, type TimeUnit } from '../../utils'
|
||||
import { ANNOTATION_MAX_TEXT_LENGTH, resolveAnnotationStyle } from './markup'
|
||||
import type { AnnotationSeriesCandidate, AnnotationSeriesInfo } from './types'
|
||||
|
||||
const ColorPicker = defineAsyncComponent(async () => {
|
||||
await import('vue3-colorpicker/style.css')
|
||||
return (await import('vue3-colorpicker')).ColorPicker
|
||||
})
|
||||
|
||||
interface Props {
|
||||
annotation: WaveformAnnotation
|
||||
mode: 'add' | 'edit'
|
||||
series?: AnnotationSeriesInfo
|
||||
seriesOptions?: AnnotationSeriesCandidate[]
|
||||
timeUnit?: TimeUnit
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
timeUnit: 'ms',
|
||||
})
|
||||
const emit = defineEmits<{
|
||||
(event: 'confirm', annotation: WaveformAnnotation): void
|
||||
(event: 'cancel'): void
|
||||
(event: 'series-change', seriesId: string): void
|
||||
}>()
|
||||
|
||||
const textarea = ref<HTMLTextAreaElement>()
|
||||
const dialogTitleId = `waveform-annotation-editor-title-${useId()}`
|
||||
const text = ref('')
|
||||
const borderColor = ref('')
|
||||
const textColor = ref('')
|
||||
const backgroundColor = ref('')
|
||||
const canConfirm = computed(() => text.value.trim().length > 0)
|
||||
const characterCount = computed(() => text.value.length)
|
||||
const selectedSeries = computed(() => {
|
||||
const option = props.seriesOptions?.find(
|
||||
(candidate) => candidate.seriesId === props.annotation.seriesId,
|
||||
)
|
||||
return option
|
||||
? { id: option.seriesId, name: option.name, color: option.color, unit: option.unit }
|
||||
: props.series
|
||||
})
|
||||
|
||||
function hydrate() {
|
||||
const style = resolveAnnotationStyle(props.annotation.style)
|
||||
text.value = props.annotation.text
|
||||
borderColor.value = style.borderColor
|
||||
textColor.value = style.textColor
|
||||
backgroundColor.value = style.backgroundColor
|
||||
void nextTick(() => textarea.value?.focus())
|
||||
}
|
||||
|
||||
watch(() => props.annotation, hydrate, { immediate: true })
|
||||
|
||||
function confirm() {
|
||||
if (!canConfirm.value) return
|
||||
emit('confirm', {
|
||||
...props.annotation,
|
||||
text: text.value.trim(),
|
||||
style: {
|
||||
borderColor: borderColor.value,
|
||||
textColor: textColor.value,
|
||||
backgroundColor: backgroundColor.value.trim() || 'rgba(255, 255, 255, 0.92)',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function handleKeydown(event: KeyboardEvent) {
|
||||
if (event.key === 'Escape') emit('cancel')
|
||||
if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
|
||||
event.preventDefault()
|
||||
confirm()
|
||||
}
|
||||
}
|
||||
|
||||
function handleSeriesChange(event: Event) {
|
||||
const select = event.target as HTMLSelectElement
|
||||
if (select.value) emit('series-change', select.value)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="waveform-annotation-editor"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-labelledby="dialogTitleId"
|
||||
@click.self="emit('cancel')"
|
||||
>
|
||||
<section class="waveform-annotation-editor__panel">
|
||||
<header class="waveform-annotation-editor__header">
|
||||
<div>
|
||||
<h2 :id="dialogTitleId">
|
||||
{{ props.mode === 'add' ? '添加标注' : '编辑标注' }}
|
||||
</h2>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="waveform-annotation-editor__close"
|
||||
aria-label="关闭标注编辑器"
|
||||
title="关闭"
|
||||
@click="emit('cancel')"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div class="waveform-annotation-editor__coordinates" aria-label="标注坐标">
|
||||
<span
|
||||
><b>X ({{ props.timeUnit }})</b
|
||||
><code>{{ formatAnnotationTime(props.annotation.x, props.timeUnit) }}</code></span
|
||||
>
|
||||
<span
|
||||
><b>Y</b><code>{{ formatPlainNumber(props.annotation.y) }}</code></span
|
||||
>
|
||||
</div>
|
||||
|
||||
<label
|
||||
v-if="selectedSeries"
|
||||
class="waveform-annotation-editor__series"
|
||||
aria-label="标注所属波形"
|
||||
>
|
||||
<i :style="{ backgroundColor: selectedSeries.color }" aria-hidden="true" />
|
||||
<span class="waveform-annotation-editor__series-label">
|
||||
<small>标注波形</small>
|
||||
<b>{{ selectedSeries.name }}</b>
|
||||
</span>
|
||||
<select
|
||||
v-if="props.seriesOptions?.length"
|
||||
:value="props.annotation.seriesId"
|
||||
aria-label="选择标注波形"
|
||||
@change="handleSeriesChange"
|
||||
>
|
||||
<option
|
||||
v-for="candidate in props.seriesOptions"
|
||||
:key="candidate.seriesId"
|
||||
:value="candidate.seriesId"
|
||||
>
|
||||
{{ candidate.name }}{{ candidate.unit ? ` (${candidate.unit})` : '' }}
|
||||
</option>
|
||||
</select>
|
||||
<code v-else-if="selectedSeries.unit">{{ selectedSeries.unit }}</code>
|
||||
</label>
|
||||
|
||||
<label class="waveform-annotation-editor__field">
|
||||
<span class="waveform-annotation-editor__label-row">
|
||||
<b>标注文本</b>
|
||||
<small>{{ characterCount }}/{{ ANNOTATION_MAX_TEXT_LENGTH }}</small>
|
||||
</span>
|
||||
<textarea
|
||||
ref="textarea"
|
||||
v-model="text"
|
||||
rows="4"
|
||||
:maxlength="ANNOTATION_MAX_TEXT_LENGTH"
|
||||
aria-label="标注文本"
|
||||
placeholder="输入这处波形的说明"
|
||||
@keydown="handleKeydown"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<fieldset class="waveform-annotation-editor__colors">
|
||||
<legend>颜色与透明度</legend>
|
||||
<label class="waveform-annotation-editor__color-field" title="调整标注边框色和透明度">
|
||||
<span>边框色</span>
|
||||
<ColorPicker
|
||||
v-model:pure-color="borderColor"
|
||||
aria-label="标注边框色"
|
||||
use-type="pure"
|
||||
picker-type="chrome"
|
||||
format="rgb"
|
||||
:disable-alpha="false"
|
||||
:blur-close="true"
|
||||
/>
|
||||
</label>
|
||||
<label class="waveform-annotation-editor__color-field" title="调整标注文字色和透明度">
|
||||
<span>文字色</span>
|
||||
<ColorPicker
|
||||
v-model:pure-color="textColor"
|
||||
aria-label="标注文字色"
|
||||
use-type="pure"
|
||||
picker-type="chrome"
|
||||
format="rgb"
|
||||
:disable-alpha="false"
|
||||
:blur-close="true"
|
||||
/>
|
||||
</label>
|
||||
<label class="waveform-annotation-editor__color-field" title="调整标注背景色和透明度">
|
||||
<span>背景色</span>
|
||||
<ColorPicker
|
||||
v-model:pure-color="backgroundColor"
|
||||
aria-label="标注背景色"
|
||||
use-type="pure"
|
||||
picker-type="chrome"
|
||||
format="rgb"
|
||||
:disable-alpha="false"
|
||||
:blur-close="true"
|
||||
/>
|
||||
</label>
|
||||
</fieldset>
|
||||
|
||||
<footer class="waveform-annotation-editor__actions">
|
||||
<button type="button" @click="emit('cancel')">取消</button>
|
||||
<button type="button" class="is-primary" :disabled="!canConfirm" @click="confirm">
|
||||
保存标注
|
||||
</button>
|
||||
</footer>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.waveform-annotation-editor {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 40;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 20px;
|
||||
background: rgb(16 24 40 / 32%);
|
||||
animation: waveform-annotation-editor-fade-in 160ms ease-out;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__panel {
|
||||
display: grid;
|
||||
gap: 20px;
|
||||
width: min(440px, 100%);
|
||||
max-height: 100%;
|
||||
overflow-y: auto;
|
||||
padding: 22px;
|
||||
color: #344054;
|
||||
font-size: 13px;
|
||||
background: #fff;
|
||||
border: 1px solid #e4e7ec;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 20px 50px rgb(16 24 40 / 22%);
|
||||
animation: waveform-annotation-editor-rise-in 180ms ease-out;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__header h2 {
|
||||
margin: 0;
|
||||
color: #101828;
|
||||
font-size: 18px;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__header p {
|
||||
margin: 5px 0 0;
|
||||
color: #667085;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__close {
|
||||
display: inline-grid;
|
||||
flex: 0 0 30px;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
padding: 0;
|
||||
place-items: center;
|
||||
color: #667085;
|
||||
font-size: 22px;
|
||||
line-height: 1;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__close:hover {
|
||||
color: #101828;
|
||||
background: #f2f4f7;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__coordinates {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__coordinates span {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 9px 10px;
|
||||
color: #667085;
|
||||
background: #f8fafc;
|
||||
border: 1px solid #eaecf0;
|
||||
border-radius: 7px;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__coordinates b {
|
||||
color: #1677ff;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__coordinates code {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
color: #344054;
|
||||
font-family: 'SFMono-Regular', Consolas, monospace;
|
||||
font-size: 11px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__series {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 9px 10px;
|
||||
background: #f8fafc;
|
||||
border: 1px solid #eaecf0;
|
||||
border-radius: 7px;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__series i {
|
||||
flex: 0 0 12px;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border: 1px solid rgb(0 0 0 / 12%);
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__series-label {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
gap: 1px;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__series select {
|
||||
min-width: 0;
|
||||
max-width: 190px;
|
||||
margin-left: auto;
|
||||
padding: 5px 7px;
|
||||
color: #344054;
|
||||
font: inherit;
|
||||
background: #fff;
|
||||
border: 1px solid #d0d5dd;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__series small {
|
||||
color: #667085;
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__series b {
|
||||
overflow: hidden;
|
||||
color: #344054;
|
||||
font-size: 12px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__series code {
|
||||
margin-left: auto;
|
||||
color: #667085;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__field,
|
||||
.waveform-annotation-editor__color-field {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__label-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__label-row b,
|
||||
.waveform-annotation-editor__colors legend {
|
||||
color: #344054;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__label-row small {
|
||||
color: #98a2b3;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor textarea {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-height: 92px;
|
||||
padding: 10px 11px;
|
||||
color: #1d2939;
|
||||
font: inherit;
|
||||
line-height: 1.5;
|
||||
background: #fff;
|
||||
border: 1px solid #d0d5dd;
|
||||
border-radius: 7px;
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor textarea:focus {
|
||||
border-color: #1677ff;
|
||||
outline: 3px solid rgb(22 119 255 / 14%);
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__colors {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
padding: 14px 0 0;
|
||||
border: 0;
|
||||
border-top: 1px solid #eaecf0;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__colors legend {
|
||||
grid-column: 1 / -1;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__color-field {
|
||||
align-items: stretch;
|
||||
min-width: 0;
|
||||
justify-items: stretch;
|
||||
color: #667085;
|
||||
font-size: 11px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__color-field :deep(.vc-color-wrap) {
|
||||
width: 100%;
|
||||
height: 34px;
|
||||
margin-right: 0;
|
||||
border: 1px solid #cfd5df;
|
||||
border-radius: 6px;
|
||||
box-shadow: inset 0 0 0 1px rgb(255 255 255 / 38%);
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__color-field :deep(.vc-color-wrap:hover) {
|
||||
border-color: #98a2b3;
|
||||
box-shadow: 0 0 0 3px rgb(22 119 255 / 12%);
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
padding-top: 2px;
|
||||
border-top: 1px solid #eaecf0;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__actions button {
|
||||
height: 34px;
|
||||
padding: 0 12px;
|
||||
color: #475467;
|
||||
background: #fff;
|
||||
border: 1px solid #d0d5dd;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__actions button.is-primary {
|
||||
color: #fff;
|
||||
background: #1677ff;
|
||||
border-color: #1677ff;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__actions button:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
@keyframes waveform-annotation-editor-fade-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes waveform-annotation-editor-rise-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(8px) scale(0.98);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0) scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 420px) {
|
||||
.waveform-annotation-editor {
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__panel {
|
||||
gap: 16px;
|
||||
padding: 18px;
|
||||
}
|
||||
|
||||
.waveform-annotation-editor__coordinates {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
119
src/components/annotation/WaveformAnnotationLayer.vue
Normal file
119
src/components/annotation/WaveformAnnotationLayer.vue
Normal file
@@ -0,0 +1,119 @@
|
||||
<script setup lang="ts">
|
||||
import type { RenderedAnnotation } from './types'
|
||||
import { ANNOTATION_TEXT_FONT, ANNOTATION_TEXT_LINE_HEIGHT } from './markup'
|
||||
|
||||
interface Props {
|
||||
annotations: RenderedAnnotation[]
|
||||
visible: boolean
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
const emit = defineEmits<{
|
||||
(event: 'contextmenu', annotationId: string, mouseEvent: MouseEvent): void
|
||||
}>()
|
||||
|
||||
function handleContextMenu(annotationId: string, event: MouseEvent) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
emit('contextmenu', annotationId, event)
|
||||
}
|
||||
|
||||
function markerId(annotationId: string) {
|
||||
return `waveform-annotation-arrow-${annotationId.replace(/[^a-zA-Z0-9_-]/g, '-')}`
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<g v-if="props.visible" class="waveform-annotation-layer">
|
||||
<g
|
||||
v-for="rendered in props.annotations"
|
||||
:key="rendered.annotation.id"
|
||||
class="waveform-annotation"
|
||||
:data-annotation-id="rendered.annotation.id"
|
||||
:data-placement="rendered.placement"
|
||||
@contextmenu="handleContextMenu(rendered.annotation.id, $event)"
|
||||
>
|
||||
<defs>
|
||||
<marker
|
||||
:id="markerId(rendered.annotation.id)"
|
||||
markerWidth="8"
|
||||
markerHeight="8"
|
||||
refX="8"
|
||||
refY="4"
|
||||
orient="auto"
|
||||
markerUnits="userSpaceOnUse"
|
||||
>
|
||||
<path d="M0,0 L8,4 L0,8 Z" :fill="rendered.style.borderColor" />
|
||||
</marker>
|
||||
</defs>
|
||||
<line
|
||||
class="waveform-annotation__arrow"
|
||||
:x1="rendered.box.lineEndX"
|
||||
:y1="rendered.box.lineEndY"
|
||||
:x2="rendered.anchorX"
|
||||
:y2="rendered.anchorY"
|
||||
:stroke="rendered.style.borderColor"
|
||||
:marker-end="`url(#${markerId(rendered.annotation.id)})`"
|
||||
/>
|
||||
<rect
|
||||
class="waveform-annotation__box"
|
||||
:x="rendered.box.x"
|
||||
:y="rendered.box.y"
|
||||
:width="rendered.box.width"
|
||||
:height="rendered.box.height"
|
||||
:fill="rendered.style.backgroundColor"
|
||||
:stroke="rendered.style.borderColor"
|
||||
/>
|
||||
<text
|
||||
class="waveform-annotation__text"
|
||||
:x="rendered.box.x + rendered.box.width / 2"
|
||||
:y="
|
||||
rendered.box.y +
|
||||
rendered.box.height / 2 -
|
||||
((rendered.lines.length - 1) * ANNOTATION_TEXT_LINE_HEIGHT) / 2
|
||||
"
|
||||
:fill="rendered.style.textColor"
|
||||
:style="{ font: ANNOTATION_TEXT_FONT }"
|
||||
text-anchor="middle"
|
||||
dominant-baseline="central"
|
||||
>
|
||||
<tspan
|
||||
v-for="(line, index) in rendered.lines"
|
||||
:key="`${rendered.annotation.id}-${index}`"
|
||||
:x="rendered.box.x + rendered.box.width / 2"
|
||||
:dy="index === 0 ? 0 : ANNOTATION_TEXT_LINE_HEIGHT"
|
||||
>
|
||||
{{ line }}
|
||||
</tspan>
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.waveform-annotation-layer {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.waveform-annotation {
|
||||
pointer-events: auto;
|
||||
cursor: context-menu;
|
||||
}
|
||||
|
||||
.waveform-annotation__arrow {
|
||||
stroke-width: 2;
|
||||
stroke-linecap: round;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.waveform-annotation__box {
|
||||
stroke-width: 1;
|
||||
rx: 3;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.waveform-annotation__text {
|
||||
pointer-events: none;
|
||||
user-select: none;
|
||||
}
|
||||
</style>
|
||||
81
src/components/annotation/WaveformAnnotationToolbar.vue
Normal file
81
src/components/annotation/WaveformAnnotationToolbar.vue
Normal file
@@ -0,0 +1,81 @@
|
||||
<script setup lang="ts">
|
||||
import type { WaveformInteractionMode } from '../../types'
|
||||
|
||||
interface Props {
|
||||
interactionMode?: WaveformInteractionMode
|
||||
annotationsVisible: boolean
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
const emit = defineEmits<{
|
||||
(event: 'update:interaction-mode', mode: WaveformInteractionMode): void
|
||||
(event: 'update:annotations-visible', visible: boolean): void
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="waveform-annotation-toolbar" role="toolbar" aria-label="波形标注工具">
|
||||
<button
|
||||
type="button"
|
||||
:class="{ 'is-active': props.interactionMode === 'zoom' }"
|
||||
aria-label="缩放模式"
|
||||
title="缩放模式"
|
||||
@click="emit('update:interaction-mode', 'zoom')"
|
||||
>
|
||||
缩放
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
:class="{ 'is-active': props.interactionMode === 'annotation' }"
|
||||
aria-label="添加标注"
|
||||
title="添加标注"
|
||||
@click="emit('update:interaction-mode', 'annotation')"
|
||||
>
|
||||
标注
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
:class="{ 'is-active': props.annotationsVisible }"
|
||||
:aria-pressed="props.annotationsVisible"
|
||||
:aria-label="props.annotationsVisible ? '隐藏标注' : '显示标注'"
|
||||
title="显示/隐藏标注"
|
||||
@click="emit('update:annotations-visible', !props.annotationsVisible)"
|
||||
>
|
||||
{{ props.annotationsVisible ? '隐藏' : '显示' }}
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.waveform-annotation-toolbar {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
right: 8px;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
padding: 5px;
|
||||
background: #fff;
|
||||
border: 1px solid #dfe5ef;
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 2px 8px rgb(0 0 0 / 8%);
|
||||
}
|
||||
|
||||
.waveform-annotation-toolbar button {
|
||||
min-width: 42px;
|
||||
height: 28px;
|
||||
padding: 0 7px;
|
||||
color: #667085;
|
||||
font-size: 12px;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
border-radius: 3px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.waveform-annotation-toolbar button:hover,
|
||||
.waveform-annotation-toolbar button.is-active {
|
||||
color: #1677ff;
|
||||
background: #e6f4ff;
|
||||
}
|
||||
</style>
|
||||
229
src/components/annotation/components.test.ts
Normal file
229
src/components/annotation/components.test.ts
Normal file
@@ -0,0 +1,229 @@
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { ColorPicker } from 'vue3-colorpicker'
|
||||
|
||||
import WaveformAnnotationContextMenu from './WaveformAnnotationContextMenu.vue'
|
||||
import WaveformAnnotationEditor from './WaveformAnnotationEditor.vue'
|
||||
import WaveformAnnotationLayer from './WaveformAnnotationLayer.vue'
|
||||
import WaveformAnnotationToolbar from './WaveformAnnotationToolbar.vue'
|
||||
|
||||
describe('waveform annotation controls', () => {
|
||||
it('allows changing the annotation series inside the editor', async () => {
|
||||
const wrapper = mount(WaveformAnnotationEditor, {
|
||||
props: {
|
||||
annotation: { id: 'note', seriesId: 'a', x: 1, y: 2, text: '说明' },
|
||||
mode: 'edit',
|
||||
series: { id: 'a', name: '通道 A', color: '#f00', unit: 'V' },
|
||||
seriesOptions: [
|
||||
{
|
||||
trackIndex: 0,
|
||||
seriesId: 'a',
|
||||
name: '通道 A',
|
||||
color: '#f00',
|
||||
unit: 'V',
|
||||
point: { x: 1, y: 2 },
|
||||
screenX: 100,
|
||||
screenY: 50,
|
||||
distance: 0,
|
||||
xValue: 1,
|
||||
},
|
||||
{
|
||||
trackIndex: 1,
|
||||
seriesId: 'b',
|
||||
name: '通道 B',
|
||||
color: '#00f',
|
||||
unit: 'A',
|
||||
point: { x: 1, y: 3 },
|
||||
screenX: 100,
|
||||
screenY: 60,
|
||||
distance: 10,
|
||||
xValue: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
await flushPromises()
|
||||
|
||||
expect(
|
||||
(wrapper.get('select[aria-label="选择标注波形"]').element as HTMLSelectElement).value,
|
||||
).toBe('a')
|
||||
await wrapper.get('select[aria-label="选择标注波形"]').setValue('b')
|
||||
expect(wrapper.emitted('series-change')).toEqual([['b']])
|
||||
expect(wrapper.get('.waveform-annotation-editor__series').text()).toContain('通道 A')
|
||||
})
|
||||
|
||||
it('emits controlled toolbar changes', async () => {
|
||||
const wrapper = mount(WaveformAnnotationToolbar, {
|
||||
props: { interactionMode: 'zoom', annotationsVisible: true },
|
||||
})
|
||||
|
||||
await wrapper.get('button[aria-label="添加标注"]').trigger('click')
|
||||
await wrapper.get('button[aria-label="隐藏标注"]').trigger('click')
|
||||
|
||||
expect(wrapper.emitted('update:interaction-mode')).toEqual([['annotation']])
|
||||
expect(wrapper.emitted('update:annotations-visible')).toEqual([[false]])
|
||||
})
|
||||
|
||||
it('validates text and emits an immutable edited annotation with style defaults', async () => {
|
||||
const annotation = { id: 'note', seriesId: 'a', x: 1, y: 2, text: '' }
|
||||
const wrapper = mount(WaveformAnnotationEditor, {
|
||||
props: { annotation, mode: 'add' },
|
||||
})
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.get('textarea').attributes('maxlength')).toBe('40')
|
||||
expect(wrapper.get('.waveform-annotation-editor__coordinates').text()).toContain(
|
||||
'X (ms)1000.000',
|
||||
)
|
||||
expect(wrapper.get('.waveform-annotation-editor__coordinates').text()).toContain('Y2')
|
||||
expect(wrapper.get('button.is-primary').attributes('disabled')).toBeDefined()
|
||||
const colorPickers = wrapper.findAllComponents(ColorPicker)
|
||||
expect(colorPickers).toHaveLength(3)
|
||||
expect(wrapper.findAll('.waveform-annotation-editor__color-field')).toHaveLength(3)
|
||||
expect(colorPickers.map((picker) => picker.props('pureColor'))).toEqual([
|
||||
'#1677ff',
|
||||
'#333333',
|
||||
'rgba(255, 255, 255, 0.92)',
|
||||
])
|
||||
colorPickers.forEach((picker) => {
|
||||
expect(picker.props()).toMatchObject({
|
||||
useType: 'pure',
|
||||
pickerType: 'chrome',
|
||||
format: 'rgb',
|
||||
disableAlpha: false,
|
||||
blurClose: true,
|
||||
})
|
||||
})
|
||||
|
||||
await wrapper.get('textarea').setValue('新标注')
|
||||
colorPickers[0].vm.$emit('update:pureColor', 'rgba(22, 119, 255, 0.7)')
|
||||
colorPickers[1].vm.$emit('update:pureColor', 'rgba(51, 51, 51, 0.8)')
|
||||
colorPickers[2].vm.$emit('update:pureColor', 'rgba(255, 255, 255, 0.5)')
|
||||
await wrapper.vm.$nextTick()
|
||||
await wrapper.get('button.is-primary').trigger('click')
|
||||
|
||||
const emitted = wrapper.emitted('confirm')?.[0]?.[0] as
|
||||
| {
|
||||
text: string
|
||||
style?: { borderColor?: string; textColor?: string; backgroundColor?: string }
|
||||
}
|
||||
| undefined
|
||||
expect(emitted).toMatchObject({
|
||||
text: '新标注',
|
||||
style: {
|
||||
borderColor: 'rgba(22, 119, 255, 0.7)',
|
||||
textColor: 'rgba(51, 51, 51, 0.8)',
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.5)',
|
||||
},
|
||||
})
|
||||
expect(annotation.text).toBe('')
|
||||
})
|
||||
|
||||
it('formats annotation coordinates using the selected display context', () => {
|
||||
const wrapper = mount(WaveformAnnotationEditor, {
|
||||
props: {
|
||||
annotation: { id: 'note', seriesId: 'series', x: 1, y: 0.0000001, text: '说明' },
|
||||
mode: 'edit',
|
||||
timeUnit: 's',
|
||||
},
|
||||
})
|
||||
|
||||
const coordinates = wrapper.get('.waveform-annotation-editor__coordinates').text()
|
||||
expect(coordinates).toContain('X (s)1.000')
|
||||
expect(coordinates).toContain('Y0.0000001')
|
||||
expect(coordinates).not.toContain('e-')
|
||||
})
|
||||
|
||||
it('hydrates hexadecimal and rgba annotation colors', async () => {
|
||||
const wrapper = mount(WaveformAnnotationEditor, {
|
||||
props: {
|
||||
annotation: {
|
||||
id: 'colored-note',
|
||||
seriesId: 'a',
|
||||
x: 1,
|
||||
y: 2,
|
||||
text: '已有标注',
|
||||
style: {
|
||||
borderColor: '#ff0000',
|
||||
textColor: 'rgba(0, 0, 0, 0.75)',
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.4)',
|
||||
},
|
||||
},
|
||||
mode: 'edit',
|
||||
},
|
||||
})
|
||||
await flushPromises()
|
||||
|
||||
expect(
|
||||
wrapper.findAllComponents(ColorPicker).map((picker) => picker.props('pureColor')),
|
||||
).toEqual(['#ff0000', 'rgba(0, 0, 0, 0.75)', 'rgba(255, 255, 255, 0.4)'])
|
||||
})
|
||||
|
||||
it('supports modal dismissal and live character counting', async () => {
|
||||
const editor = mount(WaveformAnnotationEditor, {
|
||||
props: {
|
||||
annotation: { id: 'note', seriesId: 'a', x: 1, y: 2, text: '原文字' },
|
||||
mode: 'edit',
|
||||
},
|
||||
})
|
||||
|
||||
expect(editor.get('[role="dialog"]').attributes('aria-modal')).toBe('true')
|
||||
expect(editor.get('h2').text()).toBe('编辑标注')
|
||||
await editor.get('textarea').setValue('三字说明')
|
||||
expect(editor.get('.waveform-annotation-editor__label-row').text()).toContain('4/40')
|
||||
|
||||
await editor.get('textarea').trigger('keydown', { key: 'Escape' })
|
||||
await editor.get('.waveform-annotation-editor').trigger('click')
|
||||
expect(editor.emitted('cancel')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('supports cancellation and context menu actions', async () => {
|
||||
const editor = mount(WaveformAnnotationEditor, {
|
||||
props: {
|
||||
annotation: { id: 'note', seriesId: 'a', x: 1, y: 2, text: '原文字' },
|
||||
mode: 'edit',
|
||||
},
|
||||
})
|
||||
await editor.findAll('button')[0].trigger('click')
|
||||
expect(editor.emitted('cancel')).toHaveLength(1)
|
||||
|
||||
const menu = mount(WaveformAnnotationContextMenu, {
|
||||
props: { visible: true, x: 10, y: 20, canEdit: true },
|
||||
})
|
||||
await menu.findAll('button')[0].trigger('click')
|
||||
await menu.findAll('button')[1].trigger('click')
|
||||
expect(menu.emitted('edit')).toHaveLength(1)
|
||||
expect(menu.emitted('delete')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('centers single-line and multiline annotation text inside its box', () => {
|
||||
const wrapper = mount(WaveformAnnotationLayer, {
|
||||
props: {
|
||||
visible: true,
|
||||
annotations: [
|
||||
{
|
||||
annotation: { id: 'centered', seriesId: 'a', x: 1, y: 2, text: '第一行\n第二行' },
|
||||
trackIndex: 0,
|
||||
anchorX: 80,
|
||||
anchorY: 80,
|
||||
placement: 'top',
|
||||
lines: ['第一行', '第二行'],
|
||||
box: { x: 20, y: 20, width: 80, height: 42, lineEndX: 60, lineEndY: 62 },
|
||||
style: {
|
||||
borderColor: '#1677ff',
|
||||
textColor: '#333333',
|
||||
backgroundColor: '#ffffff',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
const text = wrapper.get('.waveform-annotation__text')
|
||||
expect(text.attributes('text-anchor')).toBe('middle')
|
||||
expect(text.attributes('dominant-baseline')).toBe('central')
|
||||
expect(text.attributes('x')).toBe('60')
|
||||
expect(text.attributes('y')).toBe('33')
|
||||
expect(wrapper.findAll('tspan').map((line) => line.attributes('x'))).toEqual(['60', '60'])
|
||||
})
|
||||
})
|
||||
6
src/components/annotation/index.ts
Normal file
6
src/components/annotation/index.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export { default as WaveformAnnotationLayer } from './WaveformAnnotationLayer.vue'
|
||||
export { default as WaveformAnnotationToolbar } from './WaveformAnnotationToolbar.vue'
|
||||
export { default as WaveformAnnotationContextMenu } from './WaveformAnnotationContextMenu.vue'
|
||||
export * from './markup'
|
||||
export * from './types'
|
||||
export * from './useWaveformAnnotationInteraction'
|
||||
229
src/components/annotation/markup.test.ts
Normal file
229
src/components/annotation/markup.test.ts
Normal file
@@ -0,0 +1,229 @@
|
||||
import { scaleLinear } from 'd3'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import type { WaveformAnnotation } from '../../types'
|
||||
import {
|
||||
ANNOTATION_TEXT_HORIZONTAL_PADDING,
|
||||
ANNOTATION_TEXT_PADDING,
|
||||
ANNOTATION_TEXT_VERTICAL_PADDING,
|
||||
findAnnotationSeriesCandidates,
|
||||
findNearestAnnotationPoint,
|
||||
interpolateAnnotationPoint,
|
||||
layoutAnnotations,
|
||||
resolveAnnotationStyle,
|
||||
wrapAnnotationText,
|
||||
} from './markup'
|
||||
import type { AnnotationTrackLayout } from './types'
|
||||
|
||||
const createTrack = (
|
||||
index: number,
|
||||
id: string,
|
||||
top: number,
|
||||
points: Array<{ x: number; y: number }>,
|
||||
height = 100,
|
||||
): AnnotationTrackLayout => ({
|
||||
index,
|
||||
series: { id, points },
|
||||
top,
|
||||
height,
|
||||
xScale: scaleLinear([0, 2], [0, 200]),
|
||||
yScale: scaleLinear([0, 10], [height, 0]),
|
||||
})
|
||||
|
||||
describe('waveform annotation markup', () => {
|
||||
it('interpolates a line value at the pointer X', () => {
|
||||
expect(interpolateAnnotationPoint([{ x: 0, y: 0 }, { x: 2, y: 10 }], 1)).toEqual({
|
||||
x: 1,
|
||||
y: 5,
|
||||
})
|
||||
expect(interpolateAnnotationPoint([{ x: 0, y: 0 }, { x: 2, y: 10 }], 3)).toBeNull()
|
||||
})
|
||||
|
||||
it('sorts line candidates by screen distance and keeps series metadata', () => {
|
||||
const first = createTrack(0, 'first', 0, [
|
||||
{ x: 0, y: 0 },
|
||||
{ x: 2, y: 10 },
|
||||
])
|
||||
first.series.name = '第一通道'
|
||||
first.series.color = '#f00'
|
||||
first.series.unit = 'V'
|
||||
const second = createTrack(1, 'second', 0, [
|
||||
{ x: 0, y: 4 },
|
||||
{ x: 2, y: 8 },
|
||||
])
|
||||
const candidates = findAnnotationSeriesCandidates([first, second], 1, 100, 50)
|
||||
|
||||
expect(candidates[0]).toMatchObject({
|
||||
seriesId: 'first',
|
||||
name: '第一通道',
|
||||
color: '#f00',
|
||||
unit: 'V',
|
||||
point: { x: 1, y: 5 },
|
||||
distance: 0,
|
||||
})
|
||||
expect(candidates[1].point).toEqual({ x: 1, y: 6 })
|
||||
})
|
||||
|
||||
it('uses equal horizontal and vertical annotation padding', () => {
|
||||
expect(ANNOTATION_TEXT_HORIZONTAL_PADDING).toBe(ANNOTATION_TEXT_PADDING)
|
||||
expect(ANNOTATION_TEXT_VERTICAL_PADDING).toBe(ANNOTATION_TEXT_PADDING)
|
||||
})
|
||||
|
||||
it('finds the closest visible sample across candidate tracks', () => {
|
||||
const hit = findNearestAnnotationPoint(
|
||||
[
|
||||
createTrack(0, 'a', 0, [
|
||||
{ x: 0, y: 1 },
|
||||
{ x: 1, y: 2 },
|
||||
]),
|
||||
createTrack(1, 'b', 100, [
|
||||
{ x: 0, y: 1 },
|
||||
{ x: 1, y: 8 },
|
||||
]),
|
||||
],
|
||||
100,
|
||||
120,
|
||||
12,
|
||||
)
|
||||
|
||||
expect(hit).toMatchObject({ seriesId: 'b', trackIndex: 1 })
|
||||
expect(hit?.point).toEqual({ x: 1, y: 8 })
|
||||
})
|
||||
|
||||
it('returns no hit outside the configured screen radius', () => {
|
||||
const hit = findNearestAnnotationPoint([createTrack(0, 'a', 0, [{ x: 1, y: 2 }])], 160, 10, 12)
|
||||
|
||||
expect(hit).toBeNull()
|
||||
})
|
||||
|
||||
it('wraps labels by Unicode characters and resolves style defaults', () => {
|
||||
expect(wrapAnnotationText('1234567890中文')).toEqual(['1234567890', '中文'])
|
||||
expect(resolveAnnotationStyle({ textColor: '#ffffff' })).toEqual({
|
||||
borderColor: '#1677ff',
|
||||
textColor: '#ffffff',
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.92)',
|
||||
})
|
||||
})
|
||||
|
||||
it('filters invalid entries and separates nearby annotation boxes', () => {
|
||||
const track = createTrack(0, 'a', 0, [
|
||||
{ x: 0, y: 1 },
|
||||
{ x: 1, y: 2 },
|
||||
], 300)
|
||||
const annotations: WaveformAnnotation[] = [
|
||||
{ id: 'first', seriesId: 'a', x: 1, y: 2, text: '第一个标注' },
|
||||
{ id: 'second', seriesId: 'a', x: 1, y: 2, text: '第二个标注' },
|
||||
{ id: 'unknown', seriesId: 'missing', x: 1, y: 2, text: '不显示' },
|
||||
{ id: 'invalid', seriesId: 'a', x: Number.NaN, y: 2, text: '不显示' },
|
||||
]
|
||||
|
||||
const rendered = layoutAnnotations(annotations, [track], 300, 300)
|
||||
|
||||
expect(rendered.map((item) => item.annotation.id)).toEqual(['first', 'second'])
|
||||
expect(rendered[0].box.lineEndX).toBe(rendered[0].anchorX)
|
||||
expect(rendered[0].box.lineEndY).not.toBe(rendered[0].anchorY)
|
||||
expect(rendered[0].placement).toBe('top')
|
||||
expect(rendered[0].box).not.toMatchObject({
|
||||
x: rendered[1].box.x,
|
||||
y: rendered[1].box.y,
|
||||
})
|
||||
rendered.forEach((item) => {
|
||||
expect(item.box.x).toBeGreaterThanOrEqual(0)
|
||||
expect(item.box.y).toBeGreaterThanOrEqual(0)
|
||||
expect(item.box.x + item.box.width).toBeLessThanOrEqual(300)
|
||||
expect(item.box.y + item.box.height).toBeLessThanOrEqual(300)
|
||||
})
|
||||
})
|
||||
|
||||
it('prefers centered vertical placements and moves below a top boundary', () => {
|
||||
const track = createTrack(0, 'a', 0, [
|
||||
{ x: 0, y: 0 },
|
||||
{ x: 1, y: 5 },
|
||||
], 200)
|
||||
|
||||
const centered = layoutAnnotations(
|
||||
[{ id: 'centered', seriesId: 'a', x: 1, y: 5, text: '居中' }],
|
||||
[track],
|
||||
200,
|
||||
200,
|
||||
)[0]
|
||||
expect(centered.placement).toBe('top')
|
||||
expect(centered.box.x + centered.box.width / 2).toBe(centered.anchorX)
|
||||
expect(centered.box.lineEndX).toBe(centered.anchorX)
|
||||
expect(centered.box.lineEndY).toBe(centered.box.y + centered.box.height)
|
||||
|
||||
const nearTop = layoutAnnotations(
|
||||
[{ id: 'top-edge', seriesId: 'a', x: 1, y: 9.5, text: '顶部' }],
|
||||
[track],
|
||||
200,
|
||||
200,
|
||||
)[0]
|
||||
expect(nearTop.placement).toBe('bottom')
|
||||
expect(nearTop.box.lineEndX).toBe(nearTop.anchorX)
|
||||
expect(nearTop.box.lineEndY).toBe(nearTop.box.y)
|
||||
expect(nearTop.box.height).toBe(30)
|
||||
expect(nearTop.box.lineEndY - nearTop.anchorY).toBe(32)
|
||||
})
|
||||
|
||||
it('reverses direction when the preferred placement is clipped by a boundary', () => {
|
||||
const track = createTrack(0, 'a', 0, [
|
||||
{ x: 0, y: 0 },
|
||||
{ x: 1, y: 5 },
|
||||
], 200)
|
||||
|
||||
const nearTop = layoutAnnotations(
|
||||
[{ id: 'top-space', seriesId: 'a', x: 1, y: 7.5, text: '顶部空间不足' }],
|
||||
[track],
|
||||
200,
|
||||
200,
|
||||
)[0]
|
||||
expect(nearTop.placement).toBe('bottom')
|
||||
expect(nearTop.box.y).toBeGreaterThanOrEqual(0)
|
||||
expect(nearTop.box.y + nearTop.box.height).toBeLessThanOrEqual(200)
|
||||
|
||||
const nearBottom = layoutAnnotations(
|
||||
[{ id: 'bottom-space', seriesId: 'a', x: 1, y: 0.5, text: '底部空间不足' }],
|
||||
[track],
|
||||
200,
|
||||
200,
|
||||
)[0]
|
||||
expect(nearBottom.placement).toBe('top')
|
||||
expect(nearBottom.box.y).toBeGreaterThanOrEqual(0)
|
||||
expect(nearBottom.box.y + nearBottom.box.height).toBeLessThanOrEqual(200)
|
||||
})
|
||||
|
||||
it('keeps a clipped fallback when the plot is smaller than the annotation box', () => {
|
||||
const track = createTrack(0, 'a', 0, [{ x: 1, y: 5 }])
|
||||
const rendered = layoutAnnotations(
|
||||
[{ id: 'tiny-plot', seriesId: 'a', x: 1, y: 5, text: '无法完整放置' }],
|
||||
[track],
|
||||
40,
|
||||
20,
|
||||
)[0]
|
||||
|
||||
expect(rendered).toBeDefined()
|
||||
expect(rendered.box.x).toBeGreaterThanOrEqual(0)
|
||||
expect(rendered.box.y).toBeGreaterThanOrEqual(0)
|
||||
})
|
||||
|
||||
it('uses later directional candidates when vertical candidates collide', () => {
|
||||
const track = createTrack(0, 'a', 0, [
|
||||
{ x: 0, y: 0 },
|
||||
{ x: 1, y: 5 },
|
||||
], 200)
|
||||
const rendered = layoutAnnotations(
|
||||
[
|
||||
{ id: 'one', seriesId: 'a', x: 1, y: 5, text: '同一位置一' },
|
||||
{ id: 'two', seriesId: 'a', x: 1, y: 5, text: '同一位置二' },
|
||||
],
|
||||
[track],
|
||||
200,
|
||||
200,
|
||||
)
|
||||
|
||||
expect(rendered[0].placement).toBe('top')
|
||||
expect(rendered[1].placement).not.toBe('top')
|
||||
expect(rendered[1].box).not.toMatchObject({ x: rendered[0].box.x, y: rendered[0].box.y })
|
||||
})
|
||||
|
||||
})
|
||||
435
src/components/annotation/markup.ts
Normal file
435
src/components/annotation/markup.ts
Normal file
@@ -0,0 +1,435 @@
|
||||
import { bisector } from 'd3'
|
||||
|
||||
import type { WaveformAnnotation, WaveformAnnotationStyle } from '../../types'
|
||||
import type {
|
||||
AnnotationBoxLayout,
|
||||
AnnotationHit,
|
||||
AnnotationPlacement,
|
||||
AnnotationSeriesCandidate,
|
||||
AnnotationTrackLayout,
|
||||
RenderedAnnotation,
|
||||
} from './types'
|
||||
|
||||
export const DEFAULT_ANNOTATION_STYLE = {
|
||||
borderColor: '#1677ff',
|
||||
textColor: '#333333',
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.92)',
|
||||
} as const
|
||||
|
||||
export const ANNOTATION_HIT_RADIUS = 12
|
||||
export const ANNOTATION_AMBIGUITY_DISTANCE = 5
|
||||
export const ANNOTATION_MAX_TEXT_LENGTH = 40
|
||||
export const ANNOTATION_TEXT_PADDING = 8
|
||||
export const ANNOTATION_BOX_MIN_WIDTH = ANNOTATION_TEXT_PADDING * 2
|
||||
export const ANNOTATION_BOX_MAX_WIDTH = 240
|
||||
export const ANNOTATION_BOX_MIN_HEIGHT = 26
|
||||
export const ANNOTATION_TEXT_HORIZONTAL_PADDING = ANNOTATION_TEXT_PADDING
|
||||
export const ANNOTATION_TEXT_VERTICAL_PADDING = ANNOTATION_TEXT_PADDING
|
||||
export const ANNOTATION_TEXT_LINE_HEIGHT = 16
|
||||
export const ANNOTATION_TEXT_GLYPH_HEIGHT = 14
|
||||
export const ANNOTATION_TEXT_FONT = '12px Arial, sans-serif'
|
||||
export const ANNOTATION_CONNECTOR_LENGTH = 32
|
||||
|
||||
const ANNOTATION_PLACEMENTS: AnnotationPlacement[] = [
|
||||
'top',
|
||||
'bottom',
|
||||
'right',
|
||||
'left',
|
||||
'top-right',
|
||||
'top-left',
|
||||
'bottom-right',
|
||||
'bottom-left',
|
||||
]
|
||||
|
||||
const pointBisector = bisector((point: { x: number }) => point.x)
|
||||
|
||||
export function interpolateAnnotationPoint(
|
||||
points: Array<{ x: number; y: number }>,
|
||||
xValue: number,
|
||||
): { x: number; y: number } | null {
|
||||
if (!points.length || !Number.isFinite(xValue)) return null
|
||||
const first = points[0]
|
||||
const last = points[points.length - 1]
|
||||
if (xValue < first.x || xValue > last.x) return null
|
||||
if (points.length === 1) return xValue === first.x ? { ...first } : null
|
||||
|
||||
const rightIndex = pointBisector.left(points, xValue)
|
||||
const right = points[Math.min(rightIndex, points.length - 1)]
|
||||
if (right.x === xValue || rightIndex === 0) return { x: xValue, y: right.y }
|
||||
|
||||
const left = points[rightIndex - 1]
|
||||
const xSpan = right.x - left.x
|
||||
if (xSpan === 0) return { x: xValue, y: right.y }
|
||||
const ratio = (xValue - left.x) / xSpan
|
||||
return { x: xValue, y: left.y + (right.y - left.y) * ratio }
|
||||
}
|
||||
|
||||
export function findAnnotationSeriesCandidates(
|
||||
tracks: AnnotationTrackLayout[],
|
||||
xValue: number,
|
||||
pointerX: number,
|
||||
pointerY: number,
|
||||
): AnnotationSeriesCandidate[] {
|
||||
return tracks
|
||||
.flatMap((track): AnnotationSeriesCandidate[] => {
|
||||
const point = interpolateAnnotationPoint(track.series.points, xValue)
|
||||
if (!point) return []
|
||||
const screenX = track.xScale(point.x)
|
||||
const screenY = track.top + track.yScale(point.y)
|
||||
return [
|
||||
{
|
||||
trackIndex: track.index,
|
||||
seriesId: track.series.id,
|
||||
name: track.series.name?.trim() || track.series.id,
|
||||
color: track.series.color || DEFAULT_ANNOTATION_STYLE.borderColor,
|
||||
unit: track.series.unit,
|
||||
point,
|
||||
screenX,
|
||||
screenY,
|
||||
distance: Math.hypot(screenX - pointerX, screenY - pointerY),
|
||||
xValue,
|
||||
},
|
||||
]
|
||||
})
|
||||
.sort((first, second) => first.distance - second.distance || first.trackIndex - second.trackIndex)
|
||||
}
|
||||
let annotationTextMeasurementContext: CanvasRenderingContext2D | null | undefined
|
||||
|
||||
function fallbackAnnotationTextWidth(text: string): number {
|
||||
return Array.from(text).reduce(
|
||||
(width, character) => width + (character.codePointAt(0)! > 0xff ? 12 : 6.7),
|
||||
0,
|
||||
)
|
||||
}
|
||||
|
||||
export function measureAnnotationTextWidth(text: string): number {
|
||||
if (annotationTextMeasurementContext === undefined) {
|
||||
annotationTextMeasurementContext = null
|
||||
if (typeof document !== 'undefined' && typeof CanvasRenderingContext2D !== 'undefined') {
|
||||
const canvas = document.createElement('canvas')
|
||||
annotationTextMeasurementContext = canvas.getContext('2d')
|
||||
if (annotationTextMeasurementContext) {
|
||||
annotationTextMeasurementContext.font = ANNOTATION_TEXT_FONT
|
||||
}
|
||||
}
|
||||
}
|
||||
return annotationTextMeasurementContext?.measureText(text).width ?? fallbackAnnotationTextWidth(text)
|
||||
}
|
||||
|
||||
export function resolveAnnotationStyle(style?: WaveformAnnotationStyle) {
|
||||
return {
|
||||
borderColor: style?.borderColor || DEFAULT_ANNOTATION_STYLE.borderColor,
|
||||
textColor: style?.textColor || DEFAULT_ANNOTATION_STYLE.textColor,
|
||||
backgroundColor: style?.backgroundColor || DEFAULT_ANNOTATION_STYLE.backgroundColor,
|
||||
}
|
||||
}
|
||||
|
||||
export function isFiniteAnnotation(annotation: WaveformAnnotation): boolean {
|
||||
return (
|
||||
Boolean(annotation.id && annotation.seriesId) &&
|
||||
Number.isFinite(annotation.x) &&
|
||||
Number.isFinite(annotation.y) &&
|
||||
typeof annotation.text === 'string' &&
|
||||
annotation.text.trim().length > 0
|
||||
)
|
||||
}
|
||||
|
||||
export function wrapAnnotationText(text: string, maxChars = 10): string[] {
|
||||
const lines: string[] = []
|
||||
text.split(/\r?\n/).forEach((paragraph) => {
|
||||
const chars = Array.from(paragraph)
|
||||
if (chars.length === 0) {
|
||||
lines.push('')
|
||||
return
|
||||
}
|
||||
for (let index = 0; index < chars.length; index += maxChars) {
|
||||
lines.push(chars.slice(index, index + maxChars).join(''))
|
||||
}
|
||||
})
|
||||
return lines.length ? lines : ['']
|
||||
}
|
||||
|
||||
export function findNearestAnnotationPoint(
|
||||
tracks: AnnotationTrackLayout[],
|
||||
pointerX: number,
|
||||
pointerY: number,
|
||||
maxDistance = ANNOTATION_HIT_RADIUS,
|
||||
): AnnotationHit | null {
|
||||
let closest: AnnotationHit | null = null
|
||||
|
||||
tracks.forEach((track) => {
|
||||
const localY = pointerY - track.top
|
||||
if (localY < 0 || localY > track.height || track.series.points.length === 0) return
|
||||
|
||||
const xValue = track.xScale.invert(pointerX)
|
||||
const centerIndex = pointBisector.center(track.series.points, xValue)
|
||||
const firstIndex = Math.max(0, centerIndex - 2)
|
||||
const lastIndex = Math.min(track.series.points.length - 1, centerIndex + 2)
|
||||
|
||||
for (let candidateIndex = firstIndex; candidateIndex <= lastIndex; candidateIndex += 1) {
|
||||
const point = track.series.points[candidateIndex]
|
||||
const screenX = track.xScale(point.x)
|
||||
const screenY = track.yScale(point.y) + track.top
|
||||
const distance = Math.hypot(screenX - pointerX, screenY - pointerY)
|
||||
if (distance > maxDistance || (closest && distance >= closest.distance)) continue
|
||||
closest = {
|
||||
trackIndex: track.index,
|
||||
seriesId: track.series.id,
|
||||
point,
|
||||
screenX,
|
||||
screenY,
|
||||
distance,
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return closest
|
||||
}
|
||||
|
||||
function isWithin(value: number, domain: [number, number]): boolean {
|
||||
return value >= Math.min(domain[0], domain[1]) && value <= Math.max(domain[0], domain[1])
|
||||
}
|
||||
|
||||
function overlaps(first: AnnotationBoxLayout, second: AnnotationBoxLayout): boolean {
|
||||
return (
|
||||
first.x < second.x + second.width &&
|
||||
first.x + first.width > second.x &&
|
||||
first.y < second.y + second.height &&
|
||||
first.y + first.height > second.y
|
||||
)
|
||||
}
|
||||
|
||||
function containsPoint(box: AnnotationBoxLayout, x: number, y: number): boolean {
|
||||
return x >= box.x && x <= box.x + box.width && y >= box.y && y <= box.y + box.height
|
||||
}
|
||||
|
||||
function clampBox(box: AnnotationBoxLayout, width: number, height: number): AnnotationBoxLayout {
|
||||
const x = Math.max(0, Math.min(box.x, Math.max(0, width - box.width)))
|
||||
const y = Math.max(0, Math.min(box.y, Math.max(0, height - box.height)))
|
||||
return {
|
||||
...box,
|
||||
x,
|
||||
y,
|
||||
lineEndX: Math.max(x, Math.min(box.lineEndX, x + box.width)),
|
||||
lineEndY: Math.max(y, Math.min(box.lineEndY, y + box.height)),
|
||||
}
|
||||
}
|
||||
|
||||
function resolveConnectorStart(
|
||||
box: AnnotationBoxLayout,
|
||||
anchorX: number,
|
||||
anchorY: number,
|
||||
): { x: number; y: number } {
|
||||
const centerX = box.x + box.width / 2
|
||||
const centerY = box.y + box.height / 2
|
||||
const deltaX = anchorX - centerX
|
||||
const deltaY = anchorY - centerY
|
||||
|
||||
if (Math.abs(deltaX) * box.height > Math.abs(deltaY) * box.width) {
|
||||
const x = deltaX >= 0 ? box.x + box.width : box.x
|
||||
const ratio = deltaX === 0 ? 0 : (x - centerX) / deltaX
|
||||
return {
|
||||
x,
|
||||
y: Math.max(box.y, Math.min(box.y + box.height, centerY + deltaY * ratio)),
|
||||
}
|
||||
}
|
||||
|
||||
const y = deltaY >= 0 ? box.y + box.height : box.y
|
||||
const ratio = deltaY === 0 ? 0 : (y - centerY) / deltaY
|
||||
return {
|
||||
x: Math.max(box.x, Math.min(box.x + box.width, centerX + deltaX * ratio)),
|
||||
y,
|
||||
}
|
||||
}
|
||||
|
||||
function boxPosition(
|
||||
anchorX: number,
|
||||
anchorY: number,
|
||||
width: number,
|
||||
height: number,
|
||||
placement: AnnotationPlacement,
|
||||
): { x: number; y: number } {
|
||||
const centeredX = anchorX - width / 2
|
||||
const centeredY = anchorY - height / 2
|
||||
const rightX = anchorX + ANNOTATION_CONNECTOR_LENGTH
|
||||
const leftX = anchorX - width - ANNOTATION_CONNECTOR_LENGTH
|
||||
const topY = anchorY - height - ANNOTATION_CONNECTOR_LENGTH
|
||||
const bottomY = anchorY + ANNOTATION_CONNECTOR_LENGTH
|
||||
|
||||
switch (placement) {
|
||||
case 'top':
|
||||
return { x: centeredX, y: topY }
|
||||
case 'bottom':
|
||||
return { x: centeredX, y: bottomY }
|
||||
case 'right':
|
||||
return { x: rightX, y: centeredY }
|
||||
case 'left':
|
||||
return { x: leftX, y: centeredY }
|
||||
case 'top-right':
|
||||
return { x: rightX, y: topY }
|
||||
case 'top-left':
|
||||
return { x: leftX, y: topY }
|
||||
case 'bottom-right':
|
||||
return { x: rightX, y: bottomY }
|
||||
case 'bottom-left':
|
||||
return { x: leftX, y: bottomY }
|
||||
}
|
||||
}
|
||||
|
||||
function annotationBoxSize(
|
||||
lines: string[],
|
||||
plotWidth: number,
|
||||
plotHeight: number,
|
||||
): { width: number; height: number } {
|
||||
return {
|
||||
width: Math.min(
|
||||
plotWidth,
|
||||
Math.max(
|
||||
ANNOTATION_BOX_MIN_WIDTH,
|
||||
Math.min(
|
||||
ANNOTATION_BOX_MAX_WIDTH,
|
||||
Math.ceil(Math.max(...lines.map(measureAnnotationTextWidth), 0)) +
|
||||
ANNOTATION_TEXT_PADDING * 2,
|
||||
),
|
||||
),
|
||||
),
|
||||
height: Math.min(
|
||||
plotHeight,
|
||||
Math.max(
|
||||
ANNOTATION_BOX_MIN_HEIGHT,
|
||||
(lines.length - 1) * ANNOTATION_TEXT_LINE_HEIGHT +
|
||||
ANNOTATION_TEXT_GLYPH_HEIGHT +
|
||||
ANNOTATION_TEXT_VERTICAL_PADDING * 2,
|
||||
),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
function isPlacementWithinBounds(
|
||||
anchorX: number,
|
||||
anchorY: number,
|
||||
lines: string[],
|
||||
plotWidth: number,
|
||||
plotHeight: number,
|
||||
placement: AnnotationPlacement,
|
||||
): boolean {
|
||||
const { width, height } = annotationBoxSize(lines, plotWidth, plotHeight)
|
||||
const position = boxPosition(anchorX, anchorY, width, height, placement)
|
||||
return (
|
||||
position.x >= 0 &&
|
||||
position.y >= 0 &&
|
||||
position.x + width <= plotWidth &&
|
||||
position.y + height <= plotHeight
|
||||
)
|
||||
}
|
||||
|
||||
export function layoutAnnotationBox(
|
||||
anchorX: number,
|
||||
anchorY: number,
|
||||
lines: string[],
|
||||
plotWidth: number,
|
||||
plotHeight: number,
|
||||
placement: AnnotationPlacement,
|
||||
): AnnotationBoxLayout {
|
||||
const { width, height } = annotationBoxSize(lines, plotWidth, plotHeight)
|
||||
const position = boxPosition(anchorX, anchorY, width, height, placement)
|
||||
const clamped = clampBox(
|
||||
{ x: position.x, y: position.y, width, height, lineEndX: anchorX, lineEndY: anchorY },
|
||||
plotWidth,
|
||||
plotHeight,
|
||||
)
|
||||
const connectorStart = resolveConnectorStart(clamped, anchorX, anchorY)
|
||||
return { ...clamped, lineEndX: connectorStart.x, lineEndY: connectorStart.y }
|
||||
}
|
||||
|
||||
export function layoutAnnotations(
|
||||
annotations: WaveformAnnotation[],
|
||||
tracks: AnnotationTrackLayout[],
|
||||
plotWidth: number,
|
||||
plotHeight: number,
|
||||
): RenderedAnnotation[] {
|
||||
const placedByTrack = new Map<number, AnnotationBoxLayout[]>()
|
||||
const rendered: RenderedAnnotation[] = []
|
||||
|
||||
annotations.forEach((annotation) => {
|
||||
if (!isFiniteAnnotation(annotation)) return
|
||||
const track = tracks.find((candidate) => candidate.series.id === annotation.seriesId)
|
||||
if (!track) return
|
||||
const xDomain = track.xScale.domain() as [number, number]
|
||||
const yDomain = track.yScale.domain() as [number, number]
|
||||
if (!isWithin(annotation.x, xDomain) || !isWithin(annotation.y, yDomain)) return
|
||||
|
||||
const lines = wrapAnnotationText(annotation.text)
|
||||
const trackLeft = track.left ?? 0
|
||||
const trackWidth = track.width ?? plotWidth
|
||||
const localAnchorX = track.xScale(annotation.x)
|
||||
const anchorX = trackLeft + localAnchorX
|
||||
const anchorY = track.yScale(annotation.y) + track.top
|
||||
const localHeight = Math.min(track.height, Math.max(0, plotHeight - track.top))
|
||||
const localAnchorY = anchorY - track.top
|
||||
const placed = placedByTrack.get(track.index) || []
|
||||
let placement = ANNOTATION_PLACEMENTS[0]
|
||||
let box = layoutAnnotationBox(
|
||||
localAnchorX,
|
||||
localAnchorY,
|
||||
lines,
|
||||
trackWidth,
|
||||
localHeight,
|
||||
placement,
|
||||
)
|
||||
for (const candidatePlacement of ANNOTATION_PLACEMENTS) {
|
||||
if (
|
||||
!isPlacementWithinBounds(
|
||||
localAnchorX,
|
||||
localAnchorY,
|
||||
lines,
|
||||
trackWidth,
|
||||
localHeight,
|
||||
candidatePlacement,
|
||||
)
|
||||
) {
|
||||
continue
|
||||
}
|
||||
const candidate = layoutAnnotationBox(
|
||||
localAnchorX,
|
||||
localAnchorY,
|
||||
lines,
|
||||
trackWidth,
|
||||
localHeight,
|
||||
candidatePlacement,
|
||||
)
|
||||
if (
|
||||
!containsPoint(candidate, localAnchorX, localAnchorY) &&
|
||||
!placed.some((item) => overlaps(candidate, item))
|
||||
) {
|
||||
box = candidate
|
||||
placement = candidatePlacement
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
const globalBox = {
|
||||
...box,
|
||||
x: box.x + trackLeft,
|
||||
y: box.y + track.top,
|
||||
lineEndX: box.lineEndX + trackLeft,
|
||||
lineEndY: box.lineEndY + track.top,
|
||||
}
|
||||
placed.push(box)
|
||||
placedByTrack.set(track.index, placed)
|
||||
rendered.push({
|
||||
annotation,
|
||||
trackIndex: track.index,
|
||||
anchorX,
|
||||
anchorY,
|
||||
placement,
|
||||
lines,
|
||||
box: {
|
||||
...globalBox,
|
||||
},
|
||||
style: resolveAnnotationStyle(annotation.style),
|
||||
})
|
||||
})
|
||||
|
||||
return rendered
|
||||
}
|
||||
100
src/components/annotation/types.ts
Normal file
100
src/components/annotation/types.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
import type { ScaleLinear } from 'd3'
|
||||
|
||||
import type { WaveformAnnotation, WaveformPoint } from '../../types'
|
||||
|
||||
export interface AnnotationTrackLayout {
|
||||
index: number
|
||||
series: {
|
||||
id: string
|
||||
name?: string
|
||||
color?: string
|
||||
unit?: string
|
||||
points: WaveformPoint[]
|
||||
}
|
||||
left?: number
|
||||
top: number
|
||||
width?: number
|
||||
height: number
|
||||
xScale: ScaleLinear<number, number>
|
||||
yScale: ScaleLinear<number, number>
|
||||
}
|
||||
|
||||
export interface AnnotationHit {
|
||||
trackIndex: number
|
||||
seriesId: string
|
||||
point: WaveformPoint
|
||||
screenX: number
|
||||
screenY: number
|
||||
distance: number
|
||||
/** Data-space X under the pointer; omitted for snapped sample hits. */
|
||||
xValue?: number
|
||||
}
|
||||
|
||||
export interface AnnotationSeriesCandidate extends AnnotationHit {
|
||||
name: string
|
||||
color: string
|
||||
unit?: string
|
||||
}
|
||||
|
||||
export interface AnnotationEditorAnchor {
|
||||
x: number
|
||||
y: number
|
||||
}
|
||||
|
||||
export interface AnnotationBoxLayout {
|
||||
x: number
|
||||
y: number
|
||||
width: number
|
||||
height: number
|
||||
lineEndX: number
|
||||
lineEndY: number
|
||||
}
|
||||
|
||||
export type AnnotationPlacement =
|
||||
| 'top'
|
||||
| 'bottom'
|
||||
| 'right'
|
||||
| 'left'
|
||||
| 'top-right'
|
||||
| 'top-left'
|
||||
| 'bottom-right'
|
||||
| 'bottom-left'
|
||||
|
||||
export interface RenderedAnnotation {
|
||||
annotation: WaveformAnnotation
|
||||
trackIndex: number
|
||||
anchorX: number
|
||||
anchorY: number
|
||||
placement: AnnotationPlacement
|
||||
lines: string[]
|
||||
box: AnnotationBoxLayout
|
||||
style: {
|
||||
borderColor: string
|
||||
textColor: string
|
||||
backgroundColor: string
|
||||
}
|
||||
}
|
||||
|
||||
export type AnnotationEditorDraft =
|
||||
| { mode: 'add'; annotation: WaveformAnnotation; anchor: AnnotationEditorAnchor }
|
||||
| {
|
||||
mode: 'edit'
|
||||
annotation: WaveformAnnotation
|
||||
previous: WaveformAnnotation
|
||||
anchor: AnnotationEditorAnchor
|
||||
}
|
||||
|
||||
export interface AnnotationContextMenuState {
|
||||
x: number
|
||||
y: number
|
||||
annotationId?: string
|
||||
createHit?: AnnotationHit
|
||||
editorAnchor?: AnnotationEditorAnchor
|
||||
}
|
||||
|
||||
export interface AnnotationSeriesInfo {
|
||||
id: string
|
||||
name: string
|
||||
color: string
|
||||
unit?: string
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { ref } from 'vue'
|
||||
|
||||
import type { WaveformAnnotation } from '../../types'
|
||||
import type {
|
||||
AnnotationContextMenuState,
|
||||
AnnotationEditorAnchor,
|
||||
AnnotationEditorDraft,
|
||||
AnnotationHit,
|
||||
} from './types'
|
||||
|
||||
export function useWaveformAnnotationInteraction() {
|
||||
const editorDraft = ref<AnnotationEditorDraft | null>(null)
|
||||
const contextMenu = ref<AnnotationContextMenuState | null>(null)
|
||||
|
||||
const openCreate = (
|
||||
hit: AnnotationHit,
|
||||
createId: () => string,
|
||||
anchor: AnnotationEditorAnchor,
|
||||
) => {
|
||||
editorDraft.value = {
|
||||
mode: 'add',
|
||||
annotation: {
|
||||
id: createId(),
|
||||
seriesId: hit.seriesId,
|
||||
x: hit.xValue ?? hit.point.x,
|
||||
y: hit.point.y,
|
||||
text: '',
|
||||
createdAt: new Date().toISOString(),
|
||||
},
|
||||
anchor,
|
||||
}
|
||||
contextMenu.value = null
|
||||
}
|
||||
|
||||
const openEdit = (annotation: WaveformAnnotation, anchor: AnnotationEditorAnchor) => {
|
||||
editorDraft.value = {
|
||||
mode: 'edit',
|
||||
annotation: { ...annotation },
|
||||
previous: { ...annotation },
|
||||
anchor,
|
||||
}
|
||||
contextMenu.value = null
|
||||
}
|
||||
|
||||
const openContextMenu = (state: AnnotationContextMenuState) => {
|
||||
contextMenu.value = state
|
||||
}
|
||||
|
||||
const closeEditor = () => {
|
||||
editorDraft.value = null
|
||||
}
|
||||
|
||||
const closeContextMenu = () => {
|
||||
contextMenu.value = null
|
||||
}
|
||||
|
||||
return {
|
||||
editorDraft,
|
||||
contextMenu,
|
||||
openCreate,
|
||||
openEdit,
|
||||
openContextMenu,
|
||||
closeEditor,
|
||||
closeContextMenu,
|
||||
}
|
||||
}
|
||||
23
src/components/core/constants.ts
Normal file
23
src/components/core/constants.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* 核心常量定义
|
||||
*/
|
||||
|
||||
/** 通道颜色 */
|
||||
export const channelColors = [
|
||||
'#0960bd',
|
||||
'#ff7f0e',
|
||||
'#389e0d',
|
||||
'#cf1322',
|
||||
'#531dab',
|
||||
'#08979c',
|
||||
'#c41d7f',
|
||||
'#434343',
|
||||
'#7cb305',
|
||||
'#1d39c4',
|
||||
]
|
||||
|
||||
/** 图表边距 */
|
||||
export const margin = { top: 18, right: 24, bottom: 52, left: 64 }
|
||||
|
||||
/** 最小高度 */
|
||||
export const minimumHeight = 180
|
||||
59
src/components/core/grid.test.ts
Normal file
59
src/components/core/grid.test.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
getBottomRowCellIndexes,
|
||||
getPageCount,
|
||||
normalizeGridOptions,
|
||||
paginateSeries,
|
||||
resolveGridCellGeometry,
|
||||
X_AXIS_BAND,
|
||||
} from './grid'
|
||||
|
||||
describe('waveform grid helpers', () => {
|
||||
it('normalizes grid counts and uses a two by one default', () => {
|
||||
expect(normalizeGridOptions()).toEqual({ rowCount: 2, columnCount: 1, showPagination: true })
|
||||
expect(normalizeGridOptions({ rowCount: 0, columnCount: 99 })).toEqual({
|
||||
rowCount: 1,
|
||||
columnCount: 10,
|
||||
showPagination: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('paginates row-major slots and keeps at least one page for empty data', () => {
|
||||
const options = normalizeGridOptions({ rowCount: 2, columnCount: 2 })
|
||||
expect(getPageCount([1, 2, 3, 4, 5].length, options)).toBe(2)
|
||||
expect(paginateSeries([1, 2, 3, 4, 5], 2, options)).toEqual([5])
|
||||
expect(getPageCount(0, options)).toBe(1)
|
||||
})
|
||||
|
||||
it('resolves mode-specific gaps and bottom cells', () => {
|
||||
const options = normalizeGridOptions({ rowCount: 2, columnCount: 2 })
|
||||
const separated = resolveGridCellGeometry(400, 200, options, 'separated', [true, true, true, true])
|
||||
const compact = resolveGridCellGeometry(400, 200, options, 'compact', [true, true, true, true])
|
||||
const independent = resolveGridCellGeometry(400, 200, options, 'independent', [true, true, false, false])
|
||||
expect(separated[1].left).toBeGreaterThan(separated[0].left + separated[0].width)
|
||||
expect(separated[2].top).toBe(separated[0].plotHeight + 16)
|
||||
expect(separated[2].xAxisBand).toBe(X_AXIS_BAND)
|
||||
expect(compact[2].top).toBe(compact[0].top + compact[0].plotHeight)
|
||||
expect(compact[2].xAxisBand).toBe(X_AXIS_BAND)
|
||||
expect(independent[2].top).toBe(
|
||||
independent[0].top + independent[0].plotHeight + X_AXIS_BAND + 14,
|
||||
)
|
||||
expect(independent[0].cellHeight).toBe(independent[0].plotHeight + X_AXIS_BAND)
|
||||
expect(
|
||||
getBottomRowCellIndexes(
|
||||
separated.map((cell, index) => ({ ...cell, hasSeries: index !== 3 })),
|
||||
2,
|
||||
),
|
||||
).toEqual(new Set([2, 1]))
|
||||
})
|
||||
|
||||
it('accepts an independent horizontal gap without changing vertical spacing', () => {
|
||||
const options = normalizeGridOptions({ rowCount: 2, columnCount: 2 })
|
||||
const cells = resolveGridCellGeometry(400, 200, options, 'independent', [true, true, true, true], 64)
|
||||
|
||||
expect(cells[0].width).toBe(168)
|
||||
expect(cells[1].left).toBe(232)
|
||||
expect(cells[2].top).toBe(cells[0].plotHeight + X_AXIS_BAND + 14)
|
||||
})
|
||||
})
|
||||
139
src/components/core/grid.ts
Normal file
139
src/components/core/grid.ts
Normal file
@@ -0,0 +1,139 @@
|
||||
import type { WaveformDisplayMode } from '../../types'
|
||||
|
||||
export const GRID_MIN_COUNT = 1
|
||||
export const GRID_MAX_COUNT = 10
|
||||
export const X_AXIS_BAND = 16
|
||||
|
||||
export interface WaveformGridOptions {
|
||||
rowCount?: number
|
||||
columnCount?: number
|
||||
showPagination?: boolean
|
||||
}
|
||||
|
||||
export interface NormalizedWaveformGridOptions {
|
||||
rowCount: number
|
||||
columnCount: number
|
||||
showPagination: boolean
|
||||
}
|
||||
|
||||
export interface GridCellGeometry {
|
||||
slotIndex: number
|
||||
row: number
|
||||
column: number
|
||||
left: number
|
||||
top: number
|
||||
width: number
|
||||
/** Backward-compatible alias for the actual plot height. */
|
||||
height: number
|
||||
plotHeight: number
|
||||
cellHeight: number
|
||||
xAxisBand: number
|
||||
}
|
||||
|
||||
const normalizeCount = (value: unknown, fallback: number) => {
|
||||
const numeric = typeof value === 'number' ? value : Number(value)
|
||||
if (!Number.isFinite(numeric)) return fallback
|
||||
return Math.min(GRID_MAX_COUNT, Math.max(GRID_MIN_COUNT, Math.floor(numeric)))
|
||||
}
|
||||
|
||||
export function normalizeGridOptions(options?: WaveformGridOptions): NormalizedWaveformGridOptions {
|
||||
return {
|
||||
rowCount: normalizeCount(options?.rowCount, 2),
|
||||
columnCount: normalizeCount(options?.columnCount, 1),
|
||||
showPagination: options?.showPagination ?? true,
|
||||
}
|
||||
}
|
||||
|
||||
export function getPageSize(options: NormalizedWaveformGridOptions): number {
|
||||
return options.rowCount * options.columnCount
|
||||
}
|
||||
|
||||
export function getPageCount(seriesCount: number, options: NormalizedWaveformGridOptions): number {
|
||||
return Math.max(1, Math.ceil(Math.max(0, seriesCount) / getPageSize(options)))
|
||||
}
|
||||
|
||||
export function paginateSeries<T>(
|
||||
series: T[],
|
||||
page: number,
|
||||
options: NormalizedWaveformGridOptions,
|
||||
): T[] {
|
||||
const pageCount = getPageCount(series.length, options)
|
||||
const safePage = Math.min(pageCount, Math.max(1, Math.floor(page)))
|
||||
const start = (safePage - 1) * getPageSize(options)
|
||||
return series.slice(start, start + getPageSize(options))
|
||||
}
|
||||
|
||||
export function getGridGap(displayMode: WaveformDisplayMode): number {
|
||||
return displayMode === 'compact' ? 0 : displayMode === 'separated' ? 16 : 14
|
||||
}
|
||||
|
||||
export function resolveGridCellGeometry(
|
||||
innerWidth: number,
|
||||
innerHeight: number,
|
||||
options: NormalizedWaveformGridOptions,
|
||||
displayMode: WaveformDisplayMode,
|
||||
slotHasSeries: boolean[] = [],
|
||||
horizontalGap?: number,
|
||||
): GridCellGeometry[] {
|
||||
const defaultGap = getGridGap(displayMode)
|
||||
const columnGap = Number.isFinite(horizontalGap) ? Math.max(0, horizontalGap as number) : defaultGap
|
||||
const totalHorizontalGap = Math.max(0, options.columnCount - 1) * columnGap
|
||||
const axisRows = new Set<number>()
|
||||
if (displayMode === 'independent') {
|
||||
for (let row = 0; row < options.rowCount; row += 1) axisRows.add(row)
|
||||
} else {
|
||||
for (let column = 0; column < options.columnCount; column += 1) {
|
||||
for (let slotIndex = getPageSize(options) - 1; slotIndex >= 0; slotIndex -= 1) {
|
||||
if (slotIndex % options.columnCount !== column) continue
|
||||
if (slotHasSeries[slotIndex]) {
|
||||
axisRows.add(Math.floor(slotIndex / options.columnCount))
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const totalVerticalGap = Math.max(0, options.rowCount - 1) * defaultGap
|
||||
const totalAxisBand = axisRows.size * X_AXIS_BAND
|
||||
const width = Math.max(1, (innerWidth - totalHorizontalGap) / options.columnCount)
|
||||
const plotHeight = Math.max(1, (innerHeight - totalVerticalGap - totalAxisBand) / options.rowCount)
|
||||
|
||||
return Array.from({ length: getPageSize(options) }, (_, slotIndex) => {
|
||||
const row = Math.floor(slotIndex / options.columnCount)
|
||||
const column = slotIndex % options.columnCount
|
||||
const xAxisBand = axisRows.has(row) ? X_AXIS_BAND : 0
|
||||
const cellHeight = plotHeight + xAxisBand
|
||||
const top = Array.from({ length: row }, (_, previousRow) => {
|
||||
const previousBand = axisRows.has(previousRow) ? X_AXIS_BAND : 0
|
||||
return plotHeight + previousBand + defaultGap
|
||||
}).reduce((sum, value) => sum + value, 0)
|
||||
return {
|
||||
slotIndex,
|
||||
row,
|
||||
column,
|
||||
left: column * (width + columnGap),
|
||||
top,
|
||||
width,
|
||||
height: plotHeight,
|
||||
plotHeight,
|
||||
cellHeight,
|
||||
xAxisBand,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function getBottomRowCellIndexes(
|
||||
cells: Array<GridCellGeometry & { hasSeries?: boolean }>,
|
||||
columnCount: number,
|
||||
): Set<number> {
|
||||
const visible = new Set<number>()
|
||||
for (let column = 0; column < columnCount; column += 1) {
|
||||
for (let index = cells.length - 1; index >= 0; index -= 1) {
|
||||
const cell = cells[index]
|
||||
if (cell.column === column && cell.hasSeries) {
|
||||
visible.add(cell.slotIndex)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return visible
|
||||
}
|
||||
5
src/components/core/index.ts
Normal file
5
src/components/core/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export * from './constants'
|
||||
export * from './grid'
|
||||
export * from './layout'
|
||||
export * from './types'
|
||||
export * from './useWaveformData'
|
||||
95
src/components/core/layout.ts
Normal file
95
src/components/core/layout.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import { line, scaleLinear, zoomIdentity, type ZoomTransform } from 'd3'
|
||||
|
||||
import { selectRenderablePoints, type ResolvedWaveformRenderingOptions } from '../../core'
|
||||
import type { WaveformDisplayMode, WaveformPoint } from '../../types'
|
||||
import { buildMinorTicks, formatEndpointTime } from '../../utils'
|
||||
import {
|
||||
getBottomRowCellIndexes,
|
||||
type GridCellGeometry,
|
||||
type NormalizedWaveformGridOptions,
|
||||
} from './grid'
|
||||
import type { DisplaySeries, TrackLayout } from './types'
|
||||
|
||||
interface SeriesGridCell extends GridCellGeometry {
|
||||
series?: DisplaySeries
|
||||
}
|
||||
|
||||
export interface BuildTrackLayoutsOptions {
|
||||
cells: SeriesGridCell[]
|
||||
grid: NormalizedWaveformGridOptions
|
||||
displayMode: WaveformDisplayMode
|
||||
independentTransforms: ZoomTransform[]
|
||||
sharedZoomDomain: [number, number]
|
||||
timeUnit: 's' | 'ms'
|
||||
rendering: ResolvedWaveformRenderingOptions
|
||||
hideSecondaryLabels: boolean
|
||||
yAxisLabelX: number
|
||||
}
|
||||
|
||||
export function buildTrackLayouts(options: BuildTrackLayoutsOptions): TrackLayout[] {
|
||||
const visibleCells = options.cells.map((cell) => ({ ...cell, hasSeries: Boolean(cell.series) }))
|
||||
const bottomCells = getBottomRowCellIndexes(visibleCells, options.grid.columnCount)
|
||||
|
||||
return visibleCells.flatMap((cell, index) => {
|
||||
const series = cell.series
|
||||
if (!series) return []
|
||||
const baseXScale =
|
||||
options.displayMode === 'independent'
|
||||
? scaleLinear(series.xDomain, [0, cell.width])
|
||||
: scaleLinear(options.sharedZoomDomain, [0, cell.width])
|
||||
const transform =
|
||||
options.displayMode === 'independent'
|
||||
? (options.independentTransforms[index] ?? zoomIdentity)
|
||||
: zoomIdentity
|
||||
const xScale = transform.rescaleX(baseXScale)
|
||||
const yScale = scaleLinear(series.yDomain, [cell.plotHeight, 0]).nice()
|
||||
const xMajorTicks = xScale.ticks(Math.max(2, Math.floor(cell.width / 100)))
|
||||
const yMajorTicks = yScale.ticks(Math.max(2, Math.floor(cell.plotHeight / 55)))
|
||||
const yAxisTickValues =
|
||||
options.displayMode === 'compact' && cell.row < options.grid.rowCount - 1
|
||||
? yMajorTicks.slice(1)
|
||||
: yMajorTicks
|
||||
const domain = xScale.domain() as [number, number]
|
||||
const endpointLabels = {
|
||||
start: formatEndpointTime(domain[0], domain, options.timeUnit),
|
||||
end: formatEndpointTime(domain[1], domain, options.timeUnit),
|
||||
}
|
||||
const leftClearance = endpointLabels.start.length * 7 + 10
|
||||
const rightClearance = endpointLabels.end.length * 7 + 10
|
||||
const xAxisTickValues = xMajorTicks.filter((tick) => {
|
||||
const position = xScale(tick)
|
||||
return position > leftClearance && position < cell.width - rightClearance
|
||||
})
|
||||
const renderPoints = selectRenderablePoints(
|
||||
series.points,
|
||||
domain,
|
||||
cell.width,
|
||||
options.rendering,
|
||||
)
|
||||
|
||||
return {
|
||||
index,
|
||||
series,
|
||||
column: cell.column,
|
||||
showYAxisLabel: !options.hideSecondaryLabels || cell.column === 0,
|
||||
yAxisLabelX: options.yAxisLabelX,
|
||||
left: cell.left,
|
||||
top: cell.top,
|
||||
width: cell.width,
|
||||
height: cell.plotHeight,
|
||||
xScale,
|
||||
yScale,
|
||||
xMajorTicks,
|
||||
xMinorTicks: buildMinorTicks(xMajorTicks),
|
||||
yMajorTicks,
|
||||
yMinorTicks: buildMinorTicks(yMajorTicks),
|
||||
yAxisTickValues,
|
||||
xAxisTickValues,
|
||||
endpointLabels,
|
||||
path: line<WaveformPoint>()
|
||||
.x((point) => xScale(point.x))
|
||||
.y((point) => yScale(point.y))(renderPoints),
|
||||
showXAxis: options.displayMode === 'independent' || bottomCells.has(cell.slotIndex),
|
||||
}
|
||||
})
|
||||
}
|
||||
52
src/components/core/types.ts
Normal file
52
src/components/core/types.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import type { ScaleLinear } from 'd3'
|
||||
import type { WaveformPoint } from '../../types'
|
||||
|
||||
/**
|
||||
* 显示系列
|
||||
*/
|
||||
export interface DisplaySeries {
|
||||
id: string
|
||||
name: string
|
||||
unit?: string
|
||||
color: string
|
||||
points: WaveformPoint[]
|
||||
xDomain: [number, number]
|
||||
yDomain: [number, number]
|
||||
}
|
||||
|
||||
/**
|
||||
* 悬浮的系列点
|
||||
*/
|
||||
export interface HoveredSeriesPoint extends DisplaySeries {
|
||||
trackIndex: number
|
||||
point: WaveformPoint
|
||||
}
|
||||
|
||||
/**
|
||||
* 轨道布局
|
||||
*/
|
||||
export interface TrackLayout {
|
||||
index: number
|
||||
series: DisplaySeries
|
||||
column: number
|
||||
showYAxisLabel: boolean
|
||||
yAxisLabelX: number
|
||||
left: number
|
||||
top: number
|
||||
width: number
|
||||
height: number
|
||||
xScale: ScaleLinear<number, number>
|
||||
yScale: ScaleLinear<number, number>
|
||||
xMajorTicks: number[]
|
||||
xMinorTicks: number[]
|
||||
yMajorTicks: number[]
|
||||
yMinorTicks: number[]
|
||||
yAxisTickValues: number[]
|
||||
xAxisTickValues: number[]
|
||||
endpointLabels: { start: string; end: string }
|
||||
path: string | null
|
||||
showXAxis: boolean
|
||||
}
|
||||
|
||||
// 重新导出 WaveformPoint 方便使用
|
||||
export type { WaveformPoint }
|
||||
46
src/components/core/useWaveformData.ts
Normal file
46
src/components/core/useWaveformData.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { shallowRef, watch } from 'vue'
|
||||
|
||||
import { normalizeWaveformSeries } from '../../core'
|
||||
import type { WaveformData, WaveformPoint } from '../../types'
|
||||
import { paddedDomain } from '../../utils'
|
||||
|
||||
export interface PreparedWaveformSeries {
|
||||
id: string
|
||||
name: string
|
||||
unit?: string
|
||||
color?: string
|
||||
points: WaveformPoint[]
|
||||
xDomain: [number, number]
|
||||
yDomain: [number, number]
|
||||
}
|
||||
|
||||
function pointDomain(points: WaveformPoint[], key: 'x' | 'y'): [number, number] {
|
||||
let minimum = Number.POSITIVE_INFINITY
|
||||
let maximum = Number.NEGATIVE_INFINITY
|
||||
points.forEach((point) => {
|
||||
const value = point[key]
|
||||
if (value < minimum) minimum = value
|
||||
if (value > maximum) maximum = value
|
||||
})
|
||||
return paddedDomain(Number.isFinite(minimum) ? [minimum, maximum] : [])
|
||||
}
|
||||
|
||||
export function prepareWaveformSeries(data: WaveformData): PreparedWaveformSeries[] {
|
||||
return normalizeWaveformSeries(data).map((series) => ({
|
||||
...series,
|
||||
xDomain: pointDomain(series.points, 'x'),
|
||||
yDomain: pointDomain(series.points, 'y'),
|
||||
}))
|
||||
}
|
||||
|
||||
export function usePreparedWaveformSeries(
|
||||
data: () => WaveformData,
|
||||
onDataChange: () => void,
|
||||
) {
|
||||
const preparedSeries = shallowRef<PreparedWaveformSeries[]>(prepareWaveformSeries(data()))
|
||||
watch(data, (nextData) => {
|
||||
preparedSeries.value = prepareWaveformSeries(nextData)
|
||||
onDataChange()
|
||||
})
|
||||
return preparedSeries
|
||||
}
|
||||
1
src/components/data/index.ts
Normal file
1
src/components/data/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from './types'
|
||||
23
src/components/data/types.ts
Normal file
23
src/components/data/types.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* 数据系统类型定义
|
||||
* 重新导出 src/types 中的类型,方便组件内部使用
|
||||
*/
|
||||
|
||||
// 重新导出所有类型
|
||||
export type {
|
||||
WaveformPoint,
|
||||
WaveformDisplayMode,
|
||||
WaveformInteractionMode,
|
||||
WaveformAnnotationStyle,
|
||||
WaveformAnnotation,
|
||||
WaveformRenderingOptions,
|
||||
SingleWaveformData,
|
||||
WaveformSeries,
|
||||
WaveformData,
|
||||
NormalizedWaveformSeries,
|
||||
} from '../../types'
|
||||
|
||||
export type { WaveformGridOptions } from '../core/grid'
|
||||
|
||||
// 重新导出数据处理函数
|
||||
export { normalizeWaveformData, normalizeWaveformSeries } from '../../core'
|
||||
26
src/components/index.ts
Normal file
26
src/components/index.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
export { default as WaveformChart } from './WaveformChart.vue'
|
||||
|
||||
// 从新的系统目录导出类型,保持向后兼容
|
||||
export type {
|
||||
SingleWaveformData,
|
||||
WaveformData,
|
||||
WaveformDisplayMode,
|
||||
WaveformInteractionMode,
|
||||
WaveformAnnotationStyle,
|
||||
WaveformAnnotation,
|
||||
WaveformRenderingOptions,
|
||||
WaveformPoint,
|
||||
WaveformSeries,
|
||||
WaveformGridOptions,
|
||||
} from './data/types'
|
||||
|
||||
export type { WaveformGridOptions as WaveformGridConfig } from './core/grid'
|
||||
|
||||
// 可选:导出各系统的组件(供高级用户使用)
|
||||
export { WaveformTooltip } from './interaction'
|
||||
export { WaveformTrack } from './rendering'
|
||||
export {
|
||||
WaveformAnnotationLayer,
|
||||
WaveformAnnotationToolbar,
|
||||
WaveformAnnotationContextMenu,
|
||||
} from './annotation'
|
||||
114
src/components/interaction/WaveformTooltip.vue
Normal file
114
src/components/interaction/WaveformTooltip.vue
Normal file
@@ -0,0 +1,114 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { formatTooltipNumber, formatTooltipTime } from '../../utils'
|
||||
import type { WaveformPoint } from '../data/types'
|
||||
|
||||
interface SeriesPoint {
|
||||
trackIndex: number
|
||||
name: string
|
||||
color: string
|
||||
unit?: string
|
||||
point: WaveformPoint
|
||||
}
|
||||
|
||||
interface Props {
|
||||
/** 是否显示 */
|
||||
visible: boolean
|
||||
/** 鼠标位置 */
|
||||
position: { x: number; y: number }
|
||||
/** 时间单位 */
|
||||
timeUnit: 's' | 'ms'
|
||||
/** 悬浮的点 */
|
||||
hoveredPoint: WaveformPoint | null
|
||||
/** 所有系列的悬浮点 */
|
||||
seriesPoints: SeriesPoint[]
|
||||
/** 容器宽度 */
|
||||
containerWidth: number
|
||||
/** 容器高度 */
|
||||
containerHeight: number
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
|
||||
const tooltipStyle = computed(() => {
|
||||
if (!props.visible || !props.hoveredPoint) return { display: 'none' }
|
||||
|
||||
const estimatedHeight = 44 + props.seriesPoints.length * 22
|
||||
return {
|
||||
left: `${Math.min(props.position.x + 12, Math.max(8, props.containerWidth - 250))}px`,
|
||||
top: `${Math.max(8, Math.min(props.position.y - 18, props.containerHeight - estimatedHeight - 8))}px`,
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="visible && hoveredPoint"
|
||||
class="waveform-tooltip waveform-chart__tooltip"
|
||||
:style="tooltipStyle"
|
||||
>
|
||||
<span class="waveform-tooltip__time waveform-chart__tooltip-time">
|
||||
{{ timeUnit }}: {{ formatTooltipTime(hoveredPoint.x, timeUnit) }}
|
||||
</span>
|
||||
<span
|
||||
v-for="seriesPoint in seriesPoints"
|
||||
:key="`${seriesPoint.trackIndex}-${seriesPoint.name}`"
|
||||
class="waveform-tooltip__series waveform-chart__tooltip-series"
|
||||
>
|
||||
<i :style="{ backgroundColor: seriesPoint.color }" />
|
||||
<strong v-if="seriesPoint.name">{{ seriesPoint.name }}:</strong>
|
||||
<span>
|
||||
{{ formatTooltipNumber(seriesPoint.point.y)
|
||||
}}{{ seriesPoint.unit ? ` ${seriesPoint.unit}` : '' }}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.waveform-tooltip {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
display: grid;
|
||||
gap: 3px;
|
||||
min-width: 180px;
|
||||
max-width: 238px;
|
||||
padding: 8px 10px;
|
||||
color: #333;
|
||||
font:
|
||||
12px/1.45 ui-monospace,
|
||||
SFMono-Regular,
|
||||
Consolas,
|
||||
monospace;
|
||||
pointer-events: none;
|
||||
background: #fff;
|
||||
border: 1px solid #d9d9d9;
|
||||
border-radius: 2px;
|
||||
box-shadow: 0 4px 12px rgb(16 24 40 / 12%);
|
||||
}
|
||||
|
||||
.waveform-tooltip__time {
|
||||
padding-bottom: 4px;
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
}
|
||||
|
||||
.waveform-tooltip__series {
|
||||
display: grid;
|
||||
grid-template-columns: 8px auto minmax(0, 1fr);
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.waveform-tooltip__series i {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.waveform-tooltip__series strong {
|
||||
overflow: hidden;
|
||||
font-weight: 600;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
</style>
|
||||
1
src/components/interaction/index.ts
Normal file
1
src/components/interaction/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as WaveformTooltip } from './WaveformTooltip.vue'
|
||||
429
src/components/rendering/WaveformTrack.vue
Normal file
429
src/components/rendering/WaveformTrack.vue
Normal file
@@ -0,0 +1,429 @@
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onMounted, ref, watch } from 'vue'
|
||||
import { axisBottom, axisLeft, select } from 'd3'
|
||||
import { formatAxisTime, formatScientificYAxisLabel } from '../../utils'
|
||||
import type { WaveformDisplayMode, WaveformInteractionMode } from '../data/types'
|
||||
import type { DisplaySeries, HoveredSeriesPoint, TrackLayout } from '../core/types'
|
||||
|
||||
interface Props {
|
||||
/** 轨道布局信息 */
|
||||
track: TrackLayout
|
||||
/** clipPath ID */
|
||||
clipPathId: string
|
||||
/** 内部宽度 */
|
||||
innerWidth: number
|
||||
/** 是否显示 tooltip */
|
||||
showTooltip: boolean
|
||||
/** 是否可缩放 */
|
||||
zoomable: boolean
|
||||
/** 显示模式 */
|
||||
displayMode: WaveformDisplayMode
|
||||
/** 当前工具模式 */
|
||||
interactionMode?: WaveformInteractionMode
|
||||
/** 帧编号 */
|
||||
frameNumber?: string | number
|
||||
/** 时间单位 */
|
||||
timeUnit: 's' | 'ms'
|
||||
/** 悬浮点(用于显示十字线) */
|
||||
hoveredPoint?: HoveredSeriesPoint
|
||||
/** Y 轴标签回退值 */
|
||||
yLabel?: string
|
||||
}
|
||||
|
||||
interface Emits {
|
||||
(e: 'pointer-move', event: PointerEvent): void
|
||||
(e: 'pointer-leave'): void
|
||||
(e: 'click', event: MouseEvent): void
|
||||
(e: 'contextmenu', event: MouseEvent): void
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
interactionMode: 'zoom',
|
||||
})
|
||||
const emit = defineEmits<Emits>()
|
||||
|
||||
const xAxisElement = ref<SVGGElement>()
|
||||
const yAxisElement = ref<SVGGElement>()
|
||||
|
||||
function resolveYAxisLabel(series: DisplaySeries): string {
|
||||
return series.name.trim() || props.yLabel || ''
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否应该显示 Y 轴标签
|
||||
* 在紧凑模式下,当轨道高度太小时隐藏标签避免重叠
|
||||
*/
|
||||
function shouldShowYAxisLabel(trackHeight: number, trackIndex: number): boolean {
|
||||
const MIN_HEIGHT_FOR_LABEL = 80
|
||||
|
||||
if (trackHeight >= MIN_HEIGHT_FOR_LABEL) {
|
||||
return true
|
||||
}
|
||||
|
||||
const labelSpacing = Math.ceil(MIN_HEIGHT_FOR_LABEL / trackHeight)
|
||||
return trackIndex % labelSpacing === 0
|
||||
}
|
||||
|
||||
function crosshairX(): number {
|
||||
return props.hoveredPoint && props.hoveredPoint.trackIndex === props.track.index
|
||||
? props.track.xScale(props.hoveredPoint.point.x)
|
||||
: 0
|
||||
}
|
||||
|
||||
function crosshairY(): number {
|
||||
return props.hoveredPoint && props.hoveredPoint.trackIndex === props.track.index
|
||||
? props.track.yScale(props.hoveredPoint.point.y)
|
||||
: 0
|
||||
}
|
||||
|
||||
function hasCrosshair(): boolean {
|
||||
return (
|
||||
props.showTooltip &&
|
||||
props.hoveredPoint !== undefined &&
|
||||
props.hoveredPoint.trackIndex === props.track.index
|
||||
)
|
||||
}
|
||||
|
||||
function renderAxes() {
|
||||
if (yAxisElement.value) {
|
||||
const [axisMin, axisMax] = props.track.yScale.domain()
|
||||
const visibleTicks = props.track.yAxisTickValues ?? props.track.yMajorTicks
|
||||
const topTickValue = visibleTicks.reduce<number | undefined>((closestTick, tickValue) => {
|
||||
if (closestTick === undefined) return tickValue
|
||||
return Math.abs(tickValue - axisMax) < Math.abs(closestTick - axisMax)
|
||||
? tickValue
|
||||
: closestTick
|
||||
}, undefined)
|
||||
const yAxis = axisLeft(props.track.yScale)
|
||||
.tickFormat((value) =>
|
||||
formatScientificYAxisLabel(Number(value), { axisMin, axisMax, topTickValue }),
|
||||
)
|
||||
.tickSize(-4)
|
||||
.tickPadding(7)
|
||||
.tickSizeOuter(0)
|
||||
|
||||
if (props.track.yAxisTickValues) {
|
||||
yAxis.tickValues(props.track.yAxisTickValues)
|
||||
}
|
||||
|
||||
select(yAxisElement.value).call(yAxis)
|
||||
}
|
||||
|
||||
if (xAxisElement.value) {
|
||||
select(xAxisElement.value).call(
|
||||
axisBottom(props.track.xScale)
|
||||
.tickValues(props.track.xAxisTickValues)
|
||||
.tickFormat((value) => formatAxisTime(Number(value), props.timeUnit))
|
||||
.tickSize(-4)
|
||||
.tickPadding(7)
|
||||
.tickSizeOuter(0),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await nextTick()
|
||||
renderAxes()
|
||||
})
|
||||
|
||||
watch(
|
||||
[
|
||||
() => props.track.xScale,
|
||||
() => props.track.yScale,
|
||||
() => props.track.xAxisTickValues,
|
||||
() => props.track.yAxisTickValues,
|
||||
() => props.timeUnit,
|
||||
],
|
||||
async () => {
|
||||
await nextTick()
|
||||
renderAxes()
|
||||
},
|
||||
{ flush: 'post' },
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<g
|
||||
class="waveform-track waveform-chart__track"
|
||||
:data-track-index="track.index"
|
||||
:data-track-left="track.left"
|
||||
:data-track-width="track.width"
|
||||
:data-y-axis-label-x="track.yAxisLabelX"
|
||||
:data-track-top="track.top"
|
||||
:data-track-height="track.height"
|
||||
:transform="`translate(${track.left ?? 0}, ${track.top})`"
|
||||
>
|
||||
<!-- 网格和背景 -->
|
||||
<g :clip-path="`url(#${clipPathId}-${track.index})`" aria-hidden="true">
|
||||
<g
|
||||
class="waveform-track__grid waveform-track__grid--minor waveform-chart__grid waveform-chart__grid--minor"
|
||||
>
|
||||
<line
|
||||
v-for="tick in track.xMinorTicks"
|
||||
:key="`x-minor-${track.index}-${tick}`"
|
||||
:x1="track.xScale(tick)"
|
||||
:x2="track.xScale(tick)"
|
||||
y1="0"
|
||||
:y2="track.height"
|
||||
/>
|
||||
<line
|
||||
v-for="tick in track.yMinorTicks"
|
||||
:key="`y-minor-${track.index}-${tick}`"
|
||||
x1="0"
|
||||
:x2="track.width ?? innerWidth"
|
||||
:y1="track.yScale(tick)"
|
||||
:y2="track.yScale(tick)"
|
||||
/>
|
||||
</g>
|
||||
<g
|
||||
class="waveform-track__grid waveform-track__grid--major waveform-chart__grid waveform-chart__grid--major"
|
||||
>
|
||||
<line
|
||||
v-for="tick in track.xMajorTicks"
|
||||
:key="`x-major-${track.index}-${tick}`"
|
||||
:x1="track.xScale(tick)"
|
||||
:x2="track.xScale(tick)"
|
||||
y1="0"
|
||||
:y2="track.height"
|
||||
/>
|
||||
<line
|
||||
v-for="tick in track.yMajorTicks"
|
||||
:key="`y-major-${track.index}-${tick}`"
|
||||
x1="0"
|
||||
:x2="track.width ?? innerWidth"
|
||||
:y1="track.yScale(tick)"
|
||||
:y2="track.yScale(tick)"
|
||||
/>
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<!-- 帧编号水印 -->
|
||||
<text
|
||||
v-if="frameNumber !== undefined"
|
||||
class="waveform-track__watermark waveform-chart__watermark"
|
||||
:x="(track.width ?? innerWidth) / 2"
|
||||
:y="track.height / 2"
|
||||
:style="{ fontSize: `${Math.min(120, track.height * 0.65)}px` }"
|
||||
text-anchor="middle"
|
||||
dominant-baseline="central"
|
||||
aria-hidden="true"
|
||||
>
|
||||
{{ frameNumber }}
|
||||
</text>
|
||||
|
||||
<!-- X 轴 -->
|
||||
<g
|
||||
v-if="track.showXAxis"
|
||||
ref="xAxisElement"
|
||||
class="waveform-track__axis waveform-track__axis--x waveform-chart__axis waveform-chart__axis--x"
|
||||
:transform="`translate(0, ${track.height})`"
|
||||
/>
|
||||
<g
|
||||
v-if="track.showXAxis"
|
||||
class="waveform-track__axis-endpoints waveform-chart__axis-endpoints"
|
||||
:transform="`translate(0, ${track.height})`"
|
||||
font-family="sans-serif"
|
||||
font-size="10"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<text
|
||||
class="waveform-track__axis-endpoint waveform-track__axis-endpoint--start waveform-chart__axis-endpoint waveform-chart__axis-endpoint--start"
|
||||
x="0"
|
||||
y="7"
|
||||
dy="0.71em"
|
||||
text-anchor="start"
|
||||
>
|
||||
{{ track.endpointLabels.start }}
|
||||
</text>
|
||||
<text
|
||||
class="waveform-track__axis-endpoint waveform-track__axis-endpoint--end waveform-chart__axis-endpoint waveform-chart__axis-endpoint--end"
|
||||
:x="track.width ?? innerWidth"
|
||||
y="7"
|
||||
dy="0.71em"
|
||||
text-anchor="end"
|
||||
>
|
||||
{{ track.endpointLabels.end }}
|
||||
</text>
|
||||
</g>
|
||||
|
||||
<!-- Y 轴 -->
|
||||
<g
|
||||
ref="yAxisElement"
|
||||
class="waveform-track__axis waveform-track__axis--y waveform-chart__axis waveform-chart__axis--y"
|
||||
/>
|
||||
|
||||
<!-- Y 轴标签 -->
|
||||
<g
|
||||
v-if="
|
||||
track.showYAxisLabel &&
|
||||
resolveYAxisLabel(track.series) &&
|
||||
shouldShowYAxisLabel(track.height, track.index)
|
||||
"
|
||||
>
|
||||
<rect
|
||||
class="waveform-track__y-axis-label-bg waveform-chart__y-axis-label-bg"
|
||||
:x="track.yAxisLabelX - 12"
|
||||
:y="track.height / 2 - 40"
|
||||
width="24"
|
||||
height="80"
|
||||
rx="2"
|
||||
/>
|
||||
<text
|
||||
class="waveform-track__y-axis-label waveform-chart__y-axis-label"
|
||||
:fill="track.series.color"
|
||||
:transform="`translate(${track.yAxisLabelX}, ${track.height / 2}) rotate(-90)`"
|
||||
text-anchor="middle"
|
||||
dominant-baseline="central"
|
||||
>
|
||||
{{ resolveYAxisLabel(track.series) }}
|
||||
</text>
|
||||
</g>
|
||||
|
||||
<!-- 轨道边框 -->
|
||||
<rect
|
||||
class="waveform-track__plot-frame waveform-chart__plot-frame"
|
||||
:width="track.width ?? innerWidth"
|
||||
:height="track.height"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
|
||||
<!-- 波形线 -->
|
||||
<path
|
||||
class="waveform-track__line waveform-chart__line"
|
||||
:data-series-id="track.series.id"
|
||||
:data-series-name="track.series.name || undefined"
|
||||
:d="track.path ?? undefined"
|
||||
:stroke="track.series.color"
|
||||
:clip-path="`url(#${clipPathId}-${track.index})`"
|
||||
/>
|
||||
|
||||
<!-- 十字线 -->
|
||||
<g
|
||||
v-if="hasCrosshair()"
|
||||
class="waveform-track__crosshair waveform-chart__crosshair"
|
||||
:clip-path="`url(#${clipPathId}-${track.index})`"
|
||||
>
|
||||
<line :x1="crosshairX()" :x2="crosshairX()" y1="0" :y2="track.height" />
|
||||
<line x1="0" :x2="track.width ?? innerWidth" :y1="crosshairY()" :y2="crosshairY()" />
|
||||
<circle :cx="crosshairX()" :cy="crosshairY()" r="4" :fill="track.series.color" />
|
||||
</g>
|
||||
|
||||
<!-- 交互覆盖层(仅在独立模式下) -->
|
||||
<rect
|
||||
v-if="displayMode === 'independent'"
|
||||
class="waveform-track__overlay waveform-track__overlay--independent waveform-chart__overlay waveform-chart__overlay--independent"
|
||||
:class="{
|
||||
'is-zoomable': zoomable && interactionMode === 'zoom',
|
||||
'is-annotating': interactionMode === 'annotation',
|
||||
}"
|
||||
:data-independent-overlay-index="track.index"
|
||||
:width="track.width ?? innerWidth"
|
||||
:height="track.height"
|
||||
@pointermove="emit('pointer-move', $event)"
|
||||
@pointerleave="emit('pointer-leave')"
|
||||
@click="emit('click', $event)"
|
||||
@contextmenu="emit('contextmenu', $event)"
|
||||
/>
|
||||
</g>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.waveform-track {
|
||||
isolation: isolate;
|
||||
}
|
||||
|
||||
.waveform-track__line {
|
||||
fill: none;
|
||||
stroke-width: 1.5;
|
||||
stroke-linejoin: round;
|
||||
stroke-linecap: round;
|
||||
}
|
||||
|
||||
.waveform-track__y-axis-label-bg {
|
||||
fill: white;
|
||||
opacity: 0.9;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.waveform-track__y-axis-label {
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.waveform-track__grid {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.waveform-track__grid--major line {
|
||||
stroke: #dfe5ef;
|
||||
stroke-width: 1;
|
||||
}
|
||||
|
||||
.waveform-track__grid--minor line {
|
||||
stroke: #f2f5fa;
|
||||
stroke-width: 1;
|
||||
}
|
||||
|
||||
.waveform-track__plot-frame {
|
||||
fill: none;
|
||||
stroke: #1f2937;
|
||||
stroke-width: 1;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.waveform-track__watermark {
|
||||
fill: rgb(22 119 255 / 10%);
|
||||
font-family: Consolas, Monaco, 'Courier New', monospace;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.waveform-track__overlay {
|
||||
fill: transparent;
|
||||
cursor: crosshair;
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
.waveform-track__overlay.is-zoomable {
|
||||
cursor: grab;
|
||||
}
|
||||
|
||||
.waveform-track__overlay.is-zoomable:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
.waveform-track__overlay.is-annotating {
|
||||
cursor: crosshair;
|
||||
}
|
||||
|
||||
.waveform-track__crosshair {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.waveform-track__crosshair line {
|
||||
stroke: #57617b;
|
||||
stroke-width: 1;
|
||||
stroke-dasharray: 4 3;
|
||||
}
|
||||
|
||||
.waveform-track__crosshair circle {
|
||||
stroke: #fff;
|
||||
stroke-width: 2;
|
||||
}
|
||||
|
||||
.waveform-track__axis-endpoint {
|
||||
fill: #667085;
|
||||
font-size: 11px;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
:deep(.waveform-track__axis path),
|
||||
:deep(.waveform-track__axis line) {
|
||||
stroke: #1f2937;
|
||||
}
|
||||
|
||||
:deep(.waveform-track__axis text) {
|
||||
fill: #667085;
|
||||
font-size: 11px;
|
||||
}
|
||||
</style>
|
||||
1
src/components/rendering/index.ts
Normal file
1
src/components/rendering/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as WaveformTrack } from './WaveformTrack.vue'
|
||||
21
src/components/waveform.ts
Normal file
21
src/components/waveform.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* 向后兼容的导出文件
|
||||
* 保留原有导入路径,内部从新的模块结构导出
|
||||
*/
|
||||
|
||||
// 类型定义
|
||||
export type {
|
||||
WaveformPoint,
|
||||
WaveformDisplayMode,
|
||||
WaveformInteractionMode,
|
||||
WaveformAnnotationStyle,
|
||||
WaveformAnnotation,
|
||||
WaveformRenderingOptions,
|
||||
SingleWaveformData,
|
||||
WaveformSeries,
|
||||
WaveformData,
|
||||
NormalizedWaveformSeries,
|
||||
} from '../types'
|
||||
|
||||
// 数据处理函数
|
||||
export { normalizeWaveformData, normalizeWaveformSeries } from '../core'
|
||||
Reference in New Issue
Block a user