diff --git a/addon-test-support/index.js b/addon-test-support/index.js index d08bf17c..ca76fe2c 100644 --- a/addon-test-support/index.js +++ b/addon-test-support/index.js @@ -1,4 +1,6 @@ import { render } from '@ember/test-helpers'; +import { shellState } from '@fleetbase/ember-ui/services/shell'; +import { sheetStack } from '@fleetbase/ember-ui/utils/sheet-stack'; /** * Test helpers for the canvas layout (`Layout::Canvas` and the pieces that @@ -113,3 +115,19 @@ export async function renderShell(template, { theme = 'light' } = {}) { export function shellToken(name, element = document.body) { return getComputedStyle(element).getPropertyValue(`--fb-${name}`).trim(); } + +/** + * The shell layout (`shellState`) and the open-sheet stack are page-wide + * module state, shared by the host and its engines. Reset both before each + * test so a layout set or a sheet left open in one test cannot leak into the + * next: `QUnit.testStart(resetShellState)` in `tests/test-helper.js`, or + * `setupShellState(hooks)` per module. + */ +export function resetShellState() { + shellState.reset(); + sheetStack.reset(); +} + +export function setupShellState(hooks) { + hooks.beforeEach(resetShellState); +} diff --git a/addon/components/layout/canvas.hbs b/addon/components/layout/canvas.hbs index 5351f92c..7b2897c8 100644 --- a/addon/components/layout/canvas.hbs +++ b/addon/components/layout/canvas.hbs @@ -3,7 +3,7 @@ {{#if (has-block "backdrop")}} {{yield to="backdrop"}} {{else}} - + {{/if}}
@@ -14,4 +14,4 @@ {{yield to="chrome"}} {{/if}} - \ No newline at end of file + diff --git a/addon/components/layout/canvas.js b/addon/components/layout/canvas.js new file mode 100644 index 00000000..204654e6 --- /dev/null +++ b/addon/components/layout/canvas.js @@ -0,0 +1,24 @@ +import Component from '@glimmer/component'; +import { inject as service } from '@ember/service'; + +/** + * `Layout::Canvas` — the canvas shell root: backdrop, content and chrome layers. + * + * Without a `<:backdrop>` block the backdrop layer renders + * `Layout::Canvas::BackdropHost`, which shows the route's registered backdrop + * (a live map) or the dot grid. While mounted it marks the `shell` service's + * layout as `canvas`, so record panels render as sheets. + */ +export default class LayoutCanvasComponent extends Component { + @service shell; + + constructor() { + super(...arguments); + this.shell.canvasDidMount(); + } + + willDestroy() { + super.willDestroy(...arguments); + this.shell.canvasWillUnmount(); + } +} diff --git a/addon/components/layout/canvas/backdrop-host.hbs b/addon/components/layout/canvas/backdrop-host.hbs new file mode 100644 index 00000000..8fd04de3 --- /dev/null +++ b/addon/components/layout/canvas/backdrop-host.hbs @@ -0,0 +1,22 @@ +
+ {{#each this.entries key="name" as |entry|}} +
+ {{#if entry.isEngineComponent}} + + {{else}} + {{component entry.component registration=entry.registration isActive=entry.isActive state=this.state backdrop=this.backdrop}} + {{/if}} +
+ {{/each}} + {{#unless this.hasActive}} + + {{/unless}} +
diff --git a/addon/components/layout/canvas/backdrop-host.js b/addon/components/layout/canvas/backdrop-host.js new file mode 100644 index 00000000..185f452c --- /dev/null +++ b/addon/components/layout/canvas/backdrop-host.js @@ -0,0 +1,90 @@ +import Component from '@glimmer/component'; +import { getOwner } from '@ember/application'; +import { optionalService } from '../../../utils/shell'; + +/** + * `Layout::Canvas::BackdropHost` — renders the canvas backdrop from ember-core's + * `backdrop` service. + * + * Every registration in `backdrop.mounted` renders once, keyed by name, inside + * its own slot. Only the `active` one is visible; the others are hidden with + * `visibility: hidden` and `inert`, never torn down, so a keep-alive live map + * survives a visit to a page without one. With no active backdrop (or no + * `backdrop` service at all) the dot grid shows. + * + * A registration is `{ name, component, routes, priority, keepAlive }`. The + * component is a class, a component name, or an engine's `ExtensionComponent`. + * A class or name receives these arguments; an `ExtensionComponent` is rendered + * through `LazyEngineComponent` and receives the same values as `@params` + * (`@params.registration`, …): + * - `registration` the registration itself + * - `isActive` whether it is the visible backdrop + * - `state` the service's merged `state` (`{ layers, fitBounds, focus, mode }`) + * - `backdrop` the service, for `setInstance(map)` and `onReady()` + * + * The host never sets `pointer-events` on the backdrop layer or its slots, so + * an engine that portals its map into the slot keeps full interaction. + * + * While a backdrop is active, the canvas content layer stops taking the pointer + * in its gaps (see `layout/canvas.css`), so the map stays draggable around the + * floating cards. + */ +/** + * Whether a registration's component comes from an engine: an ember-core + * `ExtensionComponent` (`{ engine, path | class }`) or its string form + * `#extension-component::`. Those render through + * `LazyEngineComponent`, which loads the engine first. + */ +export function isEngineComponent(component) { + if (typeof component === 'string') { + return component.startsWith('#extension-component'); + } + return typeof component === 'object' && component !== null && Boolean(component.engine); +} + +export default class LayoutCanvasBackdropHostComponent extends Component { + get backdrop() { + return optionalService(getOwner(this), 'backdrop'); + } + + get active() { + return this.backdrop?.active ?? null; + } + + get state() { + return this.backdrop?.state ?? null; + } + + /** + * The registrations to render. Falls back to just the active one when the + * service has no `mounted` list. + */ + get entries() { + const backdrop = this.backdrop; + if (!backdrop) { + return []; + } + + const active = this.active; + const mounted = Array.isArray(backdrop.mounted) ? backdrop.mounted : []; + const registrations = mounted.length || !active ? mounted : [active]; + + return registrations + .filter((registration) => registration && registration.name && registration.component) + .map((registration) => { + const isActive = Boolean(active) && registration.name === active.name; + return { + name: registration.name, + component: registration.component, + isEngineComponent: isEngineComponent(registration.component), + registration, + isActive, + inert: isActive ? undefined : true, + }; + }); + } + + get hasActive() { + return this.entries.some((entry) => entry.isActive); + } +} diff --git a/addon/components/layout/resource/panel.hbs b/addon/components/layout/resource/panel.hbs index 152aec32..e787d6e1 100644 --- a/addon/components/layout/resource/panel.hbs +++ b/addon/components/layout/resource/panel.hbs @@ -1,63 +1,135 @@ - - {{#if @headerComponent}} - {{! Invoked with angle brackets so `class` lands as an ATTRIBUTE. In the curly form it - arrives as the `@class` argument, which a Glimmer component drops — losing both the - caller's @headerClass and the addon's own resource-panel-header styling hook. }} - {{#let (component @headerComponent) as |CustomHeader|}} - + <:header> + {{#if @headerComponent}} + {{! Invoked with angle brackets so `class` lands as an ATTRIBUTE. In the curly form it + arrives as the `@class` argument, which a Glimmer component drops — losing both the + caller's @headerClass and the addon's own resource-panel-header styling hook. }} + {{#let (component @headerComponent) as |CustomHeader|}} + + {{/let}} + {{else}} + + {{/if}} + + <:body> +
+ {{yield this.resource}} +
+ + +{{else}} + + {{#if @headerComponent}} + {{! Invoked with angle brackets so `class` lands as an ATTRIBUTE. In the curly form it + arrives as the `@class` argument, which a Glimmer component drops — losing both the + caller's @headerClass and the addon's own resource-panel-header styling hook. }} + {{#let (component @headerComponent) as |CustomHeader|}} + + {{/let}} + {{else}} + - {{/let}} - {{else}} - - {{/if}} + {{/if}} - - {{yield this.resource}} - - \ No newline at end of file + + {{yield this.resource}} + +
+{{/if}} diff --git a/addon/components/layout/resource/panel.js b/addon/components/layout/resource/panel.js index 22ea8a42..07344f15 100644 --- a/addon/components/layout/resource/panel.js +++ b/addon/components/layout/resource/panel.js @@ -5,6 +5,7 @@ import { action } from '@ember/object'; import { getOwner } from '@ember/application'; import contextComponentCallback from '@fleetbase/ember-core/utils/context-component-callback'; import applyContextComponentArguments from '@fleetbase/ember-core/utils/apply-context-component-arguments'; +import { shellState } from '../../../services/shell'; import lookupResourceView, { mergeHeaderButtons } from '../../../utils/resource-view'; export default class LayoutResourcePanelComponent extends Component { @@ -17,6 +18,38 @@ export default class LayoutResourcePanelComponent extends Component { @service contextPanel; @tracked overlayContext; + /** + * In the canvas layout the panel renders as a `Sheet`; in classic as the + * right-hand `Overlay` it always was. `@layout` (`canvas` | `classic`) + * overrides the shell layout (`shellState`, which engines can read too). + */ + get isCanvas() { + if (this.args.layout) { + return this.args.layout === 'canvas'; + } + return shellState.isCanvas; + } + + get sheetTitle() { + return this.args.headerTitle ?? this.resource?.name ?? this.resource?.displayName; + } + + /** + * `@sheetWidth` (a Sheet preset or length) wins; otherwise `@width`, which in + * the classic layout is an Overlay width such as `600px`. + */ + get sheetWidth() { + return this.args.sheetWidth ?? this.args.width ?? 'md'; + } + + get sheetMinWidth() { + return parseInt(this.args.minResizeWidth, 10) || undefined; + } + + get sheetMaxWidth() { + return parseInt(this.args.maxResizeWidth, 10) || undefined; + } + // Mirror args (reactive) get resource() { return this.args.resource; @@ -62,6 +95,18 @@ export default class LayoutResourcePanelComponent extends Component { contextComponentCallback(this, 'onOverlayReady', ...arguments); } + /** + * The canvas counterpart of `setOverlayContext`: the sheet's API stands in + * for the overlay context, and the panel's onLoad/onOpen callbacks fire as + * the sheet mounts. + */ + @action setSheetContext(sheet) { + this.context = sheet; + contextComponentCallback(this, 'onLoad', sheet); + contextComponentCallback(this, 'onOverlayReady', sheet); + contextComponentCallback(this, 'onOpen', { resource: this.resource, panel: sheet }); + } + @action onPressCancel() { return contextComponentCallback(this, 'onPressCancel', this.resource); } diff --git a/addon/components/layout/view-switch.hbs b/addon/components/layout/view-switch.hbs new file mode 100644 index 00000000..0042b1a8 --- /dev/null +++ b/addon/components/layout/view-switch.hbs @@ -0,0 +1,33 @@ +
+
+ {{#each this.views key="id" as |option|}} + + {{/each}} +
+ {{#if (or (has-block "actions") this.primaryAction)}} + + {{#if (has-block "actions")}} + {{yield to="actions"}} + {{else}} + + {{/if}} + {{/if}} +
diff --git a/addon/components/layout/view-switch.js b/addon/components/layout/view-switch.js new file mode 100644 index 00000000..b3182b41 --- /dev/null +++ b/addon/components/layout/view-switch.js @@ -0,0 +1,117 @@ +import Component from '@glimmer/component'; +import { tracked } from '@glimmer/tracking'; +import { action } from '@ember/object'; +import { inject as service } from '@ember/service'; +import { activateItem, isRouteActive } from '../../utils/shell'; + +export const DEFAULT_VIEWS = [ + { id: 'map', label: 'Map' }, + { id: 'table', label: 'Table' }, + { id: 'board', label: 'Board' }, +]; + +const NEXT_KEYS = ['ArrowRight', 'ArrowDown']; +const PREVIOUS_KEYS = ['ArrowLeft', 'ArrowUp']; + +/** + * `Layout::ViewSwitch` — the floating segmented pill, top-centre over the + * canvas, that switches a page between its views (C2, J1) and carries the + * page's primary action. + * + * ```hbs + * + * ``` + * + * - `@views` `[{ id, label, count?, route?, models?, query? }]`; Map, Table and + * Board when omitted. + * - `@selected` the selected view id. Without it, the view whose `route` is + * active is selected, else the last one clicked (the first to start with). + * - `@onChange(id, view)` is called on selection. Without it a view with a + * `route` navigates there. + * - `@primaryAction` `{ label, icon?, onClick | action | route }`, or an + * `<:actions>` block for anything else. + * - `@label` the radio group's accessible name (default "View"). + * + * The views are a radio group: arrow keys, Home and End move the selection. + */ +export default class LayoutViewSwitchComponent extends Component { + @service router; + @tracked lastSelected = null; + + get views() { + const views = Array.isArray(this.args.views) ? this.args.views : DEFAULT_VIEWS; + const selected = this.selectedId(views); + return views.map((view) => { + const isSelected = view.id === selected; + return { ...view, isSelected, hasCount: view.count !== undefined && view.count !== null }; + }); + } + + selectedId(views) { + if (this.args.selected !== undefined && this.args.selected !== null) { + return this.args.selected; + } + + const routed = views.filter((view) => isRouteActive(this.router, view.route)).sort((a, b) => b.route.length - a.route.length)[0]; + if (routed) { + return routed.id; + } + + if (this.lastSelected && views.some((view) => view.id === this.lastSelected)) { + return this.lastSelected; + } + + return views[0]?.id; + } + + get primaryAction() { + const primary = this.args.primaryAction; + return primary && primary.label ? primary : null; + } + + @action select(view) { + this.lastSelected = view.id; + + if (typeof this.args.onChange === 'function') { + return this.args.onChange(view.id, view); + } + + if (view.route) { + return activateItem(this.router, view); + } + } + + @action runPrimary() { + return activateItem(this.router, this.primaryAction); + } + + @action onKeydown(event) { + const views = this.views; + const current = views.findIndex((view) => view.isSelected); + let next = null; + + if (NEXT_KEYS.includes(event.key)) { + next = (current + 1) % views.length; + } else if (PREVIOUS_KEYS.includes(event.key)) { + next = (current - 1 + views.length) % views.length; + } else if (event.key === 'Home') { + next = 0; + } else if (event.key === 'End') { + next = views.length - 1; + } + + if (next === null) { + return; + } + + event.preventDefault(); + const radios = event.currentTarget.querySelectorAll('[role="radio"]'); + this.select(views[next]); + radios[next].focus(); + } +} diff --git a/addon/components/resource-context-panel.hbs b/addon/components/resource-context-panel.hbs index 7479b291..c24f87a5 100644 --- a/addon/components/resource-context-panel.hbs +++ b/addon/components/resource-context-panel.hbs @@ -1,5 +1,13 @@ -{{#each this.computedOverlays as |overlay|}} +{{! Keyed by id in the canvas layout so a stacked sheet is not re-created (and its focus and + scroll lost) whenever another overlay opens; classic keeps its original identity keying. }} +{{#each this.computedOverlays key=this.eachKey as |overlay index|}} {{/each}} -{{#if this.activeOverlay.dismissible}} +{{#if this.showDismissBackdrop}}
{{/if}} \ No newline at end of file diff --git a/addon/components/resource-context-panel.js b/addon/components/resource-context-panel.js index 824fe9e9..bd367bf0 100644 --- a/addon/components/resource-context-panel.js +++ b/addon/components/resource-context-panel.js @@ -5,6 +5,7 @@ import { task } from 'ember-concurrency'; import { dasherize } from '@ember/string'; import isModel from '@fleetbase/ember-core/utils/is-model'; import getModelName from '@fleetbase/ember-core/utils/get-model-name'; +import { shellState } from '../services/shell'; /** * Component that integrates with the resource-context-panel service @@ -31,6 +32,43 @@ export default class ResourceContextPanelComponent extends Component { fullscreen: '100vw', }; + /** + * Map of overlay sizes to Sheet width presets, for the canvas layout. + * @type {Object} + */ + sheetSizeMap = { + xxs: 'sm', + xs: 'md', + sm: 'md', + md: 'md', + lg: 'lg', + xl: 'lg', + fullscreen: 'lg', + }; + + /** + * `canvas` or `classic`: `@layout` when given, else the shell's (`shellState`). + * In the canvas layout each overlay renders as a Sheet stacked with spines, + * Escape is left to the sheets, and no click-catching backdrop is drawn (a + * sheet floats over the live map without blocking it). + * @type {String} + */ + get layout() { + return this.args.layout ?? shellState.layout; + } + + get isCanvas() { + return this.layout === 'canvas'; + } + + get eachKey() { + return this.isCanvas ? 'id' : '@identity'; + } + + get showDismissBackdrop() { + return !this.isCanvas && Boolean(this.activeOverlay?.dismissible); + } + /** * Map of overlay sizes to resizable settings. * @type {Object} @@ -66,6 +104,8 @@ export default class ResourceContextPanelComponent extends Component { model: resource, title: overlay.title ?? resource?.name ?? resource?.displayName, computedWidth: overlay.width ?? this.sizeMap[overlay.size] ?? this.sizeMap.sm, + computedSheetWidth: overlay.width ?? this.sheetSizeMap[overlay.size] ?? this.sheetSizeMap.sm, + canPark: this.resourceContextPanel.canPark(overlay), computedResizable: this.resizableMap[overlay.size] !== undefined ? this.resizableMap[overlay.size] : true, saveOptions: { ...(overlay.saveOptions ?? {}), @@ -135,6 +175,28 @@ export default class ResourceContextPanelComponent extends Component { this.resourceContextPanel.close(id); } + /** + * Brings a stacked overlay to the front (a sheet's spine was clicked). + * + * @method bringToFront + * @param {String} id - The overlay ID + * @action + */ + @action bringToFront(id) { + this.resourceContextPanel.bringToFront(id); + } + + /** + * Parks an overlay (see the service's `park()`). + * + * @method parkOverlay + * @param {String} id - The overlay ID + * @action + */ + @action parkOverlay(id) { + this.resourceContextPanel.park(id); + } + /** * Closes the active overlay. * @@ -187,7 +249,8 @@ export default class ResourceContextPanelComponent extends Component { * @action */ @action handleKeydown(event) { - if (event.key === 'Escape') { + // In the canvas layout the top Sheet handles Escape (see the sheet-stack service). + if (event.key === 'Escape' && !this.isCanvas) { const activeOverlay = this.resourceContextPanel.getActive(); if (activeOverlay && activeOverlay.dismissible) { this.closeActiveOverlay(); diff --git a/addon/components/sheet.hbs b/addon/components/sheet.hbs new file mode 100644 index 00000000..192f8cd1 --- /dev/null +++ b/addon/components/sheet.hbs @@ -0,0 +1,78 @@ + diff --git a/addon/components/sheet.js b/addon/components/sheet.js new file mode 100644 index 00000000..23740696 --- /dev/null +++ b/addon/components/sheet.js @@ -0,0 +1,318 @@ +import Component from '@glimmer/component'; +import { tracked } from '@glimmer/tracking'; +import { action } from '@ember/object'; +import { guidFor } from '@ember/object/internals'; +import { getOwner } from '@ember/application'; +import { sheetStack } from '../utils/sheet-stack'; +import { optionalService } from '../utils/shell'; + +/** Width presets in px. */ +export const SHEET_WIDTHS = { sm: 360, md: 440, lg: 640 }; + +/** How far each sheet below the top one is pushed in, in px: the width of its spine. */ +export const SPINE_WIDTH = 28; + +/** Sheets deeper than this behind the top one are hidden (still mounted). */ +export const MAX_SPINES = 3; + +export const RESIZE_STEP = 20; + +const FOCUSABLE = [ + 'a[href]', + 'area[href]', + 'button:not([disabled])', + 'input:not([disabled]):not([type="hidden"])', + 'select:not([disabled])', + 'textarea:not([disabled])', + 'iframe', + '[contenteditable]:not([contenteditable="false"])', + '[tabindex]:not([tabindex="-1"])', +].join(','); + +/** + * `Sheet` — the canvas shell's floating card for a record or a form, docked to + * the right (default) or left of the content area. + * + * ```hbs + * + * <:header as |sheet|>… + * <:body>… + * <:footer>… + * + * ``` + * + * Arguments + * - `@title` heading, spine label and accessible name (`@label` overrides the name) + * - `@side` `right` | `left` + * - `@width` `sm` (360) | `md` (440, default) | `lg` (640) | a number of px | any CSS length + * - `@resizable` adds a drag/keyboard handle on the inner edge; `@minWidth` (320), + * `@maxWidth` (960) clamp it and `@onResize(px)` reports the new width + * - `@onClose` shows × and is called by it and by Escape (when `@closeOnEscape` + * is not false); `@showClose={{false}}` hides × when the header has its own + * - `@onPark` shows the park button and is called by it + * - `@stackIndex` / `@stackSize` position this sheet in a stack (0 = bottom). + * Sheets behind the top one are pushed in by a spine each; clicking a spine + * calls `@onActivate`. Their content stays mounted but is `inert`; sheets more + * than three deep are hidden. + * - `@onOpen(sheet)` is called once mounted with `{ element, close, park, activate }` + * - `@autofocus` (default true) moves focus into the sheet when it mounts on + * top, and focus returns where it was when it closes. + * + * Blocks: `<:header>` (replaces the default title; yields `{ close, park, isTop }`), + * `<:body>` or the default block, `<:footer>`. + * + * While it is the top sheet, Tab and Shift+Tab cycle inside it, and Escape (see + * `utils/sheet-stack`) closes it unless a modal is open. + */ +export default class SheetComponent extends Component { + sheetStack = sheetStack; + @tracked customWidth = null; + + id = guidFor(this); + element = null; + #previousFocus = null; + #drag = null; + + get titleId() { + return `${this.id}-title`; + } + + get side() { + return this.args.side === 'left' ? 'left' : 'right'; + } + + get stackSize() { + const size = Number(this.args.stackSize); + return Number.isFinite(size) && size > 0 ? size : 1; + } + + get stackIndex() { + const index = Number(this.args.stackIndex); + return Number.isFinite(index) ? Math.min(Math.max(index, 0), this.stackSize - 1) : this.stackSize - 1; + } + + /** 0 for the top sheet, 1 for the one under it, … */ + get depth() { + return this.stackSize - 1 - this.stackIndex; + } + + get isTop() { + return this.depth === 0; + } + + get isSpine() { + return this.depth > 0 && this.depth <= MAX_SPINES; + } + + get isHidden() { + return this.depth > MAX_SPINES; + } + + get panelInert() { + return this.isTop ? undefined : true; + } + + get offset() { + return `${Math.min(this.depth, MAX_SPINES) * SPINE_WIDTH}px`; + } + + get minWidth() { + return this.args.minWidth ?? 320; + } + + get maxWidth() { + return this.args.maxWidth ?? 960; + } + + get presetWidth() { + const width = this.args.width ?? 'md'; + if (typeof width === 'number') { + return width; + } + if (SHEET_WIDTHS[width]) { + return SHEET_WIDTHS[width]; + } + const px = /^(\d+(?:\.\d+)?)(px)?$/.exec(String(width).trim()); + return px ? Number(px[1]) : null; + } + + /** The width as a CSS value. */ + get width() { + if (this.customWidth !== null) { + return `${this.customWidth}px`; + } + const preset = this.presetWidth; + return preset === null ? String(this.args.width) : `${preset}px`; + } + + get widthValue() { + return this.customWidth ?? this.presetWidth ?? this.element?.offsetWidth ?? this.minWidth; + } + + get label() { + return this.args.label ?? this.args.title; + } + + get showClose() { + return typeof this.args.onClose === 'function' && this.args.showClose !== false; + } + + get showPark() { + return typeof this.args.onPark === 'function'; + } + + get isResizable() { + return Boolean(this.args.resizable) && this.isTop; + } + + // ── Lifecycle ────────────────────────────────────────────────────────── + + @action didInsert(element) { + this.element = element; + this.sheetStack.register(this); + + if (this.isTop && this.args.autofocus !== false) { + this.#previousFocus = document.activeElement; + element.focus({ preventScroll: true }); + } + + if (typeof this.args.onOpen === 'function') { + this.args.onOpen({ element, close: this.close, park: this.park, activate: this.activate }); + } + } + + willDestroy() { + super.willDestroy(...arguments); + this.sheetStack.unregister(this); + this.#endDrag(); + + // Focus goes back where it came from, unless the user has since moved it elsewhere. + const previous = this.#previousFocus; + const focusWasInside = this.element.contains(document.activeElement) || document.activeElement === document.body; + if (previous && previous.isConnected && focusWasInside) { + previous.focus({ preventScroll: true }); + } + this.element = null; + } + + // ── Actions ──────────────────────────────────────────────────────────── + + @action close() { + if (typeof this.args.onClose === 'function') { + this.args.onClose(); + } + } + + @action park() { + if (typeof this.args.onPark === 'function') { + this.args.onPark(); + } + } + + @action activate() { + if (typeof this.args.onActivate === 'function') { + this.args.onActivate(); + } + } + + /** Called by the sheet stack on Escape. Returns whether the sheet handled it. */ + escape() { + if (this.args.closeOnEscape === false || typeof this.args.onClose !== 'function') { + return false; + } + // A modal over the sheets gets Escape first. Looked up optionally: inside an engine the + // owner may not have ember-ui's modals-manager. + if (optionalService(getOwner(this), 'modals-manager')?.modalIsOpened) { + return false; + } + this.close(); + return true; + } + + @action trapFocus(event) { + if (event.key !== 'Tab' || !this.sheetStack.isTop(this)) { + return; + } + + const focusables = [...this.element.querySelectorAll(FOCUSABLE)].filter((element) => !element.closest('[inert]') && element.getClientRects().length > 0); + if (focusables.length === 0) { + event.preventDefault(); + this.element.focus({ preventScroll: true }); + return; + } + + const first = focusables[0]; + const last = focusables[focusables.length - 1]; + const current = document.activeElement; + + if (event.shiftKey && (current === first || current === this.element)) { + event.preventDefault(); + last.focus(); + } else if (!event.shiftKey && current === last) { + event.preventDefault(); + first.focus(); + } + } + + // ── Resizing ─────────────────────────────────────────────────────────── + + clamp(width) { + return Math.round(Math.min(Math.max(width, this.minWidth), this.maxWidth)); + } + + setWidth(width) { + const next = this.clamp(width); + if (next !== this.customWidth) { + this.customWidth = next; + if (typeof this.args.onResize === 'function') { + this.args.onResize(next); + } + } + } + + /** +1 when moving the pointer right widens the sheet (left side), -1 otherwise. */ + get growDirection() { + return this.side === 'left' ? 1 : -1; + } + + @action startResize(event) { + if (event.button !== undefined && event.button !== 0) { + return; + } + event.preventDefault(); + this.#endDrag(); + this.#drag = { startX: event.clientX, startWidth: this.element.offsetWidth }; + window.addEventListener('pointermove', this.onPointerMove); + window.addEventListener('pointerup', this.onPointerUp); + window.addEventListener('pointercancel', this.onPointerUp); + } + + onPointerMove = (event) => { + // Only listening between pointerdown and pointerup, so a drag is always in progress here. + const delta = (event.clientX - this.#drag.startX) * this.growDirection; + this.setWidth(this.#drag.startWidth + delta); + }; + + onPointerUp = () => { + this.#endDrag(); + }; + + #endDrag() { + this.#drag = null; + window.removeEventListener('pointermove', this.onPointerMove); + window.removeEventListener('pointerup', this.onPointerUp); + window.removeEventListener('pointercancel', this.onPointerUp); + } + + @action resizeWithKeyboard(event) { + const grow = this.side === 'left' ? 'ArrowRight' : 'ArrowLeft'; + const shrink = this.side === 'left' ? 'ArrowLeft' : 'ArrowRight'; + const current = this.widthValue; + const steps = { [grow]: current + RESIZE_STEP, [shrink]: current - RESIZE_STEP, Home: this.minWidth, End: this.maxWidth }; + + if (event.key in steps) { + event.preventDefault(); + this.setWidth(steps[event.key]); + } + } +} diff --git a/addon/services/resource-context-panel.js b/addon/services/resource-context-panel.js index 7cdbdd13..b99b9d40 100644 --- a/addon/services/resource-context-panel.js +++ b/addon/services/resource-context-panel.js @@ -1,4 +1,5 @@ import Service, { inject as service } from '@ember/service'; +import Evented from '@ember/object/evented'; import { tracked } from '@glimmer/tracking'; import { action } from '@ember/object'; import { guidFor } from '@ember/object/internals'; @@ -12,7 +13,7 @@ import { guidFor } from '@ember/object/internals'; * @memberof @fleetbase/ember-ui * @extends Service */ -export default class ResourceContextPanelService extends Service { +export default class ResourceContextPanelService extends Service.extend(Evented) { @service router; @service notifications; @@ -31,6 +32,23 @@ export default class ResourceContextPanelService extends Service { */ @tracked activeTabs = {}; + /** + * Overlays parked out of the stack, oldest first. Nothing renders them yet: + * the canvas taskbar (shell phase 4) lists them and calls `unpark()`. + * @type {Array} + * @tracked + */ + @tracked parked = []; + + /** + * Whether panels offer a park button. Off until something can show parked + * panels again (the taskbar calls `enableParking()`); an overlay can also + * opt in on its own with `parkable: true` or an `onPark` hook. + * @type {Boolean} + * @tracked + */ + @tracked parkingEnabled = false; + /** * @private * Tracks registered route change listeners for overlays that should close on transition. @@ -168,6 +186,84 @@ export default class ResourceContextPanelService extends Service { } } + /** + * Turns the park button on (or off) for every panel. + * + * @method enableParking + * @param {Boolean} [enabled=true] + */ + @action enableParking(enabled = true) { + this.parkingEnabled = Boolean(enabled); + } + + /** + * Whether an overlay can be parked. + * + * @method canPark + * @param {OverlayDefinition} overlay + * @returns {Boolean} + */ + canPark(overlay) { + return Boolean(overlay) && (this.parkingEnabled || overlay.parkable === true || typeof overlay.onPark === 'function'); + } + + /** + * Moves an overlay out of the stack into `parked`, keeping its definition + * (and active tab) so `unpark()` can bring it back. Triggers + * `overlay.parked` with the overlay and calls its `onPark` hook. + * + * @method park + * @param {String} [id] - The overlay ID; the active overlay when omitted + * @returns {OverlayDefinition|null} The parked overlay + */ + @action park(id) { + const overlay = id ? this.getById(id) : this.getActive(); + if (!overlay) { + return null; + } + + this.overlays = this.overlays.filter((open) => open !== overlay); + this.parked = [...this.parked, overlay]; + + if (typeof overlay.onPark === 'function') { + overlay.onPark({ resource: overlay.resource ?? overlay.model, model: overlay.resource ?? overlay.model, unpark: () => this.unpark(overlay.id) }); + } + this.trigger('overlay.parked', overlay); + + return overlay; + } + + /** + * Puts a parked overlay back on top of the stack. Triggers `overlay.unparked`. + * + * @method unpark + * @param {String} id - The overlay ID + * @returns {OverlayDefinition|null} The restored overlay + */ + @action unpark(id) { + const overlay = this.parked.find((parked) => parked.id === id); + if (!overlay) { + return null; + } + + this.parked = this.parked.filter((parked) => parked !== overlay); + this.overlays = [...this.overlays, overlay]; + this.trigger('overlay.unparked', overlay); + + return overlay; + } + + /** + * Whether an overlay is parked. + * + * @method isParked + * @param {String} id - The overlay ID + * @returns {Boolean} + */ + isParked(id) { + return this.parked.some((parked) => parked.id === id); + } + /** * Closes all open overlay panels. * diff --git a/addon/services/shell.js b/addon/services/shell.js new file mode 100644 index 00000000..911d1cb1 --- /dev/null +++ b/addon/services/shell.js @@ -0,0 +1,107 @@ +import Service from '@ember/service'; +import { tracked } from '@glimmer/tracking'; +import { schedule } from '@ember/runloop'; + +export const LAYOUTS = ['classic', 'canvas']; + +/** + * The layout state itself, one per page. It lives at module level, not on the + * service, because components that read it (`Layout::Resource::Panel`, `Sheet`) + * also render inside engines, whose owners do not have this service: they + * import `shellState` instead of injecting it, and see the same value as the + * host. + */ +class ShellState { + // No initializers: @tracked initializers run lazily on first read, and reset() always writes + // first, so they would never execute. The constructor sets the starting values instead. + @tracked explicitLayout; + @tracked mountedCanvases; + + constructor() { + this.reset(); + } + + get layout() { + return this.mountedCanvases > 0 ? 'canvas' : this.explicitLayout; + } + + get isCanvas() { + return this.layout === 'canvas'; + } + + reset() { + this.explicitLayout = 'classic'; + this.mountedCanvases = 0; + } +} + +export const shellState = new ShellState(); + +/** + * Which application shell is on screen: `classic` (sidebar and header) or + * `canvas` (Map-Canvas+ floating chrome). + * + * The console sets the layout with `setLayout()` when it picks a shell; + * `Layout::Canvas` also marks the canvas layout while it is mounted, so a + * canvas rendered without the console (tests, the playground) behaves the + * same. Components read `shellState` (exported above), which works in engines + * too. + * + * @class ShellService + * @extends Service + */ +export default class ShellService extends Service { + state = shellState; + + get explicitLayout() { + return shellState.explicitLayout; + } + + get mountedCanvases() { + return shellState.mountedCanvases; + } + + /** `canvas` while a canvas is mounted or the console chose it, else `classic`. */ + get layout() { + return shellState.layout; + } + + get isCanvas() { + return shellState.isCanvas; + } + + get isClassic() { + return !shellState.isCanvas; + } + + /** + * Set the layout the console renders. Unknown values fall back to `classic`. + * + * @param {String} layout `classic` or `canvas` + */ + setLayout(layout) { + shellState.explicitLayout = LAYOUTS.includes(layout) ? layout : 'classic'; + } + + /** + * Called by `Layout::Canvas` as it mounts and unmounts. The count changes in + * the runloop's actions queue rather than mid-render: a panel that read the + * layout earlier in the same render would otherwise trip Glimmer's + * "updated a value already used in this render" assertion. The re-render it + * causes happens before the browser paints. + */ + canvasDidMount() { + schedule('actions', this, this.#adjust, 1); + } + + canvasWillUnmount() { + schedule('actions', this, this.#adjust, -1); + } + + #adjust(step) { + if (this.isDestroying || this.isDestroyed) { + return; + } + shellState.mountedCanvases = Math.max(0, shellState.mountedCanvases + step); + } +} diff --git a/addon/styles/addon.css b/addon/styles/addon.css index d4fc1c9a..692cffbf 100644 --- a/addon/styles/addon.css +++ b/addon/styles/addon.css @@ -59,6 +59,8 @@ @import 'components/tip-tap-editor.css'; @import 'components/tab-navigation.css'; @import 'components/resource-context-panel.css'; +@import 'components/sheet.css'; +@import 'components/view-switch.css'; @import 'components/card-grid.css'; @import 'components/report-builder.css'; @import 'components/query-builder.css'; diff --git a/addon/styles/components/sheet.css b/addon/styles/components/sheet.css new file mode 100644 index 00000000..b13d572a --- /dev/null +++ b/addon/styles/components/sheet.css @@ -0,0 +1,220 @@ +/** + * Sheet: the canvas shell's floating record card (B2, B3). + * + * A sheet is fixed to the content area's insets on its side. Sheets behind the + * top one in a stack are pushed in by `--fb-sheet-offset` (one spine width per + * level), so their left (or right) strip shows as a clickable spine. + * Layering: sheets sit in the content layer, so floating chrome stays above them. + */ + +.fb-sheet { + --fb-sheet-width: 440px; + --fb-sheet-offset: 0px; + --fb-sheet-spine: 28px; + + position: fixed; + top: var(--fb-inset-top); + bottom: var(--fb-inset-bottom); + z-index: 10; + display: flex; + width: var(--fb-sheet-width); + max-width: calc(100% - var(--fb-inset-left) - var(--fb-inset-right)); + overflow: hidden; + border: 1px solid var(--fb-chrome-border); + border-radius: 18px; + background-color: var(--fb-surface); + box-shadow: var(--fb-shadow-sheet); + color: var(--fb-text); + animation: fb-sheet-in 160ms ease-out; +} + +.fb-sheet.is-right { + right: calc(var(--fb-inset-right) + var(--fb-sheet-offset)); +} + +.fb-sheet.is-left { + left: calc(var(--fb-inset-left) + var(--fb-sheet-offset)); +} + +.fb-sheet:focus { + outline: none; +} + +.fb-sheet:focus-visible, +.fb-sheet :focus-visible { + outline: 2px solid var(--fb-focus); + outline-offset: 2px; +} + +.fb-sheet.is-top { + z-index: 14; +} + +.fb-sheet.is-spine[data-depth='1'] { + z-index: 13; +} + +.fb-sheet.is-spine[data-depth='2'] { + z-index: 12; +} + +.fb-sheet.is-spine[data-depth='3'] { + z-index: 11; +} + +.fb-sheet.is-hidden { + visibility: hidden; +} + +.fb-sheet-panel { + display: flex; + flex: 1; + min-width: 0; + flex-direction: column; +} + +.fb-sheet.is-spine .fb-sheet-panel { + opacity: 0.6; +} + +.fb-sheet-spine { + position: absolute; + top: 0; + bottom: 0; + z-index: 1; + display: flex; + width: var(--fb-sheet-spine); + align-items: flex-start; + justify-content: center; + padding: 16px 0 0; + border: 0; + background-color: var(--fb-subtle); + color: var(--fb-muted); + font: inherit; + font-size: 12px; + cursor: pointer; +} + +.fb-sheet.is-right .fb-sheet-spine { + left: 0; +} + +.fb-sheet.is-left .fb-sheet-spine { + right: 0; +} + +.fb-sheet-spine:hover { + color: var(--fb-text); +} + +.fb-sheet-spine-label { + overflow: hidden; + max-height: 100%; + text-overflow: ellipsis; + white-space: nowrap; + writing-mode: vertical-rl; +} + +.fb-sheet-header { + display: flex; + flex: none; + align-items: center; + gap: 8px; + min-height: 52px; + padding: 8px 10px 8px 18px; + border-bottom: 1px solid var(--fb-border); +} + +.fb-sheet-header-main { + flex: 1; + min-width: 0; +} + +.fb-sheet-title { + margin: 0; + overflow: hidden; + font-size: 16px; + font-weight: 700; + text-overflow: ellipsis; + white-space: nowrap; +} + +.fb-sheet-controls { + display: flex; + flex: none; + align-items: center; + gap: 2px; +} + +.fb-sheet-control { + display: inline-flex; + width: 32px; + height: 32px; + align-items: center; + justify-content: center; + border: 0; + border-radius: var(--fb-radius-control); + background: transparent; + color: var(--fb-muted); + cursor: pointer; +} + +.fb-sheet-control:hover { + background-color: var(--fb-subtle); + color: var(--fb-text); +} + +.fb-sheet-body { + flex: 1; + min-height: 0; + overflow: auto; +} + +.fb-sheet-footer { + flex: none; + padding: 10px 18px; + border-top: 1px solid var(--fb-border); +} + +.fb-sheet-resize { + position: absolute; + top: 50%; + width: 8px; + height: 56px; + margin-top: -28px; + border-radius: 4px; + background-color: var(--fb-border); + cursor: col-resize; + touch-action: none; +} + +.fb-sheet.is-right .fb-sheet-resize { + left: 2px; +} + +.fb-sheet.is-left .fb-sheet-resize { + right: 2px; +} + +.fb-sheet-resize:hover, +.fb-sheet-resize:focus-visible { + background-color: var(--fb-accent); +} + +@keyframes fb-sheet-in { + from { + opacity: 0; + transform: translateY(8px); + } + + to { + opacity: 1; + transform: none; + } +} + +@media (prefers-reduced-motion: reduce) { + .fb-sheet { + animation: none; + } +} diff --git a/addon/styles/components/view-switch.css b/addon/styles/components/view-switch.css new file mode 100644 index 00000000..e9bcb282 --- /dev/null +++ b/addon/styles/components/view-switch.css @@ -0,0 +1,82 @@ +/** + * Layout::ViewSwitch: the floating segmented pill, top-centre over the canvas + * (C2_Table, J1). It lives in the chrome layer, which passes the pointer + * through everywhere but on the pill itself. + */ + +.fb-view-switch { + position: absolute; + top: var(--fb-view-switch-top, 12px); + left: 50%; + display: flex; + height: 44px; + align-items: center; + gap: 4px; + padding: 0 6px; + border-radius: var(--fb-radius-chrome); + transform: translateX(-50%); + white-space: nowrap; +} + +.fb-view-switch-views { + display: flex; + gap: 2px; +} + +.fb-view-switch-option, +.fb-view-switch-primary { + display: inline-flex; + height: 32px; + align-items: center; + gap: 6px; + padding: 0 12px; + border: 0; + border-radius: 9px; + font: inherit; + font-size: 13px; + cursor: pointer; +} + +.fb-view-switch-option { + background: transparent; + color: var(--fb-muted); +} + +.fb-view-switch-option:hover { + background-color: var(--fb-subtle); + color: var(--fb-text); +} + +.fb-view-switch-option.is-selected { + background-color: var(--fb-accent); + color: var(--fb-accent-fg); + font-weight: 600; +} + +.fb-view-switch-count { + font-size: 12px; + font-variant-numeric: tabular-nums; + opacity: 0.85; +} + +.fb-view-switch-divider { + width: 1px; + height: 20px; + margin: 0 4px; + background-color: var(--fb-border); +} + +.fb-view-switch-primary { + background-color: var(--fb-text); + color: var(--fb-surface); + font-weight: 600; +} + +.fb-view-switch-primary:hover { + opacity: 0.9; +} + +.fb-view-switch :focus-visible { + outline: 2px solid var(--fb-focus); + outline-offset: 2px; +} diff --git a/addon/styles/layout/canvas.css b/addon/styles/layout/canvas.css index bf7809bb..83ea5e84 100644 --- a/addon/styles/layout/canvas.css +++ b/addon/styles/layout/canvas.css @@ -50,3 +50,38 @@ background-image: radial-gradient(var(--fb-canvas-dot) var(--fb-canvas-dot-size), transparent var(--fb-canvas-dot-size)); background-size: var(--fb-canvas-grid) var(--fb-canvas-grid); } + +/* Layout::Canvas::BackdropHost. Every mounted backdrop keeps its slot; only the + active one is visible. Hidden slots are `inert` and invisible but stay laid + out at full size, so a map kept alive does not lose its dimensions. */ +.fb-canvas-backdrop-host { + position: absolute; + inset: 0; +} + +.fb-canvas-backdrop-slot { + position: absolute; + inset: 0; + visibility: hidden; +} + +.fb-canvas-backdrop-slot.is-active { + visibility: visible; +} + +/* Over a live backdrop, the content layer's empty area passes the pointer to + the map; the cards and sheets inside it still take it. A page wrapper that + spans the whole content area can opt out with `fb-canvas-passthrough`. */ +.fb-canvas:has(.fb-canvas-backdrop-slot.is-active) > .fb-canvas-content { + pointer-events: none; +} + +.fb-canvas:has(.fb-canvas-backdrop-slot.is-active) > .fb-canvas-content > *, +.fb-canvas-passthrough > * { + pointer-events: auto; +} + +.fb-canvas:has(.fb-canvas-backdrop-slot.is-active) > .fb-canvas-content > .fb-canvas-passthrough, +.fb-canvas-passthrough { + pointer-events: none; +} diff --git a/addon/utils/sheet-stack.js b/addon/utils/sheet-stack.js new file mode 100644 index 00000000..f3fa5d80 --- /dev/null +++ b/addon/utils/sheet-stack.js @@ -0,0 +1,94 @@ +/** + * Keeps track of the open `Sheet`s so that exactly one of them — the top one — + * traps Tab and answers Escape. + * + * One stack per page, at module level: sheets render in the host and inside + * engines (every engine's record panels), and an engine's owner has no + * ember-ui services, so a service would split the stack in two. + * + * Sheets register as they mount and unregister as they unmount. The top sheet + * is the one with the lowest stack depth (0 is the front of a + * resource-context-panel stack); among equals the most recently mounted wins. + * + * Escape is handled on `window` in the bubble phase, after `document` + * listeners, and is ignored when something else already handled it + * (`defaultPrevented`). The top sheet's `escape()` decides whether it closes + * (it declines while a modal is open over it). + * + * Bookkeeping is untracked on purpose: it changes while sheets render and + * nothing renders from it. + */ +export class SheetStack { + #sheets = []; + #listening = false; + + /** Sheets currently mounted, in mount order. */ + get sheets() { + return [...this.#sheets]; + } + + /** The sheet that owns the keyboard, or null. */ + get top() { + let top = null; + for (const sheet of this.#sheets) { + if (top === null || sheet.depth <= top.depth) { + top = sheet; + } + } + return top; + } + + isTop(sheet) { + return this.top === sheet; + } + + /** @param {Object} sheet Anything with a `depth` and an `escape()` method */ + register(sheet) { + if (!this.#sheets.includes(sheet)) { + this.#sheets.push(sheet); + } + this.#listen(); + } + + unregister(sheet) { + this.#sheets = this.#sheets.filter((registered) => registered !== sheet); + if (this.#sheets.length === 0) { + this.#stopListening(); + } + } + + /** Drops every sheet and the listener. */ + reset() { + this.#sheets = []; + this.#stopListening(); + } + + handleKeydown = (event) => { + if (event.key !== 'Escape' || event.defaultPrevented || event.isComposing) { + return; + } + + const top = this.top; + if (top && top.escape()) { + event.preventDefault(); + } + }; + + #listen() { + if (!this.#listening) { + window.addEventListener('keydown', this.handleKeydown); + this.#listening = true; + } + } + + #stopListening() { + if (this.#listening) { + window.removeEventListener('keydown', this.handleKeydown); + this.#listening = false; + } + } +} + +export const sheetStack = new SheetStack(); + +export default sheetStack; diff --git a/app/components/layout/canvas/backdrop-host.js b/app/components/layout/canvas/backdrop-host.js new file mode 100644 index 00000000..5b5c0d52 --- /dev/null +++ b/app/components/layout/canvas/backdrop-host.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/ember-ui/components/layout/canvas/backdrop-host'; diff --git a/app/components/layout/view-switch.js b/app/components/layout/view-switch.js new file mode 100644 index 00000000..c26566dc --- /dev/null +++ b/app/components/layout/view-switch.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/ember-ui/components/layout/view-switch'; diff --git a/app/components/sheet.js b/app/components/sheet.js new file mode 100644 index 00000000..55489637 --- /dev/null +++ b/app/components/sheet.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/ember-ui/components/sheet'; diff --git a/app/services/shell.js b/app/services/shell.js new file mode 100644 index 00000000..5c66f1db --- /dev/null +++ b/app/services/shell.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/ember-ui/services/shell'; diff --git a/tests/helpers/shell-stubs.js b/tests/helpers/shell-stubs.js index 4aaf8f72..6b991b42 100644 --- a/tests/helpers/shell-stubs.js +++ b/tests/helpers/shell-stubs.js @@ -92,6 +92,44 @@ export class ContextBarStub extends Service { } } +/** + * ember-core's `backdrop` service, reduced to what the canvas host reads: + * `active`, `mounted` and `state`. Tests set `registrations` and pick the + * active one with `activate(name)` (or `activate(null)` for the dot grid); + * keep-alive registrations stay in `mounted` once activated, as in ember-core. + */ +export class BackdropStub extends Service { + @tracked registrations = []; + @tracked activeName = null; + @tracked activated = []; + @tracked state = { layers: [], fitBounds: null, focus: null, mode: null }; + requests = new Map(); + + get active() { + return this.registrations.find((registration) => registration?.name === this.activeName) ?? null; + } + + get mounted() { + return this.registrations.filter((registration) => registration?.name === this.activeName || (registration?.keepAlive && this.activated.includes(registration.name))); + } + + activate(name) { + this.activeName = name; + if (name && !this.activated.includes(name)) { + this.activated = [...this.activated, name]; + } + } + + request(owner, options = {}) { + this.requests.set(owner, options); + this.state = { ...this.state, layers: [...this.requests].map(([key, value]) => ({ owner: key, layers: value.layers ?? [] })) }; + } + + release(owner) { + return this.requests.delete(owner); + } +} + // only resolves inside a mounted engine, so it is stubbed at that boundary. class LinkToExternalStub extends Component {} const LINK_TO_EXTERNAL_TEMPLATE = hbs`{{yield}}`; diff --git a/tests/integration/components/layout/canvas-test.js b/tests/integration/components/layout/canvas-test.js index 41933c53..ea8114b1 100644 --- a/tests/integration/components/layout/canvas-test.js +++ b/tests/integration/components/layout/canvas-test.js @@ -1,6 +1,6 @@ import { module, test } from 'qunit'; import { setupRenderingTest } from 'dummy/tests/helpers'; -import { render, click } from '@ember/test-helpers'; +import { render, click, settled } from '@ember/test-helpers'; import { hbs } from 'ember-cli-htmlbars'; import { setupShellTheme, renderShell, eachShellTheme } from '@fleetbase/ember-ui/test-support'; @@ -113,6 +113,18 @@ module('Integration | Component | layout/canvas', function (hooks) { assert.strictEqual(content.offsetTop, 0); }); + test('while mounted it puts the shell in the canvas layout', async function (assert) { + const shell = this.owner.lookup('service:shell'); + this.show = true; + + await render(hbs`{{#if this.show}}{{/if}}`); + assert.strictEqual(shell.layout, 'canvas'); + + this.set('show', false); + await settled(); + assert.strictEqual(shell.layout, 'classic'); + }); + test('it forwards splattributes and leaves data-theme to the page without @theme', async function (assert) { await render(hbs``); diff --git a/tests/integration/components/layout/canvas/backdrop-host-test.js b/tests/integration/components/layout/canvas/backdrop-host-test.js new file mode 100644 index 00000000..18d73d77 --- /dev/null +++ b/tests/integration/components/layout/canvas/backdrop-host-test.js @@ -0,0 +1,258 @@ +import { module, test } from 'qunit'; +import { setupRenderingTest } from 'dummy/tests/helpers'; +import { render, click, settled } from '@ember/test-helpers'; +import { hbs } from 'ember-cli-htmlbars'; +import Component from '@glimmer/component'; +import { setComponentTemplate } from '@ember/component'; +import templateOnly from '@ember/component/template-only'; +import { BackdropStub } from '../../../../helpers/shell-stubs'; +import ExtensionComponent from '@fleetbase/ember-core/contracts/extension-component'; +import { isEngineComponent } from '@fleetbase/ember-ui/components/layout/canvas/backdrop-host'; + +// Counts constructions and teardowns so a test can tell hidden from destroyed. +const lifecycle = { created: [], destroyed: [] }; + +class EngineMapTarget extends Component { + constructor() { + super(...arguments); + lifecycle.created.push(`engine:${this.args.params.registration.name}`); + } + + willDestroy() { + super.willDestroy(...arguments); + lifecycle.destroyed.push(`engine:${this.args.params.registration.name}`); + } +} +setComponentTemplate(hbs`
`, EngineMapTarget); + +class LiveMap extends Component { + constructor() { + super(...arguments); + lifecycle.created.push(this.args.registration.name); + } + + willDestroy() { + super.willDestroy(...arguments); + lifecycle.destroyed.push(this.args.registration.name); + } +} +setComponentTemplate( + hbs`
{{@registration.name}}
`, + LiveMap +); + +function applyStyle(element, styles) { + for (const [property, value] of Object.entries(styles)) { + element.style.setProperty(property, value); + } + return element; +} + +module('Integration | Component | layout/canvas/backdrop-host', function (hooks) { + setupRenderingTest(hooks); + + hooks.beforeEach(function () { + lifecycle.created = []; + lifecycle.destroyed = []; + this.owner.register('component:test-live-map', LiveMap); + }); + + function useBackdrop(owner, registrations = []) { + owner.unregister('service:backdrop'); + owner.register('service:backdrop', BackdropStub); + const backdrop = owner.lookup('service:backdrop'); + backdrop.registrations = registrations; + return backdrop; + } + + const MAP = { name: 'fleet-ops-map', component: 'test-live-map', routes: ['console.fleet-ops'], priority: 0, keepAlive: true }; + + test('without a backdrop service it shows the dot grid', async function (assert) { + this.owner.unregister('service:backdrop'); + await render(hbs``); + + assert.dom('.fb-canvas-backdrop-host .fb-canvas-dot-grid').exists(); + assert.dom('.fb-canvas-backdrop-slot').doesNotExist(); + assert.dom('.fb-canvas-backdrop-host').doesNotHaveAttribute('data-backdrop-active'); + }); + + test('with no active backdrop it shows the dot grid', async function (assert) { + useBackdrop(this.owner, [MAP]); + await render(hbs``); + + assert.dom('.fb-canvas-dot-grid').exists(); + assert.dom('.fb-canvas-backdrop-slot').doesNotExist('nothing is mounted before it is first active'); + }); + + test('the active backdrop renders visible, with the registration, state and service', async function (assert) { + const backdrop = useBackdrop(this.owner, [MAP]); + backdrop.activate('fleet-ops-map'); + backdrop.request('orders', { layers: [{ id: 'orders' }] }); + + await render(hbs``); + + assert.dom('.fb-canvas-backdrop-host').hasAttribute('data-backdrop-active', 'fleet-ops-map'); + assert.dom('.fb-canvas-backdrop-slot').hasClass('is-active').hasAttribute('data-backdrop', 'fleet-ops-map').hasAttribute('aria-hidden', 'false'); + assert.false(this.element.querySelector('.fb-canvas-backdrop-slot').inert); + assert.strictEqual(getComputedStyle(this.element.querySelector('.fb-canvas-backdrop-slot')).visibility, 'visible'); + assert.dom('.test-map').hasText('fleet-ops-map').hasAttribute('data-active', 'yes').hasAttribute('data-layers', '1').hasAttribute('data-has-service', 'yes'); + assert.dom('.fb-canvas-dot-grid').doesNotExist(); + }); + + test('a keep-alive backdrop is hidden, not torn down, when no backdrop is active, and comes back as it was', async function (assert) { + const backdrop = useBackdrop(this.owner, [MAP]); + backdrop.activate('fleet-ops-map'); + await render(hbs``); + + const mapElement = this.element.querySelector('.test-map'); + assert.deepEqual(lifecycle.created, ['fleet-ops-map']); + + backdrop.activate(null); + await settled(); + + const slot = this.element.querySelector('.fb-canvas-backdrop-slot'); + assert.dom(slot).doesNotHaveClass('is-active').hasAttribute('aria-hidden', 'true'); + assert.true(slot.inert, 'the hidden map cannot take focus or clicks'); + assert.strictEqual(getComputedStyle(slot).visibility, 'hidden'); + assert.dom('.fb-canvas-dot-grid').exists('the dot grid shows instead'); + assert.dom('.test-map').hasAttribute('data-active', 'no'); + assert.deepEqual(lifecycle.destroyed, [], 'the map was not destroyed'); + + backdrop.activate('fleet-ops-map'); + await settled(); + + assert.strictEqual(this.element.querySelector('.test-map'), mapElement, 'the same map element is shown again'); + assert.deepEqual(lifecycle.created, ['fleet-ops-map'], 'and it was never re-created'); + assert.dom('.fb-canvas-dot-grid').doesNotExist(); + }); + + test('switching between two backdrops keeps the keep-alive one mounted and hidden', async function (assert) { + const OTHER = { name: 'storefront-map', component: 'test-live-map', routes: ['console.storefront'], priority: 0, keepAlive: false }; + const backdrop = useBackdrop(this.owner, [MAP, OTHER]); + backdrop.activate('fleet-ops-map'); + await render(hbs``); + + backdrop.activate('storefront-map'); + await settled(); + + assert.dom('.fb-canvas-backdrop-slot').exists({ count: 2 }); + assert.dom('[data-backdrop="storefront-map"]').hasClass('is-active'); + assert.dom('[data-backdrop="fleet-ops-map"]').doesNotHaveClass('is-active'); + + backdrop.activate('fleet-ops-map'); + await settled(); + + assert.dom('[data-backdrop="storefront-map"]').doesNotExist('a backdrop that is not keep-alive unmounts when it stops being active'); + assert.deepEqual(lifecycle.destroyed, ['storefront-map']); + assert.deepEqual(lifecycle.created, ['fleet-ops-map', 'storefront-map']); + }); + + test('a service without a mounted list renders just the active backdrop', async function (assert) { + const backdrop = useBackdrop(this.owner, [MAP]); + Object.defineProperty(backdrop, 'mounted', { configurable: true, value: undefined }); + await render(hbs``); + + assert.dom('.fb-canvas-backdrop-slot').doesNotExist(); + + backdrop.activate('fleet-ops-map'); + await settled(); + + assert.dom('.fb-canvas-backdrop-slot.is-active .test-map').exists(); + }); + + test('registrations without a name or component are skipped, and a missing state is passed as nothing', async function (assert) { + const backdrop = useBackdrop(this.owner, [MAP]); + backdrop.activate('fleet-ops-map'); + Object.defineProperty(backdrop, 'mounted', { configurable: true, value: [{ name: 'broken' }, { component: 'test-live-map' }, null, MAP] }); + Object.defineProperty(backdrop, 'state', { configurable: true, value: undefined }); + await render(hbs``); + + assert.dom('.fb-canvas-backdrop-slot').exists({ count: 1 }); + assert.dom('.test-map').doesNotHaveAttribute('data-layers'); + }); + + test('a service whose active backdrop is unset counts as none', async function (assert) { + const backdrop = useBackdrop(this.owner, [MAP]); + Object.defineProperty(backdrop, 'active', { configurable: true, value: undefined }); + await render(hbs``); + + assert.dom('.fb-canvas-dot-grid').exists(); + }); + + test('in Layout::Canvas the host is the default backdrop, and the map takes the pointer in the content gaps', async function (assert) { + const backdrop = useBackdrop(this.owner, [MAP]); + backdrop.activate('fleet-ops-map'); + this.cardClicks = 0; + this.onCardClick = () => this.cardClicks++; + this.owner.register('component:test-click-map', setComponentTemplate(hbs``, templateOnly())); + backdrop.registrations = [{ ...MAP, component: 'test-click-map' }]; + + await render(hbs` + + <:default>
+ <:chrome>
tray
+
+ `); + const canvas = applyStyle(this.element.querySelector('.fb-canvas'), { width: '800px', height: '500px' }); + applyStyle(this.element.querySelector('.click-map'), { position: 'absolute', inset: '0', width: '100%', height: '100%' }); + applyStyle(this.element.querySelector('.card'), { width: '120px', height: '60px' }); + + assert.dom('.fb-canvas-backdrop .fb-canvas-backdrop-host').exists(); + assert.strictEqual(getComputedStyle(this.element.querySelector('.fb-canvas-content')).pointerEvents, 'none', 'the content layer passes the pointer through'); + assert.strictEqual(getComputedStyle(this.element.querySelector('.card')).pointerEvents, 'auto', 'its cards still take it'); + + const rect = canvas.getBoundingClientRect(); + const gap = document.elementFromPoint(rect.left + rect.width * 0.75, rect.top + rect.height * 0.75); + assert.true(gap.classList.contains('click-map'), 'a point in the content gap reaches the map'); + + await click('.card-button'); + assert.strictEqual(this.cardClicks, 1, 'the card stays clickable'); + + backdrop.activate(null); + await settled(); + assert.strictEqual(getComputedStyle(this.element.querySelector('.fb-canvas-content')).pointerEvents, 'auto', 'over the dot grid the content layer takes the pointer again'); + }); + + test('a passthrough wrapper lets the pointer through to the map while its children take it', async function (assert) { + const backdrop = useBackdrop(this.owner, [MAP]); + backdrop.activate('fleet-ops-map'); + + await render(hbs` + +
card
+
+ `); + + assert.strictEqual(getComputedStyle(this.element.querySelector('.page')).pointerEvents, 'none'); + assert.strictEqual(getComputedStyle(this.element.querySelector('.card')).pointerEvents, 'auto'); + }); + + test('an engine ExtensionComponent renders through LazyEngineComponent with the values as @params, and survives being hidden', async function (assert) { + const backdrop = useBackdrop(this.owner, [{ ...MAP, component: new ExtensionComponent('@fleetbase/fleetops-engine', EngineMapTarget) }]); + backdrop.activate('fleet-ops-map'); + await render(hbs``); + + const target = this.element.querySelector('.fb-canvas-backdrop-slot.is-active .engine-map-target'); + assert.dom(target).hasAttribute('data-active', 'yes').hasAttribute('data-has-service', 'yes'); + assert.strictEqual(getComputedStyle(this.element.querySelector('.fb-canvas-backdrop-slot')).pointerEvents, 'auto', 'the host leaves the pointer to the backdrop'); + + backdrop.activate(null); + await settled(); + assert.dom('.engine-map-target').hasAttribute('data-active', 'no'); + + backdrop.activate('fleet-ops-map'); + await settled(); + assert.strictEqual(this.element.querySelector('.engine-map-target'), target, 'the same engine target element'); + assert.deepEqual(lifecycle.created, ['engine:fleet-ops-map']); + assert.deepEqual(lifecycle.destroyed, []); + }); + + test('isEngineComponent recognises ExtensionComponents and their string form only', function (assert) { + assert.true(isEngineComponent(new ExtensionComponent('@fleetbase/fleetops-engine', 'map/live-map-backdrop'))); + assert.true(isEngineComponent('#extension-component:@fleetbase/fleetops-engine:map/live-map-backdrop')); + assert.false(isEngineComponent('test-live-map')); + assert.false(isEngineComponent(LiveMap)); + assert.false(isEngineComponent(null)); + assert.false(isEngineComponent({ path: 'no-engine' })); + }); +}); diff --git a/tests/integration/components/layout/resource/panel-test.js b/tests/integration/components/layout/resource/panel-test.js index 1bc60344..c9dbb782 100644 --- a/tests/integration/components/layout/resource/panel-test.js +++ b/tests/integration/components/layout/resource/panel-test.js @@ -252,4 +252,109 @@ module('Integration | Component | layout/resource/panel', function (hooks) { assert.dom('.resource-panel-header button.btn').exists('the save control still renders under a different schema'); }); }); + + module('in the canvas layout', function () { + test('@layout="canvas" renders it as a Sheet with the resource header and body', async function (assert) { + this.cancelled = 0; + this.onPressCancel = () => this.cancelled++; + await render(hbs` + + {{resource.name}} + + `); + + assert.dom(OVERLAY).doesNotExist('no classic overlay'); + assert.dom('.fb-sheet.resource-panel-sheet').exists().hasAttribute('data-test-panel').hasAttribute('aria-label', 'Order 123'); + assert.dom('.fb-sheet-header .resource-panel-header').containsText('Order 123'); + assert.dom('.fb-sheet-close').doesNotExist('the resource header keeps its own cancel control'); + assert.dom('.fb-sheet-body .resource-panel-sheet-body.my-body .name').hasText('Order 123'); + assert.strictEqual(find('.fb-sheet').style.getPropertyValue('--fb-sheet-width'), '440px', 'without a width it uses the md sheet preset'); + assert.dom('.fb-sheet-resize').exists('resizable by default'); + + await click('.next-content-overlay-panel-cancel-button'); + assert.strictEqual(this.cancelled, 1); + }); + + test('the shell service picks the canvas layout when no @layout is given', async function (assert) { + this.owner.lookup('service:shell').setLayout('canvas'); + await render(hbs``); + + assert.dom('.fb-sheet').exists(); + assert.dom('.fb-sheet').hasAttribute('aria-label', 'Order 123', 'titled from the resource name'); + }); + + test('inside Layout::Canvas it renders as a Sheet; @layout="classic" opts out', async function (assert) { + await render(hbs` + + + + + `); + + assert.dom('.fb-sheet.canvas-panel').exists(); + assert.dom(`${PANEL}.classic-panel`).exists(); + }); + + test('sheet width, limits and stacking arguments pass through', async function (assert) { + this.activated = 0; + this.parked = 0; + this.onActivate = () => this.activated++; + this.onPark = () => this.parked++; + await render(hbs` + + + `); + + assert.dom('.back').hasClass('is-left').hasClass('is-spine'); + assert.strictEqual(find('.back').style.getPropertyValue('--fb-sheet-width'), '640px'); + await click('.back .fb-sheet-spine'); + assert.strictEqual(this.activated, 1); + + assert.dom('.front').hasClass('is-top'); + assert.dom('.front .fb-sheet-resize').doesNotExist(); + await click('.front .fb-sheet-park'); + assert.strictEqual(this.parked, 1); + }); + + test('resize limits reach the sheet handle', async function (assert) { + await render(hbs``); + + assert.dom('.fb-sheet-resize').hasAttribute('aria-valuemin', '400').hasAttribute('aria-valuemax', '700'); + }); + + test('a width given as a classic @width is used when there is no @sheetWidth', async function (assert) { + await render(hbs``); + assert.strictEqual(find('.fb-sheet').style.getPropertyValue('--fb-sheet-width'), '360px'); + }); + + test('a custom header component renders in the sheet header', async function (assert) { + await render(hbs``); + + assert.dom('.fb-sheet-header .fleetbase-loader-wrapper.my-header.resource-panel-header').exists(); + }); + + test('a displayName-only resource still titles the sheet, and none leaves it untitled', async function (assert) { + this.set('resource', { displayName: 'Driver Alex' }); + await render(hbs``); + assert.dom('.fb-sheet').hasAttribute('aria-label', 'Driver Alex'); + + await render(hbs``); + assert.dom('.fb-sheet').doesNotHaveAttribute('aria-label'); + }); + + test('the sheet stands in for the overlay context in onLoad, onOverlayReady and onOpen', async function (assert) { + const calls = []; + this.onLoad = (context) => calls.push(['onLoad', typeof context.close]); + this.options = { onOverlayReady: (context) => calls.push(['onOverlayReady', Boolean(context.element)]) }; + this.onOpen = ({ resource, panel }) => calls.push(['onOpen', resource.name, typeof panel.park]); + await render(hbs``); + + assert.deepEqual(calls, [ + ['onLoad', 'function'], + ['onOverlayReady', true], + ['onOpen', 'Order 123', 'function'], + ]); + }); + }); }); diff --git a/tests/integration/components/layout/view-switch-test.js b/tests/integration/components/layout/view-switch-test.js new file mode 100644 index 00000000..0a67c663 --- /dev/null +++ b/tests/integration/components/layout/view-switch-test.js @@ -0,0 +1,193 @@ +import { module, test } from 'qunit'; +import { setupRenderingTest } from 'dummy/tests/helpers'; +import { render, click, focus, settled, triggerKeyEvent, find, findAll } from '@ember/test-helpers'; +import { hbs } from 'ember-cli-htmlbars'; +import { setupShellStubs } from '../../../helpers/shell-stubs'; + +function labels() { + return findAll('[role="radio"]').map((radio) => radio.textContent.trim().replace(/\s+/g, ' ')); +} + +function checked() { + return findAll('[role="radio"][aria-checked="true"]').map((radio) => radio.dataset.view); +} + +module('Integration | Component | layout/view-switch', function (hooks) { + setupRenderingTest(hooks); + setupShellStubs(hooks); + + hooks.beforeEach(function () { + this.changes = []; + this.onChange = (id, view) => this.changes.push([id, view.label]); + }); + + test('without @views it offers Map, Table and Board, the first selected', async function (assert) { + await render(hbs``); + + assert.dom('.fb-view-switch [role="radiogroup"]').hasAttribute('aria-label', 'View'); + assert.deepEqual(labels(), ['Map', 'Table', 'Board']); + assert.deepEqual(checked(), ['map']); + assert.dom('[data-view="map"]').hasAttribute('tabindex', '0').hasClass('is-selected'); + assert.dom('[data-view="table"]').hasAttribute('tabindex', '-1'); + assert.dom('.fb-view-switch-primary').doesNotExist(); + assert.dom('.fb-view-switch-divider').doesNotExist(); + }); + + test('it sits top-centre in the chrome', async function (assert) { + await render(hbs`
`); + const host = find('.host'); + host.style.setProperty('position', 'relative'); + host.style.setProperty('width', '800px'); + host.style.setProperty('height', '200px'); + + const pill = find('.fb-view-switch'); + assert.strictEqual(getComputedStyle(pill).position, 'absolute'); + assert.strictEqual(pill.offsetTop, 12); + const hostRect = host.getBoundingClientRect(); + const pillRect = pill.getBoundingClientRect(); + assert.true(Math.abs(hostRect.left + hostRect.width / 2 - (pillRect.left + pillRect.width / 2)) < 1, 'centred horizontally'); + }); + + test('views show their counts, and @selected picks one', async function (assert) { + this.views = [ + { id: 'map', label: 'Map' }, + { id: 'table', label: 'Table', count: 57 }, + { id: 'board', label: 'Board', count: 0 }, + ]; + await render(hbs``); + + assert.deepEqual(labels(), ['Map', 'Table 57', 'Board 0']); + assert.deepEqual(checked(), ['table']); + assert.dom('[role="radiogroup"]').hasAttribute('aria-label', 'Orders view'); + }); + + test('clicking a view calls @onChange with its id', async function (assert) { + this.selected = 'map'; + this.setView = (id, view) => { + this.changes.push([id, view.label]); + this.set('selected', id); + }; + await render(hbs``); + + await click('[data-view="board"]'); + assert.deepEqual(this.changes, [['board', 'Board']]); + assert.deepEqual(checked(), ['board']); + }); + + test('without @selected or @onChange it remembers the last view clicked', async function (assert) { + await render(hbs``); + + await click('[data-view="table"]'); + assert.deepEqual(checked(), ['table']); + }); + + test('a remembered view that is no longer offered falls back to the first', async function (assert) { + this.views = [ + { id: 'map', label: 'Map' }, + { id: 'table', label: 'Table' }, + ]; + await render(hbs``); + await click('[data-view="table"]'); + + this.set('views', [ + { id: 'map', label: 'Map' }, + { id: 'board', label: 'Board' }, + ]); + await settled(); + assert.deepEqual(checked(), ['map']); + }); + + test('views with routes follow the current route, most specific first, and navigate when clicked', async function (assert) { + this.views = [ + { id: 'map', label: 'Map', route: 'console.fleet-ops.operations.orders.index' }, + { id: 'table', label: 'Table', route: 'console.fleet-ops.operations.orders.index', query: { layout: 'table' } }, + { id: 'board', label: 'Board', route: 'console.fleet-ops.operations.orders.index.board' }, + ]; + this.router.currentRouteName = 'console.fleet-ops.operations.orders.index.board'; + await render(hbs``); + + assert.deepEqual(checked(), ['board']); + + await click('[data-view="table"]'); + assert.deepEqual(this.router.transitions, [['console.fleet-ops.operations.orders.index', { queryParams: { layout: 'table' } }]]); + }); + + test('a view with neither a route nor @onChange only selects', async function (assert) { + await render(hbs``); + await click('[data-view="board"]'); + assert.deepEqual(this.router.transitions, []); + }); + + test('arrow keys, Home and End move the selection and focus, wrapping around', async function (assert) { + await render(hbs``); + await focus('[data-view="map"]'); + + await triggerKeyEvent('[data-view="map"]', 'keydown', 'ArrowRight'); + assert.deepEqual(checked(), ['table']); + assert.strictEqual(document.activeElement, find('[data-view="table"]')); + + await triggerKeyEvent('[data-view="table"]', 'keydown', 'ArrowDown'); + await triggerKeyEvent('[data-view="board"]', 'keydown', 'ArrowRight'); + assert.deepEqual(checked(), ['map'], 'wraps past the end'); + + await triggerKeyEvent('[data-view="map"]', 'keydown', 'ArrowLeft'); + assert.deepEqual(checked(), ['board'], 'wraps past the start'); + + await triggerKeyEvent('[data-view="board"]', 'keydown', 'ArrowUp'); + await triggerKeyEvent('[data-view="table"]', 'keydown', 'Home'); + assert.deepEqual(checked(), ['map']); + + await triggerKeyEvent('[data-view="map"]', 'keydown', 'End'); + assert.deepEqual(checked(), ['board']); + + await triggerKeyEvent('[data-view="board"]', 'keydown', 'Enter'); + assert.deepEqual(checked(), ['board'], 'other keys do nothing'); + assert.deepEqual( + this.changes.map(([id]) => id), + ['table', 'board', 'map', 'board', 'table', 'map', 'board'] + ); + }); + + test('a primary action renders after a divider and runs its handler', async function (assert) { + this.created = 0; + this.primary = { label: 'New order', icon: 'plus', onClick: () => this.created++ }; + await render(hbs``); + + assert.dom('.fb-view-switch-divider').exists(); + assert.dom('.fb-view-switch-primary').hasText('New order'); + assert.dom('.fb-view-switch-primary svg').exists('with its icon'); + + await click('.fb-view-switch-primary'); + assert.strictEqual(this.created, 1); + }); + + test('a primary action can navigate, needs a label, and may have no icon', async function (assert) { + this.primary = { label: 'New order', route: 'console.fleet-ops.operations.orders.index.new' }; + await render(hbs``); + + assert.dom('.fb-view-switch-primary svg').doesNotExist(); + await click('.fb-view-switch-primary'); + assert.deepEqual(this.router.transitions, [['console.fleet-ops.operations.orders.index.new', { queryParams: {} }]]); + + this.set('primary', { icon: 'plus' }); + assert.dom('.fb-view-switch-primary').doesNotExist(); + }); + + test('an actions block replaces the primary action', async function (assert) { + this.primary = { label: 'New order' }; + await render(hbs` + + <:actions> + + `); + + assert.dom('.fb-view-switch-divider').exists(); + assert.dom('.custom-action').hasText('Import'); + assert.dom('.fb-view-switch-primary').doesNotExist(); + }); + + test('it forwards attributes', async function (assert) { + await render(hbs``); + assert.dom('.fb-view-switch').hasClass('orders-switch').hasAttribute('data-test-switch'); + }); +}); diff --git a/tests/integration/components/resource-context-panel-canvas-test.js b/tests/integration/components/resource-context-panel-canvas-test.js new file mode 100644 index 00000000..ba3bb2cf --- /dev/null +++ b/tests/integration/components/resource-context-panel-canvas-test.js @@ -0,0 +1,136 @@ +import { module, test } from 'qunit'; +import { setupRenderingTest } from 'dummy/tests/helpers'; +import { render, click, settled, triggerKeyEvent, find, findAll } from '@ember/test-helpers'; +import { hbs } from 'ember-cli-htmlbars'; +import { setComponentTemplate } from '@ember/component'; +import templateOnly from '@ember/component/template-only'; + +/* + * The resource-context-panel stack in the canvas layout, against the real + * service: every overlay is a Sheet, earlier ones stack as spines (B3). + */ +module('Integration | Component | resource-context-panel (canvas layout)', function (hooks) { + setupRenderingTest(hooks); + + hooks.beforeEach(function () { + this.panels = this.owner.lookup('service:resource-context-panel'); + this.owner.lookup('service:shell').setLayout('canvas'); + this.owner.register('component:test-sheet-content', setComponentTemplate(hbs``, templateOnly())); + }); + + function open(panels, id, overrides = {}) { + return panels.open({ id, resource: { name: id }, content: 'test-sheet-content', ...overrides }); + } + + function depths() { + return findAll('.fb-sheet').map((sheet) => [sheet.getAttribute('aria-label'), sheet.dataset.depth]); + } + + test('each overlay renders as a sheet, and earlier ones stack behind the newest as spines', async function (assert) { + open(this.panels, 'CEN-01'); + open(this.panels, 'Amara Chen'); + open(this.panels, 'FLE9883'); + await render(hbs``); + + assert.dom('.next-content-overlay').doesNotExist(); + assert.deepEqual(depths(), [ + ['CEN-01', '2'], + ['Amara Chen', '1'], + ['FLE9883', '0'], + ]); + assert.dom('.fb-sheet.is-top .content-input').hasAttribute('aria-label', 'FLE9883'); + assert.dom('.fb-sheet-spine').exists({ count: 2 }); + }); + + test('clicking a spine brings that panel to the front without re-creating any sheet', async function (assert) { + open(this.panels, 'CEN-01'); + open(this.panels, 'Amara Chen'); + await render(hbs``); + + const before = findAll('.fb-sheet'); + find('.fb-sheet.is-spine .content-input').dataset.typed = 'kept'; + + await click('.fb-sheet.is-spine .fb-sheet-spine'); + + assert.deepEqual( + this.panels.overlays.map((overlay) => overlay.id), + ['Amara Chen', 'CEN-01'] + ); + assert.deepEqual(depths(), [ + ['Amara Chen', '1'], + ['CEN-01', '0'], + ]); + const after = findAll('.fb-sheet'); + assert.strictEqual(after[0], before[1], 'the sheets are moved, not re-created'); + assert.strictEqual(after[1], before[0]); + assert.dom('.fb-sheet.is-top .content-input').hasAttribute('data-typed', 'kept'); + }); + + test('opening another panel keeps the open sheets mounted', async function (assert) { + open(this.panels, 'CEN-01'); + await render(hbs``); + const first = find('.fb-sheet'); + + open(this.panels, 'Amara Chen'); + await settled(); + + assert.strictEqual(findAll('.fb-sheet')[0], first); + }); + + test('Escape closes only the top panel, even when it is dismissible', async function (assert) { + open(this.panels, 'CEN-01', { dismissible: true }); + open(this.panels, 'Amara Chen', { dismissible: true }); + await render(hbs``); + + assert.dom('.resource-context-panel-backdrop').doesNotExist('no click-away backdrop over the map'); + + await triggerKeyEvent('.fb-sheet.is-top .content-input', 'keydown', 'Escape'); + + assert.deepEqual( + this.panels.overlays.map((overlay) => overlay.id), + ['CEN-01'] + ); + assert.deepEqual(depths(), [['CEN-01', '0']]); + + await triggerKeyEvent('.fb-sheet', 'keydown', 'Escape'); + assert.deepEqual(this.panels.overlays, []); + assert.dom('.fb-sheet').doesNotExist(); + }); + + test('sizes map to sheet presets and an explicit width wins', async function (assert) { + open(this.panels, 'tiny', { size: 'xxs' }); + open(this.panels, 'large', { size: 'xl' }); + open(this.panels, 'custom', { width: '500px' }); + open(this.panels, 'odd', { size: 'enormous' }); + await render(hbs``); + + const widths = findAll('.fb-sheet').map((sheet) => sheet.style.getPropertyValue('--fb-sheet-width')); + assert.deepEqual(widths, ['360px', '640px', '500px', '440px']); + }); + + test('the park button appears once parking is enabled, and parks the panel', async function (assert) { + open(this.panels, 'CEN-01'); + await render(hbs``); + assert.dom('.fb-sheet-park').doesNotExist(); + + this.panels.enableParking(); + await settled(); + + const parked = []; + this.panels.on('overlay.parked', (overlay) => parked.push(overlay.id)); + await click('.fb-sheet-park'); + + assert.deepEqual(parked, ['CEN-01']); + assert.dom('.fb-sheet').doesNotExist(); + assert.true(this.panels.isParked('CEN-01')); + }); + + test('@layout="classic" keeps the classic overlay even when the shell is in canvas', async function (assert) { + open(this.panels, 'CEN-01', { dismissible: true }); + await render(hbs``); + + assert.dom('.next-content-overlay').exists(); + assert.dom('.fb-sheet').doesNotExist(); + assert.dom('.resource-context-panel-backdrop').exists(); + }); +}); diff --git a/tests/integration/components/resource-context-panel-test.js b/tests/integration/components/resource-context-panel-test.js index 4e571bb6..f16cb344 100644 --- a/tests/integration/components/resource-context-panel-test.js +++ b/tests/integration/components/resource-context-panel-test.js @@ -18,6 +18,8 @@ module('Integration | Component | resource-context-panel', function (hooks) { activeTabs: {}, closed: [], activeTabCalls: [], + fronted: [], + parkedIds: [], }; this.owner.unregister('service:resourceContextPanel'); @@ -38,6 +40,15 @@ module('Integration | Component | resource-context-panel', function (hooks) { close(id) { panel.closed.push(id); } + canPark(overlay) { + return overlay.parkable === true; + } + bringToFront(id) { + panel.fronted.push(id); + } + park(id) { + panel.parkedIds.push(id); + } setActiveTab(overlayId, tabId) { panel.activeTabCalls.push([overlayId, tabId]); } diff --git a/tests/integration/components/sheet-test.js b/tests/integration/components/sheet-test.js new file mode 100644 index 00000000..97944c90 --- /dev/null +++ b/tests/integration/components/sheet-test.js @@ -0,0 +1,430 @@ +import { module, test } from 'qunit'; +import { setupRenderingTest } from 'dummy/tests/helpers'; +import { render, click, focus, settled, triggerEvent, triggerKeyEvent, find } from '@ember/test-helpers'; +import { hbs } from 'ember-cli-htmlbars'; +import { SHEET_WIDTHS, SPINE_WIDTH, RESIZE_STEP } from '@fleetbase/ember-ui/components/sheet'; + +function cssVar(selector, name) { + return find(selector).style.getPropertyValue(name); +} + +module('Integration | Component | sheet', function (hooks) { + setupRenderingTest(hooks); + + hooks.beforeEach(function () { + this.calls = []; + this.onClose = () => this.calls.push('close'); + this.onPark = () => this.calls.push('park'); + this.onActivate = () => this.calls.push('activate'); + this.onResize = (width) => this.calls.push(['resize', width]); + }); + + module('rendering', function () { + test('by default it is a 440px sheet on the right, titled and labelled by its heading', async function (assert) { + await render(hbs`

Vehicle

`); + + const sheet = find('.fb-sheet'); + assert.dom(sheet).hasClass('is-right').hasClass('is-top').hasAttribute('role', 'dialog').hasAttribute('aria-modal', 'false').hasAttribute('data-depth', '0'); + assert.dom(sheet).doesNotHaveAttribute('aria-hidden'); + assert.strictEqual(cssVar('.fb-sheet', '--fb-sheet-width'), `${SHEET_WIDTHS.md}px`); + assert.strictEqual(cssVar('.fb-sheet', '--fb-sheet-offset'), '0px'); + assert.dom('h2.fb-sheet-title').hasText('CEN-01'); + assert.dom(sheet).hasAttribute('aria-labelledby', find('h2.fb-sheet-title').id); + assert.dom(sheet).doesNotHaveAttribute('aria-label'); + assert.dom('.fb-sheet-body .content').hasText('Vehicle'); + assert.dom('.fb-sheet-controls').doesNotExist('no close or park without handlers'); + assert.dom('.fb-sheet-footer').doesNotExist(); + assert.dom('.fb-sheet-resize').doesNotExist(); + assert.dom('.fb-sheet-spine').doesNotExist(); + assert.false(find('.fb-sheet-panel').inert); + assert.strictEqual(find('.fb-sheet').offsetWidth, SHEET_WIDTHS.md); + }); + + test('header, body and footer blocks', async function (assert) { + await render(hbs` + + <:header as |sheet|>Custom + <:body as |sheet|>

Body

+ <:footer as |sheet|> +
+ `); + + assert.dom('.fb-sheet-header .custom-header').hasText('Custom').hasAttribute('data-top', 'yes'); + assert.dom('.fb-sheet-title').doesNotExist('the header block replaces the title'); + assert.dom('.fb-sheet').hasAttribute('aria-label', 'CEN-01', 'a custom header names the sheet from @title'); + assert.dom('.fb-sheet').doesNotHaveAttribute('aria-labelledby'); + assert.dom('.fb-sheet-body .body').hasAttribute('data-top', 'yes'); + assert.dom('.fb-sheet-footer .footer-close').exists(); + + await click('.header-close'); + await click('.header-park'); + await click('.footer-close'); + assert.deepEqual(this.calls, ['close', 'park', 'close']); + }); + + test('the default block yields the sheet too', async function (assert) { + await render(hbs``); + await click('.inner'); + assert.deepEqual(this.calls, ['close']); + }); + + test('yielded actions without handlers do nothing', async function (assert) { + await render( + hbs`` + ); + await click('.inner-close'); + await click('.inner-park'); + assert.dom('.fb-sheet').exists(); + }); + + test('@label names the sheet', async function (assert) { + await render(hbs``); + assert.dom('.fb-sheet').hasAttribute('aria-label', 'Vehicle CEN-01').doesNotHaveAttribute('aria-labelledby'); + }); + + test('@side="left" docks it on the left', async function (assert) { + await render(hbs``); + assert.dom('.fb-sheet').hasClass('is-left').hasAttribute('data-side', 'left'); + }); + + const WIDTHS = [ + ['sm', `${SHEET_WIDTHS.sm}px`], + ['lg', `${SHEET_WIDTHS.lg}px`], + [500, '500px'], + ['550px', '550px'], + ['600', '600px'], + ['40vw', '40vw'], + ]; + for (const [width, css] of WIDTHS) { + test(`@width=${JSON.stringify(width)} sets the width to ${css}`, async function (assert) { + this.width = width; + await render(hbs``); + assert.strictEqual(cssVar('.fb-sheet', '--fb-sheet-width'), css); + }); + } + + test('close and park buttons call their handlers; @showClose={{false}} hides close', async function (assert) { + this.showClose = true; + await render(hbs``); + + assert.dom('.fb-sheet-park').hasAttribute('aria-label', 'Park CEN-01'); + assert.dom('.fb-sheet-close').hasAttribute('aria-label', 'Close CEN-01'); + await click('.fb-sheet-park'); + await click('.fb-sheet-close'); + assert.deepEqual(this.calls, ['park', 'close']); + + this.set('showClose', false); + assert.dom('.fb-sheet-close').doesNotExist(); + assert.dom('.fb-sheet-park').exists(); + }); + + test('@onOpen receives the sheet once it is mounted', async function (assert) { + this.onOpen = (sheet) => (this.opened = sheet); + await render(hbs``); + + assert.strictEqual(this.opened.element, find('.fb-sheet')); + this.opened.close(); + this.opened.park(); + this.opened.activate(); + assert.deepEqual(this.calls, ['close']); + }); + }); + + module('stacking', function () { + test('sheets behind the top one become spines, pushed in and inert', async function (assert) { + await render(hbs` + + + + `); + + assert.dom('.one').hasAttribute('data-depth', '2').hasClass('is-spine').doesNotHaveClass('is-top'); + assert.dom('.two').hasAttribute('data-depth', '1').hasClass('is-spine'); + assert.dom('.three').hasAttribute('data-depth', '0').hasClass('is-top').doesNotHaveClass('is-spine'); + assert.strictEqual(cssVar('.one', '--fb-sheet-offset'), `${2 * SPINE_WIDTH}px`); + assert.strictEqual(cssVar('.two', '--fb-sheet-offset'), `${SPINE_WIDTH}px`); + assert.strictEqual(cssVar('.three', '--fb-sheet-offset'), '0px'); + assert.true(find('.one .fb-sheet-panel').inert, 'content behind the top sheet is inert'); + assert.dom('.one .in-one').exists('but still mounted'); + assert.false(find('.three .fb-sheet-panel').inert); + assert.dom('.one .fb-sheet-spine').hasAttribute('aria-label', 'Show CEN-01').hasText('CEN-01'); + assert.dom('.three .fb-sheet-spine').doesNotExist(); + assert.dom('.one .fb-sheet-resize').doesNotExist(); + assert.dom('.three .fb-sheet-resize').exists('only the top sheet can be resized'); + + const zIndex = (selector) => Number(getComputedStyle(find(selector)).zIndex); + assert.true(zIndex('.three') > zIndex('.two'), 'the top sheet is in front'); + assert.true(zIndex('.two') > zIndex('.one'), 'and each spine in front of the one behind it'); + + await click('.one .fb-sheet-spine'); + await click('.two .fb-sheet-spine'); + assert.deepEqual(this.calls, ['activate'], 'a spine calls @onActivate, when given'); + }); + + test('more than three sheets behind the top one are hidden, not removed', async function (assert) { + await render(hbs` +

kept

+ + `); + + assert.dom('.deep').hasClass('is-hidden').hasAttribute('aria-hidden', 'true').doesNotHaveClass('is-spine'); + assert.strictEqual(getComputedStyle(find('.deep')).visibility, 'hidden'); + assert.strictEqual(cssVar('.deep', '--fb-sheet-offset'), `${3 * SPINE_WIDTH}px`); + assert.dom('.deep .deep-content').exists(); + }); + + test('a stack position out of range is clamped', async function (assert) { + await render(hbs` + + + + `); + + assert.dom('.over').hasAttribute('data-depth', '0'); + assert.dom('.under').hasAttribute('data-depth', '1'); + assert.dom('.bad').hasAttribute('data-depth', '0'); + }); + }); + + module('keyboard and focus', function () { + test('Escape closes only the top sheet', async function (assert) { + this.closeBottom = () => this.calls.push('bottom'); + this.closeTop = () => this.calls.push('top'); + await render(hbs` + + + `); + + await triggerKeyEvent('.top .field', 'keydown', 'Escape'); + assert.deepEqual(this.calls, ['top']); + }); + + test('Escape is ignored when @closeOnEscape is false or there is no @onClose', async function (assert) { + this.closeOnEscape = false; + await render(hbs``); + + await triggerKeyEvent('.fb-sheet', 'keydown', 'Escape'); + assert.deepEqual(this.calls, []); + + await render(hbs``); + await triggerKeyEvent('.fb-sheet', 'keydown', 'Escape'); + assert.dom('.fb-sheet').exists(); + }); + + test('Escape is left to an open modal', async function (assert) { + const modals = this.owner.lookup('service:modals-manager'); + Object.defineProperty(modals, 'modalIsOpened', { configurable: true, get: () => true }); + await render(hbs``); + + await triggerKeyEvent('.fb-sheet', 'keydown', 'Escape'); + assert.deepEqual(this.calls, []); + }); + + test('Escape still works where there is no modals-manager (inside an engine)', async function (assert) { + this.owner.unregister('service:modals-manager'); + await render(hbs``); + + await triggerKeyEvent('.fb-sheet', 'keydown', 'Escape'); + assert.deepEqual(this.calls, ['close']); + }); + + test('opening moves focus into the sheet, and closing returns it', async function (assert) { + this.open = false; + await render(hbs` + + {{#if this.open}}{{/if}} + `); + + await focus('.opener'); + this.set('open', true); + await settled(); + assert.strictEqual(document.activeElement, find('.fb-sheet'), 'the sheet takes focus'); + + await focus('.inside'); + this.set('open', false); + await settled(); + assert.strictEqual(document.activeElement, find('.opener'), 'focus goes back to the opener'); + }); + + test('focus is not pulled back when it moved elsewhere, or when the opener is gone', async function (assert) { + this.open = false; + this.showOpener = true; + await render(hbs` + {{#if this.showOpener}}{{/if}} + + {{#if this.open}}{{/if}} + `); + + await focus('.opener'); + this.set('open', true); + await settled(); + await focus('.elsewhere'); + this.set('open', false); + await settled(); + assert.strictEqual(document.activeElement, find('.elsewhere')); + + await focus('.opener'); + this.set('open', true); + await settled(); + this.set('showOpener', false); + this.set('open', false); + await settled(); + assert.dom('.opener').doesNotExist(); + }); + + test('@autofocus={{false}} leaves focus where it is', async function (assert) { + this.open = false; + await render(hbs` + + {{#if this.open}}{{/if}} + `); + + await focus('.opener'); + this.set('open', true); + await settled(); + assert.strictEqual(document.activeElement, find('.opener')); + this.set('open', false); + await settled(); + assert.strictEqual(document.activeElement, find('.opener')); + }); + + test('Tab and Shift+Tab cycle inside the top sheet', async function (assert) { + await render(hbs` + + + +
+ +
+ `); + + await focus('.last'); + await triggerKeyEvent('.last', 'keydown', 'Tab'); + assert.strictEqual(document.activeElement, find('.fb-sheet-close'), 'Tab on the last control wraps to the first'); + + await triggerKeyEvent('.fb-sheet-close', 'keydown', 'Tab', { shiftKey: true }); + assert.strictEqual(document.activeElement, find('.last'), 'Shift+Tab on the first wraps to the last, skipping hidden and inert ones'); + + await focus('.fb-sheet'); + await triggerKeyEvent('.fb-sheet', 'keydown', 'Tab', { shiftKey: true }); + assert.strictEqual(document.activeElement, find('.last'), 'Shift+Tab from the sheet itself goes to the last control'); + + await focus('.first-body'); + await triggerKeyEvent('.first-body', 'keydown', 'Tab'); + await triggerKeyEvent('.first-body', 'keydown', 'Tab', { shiftKey: true }); + await triggerKeyEvent('.first-body', 'keydown', 'Enter'); + assert.strictEqual(document.activeElement, find('.first-body'), 'Tab in the middle is left to the browser'); + }); + + test('Tab in a sheet with nothing focusable keeps focus on the sheet', async function (assert) { + await render(hbs``); + + await focus('.fb-sheet'); + await triggerKeyEvent('.fb-sheet', 'keydown', 'Tab'); + assert.strictEqual(document.activeElement, find('.fb-sheet')); + }); + + test('a sheet behind the top one does not trap Tab', async function (assert) { + await render(hbs` + + + `); + + await focus('.back .fb-sheet-spine'); + await triggerKeyEvent('.back .fb-sheet-spine', 'keydown', 'Tab'); + assert.strictEqual(document.activeElement, find('.back .fb-sheet-spine')); + }); + }); + + module('resizing', function () { + test('dragging the handle of a right-hand sheet widens it to the left, within its limits', async function (assert) { + await render(hbs``); + + assert + .dom('.fb-sheet-resize') + .hasAttribute('role', 'separator') + .hasAttribute('aria-valuenow', String(SHEET_WIDTHS.md)) + .hasAttribute('aria-valuemin', '320') + .hasAttribute('aria-valuemax', '960'); + + await triggerEvent('.fb-sheet-resize', 'pointerdown', { clientX: 500, button: 0 }); + await triggerEvent(window, 'pointermove', { clientX: 400 }); + assert.strictEqual(cssVar('.fb-sheet', '--fb-sheet-width'), `${SHEET_WIDTHS.md + 100}px`); + assert.dom('.fb-sheet-resize').hasAttribute('aria-valuenow', String(SHEET_WIDTHS.md + 100)); + + await triggerEvent(window, 'pointermove', { clientX: -2000 }); + assert.strictEqual(cssVar('.fb-sheet', '--fb-sheet-width'), '960px', 'clamped to the maximum'); + + await triggerEvent(window, 'pointermove', { clientX: 5000 }); + assert.strictEqual(cssVar('.fb-sheet', '--fb-sheet-width'), '320px', 'clamped to the minimum'); + + await triggerEvent(window, 'pointermove', { clientX: 5001 }); + await triggerEvent(window, 'pointerup'); + await triggerEvent(window, 'pointermove', { clientX: 400 }); + assert.strictEqual(cssVar('.fb-sheet', '--fb-sheet-width'), '320px', 'moves after pointerup are ignored'); + assert.deepEqual( + this.calls, + [ + ['resize', 540], + ['resize', 960], + ['resize', 320], + ], + 'onResize fires only on a change' + ); + }); + + test('a left-hand sheet widens to the right, and its limits can be set', async function (assert) { + await render(hbs``); + + await triggerEvent('.fb-sheet-resize', 'pointerdown', { clientX: 100 }); + await triggerEvent(window, 'pointermove', { clientX: 130 }); + assert.strictEqual(cssVar('.fb-sheet', '--fb-sheet-width'), `${SHEET_WIDTHS.sm + 30}px`); + await triggerEvent(window, 'pointermove', { clientX: 900 }); + assert.strictEqual(cssVar('.fb-sheet', '--fb-sheet-width'), '400px'); + await triggerEvent(window, 'pointercancel'); + }); + + test('only the main button starts a drag, and a drag ends when the sheet goes', async function (assert) { + this.open = true; + await render(hbs`{{#if this.open}}{{/if}}`); + + await triggerEvent('.fb-sheet-resize', 'pointerdown', { clientX: 500, button: 2 }); + await triggerEvent(window, 'pointermove', { clientX: 400 }); + assert.strictEqual(cssVar('.fb-sheet', '--fb-sheet-width'), `${SHEET_WIDTHS.md}px`); + + await triggerEvent('.fb-sheet-resize', 'pointerdown', { clientX: 500, button: 0 }); + this.set('open', false); + await settled(); + await triggerEvent(window, 'pointermove', { clientX: 400 }); + assert.dom('.fb-sheet').doesNotExist(); + }); + + test('the handle resizes with the keyboard', async function (assert) { + await render(hbs``); + + await triggerKeyEvent('.fb-sheet-resize', 'keydown', 'ArrowLeft'); + assert.strictEqual(cssVar('.fb-sheet', '--fb-sheet-width'), `${SHEET_WIDTHS.md + RESIZE_STEP}px`); + await triggerKeyEvent('.fb-sheet-resize', 'keydown', 'ArrowRight'); + await triggerKeyEvent('.fb-sheet-resize', 'keydown', 'ArrowRight'); + assert.strictEqual(cssVar('.fb-sheet', '--fb-sheet-width'), `${SHEET_WIDTHS.md - RESIZE_STEP}px`); + await triggerKeyEvent('.fb-sheet-resize', 'keydown', 'End'); + assert.strictEqual(cssVar('.fb-sheet', '--fb-sheet-width'), '960px'); + await triggerKeyEvent('.fb-sheet-resize', 'keydown', 'Home'); + assert.strictEqual(cssVar('.fb-sheet', '--fb-sheet-width'), '320px'); + await triggerKeyEvent('.fb-sheet-resize', 'keydown', 'Enter'); + assert.strictEqual(cssVar('.fb-sheet', '--fb-sheet-width'), '320px'); + }); + + test('on the left the arrows are mirrored, and a width in other units resizes from its rendered size', async function (assert) { + await render(hbs``); + + assert.dom('.fb-sheet-resize').hasAttribute('aria-valuenow', '320', 'an unmeasured width reports the minimum'); + const rendered = find('.fb-sheet').offsetWidth; + + await triggerKeyEvent('.fb-sheet-resize', 'keydown', 'ArrowRight'); + assert.strictEqual(cssVar('.fb-sheet', '--fb-sheet-width'), `${Math.min(rendered + RESIZE_STEP, 960)}px`); + await triggerKeyEvent('.fb-sheet-resize', 'keydown', 'ArrowLeft'); + assert.strictEqual(cssVar('.fb-sheet', '--fb-sheet-width'), `${Math.min(rendered + RESIZE_STEP, 960) - RESIZE_STEP}px`); + }); + }); +}); diff --git a/tests/test-helper.js b/tests/test-helper.js index d2fd7dc0..78b916cb 100644 --- a/tests/test-helper.js +++ b/tests/test-helper.js @@ -5,11 +5,15 @@ import { setApplication } from '@ember/test-helpers'; import { setup } from 'qunit-dom'; import { start } from 'ember-qunit'; import { forceModulesToBeLoaded, sendCoverage } from 'ember-cli-code-coverage/test-support'; +import { resetShellState } from '@fleetbase/ember-ui/test-support'; setApplication(Application.create(config.APP)); setup(QUnit.assert); +// Page-wide shell layout and sheet stack: start every test from the classic layout and no sheets. +QUnit.testStart(resetShellState); + // Evaluate every bundled module after the suite finishes so files no test imported still appear // in the coverage denominator, then post the collected coverage to the reporting middleware. // diff --git a/tests/unit/services/resource-context-panel-test.js b/tests/unit/services/resource-context-panel-test.js index cf2e0597..594cc40d 100644 --- a/tests/unit/services/resource-context-panel-test.js +++ b/tests/unit/services/resource-context-panel-test.js @@ -923,4 +923,78 @@ module('Unit | Service | resource-context-panel', function (hooks) { assert.throws(() => service.open(null), /Overlay definition is required/, 'and with an explicit null'); assert.strictEqual(service.overlays.length, 0, 'nothing is left behind'); }); + + module('parking', function () { + test('canPark is off until parking is enabled or the overlay opts in', function (assert) { + const plain = contentOverlay(); + assert.false(this.service.canPark(plain)); + assert.false(this.service.canPark(null)); + assert.true(this.service.canPark(contentOverlay({ parkable: true }))); + assert.true(this.service.canPark(contentOverlay({ onPark() {} }))); + + this.service.enableParking(); + assert.true(this.service.canPark(plain)); + + this.service.enableParking(false); + assert.false(this.service.canPark(plain)); + }); + + test('park moves an overlay out of the stack, calls its hook and triggers overlay.parked', function (assert) { + const events = []; + const hooks = []; + const resource = { name: 'Order 1' }; + this.service.on('overlay.parked', (overlay) => events.push(['parked', overlay.id])); + this.service.on('overlay.unparked', (overlay) => events.push(['unparked', overlay.id])); + + this.service.open(contentOverlay({ id: 'a', resource, onPark: (context) => hooks.push(context) })); + this.service.open(contentOverlay({ id: 'b' })); + + const parked = this.service.park('a'); + + assert.strictEqual(parked.id, 'a'); + assert.deepEqual( + this.service.overlays.map((overlay) => overlay.id), + ['b'] + ); + assert.deepEqual( + this.service.parked.map((overlay) => overlay.id), + ['a'] + ); + assert.true(this.service.isParked('a')); + assert.false(this.service.isParked('b')); + assert.strictEqual(hooks[0].resource, resource); + assert.strictEqual(hooks[0].model, resource); + + hooks[0].unpark(); + assert.deepEqual( + this.service.overlays.map((overlay) => overlay.id), + ['b', 'a'], + 'unparking puts it back on top' + ); + assert.deepEqual(this.service.parked, []); + assert.deepEqual(events, [ + ['parked', 'a'], + ['unparked', 'a'], + ]); + }); + + test('park without an id parks the active overlay; a model stands in for the resource', function (assert) { + const hooks = []; + const model = { name: 'Driver' }; + this.service.open(contentOverlay({ id: 'a', model, onPark: (context) => hooks.push(context) })); + + assert.strictEqual(this.service.park().id, 'a'); + assert.strictEqual(hooks[0].resource, model); + }); + + test('parking or unparking something that is not there does nothing', function (assert) { + assert.strictEqual(this.service.park(), null); + assert.strictEqual(this.service.park('missing'), null); + assert.strictEqual(this.service.unpark('missing'), null); + + this.service.open(contentOverlay({ id: 'a' })); + this.service.park('a'); + assert.strictEqual(this.service.unpark('a').id, 'a'); + }); + }); }); diff --git a/tests/unit/services/shell-test.js b/tests/unit/services/shell-test.js new file mode 100644 index 00000000..06851814 --- /dev/null +++ b/tests/unit/services/shell-test.js @@ -0,0 +1,70 @@ +import { module, test } from 'qunit'; +import { setupTest } from 'dummy/tests/helpers'; +import { run } from '@ember/runloop'; +import { settled } from '@ember/test-helpers'; +import { shellState } from '@fleetbase/ember-ui/services/shell'; + +module('Unit | Service | shell', function (hooks) { + setupTest(hooks); + + test('it starts in the classic layout', function (assert) { + const shell = this.owner.lookup('service:shell'); + + assert.strictEqual(shell.layout, 'classic'); + assert.true(shell.isClassic); + assert.false(shell.isCanvas); + assert.strictEqual(shell.explicitLayout, 'classic'); + }); + + test('setLayout switches layouts and falls back to classic for anything unknown', function (assert) { + const shell = this.owner.lookup('service:shell'); + + shell.setLayout('canvas'); + assert.strictEqual(shell.layout, 'canvas'); + assert.true(shell.isCanvas); + + shell.setLayout('sidebar'); + assert.strictEqual(shell.layout, 'classic'); + }); + + test('a mounted canvas makes the layout canvas until the last one unmounts', async function (assert) { + const shell = this.owner.lookup('service:shell'); + + run(() => { + shell.canvasDidMount(); + shell.canvasDidMount(); + }); + assert.strictEqual(shell.layout, 'canvas'); + + run(() => shell.canvasWillUnmount()); + assert.strictEqual(shell.layout, 'canvas', 'one canvas is still mounted'); + + run(() => shell.canvasWillUnmount()); + assert.strictEqual(shell.layout, 'classic'); + + run(() => shell.canvasWillUnmount()); + assert.strictEqual(shell.mountedCanvases, 0, 'the count never goes negative'); + await settled(); + }); + + test('a count change scheduled after the service is destroyed is dropped', async function (assert) { + const shell = this.owner.lookup('service:shell'); + + run(() => { + shell.canvasDidMount(); + shell.destroy(); + }); + await settled(); + + assert.strictEqual(shell.mountedCanvases, 0); + }); + + test('the service and engine-side readers share one state', function (assert) { + const shell = this.owner.lookup('service:shell'); + + shell.setLayout('canvas'); + + assert.strictEqual(shell.state, shellState); + assert.true(shellState.isCanvas); + }); +}); diff --git a/tests/unit/test-support/shell-state-test.js b/tests/unit/test-support/shell-state-test.js new file mode 100644 index 00000000..4bf81313 --- /dev/null +++ b/tests/unit/test-support/shell-state-test.js @@ -0,0 +1,27 @@ +import { module, test } from 'qunit'; +import { resetShellState, setupShellState } from '@fleetbase/ember-ui/test-support'; +import { shellState } from '@fleetbase/ember-ui/services/shell'; +import { sheetStack } from '@fleetbase/ember-ui/utils/sheet-stack'; + +module('Unit | test-support | shell state', function () { + test('resetShellState puts the layout back to classic and empties the sheet stack', function (assert) { + shellState.explicitLayout = 'canvas'; + shellState.mountedCanvases = 2; + sheetStack.register({ depth: 0, escape: () => false }); + + resetShellState(); + + assert.strictEqual(shellState.layout, 'classic'); + assert.strictEqual(shellState.mountedCanvases, 0); + assert.deepEqual(sheetStack.sheets, []); + }); + + module('setupShellState', function (hooks) { + shellState.explicitLayout = 'canvas'; + setupShellState(hooks); + + test('resets before each test', function (assert) { + assert.strictEqual(shellState.layout, 'classic'); + }); + }); +}); diff --git a/tests/unit/utils/sheet-stack-test.js b/tests/unit/utils/sheet-stack-test.js new file mode 100644 index 00000000..c9d89535 --- /dev/null +++ b/tests/unit/utils/sheet-stack-test.js @@ -0,0 +1,130 @@ +import { module, test } from 'qunit'; +import { SheetStack, sheetStack } from '@fleetbase/ember-ui/utils/sheet-stack'; + +function sheet(depth, handles = true) { + return { + depth, + escapes: 0, + escape() { + this.escapes++; + return handles; + }, + }; +} + +function escape(init = {}) { + const event = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true, ...init }); + window.dispatchEvent(event); + return event; +} + +module('Unit | Utility | sheet-stack', function (hooks) { + hooks.beforeEach(function () { + this.stack = new SheetStack(); + }); + + hooks.afterEach(function () { + this.stack.reset(); + }); + + test('one page-wide stack is shared by every sheet', function (assert) { + assert.true(sheetStack instanceof SheetStack); + }); + + test('the top sheet is the shallowest, and the latest among equals', function (assert) { + const bottom = sheet(1); + const front = sheet(0); + const later = sheet(0); + + assert.strictEqual(this.stack.top, null); + + this.stack.register(bottom); + this.stack.register(front); + this.stack.register(front); + assert.strictEqual(this.stack.sheets.length, 2, 'a sheet registers once'); + assert.strictEqual(this.stack.top, front); + + this.stack.register(later); + assert.true(this.stack.isTop(later)); + assert.false(this.stack.isTop(front)); + + this.stack.unregister(later); + this.stack.unregister(front); + this.stack.unregister(bottom); + assert.deepEqual(this.stack.sheets, []); + }); + + test('a deeper sheet mounted later does not take the top', function (assert) { + const front = sheet(0); + const behind = sheet(2); + this.stack.register(front); + this.stack.register(behind); + + assert.strictEqual(this.stack.top, front); + + this.stack.unregister(behind); + this.stack.unregister(front); + }); + + test('Escape asks only the top sheet and is consumed when it handles it', function (assert) { + const bottom = sheet(1); + const front = sheet(0); + this.stack.register(bottom); + this.stack.register(front); + + const event = escape(); + + assert.strictEqual(front.escapes, 1); + assert.strictEqual(bottom.escapes, 0); + assert.true(event.defaultPrevented); + + this.stack.unregister(front); + this.stack.unregister(bottom); + }); + + test('Escape is left alone when the top sheet declines it', function (assert) { + const front = sheet(0, false); + this.stack.register(front); + + assert.false(escape().defaultPrevented); + assert.strictEqual(front.escapes, 1); + + this.stack.unregister(front); + }); + + test('other keys and handled or composing events are ignored', function (assert) { + const front = sheet(0); + this.stack.register(front); + + window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter' })); + escape({ isComposing: true }); + + const handled = new KeyboardEvent('keydown', { key: 'Escape', cancelable: true }); + handled.preventDefault(); + window.dispatchEvent(handled); + + assert.strictEqual(front.escapes, 0); + this.stack.unregister(front); + }); + + test('Escape with no sheets does nothing, and the listener goes when the last sheet does', function (assert) { + const front = sheet(0); + this.stack.register(front); + this.stack.unregister(front); + + assert.false(escape().defaultPrevented); + this.stack.handleKeydown(new KeyboardEvent('keydown', { key: 'Escape' })); + assert.strictEqual(front.escapes, 0); + }); + + test('reset drops every sheet and the listener', function (assert) { + const front = sheet(0); + this.stack.register(front); + this.stack.unregister(sheet(0)); + + this.stack.reset(); + escape(); + + assert.strictEqual(front.escapes, 0); + }); +});