# Solid EDC UI - Eclipse Dataspace Connector Management Interface

## Introduction

This repository provides a comprehensive management interface for Eclipse Dataspace Connector (EDC). Built with Lit and integrated with the Startin'blox ecosystem, it offers a complete solution for managing EDC assets, policies, contract definitions, and contract negotiations through an intuitive web interface. The components are designed to work with the DataspaceConnectorStore from sib-core for seamless data management.

## Features

This EDC management interface includes:

* **Assets Management:** Complete CRUD operations for data assets with data address configuration
* **Policy Management:** ODRL policy editor with permissions, prohibitions, and constraints
* **Contract Definitions:** Link policies with assets using flexible asset selectors
* **Contract Negotiations:** Monitor and manage contract negotiation lifecycles
* **DataspaceConnectorStore Integration:** Seamless integration with sib-core's EDC store
* **Tabbed Interface:** Intuitive navigation between different management functions
* **Responsive Design:** Mobile-first design that works across all devices
* **Development Tools:**
  * **Storybook:** For component documentation and isolated development, reducing the need for a heavy local environment.
  * **Cypress:** For component testing.
  * **Unpluggin Icons:** Access to a vast library of icons from [Iconify](https://icon-sets.iconify.design/).
  * **Lit Integration:** Pre-made component classes to accelerate development.
  * **Vite-powered:** Typescript, SASS, PostCSS, Autoprefixer... Focus on your component logic, not the build process.
  * **BiomeJS:** For linting and formatting, preconfigured for Startin'blox JS styling, using the most [reasonable one](https://github.com/airbnb/javascript). Use [Biome](https://biomejs.dev/fr/) within your preferred editor.

## Getting started

### Creating a new components repository

To initialize a new component repository from this boilerplate:

1. Clone this repository.
2. Rename the `origin` remote to `upstream`:

    ```bash
    git remote rename origin upstream
    ```

3. Update the `name`, `description`, and `repository.url` fields in [`package.json`](package.json).
4. Commit the changes with a `major: Initial commit` message.
5. Create a new repository on [git.startinblox.com/components](https://git.startinblox.com/components/).
6. Add the new repository as the `origin` remote:

    ```bash
    git remote add origin https://git.startinblox.com/components/your-component-name.git
    ```

7. Configure Gitlab settings (branch protection rules, FF merge only, clone instead of fetch).
8. Push to `origin master`.

For production usage, components can be served via a CDN like JSDelivr or self-hosted.

```html
  <script type="module" src="https://cdn.jsdelivr.net/npm/@startinblox/core@latest/dist/store.js" defer=""></script>
  <!--
  Or the entire core:
  <script type="module" src="https://cdn.jsdelivr.net/npm/@startinblox/core@latest/dist/index.js" defer=""></script>
  -->
  <script type="module" src="https://cdn.jsdelivr.net/npm/your-component-name@latest" defer=""></script>
  <!-- ... -->
  <your-component-1 data-src="..."></your-component-1>
  <your-component-2>Hello World!</your-component-2>
  <!-- etc. -->
```

### Installation

To set up the local development environment with Storybook:

```bash
npm install
npm run storybook
```

## Development environment

This boilerplate is designed as a **library** for multiple web components and intentionally **does not include** a default `index.html` file.

**Storybook** is the primary development environment for isolated component development and documentation. **Cypress** is integrated for component testing.

For components intended to be packaged within the broader Startin'blox environment, integrating with a local Orbit instance is recommended.

### Updating from the boilerplate

To keep your component repository synchronized with updates from this boilerplate:

1. Ensure `upstream` is configured to point to this boilerplate's repository.
2. Pull changes from the boilerplate's `upstream`:

    ```bash
    git pull upstream master
    ```

3. Resolve any merge conflicts. Changes outside the boilerplate's core code should merge smoothly.
4. Push the updates to `origin master`.

## Core Concepts

### Pre-made component classes

* `OrbitComponent`: A component designed to display or handle a Resource or Container, optionally extending its functionality for Orbit integration.
* `ObjectsHandler`: A component for rendering an array of objects, typically used within an `OrbitComponent` to display a Container.
* `ObjectHandler`: A component for rendering a single object, commonly used within an `OrbitComponent` or `ObjectsHandler` to display a Resource.

### Store reactivity

* `setupCacheInvalidation`: Invalidates the store cache and updates the component when a `save` event occurs for resources listed by specified attributes and keywords.
* `setupOnResourceReady`: Invalidates the store cache and updates the component upon a `resourceReady` event, independent of attributes.
* `setupOnSaveReset`: Resets form values by calling the `_setValue` method (which must be custom-implemented) on a `save` event containing specified keywords.

Custom cache invalidation methods can be added:

```javascript
async _afterAttach() {
  this._subscriptions.add(["name-of-the-event", (e) => {
    // Logic to execute when `name-of-the-event` occurs
  }]);
  // Ensure event deduplication before re-subscribing
  this._subscribe();
  // _afterAttach expects a Promise, you can reject on error
  return Promise.resolve();
}
```

### `OrbitComponent` default attributes and methods

**Attributes:**

* `defaultDataSrc`: (Optional) Used within Lit Tasks to track the original data source when the component's `dataSrc` is rewritten.
* `dataSrc`: (Optional) Specifies the resource to display within a Lit Task.
* `nestedField`: (Optional) Requires manual handling within a Lit Task.
* `uniq`: (Optional) Allows multiple instances of the component within the same DOM.
* `route`: (Optional) Enables router-awareness, preventing rendering/updating when the current route does not match expectations.
* `cherryPickedProperties`: (Required) An array describing the expected RDF or named properties for the component.

**Methods:**

* `render`: A Lit method; refer to Lit documentation. Should return a Lit Task or `nothing`.
* `_afterAttach`: An asynchronous method called after the component is attached to the DOM and fully initialized. Expects a resolved or rejected Promise.
* `_navigate(e)`: Facilitates navigation using the router and predefined attributes within a `render` method.
* `_getProxyValue(dataSrc)`: An asynchronous method typically called within a Lit Task. It retrieves data based on `cherryPickedProperties`, is recursive by default, and allows `cherryPickedProperties` to be overridden.
* `_responseAdaptator(res)`: An asynchronous method called before `_getProxyValue` returns its result, allowing for response adaptation (e.g., prefixing a `name` property based on `type`).
* `gatekeeper`: A pre-written method for components intended to operate exclusively within Orbit, simplifying gatekeeping logic.

`OrbitComponent` inherits methods from `ObjectsHandler`.

### `ObjectsHandler` methods

* `hasType(type)`: Checks if any object within `this.objects` shares the requested type, returning a boolean.

### `ObjectHandler` methods

* `isType(type)`: Checks if the object shares the requested type, returning a boolean.

### Available helpers

The `src/helpers` directory contains various utilities:

* `datas`:
  * `dataBuilder`: For creating mock data.
  * `filterGenerator`: For seamless object filtering using `filterObjectByX` methods.
  * `sort`: A general-purpose sorting method.
* `ui`:
  * `formatDate`: For date formatting using native `Intl` methods.
  * `lipsum`: For configuring mock word, sentence, or paragraph generation.
* `utils`:
  * `requestNavigation`: A wrapper around the Startin'blox Router for JavaScript-based navigation.
  * `uniq`: A unique ID generator.

### `cherryPickedProperties` explained

The `cherryPickedProperties` array within an `OrbitComponent` defines the properties expected by the component. Each entry can have up to four attributes:

* `key`: The original property name or RDF.
* `value`: The name this property will have within the component.
* `cast`: A callback function (e.g., `formatDate` helper) to transform the property's value.
* `expand`: If `true`, and the property contains a Resource or Container, it will be recursively expanded using the same `cherryPickedProperties`. Exercise caution with circular dependencies; `_responseAdaptator` is often more suitable for such cases, allowing `_getProxyValue` to be called with `recursive=False` or different `cherryPickedProperties`. Defaults to `false`.

**Example:**

```typescript
  cherryPickedProperties: PropertiesPicker[] = [
    { key: "name", value: "name" },
    // Using the project property two times: One with a cast to keep its @id, and one expanded giving complete access to its datas
    { key: "project", value: "projectId", cast: (r) => r["@id"] },
    // This will expand the `project` property, using the same cherryPickedProperties, so it'll contain any `project.name`, `project.project` and `project.description`
    { key: "project", value: "project", expand: true },
    { key: "description", value: "description" },
    // In any case, the `_originalResource`, the `@id`, `@context` and `@type` will be fetched and accessible
  ];
```

## Development workflow

### Localization

This project utilizes [`@lit/localize`](https://www.npmjs.com/package/@lit/localize) for internationalization.

1. Configure [`lit-localize.json`](lit-localize.json), specifically the `targetLocales` key.
2. Run `npm run locale:extract` to generate initial localization files.
3. Execute `npm run locale:extract` to update localization files whenever `str` or `msg` methods from Lit Localize are used. XLIFF files will be generated in the `locales` directory.
4. Before production deployment, run `npm run locale:build` to generate built localization files.

To change the locale at runtime within an application:

```javascript
// With Orbit:
window.setLocale.map((setLocale) => setLocale("your-lang-code"));
// Without Orbit:
window.setLocale("your-lang-code");
```

To retrieve the current locale:

```javascript
// With Orbit:
window.getLocale.map((locale) => console.log(locale));
// Without Orbit:
console.log(window.getLocale("your-lang-code"));
```

### Testing

```bash
# Run all tests
npm run cy:run
# Open Cypress's interface
npm run cy:open
```

### Building for production

```bash
# Generate localization files
npm run locale:build
# Generate Storybook documentation
npm run build-storybook
# Build the component repository
npm run build
```

## Orbit integration

Components built with this boilerplate are designed to work seamlessly with Orbit without requiring specific configurations.

To prevent potential race conditions, include `import @src/initializer;` at the top of your component's file, before the `@customElement` declaration.

Application performance can be optimized by utilizing the `gatekeeper` method within your `OrbitComponent`'s render methods.

Note that without a complete Orbit environment, interactions with external components (e.g., route management, component deduplication, global localization, conditional component display) may be limited.

## Best practices

Adhere to general web component usage rules, as outlined by [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/Web_components) or the [webcomponents.org guideline](https://www.webcomponents.org/introduction).

Tailor web components to their expected application environment. Features like the gatekeeper and localization usage should be standard practice, not exceptions. This approach ensures components are efficient and integrate effectively with the broader application and other components.

## License

[MIT](LICENSE)
