surveilr / www.surveilr.com

Resource Surveillance & Integration Engine (`surveilr`) Public Facing Omnibus Monorepo
https://www.surveilr.com
MIT License
0 stars 11 forks source link

Integrate Ornament into Astro build process for `web-ui` pages #127

Open shah opened 6 days ago

shah commented 6 days ago

We need to make many reusable web components available to surveilr web-ui SQLPage pages. Use Ornament web component infrastructure.

This approach keeps our Ornament components integrated with minimal configuration changes, ensuring they are easily accessible via https://www.surveilr.com/js/wc/component.js.

Implement the following to integrate Ornament-based web components into our existing Astro site using Astro's built-in Vite configuration.

First, install Ornament to create web components:

npm install @sirpepe/ornament

Add components to src/web-components. Here's an example component:

// src/web-components/my-greeter.ts
import { define, attr, string, number, connected, reactive } from "@sirpepe/ornament";

@define("my-greeter")
class MyGreeter extends HTMLElement {
  #shadow = this.attachShadow({ mode: "open" });

  @attr(string()) accessor name = "Anonymous";
  @attr(number({ min: 0 })) accessor age = 0;

  @reactive()
  @connected()
  greet() {
    this.#shadow.innerHTML = `Hello! My name is ${this.name}, my age is ${this.age}`;
  }
}

Add a Vite configuration to bundle your web components:

import { defineConfig } from 'astro/config';
import fs from 'fs';
import path from 'path';

const webComponentsDir = 'src/web-components';
const webComponentsFiles = fs.readdirSync(webComponentsDir).filter(file => file.endsWith('.ts'));
const inputComponents = webComponentsFiles.reduce((acc, file) => {
  const name = path.basename(file, '.ts');
  acc[name] = path.join(webComponentsDir, file);
  return acc;
}, {});

export default defineConfig({
  vite: {
    build: {
      rollupOptions: {
        input: inputComponents,
        output: {
          dir: 'public/js/wc',
          entryFileNames: '[name].js',
        },
      },
    },
  },
});

Reference the compiled JavaScript files in our SQLPage and Astro pages:

<html>
  <head>
    <script type="module" src="/js/wc/my-greeter.js"></script>
  </head>
  <body>
    <my-greeter name="Astro User" age="25"></my-greeter>
  </body>
</html>