Merge Core main into german/hal-644-ar: Arabic on the Vue UI

Main moved the UI to Vue views and Pinia stores, so the Arabic changes to
the old DOM controllers now live in their views: the rail legend range
comes from formatScaleRange (keeping units a source supplies as given),
the voice timeout options are worded by Intl unit formatting in
VoiceControl, and the scene editor's JSON fields stay left to right in
SceneDialog. Main's CCTV status line, launch panel and calibration values
keep the Arabic isolates and Western-digit formatting.

isolate() and keepCodesWithValues() read the locale through getLocale(),
which follows the page's vue-i18n instance, and the Intl formatters take
intlLocale(getLocale()). A language switch now applies in place, and
applyDocumentLanguage sets <html dir> on every switch, so the page mirrors
without a reload.

The icon rails and their tips are placed with logical properties, so they
stay on the outer side of the mirrored stacks; Cyber's new stack offsets,
padding and edge lines are logical too, and rtl.css moves Cyber's right
stack to its new rail clearance. Main removed the Context mini radio, so its
right-to-left rules and test go.

The Arabic catalog gains main's new strings and drops the ones main no
longer uses; the other catalogs keep main's new keys and the branch's
landing labels.
This commit is contained in:
Sameh Khamis committed 2026-11-01 20:15:02 -08:00
commit bc5d038afd
630 files changed
+41141 -20956

No files matched your search

