diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..3de57a360 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,12 @@ +node_modules/ +dist/ +logs/ +.DS_Store +.git/ +config/local.json +pleroma-backend/ +test/e2e/reports/ +test/e2e-playwright/test-results/ +test/e2e-playwright/playwright-report/ +__screenshots__/ + diff --git a/.forgejo/issue_template/bug.yaml b/.forgejo/issue_template/bug.yaml new file mode 100644 index 000000000..082ee496e --- /dev/null +++ b/.forgejo/issue_template/bug.yaml @@ -0,0 +1,87 @@ +name: 'Bug report' +about: 'Bug report for Pleroma FE' +labels: + - Bug +body: +- type: input + id: env-browser + attributes: + label: Browser and OS + description: What browser are you using, including version, and what OS are you running? + placeholder: Firefox 140, Arch Linux + validations: + required: true +- type: input + id: env-instance + attributes: + label: Instance URL + validations: + required: false +- type: input + id: env-backend + attributes: + label: Backend version information + description: Backend version being used. (See Settings->Show advanced->Developer) + placeholder: Pleroma BE 2.10 + validations: + required: true +- type: input + id: env-frontend + attributes: + label: Frontend version information + description: Frontend version being used. (See Settings->Show advanced->Developer) + placeholder: Pleroma FE 2.10 + validations: + required: true +- type: input + id: env-extensions + attributes: + label: Browser extensions + description: List of browser extensions you are using, like uBlock, rikaichamp etc. If none leave empty. + validations: + required: false +- type: input + id: env-modifications + attributes: + label: Known instance/user customizations + description: Whether you are using a Pleroma FE fork, any mods mods or instance level styles among others. + validations: + required: false +- type: textarea + id: bug-text + attributes: + label: Bug description + description: A short description of the bug. Images can be helpful. + validations: + required: true +- type: textarea + id: bug-reproducer + attributes: + label: Reproduction steps + description: Ordered list of reproduction steps needed to make the bug happen. If you don't have reproduction steps, leave this empty. + placeholder: | + 1. Log in with a fresh browser session + 2. Open timeline X + 3. Click on button Y + 4. Z broke + validations: + required: false +- type: textarea + id: bug-seriousness + attributes: + label: Bug seriousness + value: | + * How annoying it is: + * How often does it happen: + * How many people does it affect: + * Is there a workaround for it: +- type: checkboxes + id: duplicate-issues + attributes: + label: Duplicate issues + hide_label: true + description: Before submitting this issue, search for same or similar issues on the [Pleroma FE bug tracker](https://git.pleroma.social/pleroma/pleroma-fe/issues). + options: + - label: I've searched for same or similar issues before submitting this issue. + required: true + visible: [form] diff --git a/.forgejo/issue_template/suggestion.yaml b/.forgejo/issue_template/suggestion.yaml new file mode 100644 index 000000000..c1531d8e3 --- /dev/null +++ b/.forgejo/issue_template/suggestion.yaml @@ -0,0 +1,22 @@ +name: 'Feature request / Suggestion / Improvement' +about: 'Feature requests, suggestions and improvements for Pleroma FE' +labels: + - Feature Request / Enhancement +body: +- type: textarea + id: issue-text + attributes: + label: Proposal + placeholder: Make groups happen! + validations: + required: true +- type: checkboxes + id: duplicate-issues + attributes: + label: Duplicate issues + hide_label: true + description: Before submitting this issue, search for same or similar requests on the [Pleroma FE bug tracker](https://git.pleroma.social/pleroma/pleroma-fe/issues). + options: + - label: I've searched for same or similar requests before submitting this issue. + required: true + visible: [form] diff --git a/.forgejo/pull_request_template.md b/.forgejo/pull_request_template.md new file mode 100644 index 000000000..d2d7689bd --- /dev/null +++ b/.forgejo/pull_request_template.md @@ -0,0 +1,12 @@ +### Checklist +- [ ] Adding a changelog: In the `changelog.d` directory, create a file named `.`. + + diff --git a/.gitignore b/.gitignore index 01ffda9a8..c4a96ee1e 100644 --- a/.gitignore +++ b/.gitignore @@ -4,8 +4,11 @@ dist/ npm-debug.log test/unit/coverage test/e2e/reports +test/e2e-playwright/test-results +test/e2e-playwright/playwright-report selenium-debug.log .idea/ +.gitlab-ci-local/ config/local.json src/assets/emoji.json logs/ diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 99c85dd36..06fbf45f9 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -34,12 +34,23 @@ check-changelog: - apk add git - sh ./tools/check-changelog -lint: +lint-eslint: stage: lint script: - yarn - - yarn lint - - yarn stylelint + - yarn ci-eslint + +lint-biome: + stage: lint + script: + - yarn + - yarn ci-biome + +lint-stylelint: + stage: lint + script: + - yarn + - yarn ci-stylelint test: stage: test @@ -60,6 +71,135 @@ test: - test/**/__screenshots__ when: on_failure +e2e-pleroma: + stage: test + image: mcr.microsoft.com/playwright:v1.57.0-jammy + services: + - name: postgres:15-alpine + alias: db + - name: $PLEROMA_IMAGE + alias: pleroma + entrypoint: ["/bin/ash", "-c"] + command: + - | + set -eu + + SEED_SENTINEL_PATH=/var/lib/pleroma/.e2e_seeded + CONFIG_OVERRIDE_PATH=/var/lib/pleroma/config.exs + + echo '-- Waiting for database...' + while ! pg_isready -U ${DB_USER:-pleroma} -d postgres://${DB_HOST:-db}:${DB_PORT:-5432}/${DB_NAME:-pleroma} -t 1; do + sleep 1s + done + + echo '-- Writing E2E config overrides...' + cat > $CONFIG_OVERRIDE_PATH </dev/null; then + kill -TERM $PLEROMA_PID + wait $PLEROMA_PID || true + fi + } + + trap cleanup INT TERM + + echo '-- Waiting for API...' + api_ok=false + for _i in $(seq 1 120); do + if wget -qO- http://127.0.0.1:4000/api/v1/instance >/dev/null 2>&1; then + api_ok=true + break + fi + sleep 1s + done + + if [ $api_ok != true ]; then + echo 'Timed out waiting for Pleroma API to become available' + exit 1 + fi + + if [ ! -f $SEED_SENTINEL_PATH ]; then + if [ -n ${E2E_ADMIN_USERNAME:-} ] && [ -n ${E2E_ADMIN_PASSWORD:-} ] && [ -n ${E2E_ADMIN_EMAIL:-} ]; then + echo '-- Seeding admin user' $E2E_ADMIN_USERNAME '...' + if ! /opt/pleroma/bin/pleroma_ctl user new $E2E_ADMIN_USERNAME $E2E_ADMIN_EMAIL --admin --password $E2E_ADMIN_PASSWORD -y; then + echo '-- User already exists or creation failed, ensuring admin + confirmed...' + /opt/pleroma/bin/pleroma_ctl user set $E2E_ADMIN_USERNAME --admin --confirmed + fi + else + echo '-- Skipping admin seeding (missing E2E_ADMIN_* env)' + fi + + touch $SEED_SENTINEL_PATH + fi + + wait $PLEROMA_PID + tags: + - amd64 + - himem + variables: + PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: "1" + FF_NETWORK_PER_BUILD: "true" + PLEROMA_IMAGE: git.pleroma.social:5050/pleroma/pleroma:stable + POSTGRES_USER: pleroma + POSTGRES_PASSWORD: pleroma + POSTGRES_DB: pleroma + DB_USER: pleroma + DB_PASS: pleroma + DB_NAME: pleroma + DB_HOST: db + DB_PORT: 5432 + DOMAIN: localhost + INSTANCE_NAME: Pleroma E2E + E2E_ADMIN_USERNAME: admin + E2E_ADMIN_PASSWORD: adminadmin + E2E_ADMIN_EMAIL: admin@example.com + ADMIN_EMAIL: $E2E_ADMIN_EMAIL + NOTIFY_EMAIL: $E2E_ADMIN_EMAIL + VITE_PROXY_TARGET: http://pleroma:4000 + VITE_PROXY_ORIGIN: http://localhost:4000 + E2E_BASE_URL: http://localhost:8080 + script: + - npm install -g yarn@1.22.22 + - yarn --frozen-lockfile + - | + echo "-- Waiting for Pleroma API..." + api_ok="false" + for _i in $(seq 1 120); do + if wget -qO- http://pleroma:4000/api/v1/instance >/dev/null 2>&1; then + api_ok="true" + break + fi + sleep 1s + done + if [ "$api_ok" != "true" ]; then + echo "Timed out waiting for Pleroma API to become available" + exit 1 + fi + - yarn e2e:pw + artifacts: + when: on_failure + paths: + - test/e2e-playwright/test-results + - test/e2e-playwright/playwright-report + build: stage: build tags: diff --git a/.gitlab/merge_request_templates/Release.md b/.gitlab/merge_request_templates/Release.md new file mode 100644 index 000000000..d02e14a73 --- /dev/null +++ b/.gitlab/merge_request_templates/Release.md @@ -0,0 +1,8 @@ +### Release checklist +* [ ] Bump version in `package.json` +* [ ] Compile a changelog with the `tools/collect-changelog` script +* [ ] Create an MR with an announcement to pleroma.social +#### post-merge +* [ ] Tag the release on the merge commit +* [ ] Make the tag into a Gitlab Releaseā„¢ +* [ ] Merge `master` into `develop` (in case the fixes are already in develop, use `git merge -s ours --no-commit` and manually merge the changelogs) diff --git a/.stylelintrc.json b/.stylelintrc.json index c91107595..afdfd5f5b 100644 --- a/.stylelintrc.json +++ b/.stylelintrc.json @@ -12,6 +12,8 @@ "custom-property-pattern": null, "keyframes-name-pattern": null, "scss/operator-no-newline-after": null, + "declaration-property-value-no-unknown": true, + "scss/declaration-property-value-no-unknown": true, "declaration-block-no-redundant-longhand-properties": [ true, { diff --git a/CHANGELOG.md b/CHANGELOG.md index c2f0e7d17..1eb5a9cb4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,76 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). + +## 2.10.1 +### Fixed +- fixed being unable to set actor type from profile page +- fixed error when clicking mute menu itself (instead of submenu items) +- fixed mute -> domain status submenu not working + +### Internal +- Add playwright E2E-tests with an optional docker-based backend + +## 2.10.0 +### Changed +- Temporary changes modal now shows actual countdown instead of fixed timeout +- Disabled elements are more disabled now +- Rearranged and split settings to make more sense and be less of a wall of text +- On mobile settings now take up full width and presented in navigation style +improved styles for settings + +### Added +- Most of the remaining AdminFE tabs were added into Admin Dashboard +- It's now possible to customize PWA Manfiest from PleromaFE +- Make every configuration option default-overridable by instance admins + +### Fixed +- Fixed settings not appearing if user never touched "show advanced" toggle +- Fix display of the broken/deleted/banned users +- Fixed incorrect emoji display in post interaction lists +- Fixed list title not being saved when editing +- Fixed poll notifications not being expandable + + +## 2.9.3 +### Fixed +- Being unable to update profile + +## 2.9.2 +### Changed +- BREAKING: due to some internal technical changes logging into AdminFE through PleromaFE is no longer possible +- User card/profile got an overhaul +- Profile editing overhaul +- Visually combined subject and content fields in post form +- Moved post form's emoji button into input field +- Minor visual changes and fixes +- Clicking on fav/rt/emoji notifications' contents expands/collapses it +- Reduced time taken processing theme by half +- Splash screen only appears if loading takes more than 2 seconds + +### Added +- Mutes received an update, adding support for regex, muting based on username and expiration time. +- Mutes are now synchronized across sessions +- Support for expiring mutes and blocks (if available) +- Clicking on emoji shows bigger version of it alongside with its shortcode + - Admins also are able to copy it into a local pack +- Added support for Akkoma and IceShrimp.NET backends +- Compatibility with stricter CSP (Akkoma backend) +- Added a way to upload new packs from a URL or ZIP file via the Admin Dashboard +- Unify show/hide content buttons +- Add support for detachable scrollTop button +- Option to left-align user bio +- Cache assets and emojis with service worker +- Indicate currently active V3 theme as a body element class +- Add arithmetic blend ISS function + +### Fixed +- Display counter for status action buttons when they are in the menu +- Fix bookmark button alignment in the extra actions menu +- Instance favicons are no longer stretched +- A lot more scalable UI fixes + - Emoji picker now should work fine when emoji size is increased + ## 2.8.0 ### Changed - BREAKING: static/img/nsfw.2958239.png is now static/img/nsfw.DepQPhG0.png, which may affect people who specify exactly this path as the cover image @@ -34,8 +104,8 @@ This does not guarantee that browsers will or will not work. - Support displaying time in absolute format - Add draft management system - Compress most kinds of images on upload. -- Added option to always convert images to JPEG format instead of using WebP when compressing images. -- Added configurable image compression option in general settings, allowing users to control whether images are compressed before upload. +- Added option to always convert images to JPEG format instead of using WebP when compressing images. +- Added configurable image compression option in general settings, allowing users to control whether images are compressed before upload. - Inform users that Smithereen public polls are public - Splash screen + loading indicator to make process of identifying initialization issues and load performance - UI for making v3 themes and palettes, support for bundling v3 themes diff --git a/README.md b/README.md index 6a37195d5..16d32dcd2 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ # For Translators -To translate Pleroma-FE, use our weblate server: https://translate.pleroma.social/. If you need to add your language it should be added as a json file in [src/i18n/](https://git.pleroma.social/pleroma/pleroma-fe/blob/develop/src/i18n/) folder and added in a list within [src/i18n/languages.js](https://git.pleroma.social/pleroma/pleroma-fe/blob/develop/src/i18n/languages.js). +To translate Pleroma-FE, use our weblate server: https://translate.pleroma.social/. If you need to add your language it should be added as a json file in [src/i18n/](https://git.pleroma.social/pleroma/pleroma-fe/src/src/i18n/) folder and added in a list within [src/i18n/languages.js](https://git.pleroma.social/pleroma/pleroma-fe/src/src/i18n/languages.js). Pleroma-FE will set your language by your browser locale, but you can change language in settings. @@ -32,10 +32,10 @@ yarn unit # For Contributors: -You can create file `/config/local.json` (see [example](https://git.pleroma.social/pleroma/pleroma-fe/blob/develop/config/local.example.json)) to enable some convenience dev options: +You can create file `/config/local.json` (see [example](https://git.pleroma.social/pleroma/pleroma-fe/src/config/local.example.json)) to enable some convenience dev options: * `target`: makes local dev server redirect to some existing instance's BE instead of local BE, useful for testing things in near-production environment and searching for real-life use-cases. -* `staticConfigPreference`: makes FE's `/static/config.json` take preference of BE-served `/api/statusnet/config.json`. Only works in dev mode. +* `staticConfigPreference`: makes FE's `/static/config.json` take preference of BE-served `/api/pleroma/frontend_configurations`. Only works in dev mode. FE Build process also leaves current commit hash in global variable `___pleromafe_commit_hash` so that you can easily see which pleroma-fe commit instance is running, also helps pinpointing which commit was used when FE was bundled into BE. diff --git a/biome.json b/biome.json new file mode 100644 index 000000000..6a464a0e5 --- /dev/null +++ b/biome.json @@ -0,0 +1,149 @@ +{ + "$schema": "https://biomejs.dev/schemas/2.3.11/schema.json", + "vcs": { + "enabled": true, + "clientKind": "git", + "useIgnoreFile": true + }, + "files": { + "includes": ["**", "!!**/dist", "!!tools/emojis.json"] + }, + "formatter": { + "enabled": true, + "indentStyle": "space" + }, + "linter": { + "enabled": true, + "domains": { + "vue": "recommended" + }, + "rules": { + "recommended": false, + "complexity": { + "noAdjacentSpacesInRegex": "error", + "noExtraBooleanCast": "error", + "noUselessCatch": "error", + "noUselessEscapeInRegex": "error" + }, + "correctness": { + "noConstAssign": "error", + "noConstantCondition": "error", + "noEmptyCharacterClassInRegex": "error", + "noEmptyPattern": "error", + "noGlobalObjectCalls": "error", + "noInvalidBuiltinInstantiation": "error", + "noInvalidConstructorSuper": "error", + "noNonoctalDecimalEscape": "error", + "noPrecisionLoss": "error", + "noSelfAssign": "error", + "noSetterReturn": "error", + "noSwitchDeclarations": "error", + "noUndeclaredVariables": "error", + "noUnreachable": "error", + "noUnreachableSuper": "error", + "noUnsafeFinally": "error", + "noUnsafeOptionalChaining": "error", + "noUnusedLabels": "error", + "noUnusedPrivateClassMembers": "error", + "noUnusedVariables": "error", + "useIsNan": "error", + "useValidForDirection": "error", + "useValidTypeof": "error", + "useYield": "error" + }, + "suspicious": { + "noAsyncPromiseExecutor": "error", + "noCatchAssign": "error", + "noClassAssign": "error", + "noCompareNegZero": "error", + "noConstantBinaryExpressions": "error", + "noControlCharactersInRegex": "error", + "noDebugger": "error", + "noDuplicateCase": "error", + "noDuplicateClassMembers": "error", + "noDuplicateElseIf": "error", + "noDuplicateObjectKeys": "error", + "noDuplicateParameters": "error", + "noEmptyBlockStatements": "error", + "noFallthroughSwitchClause": "error", + "noFunctionAssign": "error", + "noGlobalAssign": "error", + "noImportAssign": "error", + "noIrregularWhitespace": "error", + "noMisleadingCharacterClass": "error", + "noPrototypeBuiltins": "error", + "noRedeclare": "error", + "noShadowRestrictedNames": "error", + "noSparseArray": "error", + "noUnsafeNegation": "error", + "noUselessRegexBackrefs": "error", + "noWith": "error", + "useGetterReturn": "error" + } + } + }, + "javascript": { + "formatter": { + "quoteStyle": "single", + "semicolons": "asNeeded" + }, + "globals": [] + }, + "overrides": [ + { + "includes": ["**/*.spec.js", "test/fixtures/*.js"], + "javascript": { + "globals": [ + "vi", + "describe", + "it", + "test", + "expect", + "before", + "beforeEach", + "after", + "afterEach" + ] + } + }, + { + "includes": ["**/*.vue"], + "linter": { + "rules": { + "style": { + "useConst": "off", + "useImportType": "off" + }, + "correctness": { + "noUnusedVariables": "off", + "noUnusedImports": "off" + } + } + } + } + ], + "assist": { + "enabled": true, + "actions": { + "source": { + "organizeImports": { + "level": "on", + "options": { + "groups": [ + [":NODE:", ":PACKAGE:", "!src/**", "!@fortawesome/**"], + ":BLANK_LINE:", + [":PATH:", "src/components/**"], + ":BLANK_LINE:", + [":PATH:", "src/stores/**"], + ":BLANK_LINE:", + [":PATH:", "src/**", "src/stores/**", "src/components/**"], + ":BLANK_LINE:", + "@fortawesome/fontawesome-svg-core", + "@fortawesome/*" + ] + } + } + } + } + } +} diff --git a/build/check-versions.mjs b/build/check-versions.mjs index 73c1eeb15..8c5968a30 100644 --- a/build/check-versions.mjs +++ b/build/check-versions.mjs @@ -1,5 +1,5 @@ -import semver from 'semver' import chalk from 'chalk' +import semver from 'semver' import packageConfig from '../package.json' with { type: 'json' } @@ -7,8 +7,8 @@ var versionRequirements = [ { name: 'node', currentVersion: semver.clean(process.version), - versionRequirement: packageConfig.engines.node - } + versionRequirement: packageConfig.engines.node, + }, ] export default function () { @@ -16,15 +16,22 @@ export default function () { for (let i = 0; i < versionRequirements.length; i++) { const mod = versionRequirements[i] if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) { - warnings.push(mod.name + ': ' + - chalk.red(mod.currentVersion) + ' should be ' + - chalk.green(mod.versionRequirement) + warnings.push( + mod.name + + ': ' + + chalk.red(mod.currentVersion) + + ' should be ' + + chalk.green(mod.versionRequirement), ) } } if (warnings.length) { - console.warn(chalk.yellow('\nTo use this template, you must update following to modules:\n')) + console.warn( + chalk.yellow( + '\nTo use this template, you must update following to modules:\n', + ), + ) for (let i = 0; i < warnings.length; i++) { const warning = warnings[i] console.warn(' ' + warning) diff --git a/build/commit_hash.js b/build/commit_hash.js index c104af5d9..c60355804 100644 --- a/build/commit_hash.js +++ b/build/commit_hash.js @@ -1,8 +1,8 @@ import childProcess from 'child_process' -export const getCommitHash = (() => { - const subst = "$Format:%h$" - if(!subst.match(/Format:/)) { +export const getCommitHash = () => { + const subst = '$Format:%h$' + if (!subst.match(/Format:/)) { return subst } else { try { @@ -15,4 +15,4 @@ export const getCommitHash = (() => { return 'UNKNOWN' } } -}) +} diff --git a/build/copy_plugin.js b/build/copy_plugin.js index a783fe7ff..4f020f359 100644 --- a/build/copy_plugin.js +++ b/build/copy_plugin.js @@ -1,8 +1,8 @@ -import serveStatic from 'serve-static' -import { resolve } from 'node:path' import { cp } from 'node:fs/promises' +import { resolve } from 'node:path' +import serveStatic from 'serve-static' -const getPrefix = s => { +const getPrefix = (s) => { const padEnd = s.endsWith('/') ? s : s + '/' return padEnd.startsWith('/') ? padEnd : '/' + padEnd } @@ -13,28 +13,31 @@ const copyPlugin = ({ inUrl, inFs }) => { let copyTarget const handler = serveStatic(inFs) - return [{ - name: 'copy-plugin-serve', - apply: 'serve', - configureServer (server) { - server.middlewares.use(prefix, handler) - } - }, { - name: 'copy-plugin-build', - apply: 'build', - configResolved (config) { - copyTarget = resolve(config.root, config.build.outDir, subdir) + return [ + { + name: 'copy-plugin-serve', + apply: 'serve', + configureServer(server) { + server.middlewares.use(prefix, handler) + }, }, - closeBundle: { - order: 'post', - sequential: true, - async handler () { - console.log(`Copying '${inFs}' to ${copyTarget}...`) - await cp(inFs, copyTarget, { recursive: true }) - console.log('Done.') - } - } - }] + { + name: 'copy-plugin-build', + apply: 'build', + configResolved(config) { + copyTarget = resolve(config.root, config.build.outDir, subdir) + }, + closeBundle: { + order: 'post', + sequential: true, + async handler() { + console.info(`Copying '${inFs}' to ${copyTarget}...`) + await cp(inFs, copyTarget, { recursive: true }) + console.info('Done.') + }, + }, + }, + ] } export default copyPlugin diff --git a/build/emojis_plugin.js b/build/emojis_plugin.js index aed52066d..9872f5331 100644 --- a/build/emojis_plugin.js +++ b/build/emojis_plugin.js @@ -1,21 +1,23 @@ -import { resolve } from 'node:path' import { access } from 'node:fs/promises' -import { languages, langCodeToCldrName } from '../src/i18n/languages.js' +import { resolve } from 'node:path' + +import { languages } from '../src/i18n/languages.js' const annotationsImportPrefix = '@kazvmoe-infra/unicode-emoji-json/annotations/' const specialAnnotationsLocale = { - ja_easy: 'ja' + ja_easy: 'ja', } -const internalToAnnotationsLocale = (internal) => specialAnnotationsLocale[internal] || internal +const internalToAnnotationsLocale = (internal) => + specialAnnotationsLocale[internal] || internal // This gets all the annotations that are accessible (whose language // can be chosen in the settings). Data for other languages are // discarded because there is no way for it to be fetched. const getAllAccessibleAnnotations = async (projectRoot) => { - const imports = (await Promise.all( - languages - .map(async lang => { + const imports = ( + await Promise.all( + languages.map(async (lang) => { const destLang = internalToAnnotationsLocale(lang) const importModule = `${annotationsImportPrefix}${destLang}.json` const importFile = resolve(projectRoot, 'node_modules', importModule) @@ -23,11 +25,18 @@ const getAllAccessibleAnnotations = async (projectRoot) => { await access(importFile) return `'${lang}': () => import('${importModule}')` } catch (e) { + if (e.message.match(/ENOENT/)) { + console.warn(`Missing emoji annotations locale: ${destLang}`) + } else { + console.error('test', e.message) + } return } - }))) - .filter(k => k) - .join(',\n') + }), + ) + ) + .filter((k) => k) + .join(',\n') return ` export const annotationsLoader = { @@ -43,21 +52,21 @@ const emojisPlugin = () => { let projectRoot return { name: 'emojis-plugin', - configResolved (conf) { + configResolved(conf) { projectRoot = conf.root }, - resolveId (id) { + resolveId(id) { if (id === emojiAnnotationsId) { return emojiAnnotationsIdResolved } return null }, - async load (id) { + async load(id) { if (id === emojiAnnotationsIdResolved) { return await getAllAccessibleAnnotations(projectRoot) } return null - } + }, } } diff --git a/build/msw_plugin.js b/build/msw_plugin.js index f544348fc..c4e9098c5 100644 --- a/build/msw_plugin.js +++ b/build/msw_plugin.js @@ -1,5 +1,5 @@ -import { resolve } from 'node:path' import { readFile } from 'node:fs/promises' +import { resolve } from 'node:path' const target = 'node_modules/msw/lib/mockServiceWorker.js' @@ -8,10 +8,10 @@ const mswPlugin = () => { return { name: 'msw-plugin', apply: 'serve', - configResolved (conf) { + configResolved(conf) { projectRoot = conf.root }, - configureServer (server) { + configureServer(server) { server.middlewares.use(async (req, res, next) => { if (req.path === '/mockServiceWorker.js') { const file = await readFile(resolve(projectRoot, target)) @@ -21,7 +21,7 @@ const mswPlugin = () => { next() } }) - } + }, } } diff --git a/build/service_worker_messages.js b/build/service_worker_messages.js index c078e8563..0948aa919 100644 --- a/build/service_worker_messages.js +++ b/build/service_worker_messages.js @@ -1,11 +1,12 @@ -import { languages, langCodeToJsonName } from '../src/i18n/languages.js' import { readFile } from 'node:fs/promises' import { dirname, resolve } from 'node:path' import { fileURLToPath } from 'node:url' +import { langCodeToJsonName, languages } from '../src/i18n/languages.js' + const i18nDir = resolve( dirname(dirname(fileURLToPath(import.meta.url))), - 'src/i18n' + 'src/i18n', ) export const i18nFiles = languages.reduce((acc, lang) => { @@ -16,13 +17,15 @@ export const i18nFiles = languages.reduce((acc, lang) => { }, {}) export const generateServiceWorkerMessages = async () => { - const msgArray = await Promise.all(Object.entries(i18nFiles).map(async ([lang, file]) => { - const fileContent = await readFile(file, 'utf-8') - const msg = { - notifications: JSON.parse(fileContent).notifications || {} - } - return [lang, msg] - })) + const msgArray = await Promise.all( + Object.entries(i18nFiles).map(async ([lang, file]) => { + const fileContent = await readFile(file, 'utf-8') + const msg = { + notifications: JSON.parse(fileContent).notifications || {}, + } + return [lang, msg] + }), + ) return msgArray.reduce((acc, [lang, msg]) => { acc[lang] = msg return acc diff --git a/build/sw_plugin.js b/build/sw_plugin.js index a2c792b7d..03c5978d7 100644 --- a/build/sw_plugin.js +++ b/build/sw_plugin.js @@ -1,9 +1,13 @@ -import { fileURLToPath } from 'node:url' -import { dirname, resolve } from 'node:path' import { readFile } from 'node:fs/promises' -import { build } from 'vite' +import { dirname, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' import * as esbuild from 'esbuild' -import { generateServiceWorkerMessages, i18nFiles } from './service_worker_messages.js' +import { build } from 'vite' + +import { + generateServiceWorkerMessages, + i18nFiles, +} from './service_worker_messages.js' const getSWMessagesAsText = async () => { const messages = await generateServiceWorkerMessages() @@ -14,14 +18,10 @@ const projectRoot = dirname(dirname(fileURLToPath(import.meta.url))) const swEnvName = 'virtual:pleroma-fe/service_worker_env' const swEnvNameResolved = '\0' + swEnvName const getDevSwEnv = () => `self.serviceWorkerOption = { assets: [] };` -const getProdSwEnv = ({ assets }) => `self.serviceWorkerOption = { assets: ${JSON.stringify(assets)} };` +const getProdSwEnv = ({ assets }) => + `self.serviceWorkerOption = { assets: ${JSON.stringify(assets)} };` -export const devSwPlugin = ({ - swSrc, - swDest, - transformSW, - alias -}) => { +export const devSwPlugin = ({ swSrc, swDest, transformSW, alias }) => { const swFullSrc = resolve(projectRoot, swSrc) const esbuildAlias = {} Object.entries(alias).forEach(([source, dest]) => { @@ -31,9 +31,10 @@ export const devSwPlugin = ({ return { name: 'dev-sw-plugin', apply: 'serve', - configResolved (conf) { + configResolved() { + /* no-op */ }, - resolveId (id) { + resolveId(id) { const name = id.startsWith('/') ? id.slice(1) : id if (name === swDest) { return swFullSrc @@ -42,7 +43,7 @@ export const devSwPlugin = ({ } return null }, - async load (id) { + async load(id) { if (id === swFullSrc) { return readFile(swFullSrc, 'utf-8') } else if (id === swEnvNameResolved) { @@ -55,7 +56,7 @@ export const devSwPlugin = ({ * during dev, and firefox does not support ESM as service worker * https://bugzilla.mozilla.org/show_bug.cgi?id=1360870 */ - async transform (code, id) { + async transform(code, id) { if (id === swFullSrc && transformSW) { const res = await esbuild.build({ entryPoints: [swSrc], @@ -63,52 +64,54 @@ export const devSwPlugin = ({ write: false, outfile: 'sw-pleroma.js', alias: esbuildAlias, - plugins: [{ - name: 'vite-like-root-resolve', - setup (b) { - b.onResolve( - { filter: new RegExp(/^\//) }, - args => ({ - path: resolve(projectRoot, args.path.slice(1)) - }) - ) - } - }, { - name: 'sw-messages', - setup (b) { - b.onResolve( - { filter: new RegExp('^' + swMessagesName + '$') }, - args => ({ - path: args.path, - namespace: 'sw-messages' + plugins: [ + { + name: 'vite-like-root-resolve', + setup(b) { + b.onResolve({ filter: new RegExp(/^\//) }, (args) => ({ + path: resolve(projectRoot, args.path.slice(1)), })) - b.onLoad( - { filter: /.*/, namespace: 'sw-messages' }, - async () => ({ - contents: await getSWMessagesAsText() + }, + }, + { + name: 'sw-messages', + setup(b) { + b.onResolve( + { filter: new RegExp('^' + swMessagesName + '$') }, + (args) => ({ + path: args.path, + namespace: 'sw-messages', + }), + ) + b.onLoad( + { filter: /.*/, namespace: 'sw-messages' }, + async () => ({ + contents: await getSWMessagesAsText(), + }), + ) + }, + }, + { + name: 'sw-env', + setup(b) { + b.onResolve( + { filter: new RegExp('^' + swEnvName + '$') }, + (args) => ({ + path: args.path, + namespace: 'sw-env', + }), + ) + b.onLoad({ filter: /.*/, namespace: 'sw-env' }, () => ({ + contents: getDevSwEnv(), })) - } - }, { - name: 'sw-env', - setup (b) { - b.onResolve( - { filter: new RegExp('^' + swEnvName + '$') }, - args => ({ - path: args.path, - namespace: 'sw-env' - })) - b.onLoad( - { filter: /.*/, namespace: 'sw-env' }, - () => ({ - contents: getDevSwEnv() - })) - } - }] + }, + }, + ], }) const text = res.outputFiles[0].text return text } - } + }, } } @@ -118,16 +121,13 @@ export const devSwPlugin = ({ // however, we must compile the service worker to iife because of browser support. // Run another vite build just for the service worker targeting iife at // the end of the build. -export const buildSwPlugin = ({ - swSrc, - swDest, -}) => { +export const buildSwPlugin = ({ swSrc, swDest }) => { let config return { name: 'build-sw-plugin', enforce: 'post', apply: 'build', - configResolved (resolvedConfig) { + configResolved(resolvedConfig) { config = { define: resolvedConfig.define, resolve: resolvedConfig.resolve, @@ -138,50 +138,50 @@ export const buildSwPlugin = ({ lib: { entry: swSrc, formats: ['iife'], - name: 'sw_pleroma' + name: 'sw_pleroma', }, emptyOutDir: false, rollupOptions: { output: { - entryFileNames: swDest - } - } + entryFileNames: swDest, + }, + }, }, - configFile: false + configFile: false, } }, generateBundle: { order: 'post', sequential: true, - async handler (_, bundle) { + async handler(_, bundle) { const assets = Object.keys(bundle) - .filter(name => !/\.map$/.test(name)) - .map(name => '/' + name) + .filter((name) => !/\.map$/.test(name)) + .map((name) => '/' + name) config.plugins.push({ name: 'build-sw-env-plugin', - resolveId (id) { + resolveId(id) { if (id === swEnvName) { return swEnvNameResolved } return null }, - load (id) { + load(id) { if (id === swEnvNameResolved) { return getProdSwEnv({ assets }) } return null - } + }, }) - } + }, }, closeBundle: { order: 'post', sequential: true, - async handler () { - console.log('Building service worker for production') + async handler() { + console.info('Building service worker for production') await build(config) - } - } + }, + }, } } @@ -191,9 +191,9 @@ const swMessagesNameResolved = '\0' + swMessagesName export const swMessagesPlugin = () => { return { name: 'sw-messages-plugin', - resolveId (id) { + resolveId(id) { if (id === swMessagesName) { - Object.values(i18nFiles).forEach(f => { + Object.values(i18nFiles).forEach((f) => { this.addWatchFile(f) }) return swMessagesNameResolved @@ -201,11 +201,11 @@ export const swMessagesPlugin = () => { return null } }, - async load (id) { + async load(id) { if (id === swMessagesNameResolved) { return await getSWMessagesAsText() } return null - } + }, } } diff --git a/build/update-emoji.js b/build/update-emoji.js index 5d578ba61..4ff7e1de8 100644 --- a/build/update-emoji.js +++ b/build/update-emoji.js @@ -1,22 +1,21 @@ - -import emojis from '@kazvmoe-infra/unicode-emoji-json/data-by-group.json' with { type: 'json' } +import emojis from '@kazvmoe-infra/unicode-emoji-json/data-by-group.json' with { + type: 'json', +} import fs from 'fs' -Object.keys(emojis) - .map(k => { - emojis[k].map(e => { - delete e.unicode_version - delete e.emoji_version - delete e.skin_tone_support_unicode_version - }) +Object.keys(emojis).map((k) => { + emojis[k].map((e) => { + delete e.unicode_version + delete e.emoji_version + delete e.skin_tone_support_unicode_version }) +}) const res = {} -Object.keys(emojis) - .map(k => { - const groupId = k.replace('&', 'and').replace(/ /g, '-').toLowerCase() - res[groupId] = emojis[k] - }) +Object.keys(emojis).map((k) => { + const groupId = k.replace('&', 'and').replace(/ /g, '-').toLowerCase() + res[groupId] = emojis[k] +}) console.info('Updating emojis...') fs.writeFileSync('src/assets/emoji.json', JSON.stringify(res)) diff --git a/changelog.d/action-button-extra-counter.add b/changelog.d/action-button-extra-counter.add deleted file mode 100644 index 7d5c77447..000000000 --- a/changelog.d/action-button-extra-counter.add +++ /dev/null @@ -1 +0,0 @@ -Display counter for status action buttons when they are on the menu diff --git a/changelog.d/akkoma-sharkey-net-support.add b/changelog.d/akkoma-sharkey-net-support.add deleted file mode 100644 index 4b4bff7fe..000000000 --- a/changelog.d/akkoma-sharkey-net-support.add +++ /dev/null @@ -1 +0,0 @@ -Added support for Akkoma and IceShrimp.NET backend diff --git a/changelog.d/arithmetic-blend.add b/changelog.d/arithmetic-blend.add deleted file mode 100644 index c579dca28..000000000 --- a/changelog.d/arithmetic-blend.add +++ /dev/null @@ -1,2 +0,0 @@ -Add arithmetic blend ISS function - diff --git a/changelog.d/attrs-parsing.fix b/changelog.d/attrs-parsing.fix new file mode 100644 index 000000000..e36e59a86 --- /dev/null +++ b/changelog.d/attrs-parsing.fix @@ -0,0 +1 @@ +Fix HTML attribute parsing for escaped quotes \ No newline at end of file diff --git a/changelog.d/better-scroll-button.add b/changelog.d/better-scroll-button.add deleted file mode 100644 index b206869d1..000000000 --- a/changelog.d/better-scroll-button.add +++ /dev/null @@ -1 +0,0 @@ -Add support for detachable scrollTop button diff --git a/changelog.d/bookmark-button-align.fix b/changelog.d/bookmark-button-align.fix deleted file mode 100644 index 64bc2c807..000000000 --- a/changelog.d/bookmark-button-align.fix +++ /dev/null @@ -1 +0,0 @@ -Fix bookmark button alignment in the extra actions menu diff --git a/changelog.d/csp.add b/changelog.d/csp.add deleted file mode 100644 index 260337b97..000000000 --- a/changelog.d/csp.add +++ /dev/null @@ -1 +0,0 @@ -Compatibility with stricter CSP (Akkoma backend) diff --git a/changelog.d/filter-fixes.skip b/changelog.d/filter-fixes.skip deleted file mode 100644 index e69de29bb..000000000 diff --git a/changelog.d/fix-emojis-breaking-bio.fix b/changelog.d/fix-emojis-breaking-bio.fix new file mode 100644 index 000000000..62a607d8a --- /dev/null +++ b/changelog.d/fix-emojis-breaking-bio.fix @@ -0,0 +1 @@ +Fix emojis breaking user bio/description editing diff --git a/changelog.d/fix-wrap.skip b/changelog.d/fix-wrap.skip deleted file mode 100644 index e69de29bb..000000000 diff --git a/changelog.d/akkoma.skip b/changelog.d/instance-store-migration.skip similarity index 100% rename from changelog.d/akkoma.skip rename to changelog.d/instance-store-migration.skip diff --git a/changelog.d/migrate-auth-flow-pinia.skip b/changelog.d/migrate-auth-flow-pinia.skip deleted file mode 100644 index e69de29bb..000000000 diff --git a/changelog.d/migrate-oauth-tokens-module-to-pinia-store.skip b/changelog.d/migrate-oauth-tokens-module-to-pinia-store.skip deleted file mode 100644 index e69de29bb..000000000 diff --git a/changelog.d/mutes-sync.add b/changelog.d/mutes-sync.add deleted file mode 100644 index e8e0e462a..000000000 --- a/changelog.d/mutes-sync.add +++ /dev/null @@ -1 +0,0 @@ -Synchronized mutes, advanced mute control (regexp, expiry, naming) diff --git a/changelog.d/profile-error.fix b/changelog.d/profile-error.fix deleted file mode 100644 index f123db5ae..000000000 --- a/changelog.d/profile-error.fix +++ /dev/null @@ -1 +0,0 @@ -Fix error styling for user profiles diff --git a/changelog.d/small-fixes.skip b/changelog.d/small-fixes.skip deleted file mode 100644 index e69de29bb..000000000 diff --git a/changelog.d/sw-cache-assets.add b/changelog.d/sw-cache-assets.add deleted file mode 100644 index 5f7414eee..000000000 --- a/changelog.d/sw-cache-assets.add +++ /dev/null @@ -1 +0,0 @@ -Cache assets and emojis with service worker diff --git a/changelog.d/theme3-body-class.add b/changelog.d/theme3-body-class.add deleted file mode 100644 index f3d36fd70..000000000 --- a/changelog.d/theme3-body-class.add +++ /dev/null @@ -1 +0,0 @@ -Indicate currently active V3 theme as a body element class diff --git a/changelog.d/unify-show-hide-buttons.add b/changelog.d/unify-show-hide-buttons.add deleted file mode 100644 index 663bc38a5..000000000 --- a/changelog.d/unify-show-hide-buttons.add +++ /dev/null @@ -1 +0,0 @@ -Unify show/hide content buttons diff --git a/docker-compose.e2e.yml b/docker-compose.e2e.yml new file mode 100644 index 000000000..75a4979a1 --- /dev/null +++ b/docker-compose.e2e.yml @@ -0,0 +1,57 @@ +services: + db: + image: postgres:15-alpine + environment: + POSTGRES_USER: pleroma + POSTGRES_PASSWORD: pleroma + POSTGRES_DB: pleroma + healthcheck: + test: ["CMD-SHELL", "pg_isready -U pleroma -d pleroma"] + interval: 2s + timeout: 2s + retries: 30 + + pleroma: + image: ${PLEROMA_IMAGE:-git.pleroma.social:5050/pleroma/pleroma:stable} + environment: + DB_USER: pleroma + DB_PASS: pleroma + DB_NAME: pleroma + DB_HOST: db + DB_PORT: 5432 + DOMAIN: localhost + INSTANCE_NAME: Pleroma E2E + ADMIN_EMAIL: ${E2E_ADMIN_EMAIL:-admin@example.com} + NOTIFY_EMAIL: ${E2E_ADMIN_EMAIL:-admin@example.com} + E2E_ADMIN_USERNAME: ${E2E_ADMIN_USERNAME:-admin} + E2E_ADMIN_PASSWORD: ${E2E_ADMIN_PASSWORD:-adminadmin} + E2E_ADMIN_EMAIL: ${E2E_ADMIN_EMAIL:-admin@example.com} + depends_on: + db: + condition: service_healthy + volumes: + - ./docker/pleroma/entrypoint.e2e.sh:/opt/pleroma/entrypoint.e2e.sh:ro + entrypoint: ["/bin/ash", "/opt/pleroma/entrypoint.e2e.sh"] + healthcheck: + # NOTE: "localhost" may resolve to ::1 in some images (IPv6) while Pleroma only + # listens on IPv4 in this container. Use 127.0.0.1 to avoid false negatives. + test: ["CMD-SHELL", "test -f /var/lib/pleroma/.e2e_seeded && wget -qO- http://127.0.0.1:4000/api/v1/instance >/dev/null || exit 1"] + interval: 5s + timeout: 3s + retries: 60 + + e2e: + build: + context: . + dockerfile: docker/e2e/Dockerfile.e2e + depends_on: + pleroma: + condition: service_healthy + environment: + CI: "1" + VITE_PROXY_TARGET: http://pleroma:4000 + VITE_PROXY_ORIGIN: http://localhost:4000 + E2E_BASE_URL: http://localhost:8080 + E2E_ADMIN_USERNAME: ${E2E_ADMIN_USERNAME:-admin} + E2E_ADMIN_PASSWORD: ${E2E_ADMIN_PASSWORD:-adminadmin} + command: ["yarn", "e2e:pw"] diff --git a/docker/e2e/Dockerfile.e2e b/docker/e2e/Dockerfile.e2e new file mode 100644 index 000000000..e84359ceb --- /dev/null +++ b/docker/e2e/Dockerfile.e2e @@ -0,0 +1,16 @@ +FROM mcr.microsoft.com/playwright:v1.57.0-jammy + +WORKDIR /app + +ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 + +RUN npm install -g yarn@1.22.22 + +COPY package.json yarn.lock ./ +RUN yarn --frozen-lockfile + +COPY . . + +ENV CI=1 + +CMD ["yarn", "e2e:pw"] diff --git a/docker/pleroma/entrypoint.e2e.sh b/docker/pleroma/entrypoint.e2e.sh new file mode 100644 index 000000000..96920eeae --- /dev/null +++ b/docker/pleroma/entrypoint.e2e.sh @@ -0,0 +1,71 @@ +#!/bin/ash + +set -eu + +SEED_SENTINEL_PATH="/var/lib/pleroma/.e2e_seeded" +CONFIG_OVERRIDE_PATH="/var/lib/pleroma/config.exs" + +echo "-- Waiting for database..." +while ! pg_isready -U "${DB_USER:-pleroma}" -d "postgres://${DB_HOST:-db}:${DB_PORT:-5432}/${DB_NAME:-pleroma}" -t 1; do + sleep 1s +done + +echo "-- Writing E2E config overrides..." +cat > "$CONFIG_OVERRIDE_PATH" <<'EOF' +import Config + +config :pleroma, Pleroma.Captcha, + enabled: false + +config :pleroma, :instance, + registrations_open: true, + account_activation_required: false, + approval_required: false +EOF + +echo "-- Running migrations..." +/opt/pleroma/bin/pleroma_ctl migrate + +echo "-- Starting!" +/opt/pleroma/bin/pleroma start & +PLEROMA_PID="$!" + +cleanup() { + if [ -n "${PLEROMA_PID:-}" ] && kill -0 "$PLEROMA_PID" 2>/dev/null; then + kill -TERM "$PLEROMA_PID" + wait "$PLEROMA_PID" || true + fi +} + +trap cleanup INT TERM + +echo "-- Waiting for API..." +api_ok="false" +for _i in $(seq 1 120); do + if wget -qO- http://127.0.0.1:4000/api/v1/instance >/dev/null 2>&1; then + api_ok="true" + break + fi + sleep 1s +done + +if [ "$api_ok" != "true" ]; then + echo "Timed out waiting for Pleroma API to become available" + exit 1 +fi + +if [ ! -f "$SEED_SENTINEL_PATH" ]; then + if [ -n "${E2E_ADMIN_USERNAME:-}" ] && [ -n "${E2E_ADMIN_PASSWORD:-}" ] && [ -n "${E2E_ADMIN_EMAIL:-}" ]; then + echo "-- Seeding admin user (${E2E_ADMIN_USERNAME})..." + if ! /opt/pleroma/bin/pleroma_ctl user new "$E2E_ADMIN_USERNAME" "$E2E_ADMIN_EMAIL" --admin --password "$E2E_ADMIN_PASSWORD" -y; then + echo "-- User already exists (or creation failed), ensuring admin + confirmed..." + /opt/pleroma/bin/pleroma_ctl user set "$E2E_ADMIN_USERNAME" --admin --confirmed + fi + else + echo "-- Skipping admin seeding (missing E2E_ADMIN_* env)" + fi + + touch "$SEED_SENTINEL_PATH" +fi + +wait "$PLEROMA_PID" diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index dfc5f9dc3..8ca076931 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -7,9 +7,9 @@ PleromaFE gets its configuration from several sources, in order of preference (the one above overrides ones below it) -1. `/api/statusnet/config.json` - this is generated on Backend and contains multiple things including instance name, char limit etc. It also contains FE/Client-specific data, PleromaFE uses `pleromafe` field of it. For more info on changing config on BE, look [here](../backend/configuration/cheatsheet.md#frontend_configurations) -2. `/static/config.json` - this is a static FE-provided file, containing only FE specific configuration. This file is completely optional and could be removed but is useful as a fallback if some configuration JSON property isn't present in BE-provided config. It's also a reference point to check what default configuration are and what JSON properties even exist. In local dev mode it could be used to override BE configuration, more about that in HACKING.md. File is located [here](https://git.pleroma.social/pleroma/pleroma-fe/blob/develop/static/config.json). -3. Built-in defaults. Those are hard-coded defaults that are used when `/static/config.json` is not available and BE-provided configuration JSON is missing some JSON properties. ( [Code](https://git.pleroma.social/pleroma/pleroma-fe/blob/develop/src/modules/instance.js) ) +1. `/api/pleroma/frontend_configurations` - this is generated by backend and includes FE/Client-specific data. PleromaFE uses the `pleroma_fe` field of it. For more info on changing config on BE, look [here](../backend/configuration/cheatsheet.md#frontend_configurations) +2. `/static/config.json` - this is a static FE-provided file, containing only FE specific configuration. This file is completely optional and could be removed but is useful as a fallback if some configuration JSON property isn't present in BE-provided config. It's also a reference point to check what default configuration are and what JSON properties even exist. In local dev mode it could be used to override BE configuration, more about that in HACKING.md. File is located [here](https://git.pleroma.social/pleroma/pleroma-fe/src/public/static/config.json). +3. Built-in defaults. Those are hard-coded defaults that are used when `/static/config.json` is not available and BE-provided configuration JSON is missing some JSON properties. ( [Code](https://git.pleroma.social/pleroma/pleroma-fe/src/src/stores/instance.js) ) ## Instance-defaults diff --git a/docs/HACKING.md b/docs/HACKING.md index a5c491136..88760b77a 100644 --- a/docs/HACKING.md +++ b/docs/HACKING.md @@ -79,7 +79,7 @@ server { In 99% cases PleromaFE uses [MastoAPI](https://docs.joinmastodon.org/api/) with [Pleroma Extensions](../backend/API/differences_in_mastoapi_responses.md) to fetch the data. The rest is either QvitterAPI leftovers or pleroma-exclusive APIs. QvitterAPI doesn't exactly have documentation and uses different JSON structure and sometimes different parameters and workflows, [this](https://twitter-api.readthedocs.io/en/latest/index.html) could be a good reference though. Some pleroma-exclusive API may still be using QvitterAPI JSON structure. -PleromaFE supports both formats by transforming them into internal format which is basically QvitterAPI one with some additions and renaming. All data is passed trough [Entity Normalizer](https://git.pleroma.social/pleroma/pleroma-fe/-/blob/develop/src/services/entity_normalizer/entity_normalizer.service.js) which can serve as a reference of API and what's actually used, it's also a host for all the hacks and data transformation. +PleromaFE supports both formats by transforming them into internal format which is basically QvitterAPI one with some additions and renaming. All data is passed trough [Entity Normalizer](https://git.pleroma.social/pleroma/pleroma-fe/src/src/services/entity_normalizer/entity_normalizer.service.js) which can serve as a reference of API and what's actually used, it's also a host for all the hacks and data transformation. For most part, PleromaFE tries to store all the info it can get in global vuex store - every user and post are passed trough updating mechanism where data is either added or merged with existing data, reactively updating the information throughout UI, so if in newest request user's post counter increased, it will be instantly updated in open user profile cards. This is also used to find users, posts and sometimes to build timelines and/or request parameters. diff --git a/eslint.config.mjs b/eslint.config.mjs index 01bdb2038..417ff8cf3 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -1,37 +1,34 @@ -import vue from "eslint-plugin-vue"; -import js from "@eslint/js"; -import globals from "globals"; +import js from '@eslint/js' +import { defineConfig, globalIgnores } from 'eslint/config' +import vue from 'eslint-plugin-vue' +import globals from 'globals' - -export default [ +export default defineConfig([ ...vue.configs['flat/recommended'], - js.configs.recommended, + globalIgnores(['**/*.js', 'build/', 'dist/', 'config/']), { - files: ["**/*.js", "**/*.mjs", "**/*.vue"], - ignores: ["build/*.js", "config/*.js"], - + files: ['src/**/*.vue'], + plugins: { js }, + extends: ['js/recommended'], languageOptions: { ecmaVersion: 2024, - sourceType: "module", + sourceType: 'module', parserOptions: { - parser: "@babel/eslint-parser", + parser: '@babel/eslint-parser', }, globals: { ...globals.browser, ...globals.vitest, ...globals.chai, ...globals.commonjs, - ...globals.serviceworker - } + ...globals.serviceworker, + }, }, rules: { - 'arrow-parens': 0, - 'generator-star-spacing': 0, - 'no-debugger': 0, 'vue/require-prop-types': 0, 'vue/multi-word-component-names': 0, - } - } -] + }, + }, +]) diff --git a/index.html b/index.html index 96c20c4b7..26eeee19b 100644 --- a/index.html +++ b/index.html @@ -11,14 +11,12 @@ - - - + -
+
- { return null } if (!staticInitialResults) { - staticInitialResults = JSON.parse(document.getElementById('initial-results').textContent) + staticInitialResults = JSON.parse( + document.getElementById('initial-results').textContent, + ) } return staticInitialResults } @@ -54,7 +75,7 @@ const preloadFetch = async (request) => { return { ok: true, json: () => requestData, - text: () => requestData + text: () => requestData, } } @@ -63,20 +84,38 @@ const getInstanceConfig = async ({ store }) => { const res = await preloadFetch('/api/v1/instance') if (res.ok) { const data = await res.json() - const textlimit = data.max_toot_chars + const textLimit = data.max_toot_chars const vapidPublicKey = data.pleroma.vapid_public_key - store.dispatch('setInstanceOption', { name: 'pleromaExtensionsAvailable', value: data.pleroma }) - store.dispatch('setInstanceOption', { name: 'textlimit', value: textlimit }) - store.dispatch('setInstanceOption', { name: 'accountApprovalRequired', value: data.approval_required }) - store.dispatch('setInstanceOption', { name: 'birthdayRequired', value: !!data.pleroma?.metadata.birthday_required }) - store.dispatch('setInstanceOption', { name: 'birthdayMinAge', value: data.pleroma?.metadata.birthday_min_age || 0 }) + useInstanceCapabilitiesStore().set( + 'pleromaExtensionsAvailable', + data.pleroma, + ) + useInstanceStore().set({ + path: 'limits.textLimit', + value: textLimit, + }) + useInstanceStore().set({ + path: 'accountApprovalRequired', + value: data.approval_required, + }) + useInstanceStore().set({ + path: 'birthdayRequired', + value: !!data.pleroma?.metadata.birthday_required, + }) + useInstanceStore().set({ + path: 'birthdayMinAge', + value: data.pleroma?.metadata.birthday_min_age || 0, + }) if (vapidPublicKey) { - store.dispatch('setInstanceOption', { name: 'vapidPublicKey', value: vapidPublicKey }) + useInstanceStore().set({ + path: 'vapidPublicKey', + value: vapidPublicKey, + }) } } else { - throw (res) + throw res } } catch (error) { console.error('Could not load instance config, potentially fatal') @@ -93,10 +132,12 @@ const getBackendProvidedConfig = async () => { const data = await res.json() return data.pleroma_fe } else { - throw (res) + throw res } } catch (error) { - console.error('Could not load backend-provided frontend config, potentially fatal') + console.error( + 'Could not load backend-provided frontend config, potentially fatal', + ) console.error(error) } } @@ -107,7 +148,7 @@ const getStaticConfig = async () => { if (res.ok) { return res.json() } else { - throw (res) + throw res } } catch (error) { console.warn('Failed to load static/config.json, continuing without it.') @@ -129,51 +170,21 @@ const setSettings = async ({ apiConfig, staticConfig, store }) => { config = Object.assign({}, staticConfig, apiConfig) } - const copyInstanceOption = (name) => { - store.dispatch('setInstanceOption', { name, value: config[name] }) - } + Object.keys(INSTANCE_IDENTITY_DEFAULT_DEFINITIONS).forEach((source) => + useInstanceStore().set({ + value: config[source], + path: `instanceIdentity.${source}`, + }), + ) - copyInstanceOption('theme') - copyInstanceOption('style') - copyInstanceOption('palette') - copyInstanceOption('embeddedToS') - copyInstanceOption('nsfwCensorImage') - copyInstanceOption('background') - copyInstanceOption('hidePostStats') - copyInstanceOption('hideBotIndication') - copyInstanceOption('hideUserStats') - copyInstanceOption('hideFilteredStatuses') - copyInstanceOption('logo') + Object.keys(INSTANCE_DEFAULT_CONFIG_DEFINITIONS).forEach((source) => + useInstanceStore().set({ + value: config[source], + path: `prefsStorage.${source}`, + }), + ) - store.dispatch('setInstanceOption', { - name: 'logoMask', - value: typeof config.logoMask === 'undefined' - ? true - : config.logoMask - }) - - store.dispatch('setInstanceOption', { - name: 'logoMargin', - value: typeof config.logoMargin === 'undefined' - ? 0 - : config.logoMargin - }) - copyInstanceOption('logoLeft') useAuthFlowStore().setInitialStrategy(config.loginMethod) - - copyInstanceOption('redirectRootNoLogin') - copyInstanceOption('redirectRootLogin') - copyInstanceOption('showInstanceSpecificPanel') - copyInstanceOption('minimalScopesMode') - copyInstanceOption('hideMutedPosts') - copyInstanceOption('collapseMessageWithSubject') - copyInstanceOption('scopeCopy') - copyInstanceOption('subjectLineBehavior') - copyInstanceOption('postContentType') - copyInstanceOption('alwaysShowSubjectInput') - copyInstanceOption('showFeaturesPanel') - copyInstanceOption('hideSitename') - copyInstanceOption('sidebarRight') } const getTOS = async ({ store }) => { @@ -181,9 +192,9 @@ const getTOS = async ({ store }) => { const res = await window.fetch('/static/terms-of-service.html') if (res.ok) { const html = await res.text() - store.dispatch('setInstanceOption', { name: 'tos', value: html }) + useInstanceStore().set({ path: 'instanceIdentity.tos', value: html }) } else { - throw (res) + throw res } } catch (e) { console.warn("Can't load TOS\n", e) @@ -195,9 +206,12 @@ const getInstancePanel = async ({ store }) => { const res = await preloadFetch('/instance/panel.html') if (res.ok) { const html = await res.text() - store.dispatch('setInstanceOption', { name: 'instanceSpecificPanelContent', value: html }) + useInstanceStore().set({ + path: 'instanceIdentity.instanceSpecificPanelContent', + value: html, + }) } else { - throw (res) + throw res } } catch (e) { console.warn("Can't load instance panel\n", e) @@ -209,25 +223,27 @@ const getStickers = async ({ store }) => { const res = await window.fetch('/static/stickers.json') if (res.ok) { const values = await res.json() - const stickers = (await Promise.all( - Object.entries(values).map(async ([name, path]) => { - const resPack = await window.fetch(path + 'pack.json') - let meta = {} - if (resPack.ok) { - meta = await resPack.json() - } - return { - pack: name, - path, - meta - } - }) - )).sort((a, b) => { + const stickers = ( + await Promise.all( + Object.entries(values).map(async ([name, path]) => { + const resPack = await window.fetch(path + 'pack.json') + let meta = {} + if (resPack.ok) { + meta = await resPack.json() + } + return { + pack: name, + path, + meta, + } + }), + ) + ).sort((a, b) => { return a.meta.title.localeCompare(b.meta.title) }) - store.dispatch('setInstanceOption', { name: 'stickers', value: stickers }) + useEmojiStore().setStickers(stickers) } else { - throw (res) + throw res } } catch (e) { console.warn("Can't load stickers\n", e) @@ -237,13 +253,19 @@ const getStickers = async ({ store }) => { const getAppSecret = async ({ store }) => { const oauth = useOAuthStore() if (oauth.userToken) { - store.commit('setBackendInteractor', backendInteractorService(oauth.getToken)) + store.commit( + 'setBackendInteractor', + backendInteractorService(oauth.getToken), + ) } } const resolveStaffAccounts = ({ store, accounts }) => { - const nicknames = accounts.map(uri => uri.split('/').pop()) - store.dispatch('setInstanceOption', { name: 'staffAccounts', value: nicknames }) + const nicknames = accounts.map((uri) => uri.split('/').pop()) + useInstanceStore().set({ + path: 'staffAccounts', + value: nicknames, + }) } const getNodeInfo = async ({ store }) => { @@ -254,76 +276,165 @@ const getNodeInfo = async ({ store }) => { const data = await res.json() const metadata = data.metadata const features = metadata.features - store.dispatch('setInstanceOption', { name: 'name', value: metadata.nodeName }) - store.dispatch('setInstanceOption', { name: 'registrationOpen', value: data.openRegistrations }) - store.dispatch('setInstanceOption', { name: 'mediaProxyAvailable', value: features.includes('media_proxy') }) - store.dispatch('setInstanceOption', { name: 'safeDM', value: features.includes('safe_dm_mentions') }) - store.dispatch('setInstanceOption', { name: 'shoutAvailable', value: features.includes('chat') }) - store.dispatch('setInstanceOption', { name: 'pleromaChatMessagesAvailable', value: features.includes('pleroma_chat_messages') }) - store.dispatch('setInstanceOption', { - name: 'pleromaCustomEmojiReactionsAvailable', - value: - features.includes('pleroma_custom_emoji_reactions') || - features.includes('custom_emoji_reactions') + useInstanceStore().set({ + path: 'name', + value: metadata.nodeName, }) - store.dispatch('setInstanceOption', { name: 'pleromaBookmarkFoldersAvailable', value: features.includes('pleroma:bookmark_folders') }) - store.dispatch('setInstanceOption', { name: 'gopherAvailable', value: features.includes('gopher') }) - store.dispatch('setInstanceOption', { name: 'pollsAvailable', value: features.includes('polls') }) - store.dispatch('setInstanceOption', { name: 'editingAvailable', value: features.includes('editing') }) - store.dispatch('setInstanceOption', { name: 'pollLimits', value: metadata.pollLimits }) - store.dispatch('setInstanceOption', { name: 'mailerEnabled', value: metadata.mailerEnabled }) - store.dispatch('setInstanceOption', { name: 'quotingAvailable', value: features.includes('quote_posting') }) - store.dispatch('setInstanceOption', { name: 'groupActorAvailable', value: features.includes('pleroma:group_actors') }) - store.dispatch('setInstanceOption', { name: 'localBubbleInstances', value: metadata.localBubbleInstances ?? [] }) + useInstanceStore().set({ + path: 'registrationOpen', + value: data.openRegistrations, + }) + useInstanceCapabilitiesStore().set( + 'mediaProxyAvailable', + features.includes('media_proxy'), + ) + useInstanceCapabilitiesStore().set( + 'safeDM', + features.includes('safe_dm_mentions'), + ) + useInstanceCapabilitiesStore().set( + 'shoutAvailable', + features.includes('chat'), + ) + useInstanceCapabilitiesStore().set( + 'pleromaChatMessagesAvailable', + features.includes('pleroma_chat_messages'), + ) + useInstanceCapabilitiesStore().set( + 'pleromaCustomEmojiReactionsAvailable', + features.includes('pleroma_custom_emoji_reactions') || + features.includes('custom_emoji_reactions'), + ) + useInstanceCapabilitiesStore().set( + 'pleromaBookmarkFoldersAvailable', + features.includes('pleroma:bookmark_folders'), + ) + useInstanceCapabilitiesStore().set( + 'gopherAvailable', + features.includes('gopher'), + ) + useInstanceCapabilitiesStore().set( + 'pollsAvailable', + features.includes('polls'), + ) + useInstanceCapabilitiesStore().set( + 'editingAvailable', + features.includes('editing'), + ) + useInstanceCapabilitiesStore().set( + 'mailerEnabled', + metadata.mailerEnabled, + ) + useInstanceCapabilitiesStore().set( + 'quotingAvailable', + features.includes('quote_posting'), + ) + useInstanceCapabilitiesStore().set( + 'groupActorAvailable', + features.includes('pleroma:group_actors'), + ) + useInstanceCapabilitiesStore().set( + 'blockExpiration', + features.includes('pleroma:block_expiration'), + ) + useInstanceStore().set({ + path: 'localBubbleInstances', + value: metadata.localBubbleInstances ?? [], + }) + useInstanceCapabilitiesStore().set( + 'localBubble', + (metadata.localBubbleInstances ?? []).length > 0, + ) + + useInstanceStore().set({ + path: 'limits.pollLimits', + value: metadata.pollLimits, + }) const uploadLimits = metadata.uploadLimits - store.dispatch('setInstanceOption', { name: 'uploadlimit', value: parseInt(uploadLimits.general) }) - store.dispatch('setInstanceOption', { name: 'avatarlimit', value: parseInt(uploadLimits.avatar) }) - store.dispatch('setInstanceOption', { name: 'backgroundlimit', value: parseInt(uploadLimits.background) }) - store.dispatch('setInstanceOption', { name: 'bannerlimit', value: parseInt(uploadLimits.banner) }) - store.dispatch('setInstanceOption', { name: 'fieldsLimits', value: metadata.fieldsLimits }) + useInstanceStore().set({ + path: 'limits.uploadlimit', + value: parseInt(uploadLimits.general), + }) + useInstanceStore().set({ + path: 'limits.avatarlimit', + value: parseInt(uploadLimits.avatar), + }) + useInstanceStore().set({ + path: 'limits.backgroundlimit', + value: parseInt(uploadLimits.background), + }) + useInstanceStore().set({ + path: 'limits.bannerlimit', + value: parseInt(uploadLimits.banner), + }) + useInstanceStore().set({ + path: 'limits.fieldsLimits', + value: metadata.fieldsLimits, + }) - store.dispatch('setInstanceOption', { name: 'restrictedNicknames', value: metadata.restrictedNicknames }) - store.dispatch('setInstanceOption', { name: 'postFormats', value: metadata.postFormats }) + useInstanceStore().set({ + path: 'restrictedNicknames', + value: metadata.restrictedNicknames, + }) + useInstanceCapabilitiesStore().set('postFormats', metadata.postFormats) const suggestions = metadata.suggestions - store.dispatch('setInstanceOption', { name: 'suggestionsEnabled', value: suggestions.enabled }) - store.dispatch('setInstanceOption', { name: 'suggestionsWeb', value: suggestions.web }) + useInstanceCapabilitiesStore().set( + 'suggestionsEnabled', + suggestions.enabled, + ) + // this is unused, why? + useInstanceCapabilitiesStore().set('suggestionsWeb', suggestions.web) const software = data.software - store.dispatch('setInstanceOption', { name: 'backendVersion', value: software.version }) - store.dispatch('setInstanceOption', { name: 'backendRepository', value: software.repository }) + useInstanceStore().set({ + path: 'backendVersion', + value: software.version, + }) + useInstanceStore().set({ + path: 'backendRepository', + value: software.repository, + }) const priv = metadata.private - store.dispatch('setInstanceOption', { name: 'private', value: priv }) + useInstanceStore().set({ path: 'privateMode', value: priv }) const frontendVersion = window.___pleromafe_commit_hash - store.dispatch('setInstanceOption', { name: 'frontendVersion', value: frontendVersion }) + useInstanceStore().set({ + path: 'frontendVersion', + value: frontendVersion, + }) const federation = metadata.federation - store.dispatch('setInstanceOption', { - name: 'tagPolicyAvailable', - value: typeof federation.mrf_policies === 'undefined' + useInstanceCapabilitiesStore().set( + 'tagPolicyAvailable', + typeof federation.mrf_policies === 'undefined' ? false - : metadata.federation.mrf_policies.includes('TagPolicy') - }) + : metadata.federation.mrf_policies.includes('TagPolicy'), + ) - store.dispatch('setInstanceOption', { name: 'federationPolicy', value: federation }) - store.dispatch('setInstanceOption', { - name: 'federating', - value: typeof federation.enabled === 'undefined' - ? true - : federation.enabled + useInstanceStore().set({ + path: 'federationPolicy', + value: federation, + }) + useInstanceStore().set({ + path: 'federating', + value: + typeof federation.enabled === 'undefined' ? true : federation.enabled, }) const accountActivationRequired = metadata.accountActivationRequired - store.dispatch('setInstanceOption', { name: 'accountActivationRequired', value: accountActivationRequired }) + useInstanceStore().set({ + path: 'accountActivationRequired', + value: accountActivationRequired, + }) const accounts = metadata.staffAccounts resolveStaffAccounts({ store, accounts }) } else { - throw (res) + throw res } } catch (e) { console.warn('Could not load nodeinfo') @@ -333,7 +444,10 @@ const getNodeInfo = async ({ store }) => { const setConfig = async ({ store }) => { // apiConfig, staticConfig - const configInfos = await Promise.all([getBackendProvidedConfig({ store }), getStaticConfig()]) + const configInfos = await Promise.all([ + getBackendProvidedConfig({ store }), + getStaticConfig(), + ]) const apiConfig = configInfos[0] const staticConfig = configInfos[1] @@ -364,29 +478,37 @@ const afterStoreSetup = async ({ pinia, store, storageError, i18n }) => { if (process.env.NODE_ENV === 'development') { // do some checks to avoid common errors if (!Object.keys(allStores).length) { - throw new Error('No stores are available. Check the code in src/boot/after_store.js') + throw new Error( + 'No stores are available. Check the code in src/boot/after_store.js', + ) } } await Promise.all( - Object.entries(allStores) - .map(async ([name, mod]) => { - const isStoreName = name => name.startsWith('use') - if (process.env.NODE_ENV === 'development') { - if (Object.keys(mod).filter(isStoreName).length !== 1) { - throw new Error('Each store file must export exactly one store as a named export. Check your code in src/stores/') - } + Object.entries(allStores).map(async ([name, mod]) => { + const isStoreName = (name) => name.startsWith('use') + if (process.env.NODE_ENV === 'development') { + if (Object.keys(mod).filter(isStoreName).length !== 1) { + throw new Error( + 'Each store file must export exactly one store as a named export. Check your code in src/stores/', + ) } - const storeFuncName = Object.keys(mod).find(isStoreName) - if (storeFuncName && typeof mod[storeFuncName] === 'function') { - const p = mod[storeFuncName]().$persistLoaded - if (!(p instanceof Promise)) { - throw new Error(`${name} store's $persistLoaded is not a Promise. The persist plugin is not applied.`) - } - await p - } else { - throw new Error(`Store module ${name} does not export a 'use...' function`) + } + const storeFuncName = Object.keys(mod).find(isStoreName) + if (storeFuncName && typeof mod[storeFuncName] === 'function') { + const p = mod[storeFuncName]().$persistLoaded + if (!(p instanceof Promise)) { + throw new Error( + `${name} store's $persistLoaded is not a Promise. The persist plugin is not applied.`, + ) } - })) + await p + } else { + throw new Error( + `Store module ${name} does not export a 'use...' function`, + ) + } + }), + ) } try { @@ -397,11 +519,18 @@ const afterStoreSetup = async ({ pinia, store, storageError, i18n }) => { } if (storageError) { - useInterfaceStore().pushGlobalNotice({ messageKey: 'errors.storage_unavailable', level: 'error' }) + useInterfaceStore().pushGlobalNotice({ + messageKey: 'errors.storage_unavailable', + level: 'error', + }) } useInterfaceStore().setLayoutWidth(windowWidth()) useInterfaceStore().setLayoutHeight(windowHeight()) + window.syncConfig = useSyncConfigStore() + window.mergedConfig = useMergedConfigStore() + window.localConfig = useLocalConfigStore() + window.highlightConfig = useUserHighlightStore() FaviconService.initFaviconService() initServiceWorker(store) @@ -409,18 +538,25 @@ const afterStoreSetup = async ({ pinia, store, storageError, i18n }) => { window.addEventListener('focus', () => updateFocus()) const overrides = window.___pleromafe_dev_overrides || {} - const server = (typeof overrides.target !== 'undefined') ? overrides.target : window.location.origin - store.dispatch('setInstanceOption', { name: 'server', value: server }) + const server = + typeof overrides.target !== 'undefined' + ? overrides.target + : window.location.origin + useInstanceStore().set({ path: 'server', value: server }) await setConfig({ store }) try { - await useInterfaceStore().applyTheme().catch((e) => { console.error('Error setting theme', e) }) + await useInterfaceStore() + .applyTheme() + .catch((e) => { + console.error('Error setting theme', e) + }) } catch (e) { window.splashError(e) return Promise.reject(e) } - applyConfig(store.state.config, i18n.global) + applyStyleConfig(useMergedConfigStore().mergedConfig, i18n.global) // Now we can try getting the server settings and logging in // Most of these are preloaded into the index.html so blocking is minimized @@ -428,8 +564,8 @@ const afterStoreSetup = async ({ pinia, store, storageError, i18n }) => { checkOAuthToken({ store }), getInstancePanel({ store }), getNodeInfo({ store }), - getInstanceConfig({ store }) - ]).catch(e => Promise.reject(e)) + getInstanceConfig({ store }), + ]).catch((e) => Promise.reject(e)) // Start fetching things that don't need to block the UI store.dispatch('fetchMutes') @@ -442,11 +578,11 @@ const afterStoreSetup = async ({ pinia, store, storageError, i18n }) => { history: createWebHistory(), routes: routes(store), scrollBehavior: (to, _from, savedPosition) => { - if (to.matched.some(m => m.meta.dontScroll)) { + if (to.matched.some((m) => m.meta.dontScroll)) { return false } return savedPosition || { left: 0, top: 0 } - } + }, }) useI18nStore().setI18n(i18n) diff --git a/src/boot/routes.js b/src/boot/routes.js index 02abf8ce6..193daf4a7 100644 --- a/src/boot/routes.js +++ b/src/boot/routes.js @@ -1,42 +1,48 @@ -import PublicTimeline from 'components/public_timeline/public_timeline.vue' -import BubbleTimeline from 'components/bubble_timeline/bubble_timeline.vue' -import PublicAndExternalTimeline from 'components/public_and_external_timeline/public_and_external_timeline.vue' -import FriendsTimeline from 'components/friends_timeline/friends_timeline.vue' -import TagTimeline from 'components/tag_timeline/tag_timeline.vue' -import BookmarkTimeline from 'components/bookmark_timeline/bookmark_timeline.vue' -import ConversationPage from 'components/conversation-page/conversation-page.vue' -import Interactions from 'components/interactions/interactions.vue' -import DMs from 'components/dm_timeline/dm_timeline.vue' -import ChatList from 'components/chat_list/chat_list.vue' -import Chat from 'components/chat/chat.vue' -import UserProfile from 'components/user_profile/user_profile.vue' -import Search from 'components/search/search.vue' -import Registration from 'components/registration/registration.vue' -import PasswordReset from 'components/password_reset/password_reset.vue' -import FollowRequests from 'components/follow_requests/follow_requests.vue' -import OAuthCallback from 'components/oauth_callback/oauth_callback.vue' -import Notifications from 'components/notifications/notifications.vue' -import AuthForm from 'components/auth_form/auth_form.js' -import ShoutPanel from 'components/shout_panel/shout_panel.vue' -import WhoToFollow from 'components/who_to_follow/who_to_follow.vue' import About from 'components/about/about.vue' -import RemoteUserResolver from 'components/remote_user_resolver/remote_user_resolver.vue' -import Lists from 'components/lists/lists.vue' -import ListsTimeline from 'components/lists_timeline/lists_timeline.vue' -import ListsEdit from 'components/lists_edit/lists_edit.vue' -import NavPanel from 'src/components/nav_panel/nav_panel.vue' import AnnouncementsPage from 'components/announcements_page/announcements_page.vue' -import QuotesTimeline from '../components/quotes_timeline/quotes_timeline.vue' +import AuthForm from 'components/auth_form/auth_form.js' +import BookmarkTimeline from 'components/bookmark_timeline/bookmark_timeline.vue' +import BubbleTimeline from 'components/bubble_timeline/bubble_timeline.vue' +import Chat from 'components/chat/chat.vue' +import ChatList from 'components/chat_list/chat_list.vue' +import ConversationPage from 'components/conversation-page/conversation-page.vue' +import DMs from 'components/dm_timeline/dm_timeline.vue' import Drafts from 'components/drafts/drafts.vue' -import BookmarkFolders from '../components/bookmark_folders/bookmark_folders.vue' +import FollowRequests from 'components/follow_requests/follow_requests.vue' +import FriendsTimeline from 'components/friends_timeline/friends_timeline.vue' +import Interactions from 'components/interactions/interactions.vue' +import Lists from 'components/lists/lists.vue' +import ListsEdit from 'components/lists_edit/lists_edit.vue' +import ListsTimeline from 'components/lists_timeline/lists_timeline.vue' +import Notifications from 'components/notifications/notifications.vue' +import OAuthCallback from 'components/oauth_callback/oauth_callback.vue' +import PasswordReset from 'components/password_reset/password_reset.vue' +import PublicAndExternalTimeline from 'components/public_and_external_timeline/public_and_external_timeline.vue' +import PublicTimeline from 'components/public_timeline/public_timeline.vue' +import Registration from 'components/registration/registration.vue' +import RemoteUserResolver from 'components/remote_user_resolver/remote_user_resolver.vue' +import Search from 'components/search/search.vue' +import ShoutPanel from 'components/shout_panel/shout_panel.vue' +import TagTimeline from 'components/tag_timeline/tag_timeline.vue' +import UserProfile from 'components/user_profile/user_profile.vue' +import WhoToFollow from 'components/who_to_follow/who_to_follow.vue' + +import NavPanel from 'src/components/nav_panel/nav_panel.vue' import BookmarkFolderEdit from '../components/bookmark_folder_edit/bookmark_folder_edit.vue' +import BookmarkFolders from '../components/bookmark_folders/bookmark_folders.vue' +import QuotesTimeline from '../components/quotes_timeline/quotes_timeline.vue' + +import { useInstanceStore } from 'src/stores/instance.js' +import { useInstanceCapabilitiesStore } from 'src/stores/instance_capabilities.js' export default (store) => { const validateAuthenticatedRoute = (to, from, next) => { if (store.state.users.currentUser) { next() } else { - next(store.state.instance.redirectRootNoLogin || '/main/all') + next( + useInstanceStore().instanceIdentity.redirectRootNoLogin || '/main/all', + ) } } @@ -45,46 +51,125 @@ export default (store) => { name: 'root', path: '/', redirect: () => { - return (store.state.users.currentUser - ? store.state.instance.redirectRootLogin - : store.state.instance.redirectRootNoLogin) || '/main/all' - } + return ( + (store.state.users.currentUser + ? useInstanceStore().instanceIdentity.redirectRootLogin + : useInstanceStore().instanceIdentity.redirectRootNoLogin) || + '/main/all' + ) + }, + }, + { + name: 'public-external-timeline', + path: '/main/all', + component: PublicAndExternalTimeline, + }, + { + name: 'public-timeline', + path: '/main/public', + component: PublicTimeline, + }, + { + name: 'friends', + path: '/main/friends', + component: FriendsTimeline, + beforeEnter: validateAuthenticatedRoute, }, - { name: 'public-external-timeline', path: '/main/all', component: PublicAndExternalTimeline }, - { name: 'public-timeline', path: '/main/public', component: PublicTimeline }, - { name: 'friends', path: '/main/friends', component: FriendsTimeline, beforeEnter: validateAuthenticatedRoute }, { name: 'tag-timeline', path: '/tag/:tag', component: TagTimeline }, { name: 'bookmarks', path: '/bookmarks', component: BookmarkTimeline }, { name: 'bubble', path: '/bubble', component: BubbleTimeline }, - { name: 'conversation', path: '/notice/:id', component: ConversationPage, meta: { dontScroll: true } }, + { + name: 'conversation', + path: '/notice/:id', + component: ConversationPage, + meta: { dontScroll: true }, + }, { name: 'quotes', path: '/notice/:id/quotes', component: QuotesTimeline }, { name: 'remote-user-profile-acct', path: '/remote-users/:_(@)?:username([^/@]+)@:hostname([^/@]+)', component: RemoteUserResolver, - beforeEnter: validateAuthenticatedRoute + beforeEnter: validateAuthenticatedRoute, }, { name: 'remote-user-profile', path: '/remote-users/:hostname/:username', component: RemoteUserResolver, - beforeEnter: validateAuthenticatedRoute + beforeEnter: validateAuthenticatedRoute, + }, + { + name: 'external-user-profile', + path: '/users/$:id', + component: UserProfile, + }, + { + name: 'interactions', + path: '/users/:username/interactions', + component: Interactions, + beforeEnter: validateAuthenticatedRoute, + }, + { + name: 'dms', + path: '/users/:username/dms', + component: DMs, + beforeEnter: validateAuthenticatedRoute, }, - { name: 'external-user-profile', path: '/users/$:id', component: UserProfile }, - { name: 'interactions', path: '/users/:username/interactions', component: Interactions, beforeEnter: validateAuthenticatedRoute }, - { name: 'dms', path: '/users/:username/dms', component: DMs, beforeEnter: validateAuthenticatedRoute }, { name: 'registration', path: '/registration', component: Registration }, - { name: 'password-reset', path: '/password-reset', component: PasswordReset, props: true }, - { name: 'registration-token', path: '/registration/:token', component: Registration }, - { name: 'friend-requests', path: '/friend-requests', component: FollowRequests, beforeEnter: validateAuthenticatedRoute }, - { name: 'notifications', path: '/:username/notifications', component: Notifications, props: () => ({ disableTeleport: true }), beforeEnter: validateAuthenticatedRoute }, + { + name: 'password-reset', + path: '/password-reset', + component: PasswordReset, + props: true, + }, + { + name: 'registration-token', + path: '/registration/:token', + component: Registration, + }, + { + name: 'friend-requests', + path: '/friend-requests', + component: FollowRequests, + beforeEnter: validateAuthenticatedRoute, + }, + { + name: 'notifications', + path: '/:username/notifications', + component: Notifications, + props: () => ({ disableTeleport: true }), + beforeEnter: validateAuthenticatedRoute, + }, { name: 'login', path: '/login', component: AuthForm }, - { name: 'shout-panel', path: '/shout-panel', component: ShoutPanel, props: () => ({ floating: false }) }, - { name: 'oauth-callback', path: '/oauth-callback', component: OAuthCallback, props: (route) => ({ code: route.query.code }) }, - { name: 'search', path: '/search', component: Search, props: (route) => ({ query: route.query.query }) }, - { name: 'who-to-follow', path: '/who-to-follow', component: WhoToFollow, beforeEnter: validateAuthenticatedRoute }, + { + name: 'shout-panel', + path: '/shout-panel', + component: ShoutPanel, + props: () => ({ floating: false }), + }, + { + name: 'oauth-callback', + path: '/oauth-callback', + component: OAuthCallback, + props: (route) => ({ code: route.query.code }), + }, + { + name: 'search', + path: '/search', + component: Search, + props: (route) => ({ query: route.query.query }), + }, + { + name: 'who-to-follow', + path: '/who-to-follow', + component: WhoToFollow, + beforeEnter: validateAuthenticatedRoute, + }, { name: 'about', path: '/about', component: About }, - { name: 'announcements', path: '/announcements', component: AnnouncementsPage }, + { + name: 'announcements', + path: '/announcements', + component: AnnouncementsPage, + }, { name: 'drafts', path: '/drafts', component: Drafts }, { name: 'user-profile', path: '/users/:name', component: UserProfile }, { name: 'legacy-user-profile', path: '/:name', component: UserProfile }, @@ -92,17 +177,51 @@ export default (store) => { { name: 'lists-timeline', path: '/lists/:id', component: ListsTimeline }, { name: 'lists-edit', path: '/lists/:id/edit', component: ListsEdit }, { name: 'lists-new', path: '/lists/new', component: ListsEdit }, - { name: 'edit-navigation', path: '/nav-edit', component: NavPanel, props: () => ({ forceExpand: true, forceEditMode: true }), beforeEnter: validateAuthenticatedRoute }, - { name: 'bookmark-folders', path: '/bookmark_folders', component: BookmarkFolders }, - { name: 'bookmark-folder-new', path: '/bookmarks/new-folder', component: BookmarkFolderEdit }, - { name: 'bookmark-folder', path: '/bookmarks/:id', component: BookmarkTimeline }, - { name: 'bookmark-folder-edit', path: '/bookmarks/:id/edit', component: BookmarkFolderEdit } + { + name: 'edit-navigation', + path: '/nav-edit', + component: NavPanel, + props: () => ({ forceExpand: true, forceEditMode: true }), + beforeEnter: validateAuthenticatedRoute, + }, + { + name: 'bookmark-folders', + path: '/bookmark_folders', + component: BookmarkFolders, + }, + { + name: 'bookmark-folder-new', + path: '/bookmarks/new-folder', + component: BookmarkFolderEdit, + }, + { + name: 'bookmark-folder', + path: '/bookmarks/:id', + component: BookmarkTimeline, + }, + { + name: 'bookmark-folder-edit', + path: '/bookmarks/:id/edit', + component: BookmarkFolderEdit, + }, ] - if (store.state.instance.pleromaChatMessagesAvailable) { + if (useInstanceCapabilitiesStore().pleromaChatMessagesAvailable) { routes = routes.concat([ - { name: 'chat', path: '/users/:username/chats/:recipient_id', component: Chat, meta: { dontScroll: false }, beforeEnter: validateAuthenticatedRoute }, - { name: 'chats', path: '/users/:username/chats', component: ChatList, meta: { dontScroll: false }, beforeEnter: validateAuthenticatedRoute } + { + name: 'chat', + path: '/users/:username/chats/:recipient_id', + component: Chat, + meta: { dontScroll: false }, + beforeEnter: validateAuthenticatedRoute, + }, + { + name: 'chats', + path: '/users/:username/chats', + component: ChatList, + meta: { dontScroll: false }, + beforeEnter: validateAuthenticatedRoute, + }, ]) } diff --git a/src/components/about/about.js b/src/components/about/about.js index 1df258450..404843e8b 100644 --- a/src/components/about/about.js +++ b/src/components/about/about.js @@ -1,8 +1,11 @@ -import InstanceSpecificPanel from '../instance_specific_panel/instance_specific_panel.vue' import FeaturesPanel from '../features_panel/features_panel.vue' -import TermsOfServicePanel from '../terms_of_service_panel/terms_of_service_panel.vue' -import StaffPanel from '../staff_panel/staff_panel.vue' +import InstanceSpecificPanel from '../instance_specific_panel/instance_specific_panel.vue' import MRFTransparencyPanel from '../mrf_transparency_panel/mrf_transparency_panel.vue' +import StaffPanel from '../staff_panel/staff_panel.vue' +import TermsOfServicePanel from '../terms_of_service_panel/terms_of_service_panel.vue' + +import { useInstanceStore } from 'src/stores/instance.js' +import { useMergedConfigStore } from 'src/stores/merged_config.js' const About = { components: { @@ -10,16 +13,20 @@ const About = { FeaturesPanel, TermsOfServicePanel, StaffPanel, - MRFTransparencyPanel + MRFTransparencyPanel, }, computed: { - showFeaturesPanel () { return this.$store.state.instance.showFeaturesPanel }, - showInstanceSpecificPanel () { - return this.$store.state.instance.showInstanceSpecificPanel && - !this.$store.getters.mergedConfig.hideISP && - this.$store.state.instance.instanceSpecificPanelContent - } - } + showFeaturesPanel() { + return useInstanceStore().instanceIdentity.showFeaturesPanel + }, + showInstanceSpecificPanel() { + return ( + useInstanceStore().instanceIdentity.showInstanceSpecificPanel && + !useMergedConfigStore().mergedConfig.hideISP && + useInstanceStore().instanceIdentity.instanceSpecificPanelContent + ) + }, + }, } export default About diff --git a/src/components/account_actions/account_actions.js b/src/components/account_actions/account_actions.js index 9a63f57eb..f204adbde 100644 --- a/src/components/account_actions/account_actions.js +++ b/src/components/account_actions/account_actions.js @@ -1,99 +1,105 @@ -import { mapState } from 'vuex' -import ProgressButton from '../progress_button/progress_button.vue' -import Popover from '../popover/popover.vue' +import { mapState } from 'pinia' + import UserListMenu from 'src/components/user_list_menu/user_list_menu.vue' +import UserTimedFilterModal from 'src/components/user_timed_filter_modal/user_timed_filter_modal.vue' import ConfirmModal from '../confirm_modal/confirm_modal.vue' -import { library } from '@fortawesome/fontawesome-svg-core' -import { - faEllipsisV -} from '@fortawesome/free-solid-svg-icons' +import Popover from '../popover/popover.vue' +import ProgressButton from '../progress_button/progress_button.vue' + +import { useInstanceCapabilitiesStore } from 'src/stores/instance_capabilities.js' +import { useMergedConfigStore } from 'src/stores/merged_config.js' import { useReportsStore } from 'src/stores/reports' -library.add( - faEllipsisV -) +import { library } from '@fortawesome/fontawesome-svg-core' +import { faEllipsisV } from '@fortawesome/free-solid-svg-icons' + +library.add(faEllipsisV) const AccountActions = { - props: [ - 'user', 'relationship' - ], - data () { + props: ['user', 'relationship'], + data() { return { showingConfirmBlock: false, - showingConfirmRemoveFollower: false + showingConfirmRemoveFollower: false, } }, components: { ProgressButton, Popover, UserListMenu, - ConfirmModal + ConfirmModal, + UserTimedFilterModal, }, methods: { - showConfirmBlock () { - this.showingConfirmBlock = true - }, - hideConfirmBlock () { - this.showingConfirmBlock = false - }, - showConfirmRemoveUserFromFollowers () { + showConfirmRemoveUserFromFollowers() { this.showingConfirmRemoveFollower = true }, - hideConfirmRemoveUserFromFollowers () { + hideConfirmRemoveUserFromFollowers() { this.showingConfirmRemoveFollower = false }, - showRepeats () { + hideConfirmBlock() { + this.showingConfirmBlock = false + }, + showRepeats() { this.$store.dispatch('showReblogs', this.user.id) }, - hideRepeats () { + hideRepeats() { this.$store.dispatch('hideReblogs', this.user.id) }, - blockUser () { - if (!this.shouldConfirmBlock) { - this.doBlockUser() + blockUser() { + if (this.$refs.timedBlockDialog) { + this.$refs.timedBlockDialog.optionallyPrompt() } else { - this.showConfirmBlock() + if (!this.shouldConfirmBlock) { + this.doBlockUser() + } else { + this.showingConfirmBlock = true + } } }, - doBlockUser () { - this.$store.dispatch('blockUser', this.user.id) + doBlockUser() { + this.$store.dispatch('blockUser', { id: this.user.id }) this.hideConfirmBlock() }, - unblockUser () { + unblockUser() { this.$store.dispatch('unblockUser', this.user.id) }, - removeUserFromFollowers () { + removeUserFromFollowers() { if (!this.shouldConfirmRemoveUserFromFollowers) { this.doRemoveUserFromFollowers() } else { this.showConfirmRemoveUserFromFollowers() } }, - doRemoveUserFromFollowers () { + doRemoveUserFromFollowers() { this.$store.dispatch('removeUserFromFollowers', this.user.id) this.hideConfirmRemoveUserFromFollowers() }, - reportUser () { + reportUser() { useReportsStore().openUserReportingModal({ userId: this.user.id }) }, - openChat () { + openChat() { this.$router.push({ name: 'chat', - params: { username: this.$store.state.users.currentUser.screen_name, recipient_id: this.user.id } + params: { + username: this.$store.state.users.currentUser.screen_name, + recipient_id: this.user.id, + }, }) - } + }, }, computed: { - shouldConfirmBlock () { - return this.$store.getters.mergedConfig.modalOnBlock + shouldConfirmBlock() { + return useMergedConfigStore().mergedConfig.modalOnBlock }, - shouldConfirmRemoveUserFromFollowers () { - return this.$store.getters.mergedConfig.modalOnRemoveUserFromFollowers + shouldConfirmRemoveUserFromFollowers() { + return useMergedConfigStore().mergedConfig.modalOnRemoveUserFromFollowers }, - ...mapState({ - pleromaChatMessagesAvailable: state => state.instance.pleromaChatMessagesAvailable - }) - } + ...mapState(useInstanceCapabilitiesStore, [ + 'blockExpiration', + 'pleromaChatMessagesAvailable', + ]), + }, } export default AccountActions diff --git a/src/components/account_actions/account_actions.vue b/src/components/account_actions/account_actions.vue index fd4837ee4..94cb91ee0 100644 --- a/src/components/account_actions/account_actions.vue +++ b/src/components/account_actions/account_actions.vue @@ -3,7 +3,6 @@ diff --git a/src/components/alert.style.js b/src/components/alert.style.js index 868514764..8a6f842ed 100644 --- a/src/components/alert.style.js +++ b/src/components/alert.style.js @@ -1,57 +1,51 @@ export default { name: 'Alert', selector: '.alert', - validInnerComponents: [ - 'Text', - 'Icon', - 'Link', - 'Border', - 'ButtonUnstyled' - ], + validInnerComponents: ['Text', 'Icon', 'Link', 'Border', 'ButtonUnstyled'], variants: { normal: '.neutral', error: '.error', warning: '.warning', - success: '.success' + success: '.success', }, editor: { border: 1, - aspect: '3 / 1' + aspect: '3 / 1', }, defaultRules: [ { directives: { background: '--text', opacity: 0.5, - blur: '9px' - } + blur: '9px', + }, }, { parent: { - component: 'Alert' + component: 'Alert', }, component: 'Border', directives: { - textColor: '--parent' - } + textColor: '--parent', + }, }, { variant: 'error', directives: { - background: '--cRed' - } + background: '--cRed', + }, }, { variant: 'warning', directives: { - background: '--cOrange' - } + background: '--cOrange', + }, }, { variant: 'success', directives: { - background: '--cGreen' - } - } - ] + background: '--cGreen', + }, + }, + ], } diff --git a/src/components/announcement/announcement.js b/src/components/announcement/announcement.js index d1b8257d8..13d55c159 100644 --- a/src/components/announcement/announcement.js +++ b/src/components/announcement/announcement.js @@ -1,109 +1,130 @@ import { mapState } from 'vuex' + +import localeService from '../../services/locale/locale.service.js' import AnnouncementEditor from '../announcement_editor/announcement_editor.vue' import RichContent from '../rich_content/rich_content.jsx' -import localeService from '../../services/locale/locale.service.js' -import { useAnnouncementsStore } from 'src/stores/announcements' + +import { useAnnouncementsStore } from 'src/stores/announcements.js' const Announcement = { components: { AnnouncementEditor, - RichContent + RichContent, }, - data () { + data() { return { editing: false, editedAnnouncement: { content: '', startsAt: undefined, endsAt: undefined, - allDay: undefined + allDay: undefined, }, - editError: '' + editError: '', } }, props: { - announcement: Object + announcement: Object, }, computed: { ...mapState({ - currentUser: state => state.users.currentUser + currentUser: (state) => state.users.currentUser, }), - canEditAnnouncement () { - return this.currentUser && this.currentUser.privileges.includes('announcements_manage_announcements') + canEditAnnouncement() { + return ( + this.currentUser && + this.currentUser.privileges.includes( + 'announcements_manage_announcements', + ) + ) }, - content () { + content() { return this.announcement.content }, - isRead () { + isRead() { return this.announcement.read }, - publishedAt () { + publishedAt() { const time = this.announcement.published_at if (!time) { return } - return this.formatTimeOrDate(time, localeService.internalToBrowserLocale(this.$i18n.locale)) + return this.formatTimeOrDate( + time, + localeService.internalToBrowserLocale(this.$i18n.locale), + ) }, - startsAt () { + startsAt() { const time = this.announcement.starts_at if (!time) { return } - return this.formatTimeOrDate(time, localeService.internalToBrowserLocale(this.$i18n.locale)) + return this.formatTimeOrDate( + time, + localeService.internalToBrowserLocale(this.$i18n.locale), + ) }, - endsAt () { + endsAt() { const time = this.announcement.ends_at if (!time) { return } - return this.formatTimeOrDate(time, localeService.internalToBrowserLocale(this.$i18n.locale)) + return this.formatTimeOrDate( + time, + localeService.internalToBrowserLocale(this.$i18n.locale), + ) }, - inactive () { + inactive() { return this.announcement.inactive - } + }, }, methods: { - markAsRead () { + markAsRead() { if (!this.isRead) { - return useAnnouncementsStore().markAnnouncementAsRead(this.announcement.id) + return useAnnouncementsStore().markAnnouncementAsRead( + this.announcement.id, + ) } }, - deleteAnnouncement () { + deleteAnnouncement() { return useAnnouncementsStore().deleteAnnouncement(this.announcement.id) }, - formatTimeOrDate (time, locale) { + formatTimeOrDate(time, locale) { const d = new Date(time) - return this.announcement.all_day ? d.toLocaleDateString(locale) : d.toLocaleString(locale) + return this.announcement.all_day + ? d.toLocaleDateString(locale) + : d.toLocaleString(locale) }, - enterEditMode () { + enterEditMode() { this.editedAnnouncement.content = this.announcement.pleroma.raw_content this.editedAnnouncement.startsAt = this.announcement.starts_at this.editedAnnouncement.endsAt = this.announcement.ends_at this.editedAnnouncement.allDay = this.announcement.all_day this.editing = true }, - submitEdit () { - useAnnouncementsStore().editAnnouncement({ - id: this.announcement.id, - ...this.editedAnnouncement - }) + submitEdit() { + useAnnouncementsStore() + .editAnnouncement({ + id: this.announcement.id, + ...this.editedAnnouncement, + }) .then(() => { this.editing = false }) - .catch(error => { + .catch((error) => { this.editError = error.error }) }, - cancelEdit () { + cancelEdit() { this.editing = false }, - clearError () { + clearError() { this.editError = undefined - } - } + }, + }, } export default Announcement diff --git a/src/components/announcement_editor/announcement_editor.js b/src/components/announcement_editor/announcement_editor.js index 79a03afe1..6d22ac1fd 100644 --- a/src/components/announcement_editor/announcement_editor.js +++ b/src/components/announcement_editor/announcement_editor.js @@ -2,12 +2,12 @@ import Checkbox from '../checkbox/checkbox.vue' const AnnouncementEditor = { components: { - Checkbox + Checkbox, }, props: { announcement: Object, - disabled: Boolean - } + disabled: Boolean, + }, } export default AnnouncementEditor diff --git a/src/components/announcements_page/announcements_page.js b/src/components/announcements_page/announcements_page.js index 9ce0b45f5..b8b1f000a 100644 --- a/src/components/announcements_page/announcements_page.js +++ b/src/components/announcements_page/announcements_page.js @@ -1,59 +1,67 @@ import { mapState } from 'vuex' + import Announcement from '../announcement/announcement.vue' import AnnouncementEditor from '../announcement_editor/announcement_editor.vue' -import { useAnnouncementsStore } from 'src/stores/announcements' + +import { useAnnouncementsStore } from 'src/stores/announcements.js' const AnnouncementsPage = { components: { Announcement, - AnnouncementEditor + AnnouncementEditor, }, - data () { + data() { return { newAnnouncement: { content: '', startsAt: undefined, endsAt: undefined, - allDay: false + allDay: false, }, posting: false, - error: undefined + error: undefined, } }, - mounted () { + mounted() { useAnnouncementsStore().fetchAnnouncements() }, computed: { ...mapState({ - currentUser: state => state.users.currentUser + currentUser: (state) => state.users.currentUser, }), - announcements () { + announcements() { return useAnnouncementsStore().announcements }, - canPostAnnouncement () { - return this.currentUser && this.currentUser.privileges.includes('announcements_manage_announcements') - } + canPostAnnouncement() { + return ( + this.currentUser && + this.currentUser.privileges.includes( + 'announcements_manage_announcements', + ) + ) + }, }, methods: { - postAnnouncement () { + postAnnouncement() { this.posting = true - useAnnouncementsStore().postAnnouncement(this.newAnnouncement) + useAnnouncementsStore() + .postAnnouncement(this.newAnnouncement) .then(() => { this.newAnnouncement.content = '' this.startsAt = undefined this.endsAt = undefined }) - .catch(error => { + .catch((error) => { this.error = error.error }) .finally(() => { this.posting = false }) }, - clearError () { + clearError() { this.error = undefined - } - } + }, + }, } export default AnnouncementsPage diff --git a/src/components/async_component_error/async_component_error.vue b/src/components/async_component_error/async_component_error.vue index 2ff8974c1..baf430950 100644 --- a/src/components/async_component_error/async_component_error.vue +++ b/src/components/async_component_error/async_component_error.vue @@ -21,10 +21,10 @@ export default { emits: ['resetAsyncComponent'], methods: { - retry () { + retry() { this.$emit('resetAsyncComponent') - } - } + }, + }, } diff --git a/src/components/attachment/attachment.js b/src/components/attachment/attachment.js index 21d793930..fbe77a687 100644 --- a/src/components/attachment/attachment.js +++ b/src/components/attachment/attachment.js @@ -1,24 +1,29 @@ -import StillImage from '../still-image/still-image.vue' -import Flash from '../flash/flash.vue' -import VideoAttachment from '../video_attachment/video_attachment.vue' +import { mapState } from 'pinia' + import nsfwImage from '../../assets/nsfw.png' -import fileTypeService from '../../services/file_type/file_type.service.js' -import { mapGetters } from 'vuex' +import Flash from '../flash/flash.vue' +import StillImage from '../still-image/still-image.vue' +import VideoAttachment from '../video_attachment/video_attachment.vue' + +import { useInstanceStore } from 'src/stores/instance.js' +import { useInstanceCapabilitiesStore } from 'src/stores/instance_capabilities.js' +import { useMediaViewerStore } from 'src/stores/media_viewer' +import { useMergedConfigStore } from 'src/stores/merged_config.js' + import { library } from '@fortawesome/fontawesome-svg-core' import { + faAlignRight, faFile, - faMusic, faImage, - faVideo, - faPlayCircle, - faTimes, - faStop, - faSearchPlus, - faTrashAlt, + faMusic, faPencilAlt, - faAlignRight + faPlayCircle, + faSearchPlus, + faStop, + faTimes, + faTrashAlt, + faVideo, } from '@fortawesome/free-solid-svg-icons' -import { useMediaViewerStore } from 'src/stores/media_viewer' library.add( faFile, @@ -31,7 +36,7 @@ library.add( faSearchPlus, faTrashAlt, faPencilAlt, - faAlignRight + faAlignRight, ) const Attachment = { @@ -46,72 +51,72 @@ const Attachment = { 'remove', 'shiftUp', 'shiftDn', - 'edit' + 'edit', ], - data () { + data() { return { localDescription: this.description || this.attachment.description, - nsfwImage: this.$store.state.instance.nsfwCensorImage || nsfwImage, - hideNsfwLocal: this.$store.getters.mergedConfig.hideNsfw, - preloadImage: this.$store.getters.mergedConfig.preloadImage, + nsfwImage: + useInstanceStore().instanceIdentity.nsfwCensorImage || nsfwImage, + hideNsfwLocal: useMergedConfigStore().mergedConfig.hideNsfw, + preloadImage: useMergedConfigStore().mergedConfig.preloadImage, loading: false, - img: fileTypeService.fileType(this.attachment.mimetype) === 'image' && document.createElement('img'), + img: this.attachment.type === 'image' && document.createElement('img'), modalOpen: false, showHidden: false, flashLoaded: false, - showDescription: false + showDescription: false, } }, components: { Flash, StillImage, - VideoAttachment + VideoAttachment, }, computed: { - classNames () { + classNames() { return [ { '-loading': this.loading, '-nsfw-placeholder': this.hidden, '-editable': this.edit !== undefined, - '-compact': this.compact + '-compact': this.compact, }, - '-type-' + this.type, + '-type-' + this.attachment.type, this.size && '-size-' + this.size, - `-${this.useContainFit ? 'contain' : 'cover'}-fit` + `-${this.useContainFit ? 'contain' : 'cover'}-fit`, ] }, - usePlaceholder () { + usePlaceholder() { return this.size === 'hide' }, - useContainFit () { - return this.$store.getters.mergedConfig.useContainFit + useContainFit() { + return this.mergedConfig.useContainFit }, - placeholderName () { + placeholderName() { if (this.attachment.description === '' || !this.attachment.description) { - return this.type.toUpperCase() + return this.attachment.type.toUpperCase() } return this.attachment.description }, - placeholderIconClass () { - if (this.type === 'image') return 'image' - if (this.type === 'video') return 'video' - if (this.type === 'audio') return 'music' + placeholderIconClass() { + if (this.attachment.type === 'image') return 'image' + if (this.attachment.type === 'video') return 'video' + if (this.attachment.type === 'audio') return 'music' return 'file' }, - referrerpolicy () { - return this.$store.state.instance.mediaProxyAvailable ? '' : 'no-referrer' + referrerpolicy() { + return useInstanceCapabilitiesStore().mediaProxyAvailable + ? '' + : 'no-referrer' }, - type () { - return fileTypeService.fileType(this.attachment.mimetype) - }, - hidden () { + hidden() { return this.nsfw && this.hideNsfwLocal && !this.showHidden }, - isEmpty () { - return (this.type === 'html' && !this.attachment.oembed) + isEmpty() { + return this.attachment.type === 'html' && !this.attachment.oembed }, - useModal () { + useModal() { let modalTypes = [] switch (this.size) { case 'hide': @@ -124,64 +129,66 @@ const Attachment = { : ['image'] break } - return modalTypes.includes(this.type) + return modalTypes.includes(this.attachment.type) }, - videoTag () { + videoTag() { return this.useModal ? 'button' : 'span' }, - ...mapGetters(['mergedConfig']) + ...mapState(useMergedConfigStore, ['mergedConfig']), }, watch: { - 'attachment.description' (newVal) { + 'attachment.description'(newVal) { this.localDescription = newVal }, - localDescription (newVal) { + localDescription(newVal) { this.onEdit(newVal) - } + }, }, methods: { - linkClicked ({ target }) { + linkClicked({ target }) { if (target.tagName === 'A') { window.open(target.href, '_blank') } }, - openModal () { + openModal() { if (this.useModal) { this.$emit('setMedia') useMediaViewerStore().setCurrentMedia(this.attachment) - } else if (this.type === 'unknown') { + } else if (this.attachment.type === 'unknown') { window.open(this.attachment.url) } }, - openModalForce () { + openModalForce() { this.$emit('setMedia') useMediaViewerStore().setCurrentMedia(this.attachment) }, - onEdit (event) { + onEdit(event) { this.edit && this.edit(this.attachment, event) }, - onRemove () { + onRemove() { this.remove && this.remove(this.attachment) }, - onShiftUp () { + onShiftUp() { this.shiftUp && this.shiftUp(this.attachment) }, - onShiftDn () { + onShiftDn() { this.shiftDn && this.shiftDn(this.attachment) }, - stopFlash () { + stopFlash() { this.$refs.flash.closePlayer() }, - setFlashLoaded (event) { + setFlashLoaded(event) { this.flashLoaded = event }, - toggleDescription () { + toggleDescription() { this.showDescription = !this.showDescription }, - toggleHidden (event) { + toggleHidden(event) { if ( - (this.mergedConfig.useOneClickNsfw && !this.showHidden) && - (this.type !== 'video' || this.mergedConfig.playVideosInModal) + this.mergedConfig.useOneClickNsfw && + !this.showHidden && + (this.attachment.type !== 'video' || + this.mergedConfig.playVideosInModal) ) { this.openModal(event) return @@ -201,12 +208,12 @@ const Attachment = { this.showHidden = !this.showHidden } }, - onImageLoad (image) { + onImageLoad(image) { const width = image.naturalWidth const height = image.naturalHeight this.$emit('naturalSizeLoad', { id: this.attachment.id, width, height }) - } - } + }, + }, } export default Attachment diff --git a/src/components/attachment/attachment.scss b/src/components/attachment/attachment.scss index 16346c97c..97515eb32 100644 --- a/src/components/attachment/attachment.scss +++ b/src/components/attachment/attachment.scss @@ -107,9 +107,9 @@ .play-icon { position: absolute; - font-size: 64px; - top: calc(50% - 32px); - left: calc(50% - 32px); + font-size: 4.5em; + top: calc(50% - 2.25rem); + left: calc(50% - 2.25rem); color: rgb(255 255 255 / 75%); text-shadow: 0 0 2px rgb(0 0 0 / 40%); diff --git a/src/components/attachment/attachment.style.js b/src/components/attachment/attachment.style.js deleted file mode 100644 index a9455e367..000000000 --- a/src/components/attachment/attachment.style.js +++ /dev/null @@ -1,27 +0,0 @@ -export default { - name: 'Attachment', - selector: '.Attachment', - notEditable: true, - validInnerComponents: [ - 'Border', - 'Button', - 'Input' - ], - defaultRules: [ - { - directives: { - roundness: 3 - } - }, - { - component: 'Button', - parent: { - component: 'Attachment' - }, - directives: { - background: '#FFFFFF', - opacity: 0.5 - } - } - ] -} diff --git a/src/components/attachment/attachment.vue b/src/components/attachment/attachment.vue index 0701a393e..0db86ff8a 100644 --- a/src/components/attachment/attachment.vue +++ b/src/components/attachment/attachment.vue @@ -6,7 +6,7 @@ @click="openModal" >
diff --git a/src/components/checkbox/checkbox.vue b/src/components/checkbox/checkbox.vue index c8bba4c44..cbe3dd80f 100644 --- a/src/components/checkbox/checkbox.vue +++ b/src/components/checkbox/checkbox.vue @@ -1,7 +1,7 @@