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

pull/137/head
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

@ -1,9 +1,9 @@
import { FloatButton } from 'antd';
import { type ReactNode, memo, useRef } from 'react';
import {FloatButton} from 'antd';
import {type ReactNode, memo, useRef} from 'react';
import styled from 'styled-components';
import { shallow } from 'zustand/shallow';
import {shallow} from 'zustand/shallow';
import { useAppStore } from '@/store';
import {useAppStore} from '@/store';
const ContentView = styled.div<{ isPromptResizable: boolean }>`
overflow-x: hidden;
@ -11,11 +11,11 @@ const ContentView = styled.div<{ isPromptResizable: boolean }>`
flex: 1;
[id$='2img_prompt'] textarea {
max-height: ${({ isPromptResizable }) => (isPromptResizable ? 'unset' : '84px')};
max-height: ${({isPromptResizable}) => (isPromptResizable ? 'unset' : '84px')};
}
[id$='2img_neg_prompt'] textarea {
max-height: ${({ isPromptResizable }) => (isPromptResizable ? 'unset' : '84px')};
max-height: ${({isPromptResizable}) => (isPromptResizable ? 'unset' : '84px')};
}
`;
@ -24,16 +24,16 @@ interface ContentProps {
loading?: boolean;
}
const Content = memo<ContentProps>(({ children }) => {
const ref: any = useRef(null);
const [setting] = useAppStore((st) => [st.setting], shallow);
const Content = memo<ContentProps>(({children}) => {
const reference: any = useRef(null);
const [setting] = useAppStore((st) => [st.setting], shallow);
return (
<ContentView isPromptResizable={setting.promotTextarea === 'resizable'} ref={ref}>
{children}
<FloatButton.BackTop target={() => ref.current} />
</ContentView>
);
return (
<ContentView isPromptResizable={setting.promotTextarea === 'resizable'} ref={reference}>
{children}
<FloatButton.BackTop target={() => reference.current} />
</ContentView>
);
});
export default Content;

View File

@ -1,16 +1,16 @@
import { useHover } from 'ahooks';
import { ChevronDown, ChevronLeft, ChevronRight, ChevronUp } from 'lucide-react';
import type { Enable, NumberSize, Size } from 're-resizable';
import { HandleClassName, Resizable } from 're-resizable';
import { memo, useEffect, useMemo, useRef, useState } from 'react';
import { Center } from 'react-layout-kit';
import type { Props as RndProps } from 'react-rnd';
import {useHover} from 'ahooks';
import {ChevronDown, ChevronLeft, ChevronRight, ChevronUp} from 'lucide-react';
import type {Enable, NumberSize, Size} from 're-resizable';
import {HandleClassName, Resizable} from 're-resizable';
import {memo, useEffect, useMemo, useRef, useState} from 'react';
import {Center} from 'react-layout-kit';
import type {Props as RndProps} from 'react-rnd';
import useControlledState from 'use-merge-value';
import type { DivProps } from '@/types';
import type {DivProps} from '@/types';
import { useStyle } from './style';
import { revesePlacement } from './utils';
import {useStyle} from './style';
import {revesePlacement} from './utils';
const DEFAULT_HEIGHT = 180;
const DEFAULT_WIDTH = 280;
@ -38,186 +38,191 @@ export interface DraggablePanelProps extends DivProps {
}
const DraggablePanel = memo<DraggablePanelProps>(
({
pin = 'true',
mode = 'fixed',
children,
placement = 'right',
resize,
style,
size,
defaultSize: customizeDefaultSize,
minWidth,
minHeight,
onSizeChange,
onSizeDragging,
expandable = true,
expand,
defaultExpand = true,
onExpandChange,
className,
showHandlerWhenUnexpand,
destroyOnClose,
hanlderStyle,
}) => {
const ref = useRef(null);
const isHovering = useHover(ref);
const isVertical = placement === 'top' || placement === 'bottom';
({
pin = 'true',
mode = 'fixed',
children,
placement = 'right',
resize,
style,
size,
defaultSize: customizeDefaultSize,
minWidth,
minHeight,
onSizeChange,
onSizeDragging,
expandable = true,
expand,
defaultExpand = true,
onExpandChange,
className,
showHandlerWhenUnexpand,
destroyOnClose,
hanlderStyle,
}) => {
const reference = useRef(null);
const isHovering = useHover(reference);
const isVertical = placement === 'top' || placement === 'bottom';
const { styles, cx } = useStyle('draggable-panel');
const {styles, cx} = useStyle('draggable-panel');
const [isExpand, setIsExpand] = useControlledState(defaultExpand, {
value: expand,
onChange: onExpandChange,
});
const [isExpand, setIsExpand] = useControlledState(defaultExpand, {
onChange: onExpandChange,
value: expand,
});
useEffect(() => {
if (pin) return;
if (isHovering && !isExpand) {
setIsExpand(true);
} else if (!isHovering && isExpand) {
setIsExpand(false);
}
}, [pin, isHovering, isExpand]);
useEffect(() => {
if (pin) return;
if (isHovering && !isExpand) {
setIsExpand(true);
} else if (!isHovering && isExpand) {
setIsExpand(false);
}
}, [pin, isHovering, isExpand]);
const [showExpand, setShowExpand] = useState(true);
const [showExpand, setShowExpand] = useState(true);
const canResizing = resize !== false && isExpand;
const canResizing = resize !== false && isExpand;
const resizeHandleClassNames: HandleClassName = useMemo(() => {
if (!canResizing) return {};
const resizeHandleClassNames: HandleClassName = useMemo(() => {
if (!canResizing) return {};
return {
[revesePlacement(placement)]: styles[`${revesePlacement(placement)}Handle`],
};
}, [canResizing, placement]);
return {
[revesePlacement(placement)]: styles[`${revesePlacement(placement)}Handle`],
};
}, [canResizing, placement]);
const resizing = {
top: false,
bottom: false,
right: false,
left: false,
topRight: false,
bottomRight: false,
bottomLeft: false,
topLeft: false,
[revesePlacement(placement)]: true,
...(resize as Enable),
};
const defaultSize: Size = useMemo(() => {
if (isVertical)
return {
width: '100%',
height: DEFAULT_HEIGHT,
...customizeDefaultSize,
const resizing = {
bottom: false,
bottomLeft: false,
bottomRight: false,
left: false,
right: false,
top: false,
topLeft: false,
topRight: false,
[revesePlacement(placement)]: true,
...(resize as Enable),
};
return {
width: DEFAULT_WIDTH,
height: '100%',
...customizeDefaultSize,
};
}, [isVertical]);
const defaultSize: Size = useMemo(() => {
if (isVertical) {
return {
height: DEFAULT_HEIGHT,
width: '100%',
...customizeDefaultSize,
};
}
const sizeProps = isExpand
? {
minWidth: typeof minWidth === 'number' ? Math.max(minWidth, 0) : 280,
minHeight: typeof minHeight === 'number' ? Math.max(minHeight, 0) : undefined,
defaultSize,
size: size as Size,
}
: isVertical
? {
minHeight: 0,
size: { height: 0 },
}
: {
minWidth: 0,
size: { width: 0 },
};
return {
height: '100%',
width: DEFAULT_WIDTH,
...customizeDefaultSize,
};
}, [isVertical]);
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 };
}
}, [styles, placement]);
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 ?
{
minHeight: 0,
size: {height: 0},
} :
{
minWidth: 0,
size: {width: 0},
};
const handler = (
// @ts-ignore
<Center
// @ts-ignore
className={cx(styles[`toggle${arrowPlacement}`])}
style={{ opacity: isExpand ? (!pin ? 0 : undefined) : showHandlerWhenUnexpand ? 1 : 0 }}
>
<Center
onClick={() => {
setIsExpand(!isExpand);
}}
style={hanlderStyle}
>
<div
className={styles.handlerIcon}
style={{ transform: `rotate(${isExpand ? 180 : 0}deg)` }}
>
<Arrow size={16} strokeWidth={1.5} />
</div>
</Center>
</Center>
);
const {Arrow, className: arrowPlacement} = useMemo(() => {
switch (placement) {
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]);
const inner = (
// @ts-ignore
<Resizable
{...sizeProps}
className={styles.panel}
enable={canResizing ? (resizing as Enable) : undefined}
handleClasses={resizeHandleClassNames}
onResize={(_, direction, ref, delta) => {
onSizeDragging?.(delta, {
width: ref.style.width,
height: ref.style.height,
});
}}
onResizeStart={() => {
setShowExpand(false);
}}
onResizeStop={(e, direction, ref, delta) => {
setShowExpand(true);
onSizeChange?.(delta, {
width: ref.style.width,
height: ref.style.height,
});
}}
style={style}
>
{children}
</Resizable>
);
const handler = (
// @ts-ignore
<Center
// @ts-ignore
className={cx(styles[`toggle${arrowPlacement}`])}
style={{opacity: isExpand ? (pin ? undefined : 0) : showHandlerWhenUnexpand ? 1 : 0}}
>
<Center
onClick={() => {
setIsExpand(!isExpand);
}}
style={hanlderStyle}
>
<div
className={styles.handlerIcon}
style={{transform: `rotate(${isExpand ? 180 : 0}deg)`}}
>
<Arrow size={16} strokeWidth={1.5} />
</div>
</Center>
</Center>
);
return (
<div
className={cx(
styles.container,
// @ts-ignore
styles[mode === 'fixed' ? 'fixed' : `${placement}Float`],
className,
)}
ref={ref}
style={{ [`border${arrowPlacement}Width`]: 1 }}
>
{expandable && showExpand && handler}
{destroyOnClose ? isExpand && inner : inner}
</div>
);
},
const inner = (
// @ts-ignore
<Resizable
{...sizeProps}
className={styles.panel}
enable={canResizing ? (resizing as Enable) : undefined}
handleClasses={resizeHandleClassNames}
onResize={(_, direction, reference_, delta) => {
onSizeDragging?.(delta, {
height: reference_.style.height,
width: reference_.style.width,
});
}}
onResizeStart={() => {
setShowExpand(false);
}}
onResizeStop={(e, direction, reference_, delta) => {
setShowExpand(true);
onSizeChange?.(delta, {
height: reference_.style.height,
width: reference_.style.width,
});
}}
style={style}
>
{children}
</Resizable>
);
return (
<div
className={cx(
styles.container,
// @ts-ignore
styles[mode === 'fixed' ? 'fixed' : `${placement}Float`],
className,
)}
ref={reference}
style={{[`border${arrowPlacement}Width`]: 1}}
>
{expandable && showExpand && handler}
{destroyOnClose ? isExpand && inner : inner}
</div>
);
},
);
export default DraggablePanel;

View File

@ -1,11 +1,11 @@
import { createStyles, css, cx } from 'antd-style';
import {createStyles, css, cx} from 'antd-style';
const offset = 17;
const toggleLength = 40;
const toggleShort = 16;
export const useStyle = createStyles(({ token }, prefix: string) => {
const commonHandle = css`
export const useStyle = createStyles(({token}, prefix: string) => {
const commonHandle = css`
position: relative;
&::before {
@ -23,7 +23,7 @@ export const useStyle = createStyles(({ token }, prefix: string) => {
}
`;
const commonToggle = css`
const commonToggle = css`
position: absolute;
z-index: 1001;
opacity: 0;
@ -64,15 +64,36 @@ export const useStyle = createStyles(({ token }, prefix: string) => {
}
`;
const float = css`
const float = css`
position: absolute;
z-index: 2000;
`;
return {
container: cx(
prefix,
css`
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`
flex-shrink: 0;
border: 0 solid ${token.colorBorderSecondary};
@ -82,111 +103,70 @@ export const useStyle = createStyles(({ token }, prefix: string) => {
}
}
`,
),
fixed: css`
),
fixed: css`
position: relative;
`,
leftFloat: cx(
float,
css`
handlerIcon: css`
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s ${token.motionEaseOut};
`,
leftFloat: cx(
float,
css`
top: 0;
bottom: 0;
left: 0;
height: 100%;
`,
),
rightFloat: cx(
float,
css`
top: 0;
right: 0;
bottom: 0;
height: 100%;
`,
),
topFloat: cx(
float,
css`
top: 0;
right: 0;
left: 0;
width: 100%;
`,
),
bottomFloat: cx(
float,
css`
right: 0;
bottom: 0;
left: 0;
width: 100%;
`,
),
toggleLeft: cx(
`${prefix}-toggle`,
`${prefix}-toggle-left`,
commonToggle,
css`
left: -${offset}px;
width: ${toggleShort}px;
height: 100%;
),
leftHandle: cx(
css`
${commonHandle};
> div {
top: 50%;
width: ${toggleShort}px;
height: ${toggleLength}px;
margin-top: -20px;
border-radius: 4px 0 0 4px;
}
`,
),
toggleRight: cx(
`${prefix}-toggle`,
`${prefix}-toggle-right`,
commonToggle,
css`
right: -${offset}px;
width: ${toggleShort}px;
height: 100%;
> div {
top: 50%;
width: ${toggleShort}px;
height: ${toggleLength}px;
margin-top: -20px;
border-radius: 0 4px 4px 0;
}
`,
),
toggleTop: cx(
`${prefix}-toggle`,
`${prefix}-toggle-top`,
commonToggle,
css`
top: -${offset}px;
width: 100%;
height: ${toggleShort}px;
> div {
&::before {
left: 50%;
width: ${toggleLength}px;
height: ${toggleShort}px;
margin-left: -20px;
border-radius: 4px 4px 0 0;
width: 2px;
height: 100%;
}
`,
),
toggleBottom: cx(
`${prefix}-toggle`,
`${prefix}-toggle-bottom`,
commonToggle,
css`
`${prefix}-left-handle`,
),
panel: cx(
`${prefix}-fixed`,
css`
overflow: hidden;
background: ${token.colorBgContainer};
transition: all 0.2s ${token.motionEaseOut};
`,
),
rightFloat: cx(
float,
css`
top: 0;
right: 0;
bottom: 0;
height: 100%;
`,
),
rightHandle: cx(
css`
${commonHandle};
&::before {
right: 50%;
width: 2px;
height: 100%;
}
`,
`${prefix}-right-handle`,
),
toggleBottom: cx(
`${prefix}-toggle`,
`${prefix}-toggle-bottom`,
commonToggle,
css`
bottom: -${offset}px;
width: 100%;
height: ${toggleShort}px;
@ -201,47 +181,79 @@ export const useStyle = createStyles(({ token }, prefix: string) => {
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};
),
toggleLeft: cx(
`${prefix}-toggle`,
`${prefix}-toggle-left`,
commonToggle,
css`
left: -${offset}px;
width: ${toggleShort}px;
height: 100%;
&::before {
> div {
top: 50%;
width: ${toggleShort}px;
height: ${toggleLength}px;
margin-top: -20px;
border-radius: 4px 0 0 4px;
}
`,
),
toggleRight: cx(
`${prefix}-toggle`,
`${prefix}-toggle-right`,
commonToggle,
css`
right: -${offset}px;
width: ${toggleShort}px;
height: 100%;
> div {
top: 50%;
width: ${toggleShort}px;
height: ${toggleLength}px;
margin-top: -20px;
border-radius: 0 4px 4px 0;
}
`,
),
toggleTop: cx(
`${prefix}-toggle`,
`${prefix}-toggle-top`,
commonToggle,
css`
top: -${offset}px;
width: 100%;
height: ${toggleShort}px;
> div {
left: 50%;
width: 2px;
height: 100%;
width: ${toggleLength}px;
height: ${toggleShort}px;
margin-left: -20px;
border-radius: 4px 4px 0 0;
}
`,
`${prefix}-left-handle`,
),
rightHandle: cx(
css`
${commonHandle};
&::before {
right: 50%;
width: 2px;
height: 100%;
}
),
topFloat: cx(
float,
css`
top: 0;
right: 0;
left: 0;
width: 100%;
`,
`${prefix}-right-handle`,
),
topHandle: cx(
`${prefix}-top-handle`,
css`
),
topHandle: cx(
`${prefix}-top-handle`,
css`
${commonHandle};
&::before {
@ -250,18 +262,6 @@ export const useStyle = createStyles(({ token }, prefix: string) => {
height: 2px;
}
`,
),
bottomHandle: cx(
`${prefix}-bottom-handle`,
css`
${commonHandle};
&::before {
bottom: 50%;
width: 100%;
height: 2px;
}
`,
),
};
),
};
});

