From 1ede158f646456d00fd184e238a736469772949f Mon Sep 17 00:00:00 2001 From: KMchaudhary Date: Tue, 3 Nov 2026 15:39:16 +0530 Subject: [PATCH 01/20] test(layers): add Layer API contract tests and RFC draft Pin down how layers behave today, so the Layer API refactor (#2290) can move core layer types onto a registry and prove nothing changed: - Editor: the data each core type starts with, the add-on menu and creator path, media-type gating, settings-panel selection, and the window globals add-ons use. - Player: which manager gets each layer, add-on managers, validation, and the shared front-end registry and queue. - Image block: which saved layers reach the browser, and how the image renderer draws hotspot and woo layers. Tests marked "current behaviour" pin what the refactor intends to change on purpose. Also add the RFC draft (docs/rfcs/layer-api.md) with the audit of every reader of saved layers, and keep /docs/ out of the release package. Refs #2291 Co-Authored-By: Claude Opus 5.5 --- .distignore | 3 + .../render-image-frame.test.js | 146 ++++++++ .../managers/layersManager.contract.test.js | 309 +++++++++++++++++ .../godam-player/utils/layer-registry.test.js | 149 ++++++++ docs/rfcs/layer-api.md | 161 +++++++++ .../components/SidebarLayers.test.js | 326 ++++++++++++++++++ .../components/layers/Layer.test.js | 111 ++++++ pages/video-editor/index.test.js | 72 ++++ tests/js/layer-contract-globals.js | 37 ++ tests/php/ImageBlockLayerContractTest.php | 251 ++++++++++++++ tests/stubs/block-render-functions.php | 30 ++ 11 files changed, 1595 insertions(+) create mode 100644 assets/src/js/godam-image-layers/render-image-frame.test.js create mode 100644 assets/src/js/godam-player/managers/layersManager.contract.test.js create mode 100644 assets/src/js/godam-player/utils/layer-registry.test.js create mode 100644 docs/rfcs/layer-api.md create mode 100644 pages/video-editor/components/SidebarLayers.test.js create mode 100644 pages/video-editor/components/layers/Layer.test.js create mode 100644 pages/video-editor/index.test.js create mode 100644 tests/js/layer-contract-globals.js create mode 100644 tests/php/ImageBlockLayerContractTest.php create mode 100644 tests/stubs/block-render-functions.php diff --git a/.distignore b/.distignore index 16cd3c9e4c..2f7c035439 100644 --- a/.distignore +++ b/.distignore @@ -45,3 +45,6 @@ phpunit.xml.dist # Dashboard widget sample data: development and review only, never shipped. /inc/classes/class-dashboard-widget-preview.php + +# Design docs and RFCs: for contributors, not shipped. +/docs/ diff --git a/assets/src/js/godam-image-layers/render-image-frame.test.js b/assets/src/js/godam-image-layers/render-image-frame.test.js new file mode 100644 index 0000000000..cf8a202faa --- /dev/null +++ b/assets/src/js/godam-image-layers/render-image-frame.test.js @@ -0,0 +1,146 @@ +/** + * Layer API contract tests (#2291): layers on a `godam/image` block. + * + * The image renderer draws `hotspot` layers itself and hands `woo` layers to + * the manager godam-for-woo registered in the layer registry. No other type is + * drawn. #2294 moves images onto the shared layer lifecycle; tests marked + * "current behaviour" pin what it intends to change on purpose. + */ + +/** + * Internal dependencies + */ +import { initImageFrame } from './render-image-frame.js'; +import HotspotLayerManager from '../godam-player/managers/layers/hotspotLayerManager.js'; +import { registerLayerType } from '../godam-player/utils/layer-registry.js'; + +jest.mock( '../godam-player/managers/layers/hotspotLayerManager.js', () => ( { + __esModule: true, + default: jest.fn().mockImplementation( function MockHotspotLayerManager() { + this.hotspotLayers = []; + this.setupHotspotLayer = jest.fn( ( layer ) => this.hotspotLayers.push( { layer } ) ); + this.createHotspots = jest.fn(); + this.updateHotspotPositions = jest.fn(); + } ), +} ) ); + +jest.mock( '../godam-player/utils/pluginLoader.js', () => ( { + loadFontAwesome: jest.fn( () => Promise.resolve() ), + hasHotspotsWithIcons: jest.fn( () => false ), + renderFontAwesomeIcons: jest.fn(), +} ) ); + +/** + * Build the frame markup `godam-image/render.php` prints, with an already-loaded image. + * + * @param {Array} layers Saved layers. + * @return {HTMLElement} The `.godam-image__frame` element. + */ +const makeFrame = ( layers ) => { + const frame = document.createElement( 'div' ); + frame.className = 'godam-image__frame'; + frame.dataset.godamImageLayers = JSON.stringify( layers ); + frame.dataset.instanceId = 'img-1'; + frame.innerHTML = '
'; + const img = frame.querySelector( 'img' ); + Object.defineProperty( img, 'complete', { value: true } ); + Object.defineProperty( img, 'naturalWidth', { value: 800 } ); + document.body.appendChild( frame ); + return frame; +}; + +const makeWooManager = () => + jest.fn().mockImplementation( function WooManager() { + this.wooLayers = []; + this.setupLayer = jest.fn( ( layer ) => this.wooLayers.push( { layer } ) ); + this.createProductHotspots = jest.fn(); + this.emitLayerVisible = jest.fn(); + } ); + +describe( 'Layer API contract: image layers', () => { + let teardowns; + + beforeEach( () => { + delete window.__godamLayerRegistryStore; + HotspotLayerManager.mockClear(); + teardowns = []; + jest.spyOn( console, 'warn' ).mockImplementation( () => {} ); + } ); + + afterEach( () => { + teardowns.forEach( ( teardown ) => teardown() ); + document.body.innerHTML = ''; + jest.restoreAllMocks(); + } ); + + const init = ( frame ) => { + const teardown = initImageFrame( frame ); + teardowns.push( teardown ); + return teardown; + }; + + it( 'merges every hotspot layer into one hotspot manager layer', () => { + init( makeFrame( [ + { id: 'h1', type: 'hotspot', hotspots: [ { id: 's1' } ] }, + { id: 'h2', type: 'hotspot', hotspots: [ { id: 's2' } ] }, + ] ) ); + + expect( HotspotLayerManager ).toHaveBeenCalledTimes( 1 ); + const manager = HotspotLayerManager.mock.instances[ 0 ]; + const [ merged ] = manager.setupHotspotLayer.mock.calls[ 0 ]; + expect( merged ).toMatchObject( { id: 'godam-image-hotspots', type: 'hotspot' } ); + expect( merged.hotspots.map( ( h ) => h.id ) ).toEqual( [ 's1', 's2' ] ); + expect( manager.createHotspots ).toHaveBeenCalledTimes( 1 ); + } ); + + it( 'hands each woo layer to the registered woo manager and fires its impression', () => { + const WooManager = makeWooManager(); + registerLayerType( 'woo', { label: 'Woo', validator: () => true, manager: WooManager } ); + const layers = [ { id: 'w1', type: 'woo' }, { id: 'w2', type: 'woo' } ]; + const frame = makeFrame( layers ); + + init( frame ); + + expect( WooManager ).toHaveBeenCalledTimes( 1 ); + expect( WooManager.mock.calls[ 0 ][ 2 ] ).toBe( 'img-1' ); + const manager = WooManager.mock.instances[ 0 ]; + expect( manager.setupLayer.mock.calls.map( ( [ layer ] ) => layer ) ).toEqual( layers ); + expect( manager.createProductHotspots ).toHaveBeenCalledTimes( 2 ); + expect( manager.emitLayerVisible.mock.calls ).toEqual( [ [ layers[ 0 ] ], [ layers[ 1 ] ] ] ); + expect( frame.dataset.godamLayersRendered ).toBe( 'true' ); + } ); + + it( 'skips woo layers when no woo manager is registered', () => { + const frame = makeFrame( [ { id: 'w1', type: 'woo' } ] ); + init( frame ); + expect( frame.dataset.godamLayersRendered ).toBe( 'true' ); + expect( frame.querySelector( '.godam-image-woo-layer' ) ).toBeNull(); + } ); + + // Current behaviour: only `hotspot` and `woo` draw on images, even when another + // type has a registered manager. #2294 lets any type that supports images draw. + it( 'ignores any other type, even one with a registered manager', () => { + const AcmeManager = makeWooManager(); + registerLayerType( 'acme', { label: 'Acme', validator: () => true, manager: AcmeManager } ); + const frame = makeFrame( [ { id: 'a1', type: 'acme' }, { id: 'c1', type: 'cta' } ] ); + + init( frame ); + + expect( AcmeManager ).not.toHaveBeenCalled(); + expect( HotspotLayerManager ).not.toHaveBeenCalled(); + expect( frame.dataset.godamLayersRendered ).toBe( 'true' ); + } ); + + it( 'draws nothing for a frame with no layers', () => { + const frame = makeFrame( [] ); + init( frame ); + expect( frame.dataset.godamLayersRendered ).toBeUndefined(); + } ); + + it( 'returns the same teardown when a frame is initialized twice', () => { + const frame = makeFrame( [ { id: 'h1', type: 'hotspot', hotspots: [] } ] ); + const first = init( frame ); + expect( initImageFrame( frame ) ).toBe( first ); + expect( HotspotLayerManager ).toHaveBeenCalledTimes( 1 ); + } ); +} ); diff --git a/assets/src/js/godam-player/managers/layersManager.contract.test.js b/assets/src/js/godam-player/managers/layersManager.contract.test.js new file mode 100644 index 0000000000..c2a42b9ad0 --- /dev/null +++ b/assets/src/js/godam-player/managers/layersManager.contract.test.js @@ -0,0 +1,309 @@ +/** + * Layer API contract tests (#2291): how the player sets up each saved layer. + * + * `LayersManager` sends form, CTA and poll layers to `FormLayerManager`, hotspot + * layers to `HotspotLayerManager`, and any other type to the manager an add-on + * registered in the layer registry. `LayerValidator` decides first whether a + * layer runs at all. #2294 replaces this with one lifecycle; these tests are + * what it must keep passing. Tests marked "current behaviour" pin something + * #2294 intends to change on purpose. + */ + +/** + * Internal dependencies + */ +import LayersManager from './layersManager'; +import LayerValidator from './layers/layerValidator'; +import FormLayerManager from './layers/formLayerManager.js'; +import HotspotLayerManager from './layers/hotspotLayerManager.js'; +import { registerLayerType } from '../utils/layer-registry.js'; + +jest.mock( './layers/formLayerManager.js', () => ( { + __esModule: true, + default: jest.fn().mockImplementation( () => ( { + setupFormLayer: jest.fn(), + handleFormLayersTimeUpdate: jest.fn(), + handleFullscreenChange: jest.fn(), + handlePause: jest.fn(), + handleEnded: jest.fn(), + sortLayers: jest.fn(), + formLayers: [], + } ) ), +} ) ); + +jest.mock( './layers/hotspotLayerManager.js', () => ( { + __esModule: true, + default: jest.fn().mockImplementation( () => ( { + setupHotspotLayer: jest.fn(), + handleHotspotLayersTimeUpdate: jest.fn(), + handleFullscreenChange: jest.fn(), + updateHotspotPositions: jest.fn(), + } ) ), +} ) ); + +jest.mock( '../utils/pluginLoader.js', () => ( { + loadFontAwesome: jest.fn( () => Promise.resolve() ), + hasHotspotsWithIcons: jest.fn( () => false ), +} ) ); + +const allDependencies = { gravityforms: true, wpPolls: true }; + +const createPlayer = () => { + const container = document.createElement( 'div' ); + return { + on: jest.fn(), + el: () => container, + isFullscreen: () => true, + }; +}; + +/** + * Build a manager plus the `#layer--` containers the PHP template prints. + * + * @param {Array} layers Saved layers. + * @param {Object} [options] Options. + * @param {Array} [options.skip] Layer ids to print no container for. + * @param {Object} [options.extra] Extra config. + * @return {Object} `{ manager, player, isDisplayingLayers }`. + */ +const setup = ( layers, { skip = [], extra = {} } = {} ) => { + document.body.innerHTML = ''; + layers.forEach( ( layer ) => { + if ( ! skip.includes( layer.id ) ) { + const el = document.createElement( 'div' ); + el.id = `layer-7-${ layer.id }`; + document.body.appendChild( el ); + } + } ); + + const video = document.createElement( 'video' ); + video.dataset.instanceId = '7'; + const player = createPlayer(); + const isDisplayingLayers = {}; + const config = { isPreviewEnabled: false, videoSetupOptions: { layers }, ...extra }; + const manager = new LayersManager( player, video, config, isDisplayingLayers, 'player-7' ); + return { manager, player, isDisplayingLayers }; +}; + +const containerFor = ( id ) => document.getElementById( `layer-7-${ id }` ); + +describe( 'Layer API contract: LayersManager dispatch', () => { + beforeEach( () => { + delete window.__godamLayerRegistryStore; + window.godamPluginDependencies = allDependencies; + jest.spyOn( console, 'warn' ).mockImplementation( () => {} ); + } ); + + afterEach( () => { + jest.restoreAllMocks(); + delete window.godamPluginDependencies; + } ); + + it( 'sends form, CTA and poll layers to the form manager with their container', async () => { + const layers = [ + { id: 'f', type: 'form', form_type: 'gravity' }, + { id: 'c', type: 'cta' }, + { id: 'p', type: 'poll' }, + ]; + const { manager } = setup( layers ); + + await manager.setupLayers(); + + expect( manager.formLayerManager.setupFormLayer.mock.calls ).toEqual( [ + [ layers[ 0 ], containerFor( 'f' ) ], + [ layers[ 1 ], containerFor( 'c' ) ], + [ layers[ 2 ], containerFor( 'p' ) ], + ] ); + expect( manager.hotspotLayerManager.setupHotspotLayer ).not.toHaveBeenCalled(); + } ); + + it( 'sends hotspot layers to the hotspot manager', async () => { + const layer = { id: 'h', type: 'hotspot', hotspots: [] }; + const { manager } = setup( [ layer ] ); + await manager.setupLayers(); + expect( manager.hotspotLayerManager.setupHotspotLayer ).toHaveBeenCalledWith( layer, containerFor( 'h' ) ); + } ); + + it( 'hides every layer container before handing it over', async () => { + const { manager } = setup( [ { id: 'c', type: 'cta' } ] ); + await manager.setupLayers(); + expect( containerFor( 'c' ).classList.contains( 'hidden' ) ).toBe( true ); + } ); + + it( 'gives the form manager to the public player API as player.layersManager', () => { + const { manager, player } = setup( [] ); + expect( player.layersManager ).toBe( manager.formLayerManager ); + } ); + + it( 'creates the sub-managers with ( player, isDisplayingLayers, instanceId )', () => { + FormLayerManager.mockClear(); + HotspotLayerManager.mockClear(); + const { player, isDisplayingLayers } = setup( [] ); + expect( FormLayerManager ).toHaveBeenCalledWith( player, isDisplayingLayers, 'player-7' ); + expect( HotspotLayerManager ).toHaveBeenCalledWith( player, isDisplayingLayers, 'player-7' ); + } ); + + describe( 'add-on layer managers', () => { + const makeAddonManager = () => + jest.fn().mockImplementation( function AcmeManager() { + this.setupLayer = jest.fn(); + this.handleTimeUpdate = jest.fn(); + this.handleResize = jest.fn(); + this.handleFullscreenChange = jest.fn(); + } ); + + it( 'creates one registered manager per type and sends it each layer of that type', async () => { + const AcmeManager = makeAddonManager(); + registerLayerType( 'acme', { label: 'Acme', validator: () => true, manager: AcmeManager } ); + const layers = [ { id: 'a1', type: 'acme' }, { id: 'a2', type: 'acme' } ]; + const { manager, player, isDisplayingLayers } = setup( layers ); + + await manager.setupLayers(); + + expect( AcmeManager ).toHaveBeenCalledTimes( 1 ); + expect( AcmeManager ).toHaveBeenCalledWith( player, isDisplayingLayers, 'player-7' ); + const instance = manager.customLayerManagers.acme; + expect( instance.setupLayer.mock.calls ).toEqual( [ + [ layers[ 0 ], containerFor( 'a1' ) ], + [ layers[ 1 ], containerFor( 'a2' ) ], + ] ); + } ); + + it( 'forwards time updates, resizes and fullscreen changes to add-on managers', async () => { + registerLayerType( 'acme', { label: 'Acme', validator: () => true, manager: makeAddonManager() } ); + const { manager, player } = setup( [ { id: 'a1', type: 'acme' } ] ); + await manager.setupLayers(); + const instance = manager.customLayerManagers.acme; + + manager.handleCustomLayersTimeUpdate( 4.5 ); + manager.handleVideoResize(); + manager.handleFullscreenChange(); + + expect( instance.handleTimeUpdate ).toHaveBeenCalledWith( 4.5 ); + expect( instance.handleResize ).toHaveBeenCalled(); + expect( instance.handleFullscreenChange ).toHaveBeenCalledWith( true, player.el() ); + } ); + + it( 'holds add-on time updates back while layers are suppressed', async () => { + registerLayerType( 'acme', { label: 'Acme', validator: () => true, manager: makeAddonManager() } ); + const { manager } = setup( [ { id: 'a1', type: 'acme' } ] ); + await manager.setupLayers(); + manager.setSuppressionCheck( () => true ); + + manager.handleCustomLayersTimeUpdate( 4.5 ); + + expect( manager.customLayerManagers.acme.handleTimeUpdate ).not.toHaveBeenCalled(); + } ); + + it( 'tolerates an add-on manager that implements none of the optional handlers', async () => { + registerLayerType( 'acme', { label: 'Acme', validator: () => true, manager: function Bare() {} } ); + const { manager } = setup( [ { id: 'a1', type: 'acme' } ] ); + await manager.setupLayers(); + expect( () => { + manager.handleCustomLayersTimeUpdate( 1 ); + manager.handleVideoResize(); + manager.handleFullscreenChange(); + } ).not.toThrow(); + } ); + } ); + + describe( 'layers that are skipped', () => { + it( 'skips a layer with no container in the page', async () => { + const { manager } = setup( [ { id: 'c', type: 'cta' } ], { skip: [ 'c' ] } ); + await manager.setupLayers(); + expect( manager.formLayerManager.setupFormLayer ).not.toHaveBeenCalled(); + } ); + + it( 'skips a type nothing registered, without throwing', async () => { + const { manager } = setup( [ { id: 'g', type: 'ghost' } ] ); + await expect( manager.setupLayers() ).resolves.toBeUndefined(); + expect( manager.formLayerManager.setupFormLayer ).not.toHaveBeenCalled(); + expect( manager.hotspotLayerManager.setupHotspotLayer ).not.toHaveBeenCalled(); + expect( manager.customLayerManagers ).toEqual( {} ); + } ); + + it( 'skips a layer its validator rejects', async () => { + window.godamPluginDependencies = { gravityforms: false }; + const { manager } = setup( [ { id: 'f', type: 'form', form_type: 'gravity' } ] ); + await manager.setupLayers(); + expect( manager.formLayerManager.setupFormLayer ).not.toHaveBeenCalled(); + } ); + + it( 'sets nothing up in preview mode', async () => { + const { manager } = setup( [ { id: 'c', type: 'cta' } ], { extra: { isPreviewEnabled: true } } ); + await manager.setupLayers(); + expect( manager.formLayerManager.setupFormLayer ).not.toHaveBeenCalled(); + } ); + } ); +} ); + +describe( 'Layer API contract: LayerValidator', () => { + beforeEach( () => { + delete window.__godamLayerRegistryStore; + jest.spyOn( console, 'warn' ).mockImplementation( () => {} ); + } ); + + afterEach( () => { + jest.restoreAllMocks(); + delete window.godamPluginDependencies; + } ); + + it.each( [ + [ 'gravity', 'gravityforms' ], + [ 'wpforms', 'wpforms' ], + [ 'everestforms', 'everestForms' ], + [ 'cf7', 'cf7' ], + [ 'jetpack', 'jetpack' ], + [ 'sureforms', 'sureforms' ], + [ 'forminator', 'forminator' ], + [ 'fluentforms', 'fluentForms' ], + [ 'ninjaforms', 'ninjaForms' ], + [ 'metform', 'metform' ], + [ 'marketo', 'marketo' ], + [ 'hubspot', 'hubspot' ], + ] )( 'runs a %s form layer only when godamPluginDependencies.%s is set', ( formType, dependency ) => { + const layer = { type: 'form', form_type: formType }; + window.godamPluginDependencies = { [ dependency ]: true }; + expect( LayerValidator.shouldProcessLayer( layer ) ).toBe( true ); + window.godamPluginDependencies = { [ dependency ]: false }; + expect( LayerValidator.shouldProcessLayer( layer ) ).toBe( false ); + } ); + + it( 'rejects a form layer whose form_type it does not know', () => { + window.godamPluginDependencies = { gravityforms: true }; + expect( LayerValidator.shouldProcessLayer( { type: 'form', form_type: 'mystery' } ) ).toBe( false ); + } ); + + it( 'runs a poll layer only when WP-Polls is active', () => { + window.godamPluginDependencies = { wpPolls: false }; + expect( LayerValidator.shouldProcessLayer( { type: 'poll' } ) ).toBe( false ); + } ); + + it.each( [ 'cta', 'hotspot' ] )( 'always runs a %s layer', ( type ) => { + window.godamPluginDependencies = {}; + expect( LayerValidator.shouldProcessLayer( { type } ) ).toBe( true ); + } ); + + // Current behaviour: an unknown type passes validation and is dropped later by dispatch. + it( 'lets a type with no validator through', () => { + expect( LayerValidator.shouldProcessLayer( { type: 'ghost' } ) ).toBe( true ); + } ); + + it( 'asks a registered validator, passing the layer and godamPluginDependencies', () => { + const deps = { acmePlugin: true }; + window.godamPluginDependencies = deps; + const validator = jest.fn( () => false ); + registerLayerType( 'acme', { label: 'Acme', validator } ); + const layer = { type: 'acme' }; + + expect( LayerValidator.shouldProcessLayer( layer ) ).toBe( false ); + expect( validator ).toHaveBeenCalledWith( layer, deps ); + } ); + + // Current behaviour: registering a core type id replaces that type's built-in check. + it( 'lets a registered validator take over a core type', () => { + window.godamPluginDependencies = { wpPolls: false }; + registerLayerType( 'poll', { label: 'Poll', validator: () => true } ); + expect( LayerValidator.shouldProcessLayer( { type: 'poll' } ) ).toBe( true ); + } ); +} ); diff --git a/assets/src/js/godam-player/utils/layer-registry.test.js b/assets/src/js/godam-player/utils/layer-registry.test.js new file mode 100644 index 0000000000..ff29e05211 --- /dev/null +++ b/assets/src/js/godam-player/utils/layer-registry.test.js @@ -0,0 +1,149 @@ +/** + * Layer API contract tests (#2291): the front-end layer registry. + * + * Add-ons (e.g. godam-for-woo) register front-end layer types through + * `window.godamLayerRegistry`, or push to `window.godamLayerRegistryQueue` when + * they load before the player. #2294 backs this API with the new registry; these + * tests are what it must keep passing. + */ + +const STORE_KEY = '__godamLayerRegistryStore'; + +const reset = () => { + delete window[ STORE_KEY ]; + delete window.godamLayerRegistry; + delete window.godamLayerRegistryQueue; +}; + +const loadRegistry = () => { + let registry; + jest.isolateModules( () => { + registry = require( './layer-registry.js' ); + } ); + return registry; +}; + +const loadInit = () => { + jest.isolateModules( () => { + require( './layer-registry-init.js' ); + } ); +}; + +const validator = () => true; + +describe( 'Layer API contract: layer registry', () => { + let warn, error; + + beforeEach( () => { + reset(); + warn = jest.spyOn( console, 'warn' ).mockImplementation( () => {} ); + error = jest.spyOn( console, 'error' ).mockImplementation( () => {} ); + } ); + + afterEach( () => { + warn.mockRestore(); + error.mockRestore(); + reset(); + } ); + + it( 'registers a type with its label, validator and manager', () => { + const registry = loadRegistry(); + class AcmeManager {} + + expect( registry.registerLayerType( 'acme', { label: 'Acme', validator, manager: AcmeManager } ) ).toBe( true ); + + expect( registry.isLayerTypeRegistered( 'acme' ) ).toBe( true ); + expect( registry.getLayerValidator( 'acme' ) ).toBe( validator ); + expect( registry.getLayerManager( 'acme' ) ).toBe( AcmeManager ); + expect( registry.getAllRegisteredLayerTypes() ).toEqual( { acme: { label: 'Acme', manager: AcmeManager } } ); + } ); + + it( 'treats the manager as optional', () => { + const registry = loadRegistry(); + registry.registerLayerType( 'acme', { label: 'Acme', validator } ); + expect( registry.getLayerManager( 'acme' ) ).toBeNull(); + expect( registry.getAllRegisteredLayerTypes() ).toEqual( { acme: { label: 'Acme' } } ); + } ); + + it.each( [ + [ 'no label', { validator } ], + [ 'no validator', { label: 'Acme' } ], + ] )( 'rejects a registration with %s', ( _, config ) => { + const registry = loadRegistry(); + expect( registry.registerLayerType( 'acme', config ) ).toBe( false ); + expect( registry.getAllRegisteredLayerTypes() ).toEqual( {} ); + } ); + + it( 'keeps the first registration and rejects a duplicate id', () => { + const registry = loadRegistry(); + const second = () => false; + registry.registerLayerType( 'acme', { label: 'Acme', validator } ); + expect( registry.registerLayerType( 'acme', { label: 'Other', validator: second } ) ).toBe( false ); + expect( registry.getLayerValidator( 'acme' ) ).toBe( validator ); + } ); + + it( 'always reports the four core types as registered, without registering them', () => { + const registry = loadRegistry(); + [ 'form', 'cta', 'poll', 'hotspot' ].forEach( ( type ) => expect( registry.isLayerTypeRegistered( type ) ).toBe( true ) ); + expect( registry.isLayerTypeRegistered( 'ad' ) ).toBe( false ); + expect( registry.isLayerTypeRegistered( 'ghost' ) ).toBe( false ); + expect( registry.getAllRegisteredLayerTypes() ).toEqual( {} ); + } ); + + it( 'lists core types plus registered types, keyed by upper-case id', () => { + const registry = loadRegistry(); + registry.registerLayerType( 'acme', { label: 'Acme', validator } ); + expect( registry.getLayerTypes() ).toEqual( { FORM: 'form', CTA: 'cta', POLL: 'poll', HOTSPOT: 'hotspot', ACME: 'acme' } ); + } ); + + it( 'calls registry hooks with ( "register", id, config )', () => { + const registry = loadRegistry(); + const hook = jest.fn(); + const config = { label: 'Acme', validator }; + registry.addLayerRegistryHook( hook ); + registry.registerLayerType( 'acme', config ); + expect( hook ).toHaveBeenCalledWith( 'register', 'acme', config ); + } ); + + it( 'shares one store between separately bundled copies of the registry', () => { + const playerCopy = loadRegistry(); + const imageCopy = loadRegistry(); + class AcmeManager {} + + imageCopy.registerLayerType( 'acme', { label: 'Acme', validator, manager: AcmeManager } ); + + expect( playerCopy.getLayerManager( 'acme' ) ).toBe( AcmeManager ); + } ); + + describe( 'window.godamLayerRegistry', () => { + it( 'exposes the registry API on window', () => { + loadInit(); + expect( Object.keys( window.godamLayerRegistry ).sort() ).toEqual( [ + 'addLayerRegistryHook', + 'getAllRegisteredLayerTypes', + 'getLayerManager', + 'getLayerTypes', + 'getLayerValidator', + 'isLayerTypeRegistered', + 'registerLayerType', + ] ); + } ); + + it( 'registers types an add-on queued before the registry loaded, then clears the queue', () => { + class AcmeManager {} + window.godamLayerRegistryQueue = [ { id: 'acme', config: { label: 'Acme', validator, manager: AcmeManager } } ]; + + loadInit(); + + expect( window.godamLayerRegistry.getLayerManager( 'acme' ) ).toBe( AcmeManager ); + expect( window.godamLayerRegistryQueue ).toBeUndefined(); + } ); + + it( 'keeps the first window API when a second bundle initializes', () => { + loadInit(); + const first = window.godamLayerRegistry; + loadInit(); + expect( window.godamLayerRegistry ).toBe( first ); + } ); + } ); +} ); diff --git a/docs/rfcs/layer-api.md b/docs/rfcs/layer-api.md new file mode 100644 index 0000000000..3dd65ca6b0 --- /dev/null +++ b/docs/rfcs/layer-api.md @@ -0,0 +1,161 @@ +# RFC: Layer API + +- **Status:** Draft, for review +- **Issue:** #2291 (part of EPIC #2290) +- **Covers:** the decisions the EPIC lists under "To decide", the public names, and what the audit of saved-layer readers found + +## Summary + +Let a plugin add a layer type to GoDAM the way it adds a block to WordPress: one `layer.json`, one PHP call, one editor call and one front-end call. Core's own layer types register through the same API. Saved data keeps its current shape, so nothing needs migrating. + +## What exists today + +A third-party layer type has to wire up five separate mechanisms. godam-for-woo is the only one that does. + +| Surface | Mechanism | +|---|---| +| "Add layer" menu entry | PHP filter `godam_video_editor_layer_options` → `window.godamVideoEditorConfig.layerOptions` | +| Settings panel | PHP filter `godam_video_editor_layer_components` + `window.godamLayerComponents` | +| Data for a new layer | `window.godamLayerCreators[ type ]` | +| Player behaviour | `window.godamLayerRegistry.registerLayerType()` or `window.godamLayerRegistryQueue` (documented in `assets/src/js/godam-player/utils/LAYER-REGISTRY-API.md`) | +| Server markup | `do_action( 'godam_player_render_layer', $layer, $instance_id )` | + +There is also a sixth, separate path: `GoDAMAPI.createLayer()` creates layers at runtime from code. They have their own `timeupdate` handling and skip hover-preview suppression. + +The contract tests added in #2291 pin all of this down. Tests marked "current behaviour" cover things this RFC proposes to change. + +## Audit: who reads saved layers + +Layers live in the attachment's `rtgodam_meta` post meta, under `layers`. Each one is a flat object: `{ id, type, name, displayTime, ...type-specific keys }`. + +### Saving + +- **Nothing sanitizes layers on save.** `rtgodam_meta` is a `register_rest_field` on `/wp/v2/media` with no schema and no sanitize callback (`class-meta-rest-fields.php`). Whatever the editor sends is stored. +- **The editor keeps layers it doesn't recognise.** It loads every layer into the store, hides unknown types in the list and timeline, and saves them back unchanged. Deactivating an add-on doesn't lose its layers. + +### Exposure + +- **REST read access is narrow.** It requires `edit_posts` or `edit_post` on the attachment. +- **Page HTML exposes almost everything.** `godam-player.php` writes every layer, minus `html` and `text`, into the player's public `data-options`. The public `/godam/v1/video-shortcode` route and the embed page return that same markup. A layer type that stored private values would leak them. + +### Readers that branch on `type` + +| Reader | Unknown type today | +|---|---| +| Player template layer loop (`godam-player.php`) | Falls through to `godam_player_render_layer`. If nothing answers, no container is printed. The whole loop is skipped in WooCommerce contexts. | +| Ad selection (`godam-player.php`, `class-ads.php` `/godam/v1/adTagURL`) | Ignored. Both read `$layer['type']` without `isset`, so a typeless layer causes warnings. | +| Image block (`godam-image/render.php`, `edit.js`, `render-image-frame.js`) | Dropped. A hard allowlist of `hotspot` and `woo`, with no filter. | +| Player JS (`layersManager.js`, `layerValidator.js`) | Passes validation by default. Without a registered manager, the container stays hidden forever and nothing logs it. | +| FontAwesome loader (`pluginLoader.js`) | Only checks `hotspot` and `woo`. | +| Analytics events (`layerActions.js`, analytics service) | Sent, then rejected. The client and the analytics service both allow only `cta`, `form`, `hotspot`, `woo` and `poll`. | +| Analytics REST proxy (`class-analytics.php` `/layer-analytics`) | Rejected with a 400 (same allowlist). | +| Analytics timeline (`useVideoLayerData.js`, `constants/layerTypes.js`) | Not shown (five fixed per-type queries). | +| Editor list, timeline, add menu, settings panel | Hidden. The settings panel falls back to the CTA editor. | +| Image editor (`mediaCapabilities.js`) | Hidden. Allowlist `[ 'hotspot', 'woo' ]`. | +| "Edited" counts (`class-video-editor.php`) | Counted. A serialized `LIKE` counts any layer. | + +### Renderers outside this plugin + +- **GoDAM Central serves its own player.** Its oEmbed pages are at `app.godam.io/web/video/…` and `/web/embed/…` (`class-embed.php`, the LifterLMS integration and the media library). +- **No code here sends `rtgodam_meta.layers` to Central.** The only layer data that leaves the site is browser analytics events (`layer_id`, `layer_type`, `layer_name`, `layer_metadata`). +- **Whether Central's player draws WordPress-authored layers can't be told from this repo.** That needs confirming with the Central team (see D2). + +## Decisions + +Each decision gives a recommendation. Where the RFC is agreed differently, the decision is updated here before #2292, #2294 and #2295 start. + +### D1. Attribute shape: keep it flat + +**Recommendation:** attributes stay top-level keys on the layer, next to `id`, `type`, `name` and `displayTime`. There's no nested `attributes` object. + +- Saved data, the player template, the analytics page, godam-for-woo's product SEO sync and the "edited" query all read flat keys today. Nesting would mean a migration and a dual-read period in all of them. +- These core keys are reserved, and a layer type can't declare them as attributes: `id`, `type`, `name`, `displayTime`, `duration`, `allow_skip`, `custom_css`, `trigger`, `watchDepth`. + +### D2. Renderers that don't know a type + +**Recommendation:** a third-party layer type renders only in the WordPress player and image block. Everything else skips it without errors or warnings. Concretely: + +- **Player and image:** print no container and log once in the console (`GoDAM: no runtime registered for layer type "acme/countdown"`). Today the container is printed and stays hidden. +- **Editor:** show the layer in the list with a "Needs an add-on that isn't active" notice, instead of hiding it. Allow deleting it. Never open it in another type's editor. +- **Central-hosted player:** confirm with the Central team whether it reads WordPress layers. If it does, it skips unknown types. This is the one open question this RFC can't settle alone. + +### D3. Sanitization and privacy + +**Recommendation:** + +- **Every attribute declares a schema `type`:** `string`, `number`, `integer`, `boolean`, `array` or `object`. A `format` is optional: `url`, `color`, `html` (run through `wp_kses_post`) or `plain` (the default for strings, run through `sanitize_text_field`). +- **Sanitize on save.** On save, each layer of a registered type has its declared attributes sanitized and undeclared keys dropped. Layers of an unregistered type are kept unchanged, because the add-on may come back and D2 keeps them visible in the editor. +- **Private attributes.** An attribute can set `"private": true` to stay out of the public `data-options`. The default is public, so current behaviour is unchanged. +- **Escaping `render_callback` output.** `render_callback` output goes through `wp_kses_post` unless the layer type opts out with `"supports": { "rawHtml": true }`. Opting out is documented as the add-on's responsibility. + +### D4. Analytics in v1 + +**Recommendation:** v1 gives third-party layer types only the baseline actions, viewed and clicked, through `ctx.api.track()`. Custom funnels come in a later version. + +- **The analytics service needs changing first.** It rejects any `layer_type` outside its allowlist, so it must accept namespaced types (`vendor/name`) before even the baseline works. Until then, `track()` from a third-party type does nothing and logs a notice once. +- **The analytics page needs a generic per-layer query.** It needs one alongside the five per-type ones, so a namespaced layer type appears on the timeline. +- **This needs the analytics team.** Track it as a dependency of #2294, not as part of it. + +### D5. Layers from `GoDAMAPI.createLayer()` + +**Recommendation:** run them on the same lifecycle as registered layer types, so hover-preview suppression, resize and fullscreen apply to them too. The public method signature stays the same. + +### D6. Front-end registry weight + +**Recommendation:** the editor registry is a `@wordpress/data` store (`godam/layers`). The front-end registry stays plain JavaScript. The player script already loads `wp-data`, but the image-layers script loads only `lodash` and `wp-i18n`, and adding `wp-data` there would pull React onto image-only pages. + +## Names + +| Thing | Name | +|---|---| +| Editor package / script handle / global | `@godam/layers` / `godam-layers` / `window.godam.layers` | +| Editor hooks and controls package | `@godam/layer-editor` / `godam-layer-editor` / `window.godam.layerEditor` | +| Front-end runtime (same package, front-end build) | `registerLayerRuntime()` on `window.godam.layers` | +| Editor registration | `registerLayerType( metadata, { edit, preview } )`, `registerLayerVariation( 'form', … )` | +| Data store | `godam/layers` | +| PHP registration | `godam_register_layer_type( $path_or_metadata, $args )`, called on a new `godam_init` action | +| PHP filter | `godam_layer_type_metadata` | +| JS filter | `godam.layers.registerLayerType` (`@wordpress/hooks`) | +| Metadata file | `layer.json` | + +New hooks use the `godam_` prefix, which most of the codebase's hooks already use. + +### `layer.json` keys (v1) + +| Key | Required | Notes | +|---|---|---| +| `apiVersion` | yes | `1` | +| `name` | yes | `vendor/name`. Core keeps `cta`, `form`, `hotspot`, `poll`, `ad`. | +| `title` | yes | Shown in the "Add layer" menu | +| `description` | no | Second line in the menu | +| `icon` | no | Dashicon name, SVG string or `file:` URL | +| `color` | no | Marker and icon colour | +| `supports` | no | `media` (`[ 'video' ]` by default), `timeline` (`true`), `duplicate` (`true`), `skip` (`false`), `rawHtml` (`false`) | +| `attributes` | no | `{ key: { type, default?, format?, private? } }` | +| `editorScript`, `viewScript`, `style`, `editorStyle` | no | Handles or `file:` paths, as in `block.json` | +| `textdomain` | no | For translating `title` and `description` | + +## Fixes the audit found outside this EPIC + +These are worth fixing whether or not the Layer API goes ahead: + +1. **Typeless layers cause warnings.** `godam-player.php` (ad selection) and `class-ads.php` read `$layer['type']` without `isset`, so a typeless or non-array layer warns on every render and on the public ad-tag route. +2. **The analytics page's "N layers" badge never shows.** `Analytics.js` reads `attachmentData.meta.rtgodam_meta`, but `rtgodam_meta` is a top-level field on `/wp/v2/media`, not part of `meta`. +3. **WooCommerce contexts skip the whole layer loop** in `godam-player.php`, including `godam_player_render_layer`. This may be intended, but it's undocumented. + +## Test coverage from #2291 + +| Area | Test | +|---|---| +| Core layer defaults, add-on menu entries and creators, media gating, unregistered saved layers | `pages/video-editor/components/SidebarLayers.test.js` | +| Settings panel selection, add-on panels, fallbacks, error boundary | `pages/video-editor/components/layers/Layer.test.js` | +| Editor globals add-ons use | `pages/video-editor/index.test.js` | +| Front-end registry, queue, shared store | `assets/src/js/godam-player/utils/layer-registry.test.js` | +| Player dispatch, add-on managers, validation | `assets/src/js/godam-player/managers/layersManager.contract.test.js` | +| Image layers (hotspot, woo, others) | `assets/src/js/godam-image-layers/render-image-frame.test.js` | +| Which saved layers the image block sends | `tests/php/ImageBlockLayerContractTest.php` | + +**Not covered:** + +- **The player template's layer loop** (`inc/templates/godam-player.php`) and **how `class-pages.php` localizes `layerOptions` / `layerComponents`.** Both need a WordPress install to render, and the PHP suite runs without one. #2295 moves the template loop into `render_callback`s, which can be unit-tested. Until then, these are checked by hand in QA. +- **The real godam-for-woo bundle.** The tests use a stand-in add-on built with the same mechanisms. #2296 runs the real add-on against the new API. diff --git a/pages/video-editor/components/SidebarLayers.test.js b/pages/video-editor/components/SidebarLayers.test.js new file mode 100644 index 0000000000..4b1cfc7ef4 --- /dev/null +++ b/pages/video-editor/components/SidebarLayers.test.js @@ -0,0 +1,326 @@ +/** + * Layer API contract tests (#2291): the "Add layer" menu and the layer list. + * + * These pin down what the editor does today, so the Layer API refactor (#2292) + * can move core layer types onto a registry and prove nothing changed. They + * cover the exact data each core layer type starts with when it is added; the + * add-on path (`godamVideoEditorConfig.layerOptions` adds a menu entry and + * `window.godamLayerCreators[ type ]` supplies the new layer's data); media-type + * gating (video needs a playhead position, images allow only some types); and + * saved layers whose type has no registration. + * + * Tests marked "current behaviour" pin something the refactor intends to change + * on purpose. Update them in the same PR that changes the behaviour. + */ + +/** + * Internal dependencies + */ +import '../../../tests/js/layer-contract-globals'; + +/** + * External dependencies + */ +import { act } from 'react'; +import { createRoot } from 'react-dom/client'; +import { Provider } from 'react-redux'; +import { configureStore } from '@reduxjs/toolkit'; + +/** + * Internal dependencies + */ +import SidebarLayers, { getDefaultLayerName } from './SidebarLayers'; + +// The real slice reads page globals at import time; only the action shapes matter here. +jest.mock( '../redux/slice/videoSlice', () => ( { + addLayer: ( payload ) => ( { type: 'addLayer', payload } ), + removeLayer: ( payload ) => ( { type: 'removeLayer', payload } ), + setCurrentLayer: ( payload ) => ( { type: 'setCurrentLayer', payload } ), + setAddLayerModalTime: ( payload ) => ( { type: 'setAddLayerModalTime', payload } ), +} ) ); + +jest.mock( '../onboarding/productGuide', () => ( { notify: jest.fn() } ) ); + +jest.mock( 'uuid', () => ( { v4: () => 'test-uuid' } ) ); + +// Plain stand-ins for the menu primitives, so menu items are ordinary buttons +// and the dropdown content is always rendered. +jest.mock( '@wordpress/components', () => { + const { createElement: h, Fragment } = require( 'react' ); + const passthrough = ( { children } ) => h( Fragment, null, children ); + const button = ( { children, onClick, disabled, id, 'data-test-id': testId } ) => + h( 'button', { type: 'button', id, onClick, disabled, 'data-test-id': testId }, children ); + return { + Button: button, + MenuItem: button, + Icon: () => null, + Tooltip: passthrough, + MenuGroup: passthrough, + NavigableMenu: passthrough, + Popover: passthrough, + DropdownMenu: () => null, + Dropdown: ( { renderToggle, renderContent } ) => + h( Fragment, null, renderToggle( { isOpen: true, onToggle: () => {} } ), renderContent( { onClose: () => {} } ) ), + }; +} ); + +const baseState = { + loading: false, + addLayerModalTime: null, + layers: [], + currentLayer: null, + videoConfig: {}, + allowedLayerTypes: '*', + mediaType: 'video', +}; + +const makeStore = ( state = {} ) => + configureStore( { + reducer: { + videoReducer: ( current = { ...baseState, ...state }, action ) => { + if ( action.type === 'addLayer' ) { + return { ...current, layers: [ ...current.layers, action.payload ] }; + } + return current; + }, + }, + middleware: ( getDefault ) => getDefault( { serializableCheck: false } ), + } ); + +describe( 'Layer API contract: SidebarLayers', () => { + let container, root, store; + + const render = ( { state, currentTime = 12 } = {} ) => { + store = makeStore( state ); + act( () => { + root.render( + + {} } onPauseVideo={ () => {} } duration={ 120 } /> + , + ); + } ); + }; + + const control = ( key ) => container.querySelector( `[data-test-id="godam-video-editor-control-add-${ key }"]` ); + const click = ( el ) => act( () => el.click() ); + const addedLayers = () => store.getState().videoReducer.layers; + const menuKeys = () => + [ ...container.querySelectorAll( '[data-test-id^="godam-video-editor-control-add-"]' ) ] + .map( ( el ) => el.dataset.testId.replace( 'godam-video-editor-control-add-', '' ) ); + + beforeEach( () => { + global.IS_REACT_ACT_ENVIRONMENT = true; + container = document.createElement( 'div' ); + document.body.appendChild( container ); + root = createRoot( container ); + window.godamLayerCreators = undefined; + } ); + + afterEach( () => { + act( () => root.unmount() ); + container.remove(); + } ); + + describe( 'core layer defaults', () => { + it( 'adds a CTA layer with these fields', () => { + render(); + click( control( 'cta' ) ); + expect( addedLayers() ).toEqual( [ { + id: 'test-uuid', + displayTime: 12, + type: 'cta', + name: 'CTA Layer', + cta_type: 'image', + cardLayout: 'card-layout--imagecover-text', + trigger: 'timestamp', + watchDepth: 50, + html: '', + link: '', + allow_skip: true, + } ] ); + } ); + + it( 'adds a Hotspot layer with these fields', () => { + render(); + click( control( 'hotspot' ) ); + expect( addedLayers() ).toEqual( [ { + id: 'test-uuid', + displayTime: 12, + type: 'hotspot', + name: 'Hotspot Layer', + duration: 5, + pauseOnHover: false, + hotspots: [], + styleType: 'pulse', + icon: '', + customIconUrl: null, + customIconId: null, + isNew: true, + } ] ); + } ); + + it( 'adds a Form layer for the chosen form plugin', () => { + render(); + // Two form plugins are active, so "Form" opens a submenu. + click( control( 'form' ) ); + click( control( 'form-wpforms' ) ); + expect( addedLayers() ).toEqual( [ { + id: 'test-uuid', + displayTime: 12, + type: 'form', + name: 'WPForms Layer', + form_type: 'wpforms', + submitted: false, + allow_skip: true, + custom_css: '', + theme: '', + } ] ); + } ); + + it( 'adds a Poll layer with these fields', () => { + render(); + click( control( 'poll' ) ); + expect( addedLayers() ).toEqual( [ { + id: 'test-uuid', + displayTime: 12, + type: 'poll', + name: 'Poll Layer', + poll_id: '', + allow_skip: true, + custom_css: '', + } ] ); + } ); + + it( 'adds an Ad layer with these fields', () => { + render(); + click( control( 'ad' ) ); + expect( addedLayers() ).toEqual( [ { + id: 'test-uuid', + displayTime: 12, + type: 'ad', + name: 'Ad Layer', + adTagUrl: '', + ad_url: '', + skippable: false, + skip_offset: 5, + } ] ); + } ); + + it( 'adds at the time requested from the timeline, not the playhead', () => { + render( { state: { addLayerModalTime: 30 } } ); + click( control( 'cta' ) ); + expect( addedLayers()[ 0 ].displayTime ).toBe( 30 ); + } ); + + it( 'disables the Ad entry when an ad server is configured', () => { + render( { state: { videoConfig: { adServer: 'ad-server' } } } ); + expect( control( 'ad' ).disabled ).toBe( true ); + } ); + } ); + + describe( 'add-on layer types', () => { + it( 'lists add-on types from layerOptions after the core types', () => { + render(); + expect( menuKeys() ).toEqual( [ + 'cta', 'hotspot', 'form', 'poll', 'ad', + 'acme', 'woo', 'acme-inactive', 'acme-no-creator', + ] ); + } ); + + it( 'asks the add-on creator for the new layer and seeds a default name', () => { + const creator = jest.fn( ( { currentTime } ) => ( { type: 'acme', displayTime: currentTime, color: 'red' } ) ); + window.godamLayerCreators = { acme: creator }; + render(); + + click( control( 'acme' ) ); + + expect( creator ).toHaveBeenCalledWith( { layers: [], currentTime: 12, type: 'acme' } ); + expect( addedLayers() ).toEqual( [ { + name: 'Acme Layer', + type: 'acme', + displayTime: 12, + color: 'red', + id: 'test-uuid', + } ] ); + } ); + + it( 'lets the creator override the name but never the id', () => { + window.godamLayerCreators = { + acme: () => ( { type: 'acme', displayTime: 12, name: 'Custom name', id: 'creator-id' } ), + }; + render(); + click( control( 'acme' ) ); + expect( addedLayers()[ 0 ] ).toMatchObject( { name: 'Custom name', id: 'test-uuid' } ); + } ); + + it( 'adds nothing when the creator returns nothing', () => { + window.godamLayerCreators = { acme: () => null }; + render(); + click( control( 'acme' ) ); + expect( addedLayers() ).toEqual( [] ); + } ); + + // Current behaviour: an option without a creator is clickable but does nothing. + it( 'adds nothing when an add-on option has no creator', () => { + render(); + click( control( 'acme-no-creator' ) ); + expect( addedLayers() ).toEqual( [] ); + } ); + + it( 'disables an add-on entry that reports isActive: false', () => { + render(); + expect( control( 'acme-inactive' ).disabled ).toBe( true ); + } ); + } ); + + describe( 'media-type gating', () => { + it( 'disables "Add layer" on video until the playhead has moved', () => { + render( { currentTime: 0 } ); + expect( container.querySelector( '#add-layer-btn' ).disabled ).toBe( true ); + } ); + + it( 'disables "Add layer" on video when a layer already sits at the playhead', () => { + render( { state: { layers: [ { id: 'a', type: 'cta', displayTime: 12 } ] } } ); + expect( container.querySelector( '#add-layer-btn' ).disabled ).toBe( true ); + } ); + + // Current behaviour: the image allow-list names the Woo add-on (mediaCapabilities.js). + it( 'offers only the allowed types on an image, with no playhead needed', () => { + render( { currentTime: 0, state: { mediaType: 'image', allowedLayerTypes: [ 'hotspot', 'woo' ] } } ); + expect( container.querySelector( '#add-layer-btn' ).disabled ).toBe( false ); + expect( menuKeys() ).toEqual( [ 'hotspot', 'woo' ] ); + } ); + } ); + + describe( 'saved layers', () => { + // Current behaviour: a layer whose type nothing registers is hidden from + // the list but kept in the editor state, so saving does not drop it. + it( 'hides a layer of an unregistered type but keeps it in state', () => { + const ghost = { id: 'ghost', type: 'ghost', displayTime: 3 }; + render( { state: { layers: [ ghost ] } } ); + expect( container.querySelectorAll( '.godam-ve-layer-row' ) ).toHaveLength( 0 ); + expect( container.textContent ).toContain( 'Layers (1)' ); + expect( addedLayers() ).toEqual( [ ghost ] ); + } ); + + it( 'lists a layer of a registered add-on type', () => { + render( { state: { layers: [ { id: 'a1', type: 'acme', displayTime: 3, name: 'Acme Layer' } ] } } ); + expect( container.querySelectorAll( '.godam-ve-layer-row' ) ).toHaveLength( 1 ); + } ); + } ); +} ); + +describe( 'Layer API contract: getDefaultLayerName', () => { + it.each( [ + [ 'cta', undefined, 'CTA Layer' ], + [ 'hotspot', undefined, 'Hotspot Layer' ], + [ 'poll', undefined, 'Poll Layer' ], + [ 'ad', undefined, 'Ad Layer' ], + [ 'form', undefined, 'Gravity Forms Layer' ], + [ 'form', 'hubspot', 'HubSpot Layer' ], + [ 'acme', undefined, 'Acme Layer' ], + [ 'ghost', undefined, '' ], + ] )( '%s / %s → "%s"', ( type, formType, expected ) => { + expect( getDefaultLayerName( type, formType ) ).toBe( expected ); + } ); +} ); diff --git a/pages/video-editor/components/layers/Layer.test.js b/pages/video-editor/components/layers/Layer.test.js new file mode 100644 index 0000000000..40f9f69bd0 --- /dev/null +++ b/pages/video-editor/components/layers/Layer.test.js @@ -0,0 +1,111 @@ +/** + * Layer API contract tests (#2291): which settings panel opens for a layer. + * + * Core types map to their own editors. An add-on type opens when PHP lists it in + * `godamVideoEditorConfig.layerComponents` and the add-on's script put the named + * component on `window.godamLayerComponents`. Tests marked "current behaviour" + * pin something #2292 intends to change on purpose. + */ + +/** + * External dependencies + */ +import { act } from 'react'; +import { createRoot } from 'react-dom/client'; + +/** + * Internal dependencies + */ +import Layer from './Layer'; + +// A function declaration, so it is hoisted along with the jest.mock() calls. +function mockEditor( name ) { + return { + __esModule: true, + default: ( props ) => require( 'react' ).createElement( 'div', { 'data-editor': name, 'data-layer-id': props.layerID } ), + }; +} + +jest.mock( './FormLayer', () => mockEditor( 'form' ) ); +jest.mock( './CTALayer', () => mockEditor( 'cta' ) ); +jest.mock( './HotspotLayer', () => mockEditor( 'hotspot' ) ); +jest.mock( './AdsLayer', () => mockEditor( 'ad' ) ); +jest.mock( './PollLayer', () => mockEditor( 'poll' ) ); + +describe( 'Layer API contract: Layer editor dispatch', () => { + let container, root; + + const render = ( layer, props = {} ) => { + act( () => { + root.render( {} ) } duration={ 90 } /> ); + } ); + }; + const editor = () => container.querySelector( '[data-editor]' )?.dataset.editor; + + beforeEach( () => { + global.IS_REACT_ACT_ENVIRONMENT = true; + container = document.createElement( 'div' ); + document.body.appendChild( container ); + root = createRoot( container ); + window.godamVideoEditorConfig = { layerComponents: {} }; + window.godamLayerComponents = {}; + } ); + + afterEach( () => { + act( () => root.unmount() ); + container.remove(); + } ); + + it.each( [ 'form', 'cta', 'hotspot', 'ad', 'poll' ] )( 'opens the core %s editor', ( type ) => { + render( { id: 'l1', type } ); + expect( editor() ).toBe( type ); + expect( container.querySelector( '[data-layer-id]' ).dataset.layerId ).toBe( 'l1' ); + } ); + + it( 'opens an add-on editor and passes it layerID, goBack and duration', () => { + const AcmeLayer = jest.fn( () =>
); + const goBack = jest.fn(); + window.godamVideoEditorConfig.layerComponents = { acme: 'AcmeLayer' }; + window.godamLayerComponents = { AcmeLayer }; + + render( { id: 'l2', type: 'acme' }, { goBack } ); + + expect( editor() ).toBe( 'acme' ); + expect( AcmeLayer.mock.calls[ 0 ][ 0 ] ).toEqual( { layerID: 'l2', goBack, duration: 90 } ); + } ); + + it( 'lets an add-on replace a core editor by listing the same type', () => { + window.godamVideoEditorConfig.layerComponents = { cta: 'BetterCta' }; + window.godamLayerComponents = { BetterCta: () =>
}; + render( { id: 'l3', type: 'cta' } ); + expect( editor() ).toBe( 'better-cta' ); + } ); + + // Current behaviour: #2292 replaces this fallback with a "needs an add-on" notice. + it( 'falls back to the CTA editor when PHP lists a type whose component never loaded', () => { + window.godamVideoEditorConfig.layerComponents = { acme: 'AcmeLayer' }; + render( { id: 'l4', type: 'acme' } ); + expect( editor() ).toBe( 'cta' ); + } ); + + // Current behaviour: #2292 replaces this fallback with a "needs an add-on" notice. + it( 'falls back to the CTA editor for an unregistered type', () => { + render( { id: 'l5', type: 'ghost' } ); + expect( editor() ).toBe( 'cta' ); + } ); + + it( 'shows the error notice, not a blank editor, when an add-on editor throws', () => { + const consoleError = jest.spyOn( console, 'error' ).mockImplementation( () => {} ); + window.godamVideoEditorConfig.layerComponents = { acme: 'AcmeLayer' }; + window.godamLayerComponents = { + AcmeLayer: () => { + throw new Error( 'boom' ); + }, + }; + + render( { id: 'l6', type: 'acme' } ); + + expect( container.querySelector( '.godam-layer-error[role="alert"]' ) ).not.toBeNull(); + consoleError.mockRestore(); + } ); +} ); diff --git a/pages/video-editor/index.test.js b/pages/video-editor/index.test.js new file mode 100644 index 0000000000..003b3b6197 --- /dev/null +++ b/pages/video-editor/index.test.js @@ -0,0 +1,72 @@ +/** + * Layer API contract tests (#2291): what the video editor exposes to add-ons. + * + * Add-on layer editors (e.g. godam-for-woo) are built separately and reach the + * editor's shared controls, actions and helpers through these `window` globals. + * #2296 turns them into deprecated shims; until then their names must not change. + */ + +jest.mock( 'react-dom', () => ( { createRoot: () => ( { render: () => {} } ) } ) ); +jest.mock( '@posthog/react', () => ( { PostHogProvider: ( { children } ) => children } ) ); +jest.mock( '../utils/posthog', () => ( {} ) ); +jest.mock( './redux/store', () => ( {} ) ); +jest.mock( './App', () => () => null ); +jest.mock( './redux/slice/videoSlice', () => ( { updateLayerField: jest.fn() } ) ); +jest.mock( './utils/time', () => ( { formatClock: jest.fn(), parseClock: jest.fn() } ) ); + +// A function declaration, so it is hoisted along with the jest.mock() calls. +function mockComponent() { + return { __esModule: true, default: function Stub() {} }; +} +jest.mock( './components/LayerControls', () => mockComponent() ); +jest.mock( './components/layers/LayersHeader', () => mockComponent() ); +jest.mock( './components/hotspot/FontAwesomeIconPicker', () => mockComponent() ); +jest.mock( './components/shared/color-picker/ColorPickerButton.jsx', () => mockComponent() ); +jest.mock( './components/controls', () => ( { + VeSection: function VeSection() {}, + VeTextInput: function VeTextInput() {}, + VeSegmented: function VeSegmented() {}, + VeColorList: function VeColorList() {}, + VeRadioGroup: function VeRadioGroup() {}, +} ) ); + +describe( 'Layer API contract: editor globals for add-ons', () => { + beforeAll( () => { + // An add-on that loaded first and put its own entries on the same globals. + window.godamVideoEditorComponents = { AddonControl: 'kept' }; + window.godamVideoEditorActions = { addonAction: 'kept' }; + window.godamVideoEditorUtils = { addonUtil: 'kept' }; + require( './index' ); + } ); + + it( 'exposes the shared layer controls on window.godamVideoEditorComponents', () => { + const components = window.godamVideoEditorComponents; + [ + 'LayerControls', + 'LayersHeader', + 'VeSection', + 'VeTextInput', + 'VeSegmented', + 'VeColorList', + 'VeRadioGroup', + 'FontAwesomeIconPicker', + 'ColorPickerButton', + ].forEach( ( name ) => expect( typeof components[ name ] ).toBe( 'function' ) ); + } ); + + it( 'exposes the real updateLayerField action on window.godamVideoEditorActions', () => { + expect( window.godamVideoEditorActions.updateLayerField ).toBe( require( './redux/slice/videoSlice' ).updateLayerField ); + } ); + + it( 'exposes formatClock and parseClock on window.godamVideoEditorUtils', () => { + const time = require( './utils/time' ); + expect( window.godamVideoEditorUtils.formatClock ).toBe( time.formatClock ); + expect( window.godamVideoEditorUtils.parseClock ).toBe( time.parseClock ); + } ); + + it( 'keeps entries an add-on already put on those globals', () => { + expect( window.godamVideoEditorComponents.AddonControl ).toBe( 'kept' ); + expect( window.godamVideoEditorActions.addonAction ).toBe( 'kept' ); + expect( window.godamVideoEditorUtils.addonUtil ).toBe( 'kept' ); + } ); +} ); diff --git a/tests/js/layer-contract-globals.js b/tests/js/layer-contract-globals.js new file mode 100644 index 0000000000..031e83a168 --- /dev/null +++ b/tests/js/layer-contract-globals.js @@ -0,0 +1,37 @@ +/** + * Page globals for the Layer API contract tests (#2291). + * + * `SidebarLayers.js` reads plugin availability and add-on layer options from + * `window` when the module is first evaluated, so these must be set before it + * is imported. Import this file first in a test, ahead of the module under + * test. It lives under /tests so it stays out of the release package. + * + * `acme` stands in for any third-party add-on layer. `woo` mirrors how the + * godam-for-woo add-on registers its product hotspot layer today. + */ + +window.videoData = { + ...( window.videoData || {} ), + gfActive: true, + wpformsActive: true, +}; + +window.easydamMediaLibrary = { + ...( window.easydamMediaLibrary || {} ), + isPollPluginActive: true, +}; + +window.godamVideoEditorConfig = { + ...( window.godamVideoEditorConfig || {} ), + // What `godam_video_editor_layer_options` localizes. + layerOptions: [ + { type: 'acme', title: 'Acme', layerText: 'Acme', iconUrl: 'acme.svg' }, + { type: 'woo', title: 'Product Hotspot', layerText: 'Product Hotspot', iconUrl: 'woo.svg' }, + { type: 'acme-inactive', title: 'Acme Inactive', layerText: 'Acme Inactive', isActive: false, tooltipMessage: 'Acme plugin is not active' }, + { type: 'acme-no-creator', title: 'Acme No Creator', layerText: 'Acme No Creator' }, + ], + // What `godam_video_editor_layer_components` localizes. + layerComponents: { + acme: 'AcmeLayer', + }, +}; diff --git a/tests/php/ImageBlockLayerContractTest.php b/tests/php/ImageBlockLayerContractTest.php new file mode 100644 index 0000000000..7cac5cb371 --- /dev/null +++ b/tests/php/ImageBlockLayerContractTest.php @@ -0,0 +1,251 @@ + array(), + 'enqueued' => array(), + 'inline' => array(), + ); + $GLOBALS['rtgodam_stub'] = array(); + } + + /** + * Render the block for an attachment with these saved layers. + * + * @param array $layers Saved `rtgodam_meta['layers']`. + * @param array $attributes Extra block attributes. + * @return string Rendered HTML. + */ + private function render( array $layers, array $attributes = array() ): string { + $GLOBALS['rtgodam_stub']['post_meta_by_id'][ self::ATTACHMENT_ID ] = array( + 'rtgodam_meta' => array( 'layers' => $layers ), + ); + + $attributes = array_merge( + array( + 'id' => self::ATTACHMENT_ID, + 'url' => 'https://example.com/image.jpg', + 'alt' => 'An image', + 'width' => 800, + 'height' => 600, + ), + $attributes + ); + + ob_start(); + // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found -- render.php reads $attributes from this scope. + ( static function ( $attributes ) { + require dirname( __DIR__, 2 ) . '/assets/src/blocks/godam-image/render.php'; + } )( $attributes ); + return (string) ob_get_clean(); + } + + /** + * Layers the front end receives in `data-godam-image-layers`, or null when the attribute is absent. + * + * @param string $html Rendered HTML. + * @return array|null + */ + private function sent_layers( string $html ): ?array { + if ( ! preg_match( '/data-godam-image-layers="([^"]*)"/', $html, $match ) ) { + return null; + } + return json_decode( html_entity_decode( $match[1], ENT_QUOTES, 'UTF-8' ), true ); + } + + /** + * Hotspot layers with hotspots and woo layers with product hotspots are sent, in saved order. + */ + public function test_sends_hotspot_and_woo_layers_in_saved_order(): void { + $hotspot = array( + 'id' => 'h1', + 'type' => 'hotspot', + 'hotspots' => array( array( 'id' => 's1' ) ), + ); + $woo = array( + 'id' => 'w1', + 'type' => 'woo', + 'productHotspots' => array( array( 'productId' => 7 ) ), + ); + + $this->assertSame( array( $woo, $hotspot ), $this->sent_layers( $this->render( array( $woo, $hotspot ) ) ) ); + } + + /** + * Current behaviour: any other type is dropped on the server, even when an add-on handles it in JS. + */ + public function test_drops_every_other_layer_type(): void { + $keep = array( + 'id' => 'h1', + 'type' => 'hotspot', + 'hotspots' => array( array( 'id' => 's1' ) ), + ); + + $sent = $this->sent_layers( + $this->render( + array( + array( + 'id' => 'c1', + 'type' => 'cta', + ), + array( + 'id' => 'a1', + 'type' => 'acme', + 'items' => array( 1 ), + ), + $keep, + ) + ) + ); + + $this->assertSame( array( $keep ), $sent ); + } + + /** + * Empty hotspot and woo layers, untyped layers and non-array entries are dropped. + */ + public function test_drops_empty_and_malformed_layers(): void { + $html = $this->render( + array( + array( + 'id' => 'h-empty', + 'type' => 'hotspot', + 'hotspots' => array(), + ), + array( + 'id' => 'w-empty', + 'type' => 'woo', + 'productHotspots' => array(), + ), + array( 'id' => 'no-type' ), + 'not-a-layer', + ) + ); + + $this->assertNull( $this->sent_layers( $html ) ); + $this->assertStringNotContainsString( 'godam-image-layer"', $html ); + } + + /** + * With layers to draw, the overlay is printed and both front-end scripts load. + */ + public function test_prints_overlay_and_loads_scripts_when_layers_exist(): void { + $html = $this->render( + array( + array( + 'id' => 'h1', + 'type' => 'hotspot', + 'hotspots' => array( array( 'id' => 's1' ) ), + ), + ) + ); + + $this->assertMatchesRegularExpression( '/id="layer-img_[0-9a-f]{16}-all" class="easydam-layer hotspot-layer godam-image-layer"/', $html ); + $this->assertStringContainsString( 'data-id="42"', $html ); + $this->assertStringContainsString( 'data-block-source="godam-image"', $html ); + $this->assertSame( array( 'godam-layer-analytics-script', 'godam-image-layers-frontend' ), $GLOBALS['rtgodam_scripts']['enqueued'] ); + } + + /** + * With nothing to draw, no layer data, overlay or scripts. + */ + public function test_loads_nothing_when_no_layer_survives(): void { + $html = $this->render( + array( + array( + 'id' => 'c1', + 'type' => 'cta', + ), + ) + ); + + $this->assertStringNotContainsString( 'data-instance-id', $html ); + $this->assertSame( array(), $GLOBALS['rtgodam_scripts']['enqueued'] ); + } + + /** + * Add-ons add their front-end script as a dependency through this filter. + */ + public function test_add_ons_can_add_script_dependencies(): void { + $seen = null; + add_filter( + 'godam_image_layers_frontend_dependencies', + static function ( $deps ) use ( &$seen ) { + $seen = $deps; + $deps[] = 'acme-layer-frontend'; + return $deps; + } + ); + + $this->render( + array( + array( + 'id' => 'w1', + 'type' => 'woo', + 'productHotspots' => array( array( 'productId' => 7 ) ), + ), + ) + ); + + $this->assertIsArray( $seen ); + } + + /** + * Turning the block's layer toggle off sends no layers. + */ + public function test_sends_no_layers_when_the_block_hides_them(): void { + $html = $this->render( + array( + array( + 'id' => 'h1', + 'type' => 'hotspot', + 'hotspots' => array( array( 'id' => 's1' ) ), + ), + ), + array( 'showImageLayers' => false ) + ); + + $this->assertNull( $this->sent_layers( $html ) ); + } +} diff --git a/tests/stubs/block-render-functions.php b/tests/stubs/block-render-functions.php new file mode 100644 index 0000000000..a769f44920 --- /dev/null +++ b/tests/stubs/block-render-functions.php @@ -0,0 +1,30 @@ + Date: Tue, 3 Nov 2026 15:50:59 +0530 Subject: [PATCH 02/20] docs(layers): keep GoDAM Central out of the Layer API RFC The Layer API EPIC covers the plugin only. Central adopts the API from the plugin once it lands, so drop the open question about Central's player and say so in the RFC's scope. Refs #2291 Co-Authored-By: Claude Opus 5.5 --- docs/rfcs/layer-api.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/docs/rfcs/layer-api.md b/docs/rfcs/layer-api.md index 3dd65ca6b0..8dff30bb9f 100644 --- a/docs/rfcs/layer-api.md +++ b/docs/rfcs/layer-api.md @@ -3,6 +3,7 @@ - **Status:** Draft, for review - **Issue:** #2291 (part of EPIC #2290) - **Covers:** the decisions the EPIC lists under "To decide", the public names, and what the audit of saved-layer readers found +- **Scope:** the GoDAM plugin only. GoDAM Central adopts the API after it lands here. ## Summary @@ -54,11 +55,9 @@ Layers live in the attachment's `rtgodam_meta` post meta, under `layers`. Each o | Image editor (`mediaCapabilities.js`) | Hidden. Allowlist `[ 'hotspot', 'woo' ]`. | | "Edited" counts (`class-video-editor.php`) | Counted. A serialized `LIKE` counts any layer. | -### Renderers outside this plugin +### Out of scope: GoDAM Central -- **GoDAM Central serves its own player.** Its oEmbed pages are at `app.godam.io/web/video/…` and `/web/embed/…` (`class-embed.php`, the LifterLMS integration and the media library). -- **No code here sends `rtgodam_meta.layers` to Central.** The only layer data that leaves the site is browser analytics events (`layer_id`, `layer_type`, `layer_name`, `layer_metadata`). -- **Whether Central's player draws WordPress-authored layers can't be told from this repo.** That needs confirming with the Central team (see D2). +**This EPIC covers the plugin only.** GoDAM Central's own player and layer handling are out of scope: Central will adopt the Layer API from the plugin once it's done here. Nothing in this RFC waits on Central. No code in the plugin sends `rtgodam_meta.layers` to Central. The only layer data that leaves the site is browser analytics events (see D4). ## Decisions @@ -77,7 +76,6 @@ Each decision gives a recommendation. Where the RFC is agreed differently, the d - **Player and image:** print no container and log once in the console (`GoDAM: no runtime registered for layer type "acme/countdown"`). Today the container is printed and stays hidden. - **Editor:** show the layer in the list with a "Needs an add-on that isn't active" notice, instead of hiding it. Allow deleting it. Never open it in another type's editor. -- **Central-hosted player:** confirm with the Central team whether it reads WordPress layers. If it does, it skips unknown types. This is the one open question this RFC can't settle alone. ### D3. Sanitization and privacy From 144b51bfab23de6d36d268605d855c328fc430e5 Mon Sep 17 00:00:00 2001 From: KMchaudhary Date: Tue, 3 Nov 2026 16:03:54 +0530 Subject: [PATCH 03/20] ci: run unit tests on PRs into the Layer API base branch Every Layer API PR (#2290) targets feature/layer-api, which neither the JS nor the PHP unit-test workflow listed, so those PRs got no unit tests. Remove the entries once feature/layer-api is merged. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/js_unit_tests_on_pull_request.yml | 2 ++ .github/workflows/php_unit_tests_on_pull_request.yml | 2 ++ 2 files changed, 4 insertions(+) diff --git a/.github/workflows/js_unit_tests_on_pull_request.yml b/.github/workflows/js_unit_tests_on_pull_request.yml index 3bd9de5bc0..f1c7a05921 100644 --- a/.github/workflows/js_unit_tests_on_pull_request.yml +++ b/.github/workflows/js_unit_tests_on_pull_request.yml @@ -4,6 +4,8 @@ on: - develop - main - 'feat/**' + # Base branch for the Layer API EPIC (#2290); remove once it is merged. + - feature/layer-api name: JS Unit Tests diff --git a/.github/workflows/php_unit_tests_on_pull_request.yml b/.github/workflows/php_unit_tests_on_pull_request.yml index 3e568f8b42..92710126f0 100644 --- a/.github/workflows/php_unit_tests_on_pull_request.yml +++ b/.github/workflows/php_unit_tests_on_pull_request.yml @@ -3,6 +3,8 @@ on: branches: - develop - main + # Base branch for the Layer API EPIC (#2290); remove once it is merged. + - feature/layer-api name: PHP Unit Tests From 9b1fd2de36d6ca47de9c245ff1c0edb76c83b72f Mon Sep 17 00:00:00 2001 From: KMchaudhary Date: Tue, 3 Nov 2026 16:15:31 +0530 Subject: [PATCH 04/20] docs(layers): mark the Layer API RFC accepted Accepted as written. D1 now separates the keys GoDAM manages (id, type, name, displayTime) from shared keys a layer type may give its own default (duration, allow_skip, custom_css, trigger, watchDepth), which core types already rely on. Refs #2291 Co-Authored-By: Claude Opus 5.5 (cherry picked from commit afa0664ab347e6d2cb685727c14e605e6386794c) --- docs/rfcs/layer-api.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/rfcs/layer-api.md b/docs/rfcs/layer-api.md index 8dff30bb9f..e28b0336ef 100644 --- a/docs/rfcs/layer-api.md +++ b/docs/rfcs/layer-api.md @@ -1,6 +1,6 @@ # RFC: Layer API -- **Status:** Draft, for review +- **Status:** Accepted (2026-11-03) - **Issue:** #2291 (part of EPIC #2290) - **Covers:** the decisions the EPIC lists under "To decide", the public names, and what the audit of saved-layer readers found - **Scope:** the GoDAM plugin only. GoDAM Central adopts the API after it lands here. @@ -68,7 +68,8 @@ Each decision gives a recommendation. Where the RFC is agreed differently, the d **Recommendation:** attributes stay top-level keys on the layer, next to `id`, `type`, `name` and `displayTime`. There's no nested `attributes` object. - Saved data, the player template, the analytics page, godam-for-woo's product SEO sync and the "edited" query all read flat keys today. Nesting would mean a migration and a dual-read period in all of them. -- These core keys are reserved, and a layer type can't declare them as attributes: `id`, `type`, `name`, `displayTime`, `duration`, `allow_skip`, `custom_css`, `trigger`, `watchDepth`. +- **Core keys:** `id`, `type`, `name` and `displayTime` are managed by GoDAM. A layer type can't declare them. +- **Shared keys:** `duration`, `allow_skip`, `custom_css`, `trigger` and `watchDepth` have a schema GoDAM owns. A layer type may give one of them its own `default` (for example Hotspot's `duration: 5`), but can't change its `type` or `format`. ### D2. Renderers that don't know a type From c0df561a6e370a1258a84695b8013aa1b5cb1d88 Mon Sep 17 00:00:00 2001 From: KMchaudhary Date: Tue, 3 Nov 2026 16:53:41 +0530 Subject: [PATCH 05/20] feat(layers): add the Layer API editor registry Add a layer type registry the editor and add-ons share (#2292): - `godam-layers` script (`window.godam.layers`, `@godam/layers`): a `godam/layers` wp-data store with registerLayerType(), unregisterLayerType() and the `godam.layers.registerLayerType` filter. - Core layer types (CTA, Hotspot, Form, Poll, Ad) register through it, with metadata in assets/src/layers//layer.json. Form plugins are variations of the Form type; Form's save check is its validate(). - The add menu, settings panel, layer list, header, timeline, save validation and image gating read the registry. Removes utils/layerTypes.js and the allowedLayerTypes allowlist. - Add-on types from the old hooks (godam_video_editor_layer_options and friends) are bridged into the registry, so godam-for-woo is unchanged. - `window.godam.layerEditor` (`godam-layer-editor` handle) gives add-on panels useLayer() / useLayerAttributes() and the shared controls. - A saved layer whose type isn't registered stays in the list with a warning and opens a "needs an add-on" notice instead of the CTA editor (RFC D2). Timeline chips for Marketo and HubSpot form layers now name the form plugin; they showed "Gravity Forms" before. Refs #2292 Co-Authored-By: Claude Opus 5.5 --- .eslintrc | 4 + assets/src/js/godam-layers/constants.js | 38 ++ assets/src/js/godam-layers/index.js | 65 +++ assets/src/js/godam-layers/registration.js | 156 ++++++ .../src/js/godam-layers/registration.test.js | 193 +++++++ assets/src/js/godam-layers/store.js | 57 ++ assets/src/js/godam-layers/utils.js | 84 +++ assets/src/layers/ad/layer.json | 17 + assets/src/layers/cta/layer.json | 21 + assets/src/layers/form/layer.json | 19 + assets/src/layers/hotspot/layer.json | 21 + assets/src/layers/poll/layer.json | 17 + inc/classes/class-pages.php | 42 +- jest.config.js | 2 + package-lock.json | 2 +- package.json | 1 + pages/video-editor/VideoEditor.js | 24 +- pages/video-editor/_layers.scss | 14 + .../video-editor/components/SidebarLayers.js | 495 +++++------------- .../components/SidebarLayers.test.js | 42 +- pages/video-editor/components/layers/Layer.js | 99 ++-- .../components/layers/Layer.test.js | 59 ++- .../components/layers/LayersHeader.js | 11 +- .../layers/UnregisteredLayerNotice.js | 39 ++ .../components/timeline/Timeline.js | 63 +-- .../components/timeline/Timeline.test.js | 114 ++++ .../video-editor/config/mediaCapabilities.js | 27 +- pages/video-editor/index.js | 26 + pages/video-editor/index.test.js | 15 + pages/video-editor/layers/core/ad.js | 27 + pages/video-editor/layers/core/cta.js | 20 + pages/video-editor/layers/core/form.js | 99 ++++ pages/video-editor/layers/core/hotspot.js | 20 + pages/video-editor/layers/core/index.js | 28 + pages/video-editor/layers/core/poll.js | 25 + pages/video-editor/layers/hooks.js | 64 +++ pages/video-editor/layers/index.js | 16 + pages/video-editor/layers/layers.test.js | 247 +++++++++ pages/video-editor/layers/legacy.js | 81 +++ pages/video-editor/redux/slice/videoSlice.js | 13 +- pages/video-editor/utils/layerTypes.js | 96 ---- webpack.config.js | 11 + 42 files changed, 1875 insertions(+), 639 deletions(-) create mode 100644 assets/src/js/godam-layers/constants.js create mode 100644 assets/src/js/godam-layers/index.js create mode 100644 assets/src/js/godam-layers/registration.js create mode 100644 assets/src/js/godam-layers/registration.test.js create mode 100644 assets/src/js/godam-layers/store.js create mode 100644 assets/src/js/godam-layers/utils.js create mode 100644 assets/src/layers/ad/layer.json create mode 100644 assets/src/layers/cta/layer.json create mode 100644 assets/src/layers/form/layer.json create mode 100644 assets/src/layers/hotspot/layer.json create mode 100644 assets/src/layers/poll/layer.json create mode 100644 pages/video-editor/components/layers/UnregisteredLayerNotice.js create mode 100644 pages/video-editor/components/timeline/Timeline.test.js create mode 100644 pages/video-editor/layers/core/ad.js create mode 100644 pages/video-editor/layers/core/cta.js create mode 100644 pages/video-editor/layers/core/form.js create mode 100644 pages/video-editor/layers/core/hotspot.js create mode 100644 pages/video-editor/layers/core/index.js create mode 100644 pages/video-editor/layers/core/poll.js create mode 100644 pages/video-editor/layers/hooks.js create mode 100644 pages/video-editor/layers/index.js create mode 100644 pages/video-editor/layers/layers.test.js create mode 100644 pages/video-editor/layers/legacy.js delete mode 100644 pages/video-editor/utils/layerTypes.js diff --git a/.eslintrc b/.eslintrc index 428a0e1c8b..d610c35ada 100755 --- a/.eslintrc +++ b/.eslintrc @@ -8,6 +8,10 @@ "env": { "browser": true }, + "settings": { + // Provided at runtime by the `godam-layers` script (a webpack external). + "import/core-modules": [ "@godam/layers" ] + }, "rules": { "jsdoc/check-indentation": "error", "@wordpress/dependency-group": "error" diff --git a/assets/src/js/godam-layers/constants.js b/assets/src/js/godam-layers/constants.js new file mode 100644 index 0000000000..e2050b2efd --- /dev/null +++ b/assets/src/js/godam-layers/constants.js @@ -0,0 +1,38 @@ +/** + * Layer API constants (RFC: docs/rfcs/layer-api.md). + */ + +/** + * Name of the `@wordpress/data` store that holds registered layer types. + */ +export const STORE_NAME = 'godam/layers'; + +/** + * Layer types GoDAM ships. They keep their historic, un-namespaced names; every + * other layer type must be namespaced (`vendor/name`). + */ +export const CORE_LAYER_TYPES = [ 'cta', 'hotspot', 'form', 'poll', 'ad' ]; + +/** + * Keys GoDAM manages on every layer. A layer type can't declare them. + */ +export const MANAGED_KEYS = [ 'id', 'type', 'name', 'displayTime' ]; + +/** + * Keys whose schema GoDAM owns. A layer type may give one its own `default`, + * but can't change its `type` or `format`. + */ +export const SHARED_KEYS = [ 'duration', 'allow_skip', 'custom_css', 'trigger', 'watchDepth' ]; + +/** + * Default `supports` for a layer type. + */ +export const DEFAULT_SUPPORTS = { + media: [ 'video' ], + timeline: true, + duplicate: true, + skip: false, + rawHtml: false, +}; + +export const NAME_PATTERN = /^[a-z0-9-]+\/[a-z0-9-]+$/; diff --git a/assets/src/js/godam-layers/index.js b/assets/src/js/godam-layers/index.js new file mode 100644 index 0000000000..7811cb5770 --- /dev/null +++ b/assets/src/js/godam-layers/index.js @@ -0,0 +1,65 @@ +/** + * GoDAM Layer API: the layer type registry (#2292). + * + * Built as the `godam-layers` script and exposed as `window.godam.layers`. + * GoDAM's own bundles import it as `@godam/layers` (a webpack external), and + * add-ons do the same with their script depending on `godam-layers`. + */ + +/** + * Internal dependencies + */ +import { store } from './store'; +import { + registerLayerType, + unregisterLayerType, + getLayerType, + getLayerTypes, + __unstableRegisterLegacyLayerType, +} from './registration'; +import { + getDefaultAttributes, + getLayerVariation, + getDefaultVariation, + isVariationAvailable, + getAvailability, + supportsMedia, +} from './utils'; +import { CORE_LAYER_TYPES, STORE_NAME } from './constants'; + +export { + store, + STORE_NAME, + CORE_LAYER_TYPES, + registerLayerType, + unregisterLayerType, + getLayerType, + getLayerTypes, + getDefaultAttributes, + getLayerVariation, + getDefaultVariation, + isVariationAvailable, + getAvailability, + supportsMedia, + __unstableRegisterLegacyLayerType, +}; + +if ( typeof window !== 'undefined' ) { + window.godam = window.godam || {}; + window.godam.layers = { + store, + STORE_NAME, + CORE_LAYER_TYPES, + registerLayerType, + unregisterLayerType, + getLayerType, + getLayerTypes, + getDefaultAttributes, + getLayerVariation, + getDefaultVariation, + isVariationAvailable, + getAvailability, + supportsMedia, + __unstableRegisterLegacyLayerType, + }; +} diff --git a/assets/src/js/godam-layers/registration.js b/assets/src/js/godam-layers/registration.js new file mode 100644 index 0000000000..e6a573fbd1 --- /dev/null +++ b/assets/src/js/godam-layers/registration.js @@ -0,0 +1,156 @@ +/** + * Layer type registration (RFC: docs/rfcs/layer-api.md). + * + * `registerLayerType( metadata, settings )` mirrors `registerBlockType()`: + * `metadata` is the contents of a `layer.json`, `settings` adds what JSON + * can't hold (React components, callbacks, translated strings). + */ + +/** + * WordPress dependencies + */ +import { dispatch, select } from '@wordpress/data'; +import { applyFilters } from '@wordpress/hooks'; + +/** + * Internal dependencies + */ +import { store } from './store'; +import { CORE_LAYER_TYPES, DEFAULT_SUPPORTS, MANAGED_KEYS, NAME_PATTERN, SHARED_KEYS } from './constants'; + +/* eslint-disable no-console -- registration problems are reported to the add-on developer. */ + +const isUrl = ( value ) => typeof value === 'string' && /^(https?:|\/|data:)/.test( value ); + +/** + * Drop attribute declarations a layer type isn't allowed to make. + * + * @param {string} name Layer type name, for messages. + * @param {Object} attributes Declared attributes. + * @return {Object} Allowed attributes. + */ +function sanitizeAttributes( name, attributes = {} ) { + const allowed = {}; + Object.entries( attributes ).forEach( ( [ key, schema ] ) => { + if ( MANAGED_KEYS.includes( key ) ) { + console.error( `GoDAM: layer type "${ name }" can't declare the "${ key }" attribute; GoDAM manages it.` ); + return; + } + if ( SHARED_KEYS.includes( key ) ) { + // Shared keys keep GoDAM's schema; only the default is the layer type's. + allowed[ key ] = 'default' in ( schema || {} ) ? { default: schema.default } : {}; + return; + } + allowed[ key ] = schema || {}; + } ); + return allowed; +} + +/** + * Fill in defaults so every registered layer type has the same shape. + * + * @param {Object} layerType Merged metadata and settings. + * @return {Object} Normalized layer type. + */ +function normalizeLayerType( layerType ) { + const { icon, iconUrl, supports, attributes, variations, ...rest } = layerType; + return { + apiVersion: 1, + description: '', + ...rest, + label: rest.label || rest.title, + icon: isUrl( icon ) ? undefined : icon, + iconUrl: iconUrl || ( isUrl( icon ) ? icon : undefined ), + supports: { ...DEFAULT_SUPPORTS, ...( supports || {} ) }, + attributes: sanitizeAttributes( rest.name, attributes ), + variations: Array.isArray( variations ) ? variations : [], + }; +} + +/** + * Register a layer type. + * + * @param {Object|string} metadata Contents of the type's `layer.json`, or just its name. + * @param {Object} settings Editor settings: `edit`, `icon`, `getAvailability`, `validate`, `variations`, translated `title`/`description`, and so on. + * @return {Object|undefined} The registered layer type, or undefined when registration failed. + */ +export function registerLayerType( metadata, settings = {} ) { + const merged = { ...( typeof metadata === 'string' ? { name: metadata } : metadata ), ...settings }; + const { name } = merged; + + if ( typeof name !== 'string' || ( ! NAME_PATTERN.test( name ) && ! CORE_LAYER_TYPES.includes( name ) ) ) { + console.error( 'GoDAM: layer type names must be namespaced, for example "acme/countdown".' ); + return undefined; + } + + return addLayerType( merged ); +} + +/** + * Register a layer type that came through the pre-Layer-API add-on hooks + * (`godam_video_editor_layer_options` and friends). Those types have + * un-namespaced names, so they skip the name check. Not part of the public API. + * + * @param {Object} settings Layer type settings, including `name`. + * @return {Object|undefined} The registered layer type. + */ +export function __unstableRegisterLegacyLayerType( settings ) { + if ( typeof settings?.name !== 'string' || ! settings.name ) { + return undefined; + } + return addLayerType( settings ); +} + +function addLayerType( merged ) { + const { name } = merged; + + if ( select( store ).getLayerType( name ) ) { + console.error( `GoDAM: layer type "${ name }" is already registered.` ); + return undefined; + } + + /** + * Filters a layer type's settings before it is registered. + * + * @param {Object} settings Layer type settings. + * @param {string} name Layer type name. + */ + const layerType = normalizeLayerType( { ...applyFilters( 'godam.layers.registerLayerType', merged, name ), name } ); + + if ( typeof layerType.title !== 'string' || ! layerType.title ) { + console.error( `GoDAM: layer type "${ name }" needs a title.` ); + return undefined; + } + + dispatch( store ).addLayerType( layerType ); + return layerType; +} + +/** + * Unregister a layer type. + * + * @param {string} name Layer type name. + * @return {Object|undefined} The removed layer type. + */ +export function unregisterLayerType( name ) { + const layerType = select( store ).getLayerType( name ); + if ( ! layerType ) { + console.error( `GoDAM: layer type "${ name }" is not registered.` ); + return undefined; + } + dispatch( store ).removeLayerType( name ); + return layerType; +} + +/* eslint-enable no-console */ + +/** + * @param {string} name Layer type name. + * @return {Object|undefined} The registered layer type. + */ +export const getLayerType = ( name ) => select( store ).getLayerType( name ); + +/** + * @return {Object[]} Every registered layer type, in registration order. + */ +export const getLayerTypes = () => select( store ).getLayerTypes(); diff --git a/assets/src/js/godam-layers/registration.test.js b/assets/src/js/godam-layers/registration.test.js new file mode 100644 index 0000000000..303e2bb36b --- /dev/null +++ b/assets/src/js/godam-layers/registration.test.js @@ -0,0 +1,193 @@ +/** + * Layer API (#2292): layer type registration and helpers. + */ + +/** + * WordPress dependencies + */ +import { addFilter, removeFilter } from '@wordpress/hooks'; + +/** + * Internal dependencies + */ +import { + registerLayerType, + unregisterLayerType, + getLayerType, + getLayerTypes, + getDefaultAttributes, + getLayerVariation, + getDefaultVariation, + isVariationAvailable, + getAvailability, + supportsMedia, + __unstableRegisterLegacyLayerType, +} from './index'; + +describe( 'Layer API: registerLayerType', () => { + let error; + + beforeEach( () => { + error = jest.spyOn( console, 'error' ).mockImplementation( () => {} ); + } ); + + afterEach( () => { + getLayerTypes().forEach( ( { name } ) => unregisterLayerType( name ) ); + error.mockRestore(); + } ); + + it( 'registers a namespaced type from layer.json metadata plus settings', () => { + const Edit = () => null; + const registered = registerLayerType( { name: 'acme/countdown', title: 'Countdown' }, { edit: Edit } ); + + expect( registered ).toMatchObject( { name: 'acme/countdown', title: 'Countdown', edit: Edit } ); + expect( getLayerType( 'acme/countdown' ) ).toBe( registered ); + } ); + + it( 'fills in defaults for supports, label, description, attributes and variations', () => { + const registered = registerLayerType( { name: 'acme/countdown', title: 'Countdown', supports: { media: [ 'video', 'image' ] } } ); + + expect( registered ).toMatchObject( { + apiVersion: 1, + label: 'Countdown', + description: '', + attributes: {}, + variations: [], + supports: { media: [ 'video', 'image' ], timeline: true, duplicate: true, skip: false, rawHtml: false }, + } ); + } ); + + it( 'treats a URL icon as an image icon', () => { + const registered = registerLayerType( { name: 'acme/countdown', title: 'Countdown', icon: 'https://example.com/clock.svg' } ); + expect( registered.iconUrl ).toBe( 'https://example.com/clock.svg' ); + expect( registered.icon ).toBeUndefined(); + } ); + + it.each( [ 'countdown', 'Acme/Countdown', 'acme/count down', undefined ] )( 'rejects the name %p', ( name ) => { + expect( registerLayerType( { name, title: 'Countdown' } ) ).toBeUndefined(); + expect( getLayerTypes() ).toEqual( [] ); + } ); + + it( 'accepts the un-namespaced core names', () => { + expect( registerLayerType( { name: 'cta', title: 'CTA' } ) ).toBeDefined(); + } ); + + it( 'rejects a duplicate and keeps the first registration', () => { + registerLayerType( { name: 'acme/countdown', title: 'First' } ); + expect( registerLayerType( { name: 'acme/countdown', title: 'Second' } ) ).toBeUndefined(); + expect( getLayerType( 'acme/countdown' ).title ).toBe( 'First' ); + } ); + + it( 'requires a title', () => { + expect( registerLayerType( { name: 'acme/countdown' } ) ).toBeUndefined(); + } ); + + it( 'drops managed keys and keeps only the default of shared keys', () => { + const registered = registerLayerType( { + name: 'acme/countdown', + title: 'Countdown', + attributes: { + id: { type: 'string' }, + displayTime: { type: 'number' }, + duration: { type: 'string', format: 'url', default: 9 }, + allow_skip: { type: 'boolean' }, + endsAt: { type: 'string', default: '' }, + }, + } ); + + expect( registered.attributes ).toEqual( { + duration: { default: 9 }, + allow_skip: {}, + endsAt: { type: 'string', default: '' }, + } ); + } ); + + it( 'runs settings through the godam.layers.registerLayerType filter', () => { + addFilter( 'godam.layers.registerLayerType', 'test/color', ( settings, name ) => + name === 'acme/countdown' ? { ...settings, color: '#123456' } : settings, + ); + + expect( registerLayerType( { name: 'acme/countdown', title: 'Countdown' } ).color ).toBe( '#123456' ); + + removeFilter( 'godam.layers.registerLayerType', 'test/color' ); + } ); + + it( 'does not let the filter rename the type', () => { + addFilter( 'godam.layers.registerLayerType', 'test/rename', ( settings ) => ( { ...settings, name: 'acme/other' } ) ); + registerLayerType( { name: 'acme/countdown', title: 'Countdown' } ); + removeFilter( 'godam.layers.registerLayerType', 'test/rename' ); + + expect( getLayerType( 'acme/countdown' ) ).toBeDefined(); + expect( getLayerType( 'acme/other' ) ).toBeUndefined(); + } ); + + it( 'lists types in registration order and unregisters them', () => { + registerLayerType( { name: 'acme/b', title: 'B' } ); + registerLayerType( { name: 'acme/a', title: 'A' } ); + expect( getLayerTypes().map( ( { name } ) => name ) ).toEqual( [ 'acme/b', 'acme/a' ] ); + + expect( unregisterLayerType( 'acme/b' ).title ).toBe( 'B' ); + expect( getLayerTypes().map( ( { name } ) => name ) ).toEqual( [ 'acme/a' ] ); + } ); + + it( 'registers a legacy add-on type without a namespace', () => { + expect( __unstableRegisterLegacyLayerType( { name: 'woo', title: 'WooCommerce' } ) ).toMatchObject( { name: 'woo' } ); + } ); + + it( 'exposes the API on window.godam.layers', () => { + expect( window.godam.layers.registerLayerType ).toBe( registerLayerType ); + expect( window.godam.layers.getLayerTypes ).toBe( getLayerTypes ); + } ); +} ); + +describe( 'Layer API: helpers', () => { + const formType = { + attributes: { + form_type: { type: 'string', default: 'gravity' }, + fields: { type: 'array', default: [] }, + }, + variations: [ + { name: 'gravity', title: 'Gravity Forms', attributes: { form_type: 'gravity' } }, + { name: 'wpforms', title: 'WPForms', attributes: { form_type: 'wpforms' }, isDefault: true }, + ], + }; + + it( 'copies default attribute values so layers never share them', () => { + const first = getDefaultAttributes( formType ); + first.fields.push( 'x' ); + expect( getDefaultAttributes( formType ) ).toEqual( { form_type: 'gravity', fields: [] } ); + } ); + + it( 'applies a variation over the defaults', () => { + expect( getDefaultAttributes( formType, formType.variations[ 1 ] ) ).toEqual( { form_type: 'wpforms', fields: [] } ); + } ); + + it( 'finds a saved layer\'s variation, reading missing keys as defaults', () => { + expect( getLayerVariation( formType, { form_type: 'wpforms' } ).name ).toBe( 'wpforms' ); + expect( getLayerVariation( formType, {} ).name ).toBe( 'gravity' ); + expect( getLayerVariation( formType, { form_type: 'mystery' } ) ).toBeUndefined(); + } ); + + it( 'picks the isDefault variation, else the first', () => { + expect( getDefaultVariation( formType ).name ).toBe( 'wpforms' ); + expect( getDefaultVariation( { variations: [ { name: 'a' }, { name: 'b' } ] } ).name ).toBe( 'a' ); + expect( getDefaultVariation( {} ) ).toBeUndefined(); + } ); + + it( 'treats a variation as available unless isAvailable() says otherwise', () => { + expect( isVariationAvailable( {} ) ).toBe( true ); + expect( isVariationAvailable( { isAvailable: () => false } ) ).toBe( false ); + } ); + + it( 'reports availability from getAvailability( context ), defaulting to available', () => { + expect( getAvailability( {} ) ).toEqual( { available: true } ); + const ad = { getAvailability: ( { videoConfig } ) => ( videoConfig.adServer === 'ad-server' ? { available: false, reason: 'No' } : null ) }; + expect( getAvailability( ad, { videoConfig: { adServer: 'ad-server' } } ) ).toEqual( { available: false, reason: 'No' } ); + expect( getAvailability( ad, { videoConfig: {} } ) ).toEqual( { available: true } ); + } ); + + it( 'checks media support', () => { + expect( supportsMedia( { supports: { media: [ 'video', 'image' ] } }, 'image' ) ).toBe( true ); + expect( supportsMedia( { supports: { media: [ 'video' ] } }, 'audio' ) ).toBe( false ); + } ); +} ); diff --git a/assets/src/js/godam-layers/store.js b/assets/src/js/godam-layers/store.js new file mode 100644 index 0000000000..bd251737a9 --- /dev/null +++ b/assets/src/js/godam-layers/store.js @@ -0,0 +1,57 @@ +/** + * The `godam/layers` data store: every registered layer type, in registration order. + */ + +/** + * WordPress dependencies + */ +import { createReduxStore, createSelector, register } from '@wordpress/data'; + +/** + * Internal dependencies + */ +import { STORE_NAME } from './constants'; + +const DEFAULT_STATE = { + types: {}, + order: [], +}; + +const reducer = ( state = DEFAULT_STATE, action ) => { + switch ( action.type ) { + case 'ADD_LAYER_TYPE': + return { + types: { ...state.types, [ action.layerType.name ]: action.layerType }, + order: state.order.includes( action.layerType.name ) ? state.order : [ ...state.order, action.layerType.name ], + }; + case 'REMOVE_LAYER_TYPE': { + if ( ! state.types[ action.name ] ) { + return state; + } + const { [ action.name ]: removed, ...types } = state.types; // eslint-disable-line no-unused-vars + return { + types, + order: state.order.filter( ( name ) => name !== action.name ), + }; + } + default: + return state; + } +}; + +const actions = { + addLayerType: ( layerType ) => ( { type: 'ADD_LAYER_TYPE', layerType } ), + removeLayerType: ( name ) => ( { type: 'REMOVE_LAYER_TYPE', name } ), +}; + +const selectors = { + getLayerType: ( state, name ) => state.types[ name ], + getLayerTypes: createSelector( + ( state ) => state.order.map( ( name ) => state.types[ name ] ), + ( state ) => [ state.types, state.order ], + ), +}; + +export const store = createReduxStore( STORE_NAME, { reducer, actions, selectors } ); + +register( store ); diff --git a/assets/src/js/godam-layers/utils.js b/assets/src/js/godam-layers/utils.js new file mode 100644 index 0000000000..e17a5ed73a --- /dev/null +++ b/assets/src/js/godam-layers/utils.js @@ -0,0 +1,84 @@ +/** + * Helpers for working with registered layer types. + */ + +const clone = ( value ) => ( value === undefined ? undefined : JSON.parse( JSON.stringify( value ) ) ); + +/** + * Default attribute values for a new layer of this type, optionally for a + * variation. Values are copied, so layers never share an array or object. + * + * @param {Object} layerType Registered layer type. + * @param {Object} [variation] One of the type's variations. + * @return {Object} Attribute defaults. + */ +export function getDefaultAttributes( layerType, variation ) { + const defaults = {}; + Object.entries( layerType?.attributes || {} ).forEach( ( [ key, schema ] ) => { + if ( schema && 'default' in schema ) { + defaults[ key ] = clone( schema.default ); + } + } ); + return { ...defaults, ...clone( variation?.attributes || {} ) }; +} + +/** + * The variation a saved layer uses: the one whose `attributes` all match the + * layer, reading missing keys as their defaults. Undefined for a type with no + * variations, or a layer that matches none. + * + * @param {Object} layerType Registered layer type. + * @param {Object} layer Saved layer. + * @return {Object|undefined} The matching variation. + */ +export function getLayerVariation( layerType, layer ) { + const defaults = getDefaultAttributes( layerType ); + return ( layerType?.variations || [] ).find( ( variation ) => + Object.entries( variation.attributes || {} ).every( ( [ key, value ] ) => ( layer?.[ key ] ?? defaults[ key ] ) === value ), + ); +} + +/** + * The variation a new layer gets when none is chosen: the one marked + * `isDefault`, else the first. + * + * @param {Object} layerType Registered layer type. + * @return {Object|undefined} The default variation. + */ +export function getDefaultVariation( layerType ) { + const variations = layerType?.variations || []; + return variations.find( ( variation ) => variation.isDefault ) || variations[ 0 ]; +} + +/** + * Whether a variation can be used right now (e.g. its form plugin is active). + * + * @param {Object} variation A layer type variation. + * @return {boolean} True when available. + */ +export function isVariationAvailable( variation ) { + return typeof variation?.isAvailable === 'function' ? variation.isAvailable() !== false : true; +} + +/** + * Whether a layer type can be added right now, and why not. + * + * @param {Object} layerType Registered layer type. + * @param {Object} context `{ videoConfig, mediaType }` from the editor. + * @return {{available: boolean, reason?: string, disablesExisting?: boolean}} Availability. + */ +export function getAvailability( layerType, context = {} ) { + const availability = typeof layerType?.getAvailability === 'function' ? layerType.getAvailability( context ) : null; + return { available: true, ...( availability || {} ) }; +} + +/** + * Whether a layer type works on this kind of media. + * + * @param {Object} layerType Registered layer type. + * @param {string} mediaType `video`, `audio` or `image`. + * @return {boolean} True when supported. + */ +export function supportsMedia( layerType, mediaType ) { + return ( layerType?.supports?.media || [] ).includes( mediaType ); +} diff --git a/assets/src/layers/ad/layer.json b/assets/src/layers/ad/layer.json new file mode 100644 index 0000000000..7320d626fa --- /dev/null +++ b/assets/src/layers/ad/layer.json @@ -0,0 +1,17 @@ +{ + "apiVersion": 1, + "name": "ad", + "title": "Ad", + "description": "Insert an advertisement", + "color": "#CD860D", + "supports": { + "media": [ "video" ] + }, + "attributes": { + "adTagUrl": { "type": "string", "format": "url", "default": "" }, + "ad_url": { "type": "string", "format": "url", "default": "" }, + "skippable": { "type": "boolean", "default": false }, + "skip_offset": { "type": "integer", "default": 5 } + }, + "textdomain": "godam" +} diff --git a/assets/src/layers/cta/layer.json b/assets/src/layers/cta/layer.json new file mode 100644 index 0000000000..6e660abe60 --- /dev/null +++ b/assets/src/layers/cta/layer.json @@ -0,0 +1,21 @@ +{ + "apiVersion": 1, + "name": "cta", + "title": "CTA", + "description": "Add a clickable button", + "color": "#3858e9", + "supports": { + "media": [ "video" ], + "skip": true + }, + "attributes": { + "cta_type": { "type": "string", "default": "image" }, + "cardLayout": { "type": "string", "default": "card-layout--imagecover-text" }, + "trigger": { "default": "timestamp" }, + "watchDepth": { "default": 50 }, + "html": { "type": "string", "format": "html", "default": "" }, + "link": { "type": "string", "format": "url", "default": "" }, + "allow_skip": { "default": true } + }, + "textdomain": "godam" +} diff --git a/assets/src/layers/form/layer.json b/assets/src/layers/form/layer.json new file mode 100644 index 0000000000..5433a63870 --- /dev/null +++ b/assets/src/layers/form/layer.json @@ -0,0 +1,19 @@ +{ + "apiVersion": 1, + "name": "form", + "title": "Form", + "description": "Embed a lead form", + "color": "#088EAF", + "supports": { + "media": [ "video" ], + "skip": true + }, + "attributes": { + "form_type": { "type": "string", "default": "gravity" }, + "submitted": { "type": "boolean", "default": false }, + "allow_skip": { "default": true }, + "custom_css": { "default": "" }, + "theme": { "type": "string", "default": "" } + }, + "textdomain": "godam" +} diff --git a/assets/src/layers/hotspot/layer.json b/assets/src/layers/hotspot/layer.json new file mode 100644 index 0000000000..accb72a70e --- /dev/null +++ b/assets/src/layers/hotspot/layer.json @@ -0,0 +1,21 @@ +{ + "apiVersion": 1, + "name": "hotspot", + "title": "Hotspot", + "description": "Add an info hotspot", + "color": "#10B77F", + "supports": { + "media": [ "video", "image" ] + }, + "attributes": { + "duration": { "default": 5 }, + "pauseOnHover": { "type": "boolean", "default": false }, + "hotspots": { "type": "array", "default": [] }, + "styleType": { "type": "string", "default": "pulse" }, + "icon": { "type": "string", "default": "" }, + "customIconUrl": { "type": [ "string", "null" ], "format": "url", "default": null }, + "customIconId": { "type": [ "integer", "null" ], "default": null }, + "isNew": { "type": "boolean", "default": true } + }, + "textdomain": "godam" +} diff --git a/assets/src/layers/poll/layer.json b/assets/src/layers/poll/layer.json new file mode 100644 index 0000000000..b16a2f5a9a --- /dev/null +++ b/assets/src/layers/poll/layer.json @@ -0,0 +1,17 @@ +{ + "apiVersion": 1, + "name": "poll", + "title": "Poll", + "description": "Create an interactive poll", + "color": "#E8499E", + "supports": { + "media": [ "video" ], + "skip": true + }, + "attributes": { + "poll_id": { "type": "string", "default": "" }, + "allow_skip": { "default": true }, + "custom_css": { "default": "" } + }, + "textdomain": "godam" +} diff --git a/inc/classes/class-pages.php b/inc/classes/class-pages.php index 93e1ada5b2..39f41786df 100644 --- a/inc/classes/class-pages.php +++ b/inc/classes/class-pages.php @@ -655,6 +655,8 @@ public function admin_enqueue_scripts() { // Check if this is your custom admin page. if ( $screen && $this->video_editor_page_id === $screen->id ) { + $this->register_layer_api_script(); + wp_register_script( 'transcoder-page-script-video-editor', RTGODAM_URL . 'assets/build/pages/video-editor.min.js', @@ -662,7 +664,8 @@ public function admin_enqueue_scripts() { // but depends on the WP-provided builds of these packages being // present. `wp-private-apis` in particular must load so the // bundled DataViews can unlock `@wordpress/components` private APIs. - array( 'wp-element', 'wp-components', 'wp-primitives', 'wp-api-fetch', 'wp-data', 'wp-notices', 'wp-private-apis', 'wp-i18n' ), + // `godam-layers` is the layer type registry the editor reads. + array( 'wp-element', 'wp-components', 'wp-primitives', 'wp-api-fetch', 'wp-data', 'wp-notices', 'wp-private-apis', 'wp-i18n', 'godam-layers' ), filemtime( RTGODAM_PATH . 'assets/build/pages/video-editor.min.js' ), true ); @@ -834,6 +837,11 @@ public function admin_enqueue_scripts() { wp_set_script_translations( 'transcoder-page-script-video-editor', 'godam', RTGODAM_PATH . 'languages' ); wp_enqueue_script( 'transcoder-page-script-video-editor' ); + // The editor bundle provides `window.godam.layerEditor` (hooks and controls + // for layer settings panels). This handle lets an add-on's editor script + // depend on it by name, as `@godam/layer-editor`. + wp_register_script( 'godam-layer-editor', false, array( 'transcoder-page-script-video-editor' ), RTGODAM_VERSION, true ); + // The "Edit metadata" action reuses the native two-column attachment // details modal (wp.media.view.MediaFrame.EditAttachments), which is // defined in core's media-grid script. wp_enqueue_media() does not @@ -1538,6 +1546,38 @@ private function get_layer_entries_url( $layer ) { return admin_url( str_replace( '{id}', (string) $form_id, $template ) ); } + /** + * Register `godam-layers`, the Layer API's layer type registry + * (`window.godam.layers`). The video editor depends on it, and so can an + * add-on's editor script that registers its own layer types. + * + * @since n.e.x.t + * + * @return void + */ + private function register_layer_api_script() { + if ( wp_script_is( 'godam-layers', 'registered' ) ) { + return; + } + + $asset_path = RTGODAM_PATH . 'assets/build/js/godam-layers.min.asset.php'; + $asset = file_exists( $asset_path ) + // phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingVariable -- file path is a plugin constant + hardcoded build filename. + ? include $asset_path + : array( + 'dependencies' => array( 'wp-data', 'wp-hooks' ), + 'version' => RTGODAM_VERSION, + ); + + wp_register_script( + 'godam-layers', + RTGODAM_URL . 'assets/build/js/godam-layers.min.js', + $asset['dependencies'], + $asset['version'], + true + ); + } + /** * Get PostHog configuration for internal GoDAM analytics tracking. * These are hardcoded public keys - clients don't need to configure anything. diff --git a/jest.config.js b/jest.config.js index c035e21f77..e97c5fe5c7 100644 --- a/jest.config.js +++ b/jest.config.js @@ -25,5 +25,7 @@ module.exports = { '\\.(scss|css)$': '/node_modules/@wordpress/jest-preset-default/scripts/style-mock.js', '\\.(svg|png|jpe?g|gif|webp)$': '/bin/jest/asset-mock.js', + // A webpack external at runtime (`window.godam.layers`); tests use the source. + '^@godam/layers$': '/assets/src/js/godam-layers/index.js', }, }; diff --git a/package-lock.json b/package-lock.json index 6293183bf5..bc7440f689 100644 --- a/package-lock.json +++ b/package-lock.json @@ -25,6 +25,7 @@ "@uppy/golden-retriever": "5.0.0", "@uppy/screen-capture": "5.0.0", "@uppy/webcam": "5.0.0", + "@wordpress/hooks": "4.56.0", "@wordpress/html-entities": "4.55.0", "analytics": "^0.8.18", "axios": "1.20.0", @@ -11133,7 +11134,6 @@ "version": "4.56.0", "resolved": "https://registry.npmjs.org/@wordpress/hooks/-/hooks-4.56.0.tgz", "integrity": "sha512-3+90yFqbMyzhqOEu88MjwlpznzVFl3am0YYIt7kc/8mfJ79IyHkYyiDdid3/fkJDMbZHH4tGy0J/JFp84/5Q2w==", - "dev": true, "license": "GPL-2.0-or-later", "engines": { "node": ">=18.12.0" diff --git a/package.json b/package.json index 24e26265ec..549f8dbf81 100644 --- a/package.json +++ b/package.json @@ -39,6 +39,7 @@ "@uppy/golden-retriever": "5.0.0", "@uppy/screen-capture": "5.0.0", "@uppy/webcam": "5.0.0", + "@wordpress/hooks": "4.56.0", "@wordpress/html-entities": "4.55.0", "analytics": "^0.8.18", "axios": "1.20.0", diff --git a/pages/video-editor/VideoEditor.js b/pages/video-editor/VideoEditor.js index a1aafcf3d7..733f202df5 100644 --- a/pages/video-editor/VideoEditor.js +++ b/pages/video-editor/VideoEditor.js @@ -3,6 +3,7 @@ */ import React, { useCallback, useEffect, useState, useRef } from 'react'; import { useSelector, useDispatch } from 'react-redux'; +import { getLayerType } from '@godam/layers'; /** * WordPress dependencies @@ -52,7 +53,6 @@ import { formatBytes } from './components/transcription/utils'; import Timeline from './components/timeline/Timeline'; import { copyGoDAMVideoBlock, prefetchMediaDataForCopy } from './utils/index'; import { openAttachmentDetailsModal } from './utils/openAttachmentDetails'; -import { getFormIdFromLayer } from './utils/formUtils'; import { canManageAttachment } from '../../assets/src/js/media-library/utility.js'; import { ensureAddonLayersRegistered } from './utils/loadAddonLayers'; @@ -203,7 +203,6 @@ const VideoEditor = ( { attachmentID, onBackToAttachmentPicker } ) => { mediaType: mediaCapability.mediaType, tabs: mediaCapability.tabs, defaultTab: mediaCapability.defaultTab, - allowedLayerTypes: mediaCapability.allowedLayerTypes, } ) ); // Initialize the store if meta exists @@ -484,19 +483,14 @@ const VideoEditor = ( { attachmentID, onBackToAttachmentPicker } ) => { }; const pauseVideo = () => playerRef.current?.pause(); - const validateLayers = ( videoLayers ) => { - const invalidFormLayers = []; - for ( const layer of videoLayers ) { - if ( layer.type === 'form' ) { - const formType = layer.form_type; - const formId = getFormIdFromLayer( layer, formType ); - if ( ! formId ) { - invalidFormLayers.push( layer.displayTime ); - } - } - } - return invalidFormLayers; - }; + // Each layer type can refuse to save an incomplete layer (e.g. a form layer + // with no form picked) through its registered `validate( layer )`. + const validateLayers = ( videoLayers ) => videoLayers + .filter( ( layer ) => { + const validate = getLayerType( layer.type )?.validate; + return typeof validate === 'function' && ! validate( layer ); + } ) + .map( ( layer ) => layer.displayTime ); const handleSaveAttachmentMeta = async () => { const invalidLayers = validateLayers( layers ); diff --git a/pages/video-editor/_layers.scss b/pages/video-editor/_layers.scss index 7c59b39363..2bb3d4b409 100644 --- a/pages/video-editor/_layers.scss +++ b/pages/video-editor/_layers.scss @@ -16,6 +16,20 @@ $ve-faint: color-mix(in srgb, currentcolor 5%, transparent); .godam-video-editor { + // Shown instead of a layer's settings panel: the error boundary's "could not + // be opened" message, and the "needs an add-on" notice for an unregistered type. + .godam-layer-error { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 0.75rem; + padding: 1rem; + + p { + margin: 0; + } + } + .godam-ve-layers { &__head { diff --git a/pages/video-editor/components/SidebarLayers.js b/pages/video-editor/components/SidebarLayers.js index 3d845501b6..0e1e6413c1 100644 --- a/pages/video-editor/components/SidebarLayers.js +++ b/pages/video-editor/components/SidebarLayers.js @@ -2,26 +2,22 @@ * External dependencies */ import { useSelector, useDispatch } from 'react-redux'; +import { v4 as uuidv4 } from 'uuid'; +import { + store as layersStore, + getLayerType, + getDefaultAttributes, + getDefaultVariation, + getLayerVariation, + isVariationAvailable, + getAvailability, + supportsMedia, +} from '@godam/layers'; /** * Internal dependencies */ import { addLayer, setCurrentLayer, setAddLayerModalTime, removeLayer } from '../redux/slice/videoSlice'; -import { v4 as uuidv4 } from 'uuid'; -import GFIcon from '../assets/layers/GFIcon.svg'; -import WPFormsIcon from '../assets/layers/WPForms-Mascot.svg'; -import EverestFormsIcon from '../assets/layers/EverestFormsIcon.svg'; -import CF7Icon from '../assets/layers/CF7Icon.svg'; -import JetpackIcon from '../assets/layers/JetpackIcon.svg'; -import SureformsIcon from '../assets/layers/SureFormsIcons.svg'; -import ForminatorIcon from '../assets/layers/Forminator.png'; -import FluentFormsIcon from '../assets/layers/FluentFormsIcon.png'; -import NinjaFormsIcon from '../assets/layers/NinjaFormsIcon.png'; -import MetformIcon from '../assets/layers/MetFormIcon.png'; -import MarketoIcon from '../assets/layers/MarketoIcon.svg'; -import HubSpotIcon from '../assets/layers/HubSpotIcon.svg'; -import { CtaLayerIcon, HotspotLayerIcon, FormLayerIcon, PollLayerIcon } from './editor-shell/icons'; -import { LAYER_TYPE_COLORS } from '../utils/layerTypes'; import { notify as notifyGuide } from '../onboarding/productGuide'; /** @@ -29,153 +25,42 @@ import { notify as notifyGuide } from '../onboarding/productGuide'; */ import { __, sprintf } from '@wordpress/i18n'; import { Button, Icon, Tooltip, Dropdown, DropdownMenu, MenuGroup, MenuItem, NavigableMenu, Popover } from '@wordpress/components'; -import { plus, preformatted, customLink, video, customPostType, thumbsUp, moreVertical, copy, trash, chevronRight, info } from '@wordpress/icons'; +import { plus, moreVertical, copy, trash, chevronRight, info } from '@wordpress/icons'; import { useState, useEffect, useCallback, useRef } from '@wordpress/element'; +import { useSelect } from '@wordpress/data'; /** - * Layer types with their labels, icons, and integration-specific state. + * A layer type's label, or its variation's title for types with variations. + * + * @param {Object} layerType Registered layer type. + * @param {string} [variation] Variation name; defaults to the type's default variation. + * @return {string} The label, or `''`. */ -export const layerTypes = [ - { - title: __( 'CTA', 'godam' ), - icon: customLink, - type: 'cta', - layerText: __( 'CTA', 'godam' ), - }, - { - title: __( 'Hotspot', 'godam' ), - icon: customPostType, - type: 'hotspot', - layerText: __( 'Hotspot', 'godam' ), - }, - { - title: __( 'Forms', 'godam' ), - icon: preformatted, - type: 'form', - formType: { - gravity: { - layerText: __( 'Gravity Forms', 'godam' ), - icon: GFIcon, - isActive: window?.videoData?.gfActive ?? false, - tooltipMessage: __( 'Gravity Forms plugin is not active', 'godam' ), - }, - wpforms: { - layerText: __( 'WPForms', 'godam' ), - icon: WPFormsIcon, - isActive: window?.videoData?.wpformsActive ?? false, - tooltipMessage: __( 'WPForms plugin is not active', 'godam' ), - }, - cf7: { - layerText: __( 'Contact Form 7', 'godam' ), - isActive: window?.videoData?.cf7Active ?? false, - icon: CF7Icon, - tooltipMessage: __( 'Contact Form 7 plugin is not active', 'godam' ), - }, - jetpack: { - layerText: __( 'Jetpack Forms', 'godam' ), - icon: JetpackIcon, - isActive: window?.videoData?.jetpackActive ?? false, - tooltipMessage: __( 'Jetpack plugin is not active', 'godam' ), - }, - sureforms: { - layerText: __( 'SureForms', 'godam' ), - icon: SureformsIcon, - isActive: window?.videoData?.sureformsActive ?? false, - tooltipMessage: __( 'SureForms plugin is not active', 'godam' ), - }, - forminator: { - layerText: __( 'Forminator Forms', 'godam' ), - icon: ForminatorIcon, - isActive: window?.videoData?.forminatorActive ?? false, - tooltipMessage: __( 'Forminator Forms plugin is not active', 'godam' ), - }, - fluentforms: { - layerText: __( 'Fluent Forms', 'godam' ), - icon: FluentFormsIcon, - isActive: window?.videoData?.fluentformsActive ?? false, - tooltipMessage: __( 'Fluent Forms plugin is not active', 'godam' ), - }, - everestforms: { - layerText: __( 'Everest Forms', 'godam' ), - icon: EverestFormsIcon, - isActive: window?.videoData?.everestFormsActive ?? false, - tooltipMessage: __( 'Everest Forms plugin is not active', 'godam' ), - }, - ninjaforms: { - layerText: __( 'Ninja Forms', 'godam' ), - icon: NinjaFormsIcon, - isActive: window?.videoData?.ninjaFormsActive ?? false, - tooltipMessage: __( 'Ninja Forms plugin is not active', 'godam' ), - }, - metform: { - layerText: __( 'MetForm', 'godam' ), - icon: MetformIcon, - isActive: window?.videoData?.metformActive ?? false, - tooltipMessage: __( 'MetForm plugin is not active', 'godam' ), - }, - marketo: { - layerText: __( 'Marketo', 'godam' ), - icon: MarketoIcon, - // Marketo has no plugin to activate: it is always offered in the - // Add-layer menu. The layer's settings panel shows a notice linking - // to Settings → Integrations → Marketo when credentials are missing. - isActive: true, - tooltipMessage: '', - }, - hubspot: { - layerText: __( 'HubSpot', 'godam' ), - icon: HubSpotIcon, - isActive: window?.videoData?.hubspotActive ?? false, - // Say what actually unblocks the layer: turning the integration on, - // or connecting the source the admin chose (GoDAM Central by default, - // where activating the HubSpot plugin alone is not enough). - tooltipMessage: ( () => { - if ( window?.videoData?.hubspotEnabled === false ) { - return __( 'Turn on HubSpot in Settings → Integrations → HubSpot to use this form', 'godam' ); - } - return 'leadin' === ( window?.videoData?.hubspotChosenSource ?? 'central' ) - ? __( 'Activate and connect the HubSpot plugin to use this form', 'godam' ) - : __( 'Connect HubSpot in Settings → Integrations → HubSpot to use this form', 'godam' ); - } )(), - }, - }, - }, - { - title: __( 'Ad', 'godam' ), - icon: video, - type: 'ad', - layerText: __( 'Ad', 'godam' ), - tooltipMessage: __( 'This ad will be overridden by Ad server\'s ads', 'godam' ), - }, - { - title: __( 'Poll', 'godam' ), - icon: thumbsUp, - type: 'poll', - layerText: __( 'Poll', 'godam' ), - isActive: Boolean( window?.easydamMediaLibrary?.isPollPluginActive ) ?? false, - tooltipMessage: __( 'Poll plugin is not active', 'godam' ), - }, - // Add-on layers (e.g., WooCommerce) are merged from PHP via godamVideoEditorConfig. - ...( window.godamVideoEditorConfig?.layerOptions || [] ), -]; +const getLayerTypeLabel = ( layerType, variation ) => { + if ( ! layerType ) { + return ''; + } + if ( layerType.variations.length ) { + const match = variation + ? layerType.variations.find( ( v ) => v.name === variation ) + : getDefaultVariation( layerType ); + return match?.title || ''; + } + return layerType.label || layerType.title || ''; +}; /** * Build the default display name for a layer, e.g. "CTA Layer", "Hotspot Layer", - * "Gravity Forms Layer". The label is pulled from the layer-type registry above - * (including add-on layers merged via `godamVideoEditorConfig`) so it stays in - * sync with the Add-layer menu. Returns `''` for unknown types. + * "Gravity Forms Layer". The label comes from the layer registry (a variation's + * title for types with variations, such as the form plugin), so it matches the + * Add-layer menu. Returns `''` for unregistered types. * - * @param {string} type Layer type (e.g. 'cta', 'hotspot', 'form'). - * @param {string} [formType] Form integration key for `form` layers (e.g. 'gravity'). + * @param {string} type Layer type name (e.g. 'cta', 'hotspot', 'form'). + * @param {string} [variation] Variation name for types with variations (e.g. 'gravity'). * @return {string} The default layer name. */ -export const getDefaultLayerName = ( type, formType ) => { - const data = layerTypes.find( ( l ) => l.type === type ); - const label = ( - 'form' === type - ? data?.formType?.[ formType || 'gravity' ]?.layerText - : ( data?.layerText || data?.title ) - ) || ''; +export const getDefaultLayerName = ( type, variation ) => { + const label = getLayerTypeLabel( getLayerType( type ), variation ); if ( ! label ) { return ''; @@ -215,7 +100,7 @@ const AddLayerSubmenuItem = ( { opt, onParentClose } ) => { > { opt.iconUrl ? @@ -242,7 +127,7 @@ const AddLayerSubmenuItem = ( { opt, onParentClose } ) => { { sub.onSelect(); setSubOpen( false ); @@ -317,121 +202,53 @@ const SidebarLayers = ( { currentTime, onSelectLayer, onPauseVideo, duration } ) const layers = useSelector( ( state ) => state.videoReducer.layers ); const currentLayer = useSelector( ( state ) => state.videoReducer.currentLayer ); const videoConfig = useSelector( ( state ) => state.videoReducer.videoConfig ); - // Media-type gate: `'*'` (video) allows every layer type; a restricted media - // type (e.g. a future image editor with `[ 'hotspot' ]`) narrows the add menu - // and the rendered list. - const allowedLayerTypes = useSelector( ( state ) => state.videoReducer.allowedLayerTypes ); - const isLayerTypeAllowed = useCallback( - ( type ) => allowedLayerTypes === '*' || ! Array.isArray( allowedLayerTypes ) || allowedLayerTypes.includes( type ), - [ allowedLayerTypes ], - ); + // Layer types come from the registry; add-ons can register after the editor loads. + const layerTypes = useSelect( ( select ) => select( layersStore ).getLayerTypes(), [] ); // Timeline-based media (video) gate the add flow on a playhead position; // images have no timeline, so layers are added freely and land at 0:00. const mediaType = useSelector( ( state ) => state.videoReducer.mediaType ); const isTimelineMedia = mediaType !== 'image'; - const adServer = videoConfig?.adServer ?? 'self-hosted'; + const availabilityContext = { videoConfig, mediaType }; - // Sort the array (ascending order), excluding unknown and disallowed types. + // Sort the array (ascending order). A registered type that doesn't support + // this media is hidden; a type nothing registered stays listed, with a notice. const sortedLayers = [ ...layers ] - .filter( ( layer ) => layerTypes.some( ( lt ) => lt.type === layer.type ) && isLayerTypeAllowed( layer.type ) ) + .filter( ( layer ) => { + const layerType = getLayerType( layer.type ); + return ! layerType || supportsMedia( layerType, mediaType ); + } ) .sort( ( a, b ) => a.displayTime - b.displayTime ); - const addNewLayer = ( type, formType ) => { + const addNewLayer = ( type, variationName ) => { + const layerType = getLayerType( type ); + if ( ! layerType ) { + return; + } // Add at the time requested from the timeline ("Add layer" chip), else at // the current playhead. `??` keeps a valid 0:00. Cleared on menu close. const addTime = addLayerModalTime ?? currentTime; - switch ( type ) { - case 'form': - dispatch( addLayer( { - id: uuidv4(), - displayTime: addTime, - type, - name: getDefaultLayerName( type, formType ), - form_type: formType || 'gravity', - submitted: false, - allow_skip: true, - custom_css: '', - theme: '', - } ) ); - break; - case 'cta': - dispatch( addLayer( { - id: uuidv4(), - displayTime: addTime, - type, - name: getDefaultLayerName( type ), - cta_type: 'image', - cardLayout: 'card-layout--imagecover-text', - trigger: 'timestamp', - watchDepth: 50, - html: '', - link: '', - allow_skip: true, - } ) ); - break; - case 'hotspot': - dispatch( - addLayer( { - id: uuidv4(), - displayTime: addTime, - type, - name: getDefaultLayerName( type ), - duration: 5, - pauseOnHover: false, - hotspots: [], - // `styleType` marks the layer as using the shared-style - // model (and keeps the legacy-migration effect from running - // on this fresh layer). Colours are intentionally NOT seeded - // here: the Style pickers and resolveHotspotStyle supply the - // conditional defaults (pulse / library-icon background - // #0c80dfa6, library glyph #fff, custom-icon background #fff). - // Hardcoding them overrode those defaults — e.g. a seeded - // blue `iconColor` made the glyph render blue, not white. - styleType: 'pulse', - icon: '', - customIconUrl: null, - customIconId: null, - isNew: true, - } ), - ); - break; - case 'ad': - dispatch( addLayer( { - id: uuidv4(), - displayTime: addTime, - type, - name: getDefaultLayerName( type ), - adTagUrl: '', - ad_url: '', - skippable: false, - skip_offset: 5, - } ) ); - break; - case 'poll': - dispatch( addLayer( { - id: uuidv4(), - displayTime: addTime, - type, - name: getDefaultLayerName( type ), - poll_id: '', - allow_skip: true, - custom_css: '', - } ) ); - break; - default: { - // Check for add-on layer creators (registered via window.godamLayerCreators). - const addonCreator = window.godamLayerCreators?.[ type ]; - if ( addonCreator ) { - const layerData = addonCreator( { layers, currentTime: addTime, type } ); - if ( layerData ) { - // Seed a registry-derived default name; the add-on creator can - // override it by returning its own `name` (e.g. the WooCommerce - // layer names itself "Product Hotspot Layer"). - dispatch( addLayer( { name: getDefaultLayerName( type ), ...layerData, id: uuidv4() } ) ); - } - } - break; + + if ( typeof layerType.create === 'function' ) { + // Add-on types from the old hooks build their own layer data + // (`window.godamLayerCreators`). + const layerData = layerType.create( { layers, currentTime: addTime, type } ); + if ( layerData ) { + // Seed a registry-derived default name; the add-on creator can + // override it by returning its own `name` (e.g. the WooCommerce + // layer names itself "Product Hotspot Layer"). + dispatch( addLayer( { name: getDefaultLayerName( type ), ...layerData, id: uuidv4() } ) ); } + } else { + const variation = variationName + ? layerType.variations.find( ( v ) => v.name === variationName ) + : getDefaultVariation( layerType ); + dispatch( addLayer( { + id: uuidv4(), + displayTime: addTime, + type, + name: getDefaultLayerName( type, variation?.name ), + ...getDefaultAttributes( layerType, variation ), + } ) ); } // Advance the product guide's "add a layer" step once a layer is added. @@ -474,92 +291,43 @@ const SidebarLayers = ( { currentTime, onSelectLayer, onPauseVideo, duration } ) const hasLayerAtCurrentTime = Boolean( layers.find( ( l ) => l.displayTime === currentTime ) ); const isAddDisabled = isTimelineMedia && ( ! currentTime || hasLayerAtCurrentTime ); - // Colored layer-type icons (from design) used in the list rows + add menu. - const layerTypeIcons = { - cta: CtaLayerIcon, - hotspot: HotspotLayerIcon, - poll: PollLayerIcon, - }; - - // Build the "Add layer" dropdown options from the live layer types so that - // plugin availability (forms/poll/ad/add-ons) is reflected here, mirroring - // the modal's behaviour. - const buildAddOptions = () => { - const options = [ - { key: 'cta', iconComponent: CtaLayerIcon, title: __( 'CTA', 'godam' ), description: __( 'Add a clickable button', 'godam' ), onSelect: () => addNewLayer( 'cta' ) }, - { key: 'hotspot', iconComponent: HotspotLayerIcon, title: __( 'Hotspot', 'godam' ), description: __( 'Add an info hotspot', 'godam' ), onSelect: () => addNewLayer( 'hotspot' ) }, - ]; - - // "Form" entry. With multiple active form plugins it opens a side submenu - // to choose one; with a single plugin it adds directly; disabled when none - // are active. - const formLayer = layerTypes.find( ( l ) => l.type === 'form' ); - const activeForms = Object.entries( formLayer?.formType ?? {} ) - .filter( ( [ , ft ] ) => ft.isActive ) - .map( ( [ ftKey, ft ] ) => ( { - key: ftKey, - title: ft.layerText, - iconUrl: ft.icon, - onSelect: () => addNewLayer( 'form', ftKey ), - } ) ); - const formOption = { - key: 'form', - iconComponent: FormLayerIcon, - title: __( 'Form', 'godam' ), - description: __( 'Embed a lead form', 'godam' ), - }; - if ( activeForms.length === 0 ) { - formOption.disabled = true; - formOption.tooltip = __( 'No form plugin is active', 'godam' ); - } else if ( activeForms.length === 1 ) { - formOption.onSelect = activeForms[ 0 ].onSelect; - } else { - formOption.submenu = activeForms; - } - options.push( formOption ); - - const pollLayer = layerTypes.find( ( l ) => l.type === 'poll' ); - options.push( { - key: 'poll', - iconComponent: PollLayerIcon, - title: __( 'Poll', 'godam' ), - description: __( 'Create an interactive poll', 'godam' ), - disabled: pollLayer?.isActive === false, - tooltip: pollLayer?.isActive === false ? pollLayer?.tooltipMessage : '', - onSelect: () => addNewLayer( 'poll' ), - } ); - - const adLayer = layerTypes.find( ( l ) => l.type === 'ad' ); - const adDisabled = 'ad-server' === adServer; - options.push( { - key: 'ad', - iconComponent: adLayer?.icon, - title: __( 'Ad', 'godam' ), - description: __( 'Insert an advertisement', 'godam' ), - disabled: adDisabled, - tooltip: adDisabled ? adLayer?.tooltipMessage : '', - onSelect: () => addNewLayer( 'ad' ), + // Build the "Add layer" dropdown from the registry, in registration order. + // A type with variations (e.g. Form's form plugins) adds directly when one + // variation is available and opens a side submenu when several are. + const buildAddOptions = () => layerTypes + .filter( ( layerType ) => supportsMedia( layerType, mediaType ) ) + .map( ( layerType ) => { + const option = { + key: layerType.name, + iconUrl: layerType.iconUrl, + iconComponent: layerType.iconUrl ? undefined : layerType.icon, + title: layerType.title, + description: layerType.description, + color: layerType.color, + }; + const availability = getAvailability( layerType, availabilityContext ); + if ( ! availability.available ) { + return { ...option, disabled: true, tooltip: availability.reason ?? '' }; + } + if ( ! layerType.variations.length ) { + return { ...option, onSelect: () => addNewLayer( layerType.name ) }; + } + const variations = layerType.variations + .filter( isVariationAvailable ) + .map( ( variation ) => ( { + key: variation.name, + title: variation.title, + iconUrl: typeof variation.icon === 'string' ? variation.icon : undefined, + iconComponent: typeof variation.icon === 'string' ? undefined : variation.icon, + onSelect: () => addNewLayer( layerType.name, variation.name ), + } ) ); + if ( variations.length === 0 ) { + return { ...option, disabled: true, tooltip: '' }; + } + return variations.length === 1 + ? { ...option, onSelect: variations[ 0 ].onSelect } + : { ...option, submenu: variations }; } ); - - // Add-on layers (e.g., WooCommerce) merged from PHP. - layerTypes - .filter( ( lt ) => ! [ 'cta', 'hotspot', 'form', 'ad', 'poll' ].includes( lt.type ) ) - .forEach( ( lt ) => { - options.push( { - key: lt.type, - iconUrl: lt.iconUrl, - iconComponent: lt.iconUrl ? undefined : lt.icon, - title: lt.title || lt.layerText, - description: ( lt.title && lt.layerText ) ? lt.layerText : '', - disabled: lt.isActive === false, - tooltip: lt.isActive === false ? ( lt.tooltipMessage ?? '' ) : '', - onSelect: () => addNewLayer( lt.type ), - } ); - } ); - - // Restrict to the layer types the current media type allows. - return options.filter( ( opt ) => isLayerTypeAllowed( opt.key ) ); - }; const addOptions = buildAddOptions(); return ( @@ -630,7 +398,7 @@ const SidebarLayers = ( { currentTime, onSelectLayer, onPauseVideo, duration } ) > { opt.iconUrl ? @@ -687,28 +455,29 @@ const SidebarLayers = ( { currentTime, onSelectLayer, onPauseVideo, duration } ) { ! loading && sortedLayers.length > 0 && (
    { sortedLayers.map( ( layer ) => { - const layerData = layerTypes.find( ( l ) => l.type === layer.type ); - const formType = 'form' === layerData?.type ? layerData?.formType[ layer.form_type ?? 'gravity' ] : false; - const icon = formType ? formType?.icon : ( layerTypeIcons[ layer.type ] || layerData?.iconUrl || layerData?.icon ); - const layerText = formType ? formType?.layerText : ( layerData?.layerText || layerData?.title ); - - // Tooltip shown when the layer's required plugin/feature is unavailable. - const tooltipMessage = ( () => { - if ( formType && ! formType.isActive ) { - return formType.tooltipMessage; - } - if ( 'ad-server' === adServer && 'ad' === layerData?.type ) { - return layerData?.tooltipMessage; - } - if ( layerData?.isActive === false ) { - return layerData?.tooltipMessage ?? ''; + const layerType = getLayerType( layer.type ); + const variation = layerType?.variations.length ? getLayerVariation( layerType, layer ) : undefined; + const icon = variation?.icon || layerType?.iconUrl || layerType?.icon; + const layerText = variation?.title || layerType?.label || layerType?.title || layer.type; + + // Warning shown when the layer's type, variation or plugin is unavailable. + let tooltipMessage = ''; + let isLayerDisabled = false; + if ( ! layerType ) { + tooltipMessage = __( 'This layer needs an add-on that isn\'t active.', 'godam' ); + } else if ( variation && ! isVariationAvailable( variation ) ) { + tooltipMessage = variation.unavailableReason ?? ''; + isLayerDisabled = true; + } else { + const availability = getAvailability( layerType, availabilityContext ); + if ( ! availability.available ) { + tooltipMessage = availability.reason ?? ''; + isLayerDisabled = false !== availability.disablesExisting; } - return ''; - } )(); + } - const isLayerDisabled = ( formType && ! formType.isActive ) || layerData?.isActive === false; const isActive = currentLayer?.id === layer.id; - const hasImageIcon = formType || ( typeof icon === 'string' && icon ); + const hasImageIcon = typeof icon === 'string' && icon; return (
  • { hasImageIcon ? diff --git a/pages/video-editor/components/SidebarLayers.test.js b/pages/video-editor/components/SidebarLayers.test.js index 4b1cfc7ef4..9a286bb622 100644 --- a/pages/video-editor/components/SidebarLayers.test.js +++ b/pages/video-editor/components/SidebarLayers.test.js @@ -9,8 +9,11 @@ * gating (video needs a playhead position, images allow only some types); and * saved layers whose type has no registration. * - * Tests marked "current behaviour" pin something the refactor intends to change - * on purpose. Update them in the same PR that changes the behaviour. + * Since #2292 the editor reads layer types from the layer registry, so these + * tests register the core types and the add-on types from the old hooks the + * same way the editor's entry point does. Tests marked "current behaviour" pin + * something a later Layer API PR intends to change on purpose; update them in + * the PR that changes the behaviour. */ /** @@ -30,6 +33,7 @@ import { configureStore } from '@reduxjs/toolkit'; * Internal dependencies */ import SidebarLayers, { getDefaultLayerName } from './SidebarLayers'; +import { registerEditorLayerTypes } from '../layers'; // The real slice reads page globals at import time; only the action shapes matter here. jest.mock( '../redux/slice/videoSlice', () => ( { @@ -43,6 +47,14 @@ jest.mock( '../onboarding/productGuide', () => ( { notify: jest.fn() } ) ); jest.mock( 'uuid', () => ( { v4: () => 'test-uuid' } ) ); +// The core settings panels aren't rendered here; registering them is enough. +jest.mock( './layers/CTALayer', () => () => null ); +jest.mock( './layers/HotspotLayer', () => () => null ); +jest.mock( './layers/FormLayer', () => () => null ); +jest.mock( './layers/PollLayer', () => () => null ); +jest.mock( './layers/AdsLayer', () => () => null ); +jest.mock( '../utils/formUtils', () => ( { getFormIdFromLayer: () => null } ) ); + // Plain stand-ins for the menu primitives, so menu items are ordinary buttons // and the dropdown content is always rendered. jest.mock( '@wordpress/components', () => { @@ -64,13 +76,14 @@ jest.mock( '@wordpress/components', () => { }; } ); +registerEditorLayerTypes(); + const baseState = { loading: false, addLayerModalTime: null, layers: [], currentLayer: null, videoConfig: {}, - allowedLayerTypes: '*', mediaType: 'video', }; @@ -284,25 +297,34 @@ describe( 'Layer API contract: SidebarLayers', () => { expect( container.querySelector( '#add-layer-btn' ).disabled ).toBe( true ); } ); - // Current behaviour: the image allow-list names the Woo add-on (mediaCapabilities.js). - it( 'offers only the allowed types on an image, with no playhead needed', () => { - render( { currentTime: 0, state: { mediaType: 'image', allowedLayerTypes: [ 'hotspot', 'woo' ] } } ); + // Current behaviour: the Woo add-on supports images because the old-hooks + // bridge says so (layers/legacy.js); #2296 moves that into the add-on. + it( 'offers only the types that support images, with no playhead needed', () => { + render( { currentTime: 0, state: { mediaType: 'image' } } ); expect( container.querySelector( '#add-layer-btn' ).disabled ).toBe( false ); expect( menuKeys() ).toEqual( [ 'hotspot', 'woo' ] ); } ); } ); describe( 'saved layers', () => { - // Current behaviour: a layer whose type nothing registers is hidden from - // the list but kept in the editor state, so saving does not drop it. - it( 'hides a layer of an unregistered type but keeps it in state', () => { + // RFC D2: a layer whose type nothing registers stays listed with a + // warning, and stays in the editor state, so saving does not drop it. + it( 'lists a layer of an unregistered type with a warning and keeps it in state', () => { const ghost = { id: 'ghost', type: 'ghost', displayTime: 3 }; render( { state: { layers: [ ghost ] } } ); - expect( container.querySelectorAll( '.godam-ve-layer-row' ) ).toHaveLength( 0 ); + const rows = container.querySelectorAll( '.godam-ve-layer-row' ); + expect( rows ).toHaveLength( 1 ); + expect( rows[ 0 ].classList.contains( 'has-warning' ) ).toBe( true ); + expect( rows[ 0 ].querySelector( 'button' ).disabled ).toBe( false ); expect( container.textContent ).toContain( 'Layers (1)' ); expect( addedLayers() ).toEqual( [ ghost ] ); } ); + it( 'hides a layer whose registered type does not support this media', () => { + render( { state: { mediaType: 'image', layers: [ { id: 'c1', type: 'cta', displayTime: 0 } ] } } ); + expect( container.querySelectorAll( '.godam-ve-layer-row' ) ).toHaveLength( 0 ); + } ); + it( 'lists a layer of a registered add-on type', () => { render( { state: { layers: [ { id: 'a1', type: 'acme', displayTime: 3, name: 'Acme Layer' } ] } } ); expect( container.querySelectorAll( '.godam-ve-layer-row' ) ).toHaveLength( 1 ); diff --git a/pages/video-editor/components/layers/Layer.js b/pages/video-editor/components/layers/Layer.js index 10ce95034a..c94e82b60e 100644 --- a/pages/video-editor/components/layers/Layer.js +++ b/pages/video-editor/components/layers/Layer.js @@ -1,70 +1,31 @@ +/** + * External dependencies + */ +import { useDispatch } from 'react-redux'; +import { store as layersStore } from '@godam/layers'; + /** * WordPress dependencies */ import { __ } from '@wordpress/i18n'; import { Suspense } from '@wordpress/element'; +import { useSelect } from '@wordpress/data'; /** * Internal dependencies */ -import FormLayer from './FormLayer'; -import CTALayer from './CTALayer'; -import HotspotLayer from './HotspotLayer'; -import Ads from './AdsLayer'; -import PollLayer from './PollLayer'; import LayerErrorBoundary from './LayerErrorBoundary'; +import UnregisteredLayerNotice from './UnregisteredLayerNotice'; +import { LayerContext } from '../../layers/hooks'; +import { getLegacyEditComponent } from '../../layers/legacy'; +import { removeLayer } from '../../redux/slice/videoSlice'; /** - * Core Layer Components. - * Additional layer types can be registered via PHP filters. - */ -const coreLayerComponents = { - form: { - component: FormLayer, - }, - cta: { - component: CTALayer, - }, - hotspot: { - component: HotspotLayer, - }, - ad: { - component: Ads, - }, - poll: { - component: PollLayer, - }, -}; - -/** - * Get all registered layer components (core + PHP filtered). - * PHP filtered components are loaded from window.godamVideoEditorConfig and - * their actual components are loaded from window.godamLayerComponents. - * - * @return {Object} Object containing all registered layer components. - */ -const getLayerComponents = () => { - const components = { ...coreLayerComponents }; - - // Merge with PHP-filtered components (e.g., WooCommerce) - const phpComponents = window.godamVideoEditorConfig?.layerComponents || {}; - const loadedComponents = window.godamLayerComponents || {}; - - Object.keys( phpComponents ).forEach( ( key ) => { - const componentName = phpComponents[ key ]; - if ( loadedComponents[ componentName ] ) { - components[ key ] = { - component: loadedComponents[ componentName ], - }; - } - } ); - - return components; -}; - -/** - * Component to add the layer based on the type. + * The settings panel for the selected layer: its type's `edit` component from + * the layer registry. A panel an add-on names through the old + * `godam_video_editor_layer_components` hook still takes precedence. A layer + * whose type isn't registered gets a notice instead (RFC D2). * * @param {Object} param0 - Props for the Layer component. * @param {Object} param0.layer - The layer data containing type and associated metadata. @@ -74,22 +35,26 @@ const getLayerComponents = () => { * @return {JSX.Element} The rendered Layer component. */ const Layer = ( { layer, goBack, duration } ) => { - const LayerComponents = getLayerComponents(); - const layerType = layer?.type ?? 'cta'; - // Fall back to the CTA layer when the requested type has no registered component. - const Component = LayerComponents[ layerType ]?.component ?? LayerComponents.cta?.component; + const dispatch = useDispatch(); + const layerType = useSelect( ( select ) => select( layersStore ).getLayerType( layer?.type ), [ layer?.type ] ); + const Edit = getLegacyEditComponent( layer?.type ) ?? layerType?.edit; + + const handleDelete = () => { + dispatch( removeLayer( { id: layer.id } ) ); + goBack?.(); + }; - // The boundary wraps every return path (including the fallback) so no layer - // editor — core or add-on — can throw and white-screen the whole editor. + // The boundary wraps every return path so no layer editor — core or add-on — + // can throw and white-screen the whole editor. return ( - { __( 'Loading layer…', 'godam' ) }
}> - { Component ? ( - - ) : ( -
{ __( 'Error: No layer components registered', 'godam' ) }
- ) } - + + { __( 'Loading layer…', 'godam' ) }
}> + { Edit + ? + : } + + ); }; diff --git a/pages/video-editor/components/layers/Layer.test.js b/pages/video-editor/components/layers/Layer.test.js index 40f9f69bd0..9a4fcd13d4 100644 --- a/pages/video-editor/components/layers/Layer.test.js +++ b/pages/video-editor/components/layers/Layer.test.js @@ -3,8 +3,9 @@ * * Core types map to their own editors. An add-on type opens when PHP lists it in * `godamVideoEditorConfig.layerComponents` and the add-on's script put the named - * component on `window.godamLayerComponents`. Tests marked "current behaviour" - * pin something #2292 intends to change on purpose. + * component on `window.godamLayerComponents`. Since #2292 the panel comes from + * the layer registry, and a layer whose type has no panel gets a "needs an + * add-on" notice instead of the CTA editor (RFC D2). */ /** @@ -12,11 +13,14 @@ */ import { act } from 'react'; import { createRoot } from 'react-dom/client'; +import { Provider } from 'react-redux'; +import { configureStore } from '@reduxjs/toolkit'; /** * Internal dependencies */ import Layer from './Layer'; +import { registerCoreLayerTypes } from '../../layers/core'; // A function declaration, so it is hoisted along with the jest.mock() calls. function mockEditor( name ) { @@ -31,22 +35,45 @@ jest.mock( './CTALayer', () => mockEditor( 'cta' ) ); jest.mock( './HotspotLayer', () => mockEditor( 'hotspot' ) ); jest.mock( './AdsLayer', () => mockEditor( 'ad' ) ); jest.mock( './PollLayer', () => mockEditor( 'poll' ) ); +jest.mock( '../../utils/formUtils', () => ( { getFormIdFromLayer: () => null } ) ); + +// The real slice reads page globals at import time; only the action shapes matter here. +jest.mock( '../../redux/slice/videoSlice', () => ( { + removeLayer: ( payload ) => ( { type: 'removeLayer', payload } ), + updateLayerField: ( payload ) => ( { type: 'updateLayerField', payload } ), +} ) ); + +registerCoreLayerTypes(); describe( 'Layer API contract: Layer editor dispatch', () => { - let container, root; + let container, root, dispatched; const render = ( layer, props = {} ) => { + const store = configureStore( { + reducer: { + videoReducer: ( state = { layers: [ layer ] }, action ) => { + dispatched.push( action ); + return state; + }, + }, + } ); act( () => { - root.render( {} ) } duration={ 90 } /> ); + root.render( + + {} ) } duration={ 90 } /> + , + ); } ); }; const editor = () => container.querySelector( '[data-editor]' )?.dataset.editor; + const notice = () => container.querySelector( '[data-test-id="godam-video-editor-unregistered-layer"]' ); beforeEach( () => { global.IS_REACT_ACT_ENVIRONMENT = true; container = document.createElement( 'div' ); document.body.appendChild( container ); root = createRoot( container ); + dispatched = []; window.godamVideoEditorConfig = { layerComponents: {} }; window.godamLayerComponents = {}; } ); @@ -81,17 +108,27 @@ describe( 'Layer API contract: Layer editor dispatch', () => { expect( editor() ).toBe( 'better-cta' ); } ); - // Current behaviour: #2292 replaces this fallback with a "needs an add-on" notice. - it( 'falls back to the CTA editor when PHP lists a type whose component never loaded', () => { + it( 'shows the "needs an add-on" notice when PHP lists a type whose component never loaded', () => { window.godamVideoEditorConfig.layerComponents = { acme: 'AcmeLayer' }; render( { id: 'l4', type: 'acme' } ); - expect( editor() ).toBe( 'cta' ); + expect( editor() ).toBeUndefined(); + expect( notice() ).not.toBeNull(); } ); - // Current behaviour: #2292 replaces this fallback with a "needs an add-on" notice. - it( 'falls back to the CTA editor for an unregistered type', () => { + it( 'shows the "needs an add-on" notice for an unregistered type, never another type\'s editor', () => { render( { id: 'l5', type: 'ghost' } ); - expect( editor() ).toBe( 'cta' ); + expect( editor() ).toBeUndefined(); + expect( notice().textContent ).toContain( 'ghost' ); + } ); + + it( 'lets the notice delete the layer and go back', () => { + const goBack = jest.fn(); + render( { id: 'l6', type: 'ghost' }, { goBack } ); + + act( () => [ ...notice().querySelectorAll( 'button' ) ].find( ( b ) => b.textContent === 'Delete layer' ).click() ); + + expect( dispatched ).toContainEqual( { type: 'removeLayer', payload: { id: 'l6' } } ); + expect( goBack ).toHaveBeenCalled(); } ); it( 'shows the error notice, not a blank editor, when an add-on editor throws', () => { @@ -103,7 +140,7 @@ describe( 'Layer API contract: Layer editor dispatch', () => { }, }; - render( { id: 'l6', type: 'acme' } ); + render( { id: 'l7', type: 'acme' } ); expect( container.querySelector( '.godam-layer-error[role="alert"]' ) ).not.toBeNull(); consoleError.mockRestore(); diff --git a/pages/video-editor/components/layers/LayersHeader.js b/pages/video-editor/components/layers/LayersHeader.js index 25388acd5f..85ee425f23 100644 --- a/pages/video-editor/components/layers/LayersHeader.js +++ b/pages/video-editor/components/layers/LayersHeader.js @@ -16,7 +16,7 @@ import { __, sprintf } from '@wordpress/i18n'; * Internal dependencies */ import { updateLayerField, removeLayer } from '../../redux/slice/videoSlice'; -import { layerTypes } from '../SidebarLayers'; +import { getLayerType, getLayerVariation } from '@godam/layers'; /** * Header for the selected layer's configuration panel: an editable layer name, @@ -42,12 +42,9 @@ const LayersHeader = ( { layer, goBack, layerName: customLayerName } ) => { /** * Resolve the layer type label (e.g. "CTA", or the specific form integration). */ - const layerTypeData = layerTypes.find( ( l ) => l.type === layer.type ); - const typeLabel = customLayerName || ( - 'form' === layer.type - ? layerTypeData?.formType[ layer?.form_type ?? 'gravity' ]?.layerText - : layerTypeData?.layerText - ) || ''; + const layerType = getLayerType( layer.type ); + const variation = layerType?.variations.length ? getLayerVariation( layerType, layer ) : undefined; + const typeLabel = customLayerName || variation?.title || layerType?.label || ''; const handleDeleteLayer = () => { dispatch( removeLayer( { id: layer.id } ) ); diff --git a/pages/video-editor/components/layers/UnregisteredLayerNotice.js b/pages/video-editor/components/layers/UnregisteredLayerNotice.js new file mode 100644 index 0000000000..ed7c2401c7 --- /dev/null +++ b/pages/video-editor/components/layers/UnregisteredLayerNotice.js @@ -0,0 +1,39 @@ +/** + * WordPress dependencies + */ +import { __ } from '@wordpress/i18n'; +import { Button } from '@wordpress/components'; + +/** + * Shown instead of a settings panel when a saved layer's type isn't registered, + * usually because the add-on that provides it isn't active. The layer is kept + * as it was, and can only be deleted (RFC D2). + * + * @param {Object} props Props. + * @param {Object} props.layer The saved layer. + * @param {Function} props.goBack Return to the layer list. + * @param {Function} props.onDelete Delete the layer. + * @return {JSX.Element} The notice. + */ +const UnregisteredLayerNotice = ( { layer, goBack, onDelete } ) => ( +
+

+ { __( 'This layer needs an add-on that isn\'t active. It is kept as it was; activate the add-on to edit it, or delete it.', 'godam' ) } +

+

+ { layer?.type } +

+ { onDelete && ( + + ) } + { goBack && ( + + ) } +
+); + +export default UnregisteredLayerNotice; diff --git a/pages/video-editor/components/timeline/Timeline.js b/pages/video-editor/components/timeline/Timeline.js index d252bf991a..7178514f1e 100644 --- a/pages/video-editor/components/timeline/Timeline.js +++ b/pages/video-editor/components/timeline/Timeline.js @@ -13,6 +13,7 @@ */ import { useEffect, useRef, useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; +import { getLayerType, getLayerVariation, store as layersStore } from '@godam/layers'; /** * WordPress dependencies @@ -20,11 +21,11 @@ import { useDispatch, useSelector } from 'react-redux'; import { plus } from '@wordpress/icons'; import { __ } from '@wordpress/i18n'; import { Icon } from '@wordpress/components'; +import { useSelect } from '@wordpress/data'; /** * Internal dependencies */ -import { layerTypes, FORM_PLUGIN_META, LAYER_TYPE_COLORS } from '../../utils/layerTypes'; import { setCurrentLayer, setAddLayerModalTime, updateLayerField } from '../../redux/slice/videoSlice'; import { notify as notifyGuide } from '../../onboarding/productGuide'; @@ -32,26 +33,6 @@ import { notify as notifyGuide } from '../../onboarding/productGuide'; // admin theme colour, falling back to the GoDAM purple from the design). const TIMELINE_ACCENT = 'var(--wp-components-color-accent, var(--wp-admin-theme-color, #5d31ff))'; -/** - * Shopping-cart glyph (white line art) for commerce layer markers. - * `@wordpress/icons` ships no cart icon, so it's defined inline here. - * - * @return {JSX.Element} Cart SVG. - */ -const CartIcon = () => ( - -); - -// Per-type marker icon override. Takes precedence over a layer type's WordPress -// icon or add-on `iconUrl` (e.g. the WooCommerce layer shows a cart, not a logo). -const LAYER_MARKER_ICONS = { - woo: CartIcon, -}; - const Slider = ( props ) => { const { max, value, onChange, className, layers, onLayerSelect, disabled, currentLayerID, chapters, formatTimeForInput, onInteract, onAddLayer, onLayerDrag } = props; @@ -335,22 +316,23 @@ const Slider = ( props ) => { layerLeft = ( layer.displayTime / max ) * 100; } - const layerType = layerTypes.find( ( type ) => type.type === layer.type ); + const layerType = getLayerType( layer.type ); const isActive = layer.id === currentLayerID; - const markerColor = LAYER_TYPE_COLORS[ layer.type ] || TIMELINE_ACCENT; - // Form layers resolve to their specific plugin (icon + name) so the - // chip shows e.g. "WPForms" with the WPForms logo on a white chip. - const formMeta = layer.type === 'form' ? FORM_PLUGIN_META[ layer.form_type ] : null; + const markerColor = layerType?.color || TIMELINE_ACCENT; + // Layers with a variation (e.g. a form plugin) show it (icon + name), + // so the chip reads e.g. "WPForms" with the WPForms logo on a white chip. + const variation = layerType?.variations.length ? getLayerVariation( layerType, layer ) : undefined; + const variationIcon = typeof variation?.icon === 'string' ? variation.icon : null; // Timeline chips identify the layer by its type (e.g. "Hotspot"), // not its custom name — the sidebar already shows the custom name. - const markerName = formMeta?.name || layerType?.title || layer.name || layer?.type; + const markerName = variation?.title || layerType?.title || layer.name || layer?.type; const markerTime = formatTime( isBeingDragged ? ( dragPosition / 100 ) * max : layer.displayTime ); return ( // eslint-disable-next-line jsx-a11y/click-events-have-key-events
{
{ ( () => { - if ( formMeta?.icon ) { - return {; + if ( variationIcon ) { + return {; } - const OverrideIcon = LAYER_MARKER_ICONS[ layer.type ]; - if ( OverrideIcon ) { - return ; + // A marker-specific icon wins over the type's icon or add-on + // `iconUrl` (e.g. the WooCommerce layer shows a cart, not a logo). + const MarkerIcon = layerType?.markerIcon; + if ( MarkerIcon ) { + return ; } if ( layerType?.iconUrl ) { return {; @@ -512,6 +496,8 @@ const Slider = ( props ) => { const Timeline = ( { currentTime, duration, onSeek, formatTimeForInput } ) => { const dispatch = useDispatch(); const allLayers = useSelector( ( state ) => state.videoReducer.layers ); + // Layer types come from the registry; add-ons can register after the editor loads. + const layerTypes = useSelect( ( select ) => select( layersStore ).getLayerTypes(), [] ); const chapters = useSelector( ( state ) => state.videoReducer.chapters ); const currentLayer = useSelector( ( state ) => state.videoReducer.currentLayer ); const currentTab = useSelector( ( state ) => state.videoReducer.currentTab ); @@ -542,11 +528,12 @@ const Timeline = ( { currentTime, duration, onSeek, formatTimeForInput } ) => { ); } - // Exclude layers whose type isn't known (e.g. added in another branch/version) - // so they don't appear on the seeker. - const layers = allLayers.filter( - ( layer ) => layerTypes.some( ( lt ) => lt.type === layer.type ), - ); + // Exclude layers whose type isn't registered (e.g. its add-on is inactive) or + // doesn't sit on a timeline, so they don't appear on the seeker. + const layers = allLayers.filter( ( layer ) => { + const layerType = layerTypes.find( ( lt ) => lt.name === layer.type ); + return layerType && false !== layerType.supports.timeline; + } ); return ( () => null ); +jest.mock( '../layers/HotspotLayer', () => () => null ); +jest.mock( '../layers/FormLayer', () => () => null ); +jest.mock( '../layers/PollLayer', () => () => null ); +jest.mock( '../layers/AdsLayer', () => () => null ); +jest.mock( '../../utils/formUtils', () => ( { getFormIdFromLayer: () => null } ) ); +jest.mock( '../../onboarding/productGuide', () => ( { notify: jest.fn() } ) ); +jest.mock( '../../redux/slice/videoSlice', () => ( { + setCurrentLayer: ( payload ) => ( { type: 'setCurrentLayer', payload } ), + setAddLayerModalTime: ( payload ) => ( { type: 'setAddLayerModalTime', payload } ), + updateLayerField: ( payload ) => ( { type: 'updateLayerField', payload } ), +} ) ); + +window.godamVideoEditorConfig = { + layerOptions: [ { type: 'woo', title: 'WooCommerce', layerText: 'WooCommerce', iconUrl: 'woo.svg' } ], +}; +registerEditorLayerTypes(); +registerLayerType( { name: 'acme/countdown', title: 'Countdown', color: '#123456', icon: 'https://example.com/clock.svg' } ); +registerLayerType( { name: 'acme/hidden', title: 'Hidden', supports: { timeline: false } } ); + +describe( 'Layer API: timeline markers', () => { + let container, root; + + const render = ( layers ) => { + const store = configureStore( { + reducer: { + videoReducer: ( state = { layers, chapters: [], currentLayer: null, currentTab: 'layers' } ) => state, + }, + } ); + act( () => { + root.render( + + {} } formatTimeForInput={ ( t ) => String( t ) } /> + , + ); + } ); + }; + const markers = () => [ ...container.querySelectorAll( '.godam-ve-timeline__marker' ) ]; + const label = ( marker ) => marker.querySelector( '.godam-ve-timeline__chip-label' ).textContent; + + beforeEach( () => { + global.IS_REACT_ACT_ENVIRONMENT = true; + container = document.createElement( 'div' ); + document.body.appendChild( container ); + root = createRoot( container ); + } ); + + afterEach( () => { + act( () => root.unmount() ); + container.remove(); + } ); + + it( 'labels each marker with its type title and colour', () => { + render( [ + { id: 'c', type: 'cta', displayTime: 10 }, + { id: 'a', type: 'acme/countdown', displayTime: 20 }, + ] ); + + const [ cta, countdown ] = markers(); + expect( label( cta ) ).toBe( 'CTA · 0:10' ); + expect( cta.style.getPropertyValue( '--marker-color' ) ).toBe( '#3858e9' ); + expect( label( countdown ) ).toBe( 'Countdown · 0:20' ); + expect( countdown.style.getPropertyValue( '--marker-color' ) ).toBe( '#123456' ); + expect( countdown.querySelector( 'img' ).getAttribute( 'src' ) ).toBe( 'https://example.com/clock.svg' ); + } ); + + it( 'shows a form layer\'s form plugin, Marketo and HubSpot included', () => { + render( [ + { id: 'f1', type: 'form', form_type: 'wpforms', displayTime: 5 }, + { id: 'f2', type: 'form', form_type: 'marketo', displayTime: 15 }, + ] ); + + const [ wpforms, marketo ] = markers(); + expect( label( wpforms ) ).toBe( 'WPForms · 0:05' ); + expect( wpforms.classList.contains( 'godam-ve-timeline__marker--form' ) ).toBe( true ); + expect( label( marketo ) ).toBe( 'Marketo · 0:15' ); + expect( marketo.querySelector( 'img' ) ).not.toBeNull(); + } ); + + it( 'uses a type\'s marker icon over its icon URL (the Woo cart)', () => { + render( [ { id: 'w', type: 'woo', displayTime: 30 } ] ); + const [ woo ] = markers(); + expect( woo.querySelector( 'img' ) ).toBeNull(); + expect( woo.querySelector( 'svg circle' ) ).not.toBeNull(); + } ); + + it( 'leaves out unregistered types and types that opt out of the timeline', () => { + render( [ + { id: 'c', type: 'cta', displayTime: 10 }, + { id: 'g', type: 'ghost', displayTime: 20 }, + { id: 'h', type: 'acme/hidden', displayTime: 30 }, + ] ); + expect( markers().map( label ) ).toEqual( [ 'CTA · 0:10' ] ); + } ); +} ); diff --git a/pages/video-editor/config/mediaCapabilities.js b/pages/video-editor/config/mediaCapabilities.js index bb5860bfc9..e4e4597502 100644 --- a/pages/video-editor/config/mediaCapabilities.js +++ b/pages/video-editor/config/mediaCapabilities.js @@ -12,7 +12,6 @@ * `mediaType` — 'video' | 'audio' | 'image'. * `tabs` — ordered left-rail tab names; also the allow-list validating `setCurrentTab`. * `defaultTab` — tab selected when the editor opens for this media type. - * `allowedLayerTypes` — `'*'` for every registered layer type, or an array of layer `type` strings to restrict the "Add layer" menu (`[]` disables layers). * `preview` — discriminator the editor maps to a preview component (`'videojs'` → VideoJSPlayer, `'audio'` → AudioCardPreview, `'image'` → ImagePreview). Components are not stored here to keep this module free of React/store imports. * `copyBlockName` — Gutenberg block emitted by the Copy action. * `previewPage` — `godam_page` query value for the front-end Preview link. @@ -39,7 +38,6 @@ const CAPABILITIES = { mediaType: 'video', tabs: [ 'layers', 'player-settings', 'transcription', 'chapters' ], defaultTab: 'layers', - allowedLayerTypes: '*', preview: 'videojs', copyBlockName: 'godam/video', previewPage: 'video-preview', @@ -51,7 +49,6 @@ const CAPABILITIES = { mediaType: 'audio', tabs: [ 'transcription', 'chapters' ], defaultTab: 'transcription', - allowedLayerTypes: [], preview: 'audio', copyBlockName: 'godam/audio', // Audio reuses the shared front-end preview page (`godam_page=video-preview`), @@ -63,15 +60,14 @@ const CAPABILITIES = { showTimeline: false, showStats: false, }, - // Image editor — Hotspot + WooCommerce (product) hotspot layers placed - // spatially on a static image. The restricted `allowedLayerTypes` set falls - // out through the add menu without touching the core layer arrays. Copy and - // Preview are enabled: the `godam/image` front-end block exists (Iteration 2). + // Image editor — layers placed spatially on a static image. Which layer + // types it offers comes from each type's `supports.media` (Hotspot, and the + // WooCommerce product hotspot). Copy and Preview are enabled: the + // `godam/image` front-end block exists (Iteration 2). image: { mediaType: 'image', tabs: [ 'layers' ], defaultTab: 'layers', - allowedLayerTypes: [ 'hotspot', 'woo' ], preview: 'image', copyBlockName: 'godam/image', // Images reuse the shared front-end preview page (`godam_page=video-preview`), @@ -123,18 +119,3 @@ export function getCapability( mediaType ) { export function getCapabilityForMime( mimeType ) { return getCapability( getMediaTypeFromMime( mimeType ) ); } - -/** - * Filter a layer-type array by a capability's `allowedLayerTypes`. `'*'` (or a - * non-array) returns the list unchanged, so video is unaffected. - * - * @param {Array} types Layer-type descriptors (each with a `type`). - * @param {string|Array} allowedLayerTypes `'*'` or an array of allowed `type` strings. - * @return {Array} The filtered list. - */ -export function filterLayerTypesByCapability( types, allowedLayerTypes ) { - if ( allowedLayerTypes === '*' || ! Array.isArray( allowedLayerTypes ) ) { - return types; - } - return types.filter( ( lt ) => allowedLayerTypes.includes( lt.type ) ); -} diff --git a/pages/video-editor/index.js b/pages/video-editor/index.js index a881220028..a985bea1f0 100644 --- a/pages/video-editor/index.js +++ b/pages/video-editor/index.js @@ -25,6 +25,8 @@ import { import FontAwesomeIconPicker from './components/hotspot/FontAwesomeIconPicker'; import ColorPickerButton from './components/shared/color-picker/ColorPickerButton.jsx'; import { formatClock, parseClock } from './utils/time'; +import { registerEditorLayerTypes } from './layers'; +import { useLayer, useLayerAttributes } from './layers/hooks'; window.godamVideoEditorComponents = { ...( window.godamVideoEditorComponents || {} ), @@ -50,6 +52,30 @@ window.godamVideoEditorUtils = { parseClock, }; +// Layer API (#2292): hooks and controls for layer settings panels, imported by +// add-ons as `@godam/layer-editor` (script handle `godam-layer-editor`). +window.godam = window.godam || {}; +window.godam.layerEditor = { + ...( window.godam.layerEditor || {} ), + useLayer, + useLayerAttributes, + LayerCanvas: LayerControls, + LayersHeader, + VeSection, + VeTextInput, + VeSegmented, + VeColorList, + VeRadioGroup, + FontAwesomeIconPicker, + ColorPickerButton, + formatClock, + parseClock, +}; + +// Core layer types, then add-on types described through the old PHP hooks. +// Add-ons on the Layer API register themselves through `window.godam.layers`. +registerEditorLayerTypes(); + const Index = () => { return ( diff --git a/pages/video-editor/index.test.js b/pages/video-editor/index.test.js index 003b3b6197..27ea7a8ed9 100644 --- a/pages/video-editor/index.test.js +++ b/pages/video-editor/index.test.js @@ -13,6 +13,8 @@ jest.mock( './redux/store', () => ( {} ) ); jest.mock( './App', () => () => null ); jest.mock( './redux/slice/videoSlice', () => ( { updateLayerField: jest.fn() } ) ); jest.mock( './utils/time', () => ( { formatClock: jest.fn(), parseClock: jest.fn() } ) ); +jest.mock( './layers', () => ( { registerEditorLayerTypes: jest.fn() } ) ); +jest.mock( './layers/hooks', () => ( { useLayer: jest.fn(), useLayerAttributes: jest.fn() } ) ); // A function declaration, so it is hoisted along with the jest.mock() calls. function mockComponent() { @@ -64,6 +66,19 @@ describe( 'Layer API contract: editor globals for add-ons', () => { expect( window.godamVideoEditorUtils.parseClock ).toBe( time.parseClock ); } ); + it( 'exposes the layer editor hooks and controls on window.godam.layerEditor', () => { + const hooks = require( './layers/hooks' ); + const { layerEditor } = window.godam; + expect( layerEditor.useLayer ).toBe( hooks.useLayer ); + expect( layerEditor.useLayerAttributes ).toBe( hooks.useLayerAttributes ); + [ 'LayerCanvas', 'LayersHeader', 'VeSection', 'VeTextInput', 'VeSegmented', 'VeColorList', 'VeRadioGroup', 'FontAwesomeIconPicker', 'ColorPickerButton' ] + .forEach( ( name ) => expect( typeof layerEditor[ name ] ).toBe( 'function' ) ); + } ); + + it( 'registers the editor\'s layer types before rendering', () => { + expect( require( './layers' ).registerEditorLayerTypes ).toHaveBeenCalledTimes( 1 ); + } ); + it( 'keeps entries an add-on already put on those globals', () => { expect( window.godamVideoEditorComponents.AddonControl ).toBe( 'kept' ); expect( window.godamVideoEditorActions.addonAction ).toBe( 'kept' ); diff --git a/pages/video-editor/layers/core/ad.js b/pages/video-editor/layers/core/ad.js new file mode 100644 index 0000000000..044e47c29d --- /dev/null +++ b/pages/video-editor/layers/core/ad.js @@ -0,0 +1,27 @@ +/** + * WordPress dependencies + */ +import { __ } from '@wordpress/i18n'; +import { video } from '@wordpress/icons'; + +/** + * Internal dependencies + */ +import metadata from '../../../../assets/src/layers/ad/layer.json'; +import AdsLayer from '../../components/layers/AdsLayer'; + +export { metadata }; + +export const settings = { + title: __( 'Ad', 'godam' ), + description: __( 'Insert an advertisement', 'godam' ), + icon: video, + edit: AdsLayer, + // With an ad server configured its ads win, so no new Ad layers. Existing + // ones stay editable and show the warning. + getAvailability: ( { videoConfig } = {} ) => ( + 'ad-server' === videoConfig?.adServer + ? { available: false, reason: __( 'This ad will be overridden by Ad server\'s ads', 'godam' ), disablesExisting: false } + : null + ), +}; diff --git a/pages/video-editor/layers/core/cta.js b/pages/video-editor/layers/core/cta.js new file mode 100644 index 0000000000..17e47a99d5 --- /dev/null +++ b/pages/video-editor/layers/core/cta.js @@ -0,0 +1,20 @@ +/** + * WordPress dependencies + */ +import { __ } from '@wordpress/i18n'; + +/** + * Internal dependencies + */ +import metadata from '../../../../assets/src/layers/cta/layer.json'; +import CTALayer from '../../components/layers/CTALayer'; +import { CtaLayerIcon } from '../../components/editor-shell/icons'; + +export { metadata }; + +export const settings = { + title: __( 'CTA', 'godam' ), + description: __( 'Add a clickable button', 'godam' ), + icon: CtaLayerIcon, + edit: CTALayer, +}; diff --git a/pages/video-editor/layers/core/form.js b/pages/video-editor/layers/core/form.js new file mode 100644 index 0000000000..b2ffa1e656 --- /dev/null +++ b/pages/video-editor/layers/core/form.js @@ -0,0 +1,99 @@ +/** + * The Form layer. Each form plugin is a variation that sets `form_type`; #2293 + * turns these into separately registered providers. + */ + +/** + * WordPress dependencies + */ +import { __ } from '@wordpress/i18n'; + +/** + * Internal dependencies + */ +import metadata from '../../../../assets/src/layers/form/layer.json'; +import FormLayer from '../../components/layers/FormLayer'; +import { FormLayerIcon } from '../../components/editor-shell/icons'; +import { getFormIdFromLayer } from '../../utils/formUtils'; +import GFIcon from '../../assets/layers/GFIcon.svg'; +import WPFormsIcon from '../../assets/layers/WPForms-Mascot.svg'; +import EverestFormsIcon from '../../assets/layers/EverestFormsIcon.svg'; +import CF7Icon from '../../assets/layers/CF7Icon.svg'; +import JetpackIcon from '../../assets/layers/JetpackIcon.svg'; +import SureformsIcon from '../../assets/layers/SureFormsIcons.svg'; +import ForminatorIcon from '../../assets/layers/Forminator.png'; +import FluentFormsIcon from '../../assets/layers/FluentFormsIcon.png'; +import NinjaFormsIcon from '../../assets/layers/NinjaFormsIcon.png'; +import MetformIcon from '../../assets/layers/MetFormIcon.png'; +import MarketoIcon from '../../assets/layers/MarketoIcon.svg'; +import HubSpotIcon from '../../assets/layers/HubSpotIcon.svg'; + +export { metadata }; + +/** + * A form-plugin variation. Availability is read when asked, not at import, so + * page data localized after this module loads still counts. + * + * @param {string} name The `form_type` value. + * @param {string} title Display name. + * @param {string} icon Icon URL. + * @param {Function} isAvailable Whether the form plugin can be used. + * @param {string|Function} reason Why it can't, shown as a tooltip. + * @return {Object} The variation. + */ +const provider = ( name, title, icon, isAvailable, reason ) => ( { + name, + title, + icon, + attributes: { form_type: name }, + isAvailable, + get unavailableReason() { + return typeof reason === 'function' ? reason() : reason; + }, +} ); + +const flag = ( key ) => () => Boolean( window?.videoData?.[ key ] ); + +const hubspotReason = () => { + // Say what actually unblocks the layer: turning the integration on, or + // connecting the source the admin chose (GoDAM Central by default, where + // activating the HubSpot plugin alone is not enough). + if ( window?.videoData?.hubspotEnabled === false ) { + return __( 'Turn on HubSpot in Settings → Integrations → HubSpot to use this form', 'godam' ); + } + return 'leadin' === ( window?.videoData?.hubspotChosenSource ?? 'central' ) + ? __( 'Activate and connect the HubSpot plugin to use this form', 'godam' ) + : __( 'Connect HubSpot in Settings → Integrations → HubSpot to use this form', 'godam' ); +}; + +const variations = [ + { ...provider( 'gravity', __( 'Gravity Forms', 'godam' ), GFIcon, flag( 'gfActive' ), __( 'Gravity Forms plugin is not active', 'godam' ) ), isDefault: true }, + provider( 'wpforms', __( 'WPForms', 'godam' ), WPFormsIcon, flag( 'wpformsActive' ), __( 'WPForms plugin is not active', 'godam' ) ), + provider( 'cf7', __( 'Contact Form 7', 'godam' ), CF7Icon, flag( 'cf7Active' ), __( 'Contact Form 7 plugin is not active', 'godam' ) ), + provider( 'jetpack', __( 'Jetpack Forms', 'godam' ), JetpackIcon, flag( 'jetpackActive' ), __( 'Jetpack plugin is not active', 'godam' ) ), + provider( 'sureforms', __( 'SureForms', 'godam' ), SureformsIcon, flag( 'sureformsActive' ), __( 'SureForms plugin is not active', 'godam' ) ), + provider( 'forminator', __( 'Forminator Forms', 'godam' ), ForminatorIcon, flag( 'forminatorActive' ), __( 'Forminator Forms plugin is not active', 'godam' ) ), + provider( 'fluentforms', __( 'Fluent Forms', 'godam' ), FluentFormsIcon, flag( 'fluentformsActive' ), __( 'Fluent Forms plugin is not active', 'godam' ) ), + provider( 'everestforms', __( 'Everest Forms', 'godam' ), EverestFormsIcon, flag( 'everestFormsActive' ), __( 'Everest Forms plugin is not active', 'godam' ) ), + provider( 'ninjaforms', __( 'Ninja Forms', 'godam' ), NinjaFormsIcon, flag( 'ninjaFormsActive' ), __( 'Ninja Forms plugin is not active', 'godam' ) ), + provider( 'metform', __( 'MetForm', 'godam' ), MetformIcon, flag( 'metformActive' ), __( 'MetForm plugin is not active', 'godam' ) ), + // Marketo has no plugin to activate: it is always offered. Its settings panel + // links to Settings → Integrations → Marketo when credentials are missing. + provider( 'marketo', __( 'Marketo', 'godam' ), MarketoIcon, () => true, '' ), + provider( 'hubspot', __( 'HubSpot', 'godam' ), HubSpotIcon, flag( 'hubspotActive' ), hubspotReason ), +]; + +export const settings = { + title: __( 'Form', 'godam' ), + description: __( 'Embed a lead form', 'godam' ), + icon: FormLayerIcon, + edit: FormLayer, + variations, + getAvailability: () => ( + variations.some( ( variation ) => variation.isAvailable() ) + ? null + : { available: false, reason: __( 'No form plugin is active', 'godam' ) } + ), + // A form layer can't be saved until a form is picked. + validate: ( layer ) => Boolean( getFormIdFromLayer( layer, layer.form_type ) ), +}; diff --git a/pages/video-editor/layers/core/hotspot.js b/pages/video-editor/layers/core/hotspot.js new file mode 100644 index 0000000000..5eb4d47e76 --- /dev/null +++ b/pages/video-editor/layers/core/hotspot.js @@ -0,0 +1,20 @@ +/** + * WordPress dependencies + */ +import { __ } from '@wordpress/i18n'; + +/** + * Internal dependencies + */ +import metadata from '../../../../assets/src/layers/hotspot/layer.json'; +import HotspotLayer from '../../components/layers/HotspotLayer'; +import { HotspotLayerIcon } from '../../components/editor-shell/icons'; + +export { metadata }; + +export const settings = { + title: __( 'Hotspot', 'godam' ), + description: __( 'Add an info hotspot', 'godam' ), + icon: HotspotLayerIcon, + edit: HotspotLayer, +}; diff --git a/pages/video-editor/layers/core/index.js b/pages/video-editor/layers/core/index.js new file mode 100644 index 0000000000..3728dd1358 --- /dev/null +++ b/pages/video-editor/layers/core/index.js @@ -0,0 +1,28 @@ +/** + * GoDAM's own layer types, registered through the same API as add-ons. + * Registration order is the "Add layer" menu order. + */ + +/** + * External dependencies + */ +import { registerLayerType, getLayerType } from '@godam/layers'; + +/** + * Internal dependencies + */ +import * as cta from './cta'; +import * as hotspot from './hotspot'; +import * as form from './form'; +import * as poll from './poll'; +import * as ad from './ad'; + +export const coreLayerTypes = [ cta, hotspot, form, poll, ad ]; + +export function registerCoreLayerTypes() { + coreLayerTypes.forEach( ( { metadata, settings } ) => { + if ( ! getLayerType( metadata.name ) ) { + registerLayerType( metadata, settings ); + } + } ); +} diff --git a/pages/video-editor/layers/core/poll.js b/pages/video-editor/layers/core/poll.js new file mode 100644 index 0000000000..b2a292600b --- /dev/null +++ b/pages/video-editor/layers/core/poll.js @@ -0,0 +1,25 @@ +/** + * WordPress dependencies + */ +import { __ } from '@wordpress/i18n'; + +/** + * Internal dependencies + */ +import metadata from '../../../../assets/src/layers/poll/layer.json'; +import PollLayer from '../../components/layers/PollLayer'; +import { PollLayerIcon } from '../../components/editor-shell/icons'; + +export { metadata }; + +export const settings = { + title: __( 'Poll', 'godam' ), + description: __( 'Create an interactive poll', 'godam' ), + icon: PollLayerIcon, + edit: PollLayer, + getAvailability: () => ( + window?.easydamMediaLibrary?.isPollPluginActive + ? null + : { available: false, reason: __( 'Poll plugin is not active', 'godam' ) } + ), +}; diff --git a/pages/video-editor/layers/hooks.js b/pages/video-editor/layers/hooks.js new file mode 100644 index 0000000000..076112f44c --- /dev/null +++ b/pages/video-editor/layers/hooks.js @@ -0,0 +1,64 @@ +/** + * Hooks for layer settings panels, core and add-on alike. Exposed to add-ons + * on `window.godam.layerEditor`, so they never import react-redux or read the + * editor's store shape. + */ + +/** + * External dependencies + */ +import { useDispatch, useSelector } from 'react-redux'; + +/** + * WordPress dependencies + */ +import { createContext, useCallback, useContext } from '@wordpress/element'; + +/** + * Internal dependencies + */ +import { updateLayerField } from '../redux/slice/videoSlice'; + +const MANAGED_KEYS = [ 'id', 'type' ]; + +/** + * The id of the layer whose settings panel is open. + */ +export const LayerContext = createContext( null ); + +/** + * The layer whose settings panel is open, or the one with this id. + * + * @param {string} [layerId] Layer id; defaults to the open layer. + * @return {Object|undefined} The layer. + */ +export function useLayer( layerId ) { + const contextId = useContext( LayerContext ); + const id = layerId ?? contextId; + return useSelector( ( state ) => state.videoReducer.layers.find( ( layer ) => layer.id === id ) ); +} + +/** + * The open layer and a setter that merges attribute changes into it. + * + * @param {string} [layerId] Layer id; defaults to the open layer. + * @return {Array} `[ layer, setAttributes( changes ) ]`. + */ +export function useLayerAttributes( layerId ) { + const layer = useLayer( layerId ); + const dispatch = useDispatch(); + const id = layer?.id; + + const setAttributes = useCallback( ( changes ) => { + if ( ! id || ! changes ) { + return; + } + Object.entries( changes ).forEach( ( [ field, value ] ) => { + if ( ! MANAGED_KEYS.includes( field ) ) { + dispatch( updateLayerField( { id, field, value } ) ); + } + } ); + }, [ dispatch, id ] ); + + return [ layer, setAttributes ]; +} diff --git a/pages/video-editor/layers/index.js b/pages/video-editor/layers/index.js new file mode 100644 index 0000000000..6fe06900ee --- /dev/null +++ b/pages/video-editor/layers/index.js @@ -0,0 +1,16 @@ +/** + * Register every layer type the editor knows: GoDAM's own, then those add-ons + * described through the old hooks. Add-ons on the Layer API register + * themselves through `window.godam.layers.registerLayerType()`. + */ + +/** + * Internal dependencies + */ +import { registerCoreLayerTypes } from './core'; +import { registerLegacyLayerTypes } from './legacy'; + +export function registerEditorLayerTypes() { + registerCoreLayerTypes(); + registerLegacyLayerTypes(); +} diff --git a/pages/video-editor/layers/layers.test.js b/pages/video-editor/layers/layers.test.js new file mode 100644 index 0000000000..0068b4e0d0 --- /dev/null +++ b/pages/video-editor/layers/layers.test.js @@ -0,0 +1,247 @@ +/** + * Layer API (#2292): the editor's core layer types, the bridge from the old + * add-on hooks, and the hooks settings panels use. + */ + +/** + * External dependencies + */ +import { act } from 'react'; +import { createRoot } from 'react-dom/client'; +import { Provider } from 'react-redux'; +import { configureStore } from '@reduxjs/toolkit'; +import { + getLayerType, + getLayerTypes, + unregisterLayerType, + getAvailability, + getDefaultAttributes, + getLayerVariation, + supportsMedia, +} from '@godam/layers'; + +/** + * Internal dependencies + */ +import { registerEditorLayerTypes } from './index'; +import { getLegacyEditComponent } from './legacy'; +import { LayerContext, useLayer, useLayerAttributes } from './hooks'; +import { getFormIdFromLayer } from '../utils/formUtils'; + +jest.mock( '../components/layers/CTALayer', () => function CTALayer() {} ); +jest.mock( '../components/layers/HotspotLayer', () => function HotspotLayer() {} ); +jest.mock( '../components/layers/FormLayer', () => function FormLayer() {} ); +jest.mock( '../components/layers/PollLayer', () => function PollLayer() {} ); +jest.mock( '../components/layers/AdsLayer', () => function AdsLayer() {} ); +jest.mock( '../utils/formUtils', () => ( { getFormIdFromLayer: jest.fn() } ) ); +jest.mock( '../redux/slice/videoSlice', () => ( { + updateLayerField: ( payload ) => ( { type: 'updateLayerField', payload } ), +} ) ); + +const resetRegistry = () => getLayerTypes().forEach( ( { name } ) => unregisterLayerType( name ) ); + +describe( 'Layer API: core layer types', () => { + beforeAll( () => { + window.videoData = { gfActive: true }; + window.easydamMediaLibrary = { isPollPluginActive: false }; + window.godamVideoEditorConfig = {}; + registerEditorLayerTypes(); + } ); + + afterAll( resetRegistry ); + + it( 'registers the five core types in "Add layer" menu order', () => { + expect( getLayerTypes().map( ( { name } ) => name ) ).toEqual( [ 'cta', 'hotspot', 'form', 'poll', 'ad' ] ); + } ); + + it( 'gives each core type its panel, colour and translated title', () => { + expect( getLayerType( 'cta' ) ).toMatchObject( { title: 'CTA', color: '#3858e9', edit: expect.any( Function ) } ); + expect( getLayerType( 'hotspot' ).edit.name ).toBe( 'HotspotLayer' ); + expect( getLayerType( 'ad' ).description ).toBe( 'Insert an advertisement' ); + } ); + + it( 'puts Hotspot on images and every other core type on video only', () => { + expect( supportsMedia( getLayerType( 'hotspot' ), 'image' ) ).toBe( true ); + [ 'cta', 'form', 'poll', 'ad' ].forEach( ( name ) => expect( supportsMedia( getLayerType( name ), 'image' ) ).toBe( false ) ); + } ); + + it( 'is safe to register twice', () => { + const error = jest.spyOn( console, 'error' ).mockImplementation( () => {} ); + registerEditorLayerTypes(); + expect( error ).not.toHaveBeenCalled(); + expect( getLayerTypes() ).toHaveLength( 5 ); + error.mockRestore(); + } ); + + it( 'offers one form variation per form plugin, Gravity Forms by default', () => { + const form = getLayerType( 'form' ); + expect( form.variations.map( ( { name } ) => name ) ).toEqual( [ + 'gravity', 'wpforms', 'cf7', 'jetpack', 'sureforms', 'forminator', + 'fluentforms', 'everestforms', 'ninjaforms', 'metform', 'marketo', 'hubspot', + ] ); + expect( getDefaultAttributes( form ).form_type ).toBe( 'gravity' ); + expect( getLayerVariation( form, {} ).name ).toBe( 'gravity' ); + expect( getLayerVariation( form, { form_type: 'marketo' } ).title ).toBe( 'Marketo' ); + } ); + + it( 'reads form plugin availability when asked, not at import', () => { + const wpforms = getLayerType( 'form' ).variations.find( ( { name } ) => name === 'wpforms' ); + expect( wpforms.isAvailable() ).toBe( false ); + window.videoData.wpformsActive = true; + expect( wpforms.isAvailable() ).toBe( true ); + } ); + + it( 'explains why HubSpot is unavailable based on its settings', () => { + const hubspot = getLayerType( 'form' ).variations.find( ( { name } ) => name === 'hubspot' ); + window.videoData.hubspotEnabled = false; + expect( hubspot.unavailableReason ).toMatch( /Turn on HubSpot/ ); + window.videoData.hubspotEnabled = true; + window.videoData.hubspotChosenSource = 'leadin'; + expect( hubspot.unavailableReason ).toMatch( /Activate and connect the HubSpot plugin/ ); + } ); + + it( 'keeps Form available with no form plugin active, because Marketo needs none', () => { + const saved = window.videoData; + window.videoData = {}; + expect( getAvailability( getLayerType( 'form' ) ) ).toEqual( { available: true } ); + window.videoData = saved; + } ); + + it( 'refuses to save a form layer with no form picked', () => { + const { validate } = getLayerType( 'form' ); + getFormIdFromLayer.mockReturnValueOnce( null ).mockReturnValueOnce( 12 ); + expect( validate( { form_type: 'gravity' } ) ).toBe( false ); + expect( validate( { form_type: 'gravity', gf_id: 12 } ) ).toBe( true ); + } ); + + it( 'disables Poll when WP-Polls is inactive', () => { + expect( getAvailability( getLayerType( 'poll' ) ) ).toEqual( { available: false, reason: 'Poll plugin is not active' } ); + } ); + + it( 'disables new Ad layers with an ad server but keeps existing ones editable', () => { + expect( getAvailability( getLayerType( 'ad' ), { videoConfig: { adServer: 'ad-server' } } ) ).toMatchObject( { + available: false, + disablesExisting: false, + } ); + expect( getAvailability( getLayerType( 'ad' ), { videoConfig: { adServer: 'self-hosted' } } ).available ).toBe( true ); + } ); +} ); + +describe( 'Layer API: bridge from the old add-on hooks', () => { + beforeEach( () => { + resetRegistry(); + window.godamVideoEditorConfig = { + layerOptions: [ + { type: 'woo', title: 'WooCommerce', layerText: 'WooCommerce', iconUrl: 'woo.svg', isActive: false, tooltipMessage: 'Add your API key' }, + { type: 'acme', title: 'Acme', layerText: 'Acme Layer Text' }, + ], + layerComponents: { woo: 'WoocommerceLayer' }, + }; + window.godamLayerComponents = {}; + window.godamLayerCreators = {}; + registerEditorLayerTypes(); + } ); + + afterAll( resetRegistry ); + + it( 'registers each add-on type after the core types', () => { + expect( getLayerTypes().map( ( { name } ) => name ).slice( -2 ) ).toEqual( [ 'woo', 'acme' ] ); + } ); + + it( 'maps the old option fields onto the layer type', () => { + expect( getLayerType( 'acme' ) ).toMatchObject( { title: 'Acme', label: 'Acme Layer Text', description: 'Acme Layer Text' } ); + expect( getLayerType( 'woo' ).iconUrl ).toBe( 'woo.svg' ); + } ); + + it( 'keeps what core used to hard-code for the Woo layer', () => { + const woo = getLayerType( 'woo' ); + expect( woo.color ).toBe( '#873eff' ); + expect( typeof woo.markerIcon ).toBe( 'function' ); + expect( supportsMedia( woo, 'image' ) ).toBe( true ); + expect( supportsMedia( getLayerType( 'acme' ), 'image' ) ).toBe( false ); + } ); + + it( 'reports isActive: false as unavailable, with the add-on\'s message', () => { + expect( getAvailability( getLayerType( 'woo' ) ) ).toEqual( { available: false, reason: 'Add your API key' } ); + expect( getAvailability( getLayerType( 'acme' ) ).available ).toBe( true ); + } ); + + it( 'looks the creator up when a layer is added, so late add-on scripts still count', () => { + const create = getLayerType( 'acme' ).create; + expect( create( { currentTime: 1 } ) ).toBeUndefined(); + window.godamLayerCreators.acme = ( { currentTime } ) => ( { type: 'acme', displayTime: currentTime } ); + expect( create( { currentTime: 3 } ) ).toEqual( { type: 'acme', displayTime: 3 } ); + } ); + + it( 'looks the settings panel up when it opens', () => { + expect( getLegacyEditComponent( 'woo' ) ).toBeUndefined(); + const WoocommerceLayer = () => null; + window.godamLayerComponents.WoocommerceLayer = WoocommerceLayer; + expect( getLegacyEditComponent( 'woo' ) ).toBe( WoocommerceLayer ); + expect( getLegacyEditComponent( 'acme' ) ).toBeUndefined(); + } ); + + it( 'does not re-register a type an add-on already registered through the Layer API', () => { + resetRegistry(); + window.godam.layers.__unstableRegisterLegacyLayerType( { name: 'woo', title: 'Registered first' } ); + registerEditorLayerTypes(); + expect( getLayerType( 'woo' ).title ).toBe( 'Registered first' ); + } ); +} ); + +describe( 'Layer API: settings panel hooks', () => { + let container, root, store, dispatched; + + const renderHook = ( hook, layerId = 'l1' ) => { + let result; + const Probe = () => { + result = hook(); + return null; + }; + act( () => { + root.render( + + + + + , + ); + } ); + return () => result; + }; + + beforeEach( () => { + global.IS_REACT_ACT_ENVIRONMENT = true; + container = document.createElement( 'div' ); + root = createRoot( container ); + dispatched = []; + store = configureStore( { + reducer: { + videoReducer: ( state = { layers: [ { id: 'l1', type: 'acme/countdown', label: 'Hi' }, { id: 'l2', type: 'cta' } ] }, action ) => { + dispatched.push( action ); + return state; + }, + }, + } ); + } ); + + afterEach( () => act( () => root.unmount() ) ); + + it( 'useLayer() returns the open layer, or the one with the given id', () => { + expect( renderHook( () => useLayer() )() ).toMatchObject( { id: 'l1' } ); + expect( renderHook( () => useLayer( 'l2' ) )() ).toMatchObject( { id: 'l2' } ); + } ); + + it( 'useLayerAttributes() merges changes but never touches id or type', () => { + const result = renderHook( () => useLayerAttributes() ); + const [ layer, setAttributes ] = result(); + expect( layer.label ).toBe( 'Hi' ); + + act( () => setAttributes( { label: 'Bye', endsAt: '10:00', id: 'x', type: 'cta' } ) ); + + expect( dispatched.filter( ( a ) => a.type === 'updateLayerField' ).map( ( a ) => a.payload ) ).toEqual( [ + { id: 'l1', field: 'label', value: 'Bye' }, + { id: 'l1', field: 'endsAt', value: '10:00' }, + ] ); + } ); +} ); diff --git a/pages/video-editor/layers/legacy.js b/pages/video-editor/layers/legacy.js new file mode 100644 index 0000000000..66cb3f2008 --- /dev/null +++ b/pages/video-editor/layers/legacy.js @@ -0,0 +1,81 @@ +/** + * Bridge from the pre-Layer-API add-on hooks to the layer registry. + * + * Add-ons such as godam-for-woo still describe their layer through three old + * hooks: `godam_video_editor_layer_options` (the menu entry, localized as + * `godamVideoEditorConfig.layerOptions`); `godam_video_editor_layer_components` + * (the settings panel, naming a component on `window.godamLayerComponents`); + * and `window.godamLayerCreators[ type ]` (the data for a new layer). + * + * This registers those types so the editor only reads the registry. The + * component and creator are looked up when used, because add-on scripts can + * load after the editor. #2296 moves godam-for-woo onto the Layer API and + * turns these into deprecated shims; the `woo` entries below go with it. + */ + +/** + * External dependencies + */ +import { getLayerType, __unstableRegisterLegacyLayerType } from '@godam/layers'; + +/** + * Shopping-cart glyph (white line art) for commerce layer markers. + * `@wordpress/icons` ships no cart icon, so it's defined inline here. + * + * @return {JSX.Element} Cart SVG. + */ +const CartIcon = () => ( + +); + +// What core used to hard-code for the Woo layer; it can't say so through the old hooks. +const LEGACY_WOO = { + color: '#873eff', + markerIcon: CartIcon, + supports: { media: [ 'video', 'image' ] }, +}; + +/** + * The settings panel an add-on named through `godam_video_editor_layer_components`, + * if its script has put it on `window.godamLayerComponents`. Also lets an add-on + * replace a core type's panel, as it always could. + * + * @param {string} type Layer type name. + * @return {Function|undefined} The add-on's settings component. + */ +export function getLegacyEditComponent( type ) { + const componentName = window.godamVideoEditorConfig?.layerComponents?.[ type ]; + return componentName ? window.godamLayerComponents?.[ componentName ] : undefined; +} + +/** + * Register every layer type an add-on described through the old hooks. + */ +export function registerLegacyLayerTypes() { + ( window.godamVideoEditorConfig?.layerOptions || [] ).forEach( ( option ) => { + const name = option?.type; + if ( ! name || getLayerType( name ) ) { + return; + } + + __unstableRegisterLegacyLayerType( { + name, + title: option.title || option.layerText || name, + label: option.layerText || option.title, + description: option.title && option.layerText ? option.layerText : '', + icon: option.iconUrl ? undefined : option.icon, + iconUrl: option.iconUrl, + ...( 'woo' === name ? LEGACY_WOO : {} ), + getAvailability: () => ( + false === option.isActive + ? { available: false, reason: option.tooltipMessage ?? '' } + : null + ), + create: ( context ) => window.godamLayerCreators?.[ name ]?.( context ), + } ); + } ); +} diff --git a/pages/video-editor/redux/slice/videoSlice.js b/pages/video-editor/redux/slice/videoSlice.js index 97042bbd35..abf41717a7 100644 --- a/pages/video-editor/redux/slice/videoSlice.js +++ b/pages/video-editor/redux/slice/videoSlice.js @@ -45,11 +45,11 @@ const initialState = { currentLayer: null, currentTab: 'layers', // Media-type awareness. Seeded from the attachment MIME via `setMediaType`; - // `allowedTabs` gates `setCurrentTab` and `allowedLayerTypes` gates the - // "Add layer" menu. Defaults reproduce the historic video-only behaviour. + // `allowedTabs` gates `setCurrentTab`. Which layer types a media type offers + // comes from each layer type's `supports.media` in the layer registry. + // Defaults reproduce the historic video-only behaviour. mediaType: 'video', allowedTabs: [ 'layers', 'player-settings', 'transcription', 'chapters' ], - allowedLayerTypes: '*', loading: false, gforms: [], jetpackForms: [], @@ -149,14 +149,13 @@ const slice = createSlice( { state.currentTab = action.payload; } }, - // Apply a media-type capability to the store: records the media type, - // the allowed tabs / layer types, and snaps `currentTab` to a supported + // Apply a media-type capability to the store: records the media type and + // the allowed tabs, and snaps `currentTab` to a supported // tab if the current one isn't available for this media type. setMediaType: ( state, action ) => { - const { mediaType, tabs, defaultTab, allowedLayerTypes } = action.payload; + const { mediaType, tabs, defaultTab } = action.payload; state.mediaType = mediaType; state.allowedTabs = tabs; - state.allowedLayerTypes = allowedLayerTypes; if ( ! tabs.includes( state.currentTab ) ) { state.currentTab = defaultTab; } diff --git a/pages/video-editor/utils/layerTypes.js b/pages/video-editor/utils/layerTypes.js deleted file mode 100644 index 64a9895489..0000000000 --- a/pages/video-editor/utils/layerTypes.js +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Shared layer-type registry for the timeline / seeker. - * - * Maps each layer `type` to its display title and the icon used on the timeline - * marker chips. CTA / Hotspot / Form / Poll use the shared design icons from - * `editor-shell/icons` (the same ones shown in the "Add layer" dropdown) so the - * two surfaces stay in sync; Ad uses a WordPress icon. Add-on layer types (e.g. - * WooCommerce) registered via PHP filters are merged in and may carry an `iconUrl`. - */ - -/** - * WordPress dependencies - */ -import { video } from '@wordpress/icons'; -import { __ } from '@wordpress/i18n'; - -/** - * Internal dependencies - */ -import { CtaLayerIcon, HotspotLayerIcon, FormLayerIcon, PollLayerIcon } from '../components/editor-shell/icons'; -import GFIcon from '../assets/layers/GFIcon.svg'; -import WPFormsIcon from '../assets/layers/WPForms-Mascot.svg'; -import CF7Icon from '../assets/layers/CF7Icon.svg'; -import JetpackIcon from '../assets/layers/JetpackIcon.svg'; -import SureformsIcon from '../assets/layers/SureFormsIcons.svg'; -import ForminatorIcon from '../assets/layers/Forminator.png'; -import FluentFormsIcon from '../assets/layers/FluentFormsIcon.png'; -import EverestFormsIcon from '../assets/layers/EverestFormsIcon.svg'; -import NinjaFormsIcon from '../assets/layers/NinjaFormsIcon.png'; -import MetformIcon from '../assets/layers/MetFormIcon.png'; -import MarketoIcon from '../assets/layers/MarketoIcon.svg'; -import HubSpotIcon from '../assets/layers/HubSpotIcon.svg'; - -/** - * Per-form-plugin display name and icon, keyed by a form layer's `form_type`. - * Used to show the specific form (e.g. WPForms) on the timeline marker rather - * than the generic "Form" type. Mirrors the form options in `SidebarLayers`. - */ -export const FORM_PLUGIN_META = { - gravity: { name: __( 'Gravity Forms', 'godam' ), icon: GFIcon }, - wpforms: { name: __( 'WPForms', 'godam' ), icon: WPFormsIcon }, - cf7: { name: __( 'Contact Form 7', 'godam' ), icon: CF7Icon }, - jetpack: { name: __( 'Jetpack Forms', 'godam' ), icon: JetpackIcon }, - sureforms: { name: __( 'SureForms', 'godam' ), icon: SureformsIcon }, - forminator: { name: __( 'Forminator Forms', 'godam' ), icon: ForminatorIcon }, - fluentforms: { name: __( 'Fluent Forms', 'godam' ), icon: FluentFormsIcon }, - everestforms: { name: __( 'Everest Forms', 'godam' ), icon: EverestFormsIcon }, - ninjaforms: { name: __( 'Ninja Forms', 'godam' ), icon: NinjaFormsIcon }, - metform: { name: __( 'MetForm', 'godam' ), icon: MetformIcon }, - marketo: { name: __( 'Marketo', 'godam' ), icon: MarketoIcon }, - hubspot: { name: __( 'HubSpot', 'godam' ), icon: HubSpotIcon }, -}; - -/** - * Per-type icon / marker colour. Shared by the "Add layer" dropdown, the layer - * list rows and the timeline marker chips so a layer type reads in the same - * colour everywhere. Add-on types not listed here fall back to the editor accent. - */ -export const LAYER_TYPE_COLORS = { - cta: '#3858e9', - hotspot: '#10B77F', - woo: '#873eff', - poll: '#E8499E', - form: '#088EAF', - ad: '#CD860D', -}; - -export const layerTypes = [ - { - title: __( 'Gravity Forms', 'godam' ), - icon: FormLayerIcon, - type: 'form', - }, - { - title: __( 'CTA', 'godam' ), - icon: CtaLayerIcon, - type: 'cta', - }, - { - title: __( 'Hotspot', 'godam' ), - icon: HotspotLayerIcon, - type: 'hotspot', - }, - { - title: __( 'Ad', 'godam' ), - icon: video, - type: 'ad', - }, - { - title: __( 'Poll', 'godam' ), - icon: PollLayerIcon, - type: 'poll', - }, - // Merge add-on layer types registered via PHP filters (e.g. WooCommerce). - ...( window.godamVideoEditorConfig?.layerOptions || [] ), -]; diff --git a/webpack.config.js b/webpack.config.js index d0d66842ac..98a7135681 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -357,6 +357,14 @@ const ninjaFormsSubmissionsList = { }, }; +// Layer API registry (`window.godam.layers`, imported elsewhere as `@godam/layers`). +const godamLayers = { + ...sharedConfig, + entry: { + 'godam-layers': path.resolve( process.cwd(), 'assets', 'src', 'js', 'godam-layers', 'index.js' ), + }, +}; + const blockExtensions = { ...sharedConfig, entry: { @@ -453,6 +461,8 @@ const pages = { // instance core registered. DataViews itself is still bundled because // core ships no `wp-dataviews` script handle. '@wordpress/private-apis': [ 'wp', 'privateApis' ], + // The layer type registry is its own script (`godam-layers`), shared with add-ons. + '@godam/layers': [ 'godam', 'layers' ], }, resolve: { extensions: [ '.js', '.jsx' ], // Automatically resolve these extensions @@ -499,4 +509,5 @@ module.exports = [ wpBakeryDocumentCoverSelectorParam, ninjaFormsSubmissionsList, blockExtensions, + godamLayers, ]; From b1f44ed7a5b2b23b0d2d070a9b17ce34ae5905e7 Mon Sep 17 00:00:00 2001 From: KMchaudhary Date: Wed, 4 Nov 2026 12:40:48 +0530 Subject: [PATCH 06/20] feat(layers): register form providers as Form layer variations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each of the 12 form plugins is now one registerLayerVariation( 'form', … ) call carrying its title, icon, availability, panel, form-ID field and settings URL, replacing the FormLayerComponentType table. Add-ons can register their own provider; one without a panel supplies getForms() and getFormHtml( id ) and gets a shared FormProviderPanel. A form layer whose provider isn't registered shows a notice instead of an error. Adds registerLayerVariation, unregisterLayerVariation, getLayerVariationByName and getUnavailableReason to the registry. A variation registered before its type is kept and added later. Editor only; the player and PHP parts move to #2294 and #2295. Refs #2293 Co-Authored-By: Claude Opus 5.5 --- assets/src/js/godam-layers/index.js | 46 ++-- assets/src/js/godam-layers/registration.js | 99 ++++++++- .../src/js/godam-layers/registration.test.js | 88 ++++++++ assets/src/js/godam-layers/utils.js | 12 + .../video-editor/components/SidebarLayers.js | 3 +- .../components/SidebarLayers.test.js | 42 ++++ .../components/forms/FormProviderPanel.js | 117 ++++++++++ .../forms/FormProviderPanel.test.js | 131 +++++++++++ .../components/forms/fetchForms.js | 35 ++- .../components/layers/FormLayer.js | 133 +++-------- .../components/layers/FormLayer.test.js | 103 +++++++++ .../components/layers/Layer.test.js | 5 + .../components/timeline/Timeline.test.js | 5 + pages/video-editor/layers/core/form.js | 79 +------ pages/video-editor/layers/form-providers.js | 208 ++++++++++++++++++ .../layers/form-providers.test.js | 105 +++++++++ pages/video-editor/layers/index.js | 9 +- pages/video-editor/layers/layers.test.js | 10 +- pages/video-editor/utils/formUtils.js | 44 ++-- tests/js/mock-form-provider-panels.js | 69 ++++++ 20 files changed, 1102 insertions(+), 241 deletions(-) create mode 100644 pages/video-editor/components/forms/FormProviderPanel.js create mode 100644 pages/video-editor/components/forms/FormProviderPanel.test.js create mode 100644 pages/video-editor/components/layers/FormLayer.test.js create mode 100644 pages/video-editor/layers/form-providers.js create mode 100644 pages/video-editor/layers/form-providers.test.js create mode 100644 tests/js/mock-form-provider-panels.js diff --git a/assets/src/js/godam-layers/index.js b/assets/src/js/godam-layers/index.js index 7811cb5770..daf2c59ec3 100644 --- a/assets/src/js/godam-layers/index.js +++ b/assets/src/js/godam-layers/index.js @@ -15,6 +15,9 @@ import { unregisterLayerType, getLayerType, getLayerTypes, + registerLayerVariation, + unregisterLayerVariation, + getLayerVariationByName, __unstableRegisterLegacyLayerType, } from './registration'; import { @@ -22,11 +25,33 @@ import { getLayerVariation, getDefaultVariation, isVariationAvailable, + getUnavailableReason, getAvailability, supportsMedia, } from './utils'; import { CORE_LAYER_TYPES, STORE_NAME } from './constants'; +const api = { + store, + STORE_NAME, + CORE_LAYER_TYPES, + registerLayerType, + unregisterLayerType, + getLayerType, + getLayerTypes, + registerLayerVariation, + unregisterLayerVariation, + getLayerVariationByName, + getDefaultAttributes, + getLayerVariation, + getDefaultVariation, + isVariationAvailable, + getUnavailableReason, + getAvailability, + supportsMedia, + __unstableRegisterLegacyLayerType, +}; + export { store, STORE_NAME, @@ -35,10 +60,14 @@ export { unregisterLayerType, getLayerType, getLayerTypes, + registerLayerVariation, + unregisterLayerVariation, + getLayerVariationByName, getDefaultAttributes, getLayerVariation, getDefaultVariation, isVariationAvailable, + getUnavailableReason, getAvailability, supportsMedia, __unstableRegisterLegacyLayerType, @@ -46,20 +75,5 @@ export { if ( typeof window !== 'undefined' ) { window.godam = window.godam || {}; - window.godam.layers = { - store, - STORE_NAME, - CORE_LAYER_TYPES, - registerLayerType, - unregisterLayerType, - getLayerType, - getLayerTypes, - getDefaultAttributes, - getLayerVariation, - getDefaultVariation, - isVariationAvailable, - getAvailability, - supportsMedia, - __unstableRegisterLegacyLayerType, - }; + window.godam.layers = api; } diff --git a/assets/src/js/godam-layers/registration.js b/assets/src/js/godam-layers/registration.js index e6a573fbd1..3711d7041e 100644 --- a/assets/src/js/godam-layers/registration.js +++ b/assets/src/js/godam-layers/registration.js @@ -54,7 +54,7 @@ function sanitizeAttributes( name, attributes = {} ) { */ function normalizeLayerType( layerType ) { const { icon, iconUrl, supports, attributes, variations, ...rest } = layerType; - return { + const normalized = { apiVersion: 1, description: '', ...rest, @@ -63,10 +63,30 @@ function normalizeLayerType( layerType ) { iconUrl: iconUrl || ( isUrl( icon ) ? icon : undefined ), supports: { ...DEFAULT_SUPPORTS, ...( supports || {} ) }, attributes: sanitizeAttributes( rest.name, attributes ), - variations: Array.isArray( variations ) ? variations : [], }; + normalized.variations = ( Array.isArray( variations ) ? variations : [] ).map( ( variation ) => normalizeVariation( normalized, variation ) ); + return normalized; } +/** + * Give a variation the attributes that select it. A type that sets + * `variationAttribute` (Form uses `form_type`) gets `{ [ variationAttribute ]: name }` + * for any variation that doesn't set its own `attributes`. + * + * @param {Object} layerType The layer type the variation belongs to. + * @param {Object} variation The variation. + * @return {Object} The variation, with `attributes`. + */ +function normalizeVariation( layerType, variation ) { + if ( variation.attributes || ! layerType.variationAttribute ) { + return { attributes: {}, ...variation }; + } + return { ...variation, attributes: { [ layerType.variationAttribute ]: variation.name } }; +} + +// Variations registered before their layer type, applied when it registers. +const pendingVariations = {}; + /** * Register a layer type. * @@ -115,7 +135,13 @@ function addLayerType( merged ) { * @param {Object} settings Layer type settings. * @param {string} name Layer type name. */ - const layerType = normalizeLayerType( { ...applyFilters( 'godam.layers.registerLayerType', merged, name ), name } ); + const filtered = applyFilters( 'godam.layers.registerLayerType', merged, name ); + const layerType = normalizeLayerType( { + ...filtered, + name, + variations: [ ...( filtered.variations || [] ), ...( pendingVariations[ name ] || [] ) ], + } ); + delete pendingVariations[ name ]; if ( typeof layerType.title !== 'string' || ! layerType.title ) { console.error( `GoDAM: layer type "${ name }" needs a title.` ); @@ -142,8 +168,75 @@ export function unregisterLayerType( name ) { return layerType; } +/** + * Register a variation of a layer type, such as a form plugin for the Form + * layer. When the type isn't registered yet, the variation is kept and added + * when it is, so scripts can load in any order. + * + * A variation has a `name` and `title`, plus whatever its type reads; a form + * provider adds `icon`, `isAvailable`, `edit` or `getForms`/`getFormHtml`, + * `idField` and `settingsUrl`. + * + * @param {string} typeName Layer type name, e.g. `form`. + * @param {Object} variation The variation. + * @return {Object|undefined} The registered variation, or undefined when registration failed. + */ +export function registerLayerVariation( typeName, variation ) { + const name = variation?.name; + if ( typeof name !== 'string' || ! name ) { + console.error( `GoDAM: a "${ typeName }" variation needs a name.` ); + return undefined; + } + if ( typeof variation.title !== 'string' || ! variation.title ) { + console.error( `GoDAM: the "${ typeName }" variation "${ name }" needs a title.` ); + return undefined; + } + + const layerType = select( store ).getLayerType( typeName ); + const existing = layerType ? layerType.variations : ( pendingVariations[ typeName ] || [] ); + if ( existing.some( ( v ) => v.name === name ) ) { + console.error( `GoDAM: the "${ typeName }" variation "${ name }" is already registered.` ); + return undefined; + } + + if ( ! layerType ) { + pendingVariations[ typeName ] = [ ...existing, variation ]; + return variation; + } + + const normalized = normalizeVariation( layerType, variation ); + dispatch( store ).addLayerType( { ...layerType, variations: [ ...layerType.variations, normalized ] } ); + return normalized; +} + +/** + * Unregister a variation of a layer type. + * + * @param {string} typeName Layer type name. + * @param {string} variationName Variation name. + * @return {Object|undefined} The removed variation. + */ +export function unregisterLayerVariation( typeName, variationName ) { + const layerType = select( store ).getLayerType( typeName ); + const variation = layerType?.variations.find( ( v ) => v.name === variationName ); + if ( ! variation ) { + console.error( `GoDAM: the "${ typeName }" variation "${ variationName }" is not registered.` ); + return undefined; + } + dispatch( store ).addLayerType( { ...layerType, variations: layerType.variations.filter( ( v ) => v !== variation ) } ); + return variation; +} + /* eslint-enable no-console */ +/** + * @param {string} typeName Layer type name. + * @param {string} variationName Variation name. + * @return {Object|undefined} The registered variation. + */ +export const getLayerVariationByName = ( typeName, variationName ) => + select( store ).getLayerType( typeName )?.variations.find( ( v ) => v.name === variationName ); + /** * @param {string} name Layer type name. * @return {Object|undefined} The registered layer type. diff --git a/assets/src/js/godam-layers/registration.test.js b/assets/src/js/godam-layers/registration.test.js index 303e2bb36b..d9fb7101aa 100644 --- a/assets/src/js/godam-layers/registration.test.js +++ b/assets/src/js/godam-layers/registration.test.js @@ -21,6 +21,10 @@ import { isVariationAvailable, getAvailability, supportsMedia, + registerLayerVariation, + unregisterLayerVariation, + getLayerVariationByName, + getUnavailableReason, __unstableRegisterLegacyLayerType, } from './index'; @@ -140,6 +144,84 @@ describe( 'Layer API: registerLayerType', () => { } ); } ); +describe( 'Layer API: registerLayerVariation', () => { + let error; + + beforeEach( () => { + error = jest.spyOn( console, 'error' ).mockImplementation( () => {} ); + } ); + + afterEach( () => { + getLayerTypes().forEach( ( { name } ) => unregisterLayerType( name ) ); + error.mockRestore(); + } ); + + const registerForm = ( settings = {} ) => + registerLayerType( { name: 'form', title: 'Form' }, { variationAttribute: 'form_type', ...settings } ); + + it( 'adds variations in registration order, selected by the type\'s variationAttribute', () => { + registerForm(); + registerLayerVariation( 'form', { name: 'gravity', title: 'Gravity Forms' } ); + registerLayerVariation( 'form', { name: 'acme-forms', title: 'Acme Forms', idField: 'acme_form_id' } ); + + expect( getLayerType( 'form' ).variations ).toEqual( [ + { name: 'gravity', title: 'Gravity Forms', attributes: { form_type: 'gravity' } }, + { name: 'acme-forms', title: 'Acme Forms', idField: 'acme_form_id', attributes: { form_type: 'acme-forms' } }, + ] ); + expect( getLayerVariationByName( 'form', 'acme-forms' ).idField ).toBe( 'acme_form_id' ); + } ); + + it( 'keeps a variation\'s own attributes', () => { + registerForm(); + registerLayerVariation( 'form', { name: 'dark', title: 'Dark', attributes: { theme: 'dark' } } ); + expect( getLayerVariationByName( 'form', 'dark' ).attributes ).toEqual( { theme: 'dark' } ); + } ); + + it( 'holds a variation registered before its type and adds it when the type registers', () => { + registerLayerVariation( 'form', { name: 'acme-forms', title: 'Acme Forms' } ); + expect( getLayerType( 'form' ) ).toBeUndefined(); + + registerForm( { variations: [ { name: 'gravity', title: 'Gravity Forms' } ] } ); + + expect( getLayerType( 'form' ).variations.map( ( { name, attributes } ) => [ name, attributes.form_type ] ) ).toEqual( [ + [ 'gravity', 'gravity' ], + [ 'acme-forms', 'acme-forms' ], + ] ); + } ); + + it( 'rejects a duplicate name, and a variation without a name or title', () => { + registerForm(); + registerLayerVariation( 'form', { name: 'gravity', title: 'Gravity Forms' } ); + + expect( registerLayerVariation( 'form', { name: 'gravity', title: 'Again' } ) ).toBeUndefined(); + expect( registerLayerVariation( 'form', { title: 'No name' } ) ).toBeUndefined(); + expect( registerLayerVariation( 'form', { name: 'untitled' } ) ).toBeUndefined(); + expect( getLayerType( 'form' ).variations.map( ( { name } ) => name ) ).toEqual( [ 'gravity' ] ); + } ); + + it( 'unregisters a variation and keeps the others', () => { + registerForm(); + registerLayerVariation( 'form', { name: 'gravity', title: 'Gravity Forms' } ); + registerLayerVariation( 'form', { name: 'acme-forms', title: 'Acme Forms' } ); + + expect( unregisterLayerVariation( 'form', 'gravity' ).name ).toBe( 'gravity' ); + expect( getLayerType( 'form' ).variations.map( ( { name } ) => name ) ).toEqual( [ 'acme-forms' ] ); + expect( unregisterLayerVariation( 'form', 'gravity' ) ).toBeUndefined(); + } ); + + it( 'keeps the type\'s place in the registry when a variation is added', () => { + registerForm(); + registerLayerType( { name: 'acme/countdown', title: 'Countdown' } ); + registerLayerVariation( 'form', { name: 'gravity', title: 'Gravity Forms' } ); + expect( getLayerTypes().map( ( { name } ) => name ) ).toEqual( [ 'form', 'acme/countdown' ] ); + } ); + + it( 'exposes variation registration on window.godam.layers', () => { + expect( window.godam.layers.registerLayerVariation ).toBe( registerLayerVariation ); + expect( window.godam.layers.unregisterLayerVariation ).toBe( unregisterLayerVariation ); + } ); +} ); + describe( 'Layer API: helpers', () => { const formType = { attributes: { @@ -179,6 +261,12 @@ describe( 'Layer API: helpers', () => { expect( isVariationAvailable( { isAvailable: () => false } ) ).toBe( false ); } ); + it( 'reads a variation\'s unavailable reason from a string or a function', () => { + expect( getUnavailableReason( { unavailableReason: 'Activate Acme' } ) ).toBe( 'Activate Acme' ); + expect( getUnavailableReason( { unavailableReason: () => 'Connect Acme' } ) ).toBe( 'Connect Acme' ); + expect( getUnavailableReason( {} ) ).toBe( '' ); + } ); + it( 'reports availability from getAvailability( context ), defaulting to available', () => { expect( getAvailability( {} ) ).toEqual( { available: true } ); const ad = { getAvailability: ( { videoConfig } ) => ( videoConfig.adServer === 'ad-server' ? { available: false, reason: 'No' } : null ) }; diff --git a/assets/src/js/godam-layers/utils.js b/assets/src/js/godam-layers/utils.js index e17a5ed73a..60232fafb3 100644 --- a/assets/src/js/godam-layers/utils.js +++ b/assets/src/js/godam-layers/utils.js @@ -60,6 +60,18 @@ export function isVariationAvailable( variation ) { return typeof variation?.isAvailable === 'function' ? variation.isAvailable() !== false : true; } +/** + * Why a variation can't be used, e.g. which plugin to activate. `unavailableReason` + * may be a string or a function returning one, for a reason that depends on settings. + * + * @param {Object} variation A layer type variation. + * @return {string} The reason, or `''`. + */ +export function getUnavailableReason( variation ) { + const reason = variation?.unavailableReason; + return ( typeof reason === 'function' ? reason() : reason ) || ''; +} + /** * Whether a layer type can be added right now, and why not. * diff --git a/pages/video-editor/components/SidebarLayers.js b/pages/video-editor/components/SidebarLayers.js index 0e1e6413c1..fb60b7aee6 100644 --- a/pages/video-editor/components/SidebarLayers.js +++ b/pages/video-editor/components/SidebarLayers.js @@ -10,6 +10,7 @@ import { getDefaultVariation, getLayerVariation, isVariationAvailable, + getUnavailableReason, getAvailability, supportsMedia, } from '@godam/layers'; @@ -466,7 +467,7 @@ const SidebarLayers = ( { currentTime, onSelectLayer, onPauseVideo, duration } ) if ( ! layerType ) { tooltipMessage = __( 'This layer needs an add-on that isn\'t active.', 'godam' ); } else if ( variation && ! isVariationAvailable( variation ) ) { - tooltipMessage = variation.unavailableReason ?? ''; + tooltipMessage = getUnavailableReason( variation ); isLayerDisabled = true; } else { const availability = getAvailability( layerType, availabilityContext ); diff --git a/pages/video-editor/components/SidebarLayers.test.js b/pages/video-editor/components/SidebarLayers.test.js index 9a286bb622..f46d362dd0 100644 --- a/pages/video-editor/components/SidebarLayers.test.js +++ b/pages/video-editor/components/SidebarLayers.test.js @@ -16,6 +16,11 @@ * the PR that changes the behaviour. */ +/** + * Internal dependencies + */ +import '../../../tests/js/mock-form-provider-panels'; + /** * Internal dependencies */ @@ -28,6 +33,7 @@ import { act } from 'react'; import { createRoot } from 'react-dom/client'; import { Provider } from 'react-redux'; import { configureStore } from '@reduxjs/toolkit'; +import { registerLayerVariation, unregisterLayerVariation } from '@godam/layers'; /** * Internal dependencies @@ -286,6 +292,42 @@ describe( 'Layer API contract: SidebarLayers', () => { } ); } ); + describe( 'add-on form providers', () => { + beforeAll( () => { + registerLayerVariation( 'form', { name: 'acme-forms', title: 'Acme Forms', isAvailable: () => true } ); + } ); + + afterAll( () => unregisterLayerVariation( 'form', 'acme-forms' ) ); + + it( 'lists a provider registered through the Layer API in the Form submenu', () => { + render(); + click( control( 'form' ) ); + click( control( 'form-acme-forms' ) ); + expect( addedLayers() ).toEqual( [ { + id: 'test-uuid', + displayTime: 12, + type: 'form', + name: 'Acme Forms Layer', + form_type: 'acme-forms', + submitted: false, + allow_skip: true, + custom_css: '', + theme: '', + } ] ); + } ); + + it( 'leaves out a provider whose plugin is unavailable', () => { + registerLayerVariation( 'form', { name: 'acme-off', title: 'Acme Off', isAvailable: () => false } ); + render(); + click( control( 'form' ) ); + expect( control( 'form-acme-off' ) ).toBeNull(); + // The menu is still mounted and re-renders when the registry changes. + act( () => { + unregisterLayerVariation( 'form', 'acme-off' ); + } ); + } ); + } ); + describe( 'media-type gating', () => { it( 'disables "Add layer" on video until the playhead has moved', () => { render( { currentTime: 0 } ); diff --git a/pages/video-editor/components/forms/FormProviderPanel.js b/pages/video-editor/components/forms/FormProviderPanel.js new file mode 100644 index 0000000000..f6d1423611 --- /dev/null +++ b/pages/video-editor/components/forms/FormProviderPanel.js @@ -0,0 +1,117 @@ +/** + * External dependencies + */ +import { isVariationAvailable } from '@godam/layers'; + +/** + * WordPress dependencies + */ +import { __ } from '@wordpress/i18n'; +import { useEffect, useState } from '@wordpress/element'; + +/** + * Internal dependencies + */ +import FormFields from './FormFields'; +import FormPreview from './FormPreview'; +import { useLayerAttributes } from '../../layers/hooks'; +import { buildSettingsUrl } from '../../utils/formUtils'; + +// Shared across panels, so reopening a layer doesn't fetch the same list or form again. +const formListCache = new Map(); +const formHtmlCache = new Map(); + +const cached = ( cache, key, load ) => { + if ( ! cache.has( key ) ) { + cache.set( key, Promise.resolve().then( load ).catch( ( error ) => { + cache.delete( key ); + throw error; + } ) ); + } + return cache.get( key ); +}; + +/** + * The settings panel for a form provider that doesn't bring its own `edit` + * panel: a form picker filled from `provider.getForms()` and a live preview + * from `provider.getFormHtml( formId )`. The chosen ID is stored on the + * layer under `provider.idField`. + * + * `getForms()` resolves to `[ { id, title } ]`; `getFormHtml( id )` resolves + * to the form's markup. + * + * @param {Object} props Props. + * @param {string} props.layerID The form layer's id. + * @param {Object} props.provider The layer's form provider (a Form variation). + * @return {JSX.Element} The panel. + */ +const FormProviderPanel = ( { layerID, provider } ) => { + const [ layer, setAttributes ] = useLayerAttributes( layerID ); + const idField = provider.idField || 'form_id'; + const formId = layer?.[ idField ]; + const isActive = isVariationAvailable( provider ); + + const [ forms, setForms ] = useState( [] ); + const [ preview, setPreview ] = useState( { isFetching: false, html: '', error: '' } ); + + useEffect( () => { + if ( ! isActive || typeof provider.getForms !== 'function' ) { + return undefined; + } + let cancelled = false; + cached( formListCache, provider.name, () => provider.getForms() ) + .then( ( list ) => ! cancelled && setForms( Array.isArray( list ) ? list : [] ) ) + .catch( () => ! cancelled && setForms( [] ) ); + return () => { + cancelled = true; + }; + }, [ isActive, provider ] ); + + useEffect( () => { + if ( ! formId || typeof provider.getFormHtml !== 'function' ) { + setPreview( { isFetching: false, html: '', error: '' } ); + return undefined; + } + let cancelled = false; + setPreview( { isFetching: true, html: '', error: '' } ); + cached( formHtmlCache, `${ provider.name }:${ formId }`, () => provider.getFormHtml( formId ) ) + .then( ( html ) => ! cancelled && setPreview( { isFetching: false, html: html || '', error: '' } ) ) + .catch( () => ! cancelled && setPreview( { + isFetching: false, + html: '', + error: __( 'The form could not be loaded.', 'godam' ), + } ) ); + return () => { + cancelled = true; + }; + }, [ formId, provider ] ); + + if ( ! layer ) { + return null; + } + + return ( + <> + ( { value: form.id, label: form.title } ) ) } + onSelectForm={ ( id ) => setAttributes( { [ idField ]: id } ) } + editUrl={ provider.settingsUrl && formId ? buildSettingsUrl( layer.form_type, formId ) : '' } + showEditButton={ Boolean( preview.html ) } + /> + + + + ); +}; + +export default FormProviderPanel; diff --git a/pages/video-editor/components/forms/FormProviderPanel.test.js b/pages/video-editor/components/forms/FormProviderPanel.test.js new file mode 100644 index 0000000000..f8e8a61145 --- /dev/null +++ b/pages/video-editor/components/forms/FormProviderPanel.test.js @@ -0,0 +1,131 @@ +/** + * Layer API (#2293): the shared panel for a form provider without its own. + */ + +/** + * External dependencies + */ +import { act } from 'react'; +import { createRoot } from 'react-dom/client'; +import { Provider } from 'react-redux'; +import { configureStore } from '@reduxjs/toolkit'; + +/** + * Internal dependencies + */ +import FormProviderPanel from './FormProviderPanel'; + +// Capture what the shared form controls are given; their own behaviour is covered elsewhere. +jest.mock( './FormFields', () => jest.fn( () => null ) ); +jest.mock( './FormPreview', () => jest.fn( () => null ) ); +jest.mock( '../../redux/slice/videoSlice', () => ( { + updateLayerField: ( payload ) => ( { type: 'updateLayerField', payload } ), +} ) ); +jest.mock( '../../utils/formUtils', () => ( { + buildSettingsUrl: ( formType, formId ) => `settings:${ formType }:${ formId }`, +} ) ); + +const FormFields = require( './FormFields' ); +const FormPreview = require( './FormPreview' ); + +describe( 'Layer API: FormProviderPanel', () => { + let container, root, dispatched; + + const lastProps = ( mock ) => mock.mock.calls.at( -1 )[ 0 ]; + const flush = () => act( async () => { + await Promise.resolve(); + await Promise.resolve(); + } ); + + const render = async ( layer, provider ) => { + const store = configureStore( { + reducer: { + videoReducer: ( state = { layers: [ layer ] }, action ) => { + dispatched.push( action ); + return state; + }, + }, + } ); + act( () => { + root.render( + + + , + ); + } ); + await flush(); + }; + + const provider = ( overrides = {} ) => ( { + name: `acme-forms-${ Math.random() }`, + title: 'Acme Forms', + idField: 'acme_form_id', + isAvailable: () => true, + settingsUrl: 'admin.php?page=acme&form={formId}', + getForms: jest.fn( async () => [ { id: 'f1', title: 'Contact' }, { id: 'f2', title: 'Newsletter' } ] ), + getFormHtml: jest.fn( async ( id ) => `
` ), + ...overrides, + } ); + + beforeEach( () => { + global.IS_REACT_ACT_ENVIRONMENT = true; + container = document.createElement( 'div' ); + root = createRoot( container ); + dispatched = []; + FormFields.mockClear(); + FormPreview.mockClear(); + } ); + + afterEach( () => act( () => root.unmount() ) ); + + it( 'fills the form picker from getForms()', async () => { + const acme = provider(); + await render( { id: 'l1', type: 'form', form_type: acme.name }, acme ); + + expect( acme.getForms ).toHaveBeenCalledTimes( 1 ); + expect( lastProps( FormFields ) ).toMatchObject( { + isActive: true, + pluginLabel: 'Acme Forms', + forms: [ { value: 'f1', label: 'Contact' }, { value: 'f2', label: 'Newsletter' } ], + } ); + } ); + + it( 'stores the chosen form under the provider\'s idField', async () => { + const acme = provider(); + await render( { id: 'l1', type: 'form', form_type: acme.name }, acme ); + + act( () => lastProps( FormFields ).onSelectForm( 'f2' ) ); + + expect( dispatched ).toContainEqual( { type: 'updateLayerField', payload: { id: 'l1', field: 'acme_form_id', value: 'f2' } } ); + } ); + + it( 'previews the chosen form from getFormHtml() and links to its settings', async () => { + const acme = provider(); + await render( { id: 'l1', type: 'form', form_type: acme.name, acme_form_id: 'f1', allow_skip: true }, acme ); + + expect( acme.getFormHtml ).toHaveBeenCalledWith( 'f1' ); + expect( lastProps( FormPreview ) ).toMatchObject( { html: '
', isFetching: false, allowSkip: true } ); + expect( lastProps( FormFields ) ).toMatchObject( { + formID: 'f1', + editUrl: `settings:${ acme.name }:f1`, + showEditButton: true, + } ); + } ); + + it( 'shows an error when the form can\'t be loaded', async () => { + const acme = provider( { getFormHtml: jest.fn( async () => { + throw new Error( 'nope' ); + } ) } ); + await render( { id: 'l1', type: 'form', form_type: acme.name, acme_form_id: 'f1' }, acme ); + + expect( lastProps( FormPreview ) ).toMatchObject( { html: '', error: 'The form could not be loaded.' } ); + } ); + + it( 'does not fetch forms while the provider is unavailable', async () => { + const acme = provider( { isAvailable: () => false } ); + await render( { id: 'l1', type: 'form', form_type: acme.name }, acme ); + + expect( acme.getForms ).not.toHaveBeenCalled(); + expect( lastProps( FormFields ) ).toMatchObject( { isActive: false, forms: [] } ); + } ); +} ); diff --git a/pages/video-editor/components/forms/fetchForms.js b/pages/video-editor/components/forms/fetchForms.js index 4bf57163d0..45f5cf74ba 100644 --- a/pages/video-editor/components/forms/fetchForms.js +++ b/pages/video-editor/components/forms/fetchForms.js @@ -1,3 +1,8 @@ +/** + * External dependencies + */ +import { getLayerVariationByName, isVariationAvailable } from '@godam/layers'; + /** * Internal dependencies */ @@ -10,45 +15,51 @@ import { useGetForminatorFormsQuery } from '../../redux/api/forminator-forms'; import { useGetFluentFormsQuery } from '../../redux/api/fluent-forms'; import { useGetEverestFormsQuery } from '../../redux/api/everest-forms'; import { useGetNinjaFormsQuery } from '../../redux/api/ninja-forms'; -import { FormLayerComponentType } from '../layers/FormLayer'; import { useGetMetformsQuery } from '../../redux/api/metform'; import { useGetHubspotFormsQuery } from '../../redux/api/hubspot-forms'; import { useGetMarketoFormsQuery } from '../../redux/api/marketo-forms'; +// GoDAM's own providers fetch their form lists here; a provider that isn't +// registered or whose plugin is inactive is skipped. +const isProviderAvailable = ( name ) => { + const provider = getLayerVariationByName( 'form', name ); + return Boolean( provider ) && isVariationAvailable( provider ); +}; + export const useFetchForms = () => { const { data: cf7Forms = [], isFetching: isFetchingCF7 = false } = useGetCF7FormsQuery( undefined, { - skip: ! FormLayerComponentType?.cf7.isActive, + skip: ! isProviderAvailable( 'cf7' ), } ); const { data: gravityForms = [], isFetching: isFetchingGravity = false } = useGetGravityFormsQuery( undefined, { - skip: ! FormLayerComponentType?.gravity.isActive, + skip: ! isProviderAvailable( 'gravity' ), } ); const { data: wpForms = [], isFetching: isFetchingWPForms = false } = useGetWPFormsQuery( undefined, { - skip: ! FormLayerComponentType?.wpforms.isActive, + skip: ! isProviderAvailable( 'wpforms' ), } ); const { data: jetpackForms = [], isFetching: isFetchingJetpack = false } = useGetJetpackFormsQuery( undefined, { - skip: ! FormLayerComponentType?.jetpack.isActive, + skip: ! isProviderAvailable( 'jetpack' ), } ); const { data: sureforms = [], isFetching: isFetchingSureforms = false } = useGetSureformsQuery( undefined, { - skip: ! FormLayerComponentType?.sureforms.isActive, + skip: ! isProviderAvailable( 'sureforms' ), } ); const { data: forminatorForms = [], isFetching: isFetchingForminator = false } = useGetForminatorFormsQuery( undefined, { - skip: ! FormLayerComponentType?.forminator.isActive, + skip: ! isProviderAvailable( 'forminator' ), } ); const { data: fluentForms = [], isFetching: isFetchingFluentForms = false } = useGetFluentFormsQuery( undefined, { - skip: ! FormLayerComponentType?.fluentforms.isActive, + skip: ! isProviderAvailable( 'fluentforms' ), } ); const { data: everestForms = [], isFetching: isFetchingEverestForms = false } = useGetEverestFormsQuery( undefined, { - skip: ! FormLayerComponentType?.everestforms.isActive, + skip: ! isProviderAvailable( 'everestforms' ), } ); const { data: ninjaForms = [], isFetching: isFetchingNinjaForms = false } = useGetNinjaFormsQuery( undefined, { - skip: ! FormLayerComponentType?.ninjaforms.isActive, + skip: ! isProviderAvailable( 'ninjaforms' ), } ); const { data: metforms = [], isFetching: isFetchingMetforms = false } = useGetMetformsQuery( undefined, { - skip: ! FormLayerComponentType?.metform.isActive, + skip: ! isProviderAvailable( 'metform' ), } ); const { data: hubspotForms = [], isFetching: isFetchingHubspotForms = false } = useGetHubspotFormsQuery( undefined, { - skip: ! FormLayerComponentType?.hubspot.isActive, + skip: ! isProviderAvailable( 'hubspot' ), } ); // The Marketo layer is always offered (a typed form ID works without a list), // so gate the list on the connection itself. diff --git a/pages/video-editor/components/layers/FormLayer.js b/pages/video-editor/components/layers/FormLayer.js index 2e63ad177a..f7e79d280e 100644 --- a/pages/video-editor/components/layers/FormLayer.js +++ b/pages/video-editor/components/layers/FormLayer.js @@ -2,11 +2,14 @@ * External dependencies */ import { useDispatch, useSelector } from 'react-redux'; +import { store as layersStore, getLayerVariation, isVariationAvailable } from '@godam/layers'; /** * WordPress dependencies */ -import { __ } from '@wordpress/i18n'; +import { __, sprintf } from '@wordpress/i18n'; +import { Notice } from '@wordpress/components'; +import { useSelect } from '@wordpress/data'; /** * Internal dependencies @@ -15,111 +18,12 @@ import { updateLayerField } from '../../redux/slice/videoSlice'; import ColorPickerButton from '../shared/color-picker/ColorPickerButton.jsx'; import LayersHeader from './LayersHeader.js'; import { VeSection, VeToggle, VeColorList } from '../controls'; -import GravityForm from '../forms/GravityForm'; -import WPForm from '../forms/WPForm'; -import EverestForm from '../forms/EverestForm'; -import CF7 from '../forms/CF7'; -import JetpackForm from '../forms/JetpackForm'; -import SureForm from '../forms/Sureform.js'; -import FluentForm from '../forms/FluentForm.js'; -import MetForm from '../forms/MetForm.js'; -import ForminatorForm from '../forms/forminatorForms.js'; -import NinjaForm from '../forms/NinjaForm.js'; -import Marketo from '../forms/Marketo.js'; -import HubSpotForm from '../forms/HubSpotForm.js'; +import FormProviderPanel from '../forms/FormProviderPanel'; /** - * FormLayer Components Object mapping. - */ -export const FormLayerComponentType = { - gravity: { - isActive: Boolean( window?.videoData?.gfActive ) ?? false, - component: GravityForm, - idField: 'gf_id', - settingsUrl: 'admin.php?subview=confirmation&page=gf_edit_forms&id={formId}&view=settings', - }, - cf7: { - isActive: Boolean( window?.videoData?.cf7Active ) ?? false, - component: CF7, - idField: 'cf7_id', - settingsUrl: 'admin.php?page=wpcf7&post={formId}&action=edit', - }, - jetpack: { - isActive: Boolean( window?.videoData?.jetpackActive ) ?? false, - component: JetpackForm, - idField: 'jp_id', - settingsUrl: 'admin.php?page=jetpack-forms-admin#/responses', - // Special handling for Jetpack forms (extract post ID from form ID) - getFormId: ( formId ) => { - if ( ! formId ) { - return null; - } - const parts = formId.split( '-' ); - return parts[ 0 ] ? parseInt( parts[ 0 ] ) : null; - }, - }, - wpforms: { - isActive: Boolean( window?.videoData?.wpformsActive ) ?? false, - component: WPForm, - idField: 'wpform_id', - settingsUrl: 'admin.php?page=wpforms-builder&view=settings&form_id={formId}§ion=general', - }, - sureforms: { - isActive: Boolean( window?.videoData?.sureformsActive ) ?? false, - component: SureForm, - idField: 'sureform_id', - settingsUrl: 'post.php?post={formId}&action=edit', - }, - forminator: { - isActive: Boolean( window?.videoData?.forminatorActive ) ?? false, - component: ForminatorForm, - idField: 'forminator_id', - settingsUrl: 'admin.php?page=forminator-cform-wizard&id={formId}', - }, - fluentforms: { - isActive: Boolean( window?.videoData?.fluentformsActive ) ?? false, - component: FluentForm, - idField: 'fluent_form_id', - settingsUrl: 'admin.php?page=fluent_forms&form_id={formId}&route=settings&sub_route=form_settings', - }, - everestforms: { - isActive: Boolean( window?.videoData?.everestFormsActive ) ?? false, - component: EverestForm, - idField: 'everest_form_id', - settingsUrl: 'admin.php?page=evf-builder&view=fields&form_id={formId}&tab=settings', - }, - ninjaforms: { - isActive: Boolean( window?.videoData?.ninjaFormsActive ) ?? false, - component: NinjaForm, - idField: 'ninja_form_id', - settingsUrl: 'admin.php?page=ninja-forms&form_id={formId}', - }, - metform: { - isActive: Boolean( window?.videoData?.metformActive ) ?? false, - component: MetForm, - idField: 'metform_id', - settingsUrl: '?post={formId}&action=elementor', - }, - marketo: { - // Marketo has no plugin to activate: the layer is always editable and the - // panel surfaces a notice when credentials are missing in settings. - isActive: true, - component: Marketo, - idField: 'marketo_id', - settingsUrl: 'admin.php?page=rtgodam_settings', - }, - hubspot: { - isActive: Boolean( window?.videoData?.hubspotActive ) ?? false, - component: HubSpotForm, - idField: 'hubspot_id', - // HubSpot forms are managed in HubSpot, not in wp-admin, so there is no - // local settings URL. - settingsUrl: '', - }, -}; - -/** - * Component to render and manage a form layer within the video editor. + * Component to render and manage a form layer within the video editor. The + * form plugin's part of the panel comes from the layer's form provider (a Form + * layer variation): its own `edit` panel, or the shared `FormProviderPanel`. * * @param {Object} param0 - Props passed to the FormLayer component. * @param {string} param0.layerID - Unique identifier for the form layer. @@ -132,16 +36,29 @@ const FormLayer = ( { layerID, goBack, duration } ) => { const dispatch = useDispatch(); const layer = useSelector( ( state ) => state.videoReducer.layers.find( ( _layer ) => _layer.id === layerID ) ); - const FormLayerData = FormLayerComponentType[ layer?.form_type ?? 'gravity' ]; - const FormLayerComponent = FormLayerData?.component; - const isPluginActive = FormLayerData?.isActive; + const formType = useSelect( ( select ) => select( layersStore ).getLayerType( 'form' ), [] ); + const provider = getLayerVariation( formType, layer ); + const ProviderPanel = provider?.edit; + const isPluginActive = Boolean( provider ) && isVariationAvailable( provider ); return ( <>
- + { provider && ProviderPanel && } + { provider && ! ProviderPanel && } + { ! provider && ( + + + { sprintf( + /* translators: %s is a form provider name stored on the layer, e.g. "acme-forms". */ + __( 'This layer uses the "%s" form, which isn\'t available. Activate the add-on that provides it, or delete the layer.', 'godam' ), + layer?.form_type, + ) } + + + ) }
diff --git a/pages/video-editor/components/layers/FormLayer.test.js b/pages/video-editor/components/layers/FormLayer.test.js new file mode 100644 index 0000000000..0175f3abab --- /dev/null +++ b/pages/video-editor/components/layers/FormLayer.test.js @@ -0,0 +1,103 @@ +/** + * Layer API (#2293): the Form layer opens its form provider's panel. + */ + +/** + * Internal dependencies + */ +import '../../../../tests/js/mock-form-provider-panels'; + +/** + * External dependencies + */ +import { act } from 'react'; +import { createRoot } from 'react-dom/client'; +import { Provider } from 'react-redux'; +import { configureStore } from '@reduxjs/toolkit'; +import { registerLayerVariation } from '@godam/layers'; + +/** + * Internal dependencies + */ +import FormLayer from './FormLayer'; +import { registerEditorLayerTypes } from '../../layers'; + +jest.mock( './CTALayer', () => () => null ); +jest.mock( './HotspotLayer', () => () => null ); +jest.mock( './PollLayer', () => () => null ); +jest.mock( './AdsLayer', () => () => null ); +jest.mock( './LayersHeader.js', () => () => null ); +jest.mock( '../shared/color-picker/ColorPickerButton.jsx', () => () => null ); +jest.mock( '../forms/FormProviderPanel', () => ( props ) => + require( 'react' ).createElement( 'div', { 'data-form-panel': `shared:${ props.provider.name }` } ), +); +jest.mock( '../controls', () => { + const { createElement: h, Fragment } = require( 'react' ); + return { + VeSection: ( { children } ) => h( Fragment, null, children ), + VeColorList: ( { children } ) => h( Fragment, null, children ), + VeToggle: ( { disabled } ) => h( 'input', { type: 'checkbox', 'data-test-id': 'allow-skip', disabled } ), + }; +} ); +jest.mock( '../../redux/slice/videoSlice', () => ( { + updateLayerField: ( payload ) => ( { type: 'updateLayerField', payload } ), +} ) ); + +window.videoData = { wpformsActive: true }; +window.godamVideoEditorConfig = {}; +registerEditorLayerTypes(); +registerLayerVariation( 'form', { name: 'acme-forms', title: 'Acme Forms', idField: 'acme_form_id' } ); + +describe( 'Layer API: FormLayer panel', () => { + let container, root; + + const render = ( layer ) => { + const store = configureStore( { reducer: { videoReducer: ( state = { layers: [ layer ] } ) => state } } ); + act( () => { + root.render( + + {} } duration={ 60 } /> + , + ); + } ); + }; + const panel = () => container.querySelector( '[data-form-panel]' )?.dataset.formPanel; + const allowSkip = () => container.querySelector( '[data-test-id="allow-skip"]' ); + + beforeEach( () => { + global.IS_REACT_ACT_ENVIRONMENT = true; + container = document.createElement( 'div' ); + root = createRoot( container ); + } ); + + afterEach( () => act( () => root.unmount() ) ); + + it( 'opens the layer\'s form provider panel', () => { + render( { id: 'l1', type: 'form', form_type: 'wpforms' } ); + expect( panel() ).toBe( 'wpforms' ); + expect( allowSkip().disabled ).toBe( false ); + } ); + + it( 'opens Gravity Forms for an older layer with no form_type', () => { + render( { id: 'l1', type: 'form' } ); + expect( panel() ).toBe( 'gravity' ); + } ); + + it( 'disables the shared settings when the provider\'s plugin is inactive', () => { + render( { id: 'l1', type: 'form', form_type: 'cf7' } ); + expect( panel() ).toBe( 'cf7' ); + expect( allowSkip().disabled ).toBe( true ); + } ); + + it( 'opens the shared panel for an add-on provider without its own', () => { + render( { id: 'l1', type: 'form', form_type: 'acme-forms' } ); + expect( panel() ).toBe( 'shared:acme-forms' ); + } ); + + it( 'warns when nothing provides the layer\'s form', () => { + render( { id: 'l1', type: 'form', form_type: 'mystery' } ); + expect( panel() ).toBeUndefined(); + expect( container.textContent ).toContain( 'This layer uses the "mystery" form, which isn\'t available.' ); + expect( allowSkip().disabled ).toBe( true ); + } ); +} ); diff --git a/pages/video-editor/components/layers/Layer.test.js b/pages/video-editor/components/layers/Layer.test.js index 9a4fcd13d4..517dfff97b 100644 --- a/pages/video-editor/components/layers/Layer.test.js +++ b/pages/video-editor/components/layers/Layer.test.js @@ -8,6 +8,11 @@ * add-on" notice instead of the CTA editor (RFC D2). */ +/** + * Internal dependencies + */ +import '../../../../tests/js/mock-form-provider-panels'; + /** * External dependencies */ diff --git a/pages/video-editor/components/timeline/Timeline.test.js b/pages/video-editor/components/timeline/Timeline.test.js index 8e51a0cbaf..832eb98b42 100644 --- a/pages/video-editor/components/timeline/Timeline.test.js +++ b/pages/video-editor/components/timeline/Timeline.test.js @@ -2,6 +2,11 @@ * Layer API (#2292): timeline markers come from the layer registry. */ +/** + * Internal dependencies + */ +import '../../../../tests/js/mock-form-provider-panels'; + /** * External dependencies */ diff --git a/pages/video-editor/layers/core/form.js b/pages/video-editor/layers/core/form.js index b2ffa1e656..3f4f65db2b 100644 --- a/pages/video-editor/layers/core/form.js +++ b/pages/video-editor/layers/core/form.js @@ -1,8 +1,14 @@ /** - * The Form layer. Each form plugin is a variation that sets `form_type`; #2293 - * turns these into separately registered providers. + * The Form layer. Each form plugin is a variation, registered separately with + * `registerLayerVariation( 'form', … )` (see ../form-providers.js); a + * variation's `name` is stored as the layer's `form_type`. */ +/** + * External dependencies + */ +import { getLayerType, isVariationAvailable } from '@godam/layers'; + /** * WordPress dependencies */ @@ -15,82 +21,17 @@ import metadata from '../../../../assets/src/layers/form/layer.json'; import FormLayer from '../../components/layers/FormLayer'; import { FormLayerIcon } from '../../components/editor-shell/icons'; import { getFormIdFromLayer } from '../../utils/formUtils'; -import GFIcon from '../../assets/layers/GFIcon.svg'; -import WPFormsIcon from '../../assets/layers/WPForms-Mascot.svg'; -import EverestFormsIcon from '../../assets/layers/EverestFormsIcon.svg'; -import CF7Icon from '../../assets/layers/CF7Icon.svg'; -import JetpackIcon from '../../assets/layers/JetpackIcon.svg'; -import SureformsIcon from '../../assets/layers/SureFormsIcons.svg'; -import ForminatorIcon from '../../assets/layers/Forminator.png'; -import FluentFormsIcon from '../../assets/layers/FluentFormsIcon.png'; -import NinjaFormsIcon from '../../assets/layers/NinjaFormsIcon.png'; -import MetformIcon from '../../assets/layers/MetFormIcon.png'; -import MarketoIcon from '../../assets/layers/MarketoIcon.svg'; -import HubSpotIcon from '../../assets/layers/HubSpotIcon.svg'; export { metadata }; -/** - * A form-plugin variation. Availability is read when asked, not at import, so - * page data localized after this module loads still counts. - * - * @param {string} name The `form_type` value. - * @param {string} title Display name. - * @param {string} icon Icon URL. - * @param {Function} isAvailable Whether the form plugin can be used. - * @param {string|Function} reason Why it can't, shown as a tooltip. - * @return {Object} The variation. - */ -const provider = ( name, title, icon, isAvailable, reason ) => ( { - name, - title, - icon, - attributes: { form_type: name }, - isAvailable, - get unavailableReason() { - return typeof reason === 'function' ? reason() : reason; - }, -} ); - -const flag = ( key ) => () => Boolean( window?.videoData?.[ key ] ); - -const hubspotReason = () => { - // Say what actually unblocks the layer: turning the integration on, or - // connecting the source the admin chose (GoDAM Central by default, where - // activating the HubSpot plugin alone is not enough). - if ( window?.videoData?.hubspotEnabled === false ) { - return __( 'Turn on HubSpot in Settings → Integrations → HubSpot to use this form', 'godam' ); - } - return 'leadin' === ( window?.videoData?.hubspotChosenSource ?? 'central' ) - ? __( 'Activate and connect the HubSpot plugin to use this form', 'godam' ) - : __( 'Connect HubSpot in Settings → Integrations → HubSpot to use this form', 'godam' ); -}; - -const variations = [ - { ...provider( 'gravity', __( 'Gravity Forms', 'godam' ), GFIcon, flag( 'gfActive' ), __( 'Gravity Forms plugin is not active', 'godam' ) ), isDefault: true }, - provider( 'wpforms', __( 'WPForms', 'godam' ), WPFormsIcon, flag( 'wpformsActive' ), __( 'WPForms plugin is not active', 'godam' ) ), - provider( 'cf7', __( 'Contact Form 7', 'godam' ), CF7Icon, flag( 'cf7Active' ), __( 'Contact Form 7 plugin is not active', 'godam' ) ), - provider( 'jetpack', __( 'Jetpack Forms', 'godam' ), JetpackIcon, flag( 'jetpackActive' ), __( 'Jetpack plugin is not active', 'godam' ) ), - provider( 'sureforms', __( 'SureForms', 'godam' ), SureformsIcon, flag( 'sureformsActive' ), __( 'SureForms plugin is not active', 'godam' ) ), - provider( 'forminator', __( 'Forminator Forms', 'godam' ), ForminatorIcon, flag( 'forminatorActive' ), __( 'Forminator Forms plugin is not active', 'godam' ) ), - provider( 'fluentforms', __( 'Fluent Forms', 'godam' ), FluentFormsIcon, flag( 'fluentformsActive' ), __( 'Fluent Forms plugin is not active', 'godam' ) ), - provider( 'everestforms', __( 'Everest Forms', 'godam' ), EverestFormsIcon, flag( 'everestFormsActive' ), __( 'Everest Forms plugin is not active', 'godam' ) ), - provider( 'ninjaforms', __( 'Ninja Forms', 'godam' ), NinjaFormsIcon, flag( 'ninjaFormsActive' ), __( 'Ninja Forms plugin is not active', 'godam' ) ), - provider( 'metform', __( 'MetForm', 'godam' ), MetformIcon, flag( 'metformActive' ), __( 'MetForm plugin is not active', 'godam' ) ), - // Marketo has no plugin to activate: it is always offered. Its settings panel - // links to Settings → Integrations → Marketo when credentials are missing. - provider( 'marketo', __( 'Marketo', 'godam' ), MarketoIcon, () => true, '' ), - provider( 'hubspot', __( 'HubSpot', 'godam' ), HubSpotIcon, flag( 'hubspotActive' ), hubspotReason ), -]; - export const settings = { title: __( 'Form', 'godam' ), description: __( 'Embed a lead form', 'godam' ), icon: FormLayerIcon, edit: FormLayer, - variations, + variationAttribute: 'form_type', getAvailability: () => ( - variations.some( ( variation ) => variation.isAvailable() ) + ( getLayerType( 'form' )?.variations || [] ).some( isVariationAvailable ) ? null : { available: false, reason: __( 'No form plugin is active', 'godam' ) } ), diff --git a/pages/video-editor/layers/form-providers.js b/pages/video-editor/layers/form-providers.js new file mode 100644 index 0000000000..ca2ca1fad3 --- /dev/null +++ b/pages/video-editor/layers/form-providers.js @@ -0,0 +1,208 @@ +/** + * GoDAM's own form providers: one Form layer variation per form plugin, + * registered through `registerLayerVariation( 'form', … )` like an add-on's + * provider would be (#2293). Registration order is the Form submenu order. + * + * A provider is described by: + * - `name` — the layer's `form_type` + * - `title`, `icon` — shown in the Form submenu, layer list and timeline + * - `isAvailable()`, `unavailableReason` — whether its plugin can be used, and why not (a string, or a function returning one) + * - `edit` — its settings panel + * - `idField` — the layer key that holds the chosen form's ID + * - `settingsUrl` — admin path to the form's settings, with `{formId}`, or a function of the form ID + */ + +/** + * External dependencies + */ +import { registerLayerVariation, getLayerVariationByName } from '@godam/layers'; + +/** + * WordPress dependencies + */ +import { __ } from '@wordpress/i18n'; + +/** + * Internal dependencies + */ +import GravityForm from '../components/forms/GravityForm'; +import WPForm from '../components/forms/WPForm'; +import EverestForm from '../components/forms/EverestForm'; +import CF7 from '../components/forms/CF7'; +import JetpackForm from '../components/forms/JetpackForm'; +import SureForm from '../components/forms/Sureform.js'; +import FluentForm from '../components/forms/FluentForm.js'; +import MetForm from '../components/forms/MetForm.js'; +import ForminatorForm from '../components/forms/forminatorForms.js'; +import NinjaForm from '../components/forms/NinjaForm.js'; +import Marketo from '../components/forms/Marketo.js'; +import HubSpotForm from '../components/forms/HubSpotForm.js'; +import GFIcon from '../assets/layers/GFIcon.svg'; +import WPFormsIcon from '../assets/layers/WPForms-Mascot.svg'; +import EverestFormsIcon from '../assets/layers/EverestFormsIcon.svg'; +import CF7Icon from '../assets/layers/CF7Icon.svg'; +import JetpackIcon from '../assets/layers/JetpackIcon.svg'; +import SureformsIcon from '../assets/layers/SureFormsIcons.svg'; +import ForminatorIcon from '../assets/layers/Forminator.png'; +import FluentFormsIcon from '../assets/layers/FluentFormsIcon.png'; +import NinjaFormsIcon from '../assets/layers/NinjaFormsIcon.png'; +import MetformIcon from '../assets/layers/MetFormIcon.png'; +import MarketoIcon from '../assets/layers/MarketoIcon.svg'; +import HubSpotIcon from '../assets/layers/HubSpotIcon.svg'; + +// Availability is read when asked, not at import, so page data localized after +// this module loads still counts. +const flag = ( key ) => () => Boolean( window?.videoData?.[ key ] ); + +const hubspotReason = () => { + // Say what actually unblocks the layer: turning the integration on, or + // connecting the source the admin chose (GoDAM Central by default, where + // activating the HubSpot plugin alone is not enough). + if ( window?.videoData?.hubspotEnabled === false ) { + return __( 'Turn on HubSpot in Settings → Integrations → HubSpot to use this form', 'godam' ); + } + return 'leadin' === ( window?.videoData?.hubspotChosenSource ?? 'central' ) + ? __( 'Activate and connect the HubSpot plugin to use this form', 'godam' ) + : __( 'Connect HubSpot in Settings → Integrations → HubSpot to use this form', 'godam' ); +}; + +// Jetpack form IDs are `-`; the form is edited on its post. +const jetpackSettingsUrl = ( formId ) => { + const postId = formId ? parseInt( String( formId ).split( '-' )[ 0 ], 10 ) : NaN; + return postId ? `post.php?post=${ postId }&action=edit` : 'admin.php?page=jetpack-forms-admin#/responses'; +}; + +export const coreFormProviders = () => [ + { + name: 'gravity', + title: __( 'Gravity Forms', 'godam' ), + icon: GFIcon, + isDefault: true, + isAvailable: flag( 'gfActive' ), + unavailableReason: __( 'Gravity Forms plugin is not active', 'godam' ), + edit: GravityForm, + idField: 'gf_id', + settingsUrl: 'admin.php?subview=confirmation&page=gf_edit_forms&id={formId}&view=settings', + }, + { + name: 'wpforms', + title: __( 'WPForms', 'godam' ), + icon: WPFormsIcon, + isAvailable: flag( 'wpformsActive' ), + unavailableReason: __( 'WPForms plugin is not active', 'godam' ), + edit: WPForm, + idField: 'wpform_id', + settingsUrl: 'admin.php?page=wpforms-builder&view=settings&form_id={formId}§ion=general', + }, + { + name: 'cf7', + title: __( 'Contact Form 7', 'godam' ), + icon: CF7Icon, + isAvailable: flag( 'cf7Active' ), + unavailableReason: __( 'Contact Form 7 plugin is not active', 'godam' ), + edit: CF7, + idField: 'cf7_id', + settingsUrl: 'admin.php?page=wpcf7&post={formId}&action=edit', + }, + { + name: 'jetpack', + title: __( 'Jetpack Forms', 'godam' ), + icon: JetpackIcon, + isAvailable: flag( 'jetpackActive' ), + unavailableReason: __( 'Jetpack plugin is not active', 'godam' ), + edit: JetpackForm, + idField: 'jp_id', + settingsUrl: jetpackSettingsUrl, + }, + { + name: 'sureforms', + title: __( 'SureForms', 'godam' ), + icon: SureformsIcon, + isAvailable: flag( 'sureformsActive' ), + unavailableReason: __( 'SureForms plugin is not active', 'godam' ), + edit: SureForm, + idField: 'sureform_id', + settingsUrl: 'post.php?post={formId}&action=edit', + }, + { + name: 'forminator', + title: __( 'Forminator Forms', 'godam' ), + icon: ForminatorIcon, + isAvailable: flag( 'forminatorActive' ), + unavailableReason: __( 'Forminator Forms plugin is not active', 'godam' ), + edit: ForminatorForm, + idField: 'forminator_id', + settingsUrl: 'admin.php?page=forminator-cform-wizard&id={formId}', + }, + { + name: 'fluentforms', + title: __( 'Fluent Forms', 'godam' ), + icon: FluentFormsIcon, + isAvailable: flag( 'fluentformsActive' ), + unavailableReason: __( 'Fluent Forms plugin is not active', 'godam' ), + edit: FluentForm, + idField: 'fluent_form_id', + settingsUrl: 'admin.php?page=fluent_forms&form_id={formId}&route=settings&sub_route=form_settings', + }, + { + name: 'everestforms', + title: __( 'Everest Forms', 'godam' ), + icon: EverestFormsIcon, + isAvailable: flag( 'everestFormsActive' ), + unavailableReason: __( 'Everest Forms plugin is not active', 'godam' ), + edit: EverestForm, + idField: 'everest_form_id', + settingsUrl: 'admin.php?page=evf-builder&view=fields&form_id={formId}&tab=settings', + }, + { + name: 'ninjaforms', + title: __( 'Ninja Forms', 'godam' ), + icon: NinjaFormsIcon, + isAvailable: flag( 'ninjaFormsActive' ), + unavailableReason: __( 'Ninja Forms plugin is not active', 'godam' ), + edit: NinjaForm, + idField: 'ninja_form_id', + settingsUrl: 'admin.php?page=ninja-forms&form_id={formId}', + }, + { + name: 'metform', + title: __( 'MetForm', 'godam' ), + icon: MetformIcon, + isAvailable: flag( 'metformActive' ), + unavailableReason: __( 'MetForm plugin is not active', 'godam' ), + edit: MetForm, + idField: 'metform_id', + settingsUrl: '?post={formId}&action=elementor', + }, + { + // Marketo has no plugin to activate: it is always offered, and its panel + // links to Settings → Integrations → Marketo when credentials are missing. + name: 'marketo', + title: __( 'Marketo', 'godam' ), + icon: MarketoIcon, + isAvailable: () => true, + unavailableReason: '', + edit: Marketo, + idField: 'marketo_id', + settingsUrl: 'admin.php?page=rtgodam_settings', + }, + { + name: 'hubspot', + title: __( 'HubSpot', 'godam' ), + icon: HubSpotIcon, + isAvailable: flag( 'hubspotActive' ), + unavailableReason: hubspotReason, + edit: HubSpotForm, + idField: 'hubspot_id', + // HubSpot forms are managed in HubSpot, not in wp-admin. + settingsUrl: '', + }, +]; + +export function registerCoreFormProviders() { + coreFormProviders().forEach( ( provider ) => { + if ( ! getLayerVariationByName( 'form', provider.name ) ) { + registerLayerVariation( 'form', provider ); + } + } ); +} diff --git a/pages/video-editor/layers/form-providers.test.js b/pages/video-editor/layers/form-providers.test.js new file mode 100644 index 0000000000..a726d41f72 --- /dev/null +++ b/pages/video-editor/layers/form-providers.test.js @@ -0,0 +1,105 @@ +/** + * Layer API (#2293): form providers are Form layer variations. + */ + +/** + * Internal dependencies + */ +import '../../../tests/js/mock-form-provider-panels'; + +/** + * External dependencies + */ +import { getLayerType, getLayerVariationByName, getDefaultAttributes, getLayerVariation, registerLayerVariation } from '@godam/layers'; + +/** + * Internal dependencies + */ +import { registerEditorLayerTypes } from './index'; +import { getFormIdFromLayer, buildSettingsUrl } from '../utils/formUtils'; + +jest.mock( '../components/layers/CTALayer', () => () => null ); +jest.mock( '../components/layers/HotspotLayer', () => () => null ); +jest.mock( '../components/layers/FormLayer', () => () => null ); +jest.mock( '../components/layers/PollLayer', () => () => null ); +jest.mock( '../components/layers/AdsLayer', () => () => null ); +jest.mock( '../redux/slice/videoSlice', () => ( { updateLayerField: jest.fn() } ) ); + +window.videoData = { adminUrl: 'https://example.com/wp-admin/' }; +window.godamVideoEditorConfig = {}; +registerEditorLayerTypes(); + +describe( 'Layer API: core form providers', () => { + it( 'registers the 12 form plugins as Form variations, in submenu order', () => { + expect( getLayerType( 'form' ).variations.map( ( { name } ) => name ) ).toEqual( [ + 'gravity', 'wpforms', 'cf7', 'jetpack', 'sureforms', 'forminator', + 'fluentforms', 'everestforms', 'ninjaforms', 'metform', 'marketo', 'hubspot', + ] ); + } ); + + it.each( [ + [ 'gravity', 'gf_id' ], + [ 'wpforms', 'wpform_id' ], + [ 'cf7', 'cf7_id' ], + [ 'jetpack', 'jp_id' ], + [ 'sureforms', 'sureform_id' ], + [ 'forminator', 'forminator_id' ], + [ 'fluentforms', 'fluent_form_id' ], + [ 'everestforms', 'everest_form_id' ], + [ 'ninjaforms', 'ninja_form_id' ], + [ 'metform', 'metform_id' ], + [ 'marketo', 'marketo_id' ], + [ 'hubspot', 'hubspot_id' ], + ] )( '%s keeps its form ID in %s, selected by form_type', ( name, idField ) => { + const provider = getLayerVariationByName( 'form', name ); + expect( provider.idField ).toBe( idField ); + expect( provider.attributes ).toEqual( { form_type: name } ); + expect( typeof provider.edit ).toBe( 'function' ); + expect( getFormIdFromLayer( { form_type: name, [ idField ]: '7' }, name ) ).toBe( '7' ); + } ); + + it( 'has no form ID for a layer without one or a provider nobody registered', () => { + expect( getFormIdFromLayer( { form_type: 'gravity' }, 'gravity' ) ).toBeNull(); + expect( getFormIdFromLayer( { form_type: 'mystery', form_id: '7' }, 'mystery' ) ).toBeNull(); + } ); + + it( 'builds each provider\'s settings URL as before', () => { + expect( buildSettingsUrl( 'gravity', '3' ) ).toBe( 'https://example.com/wp-admin/admin.php?subview=confirmation&page=gf_edit_forms&id=3&view=settings' ); + expect( buildSettingsUrl( 'cf7', '9' ) ).toBe( 'https://example.com/wp-admin/admin.php?page=wpcf7&post=9&action=edit' ); + expect( buildSettingsUrl( 'jetpack', '42-1' ) ).toBe( 'https://example.com/wp-admin/post.php?post=42&action=edit' ); + expect( buildSettingsUrl( 'jetpack', '' ) ).toBe( 'https://example.com/wp-admin/admin.php?page=jetpack-forms-admin#/responses' ); + expect( buildSettingsUrl( 'hubspot', 'abc' ) ).toBe( 'https://example.com/wp-admin/' ); + expect( buildSettingsUrl( 'mystery', '1' ) ).toBe( '#' ); + } ); +} ); + +describe( 'Layer API: an add-on form provider', () => { + beforeAll( () => { + registerLayerVariation( 'form', { + name: 'acme-forms', + title: 'Acme Forms', + idField: 'acme_form_id', + isAvailable: () => true, + settingsUrl: ( formId ) => `https://acme.example/forms/${ formId }`, + getForms: async () => [], + getFormHtml: async () => '', + } ); + } ); + + it( 'joins the Form variations after the core providers', () => { + expect( getLayerType( 'form' ).variations.at( -1 ).name ).toBe( 'acme-forms' ); + } ); + + it( 'gives a new layer its form_type', () => { + const form = getLayerType( 'form' ); + expect( getDefaultAttributes( form, getLayerVariationByName( 'form', 'acme-forms' ) ) ).toMatchObject( { form_type: 'acme-forms' } ); + expect( getLayerVariation( form, { form_type: 'acme-forms' } ).title ).toBe( 'Acme Forms' ); + } ); + + it( 'uses its idField for the save check and its own settings URL', () => { + const { validate } = getLayerType( 'form' ); + expect( validate( { form_type: 'acme-forms' } ) ).toBe( false ); + expect( validate( { form_type: 'acme-forms', acme_form_id: '5' } ) ).toBe( true ); + expect( buildSettingsUrl( 'acme-forms', '5' ) ).toBe( 'https://acme.example/forms/5' ); + } ); +} ); diff --git a/pages/video-editor/layers/index.js b/pages/video-editor/layers/index.js index 6fe06900ee..8c42568de2 100644 --- a/pages/video-editor/layers/index.js +++ b/pages/video-editor/layers/index.js @@ -1,16 +1,19 @@ /** - * Register every layer type the editor knows: GoDAM's own, then those add-ons - * described through the old hooks. Add-ons on the Layer API register - * themselves through `window.godam.layers.registerLayerType()`. + * Register every layer type the editor knows: GoDAM's own, its form providers + * (Form layer variations), then the types add-ons described through the old + * hooks. Add-ons on the Layer API register themselves through + * `window.godam.layers.registerLayerType()` and `registerLayerVariation()`. */ /** * Internal dependencies */ import { registerCoreLayerTypes } from './core'; +import { registerCoreFormProviders } from './form-providers'; import { registerLegacyLayerTypes } from './legacy'; export function registerEditorLayerTypes() { registerCoreLayerTypes(); + registerCoreFormProviders(); registerLegacyLayerTypes(); } diff --git a/pages/video-editor/layers/layers.test.js b/pages/video-editor/layers/layers.test.js index 0068b4e0d0..fd2d5446fe 100644 --- a/pages/video-editor/layers/layers.test.js +++ b/pages/video-editor/layers/layers.test.js @@ -3,6 +3,11 @@ * add-on hooks, and the hooks settings panels use. */ +/** + * Internal dependencies + */ +import '../../../tests/js/mock-form-provider-panels'; + /** * External dependencies */ @@ -17,6 +22,7 @@ import { getAvailability, getDefaultAttributes, getLayerVariation, + getUnavailableReason, supportsMedia, } from '@godam/layers'; @@ -94,10 +100,10 @@ describe( 'Layer API: core layer types', () => { it( 'explains why HubSpot is unavailable based on its settings', () => { const hubspot = getLayerType( 'form' ).variations.find( ( { name } ) => name === 'hubspot' ); window.videoData.hubspotEnabled = false; - expect( hubspot.unavailableReason ).toMatch( /Turn on HubSpot/ ); + expect( getUnavailableReason( hubspot ) ).toMatch( /Turn on HubSpot/ ); window.videoData.hubspotEnabled = true; window.videoData.hubspotChosenSource = 'leadin'; - expect( hubspot.unavailableReason ).toMatch( /Activate and connect the HubSpot plugin/ ); + expect( getUnavailableReason( hubspot ) ).toMatch( /Activate and connect the HubSpot plugin/ ); } ); it( 'keeps Form available with no form plugin active, because Marketo needs none', () => { diff --git a/pages/video-editor/utils/formUtils.js b/pages/video-editor/utils/formUtils.js index e1cc8665cf..49a37578ee 100644 --- a/pages/video-editor/utils/formUtils.js +++ b/pages/video-editor/utils/formUtils.js @@ -1,52 +1,42 @@ /** * External dependencies */ +import { getLayerVariationByName } from '@godam/layers'; /** - * Internal dependencies - */ -import { FormLayerComponentType } from '../components/layers/FormLayer'; - -/** - * Helper function to get form ID from layer data + * The form ID a form layer holds, read from its provider's `idField`. * * @param {Object} layer - The layer object - * @param {string} formType - The form type + * @param {string} formType - The layer's `form_type` (its form provider) * @return {string|null} - The form ID or null if not found */ export const getFormIdFromLayer = ( layer, formType ) => { - const config = FormLayerComponentType[ formType ]; - if ( ! config || ! config.idField ) { + const idField = getLayerVariationByName( 'form', formType )?.idField; + if ( ! idField ) { return null; } - return layer[ config.idField ] || null; + return layer?.[ idField ] || null; }; /** - * Helper function to build settings URL for a form + * The admin URL of a form's settings, from its provider's `settingsUrl`: an + * admin path with `{formId}`, or a function of the form ID. A full URL is used + * as it is; anything else is relative to wp-admin. * - * @param {string} formType - The form type + * @param {string} formType - The layer's `form_type` (its form provider) * @param {string} formId - The form ID * @return {string} - The complete settings URL */ export const buildSettingsUrl = ( formType, formId ) => { - const config = FormLayerComponentType[ formType ]; - if ( ! config ) { + const provider = getLayerVariationByName( 'form', formType ); + if ( ! provider ) { return '#'; } - const adminUrl = window?.videoData?.adminUrl || ''; - let url = config.settingsUrl; - - // Special handling for Jetpack forms - if ( formType === 'jetpack' && config.getFormId ) { - const postId = config.getFormId( formId ); - if ( postId ) { - url = `post.php?post=${ postId }&action=edit`; - } - } else { - url = url.replace( '{formId}', formId ); - } + const { settingsUrl = '' } = provider; + const path = typeof settingsUrl === 'function' + ? settingsUrl( formId ) + : String( settingsUrl ).replace( '{formId}', formId ); - return `${ adminUrl }${ url }`; + return /^https?:\/\//.test( path ) ? path : `${ window?.videoData?.adminUrl || '' }${ path }`; }; diff --git a/tests/js/mock-form-provider-panels.js b/tests/js/mock-form-provider-panels.js new file mode 100644 index 0000000000..c529a18e78 --- /dev/null +++ b/tests/js/mock-form-provider-panels.js @@ -0,0 +1,69 @@ +/** + * Stubs for GoDAM's 12 form provider panels, for tests that register the + * editor's layer types (#2293). The real panels load their RTK Query API slices, + * which read page globals when imported. Each stub renders a + * `data-form-panel` marker naming its provider. + * + * Import this before the module under test. It lives under /tests so it stays + * out of the release package. + */ + +jest.mock( '../../pages/video-editor/components/forms/GravityForm', () => ( { + __esModule: true, + default: () => require( 'react' ).createElement( 'div', { 'data-form-panel': 'gravity' } ), +} ) ); + +jest.mock( '../../pages/video-editor/components/forms/WPForm', () => ( { + __esModule: true, + default: () => require( 'react' ).createElement( 'div', { 'data-form-panel': 'wpforms' } ), +} ) ); + +jest.mock( '../../pages/video-editor/components/forms/EverestForm', () => ( { + __esModule: true, + default: () => require( 'react' ).createElement( 'div', { 'data-form-panel': 'everestforms' } ), +} ) ); + +jest.mock( '../../pages/video-editor/components/forms/CF7', () => ( { + __esModule: true, + default: () => require( 'react' ).createElement( 'div', { 'data-form-panel': 'cf7' } ), +} ) ); + +jest.mock( '../../pages/video-editor/components/forms/JetpackForm', () => ( { + __esModule: true, + default: () => require( 'react' ).createElement( 'div', { 'data-form-panel': 'jetpack' } ), +} ) ); + +jest.mock( '../../pages/video-editor/components/forms/Sureform.js', () => ( { + __esModule: true, + default: () => require( 'react' ).createElement( 'div', { 'data-form-panel': 'sureforms' } ), +} ) ); + +jest.mock( '../../pages/video-editor/components/forms/FluentForm.js', () => ( { + __esModule: true, + default: () => require( 'react' ).createElement( 'div', { 'data-form-panel': 'fluentforms' } ), +} ) ); + +jest.mock( '../../pages/video-editor/components/forms/MetForm.js', () => ( { + __esModule: true, + default: () => require( 'react' ).createElement( 'div', { 'data-form-panel': 'metform' } ), +} ) ); + +jest.mock( '../../pages/video-editor/components/forms/forminatorForms.js', () => ( { + __esModule: true, + default: () => require( 'react' ).createElement( 'div', { 'data-form-panel': 'forminator' } ), +} ) ); + +jest.mock( '../../pages/video-editor/components/forms/NinjaForm.js', () => ( { + __esModule: true, + default: () => require( 'react' ).createElement( 'div', { 'data-form-panel': 'ninjaforms' } ), +} ) ); + +jest.mock( '../../pages/video-editor/components/forms/Marketo.js', () => ( { + __esModule: true, + default: () => require( 'react' ).createElement( 'div', { 'data-form-panel': 'marketo' } ), +} ) ); + +jest.mock( '../../pages/video-editor/components/forms/HubSpotForm.js', () => ( { + __esModule: true, + default: () => require( 'react' ).createElement( 'div', { 'data-form-panel': 'hubspot' } ), +} ) ); From fe09175061c7c895dae7c7d417dfad41ddf0d153 Mon Sep 17 00:00:00 2001 From: KMchaudhary Date: Wed, 4 Nov 2026 14:29:01 +0530 Subject: [PATCH 07/20] feat(layers): run video and image layers on one front-end runtime Adds the Layer API front-end runtime (#2294): registerLayerRuntime( name, { validate, mount, supports, usesIconFont, variations } ) on window.godam.layers, plus a layer host that mounts each saved layer and forwards player events (onReady, onTimeUpdate, onPause, onEnded, onPlay, onResize, onFullscreenChange, onReplay, destroy) to the handlers mount() returns. ctx.api gives pause, play, seek, show, hide, track and isSuppressed. - LayersManager and render-image-frame both mount through the host and no longer branch on layer type names. - CTA, Form, Poll and Hotspot are core runtimes; CTA, Form and Poll share one FormLayerManager, which now takes a per-type behaviour. - The 12 form providers register their front-end part as Form variations: availability, "submitted" detection and analytics label. This replaces LayerValidator, FORM_TYPES and hasConfirmationMessage. - Hover-preview suppression covers every runtime, including layers from GoDAMAPI.createLayer() (RFC D5), which now mount on the same host. - window.godamLayerRegistry is a shim over the new registry, and still drains window.godamLayerRegistryQueue. The window store workaround is gone, and godam-for-woo's manager runs unchanged on video and images. - An unregistered type is logged once and skipped (RFC D2). Refs #2294 Co-Authored-By: Claude Opus 5.5 --- .../godam-image-layers/render-image-frame.js | 163 +++------- .../render-image-frame.test.js | 55 +++- assets/src/js/godam-layers/index.js | 3 +- assets/src/js/godam-layers/runtime/host.js | 268 ++++++++++++++++ .../src/js/godam-layers/runtime/registry.js | 279 ++++++++++++++++ .../js/godam-layers/runtime/runtime.test.js | 298 ++++++++++++++++++ assets/src/js/godam-player/api/player.js | 119 +++++-- .../js/godam-player/api/player.layers.test.js | 91 ++++++ assets/src/js/godam-player/layers/cta.js | 31 ++ .../js/godam-player/layers/form-providers.js | 106 +++++++ assets/src/js/godam-player/layers/form.js | 80 +++++ assets/src/js/godam-player/layers/hotspot.js | 115 +++++++ assets/src/js/godam-player/layers/index.js | 23 ++ .../src/js/godam-player/layers/layers.test.js | 195 ++++++++++++ assets/src/js/godam-player/layers/overlay.js | 53 ++++ assets/src/js/godam-player/layers/poll.js | 53 ++++ .../js/godam-player/managers/layers/README.md | 7 +- .../managers/layers/formLayerManager.js | 214 ++++--------- .../managers/layers/formLayerManager.test.js | 11 +- .../managers/layers/layerValidator.js | 74 ----- .../managers/layersManager.contract.test.js | 227 +++++++++---- .../js/godam-player/managers/layersManager.js | 238 ++++---------- .../managers/layersManager.test.js | 94 +++--- .../godam-player/utils/LAYER-REGISTRY-API.md | 15 +- assets/src/js/godam-player/utils/constants.js | 41 --- .../js/godam-player/utils/layer-registry.js | 207 +++++++----- .../godam-player/utils/layer-registry.test.js | 36 ++- .../src/js/godam-player/utils/layerActions.js | 54 +--- .../src/js/godam-player/utils/pluginLoader.js | 40 --- assets/src/js/godam-player/videoPlayer.js | 17 +- docs/rfcs/layer-api.md | 2 +- 31 files changed, 2310 insertions(+), 899 deletions(-) create mode 100644 assets/src/js/godam-layers/runtime/host.js create mode 100644 assets/src/js/godam-layers/runtime/registry.js create mode 100644 assets/src/js/godam-layers/runtime/runtime.test.js create mode 100644 assets/src/js/godam-player/api/player.layers.test.js create mode 100644 assets/src/js/godam-player/layers/cta.js create mode 100644 assets/src/js/godam-player/layers/form-providers.js create mode 100644 assets/src/js/godam-player/layers/form.js create mode 100644 assets/src/js/godam-player/layers/hotspot.js create mode 100644 assets/src/js/godam-player/layers/index.js create mode 100644 assets/src/js/godam-player/layers/layers.test.js create mode 100644 assets/src/js/godam-player/layers/overlay.js create mode 100644 assets/src/js/godam-player/layers/poll.js delete mode 100644 assets/src/js/godam-player/managers/layers/layerValidator.js diff --git a/assets/src/js/godam-image-layers/render-image-frame.js b/assets/src/js/godam-image-layers/render-image-frame.js index 08ca3262ca..62558b7c49 100644 --- a/assets/src/js/godam-image-layers/render-image-frame.js +++ b/assets/src/js/godam-image-layers/render-image-frame.js @@ -1,17 +1,16 @@ /** * GoDAM Image Layers — shared frame renderer. * - * Draws hotspot and WooCommerce product-hotspot layers onto a single - * `.godam-image__frame` element. Extracted so it can be reused by both the + * Draws the saved layers of one `.godam-image__frame` element. Used by both the * front-end bootstrap (frontend.js) and the block editor preview (the * `godam/image` block's edit.js), which renders the same markup into the * editor canvas and calls this against a ref. * - * It reuses the existing player-side managers unchanged except for a single - * seam: `manager.computeContentRect` is overridden with an image-box - * implementation (the managers' own version reads a `
diff --git a/tests/fixtures/layers/acme-countdown/layer.json b/tests/fixtures/layers/acme-countdown/layer.json new file mode 100644 index 0000000000..3f1c236160 --- /dev/null +++ b/tests/fixtures/layers/acme-countdown/layer.json @@ -0,0 +1,6 @@ +{ + "apiVersion": 1, + "name": "acme/countdown-file", + "title": "Countdown from file", + "supports": { "media": [ "video", "image" ] } +} diff --git a/tests/php/ImageBlockLayerContractTest.php b/tests/php/ImageBlockLayerContractTest.php index 7cac5cb371..320cb8180c 100644 --- a/tests/php/ImageBlockLayerContractTest.php +++ b/tests/php/ImageBlockLayerContractTest.php @@ -3,12 +3,12 @@ * Layer API contract (#2291): which saved layers the `godam/image` block sends * to the browser. * - * render.php keeps `hotspot` layers that have hotspots and `woo` layers that have - * product hotspots, and drops everything else before the front end sees it. It - * only loads the image-layers script when something is left, and lets add-ons - * add script dependencies through `godam_image_layers_frontend_dependencies`. - * #2294 and #2295 replace the hard-coded type checks; tests marked "current - * behaviour" pin what they intend to change on purpose. + * render.php sends the layers whose registered type supports images and has + * something to draw (#2295): core `hotspot` layers with hotspots and legacy + * `woo` layers with product hotspots, plus any add-on type registered with + * `supports.media: [ 'image' ]`. It only loads the image-layers script when + * something is left, and lets add-ons add script dependencies through + * `godam_image_layers_frontend_dependencies`. * * @package GoDAM */ @@ -21,6 +21,7 @@ require_once dirname( __DIR__ ) . '/stubs/i18n.php'; require_once dirname( __DIR__ ) . '/stubs/script-functions.php'; require_once dirname( __DIR__ ) . '/stubs/block-render-functions.php'; +require_once dirname( __DIR__ ) . '/stubs/layer-registry.php'; if ( ! defined( 'RTGODAM_PATH' ) ) { define( 'RTGODAM_PATH', dirname( __DIR__, 2 ) . '/' ); @@ -48,6 +49,7 @@ protected function setUp(): void { 'inline' => array(), ); $GLOBALS['rtgodam_stub'] = array(); + rtgodam_test_register_core_layer_types(); } /** @@ -113,7 +115,7 @@ public function test_sends_hotspot_and_woo_layers_in_saved_order(): void { } /** - * Current behaviour: any other type is dropped on the server, even when an add-on handles it in JS. + * Video-only and unregistered types are dropped on the server. */ public function test_drops_every_other_layer_type(): void { $keep = array( @@ -142,6 +144,24 @@ public function test_drops_every_other_layer_type(): void { $this->assertSame( array( $keep ), $sent ); } + /** + * An add-on type registered with image support is sent too. + */ + public function test_sends_an_add_on_type_that_supports_images(): void { + godam_register_layer_type( + array( + 'name' => 'acme/badge', + 'supports' => array( 'media' => array( 'image' ) ), + ) + ); + $badge = array( + 'id' => 'b1', + 'type' => 'acme/badge', + ); + + $this->assertSame( array( $badge ), $this->sent_layers( $this->render( array( $badge ) ) ) ); + } + /** * Empty hotspot and woo layers, untyped layers and non-array entries are dropped. */ diff --git a/tests/php/LayerTypeRegistryTest.php b/tests/php/LayerTypeRegistryTest.php new file mode 100644 index 0000000000..f93d064787 --- /dev/null +++ b/tests/php/LayerTypeRegistryTest.php @@ -0,0 +1,498 @@ +assertSame( array( 'cta', 'form', 'poll', 'hotspot', 'ad', 'woo' ), array_keys( $this->registry()->get_all() ) ); + $this->assertSame( 'Hotspot', godam_get_layer_type( 'hotspot' )['title'] ); + $this->assertSame( array( 'video', 'image' ), godam_get_layer_type( 'hotspot' )['supports']['media'] ); + $this->assertSame( array( 'video' ), godam_get_layer_type( 'cta' )['supports']['media'] ); + $this->assertTrue( godam_get_layer_type( 'cta' )['supports']['rawHtml'] ); + } + + /** + * An add-on registers from a folder or a metadata array, and the metadata filter runs. + */ + public function test_registers_an_add_on_type_and_filters_its_metadata(): void { + add_filter( + 'godam_layer_type_metadata', + function ( $metadata ) { + $metadata['title'] = 'Filtered ' . ( $metadata['title'] ?? '' ); + return $metadata; + } + ); + + $type = godam_register_layer_type( + array( + 'name' => 'acme/countdown', + 'title' => 'Countdown', + ), + array( + 'render_callback' => function () { + return ''; + }, + ) + ); + + $this->assertSame( 'Filtered Countdown', $type['title'] ); + $this->assertSame( array( 'video' ), $type['supports']['media'] ); + + $from_file = godam_register_layer_type( RTGODAM_PATH . 'tests/fixtures/layers/acme-countdown' ); + $this->assertSame( 'Filtered Countdown from file', $from_file['title'] ); + $this->assertSame( array( 'video', 'image' ), $from_file['supports']['media'] ); + } + + /** + * A nameless or duplicate type is rejected with a notice. + */ + public function test_rejects_a_nameless_or_duplicate_type(): void { + $this->assertFalse( godam_register_layer_type( array( 'title' => 'No name' ) ) ); + $this->assertFalse( godam_register_layer_type( array( 'name' => 'cta' ) ) ); + $this->assertFalse( godam_register_layer_type( '/no/such/layer.json' ) ); + $this->assertSame( + array( 'A layer type needs a name.', 'Layer type "cta" is already registered.', 'Layer type metadata could not be read.' ), + $GLOBALS['rtgodam_stub']['doing_it_wrong'] + ); + } + + /** + * Form providers are variations selected by form_type; an old layer with none uses Gravity Forms. + */ + public function test_selects_the_form_provider_by_form_type(): void { + $form = godam_get_layer_type( 'form' ); + $this->assertSame( + array( 'gravity', 'wpforms', 'cf7', 'jetpack', 'sureforms', 'forminator', 'fluentforms', 'everestforms', 'ninjaforms', 'metform', 'marketo', 'hubspot' ), + array_column( $form['variations'], 'name' ) + ); + $this->assertSame( 'WPForms', $this->registry()->get_layer_variation( $form, array( 'form_type' => 'wpforms' ) )['title'] ); + $this->assertSame( 'gravity', $this->registry()->get_layer_variation( $form, array() )['name'] ); + $this->assertNull( $this->registry()->get_layer_variation( $form, array( 'form_type' => 'mystery' ) ) ); + } + + /** + * A variation registered before its type is added once the type registers. + */ + public function test_keeps_a_variation_registered_before_its_type(): void { + godam_register_layer_variation( 'acme/form', array( 'name' => 'early' ) ); + godam_register_layer_type( + array( + 'name' => 'acme/form', + 'variationAttribute' => 'kind', + ) + ); + + $this->assertSame( array( 'kind' => 'early' ), godam_get_layer_type( 'acme/form' )['variations'][0]['attributes'] ); + $this->assertFalse( godam_register_layer_variation( 'acme/form', array( 'name' => 'early' ) ) ); + } + + /** + * The player's dependency flags come from each type's and provider's is_available. + */ + public function test_reports_availability_under_each_dependency_key(): void { + $GLOBALS['rtgodam_stub']['active_plugins'] = array( 'wpforms-lite/wpforms.php', 'wp-polls/wp-polls.php' ); + godam_unregister_layer_type( 'form' ); + godam_register_layer_type( + array( 'name' => 'acme/x' ), + array( + 'dependency_key' => 'acmeX', + 'is_available' => function () { + return false; + }, + ) + ); + + $this->assertSame( + array( + 'wpPolls' => true, + 'acmeX' => false, + ), + $this->registry()->get_dependency_flags() + ); + + rtgodam_test_register_core_layer_types(); + $form = godam_get_layer_type( 'form' ); + $this->assertTrue( $this->registry()->is_available( $this->registry()->get_layer_variation( $form, array( 'form_type' => 'wpforms' ) ) ) ); + $this->assertFalse( $this->registry()->is_available( $this->registry()->get_layer_variation( $form, array( 'form_type' => 'cf7' ) ) ) ); + } + + /** + * A layer with no type, or not an array, renders nothing. + */ + public function test_renders_nothing_for_a_typeless_layer(): void { + $this->assertSame( '', godam_render_layer( array( 'id' => 'x' ), 'video_1' ) ); + $this->assertSame( '', godam_render_layer( 'nope', 'video_1' ) ); + } + + /** + * A type with no PHP registration renders through the old godam_player_render_layer action, on video only. + */ + public function test_renders_an_unregistered_type_through_the_old_action(): void { + add_action( + 'godam_player_render_layer', + function ( $layer, $instance_id ) { + echo '
'; + }, + 10, + 2 + ); + $layer = array( + 'id' => 'a1', + 'type' => 'acme', + ); + + $this->assertSame( '
', godam_render_layer( $layer, 'video_1' ) ); + $this->assertSame( '', godam_render_layer( $layer, 'img_1', array( 'media' => 'image' ) ) ); + } + + /** + * An add-on's output goes through wp_kses_post() unless it sets supports.rawHtml. + */ + public function test_escapes_add_on_output_unless_it_opts_out(): void { + $GLOBALS['rtgodam_stub']['kses_strip_disallowed'] = true; + $render = function () { + return '
'; + }; + godam_register_layer_type( array( 'name' => 'acme/safe' ), array( 'render_callback' => $render ) ); + godam_register_layer_type( + array( + 'name' => 'acme/raw', + 'supports' => array( 'rawHtml' => true ), + ), + array( 'render_callback' => $render ) + ); + + $this->assertSame( '
alert(1)
', godam_render_layer( array( 'type' => 'acme/safe' ), 'v' ) ); + $this->assertStringContainsString( '', + 'items' => array( 1, 2 ), + 'iconId' => 'abc', + 'duration' => '5', + 'allow_skip' => 0, + 'secretField' => 'dropped', + ) + ) + ); + } + + /** + * A value of the wrong type falls back to the attribute's default, or is removed. + */ + public function test_replaces_wrong_types_with_the_default(): void { + $clean = $this->clean( + array( + 'type' => 'acme/countdown', + 'label' => array( 'not', 'a', 'string' ), + 'seconds' => 2.5, + 'accent' => 'red; background: url(x)', + 'loop' => 'maybe', + 'items' => 'nope', + ) + ); + + $this->assertSame( + array( + 'type' => 'acme/countdown', + 'label' => '', + 'seconds' => 10, + 'accent' => '#000', + ), + $clean + ); + } + + /** + * Valid colors are kept. + */ + public function test_keeps_valid_colors(): void { + foreach ( array( '#FFFFFFB3', '#abc', 'rgba(0, 0, 0, 0.5)', 'transparent' ) as $color ) { + $this->assertSame( + $color, + $this->clean( + array( + 'type' => 'acme/countdown', + 'accent' => $color, + ) + )['accent'] + ); + } + } + + /** + * Core types are lenient: declared values of the right type are sanitized, everything else + * (including HTML, which is escaped when it renders) is kept. + */ + public function test_keeps_undeclared_and_mismatched_values_on_core_layers(): void { + $layer = array( + 'id' => 'c1', + 'type' => 'cta', + 'cta_type' => 'html', + 'html' => '

Buy

', + 'link' => 'https://example.com/buy', + 'imageText' => 'Undeclared, kept', + 'bg_color' => '#FFFFFFB3', + 'watchDepth' => 'not a number', + ); + + $this->assertSame( + array( + 'id' => 'c1', + 'type' => 'cta', + 'cta_type' => 'html', + 'html' => '

Buy

', + 'link' => 'https://example.com/buy', + 'imageText' => 'Undeclared, kept', + 'bg_color' => '#FFFFFFB3', + 'watchDepth' => 'not a number', + ), + $this->clean( $layer ) + ); + } + + /** + * A poll layer's numeric poll_id stays a number: lenient types don't convert. + */ + public function test_does_not_convert_core_values(): void { + $this->assertSame( + 4, + $this->clean( + array( + 'type' => 'poll', + 'poll_id' => 4, + ) + )['poll_id'] + ); + } + + /** + * Layers of an unregistered type, typeless layers and junk entries are kept unchanged. + */ + public function test_keeps_unregistered_and_malformed_layers(): void { + $layers = array( + array( + 'type' => 'acme/gone', + 'stuff' => '', + ), + array( 'id' => 'no-type' ), + 'junk', + ); + + $this->assertSame( $layers, Layer_Type_Registry::get_instance()->sanitize_layers( $layers ) ); + $this->assertSame( 'not-a-list', Layer_Type_Registry::get_instance()->sanitize_layers( 'not-a-list' ) ); + } + + /** + * A variation can declare the attributes it adds, e.g. a form provider's ID field. + */ + public function test_uses_the_variation_attribute_schema(): void { + godam_register_layer_type( + array( + 'name' => 'acme/form', + 'variationAttribute' => 'provider', + 'attributes' => array( 'provider' => array( 'type' => 'string' ) ), + ) + ); + godam_register_layer_variation( + 'acme/form', + array( + 'name' => 'acme', + 'attributeSchema' => array( 'acme_id' => array( 'type' => 'integer' ) ), + ) + ); + + $this->assertSame( + array( + 'type' => 'acme/form', + 'provider' => 'acme', + 'acme_id' => 7, + ), + $this->clean( + array( + 'type' => 'acme/form', + 'provider' => 'acme', + 'acme_id' => '7', + 'other_id' => 9, + ) + ) + ); + } + + /** + * Attributes marked private never reach the page. + */ + public function test_strips_private_attributes_for_the_page(): void { + godam_register_layer_type( RTGODAM_PATH . 'tests/fixtures/layers/acme-countdown' ); + + $this->assertSame( + array( + 'id' => 'a1', + 'type' => 'acme/countdown-file', + 'label' => 'Hi', + ), + Layer_Type_Registry::get_instance()->get_public_layer( + array( + 'id' => 'a1', + 'type' => 'acme/countdown-file', + 'label' => 'Hi', + 'apiToken' => 'secret', + ) + ) + ); + } +} diff --git a/tests/stubs/layer-registry.php b/tests/stubs/layer-registry.php index 46793fd677..674fa9c09b 100644 --- a/tests/stubs/layer-registry.php +++ b/tests/stubs/layer-registry.php @@ -8,6 +8,7 @@ require_once __DIR__ . '/hooks.php'; require_once __DIR__ . '/i18n.php'; +require_once __DIR__ . '/script-functions.php'; if ( ! defined( 'RTGODAM_PATH' ) ) { define( 'RTGODAM_PATH', dirname( __DIR__, 2 ) . '/' ); @@ -48,6 +49,29 @@ function trailingslashit( $value ) { // phpcs:ignore WordPress.NamingConventions } } +if ( ! function_exists( 'wp_normalize_path' ) ) { + + /** + * @param string $path Path. + * @return string + */ + function wp_normalize_path( $path ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound -- stub mirroring the WP function. + return str_replace( '\\', '/', (string) $path ); + } +} + +if ( ! function_exists( 'plugins_url' ) ) { + + /** + * @param string $path Path relative to the plugin file's folder. + * @param string $plugin A file in the plugin. + * @return string + */ + function plugins_url( $path = '', $plugin = '' ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound -- stub mirroring the WP function. + return 'https://example.com/plugins/' . basename( dirname( $plugin ) ) . '/' . ltrim( $path, '/' ); + } +} + if ( ! function_exists( '_doing_it_wrong' ) ) { /** @@ -81,6 +105,7 @@ function do_shortcode( $content ) { // phpcs:ignore WordPress.NamingConventions. require_once RTGODAM_PATH . 'inc/classes/layers/class-core-layer-types.php'; require_once RTGODAM_PATH . 'inc/classes/layers/class-form-providers.php'; require_once RTGODAM_PATH . 'inc/classes/layers/class-legacy-layer-types.php'; +require_once RTGODAM_PATH . 'inc/classes/layers/class-layer-sanitizer.php'; require_once RTGODAM_PATH . 'inc/helpers/layer-functions.php'; /** diff --git a/webpack.config.js b/webpack.config.js index 98a7135681..db111cd626 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -357,6 +357,14 @@ const ninjaFormsSubmissionsList = { }, }; +// Layer API front-end runtime registry (`godam-layer-runtime`), for add-on view scripts. +const godamLayerRuntime = { + ...sharedConfig, + entry: { + 'godam-layer-runtime': path.resolve( process.cwd(), 'assets', 'src', 'js', 'godam-layers', 'runtime', 'index.js' ), + }, +}; + // Layer API registry (`window.godam.layers`, imported elsewhere as `@godam/layers`). const godamLayers = { ...sharedConfig, @@ -510,4 +518,5 @@ module.exports = [ ninjaFormsSubmissionsList, blockExtensions, godamLayers, + godamLayerRuntime, ]; From f4cb681668bd9b2f57ed1e78e0eeeefbdfef1ff7 Mon Sep 17 00:00:00 2001 From: KMchaudhary Date: Wed, 4 Nov 2026 16:45:42 +0530 Subject: [PATCH 10/20] feat(layers): deprecate the old add-on layer hooks behind shims Part of #2296. The hooks the Layer API replaces keep working, fed into the registry, and log a deprecation notice. They are deprecated since 2.7.0 and removed in 2.9.0: - PHP: godam_video_editor_layer_options and godam_video_editor_layer_components (apply_filters_deprecated), and godam_player_render_layer (do_action_deprecated). - JS: window.godamLayerComponents, window.godamLayerCreators, window.godamVideoEditorActions and window.godamLayerRegistry.registerLayerType(), each logging one console notice per page. So godam-for-woo can register its own `woo` type: - The legacy `woo` registration runs late on godam_init, after add-ons. - The editor accepts the `woo` name without a namespace, because saved layers use it. - Panels get a useMediaType() hook. - The analytics page reads add-on icons from layer types registered through the API. Refs #2296 Co-Authored-By: Claude Opus 5.5 --- assets/src/js/godam-layers/constants.js | 6 ++++ assets/src/js/godam-layers/deprecated.js | 28 +++++++++++++++++++ assets/src/js/godam-layers/index.js | 3 ++ assets/src/js/godam-layers/registration.js | 4 +-- .../src/js/godam-layers/registration.test.js | 5 ++++ .../js/godam-player/utils/layer-registry.js | 7 +++-- .../godam-player/utils/layer-registry.test.js | 6 ++++ inc/classes/class-pages.php | 20 +++++++++++-- inc/classes/layers/class-core-layer-types.php | 4 +-- .../layers/class-layer-type-registry.php | 14 ++++++++-- .../layers/class-legacy-layer-types.php | 7 +++-- .../components/SidebarLayers.test.js | 1 + .../components/layers/Layer.test.js | 1 + pages/video-editor/index.js | 20 +++++++++---- pages/video-editor/index.test.js | 3 +- pages/video-editor/layers/hooks.js | 9 ++++++ pages/video-editor/layers/layers.test.js | 2 ++ pages/video-editor/layers/legacy.js | 17 +++++++++-- tests/php/LayerTypeRegistryTest.php | 19 +++++++++++++ tests/stubs/layer-registry.php | 19 +++++++++++++ 20 files changed, 171 insertions(+), 24 deletions(-) create mode 100644 assets/src/js/godam-layers/deprecated.js diff --git a/assets/src/js/godam-layers/constants.js b/assets/src/js/godam-layers/constants.js index e2050b2efd..5ba7fa5c7a 100644 --- a/assets/src/js/godam-layers/constants.js +++ b/assets/src/js/godam-layers/constants.js @@ -35,4 +35,10 @@ export const DEFAULT_SUPPORTS = { rawHtml: false, }; +/** + * Un-namespaced add-on layer types saved before the Layer API existed. They may + * keep their name (renaming would orphan saved layers); new types need a namespace. + */ +export const LEGACY_LAYER_TYPE_NAMES = [ 'woo' ]; + export const NAME_PATTERN = /^[a-z0-9-]+\/[a-z0-9-]+$/; diff --git a/assets/src/js/godam-layers/deprecated.js b/assets/src/js/godam-layers/deprecated.js new file mode 100644 index 0000000000..4542aae02a --- /dev/null +++ b/assets/src/js/godam-layers/deprecated.js @@ -0,0 +1,28 @@ +/** + * GoDAM Layer API: deprecation notices for the add-on hooks it replaces (#2296). + * + * The old hooks keep working until GoDAM 2.9.0; each logs one notice per page + * the first time it is used. + */ + +export const DEPRECATED_SINCE = '2.7.0'; +export const REMOVED_IN = '2.9.0'; + +const shown = new Set(); + +/** + * Log that a hook or global is deprecated, once per page. + * + * @param {string} feature What was used, e.g. `window.godamLayerCreators`. + * @param {string} alternative What to use instead. + */ +export function deprecated( feature, alternative ) { + if ( shown.has( feature ) ) { + return; + } + shown.add( feature ); + // eslint-disable-next-line no-console + console.warn( + `GoDAM: ${ feature } is deprecated since version ${ DEPRECATED_SINCE } and will be removed in version ${ REMOVED_IN }. Use ${ alternative } instead.`, + ); +} diff --git a/assets/src/js/godam-layers/index.js b/assets/src/js/godam-layers/index.js index 8527d773dc..ba08809494 100644 --- a/assets/src/js/godam-layers/index.js +++ b/assets/src/js/godam-layers/index.js @@ -30,6 +30,7 @@ import { supportsMedia, } from './utils'; import { CORE_LAYER_TYPES, STORE_NAME } from './constants'; +import { deprecated } from './deprecated'; const api = { store, @@ -50,6 +51,7 @@ const api = { getAvailability, supportsMedia, __unstableRegisterLegacyLayerType, + __unstableDeprecated: deprecated, }; export { @@ -71,6 +73,7 @@ export { getAvailability, supportsMedia, __unstableRegisterLegacyLayerType, + deprecated as __unstableDeprecated, }; if ( typeof window !== 'undefined' ) { diff --git a/assets/src/js/godam-layers/registration.js b/assets/src/js/godam-layers/registration.js index 5e00c5a557..8f71ea91c8 100644 --- a/assets/src/js/godam-layers/registration.js +++ b/assets/src/js/godam-layers/registration.js @@ -16,7 +16,7 @@ import { applyFilters } from '@wordpress/hooks'; * Internal dependencies */ import { store } from './store'; -import { CORE_LAYER_TYPES, DEFAULT_SUPPORTS, MANAGED_KEYS, NAME_PATTERN, SHARED_KEYS } from './constants'; +import { CORE_LAYER_TYPES, DEFAULT_SUPPORTS, LEGACY_LAYER_TYPE_NAMES, MANAGED_KEYS, NAME_PATTERN, SHARED_KEYS } from './constants'; /* eslint-disable no-console -- registration problems are reported to the add-on developer. */ @@ -113,7 +113,7 @@ export function registerLayerType( metadata, settings = {} ) { const merged = { ...getServerMetadata( own?.name ), ...own, ...settings }; const { name } = merged; - if ( typeof name !== 'string' || ( ! NAME_PATTERN.test( name ) && ! CORE_LAYER_TYPES.includes( name ) ) ) { + if ( typeof name !== 'string' || ( ! NAME_PATTERN.test( name ) && ! CORE_LAYER_TYPES.includes( name ) && ! LEGACY_LAYER_TYPE_NAMES.includes( name ) ) ) { console.error( 'GoDAM: layer type names must be namespaced, for example "acme/countdown".' ); return undefined; } diff --git a/assets/src/js/godam-layers/registration.test.js b/assets/src/js/godam-layers/registration.test.js index 06febb8d7d..c147274d39 100644 --- a/assets/src/js/godam-layers/registration.test.js +++ b/assets/src/js/godam-layers/registration.test.js @@ -48,6 +48,11 @@ describe( 'Layer API: registerLayerType', () => { expect( getLayerType( 'acme/countdown' ) ).toBe( registered ); } ); + it( 'lets an add-on keep the un-namespaced name its layers were saved under before the Layer API', () => { + expect( registerLayerType( { name: 'woo', title: 'WooCommerce' } ) ).toMatchObject( { name: 'woo' } ); + expect( registerLayerType( { name: 'shop', title: 'Shop' } ) ).toBeUndefined(); + } ); + it( 'fills in the metadata the type registered in PHP, letting the script override it', () => { const Edit = () => null; window.godamVideoEditorConfig = { diff --git a/assets/src/js/godam-player/utils/layer-registry.js b/assets/src/js/godam-player/utils/layer-registry.js index 5ef3e3301a..a42f99799f 100644 --- a/assets/src/js/godam-player/utils/layer-registry.js +++ b/assets/src/js/godam-player/utils/layer-registry.js @@ -15,8 +15,8 @@ * `updateProductHotspotPositions()`. Only a manager with * `createProductHotspots()` runs on images. * - * New code should call `registerLayerRuntime()` instead. #2296 moves - * godam-for-woo over and deprecates this file. + * Deprecated since GoDAM 2.7.0 (#2296), removed in 2.9.0: new code calls + * `registerLayerRuntime()`. Each call logs a deprecation notice once per page. */ /** @@ -27,6 +27,7 @@ import { getLayerRuntime, getLayerRuntimes, } from '../../godam-layers/runtime/registry.js'; +import { deprecated } from '../../godam-layers/deprecated.js'; const CORE_TYPES = [ 'form', 'cta', 'poll', 'hotspot' ]; @@ -116,6 +117,8 @@ function legacyMount( id, Manager ) { * @return {boolean} True if registration successful, false if already registered */ export function registerLayerType( id, config ) { + deprecated( 'window.godamLayerRegistry.registerLayerType()', 'window.godam.layers.registerLayerRuntime()' ); + if ( getLayerRuntime( id ) ) { // eslint-disable-next-line no-console console.warn( `Layer type "${ id }" is already registered. Skipping duplicate registration.` ); diff --git a/assets/src/js/godam-player/utils/layer-registry.test.js b/assets/src/js/godam-player/utils/layer-registry.test.js index c1180ada9a..206230d202 100644 --- a/assets/src/js/godam-player/utils/layer-registry.test.js +++ b/assets/src/js/godam-player/utils/layer-registry.test.js @@ -56,6 +56,12 @@ describe( 'Layer API contract: layer registry', () => { expect( registry.getAllRegisteredLayerTypes() ).toEqual( { acme: { label: 'Acme', manager: AcmeManager } } ); } ); + it( 'logs a deprecation notice pointing at registerLayerRuntime()', () => { + const registry = loadRegistry(); + registry.registerLayerType( 'acme', { label: 'Acme', validator } ); + expect( warn ).toHaveBeenCalledWith( 'GoDAM: window.godamLayerRegistry.registerLayerType() is deprecated since version 2.7.0 and will be removed in version 2.9.0. Use window.godam.layers.registerLayerRuntime() instead.' ); + } ); + it( 'treats the manager as optional', () => { const registry = loadRegistry(); registry.registerLayerType( 'acme', { label: 'Acme', validator } ); diff --git a/inc/classes/class-pages.php b/inc/classes/class-pages.php index c52293a39d..efada96f2a 100644 --- a/inc/classes/class-pages.php +++ b/inc/classes/class-pages.php @@ -829,8 +829,9 @@ public function admin_enqueue_scripts() { ); // Localize video editor layer options and components via PHP filters. - $layer_options = apply_filters( 'godam_video_editor_layer_options', array() ); - $layer_components = apply_filters( 'godam_video_editor_layer_components', array() ); + // Deprecated (#2296): add-ons register layer types with godam_register_layer_type(). + $layer_options = apply_filters_deprecated( 'godam_video_editor_layer_options', array( array() ), \RTGODAM\Inc\Layers\Layer_Type_Registry::HOOKS_DEPRECATED_SINCE, 'godam_register_layer_type()' ); + $layer_components = apply_filters_deprecated( 'godam_video_editor_layer_components', array( array() ), \RTGODAM\Inc\Layers\Layer_Type_Registry::HOOKS_DEPRECATED_SINCE, 'godam_register_layer_type() with an editorScript' ); wp_localize_script( 'transcoder-page-script-video-editor', @@ -1059,7 +1060,20 @@ public function admin_enqueue_scripts() { // surface. Built-in types (cta/form/hotspot/poll) have icons // hardcoded in the React bundle; this exposes only the URL-based // icons that come from PHP land. - $addon_layer_options = apply_filters( 'godam_video_editor_layer_options', array() ); + $addon_layer_options = apply_filters_deprecated( 'godam_video_editor_layer_options', array( array() ), \RTGODAM\Inc\Layers\Layer_Type_Registry::HOOKS_DEPRECATED_SINCE, 'godam_register_layer_type()' ); + $addon_layer_options = is_array( $addon_layer_options ) ? $addon_layer_options : array(); + + // Layer types registered through the Layer API name their icon in layer.json. + $addon_layer_types = array_column( $addon_layer_options, 'type' ); + foreach ( \RTGODAM\Inc\Layers\Layer_Type_Registry::get_instance()->get_all() as $layer_type_name => $layer_type ) { + if ( ! empty( $layer_type['iconUrl'] ) && ! in_array( $layer_type_name, $addon_layer_types, true ) ) { + $addon_layer_options[] = array( + 'type' => $layer_type_name, + 'title' => $layer_type['title'], + 'iconUrl' => $layer_type['iconUrl'], + ); + } + } // Published layer config for the analytics page's "active vs // removed" rendering. The analytics service stores events diff --git a/inc/classes/layers/class-core-layer-types.php b/inc/classes/layers/class-core-layer-types.php index f4b2d72a72..9a4e099a96 100644 --- a/inc/classes/layers/class-core-layer-types.php +++ b/inc/classes/layers/class-core-layer-types.php @@ -28,6 +28,8 @@ class Core_Layer_Types { */ final protected function __construct() { add_action( 'godam_init', array( $this, 'register' ), 5 ); + // After add-ons (priority 10), so an add-on that registers its own type wins. + add_action( 'godam_init', array( Legacy_Layer_Types::class, 'register' ), 100 ); } /** @@ -70,8 +72,6 @@ public function register() { $args['keep_undeclared_attributes'] = true; $registry->register( RTGODAM_PATH . 'assets/src/layers/' . $name . '/layer.json', $args ); } - - Legacy_Layer_Types::register(); } /** diff --git a/inc/classes/layers/class-layer-type-registry.php b/inc/classes/layers/class-layer-type-registry.php index 6cf152f974..458a37de83 100644 --- a/inc/classes/layers/class-layer-type-registry.php +++ b/inc/classes/layers/class-layer-type-registry.php @@ -24,6 +24,14 @@ class Layer_Type_Registry { use Singleton; + /** + * GoDAM version that deprecated the add-on hooks the Layer API replaces (#2296). + * They are removed two minor releases later, in 2.9.0. + * + * @var string + */ + const HOOKS_DEPRECATED_SINCE = '2.7.0'; + /** * Registered layer types, keyed by name, in registration order. * @@ -316,12 +324,12 @@ public function render( $layer, $instance_id, $context = array() ) { /** * Renders the container of a layer type that has no PHP registration. * - * Use `godam_register_layer_type()` with a `render_callback` instead. + * @deprecated 2.7.0 Use `godam_register_layer_type()` with a `render_callback` instead. * * @param array $layer Layer configuration. * @param string $instance_id Player instance ID. */ - do_action( 'godam_player_render_layer', $layer, $instance_id ); + do_action_deprecated( 'godam_player_render_layer', array( $layer, $instance_id ), self::HOOKS_DEPRECATED_SINCE, 'godam_register_layer_type()' ); return (string) ob_get_clean(); } @@ -442,7 +450,7 @@ public function get_editor_settings() { foreach ( $this->types as $name => $type ) { $types[ $name ] = array_intersect_key( $type, - array_flip( array( 'apiVersion', 'name', 'title', 'description', 'icon', 'color', 'category', 'supports', 'attributes', 'variationAttribute', 'textdomain' ) ) + array_flip( array( 'apiVersion', 'name', 'title', 'description', 'icon', 'iconUrl', 'color', 'category', 'supports', 'attributes', 'variationAttribute', 'textdomain' ) ) ); $variations = array(); diff --git a/inc/classes/layers/class-legacy-layer-types.php b/inc/classes/layers/class-legacy-layer-types.php index fbfc8efd65..b8c8790e28 100644 --- a/inc/classes/layers/class-legacy-layer-types.php +++ b/inc/classes/layers/class-legacy-layer-types.php @@ -4,8 +4,9 @@ * * The godam-for-woo `woo` layer renders its player container through the * `godam_player_render_layer` action and was hard-coded into the - * `godam/image` block. Registering it here keeps both working through the - * registry until #2296 moves godam-for-woo to `godam_register_layer_type()`. + * `godam/image` block. Registering it here keeps a godam-for-woo release that + * predates the Layer API working (with deprecation notices). It runs late on + * `godam_init`, so a godam-for-woo that registers `woo` itself takes over. * * @package GoDAM */ @@ -62,7 +63,7 @@ public static function register() { public static function render_with_action( $layer, $instance_id ) { ob_start(); /** This action is documented in inc/classes/layers/class-layer-type-registry.php */ - do_action( 'godam_player_render_layer', $layer, $instance_id ); + do_action_deprecated( 'godam_player_render_layer', array( $layer, $instance_id ), Layer_Type_Registry::HOOKS_DEPRECATED_SINCE, 'godam_register_layer_type()' ); return (string) ob_get_clean(); } } diff --git a/pages/video-editor/components/SidebarLayers.test.js b/pages/video-editor/components/SidebarLayers.test.js index f46d362dd0..cad135e235 100644 --- a/pages/video-editor/components/SidebarLayers.test.js +++ b/pages/video-editor/components/SidebarLayers.test.js @@ -261,6 +261,7 @@ describe( 'Layer API contract: SidebarLayers', () => { color: 'red', id: 'test-uuid', } ] ); + expect( console ).toHaveWarnedWith( 'GoDAM: window.godamLayerCreators is deprecated since version 2.7.0 and will be removed in version 2.9.0. Use the `create` setting of registerLayerType() instead.' ); } ); it( 'lets the creator override the name but never the id', () => { diff --git a/pages/video-editor/components/layers/Layer.test.js b/pages/video-editor/components/layers/Layer.test.js index 517dfff97b..0b3e43d2d7 100644 --- a/pages/video-editor/components/layers/Layer.test.js +++ b/pages/video-editor/components/layers/Layer.test.js @@ -104,6 +104,7 @@ describe( 'Layer API contract: Layer editor dispatch', () => { expect( editor() ).toBe( 'acme' ); expect( AcmeLayer.mock.calls[ 0 ][ 0 ] ).toEqual( { layerID: 'l2', goBack, duration: 90 } ); + expect( console ).toHaveWarnedWith( 'GoDAM: window.godamLayerComponents is deprecated since version 2.7.0 and will be removed in version 2.9.0. Use the `edit` setting of registerLayerType() instead.' ); } ); it( 'lets an add-on replace a core editor by listing the same type', () => { diff --git a/pages/video-editor/index.js b/pages/video-editor/index.js index a985bea1f0..ccb3271e2f 100644 --- a/pages/video-editor/index.js +++ b/pages/video-editor/index.js @@ -5,6 +5,7 @@ import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { PostHogProvider } from '@posthog/react'; +import { __unstableDeprecated as deprecated } from '@godam/layers'; /** * Internal dependencies @@ -26,7 +27,7 @@ import FontAwesomeIconPicker from './components/hotspot/FontAwesomeIconPicker'; import ColorPickerButton from './components/shared/color-picker/ColorPickerButton.jsx'; import { formatClock, parseClock } from './utils/time'; import { registerEditorLayerTypes } from './layers'; -import { useLayer, useLayerAttributes } from './layers/hooks'; +import { useLayer, useLayerAttributes, useMediaType } from './layers/hooks'; window.godamVideoEditorComponents = { ...( window.godamVideoEditorComponents || {} ), @@ -41,10 +42,18 @@ window.godamVideoEditorComponents = { ColorPickerButton, }; -window.godamVideoEditorActions = { - ...( window.godamVideoEditorActions || {} ), - updateLayerField, -}; +// Deprecated (#2296): add-ons should use `useLayerAttributes()` from `window.godam.layerEditor`. +window.godamVideoEditorActions = new Proxy( + { ...( window.godamVideoEditorActions || {} ), updateLayerField }, + { + get( actions, key ) { + if ( typeof key === 'string' && key in actions ) { + deprecated( 'window.godamVideoEditorActions', 'useLayerAttributes() from window.godam.layerEditor' ); + } + return actions[ key ]; + }, + }, +); window.godamVideoEditorUtils = { ...( window.godamVideoEditorUtils || {} ), @@ -59,6 +68,7 @@ window.godam.layerEditor = { ...( window.godam.layerEditor || {} ), useLayer, useLayerAttributes, + useMediaType, LayerCanvas: LayerControls, LayersHeader, VeSection, diff --git a/pages/video-editor/index.test.js b/pages/video-editor/index.test.js index 27ea7a8ed9..7ba57a5d7c 100644 --- a/pages/video-editor/index.test.js +++ b/pages/video-editor/index.test.js @@ -56,8 +56,9 @@ describe( 'Layer API contract: editor globals for add-ons', () => { ].forEach( ( name ) => expect( typeof components[ name ] ).toBe( 'function' ) ); } ); - it( 'exposes the real updateLayerField action on window.godamVideoEditorActions', () => { + it( 'exposes the real updateLayerField action on window.godamVideoEditorActions, with a deprecation notice', () => { expect( window.godamVideoEditorActions.updateLayerField ).toBe( require( './redux/slice/videoSlice' ).updateLayerField ); + expect( console ).toHaveWarnedWith( 'GoDAM: window.godamVideoEditorActions is deprecated since version 2.7.0 and will be removed in version 2.9.0. Use useLayerAttributes() from window.godam.layerEditor instead.' ); } ); it( 'exposes formatClock and parseClock on window.godamVideoEditorUtils', () => { diff --git a/pages/video-editor/layers/hooks.js b/pages/video-editor/layers/hooks.js index 076112f44c..6265ae0fe6 100644 --- a/pages/video-editor/layers/hooks.js +++ b/pages/video-editor/layers/hooks.js @@ -62,3 +62,12 @@ export function useLayerAttributes( layerId ) { return [ layer, setAttributes ]; } + +/** + * The kind of media open in the editor. + * + * @return {string} `video` or `image`. + */ +export function useMediaType() { + return useSelector( ( state ) => state.videoReducer.mediaType ) || 'video'; +} diff --git a/pages/video-editor/layers/layers.test.js b/pages/video-editor/layers/layers.test.js index fd2d5446fe..b7f201d882 100644 --- a/pages/video-editor/layers/layers.test.js +++ b/pages/video-editor/layers/layers.test.js @@ -177,6 +177,7 @@ describe( 'Layer API: bridge from the old add-on hooks', () => { expect( create( { currentTime: 1 } ) ).toBeUndefined(); window.godamLayerCreators.acme = ( { currentTime } ) => ( { type: 'acme', displayTime: currentTime } ); expect( create( { currentTime: 3 } ) ).toEqual( { type: 'acme', displayTime: 3 } ); + expect( console ).toHaveWarnedWith( 'GoDAM: window.godamLayerCreators is deprecated since version 2.7.0 and will be removed in version 2.9.0. Use the `create` setting of registerLayerType() instead.' ); } ); it( 'looks the settings panel up when it opens', () => { @@ -185,6 +186,7 @@ describe( 'Layer API: bridge from the old add-on hooks', () => { window.godamLayerComponents.WoocommerceLayer = WoocommerceLayer; expect( getLegacyEditComponent( 'woo' ) ).toBe( WoocommerceLayer ); expect( getLegacyEditComponent( 'acme' ) ).toBeUndefined(); + expect( console ).toHaveWarnedWith( 'GoDAM: window.godamLayerComponents is deprecated since version 2.7.0 and will be removed in version 2.9.0. Use the `edit` setting of registerLayerType() instead.' ); } ); it( 'does not re-register a type an add-on already registered through the Layer API', () => { diff --git a/pages/video-editor/layers/legacy.js b/pages/video-editor/layers/legacy.js index 66cb3f2008..aca5d2500b 100644 --- a/pages/video-editor/layers/legacy.js +++ b/pages/video-editor/layers/legacy.js @@ -16,7 +16,7 @@ /** * External dependencies */ -import { getLayerType, __unstableRegisterLegacyLayerType } from '@godam/layers'; +import { getLayerType, __unstableRegisterLegacyLayerType, __unstableDeprecated as deprecated } from '@godam/layers'; /** * Shopping-cart glyph (white line art) for commerce layer markers. @@ -49,7 +49,11 @@ const LEGACY_WOO = { */ export function getLegacyEditComponent( type ) { const componentName = window.godamVideoEditorConfig?.layerComponents?.[ type ]; - return componentName ? window.godamLayerComponents?.[ componentName ] : undefined; + const component = componentName ? window.godamLayerComponents?.[ componentName ] : undefined; + if ( component ) { + deprecated( 'window.godamLayerComponents', 'the `edit` setting of registerLayerType()' ); + } + return component; } /** @@ -75,7 +79,14 @@ export function registerLegacyLayerTypes() { ? { available: false, reason: option.tooltipMessage ?? '' } : null ), - create: ( context ) => window.godamLayerCreators?.[ name ]?.( context ), + create: ( context ) => { + const creator = window.godamLayerCreators?.[ name ]; + if ( ! creator ) { + return undefined; + } + deprecated( 'window.godamLayerCreators', 'the `create` setting of registerLayerType()' ); + return creator( context ); + }, } ); } ); } diff --git a/tests/php/LayerTypeRegistryTest.php b/tests/php/LayerTypeRegistryTest.php index f93d064787..3014b582b5 100644 --- a/tests/php/LayerTypeRegistryTest.php +++ b/tests/php/LayerTypeRegistryTest.php @@ -178,6 +178,7 @@ function ( $layer, $instance_id ) { ); $this->assertSame( '
', godam_render_layer( $layer, 'video_1' ) ); + $this->assertSame( array( 'godam_player_render_layer@2.7.0' ), $GLOBALS['rtgodam_stub']['deprecated_hooks'] ); $this->assertSame( '', godam_render_layer( $layer, 'img_1', array( 'media' => 'image' ) ) ); } @@ -473,6 +474,24 @@ public function test_finds_ad_layers_by_support(): void { $this->assertSame( '', godam_render_layer( $ad, 'video_1' ) ); } + /** + * An add-on that registers `woo` itself takes over from the legacy registration. + */ + public function test_lets_an_add_on_register_woo_itself(): void { + Layer_Type_Registry::get_instance()->reset(); + \RTGODAM\Inc\Layers\Core_Layer_Types::get_instance()->register(); + godam_register_layer_type( + array( + 'name' => 'woo', + 'title' => 'WooCommerce (add-on)', + ) + ); + \RTGODAM\Inc\Layers\Legacy_Layer_Types::register(); + + $this->assertSame( 'WooCommerce (add-on)', godam_get_layer_type( 'woo' )['title'] ); + $this->assertArrayNotHasKey( 'doing_it_wrong', $GLOBALS['rtgodam_stub'] ); + } + /** * The legacy Woo type renders through the add-on's action. */ diff --git a/tests/stubs/layer-registry.php b/tests/stubs/layer-registry.php index 674fa9c09b..fb9f6314a4 100644 --- a/tests/stubs/layer-registry.php +++ b/tests/stubs/layer-registry.php @@ -86,6 +86,24 @@ function _doing_it_wrong( $function_name, $message, $version ) { // phpcs:ignore } } +if ( ! function_exists( 'do_action_deprecated' ) ) { + + /** + * Run a deprecated action and record its name when something is hooked to it. + * + * @param string $hook_name Hook. + * @param array $args Arguments. + * @param string $version Version. + * @param string $replacement Replacement. + */ + function do_action_deprecated( $hook_name, $args, $version, $replacement = '' ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound, Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- stub mirroring the WP function. + if ( has_action( $hook_name ) ) { + $GLOBALS['rtgodam_stub']['deprecated_hooks'][] = $hook_name . '@' . $version; + } + do_action( $hook_name, ...$args ); + } +} + if ( ! function_exists( 'do_shortcode' ) ) { /** @@ -114,4 +132,5 @@ function do_shortcode( $content ) { // phpcs:ignore WordPress.NamingConventions. function rtgodam_test_register_core_layer_types() { \RTGODAM\Inc\Layers\Layer_Type_Registry::get_instance()->reset(); \RTGODAM\Inc\Layers\Core_Layer_Types::get_instance()->register(); + \RTGODAM\Inc\Layers\Legacy_Layer_Types::register(); } From 2b6afe80ebcad1ef105816a018a549c7c08a16b2 Mon Sep 17 00:00:00 2001 From: KMchaudhary Date: Wed, 4 Nov 2026 17:45:28 +0530 Subject: [PATCH 11/20] docs(layers): add the Layer API developer guide docs/layer-api.md, for add-on developers (#2297): - how a layer type fits together - a quick-start countdown layer plugin - the layer.json reference - the PHP, editor and front-end runtime references - form providers - the saved data shape and analytics - moving from the deprecated hooks - troubleshooting Refs #2297 Co-Authored-By: Claude Opus 5.5 --- docs/layer-api.md | 554 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 554 insertions(+) create mode 100644 docs/layer-api.md diff --git a/docs/layer-api.md b/docs/layer-api.md new file mode 100644 index 0000000000..35557b39d4 --- /dev/null +++ b/docs/layer-api.md @@ -0,0 +1,554 @@ +# GoDAM Layer API + +Build your own layer types for GoDAM videos and images, the way you build blocks for the WordPress block editor. + +A layer is something that appears on top of a video or image: a call to action, a form, a poll, a hotspot, a product card. GoDAM's own layer types (CTA, Form, Poll, Hotspot and Ad) are registered through this same API, so an add-on's layer type gets the same treatment: an entry in the "Add layer" menu, a settings panel, a timeline marker, saving, and rendering in the player and on `godam/image` blocks. + +> **Requires GoDAM 2.7.0.** The older add-on hooks still work until 2.9.0, with deprecation notices. See [Moving from the old hooks](#moving-from-the-old-hooks). + +## Contents + +- [How a layer type fits together](#how-a-layer-type-fits-together) +- [Quick start: a countdown layer](#quick-start-a-countdown-layer) +- [`layer.json`](#layerjson) +- [PHP](#php) +- [Editor](#editor) +- [Front end](#front-end) +- [Form providers](#form-providers) +- [Saved layer data](#saved-layer-data) +- [Analytics](#analytics) +- [Moving from the old hooks](#moving-from-the-old-hooks) +- [Troubleshooting](#troubleshooting) + +## How a layer type fits together + +A layer type has one metadata file and up to three parts. Each part registers under the same name. + +| Part | Runs in | Registers with | Does | +|---|---|---|---| +| `layer.json` | everywhere | read by the PHP call | Name, title, colour, which media it supports, its attributes, its scripts | +| PHP | the server | `godam_register_layer_type()` | Prints the layer's container in the player, says whether the type can run on this site, cleans its data on save | +| Editor script | the video editor | `window.godam.layers.registerLayerType()` | The settings panel, what a new layer starts with, availability in the "Add layer" menu | +| View script | the page | `window.godam.layers.registerLayerRuntime()` | Shows and hides the layer, reacts to playback, resize and fullscreen, on video and images | + +**Naming:** third-party layer types need a namespace, for example `acme/countdown`, made of lowercase letters, digits and dashes. That's the value saved in each layer's `type`, so pick it once and keep it. + +## Quick start: a countdown layer + +A plugin that adds a "Countdown" layer: a message that appears at a chosen time and counts down to a date. + +``` +acme-countdown/ +├── acme-countdown.php +├── layer.json +├── package.json +├── src/ +│ ├── editor.js +│ └── view.js +└── build/ ← created by `npm run build` + ├── editor.js, editor.asset.php + └── view.js, view.asset.php +``` + +### `layer.json` + +```json +{ + "apiVersion": 1, + "name": "acme/countdown", + "title": "Countdown", + "description": "Count down to a date", + "color": "#e24a4a", + "supports": { + "media": [ "video", "image" ] + }, + "attributes": { + "label": { "type": "string", "default": "Sale ends in" }, + "endsAt": { "type": "string", "default": "" }, + "duration": { "default": 10 } + }, + "editorScript": "file:./build/editor.js", + "viewScript": "file:./build/view.js", + "textdomain": "acme-countdown" +} +``` + +### `acme-countdown.php` + +```php + function ( $layer, $instance_id ) { + return sprintf( + '', + esc_attr( 'layer-' . $instance_id . '-' . $layer['id'] ), + esc_html( $layer['label'] ?? '' ), + esc_attr( $layer['endsAt'] ?? '' ) + ); + }, + ) + ); + } +); +``` + +`godam_init` fires on `init`. Registering there means the type exists before anything renders, saves or loads the editor. + +### `src/editor.js` + +```js +import { __ } from '@wordpress/i18n'; + +const { registerLayerType } = window.godam.layers; +const { useLayerAttributes, LayersHeader, VeSection, VeTextInput } = window.godam.layerEditor; + +function CountdownPanel( { layerID, goBack, duration } ) { + const [ layer, setAttributes ] = useLayerAttributes( layerID ); + if ( ! layer ) { + return null; + } + + return ( + <> + + + setAttributes( { label } ) } + /> + setAttributes( { endsAt } ) } + /> + + + ); +} + +// Name, title, colour, supports and attributes come from layer.json, which +// GoDAM passes to the editor from PHP. The script adds what only JS can provide. +registerLayerType( 'acme/countdown', { + title: __( 'Countdown', 'acme-countdown' ), + edit: CountdownPanel, +} ); +``` + +### `src/view.js` + +```js +const { registerLayerRuntime } = window.godam.layers; + +registerLayerRuntime( 'acme/countdown', { + supports: { media: [ 'video', 'image' ] }, + + mount( { layer, container, media, api } ) { + // On video the container holds the markup render_callback printed. On an + // image it's an empty wrapper, so draw the markup here. + if ( ! container.querySelector( '.acme-countdown__time' ) ) { + container.innerHTML = '

'; + container.querySelector( '.acme-countdown__label' ).textContent = layer.label || ''; + } + const time = container.querySelector( '.acme-countdown__time' ); + const tick = () => { + const seconds = Math.max( 0, Math.round( ( new Date( layer.endsAt ) - Date.now() ) / 1000 ) ); + time.textContent = `${ Math.floor( seconds / 3600 ) }h ${ Math.floor( ( seconds % 3600 ) / 60 ) }m ${ seconds % 60 }s`; + }; + const timer = setInterval( tick, 1000 ); + tick(); + + // On an image there's no timeline: show the layer straight away. + if ( media.type === 'image' ) { + api.show(); + return { destroy: () => clearInterval( timer ) }; + } + + const start = Number( layer.displayTime ) || 0; + const end = start + ( Number( layer.duration ) || 10 ); + + return { + onTimeUpdate( currentTime ) { + if ( currentTime >= start && currentTime <= end ) { + api.show(); + } else { + api.hide(); + } + }, + destroy: () => clearInterval( timer ), + }; + }, +} ); +``` + +### Build + +```json +{ + "scripts": { + "build": "wp-scripts build src/editor.js src/view.js" + }, + "devDependencies": { + "@wordpress/scripts": "^30" + } +} +``` + +`wp-scripts` writes the `*.asset.php` files GoDAM reads for each script's dependencies and version. GoDAM also adds its own dependencies: +- **Editor scripts** get `godam-layers` and `godam-layer-editor`. +- **View scripts** get `godam-layer-runtime`. + +So `window.godam.layers` and `window.godam.layerEditor` are always ready when your script runs. + +**What you get:** +- **In the video editor,** "Countdown" appears in **Add layer**, opens your panel, and gets a timeline marker in its colour. +- **On save,** the layer is saved into the attachment's `rtgodam_meta.layers` and cleaned against your declared attributes. +- **On the front end,** your container is printed in the player. `view.js` loads only on pages that show a countdown layer, and the layer works on videos and on `godam/image` blocks. + +## `layer.json` + +| Key | Type | Notes | +|---|---|---| +| `apiVersion` | number | `1` | +| `name` | string | **Required.** `vendor/name`. Saved in each layer's `type`. | +| `title` | string | **Required** (here or in the editor call). Shown in the "Add layer" menu and the layer list. | +| `description` | string | Shown under the title in the menu. | +| `icon` | string | Dashicon name or an image URL. In PHP you can also pass `iconUrl`. | +| `color` | string | The timeline marker colour. | +| `supports` | object | See below. | +| `attributes` | object | Your layer's settings and their schemas. See [Attributes](#attributes). | +| `variationAttribute` | string | The attribute that selects a variation (the Form type uses `form_type`). | +| `editorScript` | string or array | `file:./path.js` relative to `layer.json`, or a registered script handle. | +| `viewScript` | string or array | Same, for the page. | +| `textdomain` | string | Your text domain. | + +### `supports` + +| Key | Default | Meaning | +|---|---|---| +| `media` | `[ "video" ]` | Where the type works: `video`, `image`, or both. | +| `timeline` | `true` | The layer has a time on the video timeline. | +| `duplicate` | `true` | Editors can duplicate the layer. | +| `skip` | `false` | The layer has a skip button. | +| `rawHtml` | `false` | Your `render_callback` output is printed as is instead of through `wp_kses_post()`. You become responsible for escaping it. | + +### Attributes + +Attributes are your layer's settings. They're stored **flat** on the layer next to GoDAM's own keys (see [Saved layer data](#saved-layer-data)). + +```json +"attributes": { + "label": { "type": "string", "default": "" }, + "seconds": { "type": "integer", "default": 10 }, + "loop": { "type": "boolean", "default": false }, + "link": { "type": "string", "format": "url" }, + "note": { "type": "string", "format": "html" }, + "accent": { "type": "string", "format": "color", "default": "#e24a4a" }, + "items": { "type": "array", "default": [] }, + "iconId": { "type": [ "integer", "null" ], "default": null }, + "apiToken": { "type": "string", "private": true } +} +``` + +- **`type`:** `string`, `number`, `integer`, `boolean`, `array`, `object`, or a list such as `[ "integer", "null" ]`. +- **`format`** (strings): `plain` (default, `sanitize_text_field()`), `html` (`wp_kses_post()`), `url` (`esc_url_raw()`) or `color` (hex, `rgb()`/`rgba()`, `hsl()`/`hsla()` or `transparent`). +- **`default`:** what a new layer starts with, and what a value of the wrong type falls back to on save. +- **`private`:** `true` keeps the attribute out of the page. It's saved and visible in the editor, but left out of the player's and image block's layer data. + +**Shared keys:** a type may set the *default* of a key GoDAM shares across layer types (`duration`, `allow_skip`, `custom_css`, `trigger`, `watchDepth`). It can't change their type, and it can't declare GoDAM's managed keys at all (`id`, `type`, `name`, `displayTime`). + +## PHP + +### `godam_register_layer_type( $path_or_metadata, $args = array() )` + +Call it on `godam_init`. Returns the registered type, or `false` with a `_doing_it_wrong()` notice when it's rejected: no name, a name already registered, or a `layer.json` that can't be read. + +`$path_or_metadata` is a `layer.json` file, the folder that holds one, or the metadata as an array. `$args` is merged over the metadata: + +| Arg | Signature | Meaning | +|---|---|---| +| `render_callback` | `( $layer, $instance_id, $context ) => string` | The layer's container in the player. `$context` is `array( 'media' => 'video' )`. Return `''` to print nothing (for example, when a required setting is empty). | +| `is_available` | `( $layer = null ) => bool` | Whether the type can run on this site, e.g. a required plugin or API key. The editor greys out an unavailable type. | +| `dependency_key` | string | Reports `is_available` to the player as `window.godamPluginDependencies[ key ]`. | +| `should_render` | `( $layer, $context ) => bool` | Whether a saved layer is worth sending to an image block, e.g. it has content. | +| `keep_undeclared_attributes` | bool | Keep keys your `layer.json` doesn't declare when a layer is saved. See [Cleaning on save](#cleaning-on-save). | +| `variations` | array | Variations, as for `godam_register_layer_variation()`. | +| any metadata key | | Overrides `layer.json`, for example a translated `title`, or `iconUrl` built from your plugin URL. | + +**The container.** The player finds each layer by its element id and toggles the `hidden` class: + +```html + +``` + +Keep that id and those two classes. Everything inside the container is yours. Output goes through `wp_kses_post()` unless `supports.rawHtml` is `true`. If your markup includes forms, inputs or scripts, set `rawHtml` and escape everything yourself. + +Images don't use `render_callback`: the image block gives each layer an empty wrapper, and your view script draws into it. + +### Other functions + +| Function | Does | +|---|---| +| `godam_get_layer_type( $name )` | The registered type, or `null`. | +| `godam_unregister_layer_type( $name )` | Removes a type. Returns the type or `false`. | +| `godam_register_layer_variation( $name, $variation )` | Adds a variation to a type, e.g. a form provider to `form`. See [Form providers](#form-providers). | +| `godam_render_layer( $layer, $instance_id, $context )` | The container markup for one saved layer, as the player template prints it. | + +### Hooks + +| Hook | Type | Use | +|---|---|---| +| `godam_init` | action | Register layer types and variations. | +| `godam_layer_type_metadata` | filter | Change any type's metadata before it registers, including GoDAM's own. | +| `godam_plugin_dependencies` | filter | Add or change the availability flags the player reads. | + +### Cleaning on save + +When the editor saves `rtgodam_meta`, GoDAM cleans every layer of a registered type: + +1. **Declared attributes** are sanitized by `format`. +2. **A value of the wrong type** is converted when nothing is lost (`"30"` → `30` for an `integer`). If it can't be converted, it falls back to the attribute's `default`, or is removed when there's no default. +3. **Undeclared keys are dropped**, unless the type registered with `keep_undeclared_attributes`. + +GoDAM's own types keep undeclared keys for now, and keep `html` as written (it's escaped when it renders). Their `layer.json` files don't list every attribute they save yet. Layers of a type nobody registered are kept unchanged, in case the add-on that owns them comes back. + +**Declare every attribute you save.** Anything you leave out of `attributes` is deleted the next time the layer is saved. + +### Loading scripts + +- **`editorScript`** loads on the video editor page. +- **`viewScript`** loads only when a layer of your type renders on the page, or is sent to a `godam/image` block. A page with no countdown layers never loads `view.js`. + +## Editor + +The editor registry is `window.godam.layers` (script handle `godam-layers`). Panel hooks and controls are on `window.godam.layerEditor` (handle `godam-layer-editor`). If you bundle with webpack, you can import them instead by declaring externals: + +```js +// webpack.config.js +externals: { + '@godam/layers': [ 'godam', 'layers' ], + '@godam/layer-editor': [ 'godam', 'layerEditor' ], +}, +``` + +### `registerLayerType( metadataOrName, settings )` + +`metadataOrName` is your `layer.json` contents or just the name. Metadata the type registered in PHP fills in anything you don't pass, so `registerLayerType( 'acme/countdown', { edit } )` is enough. Returns the registered type, or `undefined` with a console error. + +| Setting | Meaning | +|---|---| +| `edit` | **The settings panel**, a React component. It receives `{ layerID, goBack, duration }`. | +| `create( { layers, currentTime, type } )` | The new layer, including `type` and `displayTime` (usually `currentTime`). GoDAM always sets `id`, and sets `name` when you don't. Without `create`, a new layer gets `type`, the time and your attribute defaults. | +| `getAvailability( { videoConfig, mediaType } )` | `{ available: false, reason }` to grey the type out in the menu with a tooltip, or `null` when available. Add `disablesExisting: false` to keep existing layers editable. | +| `validate( layer )` | Return `false` to block saving, e.g. a required setting is empty. The editor shows a message listing the layer's time. | +| `title`, `label`, `description` | Translated strings. `label` is the menu text and defaults to `title`. | +| `icon`, `iconUrl`, `color` | How the type looks in the menu, the layer list and the timeline. | +| `markerIcon` | A component drawn inside the timeline marker. | +| `supports`, `attributes`, `variationAttribute`, `variations` | As in `layer.json`. | + +Other registry functions: `unregisterLayerType()`, `getLayerType()`, `getLayerTypes()`, `registerLayerVariation()`, `unregisterLayerVariation()`, `getLayerVariationByName()`, `getDefaultAttributes()`, `getLayerVariation()`, `getAvailability()` and `supportsMedia()`. + +The **`godam.layers.registerLayerType`** filter (`@wordpress/hooks`) changes a type's settings as it registers: + +```js +wp.hooks.addFilter( 'godam.layers.registerLayerType', 'acme/tweak-cta', ( settings, name ) => + name === 'cta' ? { ...settings, color: '#000' } : settings +); +``` + +### Panel hooks (`window.godam.layerEditor`) + +| Hook | Returns | +|---|---| +| `useLayerAttributes( layerId )` | `[ layer, setAttributes( changes ) ]`. `setAttributes` merges changes into the layer and ignores `id` and `type`. | +| `useLayer( layerId )` | The layer. Without an id, the layer whose panel is open. | +| `useMediaType()` | `'video'` or `'image'`. | + +Use these instead of reading the editor's Redux store. The store's shape isn't part of the API. + +### Panel components (`window.godam.layerEditor`) + +| Component | Use | +|---|---| +| `LayersHeader` | The panel header with the back button and layer name. Props: `layer`, `goBack`, `duration`, `layerName`. | +| `LayerCanvas` | Renders its children on top of the video stage, for an on-stage preview. | +| `VeSection` | A titled section (`title`). | +| `VeTextInput` | A text field (`label`, `value`, `onChange( value )`, `type`, `help`, `error`). | +| `VeSegmented`, `VeRadioGroup`, `VeColorList` | Option pickers. | +| `FontAwesomeIconPicker`, `ColorPickerButton` | The icon and colour pickers GoDAM's own panels use. | +| `formatClock( seconds )`, `parseClock( text )` | `m:ss` time formatting for time fields. | + +## Front end + +The runtime registry is `window.godam.layers` (handle `godam-layer-runtime`). It's plain JavaScript with no React, so it's cheap on image-only pages. + +### `registerLayerRuntime( name, settings )` + +| Setting | Meaning | +|---|---| +| `mount( ctx )` | **Required.** Called once per saved layer. Returns handlers (below), or nothing. | +| `supports` | `{ media: [ 'video', 'image' ] }`. Defaults to video only. Image blocks only mount types that list `image`. | +| `validate( layer, { dependencies } )` | Return `false` to skip the layer. `dependencies` is `window.godamPluginDependencies`. | +| `usesIconFont( layer )` | Return `true` to have FontAwesome loaded before the layer mounts. | +| `title` | Label used in analytics names. | +| `variationAttribute`, `variations` | As in the editor. | + +A type with no runtime is skipped, and the console logs `GoDAM: no runtime registered for layer type "…"` once. + +### `mount( ctx )` + +| `ctx` | | +|---|---| +| `layer` | The saved layer (without private attributes). | +| `container` | The layer's element: your `render_callback` output on video, an empty wrapper on images. It starts with the `hidden` class. | +| `player` | The Video.js player. On images, a stand-in with the same methods (`el()`, `currentTime()` returns 0, `pause()` and `play()` do nothing) plus `computeContentRect()`, the image's box. | +| `media` | `{ type: 'video' \| 'image', element }`. | +| `instanceId` | The player instance. | +| `shared( key, create )` | A value shared by every layer on the same video or image, created on first use. | +| `api` | `show()`, `hide()`, `isVisible()`, `pause()`, `play()`, `seek( seconds )`, `currentTime()`, `isSuppressed()`, `track( action, metadata )`. | + +### Handlers + +Every handler is optional. + +| Handler | Called | +|---|---| +| `onReady()` | Once every saved layer on the video or image is mounted. | +| `onTimeUpdate( currentTime )` | On every playback time update. | +| `onPause()` | When the viewer pauses. Automatic pauses don't count, such as the player scrolling out of view. | +| `onEnded()` | When playback ends. | +| `onPlay()` | When playback starts. | +| `onResize()` | When the video or image box changes size. | +| `onFullscreenChange( isFullscreen, playerElement )` | On entering or leaving fullscreen. | +| `onReplay()` | When the player API replays from the start. | +| `destroy()` | When the layer is unmounted (the image block redraws in the editor). | + +- **During a hover preview** (the muted "Start Preview" playback), `onTimeUpdate`, `onPause` and `onEnded` aren't called, so no layer appears early. +- **To get each event once for all your layers,** return the same handlers object from several mounts. Usually that means one controller per player, kept with `ctx.shared()`: + +```js +mount( ctx ) { + const controller = ctx.shared( 'acme/countdown', () => createController( ctx ) ); + controller.add( ctx.layer, ctx.container ); + return controller.handlers; // the same object for every countdown layer on this player +} +``` + +- **An error** thrown from `mount()` or a handler is logged, and every other layer keeps running. + +## Form providers + +The Form layer is one type with a **variation per form plugin**, selected by the layer's `form_type`. To add a form plugin, register a variation in each place it needs one. + +**PHP** prints the form and says whether the plugin is active: + +```php +add_action( 'godam_init', function () { + godam_register_layer_variation( 'form', array( + 'name' => 'acme-forms', // saved as form_type + 'title' => 'Acme Forms', + 'is_available' => fn () => class_exists( 'Acme_Forms' ), + 'dependency_key' => 'acmeForms', // window.godamPluginDependencies.acmeForms + 'render_callback' => function ( $layer ) { // inner markup; '' prints no layer + return empty( $layer['acme_form_id'] ) ? '' : do_shortcode( sprintf( '[acme_form id="%d"]', $layer['acme_form_id'] ) ); + }, + 'attributeSchema' => array( 'acme_form_id' => array( 'type' => 'integer' ) ), + 'container_class' => 'acme-forms', // optional extra class on the layer container + ) ); +} ); +``` + +**Editor:** the form picker. Either bring your own `edit` panel, or give GoDAM two functions and it builds the panel (form picker, preview and Edit Form link) for you: + +```js +window.godam.layers.registerLayerVariation( 'form', { + name: 'acme-forms', + title: 'Acme Forms', + icon: 'feedback', + idField: 'acme_form_id', // where the chosen form's ID is saved + isAvailable: () => !! window.godamVideoEditorConfig?.layerAvailability?.form?.variations?.[ 'acme-forms' ], + unavailableReason: 'Activate Acme Forms to use this.', + settingsUrl: 'admin.php?page=acme-forms&form={formId}', // or ( formId ) => url + getForms: async () => [ { id: 7, title: 'Contact' } ], + getFormHtml: async ( id ) => ( await fetch( `/wp-json/acme/v1/forms/${ id }/html` ) ).text(), +} ); +``` + +**Front end:** tells GoDAM when the form was sent, so the skip button turns into "Continue" and a `submitted` event is recorded: + +```js +window.godam.layers.registerLayerRuntimeVariation( 'form', { + name: 'acme-forms', + title: 'Acme Forms', // the label in analytics names + isAvailable: ( dependencies ) => !! dependencies?.acmeForms, + isSubmitted: ( element ) => !! element.querySelector( '.acme-form-sent' ), + isUnavailable: ( element ) => !! element.querySelector( '.acme-form-error' ), // optional: let the viewer continue, record nothing +} ); +``` + +A variation registered before its type is kept and added when the type registers, so script order doesn't matter. + +## Saved layer data + +Layers are saved on the attachment in the `rtgodam_meta` post meta, as `rtgodam_meta.layers`, a list of flat objects: + +```json +{ "id": "6c0f…", "type": "acme/countdown", "name": "Countdown Layer", "displayTime": 12.5, "duration": 10, "label": "Sale ends in", "endsAt": "2026-12-01T09:00" } +``` + +| Key | Owner | +|---|---| +| `id`, `type`, `name`, `displayTime` | GoDAM (managed) | +| `duration`, `allow_skip`, `custom_css`, `trigger`, `watchDepth` | Shared by all types | +| everything else | Your type's `attributes` | + +The editor reads and writes this through `/wp/v2/media/{id}` (the `rtgodam_meta` field). Saving through that route runs the [cleaning](#cleaning-on-save). + +## Analytics + +`ctx.api.track( action, metadata )` records a layer interaction, once per layer and action per page. + +**Limitation:** GoDAM's analytics service accepts only GoDAM's own layer types today (and `woo`). For any other type, `track()` records nothing and logs `GoDAM: analytics doesn't record layer type "…" yet.` once. Support for namespaced types needs a change on the analytics service, which is planned. + +## Moving from the old hooks + +These still work until **GoDAM 2.9.0**. Each logs a deprecation notice when used: in PHP through `_deprecated_hook()` (with `WP_DEBUG`), in JS in the console once per page. + +| Deprecated since 2.7.0 | Use instead | +|---|---| +| `godam_video_editor_layer_options` filter | `godam_register_layer_type()`, plus `getAvailability` in the editor | +| `godam_video_editor_layer_components` filter | `godam_register_layer_type()` with an `editorScript` | +| `godam_player_render_layer` action | `render_callback` | +| `window.godamLayerComponents` | the `edit` setting of `registerLayerType()` | +| `window.godamLayerCreators` | the `create` setting of `registerLayerType()` | +| `window.godamVideoEditorActions` (`updateLayerField`) | `useLayerAttributes()` | +| `window.godamLayerRegistry.registerLayerType()` and `window.godamLayerRegistryQueue` | `registerLayerRuntime()` | +| reading `state.videoReducer` with your own react-redux | `useLayer()`, `useLayerAttributes()`, `useMediaType()` | + +**Keep your type's name.** Renaming it would orphan layers already saved with the old `type`. Types saved before the Layer API without a namespace (godam-for-woo's `woo`) are allowed to keep it. + +godam-for-woo's move to this API is a worked example of a full migration: rtCamp/godam-for-woo#251. + +## Troubleshooting + +| You see | Why | +|---|---| +| The type isn't in **Add layer** | The editor script didn't run, or `registerLayerType()` was rejected (check the console for `GoDAM: layer type names must be namespaced…`). Or `supports.media` doesn't include the media open in the editor. | +| "This layer needs an add-on that isn't active" in a layer's panel | The editor has a saved layer whose type nobody registered in JS. The layer is kept until someone deletes it. | +| `GoDAM: no runtime registered for layer type "…"` | The view script didn't load or didn't call `registerLayerRuntime()`. The layer is skipped. | +| The layer never appears on the video | `render_callback` returned `''`, the container's id doesn't match `layer-{instance_id}-{id}`, `validate()` returned `false`, or the handlers never call `api.show()`. | +| An attribute disappears after saving | It isn't declared in `layer.json` `attributes`. | +| Markup missing from the container | It was stripped by `wp_kses_post()`. Set `supports.rawHtml` and escape it yourself. | +| `GoDAM: … failed to mount.` / `… handler failed.` | Your `mount()` or a handler threw. The error follows in the console. | From 90e95d8e116957b43d4bcc7ac4dc57f37ddd4698 Mon Sep 17 00:00:00 2001 From: KMchaudhary Date: Wed, 4 Nov 2026 21:13:11 +0530 Subject: [PATCH 12/20] refactor(layers): give each core layer type its own folder, built like core blocks GoDAM's core layer types now follow the structure an add-on layer type uses, the way Gutenberg's block-library holds each core block: assets/src/layers// layer.json metadata, with "viewScript": "file:./view.js" .php render callback + godam_register_layer_type() editor.js registerLayerType() settings edit.js the settings panel (moved from pages/video-editor) view.js registerLayerRuntime() (moved from godam-player/layers) A new `layers` webpack config builds each view.js (with its view.asset.php) into assets/build/layers// and copies layer.json and the PHP beside it. Core_Layer_Types loads each type from the build, falling back to the source when the plugin isn't built. - View scripts load only on pages that show that layer type (Gutenberg viewScript behaviour), instead of being bundled into the player and image scripts. The image script drops from 33 KB to 16.5 KB. - The block editor and the Elementor and WPBakery editors, which draw layers without the page rendering them, enqueue the view scripts up front. - The shared FormLayerManager behind CTA, Form and Poll stays in the player bundle. The views only add their layers to it. - whenLayerRuntime() lets a player or image mount a layer whose view script loads after it started (deferred or delayed JS). - The registry only registers built file: scripts (with an *.asset.php), sets their translations, and prefixes core handles with godam-layer-. - assets/src/layers is left out of the release; it ships from assets/build/layers. Co-Authored-By: Claude Opus 5.5 --- .distignore | 2 + .../godam-image-layers/render-image-frame.js | 38 +++- .../render-image-frame.test.js | 16 ++ assets/src/js/godam-layers/runtime/host.js | 10 +- .../src/js/godam-layers/runtime/registry.js | 32 ++++ .../js/godam-layers/runtime/runtime.test.js | 19 ++ assets/src/js/godam-player/layers/index.js | 23 --- assets/src/js/godam-player/layers/overlay.js | 21 +-- .../managers/layers/formLayerManager.test.js | 4 +- .../managers/layersManager.contract.test.js | 18 +- .../js/godam-player/managers/layersManager.js | 32 +++- assets/src/layers/ad/ad.php | 33 ++++ .../src/layers/ad/edit.js | 6 +- .../ad.js => assets/src/layers/ad/editor.js | 4 +- assets/src/layers/cta/cta.php | 71 ++++++++ .../src/layers/cta/edit.js | 16 +- .../cta.js => assets/src/layers/cta/editor.js | 6 +- assets/src/layers/cta/layer.json | 1 + .../layers/cta.js => layers/cta/view.js} | 9 +- .../src/layers/form}/class-form-providers.php | 1 + .../src/layers/form/edit.js | 10 +- .../src/layers/form/edit.test.js | 22 +-- .../src/layers/form/editor.js | 8 +- assets/src/layers/form/form.php | 38 ++++ assets/src/layers/form/layer.json | 1 + .../src/layers/form/providers.js | 48 ++--- .../src/layers/form/providers.test.js | 18 +- .../form/view-providers.js} | 2 +- .../layers/form.js => layers/form/view.js} | 10 +- .../src/layers/hotspot/edit.js | 26 +-- .../src/layers/hotspot/editor.js | 6 +- assets/src/layers/hotspot/hotspot.php | 62 +++++++ assets/src/layers/hotspot/layer.json | 1 + .../hotspot.js => layers/hotspot/view.js} | 8 +- .../core => assets/src/layers}/index.js | 10 +- .../src/layers/poll/edit.js | 12 +- .../src/layers/poll/editor.js | 6 +- assets/src/layers/poll/layer.json | 1 + assets/src/layers/poll/poll.php | 59 ++++++ .../layers/poll.js => layers/poll/view.js} | 6 +- assets/src/layers/shared/overlay.js | 28 +++ .../layers.test.js => layers/views.test.js} | 13 +- docs/layer-api.md | 17 +- inc/classes/class-blocks.php | 12 ++ inc/classes/class-elementor-widgets.php | 4 + inc/classes/layers/class-core-layer-types.php | 169 +++++------------- .../layers/class-layer-type-registry.php | 36 +++- inc/classes/shortcodes/class-godam-image.php | 4 + package-lock.json | 2 + package.json | 2 + .../components/SidebarLayers.test.js | 10 +- .../components/layers/Layer.test.js | 12 +- .../components/timeline/Timeline.test.js | 10 +- pages/video-editor/layers/index.js | 4 +- pages/video-editor/layers/layers.test.js | 10 +- .../acme-countdown/build/editor.asset.php | 1 + tests/fixtures/layers/built-core/layer.json | 7 + .../fixtures/layers/built-core/view.asset.php | 1 + tests/fixtures/layers/built-core/view.js | 1 + tests/js/register-core-layer-views.js | 25 +++ tests/php/LayerAssetsTest.php | 29 ++- tests/php/LayerTypeRegistryTest.php | 2 +- tests/stubs/layer-registry.php | 4 +- webpack.config.js | 49 +++++ 64 files changed, 832 insertions(+), 336 deletions(-) delete mode 100644 assets/src/js/godam-player/layers/index.js create mode 100644 assets/src/layers/ad/ad.php rename pages/video-editor/components/layers/AdsLayer.js => assets/src/layers/ad/edit.js (79%) rename pages/video-editor/layers/core/ad.js => assets/src/layers/ad/editor.js (84%) create mode 100644 assets/src/layers/cta/cta.php rename pages/video-editor/components/layers/CTALayer.js => assets/src/layers/cta/edit.js (91%) rename pages/video-editor/layers/core/cta.js => assets/src/layers/cta/editor.js (59%) rename assets/src/{js/godam-player/layers/cta.js => layers/cta/view.js} (64%) rename {inc/classes/layers => assets/src/layers/form}/class-form-providers.php (99%) rename pages/video-editor/components/layers/FormLayer.js => assets/src/layers/form/edit.js (86%) rename pages/video-editor/components/layers/FormLayer.test.js => assets/src/layers/form/edit.test.js (79%) rename pages/video-editor/layers/core/form.js => assets/src/layers/form/editor.js (78%) create mode 100644 assets/src/layers/form/form.php rename pages/video-editor/layers/form-providers.js => assets/src/layers/form/providers.js (74%) rename pages/video-editor/layers/form-providers.test.js => assets/src/layers/form/providers.test.js (86%) rename assets/src/{js/godam-player/layers/form-providers.js => layers/form/view-providers.js} (99%) rename assets/src/{js/godam-player/layers/form.js => layers/form/view.js} (90%) rename pages/video-editor/components/layers/HotspotLayer.js => assets/src/layers/hotspot/edit.js (96%) rename pages/video-editor/layers/core/hotspot.js => assets/src/layers/hotspot/editor.js (58%) create mode 100644 assets/src/layers/hotspot/hotspot.php rename assets/src/{js/godam-player/layers/hotspot.js => layers/hotspot/view.js} (92%) rename {pages/video-editor/layers/core => assets/src/layers}/index.js (73%) rename pages/video-editor/components/layers/PollLayer.js => assets/src/layers/poll/edit.js (81%) rename pages/video-editor/layers/core/poll.js => assets/src/layers/poll/editor.js (69%) create mode 100644 assets/src/layers/poll/poll.php rename assets/src/{js/godam-player/layers/poll.js => layers/poll/view.js} (89%) create mode 100644 assets/src/layers/shared/overlay.js rename assets/src/{js/godam-player/layers/layers.test.js => layers/views.test.js} (93%) create mode 100644 tests/fixtures/layers/acme-countdown/build/editor.asset.php create mode 100644 tests/fixtures/layers/built-core/layer.json create mode 100644 tests/fixtures/layers/built-core/view.asset.php create mode 100644 tests/fixtures/layers/built-core/view.js create mode 100644 tests/js/register-core-layer-views.js diff --git a/.distignore b/.distignore index 2f7c035439..08643a97c8 100644 --- a/.distignore +++ b/.distignore @@ -2,6 +2,8 @@ node_modules/ assets/src/blocks assets/src/css assets/src/js +# Core layer types ship from assets/build/layers (layer.json, PHP and built scripts). +assets/src/layers assets/src/libs/jquery-ui-1.14.2.draggable .browserslistrc .eslintignore diff --git a/assets/src/js/godam-image-layers/render-image-frame.js b/assets/src/js/godam-image-layers/render-image-frame.js index 62558b7c49..d28e4e93b5 100644 --- a/assets/src/js/godam-image-layers/render-image-frame.js +++ b/assets/src/js/godam-image-layers/render-image-frame.js @@ -8,8 +8,8 @@ * * Layers are mounted through the Layer API runtimes (#2294), exactly as on a * video, on a host whose media is the image. Only runtimes that declare - * `supports.media: [ 'image' ]` run here (core: Hotspot; add-ons: the Woo layer - * through the legacy registry). A tiny "media host" adapter stands in for the + * `supports.media: [ 'image' ]` run here (core: Hotspot, from its view script + * `assets/build/layers/hotspot/view.js`; add-ons such as the Woo layer). A tiny "media host" adapter stands in for the * Video.js player; timeline and playback methods are no-ops. * * Note: importing this module is NOT side-effect-free — it initializes @@ -25,8 +25,7 @@ // Woo front-end script pushed to (image-only pages never boot the video player). import './../godam-player/utils/layer-registry-init.js'; import { createLayerHost } from './../godam-layers/runtime/host.js'; -import { layersUseIconFont } from './../godam-layers/runtime/registry.js'; -import { registerHotspotRuntime } from './../godam-player/layers/hotspot.js'; +import { layersUseIconFont, getLayerRuntime, whenLayerRuntime } from './../godam-layers/runtime/registry.js'; import { loadFontAwesome, renderFontAwesomeIcons } from './../godam-player/utils/pluginLoader.js'; /** @@ -112,7 +111,6 @@ export function initImageFrame( frame ) { const instanceId = frame.dataset.instanceId || ''; const adapter = makeImageAdapter( frame, img ); - registerHotspotRuntime(); // Everything that must be undone on teardown — resize listener, ResizeObserver // and (until it fires) the deferred image `load` handler. Populated as setup @@ -161,15 +159,41 @@ export function initImageFrame( frame ) { // absolute markers resolve against the positioned frame, while each // layer gets a private scope for its manager's index-based `.hotspot` // reposition queries. - layers.forEach( ( layer ) => { + const mountLayer = ( layer, runtime ) => { const layerEl = document.createElement( 'div' ); layerEl.className = 'godam-image-layer-item'; layerEl.dataset.layerType = String( layer?.type || '' ); layerEl.style.display = 'contents'; sharedEl.appendChild( layerEl ); - if ( ! host.mount( layer, layerEl ) ) { + if ( ! host.mount( layer, layerEl, runtime ) ) { layerEl.remove(); } + }; + + layers.forEach( ( layer ) => { + const runtime = getLayerRuntime( layer?.type ); + if ( runtime ) { + mountLayer( layer, runtime ); + return; + } + // Its view script may still load (deferred or delayed): mount it then. + const stop = whenLayerRuntime( layer?.type, ( lateRuntime ) => { + const mountLate = () => { + if ( torn ) { + return; + } + mountLayer( layer, lateRuntime ); + if ( typeof lateRuntime.usesIconFont === 'function' && lateRuntime.usesIconFont( layer ) ) { + renderFontAwesomeIcons( frame ); + } + }; + if ( typeof lateRuntime.usesIconFont === 'function' && lateRuntime.usesIconFont( layer ) ) { + loadFontAwesome().then( mountLate ).catch( mountLate ); + } else { + mountLate(); + } + } ); + cleanups.push( stop ); } ); host.dispatch( 'onReady' ); diff --git a/assets/src/js/godam-image-layers/render-image-frame.test.js b/assets/src/js/godam-image-layers/render-image-frame.test.js index 1f8ef36295..11a03f39ca 100644 --- a/assets/src/js/godam-image-layers/render-image-frame.test.js +++ b/assets/src/js/godam-image-layers/render-image-frame.test.js @@ -13,6 +13,7 @@ import { initImageFrame } from './render-image-frame.js'; import HotspotLayerManager from '../godam-player/managers/layers/hotspotLayerManager.js'; import { registerLayerType } from '../godam-player/utils/layer-registry.js'; import { registerLayerRuntime } from '../godam-layers/runtime/registry.js'; +import { registerHotspotRuntime } from '../../layers/hotspot/view.js'; jest.mock( '../godam-player/managers/layers/hotspotLayerManager.js', () => ( { __esModule: true, @@ -66,6 +67,8 @@ describe( 'Layer API contract: image layers', () => { beforeEach( () => { delete window.godam; + // On a page the hotspot layer's view script registers its runtime. + registerHotspotRuntime(); HotspotLayerManager.mockClear(); teardowns = []; jest.spyOn( console, 'warn' ).mockImplementation( () => {} ); @@ -158,6 +161,19 @@ describe( 'Layer API contract: image layers', () => { expect( frame.querySelector( '.godam-image-layer-item' ).textContent ).toBe( 'Countdown' ); } ); + it( 'draws a layer whose view script loads after the frame', () => { + const frame = makeFrame( [ { id: 'a1', type: 'acme/late' } ] ); + init( frame ); + expect( frame.querySelector( '.godam-image-layer-item' ) ).toBeNull(); + + registerLayerRuntime( 'acme/late', { supports: { media: [ 'image' ] }, mount: ( ctx ) => { + ctx.container.textContent = 'Late'; + return {}; + } } ); + + expect( frame.querySelector( '.godam-image-layer-item' ).textContent ).toBe( 'Late' ); + } ); + it( 'draws nothing for a frame with no layers', () => { const frame = makeFrame( [] ); init( frame ); diff --git a/assets/src/js/godam-layers/runtime/host.js b/assets/src/js/godam-layers/runtime/host.js index 0e903be503..7d607f06d5 100644 --- a/assets/src/js/godam-layers/runtime/host.js +++ b/assets/src/js/godam-layers/runtime/host.js @@ -5,7 +5,7 @@ * image. The host mounts each saved layer through its type's runtime, then * forwards player events to the handlers each `mount()` returned: * - * - `onReady()` once every saved layer is mounted + * - `onReady()` once every saved layer is mounted (and right away for a layer mounted later) * - `onTimeUpdate( currentTime )`, `onPause()`, `onEnded()` (held back while layers are suppressed) * - `onPlay()`, `onResize()`, `onFullscreenChange( isFullscreen, container )`, `onReplay()` * - `destroy()` when the layer is unmounted @@ -60,6 +60,7 @@ export function createLayerHost( { const handlerList = []; const mounted = []; const tracked = new Set(); + let ready = false; const host = { player, @@ -105,6 +106,10 @@ export function createLayerHost( { if ( ! handlerList.includes( handlers ) ) { handlerList.push( handlers ); } + // A layer mounted after `onReady` (its view script loaded late) gets it now. + if ( ready ) { + call( handlers, 'onReady' ); + } return () => host.unmount( record ); }, @@ -134,6 +139,9 @@ export function createLayerHost( { * @param {...*} args Handler arguments. */ dispatch( event, ...args ) { + if ( 'onReady' === event ) { + ready = true; + } if ( SUPPRESSIBLE_EVENTS.has( event ) && host.isSuppressed() ) { return; } diff --git a/assets/src/js/godam-layers/runtime/registry.js b/assets/src/js/godam-layers/runtime/registry.js index 4c151616cc..28cbcd5f59 100644 --- a/assets/src/js/godam-layers/runtime/registry.js +++ b/assets/src/js/godam-layers/runtime/registry.js @@ -53,6 +53,7 @@ function createRegistry() { const runtimes = new Map(); const pendingVariations = new Map(); const logged = new Set(); + const waiting = new Map(); const withVariations = ( runtime, variations ) => ( { ...runtime, @@ -101,9 +102,38 @@ function createRegistry() { ); pendingVariations.delete( name ); runtimes.set( name, runtime ); + + const callbacks = waiting.get( name ) || []; + waiting.delete( name ); + callbacks.forEach( ( callback ) => { + try { + callback( runtime ); + } catch ( error ) { + // eslint-disable-next-line no-console + console.error( `GoDAM: a layer waiting for runtime "${ name }" failed to mount.`, error ); + } + } ); return runtime; } + /** + * Run a callback once a layer type's runtime is registered: now, if it + * already is. Lets a player mount layers whose view script loads after the + * player started (scripts deferred or delayed by an optimisation plugin). + * + * @param {string} name Layer type name. + * @param {Function} callback `callback( runtime )`. + * @return {Function} Stops waiting. + */ + function whenLayerRuntime( name, callback ) { + if ( runtimes.has( name ) ) { + callback( runtimes.get( name ) ); + return () => {}; + } + waiting.set( name, [ ...( waiting.get( name ) || [] ), callback ] ); + return () => waiting.set( name, ( waiting.get( name ) || [] ).filter( ( other ) => other !== callback ) ); + } + /** * Remove a layer type's runtime. Layers already mounted keep running. * @@ -174,6 +204,7 @@ function createRegistry() { return { registerLayerRuntime, unregisterLayerRuntime, + whenLayerRuntime, registerLayerRuntimeVariation, unregisterLayerRuntimeVariation, getLayerRuntime: ( name ) => runtimes.get( name ), @@ -215,6 +246,7 @@ export function getRuntimeRegistry() { export const registerLayerRuntime = ( ...args ) => getRuntimeRegistry().registerLayerRuntime( ...args ); export const unregisterLayerRuntime = ( ...args ) => getRuntimeRegistry().unregisterLayerRuntime( ...args ); +export const whenLayerRuntime = ( ...args ) => getRuntimeRegistry().whenLayerRuntime( ...args ); export const registerLayerRuntimeVariation = ( ...args ) => getRuntimeRegistry().registerLayerRuntimeVariation( ...args ); export const unregisterLayerRuntimeVariation = ( ...args ) => getRuntimeRegistry().unregisterLayerRuntimeVariation( ...args ); export const getLayerRuntime = ( name ) => getRuntimeRegistry().getLayerRuntime( name ); diff --git a/assets/src/js/godam-layers/runtime/runtime.test.js b/assets/src/js/godam-layers/runtime/runtime.test.js index 10763496ef..404b465a7e 100644 --- a/assets/src/js/godam-layers/runtime/runtime.test.js +++ b/assets/src/js/godam-layers/runtime/runtime.test.js @@ -8,6 +8,7 @@ import { registerLayerRuntime, unregisterLayerRuntime, + whenLayerRuntime, getLayerRuntime, getLayerRuntimes, registerLayerRuntimeVariation, @@ -58,6 +59,24 @@ describe( 'Layer API: runtime registry', () => { expect( error ).toHaveBeenCalledWith( 'GoDAM: a runtime for layer type "acme/x" is already registered.' ); } ); + it( 'runs a callback once a runtime registers, or now if it already has', () => { + const late = jest.fn(); + whenLayerRuntime( 'acme/late', late ); + expect( late ).not.toHaveBeenCalled(); + registerLayerRuntime( 'acme/late', { mount } ); + expect( late ).toHaveBeenCalledWith( expect.objectContaining( { name: 'acme/late' } ) ); + + const now = jest.fn(); + whenLayerRuntime( 'acme/late', now ); + expect( now ).toHaveBeenCalledTimes( 1 ); + + const cancelled = jest.fn(); + const stop = whenLayerRuntime( 'acme/never', cancelled ); + stop(); + registerLayerRuntime( 'acme/never', { mount } ); + expect( cancelled ).not.toHaveBeenCalled(); + } ); + it( 'unregisters a runtime', () => { registerLayerRuntime( 'acme/x', { mount } ); unregisterLayerRuntime( 'acme/x' ); diff --git a/assets/src/js/godam-player/layers/index.js b/assets/src/js/godam-player/layers/index.js deleted file mode 100644 index f50e1c00b5..0000000000 --- a/assets/src/js/godam-player/layers/index.js +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Register the front-end runtimes of GoDAM's core layer types (#2294). - * - * Safe to call more than once; a type something already registered is kept. - */ - -/** - * Internal dependencies - */ -import { registerCtaRuntime } from './cta.js'; -import { registerFormRuntime } from './form.js'; -import { registerPollRuntime } from './poll.js'; -import { registerHotspotRuntime } from './hotspot.js'; - -/** - * Register the CTA, Form (with its providers), Poll and Hotspot runtimes. - */ -export function registerCoreLayerRuntimes() { - registerCtaRuntime(); - registerFormRuntime(); - registerPollRuntime(); - registerHotspotRuntime(); -} diff --git a/assets/src/js/godam-player/layers/overlay.js b/assets/src/js/godam-player/layers/overlay.js index 0cbd201a79..4d5624ca22 100644 --- a/assets/src/js/godam-player/layers/overlay.js +++ b/assets/src/js/godam-player/layers/overlay.js @@ -2,9 +2,10 @@ * The shared controller behind CTA, Form and Poll layers (#2294). * * These layers pause the video, show one at a time and have a skip button, so - * every one of them on a player shares one `FormLayerManager`. Each runtime's - * `mount()` adds its layer to it with its own `behaviour` and returns the same - * handlers, so the host sends each player event to the manager once. + * every one of them on a player shares one `FormLayerManager`. The player's + * `LayersManager` creates it, so the CTA, Form and Poll view scripts + * (`assets/src/layers/shared/overlay.js`) only add their layers to it and + * never bundle the manager themselves. */ /** @@ -37,17 +38,3 @@ export function getOverlayController( scope ) { }; } ); } - -/** - * Build a `mount()` that adds the layer to the overlay controller. - * - * @param {Function} getBehaviour `getBehaviour( ctx )` returns the `behaviour` for `FormLayerManager.setupFormLayer()`. - * @return {Function} The mount function. - */ -export function mountOverlayLayer( getBehaviour ) { - return ( ctx ) => { - const { manager, handlers } = getOverlayController( ctx ); - manager.setupFormLayer( ctx.layer, ctx.container, getBehaviour( ctx ) ); - return handlers; - }; -} diff --git a/assets/src/js/godam-player/managers/layers/formLayerManager.test.js b/assets/src/js/godam-player/managers/layers/formLayerManager.test.js index d8fa6efcba..2940e30633 100644 --- a/assets/src/js/godam-player/managers/layers/formLayerManager.test.js +++ b/assets/src/js/godam-player/managers/layers/formLayerManager.test.js @@ -2,7 +2,8 @@ * Internal dependencies */ import { createLayerHost } from '../../../godam-layers/runtime/host.js'; -import { registerCoreLayerRuntimes } from '../../layers/index.js'; +import { registerCoreLayerRuntimes } from '../../../../../../tests/js/register-core-layer-views.js'; +import { getOverlayController } from '../../layers/overlay.js'; /** * Minimal player stub — emitLayerEvent only needs a videoKey off the element. @@ -60,6 +61,7 @@ describe( 'FormLayerManager with a Marketo layer', () => { }; registerCoreLayerRuntimes(); const host = createLayerHost( { player: fakePlayer(), media: { type: 'video' }, instanceId: 'inst-1' } ); + getOverlayController( host ); layerElement = marketoLayerElement(); host.mount( { id: 'l1', type: 'form', form_type: 'marketo', displayTime: 3, allow_skip: false }, diff --git a/assets/src/js/godam-player/managers/layersManager.contract.test.js b/assets/src/js/godam-player/managers/layersManager.contract.test.js index 9e0b0341f3..78bfd55bae 100644 --- a/assets/src/js/godam-player/managers/layersManager.contract.test.js +++ b/assets/src/js/godam-player/managers/layersManager.contract.test.js @@ -17,7 +17,7 @@ import FormLayerManager from './layers/formLayerManager.js'; import HotspotLayerManager from './layers/hotspotLayerManager.js'; import { registerLayerType } from '../utils/layer-registry.js'; import { getLayerRuntime, shouldMountLayer, registerLayerRuntime, registerLayerRuntimeVariation } from '../../godam-layers/runtime/registry.js'; -import { registerCoreLayerRuntimes } from '../layers/index.js'; +import { registerCoreLayerRuntimes } from '../../../../../tests/js/register-core-layer-views.js'; jest.mock( './layers/formLayerManager.js', () => ( { __esModule: true, @@ -99,6 +99,8 @@ describe( 'Layer API contract: LayersManager dispatch', () => { beforeEach( () => { delete window.godam; delete window.godamLayerRegistry; + // On a page each core layer's view script registers its runtime. + registerCoreLayerRuntimes(); window.godamPluginDependencies = allDependencies; FormLayerManager.mockClear(); HotspotLayerManager.mockClear(); @@ -302,6 +304,20 @@ describe( 'Layer API contract: LayersManager dispatch', () => { } ); } ); + it( 'mounts a layer whose view script registers its runtime after the player set up', async () => { + const mount = jest.fn( () => ( {} ) ); + const layer = { id: 'l1', type: 'acme/late' }; + const { manager } = setup( [ layer ] ); + await manager.setupLayers(); + expect( mount ).not.toHaveBeenCalled(); + + registerLayerRuntime( 'acme/late', { mount } ); + await Promise.resolve(); + + expect( mount ).toHaveBeenCalledTimes( 1 ); + expect( mount.mock.calls[ 0 ][ 0 ].container ).toBe( containerFor( 'l1' ) ); + } ); + describe( 'layers that are skipped', () => { it( 'skips a layer with no container in the page', async () => { const { manager } = setup( [ { id: 'c', type: 'cta' } ], { skip: [ 'c' ] } ); diff --git a/assets/src/js/godam-player/managers/layersManager.js b/assets/src/js/godam-player/managers/layersManager.js index a47fed152b..a4c4d7ce30 100644 --- a/assets/src/js/godam-player/managers/layersManager.js +++ b/assets/src/js/godam-player/managers/layersManager.js @@ -7,8 +7,8 @@ import { shouldMountLayer, layersUseIconFont, logOnce, + whenLayerRuntime, } from '../../godam-layers/runtime/registry.js'; -import { registerCoreLayerRuntimes } from '../layers/index.js'; import { getOverlayController } from '../layers/overlay.js'; import { loadFontAwesome } from '../utils/pluginLoader.js'; import { isAutoPause } from './visibilityManager.js'; @@ -17,9 +17,9 @@ import { isAutoPause } from './visibilityManager.js'; * Layers Manager * * Mounts a video's saved layers through the Layer API runtimes (#2294): each - * layer's type has a runtime registered with `registerLayerRuntime()` (core - * types in `../layers/`, add-ons on `window.godam.layers`, older add-ons - * through `window.godamLayerRegistry`). The manager forwards player events to + * layer's type has a runtime registered with `registerLayerRuntime()` by its + * view script (core types in `assets/src/layers//view.js`, add-ons on + * `window.godam.layers`, older add-ons through `window.godamLayerRegistry`). The manager forwards player events to * every mounted layer and never branches on a layer type itself. */ export default class LayersManager { @@ -32,8 +32,6 @@ export default class LayersManager { this.suppressionCheck = null; // Optional predicate that pauses all layer firing this.mountedElements = new WeakSet(); - registerCoreLayerRuntimes(); - this.host = createLayerHost( { player, media: { type: 'video', element: video }, @@ -120,6 +118,8 @@ export default class LayersManager { logOnce( 'info', `GoDAM: no runtime registered for layer type "${ layer?.type }".` ); // An add-on's `godam_player_render_layer` output may not start hidden. document.querySelector( `#layer-${ this.video.dataset.instanceId }-${ layer?.id }` )?.classList.add( 'hidden' ); + // Its view script may still load (deferred or delayed): mount the layer then. + whenLayerRuntime( layer?.type, ( lateRuntime ) => this.mountLateLayer( layer, lateRuntime ) ); return; } @@ -128,6 +128,26 @@ export default class LayersManager { } } + /** + * Mount a layer whose runtime registered after the player set its layers up. + * + * @param {Object} layer - Layer configuration object + * @param {Object} runtime - The layer type's runtime + */ + async mountLateLayer( layer, runtime ) { + if ( typeof runtime.usesIconFont === 'function' && runtime.usesIconFont( layer ) ) { + try { + await loadFontAwesome(); + } catch ( error ) { + // eslint-disable-next-line no-console + console.error( 'Failed to load FontAwesome for hotspot icons:', error ); + } + } + if ( shouldMountLayer( runtime, layer ) ) { + this.handleLayerDisplay( layer, runtime ); + } + } + /** * Find the layer's element, hide it and mount the layer into it. * diff --git a/assets/src/layers/ad/ad.php b/assets/src/layers/ad/ad.php new file mode 100644 index 0000000000..bff4f37eb6 --- /dev/null +++ b/assets/src/layers/ad/ad.php @@ -0,0 +1,33 @@ + array( + 'adTag' => true, + 'rawHtml' => true, + ), + 'keep_undeclared_attributes' => true, + ) + ); +} diff --git a/pages/video-editor/components/layers/AdsLayer.js b/assets/src/layers/ad/edit.js similarity index 79% rename from pages/video-editor/components/layers/AdsLayer.js rename to assets/src/layers/ad/edit.js index 638c6d43ae..54a39950fe 100644 --- a/pages/video-editor/components/layers/AdsLayer.js +++ b/assets/src/layers/ad/edit.js @@ -11,9 +11,9 @@ import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ -import LayerControls from '../LayerControls'; -import CustomAdSettings from '../ads/CustomAdSettings'; -import LayersHeader from './LayersHeader'; +import LayerControls from '../../../../pages/video-editor/components/LayerControls'; +import CustomAdSettings from '../../../../pages/video-editor/components/ads/CustomAdSettings'; +import LayersHeader from '../../../../pages/video-editor/components/layers/LayersHeader'; const AdsLayer = ( { layerID, goBack, duration } ) => { const layer = useSelector( ( state ) => diff --git a/pages/video-editor/layers/core/ad.js b/assets/src/layers/ad/editor.js similarity index 84% rename from pages/video-editor/layers/core/ad.js rename to assets/src/layers/ad/editor.js index 044e47c29d..a7702adbdf 100644 --- a/pages/video-editor/layers/core/ad.js +++ b/assets/src/layers/ad/editor.js @@ -7,8 +7,8 @@ import { video } from '@wordpress/icons'; /** * Internal dependencies */ -import metadata from '../../../../assets/src/layers/ad/layer.json'; -import AdsLayer from '../../components/layers/AdsLayer'; +import metadata from './layer.json'; +import AdsLayer from './edit'; export { metadata }; diff --git a/assets/src/layers/cta/cta.php b/assets/src/layers/cta/cta.php new file mode 100644 index 0000000000..284546e069 --- /dev/null +++ b/assets/src/layers/cta/cta.php @@ -0,0 +1,71 @@ + __NAMESPACE__ . '\\render_cta', + // Escapes its own output (the CTA HTML goes through wp_kses_post()). + 'supports' => array( 'rawHtml' => true ), + // layer.json doesn't list every attribute a CTA saves yet. + 'keep_undeclared_attributes' => true, + ) + ); +} + +/** + * The CTA layer's container. + * + * Only HTML and card CTAs are supported. Legacy "text" CTAs (and any other + * type) render nothing: an empty box would pause playback with no content, + * and the player skips a layer whose element is missing. + * + * @param array $layer Saved layer. + * @param string $instance_id Player instance id. + * @return string Markup. + */ +function render_cta( $layer, $instance_id ) { + $cta_type = $layer['cta_type'] ?? ''; + + if ( 'html' === $cta_type && ! empty( $layer['html'] ) ) { + $cta_html = do_shortcode( $layer['html'] ); + + /** + * Filters the rendered CTA HTML content for a video layer, after + * shortcode expansion and before final sanitization. + * + * @since 2.2.0 + * + * @param string $cta_html The CTA HTML content after shortcode expansion. + * @param array $layer The layer configuration array. + */ + $cta_html = apply_filters( 'rtgodam_cta_html_content', $cta_html, $layer ); + + return Core_Layer_Types::container( $layer, $instance_id, '
' . wp_kses_post( $cta_html ) . '
' ); + } + + if ( 'image' === $cta_type && function_exists( 'rtgodam_image_cta_html' ) ) { + return Core_Layer_Types::container( $layer, $instance_id, wp_kses_post( rtgodam_image_cta_html( $layer ) ) ); + } + + return ''; +} diff --git a/pages/video-editor/components/layers/CTALayer.js b/assets/src/layers/cta/edit.js similarity index 91% rename from pages/video-editor/components/layers/CTALayer.js rename to assets/src/layers/cta/edit.js index c5f4a8edcb..3923adcddd 100644 --- a/pages/video-editor/components/layers/CTALayer.js +++ b/assets/src/layers/cta/edit.js @@ -16,14 +16,14 @@ import { useState, useEffect } from '@wordpress/element'; /** * Internal dependencies */ -import { updateLayerField } from '../../redux/slice/videoSlice'; -import CardCTA from '../cta/CardCTA'; -import HtmlCTA from '../cta/HtmlCTA'; -import LayerControls from '../LayerControls'; -import ColorPickerButton from '../shared/color-picker/ColorPickerButton.jsx'; -import LayersHeader from './LayersHeader.js'; -import TriggerSection from './shared/TriggerSection.jsx'; -import { VeSection, VeField, VeSegmented, VeCollapsible } from '../controls'; +import { updateLayerField } from '../../../../pages/video-editor/redux/slice/videoSlice'; +import CardCTA from '../../../../pages/video-editor/components/cta/CardCTA'; +import HtmlCTA from '../../../../pages/video-editor/components/cta/HtmlCTA'; +import LayerControls from '../../../../pages/video-editor/components/LayerControls'; +import ColorPickerButton from '../../../../pages/video-editor/components/shared/color-picker/ColorPickerButton.jsx'; +import LayersHeader from '../../../../pages/video-editor/components/layers/LayersHeader.js'; +import TriggerSection from '../../../../pages/video-editor/components/layers/shared/TriggerSection.jsx'; +import { VeSection, VeField, VeSegmented, VeCollapsible } from '../../../../pages/video-editor/components/controls'; // A DOMPurify config similar to what wp_kses_post() allows const wpKsesAllowed = { diff --git a/pages/video-editor/layers/core/cta.js b/assets/src/layers/cta/editor.js similarity index 59% rename from pages/video-editor/layers/core/cta.js rename to assets/src/layers/cta/editor.js index 17e47a99d5..76e85329fb 100644 --- a/pages/video-editor/layers/core/cta.js +++ b/assets/src/layers/cta/editor.js @@ -6,9 +6,9 @@ import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ -import metadata from '../../../../assets/src/layers/cta/layer.json'; -import CTALayer from '../../components/layers/CTALayer'; -import { CtaLayerIcon } from '../../components/editor-shell/icons'; +import metadata from './layer.json'; +import CTALayer from './edit'; +import { CtaLayerIcon } from '../../../../pages/video-editor/components/editor-shell/icons'; export { metadata }; diff --git a/assets/src/layers/cta/layer.json b/assets/src/layers/cta/layer.json index 6e660abe60..506cac4998 100644 --- a/assets/src/layers/cta/layer.json +++ b/assets/src/layers/cta/layer.json @@ -17,5 +17,6 @@ "link": { "type": "string", "format": "url", "default": "" }, "allow_skip": { "default": true } }, + "viewScript": "file:./view.js", "textdomain": "godam" } diff --git a/assets/src/js/godam-player/layers/cta.js b/assets/src/layers/cta/view.js similarity index 64% rename from assets/src/js/godam-player/layers/cta.js rename to assets/src/layers/cta/view.js index 673a22c431..6856325df9 100644 --- a/assets/src/js/godam-player/layers/cta.js +++ b/assets/src/layers/cta/view.js @@ -1,5 +1,6 @@ /** - * The CTA layer's front-end runtime (#2294). + * The CTA layer's front-end runtime (#2294). Built to + * `assets/build/layers/cta/view.js`; loads on pages that show a CTA layer. */ /** @@ -10,8 +11,8 @@ import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ -import { registerLayerRuntime, getLayerRuntime } from '../../godam-layers/runtime/registry.js'; -import { mountOverlayLayer } from './overlay.js'; +import { registerLayerRuntime, getLayerRuntime } from '../../js/godam-layers/runtime/registry.js'; +import { mountOverlayLayer } from '../shared/overlay.js'; /** * Register the CTA runtime, unless something already did. @@ -29,3 +30,5 @@ export function registerCtaRuntime() { } ) ), } ); } + +registerCtaRuntime(); diff --git a/inc/classes/layers/class-form-providers.php b/assets/src/layers/form/class-form-providers.php similarity index 99% rename from inc/classes/layers/class-form-providers.php rename to assets/src/layers/form/class-form-providers.php index 14b744e6f1..38b0407bbc 100644 --- a/inc/classes/layers/class-form-providers.php +++ b/assets/src/layers/form/class-form-providers.php @@ -7,6 +7,7 @@ * whether its plugin is active (`is_available`, reported to the player as * `godamPluginDependencies[ dependency_key ]`). The markup is what * `inc/templates/godam-player.php` used to print in its form `if/elseif` chain. + * Loaded by `form.php` (it lives with the Form layer, outside the autoloader). * * An add-on adds a provider with * `godam_register_layer_variation( 'form', array( 'name' => …, 'render_callback' => … ) )`. diff --git a/pages/video-editor/components/layers/FormLayer.js b/assets/src/layers/form/edit.js similarity index 86% rename from pages/video-editor/components/layers/FormLayer.js rename to assets/src/layers/form/edit.js index f7e79d280e..78ba7ff26b 100644 --- a/pages/video-editor/components/layers/FormLayer.js +++ b/assets/src/layers/form/edit.js @@ -14,11 +14,11 @@ import { useSelect } from '@wordpress/data'; /** * Internal dependencies */ -import { updateLayerField } from '../../redux/slice/videoSlice'; -import ColorPickerButton from '../shared/color-picker/ColorPickerButton.jsx'; -import LayersHeader from './LayersHeader.js'; -import { VeSection, VeToggle, VeColorList } from '../controls'; -import FormProviderPanel from '../forms/FormProviderPanel'; +import { updateLayerField } from '../../../../pages/video-editor/redux/slice/videoSlice'; +import ColorPickerButton from '../../../../pages/video-editor/components/shared/color-picker/ColorPickerButton.jsx'; +import LayersHeader from '../../../../pages/video-editor/components/layers/LayersHeader.js'; +import { VeSection, VeToggle, VeColorList } from '../../../../pages/video-editor/components/controls'; +import FormProviderPanel from '../../../../pages/video-editor/components/forms/FormProviderPanel'; /** * Component to render and manage a form layer within the video editor. The diff --git a/pages/video-editor/components/layers/FormLayer.test.js b/assets/src/layers/form/edit.test.js similarity index 79% rename from pages/video-editor/components/layers/FormLayer.test.js rename to assets/src/layers/form/edit.test.js index 0175f3abab..c59a8286a6 100644 --- a/pages/video-editor/components/layers/FormLayer.test.js +++ b/assets/src/layers/form/edit.test.js @@ -19,19 +19,19 @@ import { registerLayerVariation } from '@godam/layers'; /** * Internal dependencies */ -import FormLayer from './FormLayer'; -import { registerEditorLayerTypes } from '../../layers'; +import FormLayer from './edit'; +import { registerEditorLayerTypes } from '../../../../pages/video-editor/layers'; -jest.mock( './CTALayer', () => () => null ); -jest.mock( './HotspotLayer', () => () => null ); -jest.mock( './PollLayer', () => () => null ); -jest.mock( './AdsLayer', () => () => null ); -jest.mock( './LayersHeader.js', () => () => null ); -jest.mock( '../shared/color-picker/ColorPickerButton.jsx', () => () => null ); -jest.mock( '../forms/FormProviderPanel', () => ( props ) => +jest.mock( '../cta/edit', () => () => null ); +jest.mock( '../hotspot/edit', () => () => null ); +jest.mock( '../poll/edit', () => () => null ); +jest.mock( '../ad/edit', () => () => null ); +jest.mock( '../../../../pages/video-editor/components/layers/LayersHeader.js', () => () => null ); +jest.mock( '../../../../pages/video-editor/components/shared/color-picker/ColorPickerButton.jsx', () => () => null ); +jest.mock( '../../../../pages/video-editor/components/forms/FormProviderPanel', () => ( props ) => require( 'react' ).createElement( 'div', { 'data-form-panel': `shared:${ props.provider.name }` } ), ); -jest.mock( '../controls', () => { +jest.mock( '../../../../pages/video-editor/components/controls', () => { const { createElement: h, Fragment } = require( 'react' ); return { VeSection: ( { children } ) => h( Fragment, null, children ), @@ -39,7 +39,7 @@ jest.mock( '../controls', () => { VeToggle: ( { disabled } ) => h( 'input', { type: 'checkbox', 'data-test-id': 'allow-skip', disabled } ), }; } ); -jest.mock( '../../redux/slice/videoSlice', () => ( { +jest.mock( '../../../../pages/video-editor/redux/slice/videoSlice', () => ( { updateLayerField: ( payload ) => ( { type: 'updateLayerField', payload } ), } ) ); diff --git a/pages/video-editor/layers/core/form.js b/assets/src/layers/form/editor.js similarity index 78% rename from pages/video-editor/layers/core/form.js rename to assets/src/layers/form/editor.js index 3f4f65db2b..f1c4aedfee 100644 --- a/pages/video-editor/layers/core/form.js +++ b/assets/src/layers/form/editor.js @@ -17,10 +17,10 @@ import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ -import metadata from '../../../../assets/src/layers/form/layer.json'; -import FormLayer from '../../components/layers/FormLayer'; -import { FormLayerIcon } from '../../components/editor-shell/icons'; -import { getFormIdFromLayer } from '../../utils/formUtils'; +import metadata from './layer.json'; +import FormLayer from './edit'; +import { FormLayerIcon } from '../../../../pages/video-editor/components/editor-shell/icons'; +import { getFormIdFromLayer } from '../../../../pages/video-editor/utils/formUtils'; export { metadata }; diff --git a/assets/src/layers/form/form.php b/assets/src/layers/form/form.php new file mode 100644 index 0000000000..ee2ce58b4f --- /dev/null +++ b/assets/src/layers/form/form.php @@ -0,0 +1,38 @@ + 'form_type', + 'render_callback' => array( Form_Providers::class, 'render' ), + 'variations' => Form_Providers::get_providers(), + // Form plugins print forms, inputs and scripts, which wp_kses_post() strips. + 'supports' => array( 'rawHtml' => true ), + // Each provider saves its form ID under its own key. + 'keep_undeclared_attributes' => true, + ) + ); +} diff --git a/assets/src/layers/form/layer.json b/assets/src/layers/form/layer.json index 5433a63870..04f7d37942 100644 --- a/assets/src/layers/form/layer.json +++ b/assets/src/layers/form/layer.json @@ -15,5 +15,6 @@ "custom_css": { "default": "" }, "theme": { "type": "string", "default": "" } }, + "viewScript": "file:./view.js", "textdomain": "godam" } diff --git a/pages/video-editor/layers/form-providers.js b/assets/src/layers/form/providers.js similarity index 74% rename from pages/video-editor/layers/form-providers.js rename to assets/src/layers/form/providers.js index ca2ca1fad3..89e34fde0d 100644 --- a/pages/video-editor/layers/form-providers.js +++ b/assets/src/layers/form/providers.js @@ -25,30 +25,30 @@ import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ -import GravityForm from '../components/forms/GravityForm'; -import WPForm from '../components/forms/WPForm'; -import EverestForm from '../components/forms/EverestForm'; -import CF7 from '../components/forms/CF7'; -import JetpackForm from '../components/forms/JetpackForm'; -import SureForm from '../components/forms/Sureform.js'; -import FluentForm from '../components/forms/FluentForm.js'; -import MetForm from '../components/forms/MetForm.js'; -import ForminatorForm from '../components/forms/forminatorForms.js'; -import NinjaForm from '../components/forms/NinjaForm.js'; -import Marketo from '../components/forms/Marketo.js'; -import HubSpotForm from '../components/forms/HubSpotForm.js'; -import GFIcon from '../assets/layers/GFIcon.svg'; -import WPFormsIcon from '../assets/layers/WPForms-Mascot.svg'; -import EverestFormsIcon from '../assets/layers/EverestFormsIcon.svg'; -import CF7Icon from '../assets/layers/CF7Icon.svg'; -import JetpackIcon from '../assets/layers/JetpackIcon.svg'; -import SureformsIcon from '../assets/layers/SureFormsIcons.svg'; -import ForminatorIcon from '../assets/layers/Forminator.png'; -import FluentFormsIcon from '../assets/layers/FluentFormsIcon.png'; -import NinjaFormsIcon from '../assets/layers/NinjaFormsIcon.png'; -import MetformIcon from '../assets/layers/MetFormIcon.png'; -import MarketoIcon from '../assets/layers/MarketoIcon.svg'; -import HubSpotIcon from '../assets/layers/HubSpotIcon.svg'; +import GravityForm from '../../../../pages/video-editor/components/forms/GravityForm'; +import WPForm from '../../../../pages/video-editor/components/forms/WPForm'; +import EverestForm from '../../../../pages/video-editor/components/forms/EverestForm'; +import CF7 from '../../../../pages/video-editor/components/forms/CF7'; +import JetpackForm from '../../../../pages/video-editor/components/forms/JetpackForm'; +import SureForm from '../../../../pages/video-editor/components/forms/Sureform.js'; +import FluentForm from '../../../../pages/video-editor/components/forms/FluentForm.js'; +import MetForm from '../../../../pages/video-editor/components/forms/MetForm.js'; +import ForminatorForm from '../../../../pages/video-editor/components/forms/forminatorForms.js'; +import NinjaForm from '../../../../pages/video-editor/components/forms/NinjaForm.js'; +import Marketo from '../../../../pages/video-editor/components/forms/Marketo.js'; +import HubSpotForm from '../../../../pages/video-editor/components/forms/HubSpotForm.js'; +import GFIcon from '../../../../pages/video-editor/assets/layers/GFIcon.svg'; +import WPFormsIcon from '../../../../pages/video-editor/assets/layers/WPForms-Mascot.svg'; +import EverestFormsIcon from '../../../../pages/video-editor/assets/layers/EverestFormsIcon.svg'; +import CF7Icon from '../../../../pages/video-editor/assets/layers/CF7Icon.svg'; +import JetpackIcon from '../../../../pages/video-editor/assets/layers/JetpackIcon.svg'; +import SureformsIcon from '../../../../pages/video-editor/assets/layers/SureFormsIcons.svg'; +import ForminatorIcon from '../../../../pages/video-editor/assets/layers/Forminator.png'; +import FluentFormsIcon from '../../../../pages/video-editor/assets/layers/FluentFormsIcon.png'; +import NinjaFormsIcon from '../../../../pages/video-editor/assets/layers/NinjaFormsIcon.png'; +import MetformIcon from '../../../../pages/video-editor/assets/layers/MetFormIcon.png'; +import MarketoIcon from '../../../../pages/video-editor/assets/layers/MarketoIcon.svg'; +import HubSpotIcon from '../../../../pages/video-editor/assets/layers/HubSpotIcon.svg'; // Availability is read when asked, not at import, so page data localized after // this module loads still counts. diff --git a/pages/video-editor/layers/form-providers.test.js b/assets/src/layers/form/providers.test.js similarity index 86% rename from pages/video-editor/layers/form-providers.test.js rename to assets/src/layers/form/providers.test.js index a726d41f72..a2ebe84f7c 100644 --- a/pages/video-editor/layers/form-providers.test.js +++ b/assets/src/layers/form/providers.test.js @@ -5,7 +5,7 @@ /** * Internal dependencies */ -import '../../../tests/js/mock-form-provider-panels'; +import '../../../../tests/js/mock-form-provider-panels'; /** * External dependencies @@ -15,15 +15,15 @@ import { getLayerType, getLayerVariationByName, getDefaultAttributes, getLayerVa /** * Internal dependencies */ -import { registerEditorLayerTypes } from './index'; -import { getFormIdFromLayer, buildSettingsUrl } from '../utils/formUtils'; +import { registerEditorLayerTypes } from '../../../../pages/video-editor/layers/index'; +import { getFormIdFromLayer, buildSettingsUrl } from '../../../../pages/video-editor/utils/formUtils'; -jest.mock( '../components/layers/CTALayer', () => () => null ); -jest.mock( '../components/layers/HotspotLayer', () => () => null ); -jest.mock( '../components/layers/FormLayer', () => () => null ); -jest.mock( '../components/layers/PollLayer', () => () => null ); -jest.mock( '../components/layers/AdsLayer', () => () => null ); -jest.mock( '../redux/slice/videoSlice', () => ( { updateLayerField: jest.fn() } ) ); +jest.mock( '../cta/edit', () => () => null ); +jest.mock( '../hotspot/edit', () => () => null ); +jest.mock( './edit', () => () => null ); +jest.mock( '../poll/edit', () => () => null ); +jest.mock( '../ad/edit', () => () => null ); +jest.mock( '../../../../pages/video-editor/redux/slice/videoSlice', () => ( { updateLayerField: jest.fn() } ) ); window.videoData = { adminUrl: 'https://example.com/wp-admin/' }; window.godamVideoEditorConfig = {}; diff --git a/assets/src/js/godam-player/layers/form-providers.js b/assets/src/layers/form/view-providers.js similarity index 99% rename from assets/src/js/godam-player/layers/form-providers.js rename to assets/src/layers/form/view-providers.js index 56769099c2..824121ccc0 100644 --- a/assets/src/js/godam-player/layers/form-providers.js +++ b/assets/src/layers/form/view-providers.js @@ -14,7 +14,7 @@ /** * Internal dependencies */ -import { registerLayerRuntimeVariation, getLayerRuntime } from '../../godam-layers/runtime/registry.js'; +import { registerLayerRuntimeVariation, getLayerRuntime } from '../../js/godam-layers/runtime/registry.js'; /** * `isSubmitted()` for a provider whose confirmation matches a selector. diff --git a/assets/src/js/godam-player/layers/form.js b/assets/src/layers/form/view.js similarity index 90% rename from assets/src/js/godam-player/layers/form.js rename to assets/src/layers/form/view.js index 01b9a2e0b6..4aa0ceeee3 100644 --- a/assets/src/js/godam-player/layers/form.js +++ b/assets/src/layers/form/view.js @@ -2,7 +2,7 @@ * The Form layer's front-end runtime (#2294). * * Each form plugin is a variation selected by `layer.form_type` (see - * `form-providers.js`). A provider says whether its plugin is active, how to + * `view-providers.js`). A provider says whether its plugin is active, how to * tell the form was sent, and its label in analytics. An add-on adds a * provider with `registerLayerRuntimeVariation( 'form', { … } )`. */ @@ -19,9 +19,9 @@ import { registerLayerRuntime, getLayerRuntime, getLayerRuntimeVariation, -} from '../../godam-layers/runtime/registry.js'; -import { mountOverlayLayer } from './overlay.js'; -import { registerCoreFormProviders } from './form-providers.js'; +} from '../../js/godam-layers/runtime/registry.js'; +import { mountOverlayLayer } from '../shared/overlay.js'; +import { registerCoreFormProviders } from './view-providers.js'; /** * Whether a form layer's provider is registered and its plugin is active. @@ -78,3 +78,5 @@ export function registerFormRuntime() { } registerCoreFormProviders(); } + +registerFormRuntime(); diff --git a/pages/video-editor/components/layers/HotspotLayer.js b/assets/src/layers/hotspot/edit.js similarity index 96% rename from pages/video-editor/components/layers/HotspotLayer.js rename to assets/src/layers/hotspot/edit.js index 1b9d9c043a..9bd57b0c31 100644 --- a/pages/video-editor/components/layers/HotspotLayer.js +++ b/assets/src/layers/hotspot/edit.js @@ -26,21 +26,21 @@ import { useState, useRef, useEffect, useCallback } from '@wordpress/element'; /** * Internal dependencies */ -import { updateLayerField } from '../../redux/slice/videoSlice'; -import { isValidURL } from '../../utils'; -import { formatClock, parseClock } from '../../utils/time'; -import LayerControls from '../LayerControls'; -import FontAwesomeIconPicker from '../hotspot/FontAwesomeIconPicker'; -import ColorPickerButton from '../shared/color-picker/ColorPickerButton.jsx'; +import { updateLayerField } from '../../../../pages/video-editor/redux/slice/videoSlice'; +import { isValidURL } from '../../../../pages/video-editor/utils'; +import { formatClock, parseClock } from '../../../../pages/video-editor/utils/time'; +import LayerControls from '../../../../pages/video-editor/components/LayerControls'; +import FontAwesomeIconPicker from '../../../../pages/video-editor/components/hotspot/FontAwesomeIconPicker'; +import ColorPickerButton from '../../../../pages/video-editor/components/shared/color-picker/ColorPickerButton.jsx'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faShoppingCart } from '@fortawesome/free-solid-svg-icons'; -import LayersHeader from './LayersHeader'; -import { HOTSPOT_CONSTANTS } from '../../../../assets/src/js/godam-player/utils/constants'; -import { resolveHotspotStyle, DEFAULT_HOTSPOT_COLOR, DEFAULT_HOTSPOT_ICON_COLOR, DEFAULT_HOTSPOT_CUSTOM_ICON_BG } from '../../../../assets/src/js/godam-player/utils/hotspotStyle'; -import { resolveButtonCtaStyle, getButtonCtaClassName, getButtonCtaCssVars, getButtonFontPx, resolveButtonFontPercent, MIN_BUTTON_FONT_PX, MAX_BUTTON_FONT_PX } from '../../../../assets/src/js/godam-player/utils/buttonCtaStyle'; -import { ButtonVariantField, ButtonStyleFields, useDebouncedItemColor } from '../shared/button-cta/ButtonControls.jsx'; -import { ButtonCtaLayerIcon } from '../editor-shell/icons'; -import { VeSection, VeColorList, VeSegmented, VeTextInput, VeToggle } from '../controls'; +import LayersHeader from '../../../../pages/video-editor/components/layers/LayersHeader'; +import { HOTSPOT_CONSTANTS } from '../../js/godam-player/utils/constants'; +import { resolveHotspotStyle, DEFAULT_HOTSPOT_COLOR, DEFAULT_HOTSPOT_ICON_COLOR, DEFAULT_HOTSPOT_CUSTOM_ICON_BG } from '../../js/godam-player/utils/hotspotStyle'; +import { resolveButtonCtaStyle, getButtonCtaClassName, getButtonCtaCssVars, getButtonFontPx, resolveButtonFontPercent, MIN_BUTTON_FONT_PX, MAX_BUTTON_FONT_PX } from '../../js/godam-player/utils/buttonCtaStyle'; +import { ButtonVariantField, ButtonStyleFields, useDebouncedItemColor } from '../../../../pages/video-editor/components/shared/button-cta/ButtonControls.jsx'; +import { ButtonCtaLayerIcon } from '../../../../pages/video-editor/components/editor-shell/icons'; +import { VeSection, VeColorList, VeSegmented, VeTextInput, VeToggle } from '../../../../pages/video-editor/components/controls'; /** * Small purple pulse-dot glyph for the Style segmented control, matching the diff --git a/pages/video-editor/layers/core/hotspot.js b/assets/src/layers/hotspot/editor.js similarity index 58% rename from pages/video-editor/layers/core/hotspot.js rename to assets/src/layers/hotspot/editor.js index 5eb4d47e76..ce5f9e25cb 100644 --- a/pages/video-editor/layers/core/hotspot.js +++ b/assets/src/layers/hotspot/editor.js @@ -6,9 +6,9 @@ import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ -import metadata from '../../../../assets/src/layers/hotspot/layer.json'; -import HotspotLayer from '../../components/layers/HotspotLayer'; -import { HotspotLayerIcon } from '../../components/editor-shell/icons'; +import metadata from './layer.json'; +import HotspotLayer from './edit'; +import { HotspotLayerIcon } from '../../../../pages/video-editor/components/editor-shell/icons'; export { metadata }; diff --git a/assets/src/layers/hotspot/hotspot.php b/assets/src/layers/hotspot/hotspot.php new file mode 100644 index 0000000000..8f08560e3f --- /dev/null +++ b/assets/src/layers/hotspot/hotspot.php @@ -0,0 +1,62 @@ + __NAMESPACE__ . '\\render_hotspot', + // The image block skips a hotspot layer with nothing to draw. + 'should_render' => __NAMESPACE__ . '\\has_hotspots', + 'supports' => array( 'rawHtml' => true ), + 'keep_undeclared_attributes' => true, + ) + ); +} + +/** + * The Hotspot layer's container: empty, the view script draws the hotspots. + * + * @param array $layer Saved layer. + * @param string $instance_id Player instance id. + * @return string Markup. + */ +function render_hotspot( $layer, $instance_id ) { + return Core_Layer_Types::container( + $layer, + $instance_id, + '', + array( + 'class' => 'hotspot-layer', + 'default_bg_color' => false, + ) + ); +} + +/** + * Whether a hotspot layer has any hotspot to draw. + * + * @param array $layer Saved layer. + * @return bool + */ +function has_hotspots( $layer ) { + return ! empty( $layer['hotspots'] ); +} diff --git a/assets/src/layers/hotspot/layer.json b/assets/src/layers/hotspot/layer.json index accb72a70e..a45accb057 100644 --- a/assets/src/layers/hotspot/layer.json +++ b/assets/src/layers/hotspot/layer.json @@ -17,5 +17,6 @@ "customIconId": { "type": [ "integer", "null" ], "default": null }, "isNew": { "type": "boolean", "default": true } }, + "viewScript": "file:./view.js", "textdomain": "godam" } diff --git a/assets/src/js/godam-player/layers/hotspot.js b/assets/src/layers/hotspot/view.js similarity index 92% rename from assets/src/js/godam-player/layers/hotspot.js rename to assets/src/layers/hotspot/view.js index d2924297b9..42aa12acec 100644 --- a/assets/src/js/godam-player/layers/hotspot.js +++ b/assets/src/layers/hotspot/view.js @@ -5,9 +5,9 @@ /** * Internal dependencies */ -import { registerLayerRuntime, getLayerRuntime } from '../../godam-layers/runtime/registry.js'; -import HotspotLayerManager from '../managers/layers/hotspotLayerManager.js'; -import { resolveHotspotStyle } from '../utils/hotspotStyle.js'; +import { registerLayerRuntime, getLayerRuntime } from '../../js/godam-layers/runtime/registry.js'; +import HotspotLayerManager from '../../js/godam-player/managers/layers/hotspotLayerManager.js'; +import { resolveHotspotStyle } from '../../js/godam-player/utils/hotspotStyle.js'; /** * Whether a hotspot layer draws any FontAwesome icon. @@ -113,3 +113,5 @@ export function registerHotspotRuntime() { mount: ( ctx ) => ( ctx.media?.type === 'image' ? mountOnImage( ctx ) : mountOnVideo( ctx ) ), } ); } + +registerHotspotRuntime(); diff --git a/pages/video-editor/layers/core/index.js b/assets/src/layers/index.js similarity index 73% rename from pages/video-editor/layers/core/index.js rename to assets/src/layers/index.js index 3728dd1358..7a196f3d45 100644 --- a/pages/video-editor/layers/core/index.js +++ b/assets/src/layers/index.js @@ -11,11 +11,11 @@ import { registerLayerType, getLayerType } from '@godam/layers'; /** * Internal dependencies */ -import * as cta from './cta'; -import * as hotspot from './hotspot'; -import * as form from './form'; -import * as poll from './poll'; -import * as ad from './ad'; +import * as cta from './cta/editor'; +import * as hotspot from './hotspot/editor'; +import * as form from './form/editor'; +import * as poll from './poll/editor'; +import * as ad from './ad/editor'; export const coreLayerTypes = [ cta, hotspot, form, poll, ad ]; diff --git a/pages/video-editor/components/layers/PollLayer.js b/assets/src/layers/poll/edit.js similarity index 81% rename from pages/video-editor/components/layers/PollLayer.js rename to assets/src/layers/poll/edit.js index f2e3ad020b..489501c805 100644 --- a/pages/video-editor/components/layers/PollLayer.js +++ b/assets/src/layers/poll/edit.js @@ -12,12 +12,12 @@ import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ -import { updateLayerField } from '../../redux/slice/videoSlice'; -import ColorPickerButton from '../shared/color-picker/ColorPickerButton.jsx'; -import { useGetPollsQuery, useGetPollQuery } from '../../redux/api/polls'; -import LayersHeader from './LayersHeader.js'; -import FormPreview from '../forms/FormPreview'; -import { VeSection, VeToggle, VeColorList } from '../controls'; +import { updateLayerField } from '../../../../pages/video-editor/redux/slice/videoSlice'; +import ColorPickerButton from '../../../../pages/video-editor/components/shared/color-picker/ColorPickerButton.jsx'; +import { useGetPollsQuery, useGetPollQuery } from '../../../../pages/video-editor/redux/api/polls'; +import LayersHeader from '../../../../pages/video-editor/components/layers/LayersHeader.js'; +import FormPreview from '../../../../pages/video-editor/components/forms/FormPreview'; +import { VeSection, VeToggle, VeColorList } from '../../../../pages/video-editor/components/controls'; const PollLayer = ( { layerID, goBack, duration } ) => { const dispatch = useDispatch(); diff --git a/pages/video-editor/layers/core/poll.js b/assets/src/layers/poll/editor.js similarity index 69% rename from pages/video-editor/layers/core/poll.js rename to assets/src/layers/poll/editor.js index b2a292600b..898557c077 100644 --- a/pages/video-editor/layers/core/poll.js +++ b/assets/src/layers/poll/editor.js @@ -6,9 +6,9 @@ import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ -import metadata from '../../../../assets/src/layers/poll/layer.json'; -import PollLayer from '../../components/layers/PollLayer'; -import { PollLayerIcon } from '../../components/editor-shell/icons'; +import metadata from './layer.json'; +import PollLayer from './edit'; +import { PollLayerIcon } from '../../../../pages/video-editor/components/editor-shell/icons'; export { metadata }; diff --git a/assets/src/layers/poll/layer.json b/assets/src/layers/poll/layer.json index b16a2f5a9a..9154f249f0 100644 --- a/assets/src/layers/poll/layer.json +++ b/assets/src/layers/poll/layer.json @@ -13,5 +13,6 @@ "allow_skip": { "default": true }, "custom_css": { "default": "" } }, + "viewScript": "file:./view.js", "textdomain": "godam" } diff --git a/assets/src/layers/poll/poll.php b/assets/src/layers/poll/poll.php new file mode 100644 index 0000000000..40d1c119c0 --- /dev/null +++ b/assets/src/layers/poll/poll.php @@ -0,0 +1,59 @@ + __NAMESPACE__ . '\\render_poll', + 'is_available' => __NAMESPACE__ . '\\is_wp_polls_active', + 'dependency_key' => 'wpPolls', + // WP-Polls prints a form, which wp_kses_post() would strip. + 'supports' => array( 'rawHtml' => true ), + 'keep_undeclared_attributes' => true, + ) + ); +} + +/** + * The Poll layer's container: WP-Polls' shortcode. + * + * @param array $layer Saved layer. + * @param string $instance_id Player instance id. + * @return string Markup. + */ +function render_poll( $layer, $instance_id ) { + $poll_id = ! empty( $layer['poll_id'] ) ? intval( $layer['poll_id'] ) : 0; + return Core_Layer_Types::container( + $layer, + $instance_id, + '
' . do_shortcode( "[poll id='$poll_id']" ) . '
' + ); +} + +/** + * Whether WP-Polls is active. + * + * @return bool + */ +function is_wp_polls_active() { + return Core_Layer_Types::is_plugin_active( 'wp-polls/wp-polls.php' ); +} diff --git a/assets/src/js/godam-player/layers/poll.js b/assets/src/layers/poll/view.js similarity index 89% rename from assets/src/js/godam-player/layers/poll.js rename to assets/src/layers/poll/view.js index 786ac662e6..3332957c82 100644 --- a/assets/src/js/godam-player/layers/poll.js +++ b/assets/src/layers/poll/view.js @@ -10,8 +10,8 @@ import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ -import { registerLayerRuntime, getLayerRuntime } from '../../godam-layers/runtime/registry.js'; -import { mountOverlayLayer } from './overlay.js'; +import { registerLayerRuntime, getLayerRuntime } from '../../js/godam-layers/runtime/registry.js'; +import { mountOverlayLayer } from '../shared/overlay.js'; /** * Watch a poll layer for a vote. @@ -51,3 +51,5 @@ export function registerPollRuntime() { } ) ), } ); } + +registerPollRuntime(); diff --git a/assets/src/layers/shared/overlay.js b/assets/src/layers/shared/overlay.js new file mode 100644 index 0000000000..5dcbee75de --- /dev/null +++ b/assets/src/layers/shared/overlay.js @@ -0,0 +1,28 @@ +/** + * Mounting for the CTA, Form and Poll layers' view scripts (#2294). + * + * These layers share one `FormLayerManager` per player (pause on display, one + * at a time, skip button). The player creates it (`getOverlayController()` in + * `assets/src/js/godam-player/layers/overlay.js`) before any layer mounts, so + * a view script only adds its layer with its own `behaviour`, and does not + * bundle the manager. + */ + +// Must match OVERLAY_KEY in assets/src/js/godam-player/layers/overlay.js. +const OVERLAY_KEY = 'godam/overlay'; + +/** + * Build a `mount()` that adds the layer to the player's overlay controller. + * + * @param {Function} getBehaviour `getBehaviour( ctx )` returns the `behaviour` for `FormLayerManager.setupFormLayer()`. + * @return {Function} The mount function. + */ +export function mountOverlayLayer( getBehaviour ) { + return ( ctx ) => { + const { manager, handlers } = ctx.shared( OVERLAY_KEY, () => { + throw new Error( 'GoDAM: this layer needs the video player\'s overlay controller.' ); + } ); + manager.setupFormLayer( ctx.layer, ctx.container, getBehaviour( ctx ) ); + return handlers; + }; +} diff --git a/assets/src/js/godam-player/layers/layers.test.js b/assets/src/layers/views.test.js similarity index 93% rename from assets/src/js/godam-player/layers/layers.test.js rename to assets/src/layers/views.test.js index 572db44ac3..43032dd4b6 100644 --- a/assets/src/js/godam-player/layers/layers.test.js +++ b/assets/src/layers/views.test.js @@ -6,16 +6,17 @@ /** * Internal dependencies */ -import { registerCoreLayerRuntimes } from './index.js'; -import { hotspotLayerUsesIconFont } from './hotspot.js'; -import { createLayerHost } from '../../godam-layers/runtime/host.js'; +import { registerCoreLayerRuntimes } from '../../../tests/js/register-core-layer-views.js'; +import { hotspotLayerUsesIconFont } from './hotspot/view.js'; +import { createLayerHost } from '../js/godam-layers/runtime/host.js'; +import { getOverlayController } from '../js/godam-player/layers/overlay.js'; import { getLayerRuntime, getLayerRuntimeVariation, registerLayerRuntimeVariation, shouldMountLayer, -} from '../../godam-layers/runtime/registry.js'; -import { getLayerDisplayName } from '../utils/layerActions.js'; +} from '../js/godam-layers/runtime/registry.js'; +import { getLayerDisplayName } from '../js/godam-player/utils/layerActions.js'; const fakePlayer = () => ( { el: () => ( { getAttribute: ( attr ) => ( attr === 'data-id' ? 'vid-1' : null ) } ), @@ -55,6 +56,8 @@ describe( 'Layer API: core layer runtimes', () => { getTabHiddenAccumulatedMs: () => 0, }; host = createLayerHost( { player: fakePlayer(), media: { type: 'video' }, instanceId: 'p1', isDisplayingLayers: {} } ); + // The player's LayersManager creates the shared overlay controller. + getOverlayController( host ); } ); afterEach( () => { diff --git a/docs/layer-api.md b/docs/layer-api.md index 35557b39d4..a4f854813b 100644 --- a/docs/layer-api.md +++ b/docs/layer-api.md @@ -31,6 +31,19 @@ A layer type has one metadata file and up to three parts. Each part registers un | Editor script | the video editor | `window.godam.layers.registerLayerType()` | The settings panel, what a new layer starts with, availability in the "Add layer" menu | | View script | the page | `window.godam.layers.registerLayerRuntime()` | Shows and hides the layer, reacts to playback, resize and fullscreen, on video and images | +**GoDAM's own layer types follow the same structure.** Each lives in its own folder, the way Gutenberg's core blocks live in `packages/block-library/src//`: + +``` +assets/src/layers/cta/ +├── layer.json metadata (viewScript: "file:./view.js") +├── cta.php render callback + godam_register_layer_type() +├── editor.js registerLayerType() settings (title, icon, edit, …) +├── edit.js the settings panel +└── view.js registerLayerRuntime() +``` + +The build copies `layer.json` and the PHP to `assets/build/layers/cta/` beside the built `view.js` and `view.asset.php`, and GoDAM registers the type from there. The `cta`, `form`, `poll`, `hotspot` and `ad` folders are working examples of everything below. + **Naming:** third-party layer types need a namespace, for example `acme/countdown`, made of lowercase letters, digits and dashes. That's the value saved in each layer's `type`, so pick it once and keep it. ## Quick start: a countdown layer @@ -405,7 +418,7 @@ The runtime registry is `window.godam.layers` (handle `godam-layer-runtime`). It | `title` | Label used in analytics names. | | `variationAttribute`, `variations` | As in the editor. | -A type with no runtime is skipped, and the console logs `GoDAM: no runtime registered for layer type "…"` once. +A layer whose runtime isn't registered yet is kept back and mounted as soon as its view script registers it, so a view script that loads late (deferred or delayed by an optimisation plugin) still works. Until then the console logs `GoDAM: no runtime registered for layer type "…"` once. `whenLayerRuntime( name, callback )` runs `callback( runtime )` once a runtime registers, or straight away if it already has; it returns a function that stops waiting. ### `mount( ctx )` @@ -547,7 +560,7 @@ godam-for-woo's move to this API is a worked example of a full migration: rtCamp |---|---| | The type isn't in **Add layer** | The editor script didn't run, or `registerLayerType()` was rejected (check the console for `GoDAM: layer type names must be namespaced…`). Or `supports.media` doesn't include the media open in the editor. | | "This layer needs an add-on that isn't active" in a layer's panel | The editor has a saved layer whose type nobody registered in JS. The layer is kept until someone deletes it. | -| `GoDAM: no runtime registered for layer type "…"` | The view script didn't load or didn't call `registerLayerRuntime()`. The layer is skipped. | +| `GoDAM: no runtime registered for layer type "…"` | The view script hasn't loaded, or didn't call `registerLayerRuntime()`. The layer mounts if the runtime registers later. Otherwise it stays hidden. | | The layer never appears on the video | `render_callback` returned `''`, the container's id doesn't match `layer-{instance_id}-{id}`, `validate()` returned `false`, or the handlers never call `api.show()`. | | An attribute disappears after saving | It isn't declared in `layer.json` `attributes`. | | Markup missing from the container | It was stripped by `wp_kses_post()`. Set `supports.rawHtml` and escape it yourself. | diff --git a/inc/classes/class-blocks.php b/inc/classes/class-blocks.php index 7a60281239..96e744f839 100644 --- a/inc/classes/class-blocks.php +++ b/inc/classes/class-blocks.php @@ -33,6 +33,18 @@ protected function __construct() { */ public function setup_hooks() { add_action( 'init', array( $this, 'register_blocks' ) ); + add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_image_layer_view_scripts' ) ); + } + + /** + * Load the view scripts of layer types that run on images, for the + * godam/image block's preview. The block's edit script draws the layers in + * the editor window, so the layer runtimes must be registered there. + * + * @return void + */ + public function enqueue_image_layer_view_scripts() { + \RTGODAM\Inc\Layers\Layer_Type_Registry::get_instance()->enqueue_view_scripts_for_media( 'image' ); } /** diff --git a/inc/classes/class-elementor-widgets.php b/inc/classes/class-elementor-widgets.php index 5938112031..2b53d4a3eb 100644 --- a/inc/classes/class-elementor-widgets.php +++ b/inc/classes/class-elementor-widgets.php @@ -110,6 +110,10 @@ public function preload_image_layers_in_editor() { wp_enqueue_script( 'godam-image-layers-frontend' ); wp_enqueue_style( 'godam-image-style' ); wp_enqueue_style( 'godam-player-style' ); + + // The editor renders widgets over AJAX, where scripts a layer enqueues + // while rendering never print: load every layer type's view script now. + \RTGODAM\Inc\Layers\Layer_Type_Registry::get_instance()->enqueue_view_scripts_for_media(); } /** diff --git a/inc/classes/layers/class-core-layer-types.php b/inc/classes/layers/class-core-layer-types.php index 9a4e099a96..ad93dc2218 100644 --- a/inc/classes/layers/class-core-layer-types.php +++ b/inc/classes/layers/class-core-layer-types.php @@ -1,11 +1,13 @@ /` and adds - * its PHP part: the container it prints in the player (`render_callback`) and - * whether it can run here (`is_available`). The markup is what - * `inc/templates/godam-player.php` used to print inline. + * Each core type lives in its own folder, like a core block in Gutenberg's + * block-library: `assets/src/layers//` holds `layer.json`, `.php` + * (its render callback and registration), `editor.js`, `edit.js` and + * `view.js`. The build copies `layer.json` and the PHP to + * `assets/build/layers//` beside the built `view.js`, and this loader + * registers each type from there, through the same API add-ons use. * * @package GoDAM */ @@ -23,6 +25,13 @@ class Core_Layer_Types { use Singleton; + /** + * The core layer types, in the editor's "Add layer" order. + * + * @var string[] + */ + const TYPES = array( 'cta', 'form', 'poll', 'hotspot', 'ad' ); + /** * Register on `godam_init`, before add-ons (priority 10). */ @@ -33,47 +42,41 @@ final protected function __construct() { } /** - * Register the core types. Skips any type something already registered. + * Load each core type's PHP and register it. Skips a type something already registered. * + * @param string|null $layers_dir Folder holding the layer folders. Defaults to + * `assets/build/layers` when built, else `assets/src/layers`. * @return void */ - public function register() { - $registry = Layer_Type_Registry::get_instance(); - $types = array( - 'cta' => array( 'render_callback' => array( $this, 'render_cta' ) ), - 'form' => array( - 'variationAttribute' => 'form_type', - 'render_callback' => array( Form_Providers::class, 'render' ), - 'variations' => Form_Providers::get_providers(), - ), - 'poll' => array( - 'render_callback' => array( $this, 'render_poll' ), - 'is_available' => array( self::class, 'is_wp_polls_active' ), - 'dependency_key' => 'wpPolls', - ), - 'hotspot' => array( - 'render_callback' => array( $this, 'render_hotspot' ), - 'should_render' => array( $this, 'has_hotspots' ), - ), - // Ads play through the ad tag (IMA), so an ad layer prints no - // container; `adTag` tells the player template to request one. - 'ad' => array( 'supports' => array( 'adTag' => true ) ), - ); + public function register( $layers_dir = null ) { + $layers_dir = $layers_dir ? $layers_dir : self::get_layers_dir(); + $registry = Layer_Type_Registry::get_instance(); - foreach ( $types as $name => $args ) { - if ( null !== $registry->get( $name ) ) { + foreach ( self::TYPES as $type ) { + $file = trailingslashit( $layers_dir ) . $type . '/' . $type . '.php'; + if ( null !== $registry->get( $type ) || ! file_exists( $file ) ) { continue; } - // Core callbacks escape their own output, which includes the form - // plugins' markup (forms, inputs, scripts) that wp_kses_post() strips. - $args['supports'] = array_merge( array( 'rawHtml' => true ), $args['supports'] ?? array() ); - // Their layer.json files don't list every attribute they save yet, so - // saving cleans declared attributes and keeps the rest (see Layer_Sanitizer). - $args['keep_undeclared_attributes'] = true; - $registry->register( RTGODAM_PATH . 'assets/src/layers/' . $name . '/layer.json', $args ); + require_once $file; + $register = __NAMESPACE__ . '\\Core\\register_' . $type; + if ( function_exists( $register ) ) { + $register(); + } } } + /** + * Where the core layer folders are: the build, or the source when the plugin isn't built. + * + * Only one of them is ever loaded per request, since both declare the same functions. + * + * @return string The folder. + */ + public static function get_layers_dir() { + $build = RTGODAM_PATH . 'assets/build/layers'; + return file_exists( $build . '/cta/cta.php' ) ? $build : RTGODAM_PATH . 'assets/src/layers'; + } + /** * The `