aboutsummaryrefslogtreecommitdiffstats
path: root/apps/theming/src/mixins/admin/TextValueMixin.js
blob: 94d63ce1c8cfb6e1e86c77ec473676494ec7116d (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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
 * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'

import FieldMixin from './FieldMixin.js'

export default {
	mixins: [
		FieldMixin,
	],

	watch: {
		value(value) {
			this.localValue = value
		},
	},

	data() {
		return {
			/** @type {string|boolean} */
			localValue: this.value,
		}
	},

	computed: {
		valueToPost() {
			if (this.type === 'url') {
				// if this is already encoded just make sure there is no doublequote (HTML XSS)
				// otherwise simply URL encode
				return this.isUrlEncoded(this.localValue)
					? this.localValue.replaceAll('"', '%22')
					: encodeURI(this.localValue)
			}
			// Convert boolean to string as server expects string value
			if (typeof this.localValue === 'boolean') {
				return this.localValue ? 'yes' : 'no'
			}
			return this.localValue
		},
	},

	methods: {
		/**
		 * Check if URL is percent-encoded
		 * @param {string} url The URL to check
		 * @return {boolean}
		 */
		isUrlEncoded(url) {
			try {
				return decodeURI(url) !== url
			} catch {
				return false
			}
		},

		async save() {
			this.reset()
			const url = generateUrl('/apps/theming/ajax/updateStylesheet')

			try {
				await axios.post(url, {
					setting: this.name,
					value: this.valueToPost,
				})
				this.$emit('update:value', this.localValue)
				this.handleSuccess()
			} catch (e) {
				console.error('Failed to save changes', e)
				this.errorMessage = e.response?.data.data?.message
			}
		},

		async undo() {
			this.reset()
			const url = generateUrl('/apps/theming/ajax/undoChanges')
			try {
				const { data } = await axios.post(url, {
					setting: this.name,
				})

				if (data.data.value) {
					this.$emit('update:defaultValue', data.data.value)
				}
				this.$emit('update:value', data.data.value || this.defaultValue)
				this.handleSuccess()
			} catch (e) {
				this.errorMessage = e.response.data.data?.message
			}
		},
	},
}