@meith/forums 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "@meith/forums",
3
+ "version": "0.16.0",
4
+ "license": "LGPL-3.0-or-later",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/meith-dev/meith.git",
8
+ "directory": "packages/forums"
9
+ },
10
+ "type": "module",
11
+ "main": "./src/index.ts",
12
+ "types": "./src/index.ts",
13
+ "exports": {
14
+ ".": "./src/index.ts",
15
+ "./arrange": "./src/arrange.ts"
16
+ },
17
+ "files": [
18
+ "src",
19
+ "!src/**/*.test.*",
20
+ "!src/**/*.type-test.*"
21
+ ],
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "dependencies": {
26
+ "@meith/i18n": "0.16.0",
27
+ "@meith/core": "0.16.0"
28
+ }
29
+ }
package/src/arrange.ts ADDED
@@ -0,0 +1,224 @@
1
+ import { canHoldForums } from './placement'
2
+ import { buildTree } from './tree'
3
+ import type { ForumNode, ForumRow, ForumType, MoveTarget } from './types'
4
+
5
+ export const NUDGES = ['up', 'down', 'in', 'out'] as const
6
+ export type Nudge = (typeof NUDGES)[number]
7
+
8
+ export interface ForumOutlineRow {
9
+ readonly id: number
10
+ readonly parentId: number | null
11
+ readonly depth: number
12
+ readonly type: ForumType
13
+ readonly title: string
14
+ readonly slug: string
15
+ }
16
+
17
+ export interface DropTarget {
18
+ readonly parentId: number | null
19
+ readonly afterId: number | null
20
+ }
21
+
22
+ export interface DropProjection extends DropTarget {
23
+ readonly index: number
24
+ readonly depth: number
25
+ }
26
+
27
+ export function isNudge(value: string): value is Nudge {
28
+ return (NUDGES as readonly string[]).includes(value)
29
+ }
30
+
31
+ export function outlineOf(rows: readonly ForumRow[]): ForumOutlineRow[] {
32
+ const outline: ForumOutlineRow[] = []
33
+
34
+ const visit = (
35
+ nodes: readonly ForumNode<ForumRow>[],
36
+ parentId: number | null,
37
+ depth: number,
38
+ ): void => {
39
+ for (const node of nodes) {
40
+ outline.push({
41
+ id: node.id,
42
+ parentId,
43
+ depth,
44
+ type: node.type,
45
+ title: node.title,
46
+ slug: node.slug,
47
+ })
48
+ visit(node.children, node.id, depth + 1)
49
+ }
50
+ }
51
+
52
+ visit(buildTree(rows), null, 0)
53
+ return outline
54
+ }
55
+
56
+ export function subtreeOfOutline(
57
+ outline: readonly ForumOutlineRow[],
58
+ forumId: number,
59
+ ): ForumOutlineRow[] {
60
+ const start = outline.findIndex((row) => row.id === forumId)
61
+ if (start === -1) return []
62
+
63
+ const root = outline[start] as ForumOutlineRow
64
+ let end = start + 1
65
+ while (end < outline.length && (outline[end] as ForumOutlineRow).depth > root.depth) end += 1
66
+
67
+ return outline.slice(start, end)
68
+ }
69
+
70
+ export function withoutSubtree(
71
+ outline: readonly ForumOutlineRow[],
72
+ forumId: number,
73
+ ): ForumOutlineRow[] {
74
+ const moving = new Set(subtreeOfOutline(outline, forumId).map((row) => row.id))
75
+ return outline.filter((row) => !moving.has(row.id))
76
+ }
77
+
78
+ export function childrenOf(
79
+ outline: readonly ForumOutlineRow[],
80
+ parentId: number | null,
81
+ ): ForumOutlineRow[] {
82
+ return outline.filter((row) => row.parentId === parentId)
83
+ }
84
+
85
+ export function nudgeTarget(
86
+ outline: readonly ForumOutlineRow[],
87
+ forumId: number,
88
+ nudge: Nudge,
89
+ ): DropTarget | null {
90
+ const row = outline.find((entry) => entry.id === forumId)
91
+ if (row === undefined) return null
92
+
93
+ const siblings = childrenOf(outline, row.parentId)
94
+ const at = siblings.findIndex((entry) => entry.id === forumId)
95
+
96
+ if (nudge === 'up') {
97
+ if (at <= 0) return null
98
+ return { parentId: row.parentId, afterId: siblings[at - 2]?.id ?? null }
99
+ }
100
+
101
+ if (nudge === 'down') {
102
+ const next = siblings[at + 1]
103
+ if (next === undefined) return null
104
+ return { parentId: row.parentId, afterId: next.id }
105
+ }
106
+
107
+ if (nudge === 'in') {
108
+ const previous = siblings[at - 1]
109
+ if (previous === undefined || !canHoldForums(previous.type)) return null
110
+ return {
111
+ parentId: previous.id,
112
+ afterId: childrenOf(outline, previous.id).at(-1)?.id ?? null,
113
+ }
114
+ }
115
+
116
+ const parent = outline.find((entry) => entry.id === row.parentId)
117
+ if (parent === undefined) return null
118
+ return { parentId: parent.parentId, afterId: parent.id }
119
+ }
120
+
121
+ export function availableNudges(
122
+ outline: readonly ForumOutlineRow[],
123
+ forumId: number,
124
+ ): Record<Nudge, boolean> {
125
+ return {
126
+ up: nudgeTarget(outline, forumId, 'up') !== null,
127
+ down: nudgeTarget(outline, forumId, 'down') !== null,
128
+ in: nudgeTarget(outline, forumId, 'in') !== null,
129
+ out: nudgeTarget(outline, forumId, 'out') !== null,
130
+ }
131
+ }
132
+
133
+ export function projectDrop(
134
+ rows: readonly ForumOutlineRow[],
135
+ index: number,
136
+ depth: number,
137
+ ): DropProjection {
138
+ const at = Math.min(Math.max(index, 0), rows.length)
139
+ const previous = rows[at - 1]
140
+ const next = rows[at]
141
+
142
+ if (previous === undefined) return { index: at, depth: 0, parentId: null, afterId: null }
143
+
144
+ const deepest = canHoldForums(previous.type) ? previous.depth + 1 : previous.depth
145
+ const shallowest = next?.depth ?? 0
146
+ const settled = Math.min(Math.max(depth, shallowest), deepest)
147
+
148
+ if (settled === previous.depth + 1) {
149
+ return { index: at, depth: settled, parentId: previous.id, afterId: null }
150
+ }
151
+
152
+ for (let cursor = at - 1; cursor >= 0; cursor -= 1) {
153
+ const candidate = rows[cursor] as ForumOutlineRow
154
+ if (candidate.depth === settled) {
155
+ return {
156
+ index: at,
157
+ depth: settled,
158
+ parentId: candidate.parentId,
159
+ afterId: candidate.id,
160
+ }
161
+ }
162
+ }
163
+
164
+ return { index: at, depth: 0, parentId: null, afterId: null }
165
+ }
166
+
167
+ export function projectionOf(
168
+ outline: readonly ForumOutlineRow[],
169
+ forumId: number,
170
+ target: DropTarget,
171
+ ): DropProjection {
172
+ const rows = withoutSubtree(outline, forumId)
173
+ const parent = rows.find((row) => row.id === target.parentId)
174
+ const depth = target.parentId === null ? 0 : (parent?.depth ?? 0) + 1
175
+
176
+ if (target.afterId === null) {
177
+ const index = parent === undefined ? 0 : rows.indexOf(parent) + 1
178
+ return { ...target, index, depth }
179
+ }
180
+
181
+ const after = rows.find((row) => row.id === target.afterId)
182
+ if (after === undefined) return { ...target, index: rows.length, depth }
183
+
184
+ const followers = subtreeOfOutline(rows, after.id)
185
+ return { ...target, index: rows.indexOf(after) + followers.length, depth }
186
+ }
187
+
188
+ export function applyDrop(
189
+ outline: readonly ForumOutlineRow[],
190
+ forumId: number,
191
+ projection: DropProjection,
192
+ ): ForumOutlineRow[] {
193
+ const block = subtreeOfOutline(outline, forumId)
194
+ if (block.length === 0) return [...outline]
195
+
196
+ const rest = withoutSubtree(outline, forumId)
197
+ const shift = projection.depth - (block[0] as ForumOutlineRow).depth
198
+
199
+ const moved = block.map((row, offset) => ({
200
+ ...row,
201
+ depth: row.depth + shift,
202
+ ...(offset === 0 ? { parentId: projection.parentId } : {}),
203
+ }))
204
+
205
+ return [...rest.slice(0, projection.index), ...moved, ...rest.slice(projection.index)]
206
+ }
207
+
208
+ export function isWhereItIs(
209
+ outline: readonly ForumOutlineRow[],
210
+ forumId: number,
211
+ target: DropTarget,
212
+ ): boolean {
213
+ const row = outline.find((entry) => entry.id === forumId)
214
+ if (row === undefined || row.parentId !== target.parentId) return false
215
+
216
+ const siblings = childrenOf(outline, row.parentId)
217
+ const at = siblings.findIndex((entry) => entry.id === forumId)
218
+
219
+ return (siblings[at - 1]?.id ?? null) === target.afterId
220
+ }
221
+
222
+ export function moveTargetOf(target: DropTarget): MoveTarget {
223
+ return { newParentId: target.parentId, after: target.afterId }
224
+ }
@@ -0,0 +1,55 @@
1
+ import { type CacheDriver, CacheTags, cachedGlobal } from '@meith/core'
2
+
3
+ import type { ForumRepository } from './ports'
4
+ import type { ForumListingRow, ForumRow, MovePlan, MoveTarget, NewForum } from './types'
5
+
6
+ const TREE_KEY = ['forum-tree'] as const
7
+
8
+ export const TREE_TTL_SECONDS = 60
9
+
10
+ export class CachedForumRepository implements ForumRepository {
11
+ constructor(
12
+ private readonly inner: ForumRepository,
13
+ private readonly cache: CacheDriver,
14
+ ) {}
15
+
16
+ async listAll(): Promise<ForumRow[]> {
17
+ return cachedGlobal(
18
+ this.cache,
19
+ {
20
+ key: TREE_KEY,
21
+ tags: [CacheTags.forumTree()],
22
+ revalidate: TREE_TTL_SECONDS,
23
+ },
24
+ () => this.inner.listAll(),
25
+ )
26
+ }
27
+
28
+ async listListing(): Promise<ForumListingRow[]> {
29
+ return this.inner.listListing()
30
+ }
31
+
32
+ async findById(id: number): Promise<ForumRow | null> {
33
+ return (await this.listAll()).find((row) => row.id === id) ?? null
34
+ }
35
+
36
+ async create(input: NewForum): Promise<ForumRow> {
37
+ const created = await this.inner.create(input)
38
+ await this.invalidate()
39
+ return created
40
+ }
41
+
42
+ async move(forumId: number, target: MoveTarget): Promise<void> {
43
+ await this.inner.move(forumId, target)
44
+ await this.invalidate()
45
+ }
46
+
47
+ async applyMove(plan: MovePlan): Promise<void> {
48
+ await this.inner.applyMove(plan)
49
+ await this.invalidate()
50
+ }
51
+
52
+ private async invalidate(): Promise<void> {
53
+ await this.cache.invalidateTags([CacheTags.forumTree()])
54
+ }
55
+ }
package/src/create.ts ADDED
@@ -0,0 +1,54 @@
1
+ import { ConflictError, ValidationError } from '@meith/core'
2
+ import { msg } from '@meith/i18n'
3
+
4
+ import type { ForumRow, NewForum } from './types'
5
+
6
+ const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
7
+
8
+ export interface CreatePlan {
9
+ readonly parentId: number | null
10
+ readonly parentPath: string | null
11
+ readonly depth: number
12
+ readonly displayOrder: number
13
+ }
14
+
15
+ export function planCreate(rows: readonly ForumRow[], input: NewForum): CreatePlan {
16
+ const title = input.title.trim()
17
+ if (title === '') throw new ValidationError(msg('error.forums.forum-needs-title'))
18
+
19
+ if (!SLUG.test(input.slug)) {
20
+ throw new ValidationError(
21
+ `"${input.slug}" is not a valid slug: use lowercase letters, digits and single hyphens.`,
22
+ )
23
+ }
24
+
25
+ if (input.type === 'link' && !input.linkUrl) {
26
+ throw new ValidationError(msg('error.forums.link-forum-needs-linkurl'))
27
+ }
28
+
29
+ const parent = input.parentId === null ? null : rows.find((r) => r.id === input.parentId)
30
+ if (input.parentId !== null && !parent) {
31
+ throw new ValidationError(`No such parent forum: ${input.parentId}`)
32
+ }
33
+
34
+ if (parent?.type === 'link') {
35
+ throw new ValidationError(`"${parent.title}" is a link and cannot contain forums.`)
36
+ }
37
+
38
+ const siblings = rows.filter((r) => r.parentId === input.parentId)
39
+ if (siblings.some((s) => s.slug === input.slug)) {
40
+ throw new ConflictError(
41
+ `A forum with the slug "${input.slug}" already exists in that location.`,
42
+ )
43
+ }
44
+
45
+ const parentPath = parent?.path ?? null
46
+
47
+ return {
48
+ parentId: input.parentId,
49
+ parentPath,
50
+ depth: parent === null || parent === undefined ? 0 : parent.depth + 1,
51
+ displayOrder:
52
+ input.displayOrder ?? siblings.reduce((max, s) => Math.max(max, s.displayOrder + 1), 0),
53
+ }
54
+ }
package/src/index.ts ADDED
@@ -0,0 +1,49 @@
1
+ export {
2
+ applyDrop,
3
+ availableNudges,
4
+ childrenOf,
5
+ type DropProjection,
6
+ type DropTarget,
7
+ type ForumOutlineRow,
8
+ isNudge,
9
+ isWhereItIs,
10
+ moveTargetOf,
11
+ NUDGES,
12
+ type Nudge,
13
+ nudgeTarget,
14
+ outlineOf,
15
+ projectDrop,
16
+ projectionOf,
17
+ subtreeOfOutline,
18
+ withoutSubtree,
19
+ } from './arrange'
20
+ export { CachedForumRepository } from './cached-repo'
21
+ export { type CreatePlan, planCreate } from './create'
22
+ export { planMove } from './move'
23
+ export {
24
+ ancestorIds,
25
+ childPath,
26
+ depthOf,
27
+ formatPath,
28
+ isInSubtree,
29
+ PATH_SEPARATOR,
30
+ parsePath,
31
+ rehang,
32
+ subtreeOf,
33
+ } from './path'
34
+ export { acceptsThreads, canHoldForums, canHoldThreads } from './placement'
35
+ export type { ForumRepository } from './ports'
36
+ export { buildTree, flattenTree, keepVisibleSubtrees } from './tree'
37
+ export {
38
+ FORUM_TYPES,
39
+ type ForumListingRow,
40
+ type ForumNode,
41
+ type ForumRow,
42
+ type ForumType,
43
+ type LastPostSummary,
44
+ type MovePlan,
45
+ type MoveTarget,
46
+ type NewForum,
47
+ type PathUpdate,
48
+ type TreeShaped,
49
+ } from './types'
package/src/move.ts ADDED
@@ -0,0 +1,95 @@
1
+ import { ConflictError, ValidationError } from '@meith/core'
2
+ import { msg } from '@meith/i18n'
3
+
4
+ import { childPath, depthOf, isInSubtree, rehang } from './path'
5
+ import type { ForumRow, MovePlan, MoveTarget, PathUpdate } from './types'
6
+
7
+ export function planMove(rows: readonly ForumRow[], forumId: number, target: MoveTarget): MovePlan {
8
+ const byId = new Map(rows.map((r) => [r.id, r]))
9
+
10
+ const forum = byId.get(forumId)
11
+ if (!forum) throw new ValidationError(`No such forum: ${forumId}`)
12
+
13
+ const { newParentId } = target
14
+ const newParent = newParentId === null ? null : byId.get(newParentId)
15
+ if (newParentId !== null && !newParent) {
16
+ throw new ValidationError(`No such parent forum: ${newParentId}`)
17
+ }
18
+
19
+ if (newParent) {
20
+ if (newParent.id === forum.id) {
21
+ throw new ValidationError(msg('error.forums.forum-its-own-parent'))
22
+ }
23
+
24
+ if (isInSubtree(newParent.path, forum.path)) {
25
+ throw new ValidationError(
26
+ `Cannot move "${forum.title}" into its own descendant "${newParent.title}".`,
27
+ )
28
+ }
29
+
30
+ if (newParent.type === 'link') {
31
+ throw new ValidationError(`"${newParent.title}" is a link and cannot contain forums.`)
32
+ }
33
+ }
34
+
35
+ const siblings = rows
36
+ .filter((r) => r.parentId === newParentId && r.id !== forum.id)
37
+ .sort((a, b) => a.displayOrder - b.displayOrder || a.id - b.id)
38
+
39
+ const collision = siblings.find((s) => s.slug === forum.slug)
40
+ if (collision) {
41
+ throw new ConflictError(
42
+ `A forum with the slug "${forum.slug}" already exists in that location.`,
43
+ )
44
+ }
45
+
46
+ return {
47
+ forumId,
48
+ newParentId,
49
+ pathUpdates: planPathUpdates(rows, forum, newParent?.path ?? null),
50
+ orderUpdates: planOrderUpdates(siblings, forum.id, target),
51
+ }
52
+ }
53
+
54
+ function planPathUpdates(
55
+ rows: readonly ForumRow[],
56
+ forum: ForumRow,
57
+ newParentPath: string | null,
58
+ ): PathUpdate[] {
59
+ const newRoot = childPath(newParentPath, forum.id)
60
+
61
+ if (newRoot === forum.path) return []
62
+
63
+ return rows
64
+ .filter((row) => isInSubtree(row.path, forum.path))
65
+ .map((row) => {
66
+ const path = rehang(row.path, forum.path, newRoot)
67
+ return { id: row.id, path, depth: depthOf(path) }
68
+ })
69
+ }
70
+
71
+ function planOrderUpdates(
72
+ siblings: readonly ForumRow[],
73
+ forumId: number,
74
+ target: MoveTarget,
75
+ ): { id: number; displayOrder: number }[] {
76
+ const ids = siblings.map((s) => s.id)
77
+
78
+ ids.splice(insertionIndex(ids, target), 0, forumId)
79
+ return ids.map((id, displayOrder) => ({ id, displayOrder }))
80
+ }
81
+
82
+ function insertionIndex(ids: readonly number[], target: MoveTarget): number {
83
+ if (target.after !== undefined) {
84
+ if (target.after === null) return 0
85
+
86
+ const at = ids.indexOf(target.after)
87
+ if (at === -1) {
88
+ throw new ConflictError(msg('error.forums.forum-follow-longer-there-reload'))
89
+ }
90
+ return at + 1
91
+ }
92
+
93
+ const { position } = target
94
+ return position === undefined ? ids.length : Math.min(Math.max(position, 0), ids.length)
95
+ }
package/src/path.ts ADDED
@@ -0,0 +1,49 @@
1
+ import { ValidationError } from '@meith/core'
2
+
3
+ export const PATH_SEPARATOR = '.'
4
+
5
+ export function formatPath(ids: readonly number[]): string {
6
+ return ids.join(PATH_SEPARATOR)
7
+ }
8
+
9
+ export function parsePath(path: string): number[] {
10
+ if (path === '') return []
11
+ return path.split(PATH_SEPARATOR).map((segment) => {
12
+ const id = Number(segment)
13
+ if (!Number.isInteger(id) || id <= 0) {
14
+ throw new ValidationError(`Malformed forum path segment: ${segment}`)
15
+ }
16
+ return id
17
+ })
18
+ }
19
+
20
+ export function ancestorIds(path: string): number[] {
21
+ const ids = parsePath(path)
22
+ return ids.slice(0, -1)
23
+ }
24
+
25
+ export function depthOf(path: string): number {
26
+ return Math.max(parsePath(path).length - 1, 0)
27
+ }
28
+
29
+ export function childPath(parentPath: string | null, childId: number): string {
30
+ return parentPath === null || parentPath === ''
31
+ ? String(childId)
32
+ : `${parentPath}${PATH_SEPARATOR}${childId}`
33
+ }
34
+
35
+ export function isInSubtree(candidate: string, ancestor: string): boolean {
36
+ if (candidate === ancestor) return true
37
+ return candidate.startsWith(`${ancestor}${PATH_SEPARATOR}`)
38
+ }
39
+
40
+ export function subtreeOf(path: string): { exact: string; prefix: string } {
41
+ return { exact: path, prefix: `${path}${PATH_SEPARATOR}%` }
42
+ }
43
+
44
+ export function rehang(descendantPath: string, oldRoot: string, newRoot: string): string {
45
+ if (!isInSubtree(descendantPath, oldRoot)) {
46
+ throw new ValidationError(`${descendantPath} is not inside ${oldRoot}; refusing to rehang it`)
47
+ }
48
+ return `${newRoot}${descendantPath.slice(oldRoot.length)}`
49
+ }
@@ -0,0 +1,16 @@
1
+ import type { ForumType } from './types'
2
+
3
+ export function canHoldThreads(type: ForumType): boolean {
4
+ return type !== 'link'
5
+ }
6
+
7
+ export function canHoldForums(type: ForumType): boolean {
8
+ return type !== 'link'
9
+ }
10
+
11
+ export function acceptsThreads(row: {
12
+ readonly type: ForumType
13
+ readonly allowThreads: boolean
14
+ }): boolean {
15
+ return row.type === 'forum' || (row.type === 'category' && row.allowThreads)
16
+ }
package/src/ports.ts ADDED
@@ -0,0 +1,15 @@
1
+ import type { ForumListingRow, ForumRow, MovePlan, MoveTarget, NewForum } from './types'
2
+
3
+ export interface ForumRepository {
4
+ listAll(): Promise<ForumRow[]>
5
+
6
+ listListing(): Promise<ForumListingRow[]>
7
+
8
+ findById(id: number): Promise<ForumRow | null>
9
+
10
+ create(input: NewForum): Promise<ForumRow>
11
+
12
+ applyMove(plan: MovePlan): Promise<void>
13
+
14
+ move(forumId: number, target: MoveTarget): Promise<void>
15
+ }
package/src/tree.ts ADDED
@@ -0,0 +1,70 @@
1
+ import type { ForumNode, TreeShaped } from './types'
2
+
3
+ function bySiblingOrder(a: TreeShaped, b: TreeShaped): number {
4
+ return a.displayOrder - b.displayOrder || a.id - b.id
5
+ }
6
+
7
+ export function keepVisibleSubtrees<T extends TreeShaped>(
8
+ rows: readonly T[],
9
+ isVisible: (row: T) => boolean,
10
+ ): T[] {
11
+ const visible = rows.filter(isVisible)
12
+ const survived = new Set(visible.map((row) => row.id))
13
+
14
+ for (;;) {
15
+ const orphaned = visible.filter(
16
+ (row) => survived.has(row.id) && row.parentId !== null && !survived.has(row.parentId),
17
+ )
18
+ if (orphaned.length === 0) break
19
+ for (const row of orphaned) survived.delete(row.id)
20
+ }
21
+
22
+ return visible.filter((row) => survived.has(row.id))
23
+ }
24
+
25
+ export function buildTree<T extends TreeShaped>(rows: readonly T[]): ForumNode<T>[] {
26
+ const byId = new Map<number, T>(rows.map((row) => [row.id, row]))
27
+ const childrenOf = new Map<number | null, T[]>()
28
+
29
+ for (const row of rows) {
30
+ const parentKey =
31
+ row.parentId !== null && byId.has(row.parentId) && !isSelfOrCyclic(row, byId)
32
+ ? row.parentId
33
+ : null
34
+
35
+ const bucket = childrenOf.get(parentKey)
36
+ if (bucket) bucket.push(row)
37
+ else childrenOf.set(parentKey, [row])
38
+ }
39
+
40
+ const attach = (row: T): ForumNode<T> => ({
41
+ ...row,
42
+ children: (childrenOf.get(row.id) ?? []).sort(bySiblingOrder).map(attach),
43
+ })
44
+
45
+ return (childrenOf.get(null) ?? []).sort(bySiblingOrder).map(attach)
46
+ }
47
+
48
+ function isSelfOrCyclic<T extends TreeShaped>(row: T, byId: Map<number, T>): boolean {
49
+ const seen = new Set<number>([row.id])
50
+ let current = row.parentId
51
+
52
+ while (current !== null) {
53
+ if (seen.has(current)) return true
54
+ seen.add(current)
55
+ const parent = byId.get(current)
56
+ if (!parent) return false
57
+ current = parent.parentId
58
+ }
59
+ return false
60
+ }
61
+
62
+ export function flattenTree<T extends TreeShaped>(nodes: readonly ForumNode<T>[]): ForumNode<T>[] {
63
+ const out: ForumNode<T>[] = []
64
+ const visit = (node: ForumNode<T>): void => {
65
+ out.push(node)
66
+ for (const child of node.children) visit(child)
67
+ }
68
+ for (const node of nodes) visit(node)
69
+ return out
70
+ }
package/src/types.ts ADDED
@@ -0,0 +1,67 @@
1
+ export const FORUM_TYPES = ['category', 'forum', 'link'] as const
2
+ export type ForumType = (typeof FORUM_TYPES)[number]
3
+
4
+ export interface TreeShaped {
5
+ readonly id: number
6
+ readonly parentId: number | null
7
+ readonly displayOrder: number
8
+ }
9
+
10
+ export interface ForumRow extends TreeShaped {
11
+ readonly type: ForumType
12
+ readonly title: string
13
+ readonly slug: string
14
+ readonly description: string | null
15
+ readonly path: string
16
+ readonly depth: number
17
+ readonly linkUrl: string | null
18
+ }
19
+
20
+ export type ForumNode<T extends TreeShaped = ForumRow> = T & {
21
+ readonly children: readonly ForumNode<T>[]
22
+ }
23
+
24
+ export interface LastPostSummary {
25
+ readonly postId: number
26
+ readonly threadId: number
27
+ readonly threadTitle: string
28
+ readonly userId: number | null
29
+ readonly username: string
30
+ readonly at: Date
31
+ }
32
+
33
+ export interface ForumListingRow extends ForumRow {
34
+ readonly allowThreads: boolean
35
+ readonly threadCount: number
36
+ readonly postCount: number
37
+ readonly lastPost: LastPostSummary | null
38
+ }
39
+
40
+ export interface NewForum {
41
+ readonly type: ForumType
42
+ readonly title: string
43
+ readonly slug: string
44
+ readonly description?: string | undefined
45
+ readonly parentId: number | null
46
+ readonly linkUrl?: string | undefined
47
+ readonly displayOrder?: number | undefined
48
+ }
49
+
50
+ export interface MoveTarget {
51
+ readonly newParentId: number | null
52
+ readonly position?: number
53
+ readonly after?: number | null
54
+ }
55
+
56
+ export interface PathUpdate {
57
+ readonly id: number
58
+ readonly path: string
59
+ readonly depth: number
60
+ }
61
+
62
+ export interface MovePlan {
63
+ readonly forumId: number
64
+ readonly newParentId: number | null
65
+ readonly pathUpdates: readonly PathUpdate[]
66
+ readonly orderUpdates: readonly { readonly id: number; readonly displayOrder: number }[]
67
+ }