Add pool feature in post upload view

pull/55/head v0.11
neobooru 2023-12-05 21:25:11 +01:00
parent b7f1ce3a21
commit c74926b8c1
14 changed files with 456 additions and 240 deletions

View File

@ -23,5 +23,7 @@ module.exports = {
}, },
], ],
"@typescript-eslint/no-explicit-any": "off", "@typescript-eslint/no-explicit-any": "off",
"eol-last": ["error", "always"],
"comma-dangle": ["error", "always-multiline"],
}, },
}; };

View File

@ -10,6 +10,10 @@ import {
TagFields, TagFields,
TemporaryFileUploadResult, TemporaryFileUploadResult,
UpdatePostRequest, UpdatePostRequest,
PoolsResult,
PoolFields,
Pool,
UpdatePoolRequest,
} from "./models"; } from "./models";
import { ScrapedPostDetails, SzuruSiteConfig } from "~/models"; import { ScrapedPostDetails, SzuruSiteConfig } from "~/models";
@ -63,7 +67,7 @@ export default class SzurubooruApi {
offset = 0, offset = 0,
limit = 100, limit = 100,
fields?: TagFields[], fields?: TagFields[],
cancelToken?: CancelToken cancelToken?: CancelToken,
): Promise<TagsResult> { ): Promise<TagsResult> {
const params = new URLSearchParams(); const params = new URLSearchParams();
params.append("offset", offset.toString()); params.append("offset", offset.toString());
@ -99,6 +103,39 @@ export default class SzurubooruApi {
return (await this.apiPost("posts", obj)).data; return (await this.apiPost("posts", obj)).data;
} }
async createPool(name: string, category: string, posts?: number[]): Promise<Pool> {
const obj = <any>{
names: [name],
category,
};
if (posts) {
obj.posts = posts;
}
return (await this.apiPost("pool", obj)).data;
}
async getPools(
query?: string,
offset = 0,
limit = 100,
fields?: PoolFields[],
cancelToken?: CancelToken): Promise<PoolsResult> {
const params = new URLSearchParams();
params.append("offset", offset.toString());
params.append("limit", limit.toString());
if (fields && fields.length > 0) params.append("fields", fields.join());
if (query) params.append("query", query);
return (await this.apiGet("pools?" + params.toString(), {}, cancelToken)).data;
}
async updatePool(id: number, updateRequest: UpdatePoolRequest): Promise<Pool> {
return (await this.apiPut("pool/" + id, updateRequest)).data;
}
async reverseSearch(contentUrl: string): Promise<ImageSearchResult> { async reverseSearch(contentUrl: string): Promise<ImageSearchResult> {
const obj = { contentUrl }; const obj = { contentUrl };
return (await this.apiPost("posts/reverse-search", obj)).data; return (await this.apiPost("posts/reverse-search", obj)).data;

View File

@ -3,9 +3,11 @@
*/ */
export type Safety = "safe" | "sketchy" | "unsafe"; export type Safety = "safe" | "sketchy" | "unsafe";
export type TagFields = "names" | "category" | "usages" | "implications"; export type TagFields = "version" | "names" | "category" | "usages" | "implications";
export type PoolFields = "version" | "id" | "names" | "category" | "description" | "postCount" | "posts";
export type TagsResult = PagedSearchResult<Tag>; export type TagsResult = PagedSearchResult<Tag>;
export type PoolsResult = PagedSearchResult<Pool>;
export type TagCategoriesResult = UnpagedSearchResult<TagCategory>; export type TagCategoriesResult = UnpagedSearchResult<TagCategory>;
export interface SzuruError { export interface SzuruError {
@ -37,18 +39,28 @@ export interface MicroTag {
usages: number; usages: number;
} }
export interface Tag { export interface Tag extends MicroTag {
names: string[];
category: string;
version: number; version: number;
description?: string; // Markdown description?: string; // Markdown
creationTime: Date; creationTime: Date;
lastEditTime?: Date; lastEditTime?: Date;
usages: number;
suggestions: MicroTag[]; suggestions: MicroTag[];
implications: MicroTag[]; implications: MicroTag[];
} }
/**
* All fields can be optional.
*/
export interface Pool {
id: number;
names: string[];
category: string;
version: number;
description: null;
postCount: number;
posts: MicroPost[];
}
export interface TagCategory { export interface TagCategory {
name: string; name: string;
version: number; version: number;
@ -62,8 +74,12 @@ export interface MicroUser {
avatarUrl: string; avatarUrl: string;
} }
export interface Post { export interface MicroPost {
id: number; id: number;
thumbnailUrl: string;
}
export interface Post extends MicroPost {
version: number; version: number;
creationTime: Date; creationTime: Date;
lastEditTime?: Date; lastEditTime?: Date;
@ -76,7 +92,6 @@ export interface Post {
canvasWidth: number; canvasWidth: number;
canvasHeight: number; canvasHeight: number;
contentUrl: string; contentUrl: string;
thumbnailUrl: string;
flags: string[]; flags: string[];
tags: MicroTag[]; tags: MicroTag[];
relations: any[]; // MicroPost resource relations: any[]; // MicroPost resource
@ -127,3 +142,9 @@ export interface UpdatePostRequest {
contentUrl: string | undefined; contentUrl: string | undefined;
contentToken: string | undefined; contentToken: string | undefined;
} }
export interface UpdatePoolRequest {
version: number;
// names?: string[];
posts: number[];
}

View File

@ -8,7 +8,7 @@ import {
PostUpdateCommandData, PostUpdateCommandData,
FetchCommandData, FetchCommandData,
} from "~/models"; } from "~/models";
import { PostAlreadyUploadedError } from "~/api/models"; import { PostAlreadyUploadedError, UpdatePoolRequest } from "~/api/models";
import SzurubooruApi from "~/api"; import SzurubooruApi from "~/api";
// Only on dev mode // Only on dev mode
@ -26,7 +26,7 @@ async function uploadPost(data: PostUploadCommandData) {
const pushInfo = () => const pushInfo = () =>
browser.runtime.sendMessage( browser.runtime.sendMessage(
new BrowserCommand("set_post_upload_info", new SetPostUploadInfoData(data.selectedSite.id, data.post.id, info)) new BrowserCommand("set_post_upload_info", new SetPostUploadInfoData(data.selectedSite.id, data.post.id, info)),
); );
try { try {
@ -73,7 +73,7 @@ async function uploadPost(data: PostUploadCommandData) {
categoriesChangedCount++; categoriesChangedCount++;
} else { } else {
console.log( console.log(
`Not adding the '${wantedCategory}' category to the tag '${tags[i].names[0]}' because the szurubooru instance does not have this category.` `Not adding the '${wantedCategory}' category to the tag '${tags[i].names[0]}' because the szurubooru instance does not have this category.`,
); );
} }
} }
@ -84,11 +84,39 @@ async function uploadPost(data: PostUploadCommandData) {
pushInfo(); pushInfo();
} }
} }
// TODO: This code shouldn't all be in the same try catch.
// Add post to pools
for (const scrapedPool of data.post.pools) {
// Attention! Don't use the .name getter as it does not exist. Just use names[0].
const existingPools = await szuru.getPools(encodeTagName(scrapedPool.names[0]), 0, 1, ["id", "posts", "version"]);
if (existingPools.results.length == 0) {
// Pool does not exist. Create a new pool and add the post to it in one API call.
console.log(`Creating new pool ${scrapedPool.names[0]} and adding post ${createdPost.id}.`);
await szuru.createPool(scrapedPool.names[0], "default", [createdPost.id]);
} else {
// Pool exists, so add it to the existing pool.
const existingPool = existingPools.results[0];
const posts = existingPool.posts.map(x => x.id);
posts.push(createdPost.id);
console.log(`Adding post ${createdPost.id} to existing pool ${existingPool.id}`);
const updateRequest = <UpdatePoolRequest>{
version: existingPool.version,
posts,
};
await szuru.updatePool(existingPool.id, updateRequest);
}
}
} catch (ex: any) { } catch (ex: any) {
console.error(ex);
if (ex.name && ex.name == "PostAlreadyUploadedError") { if (ex.name && ex.name == "PostAlreadyUploadedError") {
const otherPostId = (ex as PostAlreadyUploadedError).otherPostId; const otherPostId = (ex as PostAlreadyUploadedError).otherPostId;
browser.runtime.sendMessage( browser.runtime.sendMessage(
new BrowserCommand("set_exact_post_id", new SetExactPostId(data.selectedSite.id, data.post.id, otherPostId)) new BrowserCommand("set_exact_post_id", new SetExactPostId(data.selectedSite.id, data.post.id, otherPostId)),
); );
// We don't set an error message, because we have a different message for posts that are already uploaded. // We don't set an error message, because we have a different message for posts that are already uploaded.
} else { } else {
@ -110,8 +138,8 @@ async function updatePost(data: PostUpdateCommandData) {
browser.runtime.sendMessage( browser.runtime.sendMessage(
new BrowserCommand( new BrowserCommand(
"set_post_update_info", "set_post_update_info",
new SetPostUploadInfoData(data.selectedSite.id, `merge-${data.postId}`, info) new SetPostUploadInfoData(data.selectedSite.id, `merge-${data.postId}`, info),
) ),
); );
try { try {
@ -124,6 +152,7 @@ async function updatePost(data: PostUpdateCommandData) {
info.state = "uploaded"; info.state = "uploaded";
pushInfo(); pushInfo();
} catch (ex: any) { } catch (ex: any) {
console.error(ex);
info.state = "error"; info.state = "error";
info.error = getErrorMessage(ex); info.error = getErrorMessage(ex);
pushInfo(); pushInfo();

View File

@ -0,0 +1,149 @@
<script setup lang="ts">
import axios, { CancelTokenSource } from "axios";
const inputText = ref("");
const autocompleteShown = ref(false);
const cancelSource = ref<CancelTokenSource | undefined>(undefined);
const autocompleteIndex = ref(-1);
const props = defineProps({
autocompleteItems: {
type: Array<any>,
required: true,
},
});
const emit = defineEmits(["addItem", "addFromCurrentInput", "autocompletePopulator"]);
function addItem(item: any) {
emit("addItem", item);
}
async function onAddItemKeyUp(e: KeyboardEvent) {
await autocompletePopulator((<HTMLInputElement>e.target).value);
}
function addItemFromCurrentInput() {
emit("addFromCurrentInput", inputText.value);
inputText.value = ""; // Reset input
// Only needed when the button is clicked
// When this is triggered by the enter key the `onAddItemKeyUp` will internally also hide the autocomplete.
// Though hiding it twice doesn't hurt so we don't care.
hideAutocomplete();
}
function onAddItemKeyDown(e: KeyboardEvent) {
if (e.code == "ArrowDown") {
e.preventDefault();
if (autocompleteIndex.value < props.autocompleteItems.length - 1) {
autocompleteIndex.value++;
}
} else if (e.code == "ArrowUp") {
e.preventDefault();
if (autocompleteIndex.value >= 0) {
autocompleteIndex.value--;
}
} else if (e.code == "Enter") {
if (autocompleteIndex.value == -1) {
addItemFromCurrentInput();
} else {
// Add auto completed item
const itemToAdd = props.autocompleteItems[autocompleteIndex.value];
addItem(itemToAdd);
inputText.value = ""; // Reset input
}
}
}
function onClickAutocompleteItem(item: any) {
addItem(item);
inputText.value = ""; // Reset input
autocompleteShown.value = false; // Hide autocomplete list
}
function hideAutocomplete() {
autocompleteIndex.value = -1;
autocompleteShown.value = false;
}
async function autocompletePopulator(input: string) {
// Based on https://www.w3schools.com/howto/howto_js_autocomplete.asp
// Hide autocomplete when the input is empty, and don't do anything else.
if (input.length == 0) {
hideAutocomplete();
return;
}
// Cancel previous request, not sure if this still works after the refactor.
if (cancelSource.value) {
cancelSource.value.cancel();
}
cancelSource.value = axios.CancelToken.source();
emit("autocompletePopulator", inputText.value, cancelSource.value.token);
}
watch(props, (newValue) => {
if (newValue.autocompleteItems.length > 0) {
autocompleteShown.value = true;
}
});
</script>
<template>
<div style="display: flex; flex-direction: column">
<div style="display: flex">
<input type="text" v-model="inputText" @keyup="onAddItemKeyUp" @keydown="onAddItemKeyDown" autocomplete="off" />
<button class="primary" style="margin-left: 5px" @click="addItemFromCurrentInput">Add</button>
</div>
<div class="autocomplete-items" v-bind:class="{ show: autocompleteShown }">
<div v-for="(item, idx) in autocompleteItems" @click="onClickAutocompleteItem(item)" :key="item.name" :class="{
active: idx == autocompleteIndex,
}">
<slot :item="item"></slot>
</div>
</div>
</div>
</template>
<style lang="scss">
.autocomplete-items {
position: absolute;
z-index: 10;
background-color: var(--bg-main-color);
border: 2px solid var(--primary-color);
margin-top: 34px;
display: none;
&.show {
display: block;
}
>div {
cursor: pointer;
padding: 2px 4px;
display: flex;
align-items: center;
gap: 0.5em;
&:hover {
background: var(--primary-color);
>span {
color: var(--text-color);
}
}
}
>div.active {
background: var(--primary-color);
>span {
color: var(--text-color);
}
}
}
</style>

View File

@ -0,0 +1,32 @@
<script setup lang="ts">
import type { PropType } from "vue";
import type { PoolDetails } from "~/models";
import { breakTagName } from "~/utils";
defineProps({
pools: Array as PropType<PoolDetails[]>,
showPostCount: Boolean,
showRemovePool: Boolean,
});
defineEmits(["removePool"]);
</script>
<template>
<ul class="compact-pools">
<li v-for="pool in pools" :key="pool.name">
<a v-if="showRemovePool" class="remove-tag" @click="$emit('removePool', pool)">x</a>
<span class="tag-general" v-html="breakTagName(pool.name)"></span>
<span v-if="showPostCount" class="tag-usages tag-usages-reserve-space">{{ pool.postCount ? pool.postCount : ""
}}</span>
</li>
</ul>
</template>
<style scoped lang="scss">
/* Hacky way to stop the layout from resizing when we lazy load the usage count. */
.tag-usages-reserve-space {
min-width: 5ch;
/* 5 character width */
display: inline-block;
}
</style>

View File

@ -24,7 +24,8 @@ defineEmits(["removeTag"]);
<style scoped lang="scss"> <style scoped lang="scss">
/* Hacky way to stop the layout from resizing when we lazy load the usage count. */ /* Hacky way to stop the layout from resizing when we lazy load the usage count. */
.tag-usages-reserve-space { .tag-usages-reserve-space {
min-width: 5ch; /* 5 character width */ min-width: 5ch;
/* 5 character width */
display: inline-block; display: inline-block;
} }
</style> </style>

View File

@ -0,0 +1,48 @@
<script setup lang="ts">
import { PropType } from "vue";
import { PoolDetails } from "~/models";
import { encodeTagName, getTagClasses } from "~/utils";
import SzurubooruApi from "~/api";
import { CancelToken } from "axios";
const autocompleteItems = ref<PoolDetails[]>([]);
const props = defineProps({
szuru: Object as PropType<SzurubooruApi>,
});
const emit = defineEmits(["addPool"]);
function addPool(tag: PoolDetails) {
emit("addPool", tag);
}
function addPoolFromCurrentInput(input: string) {
addPool(new PoolDetails([input]));
}
async function autocompletePopulator(input: string, ct: CancelToken) {
const query = decodeURIComponent(`*${encodeTagName(input)}*`);
const res = await props.szuru?.getPools(
query,
0,
100,
["id", "names", "category", "description", "postCount"],
ct,
);
if (res) {
// TODO: Maybe search on hamming distance or something?
autocompleteItems.value = res.results.map((x) => PoolDetails.fromPool(x));
} else {
autocompleteItems.value = [];
}
}
</script>
<template>
<AutocompleteInput :autocomplete-items="autocompleteItems" @add-item="addPool"
@add-from-current-input="addPoolFromCurrentInput" @autocomplete-populator="autocompletePopulator" v-slot="slotProps">
<span :class="getTagClasses(slotProps.item)">{{ slotProps.item.name }}</span>
<span class="tag-usages">{{ slotProps.item.usages ? slotProps.item.usages : "" }}</span>
</AutocompleteInput>
</template>

View File

@ -1,15 +1,11 @@
<script setup lang="ts"> <script setup lang="ts">
import axios, { CancelTokenSource } from "axios";
import { PropType } from "vue"; import { PropType } from "vue";
import SzurubooruApi from "~/api";
import { TagDetails } from "~/models"; import { TagDetails } from "~/models";
import { encodeTagName, getTagClasses } from "~/utils"; import { encodeTagName, getTagClasses } from "~/utils";
import SzurubooruApi from "~/api";
import { CancelToken } from "axios";
const addTagInput = ref(""); const autocompleteItems = ref<TagDetails[]>([]);
const autocompleteShown = ref(false);
const autocompleteTags = ref<TagDetails[]>([]);
const cancelSource = ref<CancelTokenSource | undefined>(undefined);
const autocompleteIndex = ref(-1);
const props = defineProps({ const props = defineProps({
szuru: Object as PropType<SzurubooruApi>, szuru: Object as PropType<SzurubooruApi>,
@ -20,148 +16,34 @@ function addTag(tag: TagDetails) {
emit("addTag", tag); emit("addTag", tag);
} }
async function onAddTagKeyUp(e: KeyboardEvent) { function addTagFromCurrentInput(input: string) {
await autocompletePopulator((<HTMLInputElement>e.target).value); addTag(new TagDetails([input]));
} }
function addTagFromCurrentInput() { async function autocompletePopulator(input: string, ct: CancelToken) {
addTag(new TagDetails([addTagInput.value]));
addTagInput.value = ""; // Reset input
// Only needed when the button is clicked
// When this is triggered by the enter key the `onAddTagKeyUp` will internally also hide the autocomplete.
// Though hiding it twice doesn't hurt so we don't care.
hideAutocomplete();
// TODO: Do we also want to add the implications?
// Answer: Probably not, because if the user wanted to have implications they should've clicked/selected the autocomplete entry.
}
function onAddTagKeyDown(e: KeyboardEvent) {
if (e.code == "ArrowDown") {
e.preventDefault();
if (autocompleteIndex.value < autocompleteTags.value.length - 1) {
autocompleteIndex.value++;
}
} else if (e.code == "ArrowUp") {
e.preventDefault();
if (autocompleteIndex.value >= 0) {
autocompleteIndex.value--;
}
} else if (e.code == "Enter") {
if (autocompleteIndex.value == -1) {
addTagFromCurrentInput();
} else {
// Add auto completed tag
const tagToAdd = autocompleteTags.value[autocompleteIndex.value];
addTag(tagToAdd);
addTagInput.value = ""; // Reset input
}
}
}
function onClickAutocompleteTagItem(tag: TagDetails) {
addTag(tag);
addTagInput.value = ""; // Reset input
autocompleteShown.value = false; // Hide autocomplete list
}
function hideAutocomplete() {
autocompleteIndex.value = -1;
autocompleteShown.value = false;
}
async function autocompletePopulator(input: string) {
// Based on https://www.w3schools.com/howto/howto_js_autocomplete.asp
// Hide autocomplete when the input is empty, and don't do anything else.
if (input.length == 0) {
hideAutocomplete();
return;
}
// Cancel previous request
if (cancelSource.value) {
cancelSource.value.cancel();
}
cancelSource.value = axios.CancelToken.source();
const query = decodeURIComponent(`*${encodeTagName(input)}* sort:usages`); const query = decodeURIComponent(`*${encodeTagName(input)}* sort:usages`);
const res = await props.szuru?.getTags( const res = await props.szuru?.getTags(
query, query,
0, 0,
100, 100,
["names", "category", "usages", "implications"], ["names", "category", "usages", "implications"],
cancelSource.value.token ct
); );
if (res) { if (res) {
// TODO: Maybe search on hamming distance or something? // TODO: Maybe search on hamming distance or something?
autocompleteTags.value = res.results.map((x) => TagDetails.fromTag(x)); autocompleteItems.value = res.results.map((x) => TagDetails.fromTag(x));
if (autocompleteTags.value.length > 0) autocompleteShown.value = true; console.dir(autocompleteItems.value);
} else { } else {
autocompleteTags.value = []; autocompleteItems.value = [];
} }
} }
</script> </script>
<template> <template>
<div style="display: flex; flex-direction: column"> <AutocompleteInput :autocomplete-items="autocompleteItems" @add-item="addTag"
<div style="display: flex"> @add-from-current-input="addTagFromCurrentInput" @autocomplete-populator="autocompletePopulator" v-slot="slotProps">
<input type="text" v-model="addTagInput" @keyup="onAddTagKeyUp" @keydown="onAddTagKeyDown" autocomplete="off" /> <span :class="getTagClasses(slotProps.item)">{{ slotProps.item.name }}</span>
<button class="primary" style="margin-left: 5px" @click="addTagFromCurrentInput">Add</button> <span class="tag-usages">{{ slotProps.item.usages ? slotProps.item.usages : "" }}</span>
</div> </AutocompleteInput>
<div class="autocomplete-items" v-bind:class="{ show: autocompleteShown }">
<div
v-for="(tag, idx) in autocompleteTags"
@click="onClickAutocompleteTagItem(tag)"
:key="tag.name"
:class="{
active: idx == autocompleteIndex,
}"
>
<span :class="getTagClasses(tag)">{{ tag.name }}</span>
<span class="tag-usages">{{ tag.usages ? tag.usages : "" }}</span>
</div>
</div>
</div>
</template> </template>
<style scoped lang="scss">
.autocomplete-items {
position: absolute;
z-index: 10;
background-color: var(--bg-main-color);
border: 2px solid var(--primary-color);
margin-top: 34px;
display: none;
&.show {
display: block;
}
> div {
cursor: pointer;
padding: 2px 4px;
display: flex;
align-items: center;
gap: 0.5em;
&:hover {
background: var(--primary-color);
> span {
color: var(--text-color);
}
}
}
> div.active {
background: var(--primary-color);
> span {
color: var(--text-color);
}
}
}
</style>

View File

@ -20,5 +20,5 @@ const storageLocal: StorageLikeAsync = {
export const useStorageLocal = <T>( export const useStorageLocal = <T>(
key: string, key: string,
initialValue: MaybeRef<T>, initialValue: MaybeRef<T>,
options?: UseStorageAsyncOptions<T> options?: UseStorageAsyncOptions<T>,
): RemovableRef<T> => useStorageAsync(key, initialValue, storageLocal, options); ): RemovableRef<T> => useStorageAsync(key, initialValue, storageLocal, options);

View File

@ -1,10 +1,10 @@
import { BooruTypes, ContentType, ScrapedNote, ScrapedPost, ScrapedTag } from "neo-scraper"; import { BooruTypes, ContentType, ScrapedNote, ScrapedPost, ScrapedTag } from "neo-scraper";
import { MicroTag, Tag, UpdatePostRequest } from "~/api/models"; import { MicroTag, Pool, Tag, UpdatePostRequest } from "~/api/models";
export class TagDetails { export class TagDetails {
public implications: TagDetails[] = []; public implications: TagDetails[] = [];
constructor(public names: string[], public category?: string, public usages?: number) {} constructor(public names: string[], public category?: string, public usages?: number) { }
get name() { get name() {
return this.names[0]; return this.names[0];
@ -29,6 +29,18 @@ export class TagDetails {
} }
} }
export class PoolDetails {
constructor(public names: string[], public category?: string, public postCount?: number) { }
get name() {
return this.names[0];
}
static fromPool(pool: Pool) {
return new PoolDetails(pool.names, pool.category, pool.postCount);
}
}
export class InstanceSpecificData { export class InstanceSpecificData {
contentToken?: string; contentToken?: string;
genericError?: string; genericError?: string;
@ -44,6 +56,7 @@ export class ScrapedPostDetails {
id = window.crypto.randomUUID(); id = window.crypto.randomUUID();
name = ""; name = "";
tags: TagDetails[] = []; tags: TagDetails[] = [];
pools: PoolDetails[] = [];
notes: ScrapedNote[]; notes: ScrapedNote[];
contentUrl: string; contentUrl: string;
extraContentUrl: string | undefined; extraContentUrl: string | undefined;
@ -83,7 +96,7 @@ export interface SimpleSimilarPost {
} }
export class SimilarPostInfo { export class SimilarPostInfo {
constructor(public readonly id: number, public readonly percentage: number) {} constructor(public readonly id: number, public readonly percentage: number) { }
} }
export type PostUploadState = "uploading" | "uploaded" | "error"; export type PostUploadState = "uploading" | "uploaded" | "error";
@ -119,31 +132,31 @@ export class BrowserCommand<T = any> {
} }
export class PostUploadCommandData { export class PostUploadCommandData {
constructor(public readonly post: ScrapedPostDetails, public readonly selectedSite: SzuruSiteConfig) {} constructor(public readonly post: ScrapedPostDetails, public readonly selectedSite: SzuruSiteConfig) { }
} }
export class SetPostUploadInfoData { export class SetPostUploadInfoData {
constructor(public instanceId: string, public postId: string, public info: PostUploadInfo) {} constructor(public instanceId: string, public postId: string, public info: PostUploadInfo) { }
} }
export class SetExactPostId { export class SetExactPostId {
constructor( constructor(
public readonly instanceId: string, public readonly instanceId: string,
public readonly postId: string, public readonly postId: string,
public readonly exactPostId: number public readonly exactPostId: number,
) {} ) { }
} }
export class PostUpdateCommandData { export class PostUpdateCommandData {
constructor( constructor(
public readonly postId: number, public readonly postId: number,
public readonly updateRequest: UpdatePostRequest, public readonly updateRequest: UpdatePostRequest,
public readonly selectedSite: SzuruSiteConfig public readonly selectedSite: SzuruSiteConfig,
) {} ) { }
} }
export class FetchCommandData { export class FetchCommandData {
constructor(public readonly url: string, public readonly options: RequestInit | undefined = undefined) {} constructor(public readonly url: string, public readonly options: RequestInit | undefined = undefined) { }
} }
export class SzuruSiteConfig { export class SzuruSiteConfig {
@ -154,7 +167,7 @@ export class SzuruSiteConfig {
} }
export class TagCategoryColor { export class TagCategoryColor {
constructor(public name: string, public color: string) {} constructor(public name: string, public color: string) { }
} }
export const getDefaultTagCategories = () => [ export const getDefaultTagCategories = () => [

View File

@ -12,6 +12,7 @@ import {
SimpleImageSearchResult, SimpleImageSearchResult,
PostUploadCommandData, PostUploadCommandData,
SzuruSiteConfig, SzuruSiteConfig,
PoolDetails,
} from "~/models"; } from "~/models";
import { ImageSearchResult } from "~/api/models"; import { ImageSearchResult } from "~/api/models";
import { isMobile } from "~/env"; import { isMobile } from "~/env";
@ -40,7 +41,7 @@ const instanceSpecificData = readonly(
if (pop.selectedPost && cfg.value.selectedSiteId) { if (pop.selectedPost && cfg.value.selectedSiteId) {
return pop.selectedPost.instanceSpecificData[cfg.value.selectedSiteId]; return pop.selectedPost.instanceSpecificData[cfg.value.selectedSiteId];
} }
}) }),
); );
watch( watch(
@ -51,7 +52,7 @@ watch(
let selectedPost = pop.posts.find((x) => x.id == value); let selectedPost = pop.posts.find((x) => x.id == value);
if (selectedPost) findSimilar(selectedPost); if (selectedPost) findSimilar(selectedPost);
} }
} },
); );
watch( watch(
@ -66,7 +67,7 @@ watch(
findSimilar(pop.selectedPost); findSimilar(pop.selectedPost);
} }
} }
} },
); );
function openOptionsPage() { function openOptionsPage() {
@ -181,6 +182,15 @@ function removeTag(tag: TagDetails) {
} }
} }
function removePool(pool: PoolDetails) {
if (pop.selectedPost) {
const idx = pop.selectedPost.pools.indexOf(pool);
if (idx != -1) {
pop.selectedPost.pools.splice(idx, 1);
}
}
}
function getActiveSitePostUrl(postId: number): string { function getActiveSitePostUrl(postId: number): string {
if (!selectedSite.value) return ""; if (!selectedSite.value) return "";
return getUrl(selectedSite.value.domain, "post", postId.toString()); return getUrl(selectedSite.value.domain, "post", postId.toString());
@ -216,6 +226,15 @@ function addTag(tag: TagDetails) {
} }
} }
function addPool(pool: PoolDetails) {
if (pop.selectedPost) {
// Only add pool if it doesn't already exist
if (pool.name.length > 0 && pop.selectedPost.pools.find((x) => x.name == pool.name) == undefined) {
pop.selectedPost.pools.push(pool);
}
}
}
async function clickFindSimilar() { async function clickFindSimilar() {
if (pop.selectedPost) return await findSimilar(pop.selectedPost); if (pop.selectedPost) return await findSimilar(pop.selectedPost);
} }
@ -361,21 +380,20 @@ useDark();
<!-- TODO: Maybe a 5px gap here? --> <!-- TODO: Maybe a 5px gap here? -->
<div style="display: flex; background: purple; border-radius: 0 2px 2px 0"> <div style="display: flex; background: purple; border-radius: 0 2px 2px 0">
<router-link <router-link :to="{
:to="{
name: 'merge', name: 'merge',
params: { params: {
siteId: cfg.selectedSiteId, siteId: cfg.selectedSiteId,
postId: instanceSpecificData?.reverseSearchResult?.exactPostId, postId: instanceSpecificData?.reverseSearchResult?.exactPostId,
}, },
}" }" style="padding: 5px 20px">Merge</router-link>
style="padding: 5px 20px"
>Merge</router-link
>
</div> </div>
</div> </div>
<!-- Only show error when it's not undefined and not empty. --> <!--
Only show error when it's not undefined and not empty.
TODO: Maybe remove this in favor of genericError?
-->
<div v-if="instanceSpecificData?.uploadState?.error?.length" class="bg-danger"> <div v-if="instanceSpecificData?.uploadState?.error?.length" class="bg-danger">
<span>Couldn't upload post. {{ instanceSpecificData.uploadState.error }}</span> <span>Couldn't upload post. {{ instanceSpecificData.uploadState.error }}</span>
</div> </div>
@ -389,15 +407,10 @@ useDark();
--> -->
<!-- TODO: Clicking a link doesn't actually open it in a new tab, see https://stackoverflow.com/questions/8915845 --> <!-- TODO: Clicking a link doesn't actually open it in a new tab, see https://stackoverflow.com/questions/8915845 -->
<div <div v-if="instanceSpecificData?.uploadState?.state == 'uploaded' && instanceSpecificData?.uploadState.instancePostId
v-if=" " class="bg-success">
instanceSpecificData?.uploadState?.state == 'uploaded' && instanceSpecificData?.uploadState.instancePostId <a :href="getActiveSitePostUrl(instanceSpecificData.uploadState.instancePostId)">Uploaded post {{
" instanceSpecificData.uploadState.instancePostId }}</a>
class="bg-success"
>
<a :href="getActiveSitePostUrl(instanceSpecificData.uploadState.instancePostId)"
>Uploaded post {{ instanceSpecificData.uploadState.instancePostId }}</a
>
</div> </div>
<div v-if="instanceSpecificData?.uploadState?.updateTagsState?.totalChanged" class="bg-success"> <div v-if="instanceSpecificData?.uploadState?.updateTagsState?.totalChanged" class="bg-success">
@ -410,64 +423,45 @@ useDark();
<div v-if="instanceSpecificData?.uploadState?.state == 'uploading'"><span>Uploading...</span></div> <div v-if="instanceSpecificData?.uploadState?.state == 'uploading'"><span>Uploading...</span></div>
<div <div v-if="instanceSpecificData?.uploadState?.updateTagsState?.total &&
v-if="
instanceSpecificData?.uploadState?.updateTagsState?.total &&
instanceSpecificData.uploadState?.updateTagsState?.current == undefined instanceSpecificData.uploadState?.updateTagsState?.current == undefined
" ">
>
<span>{{ instanceSpecificData.uploadState?.updateTagsState?.total }} tags need a different category</span> <span>{{ instanceSpecificData.uploadState?.updateTagsState?.total }} tags need a different category</span>
</div> </div>
<div <div v-if="instanceSpecificData?.uploadState?.updateTagsState?.current &&
v-if="
instanceSpecificData?.uploadState?.updateTagsState?.current &&
instanceSpecificData?.uploadState?.updateTagsState?.totalChanged == undefined instanceSpecificData?.uploadState?.updateTagsState?.totalChanged == undefined
" ">
> <span>Updating tag {{ instanceSpecificData.uploadState?.updateTagsState?.current }}/{{
<span
>Updating tag {{ instanceSpecificData.uploadState?.updateTagsState?.current }}/{{
instanceSpecificData.uploadState?.updateTagsState?.total instanceSpecificData.uploadState?.updateTagsState?.total
}}</span }}</span>
>
</div> </div>
<div v-if="isSearchingForSimilarPosts > 0 && instanceSpecificData?.uploadState == undefined"> <div v-if="isSearchingForSimilarPosts > 0 && instanceSpecificData?.uploadState == undefined">
<span>Searching for similar posts...</span> <span>Searching for similar posts...</span>
</div> </div>
<div <div v-if="instanceSpecificData?.reverseSearchResult?.similarPosts.length == 0 &&
v-if="
instanceSpecificData?.reverseSearchResult?.similarPosts.length == 0 &&
instanceSpecificData.uploadState == undefined instanceSpecificData.uploadState == undefined
" ">
>
<span>No similar posts found</span> <span>No similar posts found</span>
</div> </div>
<div <div v-for="similarPost in getSimilarPosts(instanceSpecificData?.reverseSearchResult)" :key="similarPost.id"
v-for="similarPost in getSimilarPosts(instanceSpecificData?.reverseSearchResult)" class="has-merge-button">
:key="similarPost.id" <a :href="getActiveSitePostUrl(similarPost.id)">Post {{ similarPost.id }} looks {{ similarPost.percentage }}%
class="has-merge-button" similar</a>
>
<a :href="getActiveSitePostUrl(similarPost.id)"
>Post {{ similarPost.id }} looks {{ similarPost.percentage }}% similar</a
>
<!-- TODO: Maybe a 5px gap here? --> <!-- TODO: Maybe a 5px gap here? -->
<div style="display: flex; background: purple; border-radius: 0 2px 2px 0"> <div style="display: flex; background: purple; border-radius: 0 2px 2px 0">
<router-link <router-link :to="{
:to="{
name: 'merge', name: 'merge',
params: { params: {
siteId: cfg.selectedSiteId, siteId: cfg.selectedSiteId,
postId: similarPost.id, postId: similarPost.id,
}, },
}" }" style="padding: 5px 20px">Merge</router-link>
style="padding: 5px 20px"
>Merge</router-link
>
</div> </div>
</div> </div>
</div> </div>
@ -512,18 +506,25 @@ useDark();
</div> </div>
</PopupSection> </PopupSection>
<PopupSection header="Tags"> <PopupSection header="Tags" toggleable v-model="cfg.popup.expandTags">
<div class="section-row"> <div class="section-row">
<TagInput :szuru="szuru" @add-tag="addTag" /> <TagInput :szuru="szuru" @add-tag="addTag" />
</div> </div>
<div class="section-row"> <div class="section-row">
<CompactTags <CompactTags :tags="pop.selectedPost.tags" :show-remove-tag="true" :show-usages="cfg.loadTagCounts"
:tags="pop.selectedPost.tags" @remove-tag="removeTag" />
:show-remove-tag="true" </div>
:show-usages="cfg.loadTagCounts" </PopupSection>
@remove-tag="removeTag"
/> <PopupSection header="Pools" toggleable v-model="cfg.popup.expandPools">
<div class="section-row">
<PoolInput :szuru="szuru" @add-pool="addPool" />
</div>
<div class="section-row">
<CompactPools :pools="pop.selectedPost.pools" :show-remove-pool="true" show-post-count
@remove-pool="removePool" />
</div> </div>
</PopupSection> </PopupSection>
@ -557,11 +558,8 @@ useDark();
</div> </div>
<div class="popup-section"> <div class="popup-section">
<PostContentDisplay <PostContentDisplay :content-url="pop.selectedPost.contentUrl" :content-type="pop.selectedPost.contentType"
:content-url="pop.selectedPost.contentUrl" @on-resolution-loaded="onResolutionLoaded" />
:content-type="pop.selectedPost.contentType"
@on-resolution-loaded="onResolutionLoaded"
/>
</div> </div>
</div> </div>
</div> </div>

View File

@ -30,6 +30,10 @@ export const cfg = useStorageLocal(
appendSource: true, appendSource: true,
mergeSafety: true, mergeSafety: true,
}, },
popup: {
expandTags: true,
expandPools: false,
},
tagCategories: [] as Array<TagCategoryColor>, tagCategories: [] as Array<TagCategoryColor>,
}, },
{ {
@ -56,7 +60,7 @@ export const cfg = useStorageLocal(
return cfg; return cfg;
}, },
} },
); );
export const usePopupStore = defineStore("popup", { export const usePopupStore = defineStore("popup", {

View File

@ -141,7 +141,7 @@ ul.compact {
display: inline; display: inline;
} }
.compact-tags { .compact-tags, .compact-pools {
list-style-type: none; list-style-type: none;
padding: 0; padding: 0;
display: inline; display: inline;