Update docs

This commit is contained in:
Alan Grainger
2026-10-08 22:33:54 +13:00
parent ecc22d2a08
commit bbff86957a
14 changed files with 1196 additions and 217 deletions
+14 -14
View File
@@ -1,17 +1,13 @@
{ {
"ipp": { "ipp": {
"responseHeaders": { "allowDownload": 0,
"Cache-Control": "public, max-age=2592000",
"Access-Control-Allow-Origin": "*"
},
"maxDownloadQuality": "original", "maxDownloadQuality": "original",
"downloadedFilename": 2,
"maxZoomQuality": "preview", "maxZoomQuality": "preview",
"motionPhotos": true, "motionPhotos": true,
"downloadedFilename": 2,
"allowDownload": 0,
"uploadUrl": "/upload",
"allowSlugLinks": true,
"showHomePage": true, "showHomePage": true,
"allowSlugLinks": true,
"uploadUrl": "/upload",
"showMetadata": { "showMetadata": {
"description": { "description": {
"caption": false, "caption": false,
@@ -39,26 +35,30 @@
"webLink": true "webLink": true
} }
}, },
"customInvalidResponse": false,
"gallery": { "gallery": {
"singleImage": false,
"singleVideo": true,
"singleItemAutoOpen": true,
"showTitle": true, "showTitle": true,
"showDescription": false, "showDescription": false,
"showExpiryDate": false, "showExpiryDate": false,
"expiryDateFormat": "YYYY-MM-DD", "expiryDateFormat": "YYYY-MM-DD",
"expiryDateLocale": "", "expiryDateLocale": "",
"groupByDate": false,
"showDownloadZip": true, "showDownloadZip": true,
"groupByDate": false,
"singleImage": false,
"singleVideo": true,
"singleItemAutoOpen": true,
"cacheTime": 300 "cacheTime": 300
}, },
"lightbox": { "lightbox": {
"showArrows": true, "showArrows": true,
"showDownload": true,
"mobileArrows": false, "mobileArrows": false,
"showDownload": true,
"autoPlayVideos": false, "autoPlayVideos": false,
"options": {} "options": {}
},
"customInvalidResponse": false,
"responseHeaders": {
"Cache-Control": "public, max-age=2592000",
"Access-Control-Allow-Origin": "*"
} }
} }
} }
+3 -2
View File
@@ -1,5 +1,5 @@
import { defineConfigWithTheme, type DefaultTheme } from 'vitepress' import { defineConfigWithTheme, type DefaultTheme } from 'vitepress'
import { configSchemaPlugin } from './configSchema' import { configCheckPlugin } from './configCheck'
const REPO_URL = 'https://github.com/alangrainger/immich-public-proxy' const REPO_URL = 'https://github.com/alangrainger/immich-public-proxy'
@@ -46,7 +46,7 @@ export default async () => defineConfigWithTheme<ThemeConfig>({
], ],
vite: { vite: {
// Fails the build when the config reference pages and the default config files disagree // Fails the build when the config reference pages and the default config files disagree
plugins: [configSchemaPlugin()] plugins: [configCheckPlugin()]
}, },
themeConfig: { themeConfig: {
logo: '/ipp.svg', logo: '/ipp.svg',
@@ -82,6 +82,7 @@ export default async () => defineConfigWithTheme<ThemeConfig>({
text: 'Configuration', text: 'Configuration',
items: [ items: [
{ text: 'Overview', link: '/config/' }, { text: 'Overview', link: '/config/' },
{ text: 'Config generator', link: '/config/generator' },
{ text: 'Environment variables', link: '/config/environment-variables' }, { text: 'Environment variables', link: '/config/environment-variables' },
{ text: 'General options', link: '/config/ipp-options' }, { text: 'General options', link: '/config/ipp-options' },
{ text: 'Gallery', link: '/config/gallery' }, { text: 'Gallery', link: '/config/gallery' },
+87
View File
@@ -0,0 +1,87 @@
import { readdirSync, readFileSync } from 'node:fs'
import { basename, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import type { Plugin } from 'vite'
import { checkKeys, LABELS, parsePage, parseRenamedKeys, type ConfigKey, type RenamedKey } from './configSchema'
/*
The Node half of the config schema: reads the reference pages and the
default config files from disk, and fails the docs build when they
disagree. The parsing and the checks themselves are in configSchema.ts.
*/
const DOCS_CONFIG_DIR = fileURLToPath(new URL('../config/', import.meta.url))
const REPO_ROOT = fileURLToPath(new URL('../../', import.meta.url))
/** The default config files, as repo paths. Both containers can share one config, so they are checked as one. */
const DEFAULTS_FILES = ['app/config.json', 'upload-app/config.json']
/**
* Read every page in docs/config and both default config files, and check
* them against each other. Returns `checkKeys`' keys, the renamed keys from
* config/upgrading.md, and every problem, the pages' own format problems
* first. A renamed key whose current name no page documents is a problem too,
* and so is a label in `LABELS` for a key no page documents.
*/
export function readConfigSchema (): { keys: ConfigKey[], renamed: RenamedKey[], problems: string[] } {
const keys: ConfigKey[] = []
const problems: string[] = []
for (const file of readdirSync(DOCS_CONFIG_DIR).filter(name => name.endsWith('.md')).sort()) {
const page = parsePage(readFileSync(join(DOCS_CONFIG_DIR, file), 'utf8'), '/config/' + basename(file, '.md'))
keys.push(...page.keys)
problems.push(...page.problems)
}
const files = DEFAULTS_FILES.map(name => ({ name, config: JSON.parse(readFileSync(join(REPO_ROOT, name), 'utf8')) }))
const checked = checkKeys(keys, files)
problems.push(...checked.problems)
const renamed = parseRenamedKeys(readFileSync(join(DOCS_CONFIG_DIR, 'upgrading.md'), 'utf8'))
const documented = new Set(checked.keys.map(key => key.path))
for (const { from, to } of renamed) {
if (!documented.has(to)) problems.push(`docs/config/upgrading.md: \`${from}\` is renamed to \`${to}\`, which no page documents`)
}
for (const path of Object.keys(LABELS)) {
if (!documented.has(path)) problems.push(`docs/.vitepress/configSchema.ts: LABELS has a label for \`${path}\`, which no page documents`)
}
return { keys: checked.keys, renamed, problems }
}
/** The check's problems as one message, or undefined when there are none. */
function problemsMessage (): string | undefined {
const { problems } = readConfigSchema()
if (problems.length === 0) return undefined
return 'The config reference pages (docs/config) and the default config files disagree. ' +
'See "Config reference pages" in docs/README.md.\n' + problems.map(problem => ' - ' + problem).join('\n')
}
/**
* Fails `vitepress build` when the config reference pages and the default
* config files disagree, so a mismatch never deploys. `vitepress dev` only
* warns, at start and again when a page or a default config file changes, so
* a half-edited page doesn't stop the server.
*/
export function configCheckPlugin (): Plugin {
const repoFiles = DEFAULTS_FILES.map(name => join(REPO_ROOT, name))
const isChecked = (file: string) =>
repoFiles.includes(resolve(file)) || (resolve(file).startsWith(DOCS_CONFIG_DIR) && file.endsWith('.md'))
let isBuild = false
return {
name: 'ipp-config-check',
configResolved (config) {
isBuild = config.command === 'build'
},
buildStart () {
const message = problemsMessage()
if (message && isBuild) this.error(message)
else if (message) this.warn(message)
},
configureServer (server) {
// Outside the docs folder, so Vite doesn't watch them unless told to
server.watcher.add(repoFiles)
},
handleHotUpdate ({ file, server }) {
if (!isChecked(file)) return
const message = problemsMessage()
if (message) server.config.logger.warn(message)
}
}
}
+96 -59
View File
@@ -1,21 +1,27 @@
import { readdirSync, readFileSync } from 'node:fs'
import { basename, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { isDeepStrictEqual } from 'node:util'
import type { Plugin } from 'vite'
/* /*
Reads the config reference pages (docs/config/*.md) into a schema and checks Parses the config reference pages (docs/config/*.md) into a schema and
them against the default config files, both ways. The page format this checks it against the default config files, both ways. The page format
parser accepts is the contract in docs/README.md, "Config reference pages"; this parser accepts is the contract in docs/README.md, "Config reference
change the two together. pages"; change the two together.
No Node APIs here: the config generator runs these checks in the browser
too. Reading the files from disk is in configCheck.ts.
*/ */
/** Whether a config.json value is a plain JSON object (not an array or null). */ /** Whether a config value is a plain JSON object (not an array or null). */
function isObject (value: unknown): value is Record<string, unknown> { export function isObject (value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value) return typeof value === 'object' && value !== null && !Array.isArray(value)
} }
/** Deep equality of two JSON values; the order of object keys doesn't matter. */
export function sameValue (a: unknown, b: unknown): boolean {
if (a === b) return true
if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((item, i) => sameValue(item, b[i]))
if (!isObject(a) || !isObject(b)) return false
const keys = Object.keys(a)
return keys.length === Object.keys(b).length && keys.every(key => Object.hasOwn(b, key) && sameValue(a[key], b[key]))
}
/** The types a `**Type:**` line can name, each with the check its default must pass. */ /** The types a `**Type:**` line can name, each with the check its default must pass. */
const TYPE_CHECKS = { const TYPE_CHECKS = {
bool: (value: unknown) => typeof value === 'boolean', bool: (value: unknown) => typeof value === 'boolean',
@@ -28,6 +34,47 @@ const TYPE_CHECKS = {
export type ConfigType = keyof typeof TYPE_CHECKS export type ConfigType = keyof typeof TYPE_CHECKS
/** Whether a value is of a documented type, e.g. `matchesType('int', 2)`. */
export function matchesType (type: ConfigType, value: unknown): boolean {
return TYPE_CHECKS[type](value)
}
/** Words a label writes in capitals. Add an acronym here when a new key name contains one. */
const ACRONYMS = new Set(['exif', 'gps', 'iso', 'url'])
/**
* Labels for the keys whose name, split into words, doesn't read well or
* leaves out a unit. The check fails on a path that no page documents, so a
* renamed key can't leave its label behind.
*/
export const LABELS: Record<string, string> = {
'ipp.gallery.singleImage': 'Gallery page for a single image',
'ipp.gallery.singleVideo': 'Gallery page for a single video',
'ipp.gallery.singleItemAutoOpen': 'Open single items in the lightbox',
'ipp.gallery.cacheTime': 'Cache time (seconds)',
'ipp.lightbox.autoPlayVideos': 'Autoplay videos',
'ipp.showMetadata.exif.dateTimeOriginal': 'Date taken',
'ipp.showMetadata.exif.fNumber': 'Aperture',
'ipp.showMetadata.location.webLink': 'Map link',
'ipp.upload.maxFileSize': 'Max file size (MB)',
'ipp.upload.rateLimit': 'Rate limit (files per minute)',
'ipp.upload.byteBudget': 'Byte budget (MB per hour)',
'ipp.upload.notifyTimeout': 'Notify timeout (ms)'
}
/**
* A key's label for the config generator: its entry in `LABELS`, or else the
* last part of its path as words, so `showArrows` is "Show arrows" and
* `notifyUrl` is "Notify URL".
*/
export function keyLabel (path: string): string {
if (Object.hasOwn(LABELS, path)) return LABELS[path]
const name = path.slice(path.lastIndexOf('.') + 1)
const words = name.replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase().split(' ')
const text = words.map(word => ACRONYMS.has(word) ? word.toUpperCase() : word).join(' ')
return text.charAt(0).toUpperCase() + text.slice(1)
}
/** One allowed value of a key, from its enum list. */ /** One allowed value of a key, from its enum list. */
export interface ConfigValue { export interface ConfigValue {
value: unknown value: unknown
@@ -50,6 +97,8 @@ export interface ConfigKey {
page: string page: string
/** The anchor of the key's section on that page. */ /** The anchor of the key's section on that page. */
anchor: string anchor: string
/** For a row of a flag table, the heading of the table's section. */
group?: string
} }
/** A default config file, named by its repo path for messages. */ /** A default config file, named by its repo path for messages. */
@@ -208,7 +257,7 @@ export function parsePage (markdown: string, page: string): { keys: ConfigKey[],
const parsed = parseLiteral(row[columns.default].replace(/`/g, '')) const parsed = parseLiteral(row[columns.default].replace(/`/g, ''))
if (!isConfigType(type)) problems.push(`${where}: \`${path}\` has an unknown type: ${row[columns.type]}`) if (!isConfigType(type)) problems.push(`${where}: \`${path}\` has an unknown type: ${row[columns.type]}`)
else if (!parsed.ok) problems.push(`${where}: the default of \`${path}\` is not JSON: ${row[columns.default]}`) else if (!parsed.ok) problems.push(`${where}: the default of \`${path}\` is not JSON: ${row[columns.default]}`)
else keys.push({ path, type, default: parsed.value, description: row[columns.description], page, anchor }) else keys.push({ path, type, default: parsed.value, description: row[columns.description], page, anchor, group: heading.text })
} }
} }
} }
@@ -231,9 +280,10 @@ function flatten (config: Record<string, unknown>, prefix = ''): Map<string, unk
/** /**
* Compare the documented keys with the default config files, both ways. * Compare the documented keys with the default config files, both ways.
* Returns the keys a config can set (group keys dropped, and a free-form * Returns the keys a config can set, in config.json order (group keys
* object without a default on its page given the one from its file) and one * dropped, and a free-form object without a default on its page given the one
* line per problem; no problems means the pages and files agree. * from its file), and one line per problem; no problems means the pages and
* files agree.
*/ */
export function checkKeys (keys: ConfigKey[], files: DefaultsFile[]): { keys: ConfigKey[], problems: string[] } { export function checkKeys (keys: ConfigKey[], files: DefaultsFile[]): { keys: ConfigKey[], problems: string[] } {
const problems: string[] = [] const problems: string[] = []
@@ -246,7 +296,7 @@ export function checkKeys (keys: ConfigKey[], files: DefaultsFile[]): { keys: Co
for (const [path, value] of flatten(file.config)) { for (const [path, value] of flatten(file.config)) {
const seen = nodes.get(path) const seen = nodes.get(path)
if (!seen) nodes.set(path, { value, file: file.name }) if (!seen) nodes.set(path, { value, file: file.name })
else if (!isObject(seen.value) && !isDeepStrictEqual(seen.value, value)) { else if (!isObject(seen.value) && !sameValue(seen.value, value)) {
problems.push(`\`${path}\` is ${json(seen.value)} in ${seen.file} but ${json(value)} in ${file.name}`) problems.push(`\`${path}\` is ${json(seen.value)} in ${seen.file} but ${json(value)} in ${file.name}`)
} }
} }
@@ -269,21 +319,21 @@ export function checkKeys (keys: ConfigKey[], files: DefaultsFile[]): { keys: Co
problems.push(`\`${key.path}\` is documented in ${where(key)} but is in neither ${files.map(file => file.name).join(' nor ')}`) problems.push(`\`${key.path}\` is documented in ${where(key)} but is in neither ${files.map(file => file.name).join(' nor ')}`)
continue continue
} }
if (!TYPE_CHECKS[key.type](node.value)) { if (!matchesType(key.type, node.value)) {
problems.push(`\`${key.path}\` is documented as \`${key.type}\` in ${where(key)} but is ${json(node.value)} in ${node.file}`) problems.push(`\`${key.path}\` is documented as \`${key.type}\` in ${where(key)} but is ${json(node.value)} in ${node.file}`)
continue continue
} }
if (isGroup(key)) continue if (isGroup(key)) continue
if (key.default === undefined) { if (key.default === undefined) {
if (!isFreeForm(key)) problems.push(`\`${key.path}\` has no default in ${where(key)}`) if (!isFreeForm(key)) problems.push(`\`${key.path}\` has no default in ${where(key)}`)
} else if (!isDeepStrictEqual(key.default, node.value)) { } else if (!sameValue(key.default, node.value)) {
problems.push(`\`${key.path}\` defaults to ${json(key.default)} in ${where(key)} but to ${json(node.value)} in ${node.file}`) problems.push(`\`${key.path}\` defaults to ${json(key.default)} in ${where(key)} but to ${json(node.value)} in ${node.file}`)
} }
if (key.values && !key.values.some(allowed => isDeepStrictEqual(allowed.value, node.value))) { if (key.values && !key.values.some(allowed => sameValue(allowed.value, node.value))) {
problems.push(`the allowed values of \`${key.path}\` in ${where(key)} do not include its default, ${json(node.value)}`) problems.push(`the allowed values of \`${key.path}\` in ${where(key)} do not include its default, ${json(node.value)}`)
} }
for (const allowed of key.values ?? []) { for (const allowed of key.values ?? []) {
if (!TYPE_CHECKS[key.type](allowed.value)) { if (!matchesType(key.type, allowed.value)) {
problems.push(`the allowed value ${json(allowed.value)} of \`${key.path}\` in ${where(key)} is not a \`${key.type}\``) problems.push(`the allowed value ${json(allowed.value)} of \`${key.path}\` in ${where(key)} is not a \`${key.type}\``)
} }
} }
@@ -304,51 +354,38 @@ export function checkKeys (keys: ConfigKey[], files: DefaultsFile[]): { keys: Co
const isLeaf = !isObject(node.value) || Object.keys(node.value).length === 0 const isLeaf = !isObject(node.value) || Object.keys(node.value).length === 0
if (isLeaf && !covered(path)) problems.push(`\`${path}\` in ${node.file} is not documented on any page in docs/config`) if (isLeaf && !covered(path)) problems.push(`\`${path}\` in ${node.file} is not documented on any page in docs/config`)
} }
const order = [...nodes.keys()]
fields.sort((a, b) => order.indexOf(a.path) - order.indexOf(b.path))
return { keys: fields, problems } return { keys: fields, problems }
} }
const DOCS_CONFIG_DIR = fileURLToPath(new URL('../config/', import.meta.url)) /** One row of the tables on Renamed config keys. */
const REPO_ROOT = fileURLToPath(new URL('../../', import.meta.url)) export interface RenamedKey {
/** The default config files, as repo paths. Both containers can share one config, so they are checked as one. */ /** The old dotted path. */
const DEFAULTS_FILES = ['app/config.json', 'upload-app/config.json'] from: string
/** The current dotted path. */
/** to: string
* Read every page in docs/config and both default config files, and check /** The Current key cell as markdown, which can say how the values changed. */
* them against each other. Returns `checkKeys`' keys and problems, with the note: string
* pages' own format problems first.
*/
export function readConfigSchema (): { keys: ConfigKey[], problems: string[] } {
const keys: ConfigKey[] = []
const problems: string[] = []
for (const file of readdirSync(DOCS_CONFIG_DIR).filter(name => name.endsWith('.md')).sort()) {
const page = parsePage(readFileSync(join(DOCS_CONFIG_DIR, file), 'utf8'), '/config/' + basename(file, '.md'))
keys.push(...page.keys)
problems.push(...page.problems)
}
const files = DEFAULTS_FILES.map(name => ({ name, config: JSON.parse(readFileSync(join(REPO_ROOT, name), 'utf8')) }))
const checked = checkKeys(keys, files)
return { keys: checked.keys, problems: [...problems, ...checked.problems] }
} }
/** /**
* Fails `vitepress build` when the config reference pages and the default * Read the renamed keys from config/upgrading.md: every table with `Old key`
* config files disagree, so a mismatch never deploys. `vitepress dev` only * and `Current key` columns, taking the first inline-code path in each cell.
* warns, so a half-edited page doesn't stop the server.
*/ */
export function configSchemaPlugin (): Plugin { export function parseRenamedKeys (markdown: string): RenamedKey[] {
let isBuild = false const renamed: RenamedKey[] = []
return { for (const block of toBlocks(markdown)) {
name: 'ipp-config-schema', if (block.kind !== 'table') continue
configResolved (config) { const [header, ...rows] = block.rows
isBuild = config.command === 'build' const from = header.indexOf('Old key')
}, const to = header.indexOf('Current key')
buildStart () { if (from === -1 || to === -1) continue
const { problems } = readConfigSchema() for (const row of rows) {
if (problems.length === 0) return const oldPath = /`([^`]+)`/.exec(row[from])?.[1]
const message = 'The config reference pages (docs/config) and the default config files disagree. ' + const newPath = /`([^`]+)`/.exec(row[to])?.[1]
'See "Config reference pages" in docs/README.md.\n' + problems.map(problem => ' - ' + problem).join('\n') if (oldPath && newPath) renamed.push({ from: oldPath, to: newPath, note: row[to] })
if (isBuild) this.error(message)
else this.warn(message)
} }
} }
return renamed
} }
@@ -0,0 +1,641 @@
<script lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { isObject, matchesType, sameValue } from '../../configSchema'
import { data, type GeneratorField } from './configGenerator.data'
/** How a field is edited. The text kinds keep a draft, so a half-typed value can be shown with its error. */
type Kind = 'switch' | 'select' | 'text' | 'number' | 'json' | 'jsonArea'
/** A problem with one key of a loaded config. `html` is trusted, from the docs; the rest is shown as text. */
interface Notice {
path: string
message: string
html?: string
}
const FIELDS = data.sections.flatMap(section => section.fields)
const BY_PATH = new Map(FIELDS.map(field => [field.path, field]))
const RENAMED = new Map(data.renamed.map(key => [key.from, key.html]))
/** A JSON copy, so the form never shares an object with the defaults or with a pasted config. */
function clone<T> (value: T): T {
return value === undefined ? value : JSON.parse(JSON.stringify(value))
}
function kindOf (field: GeneratorField): Kind {
if (field.values) return 'select'
if (field.type === 'bool') return 'switch'
if (field.type === 'string') return 'text'
if (field.type === 'int') return 'number'
if (field.type === 'object') return 'jsonArea'
return 'json'
}
const hasDraft = (field: GeneratorField) => ['number', 'json', 'jsonArea'].includes(kindOf(field))
function toDraft (field: GeneratorField, value: unknown): string {
if (kindOf(field) === 'number') return String(value)
return kindOf(field) === 'jsonArea' ? JSON.stringify(value, null, 2) : JSON.stringify(value)
}
/** Whether a key takes a value: one of its allowed values, or any value of its type. */
function accepts (field: GeneratorField, value: unknown): boolean {
return field.values ? field.values.some(allowed => sameValue(allowed.value, value)) : matchesType(field.type, value)
}
/*
The form's state is kept at module scope rather than in setup, so it
survives following a link to a reference page and coming back. A reload
starts again from the defaults, or from the link's config.
*/
const values = reactive<Record<string, unknown>>({})
const drafts = reactive<Record<string, string>>({})
const errors = reactive<Record<string, string>>({})
const pasteError = ref('')
const notices = ref<Notice[]>([])
function setValue (field: GeneratorField, value: unknown) {
values[field.path] = clone(value)
if (hasDraft(field)) drafts[field.path] = toDraft(field, value)
delete errors[field.path]
}
function resetAll () {
for (const field of FIELDS) setValue(field, field.default)
}
resetAll()
/** Reset the form and clear what the paste box reported. */
function startOver () {
resetAll()
notices.value = []
pasteError.value = ''
}
/** Read a text field. A value that doesn't parse leaves the last good one in place and shows why. */
function onDraft (field: GeneratorField, text: string) {
drafts[field.path] = text
let value: unknown
if (kindOf(field) === 'number') {
value = text.trim() === '' ? NaN : Number(text)
if (!Number.isInteger(value)) {
errors[field.path] = 'Enter a whole number.'
return
}
} else {
try {
value = JSON.parse(text)
} catch {
errors[field.path] = 'This is not valid JSON.'
return
}
if (!matchesType(field.type, value)) {
errors[field.path] = field.type === 'object' ? 'Enter a JSON object, such as {}.' : 'Enter true, false or a string in quotes.'
return
}
}
values[field.path] = value
delete errors[field.path]
}
/** Reset the form, then set every key of a config that the docs know, and report the rest. */
function loadConfig (config: Record<string, unknown>): Notice[] {
resetAll()
const found: Notice[] = []
const isGroup = (path: string) => FIELDS.some(field => field.path.startsWith(path + '.'))
const walk = (node: unknown, path: string) => {
const field = BY_PATH.get(path)
if (field) {
if (accepts(field, node)) setValue(field, node)
else found.push({ path, message: 'has a value this key does not take, so it was left at its default.' })
} else if (isObject(node) && (isGroup(path) || Object.keys(node).length > 0)) {
// Into unknown objects too, so a renamed key inside one is still found
for (const [name, child] of Object.entries(node)) walk(child, path + '.' + name)
} else if (isGroup(path)) {
found.push({ path, message: 'must be an object of keys, so it was left out.' })
} else if (RENAMED.has(path)) {
found.push({ path, message: 'was renamed, so it was left out. Current key:', html: RENAMED.get(path) })
} else {
found.push({ path, message: 'is not a key IPP reads, so it was left out.' })
}
}
for (const [name, child] of Object.entries(config)) walk(child, name)
return found
}
/** Read the paste box. Text around the JSON is ignored, so the whole `CONFIG: |` block can be pasted. */
function loadPasted (text: string) {
let config: unknown
try {
config = JSON.parse(text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1))
} catch {}
if (!isObject(config)) {
pasteError.value = 'This is not a JSON object. Paste the contents of config.json, or the JSON in your CONFIG variable.'
return
}
pasteError.value = ''
notices.value = loadConfig(config)
}
const isChanged = (field: GeneratorField) => !sameValue(values[field.path], field.default)
/** The changed keys, nested as in config.json and in config.json order. */
const output = computed(() => {
const config: Record<string, unknown> = {}
for (const field of FIELDS.filter(isChanged)) {
const parts = field.path.split('.')
let node = config
for (const part of parts.slice(0, -1)) node = (node[part] ??= {}) as Record<string, unknown>
node[parts[parts.length - 1]] = values[field.path]
}
return config
})
const changedCount = computed(() => FIELDS.filter(isChanged).length)
const configJson = computed(() => JSON.stringify(output.value, null, 2))
const configEnv = computed(() => 'CONFIG: |\n' + configJson.value.split('\n').map(line => ' ' + line).join('\n'))
const hasErrors = computed(() => Object.keys(errors).length > 0)
/** A section's fields, with each flag table's rows gathered into one block under the key they belong to. */
type Block = { field: GeneratorField } | { group: string, path: string, link: string, fields: GeneratorField[] }
const SECTIONS = data.sections.map(section => {
const blocks: Block[] = []
for (const field of section.fields) {
const last = blocks[blocks.length - 1]
if (field.group && last && 'group' in last && last.group === field.group) last.fields.push(field)
else if (field.group) blocks.push({ group: field.group, path: field.path.replace(/\.[^.]+$/, ''), link: field.link, fields: [field] })
else blocks.push({ field })
}
return { title: section.title, blocks }
})
const fieldId = (field: GeneratorField) => 'ipp-cg-' + field.path
</script>
<script setup lang="ts">
const pasted = ref('')
const tab = ref<'json' | 'env'>('json')
const loadOpen = ref(false)
const copied = ref<'' | 'config' | 'link'>('')
const copyFailed = ref(false)
async function copy (text: string, what: 'config' | 'link') {
try {
await navigator.clipboard.writeText(text)
copyFailed.value = false
copied.value = what
setTimeout(() => { if (copied.value === what) copied.value = '' }, 2000)
} catch {
copyFailed.value = true
}
}
/** This page's address with the changed keys in the hash, which the browser never sends to the server. */
const shareLink = computed(() =>
location.origin + location.pathname + '#config=' + encodeURIComponent(JSON.stringify(output.value)))
function selectValue (field: GeneratorField, event: Event) {
const index = Number((event.target as HTMLSelectElement).value)
setValue(field, field.values?.[index].value)
}
const selectedIndex = (field: GeneratorField) =>
field.values?.findIndex(allowed => sameValue(allowed.value, values[field.path])) ?? -1
const onLoadToggle = (event: Event) => { loadOpen.value = (event.target as HTMLDetailsElement).open }
const showOutput = () => document.getElementById('ipp-cg-output')?.scrollIntoView({ behavior: 'smooth' })
onMounted(() => {
if (!location.hash.startsWith('#config=')) return
let config: unknown
try {
config = JSON.parse(decodeURIComponent(location.hash.slice('#config='.length)))
} catch {}
if (isObject(config)) notices.value = loadConfig(config)
else pasteError.value = 'The config in this link could not be read.'
loadOpen.value = notices.value.length > 0 || pasteError.value !== ''
// Clear the hash, so a reload after more changes doesn't bring the link's config back
history.replaceState(history.state, '', location.pathname + location.search)
})
</script>
<template>
<div class="ipp-cg">
<div class="layout">
<div class="form">
<details class="load" :open="loadOpen" @toggle="onLoadToggle">
<summary>Start from your current config</summary>
<p>Paste your <code>config.json</code>, or your <code>CONFIG</code> variable. It replaces what is set below.</p>
<textarea v-model="pasted" class="input code" rows="6" placeholder='{ "ipp": { "showHomePage": false } }' spellcheck="false" />
<button type="button" class="button" @click="loadPasted(pasted)">Load</button>
<p v-if="pasteError" class="error">{{ pasteError }}</p>
<template v-if="notices.length">
<p>
Some keys were not loaded. Keys from older versions are listed in
<a href="/config/upgrading">Renamed config keys</a>.
</p>
<ul class="notices">
<li v-for="notice in notices" :key="notice.path">
<code>{{ notice.path }}</code> {{ notice.message }} <span v-if="notice.html" v-html="notice.html" />
</li>
</ul>
</template>
</details>
<section v-for="section in SECTIONS" :key="section.title">
<h2>{{ section.title }}</h2>
<template v-for="block in section.blocks" :key="'field' in block ? block.field.path : block.path">
<div v-if="'field' in block" class="field" :class="{ changed: isChanged(block.field) }">
<div class="head">
<label :for="fieldId(block.field)" :title="block.field.path">{{ block.field.label }}</label>
<input
v-if="kindOf(block.field) === 'switch'"
:id="fieldId(block.field)"
type="checkbox"
role="switch"
class="switch"
:checked="values[block.field.path] === true"
@change="setValue(block.field, ($event.target as HTMLInputElement).checked)"
>
<button v-if="isChanged(block.field)" type="button" class="reset" @click="setValue(block.field, block.field.default)">
Reset
</button>
</div>
<p class="description">
<span v-html="block.field.html" /> <a :href="block.field.link">Details</a>
</p>
<select
v-if="kindOf(block.field) === 'select'"
:id="fieldId(block.field)"
class="input"
:value="selectedIndex(block.field)"
@change="selectValue(block.field, $event)"
>
<option v-for="(allowed, index) in block.field.values" :key="index" :value="index">{{ allowed.label }}</option>
</select>
<input
v-else-if="kindOf(block.field) === 'text'"
:id="fieldId(block.field)"
class="input"
type="text"
spellcheck="false"
:value="values[block.field.path]"
@input="setValue(block.field, ($event.target as HTMLInputElement).value)"
>
<input
v-else-if="kindOf(block.field) === 'number' || kindOf(block.field) === 'json'"
:id="fieldId(block.field)"
class="input"
:class="{ code: kindOf(block.field) === 'json', invalid: errors[block.field.path] }"
:type="kindOf(block.field) === 'number' ? 'number' : 'text'"
:step="kindOf(block.field) === 'number' ? 1 : undefined"
spellcheck="false"
:value="drafts[block.field.path]"
@input="onDraft(block.field, ($event.target as HTMLInputElement).value)"
>
<textarea
v-else-if="kindOf(block.field) === 'jsonArea'"
:id="fieldId(block.field)"
class="input code"
:class="{ invalid: errors[block.field.path] }"
rows="4"
spellcheck="false"
:value="drafts[block.field.path]"
@input="onDraft(block.field, ($event.target as HTMLTextAreaElement).value)"
/>
<p v-if="errors[block.field.path]" class="error">{{ errors[block.field.path] }}</p>
</div>
<fieldset v-else class="field flags" :class="{ changed: block.fields.some(isChanged) }">
<legend :title="block.path">{{ block.group }} <a class="details" :href="block.link">Details</a></legend>
<label v-for="field in block.fields" :key="field.path" class="flag">
<input
type="checkbox"
:checked="values[field.path] === true"
@change="setValue(field, ($event.target as HTMLInputElement).checked)"
>
<span :title="field.path"><span class="flag-label">{{ field.label }}</span> <span class="flag-description" v-html="field.html" /></span>
</label>
</fieldset>
</template>
</section>
</div>
<aside id="ipp-cg-output" class="output">
<div class="tabs" role="tablist">
<button type="button" role="tab" :aria-selected="tab === 'json'" @click="tab = 'json'">config.json</button>
<button type="button" role="tab" :aria-selected="tab === 'env'" @click="tab = 'env'">CONFIG variable</button>
</div>
<p v-if="changedCount === 0" class="empty">
Nothing differs from the defaults, so no config file is needed.
</p>
<template v-else>
<pre class="code-block"><code>{{ tab === 'json' ? configJson : configEnv }}</code></pre>
<p v-if="tab === 'json'" class="hint">
Save it as <code>config.json</code> and <a href="/config/#mount-a-file">mount it</a>. If you run the upload
service, mount the same file into that container too.
</p>
<p v-else class="hint">
Add it under <code>environment:</code> in <code>docker-compose.yml</code>, indented like the other
variables. If you run the upload service, give that container the same <code>CONFIG</code> too. See
<a href="/config/#inline-via-env-var">Inline via env var</a>.
</p>
<p v-if="hasErrors" class="error">
A field has a value that can't be read. Until it is fixed, the output keeps that key's last good value.
</p>
<div class="actions">
<button type="button" class="button" @click="copy(tab === 'json' ? configJson : configEnv, 'config')">
{{ copied === 'config' ? 'Copied' : 'Copy' }}
</button>
<button type="button" class="button secondary" @click="copy(shareLink, 'link')">
{{ copied === 'link' ? 'Link copied' : 'Copy link to this config' }}
</button>
<button type="button" class="button secondary" @click="startOver">Reset all</button>
</div>
<p v-if="copyFailed" class="error">Copying didn't work in this browser. Select the text and copy it instead.</p>
<p class="hint">Anyone you send the link to sees every value in it, including any token.</p>
</template>
</aside>
</div>
<button v-if="changedCount > 0" type="button" class="jump" @click="showOutput">
{{ changedCount }} {{ changedCount === 1 ? 'key' : 'keys' }} changed · Show config
</button>
</div>
</template>
<style scoped>
.layout {
display: grid;
gap: 32px;
}
.load,
.output {
border: 1px solid var(--vp-c-divider);
border-radius: 8px;
padding: 12px 16px;
background: var(--vp-c-bg-soft);
}
.load summary {
cursor: pointer;
font-weight: 600;
}
.field {
margin: 16px 0;
padding: 4px 0 4px 12px;
border: 0;
border-left: 3px solid transparent;
}
.field.changed {
border-left-color: var(--vp-c-brand-1);
}
.head {
display: flex;
align-items: center;
gap: 12px;
}
.head label {
font-weight: 600;
}
.vp-doc .description {
margin: 4px 0 8px;
font-size: 14px;
line-height: 1.6;
color: var(--vp-c-text-2);
}
.flags {
min-width: 0;
}
.flags legend {
padding: 0;
font-weight: 600;
}
.flags .details {
margin-left: 8px;
font-size: 14px;
font-weight: 400;
}
.flag {
display: flex;
gap: 10px;
align-items: baseline;
margin: 6px 0;
font-size: 14px;
line-height: 1.6;
cursor: pointer;
}
.flag-label {
font-weight: 500;
}
.flag-description {
color: var(--vp-c-text-2);
}
.input {
display: block;
width: 100%;
padding: 6px 10px;
border: 1px solid var(--vp-c-divider);
border-radius: 6px;
background: var(--vp-c-bg);
font-size: 14px;
}
.input:focus {
border-color: var(--vp-c-brand-1);
}
.input.invalid {
border-color: var(--vp-c-danger-1);
}
/* The theme turns off the native arrow (`appearance: none`), so draw one; the grey reads on both themes */
select.input {
padding-right: 32px;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%238e8e93' stroke-width='2'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");
background-position: right 10px center;
background-repeat: no-repeat;
background-size: 16px;
cursor: pointer;
}
.code {
font-family: var(--vp-font-family-mono);
font-size: 13px;
}
textarea.input {
resize: vertical;
}
.switch {
appearance: none;
position: relative;
flex-shrink: 0;
width: 40px;
height: 22px;
border: 1px solid var(--vp-input-border-color);
border-radius: 11px;
background: var(--vp-input-switch-bg-color);
cursor: pointer;
transition: background-color 0.25s, border-color 0.25s;
}
.switch::before {
content: '';
position: absolute;
top: 1px;
left: 1px;
width: 18px;
height: 18px;
border-radius: 50%;
background: var(--vp-c-neutral-inverse);
box-shadow: var(--vp-shadow-1);
transition: transform 0.25s;
}
.switch:checked {
border-color: var(--vp-c-brand-1);
background: var(--vp-c-brand-1);
}
.switch:checked::before {
transform: translateX(18px);
background: var(--vp-c-white);
}
.switch:focus-visible,
.button:focus-visible,
.reset:focus-visible,
.tabs button:focus-visible {
outline: 2px solid var(--vp-c-brand-1);
outline-offset: 2px;
}
/* The theme's own button colours, so contrast holds in dark mode */
.button {
margin-top: 8px;
padding: 4px 14px;
border-radius: 6px;
background: var(--vp-button-brand-bg);
color: var(--vp-button-brand-text);
font-size: 14px;
font-weight: 500;
}
.button:hover {
background: var(--vp-button-brand-hover-bg);
}
.button.secondary {
background: var(--vp-button-alt-bg);
color: var(--vp-button-alt-text);
}
.button.secondary:hover {
background: var(--vp-button-alt-hover-bg);
}
.reset {
margin-left: auto;
color: var(--vp-c-brand-1);
font-size: 13px;
}
.error {
color: var(--vp-c-danger-1);
font-size: 14px;
}
.vp-doc .notices {
font-size: 14px;
}
.tabs {
display: flex;
gap: 4px;
border-bottom: 1px solid var(--vp-c-divider);
}
.tabs button {
padding: 6px 10px;
border-bottom: 2px solid transparent;
color: var(--vp-c-text-2);
font-size: 14px;
font-weight: 500;
}
.tabs button[aria-selected='true'] {
border-bottom-color: var(--vp-c-brand-1);
color: var(--vp-c-text-1);
}
.code-block {
margin: 12px 0 8px;
padding: 12px;
overflow-x: auto;
border-radius: 6px;
background: var(--vp-code-block-bg);
font-family: var(--vp-font-family-mono);
font-size: 13px;
line-height: 1.5;
}
.vp-doc .hint,
.vp-doc .empty {
margin: 8px 0;
font-size: 14px;
color: var(--vp-c-text-2);
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.jump {
position: sticky;
bottom: 16px;
display: block;
margin: 16px 0 0 auto;
padding: 8px 16px;
border-radius: 20px;
background: var(--vp-button-brand-bg);
color: var(--vp-button-brand-text);
font-size: 14px;
font-weight: 500;
box-shadow: var(--vp-shadow-3);
}
/* Side by side once there is room for both, with the output kept in view */
@media (min-width: 1280px) {
.layout {
grid-template-columns: minmax(0, 1fr) 400px;
}
.output {
position: sticky;
top: calc(var(--vp-nav-height) + 24px);
align-self: start;
max-height: calc(100vh - var(--vp-nav-height) - 48px);
overflow-y: auto;
}
.jump {
display: none;
}
}
</style>
@@ -0,0 +1,100 @@
import { createMarkdownRenderer, defineLoader, type DefaultTheme, type SiteConfig } from 'vitepress'
import { readConfigSchema } from '../../configCheck'
import { keyLabel, type ConfigType } from '../../configSchema'
/*
Build-time data for the config generator (a VitePress data loader): the
keys from the reference pages, with their descriptions rendered to HTML,
grouped into one section per page in sidebar order. Dev mode reloads it when
a watched file changes. Pages and defaults that disagree fail the build in
configCheck.ts, not here.
*/
/** A config key as the generator shows it. */
export interface GeneratorField {
path: string
/** The key's name as words, e.g. "Show arrows" for `ipp.lightbox.showArrows`. */
label: string
type: ConfigType
default: unknown
/** The allowed values, each with a plain-text label for a select. */
values?: Array<{ value: unknown, label: string }>
/** The key's description, as HTML. */
html: string
/** The key's section on its reference page. */
link: string
/** For a row of a flag table, the label of the key the table is under, e.g. "EXIF". */
group?: string
}
/** One reference page's keys. */
export interface GeneratorSection {
/** The page's sidebar label. */
title: string
fields: GeneratorField[]
}
/** A renamed key, for the paste box to suggest the current name. */
export interface GeneratorRenamedKey {
from: string
/** The Current key cell from Renamed config keys, as HTML. */
html: string
}
export interface GeneratorData {
sections: GeneratorSection[]
renamed: GeneratorRenamedKey[]
}
declare const data: GeneratorData
export { data }
/** Every sidebar link with its label, depth first, in sidebar order. */
function sidebarLinks (items: DefaultTheme.SidebarItem[]): Array<{ link: string, text: string }> {
return items.flatMap(item => [
...(item.link && item.text ? [{ link: item.link, text: item.text }] : []),
...sidebarLinks(item.items ?? [])
])
}
/** Markdown as plain text, for a `<select>` option: links keep their text, formatting goes. */
function toPlainText (markdown: string): string {
return markdown.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/[`*]/g, '')
}
/** A value as the select shows it: strings without quotes, the rest as JSON. */
function display (value: unknown): string {
return typeof value === 'string' ? value : JSON.stringify(value)
}
export default defineLoader({
watch: ['../../../config/*.md', '../../../../app/config.json', '../../../../upload-app/config.json'],
async load (): Promise<GeneratorData> {
const config: SiteConfig = (globalThis as unknown as { VITEPRESS_CONFIG: SiteConfig }).VITEPRESS_CONFIG
const md = await createMarkdownRenderer(config.srcDir, config.markdown, config.site.base, config.logger)
// A `#anchor` link in a description points at its own page, not at the generator
const render = (markdown: string, page: string) => md.renderInline(markdown.replace(/\]\(#/g, `](${page}#`))
const { keys, renamed } = readConfigSchema()
const sidebar = config.site.themeConfig.sidebar
const pages = sidebarLinks(Array.isArray(sidebar) ? sidebar : [])
const sections = pages.flatMap(({ link, text }) => {
const fields = keys.filter(key => key.page === link).map((key): GeneratorField => ({
path: key.path,
label: keyLabel(key.path),
type: key.type,
default: key.default,
values: key.values?.map(({ value, description }) => ({ value, label: `${display(value)} - ${toPlainText(description)}` })),
html: render(key.description, key.page),
link: `${key.page}#${key.anchor}`,
group: key.group && keyLabel(key.path.slice(0, key.path.lastIndexOf('.')))
}))
return fields.length ? [{ title: text, fields }] : []
})
return {
sections,
renamed: renamed.map(({ from, note }) => ({ from, html: render(note, '/config/upgrading') }))
}
}
})
+7 -2
View File
@@ -1,7 +1,8 @@
import DefaultTheme from 'vitepress/theme' import DefaultTheme from 'vitepress/theme'
import { useData } from 'vitepress' import { useData } from 'vitepress'
import { h } from 'vue' import { h, type App } from 'vue'
import type { ThemeConfig } from '../config' import type { ThemeConfig } from '../config'
import ConfigGenerator from './components/ConfigGenerator.vue'
import './custom.css' import './custom.css'
const DEMO_URL = 'https://demo.ipp.nz/s/demo-gallery' const DEMO_URL = 'https://demo.ipp.nz/s/demo-gallery'
@@ -46,10 +47,14 @@ const StarCount = {
* - use the live-demo screenshot as the hero image (`home-hero-image`), * - use the live-demo screenshot as the hero image (`home-hero-image`),
* absolutely centred within the hero image container so it lines up * absolutely centred within the hero image container so it lines up
* vertically with the hero text; * vertically with the hero text;
* - place the IPP shield logo below the feature grid (`home-features-after`). * - place the IPP shield logo below the feature grid (`home-features-after`);
* - register `<ConfigGenerator />` for the Config generator page.
*/ */
export default { export default {
extends: DefaultTheme, extends: DefaultTheme,
enhanceApp ({ app }: { app: App }) {
app.component('ConfigGenerator', ConfigGenerator)
},
Layout () { Layout () {
return h(DefaultTheme.Layout, null, { return h(DefaultTheme.Layout, null, {
'nav-bar-content-after': () => h(StarCount), 'nav-bar-content-after': () => h(StarCount),
+24 -9
View File
@@ -45,7 +45,7 @@ rather than the Diátaxis term.
| Group | Kind | Reader's question | Rules | | Group | Kind | Reader's question | Rules |
|-----------------|-----------|--------------------------------------------|-------| |-----------------|-----------|--------------------------------------------|-------|
| Getting started | Tutorial | What is this, and how do I get it running? | Ordered as a path: Introduction, Installation, Sharing from Immich, Upgrading. Numbered steps, one happy path, defaults only. Link to reference pages rather than explaining options inline. | | Getting started | Tutorial | What is this, and how do I get it running? | Ordered as a path: Introduction, Installation, Sharing from Immich, Upgrading. Numbered steps, one happy path, defaults only. Link to reference pages rather than explaining options inline. |
| Configuration | Reference | What does this key do? | One page per `ipp.*` group, mirroring `app/config.json`. Every key has a `**Type:** … · **Default:** …` line and a short description; each page opens with a worked example. Complete and neutral: no advice, no tutorials. | | Configuration | Reference | What does this key do? | One page per `ipp.*` group, mirroring `app/config.json`. Every key has a `**Type:** … · **Default:** …` line and a short description; each page opens with a worked example. Complete and neutral: no advice, no tutorials. The Config generator, after the overview, is a tool built from these pages, not a page to add content to. |
| Guides | How-to | How do I achieve this goal? | One goal per page and the title names the goal. Assume IPP is installed. Label every config block with the proxy or platform it is for; Caddy first, then others. | | Guides | How-to | How do I achieve this goal? | One goal per page and the title names the goal. Assume IPP is installed. Label every config block with the proxy or platform it is for; Caddy first, then others. |
| Troubleshooting | How-to | Why is this happening? | One page, one `##` per problem. The heading is the symptom as the user sees it (a log line, or what they observe), then the cause, then the fix, then links to the GitHub issues. | | Troubleshooting | How-to | Why is this happening? | One page, one `##` per problem. The heading is the symptom as the user sees it (a log line, or what they observe), then the cause, then the fix, then links to the GitHub issues. |
@@ -72,7 +72,8 @@ started because it is what people read first, not because it is a tutorial. If e
sidebar label and H1 instead. That is why "General options" is served from `/config/ipp-options` and "Sharing from sidebar label and H1 instead. That is why "General options" is served from `/config/ipp-options` and "Sharing from
Immich" from `/how-to-use`. Immich" from `/how-to-use`.
- Internal links are absolute site paths with optional anchors (`/config/gallery#showtitle`), never relative file - Internal links are absolute site paths with optional anchors (`/config/gallery#showtitle`), never relative file
links. Anchors are the heading text lowercased with backticks stripped and spaces as hyphens; keep headings that links. Anchors are the heading text lowercased with backticks stripped and spaces and underscores as hyphens
(`IPP_CONFIG` is `#ipp-config`); keep headings that
are link targets free of other punctuation. are link targets free of other punctuation.
- Config keys are written as `` `gallery.showTitle` `` and linked to their section the first time they appear on a page. - Config keys are written as `` `gallery.showTitle` `` and linked to their section the first time they appear on a page.
- Callouts use GitHub syntax (`> [!NOTE]`, `> [!TIP]`, `> [!WARNING]`) and are kept for things that bite. - Callouts use GitHub syntax (`> [!NOTE]`, `> [!TIP]`, `> [!WARNING]`) and are kept for things that bite.
@@ -85,15 +86,21 @@ started because it is what people read first, not because it is a tutorial. If e
## Config reference pages ## Config reference pages
The pages in `config/` are the only description of the config keys, so the build checks them against The pages in `config/` are the only description of the config keys. The Config generator (`config/generator.md`) is
`app/config.json` and `upload-app/config.json`, both ways (`.vitepress/configSchema.ts`). A disagreement fails built from them, and the build checks them against `app/config.json` and `upload-app/config.json`, both ways. A
`npm run build`, and `npm run dev` prints it as a warning. `npm test` at the repo root runs the same check without disagreement fails `npm run build`, and `npm run dev` prints it as a warning. `npm test` at the repo root runs the same
building the site (`tests/configSchema.test.ts`). The check fails when: check without building the site (`tests/configSchema.test.ts`). The check fails when:
- a key in either file is not documented, or is documented twice; - a key in either file is not documented, or is documented twice;
- a documented key is in neither file; - a documented key is in neither file;
- a documented type or default differs from the file, or the allowed values leave out the default; - a documented type or default differs from the file, or the allowed values leave out the default;
- a key in both files has a different default in each. - a key in both files has a different default in each;
- a row of Renamed config keys (`config/upgrading.md`) names a current key that no page documents;
- a label in `LABELS` (see below) is for a key that no page documents.
The parsing and the checks are in `.vitepress/configSchema.ts`, which also runs in the browser for the generator;
reading the files and failing the build are in `.vitepress/configCheck.ts`. The generator itself is
`.vitepress/theme/components/ConfigGenerator.vue`, fed by the data loader next to it.
For the same reason the docs workflow also runs on a change to either `config.json`: a key or default changed on For the same reason the docs workflow also runs on a change to either `config.json`: a key or default changed on
`main` redeploys the site, and the deploy fails if the page was not updated in the same push. `main` redeploys the site, and the deploy fails if the page was not updated in the same push.
@@ -109,12 +116,20 @@ The check reads only this format:
`object`, `` `bool` or `string` ``, or `various` (any JSON value), and the default is JSON. Leave the default out `object`, `` `bool` or `string` ``, or `various` (any JSON value), and the default is JSON. Leave the default out
only on an object key: a group whose keys are documented on their own page (`gallery` on General options), or a only on an object key: a group whose keys are documented on their own page (`gallery` on General options), or a
free-form object such as `responseHeaders`, whose default is taken from `config.json`. free-form object such as `responseHeaders`, whose default is taken from `config.json`.
- **Description.** The paragraph after the Type line. It is the key's summary, so it should make sense on its own. - **Description.** The paragraph after the Type line. The generator shows it beside the field, so it should make
sense on its own. A `#anchor` link in it is pointed at the key's own page.
- **Allowed values.** A bullet list directly after the description whose every item starts with an inline-code JSON - **Allowed values.** A bullet list directly after the description whose every item starts with an inline-code JSON
value: `` - `"original"` - the full-resolution original file ``. Any other list is prose. value: `` - `"original"` - the full-resolution original file ``. Any other list is prose. These become the
generator's choices, so list every value IPP takes, aliases included (`true` for `groupByDate`).
- **Flag tables.** A section whose first paragraph starts ``Under `ipp.showMetadata.exif`.`` and that has a table - **Flag tables.** A section whose first paragraph starts ``Under `ipp.showMetadata.exif`.`` and that has a table
with `Option`, `Type`, `Default` and `Description` columns documents one key per row, as on the Metadata page. with `Option`, `Type`, `Default` and `Description` columns documents one key per row, as on the Metadata page.
The generator has one section per reference page, in sidebar order and under the sidebar label, so a new reference
page needs its sidebar entry before its keys appear there. Its field labels are the key names as words (`showArrows`
is "Show arrows"). Where that reads badly or a number field needs its unit, `LABELS` in `.vitepress/configSchema.ts`
gives the label instead; a key name with an acronym in it goes in `ACRONYMS` there, so the label writes it in capitals. Renamed config keys feeds its paste box: a pasted old key
is shown with the Current key cell of its row, so keep that cell readable on its own.
## The README ## The README
`README.md` at the repo root is the front door, not a second copy of the site: pitch, demo, screenshot, quick start `README.md` at the repo root is the front door, not a second copy of the site: pitch, demo, screenshot, quick start
+22 -21
View File
@@ -21,24 +21,6 @@ Show the gallery title and group photos by month:
} }
``` ```
## `singleImage`
**Type:** `bool` · **Default:** `false`
By default a link to a single image will directly open the image file. Set to `true` if you want to show a gallery page instead for a single item.
## `singleVideo`
**Type:** `bool` · **Default:** `true`
When a share contains a single video, show a gallery page. Set to `false` to link directly to the video file instead.
## `singleItemAutoOpen`
**Type:** `bool` · **Default:** `true`
When a share contains a single item and is opened on its gallery page, automatically open the lightbox on the asset.
## `showTitle` ## `showTitle`
**Type:** `bool` · **Default:** `true` **Type:** `bool` · **Default:** `true`
@@ -69,6 +51,12 @@ Format for the [`showExpiryDate`](#showexpirydate) date, as a [dayjs format stri
Language for the [`showExpiryDate`](#showexpirydate) date when the format uses names (e.g. `MMMM` for month names), as a [dayjs locale code](https://github.com/iamkun/dayjs/tree/dev/src/locale) such as `"de"`, `"fr"` or `"en-gb"`. The default is English. The default numeric format needs no locale. The date-group headers from [`groupByDate`](#groupbydate) follow each visitor's own browser language instead. Language for the [`showExpiryDate`](#showexpirydate) date when the format uses names (e.g. `MMMM` for month names), as a [dayjs locale code](https://github.com/iamkun/dayjs/tree/dev/src/locale) such as `"de"`, `"fr"` or `"en-gb"`. The default is English. The default numeric format needs no locale. The date-group headers from [`groupByDate`](#groupbydate) follow each visitor's own browser language instead.
## `showDownloadZip`
**Type:** `bool` · **Default:** `true`
Show the "download all" button in the header and the multi-select download toolbar. Only takes effect when downloads are allowed by [`allowDownload`](/config/ipp-options#allowdownload). Set to `false` to hide zip downloads while still offering single downloads in the lightbox ([`lightbox.showDownload`](/config/lightbox#showdownload)).
## `groupByDate` ## `groupByDate`
**Type:** `bool` or `string` · **Default:** `false` **Type:** `bool` or `string` · **Default:** `false`
@@ -76,16 +64,29 @@ Language for the [`showExpiryDate`](#showexpirydate) date when the format uses n
Group the gallery's thumbnails by date, with a header above each group. Group the gallery's thumbnails by date, with a header above each group.
- `false` - no grouping (default). - `false` - no grouping (default).
- `"month"` - month headers like "December 2024". `true` means the same. - `"month"` - month headers like "December 2024".
- `"day"` - day headers like "Wed, 25 Dec 2024" (matching Immich's own timeline format). - `"day"` - day headers like "Wed, 25 Dec 2024" (matching Immich's own timeline format).
- `true` - the same as `"month"`.
Grouping uses the date each photo was taken, as in Immich's own timeline. Groups follow the album's sort order in Immich, and newest first for shares without one. Photos with no date go under an "Undated" header at the end. Grouping uses the date each photo was taken, as in Immich's own timeline. Groups follow the album's sort order in Immich, and newest first for shares without one. Photos with no date go under an "Undated" header at the end.
## `showDownloadZip` ## `singleImage`
**Type:** `bool` · **Default:** `false`
By default a link to a single image will directly open the image file. Set to `true` if you want to show a gallery page instead for a single item.
## `singleVideo`
**Type:** `bool` · **Default:** `true` **Type:** `bool` · **Default:** `true`
Show the "download all" button in the header and the multi-select download toolbar. Only takes effect when downloads are allowed by [`allowDownload`](/config/ipp-options#allowdownload). Set to `false` to hide zip downloads while still offering single downloads in the lightbox ([`lightbox.showDownload`](/config/lightbox#showdownload)). When a share contains a single video, show a gallery page. Set to `false` to link directly to the video file instead.
## `singleItemAutoOpen`
**Type:** `bool` · **Default:** `true`
When a share contains a single item and is opened on its gallery page, automatically open the lightbox on the asset.
## `cacheTime` ## `cacheTime`
+12
View File
@@ -0,0 +1,12 @@
---
aside: false
---
# Config generator
Set the options you want, then copy the result into a `config.json` file or your `CONFIG` variable. Only the
options you change are included. [Configuration](/config/) explains where the config goes.
<ClientOnly>
<ConfigGenerator />
</ClientOnly>
+52 -18
View File
@@ -1,40 +1,51 @@
# Configuration # Configuration
> [!TIP] IPP can run with no config at all. Every option has a default, and the defaults are the most private choice: downloads
> You can see all of the configurable options by [looking at the default config.json](https://github.com/alangrainger/immich-public-proxy/blob/main/app/config.json), and the upload service's in [its own config.json](https://github.com/alangrainger/immich-public-proxy/blob/main/upload-app/config.json). A description of each option is on the pages in this section. are off and every metadata field is hidden until you turn it on. A config holds only the keys you change; anything
you leave out keeps its default.
Connection settings (the Immich URL, public URL, port and config file location) are ## Start with the Config generator
[environment variables](/config/environment-variables). Everything else is JSON config under `ipp.*`, grouped into:
- [General options](/config/ipp-options) - downloads, zoom quality, slug links, the upload link, response headers. The [Config generator](/config/generator) is the place to build your config and the place to see what each option
- [Gallery](/config/gallery) - how the gallery page is rendered. does. It lists every option with a short description, grouped the same way as the pages in this section. Set the ones
- [Lightbox](/config/lightbox) - the PhotoSwipe image viewer. you want to change, and it writes the config for you in either of the two forms below, holding only the keys that
- [Metadata](/config/metadata) - description / EXIF / location reveal controls. differ from the defaults.
- [Error responses](/config/error-responses) - customise what invalid requests return.
- [Upload service](/config/upload-service) - the optional container that lets visitors send photos back. It also works the other way: paste the config you already have, and the form fills in from it. Keys that IPP no
- [Renamed config keys](/config/upgrading) - old keys and their current names. longer reads are listed with their current names, so it is the quickest way to update a config after a major
version upgrade.
## How to provide a config override ## How to provide a config override
> [!NOTE] There are two ways to supply the config. If both are present, `CONFIG` is used and the file is not read.
> You only need to include the keys you're changing. Anything you omit keeps its default, and the defaults are always the most private option. Nothing in the [metadata](/config/metadata) groups is shown until you set its flag to `true`.
There are two ways to supply custom config. If both are present, `CONFIG` wins and the file is not read.
### Mount a file ### Mount a file
Recommended for anything non-trivial. Make a copy of [config.json](https://github.com/alangrainger/immich-public-proxy/blob/main/app/config.json) next to your `docker-compose.yml`, edit it, then add a volume: Recommended for anything non-trivial. Put a `config.json` next to your `docker-compose.yml` holding only the keys
you change, then mount it into the container:
```yaml ```yaml
volumes: volumes:
- ./config.json:/app/config.json - ./config.json:/app/config.json
``` ```
Restart the container and your custom configuration becomes active. ```json
{
"ipp": {
"allowDownload": 1,
"gallery": {
"showTitle": false
}
}
}
```
Restart the container and the config is active. To keep the file somewhere other than `/app/config.json`, set
[`IPP_CONFIG`](/config/environment-variables#ipp-config) to its path instead of mounting over the default.
### Inline via env var ### Inline via env var
For one-off or single-key overrides, pass the configuration inline from your `docker-compose.yml` using the `CONFIG` environment variable: For one or two keys, pass the JSON in the `CONFIG` environment variable instead of a file:
```yaml ```yaml
environment: environment:
@@ -47,3 +58,26 @@ For one-off or single-key overrides, pass the configuration inline from your `do
} }
} }
``` ```
The upload service reads config the same way, so one `config.json` or `CONFIG` value can be shared by both
containers.
## Full descriptions
The generator shows each option's summary. The pages below hold the full description of every key, with the
details and worked examples that don't fit beside a form field. Each page covers one group of keys and links to it
from the generator's "Details" links.
- [Environment variables](/config/environment-variables) - the Immich URL, public URL, port and config file location.
- [General options](/config/ipp-options) - `ipp.*`: downloads, zoom quality, slug links, the upload link, response headers.
- [Gallery](/config/gallery) - `ipp.gallery.*`: how the gallery page is rendered.
- [Lightbox](/config/lightbox) - `ipp.lightbox.*`: the image viewer.
- [Metadata](/config/metadata) - `ipp.showMetadata.*`: which description, EXIF and location fields visitors can see.
- [Error responses](/config/error-responses) - what an invalid request gets instead of a 404.
- [Upload service](/config/upload-service) - `ipp.upload.*`: the optional container that lets visitors send photos back.
- [Renamed config keys](/config/upgrading) - old key names and their current ones, for a config from an earlier
major version.
The defaults themselves are in
[`app/config.json`](https://github.com/alangrainger/immich-public-proxy/blob/main/app/config.json) and, for the upload
service, [`upload-app/config.json`](https://github.com/alangrainger/immich-public-proxy/blob/main/upload-app/config.json).
+81 -82
View File
@@ -19,24 +19,26 @@ Serve full-resolution images both when zooming in the lightbox and when download
} }
``` ```
## `responseHeaders` ## `allowDownload`
**Type:** `object` **Type:** `int` · **Default:** `0`
Change the headers sent with photos, videos and static files. The default is a 30-day `Cache-Control` and a Show the download buttons: the "download all" zip, the multi-select download, and the download button in the lightbox. This only shows or hides the buttons; image quality is set by [`maxDownloadQuality`](#maxdownloadquality) and [`maxZoomQuality`](#maxzoomquality).
permissive CORS header. The "download all" zip is always sent with `Cache-Control: no-store`, and the gallery page
uses its own [`gallery.cacheTime`](/config/gallery#cachetime).
```json - `0` - downloads off.
{ - `1` - follow the Immich share's own download setting ([example](https://github.com/user-attachments/assets/79ea8c08-71ce-42ab-b025-10aec384938a)).
"ipp": { - `2` - always on.
"responseHeaders": {
"Cache-Control": "public, max-age=2592000", The bulk-zip and per-asset buttons can be toggled independently once downloads are allowed - see [`gallery.showDownloadZip`](/config/gallery#showdownloadzip) and [`lightbox.showDownload`](/config/lightbox#showdownload).
"Access-Control-Allow-Origin": "*"
} > [!NOTE]
} > With `2`, IPP shows the download buttons even on shares whose own download toggle in Immich is off. Immich still refuses to serve those shares' original files, so on such a share:
} >
``` > - **Videos** download as the playback version, usually an `.mp4`, instead of the original.
> - **Photos** download at [`maxDownloadQuality`](#maxdownloadquality) if it is below `original`. With `original` they fail.
> - **Gifs** always download as the original file, so they fail.
>
> To be sure every download works at full quality, leave the share's download permission on in Immich.
## `maxDownloadQuality` ## `maxDownloadQuality`
@@ -48,6 +50,35 @@ Highest quality served for a download (the download button and "download all" zi
- `"fullsize"` - full resolution but always browser-displayable: the original for JPEG/PNG/WebP, Immich's converted full-size image for RAW/HEIF, in JPEG or WebP per the server's image settings. - `"fullsize"` - full resolution but always browser-displayable: the original for JPEG/PNG/WebP, Immich's converted full-size image for RAW/HEIF, in JPEG or WebP per the server's image settings.
- `"preview"` - only the ~1440px preview, in JPEG or WebP per the server's image settings. - `"preview"` - only the ~1440px preview, in JPEG or WebP per the server's image settings.
## `downloadedFilename`
**Type:** `int` · **Default:** `2`
How downloaded files are named, both in the zip and for a single download. The extension always matches the bytes
served, so a preview download of a HEIC photo is `.jpg`.
- `0` - the original filename if available, falling back to the Immich asset ID.
- `1` - the Immich asset ID.
- `2` - an anonymous name made from the share and the item's position in it.
```
a3f9c2e1_001.jpg
a3f9c2e1_002.jpg
a3f9c2e1_003.mp4
```
With `2`, the same share always gives the same names, and a few selected items keep their positions in the whole
share. Unzipping a second download over the first replaces it. If the share's content or order changes, positions
shift, so a re-download then replaces files with different photos.
```json
{
"ipp": {
"downloadedFilename": 0
}
}
```
## `maxZoomQuality` ## `maxZoomQuality`
**Type:** `string` · **Default:** `"preview"` **Type:** `string` · **Default:** `"preview"`
@@ -77,73 +108,6 @@ Clips are only fetched while the toggle is on, so leaving this on costs no extra
} }
``` ```
## `downloadedFilename`
**Type:** `int` · **Default:** `2`
How downloaded files are named, both in the zip and for a single download. The extension always matches the bytes
served, so a preview download of a HEIC photo is `.jpg`.
- `0` - the original filename if available, falling back to the Immich asset ID.
- `1` - the Immich asset ID.
- `2` - an anonymous name made from the share and the item's position in it: the first 8 characters of a hash of
the share key, then the 1-based position in the order the gallery shows, zero-padded to at least three digits.
```
a3f9c2e1_001.jpg
a3f9c2e1_002.jpg
a3f9c2e1_003.mp4
```
With `2`, the same share always gives the same names, and a few selected items keep their positions in the whole
share. Unzipping a second download over the first replaces it. If the share's content or order changes, positions
shift, so a re-download then replaces files with different photos.
```json
{
"ipp": {
"downloadedFilename": 0
}
}
```
## `allowDownload`
**Type:** `int` · **Default:** `0`
Show the download buttons: the "download all" zip, the multi-select download, and the download button in the lightbox. This only shows or hides the buttons; image quality is set by [`maxDownloadQuality`](#maxdownloadquality) and [`maxZoomQuality`](#maxzoomquality).
- `0` - downloads off.
- `1` - follow the Immich share's own download setting ([example](https://github.com/user-attachments/assets/79ea8c08-71ce-42ab-b025-10aec384938a)).
- `2` - always on.
The bulk-zip and per-asset buttons can be toggled independently once downloads are allowed - see [`gallery.showDownloadZip`](/config/gallery#showdownloadzip) and [`lightbox.showDownload`](/config/lightbox#showdownload).
> [!NOTE]
> With `2`, IPP shows the download buttons even on shares whose own download toggle in Immich is off. Immich still refuses to serve those shares' original files, so on such a share:
>
> - **Videos** download as the playback version, usually an `.mp4`, instead of the original.
> - **Photos** download at [`maxDownloadQuality`](#maxdownloadquality) if it is below `original`. With `original` they fail.
> - **Gifs** always download as the original file, so they fail.
>
> To be sure every download works at full quality, leave the share's download permission on in Immich.
## `uploadUrl`
**Type:** `string` · **Default:** `"/upload"`
Where the optional upload service (the `immich-public-proxy-upload` container) is served. A share whose "Allow public user to upload" option is on in Immich then shows an "Add photos" button in the gallery header, which opens that share's page on the upload service. To set up the service, see [Let visitors send photos back](/visitor-uploads).
- **A path**, such as the default `/upload`, means the service is on IPP's own hostname under that path. Before showing the button, the gallery page checks that the upload service answers `ok` at `<path>/healthcheck`, so an install without the upload container never shows a dead button. When nothing is routed there, IPP answers that path itself with an empty 204.
- **An absolute URL**, such as `https://upload.example.com`, means the service has a hostname of its own. It is trusted without a check. The URL may include a path, such as `https://photos.example.com/upload`, which points at the same place as the default but without the check.
- **An empty string** never shows the button.
## `allowSlugLinks`
**Type:** `bool` · **Default:** `true`
Serve shared links that have a custom URL in Immich at `/s/<slug>` as well as `/share/<key>`. Set to `false` to return a 404 for slug links, so that only the key form works.
## `showHomePage` ## `showHomePage`
**Type:** `bool` · **Default:** `true` **Type:** `bool` · **Default:** `true`
@@ -158,6 +122,22 @@ Set to `false` to remove the IPP shield page at `/` and at `/share`.
} }
``` ```
## `allowSlugLinks`
**Type:** `bool` · **Default:** `true`
Serve shared links that have a custom URL in Immich at `/s/<slug>` as well as `/share/<key>`. Set to `false` to return a 404 for slug links, so that only the key form works.
## `uploadUrl`
**Type:** `string` · **Default:** `"/upload"`
Where the optional upload service (the `immich-public-proxy-upload` container) is served. A share whose "Allow public user to upload" option is on in Immich then shows an "Add photos" button in the gallery header, which opens that share's page on the upload service. To set up the service, see [Let visitors send photos back](/visitor-uploads).
- **A path**, such as the default `/upload`, means the service is on IPP's own hostname under that path. Before showing the button, the gallery page checks that the upload service answers `ok` at `<path>/healthcheck`, so an install without the upload container never shows a dead button. When nothing is routed there, IPP answers that path itself with an empty 204.
- **An absolute URL**, such as `https://upload.example.com`, means the service has a hostname of its own. It is trusted without a check. The URL may include a path, such as `https://photos.example.com/upload`, which points at the same place as the default but without the check.
- **An empty string** never shows the button.
## `gallery` ## `gallery`
**Type:** `object` **Type:** `object`
@@ -181,3 +161,22 @@ Description / EXIF / location reveal controls. See [Metadata](/config/metadata).
**Type:** `various` · **Default:** `false` **Type:** `various` · **Default:** `false`
Send a custom response instead of the default 404. See [Error responses](/config/error-responses). Send a custom response instead of the default 404. See [Error responses](/config/error-responses).
## `responseHeaders`
**Type:** `object`
Change the headers sent with photos, videos and static files. The default is a 30-day `Cache-Control` and a
permissive CORS header. The "download all" zip is always sent with `Cache-Control: no-store`, and the gallery page
uses its own [`gallery.cacheTime`](/config/gallery#cachetime).
```json
{
"ipp": {
"responseHeaders": {
"Cache-Control": "public, max-age=2592000",
"Access-Control-Allow-Origin": "*"
}
}
}
```
+6 -6
View File
@@ -26,18 +26,18 @@ Hide the download button inside the lightbox even though zip downloads are other
Show the prev/next arrows on desktop. They appear when the user hovers the lightbox. Show the prev/next arrows on desktop. They appear when the user hovers the lightbox.
## `showDownload`
**Type:** `bool` · **Default:** `true`
Show a download button in the lightbox toolbar. Only takes effect when downloads are also allowed by [`allowDownload`](/config/ipp-options#allowdownload).
## `mobileArrows` ## `mobileArrows`
**Type:** `bool` · **Default:** `false` **Type:** `bool` · **Default:** `false`
Show prev/next arrows on mobile (screens under 640px wide). Off by default, as visitors swipe instead. Show prev/next arrows on mobile (screens under 640px wide). Off by default, as visitors swipe instead.
## `showDownload`
**Type:** `bool` · **Default:** `true`
Show a download button in the lightbox toolbar. Only takes effect when downloads are also allowed by [`allowDownload`](/config/ipp-options#allowdownload).
## `autoPlayVideos` ## `autoPlayVideos`
**Type:** `bool` · **Default:** `false` **Type:** `bool` · **Default:** `false`
+51 -4
View File
@@ -1,5 +1,6 @@
import { describe, it, expect } from 'vitest' import { describe, it, expect } from 'vitest'
import { checkKeys, parsePage, readConfigSchema, type ConfigKey, type ConfigType } from '../.vitepress/configSchema' import { readConfigSchema } from '../.vitepress/configCheck'
import { checkKeys, keyLabel, parsePage, parseRenamedKeys, sameValue, type ConfigKey, type ConfigType } from '../.vitepress/configSchema'
/* /*
The first test is the one that matters: the same check `vitepress build` The first test is the one that matters: the same check `vitepress build`
@@ -120,9 +121,9 @@ describe('parsePage', () => {
'| `iso` | `bool` | `true` | ISO sensitivity. |' '| `iso` | `bool` | `true` | ISO sensitivity. |'
].join('\n')), '/config/metadata') ].join('\n')), '/config/metadata')
expect(problems).toEqual([]) expect(problems).toEqual([])
expect(keys.map(key => [key.path, key.default, key.anchor])).toEqual([ expect(keys.map(key => [key.path, key.default, key.anchor, key.group])).toEqual([
['ipp.showMetadata.exif.make', false, 'exif-group'], ['ipp.showMetadata.exif.make', false, 'exif-group', 'EXIF group'],
['ipp.showMetadata.exif.iso', true, 'exif-group'] ['ipp.showMetadata.exif.iso', true, 'exif-group', 'EXIF group']
]) ])
}) })
}) })
@@ -197,8 +198,54 @@ describe('checkKeys', () => {
expect(keys.map(field => field.path)).toEqual(['ipp.gallery.showTitle']) expect(keys.map(field => field.path)).toEqual(['ipp.gallery.showTitle'])
}) })
it('returns the keys in config.json order, not page order', () => {
const { keys } = checkKeys(
[key('ipp.b', 'bool', { default: true }), key('ipp.a', 'bool', { default: true })],
[{ name: APP, config: { ipp: { a: true, b: true } } }]
)
expect(keys.map(field => field.path)).toEqual(['ipp.a', 'ipp.b'])
})
it('reports a missing default on anything but an object key', () => { it('reports a missing default on anything but an object key', () => {
const { problems } = checkKeys([key('ipp.showTitle', 'bool')], [{ name: APP, config: { ipp: { showTitle: true } } }]) const { problems } = checkKeys([key('ipp.showTitle', 'bool')], [{ name: APP, config: { ipp: { showTitle: true } } }])
expect(problems).toEqual(['`ipp.showTitle` has no default in docs/config/test.md']) expect(problems).toEqual(['`ipp.showTitle` has no default in docs/config/test.md'])
}) })
}) })
describe('parseRenamedKeys', () => {
it('reads the first key in each cell of the Old key and Current key tables', () => {
const renamed = parseRenamedKeys([
'# Renamed config keys',
'',
'| Old key | Current key |',
'|-------------------------|----------------------------------------|',
'| `ipp.allowDownloadAll` | `ipp.allowDownload`, same `0` / `1` |',
'',
'| Group | Description |',
'|-------|-------------|',
'| `exif` | Not a rename. |'
].join('\n'))
expect(renamed).toEqual([{ from: 'ipp.allowDownloadAll', to: 'ipp.allowDownload', note: '`ipp.allowDownload`, same `0` / `1`' }])
})
})
describe('sameValue', () => {
it('compares JSON values deeply, whatever the order of object keys', () => {
expect(sameValue({ a: 1, b: [1, { c: null }] }, { b: [1, { c: null }], a: 1 })).toBe(true)
expect(sameValue({ a: 1 }, { a: 1, b: undefined })).toBe(false)
expect(sameValue([1, 2], [2, 1])).toBe(false)
expect(sameValue(0, false)).toBe(false)
})
})
describe('keyLabel', () => {
it('writes the last part of the path as words, with acronyms in capitals', () => {
expect(keyLabel('ipp.lightbox.showArrows')).toBe('Show arrows')
expect(keyLabel('ipp.upload.notifyUrl')).toBe('Notify URL')
expect(keyLabel('ipp.showMetadata.exif')).toBe('EXIF')
})
it('uses the label from LABELS where there is one', () => {
expect(keyLabel('ipp.showMetadata.exif.dateTimeOriginal')).toBe('Date taken')
})
})