aboutsummaryrefslogtreecommitdiffstats
path: root/apps/files_versions/src/components/VirtualScrolling.vue
blob: 5a502036839cba692db3ca84b37422fbceb25ecd (plain)
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
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
<?php

declare(strict_types=1);
/**
 * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */
namespace OCP\AppFramework\Http;

use OC\Streamer;
use OCP\AppFramework\Http;
use OCP\IRequest;

/**
 * Public library to send several files in one zip archive.
 *
 * @since 15.0.0
 * @template S of Http::STATUS_*
 * @template H of array<string, mixed>
 * @template-extends Response<Http::STATUS_*, array<string, mixed>>
 */
class ZipResponse extends Response implements ICallbackResponse {
	/** @var array{internalName: string, resource: resource, size: int, time: int}[] Files to be added to the zip response */
	private array $resources = [];
	/** @var string Filename that the zip file should have */
	private string $name;
	private IRequest $request;

	/**
	 * @param S $status
	 * @param H $headers
	 * @since 15.0.0
	 */
	public function __construct(IRequest $request, string $name = 'output', int $status = Http::STATUS_OK, array $headers = []) {
		parent::__construct($status, $headers);

		$this->name = $name;
		$this->request = $request;
	}

	/**
	 * @since 15.0.0
	 */
	public function addResource($r, string $internalName, pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
<!--
  - SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
  - SPDX-License-Identifier: AGPL-3.0-or-later
-->
<template>
	<div v-if="!useWindow && containerElement === null" ref="container" class="vs-container">
		<div ref="rowsContainer"
			class="vs-rows-container"
			:style="rowsContainerStyle">
			<slot :visible-sections="visibleSections" />
			<slot name="loader" />
		</div>
	</div>
	<div v-else
		ref="rowsContainer"
		class="vs-rows-container"
		:style="rowsContainerStyle">
		<slot :visible-sections="visibleSections" />
		<slot name="loader" />
	</div>
</template>

<script lang="ts">
import { defineComponent, type PropType } from 'vue'

import logger from '../utils/logger.js'

interface RowItem {
	id: string // Unique id for the item.
	key?: string // Unique key for the item.
}

interface Row {
	key: string // Unique key for the row.
	height: number // The height of the row.
	sectionKey: string // Unique key for the row.
	items: RowItem[] // List of items in the row.
}

interface VisibleRow extends Row {
	distance: number // The distance from the visible viewport
}

interface Section {
	key: string, // Unique key for the section.
	rows: Row[], // The height of the row.
	height: number, // Height of the section, excluding the header.
}

interface VisibleSection extends Section {
	rows: VisibleRow[], // The height of the row.
}

export default defineComponent({
	name: 'VirtualScrolling',

	props: {
		sections: {
			type: Array as PropType<Section[]>,
			required: true,
		},

		containerElement: {
			type: HTMLElement,
			default: null,
		},

		useWindow: {
			type: Boolean,
			default: false,
		},

		headerHeight: {
			type: Number,
			default: 75,
		},
		renderDistance: {
			type: Number,
			default: 0.5,
		},
		bottomBufferRatio: {
			type: Number,
			default: 2,
		},
		scrollToKey: {
			type: String,
			default: '',
		},
	},

	data() {
		return {
			scrollPosition: 0,
			containerHeight: 0,
			rowsContainerHeight: 0,
			resizeObserver: null as ResizeObserver|null,
		}
	},

	computed: {
		visibleSections(): VisibleSection[] {
			logger.debug('[VirtualScrolling] Computing visible section', { sections: this.sections })

			// Optimization: get those computed properties once to not go through vue's internal every time we need them.
			const containerHeight = this.containerHeight
			const containerTop = this.scrollPosition
			const containerBottom = containerTop + containerHeight

			let currentRowTop = 0
			let currentRowBottom = 0

			// Compute whether a row should be included in the DOM (shouldRender)
			// And how visible the row is.
			const visibleSections = this.sections
				.map(section => {
					currentRowBottom += this.headerHeight

					return {
						...section,
						rows: section.rows.reduce((visibleRows, row) => {
							currentRowTop = currentRowBottom
							currentRowBottom += row.height

							let distance = 0

							if (currentRowBottom < containerTop) {
								distance = (containerTop - currentRowBottom) / containerHeight
							} else if (currentRowTop > containerBottom) {
								distance = (currentRowTop - containerBottom) / containerHeight
							}

							if (distance > this.renderDistance) {
								return visibleRows
							}

							return [
								...visibleRows,
								{
									...row,
									distance,
								},
							]
						}, [] as VisibleRow[]),
					}
				})
				.filter(section => section.rows.length > 0)

			// To allow vue to recycle the DOM elements instead of adding and deleting new ones,
			// we assign a random key to each items. When a item removed, we recycle its key for new items,
			// so vue can replace the content of removed DOM elements with the content of new items, but keep the other DOM elements untouched.
			const visibleItems = visibleSections
				.flatMap(({ rows }) => rows)
				.flatMap(({ items }) => items)

			const rowIdToKeyMap = this._rowIdToKeyMap as {[key: string]: string}

			visibleItems.forEach(item => (item.key = rowIdToKeyMap[item.id]))

			const usedTokens = visibleItems
				.map(({ key }) => key)
				.filter(key => key !== undefined)

			const unusedTokens = Object.values(rowIdToKeyMap).filter(key => !usedTokens.includes(key))

			visibleItems
				.filter(({ key }) => key === undefined)
				.forEach(item => (item.key = unusedTokens.pop() ?? Math.random().toString(36).substr(2)))

			// this._rowIdToKeyMap is created in the beforeCreate hook, so value changes are not tracked.
			// Therefore, we wont trigger the computation of visibleSections again if we alter the value of this._rowIdToKeyMap.
			// eslint-disable-next-line vue/no-side-effects-in-computed-properties
			this._rowIdToKeyMap = visibleItems.reduce((finalMapping, { id, key }) => ({ ...finalMapping, [`${id}`]: key }), {})

			return visibleSections
		},

		/**
		 * Total height of all the rows + some room for the loader.
		 */
		totalHeight(): number {
			const loaderHeight = 0

			return this.sections
				.map(section => this.headerHeight + section.height)
				.reduce((totalHeight, sectionHeight) => totalHeight + sectionHeight, 0) + loaderHeight
		},

		paddingTop(): number {
			if (this.visibleSections.length === 0) {
				return 0
			}

			let paddingTop = 0

			for (const section of this.sections) {
				if (section.key !== this.visibleSections[0].rows[0].sectionKey) {
					paddingTop += this.headerHeight + section.height
					continue
				}

				for (const row of section.rows) {
					if (row.key === this.visibleSections[0].rows[0].key) {
						return paddingTop
					}

					paddingTop += row.height
				}

				paddingTop += this.headerHeight
			}

			return paddingTop
		},

		/**
		 * padding-top is used to replace not included item in the container.
		 */
		rowsContainerStyle(): { height: string; paddingTop: string } {
			return {
				height: `${this.totalHeight}px`,
				paddingTop: `${this.paddingTop}px`,
			}
		},

		/**
		 * Whether the user is near the bottom.
		 * If true, then the need-content event will be emitted.
		 */
		isNearBottom(): boolean {
			const buffer = this.containerHeight * this.bottomBufferRatio
			return this.scrollPosition + this.containerHeight >= this.totalHeight - buffer
		},

		container() {
			logger.debug('[VirtualScrolling] Computing container')
			if (this.containerElement !== null) {
				return this.containerElement
			} else if (this.useWindow) {
				return window
			} else {
				return this.$refs.container as Element
			}
		},
	},

	watch: {
		isNearBottom(value) {
			logger.debug('[VirtualScrolling] isNearBottom changed', { value })
			if (value) {
				this.$emit('need-content')
			}
		},

		visibleSections() {
			// Re-emit need-content when rows is updated and isNearBottom is still true.
			// If the height of added rows is under `bottomBufferRatio`, `isNearBottom` will still be true so we need more content.
			if (this.isNearBottom) {
				this.$emit('need-content')
			}
		},

		scrollToKey(key) {
			let currentRowTopDistanceFromTop = 0

			for (const section of this.sections) {
				if (section.key !== key) {
					currentRowTopDistanceFromTop += this.headerHeight + section.height
					continue
				}

				break
			}

			logger.debug('[VirtualScrolling] Scrolling to', { currentRowTopDistanceFromTop })
			this.container.scrollTo({ top: currentRowTopDistanceFromTop, behavior: 'smooth' })
		},
	},

	beforeCreate() {
		this._rowIdToKeyMap = {}
	},

	mounted() {
		this.resizeObserver = new ResizeObserver(entries => {
			for (const entry of entries) {
				const cr = entry.contentRect
				if (entry.target === this.container) {
					this.containerHeight = cr.height
				}
				if (entry.target.classList.contains('vs-rows-container')) {
					this.rowsContainerHeight = cr.height
				}
			}
		})

		if (this.useWindow) {
			window.addEventListener('resize', this.updateContainerSize, { passive: true })
			this.containerHeight = window.innerHeight
		} else {
			this.resizeObserver.observe(this.container as HTMLElement|Element)
		}

		this.resizeObserver.observe(this.$refs.rowsContainer as Element)
		this.container.addEventListener('scroll', this.updateScrollPosition, { passive: true })
	},

	beforeDestroy() {
		if (this.useWindow) {
			window.removeEventListener('resize', this.updateContainerSize)
		}

		this.resizeObserver?.disconnect()
		this.container.removeEventListener('scroll', this.updateScrollPosition)
	},

	methods: {
		updateScrollPosition() {
			this._onScrollHandle ??= requestAnimationFrame(() => {
				this._onScrollHandle = null
				if (this.useWindow) {
					this.scrollPosition = (this.container as Window).scrollY
				} else {
					this.scrollPosition = (this.container as HTMLElement|Element).scrollTop
				}
			})
		},

		updateContainerSize() {
			this.containerHeight = window.innerHeight
		},
	},
})
</script>

<style scoped lang="scss">
.vs-container {
	overflow-y: scroll;
	height: 100%;
}

.vs-rows-container {
	box-sizing: border-box;
	will-change: scroll-position, padding;
	contain: layout paint style;
}
</style>