View File

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

View File

@ -1,28 +1,28 @@
import { memo, useEffect } from 'react';
import {memo, useEffect} from 'react';
interface GiscusProps {
themeMode: 'light' | 'dark';
}
const Giscus = memo<GiscusProps>(({ themeMode }) => {
useEffect(() => {
const Giscus = memo<GiscusProps>(({themeMode}) => {
useEffect(() => {
// 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.crossOrigin = 'anonymous';
giscus.async = true;
document.getElementsByTagName('head')[0].appendChild(giscus);
}, []);
const giscus: HTMLScriptElement = document.createElement('script');
giscus.src = 'https://giscus.app/client.js';
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.querySelectorAll('head')[0].append(giscus);
}, []);
return <div className="giscus" id="giscus" />;
return <div className="giscus" id="giscus" />;
});
export default Giscus;

View File

@ -1,6 +1,6 @@
import type { MenuProps } from 'antd';
import { Menu } from 'antd';
import { memo, useEffect, useState } from 'react';
import type {MenuProps} from 'antd';
import {Menu} from 'antd';
import {memo, useEffect, useState} from 'react';
import styled from 'styled-components';
/******************************************************
@ -38,40 +38,40 @@ const NavBar = styled(Menu)`
************************* Dom *************************
******************************************************/
const Nav = memo(() => {
const [items, setItems] = useState<MenuProps['items']>([]);
useEffect(() => {
onUiLoaded(() => {
const buttons = gradioApp().querySelectorAll('#tabs > .tab-nav:first-child button');
const list: MenuProps['items'] | any = [];
buttons.forEach((button: HTMLButtonElement | any, index) => {
button.id = `kitchen-nav-${index}`;
list.push({
label: button.textContent,
key: String(index),
});
});
setItems(list);
});
}, []);
const onClick: MenuProps['onClick'] = (e: any) => {
const onClick: MenuProps['onClick'] = (e: any) => {
const buttons: HTMLButtonElement[] | any = gradioApp().querySelectorAll(
'#tabs > .tab-nav:first-child button',
'#tabs > .tab-nav:first-child button',
);
buttons[Number(e.key)]?.click();
};
};
return (
<NavBar
defaultActiveFirst
defaultSelectedKeys={['0']}
items={items}
mode="horizontal"
onClick={onClick}
/>
);
const Nav = memo(() => {
const [items, setItems] = useState<MenuProps['items']>([]);
useEffect(() => {
onUiLoaded(() => {
const buttons = gradioApp().querySelectorAll('#tabs > .tab-nav:first-child button');
const list: MenuProps['items'] | any = [];
buttons.forEach((button: HTMLButtonElement | any, index) => {
button.id = `kitchen-nav-${index}`;
list.push({
key: String(index),
label: button.textContent,
});
});
setItems(list);
});
}, []);
return (
<NavBar
defaultActiveFirst
defaultSelectedKeys={['0']}
items={items}
mode="horizontal"
onClick={onClick}
/>
);
});
export default Nav;

View File

@ -1,10 +1,10 @@
import { SettingOutlined } from '@ant-design/icons';
import { Button, Divider, Form, InputNumber, Popover, Segmented, Space, Switch } from 'antd';
import { memo, useCallback } from 'react';
import {SettingOutlined} from '@ant-design/icons';
import {Button, Divider, Form, InputNumber, Popover, Segmented, Space, Switch} from 'antd';
import {memo, useCallback} from 'react';
import styled from 'styled-components';
import { shallow } from 'zustand/shallow';
import {shallow} from 'zustand/shallow';
import { WebuiSetting, defaultSetting, useAppStore } from '@/store';
import {WebuiSetting, defaultSetting, useAppStore} from '@/store';
/******************************************************
*********************** Style *************************
@ -39,85 +39,85 @@ const SubTitle = styled.div`
******************************************************/
const Setting = memo(() => {
const [setting, onSetSetting] = useAppStore((st) => [st.setting, st.onSetSetting], shallow);
const [setting, onSetSetting] = useAppStore((st) => [st.setting, st.onSetSetting], shallow);
const onReset = useCallback(() => {
onSetSetting(defaultSetting);
gradioApp().getElementById('settings_restart_gradio')?.click();
}, []);
const onReset = useCallback(() => {
onSetSetting(defaultSetting);
gradioApp().querySelector('#settings_restart_gradio')?.click();
}, []);
const onFinish = useCallback((value: WebuiSetting) => {
onSetSetting(value);
gradioApp().getElementById('settings_restart_gradio')?.click();
}, []);
const onFinish = useCallback((value: WebuiSetting) => {
onSetSetting(value);
gradioApp().querySelector('#settings_restart_gradio')?.click();
}, []);
return (
<Popover
content={
<Form
initialValues={setting}
layout="horizontal"
onFinish={onFinish}
size="small"
style={{ maxWidth: 260 }}
>
<Divider style={{ margin: '4px 0 8px' }} />
<SubTitle>Promot Textarea</SubTitle>
<FormItem label="Display mode" name="promotTextarea">
<Segmented options={['scroll', 'resizable']} />
</FormItem>
<Divider style={{ margin: '4px 0 8px' }} />
<SubTitle>Sidebar</SubTitle>
<FormItem label="Default expand" name="sidebarExpand" valuePropName="checked">
<Switch />
</FormItem>
<FormItem label="Display mode" name="sidebarFixedMode">
<Segmented options={['fixed', 'float']} />
</FormItem>
<FormItem label="Default width" name="sidebarWidth">
<InputNumber />
</FormItem>
<Divider style={{ margin: '4px 0 8px' }} />
<SubTitle>ExtraNetwork Sidebar</SubTitle>
<FormItem label="Enable" name="enableExtraNetworkSidebar" valuePropName="checked">
<Switch />
</FormItem>
<FormItem label="Display mode" name="extraNetworkFixedMode" valuePropName="checked">
<Segmented options={['fixed', 'float']} />
</FormItem>
<FormItem label="Default expand" name="extraNetworkSidebarExpand" valuePropName="checked">
<Switch />
</FormItem>
<FormItem label="Default width" name="extraNetworkSidebarWidth">
<InputNumber />
</FormItem>
<FormItem label="Default card size" name="extraNetworkCardSize">
<InputNumber />
</FormItem>
<Divider style={{ margin: '4px 0 8px' }} />
<SubTitle>Other</SubTitle>
<FormItem label="Use svg icons" name="svgIcon" valuePropName="checked">
<Switch />
</FormItem>
<Divider style={{ margin: '4px 0 16px' }} />
<FormItem>
<Space>
<Button htmlType="button" onClick={onReset} style={{ borderRadius: 4 }}>
return (
<Popover
content={
<Form
initialValues={setting}
layout="horizontal"
onFinish={onFinish}
size="small"
style={{maxWidth: 260}}
>
<Divider style={{margin: '4px 0 8px'}} />
<SubTitle>Promot Textarea</SubTitle>
<FormItem label="Display mode" name="promotTextarea">
<Segmented options={['scroll', 'resizable']} />
</FormItem>
<Divider style={{margin: '4px 0 8px'}} />
<SubTitle>Sidebar</SubTitle>
<FormItem label="Default expand" name="sidebarExpand" valuePropName="checked">
<Switch />
</FormItem>
<FormItem label="Display mode" name="sidebarFixedMode">
<Segmented options={['fixed', 'float']} />
</FormItem>
<FormItem label="Default width" name="sidebarWidth">
<InputNumber />
</FormItem>
<Divider style={{margin: '4px 0 8px'}} />
<SubTitle>ExtraNetwork Sidebar</SubTitle>
<FormItem label="Enable" name="enableExtraNetworkSidebar" valuePropName="checked">
<Switch />
</FormItem>
<FormItem label="Display mode" name="extraNetworkFixedMode" valuePropName="checked">
<Segmented options={['fixed', 'float']} />
</FormItem>
<FormItem label="Default expand" name="extraNetworkSidebarExpand" valuePropName="checked">
<Switch />
</FormItem>
<FormItem label="Default width" name="extraNetworkSidebarWidth">
<InputNumber />
</FormItem>
<FormItem label="Default card size" name="extraNetworkCardSize">
<InputNumber />
</FormItem>
<Divider style={{margin: '4px 0 8px'}} />
<SubTitle>Other</SubTitle>
<FormItem label="Use svg icons" name="svgIcon" valuePropName="checked">
<Switch />
</FormItem>
<Divider style={{margin: '4px 0 16px'}} />
<FormItem>
<Space>
<Button htmlType="button" onClick={onReset} style={{borderRadius: 4}}>
Reset
</Button>
<Button htmlType="submit" style={{ borderRadius: 4 }} type="primary">
</Button>
<Button htmlType="submit" style={{borderRadius: 4}} type="primary">
Apply and restart UI
</Button>
</Space>
</FormItem>
</Form>
}
title={<Title> Setting</Title>}
trigger="click"
>
<Button icon={<SettingOutlined />} title="Setting" />
</Popover>
);
</Button>
</Space>
</FormItem>
</Form>
}
title={<Title> Setting</Title>}
trigger="click"
>
<Button icon={<SettingOutlined />} title="Setting" />
</Popover>
);
});
export default Setting;

View File

@ -1,19 +1,19 @@
import { BoldOutlined, GithubOutlined } from '@ant-design/icons';
import { Button, Modal, Space } from 'antd';
import { useResponsive } from 'antd-style';
import {BoldOutlined, GithubOutlined} from '@ant-design/icons';
import {Button, Modal, Space} from 'antd';
import {useResponsive} from 'antd-style';
import qs from 'query-string';
import { type ReactNode, memo, useCallback, useEffect, useState } from 'react';
import {type ReactNode, memo, useCallback, useEffect, useState} from 'react';
import styled from 'styled-components';
import { shallow } from 'zustand/shallow';
import {shallow} from 'zustand/shallow';
import { DraggablePanel } from '@/components';
import { useAppStore } from '@/store';
import {DraggablePanel} from '@/components';
import {useAppStore} from '@/store';
import Giscus from './Giscus';
import Logo from './Logo';
import Nav from './Nav';
import Setting from './Setting';
import { civitaiLogo, themeIcon } from './style';
import {civitaiLogo, themeIcon} from './style';
/******************************************************
*********************** Style *************************
@ -38,86 +38,86 @@ interface HeaderProps {
children: ReactNode;
}
const Header = memo<HeaderProps>(({ children }) => {
const [themeMode] = useAppStore((st) => [st.themeMode], shallow);
const { mobile } = useResponsive();
const [expand, setExpand] = useState<boolean>(true);
const [isModalOpen, setIsModalOpen] = useState(false);
const Header = memo<HeaderProps>(({children}) => {
const [themeMode] = useAppStore((st) => [st.themeMode], shallow);
const {mobile} = useResponsive();
const [expand, setExpand] = useState<boolean>(true);
const [isModalOpen, setIsModalOpen] = useState(false);
useEffect(() => {
if (mobile) setExpand(false);
}, []);
useEffect(() => {
if (mobile) setExpand(false);
}, []);
const handleSetTheme = useCallback(() => {
const theme = themeMode === 'light' ? 'dark' : 'light';
const gradioURL = qs.parseUrl(window.location.href);
gradioURL.query.__theme = theme;
window.location.replace(qs.stringifyUrl(gradioURL));
}, [themeMode]);
const handleSetTheme = useCallback(() => {
const theme = themeMode === 'light' ? 'dark' : 'light';
const gradioURL = qs.parseUrl(window.location.href);
gradioURL.query.__theme = theme;
window.location.replace(qs.stringifyUrl(gradioURL));
}, [themeMode]);
const showModal = () => setIsModalOpen(true);
const showModal = () => setIsModalOpen(true);
const handleCancel = () => setIsModalOpen(false);
const handleCancel = () => setIsModalOpen(false);
return (
<>
<DraggablePanel
defaultSize={{ height: 'auto' }}
expand={expand}
minHeight={64}
onExpandChange={setExpand}
placement="top"
>
<HeaderView id="header" style={{ flexDirection: mobile ? 'column' : 'row' }}>
<a
href="https://github.com/canisminor1990/sd-webui-kitchen-theme"
rel="noreferrer"
target="_blank"
>
<Logo themeMode={themeMode} />
</a>
<Nav />
{children}
<Space.Compact>
<a href="https://civitai.com/" rel="noreferrer" target="_blank">
<Button icon={civitaiLogo} title="Civitai" />
</a>
<a
href="https://www.birme.net/?target_width=512&target_height=512"
rel="noreferrer"
target="_blank"
return (
<>
<DraggablePanel
defaultSize={{height: 'auto'}}
expand={expand}
minHeight={64}
onExpandChange={setExpand}
placement="top"
>
<Button icon={<BoldOutlined />} title="Birme" />
</a>
<Button icon={<GithubOutlined />} onClick={showModal} title="Feedback" />
<Setting />
<Button icon={themeIcon[themeMode]} onClick={handleSetTheme} title="Switch Theme" />
</Space.Compact>
</HeaderView>
</DraggablePanel>
<Modal
footer={null}
onCancel={handleCancel}
open={isModalOpen}
title={
<a
href="https://github.com/canisminor1990/sd-webui-kitchen-theme"
rel="noreferrer"
target="_blank"
>
<Space>
<GithubOutlined />
{'canisminor1990/sd-webui-kitchen-theme'}
</Space>
</a>
}
>
<Giscus themeMode={themeMode} />
</Modal>
</>
);
<HeaderView id="header" style={{flexDirection: mobile ? 'column' : 'row'}}>
<a
href="https://github.com/canisminor1990/sd-webui-kitchen-theme"
rel="noreferrer"
target="_blank"
>
<Logo themeMode={themeMode} />
</a>
<Nav />
{children}
<Space.Compact>
<a href="https://civitai.com/" rel="noreferrer" target="_blank">
<Button icon={civitaiLogo} title="Civitai" />
</a>
<a
href="https://www.birme.net/?target_width=512&target_height=512"
rel="noreferrer"
target="_blank"
>
<Button icon={<BoldOutlined />} title="Birme" />
</a>
<Button icon={<GithubOutlined />} onClick={showModal} title="Feedback" />
<Setting />
<Button icon={themeIcon[themeMode]} onClick={handleSetTheme} title="Switch Theme" />
</Space.Compact>
</HeaderView>
</DraggablePanel>
<Modal
footer={false}
onCancel={handleCancel}
open={isModalOpen}
title={
<a
href="https://github.com/canisminor1990/sd-webui-kitchen-theme"
rel="noreferrer"
target="_blank"
>
<Space>
<GithubOutlined />
{'canisminor1990/sd-webui-kitchen-theme'}
</Space>
</a>
}
>
<Giscus themeMode={themeMode} />
</Modal>
</>
);
});
export default Header;

View File

@ -1,18 +1,18 @@
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">
<path d="M8.218 1.455c3.527.109 6.327 3.018 6.327 6.545 0 3.6-2.945 6.545-6.545 6.545a6.562 6.562 0 0 1-6.036-4h.218c3.6 0 6.545-2.945 6.545-6.545 0-.91-.182-1.745-.509-2.545m0-1.455c-.473 0-.909.218-1.2.618-.29.4-.327.946-.145 1.382.254.655.4 1.31.4 2 0 2.8-2.291 5.09-5.091 5.09h-.218c-.473 0-.91.22-1.2.62-.291.4-.328.945-.146 1.38C1.891 14.074 4.764 16 8 16c4.4 0 8-3.6 8-8a7.972 7.972 0 0 0-7.745-8h-.037Z"></path>
</svg>
</span>
),
dark: (
<span className="anticon anticon-github" role="img">
<svg fill="currentColor" height="1em" viewBox="0 0 16 16" width="1em">
<path d="M8.218 1.455c3.527.109 6.327 3.018 6.327 6.545 0 3.6-2.945 6.545-6.545 6.545a6.562 6.562 0 0 1-6.036-4h.218c3.6 0 6.545-2.945 6.545-6.545 0-.91-.182-1.745-.509-2.545m0-1.455c-.473 0-.909.218-1.2.618-.29.4-.327.946-.145 1.382.254.655.4 1.31.4 2 0 2.8-2.291 5.09-5.091 5.09h-.218c-.473 0-.91.22-1.2.62-.291.4-.328.945-.146 1.38C1.891 14.074 4.764 16 8 16c4.4 0 8-3.6 8-8a7.972 7.972 0 0 0-7.745-8h-.037Z"></path>
</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 =
@ -21,9 +21,9 @@ export const lightLogo =
'https://gw.alipayobjects.com/zos/bmw-prod/e146116d-c65a-4306-a3d2-bb8d05e1c49b.svg';
export const civitaiLogo = (
<span className="anticon civitai" role="img">
<svg fill="currentColor" height="1em" viewBox="0 0 16 16" width="1em">
<path d="M2 4.5L8 1l6 3.5v7L8 15l-6-3.5v-7zm6-1.194L3.976 5.653v4.694L8 12.694l4.024-2.347V5.653L8 3.306zm0 1.589l2.662 1.552v.824H9.25L8 6.54l-1.25.73v1.458L8 9.46l1.25-.73h1.412v.824L8 11.105 5.338 9.553V6.447L8 4.895z" />
</svg>
</span>
<span className="anticon civitai" role="img">
<svg fill="currentColor" height="1em" viewBox="0 0 16 16" width="1em">
<path d="M2 4.5L8 1l6 3.5v7L8 15l-6-3.5v-7zm6-1.194L3.976 5.653v4.694L8 12.694l4.024-2.347V5.653L8 3.306zm0 1.589l2.662 1.552v.824H9.25L8 6.54l-1.25.73v1.458L8 9.46l1.25-.73h1.412v.824L8 11.105 5.338 9.553V6.447L8 4.895z" />
</svg>
</span>
);

View File

@ -1,8 +1,8 @@
import { memo, useCallback, useState } from 'react';
import {memo, useCallback, useState} from 'react';
import styled from 'styled-components';
import TagList, { PromptType, TagItem } from './TagList';
import { formatPrompt } from './utils';
import TagList, {PromptType, TagItem} from './TagList';
import {formatPrompt} from './utils';
/******************************************************
*********************** Style *************************
@ -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;
@ -48,48 +48,54 @@ interface PromptProps {
type: PromptType;
}
const Prompt = memo<PromptProps>(({ type }) => {
const [tags, setTags] = useState<TagItem[]>([]);
const Prompt = memo<PromptProps>(({type}) => {
const [tags, setTags] = useState<TagItem[]>([]);
const id =
const id =
type === 'positive' ? "[id$='2img_prompt'] textarea" : "[id$='2img_neg_prompt'] textarea";
const getValue = useCallback(() => {
try {
const textarea: HTMLTextAreaElement | any = get_uiCurrentTabContent().querySelector(id);
if (textarea) setTags(formatPrompt(textarea.value));
} catch {}
}, []);
const getValue = useCallback(() => {
try {
const textarea: HTMLTextAreaElement | any = get_uiCurrentTabContent().querySelector(id);
if (textarea) setTags(formatPrompt(textarea.value));
} catch (error) {
console.log(error);
}
}, []);
const setValue = useCallback(() => {
try {
const textarea: HTMLTextAreaElement | any = get_uiCurrentTabContent().querySelector(id);
if (textarea) textarea.value = tags.map((t) => t.text).join(', ');
updateInput(textarea);
} catch {}
}, [tags]);
const setValue = useCallback(() => {
try {
const textarea: HTMLTextAreaElement | any = get_uiCurrentTabContent().querySelector(id);
if (textarea) textarea.value = tags.map((t) => t.text).join(', ');
updateInput(textarea);
} catch (error) {
console.log(error);
}
}, [tags]);
const setCurrentValue = useCallback((currentTags: TagItem[]) => {
try {
const textarea: HTMLTextAreaElement | any = get_uiCurrentTabContent().querySelector(id);
if (textarea) textarea.value = currentTags.map((t) => t.text).join(', ');
updateInput(textarea);
} catch {}
}, []);
const setCurrentValue = useCallback((currentTags: TagItem[]) => {
try {
const textarea: HTMLTextAreaElement | any = get_uiCurrentTabContent().querySelector(id);
if (textarea) textarea.value = currentTags.map((t) => t.text).join(', ');
updateInput(textarea);
} catch (error) {
console.log(error);
}
}, []);
return (
<View>
<TagList setTags={setTags} setValue={setCurrentValue} tags={tags} type={type} />
<BtnGroup>
<Btn onClick={getValue} title="Load Prompt">
return (
<View>
<TagList setTags={setTags} setValue={setCurrentValue} tags={tags} type={type} />
<ButtonGroup>
<Button onClick={getValue} title="Load Prompt">
🔄
</Btn>
<Btn onClick={setValue} title="Set Prompt">
</Button>
<Button onClick={setValue} title="Set Prompt">
</Btn>
</BtnGroup>
</View>
);
</Button>
</ButtonGroup>
</View>
);
});
export default Prompt;

View File

@ -1,8 +1,8 @@
import { type FC, memo, useCallback, useMemo } from 'react';
import { WithContext, ReactTagsProps as WithContextProps } from 'react-tag-input';
import {type FC, memo, useCallback, useMemo} from 'react';
import {WithContext, ReactTagsProps as WithContextProps} from 'react-tag-input';
import styled from 'styled-components';
import { genTagType, suggestions } from './utils';
import {genTagType, suggestions} from './utils';
export interface TagItem {
className?: string;
@ -73,14 +73,14 @@ const View = styled.div<{ type: PromptType }>`
font-size: var(--text-sm);
font-weight: var(--input-text-weight);
line-height: var(--line-sm);
color: ${({ type }) => (type === 'positive' ? 'var(--green-9)' : 'var(--magenta-9)')};
color: ${({type}) => (type === 'positive' ? 'var(--green-9)' : 'var(--magenta-9)')};
background: var(--button-secondary-background-fill);
border: var(--button-border-width) solid var(--button-secondary-border-color);
border-radius: var(--input-radius);
&:hover {
color: ${({ type }) => (type === 'positive' ? 'var(--green-10)' : 'var(--magenta-10)')};
color: ${({type}) => (type === 'positive' ? 'var(--green-10)' : 'var(--magenta-10)')};
}
}
@ -155,8 +155,8 @@ const View = styled.div<{ type: PromptType }>`
`;
const KeyCodes = {
comma: 188,
enter: 13,
comma: 188,
enter: 13,
};
const delimiters = [KeyCodes.comma, KeyCodes.enter];
@ -168,65 +168,65 @@ interface TagListProps {
type: PromptType;
}
const TagList = memo<TagListProps>(({ tags, setTags, type, setValue }) => {
const handleDelete = useCallback(
(i: number) => {
const newTags = tags.filter((tag, index) => index !== i);
setTags(newTags);
setValue(newTags);
},
[tags],
);
const TagList = memo<TagListProps>(({tags, setTags, type, setValue}) => {
const handleDelete = useCallback(
(index_: number) => {
const newTags = tags.filter((tag, index) => index !== index_);
setTags(newTags);
setValue(newTags);
},
[tags],
);
const handleAddition = useCallback(
(tag: TagItem) => {
const newTags = [...tags, genTagType(tag)];
setTags(newTags);
setValue(newTags);
},
[tags],
);
const handleAddition = useCallback(
(tag: TagItem) => {
const newTags = [...tags, genTagType(tag)];
setTags(newTags);
setValue(newTags);
},
[tags],
);
const handleDrag = useCallback(
(tag: TagItem, currPos: number, newPos: number) => {
const newTags = tags.slice();
newTags.splice(currPos, 1);
newTags.splice(newPos, 0, genTagType(tag));
setTags(newTags);
setValue(newTags);
},
[tags],
);
const handleDrag = useCallback(
(tag: TagItem, currentPos: number, newPos: number) => {
const newTags = [...tags];
newTags.splice(currentPos, 1);
newTags.splice(newPos, 0, genTagType(tag));
setTags(newTags);
setValue(newTags);
},
[tags],
);
const handleTagUpdate = useCallback(
(i: number, tag: TagItem) => {
const newTags = [...tags];
newTags[i] = genTagType(tag);
setTags(newTags);
setValue(newTags);
},
[tags],
);
const handleTagUpdate = useCallback(
(index: number, tag: TagItem) => {
const newTags = [...tags];
newTags[index] = genTagType(tag);
setTags(newTags);
setValue(newTags);
},
[tags],
);
const suggestionData = useMemo(() => suggestions[type], [type]);
const suggestionData = useMemo(() => suggestions[type], [type]);
return (
<View type={type}>
<ReactTags
autocomplete
delimiters={delimiters}
editable
handleAddition={handleAddition}
handleDelete={handleDelete}
handleDrag={handleDrag}
inline
inputFieldPosition="bottom"
onTagUpdate={handleTagUpdate}
suggestions={suggestionData}
tags={tags}
/>
</View>
);
return (
<View type={type}>
<ReactTags
autocomplete
delimiters={delimiters}
editable
handleAddition={handleAddition}
handleDelete={handleDelete}
handleDrag={handleDrag}
inline
inputFieldPosition="bottom"
onTagUpdate={handleTagUpdate}
suggestions={suggestionData}
tags={tags}
/>
</View>
);
});
export default TagList;

View File

@ -1,48 +1,48 @@
import negativeData from '@/data/negative.json';
import positiveData from '@/data/positive.json';
import { Converter } from '@/script/formatPrompt';
import {Converter} from '@/script/formatPrompt';
import { TagItem } from './TagList';
import {TagItem} from './TagList';
export const genTagType = (tag: TagItem): TagItem => {
const newTag = tag;
if (newTag.text.includes('<lora')) {
newTag.className = 'ReactTags__lora';
} else if (newTag.text.includes('<hypernet')) {
newTag.className = 'ReactTags__hypernet';
} else if (newTag.text.includes('<embedding')) {
newTag.className = 'ReactTags__embedding';
} else {
newTag.className = undefined;
}
return newTag;
const newTag = tag;
if (newTag.text.includes('<lora')) {
newTag.className = 'ReactTags__lora';
} else if (newTag.text.includes('<hypernet')) {
newTag.className = 'ReactTags__hypernet';
} else if (newTag.text.includes('<embedding')) {
newTag.className = 'ReactTags__embedding';
} else {
newTag.className = undefined;
}
return newTag;
};
export const formatPrompt = (value: string) => {
const text = Converter.convertStr(value);
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, ', ');
return Converter.convertStr2Array(newItem).join(', ');
});
return textArray.map((tag) => genTagType({ id: tag, text: tag }));
const text = Converter.convertStr(value);
const textArray = Converter.convertStr2Array(text).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 textArray.map((tag) => genTagType({id: tag, text: tag}));
};
const genSuggestions = (array: string[]) =>
array.map((text) => {
return {
id: text,
text,
};
});
array.map((text) => {
return {
id: text,
text,
};
});
export const suggestions = {
positive: genSuggestions(positiveData),
negative: genSuggestions(negativeData),
negative: genSuggestions(negativeData),
positive: genSuggestions(positiveData),
};

View File

@ -1,29 +1,29 @@
import { useEffect, useState } from 'react';
import {useEffect, useState} from 'react';
function checkIsDarkMode() {
try {
return window.matchMedia('(prefers-color-scheme: dark)').matches;
} catch (err) {
return false;
}
try {
return window.matchMedia('(prefers-color-scheme: dark)').matches;
} catch {
return false;
}
}
export function useIsDarkMode() {
const [isDarkMode, setIsDarkMode] = useState(checkIsDarkMode());
const [isDarkMode, setIsDarkMode] = useState(checkIsDarkMode());
useEffect(() => {
const mqList = window.matchMedia('(prefers-color-scheme: dark)');
useEffect(() => {
const mqList = window.matchMedia('(prefers-color-scheme: dark)');
const listener = (event: any) => {
setIsDarkMode(event.matches);
};
const listener = (event: any) => {
setIsDarkMode(event.matches);
};
mqList.addEventListener('change', listener);
mqList.addEventListener('change', listener);
return () => {
mqList.removeEventListener('change', listener);
};
}, []);
return () => {
mqList.removeEventListener('change', listener);
};
}, []);
return isDarkMode;
return isDarkMode;
}

View File

@ -1,14 +1,14 @@
import { Spin } from 'antd';
import { useResponsive } from 'antd-style';
import { memo, useEffect, useRef, useState } from 'react';
import {Spin} from 'antd';
import {useResponsive} from 'antd-style';
import {memo, useEffect, useRef, useState} from 'react';
import styled from 'styled-components';
import { shallow } from 'zustand/shallow';
import {shallow} from 'zustand/shallow';
import { Content, ExtraNetworkSidebar, Header, Sidebar } from '@/components';
import {Content, ExtraNetworkSidebar, Header, Sidebar} from '@/components';
import civitaiHelperFix from '@/script/civitaiHelperFix';
import dragablePanel from '@/script/draggablePanel';
import replaceIcon from '@/script/replaceIcon';
import { useAppStore } from '@/store';
import {useAppStore} from '@/store';
const View = styled.div`
position: relative;
@ -41,124 +41,126 @@ const LoadingBox = styled.div`
`;
const App = memo(() => {
const [currentTab, setCurrentTab, setting] = useAppStore(
(st) => [st.currentTab, st.setCurrentTab, st.setting],
shallow,
);
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>();
useEffect(() => {
onUiLoaded(() => {
// Content
const main = gradioApp().querySelector('.app');
if (main) mainRef.current?.appendChild(main);
if (!mobile) dragablePanel();
const [currentTab, setCurrentTab, setting] = useAppStore(
(st) => [st.currentTab, st.setCurrentTab, st.setting],
shallow,
);
const {mobile} = useResponsive();
const [loading, setLoading] = useState(true);
const [extraLoading, setExtraLoading] = useState(true);
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) mainReference.current?.append(main);
if (!mobile) dragablePanel();
// Sidebar
const sidebar = gradioApp().querySelector('#quicksettings');
if (sidebar) sidebarRef.current?.appendChild(sidebar);
// Sidebar
const sidebar = gradioApp().querySelector('#quicksettings');
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);
// ExtraNetworkSidebar
if (setting.enableExtraNetworkSidebar) {
const txt2imgExtraNetworks = gradioApp().querySelector('div#txt2img_extra_networks');
const img2imgExtraNetworks = gradioApp().querySelector('div#img2img_extra_networks');
if (txt2imgExtraNetworks && img2imgExtraNetworks) {
txt2imgExtraNetworkSidebarReference.current?.append(txt2imgExtraNetworks);
img2imgExtraNetworkSidebarReference.current?.append(img2imgExtraNetworks);
}
}
// Other
if (setting.svgIcon) replaceIcon();
setLoading(false);
});
onUiUpdate(() => {
setCurrentTab();
});
}, []);
useEffect(() => {
if (!loading && setting.enableExtraNetworkSidebar) {
if (document.querySelector('#txt2img_lora_cards')) {
civitaiHelperFix();
setExtraLoading(false);
return;
}
setTimeout(() => {
const t2indexButton: any = document.querySelector('#txt2img_extra_refresh');
const index2indexButton: any = document.querySelector('#img2img_extra_refresh');
t2indexButton.click();
index2indexButton.click();
setExtraLoading(false);
try {
const civitaiButton = document.querySelectorAll(
'button[title="Refresh Civitai Helper\'s additional buttons"]',
);
if (civitaiButton) {
civitaiButton.forEach((button: any) => (button.onclick = civitaiHelperFix));
}
civitaiHelperFix();
} catch (error) {
console.log(error);
}
}, 2000);
}
}
}, [loading]);
// Other
if (setting.svgIcon) replaceIcon();
setLoading(false);
});
onUiUpdate(() => {
setCurrentTab();
});
}, []);
useEffect(() => {
if (!loading && setting.enableExtraNetworkSidebar) {
if (document.querySelector('#txt2img_lora_cards')) {
civitaiHelperFix();
setExtraLoading(false);
return;
}
setTimeout(() => {
const t2iBtn: any = document.querySelector('#txt2img_extra_refresh');
const i2iBtn: any = document.querySelector('#img2img_extra_refresh');
t2iBtn.click();
i2iBtn.click();
setExtraLoading(false);
try {
const civitaiBtn = document.querySelectorAll(
'button[title="Refresh Civitai Helper\'s additional buttons"]',
);
if (civitaiBtn) {
civitaiBtn.forEach((btn: any) => (btn.onclick = civitaiHelperFix));
}
civitaiHelperFix();
} catch {}
}, 2000);
}
}, [loading]);
return (
<MainView>
<Header>
{loading && (
<LoadingBox>
<Spin size="small" />
</LoadingBox>
)}
</Header>
<View>
<Sidebar>
{loading && (
<LoadingBox>
<Spin size="small" />
</LoadingBox>
)}
<div id="sidebar" ref={sidebarRef} style={loading ? { display: 'none' } : {}} />
</Sidebar>
<Content loading={loading}>
{loading && (
<LoadingBox>
<Spin size="large" tip="Loading" />
</LoadingBox>
)}
<div id="content" ref={mainRef} style={loading ? { display: 'none' } : {}} />
</Content>
{setting?.enableExtraNetworkSidebar && (
<ExtraNetworkSidebar>
{extraLoading && (
<LoadingBox>
<Spin size="small" />
</LoadingBox>
)}
<div style={extraLoading ? { display: 'none' } : {}}>
<div
id="txt2img-extra-netwrok-sidebar"
ref={txt2imgExtraNetworkSidebarRef}
style={currentTab !== 'tab_img2img' ? {} : { display: 'none' }}
/>
<div
id="img2img-extra-netwrok-sidebar"
ref={img2imgExtraNetworkSidebarRef}
style={currentTab === 'tab_img2img' ? {} : { display: 'none' }}
/>
</div>
</ExtraNetworkSidebar>
)}
</View>
</MainView>
);
return (
<MainView>
<Header>
{loading && (
<LoadingBox>
<Spin size="small" />
</LoadingBox>
)}
</Header>
<View>
<Sidebar>
{loading && (
<LoadingBox>
<Spin size="small" />
</LoadingBox>
)}
<div id="sidebar" ref={sidebarReference} style={loading ? {display: 'none'} : {}} />
</Sidebar>
<Content loading={loading}>
{loading && (
<LoadingBox>
<Spin size="large" tip="Loading" />
</LoadingBox>
)}
<div id="content" ref={mainReference} style={loading ? {display: 'none'} : {}} />
</Content>
{setting?.enableExtraNetworkSidebar && (
<ExtraNetworkSidebar>
{extraLoading && (
<LoadingBox>
<Spin size="small" />
</LoadingBox>
)}
<div style={extraLoading ? {display: 'none'} : {}}>
<div
id="txt2img-extra-netwrok-sidebar"
ref={txt2imgExtraNetworkSidebarReference}
style={currentTab === 'tab_img2img' ? {display: 'none'} : {}}
/>
<div
id="img2img-extra-netwrok-sidebar"
ref={img2imgExtraNetworkSidebarReference}
style={currentTab === 'tab_img2img' ? {} : {display: 'none'}}
/>
</div>
</ExtraNetworkSidebar>
)}
</View>
</MainView>
);
});
export default App;

View File

@ -1,81 +1,81 @@
import { ThemeProvider, setupStyled } from 'antd-style';
import {ThemeProvider, setupStyled} from 'antd-style';
import qs from 'query-string';
import { memo, useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
import {memo, useEffect, useState} from 'react';
import {createRoot} from 'react-dom/client';
// @ts-ignore
import ReactFontLoader from 'react-font-loader';
import { ThemeContext } from 'styled-components';
import { shallow } from 'zustand/shallow';
import {ThemeContext} from 'styled-components';
import {shallow} from 'zustand/shallow';
import { useIsDarkMode } from '@/components/theme/useIsDarkMode';
import {useIsDarkMode} from '@/components/theme/useIsDarkMode';
import formatPrompt from '@/script/formatPrompt';
import promptBracketChecker from '@/script/promptBracketChecker';
import setupHead from '@/script/setupHead';
import { useAppStore } from '@/store';
import {useAppStore} from '@/store';
import '@/theme/style.less';
import App from './App';
import GlobalStyle from './GlobalStyle';
import { baseToken } from './style';
import {baseToken} from './style';
const Root = memo(() => {
setupStyled({ ThemeContext });
const [onSetThemeMode, onInit] = useAppStore((st) => [st.onSetThemeMode, st.onInit], shallow);
const isDarkMode = useIsDarkMode();
const [appearance, setAppearance] = useState<'light' | 'dark'>('light');
const [first, setFirst] = useState(true);
useEffect(() => {
onInit();
}, []);
useEffect(() => {
const queryTheme: any = String(qs.parseUrl(window.location.href).query.__theme || '');
if (queryTheme) {
setAppearance(queryTheme as any);
document.body.classList.add(queryTheme);
onSetThemeMode(queryTheme);
return;
}
setAppearance(isDarkMode ? 'dark' : 'light');
document.body.classList.add(isDarkMode ? 'dark' : 'light');
onSetThemeMode(isDarkMode ? 'dark' : 'light');
}, [isDarkMode]);
useEffect(() => {
if (first) {
setFirst(false);
return;
}
window.location.reload();
}, [isDarkMode]);
return (
<ThemeProvider appearance={appearance} theme={{ token: baseToken }}>
<GlobalStyle />
<ReactFontLoader url="https://raw.githubusercontent.com/IKKI2000/harmonyos-fonts/main/css/harmonyos_sans.css" />
<ReactFontLoader url="https://raw.githubusercontent.com/IKKI2000/harmonyos-fonts/main/css/harmonyos_sans_sc.css" />
<App />
</ThemeProvider>
);
setupStyled({ThemeContext});
const [onSetThemeMode, onInit] = useAppStore((st) => [st.onSetThemeMode, st.onInit], shallow);
const isDarkMode = useIsDarkMode();
const [appearance, setAppearance] = useState<'light' | 'dark'>('light');
const [first, setFirst] = useState(true);
useEffect(() => {
onInit();
}, []);
useEffect(() => {
const queryTheme: any = String(qs.parseUrl(window.location.href).query.__theme || '');
if (queryTheme) {
setAppearance(queryTheme as any);
document.body.classList.add(queryTheme);
onSetThemeMode(queryTheme);
return;
}
setAppearance(isDarkMode ? 'dark' : 'light');
document.body.classList.add(isDarkMode ? 'dark' : 'light');
onSetThemeMode(isDarkMode ? 'dark' : 'light');
}, [isDarkMode]);
useEffect(() => {
if (first) {
setFirst(false);
return;
}
window.location.reload();
}, [isDarkMode]);
return (
<ThemeProvider appearance={appearance} theme={{token: baseToken}}>
<GlobalStyle />
<ReactFontLoader url="https://raw.githubusercontent.com/IKKI2000/harmonyos-fonts/main/css/harmonyos_sans.css" />
<ReactFontLoader url="https://raw.githubusercontent.com/IKKI2000/harmonyos-fonts/main/css/harmonyos_sans_sc.css" />
<App />
</ThemeProvider>
);
});
document.addEventListener(
'DOMContentLoaded',
() => {
setupHead();
const root = document.createElement('div');
root.setAttribute('id', 'root');
try {
gradioApp()?.append(root);
} catch {
document.querySelector('gradio-app')?.append(root);
}
const client = createRoot(root);
client.render(<Root />);
},
{ once: true },
'DOMContentLoaded',
() => {
setupHead();
const root = document.createElement('div');
root.setAttribute('id', 'root');
try {
gradioApp()?.append(root);
} catch {
document.querySelector('gradio-app')?.append(root);
}
const client = createRoot(root);
client.render(<Root />);
},
{once: true},
);
onUiLoaded(() => {
formatPrompt();
promptBracketChecker();
formatPrompt();
promptBracketChecker();
});
export default () => null;
export default () => false;

View File

@ -1,17 +1,17 @@
const TAB_PREFIX_LIST = ['txt2img', 'img2img'];
const MODEL_TYPE_LIST: ['textual_inversion', 'hypernetworks', 'checkpoints', 'lora', 'lycoris'] = [
'textual_inversion',
'hypernetworks',
'checkpoints',
'lora',
'lycoris',
'textual_inversion',
'hypernetworks',
'checkpoints',
'lora',
'lycoris',
];
const MODEL_TYPE = {
textual_inversion: 'ti',
hypernetworks: 'hyper',
checkpoints: 'ckp',
lora: 'lora',
lycoris: 'lycoris',
checkpoints: 'ckp',
hypernetworks: 'hyper',
lora: 'lora',
lycoris: 'lycoris',
textual_inversion: 'ti',
};
const CARDID_SUFFIX = 'cards';
@ -23,189 +23,189 @@ 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 {
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;
}
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;
}
};
const updateCardForCivitai = () => {
if (!gradioApp().querySelector('#tab_civitai_helper')) return;
if (!gradioApp().querySelector('#tab_civitai_helper')) return;
const replacePreviewText = getTranslation('replace preview') || 'replace preview';
const replacePreviewText = getTranslation('replace preview') || 'replace preview';
// Get component
const chAlwaysDisplayCkb = gradioApp().querySelector(
'#ch_always_display_ckb input',
) as HTMLInputElement;
const chShowBtnOnThumbCkb = gradioApp().querySelector(
'#ch_show_btn_on_thumb_ckb input',
) as HTMLInputElement;
const chAlwaysDisplay = chAlwaysDisplayCkb?.checked || false;
const chShowBtnOnThumb = chShowBtnOnThumbCkb?.checked || false;
// Get component
const chAlwaysDisplayCkb = gradioApp().querySelector(
'#ch_always_display_ckb input',
) as HTMLInputElement;
const chShowButtonOnThumbCkb = gradioApp().querySelector(
'#ch_show_btn_on_thumb_ckb input',
) as HTMLInputElement;
const chAlwaysDisplay = chAlwaysDisplayCkb?.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 searchTerm = '';
let modelType = '';
let cards = null;
let needToAddButtons = false;
let isThumbMode = false;
// Change all "replace preview" into an icon
let extraNetworkId = '';
let extraNetworkNode: any;
let metadataButton: any;
let additionalNode: any;
let replacePreviewButton: any;
let ulNode: any;
let searchTermNode: any;
let searchTerm = '';
let modelType = '';
let cards;
let needToAddButtons = false;
let isThumbMode = false;
// Get current tab
TAB_PREFIX_LIST.forEach((activeTabType) => {
MODEL_TYPE_LIST.forEach((jsModelType) => {
modelType = MODEL_TYPE[jsModelType];
// Get model_type for python side
// Get current tab
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);
extraNetworkId = `${activeTabType}_${jsModelType}_${CARDID_SUFFIX}`;
extraNetworkNode = gradioApp().querySelector(`#${extraNetworkId}`);
// Check if extra network node exists
if (extraNetworkNode === null) return;
// Check if extra network node exists
if (extraNetworkNode === undefined) continue;
// Check if extr network is under thumbnail mode
isThumbMode = false;
if (extraNetworkNode?.className === 'extra-network-thumbs') isThumbMode = true;
// Check if extr network is under thumbnail mode
isThumbMode = false;
if (extraNetworkNode?.className === 'extra-network-thumbs') isThumbMode = true;
// Get all card nodes
cards = extraNetworkNode.querySelectorAll('.card');
for (const card of cards) {
if (card.querySelectorAll('.actions .additional a').length > 2) return;
// Metadata_buttoncard
metadataButton = card.querySelector('.metadata-button');
// Additional node
additionalNode = card.querySelector('.actions .additional');
// 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');
// Get all card nodes
cards = extraNetworkNode.querySelectorAll('.card');
for (const card of cards) {
if (card.querySelectorAll('.actions .additional a').length > 2) continue;
// Metadata_buttoncard
metadataButton = card.querySelector('.metadata-button');
// Additional node
additionalNode = card.querySelector('.actions .additional');
// Get ul node, which is the parent of all buttons
ulNode = card.querySelector('.actions .additional ul');
// Replace preview text button
replacePreviewButton = card.querySelector('.actions .additional a');
// Check thumb mode
if (isThumbMode && additionalNode) {
additionalNode.style.display = null;
// Check thumb mode
if (isThumbMode && additionalNode) {
additionalNode.style.display = undefined;
if (chShowBtnOnThumb) {
ulNode.style.background = BTN_THUMB_BACKGROUND;
} else {
// Reset
ulNode.style.background = null;
// Remove existed buttons
if (ulNode) {
// Find all .a child nodes
const atags = ulNode.querySelectorAll('a');
if (chShowButtonOnThumb) {
ulNode.style.background = BTN_THUMB_BACKGROUND;
} else {
// Reset
ulNode.style.background = undefined;
// Remove existed buttons
if (ulNode) {
// Find all .a child nodes
const atags = ulNode.querySelectorAll('a');
for (const atag of atags) {
// Reset display
atag.style.display = null;
// Remove extension's button
if (CH_BTN_TXTS.indexOf(atag.innerHTML) >= 0) {
// Need to remove
ulNode.removeChild(atag);
for (const atag of atags) {
// Reset display
atag.style.display = undefined;
// Remove extension's button
if (CH_BTN_TXTS.has(atag.innerHTML)) {
// Need to remove
atag.remove();
} else {
// Do not remove, just reset
atag.innerHTML = replacePreviewText;
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) brtag.remove();
}
// Just reset and remove nodes, do nothing else
continue;
}
} 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;
// Full preview mode
additionalNode.style.display = chAlwaysDisplay ? 'block' : undefined;
// Remove br tag
const brtag = ulNode.querySelector('br');
if (brtag) brtag.remove();
}
}
// Also remove br tag in ul
const brtag = ulNode.querySelector('br');
if (brtag) ulNode.removeChild(brtag);
// Change replace preview text button into icon
if (replacePreviewButton?.innerHTML !== '🖼️') {
needToAddButtons = true;
replacePreviewButton.innerHTML = '🖼️';
styleButton(replacePreviewButton, isThumbMode);
}
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) continue;
// Then we need to add 3 buttons to each ul node:
const openUrlNode = document.createElement('a');
openUrlNode.href = '#';
openUrlNode.innerHTML = '🌐';
styleButton(openUrlNode, isThumbMode);
openUrlNode.title = "Open this model's civitai url";
openUrlNode.setAttribute(
'onclick',
`open_model_url(event, '${modelType}', '${searchTerm}')`,
);
const addTriggerWordsNode = document.createElement('a');
addTriggerWordsNode.href = '#';
addTriggerWordsNode.innerHTML = '💡';
styleButton(addTriggerWordsNode, isThumbMode);
addTriggerWordsNode.title = 'Add trigger words to prompt';
addTriggerWordsNode.setAttribute(
'onclick',
`add_trigger_words(event, '${modelType}', '${searchTerm}')`,
);
const usePreviewPromptNode = document.createElement('a');
usePreviewPromptNode.href = '#';
usePreviewPromptNode.innerHTML = '🏷️';
styleButton(usePreviewPromptNode, isThumbMode);
usePreviewPromptNode.title = 'Use prompt from preview image';
usePreviewPromptNode.setAttribute(
'onclick',
`use_preview_prompt(event, '${modelType}', '${searchTerm}')`,
);
// Add to card
ulNode.append(openUrlNode);
// Add br if metadata_button exists
if (isThumbMode && metadataButton) ulNode.append(document.createElement('br'));
ulNode.append(addTriggerWordsNode);
ulNode.append(usePreviewPromptNode);
}
// Just reset and remove nodes, do nothing else
return;
}
} else {
// Full preview mode
additionalNode.style.display = chAlwaysDisplay ? 'block' : null;
// Remove br tag
const brtag = ulNode.querySelector('br');
if (brtag) ulNode.removeChild(brtag);
}
// Change replace preview text button into icon
if (replacePreviewBtn?.innerHTML !== '🖼️') {
needToAddButtons = true;
replacePreviewBtn.innerHTML = '🖼️';
styleBtn(replacePreviewBtn, isThumbMode);
}
if (!needToAddButtons) return;
// 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;
// Then we need to add 3 buttons to each ul node:
const openUrlNode = document.createElement('a');
openUrlNode.href = '#';
openUrlNode.innerHTML = '🌐';
styleBtn(openUrlNode, isThumbMode);
openUrlNode.title = "Open this model's civitai url";
openUrlNode.setAttribute(
'onclick',
`open_model_url(event, '${modelType}', '${searchTerm}')`,
);
const addTriggerWordsNode = document.createElement('a');
addTriggerWordsNode.href = '#';
addTriggerWordsNode.innerHTML = '💡';
styleBtn(addTriggerWordsNode, isThumbMode);
addTriggerWordsNode.title = 'Add trigger words to prompt';
addTriggerWordsNode.setAttribute(
'onclick',
`add_trigger_words(event, '${modelType}', '${searchTerm}')`,
);
const usePreviewPromptNode = document.createElement('a');
usePreviewPromptNode.href = '#';
usePreviewPromptNode.innerHTML = '🏷️';
styleBtn(usePreviewPromptNode, isThumbMode);
usePreviewPromptNode.title = 'Use prompt from preview image';
usePreviewPromptNode.setAttribute(
'onclick',
`use_preview_prompt(event, '${modelType}', '${searchTerm}')`,
);
// Add to card
ulNode.appendChild(openUrlNode);
// Add br if metadata_button exists
if (isThumbMode && metadataButton) ulNode.appendChild(document.createElement('br'));
ulNode.appendChild(addTriggerWordsNode);
ulNode.appendChild(usePreviewPromptNode);
}
});
});
}
};
export default () => {
const fixInterval = setInterval(() => {
const checkDom = document.querySelector('#txt2img_lora_cards');
if (checkDom) {
updateCardForCivitai();
clearInterval(fixInterval);
}
}, 1000);
const fixInterval = setInterval(() => {
const checkDom = document.querySelector('#txt2img_lora_cards');
if (checkDom) {
updateCardForCivitai();
clearInterval(fixInterval);
}
}, 1000);
};

View File

@ -1,67 +1,67 @@
const MIN_WIDTH = 240;
const addDraggable = (tabId: string) => {
const settings = document.getElementById(`${tabId}_settings`);
const checkDraggableLine = document.querySelector(`#tab_${tabId} .draggable-line`);
if (!settings || checkDraggableLine) return;
const settings: any = document.querySelector(`#${tabId}_settings`);
const checkDraggableLine = document.querySelector(`#tab_${tabId} .draggable-line`);
if (!settings || checkDraggableLine) return;
settings.style.minWidth = `min(${MIN_WIDTH}px, 100%)`;
settings.style.minWidth = `min(${MIN_WIDTH}px, 100%)`;
const lineWrapper = document.createElement('div');
lineWrapper.classList.add('draggable-line');
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 container: HTMLElement | any = settings.parentElement;
container.classList.add('draggable-container');
const results = document.getElementById(`${tabId}_results`);
if (!results) return;
const results: any = document.querySelector(`#${tabId}_results`);
if (!results) return;
results.style.minWidth = `${MIN_WIDTH}px`;
let linePosition = 50;
settings.style.flexBasis = `${linePosition}%`;
results.style.flexBasis = `${100 - linePosition}%`;
let isDragging = false;
lineWrapper.addEventListener('mousedown', (e) => {
isDragging = true;
e.preventDefault();
});
document.addEventListener('mousemove', (event) => {
if (!isDragging) return;
const tab: HTMLElement | any = document.querySelector(`#tab_${tabId}`);
if (!tab) return;
let offsetX = tab.offsetLeft;
let parent = tab.offsetParent;
while (parent) {
offsetX += parent.offsetLeft;
parent = parent.offsetParent;
}
const containerWidth = container.offsetWidth;
const mouseX = event.clientX;
const linePosition = ((mouseX - offsetX) / containerWidth) * 100;
if (linePosition <= (MIN_WIDTH / containerWidth) * 100) return;
if (linePosition >= (1 - MIN_WIDTH / containerWidth) * 100) return;
results.style.minWidth = `${MIN_WIDTH}px`;
let linePosition = 50;
settings.style.flexBasis = `${linePosition}%`;
results.style.flexBasis = `${100 - linePosition}%`;
});
document.addEventListener('mouseup', () => {
isDragging = false;
});
let isDragging = false;
lineWrapper.addEventListener('mousedown', (e) => {
isDragging = true;
e.preventDefault();
});
document.addEventListener('mousemove', (event) => {
if (!isDragging) return;
const tab: HTMLElement | any = document.querySelector(`#tab_${tabId}`);
if (!tab) return;
let offsetX = tab.offsetLeft;
let parent = tab.offsetParent;
while (parent) {
offsetX += parent.offsetLeft;
parent = parent.offsetParent;
}
const containerWidth = container.offsetWidth;
const mouseX = event.clientX;
const linePosition = ((mouseX - offsetX) / containerWidth) * 100;
if (linePosition <= (MIN_WIDTH / containerWidth) * 100) return;
if (linePosition >= (1 - MIN_WIDTH / containerWidth) * 100) return;
settings.style.flexBasis = `${linePosition}%`;
results.style.flexBasis = `${100 - linePosition}%`;
});
document.addEventListener('mouseup', () => {
isDragging = false;
});
};
export default () => {
addDraggable('txt2img');
addDraggable('img2img');
addDraggable('txt2img');
addDraggable('img2img');
};

View File

@ -1,280 +1,279 @@
/**
*
*/
export class Converter {
/**
*
* @param value
* @returns
export const Converter = {
/**
*
* @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;
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 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(', ');
}
/**
*
* @param input
* @returns
*/
static convert(input: string): string {
const re_attention = /\{|\[|\}|\]|[^{}[\]]+/gmu;
convert(input: string): string {
const re_attention = /\{|\[|\}|\]|[^{}[\]]+/gmu;
let text = Converter.convertStr(input);
const textArray = Converter.convertStr2Array(text);
text = Converter.convertArray2Str(textArray);
let text = Converter.convertStr(input);
const textArray = Converter.convertStr2Array(text);
text = Converter.convertArray2Str(textArray);
let res: [string, number][] = [];
let res: [string, number][] = [];
const curly_bracket_multiplier = 1.05;
const square_bracket_multiplier = 1 / 1.05;
const curly_bracket_multiplier = 1.05;
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 },
};
const brackets: Record<string, { multiplier: number; stack: number[] }> = {
'[': {multiplier: square_bracket_multiplier, stack: []},
'{': {multiplier: curly_bracket_multiplier, stack: []},
};
/**
/**
*
* @param start_position
* @param multiplier
*/
function multiply_range(start_position: number, multiplier: number) {
for (let pos = start_position; pos < res.length; pos++) {
res[pos][1] = Converter.round(res[pos][1] * multiplier);
}
}
for (const match of text.matchAll(re_attention)) {
let word = match[0];
if (word in brackets) {
brackets[word].stack.push(res.length);
} else if (word === '}' || word === ']') {
const bracket = brackets[word === '}' ? '{' : '['];
if (bracket.stack.length > 0) {
multiply_range(bracket.stack.pop()!, bracket.multiplier);
function multiply_range(start_position: number, multiplier: number) {
for (let pos = start_position; pos < res.length; pos++) {
res[pos][1] = Converter.round(res[pos][1] * multiplier);
}
}
} else {
res.push([word, 1.0]);
}
}
Object.keys(brackets).forEach((bracketType) => {
brackets[bracketType].stack.forEach((pos) => {
multiply_range(pos, brackets[bracketType].multiplier);
});
});
for (const match of text.matchAll(re_attention)) {
let word = match[0];
if (res.length === 0) {
res = [['', 1.0]];
}
if (word in brackets) {
brackets[word].stack.push(res.length);
} else if (word === '}' || word === ']') {
const bracket = brackets[word === '}' ? '{' : '['];
if (bracket.stack.length > 0) {
multiply_range(bracket.stack.pop()!, bracket.multiplier);
}
} else {
res.push([word, 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);
} else {
i += 1;
}
}
for (const bracketType of Object.keys(brackets)) {
for (const pos of brackets[bracketType].stack) {
multiply_range(pos, brackets[bracketType].multiplier);
}
}
let result = '';
for (const [word, value] of res) {
result += value === 1.0 ? word : `(${word}:${value.toString()})`;
}
return result;
}
if (res.length === 0) {
res = [['', 1]];
}
/**
* input
* @param target
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 {
index += 1;
}
}
let result = '';
for (const [word, value] of res) {
result += value === 1 ? word : `(${word}:${value.toString()})`;
}
return result;
},
/**
*
* @param array
* @returns
*/
static dispatchInputEvent(target: EventTarget) {
let inputEvent = new Event('input');
Object.defineProperty(inputEvent, 'target', { value: target });
target.dispatchEvent(inputEvent);
}
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 type
/**
*
* @param srt
* @returns
*/
static onClickConvert(type: string) {
const default_prompt = '';
const default_negative = '';
convertStr(srt: string): string {
return srt.replaceAll('', ':').replaceAll('', '(').replaceAll('', ')');
},
const prompt = gradioApp().querySelector(
`#${type}_prompt > label > textarea`,
) as HTMLTextAreaElement;
const result = Converter.convert(prompt.value);
prompt.value =
result.match(/^masterpiece, best quality,/) === null ? default_prompt + result : result;
Converter.dispatchInputEvent(prompt);
const negprompt = gradioApp().querySelector(
`#${type}_neg_prompt > label > textarea`,
) as HTMLTextAreaElement;
const negResult = Converter.convert(negprompt.value);
negprompt.value =
negResult.match(/^lowres,/) === null
? negResult.length === 0
? default_negative
: default_negative + negResult
: negResult;
Converter.dispatchInputEvent(negprompt);
}
/**
*
* @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
*/
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;
}
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 -
/**
* input
* @param target
*/
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);
}
}
dispatchInputEvent(target: EventTarget) {
let inputEvent = new Event('input');
Object.defineProperty(inputEvent, 'target', {value: target});
target.dispatchEvent(inputEvent);
},
/**
*
* @param type
*/
onClickConvert(type: string) {
const default_prompt = '';
const default_negative = '';
const prompt = gradioApp().querySelector(
`#${type}_prompt > label > textarea`,
) as HTMLTextAreaElement;
const result = Converter.convert(prompt.value);
prompt.value =
result.match(/^masterpiece, best quality,/) === null ? default_prompt + result : result;
Converter.dispatchInputEvent(prompt);
const negprompt = gradioApp().querySelector(
`#${type}_neg_prompt > label > textarea`,
) as HTMLTextAreaElement;
const negResult = Converter.convert(negprompt.value);
negprompt.value =
negResult.match(/^lowres,/) === null ?
negResult.length === 0 ?
default_negative :
default_negative + negResult :
negResult;
Converter.dispatchInputEvent(negprompt);
},
/**
*
* @param value
* @returns
*/
round(value: number): number {
return Math.round(value * 10_000) / 10_000;
},
};
export default () => {
Converter.addPromptButton('txt2img');
Converter.addPromptButton('img2img');
Converter.addPromptButton('txt2img');
Converter.addPromptButton('img2img');
};

View File

@ -4,52 +4,52 @@ interface ErrorString {
}
class BracketChecker {
private textArea: HTMLTextAreaElement;
private counterElt: HTMLElement;
private errorStrings: ErrorString[];
private textArea: HTMLTextAreaElement;
private counterElt: HTMLElement;
private errorStrings: ErrorString[];
constructor(textArea: HTMLTextAreaElement, counterElt: HTMLElement) {
this.textArea = textArea;
this.counterElt = counterElt;
this.errorStrings = [
{
regex: '\\(',
error: '(...) - Different number of opening and closing parentheses detected.\n',
},
{
regex: '\\[',
error: '[...] - Different number of opening and closing square brackets detected.\n',
},
{
regex: '\\{',
error: '{...} - Different number of opening and closing curly brackets detected.\n',
},
];
}
constructor(textArea: HTMLTextAreaElement, counterElt: HTMLElement) {
this.textArea = textArea;
this.counterElt = counterElt;
this.errorStrings = [
{
error: '(...) - Different number of opening and closing parentheses detected.\n',
regex: '\\(',
},
{
error: '[...] - Different number of opening and closing square brackets detected.\n',
regex: '\\[',
},
{
error: '{...} - Different number of opening and closing curly brackets detected.\n',
regex: '\\{',
},
];
}
/**
/**
*
*/
public check = (): void => {
let title = '';
this.errorStrings.forEach(({ regex, error }) => {
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'),
) || []
).length;
if (openMatches !== closeMatches) {
if (!this.counterElt.title.includes(error)) {
title += error;
public check = (): void => {
let title = '';
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.replaceAll('(', ')').replaceAll('[', ']').replaceAll('{', '}'), 'g'),
) || []
).length;
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);
};
this.counterElt.title = title;
this.counterElt.classList.toggle('error', !!title);
};
}
/**
@ -58,18 +58,18 @@ class BracketChecker {
* @param id_counter ID
*/
const setupBracketChecking = (idPrompt: string, idCounter: string): void => {
const textarea = gradioApp().querySelector(
`#${idPrompt} > label > textarea`,
) as HTMLTextAreaElement;
const counter = gradioApp().getElementById(idCounter) as HTMLElement;
const bracketChecker = new BracketChecker(textarea, counter);
textarea.addEventListener('input', bracketChecker.check);
const textarea = gradioApp().querySelector(
`#${idPrompt} > label > textarea`,
) as HTMLTextAreaElement;
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) => {
setupBracketChecking(`${prompt}_prompt`, `${prompt}_token_counter`);
setupBracketChecking(`${prompt}_prompt`, `${prompt}_negative_token_counter`);
});
const elements = ['txt2img', 'txt2img_neg', 'img2img', 'img2img_neg'];
for (const prompt of elements) {
setupBracketChecking(`${prompt}_prompt`, `${prompt}_token_counter`);
setupBracketChecking(`${prompt}_prompt`, `${prompt}_negative_token_counter`);
}
};

