- 
                Notifications
    You must be signed in to change notification settings 
- Fork 10
feat: add minimal plugin system #23
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Closed
      
      
    
  
     Closed
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            12 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      dbcb25c
              
                feat: add minimal plugin system
              
              
                ramboz f5742ee
              
                fix: default loading phase for plugins
              
              
                ramboz d2ee4c3
              
                test: add tests
              
              
                ramboz e330d10
              
                test: add tests
              
              
                ramboz 90e630b
              
                test: add tests
              
              
                ramboz 5e7192a
              
                test: add tests
              
              
                ramboz af9d7e6
              
                test: add tests
              
              
                ramboz deee3f4
              
                test: add tests
              
              
                ramboz 80da353
              
                test: add tests
              
              
                ramboz 3511e6b
              
                test: add tests
              
              
                ramboz ea5bf29
              
                chore: add linting exclusion
              
              
                ramboz 73e7eb8
              
                chore: add linting exclusion
              
              
                ramboz File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| /* | ||
| * Copyright 2023 Adobe. All rights reserved. | ||
| * This file is licensed to you under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. You may obtain a copy | ||
| * of the License at http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software distributed under | ||
| * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS | ||
| * OF ANY KIND, either express or implied. See the License for the specific language | ||
| * governing permissions and limitations under the License. | ||
| */ | ||
|  | ||
| import { loadModule } from './dom-utils.js'; | ||
|  | ||
| export default class PluginsRegistry { | ||
| #plugins; | ||
|  | ||
| static parsePluginParams(id, config) { | ||
| const pluginId = !config | ||
| ? id.split('/').splice(id.endsWith('/') ? -2 : -1, 1)[0].replace(/\.js/, '') | ||
| : id; | ||
| const pluginConfig = { | ||
| load: 'eager', | ||
| ...(typeof config === 'string' || !config | ||
| ? { url: (config || id).replace(/\/$/, '') } | ||
| : config), | ||
| }; | ||
| pluginConfig.options ||= {}; | ||
| return { id: pluginId, config: pluginConfig }; | ||
| } | ||
|  | ||
| constructor() { | ||
| this.#plugins = new Map(); | ||
| } | ||
|  | ||
| // Register a new plugin | ||
| add(id, config) { | ||
| const { id: pluginId, config: pluginConfig } = PluginsRegistry.parsePluginParams(id, config); | ||
| this.#plugins.set(pluginId, pluginConfig); | ||
| } | ||
|  | ||
| // Get the plugin | ||
| get(id) { return this.#plugins.get(id); } | ||
|  | ||
| // Check if the plugin exists | ||
| includes(id) { return !!this.#plugins.has(id); } | ||
|  | ||
| // Load all plugins that are referenced by URL, and updated their configuration with the | ||
| // actual API they expose | ||
| async load(phase, context) { | ||
| [...this.#plugins.entries()] | ||
| .filter(([, plugin]) => plugin.condition | ||
| && !plugin.condition(document, plugin.options, context)) | ||
| .map(([id]) => this.#plugins.delete(id)); | ||
| return Promise.all([...this.#plugins.entries()] | ||
| // Filter plugins that don't match the execution conditions | ||
| .filter(([, plugin]) => ( | ||
| (!plugin.condition || plugin.condition(document, plugin.options, context)) | ||
| && phase === plugin.load && plugin.url | ||
| )) | ||
| .map(async ([key, plugin]) => { | ||
| try { | ||
| // If the plugin has a default export, it will be executed immediately | ||
| const pluginApi = (await loadModule( | ||
| !plugin.url.endsWith('.js') ? `${plugin.url}/${plugin.url.split('/').pop()}.js` : plugin.url, | ||
| !plugin.url.endsWith('.js') ? `${plugin.url}/${plugin.url.split('/').pop()}.css` : null, | ||
| document, | ||
| plugin.options, | ||
| context, | ||
| )) || {}; | ||
| this.#plugins.set(key, { ...plugin, ...pluginApi }); | ||
| } catch (err) { | ||
| // eslint-disable-next-line no-console | ||
| console.error('Could not load specified plugin', key); | ||
| this.#plugins.delete(key); | ||
| } | ||
| })); | ||
| } | ||
|  | ||
| // Run a specific phase in the plugin | ||
| async run(phase, context) { | ||
| return [...this.#plugins.values()] | ||
| .reduce((promise, p) => ( // Using reduce to execute plugins sequencially | ||
| p[phase] && (!p.condition | ||
| || p.condition(document, p.options, context)) | ||
| ? promise.then(() => p[phase](document, p.options, context)) | ||
| : promise | ||
| ), Promise.resolve()); | ||
| } | ||
| } | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| /* | ||
| * Copyright 2023 Adobe. All rights reserved. | ||
| * This file is licensed to you under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. You may obtain a copy | ||
| * of the License at http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software distributed under | ||
| * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS | ||
| * OF ANY KIND, either express or implied. See the License for the specific language | ||
| * governing permissions and limitations under the License. | ||
| */ | ||
|  | ||
| import { getMetadata } from './dom-utils.js'; | ||
| import PluginsRegistry from './plugins-registry.js'; | ||
| import { toClassName } from './utils.js'; | ||
|  | ||
| export default class TemplatesRegistry { | ||
| // Register a new template | ||
| // eslint-disable-next-line class-methods-use-this | ||
| add(id, url) { | ||
| if (Array.isArray(id)) { | ||
| id.forEach((i) => this.add(i)); | ||
| return; | ||
| } | ||
| const { id: templateId, config: templateConfig } = PluginsRegistry.parsePluginParams(id, url); | ||
| templateConfig.condition = () => toClassName(getMetadata('template')) === templateId; | ||
| window.hlx.plugins.add(templateId, templateConfig); | ||
| } | ||
|  | ||
| // Get the template | ||
| // eslint-disable-next-line class-methods-use-this | ||
| get(id) { return window.hlx.plugins.get(id); } | ||
|  | ||
| // Check if the template exists | ||
| // eslint-disable-next-line class-methods-use-this | ||
| includes(id) { return window.hlx.plugins.includes(id); } | ||
| } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| <!DOCTYPE html> | ||
| <html> | ||
| <body> | ||
| <main> | ||
| <div class="section"> | ||
| <div class="wrapper"> | ||
| <div class="ablock" data-block-name="asyncblock"></div> | ||
| </div> | ||
| </div> | ||
| </main> | ||
|  | ||
| <script type="module"> | ||
| /* eslint-env mocha */ | ||
| import { runTests } from '@web/test-runner-mocha'; | ||
| import { expect } from '@esm-bundle/chai'; | ||
| import { setup } from '../../src/setup.js'; | ||
| import { loadBlock } from '../../src/block-loader.js'; | ||
|  | ||
| setup(); | ||
|  | ||
| runTests(() => { | ||
| it('loadBlock - async block', async () => { | ||
| window.hlx.codeBasePath = '/test/fixtures'; | ||
| // Modify the block name | ||
| window.hlx.patchBlockConfig.push((cfg) => ({ | ||
| ...cfg, | ||
| blockName: `${cfg.blockName}-alt`, | ||
| })); | ||
| // Modify the css/js path using the new & original block name | ||
| window.hlx.patchBlockConfig.push((cfg, original) => ({ | ||
| ...cfg, | ||
| cssPath: `/blocks-alt/${original.blockName}/${cfg.blockName}.css`, | ||
| jsPath: `/blocks-alt/${original.blockName}/${cfg.blockName}.js`, | ||
| })); | ||
|  | ||
| const block = document.querySelector('.ablock'); | ||
|  | ||
| await loadBlock(block); | ||
|  | ||
| expect(block.classList.contains('ablock')).to.be.true; | ||
| expect(block.dataset.blockName).to.equal('asyncblock'); | ||
| expect(block.dataset.blockStatus).to.equal('loaded'); | ||
|  | ||
| const css = document.querySelector('link'); | ||
| expect(css.href).to.contains('/blocks-alt/asyncblock/asyncblock-alt.css'); | ||
| }); | ||
| }); | ||
| </script> | ||
| </body> | ||
| </html> | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| <!DOCTYPE html> | ||
| <html> | ||
| <head> | ||
| <meta property="foo:bar" content="baz"> | ||
| <meta name="foo-qux" content="corge"> | ||
| </head> | ||
| <body> | ||
| <script type="module"> | ||
| /* eslint-env mocha */ | ||
| import { runTests } from '@web/test-runner-mocha'; | ||
| import { expect } from '@esm-bundle/chai'; | ||
| import { getAllMetadata } from '../../src/dom-utils.js'; | ||
|  | ||
| runTests(() => { | ||
| it('get scoped properties', () => { | ||
| expect(getAllMetadata('foo')).to.eql({ | ||
| bar: 'baz', | ||
| qux: 'corge', | ||
| }); | ||
| }); | ||
|  | ||
| it('get properties for unknown scope', () => { | ||
| expect(getAllMetadata('bar')).to.eql({}); | ||
| }); | ||
|  | ||
| // Test a custom document | ||
| const testDoc = document.implementation.createHTMLDocument(); | ||
| const titleMeta = testDoc.createElement('meta'); | ||
| titleMeta.setAttribute('property', 'grault:bar'); | ||
| titleMeta.setAttribute('content', 'baz'); | ||
| testDoc.head.appendChild(titleMeta); | ||
|  | ||
| const descriptionMeta = testDoc.createElement('meta'); | ||
| descriptionMeta.setAttribute('name', 'grault-qux'); | ||
| descriptionMeta.setAttribute('content', 'corge'); | ||
| testDoc.head.appendChild(descriptionMeta); | ||
|  | ||
| it('get scoped properties from custom document', () => { | ||
| expect(getAllMetadata('grault', testDoc)).to.eql({ | ||
| bar: 'baz', | ||
| qux: 'corge', | ||
| }); | ||
| }); | ||
|  | ||
| it('get properties for unknown scope from custom document', () => { | ||
| expect(getAllMetadata('bar', testDoc)).to.eql({}); | ||
| }); | ||
| }); | ||
| </script> | ||
| </body> | ||
| </html> | 
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Plugins would load in the
eagerphase by default. should we set this tolazyso we keep the best performance by default, and require explicit opt-in toeagerfor those plugins that would need immediate instrumentation?