diff --git a/changelog.d/1867-start-layers.md b/changelog.d/1867-start-layers.md new file mode 100644 index 0000000000..d617556057 --- /dev/null +++ b/changelog.d/1867-start-layers.md @@ -0,0 +1,4 @@ +- An application can name the layers a bare address starts with + (`startLayers` on `createApplicationControls`; none by default): they turn on + without being saved as the user's own choice, and a link's own layers always + win (samehkhamis, #1867). diff --git a/changelog.d/1869-kit-sweep-final-scan.md b/changelog.d/1869-kit-sweep-final-scan.md new file mode 100644 index 0000000000..bcdfc9d9ff --- /dev/null +++ b/changelog.d/1869-kit-sweep-final-scan.md @@ -0,0 +1,3 @@ +- The view scan now forbids any hand-written button, Material glyph, + checkbox or range in the views, and any control built in script + (manjunath22466, samehkhamis, #1869). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index ce7a0e21c7..1ffe45ca03 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -8866,6 +8866,9 @@ remembers" are different promises: a link restores what its hash carries, and a bare URL starts with the default layers and options (`src/ui/shareRestoration.js` passes `allowLocalState: false`), so clearing the address always resets the view. + A host may name the layers a bare URL starts with (`startLayers` on + `createApplicationControls`, e.g. `['flights', 'satellites']`); they are + restored passively, never written to storage, and a link's own layers win. - **Detection mode/density and scope feather have NO storage key at all.** Their only durable carrier is the URL hash (`dm`/`dd`, `scf`), written on a 500 ms debounce. A same-URL reload therefore keeps them only if that debounce already diff --git a/docs/VUE-MIGRATION.md b/docs/VUE-MIGRATION.md index bbe5450990..aa2909df10 100644 --- a/docs/VUE-MIGRATION.md +++ b/docs/VUE-MIGRATION.md @@ -84,6 +84,21 @@ Home and End), since each of Core's groups keeps its own keyboard policy, and once and asks for a change only when it lands on another option. Every segmented group in Core is a `UiSegmented`; the old `segmentedControl.js` adapter is gone. +No view hand-writes a control the kit has: every button in an SFC outside +the kit is a `UiButton`, `UiCloseButton` or another kit control, every +Material Symbols glyph a `UiIcon`, every checkbox a `UiCheckbox`, every +select a `UiSelect`, and every range a `UiSlider` except the radio +tuner's and the world timeline's, for the reasons given below. No module +outside the kit, and no SFC's script, builds a button, select, field or +Material glyph in script or writes one as markup in a string, apart from +the globe panel's standalone page (`src/tools/globePanel.js`), plain HTML +a host serves with no Vue or kit, whose Expand and Open buttons are +written as markup (`src/ui/kit/viewControls.test.mjs` pins all of it). +The native fields left are the text, number, password and file inputs +and the two text areas (the chat's message box and the scene dialog's +multiline field) the kit has no control for, and the search fields whose +surfaces this document names. The scene dialog's single-line field takes +its type from its caller, which passes text-like types only. `UiButton` adds `pressedClass`, Core's class on a pressed toggle (most use `active`); its pressed classes toggle through `classList`, so a class other code adds (a voice highlight) survives a press. Every pressed toggle (a diff --git a/src/app/controls.js b/src/app/controls.js index 8e152a1e02..e7965f39ed 100644 --- a/src/app/controls.js +++ b/src/app/controls.js @@ -21,6 +21,8 @@ export { START_VIEW }; * `homeView` is where the title's logo goes back to (with the clock live): the * start view unless given, for a host whose `startView` only carries a view * across a rebuild. + * `startLayers` are the layer ids a bare address (one that carries no link) + * starts with: none by default; a host may pass `['flights', 'satellites']`. * `services.cockpitSubjects` adds the application's own first-person subjects * to the Cockpit (src/cockpitSubjectProviders.js). */ @@ -36,6 +38,7 @@ export function createApplicationControls({ localePicker = true, startView = START_VIEW, homeView = startView, + startLayers = [], }) { // Every boot starts from the same view, before share restoration flies on. applyStartView(viewer, startView); @@ -59,6 +62,7 @@ export function createApplicationControls({ initialShareCode, localePicker, homeView, + startLayers, }); defer(() => styleManager.orbitController.stop()); defer(() => styleManager.hud.destroy()); diff --git a/src/data/layerState.test.mjs b/src/data/layerState.test.mjs index 116a77c883..93f4f8e568 100644 --- a/src/data/layerState.test.mjs +++ b/src/data/layerState.test.mjs @@ -3231,3 +3231,46 @@ test('an application with every layer registered keeps every requested layer', a ]); coordinator.destroy(); }); + +test('start layers turn on when nothing names any, and are never written as the user choice', async () => { + const storage = memoryStorage(); + const manager = productionManager(); + const coordinator = new LayerStateCoordinator(manager, shareSink(), { + storage, + }); + const results = await coordinator.start({ + allowLocalState: false, + startLayerIds: ['earthquakes', 'traffic', 'not-a-layer'], + }); + assert.equal(coordinator.source, 'start'); + assert.deepEqual(coordinator.getDurableState().enabledLayerIds, [ + 'earthquakes', + 'traffic', + ]); + assert.equal(manager.isEnabled('earthquakes'), true); + assert.equal(manager.isEnabled('traffic'), true); + assert.equal( + results.every((result) => result.persistenceWrite === false), + true, + ); + assert.deepEqual(storage.writes, []); + coordinator.destroy(); +}); + +test('a shared layer payload wins over start layers', async () => { + const manager = productionManager(); + const coordinator = new LayerStateCoordinator(manager, shareSink(), { + storage: memoryStorage(), + }); + const shared = createDefaultLayerState(); + shared.enabledLayerIds = ['radio']; + await coordinator.start({ + shareLayerState: shared, + allowLocalState: false, + startLayerIds: ['earthquakes'], + }); + assert.equal(coordinator.source, 'share'); + assert.deepEqual(coordinator.getDurableState().enabledLayerIds, ['radio']); + assert.equal(manager.isEnabled('earthquakes'), false); + coordinator.destroy(); +}); diff --git a/src/data/layerStateCoordinator.js b/src/data/layerStateCoordinator.js index 7cd5545392..ad1b3e31aa 100644 --- a/src/data/layerStateCoordinator.js +++ b/src/data/layerStateCoordinator.js @@ -103,6 +103,7 @@ export class LayerStateCoordinator { shareLayerState = null, allowLocalState = true, shareCreatedAtMs = null, + startLayerIds = [], } = {}) { if (this._destroyed) throw new Error('Layer-state coordinator is destroyed'); @@ -125,7 +126,13 @@ export class LayerStateCoordinator { selected = this._normalize(stored); this._source = 'local'; } - } else { + } + if (!selected && startLayerIds.length) { + // The layers the application starts with when nothing names any: + // restored passively, so they are never written as the user's choice. + selected = this._normalize({ enabledLayerIds: startLayerIds }); + this._source = 'start'; + } else if (!selected && !allowLocalState) { // A valid historical camera/style share with no v2 layer payload keeps // the exact legacy default-layer behavior. It must not inherit an // unrelated recipient's saved local layer preferences. diff --git a/src/ui/applicationShell.js b/src/ui/applicationShell.js index c086cefd84..655540c924 100644 --- a/src/ui/applicationShell.js +++ b/src/ui/applicationShell.js @@ -118,6 +118,8 @@ export class StyleManager extends ShellFacade { * @param {{lon: number, lat: number, height: number, heading?: number, * pitch?: number}|null} [options.homeView] - where the title's logo goes * back to (degrees): the view the app started from. + * @param {string[]} [options.startLayers] - the layers a bare address (one + * that carries no link) starts with; none by default. */ constructor( viewer, @@ -129,6 +131,7 @@ export class StyleManager extends ShellFacade { initialShareCode = null, localePicker = true, homeView = null, + startLayers = [], } = {}, ) { super(); @@ -257,6 +260,7 @@ export class StyleManager extends ShellFacade { updateFeedback: () => this._updateGlobalLoadingFeedback(), applyFollowOffset: (followed, offset) => applyShareFollowOffset(viewer, followed, offset), + startLayers, }); this._visualSettings = new VisualSettings({ diff --git a/src/ui/kit/viewControls.test.mjs b/src/ui/kit/viewControls.test.mjs index 81ff7a7ca4..7ef7d42ba2 100644 --- a/src/ui/kit/viewControls.test.mjs +++ b/src/ui/kit/viewControls.test.mjs @@ -1,10 +1,14 @@ // The kit's every-control claims in docs/VUE-MIGRATION.md, read from every -// SFC outside the kit: every select is a UiSelect, every pressed toggle a -// UiButton with `pressed` (no template hand-writes `aria-pressed` on any -// element, as an attribute or inside a `v-bind` object, apart from the -// exceptions below), and every close, dismiss and clear button a -// UiCloseButton. -// Controls built in script are not read here. +// SFC outside the kit: every button is a kit button, every select a +// UiSelect, every checkbox a UiCheckbox, every range a UiSlider apart from +// the two named below, and every Material Symbols glyph a UiIcon; every +// pressed toggle is a UiButton with `pressed` (no template hand-writes +// `aria-pressed` on any element, as an attribute or inside a `v-bind` +// object, apart from the exceptions below), and every close, dismiss and +// clear button a UiCloseButton. Outside the kit, no module (nor an SFC's +// script) builds a button, select, field or Material glyph in script, or +// writes one as markup in a string, apart from the globe panel's standalone +// page named below. import { test } from 'node:test'; import assert from 'node:assert/strict'; import { readFileSync, readdirSync } from 'node:fs'; @@ -69,6 +73,59 @@ const HAND_WRITTEN_CLOSE = new RegExp( const tidy = (markup) => markup.replace(/\s+/g, ' '); +// The two ranges that stay native, by file (docs/VUE-MIGRATION.md says why). +const NATIVE_RANGES = { + 'src/ui/views/panels/RadioTuner.vue': 1, + 'src/ui/views/panels/WorldTimeline.vue': 1, +}; +const RAW_BUTTON = /`, 'gi'); +// An attribute and its value, read from the tag rather than other values. +const ATTRIBUTE = /([^\s=/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'/>]+)))?/g; +/** + * A tag's `type`: written, bound to a quoted literal (`:type="'checkbox'"`), + * or named in a `v-bind` object; null when it is bound to anything else. + */ +function inputType(attrs) { + for (const m of attrs.matchAll(ATTRIBUTE)) { + const name = m[1].toLowerCase(); + const value = m[2] ?? m[3] ?? m[4] ?? ''; + if (name === 'type') return value.toLowerCase(); + if (name === ':type' || name === 'v-bind:type') { + const literal = /^\s*(['`])([^'`]*)\1\s*$/.exec(value); + if (literal) return literal[2].toLowerCase(); + } + if (name === 'v-bind' || name === ':') { + const named = /\btype\s*:\s*(['`])([^'`]*)\1/.exec(value); + if (named) return named[2].toLowerCase(); + } + } + return null; +} + +/** Hand-written buttons in an SFC's template. */ +const rawButtons = (source) => + [...template(source).matchAll(RAW_BUTTON)].map((m) => m[0]); + +/** Tags in an SFC's template that draw a Material glyph by hand. */ +function materialGlyphs(source) { + const found = []; + for (const m of template(source).matchAll(ANY_TAG)) + if (!/^ + [...template(source).matchAll(INPUT_TAG)] + .filter((m) => inputType(m[1]) === type) + .map((m) => tidy(m[0])); + /** Raw selects in an SFC's template. */ const rawSelects = (source) => [...template(source).matchAll(RAW_SELECT)].map((m) => m[0]); @@ -134,6 +191,82 @@ test('the scans find each hand-written control', () => { assert.equal(handWrittenCloses(markup).length, 0, markup); }); +test('the scans find each hand-written button, glyph, checkbox and range', () => { + for (const markup of [ + '', + '', + ]) + assert.equal(rawButtons(markup).length, 1, markup); + for (const markup of [ + '', + '', + '', + ]) + assert.equal(rawButtons(markup).length, 0, markup); + + for (const markup of [ + '', + '', + '', + '', + ]) + assert.equal(materialGlyphs(markup).length, 1, markup); + for (const markup of [ + '', + '', + '', + ]) + assert.equal(materialGlyphs(markup).length, 0, markup); + + assert.equal( + nativeInputs( + '', + 'checkbox', + ).length, + 1, + ); + assert.equal( + nativeInputs( + '', + 'range', + ).length, + 1, + ); + assert.equal( + nativeInputs( + '', + 'checkbox', + ).length, + 0, + ); + assert.equal( + nativeInputs( + '', + 'checkbox', + ).length, + 0, + ); + for (const markup of [ + ``, + ``, + ``, + '', + '', + ]) + assert.equal(nativeInputs(markup, 'checkbox').length, 1, markup); + assert.equal( + nativeInputs('', 'checkbox') + .length, + 0, + ); + assert.equal( + materialGlyphs( + ``, + ).length, + 1, + ); +}); + test('the views are read: the scan reaches the views and skips the kit', () => { const files = views.map((view) => view.file); assert.ok(files.includes('src/ui/views/panels/ChatPanel.vue')); @@ -169,3 +302,138 @@ test('no view hand-writes a close button; each is a UiCloseButton', () => { found.push(`${file}: ${markup}`); assert.deepEqual(found, []); }); + +test('every button in the views is a kit button', () => { + const found = []; + for (const { file, source } of views) + for (const markup of rawButtons(source)) found.push(`${file}: ${markup}`); + assert.deepEqual(found, []); +}); + +test('every Material Symbols glyph in the views is a UiIcon', () => { + const found = []; + for (const { file, source } of views) + for (const markup of materialGlyphs(source)) + found.push(`${file}: ${markup}`); + assert.deepEqual(found, []); +}); + +test('every checkbox in the views is a UiCheckbox', () => { + const found = []; + for (const { file, source } of views) + for (const markup of nativeInputs(source, 'checkbox')) + found.push(`${file}: ${markup}`); + assert.deepEqual(found, []); +}); + +test('every range in the views is a UiSlider apart from the two named', () => { + const counts = {}; + for (const { file, source } of views) { + const n = nativeInputs(source, 'range').length; + if (n) counts[file] = n; + } + assert.deepEqual(counts, NATIVE_RANGES); +}); + +// The globe panel's standalone page: plain HTML a host serves, with no Vue +// and no kit, so its two buttons are written as markup. +const STRING_MARKUP_PAGES = new Set(['src/tools/globePanel.js']); + +/** + * Every module under src outside the kit, tests and test support, and every + * SFC's script blocks, as `{ file, source }`. + */ +function scriptSources(directory = SRC_ROOT) { + const found = []; + for (const entry of readdirSync(directory, { withFileTypes: true })) { + const absolute = path.join(directory, entry.name); + const file = path.relative(REPO_ROOT, absolute).split(path.sep).join('/'); + if (entry.isDirectory()) { + if ( + path.relative(KIT_ROOT, absolute) !== '' && + entry.name !== 'testSupport' + ) + found.push(...scriptSources(absolute)); + } else if ( + !entry.isFile() || + /\.test\.(?:js|mjs|ts)$|Fixture\.mjs$/.test(entry.name) + ) { + continue; + } else if (/\.(?:js|mjs|ts)$/.test(entry.name)) { + found.push({ file, source: readFileSync(absolute, 'utf8') }); + } else if (entry.name.endsWith('.vue')) { + const blocks = [ + ...readFileSync(absolute, 'utf8').matchAll( + /]*>([\s\S]*?)<\/script\s*>/g, + ), + ]; + found.push({ file, source: blocks.map((m) => m[1]).join('\n') }); + } + } + return found; +} + +const SCRIPT_CONTROL = + /\bcreateElement(?:NS)?\(\s*(?:[^,)]*,\s*)?['"`](?:button|select|input|textarea)['"`]/gi; +const SCRIPT_GLYPH = + /['"`][^'"`]*\bmaterial-symbols-(?:outlined|rounded|sharp|\$\{)/g; +const STRING_MARKUP = /<(?:button|select|input|textarea)\b/gi; + +/** A source with its comments blanked, line numbers kept. */ +const uncommented = (source) => + source + .replace(/\/\*[\s\S]*?\*\//g, (comment) => comment.replace(/[^\n]/g, ' ')) + .replace(/(^|[^:'"`\\])\/\/[^\n]*/g, '$1'); + +/** Each match in a source, as `file:line: text`. */ +function hits(file, source, pattern) { + return [...source.matchAll(pattern)].map((m) => { + const line = source.slice(0, m.index).split('\n').length; + return `${file}:${line}: ${source.split('\n')[line - 1].trim()}`; + }); +} + +test('no module outside the kit builds a control or Material glyph in script', () => { + const sees = (pattern, text) => [...text.matchAll(pattern)].length > 0; + assert.ok( + sees(SCRIPT_CONTROL, "const b = document.createElement('button');"), + ); + assert.ok(sees(SCRIPT_CONTROL, 'doc.createElement("INPUT")')); + assert.ok( + sees(SCRIPT_CONTROL, "someDocument.createElement(\n 'button',\n);"), + ); + assert.ok(!sees(SCRIPT_CONTROL, "document.createElement('div')")); + assert.ok( + sees(SCRIPT_GLYPH, "span.className = 'material-symbols-outlined';"), + ); + assert.ok(sees(SCRIPT_GLYPH, 'el.className = `material-symbols-${style}`;')); + assert.ok( + !sees(SCRIPT_GLYPH, 'ctx.font = \'24px "Material Symbols Outlined"\';'), + ); + assert.ok(sees(STRING_MARKUP, "host.innerHTML = '';")); + assert.ok( + !sees(STRING_MARKUP, "''".replace('', '')), + ); + + const sources = scriptSources(); + assert.ok( + sources.some(({ file }) => file === 'src/ui/views/panels/ChatPanel.vue'), + ); + const found = []; + for (const { file, source } of sources) { + found.push( + ...hits(file, source, SCRIPT_CONTROL), + ...hits(file, source, SCRIPT_GLYPH), + ); + if (!STRING_MARKUP_PAGES.has(file)) + found.push(...hits(file, uncommented(source), STRING_MARKUP)); + } + assert.deepEqual(found, []); + for (const file of STRING_MARKUP_PAGES) { + const page = sources.find((s) => s.file === file); + assert.ok( + page && hits(file, page.source, STRING_MARKUP).length, + `${file} no longer writes markup`, + ); + } +}); diff --git a/src/ui/shareRestoration.js b/src/ui/shareRestoration.js index 6d93d5061c..0b34ffbd55 100644 --- a/src/ui/shareRestoration.js +++ b/src/ui/shareRestoration.js @@ -167,7 +167,10 @@ export class ShareRestoration { feedback, updateFeedback, applyFollowOffset = null, + startLayers = [], }) { + // The layers a bare address starts with; a link names its own. + this._startLayers = startLayers; Object.assign(this, { viewer, navigation, @@ -421,6 +424,7 @@ export class ShareRestoration { // with the default layers. Saved layer choices never come back on // their own, so clearing the address always resets the view. allowLocalState: false, + startLayerIds: this._initialShareState ? [] : this._startLayers, }); if (this._initialShareSelectionSuperseded) { this._layerStateCoordinator.cancelPendingShareTracking(