👷 ci(lint): update lint config and code style

main
canisminor1990 2023-06-18 00:20:15 +08:00
parent 56cf8f327b
commit e9e51e66b2
34 changed files with 1837 additions and 1797 deletions

View File

@ -1,13 +1,16 @@
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 2
tab_width = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 100
[*.md]
trim_trailing_whitespace = false

View File

@ -1 +1,12 @@
module.exports = require('@lobehub/lint').eslint;
module.exports = {
...require('@lobehub/lint').eslint,
overrides: [
{
files: ['*.ts', '*.tsx'],
rules: {
'no-undef': 0,
'unicorn/prefer-add-event-listener': 0,
},
},
],
};

View File

@ -3,5 +3,11 @@ module.exports = {
rules: {
'selector-class-pattern': null,
'selector-id-pattern': null,
'no-descending-specificity': [
true,
{
severity: 'warning',
},
],
},
};

File diff suppressed because one or more lines are too long

View File

@ -25,13 +25,13 @@ interface ContentProps {
}
const Content = memo<ContentProps>(({children}) => {
const ref: any = useRef(null);
const reference: any = useRef(null);
const [setting] = useAppStore((st) => [st.setting], shallow);
return (
<ContentView isPromptResizable={setting.promotTextarea === 'resizable'} ref={ref}>
<ContentView isPromptResizable={setting.promotTextarea === 'resizable'} ref={reference}>
{children}
<FloatButton.BackTop target={() => ref.current} />
<FloatButton.BackTop target={() => reference.current} />
</ContentView>
);
});

View File

