File size: 10,801 Bytes
3dabe4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
import type { GlobalConf } from '@/api'
import type { ExtraPathType, MatchImageByTagsReq, Tag } from '@/api/db'
import { FileNodeInfo } from '@/api/files'
import { i18n, t } from '@/i18n'
import { getPreferredLang } from '@/i18n'
import { SortMethod } from '@/page/fileTransfer/fileSort'
import { Props as FileTransferProps } from '@/page/fileTransfer/hooks'
import type { getQuickMovePaths } from '@/page/taskRecord/autoComplete'
import { type Dict, type ReturnTypeAsync } from '@/util'
import { AnyFn, usePreferredDark } from '@vueuse/core'
import { cloneDeep, uniqueId, last } from 'lodash-es'
import { defineStore } from 'pinia'
import { VNode, computed, onMounted, reactive, toRaw, watch } from 'vue'
import { ref } from 'vue'
import { WithRequired } from 'vue3-ts-util'
import * as Path from '../util/path'
import { prefix } from '@/util/const'

interface TabPaneBase {
  name: string | VNode
  nameFallbackStr?: string
  readonly key: string
}

interface OtherTabPane extends TabPaneBase {
  type: 'global-setting' | 'tag-search' |  'batch-download' | 'workspace-snapshot'
}

export interface EmptyStartTabPane extends TabPaneBase  {
  type: 'empty' 
  popAddPathModal?: {
    path: string
    type: ExtraPathType
  }
}

export type GridViewFileTag = WithRequired<Partial<Tag>, 'name'>;

export interface GridViewFile extends FileNodeInfo {
  /**
   * Tags for displaying the file. The 'name' property is required,
   * while the other properties are optional.
   */
  tags?: GridViewFileTag[];
}

/**
 * A tab pane that displays files in a grid view.
 */
interface GridViewTabPane extends TabPaneBase {
  type: 'grid-view'
  /**
   * Indicates whether the files in the grid view can be deleted.
   */
  removable?: boolean
  /**
   * Indicates whether files can be dragged and dropped from other pages into the grid view.
   */
  allowDragAndDrop?: boolean,
  files: GridViewFile[]
}


export interface GridViewFile extends FileNodeInfo {
  /**
   * Tags for displaying the file. The 'name' property is required,
   * while the other properties are optional.
   */
  tags?: GridViewFileTag[];
}

/**
 * A tab pane that displays files in a grid view.
 */
interface GridViewTabPane extends TabPaneBase {
  type: 'grid-view'
  /**
   * Indicates whether the files in the grid view can be deleted.
   */
  removable?: boolean
  /**
   * Indicates whether files can be dragged and dropped from other pages into the grid view.
   */
  allowDragAndDrop?: boolean,
  files: GridViewFile[]
}

interface TagSearchMatchedImageGridTabPane extends TabPaneBase {
  type: 'tag-search-matched-image-grid'
  selectedTagIds: MatchImageByTagsReq
  id: string
}
export interface ImgSliTabPane extends TabPaneBase {
  type: 'img-sli'
  left: FileNodeInfo
  right: FileNodeInfo
}

export interface FileTransferTabPane extends TabPaneBase {
  type: 'local'
  path?: string
  mode?: FileTransferProps['mode']
  stackKey?: string
}

export interface TagSearchTabPane extends TabPaneBase {
  type: 'tag-search'
  searchScope?: string
}

export interface FuzzySearchTabPane extends TabPaneBase {
  type: 'fuzzy-search'
  searchScope?: string
}

export type TabPane = EmptyStartTabPane | FileTransferTabPane | OtherTabPane | TagSearchMatchedImageGridTabPane | ImgSliTabPane | TagSearchTabPane | FuzzySearchTabPane| GridViewTabPane

/**
 * This interface represents a tab, which contains an array of panes, an ID, and a key
 */
export interface Tab {
  /**
   * An array of panes that belong to this tab
   */
  panes: TabPane[]
  /**
   * A unique identifier for this tab
   */
  id: string
  /**
   * A value indicating which pane is currently selected within the tab
   */
  key: string
}

