Skip to content

Commit

Permalink
refactor: Js
Browse files Browse the repository at this point in the history
  • Loading branch information
lee-to committed Nov 22, 2024
1 parent 308694f commit 357d2e2
Show file tree
Hide file tree
Showing 34 changed files with 307 additions and 250 deletions.
4 changes: 2 additions & 2 deletions src/Laravel/src/Buttons/QueryTagButton.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public static function for(CrudResource $resource, QueryTag $tag): ActionButtonC
->icon($tag->getIconValue(), $tag->isCustomIcon(), $tag->getIconPath())
->canSee(static fn (mixed $data): bool => $tag->isSee())
->class('js-query-tag-button')
->xDataMethod('asyncLink', 'btn-primary', $resource->getListEventName())
->xDataMethod('queryTag', 'btn-primary', $resource->getListEventName())
->when(
$tag->isActive(),
static fn (ActionButtonContract $btn): ActionButtonContract => $btn
Expand All @@ -35,7 +35,7 @@ public static function for(CrudResource $resource, QueryTag $tag): ActionButtonC
$resource->isAsync(),
static fn (ActionButtonContract $btn): ActionButtonContract => $btn
->onClick(
static fn ($action): string => "queryTagRequest(`{$tag->getUri()}`)",
static fn ($action): string => "request(`{$tag->getUri()}`)",
'prevent'
)
)
Expand Down
10 changes: 7 additions & 3 deletions src/Laravel/src/Components/Fragment.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,6 @@
use MoonShine\UI\Traits\HasAsync;
use Throwable;

/**
* @method static static make(iterable $components = [])
*/
class Fragment extends AbstractWithComponents implements HasAsyncContract
{
use HasAsync;
Expand Down Expand Up @@ -65,6 +62,13 @@ public function updateWith(
);
}

public function withQueryParams(): static
{
return $this->customAttributes(
AlpineJs::asyncWithQueryParamsAttributes()
);
}

/**
* @param array<string, string> $selectors
*/
Expand Down
5 changes: 5 additions & 0 deletions src/Laravel/src/Fields/Relationships/BelongsToMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,11 @@ public function withCheckAll(): static
->onClick(static fn (): string => 'checkAll', 'prevent')
->primary()
->icon('check'),

ActionButton::make('')
->onClick(static fn (): string => 'uncheckAll', 'prevent')
->error()
->icon('x-mark'),
]);
}

Expand Down
11 changes: 9 additions & 2 deletions src/Support/src/AlpineJs.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,14 +86,21 @@ public static function asyncSelectorsParamsAttributes(array $selectors): array
]);
}