View File

@ -1,73 +1,73 @@
const replaceIcon = (button: HTMLButtonElement, emoji: string[], svg: string) => {
if (!button?.textContent) return;
emoji.forEach((e) => {
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>`;
if (!button?.textContent) return;
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) => {
replaceIcon(
button,
['📂'],
'<path d="M880 298.4H521L403.7 186.2a8.15 8.15 0 00-5.5-2.2H144c-17.7 0-32 14.3-32 32v592c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V330.4c0-17.7-14.3-32-32-32zM840 768H184V256h188.5l119.6 114.4H840V768z"></path>',
);
replaceIcon(
button,
['🔄', '🔁'],
'<path d="M909.1 209.3l-56.4 44.1C775.8 155.1 656.2 92 521.9 92 290 92 102.3 279.5 102 511.5 101.7 743.7 289.8 932 521.9 932c181.3 0 335.8-115 394.6-276.1 1.5-4.2-.7-8.9-4.9-10.3l-56.7-19.5a8 8 0 00-10.1 4.8c-1.8 5-3.8 10-5.9 14.9-17.3 41-42.1 77.8-73.7 109.4A344.77 344.77 0 01655.9 829c-42.3 17.9-87.4 27-133.8 27-46.5 0-91.5-9.1-133.8-27A341.5 341.5 0 01279 755.2a342.16 342.16 0 01-73.7-109.4c-17.9-42.4-27-87.4-27-133.9s9.1-91.5 27-133.9c17.3-41 42.1-77.8 73.7-109.4 31.6-31.6 68.4-56.4 109.3-73.8 42.3-17.9 87.4-27 133.8-27 46.5 0 91.5 9.1 133.8 27a341.5 341.5 0 01109.3 73.8c9.9 9.9 19.2 20.4 27.8 31.4l-60.2 47a8 8 0 003 14.1l175.6 43c5 1.2 9.9-2.6 9.9-7.7l.8-180.9c-.1-6.6-7.8-10.3-13-6.2z"></path>',
);
replaceIcon(
button,
['↙️'],
'<path d="M603.3 327.5l-246 178a7.95 7.95 0 000 12.9l246 178c5.3 3.8 12.7 0 12.7-6.5V643c0-10.2-4.9-19.9-13.2-25.9L457.4 512l145.4-105.2c8.3-6 13.2-15.6 13.2-25.9V334c0-6.5-7.4-10.3-12.7-6.5z"></path><path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372z"></path>',
);
replaceIcon(
button,
['🗑️'],
'<path d="M360 184h-8c4.4 0 8-3.6 8-8v8h304v-8c0 4.4 3.6 8 8 8h-8v72h72v-80c0-35.3-28.7-64-64-64H352c-35.3 0-64 28.7-64 64v80h72v-72zm504 72H160c-17.7 0-32 14.3-32 32v32c0 4.4 3.6 8 8 8h60.4l24.7 523c1.6 34.1 29.8 61 63.9 61h454c34.2 0 62.3-26.8 63.9-61l24.7-523H888c4.4 0 8-3.6 8-8v-32c0-17.7-14.3-32-32-32zM731.3 840H292.7l-24.2-512h487l-24.2 512z"></path>',
);
replaceIcon(
button,
['📋'],
'<path d="M832 112H724V72c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v40H500V72c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v40H320c-17.7 0-32 14.3-32 32v120h-96c-17.7 0-32 14.3-32 32v632c0 17.7 14.3 32 32 32h512c17.7 0 32-14.3 32-32v-96h96c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32zM664 888H232V336h218v174c0 22.1 17.9 40 40 40h174v338zm0-402H514V336h.2L664 485.8v.2zm128 274h-56V456L544 264H360v-80h68v32c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8v-32h152v32c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8v-32h68v576z"></path>',
);
replaceIcon(
button,
['💾'],
'<path d="M893.3 293.3L730.7 130.7c-7.5-7.5-16.7-13-26.7-16V112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V338.5c0-17-6.7-33.2-18.7-45.2zM384 184h256v104H384V184zm456 656H184V184h136v136c0 17.7 14.3 32 32 32h320c17.7 0 32-14.3 32-32V205.8l136 136V840zM512 442c-79.5 0-144 64.5-144 144s64.5 144 144 144 144-64.5 144-144-64.5-144-144-144zm0 224c-44.2 0-80-35.8-80-80s35.8-80 80-80 80 35.8 80 80-35.8 80-80 80z"></path>',
);
replaceIcon(
button,
['🎲️'],
'<path d="M136 552h63.6c4.4 0 8-3.6 8-8V288.7h528.6v72.6c0 1.9.6 3.7 1.8 5.2a8.3 8.3 0 0011.7 1.4L893 255.4c4.3-5 3.6-10.3 0-13.2L749.7 129.8a8.22 8.22 0 00-5.2-1.8c-4.6 0-8.4 3.8-8.4 8.4V209H199.7c-39.5 0-71.7 32.2-71.7 71.8V544c0 4.4 3.6 8 8 8zm752-80h-63.6c-4.4 0-8 3.6-8 8v255.3H287.8v-72.6c0-1.9-.6-3.7-1.8-5.2a8.3 8.3 0 00-11.7-1.4L131 768.6c-4.3 5-3.6 10.3 0 13.2l143.3 112.4c1.5 1.2 3.3 1.8 5.2 1.8 4.6 0 8.4-3.8 8.4-8.4V815h536.6c39.5 0 71.7-32.2 71.7-71.8V480c-.2-4.4-3.8-8-8.2-8z"></path>',
);
replaceIcon(
button,
['♻️'],
'<path d="M793 242H366v-74c0-6.7-7.7-10.4-12.9-6.3l-142 112a8 8 0 000 12.6l142 112c5.2 4.1 12.9.4 12.9-6.3v-74h415v470H175c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h618c35.3 0 64-28.7 64-64V306c0-35.3-28.7-64-64-64z"></path>',
);
replaceIcon(
button,
['🪄'],
'<defs><style></style></defs><path d="M899.1 869.6l-53-305.6H864c14.4 0 26-11.6 26-26V346c0-14.4-11.6-26-26-26H618V138c0-14.4-11.6-26-26-26H432c-14.4 0-26 11.6-26 26v182H160c-14.4 0-26 11.6-26 26v192c0 14.4 11.6 26 26 26h17.9l-53 305.6a25.95 25.95 0 0025.6 30.4h723c1.5 0 3-.1 4.4-.4a25.88 25.88 0 0021.2-30zM204 390h272V182h72v208h272v104H204V390zm468 440V674c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v156H416V674c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v156H202.8l45.1-260H776l45.1 260H672z"></path>',
);
replaceIcon(
button,
['⚙️'],
'<path d="M400 317.7h73.9V656c0 4.4 3.6 8 8 8h60c4.4 0 8-3.6 8-8V317.7H624c6.7 0 10.4-7.7 6.3-12.9L518.3 163a8 8 0 00-12.6 0l-112 141.7c-4.1 5.3-.4 13 6.3 13zM878 626h-60c-4.4 0-8 3.6-8 8v154H214V634c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v198c0 17.7 14.3 32 32 32h684c17.7 0 32-14.3 32-32V634c0-4.4-3.6-8-8-8z"></path>',
);
replaceIcon(
button,
['➡️'],
'<path d="M666.7 505.5l-246-178A8 8 0 00408 334v46.9c0 10.2 4.9 19.9 13.2 25.9L566.6 512 421.2 617.2c-8.3 6-13.2 15.6-13.2 25.9V690c0 6.5 7.4 10.3 12.7 6.5l246-178c4.4-3.2 4.4-9.8 0-13z"></path><path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372z"></path>',
);
replaceIcon(
button,
['⇅'],
'<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>',
);
});
for (const button of document.querySelectorAll('button')) {
replaceIcon(
button,
['📂'],
'<path d="M880 298.4H521L403.7 186.2a8.15 8.15 0 00-5.5-2.2H144c-17.7 0-32 14.3-32 32v592c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V330.4c0-17.7-14.3-32-32-32zM840 768H184V256h188.5l119.6 114.4H840V768z"></path>',
);
replaceIcon(
button,
['🔄', '🔁'],
'<path d="M909.1 209.3l-56.4 44.1C775.8 155.1 656.2 92 521.9 92 290 92 102.3 279.5 102 511.5 101.7 743.7 289.8 932 521.9 932c181.3 0 335.8-115 394.6-276.1 1.5-4.2-.7-8.9-4.9-10.3l-56.7-19.5a8 8 0 00-10.1 4.8c-1.8 5-3.8 10-5.9 14.9-17.3 41-42.1 77.8-73.7 109.4A344.77 344.77 0 01655.9 829c-42.3 17.9-87.4 27-133.8 27-46.5 0-91.5-9.1-133.8-27A341.5 341.5 0 01279 755.2a342.16 342.16 0 01-73.7-109.4c-17.9-42.4-27-87.4-27-133.9s9.1-91.5 27-133.9c17.3-41 42.1-77.8 73.7-109.4 31.6-31.6 68.4-56.4 109.3-73.8 42.3-17.9 87.4-27 133.8-27 46.5 0 91.5 9.1 133.8 27a341.5 341.5 0 01109.3 73.8c9.9 9.9 19.2 20.4 27.8 31.4l-60.2 47a8 8 0 003 14.1l175.6 43c5 1.2 9.9-2.6 9.9-7.7l.8-180.9c-.1-6.6-7.8-10.3-13-6.2z"></path>',
);
replaceIcon(
button,
['↙️'],
'<path d="M603.3 327.5l-246 178a7.95 7.95 0 000 12.9l246 178c5.3 3.8 12.7 0 12.7-6.5V643c0-10.2-4.9-19.9-13.2-25.9L457.4 512l145.4-105.2c8.3-6 13.2-15.6 13.2-25.9V334c0-6.5-7.4-10.3-12.7-6.5z"></path><path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372z"></path>',
);
replaceIcon(
button,
['🗑️'],
'<path d="M360 184h-8c4.4 0 8-3.6 8-8v8h304v-8c0 4.4 3.6 8 8 8h-8v72h72v-80c0-35.3-28.7-64-64-64H352c-35.3 0-64 28.7-64 64v80h72v-72zm504 72H160c-17.7 0-32 14.3-32 32v32c0 4.4 3.6 8 8 8h60.4l24.7 523c1.6 34.1 29.8 61 63.9 61h454c34.2 0 62.3-26.8 63.9-61l24.7-523H888c4.4 0 8-3.6 8-8v-32c0-17.7-14.3-32-32-32zM731.3 840H292.7l-24.2-512h487l-24.2 512z"></path>',
);
replaceIcon(
button,
['📋'],
'<path d="M832 112H724V72c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v40H500V72c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v40H320c-17.7 0-32 14.3-32 32v120h-96c-17.7 0-32 14.3-32 32v632c0 17.7 14.3 32 32 32h512c17.7 0 32-14.3 32-32v-96h96c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32zM664 888H232V336h218v174c0 22.1 17.9 40 40 40h174v338zm0-402H514V336h.2L664 485.8v.2zm128 274h-56V456L544 264H360v-80h68v32c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8v-32h152v32c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8v-32h68v576z"></path>',
);
replaceIcon(
button,
['💾'],
'<path d="M893.3 293.3L730.7 130.7c-7.5-7.5-16.7-13-26.7-16V112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V338.5c0-17-6.7-33.2-18.7-45.2zM384 184h256v104H384V184zm456 656H184V184h136v136c0 17.7 14.3 32 32 32h320c17.7 0 32-14.3 32-32V205.8l136 136V840zM512 442c-79.5 0-144 64.5-144 144s64.5 144 144 144 144-64.5 144-144-64.5-144-144-144zm0 224c-44.2 0-80-35.8-80-80s35.8-80 80-80 80 35.8 80 80-35.8 80-80 80z"></path>',
);
replaceIcon(
button,
['🎲️'],
'<path d="M136 552h63.6c4.4 0 8-3.6 8-8V288.7h528.6v72.6c0 1.9.6 3.7 1.8 5.2a8.3 8.3 0 0011.7 1.4L893 255.4c4.3-5 3.6-10.3 0-13.2L749.7 129.8a8.22 8.22 0 00-5.2-1.8c-4.6 0-8.4 3.8-8.4 8.4V209H199.7c-39.5 0-71.7 32.2-71.7 71.8V544c0 4.4 3.6 8 8 8zm752-80h-63.6c-4.4 0-8 3.6-8 8v255.3H287.8v-72.6c0-1.9-.6-3.7-1.8-5.2a8.3 8.3 0 00-11.7-1.4L131 768.6c-4.3 5-3.6 10.3 0 13.2l143.3 112.4c1.5 1.2 3.3 1.8 5.2 1.8 4.6 0 8.4-3.8 8.4-8.4V815h536.6c39.5 0 71.7-32.2 71.7-71.8V480c-.2-4.4-3.8-8-8.2-8z"></path>',
);
replaceIcon(
button,
['♻️'],
'<path d="M793 242H366v-74c0-6.7-7.7-10.4-12.9-6.3l-142 112a8 8 0 000 12.6l142 112c5.2 4.1 12.9.4 12.9-6.3v-74h415v470H175c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h618c35.3 0 64-28.7 64-64V306c0-35.3-28.7-64-64-64z"></path>',
);
replaceIcon(
button,
['🪄'],
'<defs><style></style></defs><path d="M899.1 869.6l-53-305.6H864c14.4 0 26-11.6 26-26V346c0-14.4-11.6-26-26-26H618V138c0-14.4-11.6-26-26-26H432c-14.4 0-26 11.6-26 26v182H160c-14.4 0-26 11.6-26 26v192c0 14.4 11.6 26 26 26h17.9l-53 305.6a25.95 25.95 0 0025.6 30.4h723c1.5 0 3-.1 4.4-.4a25.88 25.88 0 0021.2-30zM204 390h272V182h72v208h272v104H204V390zm468 440V674c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v156H416V674c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v156H202.8l45.1-260H776l45.1 260H672z"></path>',
);
replaceIcon(
button,
['⚙️'],
'<path d="M400 317.7h73.9V656c0 4.4 3.6 8 8 8h60c4.4 0 8-3.6 8-8V317.7H624c6.7 0 10.4-7.7 6.3-12.9L518.3 163a8 8 0 00-12.6 0l-112 141.7c-4.1 5.3-.4 13 6.3 13zM878 626h-60c-4.4 0-8 3.6-8 8v154H214V634c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v198c0 17.7 14.3 32 32 32h684c17.7 0 32-14.3 32-32V634c0-4.4-3.6-8-8-8z"></path>',
);
replaceIcon(
button,
['➡️'],
'<path d="M666.7 505.5l-246-178A8 8 0 00408 334v46.9c0 10.2 4.9 19.9 13.2 25.9L566.6 512 421.2 617.2c-8.3 6-13.2 15.6-13.2 25.9V690c0 6.5 7.4 10.3 12.7 6.5l246-178c4.4-3.2 4.4-9.8 0-13z"></path><path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372z"></path>',
);
replaceIcon(
button,
['⇅'],
'<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

@ -1,9 +1,9 @@
export default () => {
// favicon
const favicon: HTMLLinkElement = document.createElement('link');
favicon.rel = 'icon';
favicon.type = 'image/svg+xml';
favicon.href =
// favicon
const favicon: HTMLLinkElement = document.createElement('link');
favicon.rel = 'icon';
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

@ -1,5 +1,5 @@
import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
import {create} from 'zustand';
import {devtools} from 'zustand/middleware';
const SETTING_KEY = 'SD-KITCHEN-SETTING';
@ -17,16 +17,16 @@ export interface WebuiSetting {
}
export const defaultSetting: WebuiSetting = {
promotTextarea: 'scroll',
sidebarExpand: true,
sidebarFixedMode: 'fixed',
sidebarWidth: 280,
enableExtraNetworkSidebar: true,
extraNetworkSidebarExpand: true,
extraNetworkFixedMode: 'fixed',
extraNetworkSidebarWidth: 340,
extraNetworkCardSize: 86,
svgIcon: false,
enableExtraNetworkSidebar: true,
extraNetworkCardSize: 86,
extraNetworkFixedMode: 'fixed',
extraNetworkSidebarExpand: true,
extraNetworkSidebarWidth: 340,
promotTextarea: 'scroll',
sidebarExpand: true,
sidebarFixedMode: 'fixed',
sidebarWidth: 280,
svgIcon: false,
};
export interface AppState {
currentTab: string;
@ -39,33 +39,33 @@ export interface AppState {
themeMode: 'light' | 'dark';
}
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');
},
onLoadSetting: () => {
let setting: any = localStorage.getItem(SETTING_KEY);
if (setting) {
setting = JSON.parse(setting);
} else {
setting = defaultSetting;
localStorage.setItem(SETTING_KEY, JSON.stringify(defaultSetting));
}
set(() => ({ setting: { ...defaultSetting, ...setting } }), false, 'onLoadSetting');
},
onSetSetting: (setting) => {
localStorage.setItem(SETTING_KEY, JSON.stringify(setting));
set(() => ({ setting }), false, 'onSetSetting');
},
onInit: () => {
get().onLoadSetting();
},
})),
devtools((set, get) => ({
currentTab: 'tab_txt2img',
onInit: () => {
get().onLoadSetting();
},
onLoadSetting: () => {
let setting: any = localStorage.getItem(SETTING_KEY);
if (setting) {
setting = JSON.parse(setting);
} else {
setting = defaultSetting;
localStorage.setItem(SETTING_KEY, JSON.stringify(defaultSetting));
}
set(() => ({setting: {...defaultSetting, ...setting}}), false, 'onLoadSetting');
},
onSetSetting: (setting) => {
localStorage.setItem(SETTING_KEY, JSON.stringify(setting));
set(() => ({setting}), false, 'onSetSetting');
},
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"]
}