export type Shortcut = Record<`toggle_tag_${string}` | 'delete' | 'download', string | undefined> 

export type DefaultInitinalPage = `workspace_snapshot_${string}` | 'empty' | 'last-workspace-state'

export const copyPane = (pane: TabPane) => {
  return cloneDeep({
    ...pane,
    name: typeof pane.name === 'string' ? pane.name : pane.nameFallbackStr ?? ''
  })
}

export const copyTab = (tab: Tab): Tab => {
  return {
    ...tab,
    panes: tab.panes.map(copyPane)
  }
}

export const copyTabFilterWorkspaceSnapShot = (tab: Tab): Tab => {
  if (!tab.panes.some(v => v.type === 'workspace-snapshot')) {
    return copyTab(tab)
  }
  const newPanes = tab.panes.filter(v => v.type !== 'workspace-snapshot').map(copyPane)
  return {
    ...tab,
    panes: newPanes,
    key: last(newPanes)?.key ?? ''
  }
}


export type ActionConfirmRequired = 'deleteOneOnly'

export const presistKeys = [
  'defaultChangeIndchecked',
  'defaultSeedChangeChecked',
  'darkModeControl',
  'dontShowAgainNewImgOpts',
  'defaultSortingMethod',
  'defaultGridCellWidth',
  'dontShowAgain',
  'lang',
  'enableThumbnail',
  'tabListHistoryRecord',
  'recent',
  'gridThumbnailResolution',
  'longPressOpenContextMenu',
  'onlyFoldersAndImages',
  'shortcut',
  'ignoredConfirmActions',
  'previewBgOpacity',
  'defaultInitinalPage',
  'autoRefreshWalkMode',
  'autoRefreshWalkModePosLimit',
  'autoRefreshNormalFixedMode',
  'showCommaInInfoPanel'
]

function cellWidthMap(x: number): number {
  if (x < 768) {
    return 176;
  } else {
    const y = 160 + Math.floor((x - 768) / 128) * 16;
    return Math.min(y, 256);
  }
}

