Co-authored-by: gorbenko.pavel <gorbenko.pavel@tansu.kz> Reviewed-on: http://git.tnsu.kz/gorbenko.pavel/tnsu-approval-route/pulls/6
This commit was merged in pull request #6.
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
import * as React from 'react';
|
||||
|
||||
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Как React.useState, но значение переживает перезагрузку страницы — хранится
|
||||
* в localStorage под key. Падение доступа к localStorage (приватный режим,
|
||||
* квота) не ломает форму — просто не персистит.
|
||||
*
|
||||
* Сохранённое значение мелко мёржится с initial (для объектных T): если после
|
||||
* обновления в форму добавили новое поле, у пользователей со старой записью в
|
||||
* localStorage оно не потеряется как undefined (что уронило бы рендер на
|
||||
* первом же .map/.trim по этому полю), а подставится дефолт из initial.
|
||||
*/
|
||||
export function useLocalStorageState<T>(key: string, initial: T): [T, React.Dispatch<React.SetStateAction<T>>] {
|
||||
const [value, setValue] = React.useState<T>(() => {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(key);
|
||||
if (!raw) return initial;
|
||||
|
||||
const parsed = JSON.parse(raw) as T;
|
||||
return isPlainObject(initial) && isPlainObject(parsed) ? { ...initial, ...parsed } as T : parsed;
|
||||
} catch {
|
||||
return initial;
|
||||
}
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
try {
|
||||
window.localStorage.setItem(key, JSON.stringify(value));
|
||||
} catch {
|
||||
// приватный режим / переполненная квота — не критично, просто не персистим
|
||||
}
|
||||
}, [key, value]);
|
||||
|
||||
return [value, setValue];
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import * as React from 'react';
|
||||
import { SharePointListField, SharePointListsClient } from '../services/sharePointLists';
|
||||
|
||||
export interface SharePointFieldsState {
|
||||
items: SharePointListField[];
|
||||
isLoading: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/** Заголовки столбцов списка (site_url + list_name типа заявки) — источник значений для field_name шага. */
|
||||
export function useSharePointFields(
|
||||
client: SharePointListsClient | undefined,
|
||||
siteUrl: string | undefined | null,
|
||||
listTitle: string | undefined | null
|
||||
): SharePointFieldsState {
|
||||
const [items, setItems] = React.useState<SharePointListField[]>([]);
|
||||
const [isLoading, setIsLoading] = React.useState(false);
|
||||
const [error, setError] = React.useState<string | undefined>();
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!client || !siteUrl?.trim() || !listTitle?.trim()) {
|
||||
setItems([]);
|
||||
setError(undefined);
|
||||
setIsLoading(false);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
setIsLoading(true);
|
||||
setError(undefined);
|
||||
|
||||
client.listFields(siteUrl.trim(), listTitle.trim())
|
||||
.then(result => { if (!cancelled) setItems(result); })
|
||||
.catch((e: Error) => { if (!cancelled) { setItems([]); setError(e.message); } })
|
||||
.finally(() => { if (!cancelled) setIsLoading(false); });
|
||||
|
||||
return () => { cancelled = true; };
|
||||
}, [client, siteUrl, listTitle]);
|
||||
|
||||
return { items, isLoading, error };
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import * as React from 'react';
|
||||
import { SharePointList, SharePointListsClient } from '../services/sharePointLists';
|
||||
|
||||
export interface SharePointListsState {
|
||||
items: SharePointList[];
|
||||
isLoading: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
const DEBOUNCE_MS = 500;
|
||||
|
||||
/**
|
||||
* Списки указанного сайта SharePoint — подгружаются автоматически по мере ввода
|
||||
* site_url (с задержкой, чтобы не дёргать сайт на каждый символ).
|
||||
*/
|
||||
export function useSharePointLists(client: SharePointListsClient | undefined, siteUrl: string): SharePointListsState {
|
||||
const [items, setItems] = React.useState<SharePointList[]>([]);
|
||||
const [isLoading, setIsLoading] = React.useState(false);
|
||||
const [error, setError] = React.useState<string | undefined>();
|
||||
|
||||
React.useEffect(() => {
|
||||
const trimmed = siteUrl.trim();
|
||||
if (!client || !trimmed) {
|
||||
setItems([]);
|
||||
setError(undefined);
|
||||
setIsLoading(false);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
setIsLoading(true);
|
||||
setError(undefined);
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
client.listLists(trimmed)
|
||||
.then(result => { if (!cancelled) setItems(result); })
|
||||
.catch((e: Error) => { if (!cancelled) { setItems([]); setError(e.message); } })
|
||||
.finally(() => { if (!cancelled) setIsLoading(false); });
|
||||
}, DEBOUNCE_MS);
|
||||
|
||||
return () => { cancelled = true; clearTimeout(timer); };
|
||||
}, [client, siteUrl]);
|
||||
|
||||
return { items, isLoading, error };
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import * as React from 'react';
|
||||
import { SharePointListsClient } from '../services/sharePointLists';
|
||||
|
||||
export interface SharePointSiteTitleState {
|
||||
title: string | null;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
/** Заголовок сайта SharePoint по его url — для отображения «Название — url» вместо голого url. */
|
||||
export function useSharePointSiteTitle(
|
||||
client: SharePointListsClient | undefined,
|
||||
siteUrl: string | undefined | null
|
||||
): SharePointSiteTitleState {
|
||||
const [title, setTitle] = React.useState<string | null>(null);
|
||||
const [isLoading, setIsLoading] = React.useState(false);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!client || !siteUrl?.trim()) {
|
||||
setTitle(null);
|
||||
setIsLoading(false);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
setIsLoading(true);
|
||||
|
||||
client.getSiteTitle(siteUrl.trim())
|
||||
.then(result => { if (!cancelled) setTitle(result); })
|
||||
.catch(() => { if (!cancelled) setTitle(null); })
|
||||
.finally(() => { if (!cancelled) setIsLoading(false); });
|
||||
|
||||
return () => { cancelled = true; };
|
||||
}, [client, siteUrl]);
|
||||
|
||||
return { title, isLoading };
|
||||
}
|
||||
Reference in New Issue
Block a user