ui: chore - upgrade ember and friends (#14518)

* v3.20.2...v3.24.0

* Fix handle undefined outlet in route component

* Don't use template helper for optional modal.open

Using the optional-helper here will trigger a computation
in the same runloop error. This is because we are setting
the `modal`-property when the `<Ref>` component gets
rendered which will update the `this.modal`-property which
will then recompute the `optional`-helper leading to this
error.

Instead we will create an action that will call the `open`-method
on the modal when it is defined. This gets rid of the double
computation error as we will not access the modal property
twice in the same runloop when `modal` is getting set.

* Fix - fn needs to be passed function tab-nav

We create functions in the component file instead
so that fn-helper stops complaining about the
need to pass a function.

* Update ember-exam to 6.1 version

"Makes it compatible" with ember-qunit v5

* scheduleOnce setMaxHeight paged-collection

We need to schedule to get around double-computation error.

* Fix - model.data is removed from ember-data

This has been private API all along - we need to
work around the removal.

Reference: https://github.com/emberjs/data/pull/7338/files#diff-9a8746fc5c86fd57e6122f00fef3155f76f0f3003a24b53fb7c4621d95dcd9bfL1310

* Fix `propContains` instead of `deepEqual` policy

Recent model.data works differently than iterating attributes.
We use `propContains` instead of `deepEqual`. We are only
interested in the properties we assert against and match
the previous behavior with this change.

* Fix `propContains` instead of `deepEqual` token

* Better handling single-records repo test-helper

`model.data` has been removed we need to handle proxies and
model instances differently.

* Fix remaining repository tests with propContains

We don't want to match entire objects - we don't care
about properties we haven't defined in the assertion.

* Don't use template helper for optional modal.open

Using a template helper will give us a recomputation error -
we work around it by creating an explicit action on
the component instead.

* Await `I $verb the $pageObject object` step

* Fix no more customization ember-can

No need to customize, the helper handles destruction
fine on its own.

* Fix - don't pass `optional` functions to fn

We will declare the functions on the component instead.
This gives us the same behavior but no error from
`fn`, which expects a function to be passed.

* Fix - handle `undefined` state on validate modifier

StateChart can yield out an undefined `state` we need
to handle that in the validate modifier

* Fix linting errors tests directory

* Warn / turn off new ember linting issues

We will tackle them one by one and don't want to
autofix issues that could be dangerous to auto-fix.

* Auto-fix linting issues

* More linting configuration

* Fix remaining linting issues

* Fix linting issues new files after rebase

* ui: Remove ember-cli-uglify config now we are using terser (#14574)

Co-authored-by: John Cowen <johncowen@users.noreply.github.com>
This commit is contained in:
Michael Klein 2022-09-15 10:43:17 +02:00 committed by GitHub
parent f3a508f55b
commit 048572946c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
828 changed files with 6841 additions and 6517 deletions

View File

@ -1,26 +1,18 @@
<div <div class="consul-nspace-form" ...attributes>
class="consul-nspace-form"
...attributes
>
<DataWriter <DataWriter
@sink={{uri @sink={{uri
'/${partition}/${nspace}/${dc}/nspace' "/${partition}/${nspace}/${dc}/nspace"
(hash (hash partition="" nspace="" dc=@item.Datacenter)
partition=''
nspace=''
dc=@item.Datacenter
)
}} }}
@type={{'nspace'}} @type={{"nspace"}}
@label={{"Namespace"}} @label={{"Namespace"}}
@ondelete={{fn (if @ondelete @ondelete @onsubmit) @item}} @ondelete={{fn this.onDelete @item}}
@onchange={{fn (optional @onsubmit) @item}} @onchange={{fn this.onSubmit @item}}
as |writer|> as |writer|
>
<BlockSlot @name="removed" as |after|> <BlockSlot @name="removed" as |after|>
<Consul::Nspace::Notifications <Consul::Nspace::Notifications
{{notification {{notification after=(action after)}}
after=(action after)
}}
@type="remove" @type="remove"
/> />
</BlockSlot> </BlockSlot>
@ -28,34 +20,26 @@
<BlockSlot @name="content"> <BlockSlot @name="content">
{{#let {{#let
(not (can "write nspaces")) (not (can "write nspaces"))
@item @item
(hash (hash
help='Must be a valid DNS hostname. Must contain 1-64 characters (numbers, letters, and hyphens), and must begin with a letter. Once created, this cannot be changed.' help="Must be a valid DNS hostname. Must contain 1-64 characters (numbers, letters, and hyphens), and must begin with a letter. Once created, this cannot be changed."
Name=(array Name=(array
(hash (hash
test='^[a-zA-Z0-9]([a-zA-Z0-9-]{0,62}[a-zA-Z0-9])?$' test="^[a-zA-Z0-9]([a-zA-Z0-9-]{0,62}[a-zA-Z0-9])?$"
error='Name must be a valid DNS hostname.' error="Name must be a valid DNS hostname."
) )
) )
) )
(hash Description=(array))
(hash as |readOnly item Name Description|
Description=(array) }}
) <form {{on "submit" (fn writer.persist item)}} {{disabled readOnly}}>
as |readOnly item Name Description|}}
<form
{{on 'submit' (fn writer.persist item)}}
{{disabled readOnly}}
>
<StateChart <StateChart
@src={{state-chart 'validate'}} @src={{state-chart "validate"}}
as |State Guard ChartAction dispatch state|> as |State Guard ChartAction dispatch state|
>
<fieldset> <fieldset>
{{#if (is "new nspace" item=item)}} {{#if (is "new nspace" item=item)}}
@ -64,10 +48,7 @@ as |State Guard ChartAction dispatch state|>
@placeholder="Name" @placeholder="Name"
@item={{item}} @item={{item}}
@validations={{Name}} @validations={{Name}}
@chart={{hash @chart={{hash state=state dispatch=dispatch}}
state=state
dispatch=dispatch
}}
/> />
{{/if}} {{/if}}
<TextInput <TextInput
@ -76,20 +57,19 @@ as |State Guard ChartAction dispatch state|>
@label="Description (Optional)" @label="Description (Optional)"
@item={{item}} @item={{item}}
@validations={{Description}} @validations={{Description}}
@chart={{hash @chart={{hash state=state dispatch=dispatch}}
state=state
dispatch=dispatch
}}
/> />
</fieldset> </fieldset>
{{#if (can 'use acls')}} {{#if (can "use acls")}}
<fieldset id="roles"> <fieldset id="roles">
<h2>Roles</h2> <h2>Roles</h2>
<p> <p>
{{#if (can "write nspace" item=item)}} {{#if (can "write nspace" item=item)}}
By adding roles to this namespaces, you will apply them to all tokens created within this namespace. By adding roles to this namespaces, you will apply them to
all tokens created within this namespace.
{{else}} {{else}}
The following roles are applied to all tokens created within this namespace. The following roles are applied to all tokens created within
this namespace.
{{/if}} {{/if}}
</p> </p>
<RoleSelector <RoleSelector
@ -104,9 +84,11 @@ as |State Guard ChartAction dispatch state|>
<h2>Policies</h2> <h2>Policies</h2>
<p> <p>
{{#if (not readOnly)}} {{#if (not readOnly)}}
By adding policies to this namespace, you will apply them to all tokens created within this namespace. By adding policies to this namespace, you will apply them to
all tokens created within this namespace.
{{else}} {{else}}
The following policies are applied to all tokens created within this namespace. The following policies are applied to all tokens created
within this namespace.
{{/if}} {{/if}}
</p> </p>
<PolicySelector <PolicySelector
@ -123,7 +105,12 @@ as |State Guard ChartAction dispatch state|>
{{#if (and (is "new nspace" item=item) (can "create nspaces"))}} {{#if (and (is "new nspace" item=item) (can "create nspaces"))}}
<Action <Action
@type="submit" @type="submit"
{{disabled (or (is "pristine nspace" item=item) (state-matches state "error"))}} {{disabled
(or
(is "pristine nspace" item=item)
(state-matches state "error")
)
}}
> >
Save Save
</Action> </Action>
@ -131,20 +118,24 @@ as |State Guard ChartAction dispatch state|>
<Action @type="submit">Save</Action> <Action @type="submit">Save</Action>
{{/if}} {{/if}}
<Action <Action @type="reset" {{on "click" (fn this.onCancel item)}}>
@type="reset"
{{on 'click' (if @oncancel (fn @oncancel item) (fn @onsubmit item))}}
>
Cancel Cancel
</Action> </Action>
{{#if (and (not (is "new nspace" item=item)) (can "delete nspace" item=item))}} {{#if
<ConfirmationDialog @message="Are you sure you want to delete this Namespace?"> (and
(not (is "new nspace" item=item))
(can "delete nspace" item=item)
)
}}
<ConfirmationDialog
@message="Are you sure you want to delete this Namespace?"
>
<BlockSlot @name="action" as |confirm|> <BlockSlot @name="action" as |confirm|>
<Action <Action
data-test-delete data-test-delete
class="type-delete" class="type-delete"
{{on 'click' (fn confirm (fn writer.delete item))}} {{on "click" (fn confirm (fn writer.delete item))}}
> >
Delete Delete
</Action> </Action>
@ -166,4 +157,3 @@ as |State Guard ChartAction dispatch state|>
</BlockSlot> </BlockSlot>
</DataWriter> </DataWriter>
</div> </div>

View File

@ -0,0 +1,33 @@
import Component from "@glimmer/component";
import { action } from "@ember/object";
export default class NspaceForm extends Component {
@action onSubmit(item) {
const onSubmit = this.args.onsubmit;
if (onSubmit) return onSubmit(item);
}
@action onDelete(item) {
const { onsubmit, ondelete } = this.args;
if (ondelete) {
return ondelete(item);
} else {
if (onsubmit) {
return onsubmit(item);
}
}
}
@action onCancel(item) {
const { oncancel, onsubmit } = this.args;
if (oncancel) {
return oncancel(item);
} else {
if (onsubmit) {
return onsubmit(item);
}
}
}
}

View File

@ -33,24 +33,20 @@ refractor.register(handlebars);
refractor.alias({ refractor.alias({
handlebars: ['hbs'], handlebars: ['hbs'],
shell: ['sh'] shell: ['sh'],
}); });
module.exports = { module.exports = {
remarkHbsOptions: { remarkHbsOptions: {
escapeCurliesCode: false escapeCurliesCode: false,
}, },
remarkPlugins: [ remarkPlugins: [
autolinkHeadings, autolinkHeadings,
{ {
behavior: 'wrap' behavior: 'wrap',
} },
],
rehypePlugins: [
prism
], ],
rehypePlugins: [prism],
sources: [ sources: [
{ {
root: path.resolve(__dirname, 'docs'), root: path.resolve(__dirname, 'docs'),
@ -129,10 +125,10 @@ module.exports = {
pattern: '**/README.mdx', pattern: '**/README.mdx',
urlSchema: 'auto', urlSchema: 'auto',
urlPrefix: 'docs/consul-nspaces', urlPrefix: 'docs/consul-nspaces',
} },
].concat(user.sources), ].concat(user.sources),
labels: { labels: {
"consul": "Consul Components", consul: 'Consul Components',
...user.labels ...user.labels,
} },
}; };

View File

@ -15,6 +15,7 @@ app/utils/dom/event-target/event-target-shim/event.js
# misc # misc
/coverage/ /coverage/
!.* !.*
.eslintcache
# ember-try # ember-try
/.node_modules.ember-try/ /.node_modules.ember-try/

View File

@ -9,7 +9,7 @@ module.exports = {
}, },
}, },
plugins: ['ember'], plugins: ['ember'],
extends: ['eslint:recommended', 'plugin:ember/recommended'], extends: ['eslint:recommended', 'plugin:ember/recommended', 'plugin:prettier/recommended'],
env: { env: {
browser: true, browser: true,
}, },
@ -19,14 +19,34 @@ module.exports = {
'ember/no-new-mixins': ['warn'], 'ember/no-new-mixins': ['warn'],
'ember/no-jquery': 'warn', 'ember/no-jquery': 'warn',
'ember/no-global-jquery': 'warn', 'ember/no-global-jquery': 'warn',
// for 3.24 update
'ember/classic-decorator-no-classic-methods': ['warn'],
'ember/classic-decorator-hooks': ['warn'],
'ember/no-classic-classes': ['warn'],
'ember/no-mixins': ['warn'],
'ember/no-computed-properties-in-native-classes': ['warn'],
'ember/no-private-routing-service': ['warn'],
'ember/no-test-import-export': ['warn'],
'ember/no-actions-hash': ['warn'],
'ember/no-classic-components': ['warn'],
'ember/no-component-lifecycle-hooks': ['warn'],
'ember/require-tagless-components': ['warn'],
'ember/no-legacy-test-waiters': ['warn'],
'ember/no-empty-glimmer-component-classes': ['warn'],
'ember/no-get': ['off'], // be careful with autofix, might change behavior
'ember/require-computed-property-dependencies': ['off'], // be careful with autofix
'ember/use-ember-data-rfc-395-imports': ['off'], // be carful with autofix
'ember/require-super-in-lifecycle-hooks': ['off'], // be careful with autofix
'ember/require-computed-macros': ['off'], // be careful with autofix
}, },
overrides: [ overrides: [
// node files // node files
{ {
files: [ files: [
'.eslintrc.js', '.eslintrc.js',
'.dev.eslintrc.js',
'.docfy-config.js', '.docfy-config.js',
'.prettierrc.js',
'.template-lintrc.js', '.template-lintrc.js',
'ember-cli-build.js', 'ember-cli-build.js',
'testem.js', 'testem.js',

26
ui/packages/consul-ui/.gitignore vendored Normal file
View File

@ -0,0 +1,26 @@
# See https://help.github.com/ignore-files/ for more about ignoring files.
# compiled output
/dist/
/tmp/
# dependencies
/bower_components/
/node_modules/
# misc
/.env*
/.pnp*
/.sass-cache
/.eslintcache
/connect.lock
/coverage/
/libpeerconnection.log
/npm-debug.log*
/testem.log
/yarn-error.log
# ember-try
/.node_modules.ember-try/
/bower.json.ember-try
/package.json.ember-try

View File

@ -0,0 +1,21 @@
# unconventional js
/blueprints/*/files/
/vendor/
# compiled output
/dist/
/tmp/
# dependencies
/bower_components/
/node_modules/
# misc
/coverage/
!.*
.eslintcache
# ember-try
/.node_modules.ember-try/
/bower.json.ember-try
/package.json.ember-try

View File

@ -0,0 +1,5 @@
'use strict';
module.exports = {
singleQuote: true,
};

View File

@ -54,7 +54,7 @@ export default class BaseAbility extends Ability {
get canRead() { get canRead() {
if (typeof this.item !== 'undefined') { if (typeof this.item !== 'undefined') {
const perm = (get(this, 'item.Resources') || []).find(item => item.Access === ACCESS_READ); const perm = (get(this, 'item.Resources') || []).find((item) => item.Access === ACCESS_READ);
if (perm) { if (perm) {
return perm.Allow; return perm.Allow;
} }
@ -64,7 +64,7 @@ export default class BaseAbility extends Ability {
get canList() { get canList() {
if (typeof this.item !== 'undefined') { if (typeof this.item !== 'undefined') {
const perm = (get(this, 'item.Resources') || []).find(item => item.Access === ACCESS_LIST); const perm = (get(this, 'item.Resources') || []).find((item) => item.Access === ACCESS_LIST);
if (perm) { if (perm) {
return perm.Allow; return perm.Allow;
} }
@ -74,7 +74,7 @@ export default class BaseAbility extends Ability {
get canWrite() { get canWrite() {
if (typeof this.item !== 'undefined') { if (typeof this.item !== 'undefined') {
const perm = (get(this, 'item.Resources') || []).find(item => item.Access === ACCESS_WRITE); const perm = (get(this, 'item.Resources') || []).find((item) => item.Access === ACCESS_WRITE);
if (perm) { if (perm) {
return perm.Allow; return perm.Allow;
} }

View File

@ -8,10 +8,9 @@ export default class IntentionAbility extends BaseAbility {
if (typeof this.item !== 'undefined' && typeof this.item.SourcePeer !== 'undefined') { if (typeof this.item !== 'undefined' && typeof this.item.SourcePeer !== 'undefined') {
return false; return false;
} }
return super.canWrite && return super.canWrite && (typeof this.item === 'undefined' || !this.canViewCRD);
(typeof this.item === 'undefined' || !this.canViewCRD);
} }
get canViewCRD() { get canViewCRD() {
return (typeof this.item !== 'undefined' && this.item.IsManagedByCRD); return typeof this.item !== 'undefined' && this.item.IsManagedByCRD;
} }
} }

View File

@ -11,10 +11,7 @@ export default class PeerAbility extends BaseAbility {
return this.canDelete; return this.canDelete;
} }
get canDelete() { get canDelete() {
return ![ return !['DELETING', 'TERMINATED'].includes(this.item.State) && super.canDelete;
'DELETING',
'TERMINATED'
].includes(this.item.State) && super.canDelete;
} }
get canUse() { get canUse() {

View File

@ -6,7 +6,9 @@ export default class ServiceInstanceAbility extends BaseAbility {
// When we ask for service-instances its almost like a request for a single service // When we ask for service-instances its almost like a request for a single service
// When we do that we also want to know if we can read/write intentions for services // When we do that we also want to know if we can read/write intentions for services
// so here we add intentions read/write for the specific segment/service prefix // so here we add intentions read/write for the specific segment/service prefix
return super.generateForSegment(...arguments).concat([ return super
.generateForSegment(...arguments)
.concat([
this.permissions.generate('intention', ACCESS_READ, segment), this.permissions.generate('intention', ACCESS_READ, segment),
this.permissions.generate('intention', ACCESS_WRITE, segment), this.permissions.generate('intention', ACCESS_WRITE, segment),
]); ]);

View File

@ -12,7 +12,7 @@ export default class ZerviceAbility extends BaseAbility {
return false; return false;
} }
const found = this.item.Resources.find( const found = this.item.Resources.find(
item => item.Resource === 'intention' && item.Access === 'read' && item.Allow === true (item) => item.Resource === 'intention' && item.Access === 'read' && item.Allow === true
); );
return typeof found !== 'undefined'; return typeof found !== 'undefined';
} }
@ -22,7 +22,7 @@ export default class ZerviceAbility extends BaseAbility {
return false; return false;
} }
const found = this.item.Resources.find( const found = this.item.Resources.find(
item => item.Resource === 'intention' && item.Access === 'write' && item.Allow === true (item) => item.Resource === 'intention' && item.Access === 'write' && item.Allow === true
); );
return typeof found !== 'undefined'; return typeof found !== 'undefined';
} }

View File

@ -40,8 +40,8 @@ export default class NspaceAdapter extends Adapter {
Name: serialized.Name, Name: serialized.Name,
Description: serialized.Description, Description: serialized.Description,
ACLs: { ACLs: {
PolicyDefaults: serialized.ACLs.PolicyDefaults.map(item => ({ ID: item.ID })), PolicyDefaults: serialized.ACLs.PolicyDefaults.map((item) => ({ ID: item.ID })),
RoleDefaults: serialized.ACLs.RoleDefaults.map(item => ({ ID: item.ID })), RoleDefaults: serialized.ACLs.RoleDefaults.map((item) => ({ ID: item.ID })),
}, },
}} }}
`; `;
@ -57,8 +57,8 @@ export default class NspaceAdapter extends Adapter {
${{ ${{
Description: serialized.Description, Description: serialized.Description,
ACLs: { ACLs: {
PolicyDefaults: serialized.ACLs.PolicyDefaults.map(item => ({ ID: item.ID })), PolicyDefaults: serialized.ACLs.PolicyDefaults.map((item) => ({ ID: item.ID })),
RoleDefaults: serialized.ACLs.RoleDefaults.map(item => ({ ID: item.ID })), RoleDefaults: serialized.ACLs.RoleDefaults.map((item) => ({ ID: item.ID })),
}, },
}} }}
`; `;

View File

@ -16,10 +16,10 @@ export default class PermissionAdapter extends Adapter {
// ^ same goes for Partitions // ^ same goes for Partitions
if (this.env.var('CONSUL_NSPACES_ENABLED')) { if (this.env.var('CONSUL_NSPACES_ENABLED')) {
resources = resources.map(item => ({ ...item, Namespace: ns })); resources = resources.map((item) => ({ ...item, Namespace: ns }));
} }
if (this.env.var('CONSUL_PARTITIONS_ENABLED')) { if (this.env.var('CONSUL_PARTITIONS_ENABLED')) {
resources = resources.map(item => ({ ...item, Partition: partition })); resources = resources.map((item) => ({ ...item, Partition: partition }));
} }
return request` return request`
POST /v1/internal/acl/authorize?${{ dc }} POST /v1/internal/acl/authorize?${{ dc }}

View File

@ -138,7 +138,7 @@ export default Component.extend({
// Take the trigger out of the tabbing whilst the menu is open // Take the trigger out of the tabbing whilst the menu is open
this.$trigger.setAttribute('tabindex', '-1'); this.$trigger.setAttribute('tabindex', '-1');
this._listeners.add(this.dom.document(), { this._listeners.add(this.dom.document(), {
keydown: e => { keydown: (e) => {
// Keep focus on the trigger when you close via ESC // Keep focus on the trigger when you close via ESC
if (e.keyCode === ESC) { if (e.keyCode === ESC) {
this.$trigger.focus(); this.$trigger.focus();

View File

@ -1,4 +1,5 @@
export default (submitable, clickable, attribute) => (scope = '.auth-form') => { export default (submitable, clickable, attribute) =>
(scope = '.auth-form') => {
return { return {
scope: scope, scope: scope,
...submitable(), ...submitable(),

View File

@ -24,7 +24,7 @@ export default Component.extend(Slotted, {
init: function () { init: function () {
this._super(...arguments); this._super(...arguments);
this._listeners = this.dom.listeners(); this._listeners = this.dom.listeners();
this.form = this.formContainer.form(this.type); set(this, 'form', this.formContainer.form(this.type));
this.form.clear({ Datacenter: this.dc, Namespace: this.nspace }); this.form.clear({ Datacenter: this.dc, Namespace: this.nspace });
}, },
willDestroyElement: function () { willDestroyElement: function () {
@ -40,7 +40,7 @@ export default Component.extend(Slotted, {
// filter out any items from the available options that have already been // filter out any items from the available options that have already been
// selected/added // selected/added
// TODO: find a proper ember-data diff // TODO: find a proper ember-data diff
options = options.filter(item => !items.findBy('ID', get(item, 'ID'))); options = options.filter((item) => !items.findBy('ID', get(item, 'ID')));
} }
return options; return options;
}), }),

View File

@ -70,7 +70,7 @@ export default Component.extend({
set(this, 'value', $code.firstChild.wholeText); set(this, 'value', $code.firstChild.wholeText);
} }
set(this, 'editor', this.helper.getEditor(this.element)); set(this, 'editor', this.helper.getEditor(this.element));
this.settings.findBySlug('code-editor').then(mode => { this.settings.findBySlug('code-editor').then((mode) => {
const modes = this.modes; const modes = this.modes;
const syntax = this.syntax; const syntax = this.syntax;
if (syntax) { if (syntax) {

View File

@ -17,7 +17,7 @@ export default Component.extend({
}, },
didInsertElement: function () { didInsertElement: function () {
this._listeners.add(this.dom.document(), { this._listeners.add(this.dom.document(), {
click: e => { click: (e) => {
// all route/splitter/resolver components currently // all route/splitter/resolver components currently
// have classes that end in '-card' // have classes that end in '-card'
if (!this.dom.closest('[class$="-card"]', e.target)) { if (!this.dom.closest('[class$="-card"]', e.target)) {
@ -40,8 +40,8 @@ export default Component.extend({
// if we have no routes with a PathPrefix of '/' or one with no definition at all // if we have no routes with a PathPrefix of '/' or one with no definition at all
// then add our own 'default catch all' // then add our own 'default catch all'
if ( if (
!routes.find(item => get(item, 'Definition.Match.HTTP.PathPrefix') === '/') && !routes.find((item) => get(item, 'Definition.Match.HTTP.PathPrefix') === '/') &&
!routes.find(item => typeof item.Definition === 'undefined') !routes.find((item) => typeof item.Definition === 'undefined')
) { ) {
let nextNode; let nextNode;
const resolverID = `resolver:${this.chain.ServiceName}.${this.chain.Namespace}.${this.chain.Partition}.${this.chain.Datacenter}`; const resolverID = `resolver:${this.chain.ServiceName}.${this.chain.Namespace}.${this.chain.Partition}.${this.chain.Datacenter}`;
@ -94,7 +94,7 @@ export default Component.extend({
value.NextItem = nodes[value.NextNode]; value.NextItem = nodes[value.NextNode];
} }
if (typeof value.Splits !== 'undefined') { if (typeof value.Splits !== 'undefined') {
value.Splits.forEach(item => { value.Splits.forEach((item) => {
if (typeof item.NextNode !== 'undefined') { if (typeof item.NextNode !== 'undefined') {
item.NextItem = nodes[item.NextNode]; item.NextItem = nodes[item.NextNode];
} }
@ -114,8 +114,8 @@ export default Component.extend({
}), }),
graph: computed('splitters', 'routes.[]', function () { graph: computed('splitters', 'routes.[]', function () {
const graph = this.dataStructs.graph(); const graph = this.dataStructs.graph();
this.splitters.forEach(item => { this.splitters.forEach((item) => {
item.Splits.forEach(splitter => { item.Splits.forEach((splitter) => {
graph.addLink(item.ID, splitter.NextNode); graph.addLink(item.ID, splitter.NextNode);
}); });
}); });
@ -144,8 +144,8 @@ export default Component.extend({
}); });
}); });
return { return {
nodes: nodes.map(item => `#${CSS.escape(item)}`), nodes: nodes.map((item) => `#${CSS.escape(item)}`),
edges: edges.map(item => `#${CSS.escape(item)}`), edges: edges.map((item) => `#${CSS.escape(item)}`),
}; };
}), }),
actions: { actions: {

View File

@ -1,5 +1,5 @@
const getNodesByType = function (nodes = {}, type) { const getNodesByType = function (nodes = {}, type) {
return Object.values(nodes).filter(item => item.Type === type); return Object.values(nodes).filter((item) => item.Type === type);
}; };
const findResolver = function (resolvers, service, nspace = 'default', partition = 'default', dc) { const findResolver = function (resolvers, service, nspace = 'default', partition = 'default', dc) {
if (typeof resolvers[service] === 'undefined') { if (typeof resolvers[service] === 'undefined') {
@ -18,7 +18,7 @@ export const getAlternateServices = function(targets, a) {
// with dots in the name, but by the time that becomes an issue // with dots in the name, but by the time that becomes an issue
// we might have more data from the endpoint so we don't have to guess // we might have more data from the endpoint so we don't have to guess
// right now the backend also doesn't support dots in service names // right now the backend also doesn't support dots in service names
const [aRev, bRev] = [a, b].map(item => item.split('.').reverse()); const [aRev, bRev] = [a, b].map((item) => item.split('.').reverse());
const types = ['Datacenter', 'Partition', 'Namespace', 'Service', 'Subset']; const types = ['Datacenter', 'Partition', 'Namespace', 'Service', 'Subset'];
return bRev.find(function (item, i) { return bRev.find(function (item, i) {
const res = item !== aRev[i]; const res = item !== aRev[i];
@ -72,7 +72,7 @@ export const getResolvers = function(
const resolvers = {}; const resolvers = {};
// make all our resolver nodes // make all our resolver nodes
Object.values(nodes) Object.values(nodes)
.filter(item => item.Type === 'resolver') .filter((item) => item.Type === 'resolver')
.forEach(function (item) { .forEach(function (item) {
const parts = item.Name.split('.'); const parts = item.Name.split('.');
let subset; let subset;
@ -113,7 +113,7 @@ export const getResolvers = function(
} }
} }
}); });
Object.values(targets).forEach(target => { Object.values(targets).forEach((target) => {
// Failovers don't have a specific node // Failovers don't have a specific node
if (typeof nodes[`resolver:${target.ID}`] !== 'undefined') { if (typeof nodes[`resolver:${target.ID}`] !== 'undefined') {
// We use this to figure out whether this target is a redirect target // We use this to figure out whether this target is a redirect target

View File

@ -1,4 +1,5 @@
export default (collection, text) => (scope = '.consul-health-check-list') => { export default (collection, text) =>
(scope = '.consul-health-check-list') => {
return { return {
scope, scope,
item: collection('li', { item: collection('li', {

View File

@ -192,7 +192,7 @@
<button <button
data-test-create-permission data-test-create-permission
type="button" type="button"
{{on "click" (optional this.modal.open)}} {{on "click" (action this.openModal)}}
> >
Add permission Add permission
</button> </button>
@ -201,7 +201,7 @@
<Consul::Intention::Notice::Permissions /> <Consul::Intention::Notice::Permissions />
<Consul::Intention::Permission::List <Consul::Intention::Permission::List
@items={{item.Permissions}} @items={{item.Permissions}}
@onclick={{queue (action (mut permission)) (action (optional this.modal.open))}} @onclick={{queue (action (mut permission)) (action this.openModal)}}
@ondelete={{action 'delete' 'Permissions' item}} @ondelete={{action 'delete' 'Permissions' item}}
/> />
{{else}} {{else}}

View File

@ -5,6 +5,10 @@ export default Component.extend({
shouldShowPermissionForm: false, shouldShowPermissionForm: false,
openModal() {
this.modal?.open();
},
actions: { actions: {
createNewLabel: function (template, term) { createNewLabel: function (template, term) {
return template.replace(/{{term}}/g, term); return template.replace(/{{term}}/g, term);

View File

@ -79,7 +79,9 @@ export default class ConsulIntentionForm extends Component {
let items = e.data let items = e.data
.uniqBy('Name') .uniqBy('Name')
.toArray() .toArray()
.filter(item => !['connect-proxy', 'mesh-gateway', 'terminating-gateway'].includes(item.Kind)) .filter(
(item) => !['connect-proxy', 'mesh-gateway', 'terminating-gateway'].includes(item.Kind)
)
.sort((a, b) => a.Name.localeCompare(b.Name)); .sort((a, b) => a.Name.localeCompare(b.Name));
items = [{ Name: '*' }].concat(items); items = [{ Name: '*' }].concat(items);
let source = items.findBy('Name', item.SourceName); let source = items.findBy('Name', item.SourceName);

View File

@ -1,9 +1,11 @@
export default (collection, clickable, attribute, isPresent, deletable) => ( export default (collection, clickable, attribute, isPresent, deletable) =>
scope = '.consul-intention-list' (scope = '.consul-intention-list') => {
) => {
const row = { const row = {
source: attribute('data-test-intention-source', '[data-test-intention-source]'), source: attribute('data-test-intention-source', '[data-test-intention-source]'),
destination: attribute('data-test-intention-destination', '[data-test-intention-destination]'), destination: attribute(
'data-test-intention-destination',
'[data-test-intention-destination]'
),
action: attribute('data-test-intention-action', '[data-test-intention-action]'), action: attribute('data-test-intention-action', '[data-test-intention-action]'),
intention: clickable('a'), intention: clickable('a'),
actions: clickable('label'), actions: clickable('label'),

View File

@ -96,7 +96,7 @@ export default Component.extend({
({ key, value }) => key === 'HTTP.PathType' || key === 'HTTP.Path' ({ key, value }) => key === 'HTTP.PathType' || key === 'HTTP.Path'
) !== 'undefined'; ) !== 'undefined';
if (pathChanged) { if (pathChanged) {
this.pathProps.forEach(prop => { this.pathProps.forEach((prop) => {
changeset.set(`HTTP.${prop}`, undefined); changeset.set(`HTTP.${prop}`, undefined);
}); });
if (changeset.HTTP.PathType !== 'NoPath') { if (changeset.HTTP.PathType !== 'NoPath') {

View File

@ -54,7 +54,7 @@ export default Component.extend({
changeset.validate(); changeset.validate();
}, },
submit: function (changeset) { submit: function (changeset) {
this.headerTypes.forEach(prop => { this.headerTypes.forEach((prop) => {
changeset.set(prop, undefined); changeset.set(prop, undefined);
}); });
// Present is a boolean, whereas all other header types have a value // Present is a boolean, whereas all other header types have a value

View File

@ -19,7 +19,7 @@ export default class TomographyGraph extends Component {
get milliseconds() { get milliseconds() {
const distances = this.args.distances || []; const distances = this.args.distances || [];
const max = distances.reduce((prev, d) => Math.max(prev, d.distance), this.max); const max = distances.reduce((prev, d) => Math.max(prev, d.distance), this.max);
return [25, 50, 75, 100].map(item => milliseconds(item, max)); return [25, 50, 75, 100].map((item) => milliseconds(item, max));
} }
get distances() { get distances() {

View File

@ -1,4 +1,5 @@
export default (collection, text) => (scope = '.consul-upstream-instance-list') => { export default (collection, text) =>
(scope = '.consul-upstream-instance-list') => {
return { return {
scope, scope,
item: collection('li', { item: collection('li', {

View File

@ -12,7 +12,13 @@ const typeCast = (attributeInfo, value) => {
const d = attributeInfo.default; const d = attributeInfo.default;
value = value == null ? attributeInfo.default : value; value = value == null ? attributeInfo.default : value;
if (type.indexOf('|') !== -1) { if (type.indexOf('|') !== -1) {
assert(`"${value} is not of type '${type}'"`, type.split('|').map(item => item.replaceAll('"', '').trim()).includes(value)); assert(
`"${value} is not of type '${type}'"`,
type
.split('|')
.map((item) => item.replaceAll('"', '').trim())
.includes(value)
);
type = 'string'; type = 'string';
} }
switch (type) { switch (type) {
@ -33,7 +39,7 @@ const typeCast = (attributeInfo, value) => {
case 'string': case 'string':
return (value || '').toString(); return (value || '').toString();
} }
} };
const attributeChangingElement = (name, Cls = HTMLElement, attributes = {}, cssprops = {}) => { const attributeChangingElement = (name, Cls = HTMLElement, attributes = {}, cssprops = {}) => {
const attrs = Object.keys(attributes); const attrs = Object.keys(attributes);
@ -49,10 +55,7 @@ const attributeChangingElement = (name, Cls = HTMLElement, attributes = {}, cssp
const cssProp = cssprops[`--${name}`]; const cssProp = cssprops[`--${name}`];
if (typeof cssProp !== 'undefined' && cssProp.track === `[${name}]`) { if (typeof cssProp !== 'undefined' && cssProp.track === `[${name}]`) {
this.style.setProperty( this.style.setProperty(`--${name}`, value);
`--${name}`,
value
);
} }
if (typeof super.attributeChangedCallback === 'function') { if (typeof super.attributeChangedCallback === 'function') {
@ -60,23 +63,19 @@ const attributeChangingElement = (name, Cls = HTMLElement, attributes = {}, cssp
} }
this.dispatchEvent( this.dispatchEvent(
new CustomEvent( new CustomEvent(ATTRIBUTE_CHANGE, {
ATTRIBUTE_CHANGE,
{
detail: { detail: {
name: name, name: name,
previousValue: prev, previousValue: prev,
value: value value: value,
} },
} })
)
); );
}
} }
};
customElements.define(name, customClass); customElements.define(name, customClass);
return () => {}; return () => {};
} };
const infoFromArray = (arr, keys) => { const infoFromArray = (arr, keys) => {
return (arr || []).reduce((prev, info) => { return (arr || []).reduce((prev, info) => {
@ -87,18 +86,18 @@ const infoFromArray = (arr, keys) => {
key = i; key = i;
return; return;
} }
obj[item] = info[i] obj[item] = info[i];
}); });
prev[info[key]] = obj; prev[info[key]] = obj;
return prev; return prev;
}, {}); }, {});
} };
const debounceRAF = (cb, prev) => { const debounceRAF = (cb, prev) => {
if (typeof prev !== 'undefined') { if (typeof prev !== 'undefined') {
cancelAnimationFrame(prev); cancelAnimationFrame(prev);
} }
return requestAnimationFrame(cb); return requestAnimationFrame(cb);
} };
const createElementProxy = ($element, component) => { const createElementProxy = ($element, component) => {
return new Proxy($element, { return new Proxy($element, {
get: (target, prop, receiver) => { get: (target, prop, receiver) => {
@ -115,21 +114,18 @@ const createElementProxy = ($element, component) => {
// this.methods.set(prop, method); // this.methods.set(prop, method);
return method; return method;
} }
}
} }
},
}); });
} };
export default class CustomElementComponent extends Component { export default class CustomElementComponent extends Component {
@tracked $element; @tracked $element;
@tracked _attributes = {}; @tracked _attributes = {};
__attributes; __attributes;
_attchange; _attchange;
constructor(owner, args) { constructor(owner, args) {
super(...arguments); super(...arguments);
if (!elements.has(args.element)) { if (!elements.has(args.element)) {
@ -138,7 +134,7 @@ export default class CustomElementComponent extends Component {
args.class, args.class,
infoFromArray(args.attrs, ['_', 'type', 'default', 'description']), infoFromArray(args.attrs, ['_', 'type', 'default', 'description']),
infoFromArray(args.cssprops, ['_', 'type', 'track', 'description']) infoFromArray(args.cssprops, ['_', 'type', 'track', 'description'])
) );
elements.set(args.element, cb); elements.set(args.element, cb);
} }
} }
@ -165,9 +161,9 @@ export default class CustomElementComponent extends Component {
this.$element = $element; this.$element = $element;
this.$element.addEventListener(ATTRIBUTE_CHANGE, this.attributeChange); this.$element.addEventListener(ATTRIBUTE_CHANGE, this.attributeChange);
(this.args.attrs || []).forEach(entry => { (this.args.attrs || []).forEach((entry) => {
const value = $element.getAttribute(entry[0]); const value = $element.getAttribute(entry[0]);
$element.attributeChangedCallback(entry[0], value, value) $element.attributeChangedCallback(entry[0], value, value);
}); });
} }
@ -183,7 +179,7 @@ export default class CustomElementComponent extends Component {
// they all change // they all change
this.__attributes = { this.__attributes = {
...this.__attributes, ...this.__attributes,
[e.detail.name]: e.detail.value [e.detail.name]: e.detail.value,
}; };
this._attchange = debounceRAF(() => { this._attchange = debounceRAF(() => {
// tell glimmer we changed the attrs // tell glimmer we changed the attrs

View File

@ -5,7 +5,7 @@ import Slotted from 'block-slots';
import chart from './chart.xstate'; import chart from './chart.xstate';
export default Component.extend(Slotted, { export default Component.extend(Slotted, {
tagName: '', tagName: '',
onchange: data => data, onchange: (data) => data,
init: function () { init: function () {
this._super(...arguments); this._super(...arguments);
this.chart = chart; this.chart = chart;

View File

@ -36,7 +36,7 @@ export default Component.extend({
id = `active.${id}`; id = `active.${id}`;
} }
return { return {
matches: name => id.indexOf(name) !== -1, matches: (name) => id.indexOf(name) !== -1,
}; };
}), }),
@ -50,7 +50,7 @@ export default Component.extend({
}, },
source: function (cb) { source: function (cb) {
const source = once(cb); const source = once(cb);
const error = err => { const error = (err) => {
set(this, 'instance', undefined); set(this, 'instance', undefined);
try { try {
this.onerror(err); this.onerror(err);
@ -60,7 +60,7 @@ export default Component.extend({
} }
}; };
this._listeners.add(source, { this._listeners.add(source, {
message: e => { message: (e) => {
try { try {
set(this, 'instance', undefined); set(this, 'instance', undefined);
this.onchange(e); this.onchange(e);
@ -68,7 +68,7 @@ export default Component.extend({
error(err); error(err);
} }
}, },
error: e => error(e), error: (e) => error(e),
}); });
return source; return source;
}, },

View File

@ -29,7 +29,7 @@ const replace = function(
}; };
const noop = () => {}; const noop = () => {};
const optional = op => (typeof op === 'function' ? op : noop); const optional = (op) => (typeof op === 'function' ? op : noop);
// possible values for @loading="" // possible values for @loading=""
const LOADING = ['eager', 'lazy']; const LOADING = ['eager', 'lazy'];
@ -74,7 +74,7 @@ export default class DataSource extends Component {
// otherwise its an array from the did-insert-helper // otherwise its an array from the did-insert-helper
if (!Array.isArray($el)) { if (!Array.isArray($el)) {
this._lazyListeners.add( this._lazyListeners.add(
this.dom.isInViewport($el, inViewport => { this.dom.isInViewport($el, (inViewport) => {
this.isIntersecting = inViewport; this.isIntersecting = inViewport;
if (!this.isIntersecting) { if (!this.isIntersecting) {
this.close(); this.close();
@ -130,7 +130,7 @@ export default class DataSource extends Component {
this.dataSource.close(prev, this); this.dataSource.close(prev, this);
} }
); );
const error = err => { const error = (err) => {
try { try {
const error = get(err, 'error.errors.firstObject') || {}; const error = get(err, 'error.errors.firstObject') || {};
if (get(error, 'status') !== '429') { if (get(error, 'status') !== '429') {
@ -143,14 +143,14 @@ export default class DataSource extends Component {
}; };
// set up the listeners (which auto cleanup on component destruction) // set up the listeners (which auto cleanup on component destruction)
const remove = this._listeners.add(this.source, { const remove = this._listeners.add(this.source, {
message: e => { message: (e) => {
try { try {
this.onchange(e); this.onchange(e);
} catch (err) { } catch (err) {
error(err); error(err);
} }
}, },
error: e => { error: (e) => {
error(e); error(e);
}, },
}); });
@ -187,7 +187,7 @@ export default class DataSource extends Component {
this.disconnect(); this.disconnect();
schedule('afterRender', () => { schedule('afterRender', () => {
// TODO: Support lazy data-sources by keeping a reference to $el // TODO: Support lazy data-sources by keeping a reference to $el
runInDebug(_ => runInDebug((_) =>
console.debug( console.debug(
`Invalidation is only supported for non-lazy data sources. If you want to use this you should fixup support for lazy data sources` `Invalidation is only supported for non-lazy data sources. If you want to use this you should fixup support for lazy data sources`
) )

View File

@ -28,8 +28,7 @@ export default Component.extend(Slotted, {
set( set(
this, this,
'error', 'error',
typeof data.error.errors !== 'undefined' ? typeof data.error.errors !== 'undefined' ? data.error.errors.firstObject : data.error
data.error.errors.firstObject : data.error
); );
this.dispatch('ERROR'); this.dispatch('ERROR');
}, },

View File

@ -17,7 +17,7 @@ export default class DisclosureComponent extends Component {
remove(id) { remove(id) {
this.ids = this.ids this.ids = this.ids
.split(' ') .split(' ')
.filter(item => item !== id) .filter((item) => item !== id)
.join(' '); .join(' ');
} }
} }

View File

@ -22,11 +22,11 @@ export default (css) => {
border-radius: var(--decor-radius-999); border-radius: var(--decor-radius-999);
transition-property: transform; transition-property: transform;
transition-timing-function: ease-out; transition-timing-function: ease-out;
transition-duration: .1s; transition-duration: 0.1s;
} }
:host([type='linear']) dl:hover { :host([type='linear']) dl:hover {
transform: scaleY(3); transform: scaleY(3);
box-shadow: var(--decor-elevation-200); box-shadow: var(--decor-elevation-200);
} }
`; `;
} };

View File

@ -1,7 +1,7 @@
const parseFloatWithDefault = (val, d = 0) => { const parseFloatWithDefault = (val, d = 0) => {
const num = parseFloat(val); const num = parseFloat(val);
return isNaN(num) ? d : num; return isNaN(num) ? d : num;
} };
export default (Component) => { export default (Component) => {
return class extends Component { return class extends Component {
@ -12,8 +12,11 @@ export default (Component) => {
let prevSibling = target; let prevSibling = target;
while (prevSibling) { while (prevSibling) {
const nextSibling = prevSibling.nextElementSibling; const nextSibling = prevSibling.nextElementSibling;
const aggregatedPercentage = nextSibling ? parseFloatWithDefault(nextSibling.style.getPropertyValue('--aggregated-percentage')) : 0; const aggregatedPercentage = nextSibling
const perc = parseFloatWithDefault(prevSibling.getAttribute('percentage')) + aggregatedPercentage; ? parseFloatWithDefault(nextSibling.style.getPropertyValue('--aggregated-percentage'))
: 0;
const perc =
parseFloatWithDefault(prevSibling.getAttribute('percentage')) + aggregatedPercentage;
prevSibling.style.setProperty('--aggregated-percentage', perc); prevSibling.style.setProperty('--aggregated-percentage', perc);
prevSibling.setAttribute('aggregated-percentage', perc); prevSibling.setAttribute('aggregated-percentage', perc);
prevSibling = prevSibling.previousElementSibling; prevSibling = prevSibling.previousElementSibling;
@ -22,5 +25,5 @@ export default (Component) => {
} }
} }
} }
} };
} };

View File

@ -18,9 +18,10 @@ export default (css) => {
height: 100%; height: 100%;
transition-timing-function: ease-out; transition-timing-function: ease-out;
transition-duration: .5s; transition-duration: 0.5s;
} }
dt, dd meter { dt,
dd meter {
animation-name: visually-hidden; animation-name: visually-hidden;
animation-fill-mode: forwards; animation-fill-mode: forwards;
animation-play-state: paused; animation-play-state: paused;
@ -49,7 +50,7 @@ export default (css) => {
:host(.type-radial) circle, :host(.type-radial) circle,
:host(.type-circular) circle { :host(.type-circular) circle {
transition-timing-function: ease-out; transition-timing-function: ease-out;
transition-duration: .5s; transition-duration: 0.5s;
pointer-events: stroke; pointer-events: stroke;
transition-property: stroke-dashoffset, stroke-width; transition-property: stroke-dashoffset, stroke-width;
transform: rotate(-90deg); transform: rotate(-90deg);
@ -76,4 +77,4 @@ export default (css) => {
stroke-width: 14; stroke-width: 14;
} }
`; `;
} };

View File

@ -1,4 +1,5 @@
export default present => (scope = '.empty-state') => { export default (present) =>
(scope = '.empty-state') => {
return { return {
scope: scope, scope: scope,
login: present('[data-test-empty-state-login]'), login: present('[data-test-empty-state-login]'),

View File

@ -56,7 +56,7 @@ export default Component.extend({
prev.destroy(); prev.destroy();
} }
}); });
const error = err => { const error = (err) => {
try { try {
const error = get(err, 'error.errors.firstObject'); const error = get(err, 'error.errors.firstObject');
if (get(error || {}, 'status') !== '429') { if (get(error || {}, 'status') !== '429') {
@ -71,7 +71,7 @@ export default Component.extend({
// we only need errors here as this only uses proxies which // we only need errors here as this only uses proxies which
// automatically update their data // automatically update their data
const remove = this._listeners.add(this.source, { const remove = this._listeners.add(this.source, {
error: e => { error: (e) => {
error(e); error(e);
}, },
}); });

View File

@ -21,15 +21,12 @@ export default class Element extends Component {
} }
} }
get prop() { get prop() {
return `${this.args.name return `${this.args.name.toLowerCase().split('.').join('-')}`;
.toLowerCase()
.split('.')
.join('-')}`;
} }
get state() { get state() {
const error = this.touched && this.args.error; const error = this.touched && this.args.error;
return { return {
matches: name => name === 'error' && error, matches: (name) => name === 'error' && error,
}; };
} }

View File

@ -1,4 +1,4 @@
export default triggerable => () => { export default (triggerable) => () => {
return { return {
...{ ...{
search: triggerable('keypress', '[name="s"]'), search: triggerable('keypress', '[name="s"]'),

View File

@ -1,4 +1,4 @@
export default (collection, clickable, attribute, is, authForm, emptyState) => scope => { export default (collection, clickable, attribute, is, authForm, emptyState) => (scope) => {
const page = { const page = {
navigation: [ navigation: [
'services', 'services',

View File

@ -18,8 +18,8 @@ export default class JWTSource extends Component {
// TODO: Could this use once? Double check but I don't think it can // TODO: Could this use once? Double check but I don't think it can
this.source = fromPromise(this.repo.findCodeByURL(this.args.src)); this.source = fromPromise(this.repo.findCodeByURL(this.args.src));
this._listeners.add(this.source, { this._listeners.add(this.source, {
message: e => this.onchange(e), message: (e) => this.onchange(e),
error: e => this.onerror(e), error: (e) => this.onerror(e),
}); });
} }

View File

@ -13,12 +13,12 @@ export default Component.extend(Slotted, {
connect: function ($el) { connect: function ($el) {
this.dialog = new A11yDialog($el); this.dialog = new A11yDialog($el);
this.dialog.on('hide', () => { this.dialog.on('hide', () => {
schedule('afterRender', _ => set(this, 'isOpen', false)); schedule('afterRender', (_) => set(this, 'isOpen', false));
this.onclose({ target: $el }) this.onclose({ target: $el });
}); });
this.dialog.on('show', () => { this.dialog.on('show', () => {
set(this, 'isOpen', true) set(this, 'isOpen', true);
this.onopen({ target: $el }) this.onopen({ target: $el });
}); });
if (this.open) { if (this.open) {
this.actions.open.apply(this, []); this.actions.open.apply(this, []);

View File

@ -1,9 +1,9 @@
import Component from '@glimmer/component'; import Component from '@glimmer/component';
import { action } from '@ember/object'; import { action } from '@ember/object';
import { tracked } from '@glimmer/tracking'; import { tracked } from '@glimmer/tracking';
import { scheduleOnce } from '@ember/runloop';
export default class PagedCollectionComponent extends Component { export default class PagedCollectionComponent extends Component {
@tracked $pane; @tracked $pane;
@tracked $viewport; @tracked $viewport;
@ -25,7 +25,7 @@ export default class PagedCollectionComponent extends Component {
get perPage() { get perPage() {
switch (this.type) { switch (this.type) {
case 'virtual-scroll': case 'virtual-scroll':
return this.visibleItems + (this.overflow * 2); return this.visibleItems + this.overflow * 2;
case 'index': case 'index':
return parseInt(this.args.perPage); return parseInt(this.args.perPage);
} }
@ -93,7 +93,8 @@ export default class PagedCollectionComponent extends Component {
@action @action
setViewport($viewport) { setViewport($viewport) {
this.$viewport = $viewport === 'html' ? [...document.getElementsByTagName('html')][0] : $viewport; this.$viewport =
$viewport === 'html' ? [...document.getElementsByTagName('html')][0] : $viewport;
this.$viewport.addEventListener('scroll', this.scroll); this.$viewport.addEventListener('scroll', this.scroll);
if ($viewport === 'html') { if ($viewport === 'html') {
this.$viewport.addEventListener('resize', this.resize); this.$viewport.addEventListener('resize', this.resize);
@ -111,7 +112,12 @@ export default class PagedCollectionComponent extends Component {
} }
@action setMaxHeight(str) { @action setMaxHeight(str) {
scheduleOnce('actions', this, '_setMaxHeight');
}
@action _setMaxHeight(str) {
const maxHeight = parseFloat(str); const maxHeight = parseFloat(str);
if (!isNaN(maxHeight)) { if (!isNaN(maxHeight)) {
this._type = 'virtual-scroll'; this._type = 'virtual-scroll';
} }

View File

@ -21,7 +21,7 @@ const BADGE_LOOKUP = {
tooltip: 'Someone in the other peer may have deleted this peering connection.', tooltip: 'Someone in the other peer may have deleted this peering connection.',
}, },
UNDEFINED: { UNDEFINED: {
tooltip: '' tooltip: '',
}, },
}; };
export default class PeeringsBadge extends Component { export default class PeeringsBadge extends Component {

View File

@ -1,6 +1,5 @@
export default (submitable, cancelable, radiogroup, text) => ( export default (submitable, cancelable, radiogroup, text) =>
scope = '[data-test-policy-form]' (scope = '[data-test-policy-form]') => {
) => {
return { return {
// this should probably be settable // this should probably be settable
resetScope: true, resetScope: true,

View File

@ -20,7 +20,7 @@
<label <label
class="type-dialog" class="type-dialog"
data-test-policy-create data-test-policy-create
{{on "click" (optional this.modal.open)}} {{on "click" (action this.openModal)}}
> >
<span>Create new policy</span> <span>Create new policy</span>
</label> </label>

View File

@ -17,7 +17,7 @@ export default ChildSelectorComponent.extend({
const source = this.source; const source = this.source;
if (source) { if (source) {
this._listeners.add(source, { this._listeners.add(source, {
save: e => { save: (e) => {
this.save.perform(...e.data); this.save.perform(...e.data);
}, },
}); });
@ -57,6 +57,13 @@ export default ChildSelectorComponent.extend({
throw err; throw err;
} }
}, },
openModal: function () {
const { modal } = this;
if (modal) {
modal.open();
}
},
actions: { actions: {
open: function (e) { open: function (e) {
this.refreshCodeEditor(e, e.target.parentElement); this.refreshCodeEditor(e, e.target.parentElement);

View File

@ -1,7 +1,5 @@
export default (clickable, deletable, collection, alias, policyForm) => ( export default (clickable, deletable, collection, alias, policyForm) =>
scope = '#policies', (scope = '#policies', createSelector = '[data-test-policy-create]') => {
createSelector = '[data-test-policy-create]'
) => {
return { return {
scope: scope, scope: scope,
create: clickable(createSelector), create: clickable(createSelector),

View File

@ -25,13 +25,13 @@ export default Component.extend(Slotted, {
return e; return e;
} }
[...this._options] [...this._options]
.filter(item => item !== option) .filter((item) => item !== option)
.forEach(item => { .forEach((item) => {
item.selected = false; item.selected = false;
}); });
} else { } else {
if (option.selected && this.required) { if (option.selected && this.required) {
const other = [...this._options].find(item => item !== option && item.selected); const other = [...this._options].find((item) => item !== option && item.selected);
if (!other) { if (!other) {
return e; return e;
} }
@ -40,11 +40,11 @@ export default Component.extend(Slotted, {
option.selected = !option.selected; option.selected = !option.selected;
this.onchange( this.onchange(
this.dom.setEventTargetProperties(e, { this.dom.setEventTargetProperties(e, {
selected: target => option.args.value, selected: (target) => option.args.value,
selectedItems: target => { selectedItems: (target) => {
return [...this._options] return [...this._options]
.filter(item => item.selected) .filter((item) => item.selected)
.map(item => item.args.value) .map((item) => item.args.value)
.join(','); .join(',');
}, },
}) })

View File

@ -1,4 +1,5 @@
export default (clickable, collection) => (scope = '.popover-select') => { export default (clickable, collection) =>
(scope = '.popover-select') => {
return { return {
scope: scope, scope: scope,
selected: clickable('button'), selected: clickable('button'),

View File

@ -1,6 +1,6 @@
import { clickable, isPresent } from 'ember-cli-page-object'; import { clickable, isPresent } from 'ember-cli-page-object';
export default options => { export default (options) => {
return { return {
present: isPresent('.ember-power-select-trigger'), present: isPresent('.ember-power-select-trigger'),
click: clickable('.ember-power-select-trigger'), click: clickable('.ember-power-select-trigger'),

View File

@ -18,7 +18,7 @@ export default Component.extend({
}, },
change: function (e) { change: function (e) {
this.onchange( this.onchange(
this.dom.setEventTargetProperty(e, 'value', value => (value === '' ? undefined : value)) this.dom.setEventTargetProperty(e, 'value', (value) => (value === '' ? undefined : value))
); );
}, },
}, },

View File

@ -17,7 +17,7 @@ export default ChildSelectorComponent.extend({
policy: alias('policyForm.data'), policy: alias('policyForm.data'),
init: function () { init: function () {
this._super(...arguments); this._super(...arguments);
this.policyForm = this.formContainer.form('policy'); set(this, 'policyForm', this.formContainer.form('policy'));
this.source = new EventSource(); this.source = new EventSource();
}, },
actions: { actions: {

View File

@ -1,16 +1,14 @@
export default (clickable, deletable, collection, alias, roleForm) => (scope = '#roles') => { export default (clickable, deletable, collection, alias, roleForm) =>
(scope = '#roles') => {
return { return {
scope: scope, scope: scope,
create: clickable('[data-test-role-create]'), create: clickable('[data-test-role-create]'),
form: roleForm(), form: roleForm(),
roles: alias('selectedOptions'), roles: alias('selectedOptions'),
selectedOptions: collection( selectedOptions: collection('[data-test-roles] [data-test-tabular-row]', {
'[data-test-roles] [data-test-tabular-row]',
{
actions: clickable('label > button'), actions: clickable('label > button'),
delete: clickable('[data-test-delete]'), delete: clickable('[data-test-delete]'),
confirmDelete: clickable('.informed-action button'), confirmDelete: clickable('.informed-action button'),
} }),
),
}; };
}; };

View File

@ -14,7 +14,7 @@ export default class RouteComponent extends Component {
constructor() { constructor() {
super(...arguments); super(...arguments);
this.intlKey = this.encoder.createRegExpEncoder(templateRe, _ => _); this.intlKey = this.encoder.createRegExpEncoder(templateRe, (_) => _);
} }
get params() { get params() {
@ -27,8 +27,11 @@ export default class RouteComponent extends Component {
} }
if (this.args.name) { if (this.args.name) {
const outlet = this.routlet.outletFor(this.args.name); const outlet = this.routlet.outletFor(this.args.name);
if (outlet) {
return this.routlet.modelFor(outlet.name); return this.routlet.modelFor(outlet.name);
} }
}
return undefined; return undefined;
} }

View File

@ -1,5 +1,5 @@
export const diff = (a, b) => { export const diff = (a, b) => {
return a.filter(item => !b.includes(item)); return a.filter((item) => !b.includes(item));
}; };
/** /**
* filters accepts the args.filter @attribute which is shaped like * filters accepts the args.filter @attribute which is shaped like
@ -11,7 +11,7 @@ export const diff = (a, b) => {
* There is more explanation in the unit tests for this function so thats worthwhile * There is more explanation in the unit tests for this function so thats worthwhile
* checking if you are in amongst this * checking if you are in amongst this
*/ */
export const filters = filters => { export const filters = (filters) => {
return Object.entries(filters) return Object.entries(filters)
.filter(([key, value]) => { .filter(([key, value]) => {
if (key === 'searchproperty') { if (key === 'searchproperty') {
@ -21,7 +21,7 @@ export const filters = filters => {
}) })
.reduce((prev, [key, value]) => { .reduce((prev, [key, value]) => {
return prev.concat( return prev.concat(
value.value.map(item => { value.value.map((item) => {
const obj = { const obj = {
key: key, key: key,
value: item, value: item,

View File

@ -3,12 +3,10 @@ import { action } from '@ember/object';
import { tracked } from '@glimmer/tracking'; import { tracked } from '@glimmer/tracking';
export default class ShadowHostComponent extends Component { export default class ShadowHostComponent extends Component {
@tracked shadowRoot; @tracked shadowRoot;
@action @action
attachShadow($element) { attachShadow($element) {
this.shadowRoot = $element.attachShadow({ mode: 'open' }); this.shadowRoot = $element.attachShadow({ mode: 'open' });
} }
} }

View File

@ -19,11 +19,11 @@ export default Component.extend({
this.src.initial = this.initial; this.src.initial = this.initial;
} }
this.machine = this.chart.interpret(this.src, { this.machine = this.chart.interpret(this.src, {
onTransition: state => { onTransition: (state) => {
const e = new CustomEvent('transition', { detail: state }); const e = new CustomEvent('transition', { detail: state });
this.ontransition(e); this.ontransition(e);
if (!e.defaultPrevented) { if (!e.defaultPrevented) {
state.actions.forEach(item => { state.actions.forEach((item) => {
const action = this._actions[item.type]; const action = this._actions[item.type];
if (typeof action === 'function') { if (typeof action === 'function') {
this._actions[item.type](item.type, state.context, state.event); this._actions[item.type](item.type, state.context, state.event);

View File

@ -1,4 +1,3 @@
import Component from '../state-chart/index'; import Component from '../state-chart/index';
export default Component.extend({}); export default Component.extend({});

View File

@ -13,8 +13,9 @@ export default class State extends Component {
if (typeof state === 'undefined') { if (typeof state === 'undefined') {
return; return;
} }
this.render = typeof matches !== 'undefined' ? this.render =
this.state.matches(state, matches) : typeof matches !== 'undefined'
!this.state.matches(state, notMatches); ? this.state.matches(state, matches)
: !this.state.matches(state, notMatches);
} }
} }

View File

@ -31,16 +31,10 @@ as |select name|}}
> >
<Action <Action
{{on 'click' {{on 'click'
(if (not-eq @onclick undefined) (fn this.onClick (uppercase item.label))
(fn @onclick (uppercase item.label))
(noop)
)
}} }}
{{on 'click' {{on 'click'
(if @onTabClicked (fn this.onTabClicked item)
(fn @onTabClicked item)
(noop)
)
}} }}
@href={{item.href}} @href={{item.href}}
> >

View File

@ -1,3 +1,12 @@
import Component from '@glimmer/component'; import Component from '@glimmer/component';
export default class TabNav extends Component {} function noop() {}
export default class TabNav extends Component {
get onClick() {
return this.args.onclick || noop;
}
get onTabClicked() {
return this.args.onTabClicked || noop;
}
}

View File

@ -28,7 +28,7 @@ export default Component.extend({
addClickOutsideListener: function () { addClickOutsideListener: function () {
// default onblur event // default onblur event
this._listeners.remove(); this._listeners.remove();
this._listeners.add(this.dom.document(), 'click', e => { this._listeners.add(this.dom.document(), 'click', (e) => {
if (this.dom.isOutside(this.label, e.target)) { if (this.dom.isOutside(this.label, e.target)) {
if (this.dom.isOutside(this.label.nextElementSibling, e.target)) { if (this.dom.isOutside(this.label.nextElementSibling, e.target)) {
if (this.input.checked) { if (this.input.checked) {

View File

@ -43,5 +43,4 @@ export default class TokenSource extends Component {
this.args.onchange(e); this.args.onchange(e);
} }
} }
} }

View File

@ -16,7 +16,7 @@ export default class TopoloyMetricsDownLines extends Component {
const view = this.args.view; const view = this.args.view;
const lines = [...document.querySelectorAll('#downstream-lines path')]; const lines = [...document.querySelectorAll('#downstream-lines path')];
this.iconPositions = lines.map(item => { this.iconPositions = lines.map((item) => {
const pathLen = parseFloat(item.getTotalLength()); const pathLen = parseFloat(item.getTotalLength());
const thirdLen = item.getPointAtLength(Math.ceil(pathLen / 3)); const thirdLen = item.getPointAtLength(Math.ceil(pathLen / 3));

View File

@ -24,7 +24,7 @@ export default class TopologyMetrics extends Component {
}; };
return items return items
.map(item => { .map((item) => {
const dimensions = item.getBoundingClientRect(); const dimensions = item.getBoundingClientRect();
const src = { const src = {
x: dimensions.x + dimensions.width, x: dimensions.x + dimensions.width,
@ -51,7 +51,7 @@ export default class TopologyMetrics extends Component {
}; };
return items return items
.map(item => { .map((item) => {
const dimensions = item.getBoundingClientRect(); const dimensions = item.getBoundingClientRect();
const dest = { const dest = {
x: dimensions.x - dimensions.width - 25, x: dimensions.x - dimensions.width - 25,
@ -104,7 +104,7 @@ export default class TopologyMetrics extends Component {
get upstreams() { get upstreams() {
const upstreams = get(this.args.topology, 'Upstreams') || []; const upstreams = get(this.args.topology, 'Upstreams') || [];
upstreams.forEach(u => { upstreams.forEach((u) => {
u.PeerOrDatacenter = u.PeerName || u.Datacenter; u.PeerOrDatacenter = u.PeerName || u.Datacenter;
}); });
const items = [...upstreams]; const items = [...upstreams];

View File

@ -56,7 +56,7 @@ export default Component.extend({
let series = maybeData.data || []; let series = maybeData.data || [];
let labels = maybeData.labels || {}; let labels = maybeData.labels || {};
let unitSuffix = maybeData.unitSuffix || ''; let unitSuffix = maybeData.unitSuffix || '';
let keys = Object.keys(labels).filter(l => l != 'Total'); let keys = Object.keys(labels).filter((l) => l != 'Total');
if (series.length == 0 || keys.length == 0) { if (series.length == 0 || keys.length == 0) {
// Put the graph in an error state that might get fixed if metrics show up // Put the graph in an error state that might get fixed if metrics show up
@ -67,9 +67,7 @@ export default Component.extend({
set(this, 'empty', false); set(this, 'empty', false);
} }
let st = stack() let st = stack().keys(keys).order(stackOrderReverse);
.keys(keys)
.order(stackOrderReverse);
let stackData = st(series); let stackData = st(series);
@ -77,16 +75,16 @@ export default Component.extend({
// stackData contains this but I didn't find reliable documentation on // stackData contains this but I didn't find reliable documentation on
// whether we can rely on the highest stacked area to always be first/last // whether we can rely on the highest stacked area to always be first/last
// in array etc. so this is simpler. // in array etc. so this is simpler.
let summed = series.map(d => { let summed = series.map((d) => {
let sum = 0; let sum = 0;
keys.forEach(l => { keys.forEach((l) => {
sum = sum + d[l]; sum = sum + d[l];
}); });
return sum; return sum;
}); });
let x = scaleTime() let x = scaleTime()
.domain(extent(series, d => d.time)) .domain(extent(series, (d) => d.time))
.range([0, w]); .range([0, w]);
let y = scaleLinear() let y = scaleLinear()
@ -94,9 +92,9 @@ export default Component.extend({
.range([h, 0]); .range([h, 0]);
let a = area() let a = area()
.x(d => x(d.data.time)) .x((d) => x(d.data.time))
.y1(d => y(d[0])) .y1((d) => y(d[0]))
.y0(d => y(d[1])); .y0((d) => y(d[1]));
// Use the grey/red we prefer by default but have more colors available in // Use the grey/red we prefer by default but have more colors available in
// case user adds extra series with a custom provider. // case user adds extra series with a custom provider.
@ -136,11 +134,7 @@ export default Component.extend({
.attr('class', 'sparkline-tt-legend-color') .attr('class', 'sparkline-tt-legend-color')
.style('background-color', color(k)); .style('background-color', color(k));
legend legend.append('span').text(k).append('span').attr('class', 'sparkline-tt-legend-value');
.append('span')
.text(k)
.append('span')
.attr('class', 'sparkline-tt-legend-value');
} }
let tipVals = tooltip.selectAll('.sparkline-tt-legend-value'); let tipVals = tooltip.selectAll('.sparkline-tt-legend-value');

View File

@ -17,7 +17,7 @@ export default class TopologyMetricsUpLines extends Component {
const view = this.args.view; const view = this.args.view;
const lines = [...document.querySelectorAll('#upstream-lines path')]; const lines = [...document.querySelectorAll('#upstream-lines path')];
this.iconPositions = lines.map(item => { this.iconPositions = lines.map((item) => {
const pathLen = parseFloat(item.getTotalLength()); const pathLen = parseFloat(item.getTotalLength());
const partLen = item.getPointAtLength(Math.ceil(pathLen * 0.666)); const partLen = item.getPointAtLength(Math.ceil(pathLen * 0.666));
return { return {

View File

@ -8,7 +8,7 @@ export default class PeeredResourceController extends Controller {
const { searchProperties } = this; const { searchProperties } = this;
if (!this.abilities.can('use peers')) { if (!this.abilities.can('use peers')) {
return searchProperties.filter(propertyName => propertyName !== 'PeerName'); return searchProperties.filter((propertyName) => propertyName !== 'PeerName');
} else { } else {
return searchProperties; return searchProperties;
} }

View File

@ -52,7 +52,7 @@ export default class ApplicationController extends Controller {
// thats ok as we then transition to the actual route you were trying // thats ok as we then transition to the actual route you were trying
// to get to originally anyway // to get to originally anyway
}) })
.then(res => { .then((res) => {
// Use transitionable if we need to change a section of the URL // Use transitionable if we need to change a section of the URL
// or routeName and currentRouteName aren't equal (i.e. error page) // or routeName and currentRouteName aren't equal (i.e. error page)
if ( if (

View File

@ -3,18 +3,18 @@ import wayfarer from 'wayfarer';
const router = wayfarer(); const router = wayfarer();
const routes = {}; const routes = {};
export default path => (target, propertyKey, desc) => { export default (path) => (target, propertyKey, desc) => {
runInDebug(() => { runInDebug(() => {
routes[path] = { cls: target, method: propertyKey }; routes[path] = { cls: target, method: propertyKey };
}); });
router.on(path, function (params, owner, request) { router.on(path, function (params, owner, request) {
const container = owner.lookup('service:container'); const container = owner.lookup('service:container');
const instance = container.get(target); const instance = container.get(target);
return configuration => desc.value.apply(instance, [params, configuration, request]); return (configuration) => desc.value.apply(instance, [params, configuration, request]);
}); });
return desc; return desc;
}; };
export const match = path => { export const match = (path) => {
return router.match(path); return router.match(path);
}; };
@ -29,13 +29,10 @@ runInDebug(() => {
<pre> <pre>
${Object.entries(routes) ${Object.entries(routes)
.map(([key, value]) => { .map(([key, value]) => {
let cls = container let cls = container.keyForClass(value.cls).split('/').pop();
.keyForClass(value.cls)
.split('/')
.pop();
cls = cls cls = cls
.split('-') .split('-')
.map(item => `${item[0].toUpperCase()}${item.substr(1)}`) .map((item) => `${item[0].toUpperCase()}${item.substr(1)}`)
.join(''); .join('');
return `${key} return `${key}
${cls}Repository.${value.method}(params) ${cls}Repository.${value.method}(params)

View File

@ -2,7 +2,5 @@ import validations from 'consul-ui/validations/role';
import builderFactory from 'consul-ui/utils/form/builder'; import builderFactory from 'consul-ui/utils/form/builder';
const builder = builderFactory(); const builder = builderFactory();
export default function (container, name = 'role', v = validations, form = builder) { export default function (container, name = 'role', v = validations, form = builder) {
return form(name, {}) return form(name, {}).setValidators(v).add(container.form('policy'));
.setValidators(v)
.add(container.form('policy'));
} }

View File

@ -2,8 +2,5 @@ import validations from 'consul-ui/validations/token';
import builderFactory from 'consul-ui/utils/form/builder'; import builderFactory from 'consul-ui/utils/form/builder';
const builder = builderFactory(); const builder = builderFactory();
export default function (container, name = '', v = validations, form = builder) { export default function (container, name = '', v = validations, form = builder) {
return form(name, {}) return form(name, {}).setValidators(v).add(container.form('policy')).add(container.form('role'));
.setValidators(v)
.add(container.form('policy'))
.add(container.form('role'));
} }

View File

@ -1,9 +0,0 @@
import Helper from 'ember-can/helpers/can';
export default class extends Helper {
_addAbilityObserver(ability, propertyName) {
if(!this.isDestroyed && !this.isDestroying) {
super._addAbilityObserver(...arguments);
}
}
}

View File

@ -7,11 +7,11 @@ import { helper } from '@ember/component/helper';
* @typedef {([string, boolean] | [string])} classInfo * @typedef {([string, boolean] | [string])} classInfo
* @param {(classInfo | string)[]} entries - An array of 'entry-like' arrays of `classInfo`s to map * @param {(classInfo | string)[]} entries - An array of 'entry-like' arrays of `classInfo`s to map
*/ */
const classMap = entries => { const classMap = (entries) => {
const str = entries const str = entries
.filter(Boolean) .filter(Boolean)
.filter(entry => (typeof entry === 'string' ? true : entry[entry.length - 1])) .filter((entry) => (typeof entry === 'string' ? true : entry[entry.length - 1]))
.map(entry => (typeof entry === 'string' ? entry : entry[0])) .map((entry) => (typeof entry === 'string' ? entry : entry[0]))
.join(' '); .join(' ');
return str.length > 0 ? str : undefined; return str.length > 0 ? str : undefined;
}; };

View File

@ -8,9 +8,9 @@ import { CSSResult } from '@lit/reactive-element';
* @typedef {([CSSResult, boolean] | [CSSResult])} cssInfo * @typedef {([CSSResult, boolean] | [CSSResult])} cssInfo
* @param {(cssInfo | string)[]} entries - An array of 'entry-like' arrays of `cssInfo`s to map * @param {(cssInfo | string)[]} entries - An array of 'entry-like' arrays of `cssInfo`s to map
*/ */
const cssMap = entries => { const cssMap = (entries) => {
return entries return entries
.filter(entry => (entry instanceof CSSResult ? true : entry[entry.length - 1])) .filter((entry) => (entry instanceof CSSResult ? true : entry[entry.length - 1]))
.map(entry => (entry instanceof CSSResult ? entry : entry[0])) .map((entry) => (entry instanceof CSSResult ? entry : entry[0]));
}; };
export default helper(cssMap); export default helper(cssMap);

View File

@ -30,7 +30,7 @@ export default class DocumentAttrsHelper extends Helper {
let map = attrs.get(key); let map = attrs.get(key);
if (typeof map !== 'undefined') { if (typeof map !== 'undefined') {
[...new Set(value.split(' '))].map(val => map.remove(val, this)); [...new Set(value.split(' '))].map((val) => map.remove(val, this));
} }
}); });
} }
@ -43,7 +43,7 @@ export default class DocumentAttrsHelper extends Helper {
values = new MultiMap(Set); values = new MultiMap(Set);
attrs.set(key, values); attrs.set(key, values);
} }
[...new Set(value.split(' '))].map(val => { [...new Set(value.split(' '))].map((val) => {
if (values.count(val) === 0) { if (values.count(val) === 0) {
values.set(val, null); values.set(val, null);
} }
@ -60,7 +60,7 @@ export default class DocumentAttrsHelper extends Helper {
} }
// go through our list of properties and synchronize the DOM // go through our list of properties and synchronize the DOM
// properties with our properties // properties with our properties
[...values.keys()].forEach(value => { [...values.keys()].forEach((value) => {
if (values.count(value) === 1) { if (values.count(value) === 1) {
switch (type) { switch (type) {
case 'class': case 'class':

View File

@ -2,7 +2,7 @@ import Helper from '@ember/component/helper';
export default class DomPosition extends Helper { export default class DomPosition extends Helper {
compute([target], { from, offset = false }) { compute([target], { from, offset = false }) {
return e => { return (e) => {
if (typeof target === 'function') { if (typeof target === 'function') {
let rect; let rect;
let $el; let $el;
@ -29,11 +29,9 @@ export default class DomPosition extends Helper {
// provide and easy way to map coords to CSS props // provide and easy way to map coords to CSS props
const $el = e.target; const $el = e.target;
const rect = $el.getBoundingClientRect(); const rect = $el.getBoundingClientRect();
target.forEach( target.forEach(([prop, value]) => {
([prop, value]) => {
$el.style[value] = `${rect[prop]}px`; $el.style[value] = `${rect[prop]}px`;
} });
);
} }
}; };
} }

View File

@ -3,6 +3,6 @@ import { helper } from '@ember/component/helper';
export default helper(function flattenProperty([obj, prop], hash) { export default helper(function flattenProperty([obj, prop], hash) {
const pages = hash.pages || []; const pages = hash.pages || [];
pages.push(...obj.pages); pages.push(...obj.pages);
obj.children.forEach(child => flattenProperty([child], { pages: pages })); obj.children.forEach((child) => flattenProperty([child], { pages: pages }));
return pages; return pages;
}); });

View File

@ -34,10 +34,7 @@ export const hrefTo = function(container, params, hash = {}) {
// if the routeName is a wildcard (*) route url encode all of the params // if the routeName is a wildcard (*) route url encode all of the params
if (isWildcard(routeName)) { if (isWildcard(routeName)) {
_params = _params.map((item, i) => { _params = _params.map((item, i) => {
return item return item.split('/').map(encodeURIComponent).join('/');
.split('/')
.map(encodeURIComponent)
.join('/');
}); });
} }
return location.hrefTo(routeName, _params, _hash); return location.hrefTo(routeName, _params, _hash);

View File

@ -1034,12 +1034,13 @@ export default helper(function([lib], hash) {
'zoom-in-16.svg', 'zoom-in-16.svg',
'zoom-in-24.svg', 'zoom-in-24.svg',
'zoom-out-16.svg', 'zoom-out-16.svg',
'zoom-out-24.svg' 'zoom-out-24.svg',
]
].filter(item => { .filter((item) => {
const sized = item.endsWith('-16.svg') || item.endsWith('-24.svg'); const sized = item.endsWith('-16.svg') || item.endsWith('-24.svg');
return lib === 'structure' ? !sized : sized; return lib === 'structure' ? !sized : sized;
}).map(item => { })
.map((item) => {
const temp = item.split('.'); const temp = item.split('.');
temp.pop(); temp.pop();
const name = temp.join('.'); const name = temp.join('.');
@ -1051,7 +1052,7 @@ export default helper(function([lib], hash) {
} }
return { return {
placeholder: placeholder, placeholder: placeholder,
name: name name: name,
}; };
}) });
}); });

View File

@ -12,11 +12,8 @@ export const is = (helper, [abilityString, model], properties) => {
propertyName = camelize(`is-${propertyName}`); propertyName = camelize(`is-${propertyName}`);
} }
helper._removeAbilityObserver();
helper._addAbilityObserver(ability, propertyName);
return get(ability, propertyName); return get(ability, propertyName);
} };
export default class extends Helper { export default class extends Helper {
compute([abilityString, model], properties) { compute([abilityString, model], properties) {
return is(this, [abilityString, model], properties); return is(this, [abilityString, model], properties);

View File

@ -4,6 +4,6 @@ export default helper(function(args, hash) {
try { try {
return JSON.stringify(...args); return JSON.stringify(...args);
} catch (e) { } catch (e) {
return args[0].map(item => JSON.stringify(item, args[1], args[2])); return args[0].map((item) => JSON.stringify(item, args[1], args[2]));
} }
}); });

View File

@ -2,8 +2,5 @@ import { helper } from '@ember/component/helper';
import mergeChecks from 'consul-ui/utils/merge-checks'; import mergeChecks from 'consul-ui/utils/merge-checks';
export default helper(function ([checks, exposed], hash) { export default helper(function ([checks, exposed], hash) {
return mergeChecks( return mergeChecks(checks, exposed);
checks,
exposed
);
}); });

View File

@ -1,7 +1,7 @@
import { helper } from '@ember/component/helper'; import { helper } from '@ember/component/helper';
export default helper(function ([of, num], hash) { export default helper(function ([of, num], hash) {
const perc = (of / num * 100); const perc = (of / num) * 100;
if (isNaN(perc)) { if (isNaN(perc)) {
return 0; return 0;
} }

View File

@ -4,7 +4,6 @@ import require from 'require';
import { css } from '@lit/reactive-element'; import { css } from '@lit/reactive-element';
import resolve from 'consul-ui/utils/path/resolve'; import resolve from 'consul-ui/utils/path/resolve';
const appName = 'consul-ui'; const appName = 'consul-ui';
const container = new Map(); const container = new Map();
@ -22,7 +21,7 @@ export default helper(([path = ''], options) => {
if (require.has(fullPath)) { if (require.has(fullPath)) {
module = require(fullPath)[options.export || 'default']; module = require(fullPath)[options.export || 'default'];
} else { } else {
throw new Error(`Unable to resolve '${fullPath}' does the file exist?`) throw new Error(`Unable to resolve '${fullPath}' does the file exist?`);
} }
switch (true) { switch (true) {

View File

@ -2,7 +2,7 @@ import { helper } from '@ember/component/helper';
export default helper(function routeMatch([item], hash) { export default helper(function routeMatch([item], hash) {
const prop = ['Present', 'Exact', 'Prefix', 'Suffix', 'Regex'].find( const prop = ['Present', 'Exact', 'Prefix', 'Suffix', 'Regex'].find(
prop => typeof item[prop] !== 'undefined' (prop) => typeof item[prop] !== 'undefined'
); );
switch (prop) { switch (prop) {

View File

@ -12,7 +12,7 @@ const curve = function() {
// `Q|C x y, x y, x y` etc // `Q|C x y, x y, x y` etc
return `${arguments.length > 2 ? `C` : `Q`} ${args return `${arguments.length > 2 ? `C` : `Q`} ${args
.concat(args.shift()) .concat(args.shift())
.map(p => Object.values(p).join(' ')) .map((p) => Object.values(p).join(' '))
.join(',')}`; .join(',')}`;
}; };
const move = function (d) { const move = function (d) {

View File

@ -5,7 +5,7 @@ import merge from 'deepmerge';
const doc = document; const doc = document;
export const services = merge.all( export const services = merge.all(
[...doc.querySelectorAll(`script[data-services]`)].map($item => [...doc.querySelectorAll(`script[data-services]`)].map(($item) =>
JSON.parse($item.dataset[`services`]) JSON.parse($item.dataset[`services`])
) )
); );
@ -42,10 +42,10 @@ export default {
let repositories = container let repositories = container
.get('container-debug-adapter:main') .get('container-debug-adapter:main')
.catalogEntriesByType('service') .catalogEntriesByType('service')
.filter(item => item.startsWith('repository/') || item === 'ui-config'); .filter((item) => item.startsWith('repository/') || item === 'ui-config');
// during testing we get -test files in here, filter those out but only in debug envs // during testing we get -test files in here, filter those out but only in debug envs
runInDebug(() => (repositories = repositories.filter(item => !item.endsWith('-test')))); runInDebug(() => (repositories = repositories.filter((item) => !item.endsWith('-test'))));
// 'service' service is not returned by catalogEntriesByType, possibly // 'service' service is not returned by catalogEntriesByType, possibly
// related to pods and the service being called 'service': // related to pods and the service being called 'service':
@ -53,7 +53,7 @@ export default {
// so push it on the end // so push it on the end
repositories.push('repository/service'); repositories.push('repository/service');
// //
repositories.forEach(item => { repositories.forEach((item) => {
const key = `service:${item}`; const key = `service:${item}`;
container.set(key, container.resolveRegistration(key)); container.set(key, container.resolveRegistration(key));
}); });

View File

@ -128,7 +128,7 @@ export default {
const dom = container.lookup('service:dom'); const dom = container.lookup('service:dom');
const doc = dom.document(); const doc = dom.document();
const listener = e => { const listener = (e) => {
const link = e.target.tagName === 'A' ? e.target : closestLink(e.target); const link = e.target.tagName === 'A' ? e.target : closestLink(e.target);
if (link) { if (link) {
const hrefTo = new HrefTo(container, link); const hrefTo = new HrefTo(container, link);

View File

@ -33,11 +33,11 @@ export default class FSMWithOptionalTestLocation extends FSMWithOptionalLocation
// taken from emberjs/application/instance:visit but cleaned up a little // taken from emberjs/application/instance:visit but cleaned up a little
// https://github.com/emberjs/ember.js/blob/21bd70c773dcc4bfe4883d7943e8a68d203b5bad/packages/%40ember/application/instance.js#L236-L277 // https://github.com/emberjs/ember.js/blob/21bd70c773dcc4bfe4883d7943e8a68d203b5bad/packages/%40ember/application/instance.js#L236-L277
const handleTransitionResolve = async _ => { const handleTransitionResolve = async (_) => {
await settled(); await settled();
return new Promise(resolve => setTimeout(resolve(app), 0)); return new Promise((resolve) => setTimeout(resolve(app), 0));
}; };
const handleTransitionReject = error => { const handleTransitionReject = (error) => {
if (error.error) { if (error.error) {
throw error.error; throw error.error;
} else if (error.name === 'TransitionAborted' && router._routerMicrolib.activeTransition) { } else if (error.name === 'TransitionAborted' && router._routerMicrolib.activeTransition) {

View File

@ -16,7 +16,7 @@ const trailingSlashRe = /\/$/;
// const moreThan1SlashRe = /\/{2,}/g; // const moreThan1SlashRe = /\/{2,}/g;
const _uuid = function () { const _uuid = function () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0; const r = (Math.random() * 16) | 0;
return (c === 'x' ? r : (r & 3) | 8).toString(16); return (c === 'x' ? r : (r & 3) | 8).toString(16);
}); });
@ -303,9 +303,11 @@ export default class FSMWithOptionalLocation {
const temp = url.split('/'); const temp = url.split('/');
optional = { optional = {
...this.optional, ...this.optional,
...(optional || {}) ...(optional || {}),
}; };
optional = Object.values(optional).filter(item => Boolean(item)).map(item => item.value || item, []); optional = Object.values(optional)
.filter((item) => Boolean(item))
.map((item) => item.value || item, []);
temp.splice(...[1, 0].concat(optional)); temp.splice(...[1, 0].concat(optional));
url = temp.join('/'); url = temp.join('/');
} }

View File

@ -78,7 +78,7 @@ export default Mixin.create({
create: function (item) { create: function (item) {
return this.feedback.execute( return this.feedback.execute(
() => { () => {
return this.repo.persist(item).then(item => { return this.repo.persist(item).then((item) => {
return this.afterCreate(...arguments); return this.afterCreate(...arguments);
}); });
}, },
@ -122,7 +122,7 @@ export default Mixin.create({
partition: get(item, 'Partition'), partition: get(item, 'Partition'),
id: get(item, 'AccessorID'), id: get(item, 'AccessorID'),
}) })
.then(item => { .then((item) => {
return this.settings.persist({ return this.settings.persist({
token: { token: {
AccessorID: get(item, 'AccessorID'), AccessorID: get(item, 'AccessorID'),
@ -141,7 +141,7 @@ export default Mixin.create({
return this.feedback.execute(() => { return this.feedback.execute(() => {
return this.repo return this.repo
.clone(item) .clone(item)
.then(item => { .then((item) => {
cloned = item; cloned = item;
// cloning is similar to delete in that // cloning is similar to delete in that
// if you clone from the listing page, stay on the listing page // if you clone from the listing page, stay on the listing page

View File

@ -26,6 +26,6 @@ export default class IntentionPermission extends Fragment {
@computed(...schema.HeaderType.allowedValues) @computed(...schema.HeaderType.allowedValues)
get HeaderType() { get HeaderType() {
return schema.HeaderType.allowedValues.find(prop => typeof this[prop] !== 'undefined'); return schema.HeaderType.allowedValues.find((prop) => typeof this[prop] !== 'undefined');
} }
} }

View File

@ -25,6 +25,6 @@ export default class IntentionPermissionHttp extends Fragment {
@computed(...schema.PathType.allowedValues) @computed(...schema.PathType.allowedValues)
get PathType() { get PathType() {
return schema.PathType.allowedValues.find(prop => typeof this[prop] === 'string'); return schema.PathType.allowedValues.find((prop) => typeof this[prop] === 'string');
} }
} }

View File

@ -28,11 +28,11 @@ export default class Node extends Model {
@fragmentArray('health-check') Checks; @fragmentArray('health-check') Checks;
// MeshServiceInstances are all instances that aren't connect-proxies this // MeshServiceInstances are all instances that aren't connect-proxies this
// currently includes gateways as these need to show up in listings // currently includes gateways as these need to show up in listings
@filter('Services', item => item.Service.Kind !== 'connect-proxy') MeshServiceInstances; @filter('Services', (item) => item.Service.Kind !== 'connect-proxy') MeshServiceInstances;
// ProxyServiceInstances are all instances that are connect-proxies // ProxyServiceInstances are all instances that are connect-proxies
@filter('Services', item => item.Service.Kind === 'connect-proxy') ProxyServiceInstances; @filter('Services', (item) => item.Service.Kind === 'connect-proxy') ProxyServiceInstances;
@filter('Checks', item => item.ServiceID === '') NodeChecks; @filter('Checks', (item) => item.ServiceID === '') NodeChecks;
@computed('ChecksCritical', 'ChecksPassing', 'ChecksWarning') @computed('ChecksCritical', 'ChecksPassing', 'ChecksWarning')
get Status() { get Status() {
@ -50,16 +50,16 @@ export default class Node extends Model {
@computed('NodeChecks.[]') @computed('NodeChecks.[]')
get ChecksCritical() { get ChecksCritical() {
return this.NodeChecks.filter(item => item.Status === 'critical').length; return this.NodeChecks.filter((item) => item.Status === 'critical').length;
} }
@computed('NodeChecks.[]') @computed('NodeChecks.[]')
get ChecksPassing() { get ChecksPassing() {
return this.NodeChecks.filter(item => item.Status === 'passing').length; return this.NodeChecks.filter((item) => item.Status === 'passing').length;
} }
@computed('NodeChecks.[]') @computed('NodeChecks.[]')
get ChecksWarning() { get ChecksWarning() {
return this.NodeChecks.filter(item => item.Status === 'warning').length; return this.NodeChecks.filter((item) => item.Status === 'warning').length;
} }
} }

Some files were not shown because too many files have changed in this diff Show More