export const useGlobalStore = defineStore(
  prefix + 'useGlobalStore',
  () => {
    const conf = ref<GlobalConf>()
    const quickMovePaths = ref([] as ReturnTypeAsync<typeof getQuickMovePaths>)

    const enableThumbnail = ref(true)
    const gridThumbnailResolution = ref(512)
    const defaultSortingMethod = ref(SortMethod.CREATED_TIME_DESC)
    const defaultGridCellWidth = ref(cellWidthMap(parent.window.innerHeight))
    
    const darkModeControl = ref<'light' | 'dark' | 'auto'>('auto')

    const createEmptyPane = (): TabPane => ({
      type: 'empty',
      name: t('emptyStartPage'),
      key: uniqueId()
    })
    const tabList = ref<Tab[]>([])
    onMounted(() => {
      const emptyPane = createEmptyPane()
      tabList.value.push({ panes: [emptyPane], key: emptyPane.key, id: uniqueId() })
    })
    const dragingTab = ref<{ tabIdx: number; paneIdx: number }>()
    const recent = ref(new Array<{ path: string; key: string, mode: FileTransferTabPane['mode'] }>())
    const time = Date.now()
    const tabListHistoryRecord = ref<{ time: number; tabs: Tab[] }[]>() // [curr,last]
    const saveRecord = () => {
      const tabs = toRaw(tabList.value).map(copyTab)
      if (tabListHistoryRecord.value?.[0].time !== time) {
        tabListHistoryRecord.value = [{ tabs, time }, ...(tabListHistoryRecord.value ?? [])]
      } else {
        tabListHistoryRecord.value[0].tabs = tabs
      }
      tabListHistoryRecord.value = tabListHistoryRecord.value.slice(0, 2)
    }

    const openTagSearchMatchedImageGridInRight = async (
      tabIdx: number,
      id: string,
      tagIds: MatchImageByTagsReq
    ) => {
      let pane = tabList.value
        .map((v) => v.panes)
        .flat()
        .find(
          (v) => v.type === 'tag-search-matched-image-grid' && v.id === id
        ) as TagSearchMatchedImageGridTabPane
      if (pane) {
        pane.selectedTagIds = cloneDeep(tagIds)
        return
      } else {
        pane = {
          type: 'tag-search-matched-image-grid',
          id: id,
          selectedTagIds: cloneDeep(tagIds),
          key: uniqueId(),
          name: t('searchResults')
        }
      }

      const tab = tabList.value[tabIdx + 1]
      if (!tab) {
        tabList.value.push({ panes: [pane], key: pane.key, id: uniqueId() })
      } else {
        tab.key = pane.key
        tab.panes.push(pane)
      }
    }

    const lang = ref(getPreferredLang())
    watch(lang, (v) => (i18n.global.locale.value = v as any))

    const longPressOpenContextMenu = ref(false)

    const shortcut = ref<Shortcut>({
      delete: '',
      download: ''
    })

    const extraPathAliasMap = ref({} as Dict<string>)
    const pathAliasMap = computed((): Dict<string> => {
      const keys = [
        'outdir_extras_samples',
        'outdir_save',
        'outdir_txt2img_samples',
        'outdir_img2img_samples',
        'outdir_img2img_grids',
        'outdir_txt2img_grids'
      ]
      const res = quickMovePaths.value.filter((v) => keys.includes(v.key)).map((v) => [v.zh, v.dir])
      return {...Object.fromEntries(res), ...extraPathAliasMap.value}
    })

    const pageFuncExportMap = new Map<string, Dict<AnyFn>>()
    const ignoredConfirmActions = reactive<Record<ActionConfirmRequired, boolean>>({ deleteOneOnly: false })

    const dark = usePreferredDark()

    const computedTheme = computed(() =>  {
      const getParDark = () => {
        try {
          return parent.location.search.includes('theme=dark') // sd-webui的
        } catch (error) {
          return false
        }
      }
      const isDark = darkModeControl.value === 'auto' ? (dark.value || getParDark()) : (darkModeControl.value === 'dark')
      return isDark ? 'dark' : 'light'
    })

    // 简化路径
    const getShortPath = (loc: string) => {
      try {
        loc = loc.trim()
        const map = pathAliasMap.value
        const np = Path.normalize(loc)
        const replacedPaths = [] as string[]
        for (const [k, v] of Object.entries(map)) {
          if (k && v) {
            if (loc === v || np === v) return k
            replacedPaths.push(np.replace(v, '$' + k))
          }
        }
        return replacedPaths.sort((a, b) => a.length - b.length)?.[0] ?? loc
      } catch (error) {
        console.error(error)
        return loc
      }
    }
    const previewBgOpacity = ref(0.6)
    return {
      computedTheme,
      darkModeControl,
      defaultSortingMethod,
      defaultGridCellWidth,
      defaultChangeIndchecked: ref(true),
      defaultSeedChangeChecked: ref(false),
      pathAliasMap,
      createEmptyPane,
      lang,
      tabList,
      conf,
      quickMovePaths,
      enableThumbnail,
      dragingTab,
      saveRecord,
      recent,
      tabListHistoryRecord,
      gridThumbnailResolution,
      longPressOpenContextMenu,
      openTagSearchMatchedImageGridInRight,
      onlyFoldersAndImages: ref(true),
      keepMultiSelect: ref(false),
      fullscreenPreviewInitialUrl: ref(''),
      shortcut,
      pageFuncExportMap,
      dontShowAgain: ref(false),
      dontShowAgainNewImgOpts: ref(false),
      ignoredConfirmActions,
      getShortPath,
      extraPathAliasMap,
      previewBgOpacity,
      defaultInitinalPage: ref<DefaultInitinalPage>('empty'),
      autoRefreshWalkMode: ref(true),
      autoRefreshWalkModePosLimit: ref(128),
      autoRefreshNormalFixedMode: ref(true),
      showCommaInInfoPanel: ref(false),
    }
  },
  {
    persist: {
      // debug: true,
      paths: presistKeys
    }
  }
)