All files / app/shared/helpers picture-tooltip.ts

69.23% Statements 81/117
75.86% Branches 22/29
71.42% Functions 15/21
69.02% Lines 78/113

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 2572x 2x 2x   2x                 2x 57x   57x 57x 57x   57x 55x   54x 4x   50x   57x     57x   55x 55x   55x 51x     4x 4x     4x   4x 3x               54x   54x   54x 1x 1x           57x                                                               57x                     2x   2x 11x       11x 8x 8x   8x 6x       5x     2x 59x 59x       59x 11x     59x                         4x   4x 4x   4x 4x 4x 2x 2x   4x 1x 1x                 4x 4x       4x       1x 1x                               2x 2x 2x             59x 59x       59x 9x 9x 9x   9x 3x 6x 1x   5x       59x                                                        
import { MAX_PICTURES_BATCH_SIZE } from '../../services/pictures/picture.constants';
import { Extension, RangeSetBuilder, StateEffect, StateField } from '@codemirror/state';
import { Decoration, DecorationSet, EditorView, hoverTooltip, Tooltip, ViewPlugin, ViewUpdate } from '@codemirror/view';
import { PictureBatchResponse, Picture } from '@drevo-web/shared';
import { firstValueFrom, Observable } from 'rxjs';
 
// --- Public API ---
 
export interface PictureTooltipOptions {
    readonly getPicturesBatch: (ids: readonly number[]) => Observable<PictureBatchResponse>;
    readonly onPictureClick: (id: number) => void;
}
 
export function createPicturePreviewExtension(options: PictureTooltipOptions): Extension {
    const picturesUpdated = StateEffect.define<void>();
 
    const cache = new Map<number, Picture>();
    const errorIds = new Set<number>();
    const pendingIds = new Set<number>();
 
    const decorationField = StateField.define<DecorationSet>({
        create: state => buildDecorations(state.doc.toString(), cache, errorIds),
        update: (decorations, tr) => {
            if (tr.docChanged || tr.effects.some(e => e.is(picturesUpdated))) {
                return buildDecorations(tr.newDoc.toString(), cache, errorIds);
            }
            return decorations;
        },
        provide: f => EditorView.decorations.from(f),
    });
 
    const fetchPlugin = ViewPlugin.define(view => {
        function scheduleResolve(): void {
            const ids = extractPictureIds(view.state.doc.toString());
            const toFetch = ids.filter(id => !cache.has(id) && !pendingIds.has(id) && !errorIds.has(id));
 
            if (toFetch.length === 0) {
                return;
            }
 
            for (const id of toFetch) {
                pendingIds.add(id);
            }
 
            fetchBatch(toFetch, options, cache, errorIds, pendingIds)
                .then(hasChanges => {
                    if (hasChanges) {
                        view.dispatch({ effects: picturesUpdated.of(undefined) });
                    }
                })
                .catch(() => {
                    // noop — view may already be destroyed
                });
        }
 
        scheduleResolve();
 
        return {
            update(update: ViewUpdate) {
                if (update.docChanged) {
                    retryEditedErrors(update, errorIds);
                    scheduleResolve();
                }
            },
        };
    });
 
    const tooltip = hoverTooltip(
        (view, pos) => {
            const line = view.state.doc.lineAt(pos);
            const posInLine = pos - line.from;
            const found = findPictureCodeAtPosition(line.text, posInLine);
 
            if (!found) {
                // eslint-disable-next-line no-null/no-null
                return null;
            }
 
            const picture = cache.get(found.id);
            if (!picture) {
                // eslint-disable-next-line no-null/no-null
                return null;
            }
 
            const absoluteFrom = line.from + found.from;
            const absoluteTo = line.from + found.to;
 
            const result: Tooltip = {
                pos: absoluteFrom,
                end: absoluteTo,
                above: true,
                create: () => createTooltipDom(picture, found.id, options.onPictureClick),
            };
 
            return result;
        },
        { hoverTime: 100, hideOnChange: true },
    );
 
    return [decorationField, fetchPlugin, tooltip];
}
 
// --- Pure helpers (exported for testing) ---
 
export interface PictureCodeMatch {
    readonly id: number;
    readonly from: number;
    readonly to: number;
}
 
const PICTURE_CODE_RE = /@(\d+)@/g;
 
