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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
|
<template>
<div class="_gaps_m">
<div :class="$style.buttons">
<MkButton inline primary @click="saveNew">{{ ts._preferencesBackups.saveNew }}</MkButton>
<MkButton inline @click="loadFile">{{ ts._preferencesBackups.loadFile }}</MkButton>
</div>
<FormSection>
<template #label>{{ ts._preferencesBackups.list }}</template>
<template v-if="profiles && Object.keys(profiles).length > 0">
<div class="_gaps_s">
<div
v-for="(profile, id) in profiles"
:key="id"
class="_panel"
:class="$style.profile"
@click="$event => menu($event, id)"
@contextmenu.prevent.stop="$event => menu($event, id)"
>
<div :class="$style.profileName">{{ profile.name }}</div>
<div :class="$style.profileTime">{{ t('_preferencesBackups.createdAt', { date: (new Date(profile.createdAt)).toLocaleDateString(), time: (new Date(profile.createdAt)).toLocaleTimeString() }) }}</div>
<div v-if="profile.updatedAt" :class="$style.profileTime">{{ t('_preferencesBackups.updatedAt', { date: (new Date(profile.updatedAt)).toLocaleDateString(), time: (new Date(profile.updatedAt)).toLocaleTimeString() }) }}</div>
</div>
</div>
</template>
<div v-else-if="profiles">
<MkInfo>{{ ts._preferencesBackups.noBackups }}</MkInfo>
</div>
<MkLoading v-else/>
</FormSection>
</div>
</template>
<script lang="ts" setup>
import { computed, onMounted, onUnmounted, useCssModule } from 'vue';
import { v4 as uuid } from 'uuid';
import FormSection from '@/components/form/section.vue';
import MkButton from '@/components/MkButton.vue';
import MkInfo from '@/components/MkInfo.vue';
import * as os from '@/os';
import { ColdDeviceStorage, defaultStore } from '@/store';
import { unisonReload } from '@/scripts/unison-reload';
import { stream } from '@/stream';
import { $i } from '@/account';
import { i18n } from '@/i18n';
import { version, host } from '@/config';
import { definePageMetadata } from '@/scripts/page-metadata';
import { miLocalStorage } from '@/local-storage';
const { t, ts } = i18n;
useCssModule();
const defaultStoreSaveKeys: (keyof typeof defaultStore['state'])[] = [
'menu',
'visibility',
'localOnly',
'statusbars',
'widgets',
'tl',
'overridedDeviceKind',
'serverDisconnectedBehavior',
'collapseRenotes',
'showNoteActionsOnlyHover',
'nsfw',
'animation',
'animatedMfm',
'advancedMfm',
'loadRawImages',
'imageNewTab',
'disableShowingAnimatedImages',
'emojiStyle',
'disableDrawer',
'useBlurEffectForModal',
'useBlurEffect',
'showFixedPostForm',
'showFixedPostFormInChannel',
'enableInfiniteScroll',
'useReactionPickerForContextMenu',
'showGapBetweenNotesInTimeline',
'instanceTicker',
'reactionPickerSize',
'reactionPickerWidth',
'reactionPickerHeight',
'reactionPickerUseDrawerForMobile',
'defaultSideView',
'menuDisplay',
'reportError',
'squareAvatars',
'numberOfPageCache',
'aiChanMode',
'mediaListWithOneImageAppearance',
];
const coldDeviceStorageSaveKeys: (keyof typeof ColdDeviceStorage.default)[] = [
'lightTheme',
'darkTheme',
'syncDeviceDarkMode',
'plugins',
'mediaVolume',
'sound_masterVolume',
'sound_note',
'sound_noteMy',
'sound_notification',
'sound_chat',
'sound_chatBg',
'sound_antenna',
'sound_channel',
];
const scope = ['clientPreferencesProfiles'];
const profileProps = ['name', 'createdAt', 'updatedAt', 'misskeyVersion', 'settings', 'host'];
type Profile = {
name: string;
createdAt: string;
updatedAt: string | null;
misskeyVersion: string;
host: string;
settings: {
hot: Record<keyof typeof defaultStoreSaveKeys, unknown>;
cold: Record<keyof typeof coldDeviceStorageSaveKeys, unknown>;
fontSize: string | null;
useSystemFont: 't' | null;
wallpaper: string | null;
};
};
const connection = $i && stream.useChannel('main');
let profiles = $ref<Record<string, Profile> | null>(null);
os.api('i/registry/get-all', { scope })
.then(res => {
profiles = res || {};
});
function isObject(value: unknown): value is Record<string, unknown> {
return value != null && typeof value === 'object' && !Array.isArray(value);
}
function validate(profile: unknown): void {
if (!isObject(profile)) throw new Error('not an object');
// Check if unnecessary properties exist
if (Object.keys(profile).some(key => !profileProps.includes(key))) throw new Error('Unnecessary properties exist');
if (!profile.name) throw new Error('Missing required prop: name');
if (!profile.misskeyVersion) throw new Error('Missing required prop: misskeyVersion');
// Check if createdAt and updatedAt is Date
// https://zenn.dev/lollipop_onl/articles/eoz-judge-js-invalid-date
if (!profile.createdAt || Number.isNaN(new Date(profile.createdAt).getTime())) throw new Error('createdAt is falsy or not Date');
if (profile.updatedAt) {
if (Number.isNaN(new Date(profile.updatedAt).getTime())) {
throw new Error('updatedAt is not Date');
}
} else if (profile.updatedAt !== null) {
throw new Error('updatedAt is not null');
}
if (!profile.settings) throw new Error('Missing required prop: settings');
if (!isObject(profile.settings)) throw new Error('Invalid prop: settings');
}
function getSettings(): Profile['settings'] {
const hot = {} as Record<keyof typeof defaultStoreSaveKeys, unknown>;
for (const key of defaultStoreSaveKeys) {
hot[key] = defaultStore.state[key];
}
const cold = {} as Record<keyof typeof coldDeviceStorageSaveKeys, unknown>;
for (const key of coldDeviceStorageSaveKeys) {
cold[key] = ColdDeviceStorage.get(key);
}
return {
hot,
cold,
fontSize: miLocalStorage.getItem('fontSize'),
useSystemFont: miLocalStorage.getItem('useSystemFont') as 't' | null,
wallpaper: miLocalStorage.getItem('wallpaper'),
};
}
async function saveNew(): Promise<void> {
if (!profiles) return;
const { canceled, result: name } = await os.inputText({
title: ts._preferencesBackups.inputName,
});
if (canceled) return;
if (Object.values(profiles).some(x => x.name === name)) {
return os.alert({
title: ts._preferencesBackups.cannotSave,
text: t('_preferencesBackups.nameAlreadyExists', { name }),
});
}
const id = uuid();
const profile: Profile = {
name,
createdAt: (new Date()).toISOString(),
updatedAt: null,
misskeyVersion: version,
host,
settings: getSettings(),
};
await os.apiWithDialog('i/registry/set', { scope, key: id, value: profile });
}
function loadFile(): void {
const input = document.createElement('input');
input.type = 'file';
input.multiple = false;
input.onchange = async () => {
if (!profiles) return;
if (!input.files || input.files.length === 0) return;
const file = input.files[0];
if (file.type !== 'application/json') {
return os.alert({
type: 'error',
title: ts._preferencesBackups.cannotLoad,
text: ts._preferencesBackups.invalidFile,
});
}
let profile: Profile;
try {
profile = JSON.parse(await file.text()) as unknown as Profile;
validate(profile);
} catch (err) {
return os.alert({
type: 'error',
title: ts._preferencesBackups.cannotLoad,
text: err?.message,
});
}
const id = uuid();
await os.apiWithDialog('i/registry/set', { scope, key: id, value: profile });
// 一応廃棄
(window as any).__misskey_input_ref__ = null;
};
// https://qiita.com/fukasawah/items/b9dc732d95d99551013d
// iOS Safari で正常に動かす為のおまじない
(window as any).__misskey_input_ref__ = input;
input.click();
}
async function applyProfile(id: string): Promise<void> {
if (!profiles) return;
const profile = profiles[id];
const { canceled: cancel1 } = await os.confirm({
type: 'warning',
title: ts._preferencesBackups.apply,
text: t('_preferencesBackups.applyConfirm', { name: profile.name }),
});
if (cancel1) return;
// TODO: バージョン or ホストが違ったらさらに警告を表示
const settings = profile.settings;
// defaultStore
for (const key of defaultStoreSaveKeys) {
if (settings.hot[key] !== undefined) {
defaultStore.set(key, settings.hot[key]);
}
}
// coldDeviceStorage
for (const key of coldDeviceStorageSaveKeys) {
if (settings.cold[key] !== undefined) {
ColdDeviceStorage.set(key, settings.cold[key]);
}
}
// fontSize
if (settings.fontSize) {
miLocalStorage.setItem('fontSize', settings.fontSize);
} else {
miLocalStorage.removeItem('fontSize');
}
// useSystemFont
if (settings.useSystemFont) {
miLocalStorage.setItem('useSystemFont', settings.useSystemFont);
} else {
miLocalStorage.removeItem('useSystemFont');
}
// wallpaper
if (settings.wallpaper != null) {
miLocalStorage.setItem('wallpaper', settings.wallpaper);
} else {
miLocalStorage.removeItem('wallpaper');
}
const { canceled: cancel2 } = await os.confirm({
type: 'info',
text: ts.reloadToApplySetting,
});
if (cancel2) return;
unisonReload();
}
async function deleteProfile(id: string): Promise<void> {
if (!profiles) return;
const { canceled } = await os.confirm({
type: 'info',
title: ts.delete,
text: t('deleteAreYouSure', { x: profiles[id].name }),
});
if (canceled) return;
await os.apiWithDialog('i/registry/remove', { scope, key: id });
delete profiles[id];
}
async function save(id: string): Promise<void> {
if (!profiles) return;
const { name, createdAt } = profiles[id];
const { canceled } = await os.confirm({
type: 'info',
title: ts._preferencesBackups.save,
text: t('_preferencesBackups.saveConfirm', { name }),
});
if (canceled) return;
const profile: Profile = {
name,
createdAt,
updatedAt: (new Date()).toISOString(),
misskeyVersion: version,
host,
settings: getSettings(),
};
await os.apiWithDialog('i/registry/set', { scope, key: id, value: profile });
}
async function rename(id: string): Promise<void> {
if (!profiles) return;
const { canceled: cancel1, result: name } = await os.inputText({
title: ts._preferencesBackups.inputName,
});
if (cancel1 || profiles[id].name === name) return;
if (Object.values(profiles).some(x => x.name === name)) {
return os.alert({
title: ts._preferencesBackups.cannotSave,
text: t('_preferencesBackups.nameAlreadyExists', { name }),
});
}
const registry = Object.assign({}, { ...profiles[id] });
const { canceled: cancel2 } = await os.confirm({
type: 'info',
title: ts._preferencesBackups.rename,
text: t('_preferencesBackups.renameConfirm', { old: registry.name, new: name }),
});
if (cancel2) return;
registry.name = name;
await os.apiWithDialog('i/registry/set', { scope, key: id, value: registry });
}
function menu(ev: MouseEvent, profileId: string) {
if (!profiles) return;
return os.popupMenu([{
text: ts._preferencesBackups.apply,
icon: 'ti ti-check',
action: () => applyProfile(profileId),
}, {
type: 'a',
text: ts.download,
icon: 'ti ti-download',
href: URL.createObjectURL(new Blob([JSON.stringify(profiles[profileId], null, 2)], { type: 'application/json' })),
download: `${profiles[profileId].name}.json`,
}, null, {
text: ts.rename,
icon: 'ti ti-forms',
action: () => rename(profileId),
}, {
text: ts._preferencesBackups.save,
icon: 'ti ti-device-floppy',
action: () => save(profileId),
}, null, {
text: ts.delete,
icon: 'ti ti-trash',
action: () => deleteProfile(profileId),
danger: true,
}], ev.currentTarget ?? ev.target);
}
onMounted(() => {
// streamingのuser storage updateイベントを監視して更新
connection?.on('registryUpdated', ({ scope: recievedScope, key, value }) => {
if (!recievedScope || recievedScope.length !== scope.length || recievedScope[0] !== scope[0]) return;
if (!profiles) return;
profiles[key] = value;
});
});
onUnmounted(() => {
connection?.off('registryUpdated');
});
definePageMetadata(computed(() => ({
title: ts.preferencesBackups,
icon: 'ti ti-device-floppy',
})));
</script>
<style lang="scss" module>
.buttons {
display: flex;
gap: var(--margin);
flex-wrap: wrap;
}
.profile {
padding: 20px;
cursor: pointer;
&Name {
font-weight: 700;
}
&Time {
font-size: .85em;
opacity: .7;
}
}
</style>
|