public static function requestWithFieldValue(
public static function asyncWithQueryParamsAttributes(): array
{
return [
'data-async-with-query-params' => true
];
}

public static function onChangeSaveField(
string $url,
string $column,
string $value = '',
array $additionally = []
): array {
return [
'@change' => "requestWithFieldValue(`$url`, `$column`, $value);"
'@change' => "saveField(`$url`, `$column`, $value);"
. implode(';', array_filter($additionally)),
];
}
Expand Down
18 changes: 9 additions & 9 deletions src/UI/dist/assets/app.js

Large diffs are not rendered by default.

23 changes: 12 additions & 11 deletions src/UI/resources/js/Components/ActionButton.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ import selectorsParams from '../Support/SelectorsParams.js'
import {ComponentRequestData} from '../DTOs/ComponentRequestData.js'
import {dispatchEvents as de} from '../Support/DispatchEvents.js'
import request from '../Request/Core.js'
import {mergeURLString, prepareQueryParams} from '../Support/URLs.js'

export default () => ({
url: '',
method: 'GET',
withParams: '',
withQueryParams: false,
loading: false,
btnText: '',

Expand All @@ -16,6 +18,7 @@ export default () => ({
this.method = this.$el?.dataset?.asyncMethod

this.withParams = this.$el?.dataset?.asyncWithParams
this.withQueryParams = this.$el?.dataset?.asyncWithQueryParams ?? false

this.loading = false
const el = this.$el
Expand All @@ -32,17 +35,9 @@ export default () => ({
dispatchEvents(componentEvent, exclude = null, extra = {}) {
const url = new URL(this.$el.href)

let params = new URLSearchParams(url.search)

if (exclude !== null) {
const excludes = exclude.split(',')

excludes.forEach(function (excludeName) {
params.delete(excludeName)
})
}

extra['_data'] = exclude === '*' ? {} : Object.fromEntries(params)
extra['_data'] = exclude === '*' ? {} : Object.fromEntries(
prepareQueryParams(new URLSearchParams(url.search), exclude)
)

de(componentEvent, '', this, extra)
},
Expand All @@ -62,6 +57,12 @@ export default () => ({

let body = selectorsParams(this.withParams)

if(this.withQueryParams) {
const queryParams = new URLSearchParams(window.location.search)

this.url = mergeURLString(this.url, queryParams)
}

let stopLoading = function (data, t) {
t.loading = false
}
Expand Down
42 changes: 0 additions & 42 deletions src/UI/resources/js/Components/AsyncSearch.js

This file was deleted.

83 changes: 83 additions & 0 deletions src/UI/resources/js/Components/BelongsToMany.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import {crudFormQuery} from '../Support/Forms.js'

export default () => ({
items: [],
match: [],
query: '',
async search(route) {
if (this.query.length > 0) {
let query = '&query=' + this.query

const form = this.$el.closest('form')
const formQuery = crudFormQuery(form.querySelectorAll('[name]'))

fetch(route + query + (formQuery.length ? '&' + formQuery : ''))
.then(response => {
return response.json()
})
.then(data => {
this.match = data
})
}
},
select(item) {
this.query = ''
this.match = []

const pivot = this.$root.querySelector('.js-pivot-table')

if (pivot !== null) {
const tableName = pivot.dataset.tableName.toLowerCase()

this.$dispatch('table_row_added:' + tableName)

const tr = pivot.querySelector('table > tbody > tr:last-child')
tr.querySelector('.js-pivot-title').innerHTML = item.label
tr.dataset.rowKey = item.value
tr.querySelector('.js-pivot-checker').checked = true

this.$dispatch('table_reindex:' + tableName)
}
},
tree(checked = {}) {
checked.forEach(value => {
this.$el
.querySelectorAll('input[value="' + value + '"]')
.forEach(input => (input.checked = true))
})
},
pivot() {
this.$root.querySelectorAll('.js-pivot-title')?.forEach(function (el) {
el.addEventListener('click', event => {
let tr = el.closest('tr')
let checker = tr.querySelector('.js-pivot-checker')

checker.checked = !checker.checked
})
})

this.autoCheck()
},
autoCheck() {
let fields = this.$root.querySelectorAll('.js-pivot-field')

fields.forEach(function (el, key) {
el.addEventListener('change', event => {
let tr = el.closest('tr')
let checker = tr.querySelector('.js-pivot-checker')

checker.checked = event.target.value
})
})
},
checkAll() {
this.$root.querySelectorAll('.js-pivot-checker')?.forEach(function (el) {
el.checked = true
})
},
uncheckAll() {
this.$root.querySelectorAll('.js-pivot-checker')?.forEach(function (el) {
el.checked = false
})
},
})
1 change: 0 additions & 1 deletion src/UI/resources/js/Components/FormBuilder.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,6 @@ export default (name = '', initData = {}, reactive = {}) => ({

return false
},

showResetButton() {
const form = this.$el

Expand Down
21 changes: 18 additions & 3 deletions src/UI/resources/js/Components/Fragment.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@ import selectorsParams from '../Support/SelectorsParams.js'
import {ComponentRequestData} from '../DTOs/ComponentRequestData.js'
import request, {afterResponse, beforeRequest, initCallback} from '../Request/Core.js'
import {getQueryString} from '../Support/Forms.js'
import {mergeURLString} from '../Support/URLs.js'

export default (asyncUpdateRoute = '') => ({
asyncUpdateRoute: asyncUpdateRoute,
withParams: '',
withQueryParams: false,
loading: false,

init() {
this.loading = false
this.withParams = this.$el?.dataset?.asyncWithParams
this.withQueryParams = this.$el?.dataset?.asyncWithQueryParams ?? false
},
async fragmentUpdate(events, callback = {}) {
if (this.asyncUpdateRoute === '') {
Expand All @@ -29,10 +32,22 @@ export default (asyncUpdateRoute = '') => ({

const t = this

const query = new URLSearchParams(body).toString()
const bodyParams = new URLSearchParams(body)

t.asyncUpdateRoute += t.asyncUpdateRoute.includes('?') ? '&' + query : '?' + query
t.asyncUpdateRoute += getQueryString(this.$event.detail)
if(this.withQueryParams) {
const queryParams = new URLSearchParams(window.location.search)
for (const [key, value] of queryParams) {
bodyParams.append(key, value)
}
}

t.asyncUpdateRoute = mergeURLString(t.asyncUpdateRoute, bodyParams.toString())

const eventDetailQuery = getQueryString(this.$event.detail)

if(eventDetailQuery) {
t.asyncUpdateRoute = mergeURLString(t.asyncUpdateRoute, eventDetailQuery)
}

let stopLoading = function (data, t) {
t.loading = false
Expand Down
40 changes: 40 additions & 0 deletions src/UI/resources/js/Components/Global.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import {ComponentRequestData} from '../DTOs/ComponentRequestData.js'
import request from '../Request/Core.js'

export default () => ({
saveField(route, column, value = null) {
if (value === null) {
value = this.$el.value
}

if (value === null &&
(this.$el.type === 'checkbox' || this.$el.type === 'radio')) {
value = this.$el.checked
}

if (this.$el.tagName.toLowerCase() === 'select' && this.$el.multiple) {
value = []
for (let i = 0; i < this.$el.options.length; i++) {
let option = this.$el.options[i]
if (option.selected) {
value.push(option.value)
}
}
}

const componentRequestData = new ComponentRequestData()
componentRequestData.fromDataset(this.$el?.dataset ?? {})

request(
this,
route,
this.$el?.dataset?.asyncMethod ?? 'put',
{
value: value,
field: column,
},
{},
componentRequestData,
)
},
})
Loading

0 comments on commit 357d2e2

Please sign in to comment.