+34
View File
@@ -0,0 +1,34 @@
<script setup>
import { storeToRefs } from 'pinia';
import { computed } from 'vue';
import UiPanelToggle from '../kit/UiPanelToggle.vue';
import { usePanelChromeStore } from '../stores/panelChrome.js';
// The collapse button of a panel not built on UiPanel: it follows the panel's
// state in the panel chrome store, and a click asks PanelChrome to toggle it.
// Until PanelChrome presents the panel it follows the markup's state.
const props = defineProps({
target: { type: String, required: true },
/** The panel's name in "Expand {name}", already translated. */
name: { type: String, default: undefined },
sideways: { type: Boolean, default: false },
/** Whether the panel's markup starts collapsed. */
startCollapsed: { type: Boolean, default: false },
});
const chrome = usePanelChromeStore();
const { panels } = storeToRefs(chrome);
const collapsedNow = computed(
() => panels.value[props.target]?.collapsed ?? props.startCollapsed,
);
</script>
<template>
<UiPanelToggle
:target="target"
:name="name"
:sideways="sideways"
:collapsed="collapsedNow"
@update:collapsed="chrome.act('toggle', target)"
/>
</template>
+68
View File
@@ -0,0 +1,68 @@
<script setup>
import { computed, onBeforeUnmount } from 'vue';
import RailCardBlocks from './RailCardBlocks.vue';
import UiBadge from '../kit/UiBadge.vue';
// One keyed card: a disclosure header and its blocks. The owner decides
// which card is open.
const props = defineProps({
card: { type: Object, required: true },
cardClassName: { type: String, default: '' },
badgeClassName: { type: String, default: '' },
onParams: { type: Function, default: () => {} },
onOpen: { type: Function, default: () => {} },
});
const bodyId = `rail-card-body-${nextBodyId()}`;
const open = computed(() => props.card.open !== false);
// A removed card's header opens nothing.
let live = true;
onBeforeUnmount(() => {
live = false;
});
const select = () => live && props.onOpen(props.card.id);
</script>
<script>
let bodies = 0;
const nextBodyId = () => ++bodies;
</script>
<template>
<article
:class="`rail-card${cardClassName ? ` ${cardClassName}` : ''}${open ? ' is-open' : ''}`"
:data-card-id="card.id"
:data-open="String(open)"
><button
class="rail-card-header"
type="button"
:aria-controls="bodyId"
:aria-expanded="String(open)"
@click="select"
><span class="rail-card-labels"
><span class="rail-card-heading"
><span class="data-icon" aria-hidden="true" :hidden="!card.icon">{{
card.icon || ''
}}</span
><span class="rail-card-title rail-card-nowrap" :title="card.title">{{
card.title
}}</span></span
><UiBadge
:class="`gev-status-badge--plain rail-card-badge${badgeClassName ? ` ${badgeClassName}` : ''}`"
:hidden="!card.badge"
>{{ card.badge || '' }}</UiBadge
></span
><span class="rail-card-disclosure" aria-hidden="true">{{
open ? '▾' : '▸'
}}</span
><span
:class="`rail-card-compact${card.compactStatus ? ' status' : ''}`"
:hidden="open"
>{{ card.compact || '' }}</span
></button
><div :id="bodyId" class="rail-card-body" :hidden="!open"
><RailCardBlocks
:blocks="card.blocks || []"
:card-id="card.id"
:on-params="onParams" /></div
></article>
</template>
+208
View File
@@ -0,0 +1,208 @@
<script setup>
import { onBeforeUnmount } from 'vue';
import { t } from '../../i18n/index.js';
import { formatScaleRange } from '../unitLabels.js';
import RailCardSetting from './RailCardSetting.vue';
import RailChips from './RailChips.vue';
import RailRowList from './RailRowList.vue';
// Optional, ordered blocks without disclosure state. Every control is keyed.
const props = defineProps({
blocks: { type: Array, default: () => [] },
cardId: { type: String, default: undefined },
onParams: { type: Function, default: () => {} },
});
// Controls of removed blocks dispatch nothing: a detached element keeps its
// last handler, which names a block the owner no longer lists.
let live = true;
onBeforeUnmount(() => {
live = false;
});
function dispatch(descriptor, block) {
if (!live || !props.blocks.includes(block)) return;
if (!descriptor || descriptor.disabled) return;
if (descriptor.params) props.onParams(props.cardId, descriptor.params);
else descriptor.onClick?.();
}
const rootTag = (block) =>
block.type === 'list' ? 'ol' : block.type === 'actions' ? 'footer' : 'div';
const lines = (block) => block.lines || [{ id: block.id, text: block.text }];
function legendView(legend) {
const colors = (legend?.colors || []).filter((color) =>
/^#(?:[0-9a-f]{6}|[0-9a-f]{8})$/i.test(color),
);
const visible = colors.length >= 2 && colors.length === legend.colors.length;
const zeroVisible =
visible &&
legend.units === '°C' &&
Number.isInteger(legend.zeroIndex) &&
legend.zeroIndex >= 0 &&
legend.zeroIndex < colors.length;
return {
colors,
visible,
categorical: Boolean(legend?.categorical),
zeroVisible,
// Styles are strings so an unchanged legend writes nothing; browsers
// normalize the colors they read back.
rampStyle: visible
? `background: linear-gradient(to right, ${colors.join(',')})`
: undefined,
zeroStyle: zeroVisible
? `left: ${(legend.zeroIndex / (colors.length - 1)) * 100}%`
: undefined,
scale: visible
? formatScaleRange(
legend.labels[0],
legend.labels.at(-1),
legend.units,
legend.unitsVerbatim === true,
)
: '',
labels: legend?.labels || [],
};
}
</script>
<template>
<template v-for="block in blocks" :key="`${block.id}:${block.type}`"
><RailRowList
v-if="block.type === 'list'"
:list="block.list"
:block-id="block.id"
:on-select="(item) => dispatch(item, block)"
/><component
:is="rootTag(block)"
v-else
:class="`rail-card-${block.type}`"
:data-block-id="block.id"
:hidden="
block.type === 'legend' ? !legendView(block.legend).visible : undefined
"
><RailCardBlocks
v-if="block.type === 'settings'"
:blocks="
(block.settings || []).map((setting) => ({
...setting,
type: 'setting',
}))
"
:card-id="cardId"
:on-params="onParams"
/><RailCardSetting
v-else-if="block.type === 'setting'"
:setting="block"
:dispatch="(descriptor) => dispatch(descriptor, block)"
/><template v-else-if="block.type === 'result'"
><div class="rail-card-result-header"
><span class="panel-title">{{ block.label }}</span
><button
class="data-toggle-chip"
type="button"
data-action-id="clear"
:aria-label="t('Clear reading')"
:title="t('Clear reading')"
:hidden="!block.clear"
@click="dispatch(block.clear, block)"
>×</button
></div
><div class="rail-card-result-lines"
><RailCardBlocks
:blocks="[
{ id: 'result-lines', type: 'lines', lines: block.lines },
]"
:card-id="cardId"
:on-params="onParams" /></div></template
><template v-else-if="block.type === 'legend'"
><div
class="rail-card-ramp"
:hidden="
!legendView(block.legend).visible ||
legendView(block.legend).categorical
"
:style="legendView(block.legend).rampStyle"
><span
class="rail-card-zero"
aria-hidden="true"
:hidden="!legendView(block.legend).zeroVisible"
:style="legendView(block.legend).zeroStyle"
></span></div
><div
class="rail-card-scale"
:hidden="legendView(block.legend).categorical"
>{{ legendView(block.legend).scale }}</div
><div
class="rail-card-legend-entries"
:hidden="!legendView(block.legend).categorical"
><template v-if="legendView(block.legend).categorical"
><div
v-for="(color, index) in legendView(block.legend).colors"
:key="index"
class="rail-card-legend-entry"
:data-color="color"
><span
class="rail-card-legend-swatch"
:style="`background: ${color}`"
></span
><span>{{
legendView(block.legend).labels[index] || ''
}}</span></div
></template
></div
></template
><template v-else-if="block.type === 'actions'"
><template
v-for="action in block.actions || []"
:key="`${action.id}:${action.href ? 'a' : 'button'}`"
><a
v-if="action.href"
class="data-toggle-chip"
:data-action-id="action.id"
target="_blank"
rel="noopener"
:href="action.href"
:title="action.title || undefined"
@click="dispatch(action, block)"
>{{ action.label }}</a
><button
v-else
:class="[
'data-toggle-chip',
{ active: action.pressed, 'is-reserved': action.reserved },
]"
type="button"
:data-action-id="action.id"
:title="action.title || undefined"
:disabled="Boolean(action.disabled)"
:aria-pressed="
action.pressed === undefined
? undefined
: String(Boolean(action.pressed))
"
:aria-hidden="
action.reserved === undefined
? undefined
: String(Boolean(action.reserved))
"
@click="dispatch(action, block)"
>{{ action.label }}</button
><span class="rail-card-action-hint" :hidden="!action.hint">{{
action.hint || ''
}}</span></template
></template
><template v-else
><div
v-for="line in lines(block)"
:key="line.id"
:class="`rail-card-line${line.muted ? ' muted' : ''}`"
:data-line-id="line.id"
>{{ String(line.text ?? '') }}</div
></template
></component
></template
>
</template>
+115
View File
@@ -0,0 +1,115 @@
<script setup>
import { computed, ref, watch } from 'vue';
import RailChips from './RailChips.vue';
import UiSlider from '../kit/UiSlider.js';
// One setting: a chip group and an optional range. The handle's value is held
// until the owner's next update; a range that commits on change keeps it
// across updates until its descriptor changes.
const props = defineProps({
setting: { type: Object, required: true },
dispatch: { type: Function, required: true },
});
const draft = ref(null);
watch(
() => props.setting,
() => {
const range = props.setting.range;
const held = draft.value;
if (
held &&
(held.committed ||
!range ||
range.disabled ||
!range.commitOnChange ||
['id', 'param', 'min', 'max', 'step', 'value'].some(
(key) => range[key] !== held.range[key],
))
)
draft.value = null;
},
{ flush: 'sync' },
);
const range = computed(() => props.setting.range);
const value = computed(() => {
const { min, max } = range.value;
const candidate = Number(draft.value?.value ?? range.value.value);
return Math.min(
Number(max),
Math.max(Number(min), Number.isFinite(candidate) ? candidate : Number(min)),
);
});
const valueText = computed(() => `${value.value}${range.value.unit || ''}`);
function rangeParams(input) {
const current = range.value;
const next = Number(input.value);
if (
!current?.param ||
current.disabled ||
!Number.isFinite(next) ||
next < Number(current.min) ||
next > Number(current.max)
)
return null;
return { params: { [current.param]: next } };
}
// The handle shows the value again once the owner has answered: an owner
// that clamps or refuses may leave the slider's model where it last
// rendered, and then it would not render.
function place(input) {
if (!range.value) return;
const next = String(value.value);
if (input.value !== next) input.value = next;
}
function onInput(event) {
const params = rangeParams(event.target);
if (!params) return;
// The readout follows the handle at once, whether or not the owner redraws.
draft.value = { range: range.value, value: Number(event.target.value) };
if (range.value.commitOnChange) return;
props.dispatch(params);
place(event.target);
}
function onChange(event) {
if (!range.value?.commitOnChange) return;
const params = rangeParams(event.target);
// Committed: the next update shows the owner's value, as before.
if (draft.value) draft.value = { ...draft.value, committed: true };
if (params) props.dispatch(params);
place(event.target);
}
</script>
<template>
<span class="rail-card-setting-label panel-title">{{ setting.label }}</span
><div class="rail-card-chips" role="group" :aria-label="setting.label"
><RailChips :chips="setting.chips" :on-select="dispatch" /></div
><div class="rail-card-setting-range-row" :hidden="!range"
><template v-if="range"
><span class="rail-card-setting-range-label" :hidden="!range.label">{{
range.label || ''
}}</span
><UiSlider
class="rail-card-setting-range"
:data-range-id="range.id || setting.id"
:min="String(Number(range.min))"
:max="String(Number(range.max))"
:step="String(Number(range.step))"
:model-value="String(value)"
:disabled="Boolean(range.disabled)"
:aria-label="range.ariaLabel || setting.label"
:aria-valuetext="valueText"
@input="onInput"
@change="onChange"
/><span class="rail-card-setting-range-value">{{
valueText
}}</span></template
></div
>
</template>
+24
View File
@@ -0,0 +1,24 @@
<script setup>
import RailCard from './RailCard.vue';
// Keyed cards in the owner's order; the owner owns the open-card choice.
defineProps({
cards: { type: Array, default: () => [] },
cardClassName: { type: String, default: '' },
badgeClassName: { type: String, default: '' },
onParams: { type: Function, default: () => {} },
onOpen: { type: Function, default: () => {} },
});
</script>
<template>
<RailCard
v-for="card in cards"
:key="card.id"
:card="card"
:card-class-name="cardClassName"
:badge-class-name="badgeClassName"
:on-params="onParams"
:on-open="onOpen"
/>
</template>
+30
View File
@@ -0,0 +1,30 @@
<script setup>
import UiButton from '../kit/UiButton.vue';
// Keyed chips shared by rail cards; the owner decides what a click does.
defineProps({
chips: { type: Array, default: () => [] },
onSelect: { type: Function, default: () => {} },
});
const chipClass = (chip) =>
`data-toggle-chip chip-${chip.state || (chip.active ? 'active' : 'idle')}`;
</script>
<template>
<UiButton
v-for="chip in chips"
:key="chip.id"
:data-chip-id="chip.id"
:class="chipClass(chip)"
:pressed="Boolean(chip.active)"
pressed-class="active"
:style="chip.color ? `--chip-color: ${chip.color}` : undefined"
:data-chip-color="chip.color || undefined"
:title="chip.title || undefined"
:disabled="Boolean(chip.disabled)"
:aria-busy="String(Boolean(chip.busy))"
@click="onSelect(chip)"
>{{ chip.label }}</UiButton
>
</template>
+41
View File
@@ -0,0 +1,41 @@
<script setup>
import { storeToRefs } from 'pinia';
import { computed } from 'vue';
import UiPanel from '../kit/UiPanel.vue';
import { usePanelChromeStore } from '../stores/panelChrome.js';
import { vPanelState } from './panelState.js';
// A panel PanelChrome owns: a collapsible UiPanel whose state classes
// (vPanelState) and collapse button follow the panel chrome store, with the
// button's clicks forwarded to PanelChrome. Every other prop, attribute and
// slot passes through to UiPanel.
defineOptions({ inheritAttrs: false });
const props = defineProps({
id: { type: String, required: true },
/** Whether the markup starts collapsed, until PanelChrome presents it. */
startCollapsed: { type: Boolean, default: false },
});
const chrome = usePanelChromeStore();
const { panels } = storeToRefs(chrome);
const collapsedNow = computed(
() => panels.value[props.id]?.collapsed ?? props.startCollapsed,
);
</script>
<template>
<UiPanel
v-panel-state="props.id"
v-bind="$attrs"
:id="props.id"
:class="{ collapsed: props.startCollapsed }"
:data-panel-id="props.id"
collapsible
:collapsed="collapsedNow"
@update:collapsed="chrome.act('toggle', props.id)"
>
<template v-for="(_, name) in $slots" #[name]
><slot :name="name"
/></template>
</UiPanel>
</template>
+62
View File
@@ -0,0 +1,62 @@
<script setup>
import { onMounted, onUpdated, ref } from 'vue';
// An ordered list whose rows keep their identity, so a focused row stays.
const props = defineProps({
list: { type: Object, default: null },
blockId: { type: String, default: undefined },
onSelect: { type: Function, default: () => {} },
});
const root = ref(null);
const rowClass = (item) =>
`data-row-list-item${item.disabled ? ' note' : ''}${item.active ? ' active' : ''}${item.current ? ' current' : ''}`;
// Follow the flight, but never steal a scroll the reader is making
// themselves: only when the step actually changed.
function followCurrent() {
const list = root.value;
if (!list) return;
const current = props.list?.items?.find((item) => item.current);
if (!current) {
delete list.dataset.currentId;
return;
}
if (list.dataset.currentId === current.id) return;
list.dataset.currentId = current.id;
[...list.querySelectorAll('.data-row-list-item')]
.find((button) => button.dataset.listItemId === current.id)
?.scrollIntoView?.({ block: 'nearest' });
}
onMounted(followCurrent);
onUpdated(followCurrent);
</script>
<template>
<ol
ref="root"
class="data-row-list ui-scroll"
:data-block-id="blockId"
:hidden="!list?.items?.length"
:aria-label="list?.ariaLabel || ''"
><li
v-for="item in list?.items ?? []"
:key="item.id"
:data-list-item-id="item.id"
><button
type="button"
:class="rowClass(item)"
:data-list-item-id="item.id"
:disabled="Boolean(item.disabled)"
:aria-current="item.current ? 'step' : 'false'"
:aria-pressed="item.active ? 'true' : 'false'"
:title="String(item.text ?? '')"
@click="onSelect(item)"
><span class="data-row-list-lead">{{ String(item.lead ?? '') }}</span
><span class="data-row-list-text">{{
String(item.text ?? '')
}}</span></button
></li
></ol
>
</template>
+178
View File
@@ -0,0 +1,178 @@
<script setup>
import { computed, onBeforeUnmount, shallowRef, watch } from 'vue';
import { formatUtcDayMonth, t } from '../../i18n/index.js';
import { utcClock } from './utcClock.js';
import UiSlider from '../kit/UiSlider.js';
// Stable native transport with local preview and a coalesced 150 ms drag
// commit. While the handle is dragged the slider keeps the ticks it was
// dragged over; the owner's updates apply once the drag ends.
const props = defineProps({
state: { type: Object, required: true },
sliderClassName: { type: String, default: '' },
heading: { type: Boolean, default: true },
onCommit: { type: Function, default: () => {} },
onPreview: { type: Function, default: () => {} },
onStep: { type: Function, default: () => {} },
onLatest: { type: Function, default: () => {} },
onPlay: { type: Function, default: () => {} },
});
const utc = (tick) =>
Number.isFinite(Date.parse(tick))
? `${formatUtcDayMonth(tick)} ${utcClock(tick)}`
: '';
// What the slider shows: the owner's ticks, index and readout, frozen while
// dragging.
const shown = shallowRef({ ticks: [], index: 0, readout: '' });
let dragging = false;
let timer = null;
let pending = null;
let live = true;
const cancel = () => {
if (timer !== null) clearTimeout(timer);
timer = null;
};
const sync = () => {
if (dragging) return;
const ticks = [...props.state.ticks];
shown.value = {
ticks,
index: Math.max(0, Math.min(props.state.index, ticks.length - 1)),
readout: props.state.readout || '',
};
};
watch(
() => props.state,
(state) => {
if (state.disabled) {
cancel();
pending = null;
dragging = false;
}
sync();
},
{ immediate: true, flush: 'sync' },
);
onBeforeUnmount(() => {
live = false;
cancel();
});
const disabled = computed(() => Boolean(props.state.disabled));
const latestActive = computed(() => props.state.mode === 'latest');
const playing = computed(() => Boolean(props.state.playing));
function commit() {
cancel();
const value = pending;
pending = null;
if (live && value && !props.state.disabled)
props.onCommit(value.tick, value.index);
}
function preview(event) {
if (props.state.disabled) return;
dragging = true;
const index = Number(event.target.value);
const tick = shown.value.ticks[index];
if (!tick) return;
pending = { tick, index };
// Shown before the owner hears of it: an update from inside onPreview
// must not move the handle back.
shown.value = { ...shown.value, index };
const readout = props.onPreview(tick, index);
// The owner may have ended the drag (disabled) from inside onPreview.
if (!dragging) return;
if (typeof readout === 'string') shown.value = { ...shown.value, readout };
if (timer === null) timer = setTimeout(commit, 150);
}
// The handle shows the shown index again. A drag that ends where it began
// (an input and a cancel, or a refused commit, before the next render)
// leaves the slider's model unchanged, so it would not render.
const place = (input) => {
const index = String(shown.value.index);
if (input && input.value !== index) input.value = index;
};
function change(event) {
if (props.state.disabled) return;
const index = Number(event.target.value);
pending = { tick: shown.value.ticks[index], index };
dragging = false;
commit();
sync();
place(event.target);
}
function reset(event) {
cancel();
pending = null;
dragging = false;
sync();
place(event?.target);
}
function blur(event) {
if (dragging) change(event);
}
const act = (fn) => {
reset();
if (live && !props.state.disabled) fn();
};
</script>
<template>
<section class="rail-timeline"
><div v-if="heading" class="panel-title">{{ t('Observed history') }}</div
><div class="rail-timeline-track"
><button
type="button"
class="data-toggle-chip"
:title="t('Earlier observation')"
:disabled="disabled || state.index <= 0"
@click="act(() => onStep(-1))"
>‹</button
><UiSlider
:class="sliderClassName || undefined"
min="0"
:max="String(Math.max(0, shown.ticks.length - 1))"
step="1"
:model-value="String(shown.index)"
:disabled="disabled"
:aria-label="t('Observed history')"
:aria-valuetext="utc(shown.ticks[shown.index])"
@input="preview"
@change="change"
@pointercancel="reset"
@blur="blur"
/><button
type="button"
class="data-toggle-chip"
:title="t('Later observation')"
:disabled="disabled || state.index >= state.ticks.length - 1"
@click="act(() => onStep(1))"
>›</button
><div class="rail-timeline-endpoints"
><span>{{ utcClock(shown.ticks[0]) }}</span
><span>{{ utcClock(shown.ticks.at(-1)) }}</span></div
></div
><div class="rail-timeline-controls"
><button
type="button"
:class="`data-toggle-chip${latestActive ? ' active' : ''}`"
:title="t('Newest frame per product')"
:disabled="disabled"
:aria-pressed="String(latestActive)"
@click="act(onLatest)"
>{{ t('Latest') }}</button
><button
type="button"
:class="`data-toggle-chip${playing ? ' active' : ''}`"
:title="t('Replay observed history')"
:disabled="disabled"
:aria-pressed="String(playing)"
@click="act(onPlay)"
>{{ playing ? t('Pause') : t('Play') }}</button
><span class="rail-timeline-readout">{{ shown.readout }}</span></div
></section
>
</template>
+11
View File
@@ -0,0 +1,11 @@
/**
* `v-class-toggle`: toggles each named class with `classList`, so classes other
* code adds to the element (a voice highlight) survive a re-render. A `:class`
* binding rewrites the whole `className` instead.
*/
const apply = (el, { value }) => {
for (const [name, on] of Object.entries(value || {}))
if (el.classList.contains(name) !== Boolean(on))
el.classList.toggle(name, Boolean(on));
};
export const vClassToggle = { mounted: apply, updated: apply };
+23
View File
@@ -0,0 +1,23 @@
/**
* `v-field-value`: a form field's live value, written only when it differs
* and the field is not focused, so a render never overwrites what a person
* is typing, picking or dragging. Focus is read before the render patches
* the field too, since disabling it drops focus. A null value leaves the
* field as it is. Unlike a `:value` binding, the value attribute is never
* rewritten.
*/
const focused = (el) => el.ownerDocument?.activeElement === el;
const apply = (el, { value }) => {
const held = focused(el) || el.__fieldValueFocused;
el.__fieldValueFocused = false;
if (value == null || held) return;
const next = String(value);
if (el.value !== next) el.value = next;
};
export const vFieldValue = {
mounted: apply,
beforeUpdate(el) {
el.__fieldValueFocused = focused(el);
},
updated: apply,
};
+81
View File
@@ -0,0 +1,81 @@
// src/ui/rail/fieldValue.test.mjs — v-field-value never writes over a field
// that has focus, and leaves a field alone for a null value.
import '../../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { createApp, h, nextTick, shallowRef, withDirectives } from 'vue';
import { vFieldValue } from './fieldValue.js';
test('a render writes the value unless the field has focus or the value is null', async (t) => {
document.body.replaceChildren();
const host = document.body.appendChild(document.createElement('div'));
const value = shallowRef('98.5');
const app = createApp({
render: () =>
withDirectives(h('input', { type: 'number', id: 'field' }), [
[vFieldValue, value.value],
]),
});
app.mount(host);
t.after(() => app.unmount());
const field = document.getElementById('field');
assert.equal(field.value, '98.5');
field.focus();
field.value = '101.1';
value.value = '98.7';
await nextTick();
assert.equal(field.value, '101.1', 'typing stands');
field.blur();
value.value = null;
await nextTick();
assert.equal(field.value, '101.1', 'null leaves it');
value.value = '98.9';
await nextTick();
assert.equal(field.value, '98.9');
});
test('a render that disables a focused field leaves its value', async (t) => {
document.body.replaceChildren();
const host = document.body.appendChild(document.createElement('div'));
const state = shallowRef({ value: 'auto', disabled: false });
const app = createApp({
render: () =>
withDirectives(
h('select', { id: 'gain', disabled: state.value.disabled }, [
h('option', { value: 'auto' }, 'AUTO'),
h('option', { value: '20.7' }, '20.7 dB'),
]),
[[vFieldValue, state.value.value]],
),
});
app.mount(host);
t.after(() => app.unmount());
const gain = document.getElementById('gain');
// Browsers drop focus from a field that becomes disabled; happy-dom does
// not, so focus moves to the page here.
const page = document.body.appendChild(document.createElement('button'));
const drop = () => page.focus();
const disabled = Object.getOwnPropertyDescriptor(
Object.getPrototypeOf(gain),
'disabled',
);
Object.defineProperty(gain, 'disabled', {
get: () => disabled.get.call(gain),
set: (on) => {
disabled.set.call(gain, on);
if (on) drop();
},
});
const setAttribute = gain.setAttribute.bind(gain);
gain.setAttribute = (name, value) => {
setAttribute(name, value);
if (name === 'disabled') drop();
};
gain.focus();
gain.value = '20.7';
state.value = { value: 'auto', disabled: true };
await nextTick();
assert.equal(gain.disabled, true);
assert.equal(document.activeElement === gain, false, 'focus left the field');
assert.equal(gain.value, '20.7');
});
+58
View File
@@ -0,0 +1,58 @@
/**
* `v-focus-safe-children`: lets a keyed list reorder without dropping keyboard
* focus. A browser blurs any element it moves, so Vue moving the row that
* holds focus would drop it. This directive turns such a move into moves of
* the rows around the focused one, which reach the same order while the
* focused row stays put. Before the focused row itself is removed, it calls
* the directive's value so focus can go somewhere that stays.
*/
const focusedChild = (el, node) =>
node.parentNode === el && node.contains(el.ownerDocument.activeElement);
/**
* Place `node` before `anchor` (null: at the end) without moving `node`. Only
* elements move; the empty text nodes Vue anchors a list with stay put.
*/
function moveAround(el, node, anchor) {
const insert = (child, before) =>
Node.prototype.insertBefore.call(el, child, before);
const children = [...el.childNodes];
const from = children.indexOf(node);
const to = anchor === null ? children.length : children.indexOf(anchor);
const elements = (list) =>
list.filter((child) => child.nodeType === Node.ELEMENT_NODE);
if (to > from) {
// The rows between it and its anchor go in front of it.
for (const child of elements(children.slice(from + 1, to)))
insert(child, node);
} else {
// The rows from the anchor up to it go behind it, in order.
const after = node.nextSibling;
for (const child of elements(children.slice(to, from)))
insert(child, after);
}
return node;
}
export const vFocusSafeChildren = {
mounted(el, binding) {
el._focusSafeLeave = binding.value;
el.insertBefore = function (node, anchor) {
if (node !== anchor && focusedChild(el, node))
return moveAround(el, node, anchor ?? null);
return Node.prototype.insertBefore.call(el, node, anchor);
};
el.removeChild = function (node) {
if (focusedChild(el, node)) el._focusSafeLeave?.();
return Node.prototype.removeChild.call(el, node);
};
},
updated(el, binding) {
el._focusSafeLeave = binding.value;
},
unmounted(el) {
delete el.insertBefore;
delete el.removeChild;
delete el._focusSafeLeave;
},
};
+86
View File
@@ -0,0 +1,86 @@
import { watch } from 'vue';
import { usePanelChromeStore } from '../stores/panelChrome.js';
/** The classes a panel's state draws on its root. */
const CLASSES = Object.freeze({
collapsed: (state) => state.collapsed,
'dock-pinned': (state) => state.pinned,
'dock-pinned-top': (state) => state.pinnedTop,
'layout-auto-collapsed': (state) => state.auto === 'layout',
'accordion-collapsed': (state) => state.auto === 'accordion',
});
/**
* Draw `state` on a panel's root with `classList`, leaving other classes.
* @param {Element} el
* @param {import('../stores/panelChrome.js').PanelState} state
*/
export function applyPanelState(el, state) {
for (const [name, on] of Object.entries(CLASSES))
if (el.classList.contains(name) !== on(state))
el.classList.toggle(name, on(state));
}
/**
* Keep `el` drawing the state `store` holds for `panelId`, synchronously:
* the panel layouts measure a panel in the same task that opens or closes
* it. Until the panel is presented its markup's classes stand.
* @returns {() => void} Stops following the store.
*/
export function followPanelState(store, panelId, el) {
return watch(
() => store.panels[panelId],
(state) => state && applyPanelState(el, state),
{ flush: 'sync', immediate: true },
);
}
/**
* `v-panel-state="'data-panel'"`: the panel root draws its open, pinned and
* layout-collapsed state from the panel chrome store.
*/
export const vPanelState = {
mounted(el, binding) {
const store = usePanelChromeStore(binding.instance.$pinia);
el._panelStateStore = store;
el._stopPanelState = followPanelState(store, binding.value, el);
},
// A re-render that rewrites the root's class (its class binding changed)
// would restore the markup's state; draw the presented state again.
updated(el, binding) {
const state = el._panelStateStore?.panels[binding.value];
if (state) applyPanelState(el, state);
},
beforeUnmount(el) {
el._stopPanelState?.();
},
};
/**
* Whether the person keeps a panel closed, as share links record it: a
* collapse a layout applied only for space still counts as open.
* @param {import('../stores/panelChrome.js').PanelState} state
*/
export function prefersCollapsed(state) {
return state.collapsed && !state.auto;
}
/**
* A panel's state as its classes draw it: the markup's state, before its
* owner first presents the panel.
* @param {Element} el
* @returns {import('../stores/panelChrome.js').PanelState}
*/
export function readPanelState(el) {
const has = (name) => el.classList.contains(name);
return {
collapsed: has('collapsed'),
pinned: has('dock-pinned'),
pinnedTop: has('dock-pinned-top'),
auto: has('layout-auto-collapsed')
? 'layout'
: has('accordion-collapsed')
? 'accordion'
: null,
};
}
+12
View File
@@ -0,0 +1,12 @@
/**
* `v-range-value`: a range input's (or a select's or text field's) live
* value, written only when it differs.
* A `:value` binding would also rewrite the value attribute on every patch;
* the directive runs after the element's min, max and step are patched, so
* the value is never clamped to a stale range.
*/
const apply = (el, { value }) => {
const next = String(value);
if (el.value !== next) el.value = next;
};
export const vRangeValue = { mounted: apply, updated: apply };
+14
View File
@@ -0,0 +1,14 @@
/**
* Write a live region's message, even a repeated one, so a screen reader
* announces it again. The value is `{text, seq}`; the owner bumps `seq` for
* every message it says.
*/
export const vStatusText = {
mounted(el, { value }) {
el.textContent = value.text;
},
updated(el, { value, oldValue }) {
if (value.seq !== oldValue?.seq || value.text !== oldValue?.text)
el.textContent = value.text;
},
};
+9
View File
@@ -0,0 +1,9 @@
/**
* "HH:MM UTC" of a time, or '' when it is not one. Computed on its own rather
* than cut from the dated readout: the localized day and month vary in length
* ("3/9" in Spanish, "09-03" in English).
*/
export const utcClock = (tick) =>
Number.isFinite(Date.parse(tick))
? `${new Date(tick).toISOString().slice(11, 16)} UTC`
: '';