export function findPictureCodeAtPosition(lineText: string, posInLine: number): PictureCodeMatch | undefined {
    const regex = new RegExp(PICTURE_CODE_RE.source, PICTURE_CODE_RE.flags);
    let match: RegExpExecArray | null;
 
    // eslint-disable-next-line no-null/no-null
    while ((match = regex.exec(lineText)) !== null) {
        const from = match.index;
        const to = from + match[0].length;
 
        if (posInLine >= from && posInLine <= to) {
            return { id: Number(match[1]), from, to };
        }
    }
 
    return undefined;
}
 
export function extractPictureIds(text: string): number[] {
    const regex = new RegExp(PICTURE_CODE_RE.source, PICTURE_CODE_RE.flags);
    const ids = new Set<number>();
    let match: RegExpExecArray | null;
 
    // eslint-disable-next-line no-null/no-null
    while ((match = regex.exec(text)) !== null) {
        ids.add(Number(match[1]));
    }
 
    return Array.from(ids);
}
 
// --- Internal helpers ---
 
 
async function fetchBatch(
    ids: number[],
    options: PictureTooltipOptions,
    cache: Map<number, Picture>,
    errorIds: Set<number>,
    pendingIds: Set<number>,
): Promise<boolean> {
    let hasChanges = false;
 
    for (let i = 0; i < ids.length; i += MAX_PICTURES_BATCH_SIZE) {
        const chunk = ids.slice(i, i + MAX_PICTURES_BATCH_SIZE);
 
        try {
            const response = await firstValueFrom(options.getPicturesBatch(chunk));
            for (const picture of response.items) {
                cache.set(picture.id, picture);
                hasChanges = true;
            }
            for (const id of response.notFoundIds) {
                errorIds.add(id);
                hasChanges = true;
            }
        } catch {
            for (const id of chunk) {
                errorIds.add(id);
                hasChanges = true;
            }
        }
 
        for (const id of chunk) {
            pendingIds.delete(id);
        }
    }
 
    return hasChanges;
}
 
function retryEditedErrors(update: ViewUpdate, errorIds: Set<number>): void {
    Eif (errorIds.size === 0) {
        return;
    }
 
    update.changes.iterChangedRanges((_fromA, _toA, fromB, toB) => {
        const changedText = update.state.doc.sliceString(fromB, toB);
        const regex = new RegExp(PICTURE_CODE_RE.source, PICTURE_CODE_RE.flags);
        let match: RegExpExecArray | null;
 
        // eslint-disable-next-line no-null/no-null
        while ((match = regex.exec(changedText)) !== null) {
            const id = Number(match[1]);
            errorIds.delete(id);
        }
    });
}
 
const pendingDecoration = Decoration.mark({ class: 'cm-picture-pending' });
const resolvedDecoration = Decoration.mark({ class: 'cm-picture-resolved' });
const errorDecoration = Decoration.mark({ class: 'cm-picture-error' });
 
function buildDecorations(
    text: string,
    cache: Map<number, Picture>,
    errorIds: Set<number>,
): DecorationSet {
    const builder = new RangeSetBuilder<Decoration>();
    const regex = new RegExp(PICTURE_CODE_RE.source, PICTURE_CODE_RE.flags);
    let match: RegExpExecArray | null;
 
    // eslint-disable-next-line no-null/no-null
    while ((match = regex.exec(text)) !== null) {
        const from = match.index;
        const to = from + match[0].length;
        const id = Number(match[1]);
 
        if (cache.has(id)) {
            builder.add(from, to, resolvedDecoration);
        } else if (errorIds.has(id)) {
            builder.add(from, to, errorDecoration);
        } else {
            builder.add(from, to, pendingDecoration);
        }
    }
 
    return builder.finish();
}
 
// Direct `document` access is safe here: CM6 is browser-only and
// EditorComponent guards creation with `isServer()` check.
function createTooltipDom(
    picture: Picture,
    pictureId: number,
    onPictureClick: (id: number) => void,
): { dom: HTMLElement; offset: { x: number; y: number } } {
    const container = document.createElement('div');
    container.className = 'cm-picture-tooltip';
    container.addEventListener('click', () => onPictureClick(pictureId));
 
    const img = document.createElement('img');
    img.src = picture.thumbnailUrl;
    img.alt = picture.title;
    container.appendChild(img);
 
    if (picture.title) {
        const title = document.createElement('span');
        title.className = 'cm-picture-tooltip-title';
        title.textContent = picture.title;
        container.appendChild(title);
    }
 
    return { dom: container, offset: { x: 0, y: 4 } };
}