UNPKG

@wordpress/widget-dashboard

Version:

Stateless rendering engine for widget dashboards: the WidgetDashboard compound component and its grid-settings kit.

1 lines • 15.6 kB
{"version":3,"file":"widget-attributes.mjs","names":["styles"],"sources":["../../../../style-runtime/src/index.ts","../../../src/components/widget-attributes/widget-attributes.module.css","../../../src/components/widget-attributes/widget-attributes.tsx"],"sourcesContent":["type GlobalScopeWithStyleRuntime = typeof globalThis & {\n\t// This global is shared by separately bundled copies of this package.\n\t// Keep its shape backward compatible after release.\n\t__wpStyleRuntime?: {\n\t\tdocuments: Map< Document, number >;\n\t\tstyles: Map< string, string >;\n\t\tinjectedStyles: WeakMap< Document, Set< string > >;\n\t};\n};\n\nconst STYLE_HASH_ATTRIBUTE = 'data-wp-hash';\n\n/**\n * Returns the shared style runtime registry.\n *\n * The registry is stored on `globalThis` so separately bundled copies of this\n * package can coordinate through the same document and style maps.\n *\n * @return The shared runtime registry.\n */\nfunction getRuntime() {\n\tconst globalScope = globalThis as GlobalScopeWithStyleRuntime;\n\n\tif ( globalScope.__wpStyleRuntime ) {\n\t\treturn globalScope.__wpStyleRuntime;\n\t}\n\n\tglobalScope.__wpStyleRuntime = {\n\t\tdocuments: new Map(),\n\t\tstyles: new Map(),\n\t\tinjectedStyles: new WeakMap(),\n\t};\n\n\tif ( typeof document !== 'undefined' ) {\n\t\tregisterDocument( document );\n\t}\n\n\treturn globalScope.__wpStyleRuntime;\n}\n\n/**\n * Checks whether a document already contains a style tag for a hash.\n *\n * @param targetDocument Document to inspect.\n * @param hash Stable hash for the transformed CSS.\n *\n * @return Whether the style hash already exists in the document.\n */\nfunction documentContainsStyleHash(\n\ttargetDocument: Document,\n\thash: string\n): boolean {\n\tif ( ! targetDocument.head ) {\n\t\treturn false;\n\t}\n\n\tfor ( const style of targetDocument.head.querySelectorAll(\n\t\t`style[${ STYLE_HASH_ATTRIBUTE }]`\n\t) ) {\n\t\tif ( style.getAttribute( STYLE_HASH_ATTRIBUTE ) === hash ) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\n/**\n * Injects a registered style into a document, unless that document already\n * contains a style tag for the same hash.\n *\n * @param targetDocument Document to inject the style into.\n * @param hash Stable hash for the transformed CSS.\n * @param css CSS text to inject.\n */\nfunction injectStyle( targetDocument: Document, hash: string, css: string ) {\n\tif ( ! targetDocument.head ) {\n\t\treturn;\n\t}\n\n\tconst runtime = getRuntime();\n\tlet injectedStyles = runtime.injectedStyles.get( targetDocument );\n\n\tif ( ! injectedStyles ) {\n\t\tinjectedStyles = new Set();\n\t\truntime.injectedStyles.set( targetDocument, injectedStyles );\n\t}\n\n\tif ( injectedStyles.has( hash ) ) {\n\t\treturn;\n\t}\n\n\t// Older generated CSS module output can still inject matching style tags\n\t// after this document's cache is created, so keep the DOM as the fallback\n\t// source of truth on cache misses.\n\tif ( documentContainsStyleHash( targetDocument, hash ) ) {\n\t\tinjectedStyles.add( hash );\n\t\treturn;\n\t}\n\n\tconst style = targetDocument.createElement( 'style' );\n\tstyle.setAttribute( STYLE_HASH_ATTRIBUTE, hash );\n\tstyle.appendChild( targetDocument.createTextNode( css ) );\n\ttargetDocument.head.appendChild( style );\n\tinjectedStyles.add( hash );\n}\n\n/**\n * Registers a document as a style injection target.\n *\n * Existing registered styles are replayed into the document immediately.\n * Documents are reference-counted so multiple providers can safely register the\n * same document without one cleanup removing it while another registration is\n * still active.\n *\n * @param targetDocument Document to receive registered styles.\n * @return Cleanup function that unregisters this document registration.\n */\nexport function registerDocument( targetDocument: Document ) {\n\tconst runtime = getRuntime();\n\n\truntime.documents.set(\n\t\ttargetDocument,\n\t\t( runtime.documents.get( targetDocument ) ?? 0 ) + 1\n\t);\n\n\tfor ( const [ hash, css ] of runtime.styles ) {\n\t\tinjectStyle( targetDocument, hash, css );\n\t}\n\n\treturn () => {\n\t\tconst count = runtime.documents.get( targetDocument );\n\n\t\tif ( count === undefined ) {\n\t\t\treturn;\n\t\t}\n\n\t\tif ( count <= 1 ) {\n\t\t\truntime.documents.delete( targetDocument );\n\t\t\treturn;\n\t\t}\n\n\t\truntime.documents.set( targetDocument, count - 1 );\n\t};\n}\n\n/**\n * Registers a style and injects it into all registered documents.\n *\n * The hash is used as the deduplication key, so calling this repeatedly with\n * the same hash will not add duplicate style tags to a document.\n * Registered styles are retained for the lifetime of the page so they can be\n * replayed into documents that are registered later.\n *\n * @param hash Stable hash for the transformed CSS.\n * @param css CSS text to inject.\n */\nexport function registerStyle( hash: string, css: string ) {\n\tconst runtime = getRuntime();\n\n\truntime.styles.set( hash, css );\n\n\tfor ( const targetDocument of runtime.documents.keys() ) {\n\t\tinjectStyle( targetDocument, hash, css );\n\t}\n}\n","import { registerStyle } from '@wordpress/style-runtime';\nif (typeof process === 'undefined' || process.env.NODE_ENV !== 'test') {\n\tregisterStyle(\"27fba157f9\", \".dfa7591b08f2a1f2__inline-controls{flex-shrink:0}.e0925dcc0f5ef942__persistent-controls{display:inline-flex}._250cbb9f4bc68d8e__dropdown-area{display:contents}._2f55b82b27647445__dropdown-popup{max-width:300px}\");\n}\nexport default {\"inline-controls\":\"dfa7591b08f2a1f2__inline-controls\",\"persistent-controls\":\"e0925dcc0f5ef942__persistent-controls\",\"dropdown-area\":\"_250cbb9f4bc68d8e__dropdown-area\",\"dropdown-popup\":\"_2f55b82b27647445__dropdown-popup\"};\n","import { DataForm } from '@wordpress/dataviews';\nimport type { Field, Form } from '@wordpress/dataviews';\nimport { useCallback, useEffect, useMemo, useState } from '@wordpress/element';\nimport { Stack } from '@wordpress/ui';\nimport type { WidgetType } from '@wordpress/widget-primitives';\nimport { useDashboardInternalContext } from '../../context/dashboard-context';\nimport { useReserveHeaderSpace } from '../widget-header/widget-header-fit';\nimport { WidgetSettingsTrigger } from '../widget-settings';\nimport { AttributesDropdown } from './attributes-dropdown';\nimport { useInlineFit } from './use-inline-fit';\nimport styles from './widget-attributes.module.css';\nimport type { DashboardWidget, WidgetAttributeValues } from '../../types';\n\ntype WidgetAttributesProps = {\n\t/**\n\t * The instance whose attributes these controls edit.\n\t */\n\twidget: DashboardWidget< unknown >;\n\n\t/**\n\t * The instance's widget type, source of the attribute schema.\n\t */\n\twidgetType: WidgetType;\n};\n\n/**\n * Normal-mode controls: the `relevance: 'high'` attributes on a prominent\n * surface, plus a settings entry point when needed.\n *\n * Inline controls appear only for the high-relevance fields; edits stage live\n * and auto-save on the dashboard's shared debounce.\n *\n * The inline presentation holds only while it fits the header.\n * When the fields' natural width exceeds the space the header can grant,\n * they unmount and collapse into a dropdown holding them as a form; the\n * settings trigger is not part of the collapse and stays in the toolbar.\n * While collapsed, the last measurement is retained to decide when to\n * expand back; remounting re-measures and re-collapses if the retained\n * value went stale.\n *\n * @param {WidgetAttributesProps} props Component props.\n */\nexport function WidgetAttributes( {\n\twidget,\n\twidgetType,\n}: WidgetAttributesProps ): React.ReactNode {\n\tconst { layout, onLayoutChange, scheduleAutoSave } =\n\t\tuseDashboardInternalContext();\n\n\tconst hasSettingsSurface = !! widgetType.attributes?.some(\n\t\t( attribute ) => attribute.relevance !== 'high'\n\t);\n\n\t// The settings trigger stays in the toolbar in both presentations, so it\n\t// reserves its own footprint from the header's fit budget.\n\tconst settingsReserveRef =\n\t\tuseReserveHeaderSpace< HTMLSpanElement >( 'settings' );\n\n\t// While the user interacts with a presentation, the fit holds it in\n\t// place; replacing it mid-interaction would drop focus on the floor.\n\t// The hold covers the open dropdown, focus inside the inline form, and\n\t// focus on the dropdown trigger itself: dismissing the popup restores\n\t// focus to the trigger asynchronously, so the trigger must survive\n\t// until focus moves on. The pending transition applies afterwards.\n\tconst [ dropdownOpen, setDropdownOpen ] = useState( false );\n\tconst [ inlineHasFocus, setInlineHasFocus ] = useState( false );\n\tconst [ dropdownTriggerHasFocus, setDropdownTriggerHasFocus ] =\n\t\tuseState( false );\n\n\tconst { measureRef, collapsed } = useInlineFit( {\n\t\tlocked: dropdownOpen || inlineHasFocus || dropdownTriggerHasFocus,\n\t} );\n\n\t// A transition can only start once focus left the outgoing\n\t// presentation; clear its flag if it unmounts with the flag still set.\n\tuseEffect( () => {\n\t\tif ( collapsed ) {\n\t\t\tsetInlineHasFocus( false );\n\t\t} else {\n\t\t\tsetDropdownTriggerHasFocus( false );\n\t\t}\n\t}, [ collapsed ] );\n\n\tconst fields = useMemo< Field< WidgetAttributeValues >[] >(\n\t\t() =>\n\t\t\t( widgetType.attributes ?? [] ).filter(\n\t\t\t\t( attribute ) => attribute.relevance === 'high'\n\t\t\t) as Field< WidgetAttributeValues >[],\n\t\t[ widgetType.attributes ]\n\t);\n\n\t// A `row` top-level layout lays the controls out horizontally; each field\n\t// carries `labelPosition: 'none'` so the control renders bare.\n\tconst form = useMemo< Form >(\n\t\t() => ( {\n\t\t\tlayout: { type: 'row', alignment: 'center' },\n\t\t\tfields: fields.map( ( field ) => ( {\n\t\t\t\tid: field.id,\n\t\t\t\tlayout: { type: 'regular', labelPosition: 'none' },\n\t\t\t} ) ),\n\t\t} ),\n\t\t[ fields ]\n\t);\n\n\tconst handleChange = useCallback(\n\t\t( edits: Record< string, unknown > ) => {\n\t\t\tonLayoutChange(\n\t\t\t\tlayout.map( ( instance ) =>\n\t\t\t\t\tinstance.uuid === widget.uuid\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t...instance,\n\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t...( instance.attributes as object ),\n\t\t\t\t\t\t\t\t\t...edits,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: instance\n\t\t\t\t)\n\t\t\t);\n\n\t\t\tscheduleAutoSave();\n\t\t},\n\t\t[ layout, onLayoutChange, widget.uuid, scheduleAutoSave ]\n\t);\n\n\tconst data = ( widget.attributes ??\n\t\twidgetType.example?.attributes ??\n\t\t{} ) as WidgetAttributeValues;\n\n\treturn (\n\t\t<>\n\t\t\t{ ! collapsed ? (\n\t\t\t\tfields.length > 0 && (\n\t\t\t\t\t<Stack\n\t\t\t\t\t\tdirection=\"row\"\n\t\t\t\t\t\talign=\"center\"\n\t\t\t\t\t\tgap=\"xs\"\n\t\t\t\t\t\tref={ measureRef }\n\t\t\t\t\t\tclassName={ styles[ 'inline-controls' ] }\n\t\t\t\t\t\tonFocus={ () => setInlineHasFocus( true ) }\n\t\t\t\t\t\tonBlur={ ( event ) => {\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t! event.currentTarget.contains(\n\t\t\t\t\t\t\t\t\tevent.relatedTarget as Node | null\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tsetInlineHasFocus( false );\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} }\n\t\t\t\t\t>\n\t\t\t\t\t\t<DataForm< WidgetAttributeValues >\n\t\t\t\t\t\t\tdata={ data }\n\t\t\t\t\t\t\tfields={ fields }\n\t\t\t\t\t\t\tform={ form }\n\t\t\t\t\t\t\tonChange={ handleChange }\n\t\t\t\t\t\t/>\n\t\t\t\t\t</Stack>\n\t\t\t\t)\n\t\t\t) : (\n\t\t\t\t<span\n\t\t\t\t\tclassName={ styles[ 'dropdown-area' ] }\n\t\t\t\t\tonFocus={ () => setDropdownTriggerHasFocus( true ) }\n\t\t\t\t\tonBlur={ ( event ) => {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t! event.currentTarget.contains(\n\t\t\t\t\t\t\t\tevent.relatedTarget as Node | null\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tsetDropdownTriggerHasFocus( false );\n\t\t\t\t\t\t}\n\t\t\t\t\t} }\n\t\t\t\t>\n\t\t\t\t\t<AttributesDropdown\n\t\t\t\t\t\tfields={ fields }\n\t\t\t\t\t\tdata={ data }\n\t\t\t\t\t\tonChange={ handleChange }\n\t\t\t\t\t\tonOpenChange={ setDropdownOpen }\n\t\t\t\t\t/>\n\t\t\t\t</span>\n\t\t\t) }\n\n\t\t\t{ hasSettingsSurface && (\n\t\t\t\t<span\n\t\t\t\t\tref={ settingsReserveR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