Commit Graph

4 Commits

Author SHA1 Message Date
c528a6c336 web/admin: add application bindings to the application wizard (#11462)
* web: fix Flash of Unstructured Content while SearchSelect is loading from the backend

Provide an alternative, readonly, disabled, unindexed input object with the text "Loading...", to be
replaced with the _real_ input element after the content is loaded.

This provides the correct appearance and spacing so the content doesn't jiggle about between the
start of loading and the SearchSelect element being finalized.  It was visually distracting and
unappealing.

* web: comment on state management in API layer, move file to point to correct component under test.

* web: test for flash of unstructured content

- Add a unit test to ensure the "Loading..." element is displayed correctly before data arrives
- Demo how to mock a `fetchObjects()` call in testing. Very cool.
- Make distinguishing rule sets for code, tests, and scripts in nightmare mode
- In SearchSelect, Move the `styles()` declaration to the top of the class for consistency.

- To test for the FLOUC issue in SearchSelect.

This is both an exercise in mocking @beryju's `fetchObjects()` protocol, and shows how we can unit
test generic components that render API objects.

* web: interim commit of the basic sortable & selectable table.

* web: added basic unit testing to API-free tables

Mostly these tests assert that the table renders and that the content we give it
is where we expect it to be after sorting. For select tables, it also asserts that
the overall value of the table is what we expect it to be when we click on a
single row, or on the "select all" button.

* web: finalize testing for tables

Includes documentation updates and better tests for select-table.

* Provide unit test accessibility to Firefox and Safari; wrap calls to manipulate test DOMs directly in a browser.exec call so they run in the proper context and be await()ed properly

* web: repeat is needed to make sure sub-elements move around correctly. Map does not do full tracking.

* web: Update HorizontalLightComponent to accurately convey its value "upwards."

* interim commit, gods, the CSS is finally working.

* web: update

Got the binding editor in.  The tests complete.  Removed sonarjs.

* web: fixed tests to complete.

* web: fixed round-trip between binding list and binding editor. Fixed 'delete'.  TODO: Fix error reporting on home page, the edit button is ugly, and the height is off somehow, but I'm not yet sure how. I just know it bugs my eyes.

* core: add support to set policy bindings in transactional endpoint

Signed-off-by: Jens Langhammer <jens@goauthentik.io>

* improve permission checks

especially since we'll be using the wizard as default in the future, it shouldn't be superuser only

Signed-off-by: Jens Langhammer <jens@goauthentik.io>

* web: update api-less tables

- Replace `th` with `td` in `thead` components. Because Patternfly.
- Add @beryju's styling to the tables, which make it much better looking

* web: wizard for applications, now with bindings!

- Add policy bindings to the application wizard

- Restructures the Wizard base code.
  - ak-wizard-steps holds the steps and listens for NavigationRequest events to move
    from one step to the next.
  - WizardStep is a base class (no component registration provided) that provides the *whole frame*,
    not just the form.  It receives the navigation content for the sidebar from ak-wizard-steps,
    and provides the styling for the header, footer, sidebar, and main form.  It has abstractions
    for `buttons`, `renderMain()`, `handleButton()`, `handleEnable()`, in a section well-marked as
    "Public API".  Steps inherit from this class.

Conceptually:

- A wizard is a series of pages ("steps") with a distinct beginning and end, linked in a series,
  to complete a task.
- Later steps in the series are inaccessible until an earlier steps has granted access to it.
- Access is predicated on the earlier step being complete and valid. The developer is responsible
  for determining what "complete and valid" means.
- The series is visible, giving the customer a sense of how much effort is needed to complete the
  task.
- A parent object maintains (and can modify as needed) the list of steps. It *can* maintain the
  information being collected from the user. Alternatively, that information can be kept in each
  step.

Details:

- Keeping with the Lit paradigm, "requests to change the system flow up, information changed by
  valid requests flows down."
- The information flows up using events: WizardNavigation, WizardUpdate, WizardClose.
- The information flows down using properties.

- ak-application-wizard-main holds the list of steps, providing a unique slot name for each.
  - It maintains the ApplicationWizardState object.
- ApplicationWizardStep inherits from WizardStep and provides:
  - A means of extraction information from forms
  - A convenience method for updating the ApplicationWizardState object, enabling future steps, and
    navigating to a future step, in the correct order.
  - A method for cleaning error from the error reporting mechanism as the user navigates from an
    error-handling state.
  - The title, description, and cancelability of the wizard.
- Steps:
  - step: Handles the application. A good starting point for understanding the point of
    the Wizard.  Check the `handleButton()` method to understand how we enable or disable access to
    future steps.
  - provider-choice: Just a list. Shows validation without the form.
  - provider: Uses a *very* esoteric Lit feature, `unsafeStaticTag`, which enables
    the display to show anything that conforms to the expectations of ApplicationWizardProviderForm.
    - ApplicationWizardProviderForm repeats some of the base of ApplicationWizardStep, but allows us
      to provide multiple variants on a single form without having to create separate steps for each
      form.
    - The forms (`provider-for-ldap`, `provider-for-radius`) are therefore *just* the form and any
      fetchers needed to populate it.
  - bindings: Shows the table of bindings.  Has a custom display for "This table is empty."
  - edit-binding: Showcase for the `SearchSelectEZ` configuration format. Has an override on the
    `handleButton` feature to figure out which binding is about to be overridden. Is also a
    `.hidden` page; it doesn't show up on the navigation sidebar, as is only navigable-to by buttons
    not associated with the button bar at the bottom.
  - submit: Has a lot of machinery of state: Reviewing with errors, reviewing without errors,
    running submission, and success. Uses `ts-pattern` a lot to make sure the state/request pairs
    make sense.

The key insight is that, even though a wizard is a series in order, that order can't be simply
maintained in a list. The parent needs various strategies for swapping pages in and out of the
sequence, while still maintaining a coherent idea of "flow" and providing the visual cues the user
needs to feel confident that the work can be completed and completed quickly. The entire mechanism
for using an array and index to navigate, with index numbering, blocked the implementation of the
bindings pages.

One thing led to another.  *Sigh*  Really wish this hadn't been as much of a mess as it turned out.
The end result is pretty good, though.  Definitely re-usable.

One important feature to note is that the wizard is *not* tied to the ModalButton object; it's
simply embedded in a modal as-needed.  This allows us to use wizards in other places, such as just
being in a DIV, or just a page on its own.

* web: rollback dependabot "upgrade" that broke testing

Dependabot rolled us into WebdriverIO 9.  While that's probably the
right thing to do, right now it breaks out end-to-end tests badly.
Dependabot's mucking with infrastructure should not be taken lightly,
especially in cases when the infrastructure is for DX, not UX, and
doesn't create a bigger attack surface on the running product.

* web: small fixes for wdio and lint

- Roll back another dependabot breaking change, this time to WebdriverIO
- Remove the redundant scripts wrapping ESLint for Precommit mode. Access to those modes is
  available through the flags to the `./web/scripts/eslint.mjs` script.
- Remove SonarJS checks until SonarJS is ESLint 9 compatible.
- Minor nitpicking.

* web: not sure where all these getElement() additions come from; did I add them?  Anyway, they were breaking the tests, they're a Wdio9-ism.

* package-lock.json update

* web: small fixes for wdio and lint

**PLEASE** Stop trying to upgrade WebdriverIO following Dependabot's instructions. The changes
between wdio8 and wdio9 are extensive enough to require a lot more manual intervention. The unit
tests fail in wdio 9, with the testbed driver Wdio uses to compile content to push to the browser
([vite](https://vitejs.dev) complaining:

```
2024-09-27T15:30:03.672Z WARN @wdio/browser-runner:vite: warning: Unrecognized default export in file /Users/ken/projects/dev/web/node_modules/@patternfly/patternfly/components/Dropdown/dropdown.css
  Plugin: postcss-lit
  File: /Users/ken/projects/dev/web/node_modules/@patternfly/patternfly/components/Dropdown/dropdown.css
[0-6] 2024-09-27T15:30:04.083Z INFO webdriver: BIDI COMMAND script.callFunction {"functionDeclaration":"<Function[976 bytes]>","awaitPromise":true,"arguments":[],"target":{"context":"8E608E6D13E355DFFC28112C236B73AF"}}
[0-6]  Error:  Test failed due to following error(s):
  - ak-search-select.test.ts: The requested module '/src/common/styles/authentik.css' does not provide an export named 'default': SyntaxError: The requested module '/src/common/styles/authentik.css' does not provide an export named 'default'

```

So until we can figure out why the Vite installation isn't liking our CSS import scheme, we'll
have to soldier on with what we have.  At least with Wdio 8, we get:

```
Spec Files:      7 passed, 7 total (100% completed) in 00:00:19
```

* Forgot to run prettier.

* web: small fixes for elements and forms

- provides a new utility, `_isSlug_`, used to verify a user input
- extends the ak-horizontal-component wrapper to have a stronger identity and available value
- updates the types that use the wrapper to be typed more strongly
  - (Why) The above are used in the wizard to get and store values
- fixes a bug in SearchSelectEZ that broke the display if the user didn't supply a `groupBy` field.
- Adds `@wdio/types` to the package file so eslint is satisfied wdio builds correctly
- updates the end-to-end test to understand the revised button identities on the login page
  - Running the end-to-end tests verifies that changes to the components listed above did not break
    the semantics of those components.

* Prettier had opinions

* Fix the oauth2 provider test.

* web: fix oauth2 provider.  Fix resolutions in package-lock.json

* Provide an error field for the form errors on the OAuth2 form.  Unfortunately, this does not solve the general problem that we have a UX issue with which stage bindings to show where now that we've introduced the Invalidation Stage.

* web: Add InvalidationFlow to Radius Provider dialogues

## What

- Bugfix: adds the InvalidationFlow to the Radius Provider dialogues
  - Repairs: `{"invalidation_flow":["This field is required."]}` message, which was *not* propagated
    to the Notification.
- Nitpick: Pretties `?foo=${true}` expressions: `s/\?([^=]+)=\$\{true\}/\1/`

## Note

Yes, I know I'm going to have to do more magic when we harmonize the forms, and no, I didn't add the
Property Mappings to the wizard, and yes, I know I'm going to have pain with the *new* version of
the wizard. But this is a serious bug; you can't make Radius servers with *either* of the current
dialogues at the moment.

* web/admin: provide default invalidation flows for LDAP provider.

* admin/web: the default invalidation flows for LDAP and Radius are different from the others.

* Updating the SAML Wizard page to correspond to the provider page.  *This is an intermediate fix to get the tests passing. It will probably be mooted with the next revision.*

* Making progress...

* web/admin: provider formectomy complete

* fix minor issues

Signed-off-by: Jens Langhammer <jens@goauthentik.io>

* custom ordering for provider types

Signed-off-by: Jens Langhammer <jens@goauthentik.io>

* fix css

Signed-off-by: Jens Langhammer <jens@goauthentik.io>

* fix missing PFBase causing wrong font

Signed-off-by: Jens Langhammer <jens@goauthentik.io>

* fix missing card for type select

Signed-off-by: Jens Langhammer <jens@goauthentik.io>

* fix padding on last page

Signed-off-by: Jens Langhammer <jens@goauthentik.io>

* add card to bindings

Signed-off-by: Jens Langhammer <jens@goauthentik.io>

* web/element/wizard: fix the CSS cascade so the modifications to the title display don't affect the wiard header.

* web/elements/wizard: fix logic on unavailable / available / current indicators in nav bar.

* Debugging code is not needed.

* web: small visual fixes

As requested by reviewers:

- Fixed the height to 75% of the viewport
- Put 1rem of whitespace between the hint label and the Wizard startup button.

* web: disable lint check for cAsEfUnNy AtTrIbUtE nAmEs.

* Apply suggestions from code review

Co-authored-by: Marc 'risson' Schmitt <marc.schmitt@risson.space>
Signed-off-by: Jens L. <jens@beryju.org>

* rework title

Signed-off-by: Jens Langhammer <jens@goauthentik.io>

* format

Signed-off-by: Jens Langhammer <jens@goauthentik.io>

---------

Signed-off-by: Jens Langhammer <jens@goauthentik.io>
Signed-off-by: Jens L. <jens@beryju.org>
Co-authored-by: Jens Langhammer <jens@goauthentik.io>
Co-authored-by: Marc 'risson' Schmitt <marc.schmitt@risson.space>
2024-12-18 18:44:27 +01:00
dec8cfbb39 web: audit and update package.json and associated test harness, with upgrade to WebdriverIO 9 (#11596)
* Just cleaning up.

* web: removing sonarjs from yet another branch.

* web: everything except the tests are up-to-date.  There was a lot, it turns out, we simply weren't using.

* web: update package.json to support WebdriverIO 9

This commit:

- Upgrades to WebdriverIO 9.1.2
- Resets our `devDependencies` collection to remove all imports that we either were not using or
  were duplicates of existing dependencies:
  - *Babel*, of all things
  - Storybook addon css user preferences, now native to Storybook 8
  - SonarJS, *again*, sigh.
  - React

- Fixes a bug where ESLint would report missing features in our build scripts
- Fixes a bug where Wdio might not reach a headless browser before timeout
- Replaces Rollup's CSSLit with Vite's CSSLit, which actually works without hacks, for testing.
- Moves the package-lock scanner to its own script, with better reporting and tool verification,
  which also cleans up the package.lock file a little.

* Prettier just havin' all the opinions.
2024-10-03 08:11:05 -07:00
752735d480 web: search select with focus, autocomplete, and progressive search (#10728)
* web: much better focus discipline

Fix the way focus is handled in SearchSelect so that the drop-down isn't grabbing the focus away
from the Input when the user wants to type in their selection.

Because it was broken otherwise!

There's still a bug where it's possible to type in a complete value
*Label*, then leave the component's focus (input and menu) completely,
in which case the Label remains, looking innocent and correct, but
it is *not* reflective of the value as understood by the SearchSelect
API controller.

Gonna try to fix that next.  But I'm saving this as a useful checkpoint.

* .

* root: insert daphne app in correct order

Signed-off-by: Jens Langhammer <jens@goauthentik.io>

* web: implement ak-list-select

Creates a new element, ak-list-select, which is a scrollable list that reports when an element is clicked or
selected by the keyboard.

I was hideously over-engineering ak-search-select-menu, and I decided to try something simpler.  This is
that something.  The events we care about are just "change" and "lost focus", and both of those can be
attached by the parent regardless of portaling.

* web: ak-list-select is complete

An extraction of the "menu" and "list" features from SearchSelect
and DualSelect, this is a very simplified version of a visible list
that emulates the Radio/Select behavior (i.e only one from the
collection may be "valued" at the time).  It has no visible indicators
of selection (aside from some highlighting), as it's meant to be
used to present the list rather than be indicative of any state of
the list.

I was seriously over-engineering the menu.  It turns out, it's just
not that difficult after all.  The only things we care about, really,
are "did the user change the selection," "did the user click out
of the list," and "did the user press the escape key."  Those are
pre-existing events (click w/value, blur, and keydown w/keycode,
respectively), so there was no need for me to introduce new custom
events to handler them.

* web: downgrade sonarjs again, because dependabot

Dammit, really need to tell that machine to leave our versions alone.

* web: search select

After a lot of testing and experimenting, it's finally starting to look stable.
What a pain in the neck this has all been.

* web: hold

* web: search select with focus and progressive search

- New component: ak-list-select, which allows you to select from a list of elements, with keyboard
  control.
- New component: ak-portal, which manages elements by moving "slotted" content into a distant
  component, usually one attached to the body, and positions it relative to an existing element.
- ak-search-select-view has been revamped to handle focus, change, input, and blur using
  the browser native event handlers, rather than inventing my own.
- ak-search-select has been turned into a simple driver that manages the view.
- ak-search-select has a new declarative syntax for the most common use case.

I seriously over-engineered this thing, leaning too heavily on outdated knowledge or assumptions
about how the browser works.  The native event handlers attached at the component's borders works
more than fine, and by attaching the event handlers to the portaled component before sending it
off to the slots, the correct handlers get the message.  This revision leverages the browser
a *lot* more, and gets much more effective interaction with much less code.

`<ak-list-select>` is a new component that replaces the ad-hoc menu object of the old SearchSelect.
It is a standalone component that just shows a list, allows someone to navigate that list with the
keyboard or the mouse. By default, it is limited to half the height of the viewport.

The list does not have an indicator of "selected" at this time.  That's just a side effect of it
being developed as an adjunct to search-select.  Its design does not preclude extension.

It has a *lot* of CSS components that can be customized. The properties and events are documented,
but there is only one event: `change`. Consistent with HTML, the value is not sent with the `change`
event; clients are expected to extract it with `change:event.target.value`.

Like all HTML components, it is completely stringly defined; the value is either a string or
undefined.

`<ak-portal>` is a somewhat specialized "portal" component that places an `ak-list-select` in an
object on top of the existing DOM content. It can generalized to do this with any component, though,
and can be extended. It has no events or CSS, since it's "just" managing the portaling relationship.

`<ak-search-select-view>` is the heart of the system.  It takes a collection options and behaves
like an autocomplete component for them.  The only unique event it sends out is `change`, and like
`ak-list-select`, it expects the client to retrieve the value.

Like all HTML components, it is completely stringly defined; the value is either a string or
undefined.

This is the SearchSelect component we've all known to come and love, but with a better pop-up and
cleaner keyboard interaction.  It emits only one event, `ak-change`, which *does* carry the value
with it.

The Storybooks have been updated to show the current version of Search Select, with a (simulated)
API layer as well as more blunt stringly-typed tests for the View layer.  A handful of tests have
been provided to cover a number of edge cases that I discovered during testing.  These run fine
with the `npx` command, and I would love to see them integrated into CI/CD.

The search select fields `renderElement`, `renderDescription`, and `value` properties of
`ak-search-select` have been modified to take a string.  For example, the search for the
list of user looks like this:

```
<ak-search-select
    .fetchObjects=${async (query?: string): Promise<User[]> => {
        const args: CoreUsersListRequest = { ordering: "username" };
        if (query !== undefined) {
            args.search = query;
        }
        const users = await new CoreApi(DEFAULT_CONFIG).coreUsersList(args);
        return users.results;
    }}
    .renderElement=${(user: User): string => {
        return user.username;
    }}
    .renderDescription=${(user: User): TemplateResult => {
        return html`${user.name}`;
    }}
    .value=${(user: User | undefined): string | undefined => {
        return user?.username;
     }}
></ak-search-select>
```

The most common syntax for the these three fields is "just return the string contents of a field by
name," in the case of the description wrapped in a TemplateResult with no DOM components. By
automating that initialization in the `connectedCallback` of the `ak-search-select` component,
this object would look like:

<ak-search-select
    .fetchObjects=${async (query?: string): Promise<User[]> => {
        const args: CoreUsersListRequest = { ordering: "username" };
        if (query !== undefined) {
            args.search = query;
        }
        const users = await new CoreApi(DEFAULT_CONFIG).coreUsersList(args);
        return users.results;
    }}
    .renderElement=${"username"}
    .renderDescription=${"name"}
    .value=${"username"}
></ak-search-select>
```

Due to a limitation in the way properties (such as functions) are interpreted, the syntax
`renderElement="username"` is invalid; it has to be a property expression. Sorry; best I could do.

The old syntax works just fine.  This is a "detect and extend at runtime" enhancement.

* Added comments to the Component Driver Harness.

* Added more safety and comments.

* web: remove string-based access to API; replace with a consolidated "adapter" layer.

Clean out the string-based API layer in SearchSelect.  Break SearchSelect into a
"Base" that does all the work, and then wrap it in two different front-ends:
one that conforms to the old WCAPI, and one with a slightly new WCAPI:

```
<ak-search-select-ez
    .config=${{
        fetchObjects: async (query?: string): Promise<Group[]> => {
            const args: CoreGroupsListRequest = {
                ordering: "name",
                includeUsers: false,
            };
            if (query !== undefined) {
                args.search = query;
            }
            const groups = await new CoreApi(DEFAULT_CONFIG).coreGroupsList(
                args,
            );
            return groups.results;
        },
        renderElement: (group: Group): string => group.name,
        value: (group: Group | undefined): string | undefined => group?.pk,
        selected: (group: Group): boolean => group.pk === this.instance?.group
     }}
    blankable
>
</ak-search-select-ez>
```

* Prettier had opinions. In one case, an important opinion.

* Rename test and fix lint error.

* fix lint

Signed-off-by: Jens Langhammer <jens@goauthentik.io>

---------

Signed-off-by: Jens Langhammer <jens@goauthentik.io>
Co-authored-by: Jens Langhammer <jens@goauthentik.io>
2024-08-14 18:35:00 +02:00
79c01ca473 web: update to ESLint 9 (#10812)
* web: update to ESLint 9

ESLint 9 has been out for awhile now, and all of the plug-ins that we use have caught up, so it is
time to bite the bullet and upgrade.  This commit:

- upgrades to ESLint 9, and upgrades all associated plugins
- Replaces the `.eslintrc` and `.eslintignore` files with the new, "flat" configuration file,
  "eslint.config.mjs".
- Places the previous "precommit" and "nightmare" rules in `./scripts/eslint.precommit.mjs` and
  `./scripts/eslint.nightmare.mjs`, respectively
- Replaces the scripted wrappers for eslint (`eslint`, `eslint-precommit`) with a single executable
  that takes the arguments `--precommit`, which applies a stricter set of rules, and `--nightmare`,
  which applies an even more terrifyingly strict set of rules.
- Provides the scripted wrapper `./scripts/eslint.mjs` so that eslint can be run from `bun`, if one
  so chooses.
- Fixes *all* of the lint `eslint.config.mjs` now finds, including removing all of the `eslint`
  styling rules and overrides because Eslint now proudly leaves that entirely up to Prettier.

To shut Dependabot up about ESLint.

* Added explanation for no-console removal.

* web: did not need the old and unmaintained nightmare mode; it can be configured directly.
2024-08-07 15:04:18 -07:00