Skip to content

Commit

Permalink
wip: strict mode
Browse files Browse the repository at this point in the history
  • Loading branch information
rboixaderg committed Mar 30, 2024
1 parent 46b1aac commit 4e4c5eb
Show file tree
Hide file tree
Showing 28 changed files with 324 additions and 232 deletions.
4 changes: 2 additions & 2 deletions src/guillo-gmi/components/Link.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export function Link({ aRef, model, children, ...props }: Props) {
const [path, navigate] = useLocation()
const aStyle = { textDecoration: 'none', color: 'currentColor' }

function onClick(e) {
function onClick(e: React.MouseEvent<HTMLAnchorElement>) {
e.stopPropagation()
if (actAsLink(e)) return
e.preventDefault()
Expand All @@ -32,6 +32,6 @@ export function Link({ aRef, model, children, ...props }: Props) {
)
}

function actAsLink(e) {
function actAsLink(e: React.MouseEvent<HTMLAnchorElement>) {
return e.ctrlKey || e.metaKey || e.altKey || e.shiftKey || e.button !== 0
}
29 changes: 17 additions & 12 deletions src/guillo-gmi/components/context_toolbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@ import { useLocation } from '../hooks/useLocation'
import { Select } from './input/select'
import { useIntl } from 'react-intl'
import { genericMessages } from '../locales/generic_messages'
import { FilterFormElement } from '../types/global'

interface State {
types?: string[]
types: string[]
isActive?: boolean
}
const initialState = { types: undefined }
const initialState = { types: [] }

export function CreateButton() {
const intl = useIntl()
Expand All @@ -24,15 +25,15 @@ export function CreateButton() {
const Config = useConfig()
useEffect(() => {
async function anyNameFunction() {
const types = await Ctx.client.getTypes(Ctx.path)
const types: string[] = await Ctx.client.getTypes(Ctx.path)
setState({
types: types.filter((item) => !Config.DisabledTypes.includes(item)),
})
}
anyNameFunction()
}, [Ctx.path])

const doAction = (item) => {
const doAction = (item: string) => {
Ctx.doAction('addItem', { type: item })
setState({ isActive: false })
}
Expand Down Expand Up @@ -77,7 +78,7 @@ export function ContextToolbar({ AddButton }: Props) {
const [location, setLocation, del] = useLocation()
const traversal = useTraversal()
const Config = useConfig()
const searchText = location.get('q')
const searchText = location.get('q') || ''
const [searchValue, setSearchValue] = useState(searchText || '')

useEffect(() => {
Expand All @@ -89,19 +90,22 @@ export function ContextToolbar({ AddButton }: Props) {
}, [searchText])

async function loadTypes() {
const types = await traversal.client.getTypes(traversal.path)
const types: string[] = await traversal.client.getTypes(traversal.path)
setState({
types: types.filter((item) => !Config.DisabledTypes.includes(item)),
})
}

const onSearchQuery = (ev) => {
const search = ev.target[0].value
setLocation({ q: search, tab: 'Items', page: 0 })
ev.preventDefault()
const onSearchQuery = (event: React.FormEvent<FilterFormElement>) => {
event.preventDefault()
setLocation({
q: event.currentTarget.elements.filterInput.value,
tab: 'Items',
page: 0,
})
}

const onSearchByType = (typeText) => {
const onSearchByType = (typeText: string) => {
if (typeText && typeText !== '') {
setLocation({ type: typeText, tab: 'Items', page: 0 })
} else {
Expand All @@ -122,6 +126,7 @@ export function ContextToolbar({ AddButton }: Props) {
className="input is-size-7"
placeholder={intl.formatMessage(genericMessages.search)}
data-test="inputFilterTest"
id="filterInput"
/>
</div>
<div className="control">
Expand All @@ -145,7 +150,7 @@ export function ContextToolbar({ AddButton }: Props) {
text: item,
value: item,
}))}
onChange={onSearchByType}
onChange={(value) => onSearchByType(value as string)}
/>
</div>
{traversal.hasPerm('guillotina.AddContent') && (
Expand Down
28 changes: 15 additions & 13 deletions src/guillo-gmi/components/input/form_builder.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ const formComponents = {

interface Props {
schema: GuillotinaSchema
formData?: any
onSubmit: (formData: any, initialData: any) => void
formData?: IndexSignature
onSubmit: (formData: IndexSignature, initialData: IndexSignature) => void
actionName: string
children?: React.ReactNode
exclude?: string[]
Expand All @@ -40,39 +40,42 @@ export function FormBuilder({
remotes = {},
submitButton = true,
}: Props) {
const ref = useRef<unknown>()
const ref = useRef<IndexSignature | null>(null)
const { properties, required } = schema
const values = Object.assign({}, formData || {})

// build initial state
const initialState = {}
const initialState: IndexSignature = {}
const fields = Object.keys(properties).filter((x) => !exclude.includes(x))

fields.forEach((element) => {
initialState[element] = values[element] || undefined
})

// Register remotes
if (!ref.current) {
if (ref.current === null) {
ref.current = {}
Object.keys(remotes).forEach((item) => (ref.current[item] = remotes[item]))
Object.keys(remotes).forEach((item) => (ref.current![item] = remotes[item]))
} else {
// apply remote changes
Object.keys(remotes).forEach((key) => {
if (JSON.stringify(ref.current[key]) !== JSON.stringify(remotes[key])) {
ref.current[key] = remotes[key]
if (JSON.stringify(ref.current![key]) !== JSON.stringify(remotes[key])) {
ref.current![key] = remotes[key]
}
})
}

ref.current = ref.current || {}
const onUpdate = (field) => (ev) => {
ref.current[field] = ev.target ? ev.target.value : ev.value || ev
const onUpdate = (field: string) => (value: boolean | string) => {
ref.current![field] = value
}

const GetTag = ({ field }: { field: string }) => {
const property = properties[field] as GuillotinaSchemaProperty
const Tag = formComponents[property.widget || property.type]
const key = (property.widget ||
property.type) as keyof typeof formComponents

const Tag: React.ComponentType<any> = formComponents[key]

const props = {
value: initialState[field],
Expand All @@ -87,7 +90,6 @@ export function FormBuilder({
props.required = true
props.placeholder += ' *'
}
Tag.displayName = `${field}Field`
return <Tag {...props} />
}

Expand All @@ -100,7 +102,7 @@ export function FormBuilder({
})

const changes = () => {
onSubmit(ref.current, values)
onSubmit(ref.current!, values)
}

return (
Expand Down
8 changes: 4 additions & 4 deletions src/guillo-gmi/components/login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React, { useRef, useEffect } from 'react'
import useSetState from '../hooks/useSetState'
import { Auth } from '../lib/auth'

const ERRORS = {
const ERRORS: { [key: string]: string } = {
failed_to_fetch: 'Failed to fetch data: Backend not running?',
invalid_credentials: 'Failed! Invalid credentials',
}
Expand Down Expand Up @@ -34,15 +34,15 @@ export const Login = ({
onLogin,
}: Props) => {
const [state, setState] = useSetState<State>(initialState)
const inputRef = useRef(null)
const inputRef = useRef<HTMLInputElement | null>(null)

useEffect(() => {
if (inputRef) {
if (inputRef && inputRef.current) {
inputRef.current.focus()
}
}, [inputRef])

const doLogin = async (ev) => {
const doLogin = async (ev: React.FormEvent) => {
ev.preventDefault()
setState({ loading: true, errors: undefined })
const { username, password } = state
Expand Down
30 changes: 19 additions & 11 deletions src/guillo-gmi/components/panel/items.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@ import { SelectVocabulary } from '../input/select_vocabulary'
import { useIntl } from 'react-intl'
import { genericMessages } from '../../locales/generic_messages'

import { RegistrySchemaFilter, SearchItem } from '../../types/guillotina'
import {
ItemColumn,
RegistrySchemaFilter,
SearchItem,
} from '../../types/guillotina'

interface InitialState {
page: number
Expand Down Expand Up @@ -145,11 +149,15 @@ export function PanelItems() {
}

const { signal } = controller
const data = await Ctx.client.search(Ctx.path, qs, false, false, {
signal,
})
const data = await Ctx.client.search<SearchItem>(
Ctx.path,
qs,
false,
false,
signal
)
setState({
items: data.member,
items: data.items,
loading: false,
total: data.items_count,
})
Expand All @@ -167,11 +175,11 @@ export function PanelItems() {
...resultDynamicLocation,
])

const doPaginate = (page) => {
const doPaginate = (page: number) => {
setLocation({ page: page })
}

const getIcon = (key, isSortable) => {
const getIcon = (key: string, isSortable: boolean) => {
let icon = null
if (isSortable) {
if (sort !== key) {
Expand All @@ -198,7 +206,7 @@ export function PanelItems() {
placeholder={filter.label}
appendDefault
classWrap="is-size-7 is-fullwidth"
options={filter.values}
options={filter.values ?? []}
value={location.get(filter.attribute_key) || ''}
dataTest={`filterInput${filter.attribute_key}`}
onChange={(value) => {
Expand Down Expand Up @@ -330,15 +338,15 @@ export function PanelItems() {
<th>
<AllItemsCheckbox />
</th>
{columns.map((column) => (
{columns.map((column: ItemColumn) => (
<th
key={`table-col-${column.label}`}
onClick={() => column.isSortable && onSort(column.key)}
data-test={`sortableColumn${column.key}`}
>
<div className="has-text-info is-flex is-align-items-center">
<span>{column.label}</span>
{getIcon(column.key, column.isSortable)}
{getIcon(column.key, !!column.isSortable)}
</div>
</th>
))}
Expand All @@ -351,7 +359,7 @@ export function PanelItems() {
<RItem
item={item}
key={item['@uid']}
search={search}
search={search ?? ''}
columns={columns}
/>
))}
Expand Down
14 changes: 9 additions & 5 deletions src/guillo-gmi/components/panel/properties.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
GuillotinaSchema,
GuillotinaSchemaProperty,
} from '../../types/guillotina'
import { get } from '../../lib/utils'

const _showProperties = ['@id', '@name', '@uid']
const _ignoreFields = [
Expand All @@ -35,7 +36,7 @@ const _ignoreFields = [
interface State {
data: GuillotinaSchema
loading: boolean
error: string
error: string | unknown
}

export function PanelProperties() {
Expand All @@ -52,7 +53,7 @@ export function PanelProperties() {

const model = new ItemModel(Ctx.context)

const showProperties =
const showProperties: string[] =
Ctx.registry.getProperties(Ctx.context['@type']).default ||
cfg.properties_default ||
_showProperties
Expand All @@ -74,7 +75,10 @@ export function PanelProperties() {
if (!schema.loading && !schema.data && !schema.error) {
try {
setSchema({ loading: true })
const dataJson = await Ctx.client.getTypeSchema(Ctx.path, model.type)
const dataJson = await Ctx.client.getTypeSchema(
Ctx.path,
Ctx.context.type_name
)
setSchema({ loading: false, data: dataJson })
} catch (err) {
setSchema({ loading: false, error: err })
Expand Down Expand Up @@ -121,7 +125,7 @@ export function PanelProperties() {
<td>
<EditableField
field={prop}
value={Ctx.context[prop]}
value={get(Ctx.context, prop, '')}
modifyContent={false}
/>
</td>
Expand Down Expand Up @@ -149,7 +153,7 @@ export function PanelProperties() {
<td>
<EditableField
field={key}
value={Ctx.context[key]}
value={get(Ctx.context, key, '')}
schema={value}
modifyContent={modifyContent}
required={(schema.data?.required ?? []).includes(
Expand Down
6 changes: 3 additions & 3 deletions src/guillo-gmi/components/search_options_labels.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ interface Props {
}
export function SearchOptionsLabels({ query = 'q', options }: Props) {
const [location, , del] = useLocation()
const [renderValue, setRenderValue] = useState(undefined)
const defaultRenderValue = location.get(query)
const [renderValue, setRenderValue] = useState<string | undefined>(undefined)
const defaultRenderValue = location.get(query) || ''

useEffect(() => {
let value = defaultRenderValue
if ((options ?? []).length > 0) {
if (options && (options ?? []).length > 0) {
const option = options.find((item) => item.value === value)
if (option) {
value = option.text
Expand Down
6 changes: 3 additions & 3 deletions src/guillo-gmi/components/search_vocabulary_labels.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ import { useVocabulary } from '../hooks/useVocabulary'

interface Props {
query?: string
vocabularyName?: string
vocabularyName: string
}

export function SearchVocabularyLabels({ query = 'q', vocabularyName }: Props) {
const [location, , del] = useLocation()
const [renderValue, setRenderValue] = useState(undefined)
const [renderValue, setRenderValue] = useState<string | undefined>(undefined)
const vocabulary = useVocabulary(vocabularyName)
const defaultRenderValue = location.get(query)
const defaultRenderValue = location.get(query) || ''

useEffect(() => {
let value: string = defaultRenderValue
Expand Down
Loading

0 comments on commit 4e4c5eb

Please sign in to comment.