@ -60,15 +60,15 @@ const DraggablePanel = memo<DraggablePanelProps>(
destroyOnClose,
hanlderStyle,
}) => {
const ref = useRef(null);
const isHovering = useHover(ref);
const reference = useRef(null);
const isHovering = useHover(reference);
const isVertical = placement === 'top' || placement === 'bottom';
const {styles, cx} = useStyle('draggable-panel');
const [isExpand, setIsExpand] = useControlledState(defaultExpand, {
value: expand,
onChange: onExpandChange,
value: expand,
});
useEffect(() => {
@ -93,60 +93,65 @@ const DraggablePanel = memo<DraggablePanelProps>(
}, [canResizing, placement]);
const resizing = {
top: false,
bottom: false,
right: false,
left: false,
topRight: false,
bottomRight: false,
bottomLeft: false,
bottomRight: false,
left: false,
right: false,
top: false,
topLeft: false,
topRight: false,
[revesePlacement(placement)]: true,
...(resize as Enable),
};
const defaultSize: Size = useMemo(() => {
if (isVertical)
if (isVertical) {
return {
width: '100%',
height: DEFAULT_HEIGHT,
width: '100%',
...customizeDefaultSize,
};
}
return {
width: DEFAULT_WIDTH,
height: '100%',
width: DEFAULT_WIDTH,
...customizeDefaultSize,
};
}, [isVertical]);
const sizeProps = isExpand
? {
minWidth: typeof minWidth === 'number' ? Math.max(minWidth, 0) : 280,
minHeight: typeof minHeight === 'number' ? Math.max(minHeight, 0) : undefined,
const sizeProps = isExpand ?
{
defaultSize,
minHeight: typeof minHeight === 'number' ? Math.max(minHeight, 0) : undefined,
minWidth: typeof minWidth === 'number' ? Math.max(minWidth, 0) : 280,
size: size as Size,
}
: isVertical
? {
} :
isVertical ?
{
minHeight: 0,
size: {height: 0},
}
: {
} :
{
minWidth: 0,
size: {width: 0},
};
const {Arrow, className: arrowPlacement} = useMemo(() => {
switch (placement) {
case 'top':
return { className: 'Bottom', Arrow: ChevronDown };
case 'bottom':
return { className: 'Top', Arrow: ChevronUp };
case 'right':
return { className: 'Left', Arrow: ChevronLeft };
case 'left':
return { className: 'Right', Arrow: ChevronRight };
case 'top': {
return {Arrow: ChevronDown, className: 'Bottom'};
}
case 'bottom': {
return {Arrow: ChevronUp, className: 'Top'};
}
case 'right': {
return {Arrow: ChevronLeft, className: 'Left'};
}
case 'left': {
return {Arrow: ChevronRight, className: 'Right'};
}
}
}, [styles, placement]);
@ -155,7 +160,7 @@ const DraggablePanel = memo<DraggablePanelProps>(
<Center
// @ts-ignore
className={cx(styles[`toggle${arrowPlacement}`])}
style={{ opacity: isExpand ? (!pin ? 0 : undefined) : showHandlerWhenUnexpand ? 1 : 0 }}
style={{opacity: isExpand ? (pin ? undefined : 0) : showHandlerWhenUnexpand ? 1 : 0}}
>
<Center
onClick={() => {
@ -180,20 +185,20 @@ const DraggablePanel = memo<DraggablePanelProps>(
className={styles.panel}
enable={canResizing ? (resizing as Enable) : undefined}
handleClasses={resizeHandleClassNames}
onResize={(_, direction, ref, delta) => {
onResize={(_, direction, reference_, delta) => {
onSizeDragging?.(delta, {
width: ref.style.width,
height: ref.style.height,
height: reference_.style.height,
width: reference_.style.width,
});
}}
onResizeStart={() => {
setShowExpand(false);
}}
onResizeStop={(e, direction, ref, delta) => {
onResizeStop={(e, direction, reference_, delta) => {
setShowExpand(true);
onSizeChange?.(delta, {
width: ref.style.width,
height: ref.style.height,
height: reference_.style.height,
width: reference_.style.width,
});
}}
style={style}
@ -210,7 +215,7 @@ const DraggablePanel = memo<DraggablePanelProps>(
styles[mode === 'fixed' ? 'fixed' : `${placement}Float`],
className,
)}
ref={ref}
ref={reference}
style={{[`border${arrowPlacement}Width`]: 1}}
>
{expandable && showExpand && handler}

View File

@ -70,6 +70,27 @@ export const useStyle = createStyles(({ token }, prefix: string) => {
`;
return {
bottomFloat: cx(
float,
css`
right: 0;
bottom: 0;
left: 0;
width: 100%;
`,
),
bottomHandle: cx(
`${prefix}-bottom-handle`,
css`
${commonHandle};
&::before {
bottom: 50%;
width: 100%;
height: 2px;
}
`,
),
container: cx(
prefix,
css`
@ -85,6 +106,12 @@ export const useStyle = createStyles(({ token }, prefix: string) => {
),
fixed: css`
position: relative;
`,
handlerIcon: css`
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s ${token.motionEaseOut};
`,
leftFloat: cx(
float,
@ -93,6 +120,26 @@ export const useStyle = createStyles(({ token }, prefix: string) => {
bottom: 0;
left: 0;
height: 100%;
`,
),
leftHandle: cx(
css`
${commonHandle};
&::before {
left: 50%;
width: 2px;
height: 100%;
}
`,
`${prefix}-left-handle`,
),
panel: cx(
`${prefix}-fixed`,
css`
overflow: hidden;
background: ${token.colorBgContainer};
transition: all 0.2s ${token.motionEaseOut};
`,
),
rightFloat: cx(
@ -104,22 +151,35 @@ export const useStyle = createStyles(({ token }, prefix: string) => {
height: 100%;
`,
),
topFloat: cx(
float,
rightHandle: cx(
css`
top: 0;
right: 0;
left: 0;
width: 100%;
${commonHandle};
&::before {
right: 50%;
width: 2px;
height: 100%;
}
`,
`${prefix}-right-handle`,
),
bottomFloat: cx(
float,
toggleBottom: cx(
`${prefix}-toggle`,
`${prefix}-toggle-bottom`,
commonToggle,
css`
right: 0;
bottom: 0;
left: 0;
bottom: -${offset}px;
width: 100%;
height: ${toggleShort}px;
> div {
left: 50%;
width: ${toggleLength}px;
height: 16px;
margin-left: -20px;
border-radius: 0 0 4px 4px;
}
`,
),
toggleLeft: cx(
@ -182,63 +242,15 @@ export const useStyle = createStyles(({ token }, prefix: string) => {
}
`,
),
toggleBottom: cx(
`${prefix}-toggle`,
`${prefix}-toggle-bottom`,
commonToggle,
topFloat: cx(
float,
css`
bottom: -${offset}px;
top: 0;
right: 0;
left: 0;
width: 100%;
height: ${toggleShort}px;
> div {
left: 50%;
width: ${toggleLength}px;
height: 16px;
margin-left: -20px;
border-radius: 0 0 4px 4px;
}
`,
),
panel: cx(
`${prefix}-fixed`,
css`
overflow: hidden;
background: ${token.colorBgContainer};
transition: all 0.2s ${token.motionEaseOut};
`,
),
handlerIcon: css`
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s ${token.motionEaseOut};
`,
leftHandle: cx(
css`
${commonHandle};
&::before {
left: 50%;
width: 2px;
height: 100%;
}
`,
`${prefix}-left-handle`,
),
rightHandle: cx(
css`
${commonHandle};
&::before {
right: 50%;
width: 2px;
height: 100%;
}
`,
`${prefix}-right-handle`,
),
topHandle: cx(
`${prefix}-top-handle`,
css`
@ -251,17 +263,5 @@ export const useStyle = createStyles(({ token }, prefix: string) => {
}
`,
),
bottomHandle: cx(
`${prefix}-bottom-handle`,
css`
${commonHandle};
&::before {
bottom: 50%;
width: 100%;
height: 2px;
}
`,
),
};
});

View File

@ -2,13 +2,17 @@ import { placementType } from './index';
export const revesePlacement = (placement: placementType) => {
switch (placement) {
case 'bottom':
case 'bottom': {
return 'top';
case 'top':
}
case 'top': {
return 'bottom';
case 'right':
}
case 'right': {
return 'left';
case 'left':
}
case 'left': {
return 'right';
}
}
};

View File

@ -8,18 +8,18 @@ const Giscus = memo<GiscusProps>(({ themeMode }) => {
// giscus
const giscus: HTMLScriptElement = document.createElement('script');
giscus.src = 'https://giscus.app/client.js';
giscus.setAttribute('data-repo', 'canisminor1990/sd-webui-kitchen-theme');
giscus.setAttribute('data-repo-id', 'R_kgDOJCPcNg');
giscus.setAttribute('data-mapping', 'number');
giscus.setAttribute('data-term', '53');
giscus.setAttribute('data-reactions-enabled', '1');
giscus.setAttribute('data-emit-metadata', '0');
giscus.setAttribute('data-input-position', 'bottom');
giscus.setAttribute('data-theme', themeMode);
giscus.setAttribute('data-lang', 'en');
giscus.dataset.repo = 'canisminor1990/sd-webui-kitchen-theme';
giscus.dataset.repoId = 'R_kgDOJCPcNg';
giscus.dataset.mapping = 'number';
giscus.dataset.term = '53';
giscus.dataset.reactionsEnabled = '1';
giscus.dataset.emitMetadata = '0';
giscus.dataset.inputPosition = 'bottom';
giscus.dataset.theme = themeMode;
giscus.dataset.lang = 'en';
giscus.crossOrigin = 'anonymous';
giscus.async = true;
document.getElementsByTagName('head')[0].appendChild(giscus);
document.querySelectorAll('head')[0].append(giscus);
}, []);
return <div className="giscus" id="giscus" />;

View File

@ -38,6 +38,13 @@ const NavBar = styled(Menu)`
************************* Dom *************************
******************************************************/
const onClick: MenuProps['onClick'] = (e: any) => {
const buttons: HTMLButtonElement[] | any = gradioApp().querySelectorAll(
'#tabs > .tab-nav:first-child button',
);
buttons[Number(e.key)]?.click();
};
const Nav = memo(() => {
const [items, setItems] = useState<MenuProps['items']>([]);
@ -48,21 +55,14 @@ const Nav = memo(() => {
buttons.forEach((button: HTMLButtonElement | any, index) => {
button.id = `kitchen-nav-${index}`;
list.push({
label: button.textContent,
key: String(index),
label: button.textContent,
});
});
setItems(list);
});
}, []);
const onClick: MenuProps['onClick'] = (e: any) => {
const buttons: HTMLButtonElement[] | any = gradioApp().querySelectorAll(
'#tabs > .tab-nav:first-child button',
);
buttons[Number(e.key)]?.click();
};
return (
<NavBar
defaultActiveFirst

View File

@ -43,12 +43,12 @@ const Setting = memo(() => {
const onReset = useCallback(() => {
onSetSetting(defaultSetting);
gradioApp().getElementById('settings_restart_gradio')?.click();
gradioApp().querySelector('#settings_restart_gradio')?.click();
}, []);
const onFinish = useCallback((value: WebuiSetting) => {
onSetSetting(value);
gradioApp().getElementById('settings_restart_gradio')?.click();
gradioApp().querySelector('#settings_restart_gradio')?.click();
}, []);
return (

View File

@ -98,7 +98,7 @@ const Header = memo<HeaderProps>(({ children }) => {
</HeaderView>
</DraggablePanel>
<Modal
footer={null}
footer={false}
onCancel={handleCancel}
open={isModalOpen}
title={

View File

@ -1,11 +1,4 @@
export const themeIcon = {
light: (
<span className="anticon anticon-github" role="img">
<svg fill="currentColor" height="1em" viewBox="0 0 16 16" width="1em">
<path d="M8 13a1 1 0 0 1 1 1v1a1 1 0 1 1-2 0v-1a1 1 0 0 1 1-1ZM8 3a1 1 0 0 1-1-1V1a1 1 0 1 1 2 0v1a1 1 0 0 1-1 1Zm7 4a1 1 0 1 1 0 2h-1a1 1 0 1 1 0-2h1ZM3 8a1 1 0 0 1-1 1H1a1 1 0 1 1 0-2h1a1 1 0 0 1 1 1Zm9.95 3.536.707.707a1 1 0 0 1-1.414 1.414l-.707-.707a1 1 0 0 1 1.414-1.414Zm-9.9-7.072-.707-.707a1 1 0 0 1 1.414-1.414l.707.707A1 1 0 0 1 3.05 4.464Zm9.9 0a1 1 0 0 1-1.414-1.414l.707-.707a1 1 0 0 1 1.414 1.414l-.707.707Zm-9.9 7.072a1 1 0 0 1 1.414 1.414l-.707.707a1 1 0 0 1-1.414-1.414l.707-.707ZM8 4a4 4 0 1 0 0 8 4 4 0 0 0 0-8Zm0 6.5a2.5 2.5 0 1 1 0-5 2.5 2.5 0 0 1 0 5Z"></path>
</svg>
</span>
),
dark: (
<span className="anticon anticon-github" role="img">
<svg fill="currentColor" height="1em" viewBox="0 0 16 16" width="1em">
@ -13,6 +6,13 @@ export const themeIcon = {
</svg>
</span>
),
light: (
<span className="anticon anticon-github" role="img">
<svg fill="currentColor" height="1em" viewBox="0 0 16 16" width="1em">
<path d="M8 13a1 1 0 0 1 1 1v1a1 1 0 1 1-2 0v-1a1 1 0 0 1 1-1ZM8 3a1 1 0 0 1-1-1V1a1 1 0 1 1 2 0v1a1 1 0 0 1-1 1Zm7 4a1 1 0 1 1 0 2h-1a1 1 0 1 1 0-2h1ZM3 8a1 1 0 0 1-1 1H1a1 1 0 1 1 0-2h1a1 1 0 0 1 1 1Zm9.95 3.536.707.707a1 1 0 0 1-1.414 1.414l-.707-.707a1 1 0 0 1 1.414-1.414Zm-9.9-7.072-.707-.707a1 1 0 0 1 1.414-1.414l.707.707A1 1 0 0 1 3.05 4.464Zm9.9 0a1 1 0 0 1-1.414-1.414l.707-.707a1 1 0 0 1 1.414 1.414l-.707.707Zm-9.9 7.072a1 1 0 0 1 1.414 1.414l-.707.707a1 1 0 0 1-1.414-1.414l.707-.707ZM8 4a4 4 0 1 0 0 8 4 4 0 0 0 0-8Zm0 6.5a2.5 2.5 0 1 1 0-5 2.5 2.5 0 0 1 0 5Z"></path>
</svg>
</span>
),
};
export const darkLogo =

View File

@ -14,12 +14,12 @@ const View = styled.div`
gap: 8px;
`;
const BtnGroup = styled.div`
const ButtonGroup = styled.div`
display: flex;
gap: 8px;
`;
const Btn = styled.button`
const Button = styled.button`
cursor: pointer;
position: relative;
@ -58,7 +58,9 @@ const Prompt = memo<PromptProps>(({ type }) => {
try {
const textarea: HTMLTextAreaElement | any = get_uiCurrentTabContent().querySelector(id);
if (textarea) setTags(formatPrompt(textarea.value));
} catch {}
} catch (error) {
console.log(error);
}
}, []);
const setValue = useCallback(() => {
@ -66,7 +68,9 @@ const Prompt = memo<PromptProps>(({ type }) => {
const textarea: HTMLTextAreaElement | any = get_uiCurrentTabContent().querySelector(id);
if (textarea) textarea.value = tags.map((t) => t.text).join(', ');
updateInput(textarea);
} catch {}
} catch (error) {
console.log(error);
}
}, [tags]);
const setCurrentValue = useCallback((currentTags: TagItem[]) => {
@ -74,20 +78,22 @@ const Prompt = memo<PromptProps>(({ type }) => {
const textarea: HTMLTextAreaElement | any = get_uiCurrentTabContent().querySelector(id);
if (textarea) textarea.value = currentTags.map((t) => t.text).join(', ');
updateInput(textarea);
} catch {}
} catch (error) {
console.log(error);
}
}, []);
return (
<View>
<TagList setTags={setTags} setValue={setCurrentValue} tags={tags} type={type} />
<BtnGroup>
<Btn onClick={getValue} title="Load Prompt">
<ButtonGroup>
<Button onClick={getValue} title="Load Prompt">
🔄
</Btn>
<Btn onClick={setValue} title="Set Prompt">
</Button>
<Button onClick={setValue} title="Set Prompt">
</Btn>
</BtnGroup>
</Button>
</ButtonGroup>
</View>
);
});

View File

@ -170,8 +170,8 @@ interface TagListProps {
const TagList = memo<TagListProps>(({tags, setTags, type, setValue}) => {
const handleDelete = useCallback(
(i: number) => {
const newTags = tags.filter((tag, index) => index !== i);
(index_: number) => {
const newTags = tags.filter((tag, index) => index !== index_);
setTags(newTags);
setValue(newTags);
},
@ -188,9 +188,9 @@ const TagList = memo<TagListProps>(({ tags, setTags, type, setValue }) => {
);
const handleDrag = useCallback(
(tag: TagItem, currPos: number, newPos: number) => {
const newTags = tags.slice();
newTags.splice(currPos, 1);
(tag: TagItem, currentPos: number, newPos: number) => {
const newTags = [...tags];
newTags.splice(currentPos, 1);
newTags.splice(newPos, 0, genTagType(tag));
setTags(newTags);
setValue(newTags);
@ -199,9 +199,9 @@ const TagList = memo<TagListProps>(({ tags, setTags, type, setValue }) => {
);
const handleTagUpdate = useCallback(
(i: number, tag: TagItem) => {
(index: number, tag: TagItem) => {
const newTags = [...tags];
newTags[i] = genTagType(tag);
newTags[index] = genTagType(tag);
setTags(newTags);
setValue(newTags);
},

View File

@ -23,12 +23,12 @@ export const formatPrompt = (value: string) => {
const textArray = Converter.convertStr2Array(text).map((item) => {
if (item.includes('<')) return item;
const newItem = item
.replace(/\s+/g, ' ')
.replace(/|\.\|。/g, ',')
.replace(/“||”|"|\/'/g, '')
.replace(/, /g, ',')
.replace(/,,/g, ',')
.replace(/,/g, ', ');
.replaceAll(/\s+/g, ' ')
.replaceAll(/|\.\|。/g, ',')
.replaceAll(/“||”|"|\/'/g, '')
.replaceAll(', ', ',')
.replaceAll(',,', ',')
.replaceAll(',', ', ');
return Converter.convertStr2Array(newItem).join(', ');
});
return textArray.map((tag) => genTagType({id: tag, text: tag}));
@ -43,6 +43,6 @@ const genSuggestions = (array: string[]) =>
});
export const suggestions = {
positive: genSuggestions(positiveData),
negative: genSuggestions(negativeData),
positive: genSuggestions(positiveData),
};

View File

@ -3,7 +3,7 @@ import { useEffect, useState } from 'react';
function checkIsDarkMode() {
try {
return window.matchMedia('(prefers-color-scheme: dark)').matches;
} catch (err) {
} catch {
return false;
}
}

View File

@ -48,28 +48,28 @@ const App = memo(() => {
const {mobile} = useResponsive();
const [loading, setLoading] = useState(true);
const [extraLoading, setExtraLoading] = useState(true);
const sidebarRef: any = useRef<HTMLElement>();
const mainRef: any = useRef<HTMLElement>();
const txt2imgExtraNetworkSidebarRef: any = useRef<HTMLElement>();
const img2imgExtraNetworkSidebarRef: any = useRef<HTMLElement>();
const sidebarReference: any = useRef<HTMLElement>();
const mainReference: any = useRef<HTMLElement>();
const txt2imgExtraNetworkSidebarReference: any = useRef<HTMLElement>();
const img2imgExtraNetworkSidebarReference: any = useRef<HTMLElement>();
useEffect(() => {
onUiLoaded(() => {
// Content
const main = gradioApp().querySelector('.app');
if (main) mainRef.current?.appendChild(main);
if (main) mainReference.current?.append(main);
if (!mobile) dragablePanel();
// Sidebar
const sidebar = gradioApp().querySelector('#quicksettings');
if (sidebar) sidebarRef.current?.appendChild(sidebar);
if (sidebar) sidebarReference.current?.append(sidebar);
// ExtraNetworkSidebar
if (setting.enableExtraNetworkSidebar) {
const txt2imgExtraNetworks = gradioApp().querySelector('div#txt2img_extra_networks');
const img2imgExtraNetworks = gradioApp().querySelector('div#img2img_extra_networks');
if (txt2imgExtraNetworks && img2imgExtraNetworks) {
txt2imgExtraNetworkSidebarRef.current?.appendChild(txt2imgExtraNetworks);
img2imgExtraNetworkSidebarRef.current?.appendChild(img2imgExtraNetworks);
txt2imgExtraNetworkSidebarReference.current?.append(txt2imgExtraNetworks);
img2imgExtraNetworkSidebarReference.current?.append(img2imgExtraNetworks);
}
}
@ -91,20 +91,22 @@ const App = memo(() => {
return;
}
setTimeout(() => {
const t2iBtn: any = document.querySelector('#txt2img_extra_refresh');
const i2iBtn: any = document.querySelector('#img2img_extra_refresh');
t2iBtn.click();
i2iBtn.click();
const t2indexButton: any = document.querySelector('#txt2img_extra_refresh');
const index2indexButton: any = document.querySelector('#img2img_extra_refresh');
t2indexButton.click();
index2indexButton.click();
setExtraLoading(false);
try {
const civitaiBtn = document.querySelectorAll(
const civitaiButton = document.querySelectorAll(
'button[title="Refresh Civitai Helper\'s additional buttons"]',
);
if (civitaiBtn) {
civitaiBtn.forEach((btn: any) => (btn.onclick = civitaiHelperFix));
if (civitaiButton) {
civitaiButton.forEach((button: any) => (button.onclick = civitaiHelperFix));
}
civitaiHelperFix();
} catch {}
} catch (error) {
console.log(error);
}
}, 2000);
}
}, [loading]);
@ -125,7 +127,7 @@ const App = memo(() => {
<Spin size="small" />
</LoadingBox>
)}
<div id="sidebar" ref={sidebarRef} style={loading ? { display: 'none' } : {}} />
<div id="sidebar" ref={sidebarReference} style={loading ? {display: 'none'} : {}} />
</Sidebar>
<Content loading={loading}>
{loading && (
@ -133,7 +135,7 @@ const App = memo(() => {
<Spin size="large" tip="Loading" />
</LoadingBox>
)}
<div id="content" ref={mainRef} style={loading ? { display: 'none' } : {}} />
<div id="content" ref={mainReference} style={loading ? {display: 'none'} : {}} />
</Content>
{setting?.enableExtraNetworkSidebar && (
<ExtraNetworkSidebar>
@ -145,12 +147,12 @@ const App = memo(() => {
<div style={extraLoading ? {display: 'none'} : {}}>
<div
id="txt2img-extra-netwrok-sidebar"
ref={txt2imgExtraNetworkSidebarRef}
style={currentTab !== 'tab_img2img' ? {} : { display: 'none' }}
ref={txt2imgExtraNetworkSidebarReference}
style={currentTab === 'tab_img2img' ? {display: 'none'} : {}}
/>
<div
id="img2img-extra-netwrok-sidebar"
ref={img2imgExtraNetworkSidebarRef}
ref={img2imgExtraNetworkSidebarReference}
style={currentTab === 'tab_img2img' ? {} : {display: 'none'}}
/>
</div>

View File

@ -78,4 +78,4 @@ onUiLoaded(() => {
promptBracketChecker();
});
export default () => null;
export default () => false;

View File

@ -7,11 +7,11 @@ const MODEL_TYPE_LIST: ['textual_inversion', 'hypernetworks', 'checkpoints', 'lo
'lycoris',
];
const MODEL_TYPE = {
textual_inversion: 'ti',
hypernetworks: 'hyper',
checkpoints: 'ckp',
hypernetworks: 'hyper',
lora: 'lora',
lycoris: 'lycoris',
textual_inversion: 'ti',
};
const CARDID_SUFFIX = 'cards';
@ -23,17 +23,17 @@ const BTN_THUMB_DISPLAY = 'inline';
const BTN_THUMB_POS = 'static';
const BTN_THUMB_BACKGROUND_IMAGE = 'none';
const BTN_THUMB_BACKGROUND = 'rgba(0, 0, 0, 0.8)';
const CH_BTN_TXTS = ['🌐', '💡', '🏷️'];
const CH_BTN_TXTS = new Set(['🌐', '💡', '🏷️']);
const styleBtn = (node: HTMLElement, isThumbMode: boolean) => {
if (!isThumbMode) {
node.style.fontSize = BTN_FONT_SIZE;
node.style.margin = BTN_MARGIN;
} else {
const styleButton = (node: HTMLElement, isThumbMode: boolean) => {
if (isThumbMode) {
node.style.display = BTN_THUMB_DISPLAY;
node.style.fontSize = BTN_THUMB_FONT_SIZE;
node.style.position = BTN_THUMB_POS;
node.style.backgroundImage = BTN_THUMB_BACKGROUND_IMAGE;
} else {
node.style.fontSize = BTN_FONT_SIZE;
node.style.margin = BTN_MARGIN;
}
};
@ -46,37 +46,37 @@ const updateCardForCivitai = () => {
const chAlwaysDisplayCkb = gradioApp().querySelector(
'#ch_always_display_ckb input',
) as HTMLInputElement;
const chShowBtnOnThumbCkb = gradioApp().querySelector(
const chShowButtonOnThumbCkb = gradioApp().querySelector(
'#ch_show_btn_on_thumb_ckb input',
) as HTMLInputElement;
const chAlwaysDisplay = chAlwaysDisplayCkb?.checked || false;
const chShowBtnOnThumb = chShowBtnOnThumbCkb?.checked || false;
const chShowButtonOnThumb = chShowButtonOnThumbCkb?.checked || false;
// Change all "replace preview" into an icon
let extraNetworkId = '';
let extraNetworkNode: any = null;
let metadataButton: any = null;
let additionalNode: any = null;
let replacePreviewBtn: any = null;
let ulNode: any = null;
let searchTermNode: any = null;
let extraNetworkNode: any;
let metadataButton: any;
let additionalNode: any;
let replacePreviewButton: any;
let ulNode: any;
let searchTermNode: any;
let searchTerm = '';
let modelType = '';
let cards = null;
let cards;
let needToAddButtons = false;
let isThumbMode = false;
// Get current tab
TAB_PREFIX_LIST.forEach((activeTabType) => {
MODEL_TYPE_LIST.forEach((jsModelType) => {
for (const activeTabType of TAB_PREFIX_LIST) {
for (const jsModelType of MODEL_TYPE_LIST) {
modelType = MODEL_TYPE[jsModelType];
// Get model_type for python side
extraNetworkId = `${activeTabType}_${jsModelType}_${CARDID_SUFFIX}`;
extraNetworkNode = gradioApp().getElementById(extraNetworkId);
extraNetworkNode = gradioApp().querySelector(`#${extraNetworkId}`);
// Check if extra network node exists
if (extraNetworkNode === null) return;
if (extraNetworkNode === undefined) continue;
// Check if extr network is under thumbnail mode
isThumbMode = false;
@ -85,7 +85,7 @@ const updateCardForCivitai = () => {
// Get all card nodes
cards = extraNetworkNode.querySelectorAll('.card');
for (const card of cards) {
if (card.querySelectorAll('.actions .additional a').length > 2) return;
if (card.querySelectorAll('.actions .additional a').length > 2) continue;
// Metadata_buttoncard
metadataButton = card.querySelector('.metadata-button');
// Additional node
@ -93,17 +93,17 @@ const updateCardForCivitai = () => {
// Get ul node, which is the parent of all buttons
ulNode = card.querySelector('.actions .additional ul');
// Replace preview text button
replacePreviewBtn = card.querySelector('.actions .additional a');
replacePreviewButton = card.querySelector('.actions .additional a');
// Check thumb mode
if (isThumbMode && additionalNode) {
additionalNode.style.display = null;
additionalNode.style.display = undefined;
if (chShowBtnOnThumb) {
if (chShowButtonOnThumb) {
ulNode.style.background = BTN_THUMB_BACKGROUND;
} else {
// Reset
ulNode.style.background = null;
ulNode.style.background = undefined;
// Remove existed buttons
if (ulNode) {
// Find all .a child nodes
@ -111,58 +111,58 @@ const updateCardForCivitai = () => {
for (const atag of atags) {
// Reset display
atag.style.display = null;
atag.style.display = undefined;
// Remove extension's button
if (CH_BTN_TXTS.indexOf(atag.innerHTML) >= 0) {
if (CH_BTN_TXTS.has(atag.innerHTML)) {
// Need to remove
ulNode.removeChild(atag);
atag.remove();
} else {
// Do not remove, just reset
atag.innerHTML = replacePreviewText;
atag.style.display = null;
atag.style.fontSize = null;
atag.style.position = null;
atag.style.backgroundImage = null;
atag.style.display = undefined;
atag.style.fontSize = undefined;
atag.style.position = undefined;
atag.style.backgroundImage = undefined;
}
}
// Also remove br tag in ul
const brtag = ulNode.querySelector('br');
if (brtag) ulNode.removeChild(brtag);
if (brtag) brtag.remove();
}
// Just reset and remove nodes, do nothing else
return;
continue;
}
} else {
// Full preview mode
additionalNode.style.display = chAlwaysDisplay ? 'block' : null;
additionalNode.style.display = chAlwaysDisplay ? 'block' : undefined;
// Remove br tag
const brtag = ulNode.querySelector('br');
if (brtag) ulNode.removeChild(brtag);
if (brtag) brtag.remove();
}
// Change replace preview text button into icon
if (replacePreviewBtn?.innerHTML !== '🖼️') {
if (replacePreviewButton?.innerHTML !== '🖼️') {
needToAddButtons = true;
replacePreviewBtn.innerHTML = '🖼️';
styleBtn(replacePreviewBtn, isThumbMode);
replacePreviewButton.innerHTML = '🖼️';
styleButton(replacePreviewButton, isThumbMode);
}
if (!needToAddButtons) return;
if (!needToAddButtons) continue;
// Search_term node
// Search_term = subfolder path + model name + ext
searchTermNode = card.querySelector('.actions .additional .search_term');
if (!searchTermNode) return;
// Get search_term
searchTerm = searchTermNode.innerHTML;
if (!searchTerm) return;
if (!searchTerm) continue;
// Then we need to add 3 buttons to each ul node:
const openUrlNode = document.createElement('a');
openUrlNode.href = '#';
openUrlNode.innerHTML = '🌐';
styleBtn(openUrlNode, isThumbMode);
styleButton(openUrlNode, isThumbMode);
openUrlNode.title = "Open this model's civitai url";
openUrlNode.setAttribute(
'onclick',
@ -172,7 +172,7 @@ const updateCardForCivitai = () => {
const addTriggerWordsNode = document.createElement('a');
addTriggerWordsNode.href = '#';
addTriggerWordsNode.innerHTML = '💡';
styleBtn(addTriggerWordsNode, isThumbMode);
styleButton(addTriggerWordsNode, isThumbMode);
addTriggerWordsNode.title = 'Add trigger words to prompt';
addTriggerWordsNode.setAttribute(
'onclick',
@ -182,7 +182,7 @@ const updateCardForCivitai = () => {
const usePreviewPromptNode = document.createElement('a');
usePreviewPromptNode.href = '#';
usePreviewPromptNode.innerHTML = '🏷️';
styleBtn(usePreviewPromptNode, isThumbMode);
styleButton(usePreviewPromptNode, isThumbMode);
usePreviewPromptNode.title = 'Use prompt from preview image';
usePreviewPromptNode.setAttribute(
'onclick',
@ -190,14 +190,14 @@ const updateCardForCivitai = () => {
);
// Add to card
ulNode.appendChild(openUrlNode);
ulNode.append(openUrlNode);
// Add br if metadata_button exists
if (isThumbMode && metadataButton) ulNode.appendChild(document.createElement('br'));
ulNode.appendChild(addTriggerWordsNode);
ulNode.appendChild(usePreviewPromptNode);
if (isThumbMode && metadataButton) ulNode.append(document.createElement('br'));
ulNode.append(addTriggerWordsNode);
ulNode.append(usePreviewPromptNode);
}
}
}
});
});
};
export default () => {

View File

@ -1,7 +1,7 @@
const MIN_WIDTH = 240;
const addDraggable = (tabId: string) => {
const settings = document.getElementById(`${tabId}_settings`);
const settings: any = document.querySelector(`#${tabId}_settings`);
const checkDraggableLine = document.querySelector(`#tab_${tabId} .draggable-line`);
if (!settings || checkDraggableLine) return;
@ -10,12 +10,12 @@ const addDraggable = (tabId: string) => {
const lineWrapper = document.createElement('div');
lineWrapper.classList.add('draggable-line');
settings.insertAdjacentElement('afterend', lineWrapper);
settings.after(lineWrapper);
const container: HTMLElement | any = settings.parentElement;
container.classList.add('draggable-container');
const results = document.getElementById(`${tabId}_results`);
const results: any = document.querySelector(`#${tabId}_results`);
if (!results) return;
results.style.minWidth = `${MIN_WIDTH}px`;

View File

@ -1,138 +1,27 @@
/**
*
*/
export class Converter {
export const Converter = {
/**
*
* @param value
* @returns
*
* @param type -
*/
static round(value: number): number {
return Math.round(value * 10000) / 10000;
}
/**
*
* @param srt
* @returns
*/
static convertStr(srt: string): string {
return srt.replace(//g, ':').replace(//g, '(').replace(//g, ')');
}
/**
*
* @param str
* @returns
*/
static convertStr2Array(str: string): string[] {
// 匹配各种括号中的内容,包括括号本身
const bracketRegex = /([()<>[\]])/g;
/**
*
* @param str
* @returns
*/
const splitByBracket = (str: string): string[] => {
const arr: string[] = [];
let start = 0;
let depth = 0;
let match;
while ((match = bracketRegex.exec(str)) !== null) {
if (depth === 0 && match.index > start) {
arr.push(str.substring(start, match.index));
start = match.index;
}
if (match[0] === '(' || match[0] === '<' || match[0] === '[') {
depth++;
} else if (match[0] === ')' || match[0] === '>' || match[0] === ']') {
depth--;
}
if (depth === 0) {
arr.push(str.substring(start, match.index + 1));
start = match.index + 1;
}
}
if (start < str.length) {
arr.push(str.substring(start));
}
return arr;
};
/**
*
* @param str
* @returns
*/
const splitByComma = (str: string): string[] => {
const arr: string[] = [];
let start = 0;
let inBracket = false;
for (let i = 0; i < str.length; i++) {
if (str[i] === ',' && !inBracket) {
arr.push(str.substring(start, i).trim());
start = i + 1;
} else if (str[i].match(bracketRegex)) {
inBracket = !inBracket;
}
}
arr.push(str.substring(start).trim());
return arr;
};
/**
*
* @param str
* @returns
*/
const cleanStr = (str: string): string[] => {
let arr = splitByBracket(str);
arr = arr.flatMap((s) => splitByComma(s));
return arr.filter((s) => s !== '');
};
return cleanStr(str)
.filter((item) => {
const pattern = /^[,\s ]+$/;
return !pattern.test(item);
})
.filter(Boolean)
.sort((a, b) => {
return a.includes('<') && !b.includes('<')
? 1
: b.includes('<') && !a.includes('<')
? -1
: 0;
});
}
/**
*
* @param array
* @returns
*/
static convertArray2Str(array: string[]): string {
const newArray = array.map((item) => {
if (item.includes('<')) return item;
const newItem = item
.replace(/\s+/g, ' ')
.replace(/|\.\|。/g, ',')
.replace(/“||”|"|\/'/g, '')
.replace(/, /g, ',')
.replace(/,,/g, ',')
.replace(/,/g, ', ');
return Converter.convertStr2Array(newItem).join(', ');
});
return newArray.join(', ');
}
addPromptButton(type: string): void {
const generateButton: HTMLElement | null = gradioApp().querySelector(`#${type}_generate`);
const actionsColumn: HTMLElement | null = gradioApp().querySelector(`#${type}_style_create`);
const nai2local: HTMLElement | null = gradioApp().querySelector(`#${type}_formatconvert`);
if (!generateButton || !actionsColumn || nai2local) return;
const convertButton: HTMLElement = Converter.createButton(`${type}_formatconvert`, '🪄', () =>
Converter.onClickConvert(type));
actionsColumn.parentNode?.append(convertButton);
},
/**
*
* @param input
* @returns
*/
static convert(input: string): string {
convert(input: string): string {
const re_attention = /\{|\[|\}|\]|[^{}[\]]+/gmu;
let text = Converter.convertStr(input);
@ -145,8 +34,8 @@ export class Converter {
const square_bracket_multiplier = 1 / 1.05;
const brackets: Record<string, { multiplier: number; stack: number[] }> = {
'{': { stack: [], multiplier: curly_bracket_multiplier },
'[': { stack: [], multiplier: square_bracket_multiplier },
'[': {multiplier: square_bracket_multiplier, stack: []},
'{': {multiplier: curly_bracket_multiplier, stack: []},
};
/**
@ -171,52 +60,186 @@ export class Converter {
multiply_range(bracket.stack.pop()!, bracket.multiplier);
}
} else {
res.push([word, 1.0]);
res.push([word, 1]);
}
}
Object.keys(brackets).forEach((bracketType) => {
brackets[bracketType].stack.forEach((pos) => {
for (const bracketType of Object.keys(brackets)) {
for (const pos of brackets[bracketType].stack) {
multiply_range(pos, brackets[bracketType].multiplier);
});
});
}
}
if (res.length === 0) {
res = [['', 1.0]];
res = [['', 1]];
}
let i = 0;
while (i + 1 < res.length) {
if (res[i][1] === res[i + 1][1]) {
res[i][0] += res[i + 1][0];
res.splice(i + 1, 1);
let index = 0;
while (index + 1 < res.length) {
if (res[index][1] === res[index + 1][1]) {
res[index][0] += res[index + 1][0];
res.splice(index + 1, 1);
} else {
i += 1;
index += 1;
}
}
let result = '';
for (const [word, value] of res) {
result += value === 1.0 ? word : `(${word}:${value.toString()})`;
result += value === 1 ? word : `(${word}:${value.toString()})`;
}
return result;
},
/**
*
* @param array
* @returns
*/
convertArray2Str(array: string[]): string {
const newArray = array.map((item) => {
if (item.includes('<')) return item;
const newItem = item
.replaceAll(/\s+/g, ' ')
.replaceAll(/|\.\|。/g, ',')
.replaceAll(/“||”|"|\/'/g, '')
.replaceAll(', ', ',')
.replaceAll(',,', ',')
.replaceAll(',', ', ');
return Converter.convertStr2Array(newItem).join(', ');
});
return newArray.join(', ');
},
/**
*
* @param srt
* @returns
*/
convertStr(srt: string): string {
return srt.replaceAll('', ':').replaceAll('', '(').replaceAll('', ')');
},
/**
*
* @param str
* @returns
*/
convertStr2Array(string_: string): string[] {
// 匹配各种括号中的内容,包括括号本身
const bracketRegex = /([()<>[\]])/g;
/**
*
* @param str
* @returns
*/
const splitByBracket = (string__: string): string[] => {
const array: string[] = [];
let start = 0;
let depth = 0;
let match;
while ((match = bracketRegex.exec(string__)) !== null) {
if (depth === 0 && match.index > start) {
array.push(string__.slice(start, match.index));
start = match.index;
}
if (match[0] === '(' || match[0] === '<' || match[0] === '[') {
depth++;
} else if (match[0] === ')' || match[0] === '>' || match[0] === ']') {
depth--;
}
if (depth === 0) {
array.push(string__.slice(start, match.index + 1));
start = match.index + 1;
}
}
if (start < string__.length) {
array.push(string__.slice(Math.max(0, start)));
}
return array;
};
/**
*
* @param str
* @returns
*/
const splitByComma = (string__: string): string[] => {
const array: string[] = [];
let start = 0;
let inBracket = false;
for (let index = 0; index < string__.length; index++) {
if (string__[index] === ',' && !inBracket) {
array.push(string__.slice(start, index).trim());
start = index + 1;
} else if (bracketRegex.test(string__[index])) {
inBracket = !inBracket;
}
}
array.push(string__.slice(Math.max(0, start)).trim());
return array;
};
/**
*
* @param str
* @returns
*/
const cleanString = (string__: string): string[] => {
let array = splitByBracket(string__);
array = array.flatMap((s) => splitByComma(s));
return array.filter((s) => s !== '');
};
return cleanString(string_)
.filter((item) => {
const pattern = /^[\s,]+$/;
return !pattern.test(item);
})
.filter(Boolean)
.sort((a, b) => {
return a.includes('<') && !b.includes('<') ?
1 :
b.includes('<') && !a.includes('<') ?
-1 :
0;
});
},
/**
*
* @param id id
* @param innerHTML
* @param onClick
* @returns
*/
createButton(id: string, innerHTML: string, onClick: () => void): HTMLButtonElement {
const button = document.createElement('button');
button.id = id;
button.type = 'button';
button.innerHTML = innerHTML;
button.title = 'Format prompt~🪄';
button.className = 'lg secondary gradio-button tool svelte-1ipelgc';
button.addEventListener('click', onClick);
return button;
},
/**
* input
* @param target
*/
static dispatchInputEvent(target: EventTarget) {
dispatchInputEvent(target: EventTarget) {
let inputEvent = new Event('input');
Object.defineProperty(inputEvent, 'target', {value: target});
target.dispatchEvent(inputEvent);
}
},
/**
*
* @param type
*/
static onClickConvert(type: string) {
onClickConvert(type: string) {
const default_prompt = '';
const default_negative = '';
@ -232,47 +255,23 @@ export class Converter {
) as HTMLTextAreaElement;
const negResult = Converter.convert(negprompt.value);
negprompt.value =
negResult.match(/^lowres,/) === null
? negResult.length === 0
? default_negative
: default_negative + negResult
: negResult;
negResult.match(/^lowres,/) === null ?
negResult.length === 0 ?
default_negative :
default_negative + negResult :
negResult;
Converter.dispatchInputEvent(negprompt);
}
},
/**
*
* @param id id
* @param innerHTML
* @param onClick
* @returns
*
* @param value
* @returns
*/
static createButton(id: string, innerHTML: string, onClick: () => void): HTMLButtonElement {
const button = document.createElement('button');
button.id = id;
button.type = 'button';
button.innerHTML = innerHTML;
button.title = 'Format prompt~🪄';
button.className = 'lg secondary gradio-button tool svelte-1ipelgc';
button.addEventListener('click', onClick);
return button;
}
/**
*
* @param type -
*/
static addPromptButton(type: string): void {
const generateBtn: HTMLElement | null = gradioApp().querySelector(`#${type}_generate`);
const actionsColumn: HTMLElement | null = gradioApp().querySelector(`#${type}_style_create`);
const nai2local: HTMLElement | null = gradioApp().querySelector(`#${type}_formatconvert`);
if (!generateBtn || !actionsColumn || nai2local) return;
const convertBtn: HTMLElement = Converter.createButton(`${type}_formatconvert`, '🪄', () =>
Converter.onClickConvert(type),
);
actionsColumn.parentNode?.append(convertBtn);
}
}
round(value: number): number {
return Math.round(value * 10_000) / 10_000;
},
};
export default () => {
Converter.addPromptButton('txt2img');

View File

@ -13,16 +13,16 @@ class BracketChecker {
this.counterElt = counterElt;
this.errorStrings = [
{
regex: '\\(',
error: '(...) - Different number of opening and closing parentheses detected.\n',
regex: '\\(',
},
{
regex: '\\[',
error: '[...] - Different number of opening and closing square brackets detected.\n',
regex: '\\[',
},
{
regex: '\\{',
error: '{...} - Different number of opening and closing curly brackets detected.\n',
regex: '\\{',
},
];
}
@ -32,21 +32,21 @@ class BracketChecker {
*/
public check = (): void => {
let title = '';
this.errorStrings.forEach(({ regex, error }) => {
for (const {regex, error} of this.errorStrings) {
const openMatches = (this.textArea.value.match(new RegExp(regex, 'g')) || []).length;
const closeMatches = (
this.textArea.value.match(
new RegExp(regex.replace(/\(/g, ')').replace(/\[/g, ']').replace(/\{/g, '}'), 'g'),
new RegExp(regex.replaceAll('(', ')').replaceAll('[', ']').replaceAll('{', '}'), 'g'),
) || []
).length;
if (openMatches !== closeMatches) {
if (openMatches === closeMatches) {
title = this.counterElt.title.replace(error, '');
} else {
if (!this.counterElt.title.includes(error)) {
title += error;
}
} else {
title = this.counterElt.title.replace(error, '');
}
});
}
this.counterElt.title = title;
this.counterElt.classList.toggle('error', !!title);
};
@ -61,15 +61,15 @@ const setupBracketChecking = (idPrompt: string, idCounter: string): void => {
const textarea = gradioApp().querySelector(
`#${idPrompt} > label > textarea`,
) as HTMLTextAreaElement;
const counter = gradioApp().getElementById(idCounter) as HTMLElement;
const counter = gradioApp().querySelector(`#${idCounter}`) as HTMLElement;
const bracketChecker = new BracketChecker(textarea, counter);
textarea.addEventListener('input', bracketChecker.check);
};
export default () => {
const elements = ['txt2img', 'txt2img_neg', 'img2img', 'img2img_neg'];
elements.forEach((prompt) => {
for (const prompt of elements) {
setupBracketChecking(`${prompt}_prompt`, `${prompt}_token_counter`);
setupBracketChecking(`${prompt}_prompt`, `${prompt}_negative_token_counter`);
});
}
};

View File

@ -1,14 +1,14 @@
const replaceIcon = (button: HTMLButtonElement, emoji: string[], svg: string) => {
if (!button?.textContent) return;
emoji.forEach((e) => {
for (const e of emoji) {
if (button?.textContent?.includes(e)) {
button.innerHTML = `<span role="img" class="anticon anticon-replace" aria-label={button.textContent}><svg viewBox="64 64 896 896" focusable="false" width="1em" height="1em" fill="currentColor" aria-hidden="true">${svg}</svg></span>`;
}
});
}
};
export default () => {
document.querySelectorAll('button').forEach((button) => {
for (const button of document.querySelectorAll('button')) {
replaceIcon(
button,
['📂'],
@ -69,5 +69,5 @@ export default () => {
['⇅'],
'<path d="M847.9 592H152c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h605.2L612.9 851c-4.1 5.2-.4 13 6.3 13h72.5c4.9 0 9.5-2.2 12.6-6.1l168.8-214.1c16.5-21 1.6-51.8-25.2-51.8zM872 356H266.8l144.3-183c4.1-5.2.4-13-6.3-13h-72.5c-4.9 0-9.5 2.2-12.6 6.1L150.9 380.2c-16.5 21-1.6 51.8 25.1 51.8h696c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8z"></path>',
);
});
}
};

View File

@ -5,5 +5,5 @@ export default () => {
favicon.type = 'image/svg+xml';
favicon.href =
'https://gw.alipayobjects.com/zos/bmw-prod/51a51720-8a30-4430-b6c9-be5712364f04.svg';
document.getElementsByTagName('head')[0].appendChild(favicon);
document.querySelectorAll('head')[0].append(favicon);
};

View File

@ -17,15 +17,15 @@ export interface WebuiSetting {
}
export const defaultSetting: WebuiSetting = {
enableExtraNetworkSidebar: true,
extraNetworkCardSize: 86,
extraNetworkFixedMode: 'fixed',
extraNetworkSidebarExpand: true,
extraNetworkSidebarWidth: 340,
promotTextarea: 'scroll',
sidebarExpand: true,
sidebarFixedMode: 'fixed',
sidebarWidth: 280,
enableExtraNetworkSidebar: true,
extraNetworkSidebarExpand: true,
extraNetworkFixedMode: 'fixed',
extraNetworkSidebarWidth: 340,
extraNetworkCardSize: 86,
svgIcon: false,
};
export interface AppState {
@ -40,15 +40,9 @@ export interface AppState {
}
export const useAppStore = create<AppState>()(
devtools((set, get) => ({
themeMode: 'light',
setting: defaultSetting,
currentTab: 'tab_txt2img',
setCurrentTab: () => {
const currentTab = get_uiCurrentTabContent().id;
if (currentTab !== get().currentTab) set({ currentTab }, false, 'setCurrentTab');
},
onSetThemeMode: (themeMode) => {
set(() => ({ themeMode }), false, 'onSetThemeMode');
onInit: () => {
get().onLoadSetting();
},
onLoadSetting: () => {
let setting: any = localStorage.getItem(SETTING_KEY);
@ -64,8 +58,14 @@ export const useAppStore = create<AppState>()(
localStorage.setItem(SETTING_KEY, JSON.stringify(setting));
set(() => ({setting}), false, 'onSetSetting');
},
onInit: () => {
get().onLoadSetting();
onSetThemeMode: (themeMode) => {
set(() => ({themeMode}), false, 'onSetThemeMode');
},
setCurrentTab: () => {
const currentTab = get_uiCurrentTabContent().id;
if (currentTab !== get().currentTab) set({currentTab}, false, 'setCurrentTab');
},
setting: defaultSetting,
themeMode: 'light',
})),
);

View File

@ -21,6 +21,12 @@
padding: 6px;
}
.head {
> label {
overflow: hidden;
}
}
.wrap.svelte-1p9xokt.svelte-1p9xokt.svelte-1p9xokt {
gap: 8px !important;
@ -35,9 +41,9 @@
background: transparent;
}
[id$='_results'],
#tab_image_browser,
#tab_dreambooth_interface,
[id$='_results'] {
#tab_dreambooth_interface {
.block.gradio-accordion.svelte-mppz8v.padded {
display: flex;
flex-direction: column;
@ -76,9 +82,3 @@
div.svelte-1oo81b7 > *:not(.absolute) {
border-radius: var(--border-radius) !important;
}
.head {
> label {
overflow: hidden;
}
}

View File

@ -1,21 +1,14 @@
#txt2img_extra_networks,
#img2img_extra_networks {
.tabitem.gradio-tabitem.svelte-19hvt5v {
padding: 0;
.extra-network-thumbs {
.name {
overflow: hidden;
display: block;
font-size: 12px !important;
text-overflow: ellipsis;
white-space: nowrap;
background: transparent;
}
.search {
box-sizing: border-box;
width: var(--fill-available);
max-width: var(--fill-available);
max-height: 36px !important;
padding: 8px;
}
button {
height: 32px !important;
}
}
.extra-networks {
@ -140,15 +133,22 @@
}
}
.extra-network-thumbs {
.name {
overflow: hidden;
display: block;
font-size: 12px !important;
text-overflow: ellipsis;
white-space: nowrap;
#txt2img_extra_networks,
#img2img_extra_networks {
.tabitem.gradio-tabitem.svelte-19hvt5v {
padding: 0;
background: transparent;
}
.search {
box-sizing: border-box;
width: var(--fill-available);
max-width: var(--fill-available);
max-height: 36px !important;
padding: 8px;
}
button {
height: 32px !important;
}
}

View File

@ -1,5 +1,12 @@
#tab_txt2img,
#tab_img2img {
[id$='_settings'] {
div.svelte-15lo0d8 > *,
div.svelte-15lo0d8 > .form > * {
flex: 1;
}
}
#txt2img_settings,
#img2img_settings {
.block.gradio-checkbox {
@ -34,6 +41,10 @@
border-radius: var(--border-radius) !important;
}
.image-buttons button {
min-width: min(160px, 100%) !important;
}
[id$='2img_tools'] > div {
display: flex;
justify-content: center;
@ -43,10 +54,6 @@
}
}
.image-buttons button {
min-width: min(160px, 100%) !important;
}
#img2img_label_copy_to_img2img {
display: none;
}
@ -58,13 +65,6 @@
gap: 8px !important;
}
[id$='_settings'] {
div.svelte-15lo0d8 > *,
div.svelte-15lo0d8 > .form > * {
flex: 1;
}
}
#script_list {
margin-top: 0 !important;
margin-bottom: var(--size-ms) !important;

6
src/types/global.d.ts vendored Normal file
View File

@ -0,0 +1,6 @@
import {Theme as AntdStyleTheme} from 'antd-style';
declare module 'styled-components' {
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface DefaultTheme extends AntdStyleTheme {}
}

View File

@ -1,6 +1,11 @@
import React from 'react';
import {type HTMLAttributes} from 'react';
export type DivProps = React.DetailedHTMLProps<
React.HTMLAttributes<HTMLDivElement>,
HTMLDivElement
>;
export type DivProps = HTMLAttributes<HTMLDivElement>;
export type SvgProps = HTMLAttributes<SVGSVGElement>;
export type ImgProps = HTMLAttributes<HTMLImageElement>;
export type InputProps = HTMLAttributes<HTMLInputElement>;
export type TextAreaProps = HTMLAttributes<HTMLTextAreaElement>;

12
src/types/webui.d.ts vendored
View File

@ -5,7 +5,7 @@ declare const all_gallery_buttons: () => Element[];
declare const selected_gallery_button: () => Element | null;
declare const selected_gallery_index: () => number;
declare const extract_image_from_gallery: (gallery: Element[]) => Element[];
declare const args_to_array: (args: IArguments) => any[];
declare const arguments_to_array: (arguments_: IArguments) => any[];
declare const switch_to_txt2img: () => any[];
declare const switch_to_img2img_tab: (no: number) => void;
declare const switch_to_img2img: () => any[];
@ -14,15 +14,15 @@ declare const switch_to_inpaint_sketch: () => any[];
declare const switch_to_inpaint: () => any[];
declare const switch_to_extras: () => any[];
declare const get_tab_index: (tabId: string) => number;
declare const create_tab_index_args: (tabId: string, args: any[]) => any[];
declare const create_tab_index_arguments: (tabId: string, arguments_: any[]) => any[];
declare const get_img2img_tab_index: () => any[];
declare const create_submit_args: (args: any[]) => any[];
declare const create_submit_arguments: (arguments_: any[]) => any[];
declare const showSubmitButtons: (tabname: string, show: boolean) => void;
declare const submit: () => any[];
declare const submit_img2img: () => any[];
declare const modelmerger: () => any[];
declare const ask_for_style_name: (
arg0: any,
argument0: any,
prompt_text: string,
negative_prompt_text: string,
) => [string, string, string];
@ -30,8 +30,8 @@ declare const confirm_clear_prompt: (prompt: string, negative_prompt: string) =>
declare const recalculatePromptTokens: (name: string) => void;
declare const recalculate_prompts_txt2img: () => any[];
declare const recalculate_prompts_img2img: () => any[];
declare const update_txt2img_tokens: (...args: any[]) => any;
declare const update_img2img_tokens: (...args: any[]) => any;
declare const update_txt2img_tokens: (...arguments_: any[]) => any;
declare const update_img2img_tokens: (...arguments_: any[]) => any;
declare const restart_reload: () => any[];
declare const updateInput: (target: Element) => void;
declare const selectCheckpoint: (name: string) => void;

File diff suppressed because one or more lines are too long

View File

@ -1,26 +1,19 @@
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",
"incremental": true,
"baseUrl": ".",
"declaration": true,
"downlevelIteration": true,
"esModuleInterop": true,
"jsx": "react-jsx",
"lib": ["dom", "dom.iterable", "esnext"],
"paths": {
"@/*": ["./src/*"]
}
},
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": true
},
"exclude": ["javascript"],
"extends": "./src/.umi/tsconfig.json",
"include": ["src"]
"include": ["src", "typings.d.ts", "*.ts"]
}