Wikimedia Vue UI (WVUI) components – Wikimedia Foundation's Vue.js shared user-interface components for Wikipedia, MediaWiki, and beyond. See quick start to contribute.
- Table of contents
- Installation and version history
- Development
- Performance
- Library design goals
- License (GPL-2.0+)
Install the library and Vue.js v2:
npm i --save-prefix= vue@2 @wikimedia/wvui
WVUI is semantically versioned. See the changelog for release notes.
We recommend pinning WVUI to an exact patch version. For example:
…,
"dependencies": {
"…": "…",
"@wikimedia/wvui": "1.2.3",
"…": "…"
}
…,
Expand for details…
WVUI is semantically versioned but bugs occasionally slip through. They're easier for consumers to
identify when upgrades are tracked deliberately via package.json. If
semver ranges are used instead, like "^1.2.3"
, only the
verbose and noisy package-lock.json will change on an upgrade which may go unnoticed. Additionally,
new features are easier to consider and socialize at upgrade time when minor / major version
upgrades are intentional and reflected in package.json.
The recommendation to use exact patch versions like "1.2.3"
may seem pedantic but if a project
specifies dependencies with looser versioning instead, that project will be at the mercy of its
dependencies instead of in control of them.
There is currently one bundle available:
-
Combined: the complete library. This bundle is the simplest to use because it contains all code but is not performant if only part is used or if different parts should be loaded at different times.
⚠️ This chunk is standalone and should not be loaded with split chunks.- wvui.js/css: the complete library and default export. No other chunks required.
Each chunk is side-effect free. All chunks are fully compiled ES5 / CSS and require a Vue.js runtime. See peerDependencies.
See the performance section for related topics.
npm install
npm start
install
/i
: install project dependencies.start
: run Storybook development workflow.test
/t
: build the project and execute all tests. Anything that can be validated automatically before publishing runs through this command. See testing.run test:unit
: run the unit tests. Pass-u
to update all Jest snapshots.run format
: apply lint fixes automatically where available.run build
: compile source inputs to bundle outputs underdist/
.run docs
: generate all documentation underdocs/
.version
: increment the version. See versioning.publish
: publish the version to NPM. See versioning.
Scripts containing :
delimiters in their names are sub-scripts. They are invoked by the outermost
delimited name (and possibly other scripts). For example, test:unit
is executed by test
.
Undocumented scripts are considered internal utilities and not expressly supported workflows.
💡 Tips:
- Add
--
to pass arguments to the script command. For example,npm run test:unit -- -u
. - Add
-s
to omit verbose command echoing. For example,npm -s i
ornpm -s run format
.
NVM is recommended to configure the Node.js version used whenever executing these scripts. Expand for example…
# Install the project's recommended Node.js version. This is a one-time installation command and
# does not need to be run again except when the project's .nvmrc is revised. `nvm use` will print an
# error message if this command needs to be run again.
nvm install "$(<.nvmrc)"
# Configure the current shell's environment to use the recommended Node.js version. This command
# should be run whenever opening a new shell to work on the project _prior_ to executing any of the
# project's NPM scripts, especially `npm install`.
nvm use
# Install the project's development and production dependencies. This is a one-time installation
# command and does not need to be run again except when the project's package.json `dependencies` or
# `devDependencies` are revised.
npm install
# All dependencies are now available. Execute any project scripts as wanted.
As the primary development flow WVUI uses
Storybook which allows developing UI components
in isolation without worrying about
specific dependencies and requirements. Storybook uses so called
stories. For each SFC (single file
component) its story should be placed in the same directory:
|-- src
|-- components
|-- your-component
|-- YourComponent.vue
|-- YourComponent.stories.ts
Each story represents a single visual state of a component.
WVUI uses different Storybook addons, namely:
- Knobs that allows you to edit component props dynamically.
- Actions to retrieve data from event handlers.
- a11y to analyze accessibility issues.
- links which allows a developer to create links that navigate between different stories.
- backgrounds to change background colors inside the preview
- viewport to display UI components in different sizes and layouts
- storysource to show story source in Storybook.
To start developing with Storybook, simply run npm start
command (see
NPM scripts). This command will open Storybook in your browser.
Vue.js Single File Components are used for all runtime components. The Vue.js template explorer is useful for debugging.
The Vue.js Style Guide is adhered to where possible.
- PascalCase multi-word component names are used per the Vue.js Style Guide. Since every component
is prefixed with
Mw
, all components are multi-word just by keeping that pattern. E.g.: - ✓ UseMwFoo
with a lowercase "w". - ✗ Do not useMWFoo
with a capital "W". This breaks kebab-cased HTML in templates. - Avoid making primitive base components complex. Make new components instead.
TypeScript is used for all runtime sources. The TypeScript playground is useful for debugging.
- All top-level file symbols should be fully typed. Seams should not have their types inferred because they are most likely to have subtle flaws.
- All named functions and methods should have inputs and output typed. When functions are fully typed, their contents usually can be inferred.
- Favor type inference for locals rather than explicit typing. Locals are unlikely to have incorrect typing assumptions and the verbosity of typing is usually a hindrance.
- Use TypeScript typing where available, JSDoc typing where not. Avoid typing both as this is verbose and the docs may be incorrect.
- TypeScript supports
import
. For example,import Vue from 'vue';
. - Destructuring is supported. For example,
import { PropType } from 'vue';
. Destructuring can be combined with default imports. For example,import Vue, { PropType } from 'vue';
. - According to the TypeScript
paths
and Webpackalias
configurations,@
references paths relative the source root (src
) directory. For example,import WvuiButton from '../../src/components/button/Button.vue
may be equivalent toimport WvuiButton from '@/components/button/Button.vue
. - Vue imports terminate in
.vue
. TypeScript imports are extensionless. A compilation error will occur otherwise.
Less is used for all runtime styles. The Less playground is useful for debugging.
- BEM naming conventions are adhered to where possible.
- All components use a box-sizing of
border-box
. - Each component should be entirely independent and usable in any context. Parents can specify the
presentation of their children (for example,
display: flex
) but no component should expect to only exist in a given container.
Several import options are available. The two most relevant are:
once
: the default. If no option is specified, theonce
option is implied. Use with care as this bundles one full copy of the specified file into the bundle. References are always preferred. For example,@import "foo.less";
.reference
: When only symbols or mixins are necessary for Less to CSS compilation, use areference
import. Only the compiled output ships, not the definitions themselves or dead code. For example,@import (reference) "foo.less";
.
Import paths are resolved using less-loader:
- Relative paths are used for project files. For example,
@import ( reference ) './Foo.less';
. - Prepend
@/
for paths relative the source root (src
) directory. For example,@import ( reference ) '@/themes/wikimedia-ui.less';
. - Prepend a single
~
for NPM dependency files. For example,@import ( reference ) '~wikimedia-ui-base/wikimedia-ui-base.less';
.
To run tests, use npm test
command (see NPM scripts).
- WVUI uses Vue Test Utils, the official unit testing utility library for Vue.js.
- WVUI uses Jest as a test runner.
- Tests for every component should be colocated with the component itself:
|-- src
|-- components
|-- your-component
|-- YourComponent.vue
|-- YourComponent.test.ts
- WVUI uses snapshot testing, snapshot files are colocated with components as well:
|-- src
|-- components
|-- your-component
|-- YourComponent.vue <-- Functional code and test subject
|-- YourComponent.test.ts <-- Unit tests
|-- YourComponent.snap.ts <-- Jest snapshot rendered component HTML
Coverage reports are generated automatically in the docs/coverage directory whenever unit tests are executed.
Coverage thresholds are configured under .jest/jest.config.json. These are lower limits for the entire repo and, as a convention, the number is rounded down to the nearest 10%. For example, if the actual repository coverage is 89%, the threshold is configured to 80%. See Jest documentation for details.
./src/entries/*.ts
is excluded from the coverage report and expected to be side-effect free.
Example: I want to see my local WVUI library changes live in my app or MediaWiki skin.
Package linking is the primary integrated development workflow for use when isolated development is impractical. Tight coupling of WVUI to a specific implementation is strongly discouraged. Nevertheless, it is often the case that changes tested live in the context of a particular use case are wanted prior to publishing. For example, perhaps a bug only manifests easily in one target.
The steps are:
- Clone the WVUI repository if you haven't already.
- Enter the WVUI directory.
- Install the WVUI dependencies if you haven't already (see NPM scripts).
- Note WVUI's directory. For example,
wvuiDir="$PWD"
. - Enter your integration project's directory. For example, if you are integrating WVUI into Vector,
the command might be
cd ~/dev/mediawiki/skins/Vector
. This location should contain a package.json with a@wikimedia/wvui
dependency (eitherdependency
,devDependency
, orpeerDependency
). - Symbolically link the development WVUI into the integration project via
npm link "$wvuiDir"
where$wvuiDir
is the location of WVUI. This swaps the published production WVUI library for a link to your local development copy. - Verify the link is correct by seeing where that it resolves to WVUI's location. For example,
readlink -m node_modules/@wikimedia/wvui
should match$wvuiDir
. - Perform all development and iteration wanted in WVUI and integration project.
- Unlink the development WVUI via
npm unlink @wikimedia/wvui
. This deletes the symlink to your development copy of WVUI.
The above process seems a little clumsy because it is initially. However, it's quite practical and becomes easy with practice.
- Always configure your environment with NVM prior to un/installing dependencies as these operations modify the NPM lockfile. See NPM scripts for example usage.
- Obviously, carefully consider any proposed new dependencies. Runtime dependencies that increase the bandwidth consumption should be given especial care and implicit dependencies should be avoided.
- When adding or revising NPM dependencies, pin
dependencies
anddevDependencies
to exact patch versions for the same reasons pinning WVUI itself to patch version is recommended. See Installation and version history for details. - Dependencies are not transpiled and must be ES5. Additionally, dependencies must only use supported browser APIs.
WVUI uses several linters and formatters. The former identify functional issues and the latter
identify nonfunctional presentational inconsistencies such as incorrect indentation. Both support
some measure of fixing or "formatting" problems automatically by executing npm run format
.
- Prettier: Markdown and JSON files are formatted by Prettier. When it comes to generating beautiful and extremely consistently styled code, Prettier's ability to accept utter garbage code in and automatically apply formatting changes is exceptional, far superior to ESLint, and may even change the way you write code. For example, the indentation of braceless loops is never misleading once prettified. However, Prettier can never replace ESLint as it doesn't support any functional linting, only nonfunctional formatting. ESLint integration and additional languages such as TypeScript and JavaScript are supported but currently unused in WVUI. See .prettierrc.json and .prettierignore for configuration.
- ESLint: ESLint is used for linting and formatting JavaScript, TypeScript, and Vue.js files. A hierarchy of overrides is used so that extends and rules can be separated. See .eslintrc.json and .eslintignore for details and configuration. An additional configuration is present in dist/.eslintrc.json for validating that only ES5 is shipped.
- Stylelint: Stylelint is used for linting and formatting Less and Vue.js files. See .stylelintrc.json and .stylelintignore for configuration.
To publish a new release:
- Update the changelog with release notes.
- Commit the changelog.
- Execute
npm version <patch|minor|major>
. - Execute
npm publish --access public
. - Perform a rolling development release.
Expand for example…
# Review the changes since the last release. For example,
# `git log "$(git describe --tags --abbrev=0)..@" --oneline`.
# Document a new feature and a couple bug fixes since the last release. (Emacs can also be used to
# edit the changelog.)
vim changelog.md
# Stage the changelog.
git add changelog.md
# Commit the changelog.
git commit -m '[docs][changelog] prepare release notes'
# Version, build, and test a release.
npm version minor
# Publish the release
npm publish --access public
The NPM scripts are configured to help ensure that only tested artifacts are published on Git and npmjs.com. Expand for details…
By executing npm version
, the following scripts are invoked in this order:
preversion
: test that the workspace contains no uncommitted changes.version
: increment the version, clean, build, and test the candidate, commit, and tag the change.
In detail, version
is a built-in NPM script that increases the package.json's version
property
(patch
, minor
, or major
) as specified, commits the result to version control, and adds a Git
tag. Prior to committing the version bump, clean, build, and test the candidate artifact. See
npm help version
for further details.
The preversion
NPM script, which runs prior to version
, is defined to test that Git's version
control state is clean before that happens. No uncommitted changes are allowed! For example, imagine
if a superfluous file containing a password was unintentionally in the workspace and published to
npmjs.com.
By executing npm publish
, the following scripts are invoked in this order:
prepublishOnly
: push the Git tag to the remote.publish
: push the artifacts to npmjs.com as per usual.
Before publish
is executed, prepublishOnly
pushes the current commit and tag to the Git remote.
If the push or publish fail due to connectivity, you should probably call npm publish
directly
which will re-push the tag and archive as needed.
Finally, the publish
script is executed which releases the raw files built into the wild at the
npm registry. See npm help publish
for further details.
The intended result is:
- Uncommitted changes (both modifications and untracked files) are forbidden.
- Only clean and tested packages are published.
- Git tags are available for all releases.
- Git tags pushed and NPM artifacts publishes are always in sync.
- NPM's
@latest
tag points to the current stable release and@next
points to the latest commit.
See also:
To publish a new alpha, beta, or release candidate:
- Execute
npm version <prerelease|prepatch|preminor|premajor> --preid=<alpha|beta|rc>
. This will create a new version commit on the current branch. - Execute
npm publish --access public
.
Expand for details on which version to use…
prerelease
is the safest choice. It always bumps the metadata number and only bumps the patch
number if a stable version exists. For example, given the current version is a stable v1.2.3,
npm version prerelease --preid=alpha
will create v1.2.4-alpha.0
. Note that both the patch is
bumped and metadata is added. If executed again, note that only the metadata number is bumped and
the patch number stays the same: v1.2.4-alpha.1
.
prerelease
can be slightly incorrect if the next release is known to be a minor or major release.
In those cases, the correct initial alpha release would be npm version preminor --preid=alpha
(or
premajor
) which would create v1.3.0-alpha.0
. The subsequent alpha release would then be
npm version prerelease --preid=alpha
(note the command changes to prerelease
) which creates
v1.3.0-alpha.1
.
To publish the current master
HEAD
, execute bin/release-dev
.
Development releases can be installed by consumers via npm install @wikimedia/wvui@next
. These
releases are useful for integration testing and development as well as for early adopters who don't
wish to build the WVUI library themselves.
Great workflows often require great tooling and those tools need to be configured. This section describes how to optimize your editor or IDE for optimal usage.
- Configure your line length to 100. For example, add common widths:
"editor.rulers": [ 80, 100 ]
.
- Vetur - Enable
vetur.experimental.templateInterpolationService
for HTML template type checking in single file components. - Prettier
- ESLint
- stylelint
- Code Spell Checker -
Lower the logging level to informational by setting
cSpell.logLevel
to"Information"
. - Markdown Preview Enhanced
- Authors should revise the changelog each commit so this work is not postponed to release.
- WVUI uses a "squash-and-merge" convention for changes.0
- Operating system and editor-specific files are not considered.1
- The Git configuration should be precise and accurate like any other part of the codebase. The .gitignore file, for instance, should not become cluttered or vague.
0Expand for details on squash-and-merge…
Development of a change worth merging is often messy. A merge-worthy change usually occurs over multiple patchsets in a Gerrit patch or commits in a GitHub pull request. These interim changes can often be quite noisy in themselves and not useful or even detrimental to preserve distinctly in the Git log. Example improvements during review often include whitespace changes, bug fixes, refactoring of introduced code, and renaming of new symbols.
Therefor, distinct interim commits are collapsed into a single logical commit at merge time that often satisfies the intent of the original commit. The tradeoffs are that only a single polished commit representative of all of that back-and-forth discourse during code review is made at the expense that less noteworthy history is lost.
1Expand for details on OS and editor-specific files…
Different programmers use different editors and IDEs. WVUI will attempt to facilitate different workflows, especially in the form of documentation, but will avoid making changes specific to them such as ignoring Vim swap files.
OS-specific files such as .DS_Store and Thumbs.db should be excluded by the user's global Git configuration as they're unwanted in every repository and not specific to WVUI. See gitignore documentation for details.
Example:
- Add a global exclusions file by executing
git config --global core.excludesfile '~/.gitignore'
or updating your~/.gitconfig
manually:
excludesfile = ~/.gitignore
- Always ignore
.DS_Store
files by executingecho .DS_Store >> ~/.gitignore
or updating your~/.gitignore
manually:
.DS_Store
The expectations for submitting a patch are:
- Write your best work.
- Functional changes compile, run, and pass tests.
- Established patterns at least within the WVUI repository are considered.
- Any submitted change is an overall improvement. The rationale is that if a patch is an overall improvement, it's obvious to merge. If it's not, why should should it be merged?
- Smaller patches get better reviews.
- The goal of code review is to help write great code, not only prevent bad code from being written. The distinction is that the former is helping to achieve whereas the latter is focused on prevention. Nourishing good ideas is better than extinguishing formative ideas.
- Be specific when providing constructive feedback. Vague concerns, such as "there are many reasons" or "it's more nuanced than that," prevent further discussion and create invisible barriers to participation that cannot be overcome. Make your point and allow the author to address it. When possible, suggest an approach or reference with your request. The more clearly you express the changes you want, the easier it will be for the author to provide.
- If you as a reviewer are making requests of the author, attempt to match their level of effort and timeliness. Everyone is busy and doing their best but differently abled.
- Be open-minded. New ideas, especially standard ideas that are only new to you, are not inherently bad. It's ok to downvote to request improved documentation or clarification but not for an education in industry standard practice. You are responsible in part for creating the culture you want.
Vue.extend()
is used for the type inference of components. This is anticipated to be replaced bydefineComponent()
in the Vue v3 Composition API.- Storybook is incompatible with Vue Devtools. Tap "Open canvas in a new tab" as a workaround.
- "Download the React DevTools…" is printed to the browser console when running Storybook.
- If Storybook encounters an error when booting, it does not launch even after the error is resolved.
- JavaScript configuration files are not type checked when building the library. This seems to be
because Webpack shakes out dead code. All types can be tested manually via
npx --no-install tsc --noEmit --incremental false
. - The linter doesn't enforce tabs in in TypeScript enumerations or module declarations.
WVUI uses Browserslist to help support and enforce browser compatibility. Supported targets are
configured in .browserslistsrc according to MediaWiki grade A compatibility.
To see the current list, execute npx --no-install browserslist
.
JavaScript build products are linted for ES5 compatibility.
Less inputs are linted for compatibility and automatically prefixed for browser vendors according to
the Browserslist config via the PostCSS plugin. The current configuration only adds
vendor prefixes like -webkit-transition:all 1s; transition:all 1s
, not polyfills. #rgba
color
syntax, like #0000
for transparent
, are also replaced as needed by cssnano. The prefixes used
can be seen by executing npx --no-install autoprefixer --info
.
The contents of each bundle generated can be evaluated through its source map. source-map-explorer and Webpack Bundle Analyzer are used to generate reports for minified and minified + gzipped bundle breakdowns. The reports are similar but crosschecking may be useful.
WVUI uses Webpack for bundling different library entry points into distinct build products or "bundles". All JavaScript and CSS build product bandwidth performances are tracked and tested with bundlesize and versioned in bundlesize.config.json. Reports are generated under docs/minGzipBundleSize.txt.
The rule of thumb is: identical data generally compresses well. It is recommended to evaluate performance using the minified gzipped outputs. For example, some CSS selectors are distant but have identical rules. This creates a large uncompressed CSS bundle when compiled. However, the compressed size may be negligible. Use the bundlesize tests to evaluate gzipped sizes before making optimizations that impede readability.
Expand for manual evaluation details…
If a second opinion is wanted, consider using the gzip CLI:
# Individual chunk sizes (min / min+gz).
ls -1 dist/*.{js,css}|
sort|
while IFS= read filename; do
printf \
'%s: %sB / %sB\n' \
"$filename" \
"$(wc -c < "$filename"|numfmt --to=iec-i)" \
"$(gzip -c "$filename"|wc -c|numfmt --to=iec-i)"
done
# All chunks concatenated (allows maximum possible compression). This makes sense if a request to
# ResourceLoader will depend on multiple chunks.
printf \
'%s: %sB / %sB\n' \
"Total" \
"$(cat dist/*.{js,css}|wc -c|numfmt --to=iec-i)" \
"$(cat dist/*.{js,css}|gzip -c|wc -c|numfmt --to=iec-i)"
When changing the bundlesize configuration:
- The values in the configuration are upper limits. As a convention, the number is rounded up to
the nearest tenth of a kibibyte. For example, a new file added of size
4.15 KB
would have its initial limit set at4.2 KB
. Whenever intentional changes causes its limit to increase or decrease beyond a tenth of a kibibyte boundary, the size should be revised. - bundlesize internally uses Bytes utility which only supports base-2 units. Case-insensitive decimal JEDEC notation is used in the config. This means 1.5 KB or 1.5 kb is 1536 bytes, not 1500 bytes.
⚠️ Warning: values that cannot be parsed are silently ignored! When making changes, verify that a comparison of two values is printed like2.54KB < maxSize 2.6KB (gzip)
. If only one number is shown (e.g.,2.54KB (gzip)
), the number has been entered incorrectly.⚠️ Warning: values entered must have a leading units position specified. Sub-one sizes like.5 KB
must be written with a leading zero like0.5 KB
or they will not be pared.- The bundlesize thresholds specify minified gzipped maximums. Outputs are minified as part of the build process and gzip is the most common HTTP compression.
- Deploy search to all test wikis before August 31, 2020: frwiktionary, hewiki, ptwikiversity, frwiki, euwiki, fawiki.
- Relevant, modern, efficient, iterative contributor workflows.
- Delightful user experiences shareable as an NPM package and reusable everywhere with and without MediaWiki.
- Fully typed. Accurate typing improves comprehension for tooling and programmers.
- Semantically versioned.
- Thoroughly documented for development and usage; everything needed to be productive is in the readme.
- Well tested and robust.
See LICENSE.