Files
traxxx-web/components/scenes/relation.vue
T

783 lines
18 KiB
Vue

<script setup>
import { format, startOfDay, startOfMonth, startOfYear } from 'date-fns';
import { computed, onMounted, ref, useId, watch } from 'vue';
import Dialog from '#/components/dialog/dialog.vue';
import Ellipsis from '#/components/loading/ellipsis.vue';
import { get, post } from '#/src/api.js';
import getPath from '#/src/get-path.js';
import { getRelationLabel, sortRelationTypes } from '#/utils/relation-labels.js';
const props = defineProps({
scene: {
type: Object,
required: true,
},
types: {
type: Array,
required: true,
},
});
const emit = defineEmits(['close', 'relation']);
const searchDelay = 300;
const searchDropdownId = useId();
const query = ref('');
const queryInput = ref(null);
const results = ref([]);
const searching = ref(false);
const selectedScene = ref(null);
const selectedOption = ref(null);
const comment = ref('');
const commentLimit = 500; // matches the server limit
const searchCompleted = ref(false); // only show 'no results' once a search for the current query has finished
let searchTimeout = null;
let searchCount = 0;
// copy actors or tags between the scenes once when the revision is applied, relative to this scene
const share = ref({});
const shareOptions = ref(null); // what each scene would get from the other if everything were copied both ways
const previewing = ref(false);
const shareFieldLabels = {
actors: 'Copy actors',
tags: 'Copy tags',
duration: 'Duration',
};
const sceneTitle = computed(() => props.scene.title || `scene #${props.scene.id}`);
const relatedTitle = computed(() => (selectedScene.value ? selectedScene.value.title || `scene #${selectedScene.value.id}` : 'the related scene'));
// the same modes for every field, with titles naming the field they apply to
function getShareModes(field) {
const fieldName = (shareFieldLabels[field] || field).toLowerCase();
return [
{ mode: 'from', label: 'From related', title: `Copy ${fieldName} from "${relatedTitle.value}" to "${sceneTitle.value}"` },
{ mode: 'both', label: 'Both ways', title: `Copy ${fieldName} between both scenes` },
{ mode: 'to', label: 'To related', title: `Copy ${fieldName} from "${sceneTitle.value}" to "${relatedTitle.value}"` },
{ mode: 'none', label: 'None', title: `Do not share any ${fieldName}` },
];
}
let previewCount = 0;
// each type can be read from either side, e.g. this scene is a 'Remaster of' or 'Remastered as' the selected scene
// symmetric types like variants read the same both ways
const options = computed(() => sortRelationTypes(props.types, ({ type }) => type).flatMap(({ type, symmetric }) => (symmetric ? ['both'] : ['target', 'source']).map((direction) => ({
key: `${type}-${direction}`,
type,
direction,
label: getRelationLabel(type, direction),
}))));
const hasQuery = computed(() => query.value.trim().length > 0);
const showResults = computed(() => results.value.length > 0 || (hasQuery.value && !searching.value && searchCompleted.value));
// derivations and compilations are released after what they're based on, the source of the relation should not predate the target
const chronologicalTypes = ['rerelease', 'remaster', 'reedit', 'compilation'];
const datePrecisions = { year: startOfYear, month: startOfMonth };
// compare at the coarsest precision of the two, a scene known only by its year isn't necessarily earlier than one from later that year
function getComparableDates(sceneA, sceneB) {
const precision = ['year', 'month'].find((datePrecision) => [sceneA.datePrecision, sceneB.datePrecision].includes(datePrecision));
const truncate = datePrecisions[precision] || startOfDay;
return [truncate(new Date(sceneA.date)), truncate(new Date(sceneB.date))];
}
// only a hint, the dates may be wrong or the relation unusual, so it never blocks
const inversion = computed(() => {
if (!selectedScene.value || !selectedOption.value || !chronologicalTypes.includes(selectedOption.value.type)) {
return null;
}
const { type, direction } = selectedOption.value;
const [sourceScene, targetScene] = direction === 'target' ? [props.scene, selectedScene.value] : [selectedScene.value, props.scene];
if (!sourceScene.date || !targetScene.date) {
return null;
}
const [sourceDate, targetDate] = getComparableDates(sourceScene, targetScene);
if (sourceDate >= targetDate) {
return null;
}
return {
isCurrentEarlier: sourceScene === props.scene,
option: options.value.find((option) => option.type === type && option.direction === (direction === 'target' ? 'source' : 'target')),
};
});
const selectedType = computed(() => props.types.find((type) => type.type === selectedOption.value?.type));
// every type has the same shareable fields, so they can be shown before a type is selected
const shareFields = computed(() => selectedType.value?.shareFields || props.types[0]?.shareFields || []);
const isSharing = computed(() => Object.values(share.value).some((mode) => mode && mode !== 'none'));
// defaults are stored by which side of the relation receives, translate them to this scene's point of view
function getDefaultShare(type, direction) {
const ownSide = direction === 'target' ? 'source' : 'target'; // direction is the related scene's side
return Object.fromEntries((type?.shareFields || []).map((field) => {
const receiver = type.shareDefaults?.[field];
if (!receiver) {
return [field, 'none'];
}
if (receiver === 'both' || direction === 'both') {
return [field, 'both'];
}
return [field, receiver === ownSide ? 'from' : 'to'];
}));
}
watch(selectedOption, (option) => {
share.value = getDefaultShare(selectedType.value, option?.direction);
});
// what can be copied only depends on the two scenes, so it's fetched once per selected scene and filtered by the share modes locally
async function fetchShareOptions() {
const previewId = ++previewCount;
shareOptions.value = null;
if (!selectedScene.value) {
previewing.value = false;
return;
}
previewing.value = true;
try {
const result = await post(`/scenes/${props.scene.id}/relations/share-preview`, {
sceneId: selectedScene.value.id,
});
if (previewId === previewCount) {
shareOptions.value = result;
}
}
catch (_error) {
// the preview is only informative
}
finally {
if (previewId === previewCount) {
previewing.value = false;
}
}
}
watch(selectedScene, fetchShareOptions);
// what a scene gets with the selected share modes, out of everything it could get
const emptyShareOption = { actors: [], tags: [], duration: null };
// shown before a scene is selected, with nothing to copy yet
function getPreviewScene(key, title, option = emptyShareOption, receives) {
const fields = new Set(Object.entries(share.value).filter(([, mode]) => mode === 'both' || mode === receives).map(([field]) => field));
const actors = fields.has('actors') ? option.actors : [];
const tags = fields.has('tags') ? option.tags : [];
const duration = fields.has('duration') ? option.duration : null;
return {
key,
title,
actors,
tags,
duration,
};
}
const preview = computed(() => [
getPreviewScene('scene', sceneTitle.value, shareOptions.value?.scene, 'from'),
getPreviewScene('related', selectedScene.value ? relatedTitle.value : 'Related scene', shareOptions.value?.relatedScene, 'to'),
]);
function formatDuration(seconds) {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
return [hours, minutes, seconds % 60].map((unit, index) => (index === 0 ? unit : String(unit).padStart(2, '0'))).join(':').replace(/^0:/, '');
}
const canSubmit = computed(() => !!selectedScene.value && !!selectedOption.value);
const hasChanges = computed(() => !!selectedScene.value || !!selectedOption.value || comment.value.trim().length > 0);
// accept a pasted scene ID or traxxx scene URL, the search index does not match IDs
function getSceneId(value) {
const id = value.match(/^\s*(\d+)\s*$/)?.[1] || value.match(/\/scene\/(\d+)/)?.[1];
return id ? Number(id) : null;
}
async function search() {
const searchId = ++searchCount;
const sceneId = getSceneId(query.value);
searching.value = true;
searchCompleted.value = false;
try {
const scenes = sceneId
? [await get(`/scenes/${sceneId}`)]
: (await get('/scenes', { q: query.value, limit: 10 })).scenes;
if (searchId === searchCount) {
results.value = scenes.filter((result) => result && result.id !== props.scene.id);
}
}
catch (_error) {
if (searchId === searchCount) {
results.value = [];
}
}
finally {
if (searchId === searchCount) {
searching.value = false;
searchCompleted.value = true;
}
}
}
function queueSearch() {
clearTimeout(searchTimeout);
searchCompleted.value = false;
if (!hasQuery.value) {
searchCount += 1; // discard pending responses
results.value = [];
searching.value = false;
return;
}
searchTimeout = setTimeout(search, searchDelay);
}
function focusInput() {
setTimeout(() => {
queryInput.value?.focus();
}, 100);
}
function selectScene(result) {
selectedScene.value = result;
results.value = [];
query.value = '';
searchCompleted.value = false;
}
function deselectScene() {
selectedScene.value = null;
focusInput();
}
function formatSceneMeta(result) {
return [result.channel.name, result.date && format(result.date, 'yyyy-MM-dd')].filter(Boolean).join(', ');
}
// the relation is only added to the edit, it's stored when the revision is submitted
function addRelation() {
emit('relation', {
sceneId: selectedScene.value.id,
type: selectedOption.value.type,
direction: selectedOption.value.direction,
comment: comment.value.trim() || null,
share: isSharing.value
? Object.fromEntries(Object.entries(share.value).filter(([, mode]) => mode !== 'none'))
: null,
scene: selectedScene.value,
});
}
onMounted(() => focusInput());
</script>
<template>
<Dialog
title="Add relation"
:confirm-close="hasChanges"
@close="emit('close')"
>
<form
class="dialog-body"
@submit.prevent="addRelation"
>
<div class="scene current">
<img
v-if="scene.poster"
:src="getPath(scene.poster, 'thumbnail')"
class="poster"
>
<span class="info">
<h4 class="title ellipsis">{{ scene.title || `Scene #${scene.id}` }}</h4>
<span class="meta ellipsis">{{ formatSceneMeta(scene) }}</span>
</span>
</div>
<select
v-model="selectedOption"
class="input"
>
<option
:value="null"
disabled
>Select relation</option>
<option
v-for="option in options"
:key="`option-${option.key}`"
:value="option"
>{{ option.label }}</option>
</select>
<div
v-if="selectedScene"
class="scene selected"
>
<img
v-if="selectedScene.poster"
:src="getPath(selectedScene.poster, 'thumbnail')"
class="poster"
>
<span class="info">
<h4 class="title ellipsis">{{ selectedScene.title || `Scene #${selectedScene.id}` }}</h4>
<span class="meta ellipsis">{{ formatSceneMeta(selectedScene) }}</span>
</span>
<Icon
icon="cross2"
title="Choose another scene"
class="deselect"
@click="deselectScene"
/>
</div>
<VDropdown
v-else
:aria-id="searchDropdownId"
:triggers="[]"
:shown="showResults"
:auto-hide="false"
placement="bottom-start"
class="search"
>
<input
ref="queryInput"
v-model="query"
type="search"
enterkeyhint="search"
placeholder="Search scene, or paste an ID or URL"
class="input"
@input="queueSearch"
@keydown.enter.prevent
>
<template #popper>
<ul
v-if="results.length > 0"
class="results nolist"
>
<li
v-for="result in results"
:key="`result-${result.id}`"
v-close-popper
class="scene result"
@click="selectScene(result)"
>
<img
v-if="result.poster"
:src="getPath(result.poster, 'thumbnail')"
loading="lazy"
class="poster"
>
<span class="info">
<h4 class="title ellipsis">{{ result.title || `Scene #${result.id}` }}</h4>
<span class="meta ellipsis">{{ formatSceneMeta(result) }}</span>
</span>
</li>
</ul>
<p
v-else
class="status"
>No scenes found</p>
</template>
</VDropdown>
<div
class="share"
:class="{ disabled: !selectedOption && !selectedScene }"
>
<div
v-for="field in shareFields"
:key="`share-${field}`"
class="share-field"
>
<strong class="share-label">{{ shareFieldLabels[field] || field }}</strong>
<div class="share-modes">
<label
v-for="shareMode in getShareModes(field)"
:key="`share-${field}-${shareMode.mode}`"
v-tooltip="shareMode.title"
class="share-mode"
:class="{ active: (share[field] || 'none') === shareMode.mode }"
>
<input
v-model="share[field]"
type="radio"
:name="`share-${field}`"
:value="shareMode.mode"
class="share-radio"
>{{ shareMode.label }}
</label>
</div>
</div>
<div
class="share-preview"
>
<div
v-for="previewScene in preview"
:key="`preview-${previewScene.key}`"
class="preview-scene"
>
<h4 class="heading preview-title">{{ previewScene.title }}</h4>
<span class="preview-row"><strong class="preview-label">New actors</strong>:
<Ellipsis
v-if="previewing"
class="preview-loading"
/>
<span v-else-if="previewScene.actors.length > 0">{{ previewScene.actors.map((actor) => actor.name).join(', ') }}</span>
<span
v-else
class="preview-none"
>None</span>
</span>
<span class="preview-row"><strong class="preview-label">New tags</strong>:
<Ellipsis
v-if="previewing"
class="preview-loading"
/>
<span v-else-if="previewScene.tags.length > 0">{{ previewScene.tags.map((tag) => tag.name).join(', ') }}</span>
<span
v-else
class="preview-none"
>None</span>
</span>
<span
v-if="previewScene.duration"
class="preview-row"
><strong class="preview-label">Duration</strong>: {{ formatDuration(previewScene.duration) }}</span>
</div>
</div>
</div>
<textarea
v-model="comment"
:maxlength="commentLimit"
rows="2"
placeholder="Optional comment"
class="comment input"
/>
<p
v-if="inversion"
class="inversion"
>
<Icon icon="warning2" />
<span>
The source scene was released {{ inversion.isCurrentEarlier ? 'before' : 'after' }} the target scene, did you mean
<button
type="button"
class="inversion-option"
@click="selectedOption = inversion.option"
>{{ inversion.option.label }}</button>?
</span>
</p>
<div class="dialog-actions">
<button
:disabled="!canSubmit"
class="button button-primary"
>Add relation</button>
</div>
</form>
</Dialog>
</template>
<style scoped>
.dialog-body {
width: 30rem;
max-width: 100%;
box-sizing: border-box;
gap: .75rem;
padding: 1rem;
overflow-y: auto;
.input {
width: 100%;
box-sizing: border-box;
}
}
.dialog-heading {
margin: 0;
}
.inversion {
display: flex;
align-items: center;
gap: 1rem;
padding: .5rem;
margin: 0;
border-radius: .25rem;
background: var(--warn);
color: var(--text-light);
font-size: .9rem;
line-height: 1.25;
.icon {
flex-shrink: 0;
fill: var(--text-light);
}
}
.inversion-option {
padding: 0;
border: none;
background: none;
color: inherit;
font: inherit;
font-weight: bold;
text-decoration: underline;
cursor: pointer;
}
.share {
display: flex;
flex-direction: column;
gap: .5rem;
margin-top: .5rem;
&.disabled {
opacity: .5;
pointer-events: none;
}
}
.share-legend {
padding: 0 .25rem;
color: var(--glass-strong-10);
font-size: .9rem;
}
.share-field {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: .25rem .75rem;
}
.share-label {
flex-grow: 1;
width: 4.5rem;
font-size: .9rem;
}
.share-modes {
display: flex;
flex-wrap: wrap;
overflow: hidden;
border-radius: .25rem;
box-shadow: 0 0 3px var(--shadow-weak-30);
}
.share-mode {
padding: .5rem .75rem;
font-size: .85rem;
cursor: pointer;
user-select: none;
&:not(:last-child) {
border-right: solid 1px var(--glass-weak-40);
}
&:hover {
color: var(--primary);
}
&.active {
background: var(--primary);
color: var(--text-light);
}
&:has(:focus-visible) {
outline: solid 2px var(--primary);
outline-offset: -2px;
}
}
.share-radio {
position: absolute;
opacity: 0;
pointer-events: none;
}
.share-preview {
display: flex;
flex-direction: column;
gap: .25rem;
margin: .5rem 0 0 0;
font-size: .9rem;
line-height: 1.3;
}
.share-note {
margin: 0;
color: var(--glass-strong-10);
font-size: .8rem;
line-height: 1.3;
}
.preview-title {
margin: 0;
}
.preview-row {
display: block;
margin: .25rem 0;
}
/* the loader is sized for a page, keep it within a line of text */
.preview-loading {
width: 2.5rem;
height: 1em;
padding: 0;
align-items: center;
vertical-align: middle;
:deep(.load-ellipsis) {
flex-shrink: 0;
transform: scale(.5);
transform-origin: left center;
}
}
.preview-none {
color: var(--glass-strong-10);
font-style: italic;
}
.dialog-actions {
display: flex;
justify-content: center;
margin-top: .5rem;
}
.search {
width: 100%;
}
.results {
width: 28rem;
max-width: calc(100vw - 2rem);
max-height: 18rem;
overflow-y: auto;
}
.scene {
display: flex;
flex-shrink: 0;
align-items: center;
gap: .5rem;
overflow: hidden;
}
.result:not(:last-child) {
border-bottom: solid 1px var(--shadow-weak-40);
}
.result:hover {
background: var(--glass-weak-50);
cursor: pointer;
.title {
color: var(--primary);
}
}
.current,
.selected {
border-radius: .25rem;
background: var(--glass-weak-50);
}
.deselect {
flex-shrink: 0;
padding: .5rem;
fill: var(--glass-strong-10);
&:hover {
fill: var(--primary);
cursor: pointer;
}
}
.poster {
width: 5rem;
aspect-ratio: 16 / 9;
flex-shrink: 0;
object-fit: cover;
border-radius: .25rem;
}
.info {
display: flex;
flex-direction: column;
flex-grow: 1;
gap: .15rem;
overflow: hidden;
.title {
font-size: .9rem;
margin: 0;
}
}
.meta,
.status {
color: var(--glass-strong-10);
font-size: .9rem;
}
.status {
margin: 0;
padding: .5rem;
}
.comment {
/* .input has flex-basis: 0, which collapses a textarea in the column layout, size it by its rows instead */
flex: 0 0 auto;
margin: .5rem 0 0 0;
resize: vertical;
}
</style>