diff --git a/.editorconfig b/.editorconfig deleted file mode 100644 index 69cfa45..0000000 --- a/.editorconfig +++ /dev/null @@ -1,21 +0,0 @@ -# http://editorconfig.org - -# top-most EditorConfig file -root = true - -# Unix-style newlines with a newline ending every file -[*] -end_of_line = lf -insert_final_newline = true -charset = utf-8 -indent_style = tab -indent_size = 4 -trim_trailing_whitespace = true -insert_final_newline = true - -[{*.md,*.scss,*.css,*.php,*.yml,package.json}] -indent_style = space -indent_size = 2 - -[*.md] -trim_trailing_whitespace = false diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000..bf09e82 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,2 @@ +# Prettier format sweep +e1f4a95992d0b10d470a209cccba69c28598a338 diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..73b5cba --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,57 @@ +name: Bug report +description: Something in jQuery loadJSON does not work as documented. +labels: ["bug"] +body: + - type: markdown + attributes: + value: | + Please search the [open issues](https://github.com/kevindb/jquery-load-json/issues) first, and see [Reporting a bug](https://github.com/kevindb/jquery-load-json/blob/main/CONTRIBUTING.md#reporting-a-bug). + Do not report security issues here; see the [security policy](https://github.com/kevindb/jquery-load-json/blob/main/SECURITY.md). + - type: textarea + id: description + attributes: + label: Description + description: What happened? + validations: + required: true + - type: textarea + id: expected + attributes: + label: Expected behavior + description: What did you expect to happen? + validations: + required: true + - type: textarea + id: steps + attributes: + label: Steps to reproduce + description: The HTML template, the data you pass to `loadJSON`, and any options. + render: html + validations: + required: true + - type: input + id: demo + attributes: + label: Demonstration + description: A link to a minimal example, for instance on [JSFiddle](https://jsfiddle.net/) or [CodePen](https://codepen.io/). + - type: input + id: plugin-version + attributes: + label: jQuery loadJSON version + placeholder: "1.4.0" + validations: + required: true + - type: input + id: jquery-version + attributes: + label: jQuery version + placeholder: "3.7.1" + validations: + required: true + - type: input + id: browsers + attributes: + label: Browsers and versions + placeholder: "Firefox 140, Safari 26" + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..d66fb4d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,8 @@ +blank_issues_enabled: true +contact_links: + - name: Report a security vulnerability + url: https://github.com/kevindb/jquery-load-json/security/advisories/new + about: Please report security issues privately, as the security policy (SECURITY.md) describes, not in a public issue. + - name: Documentation + url: https://github.com/kevindb/jquery-load-json#readme + about: Usage, options and examples. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..3e8a1fe --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,29 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + commit-message: + prefix: ci + groups: + github-actions: + patterns: + - "*" + + # Version updates for the dev tooling only. The jQuery dev dependencies (jquery3, jquery4) + # are pinned on purpose: the test matrix runs those exact releases. + - package-ecosystem: npm + directory: / + schedule: + interval: weekly + allow: + - dependency-type: development + ignore: + - dependency-name: "jquery*" + commit-message: + prefix: build + include: scope + groups: + dev-dependencies: + dependency-type: development diff --git a/.github/issue_template.md b/.github/issue_template.md deleted file mode 100644 index fb7fcb0..0000000 --- a/.github/issue_template.md +++ /dev/null @@ -1,17 +0,0 @@ -Please review [Instructions for Reporting a Bug](https://github.com/kevindb/jquery-load-json/blob/master/CONTRIBUTING.md#reporting-a-bug). - -### Description: - -### Expected Behavior: - -### Actual behavior: - -### Versions: -**LoadJSON:** -**jQuery:** -**Browsers:** - -### Demonstration -Link to demonstration of issue in [CodePen](https://codepen.io/) or [JSFiddle](https://jsfiddle.net/): - -### Steps to reproduce: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..9626cbd --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,83 @@ +name: CI + +on: + push: + branches: [main] + paths-ignore: ["docs/**", "**/*.md"] + # No paths-ignore on pull requests: a skipped workflow never reports its required checks. + pull_request: + +concurrency: + group: ci-${{ github.workflow }}-${{ github.head_ref || github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + # Lint, format check, build, coverage on Chromium, Firefox and WebKit with jQuery 3.7.1, and a check + # that the committed dist/ (and its copy for the examples) matches the build. + test: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version-file: .nvmrc + cache: npm + - run: npm ci + - name: Get Playwright version + id: playwright + run: echo "version=$(node -p "require('playwright/package.json').version")" >> "$GITHUB_OUTPUT" + - name: Cache Playwright browsers + uses: actions/cache@v6 + with: + path: ~/.cache/ms-playwright + key: playwright-${{ runner.os }}-${{ steps.playwright.outputs.version }}-all + - run: npx playwright install --with-deps chromium firefox webkit + - run: npm test + - name: Check committed dist and the examples' copy match the build + run: git diff --exit-code -- dist docs/examples/jquery.loadJSON.js + + # The suite and the end-to-end tests against the jQuery support floor, the latest 3.x, and 4.x. + jquery: + name: jQuery ${{ matrix.jquery }} on ${{ matrix.browser }} + runs-on: ubuntu-latest + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + browser: [chromium, firefox, webkit] + jquery: ["1.7.2", "3.7.1", "4.0.0"] + include: + - { jquery: "1.7.2", file: ".jquery/jquery-1.7.2.js" } + - { jquery: "3.7.1", file: "node_modules/jquery3/dist/jquery.js" } + - { jquery: "4.0.0", file: "node_modules/jquery4/dist/jquery.js" } + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version-file: .nvmrc + cache: npm + - run: npm ci + - name: Get Playwright version + id: playwright + run: echo "version=$(node -p "require('playwright/package.json').version")" >> "$GITHUB_OUTPUT" + - name: Cache Playwright browsers + uses: actions/cache@v6 + with: + path: ~/.cache/ms-playwright + key: playwright-${{ runner.os }}-${{ steps.playwright.outputs.version }}-${{ matrix.browser }} + - run: npx playwright install --with-deps ${{ matrix.browser }} + - name: Fetch jQuery 1.7.2 + if: matrix.jquery == '1.7.2' + run: scripts/fetch-jquery.sh 1.7.2 + - name: Run the suite + run: npx vitest run --project suite-${{ matrix.browser }} + env: + JQUERY_FILE: ${{ matrix.file }} + - name: Run the end-to-end tests + run: npm run test:e2e -- --project ${{ matrix.browser }} + env: + JQUERY_FILE: ${{ matrix.file }} diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml deleted file mode 100644 index f44751b..0000000 --- a/.github/workflows/codeql-analysis.yml +++ /dev/null @@ -1,62 +0,0 @@ -name: "CodeQL" - -on: - push: - branches: [master] - pull_request: - # The branches below must be a subset of the branches above - branches: [master] - schedule: - - cron: '0 18 * * 3' - -jobs: - analyze: - name: Analyze - runs-on: ubuntu-latest - - strategy: - fail-fast: false - matrix: - # Override automatic language detection by changing the below list - # Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python'] - language: ['javascript'] - # Learn more... - # https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection - - steps: - - name: Checkout repository - uses: actions/checkout@v2 - with: - # We must fetch at least the immediate parents so that if this is - # a pull request then we can checkout the head. - fetch-depth: 2 - - # If this run was triggered by a pull request event, then checkout - # the head of the pull request instead of the merge commit. - - run: git checkout HEAD^2 - if: ${{ github.event_name == 'pull_request' }} - - # Initializes the CodeQL tools for scanning. - - name: Initialize CodeQL - uses: github/codeql-action/init@v1 - with: - languages: ${{ matrix.language }} - - # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). - # If this step fails, then you should remove it and run the build manually (see below) - - name: Autobuild - uses: github/codeql-action/autobuild@v1 - - # â„šī¸ Command-line programs to run using the OS shell. - # 📚 https://git.io/JvXDl - - # âœī¸ If the Autobuild fails above, remove it and uncomment the following three lines - # and modify them (or add more) to build your code if your project - # uses a compiled language - - #- run: | - # make bootstrap - # make release - - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v1 diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..dfd0808 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,45 @@ +name: CodeQL + +on: + push: + branches: [main] + pull_request: + branches: [main] + schedule: + - cron: "23 6 * * 1" + +concurrency: + group: codeql-${{ github.head_ref || github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + analyze: + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + strategy: + fail-fast: false + matrix: + language: [javascript-typescript, actions] + steps: + - uses: actions/checkout@v7 + - uses: github/codeql-action/init@v4 + with: + languages: ${{ matrix.language }} + build-mode: none + queries: security-extended + # Scan the source once: every dist/ build repeats its alerts, and tests and docs are not shipped. + config: | + paths-ignore: + - dist + - test + - docs + - node_modules + - uses: github/codeql-action/analyze@v4 + with: + category: /language:${{ matrix.language }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..c8c443c --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,78 @@ +name: Release + +# Publishes a v* tag to npm through trusted publishing (OIDC, with provenance). The publish job runs +# in the `npm` environment, which needs a maintainer's approval and accepts only v* tags; npm accepts +# OIDC tokens only from this workflow file in that environment. Run it by hand to rehearse `verify`. +on: + push: + tags: ["v*"] + workflow_dispatch: + +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false + +permissions: + contents: read + +jobs: + verify: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version-file: .nvmrc + cache: npm + - run: npm ci + - name: Get Playwright version + id: playwright + run: echo "version=$(node -p "require('playwright/package.json').version")" >> "$GITHUB_OUTPUT" + - name: Cache Playwright browsers + uses: actions/cache@v6 + with: + path: ~/.cache/ms-playwright + key: playwright-${{ runner.os }}-${{ steps.playwright.outputs.version }}-all + # npm test runs the suite in Chromium, Firefox and WebKit, which need their system libraries. + - run: npx playwright install --with-deps chromium firefox webkit + - run: npm test + - name: Check committed dist matches the build + run: git diff --exit-code -- dist + - name: Check the tag matches an unpublished package version + if: startsWith(github.ref, 'refs/tags/v') + run: | + version=$(node -p "require('./package.json').version") + if [ "v$version" != "$GITHUB_REF_NAME" ]; then + echo "Tag $GITHUB_REF_NAME does not match package.json version v$version." + exit 1 + fi + if [ -n "$(npm view "jquery-load-json@$version" version 2>/dev/null)" ]; then + echo "jquery-load-json@$version is already on npm." + exit 1 + fi + # npm pack lists the same files as npm publish without asking the registry, so a rehearsal from + # a branch passes even though its version is already published. + - name: Show the tarball that would be published + run: npm pack --dry-run + + publish: + needs: verify + if: startsWith(github.ref, 'refs/tags/v') + runs-on: ubuntu-latest + timeout-minutes: 5 + environment: npm + permissions: + contents: read + id-token: write + steps: + # No npm ci: no dependency code runs in the job that can publish. dist/ is committed, and the + # verify job has checked it against a fresh build. + - uses: actions/checkout@v7 + with: + persist-credentials: false + - uses: actions/setup-node@v7 + with: + node-version-file: .nvmrc + registry-url: https://registry.npmjs.org + - run: npm publish diff --git a/.gitignore b/.gitignore index efeb816..56508d1 100644 --- a/.gitignore +++ b/.gitignore @@ -227,3 +227,10 @@ $RECYCLE.BIN/ *.lnk # End of https://www.gitignore.io/api/composer,git,laravel,macos,node,phpstorm,pycharm,sublimetext,vim,visualstudiocode,webstorm,windows + +# Test output +.jquery/ +coverage/ +.vitest/ +test-results/ +playwright-report/ diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000..6f4247a --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +26 diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..5eeb358 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,10 @@ +/*.md +.jquery/ +.vitest/ +coverage/ +dist/ +docs/examples/jquery.loadJSON.js +node_modules/ +package-lock.json +playwright-report/ +test-results/ diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000..12c91d0 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,4 @@ +{ + "printWidth": 100, + "trailingComma": "es5" +} diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..0538395 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,13 @@ +## Agent skills + +### Issue tracker + +Issues and specs live in [GitHub Issues](https://github.com/kevindb/jquery-load-json/issues) for `kevindb/jquery-load-json`; use the `gh` CLI. See `docs/agents/issue-tracker.md`. + +### Domain docs + +Single-context: root `GLOSSARY.md` (when present) and `docs/adr/`. See `docs/agents/domain.md`. + +### Coding standards + +Read `docs/agents/coding-standards.md` when modifying source, tests, build/lint/format config, packaging/tooling, or commits. Conventional Commits (1–3 lines), BDD + AAA tests, edit `src/` never `dist/`; config wins once tooling lands. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 622dbfc..6067319 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,12 +5,56 @@ Here are a couple of guidelines that will help you contribute. Before we get sta #### Overview +* [Development](#development) * [Contribution workflow](#contribution-workflow) * [Reporting a bug](#reporting-a-bug) * [Contributing to an existing issue](#contributing-to-an-existing-issue) * [Feature Requests](#feature-requests) * [Additional info](#additional-info) +## Development + +You need [Node.js](https://nodejs.org/) 26 (the version is in `.nvmrc`, so `nvm use` picks it). + +```shell +npm ci +npx playwright install chromium firefox webkit +npm test +``` + +`npm test` is the one command to run before sending a change. It lints (ESLint), checks formatting +(Prettier), builds `dist/` with Rollup, and runs the test suite in Chromium (with coverage, which +must stay at 100%), Firefox and WebKit, plus the tests of the published files. + +* Edit `src/`, never `dist/`. `dist/` and `docs/examples/jquery.loadJSON.js` are generated by + `npm run build` but committed, and CI checks they match a fresh build, so commit them with your + change. +* `npm run format` fixes formatting. +* Tests use [Vitest](https://vitest.dev/) browser mode and live in `test/suite/`. Name them by + behavior (`describe` / `it`: "when X, it should Y") and keep Arrange, Act and Assert apart. +* `npm run test:e2e` runs the end-to-end tests with Playwright. + +### jQuery versions + +The suite runs against jQuery 3.7.1 by default. CI also runs it, and the end-to-end tests, against +jQuery 1.7.2 (the oldest supported version), 3.7.1 and 4.0.0, each in Chromium, Firefox and WebKit. +To run another version locally, set `JQUERY_FILE`: + +```shell +JQUERY_FILE=node_modules/jquery4/dist/jquery.js npx vitest run --project suite-chromium +scripts/fetch-jquery.sh 1.7.2 +JQUERY_FILE=.jquery/jquery-1.7.2.js npx vitest run --project suite-chromium +``` + +`scripts/fetch-jquery.sh` downloads jQuery 1.7.2, which npm does not ship as a file, and checks +its hash. + +### Documentation and examples + +The documentation is in `docs/`, and GitHub Pages serves it with the live examples in +`docs/examples/`. To try the examples locally, serve `docs/` over HTTP (for example +`npx serve docs`); they load their data with Ajax, so opening the files directly does not work. + ## Contribution workflow 1. Fork the repository in GitHub with the `Fork` button. @@ -19,14 +63,7 @@ Here are a couple of guidelines that will help you contribute. Before we get sta 3. Make your feature addition or bug fix. 4. Send a pull request (PR). Bonus points for topic branches. * Please make sure all of your commits are atomic (one feature per commit). - * Use sensible commit messages. - * Always write a clear log message for your commits. One-line messages are fine for small changes, but bigger changes should look like this: - -```shell - $ git commit -m "A brief summary of the commit" - > - > A paragraph describing what changed and its impact." -``` + * Write commit messages in the [Conventional Commits](https://www.conventionalcommits.org/) style, such as `fix: keep the fragment when adding a link parameter`, with a short body if the change needs one. * If your PR fixes a separate issue number, include it in the commit message. ### Things to keep in mind diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 36be62e..85b3959 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -15,3 +15,6 @@ It is based on Alexandre Caprais's notemplate plugin with several enhancements t Original work on [notemplate plugin](https://code.google.com/p/notemplate/) by Alexandre Caprais. Project Home: [code.google.com/p/notemplate](https://code.google.com/p/notemplate/) Plugin for jQuery. Populate HTML with a JSON data source. + +### Francesco Angi +Fixed loading an array into an element that is not a select or form ([#28](https://github.com/kevindb/jquery-load-json/pull/28)). diff --git a/GLOSSARY.md b/GLOSSARY.md new file mode 100644 index 0000000..4c24333 --- /dev/null +++ b/GLOSSARY.md @@ -0,0 +1,65 @@ +# jQuery loadJSON + +A jQuery plugin that fills existing HTML markup, forms included, with values from a JSON object. + +## Loading + +**Template**: +The HTML markup that loadJSON fills: an element and everything inside it. +_Avoid_: view, form (when the markup is not a form) + +**Saved template**: +A copy of a template's original markup, kept on the element so a later load can start from it. +_Avoid_: template cache + +**Data**: +The JSON value loaded into a template: an object, an array or a single value. +_Avoid_: model, JSON object (when the value is not an object) + +**Key**: +A property name in the data, used to find the elements that take its value. +_Avoid_: binding key, property (the older README wording), field name + +**Scope**: +The element a key is looked up inside: the template for top-level keys, the match of the enclosing key for nested ones. +_Avoid_: context, container + +**Match**: +The elements a key resolves to within its scope, found by class, then id, then name. +_Avoid_: binding, child, target + +**Repeat**: +Loading an array by filling existing matching elements in order, then appending copies of the last one for the remaining items. +_Avoid_: clone, iteration, template (for the copied element) + +## Element kinds + +**Element kind**: +The category of an element that decides how a value is set on it. +_Avoid_: element type, input type (only some kinds are inputs) + +**Field**: +A text-like input whose value is set directly, such as text, number, date or hidden. +_Avoid_: text input (not all fields are text) + +**Checkbox**, **Radio**: +Inputs that become checked when their value equals the loaded value, or is among the loaded values for a checkbox group. + +**Option**, **Select-one**, **Select-multiple**: +A select's option, set from a value and text; a single select, which selects a value or gains options from an array; a multiple select, which selects several values or gains options. + +**Link**: +An anchor whose `href` takes the value, either as the whole address or as an added query parameter named after the key. + +**Image**: +An image whose `src`, `alt` and `title` take the value. + +**Content**: +Any other element, whose contents take the value. +_Avoid_: text element, HTML element + +## Releases + +**Deprecation notice**: +A console warning, shown only when debugging is turned on, that announces behavior removed in the next major version. +_Avoid_: deprecation warning, debug log diff --git a/Gruntfile.js b/Gruntfile.js deleted file mode 100644 index 4b7a1da..0000000 --- a/Gruntfile.js +++ /dev/null @@ -1,31 +0,0 @@ -module.exports = function(grunt) { - grunt.initConfig({ - pkg: grunt.file.readJSON('package.json'), - meta: { - banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd HH:MM:ss") %> */' - }, - - // Minifies JS files - uglify: { - options: { - preserveComments: /^!|@preserve|@license|@cc_on/i - }, - dist: { - files: [{ - expand: true, - cwd: 'src', - src: ['*.js','!*.min.js'], - dest: 'dist', - ext: '.min.js', - extDot: 'last' - }] - } - }, - }); - - // Load tasks - grunt.loadNpmTasks('grunt-contrib-uglify'); - - // Default task. - grunt.registerTask('default', [ 'uglify' ]); -}; diff --git a/README.md b/README.md index 7870214..c380778 100644 --- a/README.md +++ b/README.md @@ -1,96 +1,93 @@ -# jQuery loadJSON plugin -This is a jQuery plugin that enables developers to load JSON data from the server and load JSON object into the DOM. No templating language is required - this plugin matches DOM elements in the HTML page with a JSON object using a DOM element properties. +# jQuery loadJSON -## Community -Want to contribute to jQuery loadJSON? Awesome! See [CONTRIBUTING](CONTRIBUTING.md) for more information. +A jQuery plugin that fills HTML markup you already have, forms included, with values from a JSON +object. There is no template language: the plugin matches each key of the data to the elements +whose class, id or name is that key, and sets each value in the way that suits the element. Text +goes into content elements, form controls get their value or checked state, links and images get +their `href` and `src`, and arrays repeat an element once per item. -### Code of Conduct -Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md) to ensure that this project is a welcoming place for **everyone** to contribute to. By participating in this project you agree to abide by its terms. +Works with jQuery 1.7 and later, jQuery 4 included. -## Requirements -Requires jQuery 1.7+. +## Install -## Download -* **Development:** [src/jquery.loadJSON.js](https://github.com/kevindb/jquery-load-json/blob/master/src/jquery.loadJSON.js) -* **Production/Minified:** [dist/jquery.loadJSON.min.js](https://github.com/kevindb/jquery-load-json/blob/master/dist/jquery.form.min.js) +With npm: -### CDN -```html - +```sh +npm install jquery-load-json ``` -or -```html - + +```js +import $ from "jquery"; +import "jquery-load-json"; ``` -## Usage -To use loadJSON plugin two items should be defined: - * HTML code that will be used as template - * JSON object that will be used to populate template +The package also has a classic build for script tags, AMD and CommonJS +(`dist/jquery.loadJSON.js`), and a minified one (`dist/jquery.loadJSON.min.js`). -### HTML template -Template is plain HTML code. Only requirement is that elements that should be populated must have id, name, class, or rel attributes that have matching properties in the JSON object. Example of HTML template is shown below: -``` -
-

- - - - -
+From a CDN, after jQuery: + +```html + ``` -In the template h1 tag with id Name, and span tags with ids Address and Contact will be populated with JSON properties. +or -### JSON object -Once HTML template is defined JSON object that will be used to populate template must be defines. Example of object that can populate template shown above is shown in the following listing: -``` - data = { - "Name":"Emkay Entertainments", - "Address":"Nobel House, Regent Centre", - "Contact":"Phone" - } +```html + ``` -Object has three properties (Name, Address, and Contact) that will be injected into the template. -### Binding JSON object to the template -Once HTML template and JSON object are defined, JSON object can be loaded into the HTML code. This can be achieved using the following line of JavaScript code: -``` - $('div#data').loadJSON(data); +## Example + +```html +
+

+

+ Website +
``` -As a result 'data' object will be loaded into the HTML fragment with id data. Resulting HTML is shown in the following listing: + +```js +$("#company").loadJSON({ + Name: "Emkay Entertainments", + Address: "Nobel House, Regent Centre", + Website: "https://example.com", +}); ``` -
-

Emkay Entertainments

- - Nobel House, Regent Centre - - Phone -
+ +```html +
+

Emkay Entertainments

+

Nobel House, Regent Centre

+ Website +
``` -You can find detailed instructions how the plugin can be used in the following pages: - 1. [How to load object into the HTML element](https://github.com/kevindb/jquery-load-json/wiki/LoadingHTMLElements) where is explained how the JavaScript objects are loaded in the HTML elements - 1. [Using loadJSON plugin as a template engine](https://github.com/kevindb/jquery-load-json/wiki/HTMLTemplate) where is explained how this plugin can be used for generating output based on template - 1. [Working with HTML forms](https://github.com/kevindb/jquery-load-json/wiki/WorkingWithFormElements) where is explained how you can load HTML form with JavaScript object - -## Examples -You can see few live examples where it is shown how loadJSON plugin can be used: - 1. [Creating list of elements](examples/list.html) - in this example is shown how the array of JSON objects can be bound to the simple HTML template, - 1. [Showing details of the JSON object](examples/details.html?ID=17) - this example shows how details about the single object can be bound to the HTML template, - 1. [Populating form with JSON object](examples/edit.html?ID=17) - this example shows how you can populate form elements from the JSON object, - 1. [Loading complex/hierarchical structure](examples/hierarchy.html) this example show how you can generate complex structures using loadJSON plugin, - 1. [Generate template for array elements](examples/array.html) in this example is shown how you can define custom templates for different elements in the array, - 1. [Adding load events](examples/events.html) in this example is shown how you can define on load events, - 1. [Loading JSON from the external sites](examples/BingMapsSearch.html) - in this example is shown how you can load JSON data that will be loaded from the external sites - in this case from the Bing Maps web service. - 1. [Populating connected drop-downs using the Ajax calls](examples/categories-ajax.html) - in this example is shown how you can load subcategories drop-downs when parent category drop-down is changed. Drop-down values are taken from the server-side via Ajax calls. - 1. [Populating connected dropdowns using LINQ](examples/linq.html) - in this example is shown how you can load subcategories dropdown when parent category dropdown is changed. Values are stored as a local JavaScript arrays and filtered using the LINQ library. - -## Contributors -This project has had several previous homes. -See [CONTRIBUTORS](CONTRIBUTORS.md) for details. +Values are inserted as HTML in 1.x. Escape data from untrusted sources before loading it. + +## Documentation + +- [Loading data](docs/loading-data.md): templates, keys, matching, nested objects, arguments and + callbacks +- [Elements](docs/elements.md): text, links and images +- [Forms](docs/forms.md): inputs, checkboxes, radio buttons, textareas and selects +- [Arrays and repeats](docs/arrays.md): lists from arrays of objects +- [Debugging and deprecations](docs/debugging.md): `$.fn.loadJSON.debug` and what 2.0 removes +- [Live examples](https://kevindb.github.io/jquery-load-json/examples/) + +## Community + +Want to contribute? See [CONTRIBUTING](CONTRIBUTING.md). Security issues: see +[SECURITY](SECURITY.md). + +This project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating +in it you agree to abide by its terms. + +## Credits + +jQuery loadJSON was created by Jovan Popovic, building on Alexandre Caprais's notemplate plugin. +Thank you, Jovan. Jovan's newer [jquery-view-engine](https://github.com/JocaPC/jquery-view-engine) +takes the same idea further. See [CONTRIBUTORS](CONTRIBUTORS.md) for the project's history. ## License -This repository is licensed under the GNU Lesser General Public License v2.1. -See [LICENSE](LICENSE.md) for details. +GNU Lesser General Public License v2.1 or later. See [LICENSE](LICENSE.md). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..30539bf --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,20 @@ +# Security policy + +## Supported versions + +| Version | Supported | +| -------------------- | --------- | +| 1.x (latest release) | Yes | +| Earlier | No | + +Fixes land on `main` and ship in the next release. + +## Reporting a vulnerability + +Please do not report security issues in public issues, pull requests or discussions. + +Report them privately through GitHub: open the repository's **Security** tab and choose +**Report a vulnerability** (). + +Include the plugin and jQuery versions, the data and markup used, and a minimal reproduction. +Reporters are credited in the advisory unless they ask not to be. diff --git a/bower.json b/bower.json index c4f9b04..3b40dae 100644 --- a/bower.json +++ b/bower.json @@ -1,18 +1,36 @@ { "name": "jquery-load-json", "description": "jQuery plugin that enables developers to load JSON data from the server and load JSON object into the DOM.", - "main": "src/jquery.loadJSON.js", - "moduleType": [ "globals", "amd", "node" ], - "license": "LGPL-2.1", + "main": "dist/jquery.loadJSON.js", + "moduleType": ["globals", "amd", "node"], + "license": "LGPL-2.1-or-later", "ignore": [ - "README.md", + "**/.*", + "docs", + "node_modules", + "scripts", + "test", + "*.config.mjs", "composer.json", - "package.json" + "package.json", + "package-lock.json" + ], + "keywords": [ + "javascript", + "jquery", + "html-form", + "ajax-form", + "json", + "loadjson-plugin", + "jquery-plugin" ], - "keywords": [ "javascript", "jquery", "html-form", "ajax-form", "json", "loadjson-plugin", "jquery-plugin" ], "authors": [ - { "name": "Kevin Morris" }, - { "name": "Jovan Popovic" } + { + "name": "Kevin Morris" + }, + { + "name": "Jovan Popovic" + } ], "homepage": "https://github.com/kevindb/jquery-load-json", "repository": { diff --git a/composer.json b/composer.json index 2a0c1ff..bfde605 100644 --- a/composer.json +++ b/composer.json @@ -1,23 +1,35 @@ { "name": "kevindb/jquery-load-json", "description": "jQuery plugin that enables developers to load JSON data from the server and load JSON object into the DOM.", - "keywords": [ "javascript", "jquery", "html-form", "ajax-form", "json", "loadjson-plugin", "jquery-plugin" ], + "keywords": [ + "javascript", + "jquery", + "html-form", + "ajax-form", + "json", + "loadjson-plugin", + "jquery-plugin" + ], "homepage": "https://github.com/kevindb/jquery-load-json", - "license": "LGPL-2.1", + "license": "LGPL-2.1-or-later", "authors": [ - { "name": "Kevin Morris" }, - { "name": "Jovan Popovic" } + { + "name": "Kevin Morris" + }, + { + "name": "Jovan Popovic" + } ], "support": { "issues": "https://github.com/kevindb/jquery-load-json/issues" }, "require": { - "components/jquery": "^3.4.1" + "components/jquery": ">=1.7" }, "extra": { "component": { "scripts": [ - "src/jquery.loadJSON.js" + "dist/jquery.loadJSON.js" ], "shim": { "deps": [ diff --git a/dist/jquery.loadJSON.js b/dist/jquery.loadJSON.js new file mode 100644 index 0000000..9f2c05d --- /dev/null +++ b/dist/jquery.loadJSON.js @@ -0,0 +1,567 @@ +/*! + * jQuery loadJSON plugin + * v1.4.0 + * https://github.com/kevindb/jquery-load-json + * + * This is a jQuery plugin that enables developers to load JSON data from the server and load JSON object into the DOM. + * + * Copyright 2015 Kevin Morris + * Copyright 2011 Jovan Popovic + * Copyright 2008 Alexandre Caprais + * + * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + */ + +(function (factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['jquery'], factory); + } else if (typeof module === 'object' && module.exports) { + // Node/CommonJS + module.exports = function( root, jQuery ) { + if ( jQuery === undefined ) { + // require('jQuery') returns a factory that requires window to build a jQuery instance, we normalize how we use modules + // that require this pattern but the window provided is a noop if it's defined (how jquery works) + if ( typeof window !== 'undefined' ) { + jQuery = require('jquery'); + } + else { + // jQuery 4 builds a jQuery for a window from jquery/factory; jQuery 3 from the package itself + var jQueryFactory; + try { + jQueryFactory = require('jquery/factory').jQueryFactory; + } catch (error) {} + jQuery = jQueryFactory ? jQueryFactory(root) : require('jquery')(root); + } + } + factory(jQuery); + return jQuery; + }; + } else { + // Browser globals + factory(jQuery); + } + +}(function (jQuery) { + 'use strict'; +// Behavior kept for compatibility with earlier versions and removed in 2.0. + +var $$1 = jQuery; + +// Adds Array.prototype.contains (loose equality), which earlier versions defined on every call. +function installContains() { + notice("contains"); + Object.defineProperty(Array.prototype, "contains", { + configurable: true, + writable: true, + value: function (obj) { + var i = this.length; + while (i--) { + if (this[i] == obj) { + return true; + } + } + return false; + }, + }); +} + +// Refreshes a jQuery Mobile widget (selectmenu or checkboxradio) when the element has one. +function refreshMobile($element, widget) { + try { + if ($$1.isFunction($element[widget])) { + notice("mobile"); + $element[widget]("refresh"); + } + } catch (ex) {} +} + +// Deprecation notices: shown once per page with console.warn when $.fn.loadJSON.debug is true. +var messages = { + contains: + "Array.prototype.contains is deprecated and will be removed in 2.0. Use Array.prototype.indexOf instead.", + mobile: + "Refreshing jQuery Mobile selectmenu and checkboxradio widgets is deprecated and will be removed in 2.0. Refresh them in onLoaded instead.", + mobileOption: "The mobile option has no effect and will be removed in 2.0.", + srcAlt: + 'An image value is used as the whole src: the "src$alt" format is not supported. Pass {src, alt} instead.', + imageFallback: + "Setting images from the top-level src, alt and title is deprecated and will be removed in 2.0. Give each image its own value.", + rel: "Matching keys by the rel attribute is deprecated and will be removed in 2.0. Use a class, id or name.", + relIndex: + 'Loading array items into rel="index" children is deprecated and will be removed in 2.0.', + url: "Passing a URL to loadJSON is deprecated and will be removed in 2.0. Load the data with $.getJSON and pass it to loadJSON.", + html: "Values are inserted as HTML. From 2.0 they are inserted as text unless the html option is true.", +}; + +var shown = {}; + +function notice(id) { + if (!$$1.fn.loadJSON.debug || shown[id]) { + return; + } + shown[id] = true; + console.warn("jQuery loadJSON: " + messages[id]); +} + +// Element kinds: how a value is set on each kind of element. + +var $ = jQuery; + +// Input types whose value is set directly. +var rField = + /^(?:color|date|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/; + +// Appends a copy of the select's last option for each {value, text, selected} item. +function addOptions(select, items) { + var options = jQuery.makeArray(select); + var last = options[options.length - 1]; + var template = $(last).clone(true); + + // Each copy goes right after the original last option, so the items are added from the end + for (var i = items.length - 1; i >= 0; i--) { + var $option = template.clone(true).insertAfter(last); + $option.attr("value", items[i].value); + $option.text(items[i].text); + if (items[i].selected) { + $option.attr("selected", true); + } + } + + refreshMobile($(select), "selectmenu"); +} + +// Whether an array holds a value, comparing with ==. +function containsLoosely(values, value) { + for (var i = 0; i < values.length; i++) { + if (values[i] == value) { + return true; + } + } + return false; +} + +function field(element, value) { + $(element).val(value); +} + +function checkbox(element, value) { + var $element = $(element); + var elementValue = $element.val(); + + $element.prop( + "checked", + (value.constructor == Array && containsLoosely(value, elementValue)) || value == elementValue + ); + refreshMobile($element, "checkboxradio"); +} + +function radio(element, value) { + var $element = $(element); + + $element.prop("checked", value.toString().toLowerCase() == element.value.toLowerCase()); + refreshMobile($element, "checkboxradio"); +} + +function option(element, value) { + var $element = $(element); + + $element.attr("value", value.value); + $element.text(value.text); + if (value.selected) { + $element.attr("selected", true); + } +} + +function selectOne(element, value) { + if (value.constructor == Array) { + addOptions(element, value); + } else { + $(element).val(value); + refreshMobile($(element), "selectmenu"); + } +} + +function selectMultiple(element, value) { + var options = element.options; + + // An array loaded into a select with one option or none adds options; otherwise it selects + if (value.constructor == Array && options.length <= 1) { + addOptions(element, value); + return; + } + + var values = value.constructor == Array ? value : [value]; + for (var i = 0; i < options.length; i++) { + for (var j = 0; j < values.length; j++) { + options[i].selected |= options[i].value == values[j]; + } + } + refreshMobile($(element), "selectmenu"); +} + +function link(element, value, name) { + var $element = $(element); + var href = $element.attr("href"); + + if (href) { + // If a href value exists, add the pair to its query, before any fragment + var iFragment = href.indexOf("#"); + var fragment = ""; + + if (iFragment >= 0) { + fragment = href.substring(iFragment); + href = href.substring(0, iFragment); + } + + href += (href.indexOf("?") >= 0 ? "&" : "?") + name + "=" + value + fragment; + } else { + // If no href exists, set href to value + href = value; + } + + $element.attr("href", href); +} + +function image(element, value, name, data) { + var $element = $(element); + + if (typeof value == "string") { + // A string is the image address + if (value.indexOf("$") >= 0) { + notice("srcAlt"); + } + $element.attr("src", value); + } else if (value.constructor == Object) { + // An object sets the image's own src, alt and title + $element.attr("src", value.src); + $element.attr("alt", value.alt); + $element.attr("title", value.title); + } else { + // Otherwise the top-level src, alt and title apply to every matched image + if (data.src !== undefined || data.alt !== undefined || data.title !== undefined) { + notice("imageFallback"); + } + $element.attr("src", data.src); + $element.attr("alt", data.alt); + $element.attr("title", data.title); + } +} + +function content(element, value) { + if (typeof value == "string" && /<[a-z!/?]/i.test(value)) { + notice("html"); + } + try { + $(element).html(value.toString()); + } catch (exc) {} +} + +var kinds = { + field: field, + checkbox: checkbox, + radio: radio, + option: option, + "select-one": selectOne, + "select-multiple": selectMultiple, + link: link, + image: image, + content: content, +}; + +// The element kind of a DOM element, from its type or, when it has none, its tag name. +function kindOf(element) { + var type = (element.type || element.tagName).toLowerCase(); + + switch (type) { + case "checkbox": + case "radio": + case "option": + case "select-one": + case "select-multiple": + return type; + case "a": + return "link"; + case "img": + return "image"; + default: + return rField.test(type) ? "field" : "content"; + } +} + +/** + * Sets a value on an element by its kind. `element` is a DOM element or a jQuery set of one; + * `name` is the key the value was loaded from and `data` the data passed to loadJSON. + */ +function setValue(element, value, name, data) { + var node = $(element)[0]; + + kinds[kindOf(node)](node, value, name, data); +} + +// Whether a DOM element's kind takes an object whole (an option or an image), rather than the walk +// loading each of its keys into a match. +function takesObject(element) { + var kind = kindOf(element); + + return kind == "option" || kind == "image"; +} + +// Each step of a match: its selector for the key, and the same test without a selector. +var steps = [ + { + selector: function (key) { + return "." + key; + }, + test: function (element, key) { + return jQuery(element).hasClass(key); + }, + }, + { + selector: function (key) { + return "#" + key; + }, + test: function (element, key) { + return element.id === key; + }, + }, + { + selector: function (key) { + return '[name="' + key + '"]'; + }, + test: function (element, key) { + return element.getAttribute("name") === key; + }, + }, +]; + +var relStep = { + selector: function (key) { + return '[rel="' + key + '"]'; + }, + test: function (element, key) { + return element.getAttribute("rel") === key; + }, +}; + +// Whether the browser accepts a selector as CSS. +function isValidCss(selector) { + try { + document.createDocumentFragment().querySelector(selector); + return true; + } catch (error) { + return false; + } +} + +// Runs a step's selector inside scope. When the key makes the selector invalid (jQuery throws, or, +// before jQuery 3, finds nothing for a selector the browser rejects), it compares each element's +// attribute with the key instead. +function query(step, key, scope) { + var selector = step.selector(key); + + try { + var $matches = jQuery(selector, scope); + if ($matches.length > 0 || isValidCss(selector)) { + return $matches; + } + } catch (error) {} + + return jQuery(scope) + .find("*") + .filter(function () { + return step.test(this, key); + }); +} + +/** + * The match of a key: the elements inside `scope` whose class, then id, then name is the key. + * When none match, the elements anywhere in the document whose rel attribute is the key. + */ +function match(key, scope) { + for (var i = 0; i < steps.length; i++) { + var $matches = query(steps[i], key, scope); + if ($matches.length > 0) { + return $matches; + } + } + + var $rel = query(relStep, key, document); + if ($rel.length > 0) { + notice("rel"); + } + return $rel; +} + + +(function ($) { + + // Whether a DOM element is a select (one or multiple). + function isSelect(element) { + return element.nodeType === 1 && /^select-/.test(kindOf(element)); + } + + // Loads each key of an object into its match within the element. + function walkObject(object, element, name, data) { + // An option or an image matched by the enclosing key takes the object whole + if (element.length >= 1 && takesObject(element[0])) { + if (kindOf(element[0]) == "option") { + setValue(element[0], object, name, data); + } else { + element.each(function () { + setValue(this, object, name, data); + }); + } + } + + for (var key in object) { + if (key.length === 0) { + continue; + } + var $match = match(key, element); + if ($match.length !== 0) { + walk(object[key], $match, key, data); + } + } + } + + // Loads an array: whole into a select or a checkbox group, item by item into rel index + // children, or as a repeat of the element. + function walkArray(array, element, name, data) { + if (element.length == 1 && (isSelect(element) || isSelect(element[0]))) { + setValue(element, array, name, data); + return; + } + + if (element.length > 0 && kindOf(element[0]) == "checkbox") { + element.each(function () { + setValue(this, array, name, data); + }); + return; + } + + var $element = $(element); + var $children = $element.children("[rel]"); + if ($children.length > 0) { + notice("relIndex"); + $children.each(function () { + var $child = $(this); + walk(array[$child.attr("rel")], $child, name, data); + }); + return; + } + + repeat(array, element, name, data); + } + + // Fills the existing elements in order, then appends copies of the last one for the remaining + // items. A select's options are not filled; each item gets a copy of the last option. + function repeat(array, element, name, data) { + var elements = jQuery.makeArray(element); + var last = elements[elements.length - 1]; + var $copySource = $(last).clone(true); + var filled = 0; + + if (elements[0].tagName != "OPTION") { + filled = Math.min(elements.length, array.length); + for (var i = 0; i < filled; i++) { + walk(array[i], $(element).eq(i), name, data); + } + } + + // Each copy goes right after the original last element, so the items are added from the end + for (var j = array.length - 1; j >= filled; j--) { + walk(array[j], $copySource.clone(true).insertAfter(last), name, data); + } + } + + // Sets a single value on each element of the set, or on the element itself. + function walkValue(value, element, name, data) { + if (element.length > 0) { + for (var i = 0; i < element.length; i++) { + setValue(element[i], value, name, data); + } + } else { + setValue(element, value, name, data); + } + } + + // Loads a value of any shape into an element (a DOM element or a jQuery set). + function walk(value, element, name, data) { + if (value === undefined || value === null) { + return; + } + if (value.constructor == Object) { + walkObject(value, element, name, data); + } else if (value.constructor == Array) { + walkArray(value, element, name, data); + } else { + walkValue(value, element, name, data); + } + } + + // Restores the saved template, or saves the current markup when there is none. + function useSavedTemplate($element) { + var saved = $element.data("loadJSON-template"); + + if (saved !== null && saved != "") { + $element.html(saved); + } else { + $element.data("loadJSON-template", $element.html()); + } + } + + // Loads data into one element: the saved template, the callbacks and the walk. + function load(element, data, argument, properties) { + useSavedTemplate($(element)); + properties.onLoading(); + walk(data, element, undefined, argument); + properties.onLoaded(); + } + + // Loads the loadJSON argument into one element. A string starting with { or [ is JSON; any + // other string is a URL, requested once per element, whose response is loaded the same way. + function loadArgument(element, argument, properties) { + if (argument.constructor != String) { + load(element, argument, argument, properties); + } else if (argument.charAt(0) == "{" || argument.charAt(0) == "[") { + load(element, JSON.parse(argument), argument, properties); + } else { + notice("url"); + $.ajax({ + url: argument, + success: function (response) { + loadArgument(element, response, properties); + }, + cache: false, + dataType: "json", + }); + } + } + + $.fn.loadJSON = function (data, options) { + installContains(); + if (options && "mobile" in options) { + notice("mobileOption"); + } + + var defaults = { + onLoading: function () {}, + onLoaded: function () {}, + mobile: false, + }; + var properties = $.extend(defaults, options); + + return this.each(function () { + loadArgument(this, data, properties); + }); + }; + + // Set to true to show a console warning, once per page, for each behavior removed in 2.0. + $.fn.loadJSON.debug = false; +})(jQuery); +})); diff --git a/dist/jquery.loadJSON.min.js b/dist/jquery.loadJSON.min.js index c129d7c..be46af8 100644 --- a/dist/jquery.loadJSON.min.js +++ b/dist/jquery.loadJSON.min.js @@ -1,18 +1,19 @@ /*! -* jQuery loadJSON plugin -* v1.3.4 -* https://github.com/kevindb/jquery-load-json -* -* This is a jQuery plugin that enables developers to load JSON data from the server and load JSON object into the DOM. -* -* Copyright 2015 Kevin Morris -* Copyright 2011 Jovan Popovic -* Copyright 2008 Alexandre Caprais -* -* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public -* License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. -* -* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. -*/ -!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof module&&module.exports?module.exports=function(b,c){return void 0===c&&(c="undefined"!=typeof window?require("jquery"):require("jquery")(b)),a(c),c}:a(jQuery)}(function(a){"use strict";a.fn.loadJSON=function(b,c){function d(b){try{a.isFunction(b.selectmenu)&&b.selectmenu("refresh")}catch(a){}}function e(b){try{a.isFunction(b.checkboxradio)&&b.checkboxradio("refresh")}catch(a){}}function f(c,e,f){for(var g=jQuery.makeArray(c),h=a(g[g.length-1]).clone(!0),i=b.length,j=i-1,k=0;k1){for(var m=g.constructor==Array?g:[g],n=0;n1e6?p=p.substr(0,q)+"&"+h+"="+g+p.substr(q):(q=p.indexOf("?"),q>0?p+="&"+h+"="+g:p=p+"?"+h+"="+g)}else p=g;i.attr("href",p);break;case"img":if("String"==b.constructor){var q=g.indexOf("$"),r="",s="";if(q>0)r=g.substring(0,q),s=g.substring(q+1);else{r=g;var t=g.lastIndexOf("/")+1,u=g.indexOf(".");s=g.substring(t,u)}i.attr("src",r),i.attr("alt",s)}else i.attr("src",b.src),i.attr("alt",b.alt),i.attr("title",b.title);break;case"textarea":case"submit":case"button":default:try{i.html(g.toString())}catch(a){}}}function h(b,c,d){var e=a(c);if(void 0===b||null===b);else if(b.constructor==Object){c.length>=1&&"OPTION"==c[0].tagName&&g(c[0],b,d);for(var f in b)if(null!==f&&void 0!==f&&0!==f.length){var i=jQuery.makeArray(jQuery("."+f,c)).length>0?jQuery("."+f,c):jQuery("#"+f,c).length>0?jQuery("#"+f,c):jQuery('[name="'+f+'"]',c).length>0?jQuery('[name="'+f+'"]',c):jQuery('[rel="'+f+'"]');0!==i.length&&h(b[f],jQuery(i,c),f)}}else if(b.constructor==Array){if(1==c.length&&("select"==c.type||"select-one"==c.type||"select-multiple"==c.type||"select"==c[0].type||"select-one"==c[0].type||"select-multiple"==c[0].type))return void g(c,b,d);if(c.length>0&&"checkbox"==c[0].type)c.each(function(){g(this,b,d)});else{var j=e.children("[rel]");if(j.length>0)j.each(function(){var c=a(this),e=c.attr("rel");h(b[e],c,d)});else{var k=jQuery.makeArray(c),l=k.length,m=a(k[l-1]).clone(!0),n=b.length,o=0;if(null===c[0]||null!==c[0]&&"OPTION"!=c[0].tagName){for(var p=0;p0)for(var o=0;o=0;l--){var u=c.clone(!0).insertAfter(o);u.attr("value",r[l].value),u.text(r[l].text),r[l].selected&&u.attr("selected",!0)}n(i(t),"selectmenu")}var u={field:function(e,t){i(e).val(t)},checkbox:function(e,t){var r=i(e),a=r.val();r.prop("checked",t.constructor==Array&&function(e,t){for(var n=0;n=0&&(c=a.substring(o),a=a.substring(0,o)),a+=(a.indexOf("?")>=0?"&":"?")+n+"="+t+c}else a=t;r.attr("href",a)},image:function(e,t,n,r){var a=i(e);"string"==typeof t?(t.indexOf("$")>=0&&o("srcAlt"),a.attr("src",t)):t.constructor==Object?(a.attr("src",t.src),a.attr("alt",t.alt),a.attr("title",t.title)):(void 0===r.src&&void 0===r.alt&&void 0===r.title||o("imageFallback"),a.attr("src",r.src),a.attr("alt",r.alt),a.attr("title",r.title))},content:function(e,t){"string"==typeof t&&/<[a-z!/?]/i.test(t)&&o("html");try{i(e).html(t.toString())}catch(e){}}};function s(e){var t=(e.type||e.tagName).toLowerCase();switch(t){case"checkbox":case"radio":case"option":case"select-one":case"select-multiple":return t;case"a":return"link";case"img":return"image";default:return c.test(t)?"field":"content"}}function d(e,t,n,r){var a=i(e)[0];u[s(a)](a,t,n,r)}var f=[{selector:function(e){return"."+e},test:function(t,n){return e(t).hasClass(n)}},{selector:function(e){return"#"+e},test:function(e,t){return e.id===t}},{selector:function(e){return'[name="'+e+'"]'},test:function(e,t){return e.getAttribute("name")===t}}],h={selector:function(e){return'[rel="'+e+'"]'},test:function(e,t){return e.getAttribute("rel")===t}};function v(t,n,r){var a=t.selector(n);try{var o=e(a,r);if(o.length>0||function(e){try{return document.createDocumentFragment().querySelector(e),!0}catch(e){return!1}}(a))return o}catch(e){}return e(r).find("*").filter(function(){return t.test(this,n)})}function m(e,t){for(var n=0;n0)return r}var a=v(h,e,document);return a.length>0&&o("rel"),a}!function(t){function n(e){return 1===e.nodeType&&/^select-/.test(s(e))}function r(e,t,n,r){for(var a in t.length>=1&&function(e){var t=s(e);return"option"==t||"image"==t}(t[0])&&("option"==s(t[0])?d(t[0],e,n,r):t.each(function(){d(this,e,n,r)})),e)if(0!==a.length){var o=m(a,t);0!==o.length&&i(e[a],o,a,r)}}function a(r,a,c,l){if(1!=a.length||!n(a)&&!n(a[0]))if(a.length>0&&"checkbox"==s(a[0]))a.each(function(){d(this,r,c,l)});else{var u=t(a).children("[rel]");if(u.length>0)return o("relIndex"),void u.each(function(){var e=t(this);i(r[e.attr("rel")],e,c,l)});!function(n,r,a,o){var c=e.makeArray(r),l=c[c.length-1],u=t(l).clone(!0),s=0;if("OPTION"!=c[0].tagName){s=Math.min(c.length,n.length);for(var d=0;d=s;f--)i(n[f],u.clone(!0).insertAfter(l),a,o)}(r,a,c,l)}else d(a,r,c,l)}function i(e,t,n,o){null!=e&&(e.constructor==Object?r(e,t,n,o):e.constructor==Array?a(e,t,n,o):function(e,t,n,r){if(t.length>0)for(var a=0;a= 0; i--) {\n var $option = template.clone(true).insertAfter(last);\n $option.attr(\"value\", items[i].value);\n $option.text(items[i].text);\n if (items[i].selected) {\n $option.attr(\"selected\", true);\n }\n }\n\n refreshMobile($(select), \"selectmenu\");\n}\n\n// Whether an array holds a value, comparing with ==.\nfunction containsLoosely(values, value) {\n for (var i = 0; i < values.length; i++) {\n if (values[i] == value) {\n return true;\n }\n }\n return false;\n}\n\nfunction field(element, value) {\n $(element).val(value);\n}\n\nfunction checkbox(element, value) {\n var $element = $(element);\n var elementValue = $element.val();\n\n $element.prop(\n \"checked\",\n (value.constructor == Array && containsLoosely(value, elementValue)) || value == elementValue\n );\n refreshMobile($element, \"checkboxradio\");\n}\n\nfunction radio(element, value) {\n var $element = $(element);\n\n $element.prop(\"checked\", value.toString().toLowerCase() == element.value.toLowerCase());\n refreshMobile($element, \"checkboxradio\");\n}\n\nfunction option(element, value) {\n var $element = $(element);\n\n $element.attr(\"value\", value.value);\n $element.text(value.text);\n if (value.selected) {\n $element.attr(\"selected\", true);\n }\n}\n\nfunction selectOne(element, value) {\n if (value.constructor == Array) {\n addOptions(element, value);\n } else {\n $(element).val(value);\n refreshMobile($(element), \"selectmenu\");\n }\n}\n\nfunction selectMultiple(element, value) {\n var options = element.options;\n\n // An array loaded into a select with one option or none adds options; otherwise it selects\n if (value.constructor == Array && options.length <= 1) {\n addOptions(element, value);\n return;\n }\n\n var values = value.constructor == Array ? value : [value];\n for (var i = 0; i < options.length; i++) {\n for (var j = 0; j < values.length; j++) {\n options[i].selected |= options[i].value == values[j];\n }\n }\n refreshMobile($(element), \"selectmenu\");\n}\n\nfunction link(element, value, name) {\n var $element = $(element);\n var href = $element.attr(\"href\");\n\n if (href) {\n // If a href value exists, add the pair to its query, before any fragment\n var iFragment = href.indexOf(\"#\");\n var fragment = \"\";\n\n if (iFragment >= 0) {\n fragment = href.substring(iFragment);\n href = href.substring(0, iFragment);\n }\n\n href += (href.indexOf(\"?\") >= 0 ? \"&\" : \"?\") + name + \"=\" + value + fragment;\n } else {\n // If no href exists, set href to value\n href = value;\n }\n\n $element.attr(\"href\", href);\n}\n\nfunction image(element, value, name, data) {\n var $element = $(element);\n\n if (typeof value == \"string\") {\n // A string is the image address\n if (value.indexOf(\"$\") >= 0) {\n notice(\"srcAlt\");\n }\n $element.attr(\"src\", value);\n } else if (value.constructor == Object) {\n // An object sets the image's own src, alt and title\n $element.attr(\"src\", value.src);\n $element.attr(\"alt\", value.alt);\n $element.attr(\"title\", value.title);\n } else {\n // Otherwise the top-level src, alt and title apply to every matched image\n if (data.src !== undefined || data.alt !== undefined || data.title !== undefined) {\n notice(\"imageFallback\");\n }\n $element.attr(\"src\", data.src);\n $element.attr(\"alt\", data.alt);\n $element.attr(\"title\", data.title);\n }\n}\n\nfunction content(element, value) {\n if (typeof value == \"string\" && /<[a-z!/?]/i.test(value)) {\n notice(\"html\");\n }\n try {\n $(element).html(value.toString());\n } catch (exc) {}\n}\n\nvar kinds = {\n field: field,\n checkbox: checkbox,\n radio: radio,\n option: option,\n \"select-one\": selectOne,\n \"select-multiple\": selectMultiple,\n link: link,\n image: image,\n content: content,\n};\n\n// The element kind of a DOM element, from its type or, when it has none, its tag name.\nexport function kindOf(element) {\n var type = (element.type || element.tagName).toLowerCase();\n\n switch (type) {\n case \"checkbox\":\n case \"radio\":\n case \"option\":\n case \"select-one\":\n case \"select-multiple\":\n return type;\n case \"a\":\n return \"link\";\n case \"img\":\n return \"image\";\n default:\n return rField.test(type) ? \"field\" : \"content\";\n }\n}\n\n/**\n * Sets a value on an element by its kind. `element` is a DOM element or a jQuery set of one;\n * `name` is the key the value was loaded from and `data` the data passed to loadJSON.\n */\nexport function setValue(element, value, name, data) {\n var node = $(element)[0];\n\n kinds[kindOf(node)](node, value, name, data);\n}\n\n// Whether a DOM element's kind takes an object whole (an option or an image), rather than the walk\n// loading each of its keys into a match.\nexport function takesObject(element) {\n var kind = kindOf(element);\n\n return kind == \"option\" || kind == \"image\";\n}\n","import jQuery from \"jquery\";\nimport { notice } from \"./legacy.js\";\n\n// Each step of a match: its selector for the key, and the same test without a selector.\nvar steps = [\n {\n selector: function (key) {\n return \".\" + key;\n },\n test: function (element, key) {\n return jQuery(element).hasClass(key);\n },\n },\n {\n selector: function (key) {\n return \"#\" + key;\n },\n test: function (element, key) {\n return element.id === key;\n },\n },\n {\n selector: function (key) {\n return '[name=\"' + key + '\"]';\n },\n test: function (element, key) {\n return element.getAttribute(\"name\") === key;\n },\n },\n];\n\nvar relStep = {\n selector: function (key) {\n return '[rel=\"' + key + '\"]';\n },\n test: function (element, key) {\n return element.getAttribute(\"rel\") === key;\n },\n};\n\n// Whether the browser accepts a selector as CSS.\nfunction isValidCss(selector) {\n try {\n document.createDocumentFragment().querySelector(selector);\n return true;\n } catch (error) {\n return false;\n }\n}\n\n// Runs a step's selector inside scope. When the key makes the selector invalid (jQuery throws, or,\n// before jQuery 3, finds nothing for a selector the browser rejects), it compares each element's\n// attribute with the key instead.\nfunction query(step, key, scope) {\n var selector = step.selector(key);\n\n try {\n var $matches = jQuery(selector, scope);\n if ($matches.length > 0 || isValidCss(selector)) {\n return $matches;\n }\n } catch (error) {}\n\n return jQuery(scope)\n .find(\"*\")\n .filter(function () {\n return step.test(this, key);\n });\n}\n\n/**\n * The match of a key: the elements inside `scope` whose class, then id, then name is the key.\n * When none match, the elements anywhere in the document whose rel attribute is the key.\n */\nexport function match(key, scope) {\n for (var i = 0; i < steps.length; i++) {\n var $matches = query(steps[i], key, scope);\n if ($matches.length > 0) {\n return $matches;\n }\n }\n\n var $rel = query(relStep, key, document);\n if ($rel.length > 0) {\n notice(\"rel\");\n }\n return $rel;\n}\n","/*!\n * jQuery loadJSON plugin\n * v1.4.0\n * https://github.com/kevindb/jquery-load-json\n *\n * This is a jQuery plugin that enables developers to load JSON data from the server and load JSON object into the DOM.\n *\n * Copyright 2015 Kevin Morris\n * Copyright 2011 Jovan Popovic\n * Copyright 2008 Alexandre Caprais\n *\n * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.\n */\n\nimport jQuery from \"jquery\";\nimport { kindOf, setValue, takesObject } from \"./element-kinds.js\";\nimport { installContains, notice } from \"./legacy.js\";\nimport { match } from \"./key-match.js\";\n\n(function ($) {\n \"use strict\";\n\n // Whether a DOM element is a select (one or multiple).\n function isSelect(element) {\n return element.nodeType === 1 && /^select-/.test(kindOf(element));\n }\n\n // Loads each key of an object into its match within the element.\n function walkObject(object, element, name, data) {\n // An option or an image matched by the enclosing key takes the object whole\n if (element.length >= 1 && takesObject(element[0])) {\n if (kindOf(element[0]) == \"option\") {\n setValue(element[0], object, name, data);\n } else {\n element.each(function () {\n setValue(this, object, name, data);\n });\n }\n }\n\n for (var key in object) {\n if (key.length === 0) {\n continue;\n }\n var $match = match(key, element);\n if ($match.length !== 0) {\n walk(object[key], $match, key, data);\n }\n }\n }\n\n // Loads an array: whole into a select or a checkbox group, item by item into rel index\n // children, or as a repeat of the element.\n function walkArray(array, element, name, data) {\n if (element.length == 1 && (isSelect(element) || isSelect(element[0]))) {\n setValue(element, array, name, data);\n return;\n }\n\n if (element.length > 0 && kindOf(element[0]) == \"checkbox\") {\n element.each(function () {\n setValue(this, array, name, data);\n });\n return;\n }\n\n var $element = $(element);\n var $children = $element.children(\"[rel]\");\n if ($children.length > 0) {\n notice(\"relIndex\");\n $children.each(function () {\n var $child = $(this);\n walk(array[$child.attr(\"rel\")], $child, name, data);\n });\n return;\n }\n\n repeat(array, element, name, data);\n }\n\n // Fills the existing elements in order, then appends copies of the last one for the remaining\n // items. A select's options are not filled; each item gets a copy of the last option.\n function repeat(array, element, name, data) {\n var elements = jQuery.makeArray(element);\n var last = elements[elements.length - 1];\n var $copySource = $(last).clone(true);\n var filled = 0;\n\n if (elements[0].tagName != \"OPTION\") {\n filled = Math.min(elements.length, array.length);\n for (var i = 0; i < filled; i++) {\n walk(array[i], $(element).eq(i), name, data);\n }\n }\n\n // Each copy goes right after the original last element, so the items are added from the end\n for (var j = array.length - 1; j >= filled; j--) {\n walk(array[j], $copySource.clone(true).insertAfter(last), name, data);\n }\n }\n\n // Sets a single value on each element of the set, or on the element itself.\n function walkValue(value, element, name, data) {\n if (element.length > 0) {\n for (var i = 0; i < element.length; i++) {\n setValue(element[i], value, name, data);\n }\n } else {\n setValue(element, value, name, data);\n }\n }\n\n // Loads a value of any shape into an element (a DOM element or a jQuery set).\n function walk(value, element, name, data) {\n if (value === undefined || value === null) {\n return;\n }\n if (value.constructor == Object) {\n walkObject(value, element, name, data);\n } else if (value.constructor == Array) {\n walkArray(value, element, name, data);\n } else {\n walkValue(value, element, name, data);\n }\n }\n\n // Restores the saved template, or saves the current markup when there is none.\n function useSavedTemplate($element) {\n var saved = $element.data(\"loadJSON-template\");\n\n if (saved !== null && saved != \"\") {\n $element.html(saved);\n } else {\n $element.data(\"loadJSON-template\", $element.html());\n }\n }\n\n // Loads data into one element: the saved template, the callbacks and the walk.\n function load(element, data, argument, properties) {\n useSavedTemplate($(element));\n properties.onLoading();\n walk(data, element, undefined, argument);\n properties.onLoaded();\n }\n\n // Loads the loadJSON argument into one element. A string starting with { or [ is JSON; any\n // other string is a URL, requested once per element, whose response is loaded the same way.\n function loadArgument(element, argument, properties) {\n if (argument.constructor != String) {\n load(element, argument, argument, properties);\n } else if (argument.charAt(0) == \"{\" || argument.charAt(0) == \"[\") {\n load(element, JSON.parse(argument), argument, properties);\n } else {\n notice(\"url\");\n $.ajax({\n url: argument,\n success: function (response) {\n loadArgument(element, response, properties);\n },\n cache: false,\n dataType: \"json\",\n });\n }\n }\n\n $.fn.loadJSON = function (data, options) {\n installContains();\n if (options && \"mobile\" in options) {\n notice(\"mobileOption\");\n }\n\n var defaults = {\n onLoading: function () {},\n onLoaded: function () {},\n mobile: false,\n };\n var properties = $.extend(defaults, options);\n\n return this.each(function () {\n loadArgument(this, data, properties);\n });\n };\n\n // Set to true to show a console warning, once per page, for each behavior removed in 2.0.\n $.fn.loadJSON.debug = false;\n})(jQuery);\n\nexport default jQuery;\n"],"names":["$","jQuery","refreshMobile","$element","widget","isFunction","notice","ex","messages","contains","mobile","mobileOption","srcAlt","imageFallback","rel","relIndex","url","html","shown","id","fn","loadJSON","debug","console","warn","rField","addOptions","select","items","options","makeArray","last","length","template","clone","i","$option","insertAfter","attr","value","text","selected","kinds","field","element","val","checkbox","elementValue","prop","constructor","Array","values","containsLoosely","radio","toString","toLowerCase","option","j","link","name","href","iFragment","indexOf","fragment","substring","image","data","Object","src","alt","title","undefined","content","test","exc","kindOf","type","tagName","setValue","node","steps","selector","key","hasClass","getAttribute","relStep","query","step","scope","$matches","document","createDocumentFragment","querySelector","error","isValidCss","find","filter","this","match","$rel","isSelect","nodeType","walkObject","object","kind","takesObject","each","$match","walk","walkArray","array","$children","children","$child","elements","$copySource","filled","Math","min","eq","repeat","walkValue","load","argument","properties","saved","onLoading","onLoaded","loadArgument","String","charAt","JSON","parse","ajax","success","response","cache","dataType","defineProperty","prototype","configurable","writable","obj","extend"],"mappings":";;;;;;;;;;;;;;;;;iWAIA,IAAIA,EAAIC,EAqBD,SAASC,EAAcC,EAAUC,GACtC,IACMJ,EAAEK,WAAWF,EAASC,MACxBE,EAAO,UACPH,EAASC,GAAQ,WAErB,CAAE,MAAOG,GAAK,CAChB,CAGA,IAAIC,EAAW,CACbC,SACE,0GACFC,OACE,4IACFC,aAAc,8DACdC,OACE,2GACFC,cACE,gIACFC,IAAK,wGACLC,SACE,0FACFC,IAAK,4HACLC,KAAM,mGAGJC,EAAQ,CAAA,EAEL,SAASZ,EAAOa,GAChBnB,EAAEoB,GAAGC,SAASC,QAASJ,EAAMC,KAGlCD,EAAMC,IAAM,EACZI,QAAQC,KAAK,oBAAsBhB,EAASW,IAC9C,CCvDA,IAAInB,EAAIC,EAGJwB,EACF,yGAGF,SAASC,EAAWC,EAAQC,GAM1B,IALA,IAAIC,EAAU5B,EAAO6B,UAAUH,GAC3BI,EAAOF,EAAQA,EAAQG,OAAS,GAChCC,EAAWjC,EAAE+B,GAAMG,OAAM,GAGpBC,EAAIP,EAAMI,OAAS,EAAGG,GAAK,EAAGA,IAAK,CAC1C,IAAIC,EAAUH,EAASC,OAAM,GAAMG,YAAYN,GAC/CK,EAAQE,KAAK,QAASV,EAAMO,GAAGI,OAC/BH,EAAQI,KAAKZ,EAAMO,GAAGK,MAClBZ,EAAMO,GAAGM,UACXL,EAAQE,KAAK,YAAY,EAE7B,CAEApC,EAAcF,EAAE2B,GAAS,aAC3B,CAgIA,IAAIe,EAAQ,CACVC,MArHF,SAAeC,EAASL,GACtBvC,EAAE4C,GAASC,IAAIN,EACjB,EAoHEO,SAlHF,SAAkBF,EAASL,GACzB,IAAIpC,EAAWH,EAAE4C,GACbG,EAAe5C,EAAS0C,MAE5B1C,EAAS6C,KACP,UACCT,EAAMU,aAAeC,OAnB1B,SAAyBC,EAAQZ,GAC/B,IAAK,IAAIJ,EAAI,EAAGA,EAAIgB,EAAOnB,OAAQG,IACjC,GAAIgB,EAAOhB,IAAMI,EACf,OAAO,EAGX,OAAO,CACT,CAYmCa,CAAgBb,EAAOQ,IAAkBR,GAASQ,GAEnF7C,EAAcC,EAAU,gBAC1B,EA0GEkD,MAxGF,SAAeT,EAASL,GACtB,IAAIpC,EAAWH,EAAE4C,GAEjBzC,EAAS6C,KAAK,UAAWT,EAAMe,WAAWC,eAAiBX,EAAQL,MAAMgB,eACzErD,EAAcC,EAAU,gBAC1B,EAoGEqD,OAlGF,SAAgBZ,EAASL,GACvB,IAAIpC,EAAWH,EAAE4C,GAEjBzC,EAASmC,KAAK,QAASC,EAAMA,OAC7BpC,EAASqC,KAAKD,EAAMC,MAChBD,EAAME,UACRtC,EAASmC,KAAK,YAAY,EAE9B,EA2FE,aAzFF,SAAmBM,EAASL,GACtBA,EAAMU,aAAeC,MACvBxB,EAAWkB,EAASL,IAEpBvC,EAAE4C,GAASC,IAAIN,GACfrC,EAAcF,EAAE4C,GAAU,cAE9B,EAmFE,kBAjFF,SAAwBA,EAASL,GAC/B,IAAIV,EAAUe,EAAQf,QAGtB,GAAIU,EAAMU,aAAeC,OAASrB,EAAQG,QAAU,EAClDN,EAAWkB,EAASL,OADtB,CAMA,IADA,IAAIY,EAASZ,EAAMU,aAAeC,MAAQX,EAAQ,CAACA,GAC1CJ,EAAI,EAAGA,EAAIN,EAAQG,OAAQG,IAClC,IAAK,IAAIsB,EAAI,EAAGA,EAAIN,EAAOnB,OAAQyB,IACjC5B,EAAQM,GAAGM,UAAYZ,EAAQM,GAAGI,OAASY,EAAOM,GAGtDvD,EAAcF,EAAE4C,GAAU,aAR1B,CASF,EAkEEc,KAhEF,SAAcd,EAASL,EAAOoB,GAC5B,IAAIxD,EAAWH,EAAE4C,GACbgB,EAAOzD,EAASmC,KAAK,QAEzB,GAAIsB,EAAM,CAER,IAAIC,EAAYD,EAAKE,QAAQ,KACzBC,EAAW,GAEXF,GAAa,IACfE,EAAWH,EAAKI,UAAUH,GAC1BD,EAAOA,EAAKI,UAAU,EAAGH,IAG3BD,IAASA,EAAKE,QAAQ,MAAQ,EAAI,IAAM,KAAOH,EAAO,IAAMpB,EAAQwB,CACtE,MAEEH,EAAOrB,EAGTpC,EAASmC,KAAK,OAAQsB,EACxB,EA4CEK,MA1CF,SAAerB,EAASL,EAAOoB,EAAMO,GACnC,IAAI/D,EAAWH,EAAE4C,GAEG,iBAATL,GAELA,EAAMuB,QAAQ,MAAQ,GACxBxD,EAAO,UAETH,EAASmC,KAAK,MAAOC,IACZA,EAAMU,aAAekB,QAE9BhE,EAASmC,KAAK,MAAOC,EAAM6B,KAC3BjE,EAASmC,KAAK,MAAOC,EAAM8B,KAC3BlE,EAASmC,KAAK,QAASC,EAAM+B,cAGZC,IAAbL,EAAKE,UAAkCG,IAAbL,EAAKG,UAAoCE,IAAfL,EAAKI,OAC3DhE,EAAO,iBAETH,EAASmC,KAAK,MAAO4B,EAAKE,KAC1BjE,EAASmC,KAAK,MAAO4B,EAAKG,KAC1BlE,EAASmC,KAAK,QAAS4B,EAAKI,OAEhC,EAoBEE,QAlBF,SAAiB5B,EAASL,GACJ,iBAATA,GAAqB,aAAakC,KAAKlC,IAChDjC,EAAO,QAET,IACEN,EAAE4C,GAAS3B,KAAKsB,EAAMe,WACxB,CAAE,MAAOoB,GAAM,CACjB,GAeO,SAASC,EAAO/B,GACrB,IAAIgC,GAAQhC,EAAQgC,MAAQhC,EAAQiC,SAAStB,cAE7C,OAAQqB,GACN,IAAK,WACL,IAAK,QACL,IAAK,SACL,IAAK,aACL,IAAK,kBACH,OAAOA,EACT,IAAK,IACH,MAAO,OACT,IAAK,MACH,MAAO,QACT,QACE,OAAOnD,EAAOgD,KAAKG,GAAQ,QAAU,UAE3C,CAMO,SAASE,EAASlC,EAASL,EAAOoB,EAAMO,GAC7C,IAAIa,EAAO/E,EAAE4C,GAAS,GAEtBF,EAAMiC,EAAOI,IAAOA,EAAMxC,EAAOoB,EAAMO,EACzC,CChMA,IAAIc,EAAQ,CACV,CACEC,SAAU,SAAUC,GAClB,MAAO,IAAMA,CACf,EACAT,KAAM,SAAU7B,EAASsC,GACvB,OAAOjF,EAAO2C,GAASuC,SAASD,EAClC,GAEF,CACED,SAAU,SAAUC,GAClB,MAAO,IAAMA,CACf,EACAT,KAAM,SAAU7B,EAASsC,GACvB,OAAOtC,EAAQzB,KAAO+D,CACxB,GAEF,CACED,SAAU,SAAUC,GAClB,MAAO,UAAYA,EAAM,IAC3B,EACAT,KAAM,SAAU7B,EAASsC,GACvB,OAAOtC,EAAQwC,aAAa,UAAYF,CAC1C,IAIAG,EAAU,CACZJ,SAAU,SAAUC,GAClB,MAAO,SAAWA,EAAM,IAC1B,EACAT,KAAM,SAAU7B,EAASsC,GACvB,OAAOtC,EAAQwC,aAAa,SAAWF,CACzC,GAgBF,SAASI,EAAMC,EAAML,EAAKM,GACxB,IAAIP,EAAWM,EAAKN,SAASC,GAE7B,IACE,IAAIO,EAAWxF,EAAOgF,EAAUO,GAChC,GAAIC,EAASzD,OAAS,GAjB1B,SAAoBiD,GAClB,IAEE,OADAS,SAASC,yBAAyBC,cAAcX,IACzC,CACT,CAAE,MAAOY,GACP,OAAO,CACT,CACF,CAU+BC,CAAWb,GACpC,OAAOQ,CAEX,CAAE,MAAOI,GAAQ,CAEjB,OAAO5F,EAAOuF,GACXO,KAAK,KACLC,OAAO,WACN,OAAOT,EAAKd,KAAKwB,KAAMf,EACzB,EACJ,CAMO,SAASgB,EAAMhB,EAAKM,GACzB,IAAK,IAAIrD,EAAI,EAAGA,EAAI6C,EAAMhD,OAAQG,IAAK,CACrC,IAAIsD,EAAWH,EAAMN,EAAM7C,GAAI+C,EAAKM,GACpC,GAAIC,EAASzD,OAAS,EACpB,OAAOyD,CAEX,CAEA,IAAIU,EAAOb,EAAMD,EAASH,EAAKQ,UAI/B,OAHIS,EAAKnE,OAAS,GAChB1B,EAAO,OAEF6F,CACT,EChEA,SAAWnG,GAIT,SAASoG,EAASxD,GAChB,OAA4B,IAArBA,EAAQyD,UAAkB,WAAW5B,KAAKE,EAAO/B,GAC1D,CAGA,SAAS0D,EAAWC,EAAQ3D,EAASe,EAAMO,GAYzC,IAAK,IAAIgB,KAVLtC,EAAQZ,QAAU,GFsKnB,SAAqBY,GAC1B,IAAI4D,EAAO7B,EAAO/B,GAElB,MAAe,UAAR4D,GAA4B,SAARA,CAC7B,CE1K+BC,CAAY7D,EAAQ,MACnB,UAAtB+B,EAAO/B,EAAQ,IACjBkC,EAASlC,EAAQ,GAAI2D,EAAQ5C,EAAMO,GAEnCtB,EAAQ8D,KAAK,WACX5B,EAASmB,KAAMM,EAAQ5C,EAAMO,EAC/B,IAIYqC,EACd,GAAmB,IAAfrB,EAAIlD,OAAR,CAGA,IAAI2E,EAAST,EAAMhB,EAAKtC,GACF,IAAlB+D,EAAO3E,QACT4E,EAAKL,EAAOrB,GAAMyB,EAAQzB,EAAKhB,EAHjC,CAMJ,CAIA,SAAS2C,EAAUC,EAAOlE,EAASe,EAAMO,GACvC,GAAsB,GAAlBtB,EAAQZ,SAAgBoE,EAASxD,KAAYwD,EAASxD,EAAQ,IAKlE,GAAIA,EAAQZ,OAAS,GAA2B,YAAtB2C,EAAO/B,EAAQ,IACvCA,EAAQ8D,KAAK,WACX5B,EAASmB,KAAMa,EAAOnD,EAAMO,EAC9B,OAHF,CAOA,IACI6C,EADW/G,EAAE4C,GACQoE,SAAS,SAClC,GAAID,EAAU/E,OAAS,EAMrB,OALA1B,EAAO,iBACPyG,EAAUL,KAAK,WACb,IAAIO,EAASjH,EAAEiG,MACfW,EAAKE,EAAMG,EAAO3E,KAAK,QAAS2E,EAAQtD,EAAMO,EAChD,IASJ,SAAgB4C,EAAOlE,EAASe,EAAMO,GACpC,IAAIgD,EAAWjH,EAAO6B,UAAUc,GAC5Bb,EAAOmF,EAASA,EAASlF,OAAS,GAClCmF,EAAcnH,EAAE+B,GAAMG,OAAM,GAC5BkF,EAAS,EAEb,GAA2B,UAAvBF,EAAS,GAAGrC,QAAqB,CACnCuC,EAASC,KAAKC,IAAIJ,EAASlF,OAAQ8E,EAAM9E,QACzC,IAAK,IAAIG,EAAI,EAAGA,EAAIiF,EAAQjF,IAC1ByE,EAAKE,EAAM3E,GAAInC,EAAE4C,GAAS2E,GAAGpF,GAAIwB,EAAMO,EAE3C,CAGA,IAAK,IAAIT,EAAIqD,EAAM9E,OAAS,EAAGyB,GAAK2D,EAAQ3D,IAC1CmD,EAAKE,EAAMrD,GAAI0D,EAAYjF,OAAM,GAAMG,YAAYN,GAAO4B,EAAMO,EAEpE,CAtBEsD,CAAOV,EAAOlE,EAASe,EAAMO,EAb7B,MATEY,EAASlC,EAASkE,EAAOnD,EAAMO,EAuBnC,CAmCA,SAAS0C,EAAKrE,EAAOK,EAASe,EAAMO,GAC9B3B,UAGAA,EAAMU,aAAekB,OACvBmC,EAAW/D,EAAOK,EAASe,EAAMO,GACxB3B,EAAMU,aAAeC,MAC9B2D,EAAUtE,EAAOK,EAASe,EAAMO,GAlBpC,SAAmB3B,EAAOK,EAASe,EAAMO,GACvC,GAAItB,EAAQZ,OAAS,EACnB,IAAK,IAAIG,EAAI,EAAGA,EAAIS,EAAQZ,OAAQG,IAClC2C,EAASlC,EAAQT,GAAII,EAAOoB,EAAMO,QAGpCY,EAASlC,EAASL,EAAOoB,EAAMO,EAEnC,CAYIuD,CAAUlF,EAAOK,EAASe,EAAMO,GAEpC,CAcA,SAASwD,EAAK9E,EAASsB,EAAMyD,EAAUC,GAXvC,IAA0BzH,EACpB0H,EADoB1H,EAYPH,EAAE4C,GATL,QAFViF,EAAQ1H,EAAS+D,KAAK,uBAEK,IAAT2D,EACpB1H,EAASc,KAAK4G,GAEd1H,EAAS+D,KAAK,oBAAqB/D,EAASc,QAO9C2G,EAAWE,YACXlB,EAAK1C,EAAMtB,OAAS2B,EAAWoD,GAC/BC,EAAWG,UACb,CAIA,SAASC,EAAapF,EAAS+E,EAAUC,GACnCD,EAAS1E,aAAegF,OAC1BP,EAAK9E,EAAS+E,EAAUA,EAAUC,GACH,KAAtBD,EAASO,OAAO,IAAmC,KAAtBP,EAASO,OAAO,GACtDR,EAAK9E,EAASuF,KAAKC,MAAMT,GAAWA,EAAUC,IAE9CtH,EAAO,OACPN,EAAEqI,KAAK,CACLrH,IAAK2G,EACLW,QAAS,SAAUC,GACjBP,EAAapF,EAAS2F,EAAUX,EAClC,EACAY,OAAO,EACPC,SAAU,SAGhB,CAEAzI,EAAEoB,GAAGC,SAAW,SAAU6C,EAAMrC,GHjKhCvB,EAAO,YACP6D,OAAOuE,eAAexF,MAAMyF,UAAW,WAAY,CACjDC,cAAc,EACdC,UAAU,EACVtG,MAAO,SAAUuG,GAEf,IADA,IAAI3G,EAAI8D,KAAKjE,OACNG,KACL,GAAI8D,KAAK9D,IAAM2G,EACb,OAAO,EAGX,OAAO,CACT,IGuJIjH,GAAW,WAAYA,GACzBvB,EAAO,gBAGT,IAKIsH,EAAa5H,EAAE+I,OALJ,CACbjB,UAAW,WAAa,EACxBC,SAAU,WAAa,EACvBrH,QAAQ,GAE0BmB,GAEpC,OAAOoE,KAAKS,KAAK,WACfsB,EAAa/B,KAAM/B,EAAM0D,EAC3B,EACF,EAGA5H,EAAEoB,GAAGC,SAASC,OAAQ,CACvB,CAtKD,CAsKGrB"} \ No newline at end of file diff --git a/dist/jquery.loadJSON.mjs b/dist/jquery.loadJSON.mjs new file mode 100644 index 0000000..6a77c25 --- /dev/null +++ b/dist/jquery.loadJSON.mjs @@ -0,0 +1,537 @@ +/*! + * jQuery loadJSON plugin + * v1.4.0 + * https://github.com/kevindb/jquery-load-json + * + * This is a jQuery plugin that enables developers to load JSON data from the server and load JSON object into the DOM. + * + * Copyright 2015 Kevin Morris + * Copyright 2011 Jovan Popovic + * Copyright 2008 Alexandre Caprais + * + * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + */ + +import jQuery from 'jquery'; +export { default } from 'jquery'; + +// Behavior kept for compatibility with earlier versions and removed in 2.0. + +var $$1 = jQuery; + +// Adds Array.prototype.contains (loose equality), which earlier versions defined on every call. +function installContains() { + notice("contains"); + Object.defineProperty(Array.prototype, "contains", { + configurable: true, + writable: true, + value: function (obj) { + var i = this.length; + while (i--) { + if (this[i] == obj) { + return true; + } + } + return false; + }, + }); +} + +// Refreshes a jQuery Mobile widget (selectmenu or checkboxradio) when the element has one. +function refreshMobile($element, widget) { + try { + if ($$1.isFunction($element[widget])) { + notice("mobile"); + $element[widget]("refresh"); + } + } catch (ex) {} +} + +// Deprecation notices: shown once per page with console.warn when $.fn.loadJSON.debug is true. +var messages = { + contains: + "Array.prototype.contains is deprecated and will be removed in 2.0. Use Array.prototype.indexOf instead.", + mobile: + "Refreshing jQuery Mobile selectmenu and checkboxradio widgets is deprecated and will be removed in 2.0. Refresh them in onLoaded instead.", + mobileOption: "The mobile option has no effect and will be removed in 2.0.", + srcAlt: + 'An image value is used as the whole src: the "src$alt" format is not supported. Pass {src, alt} instead.', + imageFallback: + "Setting images from the top-level src, alt and title is deprecated and will be removed in 2.0. Give each image its own value.", + rel: "Matching keys by the rel attribute is deprecated and will be removed in 2.0. Use a class, id or name.", + relIndex: + 'Loading array items into rel="index" children is deprecated and will be removed in 2.0.', + url: "Passing a URL to loadJSON is deprecated and will be removed in 2.0. Load the data with $.getJSON and pass it to loadJSON.", + html: "Values are inserted as HTML. From 2.0 they are inserted as text unless the html option is true.", +}; + +var shown = {}; + +function notice(id) { + if (!$$1.fn.loadJSON.debug || shown[id]) { + return; + } + shown[id] = true; + console.warn("jQuery loadJSON: " + messages[id]); +} + +// Element kinds: how a value is set on each kind of element. + +var $ = jQuery; + +// Input types whose value is set directly. +var rField = + /^(?:color|date|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/; + +// Appends a copy of the select's last option for each {value, text, selected} item. +function addOptions(select, items) { + var options = jQuery.makeArray(select); + var last = options[options.length - 1]; + var template = $(last).clone(true); + + // Each copy goes right after the original last option, so the items are added from the end + for (var i = items.length - 1; i >= 0; i--) { + var $option = template.clone(true).insertAfter(last); + $option.attr("value", items[i].value); + $option.text(items[i].text); + if (items[i].selected) { + $option.attr("selected", true); + } + } + + refreshMobile($(select), "selectmenu"); +} + +// Whether an array holds a value, comparing with ==. +function containsLoosely(values, value) { + for (var i = 0; i < values.length; i++) { + if (values[i] == value) { + return true; + } + } + return false; +} + +function field(element, value) { + $(element).val(value); +} + +function checkbox(element, value) { + var $element = $(element); + var elementValue = $element.val(); + + $element.prop( + "checked", + (value.constructor == Array && containsLoosely(value, elementValue)) || value == elementValue + ); + refreshMobile($element, "checkboxradio"); +} + +function radio(element, value) { + var $element = $(element); + + $element.prop("checked", value.toString().toLowerCase() == element.value.toLowerCase()); + refreshMobile($element, "checkboxradio"); +} + +function option(element, value) { + var $element = $(element); + + $element.attr("value", value.value); + $element.text(value.text); + if (value.selected) { + $element.attr("selected", true); + } +} + +function selectOne(element, value) { + if (value.constructor == Array) { + addOptions(element, value); + } else { + $(element).val(value); + refreshMobile($(element), "selectmenu"); + } +} + +function selectMultiple(element, value) { + var options = element.options; + + // An array loaded into a select with one option or none adds options; otherwise it selects + if (value.constructor == Array && options.length <= 1) { + addOptions(element, value); + return; + } + + var values = value.constructor == Array ? value : [value]; + for (var i = 0; i < options.length; i++) { + for (var j = 0; j < values.length; j++) { + options[i].selected |= options[i].value == values[j]; + } + } + refreshMobile($(element), "selectmenu"); +} + +function link(element, value, name) { + var $element = $(element); + var href = $element.attr("href"); + + if (href) { + // If a href value exists, add the pair to its query, before any fragment + var iFragment = href.indexOf("#"); + var fragment = ""; + + if (iFragment >= 0) { + fragment = href.substring(iFragment); + href = href.substring(0, iFragment); + } + + href += (href.indexOf("?") >= 0 ? "&" : "?") + name + "=" + value + fragment; + } else { + // If no href exists, set href to value + href = value; + } + + $element.attr("href", href); +} + +function image(element, value, name, data) { + var $element = $(element); + + if (typeof value == "string") { + // A string is the image address + if (value.indexOf("$") >= 0) { + notice("srcAlt"); + } + $element.attr("src", value); + } else if (value.constructor == Object) { + // An object sets the image's own src, alt and title + $element.attr("src", value.src); + $element.attr("alt", value.alt); + $element.attr("title", value.title); + } else { + // Otherwise the top-level src, alt and title apply to every matched image + if (data.src !== undefined || data.alt !== undefined || data.title !== undefined) { + notice("imageFallback"); + } + $element.attr("src", data.src); + $element.attr("alt", data.alt); + $element.attr("title", data.title); + } +} + +function content(element, value) { + if (typeof value == "string" && /<[a-z!/?]/i.test(value)) { + notice("html"); + } + try { + $(element).html(value.toString()); + } catch (exc) {} +} + +var kinds = { + field: field, + checkbox: checkbox, + radio: radio, + option: option, + "select-one": selectOne, + "select-multiple": selectMultiple, + link: link, + image: image, + content: content, +}; + +// The element kind of a DOM element, from its type or, when it has none, its tag name. +function kindOf(element) { + var type = (element.type || element.tagName).toLowerCase(); + + switch (type) { + case "checkbox": + case "radio": + case "option": + case "select-one": + case "select-multiple": + return type; + case "a": + return "link"; + case "img": + return "image"; + default: + return rField.test(type) ? "field" : "content"; + } +} + +/** + * Sets a value on an element by its kind. `element` is a DOM element or a jQuery set of one; + * `name` is the key the value was loaded from and `data` the data passed to loadJSON. + */ +function setValue(element, value, name, data) { + var node = $(element)[0]; + + kinds[kindOf(node)](node, value, name, data); +} + +// Whether a DOM element's kind takes an object whole (an option or an image), rather than the walk +// loading each of its keys into a match. +function takesObject(element) { + var kind = kindOf(element); + + return kind == "option" || kind == "image"; +} + +// Each step of a match: its selector for the key, and the same test without a selector. +var steps = [ + { + selector: function (key) { + return "." + key; + }, + test: function (element, key) { + return jQuery(element).hasClass(key); + }, + }, + { + selector: function (key) { + return "#" + key; + }, + test: function (element, key) { + return element.id === key; + }, + }, + { + selector: function (key) { + return '[name="' + key + '"]'; + }, + test: function (element, key) { + return element.getAttribute("name") === key; + }, + }, +]; + +var relStep = { + selector: function (key) { + return '[rel="' + key + '"]'; + }, + test: function (element, key) { + return element.getAttribute("rel") === key; + }, +}; + +// Whether the browser accepts a selector as CSS. +function isValidCss(selector) { + try { + document.createDocumentFragment().querySelector(selector); + return true; + } catch (error) { + return false; + } +} + +// Runs a step's selector inside scope. When the key makes the selector invalid (jQuery throws, or, +// before jQuery 3, finds nothing for a selector the browser rejects), it compares each element's +// attribute with the key instead. +function query(step, key, scope) { + var selector = step.selector(key); + + try { + var $matches = jQuery(selector, scope); + if ($matches.length > 0 || isValidCss(selector)) { + return $matches; + } + } catch (error) {} + + return jQuery(scope) + .find("*") + .filter(function () { + return step.test(this, key); + }); +} + +/** + * The match of a key: the elements inside `scope` whose class, then id, then name is the key. + * When none match, the elements anywhere in the document whose rel attribute is the key. + */ +function match(key, scope) { + for (var i = 0; i < steps.length; i++) { + var $matches = query(steps[i], key, scope); + if ($matches.length > 0) { + return $matches; + } + } + + var $rel = query(relStep, key, document); + if ($rel.length > 0) { + notice("rel"); + } + return $rel; +} + + +(function ($) { + + // Whether a DOM element is a select (one or multiple). + function isSelect(element) { + return element.nodeType === 1 && /^select-/.test(kindOf(element)); + } + + // Loads each key of an object into its match within the element. + function walkObject(object, element, name, data) { + // An option or an image matched by the enclosing key takes the object whole + if (element.length >= 1 && takesObject(element[0])) { + if (kindOf(element[0]) == "option") { + setValue(element[0], object, name, data); + } else { + element.each(function () { + setValue(this, object, name, data); + }); + } + } + + for (var key in object) { + if (key.length === 0) { + continue; + } + var $match = match(key, element); + if ($match.length !== 0) { + walk(object[key], $match, key, data); + } + } + } + + // Loads an array: whole into a select or a checkbox group, item by item into rel index + // children, or as a repeat of the element. + function walkArray(array, element, name, data) { + if (element.length == 1 && (isSelect(element) || isSelect(element[0]))) { + setValue(element, array, name, data); + return; + } + + if (element.length > 0 && kindOf(element[0]) == "checkbox") { + element.each(function () { + setValue(this, array, name, data); + }); + return; + } + + var $element = $(element); + var $children = $element.children("[rel]"); + if ($children.length > 0) { + notice("relIndex"); + $children.each(function () { + var $child = $(this); + walk(array[$child.attr("rel")], $child, name, data); + }); + return; + } + + repeat(array, element, name, data); + } + + // Fills the existing elements in order, then appends copies of the last one for the remaining + // items. A select's options are not filled; each item gets a copy of the last option. + function repeat(array, element, name, data) { + var elements = jQuery.makeArray(element); + var last = elements[elements.length - 1]; + var $copySource = $(last).clone(true); + var filled = 0; + + if (elements[0].tagName != "OPTION") { + filled = Math.min(elements.length, array.length); + for (var i = 0; i < filled; i++) { + walk(array[i], $(element).eq(i), name, data); + } + } + + // Each copy goes right after the original last element, so the items are added from the end + for (var j = array.length - 1; j >= filled; j--) { + walk(array[j], $copySource.clone(true).insertAfter(last), name, data); + } + } + + // Sets a single value on each element of the set, or on the element itself. + function walkValue(value, element, name, data) { + if (element.length > 0) { + for (var i = 0; i < element.length; i++) { + setValue(element[i], value, name, data); + } + } else { + setValue(element, value, name, data); + } + } + + // Loads a value of any shape into an element (a DOM element or a jQuery set). + function walk(value, element, name, data) { + if (value === undefined || value === null) { + return; + } + if (value.constructor == Object) { + walkObject(value, element, name, data); + } else if (value.constructor == Array) { + walkArray(value, element, name, data); + } else { + walkValue(value, element, name, data); + } + } + + // Restores the saved template, or saves the current markup when there is none. + function useSavedTemplate($element) { + var saved = $element.data("loadJSON-template"); + + if (saved !== null && saved != "") { + $element.html(saved); + } else { + $element.data("loadJSON-template", $element.html()); + } + } + + // Loads data into one element: the saved template, the callbacks and the walk. + function load(element, data, argument, properties) { + useSavedTemplate($(element)); + properties.onLoading(); + walk(data, element, undefined, argument); + properties.onLoaded(); + } + + // Loads the loadJSON argument into one element. A string starting with { or [ is JSON; any + // other string is a URL, requested once per element, whose response is loaded the same way. + function loadArgument(element, argument, properties) { + if (argument.constructor != String) { + load(element, argument, argument, properties); + } else if (argument.charAt(0) == "{" || argument.charAt(0) == "[") { + load(element, JSON.parse(argument), argument, properties); + } else { + notice("url"); + $.ajax({ + url: argument, + success: function (response) { + loadArgument(element, response, properties); + }, + cache: false, + dataType: "json", + }); + } + } + + $.fn.loadJSON = function (data, options) { + installContains(); + if (options && "mobile" in options) { + notice("mobileOption"); + } + + var defaults = { + onLoading: function () {}, + onLoaded: function () {}, + mobile: false, + }; + var properties = $.extend(defaults, options); + + return this.each(function () { + loadArgument(this, data, properties); + }); + }; + + // Set to true to show a console warning, once per page, for each behavior removed in 2.0. + $.fn.loadJSON.debug = false; +})(jQuery); diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..281f26e --- /dev/null +++ b/docs/README.md @@ -0,0 +1,32 @@ +# jQuery loadJSON documentation + +jQuery loadJSON fills HTML markup you already have, forms included, with values from a JSON +object. There is no template language: the plugin finds the elements whose class, id or name is a +key of the data and sets each one's value in the way that suits the element. + +## Guides + +- [Loading data](loading-data.md): templates, keys, matching, nested objects, arguments and + callbacks. +- [Elements](elements.md): how text, links and images take a value. +- [Forms](forms.md): inputs, checkboxes, radio buttons, textareas and selects. +- [Arrays and repeats](arrays.md): generating lists from an array of objects. +- [Debugging and deprecations](debugging.md): `$.fn.loadJSON.debug` and the behavior that 2.0 + removes. + +## Examples + +[Live examples](examples/index.html) run the built plugin with the current jQuery. Their source is +in [`docs/examples/`](https://github.com/kevindb/jquery-load-json/tree/main/docs/examples). + +## Terms + +These pages use a few words in a fixed sense: + +- **Template**: the markup loadJSON fills, an element and everything inside it. +- **Data**: the value loaded into a template: an object, an array or a single value. +- **Key**: a property name in the data, used to find the elements that take its value. +- **Scope**: the element a key is looked up inside. +- **Match**: the elements a key resolves to within its scope. +- **Repeat**: loading an array by filling existing matching elements, then appending copies of the + last one. diff --git a/docs/_config.yml b/docs/_config.yml new file mode 100644 index 0000000..9c33b72 --- /dev/null +++ b/docs/_config.yml @@ -0,0 +1,5 @@ +# Project-internal notes live in the repository, not on the site. +exclude: + - adr/ + - agents/ + - plans/ diff --git a/docs/adr/0001-dual-publish-surface.md b/docs/adr/0001-dual-publish-surface.md new file mode 100644 index 0000000..9a603ea --- /dev/null +++ b/docs/adr/0001-dual-publish-surface.md @@ -0,0 +1,3 @@ +# Dual publish: classic `$.fn` and modern module + +jQuery loadJSON is consumed as a classic jQuery plugin (script tag, AMD, CommonJS `(root, jQuery)` factory, `$.fn.loadJSON`) and must keep working that way. We publish **both** a modern module entry and a classic UMD build from the same source. ESM-only was rejected: it would break the long tail of script-tag and AMD users. Packaging changes preserve both surfaces, and published-file tests cover each one. diff --git a/docs/adr/0002-branching-and-release.md b/docs/adr/0002-branching-and-release.md new file mode 100644 index 0000000..63d19e7 --- /dev/null +++ b/docs/adr/0002-branching-and-release.md @@ -0,0 +1,3 @@ +# Trunk-based branching and two release lines + +One maintainer, one trunk: **`main`**. Work happens on a short-lived branch per release (`release-1.4`, `release-2.0`) merged by PR. 1.x (compatible) ships before 2.0 (breaking), sequentially on `main`. After 2.0, 1.x patches come from an on-demand **`release/1.x`** branch cut from the last 1.x tag; npm dist-tags are **`latest`** (current major) and **`v1`**. Releases are maintainer-tagged `vX.Y.Z`; `release.yml` publishes the tag to npm through trusted publishing with provenance after the maintainer approves the `npm` environment. `main` requires a PR and the `test` check, with no approving review (a sole maintainer cannot approve their own PR). The trunk was renamed from `master` to `main` in November 2026; GitHub redirects old links. diff --git a/docs/agents/coding-standards.md b/docs/agents/coding-standards.md new file mode 100644 index 0000000..3b25d72 --- /dev/null +++ b/docs/agents/coding-standards.md @@ -0,0 +1,51 @@ +# Coding standards + +Agent-facing standards for changing this repo. Once tooling lands, **config and scripts win**: +ESLint, Prettier, `package.json` and CI encode these rules; look them up rather than restating them. + +Human PR/process stays in `CONTRIBUTING.md`. + +## Workshop + +| Concern | Target | +| ------------ | ---------------------------------------------------------------------------------------------------------- | +| Runtime / CI | **Node 26** (`.nvmrc`); **GitHub Actions** runs `npm test`. | +| Lint | **ESLint** flat config: correctness and quality. | +| Format | **Prettier** defaults with `printWidth: 100` and `trailingComma: "es5"`. No `.editorconfig`. | +| Verify | **`npm test`** is the one command agents run. | +| Tests | Vitest browser mode (Playwright provider, v8 coverage); jQuery matrix on Chromium, Firefox and WebKit. | +| Publish | **Dual surface** (ADR-0001): module entry **and** classic UMD / script-tag `$.fn` build, both from Rollup. | +| Language | Plain JavaScript. | + +## Commits + +**[Conventional Commits](https://www.conventionalcommits.org/)**, each message **1–3 lines** (subject +plus at most a short body). Use the type that matches the change (`fix`, `feat`, `docs`, `test`, +`chore`, `refactor`, `ci`, `build`). Omit `Co-authored-by` and similar trailers. Don't mix a behavior change and a refactor or format sweep in one +commit. + +## Public text + +Public text is anything a user of the library reads: `README.md`, `CONTRIBUTING.md`, `SECURITY.md`, +`docs/` pages, comments in `src/` (they ship in `dist/`), GitHub release notes, and issue and PR +comments. + +- Write it so it makes sense without `docs/plans/`, `docs/agents/` and `docs/adr/`. +- Don't mention plan phases, internal finding labels or `it.fails` records. Name the behavior, the + version or the GitHub issue instead. +- Don't link to `docs/plans/`. An ADR link is fine where its reasoning helps a contributor. + +## Tests + +- **Names:** BDD style, behavior in plain language (`describe` / `it`): "when X, it should Y". +- **Shape:** **AAA** in each example: Arrange, Act, Assert as distinct steps (blank line between). +- A known bug is an `it.fails` test of the intended behavior; the fix flips it to `it`. + +## When changing code + +1. Read this doc and the configs it points at. +2. Edit **`src/`**, never `dist/` (generated, but committed; CI checks it matches a build). +3. Preserve the classic `$.fn` surface and the module entry (ADR-0001). +4. Add or update tests with BDD names and AAA shape when behavior changes. +5. Run **`npm test`**. Done when it passes. +6. Commit with Conventional Commits, 1–3 lines. diff --git a/docs/agents/domain.md b/docs/agents/domain.md new file mode 100644 index 0000000..140ee45 --- /dev/null +++ b/docs/agents/domain.md @@ -0,0 +1,24 @@ +# Domain docs + +How agents consume this repo's domain documentation when exploring or changing behavior. + +This repo is a **single context**: one glossary at the root, system-wide ADRs under `docs/adr/`. There is no `GLOSSARY-MAP.md` and no per-package glossaries. + +## Before exploring, read these + +- **`GLOSSARY.md`** at the repo root (when present) +- **`docs/adr/`** — ADRs that touch the area you're about to work in (e.g. publish surface, packaging) + +If a file or directory doesn't exist yet, **proceed silently**. Don't flag absence; don't suggest creating glossary/ADR files upfront. `/domain-modeling` (via `/grill-with-docs` and related flows) creates them lazily when terms or decisions actually resolve. + +## Use the glossary's vocabulary + +When your output names a domain concept (issue title, refactor proposal, hypothesis, test name), use the term as defined in `GLOSSARY.md`. Don't drift to synonyms the glossary explicitly avoids. + +If the concept isn't in the glossary yet: either you're inventing language the project doesn't use (reconsider) or there's a real gap (note it for `/domain-modeling`). + +## Flag ADR conflicts + +If your output contradicts an existing ADR, surface it explicitly rather than silently overriding: + +> _Contradicts ADR-0001 (dual publish surface), but worth reopening becauseâ€Ļ_ diff --git a/docs/agents/issue-tracker.md b/docs/agents/issue-tracker.md new file mode 100644 index 0000000..474d0d0 --- /dev/null +++ b/docs/agents/issue-tracker.md @@ -0,0 +1,35 @@ +# Issue tracker: GitHub + +Issues and specs for this repo live as GitHub issues. Use the `gh` CLI for all operations. + +## Conventions + +- **Create an issue**: `gh issue create --title "..." --body "..."`. Use a heredoc for multi-line bodies. +- **Read an issue**: `gh issue view --json number,title,body,labels,comments`. +- **List issues**: `gh issue list --state open --json number,title,body,labels,comments --jq '[.[] | {number, title, body, labels: [.labels[].name], comments: [.comments[].body]}]'` with appropriate `--label` and `--state` filters. +- **Make an issue a sub-issue of a parent**: `gh issue create --parent ...`, or `gh issue edit --add-sub-issue ` afterwards (`gh` 2.94+). Older `gh`: `gh api --method POST repos///issues//sub_issues -F sub_issue_id=` (database id, as in **Blocking** below). Without sub-issues, put `Part of #` at the top of the child body. +- **Comment on an issue**: `gh issue comment --body "..."` +- **Apply / remove labels**: `gh issue edit --add-label "..."` / `--remove-label "..."` +- **Close**: `gh issue close --comment "..."` + +Infer the repo from `git remote -v`; `gh` does this automatically when run inside a clone. + +## Pull requests as a triage surface + +**PRs as a request surface: no.** _(Set to `yes` if this repo treats external PRs as feature requests; `/triage` reads this flag.)_ + +When set to `yes`, PRs run through the same labels and states as issues, using the `gh pr` equivalents: + +- **Read a PR**: `gh pr view --comments` and `gh pr diff ` for the diff. +- **List external PRs for triage**: `gh api --paginate 'repos/{owner}/{repo}/pulls?state=open' --jq '.[] | select(.author_association | IN("OWNER","MEMBER","COLLABORATOR") | not) | {number, title, author: .user.login, author_association, labels: [.labels[].name]}'`. +- **Comment / label / close**: `gh pr comment`, `gh pr edit --add-label`/`--remove-label`, `gh pr close`. + +GitHub shares one number space across issues and PRs, so a bare `#42` may be either: resolve with `gh pr view 42` and fall back to `gh issue view 42`. + +## When a skill says "publish to the issue tracker" + +Create a GitHub issue. + +## When a skill says "fetch the relevant ticket" + +Read it as in **Read an issue** above. diff --git a/docs/arrays.md b/docs/arrays.md new file mode 100644 index 0000000..57b86b7 --- /dev/null +++ b/docs/arrays.md @@ -0,0 +1,129 @@ +# Arrays and repeats + +loadJSON can generate a list from an array of objects, using an element of the page as the item to +copy. See it in the [list example](https://kevindb.github.io/jquery-load-json/examples/list.html). + +## Template + +Write the markup for one item, with elements whose class, id or name are the keys of each object: + +```html +
    +
  • + + +
  • +
+``` + +Prefer classes inside items: every copy repeats the same markup, and an id must be unique in a page. + +## Data + +```js +var companies = [ + { ID: 17, Name: "Emkay Entertainments", Address: "Nobel House, Regent Centre" }, + { ID: 18, Name: "The Empire", Address: "Milton Keynes Leisure Plaza" }, + { ID: 19, Name: "Asadul Ltd", Address: "Hophouse" }, +]; +``` + +## Repeating an element + +Load the array into the item: + +```js +$("ul li").loadJSON(companies); +``` + +The `li` is filled with the first object, and a copy of it is added for each of the others: + +```html + +``` + +The link already has an `href`, so each one gains its item's `ID` as a query parameter (see +[Links](elements.md#links)). + +## Repeating by key + +An array can also be the value of a key. Its match is repeated in the same way: + +```html +
+

+
    +
  • +
+
+``` + +```js +$("#company").loadJSON({ Name: "The Empire", Phones: ["0123 456", "0123 789"] }); +``` + +Each item can be a single value, as here, or an object whose keys are matched inside its copy. +Arrays can be nested: an item's key can hold another array, which repeats inside the item's copy. +See the [hierarchy example](https://kevindb.github.io/jquery-load-json/examples/hierarchy.html). + +## How a repeat works + +- When the match of a key has several elements, they are filled in order: the first with the first + item, the second with the second, and so on. +- For each remaining item, a copy of the last matched element is added after it. The copy is taken + before loading, so it carries the original markup, and event handlers bound to it (and inside it) + are copied too. +- When the array is shorter than the match, the extra elements are left unchanged. An empty array + changes nothing. + +Writing several items for a key lets each have its own markup. The first two items below get their +own layout, and the rest repeat the last one: + +```html +
+
    +
  • +
  • +
  • +
+
+``` + +```js +$("#directory").loadJSON({ Companies: companies }); +``` + +This works through a key only. Loading the array straight into a jQuery set of several elements, +such as `$("#directory li").loadJSON(companies)`, loads the whole array into each element, so each +one is repeated on its own. + +See the [array example](https://kevindb.github.io/jquery-load-json/examples/array.html). + +## Arrays that are not repeated + +- A select takes an array as a list of options to add, or of values to select (see + [Selects](forms.md#selects)). +- A group of checkboxes takes an array as the values to check (see [Checkboxes](forms.md#checkboxes)). +- An element with children that have a `rel` attribute loads the item at each child's `rel` index + into that child (`rel="0"` takes the first item). This is deprecated and removed in 2.0; see + [Debugging and deprecations](debugging.md). + +## Loading again + +Copies added by a repeat stay in the page, and a second call finds them. Through a key, they are +filled in order before more copies are added. Loaded directly, as with `$("ul li")`, the set now +holds every copy, and each one is repeated again. To load a new array, start each call from the +original markup as described in [Loading the same template again](loading-data.md#loading-the-same-template-again). diff --git a/docs/debugging.md b/docs/debugging.md new file mode 100644 index 0000000..3229624 --- /dev/null +++ b/docs/debugging.md @@ -0,0 +1,138 @@ +# Debugging and deprecations + +Version 2.0 removes some behavior that 1.x keeps for compatibility. Version 1.4 can tell you which of +it your page uses. + +## Turning on debugging + +Set `$.fn.loadJSON.debug` to `true` before loading: + +```js +$.fn.loadJSON.debug = true; +$("#company").loadJSON(data); +``` + +With debugging on, loadJSON writes a **deprecation notice** to the console (`console.warn`) the +first time a page runs each behavior that 2.0 removes or changes. Each notice is shown once per page, +however often the behavior runs. Debugging is off by default, and turning it on changes nothing but +the console output. + +Turn it on while developing or testing, load your pages as users would, and work through the notices +before upgrading to 2.0. + +## Notices + +Every notice starts with `jQuery loadJSON:`. + +### `Array.prototype.contains` + +> Array.prototype.contains is deprecated and will be removed in 2.0. Use Array.prototype.indexOf +> instead. + +Every call to `loadJSON` defines `Array.prototype.contains` on all arrays in the page, as earlier +versions did. Since 1.4 it is not enumerable, so it no longer shows up in `for...in` loops. 2.0 stops +defining it. If your own code calls `.contains()` on arrays, use `indexOf` (or `includes`) instead. + +This notice appears on the first call with debugging on, whether or not your code uses `contains`. + +### jQuery Mobile refresh + +> Refreshing jQuery Mobile selectmenu and checkboxradio widgets is deprecated and will be removed in +> 2.0. Refresh them in onLoaded instead. + +After setting a select, checkbox or radio button, loadJSON refreshes its jQuery Mobile widget when +the element has one. With jQuery 4 this never happens. 2.0 removes the refresh. Refresh the widgets +yourself: + +```js +$("#form").loadJSON(data, { + onLoaded: function () { + $("#form select").selectmenu("refresh"); + $("#form :checkbox, #form :radio").checkboxradio("refresh"); + }, +}); +``` + +### The `mobile` option + +> The mobile option has no effect and will be removed in 2.0. + +The `mobile` option has never been read. Remove it from your options. + +### The `"src$alt"` image format + +> An image value is used as the whole src: the "src$alt" format is not supported. Pass {src, alt} +> instead. + +Shown when a string loaded into an image contains `$`. The whole string becomes the image's `src`. +To set the `alt` text, load an object: + +```js +$("#company").loadJSON({ Logo: { src: "images/logo.jpg", alt: "Our logo" } }); +``` + +### Images from the top-level `src`, `alt` and `title` + +> Setting images from the top-level src, alt and title is deprecated and will be removed in 2.0. Give +> each image its own value. + +Shown when an image's own value is neither a string nor an object, and the top-level data has a +`src`, `alt` or `title`, which the image then takes. Load a string or an object into each image +instead (see [Images](elements.md#images)). + +### Matching by `rel` + +> Matching keys by the rel attribute is deprecated and will be removed in 2.0. Use a class, id or +> name. + +Shown when a key matches no class, id or name and is matched by a `rel` attribute instead. This +match searches the whole page, not only the loaded element. Give the element a class equal to the +key: + +```html + + + + +``` + +### Array items in `rel` index children + +> Loading array items into rel="index" children is deprecated and will be removed in 2.0. + +Shown when an array is loaded into an element whose children have `rel` attributes, each child +taking the item at its `rel` index. Write one element per item instead, without `rel`: a +[repeat](arrays.md#how-a-repeat-works) fills existing elements in order before adding copies. + +### URL arguments + +> Passing a URL to loadJSON is deprecated and will be removed in 2.0. Load the data with $.getJSON +> and pass it to loadJSON. + +Shown when `loadJSON` is given a string that is not JSON, which it requests as a URL. Request the +data yourself; this also lets you handle errors, which the built-in request ignores: + +```js +// Before +$("#company").loadJSON("company.json"); + +// After +$.getJSON("company.json") + .done(function (data) { + $("#company").loadJSON(data); + }) + .fail(function () { + $("#company").text("The company could not be loaded."); + }); +``` + +The built-in request is never cached; pass `cache: false` to `$.ajax` if you depend on that. + +### Values inserted as HTML + +> Values are inserted as HTML. From 2.0 they are inserted as text unless the html option is true. + +Shown when a string that looks like markup (it contains `<` followed by a letter, `/`, `!` or `?`) +is loaded into a content element. In 1.x the markup is parsed and added to the page. In 2.0 it is +shown as text, and an `html: true` option keeps the 1.x behavior. If the value comes from users or +another untrusted source, escape it now: inserting it as HTML lets markup in it run in your page. diff --git a/docs/elements.md b/docs/elements.md new file mode 100644 index 0000000..8806087 --- /dev/null +++ b/docs/elements.md @@ -0,0 +1,105 @@ +# Elements + +How content elements, links and images take a value. For form controls, see [Forms](forms.md). + +## Content + +Any element that is not a form control, link or image (`span`, `p`, `div`, `li`, `h1`, `td`, +`button` and so on) takes the value as its contents: + +```html +

+ +

+``` + +```js +$("body").loadJSON({ + Title: "This is a title", + Address: "Regent Street", + Description: "Lorem ipsum dolor sit amet", +}); +``` + +```html +

This is a title

+Regent Street +

Lorem ipsum dolor sit amet

+``` + +Numbers and booleans are converted to strings. The value replaces the element's contents and is +inserted as HTML, so a value of `"New"` shows a bold "New". Escape untrusted values before +loading them. In 2.0, values are inserted as text unless the `html` option is `true`. + +## Links + +A link with no `href` (or an empty one) takes the value as its address: + +```html +Google +``` + +```js +$("body").loadJSON({ Link: "https://www.google.com" }); +``` + +```html +Google +``` + +The link text is not changed. To load the text as well, put an element for it inside the link: + +```html + +``` + +```js +$("body").loadJSON({ Link: "https://www.google.com", LinkText: "Google" }); +``` + +A link that already has an `href` keeps it and gains a query parameter named after the key. The +parameter goes before any `#fragment`, after `?` or after `&` when there is already a query: + +```html +Details +Details +``` + +```js +$("body").loadJSON({ ID: 17 }); +``` + +```html +Details +Details +``` + +The value is added as is, without URL encoding. Encode values that may contain `&`, `#`, spaces or +other reserved characters with `encodeURIComponent` before loading them. + +## Images + +An image takes a string value as its `src`: + +```html + +``` + +```js +$("body").loadJSON({ Logo: "images/logo.jpg" }); +``` + +An object value sets the image's `src`, `alt` and `title`: + +```js +$("body").loadJSON({ + Logo: { src: "images/logo.jpg", alt: "Emkay Entertainments", title: "Our logo" }, +}); +``` + +Earlier versions documented a `"src$alt"` string format (`"images/logo.jpg$Our logo"`). It was never +applied as described: the whole string becomes the `src`. Use an object to set the `alt`. + +When an image's own value is neither a string nor an object (a number, for example), the image takes +the `src`, `alt` and `title` keys at the top level of the data instead. This is deprecated and +removed in 2.0: give each image its own string or object value. diff --git a/docs/examples/array.html b/docs/examples/array.html new file mode 100644 index 0000000..809c527 --- /dev/null +++ b/docs/examples/array.html @@ -0,0 +1,62 @@ + + + + + + Different markup per item ¡ jQuery loadJSON + + + + +
+

Different markup per item

+

+ When a key matches several elements, they are filled in order before any copies are added. + Here the first company gets a featured layout with its logo, and the rest repeat the last + item. +

+

Result

+
+
+
    +
  • +
    + , +
  • +
  • + +
  • +
+
+
+ +

Template

+
+

Script

+
+

+ The array is the value of the Companies key. Loading it into + $("#directory li") instead would repeat each li separately, + because every element of a jQuery set is loaded with the whole data. +

+
+ + + + + + diff --git a/docs/examples/categories.html b/docs/examples/categories.html new file mode 100644 index 0000000..8617cfe --- /dev/null +++ b/docs/examples/categories.html @@ -0,0 +1,66 @@ + + + + + + Connected selects from the server ¡ jQuery loadJSON + + + + +
+

Connected selects from the server

+

+ The regions are requested when the page loads and added as options. Choosing a region + requests its towns and adds them to the second select. Each array is loaded into a classed + placeholder option, which is copied once per item. +

+

Result

+
+
+ + + + + +
+
+ +

Template

+
+

Script

+
+

+ Options added by an earlier load stay in the select, so the script removes the old towns + before loading new ones. +

+
+ + + + + + diff --git a/docs/examples/data/company-17.json b/docs/examples/data/company-17.json new file mode 100644 index 0000000..cb13bdc --- /dev/null +++ b/docs/examples/data/company-17.json @@ -0,0 +1,13 @@ +{ + "ID": 17, + "Name": "Emkay Entertainments", + "Address": "Nobel House, Regent Centre", + "Town": "Lothian", + "Contact": "Phone", + "IsFeatured": true, + "Country": ["UK", "USA"], + "Logo": { + "src": "images/logo17.jpg", + "alt": "Emkay Entertainments logo" + } +} diff --git a/docs/examples/data/company-18.json b/docs/examples/data/company-18.json new file mode 100644 index 0000000..d8b0dd1 --- /dev/null +++ b/docs/examples/data/company-18.json @@ -0,0 +1,13 @@ +{ + "ID": 18, + "Name": "The Empire", + "Address": "Milton Keynes Leisure Plaza", + "Town": "London", + "Contact": "Email", + "IsFeatured": false, + "Country": ["UK"], + "Logo": { + "src": "images/logo18.jpg", + "alt": "The Empire logo" + } +} diff --git a/docs/examples/data/company-19.json b/docs/examples/data/company-19.json new file mode 100644 index 0000000..d691e37 --- /dev/null +++ b/docs/examples/data/company-19.json @@ -0,0 +1,13 @@ +{ + "ID": 19, + "Name": "Asadul Ltd", + "Address": "Hophouse", + "Town": "Essex", + "Contact": "Phone", + "IsFeatured": false, + "Country": null, + "Logo": { + "src": "images/logo19.jpg", + "alt": "Asadul Ltd logo" + } +} diff --git a/docs/examples/data/company-20.json b/docs/examples/data/company-20.json new file mode 100644 index 0000000..af92e26 --- /dev/null +++ b/docs/examples/data/company-20.json @@ -0,0 +1,13 @@ +{ + "ID": 20, + "Name": "Star Records", + "Address": "Nobel House, Regent Centre", + "Town": "London", + "Contact": "Phone", + "IsFeatured": true, + "Country": ["SRB", "UK"], + "Logo": { + "src": "images/logo20.jpg", + "alt": "Star Records logo" + } +} diff --git a/docs/examples/data/company-21.json b/docs/examples/data/company-21.json new file mode 100644 index 0000000..ccca9cb --- /dev/null +++ b/docs/examples/data/company-21.json @@ -0,0 +1,13 @@ +{ + "ID": 21, + "Name": "Ashley Mark Publishing Company", + "Address": "1-2 Vance Court", + "Town": "London", + "Contact": null, + "IsFeatured": true, + "Country": null, + "Logo": { + "src": "images/logo21.jpg", + "alt": "Ashley Mark Publishing Company logo" + } +} diff --git a/docs/examples/data/hierarchy.json b/docs/examples/data/hierarchy.json new file mode 100644 index 0000000..86b5773 --- /dev/null +++ b/docs/examples/data/hierarchy.json @@ -0,0 +1,137 @@ +[ + { + "ID": 17, + "Name": "Emkay Entertainments", + "Address": "Nobel House, Regent Centre", + "Manager": { + "ID": 17, + "FirstName": "Nick", + "LastName": "Donovan" + }, + "Employees": [ + { + "ID": 18, + "FirstName": "John", + "LastName": "Doe" + }, + { + "ID": 19, + "FirstName": "Alex", + "LastName": "Watkins" + }, + { + "ID": 20, + "FirstName": "Mick", + "LastName": "Henning" + } + ] + }, + { + "ID": 18, + "Name": "The Empire", + "Address": "Milton Keynes Leisure Plaza", + "Manager": { + "ID": 21, + "FirstName": "Ana", + "LastName": "Frank" + }, + "Employees": [ + { + "ID": 22, + "FirstName": "Mark", + "LastName": "Anderson" + }, + { + "ID": 23, + "FirstName": "John", + "LastName": "Haus" + }, + { + "ID": 24, + "FirstName": "Sinthia", + "LastName": "Clouny" + } + ] + }, + { + "ID": 19, + "Name": "Asadul Ltd", + "Address": "Hophouse", + "Manager": { + "ID": 25, + "FirstName": "John", + "LastName": "Feigan" + }, + "Employees": [ + { + "ID": 26, + "FirstName": "Micheal", + "LastName": "King" + }, + { + "ID": 27, + "FirstName": "Jody", + "LastName": "Palmer" + } + ] + }, + { + "ID": 20, + "Name": "Star Records", + "Address": "Oxford Street 22-24", + "Manager": { + "ID": 28, + "FirstName": "Steve", + "LastName": "Carter" + }, + "Employees": [ + { + "ID": 29, + "FirstName": "Andrea", + "LastName": "Smith" + }, + { + "ID": 30, + "FirstName": "Jane", + "LastName": "Anderson" + }, + { + "ID": 31, + "FirstName": "Anthony", + "LastName": "Willis" + }, + { + "ID": 32, + "FirstName": "George", + "LastName": "Hill" + } + ] + }, + { + "ID": 21, + "Name": "Ashley Mark Publishing Company", + "Address": "1-2 Vance Court", + "Manager": { + "ID": 33, + "FirstName": "Micheal", + "LastName": "Johnson" + }, + "Employees": [ + { + "ID": 34, + "FirstName": "Micheal", + "LastName": "Sharp" + }, + { + "ID": 35, + "FirstName": "Jeff", + "LastName": "Cave" + }, + { + "ID": 36, + "FirstName": "Peter", + "LastName": "Hayward" + } + ] + } +] diff --git a/docs/examples/data/list.json b/docs/examples/data/list.json new file mode 100644 index 0000000..4cc8676 --- /dev/null +++ b/docs/examples/data/list.json @@ -0,0 +1,29 @@ +[ + { + "ID": 17, + "Name": "Emkay Entertainments", + "Address": "Nobel House, Regent Centre", + "Town": "Lothian", + "Logo": "images/logo17.jpg" + }, + { + "ID": 18, + "Name": "The Empire", + "Address": "Milton Keynes Leisure Plaza" + }, + { + "ID": 19, + "Name": "Asadul Ltd", + "Address": "Hophouse" + }, + { + "ID": 20, + "Name": "Star Records", + "Address": "St Danny Street" + }, + { + "ID": 21, + "Name": "Ashley Mark Publishing Company", + "Address": "1-2 Vance Court" + } +] diff --git a/docs/examples/data/regions.json b/docs/examples/data/regions.json new file mode 100644 index 0000000..fb3b256 --- /dev/null +++ b/docs/examples/data/regions.json @@ -0,0 +1,16 @@ +{ + "regions": [ + { + "value": 1, + "text": "East Europe" + }, + { + "value": 2, + "text": "West Europe" + }, + { + "value": 3, + "text": "Middle Europe" + } + ] +} diff --git a/docs/examples/data/towns-1.json b/docs/examples/data/towns-1.json new file mode 100644 index 0000000..4eca8af --- /dev/null +++ b/docs/examples/data/towns-1.json @@ -0,0 +1,16 @@ +{ + "towns": [ + { + "value": 17, + "text": "Belgrade" + }, + { + "value": 19, + "text": "Moscow" + }, + { + "value": 20, + "text": "Kiev" + } + ] +} diff --git a/docs/examples/data/towns-2.json b/docs/examples/data/towns-2.json new file mode 100644 index 0000000..1ea5d3f --- /dev/null +++ b/docs/examples/data/towns-2.json @@ -0,0 +1,24 @@ +{ + "towns": [ + { + "value": 21, + "text": "London" + }, + { + "value": 22, + "text": "Paris" + }, + { + "value": 23, + "text": "Madrid" + }, + { + "value": 24, + "text": "Lisbon" + }, + { + "value": 25, + "text": "Amsterdam" + } + ] +} diff --git a/docs/examples/data/towns-3.json b/docs/examples/data/towns-3.json new file mode 100644 index 0000000..867dfa7 --- /dev/null +++ b/docs/examples/data/towns-3.json @@ -0,0 +1,20 @@ +{ + "towns": [ + { + "value": 31, + "text": "Berlin" + }, + { + "value": 32, + "text": "Vienna" + }, + { + "value": 33, + "text": "Budapest" + }, + { + "value": 34, + "text": "Prague" + } + ] +} diff --git a/docs/examples/details.html b/docs/examples/details.html new file mode 100644 index 0000000..15056d9 --- /dev/null +++ b/docs/examples/details.html @@ -0,0 +1,68 @@ + + + + + + Details of one object ¡ jQuery loadJSON + + + + +
+

Details of one object

+

+ One object loaded into a block of content elements, an image and a link. The company comes + from the ID in the address: 17, 18, + 19, 20, 21. +

+

Result

+
+
+

+
+
Address
+
,
+
Contact by
+
+
Countries
+
+
    +
  • +
+
+
+ Edit this company +
+
+ +

Template

+
+

Script

+
+

+ The Logo value is an object, which sets the image's src and + alt. Country is an array, so its li is repeated. +

+
+ + + + + + diff --git a/docs/examples/edit.html b/docs/examples/edit.html new file mode 100644 index 0000000..aeb73b6 --- /dev/null +++ b/docs/examples/edit.html @@ -0,0 +1,96 @@ + + + + + + Filling a form ¡ jQuery loadJSON + + + + +
+

Filling a form

+

+ One object loaded into a form. Each control takes its value in the way that suits it: text + fields and the textarea take it as text, the checkbox and radio buttons are checked when + their value matches, and the selects select matching options. Try another company: + 17, 18, 19, + 20, 21. +

+

Result

+
+
+ + + + + + + + + + + + + + + + +
+ Contact by + + + +
+ +

+
+
+ +

Template

+
+

Script

+
+

+ IsFeatured is a boolean. The checkbox has value="1", which + true equals in a loose comparison. Saving submits the form to the details page, + which loads the company again from its ID. +

+
+ + + + + + diff --git a/docs/examples/events.html b/docs/examples/events.html new file mode 100644 index 0000000..1777151 --- /dev/null +++ b/docs/examples/events.html @@ -0,0 +1,76 @@ + + + + + + Callbacks ¡ jQuery loadJSON + + + + +
+

Callbacks

+

+ onLoading runs before the data is loaded and onLoaded after. Here + the table is hidden while it fills and faded in when it is done. The click handler bound to + the row before loading is copied to every new row: click a row to highlight it. +

+

Result

+
+

+ + + + + + + + + + + + + + + +
NameAddressTown
+ +
+
+ +

Template

+
+

Script

+
+
+ + + + + + diff --git a/docs/examples/filter.html b/docs/examples/filter.html new file mode 100644 index 0000000..b59b0a6 --- /dev/null +++ b/docs/examples/filter.html @@ -0,0 +1,81 @@ + + + + + + Connected selects from local data ¡ jQuery loadJSON + + + + +
+

Connected selects from local data

+

+ The same connected selects, with the data already in the page. Choosing a region filters the + towns with Array.prototype.filter, sorts them, and loads the result. +

+

Result

+
+
+ + + + + +
+
+ +

Template

+
+

Script

+
+
+ + + + + + diff --git a/docs/examples/hierarchy.html b/docs/examples/hierarchy.html new file mode 100644 index 0000000..dab4397 --- /dev/null +++ b/docs/examples/hierarchy.html @@ -0,0 +1,60 @@ + + + + + + Nested objects and arrays ¡ jQuery loadJSON + + + + +
+

Nested objects and arrays

+

+ Each company has a Manager object and an Employees array. Their + keys are looked up inside the element their own key matched, so each + FirstName lands in the right place, and the employees repeat inside each + company's copy. +

+

Result

+
+
    +
  • + , + +
    + Manager: +
    +
    Employees:
    +
      +
    • + +
    • +
    +
  • +
+
+ +

Template

+
+

Script

+
+
+ + + + + + diff --git a/examples/images/logo17.jpg b/docs/examples/images/logo17.jpg similarity index 100% rename from examples/images/logo17.jpg rename to docs/examples/images/logo17.jpg diff --git a/examples/images/logo18.jpg b/docs/examples/images/logo18.jpg similarity index 100% rename from examples/images/logo18.jpg rename to docs/examples/images/logo18.jpg diff --git a/examples/images/logo19.jpg b/docs/examples/images/logo19.jpg similarity index 100% rename from examples/images/logo19.jpg rename to docs/examples/images/logo19.jpg diff --git a/examples/images/logo20.jpg b/docs/examples/images/logo20.jpg similarity index 100% rename from examples/images/logo20.jpg rename to docs/examples/images/logo20.jpg diff --git a/examples/images/logo21.jpg b/docs/examples/images/logo21.jpg similarity index 100% rename from examples/images/logo21.jpg rename to docs/examples/images/logo21.jpg diff --git a/docs/examples/index.html b/docs/examples/index.html new file mode 100644 index 0000000..cccbb74 --- /dev/null +++ b/docs/examples/index.html @@ -0,0 +1,32 @@ + + + + + + Examples ¡ jQuery loadJSON + + + + +
+

jQuery loadJSON examples

+

+ Each example runs the current build of the plugin with jQuery 4 and shows its own template + and script. +

+ +
+ + diff --git a/docs/examples/jquery.loadJSON.js b/docs/examples/jquery.loadJSON.js new file mode 100644 index 0000000..9f2c05d --- /dev/null +++ b/docs/examples/jquery.loadJSON.js @@ -0,0 +1,567 @@ +/*! + * jQuery loadJSON plugin + * v1.4.0 + * https://github.com/kevindb/jquery-load-json + * + * This is a jQuery plugin that enables developers to load JSON data from the server and load JSON object into the DOM. + * + * Copyright 2015 Kevin Morris + * Copyright 2011 Jovan Popovic + * Copyright 2008 Alexandre Caprais + * + * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + */ + +(function (factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['jquery'], factory); + } else if (typeof module === 'object' && module.exports) { + // Node/CommonJS + module.exports = function( root, jQuery ) { + if ( jQuery === undefined ) { + // require('jQuery') returns a factory that requires window to build a jQuery instance, we normalize how we use modules + // that require this pattern but the window provided is a noop if it's defined (how jquery works) + if ( typeof window !== 'undefined' ) { + jQuery = require('jquery'); + } + else { + // jQuery 4 builds a jQuery for a window from jquery/factory; jQuery 3 from the package itself + var jQueryFactory; + try { + jQueryFactory = require('jquery/factory').jQueryFactory; + } catch (error) {} + jQuery = jQueryFactory ? jQueryFactory(root) : require('jquery')(root); + } + } + factory(jQuery); + return jQuery; + }; + } else { + // Browser globals + factory(jQuery); + } + +}(function (jQuery) { + 'use strict'; +// Behavior kept for compatibility with earlier versions and removed in 2.0. + +var $$1 = jQuery; + +// Adds Array.prototype.contains (loose equality), which earlier versions defined on every call. +function installContains() { + notice("contains"); + Object.defineProperty(Array.prototype, "contains", { + configurable: true, + writable: true, + value: function (obj) { + var i = this.length; + while (i--) { + if (this[i] == obj) { + return true; + } + } + return false; + }, + }); +} + +// Refreshes a jQuery Mobile widget (selectmenu or checkboxradio) when the element has one. +function refreshMobile($element, widget) { + try { + if ($$1.isFunction($element[widget])) { + notice("mobile"); + $element[widget]("refresh"); + } + } catch (ex) {} +} + +// Deprecation notices: shown once per page with console.warn when $.fn.loadJSON.debug is true. +var messages = { + contains: + "Array.prototype.contains is deprecated and will be removed in 2.0. Use Array.prototype.indexOf instead.", + mobile: + "Refreshing jQuery Mobile selectmenu and checkboxradio widgets is deprecated and will be removed in 2.0. Refresh them in onLoaded instead.", + mobileOption: "The mobile option has no effect and will be removed in 2.0.", + srcAlt: + 'An image value is used as the whole src: the "src$alt" format is not supported. Pass {src, alt} instead.', + imageFallback: + "Setting images from the top-level src, alt and title is deprecated and will be removed in 2.0. Give each image its own value.", + rel: "Matching keys by the rel attribute is deprecated and will be removed in 2.0. Use a class, id or name.", + relIndex: + 'Loading array items into rel="index" children is deprecated and will be removed in 2.0.', + url: "Passing a URL to loadJSON is deprecated and will be removed in 2.0. Load the data with $.getJSON and pass it to loadJSON.", + html: "Values are inserted as HTML. From 2.0 they are inserted as text unless the html option is true.", +}; + +var shown = {}; + +function notice(id) { + if (!$$1.fn.loadJSON.debug || shown[id]) { + return; + } + shown[id] = true; + console.warn("jQuery loadJSON: " + messages[id]); +} + +// Element kinds: how a value is set on each kind of element. + +var $ = jQuery; + +// Input types whose value is set directly. +var rField = + /^(?:color|date|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/; + +// Appends a copy of the select's last option for each {value, text, selected} item. +function addOptions(select, items) { + var options = jQuery.makeArray(select); + var last = options[options.length - 1]; + var template = $(last).clone(true); + + // Each copy goes right after the original last option, so the items are added from the end + for (var i = items.length - 1; i >= 0; i--) { + var $option = template.clone(true).insertAfter(last); + $option.attr("value", items[i].value); + $option.text(items[i].text); + if (items[i].selected) { + $option.attr("selected", true); + } + } + + refreshMobile($(select), "selectmenu"); +} + +// Whether an array holds a value, comparing with ==. +function containsLoosely(values, value) { + for (var i = 0; i < values.length; i++) { + if (values[i] == value) { + return true; + } + } + return false; +} + +function field(element, value) { + $(element).val(value); +} + +function checkbox(element, value) { + var $element = $(element); + var elementValue = $element.val(); + + $element.prop( + "checked", + (value.constructor == Array && containsLoosely(value, elementValue)) || value == elementValue + ); + refreshMobile($element, "checkboxradio"); +} + +function radio(element, value) { + var $element = $(element); + + $element.prop("checked", value.toString().toLowerCase() == element.value.toLowerCase()); + refreshMobile($element, "checkboxradio"); +} + +function option(element, value) { + var $element = $(element); + + $element.attr("value", value.value); + $element.text(value.text); + if (value.selected) { + $element.attr("selected", true); + } +} + +function selectOne(element, value) { + if (value.constructor == Array) { + addOptions(element, value); + } else { + $(element).val(value); + refreshMobile($(element), "selectmenu"); + } +} + +function selectMultiple(element, value) { + var options = element.options; + + // An array loaded into a select with one option or none adds options; otherwise it selects + if (value.constructor == Array && options.length <= 1) { + addOptions(element, value); + return; + } + + var values = value.constructor == Array ? value : [value]; + for (var i = 0; i < options.length; i++) { + for (var j = 0; j < values.length; j++) { + options[i].selected |= options[i].value == values[j]; + } + } + refreshMobile($(element), "selectmenu"); +} + +function link(element, value, name) { + var $element = $(element); + var href = $element.attr("href"); + + if (href) { + // If a href value exists, add the pair to its query, before any fragment + var iFragment = href.indexOf("#"); + var fragment = ""; + + if (iFragment >= 0) { + fragment = href.substring(iFragment); + href = href.substring(0, iFragment); + } + + href += (href.indexOf("?") >= 0 ? "&" : "?") + name + "=" + value + fragment; + } else { + // If no href exists, set href to value + href = value; + } + + $element.attr("href", href); +} + +function image(element, value, name, data) { + var $element = $(element); + + if (typeof value == "string") { + // A string is the image address + if (value.indexOf("$") >= 0) { + notice("srcAlt"); + } + $element.attr("src", value); + } else if (value.constructor == Object) { + // An object sets the image's own src, alt and title + $element.attr("src", value.src); + $element.attr("alt", value.alt); + $element.attr("title", value.title); + } else { + // Otherwise the top-level src, alt and title apply to every matched image + if (data.src !== undefined || data.alt !== undefined || data.title !== undefined) { + notice("imageFallback"); + } + $element.attr("src", data.src); + $element.attr("alt", data.alt); + $element.attr("title", data.title); + } +} + +function content(element, value) { + if (typeof value == "string" && /<[a-z!/?]/i.test(value)) { + notice("html"); + } + try { + $(element).html(value.toString()); + } catch (exc) {} +} + +var kinds = { + field: field, + checkbox: checkbox, + radio: radio, + option: option, + "select-one": selectOne, + "select-multiple": selectMultiple, + link: link, + image: image, + content: content, +}; + +// The element kind of a DOM element, from its type or, when it has none, its tag name. +function kindOf(element) { + var type = (element.type || element.tagName).toLowerCase(); + + switch (type) { + case "checkbox": + case "radio": + case "option": + case "select-one": + case "select-multiple": + return type; + case "a": + return "link"; + case "img": + return "image"; + default: + return rField.test(type) ? "field" : "content"; + } +} + +/** + * Sets a value on an element by its kind. `element` is a DOM element or a jQuery set of one; + * `name` is the key the value was loaded from and `data` the data passed to loadJSON. + */ +function setValue(element, value, name, data) { + var node = $(element)[0]; + + kinds[kindOf(node)](node, value, name, data); +} + +// Whether a DOM element's kind takes an object whole (an option or an image), rather than the walk +// loading each of its keys into a match. +function takesObject(element) { + var kind = kindOf(element); + + return kind == "option" || kind == "image"; +} + +// Each step of a match: its selector for the key, and the same test without a selector. +var steps = [ + { + selector: function (key) { + return "." + key; + }, + test: function (element, key) { + return jQuery(element).hasClass(key); + }, + }, + { + selector: function (key) { + return "#" + key; + }, + test: function (element, key) { + return element.id === key; + }, + }, + { + selector: function (key) { + return '[name="' + key + '"]'; + }, + test: function (element, key) { + return element.getAttribute("name") === key; + }, + }, +]; + +var relStep = { + selector: function (key) { + return '[rel="' + key + '"]'; + }, + test: function (element, key) { + return element.getAttribute("rel") === key; + }, +}; + +// Whether the browser accepts a selector as CSS. +function isValidCss(selector) { + try { + document.createDocumentFragment().querySelector(selector); + return true; + } catch (error) { + return false; + } +} + +// Runs a step's selector inside scope. When the key makes the selector invalid (jQuery throws, or, +// before jQuery 3, finds nothing for a selector the browser rejects), it compares each element's +// attribute with the key instead. +function query(step, key, scope) { + var selector = step.selector(key); + + try { + var $matches = jQuery(selector, scope); + if ($matches.length > 0 || isValidCss(selector)) { + return $matches; + } + } catch (error) {} + + return jQuery(scope) + .find("*") + .filter(function () { + return step.test(this, key); + }); +} + +/** + * The match of a key: the elements inside `scope` whose class, then id, then name is the key. + * When none match, the elements anywhere in the document whose rel attribute is the key. + */ +function match(key, scope) { + for (var i = 0; i < steps.length; i++) { + var $matches = query(steps[i], key, scope); + if ($matches.length > 0) { + return $matches; + } + } + + var $rel = query(relStep, key, document); + if ($rel.length > 0) { + notice("rel"); + } + return $rel; +} + + +(function ($) { + + // Whether a DOM element is a select (one or multiple). + function isSelect(element) { + return element.nodeType === 1 && /^select-/.test(kindOf(element)); + } + + // Loads each key of an object into its match within the element. + function walkObject(object, element, name, data) { + // An option or an image matched by the enclosing key takes the object whole + if (element.length >= 1 && takesObject(element[0])) { + if (kindOf(element[0]) == "option") { + setValue(element[0], object, name, data); + } else { + element.each(function () { + setValue(this, object, name, data); + }); + } + } + + for (var key in object) { + if (key.length === 0) { + continue; + } + var $match = match(key, element); + if ($match.length !== 0) { + walk(object[key], $match, key, data); + } + } + } + + // Loads an array: whole into a select or a checkbox group, item by item into rel index + // children, or as a repeat of the element. + function walkArray(array, element, name, data) { + if (element.length == 1 && (isSelect(element) || isSelect(element[0]))) { + setValue(element, array, name, data); + return; + } + + if (element.length > 0 && kindOf(element[0]) == "checkbox") { + element.each(function () { + setValue(this, array, name, data); + }); + return; + } + + var $element = $(element); + var $children = $element.children("[rel]"); + if ($children.length > 0) { + notice("relIndex"); + $children.each(function () { + var $child = $(this); + walk(array[$child.attr("rel")], $child, name, data); + }); + return; + } + + repeat(array, element, name, data); + } + + // Fills the existing elements in order, then appends copies of the last one for the remaining + // items. A select's options are not filled; each item gets a copy of the last option. + function repeat(array, element, name, data) { + var elements = jQuery.makeArray(element); + var last = elements[elements.length - 1]; + var $copySource = $(last).clone(true); + var filled = 0; + + if (elements[0].tagName != "OPTION") { + filled = Math.min(elements.length, array.length); + for (var i = 0; i < filled; i++) { + walk(array[i], $(element).eq(i), name, data); + } + } + + // Each copy goes right after the original last element, so the items are added from the end + for (var j = array.length - 1; j >= filled; j--) { + walk(array[j], $copySource.clone(true).insertAfter(last), name, data); + } + } + + // Sets a single value on each element of the set, or on the element itself. + function walkValue(value, element, name, data) { + if (element.length > 0) { + for (var i = 0; i < element.length; i++) { + setValue(element[i], value, name, data); + } + } else { + setValue(element, value, name, data); + } + } + + // Loads a value of any shape into an element (a DOM element or a jQuery set). + function walk(value, element, name, data) { + if (value === undefined || value === null) { + return; + } + if (value.constructor == Object) { + walkObject(value, element, name, data); + } else if (value.constructor == Array) { + walkArray(value, element, name, data); + } else { + walkValue(value, element, name, data); + } + } + + // Restores the saved template, or saves the current markup when there is none. + function useSavedTemplate($element) { + var saved = $element.data("loadJSON-template"); + + if (saved !== null && saved != "") { + $element.html(saved); + } else { + $element.data("loadJSON-template", $element.html()); + } + } + + // Loads data into one element: the saved template, the callbacks and the walk. + function load(element, data, argument, properties) { + useSavedTemplate($(element)); + properties.onLoading(); + walk(data, element, undefined, argument); + properties.onLoaded(); + } + + // Loads the loadJSON argument into one element. A string starting with { or [ is JSON; any + // other string is a URL, requested once per element, whose response is loaded the same way. + function loadArgument(element, argument, properties) { + if (argument.constructor != String) { + load(element, argument, argument, properties); + } else if (argument.charAt(0) == "{" || argument.charAt(0) == "[") { + load(element, JSON.parse(argument), argument, properties); + } else { + notice("url"); + $.ajax({ + url: argument, + success: function (response) { + loadArgument(element, response, properties); + }, + cache: false, + dataType: "json", + }); + } + } + + $.fn.loadJSON = function (data, options) { + installContains(); + if (options && "mobile" in options) { + notice("mobileOption"); + } + + var defaults = { + onLoading: function () {}, + onLoaded: function () {}, + mobile: false, + }; + var properties = $.extend(defaults, options); + + return this.each(function () { + loadArgument(this, data, properties); + }); + }; + + // Set to true to show a console warning, once per page, for each behavior removed in 2.0. + $.fn.loadJSON.debug = false; +})(jQuery); +})); diff --git a/docs/examples/list.html b/docs/examples/list.html new file mode 100644 index 0000000..e11aab9 --- /dev/null +++ b/docs/examples/list.html @@ -0,0 +1,50 @@ + + + + + + A list from an array ¡ jQuery loadJSON + + + + +
+

A list from an array

+

+ An array of objects loaded into one li: the item is filled with the first + object and copied for each of the others. The links already have an href, so + each gains its company's ID. +

+

Result

+
+
    +
  • + , + +
  • +
+
+ +

Template

+
+

Script

+
+
+ + + + + + diff --git a/docs/examples/show-source.js b/docs/examples/show-source.js new file mode 100644 index 0000000..4cd83d0 --- /dev/null +++ b/docs/examples/show-source.js @@ -0,0 +1,42 @@ +// Shows each example's own markup and script on the page, so the code you read is the code that +// runs. The markup is read before the example's script runs, so it is shown before loadJSON fills it. + +// Removes the indentation the lines share. An element's outerHTML starts at its tag, so its first +// line has none and is left out of the count (skipFirst). +function dedent(text, skipFirst) { + var lines = text.replace(/^\s*\n|\n\s*$/g, "").split("\n"); + var counted = skipFirst ? lines.slice(1) : lines; + var indent = Math.min.apply( + null, + counted + .filter(function (line) { + return line.trim().length > 0; + }) + .map(function (line) { + return line.match(/^\s*/)[0].length; + }) + ); + + return lines + .map(function (line) { + return line.slice(Math.min(indent, line.match(/^\s*/)[0].length)); + }) + .join("\n"); +} + +document.querySelectorAll("pre[data-source]").forEach(function (pre) { + var source = document.querySelector(pre.getAttribute("data-source")); + pre.querySelector("code").textContent = dedent( + source.outerHTML.replace(/ (multiple|selected|checked|disabled|hidden)=""/g, " $1"), + true + ); +}); + +// The example's script comes after this one, so it is shown once the page is parsed. +document.addEventListener("DOMContentLoaded", function () { + document.querySelectorAll("pre[data-script]").forEach(function (pre) { + var script = document.querySelector(pre.getAttribute("data-script")); + + pre.querySelector("code").textContent = dedent(script.textContent); + }); +}); diff --git a/docs/examples/style.css b/docs/examples/style.css new file mode 100644 index 0000000..7f99a4f --- /dev/null +++ b/docs/examples/style.css @@ -0,0 +1,140 @@ +:root { + color-scheme: light dark; + --text: #1d2125; + --muted: #5c6670; + --background: #f4f5f7; + --surface: #ffffff; + --border: #d5d9de; + --accent: #0b5cad; + --code: #eef1f4; +} + +@media (prefers-color-scheme: dark) { + :root { + --text: #e6e8eb; + --muted: #a1a9b2; + --background: #15181b; + --surface: #1e2226; + --border: #3a4047; + --accent: #7db7f0; + --code: #262b30; + } +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + padding: 0 16px; + background: var(--background); + color: var(--text); + font: + 16px/1.5 system-ui, + -apple-system, + "Segoe UI", + sans-serif; +} + +main { + max-width: 760px; + margin: 24px auto 48px; + padding: 24px; + background: var(--surface); + border: 1px solid var(--border); + border-radius: 8px; +} + +nav { + max-width: 760px; + margin: 16px auto 0; + font-size: 14px; +} + +a { + color: var(--accent); +} + +h1 { + margin-top: 0; + font-size: 1.6rem; +} + +h2 { + margin-top: 2rem; + font-size: 1.2rem; +} + +.result { + padding: 16px; + border: 1px dashed var(--border); + border-radius: 6px; +} + +pre { + overflow-x: auto; + padding: 12px; + background: var(--code); + border-radius: 6px; + font-size: 13px; +} + +code { + font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; +} + +label { + display: block; + margin-top: 12px; + font-weight: 600; +} + +fieldset label { + display: inline; + margin-right: 12px; + font-weight: normal; +} + +fieldset { + margin-top: 12px; + border: 1px solid var(--border); + border-radius: 6px; +} + +input[type="text"], +textarea, +select { + width: 100%; + max-width: 420px; + padding: 6px; + font: inherit; +} + +table { + width: 100%; + border-collapse: collapse; +} + +th, +td { + padding: 6px 8px; + border-bottom: 1px solid var(--border); + text-align: left; +} + +img { + vertical-align: middle; +} + +.status { + color: var(--muted); + font-style: italic; +} + +.error { + color: #c0392b; +} +tr.selected td { + background: var(--code); +} diff --git a/docs/forms.md b/docs/forms.md new file mode 100644 index 0000000..254775b --- /dev/null +++ b/docs/forms.md @@ -0,0 +1,169 @@ +# Forms + +loadJSON fills a form from an object whose keys are the controls' names. Each control takes the value +in the way that suits its kind. See it in the +[form example](https://kevindb.github.io/jquery-load-json/examples/edit.html?ID=17). + +## Template + +```html +
+ + + + + + + + + + + + + + + + + +
+ Contact + + + +
+ + +
+``` + +## Data + +```js +$("#company").loadJSON({ + ID: 17, + Name: "Emkay Entertainments", + Address: "Nobel House, Regent Centre", + Country: ["UK", "FRA"], + IsFeatured: true, + Town: "Lothian", + Contact: "Phone", +}); +``` + +Keys are matched by class, then id, then name (see [Loading data](loading-data.md#how-keys-find-elements)). +In this form the labelled controls have an id equal to their name, so either one finds them. + +## Fields + +Text-like inputs take the value directly: `text`, `hidden`, `password`, `email`, `url`, `tel`, +`search`, `number`, `range`, `color`, `date`, `datetime-local`, `month`, `week` and `time`. + +Submit, reset, button, image and file inputs are left unchanged. + +## Textareas + +A textarea takes the value as its text. Markup in the value shows as text and is not parsed. + +## Checkboxes + +A checkbox is checked when its `value` equals the loaded value, and unchecked otherwise. The +comparison is loose, so the number `1` checks `value="1"`. + +- An array checks every box in the group whose value is in the array: + + ```html + + + + ``` + + ```js + $("form").loadJSON({ Tags: ["new", "featured"] }); + ``` + +- For a single box driven by a boolean, give the box `value="1"`: `true` equals `"1"` loosely and + checks it, `false` unchecks it. A box with no `value` attribute is not checked by `true`. + +## Radio buttons + +A radio button is checked when its `value` equals the loaded value, ignoring case, and unchecked +otherwise. Numbers and booleans are compared by their string form, so `3` checks `value="3"`. + +## Selects + +A single select selects the option whose value equals the loaded value: + +```js +$("form").loadJSON({ Town: "Lothian" }); +``` + +A multiple select selects each option whose value is the loaded value or is in the loaded array. +Options that were already selected stay selected. + +```js +$("form").loadJSON({ Country: ["UK", "FRA"] }); +``` + +### Adding options + +An array of `{ value, text, selected }` objects adds options to a select instead. Each item gets a +copy of the select's last option, inserted after it, with its value and text set; `selected: true` +selects it. Event handlers on the last option are copied too. + +```html + +``` + +```js +$("form").loadJSON({ + Region: [ + { value: 1, text: "East Europe" }, + { value: 2, text: "West Europe", selected: true }, + ], +}); +``` + +```html + +``` + +For a single select, any array adds options. For a multiple select, an array adds options only when +the select has one option or none; with more, the array is a list of values to select. + +The existing options stay, so loading a second array adds to the first. To replace the options, +remove the old ones before loading: + +```js +$("#Town").find("option:not(:first)").remove(); +$("#Town").loadJSON(towns); +``` + +### Options loaded directly + +An option matched by a key takes an object as its value, text and selected state: + +```html + +``` + +```js +$("form").loadJSON({ Default: { value: "", text: "Any", selected: true } }); +``` diff --git a/docs/loading-data.md b/docs/loading-data.md new file mode 100644 index 0000000..1302158 --- /dev/null +++ b/docs/loading-data.md @@ -0,0 +1,179 @@ +# Loading data + +To use loadJSON you need two things: a **template**, which is ordinary HTML, and the **data** to +load into it. + +## Template + +A template is plain markup. The elements that should take a value need a class, id or name equal to +a key of the data: + +```html +
+

+ + + + +
+``` + +## Data + +The data is a JavaScript object (or an array, or a single value). Each key names the elements that +take its value: + +```js +var data = { + Name: "Emkay Entertainments", + Address: "Nobel House, Regent Centre", + Contact: "Phone", +}; +``` + +## Loading + +Call `loadJSON` on the template with the data: + +```js +$("#company").loadJSON(data); +``` + +The result: + +```html +
+

Emkay Entertainments

+ + Nobel House, Regent Centre + + Phone +
+``` + +`loadJSON` returns the same jQuery object, so calls can be chained. When the jQuery set holds +several elements, each one is loaded with the same data. + +## How keys find elements + +For each key, loadJSON looks inside the **scope** (the template, for top-level keys) for its +**match**, trying in order: + +1. elements with the key as a class (`class="Name"`); +2. otherwise, elements with the key as their id (`id="Name"`); +3. otherwise, elements with the key as their name (`name="Name"`), including names with brackets + such as `name="tags[]"`. + +The first step that finds anything wins, and every element it finds takes the value. So +`class="Price"` on three elements loads the price into all three. + +- A key that matches nothing is skipped, as is an empty key. +- A `null` or `undefined` value leaves its elements unchanged. +- Keys that are not valid CSS selectors (with spaces, colons or quotes, for example) are compared + with each element's class, id or name directly. +- A key containing a dot, such as `"a.b"`, is read as the selector `.a.b` (class `a` and class + `b`), not as a class named `a.b`. Avoid dots in keys you match by class. + +If no class, id or name matches, elements anywhere in the page whose `rel` attribute is the key are +loaded. This is deprecated and removed in 2.0; see [Debugging and deprecations](debugging.md). + +## Nested objects + +When a value is an object, its keys are looked up inside the match of the enclosing key, which +becomes their scope: + +```html +
+
+ +
+
+ +
+
+``` + +```js +$("#order").loadJSON({ + customer: { name: "Asadul Ltd" }, + supplier: { name: "The Empire" }, +}); +``` + +Each `name` is found only inside its own `customer` or `supplier` element. + +## How elements take a value + +What a match does with its value depends on its **element kind**: + +| Element kind | Takes the value as | Details | +| ---------------------------------- | ----------------------------------------------------- | ----------------------- | +| Content (`div`, `span`, `p`, ...) | its contents, inserted as HTML | [Elements](elements.md) | +| Link (`a`) | its `href`, or a query parameter added to the `href` | [Elements](elements.md) | +| Image (`img`) | its `src`, or `src`, `alt` and `title` from an object | [Elements](elements.md) | +| Field (text, number, hidden, ...) | its value | [Forms](forms.md) | +| Checkbox, radio | checked when its value equals the value | [Forms](forms.md) | +| Select, option | the selected value, or new options from an array | [Forms](forms.md) | +| Any element given an array of data | one copy of the element per item | [Arrays](arrays.md) | + +## What you can pass + +`loadJSON(data, options)` accepts: + +- **An object or an array**: loaded as described above. +- **A single value** (a string, number or boolean): set on the template element itself, or on each + control when the template is a form. +- **A JSON string** that starts with `{` or `[`: parsed with `JSON.parse`, then loaded. Invalid JSON + throws. +- **Any other string** is requested as a URL and the JSON response is loaded. This is deprecated and + removed in 2.0. Request the data yourself and pass it in: + + ```js + $.getJSON("company.json").done(function (data) { + $("#company").loadJSON(data); + }); + ``` + +Calling `loadJSON()` with nothing or with `null` throws a `TypeError`. + +## Options + +| Option | Default | Description | +| ----------- | ---------- | --------------------------------------- | +| `onLoading` | do nothing | Called before each element is loaded. | +| `onLoaded` | do nothing | Called after each element is loaded. | +| `mobile` | `false` | Ignored. Deprecated and removed in 2.0. | + +The callbacks run once per element in the jQuery set, with no arguments: + +```js +$("#company").loadJSON(data, { + onLoading: function () { + $("#company").hide(); + }, + onLoaded: function () { + $("#company").fadeIn(); + }, +}); +``` + +## Loading the same template again + +loadJSON does not reset a template between calls: a second call loads into the output of the first, +including any copies a [repeat](arrays.md) added. To start each call from the original markup, set +the element's `loadJSON-template` data to an empty string before the first call: + +```js +$("#list").data("loadJSON-template", ""); +$("#list").loadJSON(firstPage); // saves the original markup, then loads +$("#list").loadJSON(secondPage); // restores the original markup, then loads +``` + +Restoring the saved markup replaces the template's content, so event handlers bound inside it after +the first call are lost. Bind them on the template element itself (delegated events) instead. + +## Untrusted data + +Values loaded into content elements, `').click(function(){o.click.apply(c.element[0],arguments)}).appendTo(j);b.each(o,function(k,m){if(k!=="click")k in g?l[k](m):l.attr(k,m)});b.fn.button&&l.button()});i.appendTo(c.uiDialog)}},_makeDraggable:function(){function a(n){return{position:n.position,offset:n.offset}}var c=this,h=c.options,i=b(document),j;c.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close", -handle:".ui-dialog-titlebar",containment:"document",start:function(n,o){j=h.height==="auto"?"auto":b(this).height();b(this).height(b(this).height()).addClass("ui-dialog-dragging");c._trigger("dragStart",n,a(o))},drag:function(n,o){c._trigger("drag",n,a(o))},stop:function(n,o){h.position=[o.position.left-i.scrollLeft(),o.position.top-i.scrollTop()];b(this).removeClass("ui-dialog-dragging").height(j);c._trigger("dragStop",n,a(o));b.ui.dialog.overlay.resize()}})},_makeResizable:function(a){function c(n){return{originalPosition:n.originalPosition, -originalSize:n.originalSize,position:n.position,size:n.size}}a=a===d?this.options.resizable:a;var h=this,i=h.options,j=h.uiDialog.css("position");a=typeof a==="string"?a:"n,e,s,w,se,sw,ne,nw";h.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:h.element,maxWidth:i.maxWidth,maxHeight:i.maxHeight,minWidth:i.minWidth,minHeight:h._minHeight(),handles:a,start:function(n,o){b(this).addClass("ui-dialog-resizing");h._trigger("resizeStart",n,c(o))},resize:function(n,o){h._trigger("resize", -n,c(o))},stop:function(n,o){b(this).removeClass("ui-dialog-resizing");i.height=b(this).height();i.width=b(this).width();h._trigger("resizeStop",n,c(o));b.ui.dialog.overlay.resize()}}).css("position",j).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")},_minHeight:function(){var a=this.options;return a.height==="auto"?a.minHeight:Math.min(a.minHeight,a.height)},_position:function(a){var c=[],h=[0,0],i;if(a){if(typeof a==="string"||typeof a==="object"&&"0"in a){c=a.split?a.split(" "): -[a[0],a[1]];if(c.length===1)c[1]=c[0];b.each(["left","top"],function(j,n){if(+c[j]===c[j]){h[j]=c[j];c[j]=n}});a={my:c.join(" "),at:c.join(" "),offset:h.join(" ")}}a=b.extend({},b.ui.dialog.prototype.options.position,a)}else a=b.ui.dialog.prototype.options.position;(i=this.uiDialog.is(":visible"))||this.uiDialog.show();this.uiDialog.css({top:0,left:0}).position(b.extend({of:window},a));i||this.uiDialog.hide()},_setOptions:function(a){var c=this,h={},i=false;b.each(a,function(j,n){c._setOption(j,n); -if(j in e)i=true;if(j in f)h[j]=n});i&&this._size();this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option",h)},_setOption:function(a,c){var h=this,i=h.uiDialog;switch(a){case "beforeclose":a="beforeClose";break;case "buttons":h._createButtons(c);break;case "closeText":h.uiDialogTitlebarCloseText.text(""+c);break;case "dialogClass":i.removeClass(h.options.dialogClass).addClass("ui-dialog ui-widget ui-widget-content ui-corner-all "+c);break;case "disabled":c?i.addClass("ui-dialog-disabled"): -i.removeClass("ui-dialog-disabled");break;case "draggable":var j=i.is(":data(draggable)");j&&!c&&i.draggable("destroy");!j&&c&&h._makeDraggable();break;case "position":h._position(c);break;case "resizable":(j=i.is(":data(resizable)"))&&!c&&i.resizable("destroy");j&&typeof c==="string"&&i.resizable("option","handles",c);!j&&c!==false&&h._makeResizable(c);break;case "title":b(".ui-dialog-title",h.uiDialogTitlebar).html(""+(c||" "));break}b.Widget.prototype._setOption.apply(h,arguments)},_size:function(){var a= -this.options,c,h,i=this.uiDialog.is(":visible");this.element.show().css({width:"auto",minHeight:0,height:0});if(a.minWidth>a.width)a.width=a.minWidth;c=this.uiDialog.css({height:"auto",width:a.width}).height();h=Math.max(0,a.minHeight-c);if(a.height==="auto")if(b.support.minHeight)this.element.css({minHeight:h,height:"auto"});else{this.uiDialog.show();a=this.element.css("height","auto").height();i||this.uiDialog.hide();this.element.height(Math.max(a,h))}else this.element.height(Math.max(a.height- -c,0));this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())}});b.extend(b.ui.dialog,{version:"1.8.12",uuid:0,maxZ:0,getTitleId:function(a){a=a.attr("id");if(!a){this.uuid+=1;a=this.uuid}return"ui-dialog-title-"+a},overlay:function(a){this.$el=b.ui.dialog.overlay.create(a)}});b.extend(b.ui.dialog.overlay,{instances:[],oldInstances:[],maxZ:0,events:b.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(a){return a+".dialog-overlay"}).join(" "), -create:function(a){if(this.instances.length===0){setTimeout(function(){b.ui.dialog.overlay.instances.length&&b(document).bind(b.ui.dialog.overlay.events,function(h){if(b(h.target).zIndex()").addClass("ui-widget-overlay")).appendTo(document.body).css({width:this.width(), -height:this.height()});b.fn.bgiframe&&c.bgiframe();this.instances.push(c);return c},destroy:function(a){var c=b.inArray(a,this.instances);c!=-1&&this.oldInstances.push(this.instances.splice(c,1)[0]);this.instances.length===0&&b([document,window]).unbind(".dialog-overlay");a.remove();var h=0;b.each(this.instances,function(){h=Math.max(h,this.css("z-index"))});this.maxZ=h},height:function(){var a,c;if(b.browser.msie&&b.browser.version<7){a=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight); -c=Math.max(document.documentElement.offsetHeight,document.body.offsetHeight);return a0?a.left-h:Math.max(a.left-c.collisionPosition.left,a.left)},top:function(a,c){var h=b(window);h=c.collisionPosition.top+c.collisionHeight-h.height()-h.scrollTop();a.top=h>0?a.top-h:Math.max(a.top-c.collisionPosition.top,a.top)}},flip:{left:function(a,c){if(c.at[0]!=="center"){var h=b(window);h=c.collisionPosition.left+c.collisionWidth-h.width()-h.scrollLeft();var i=c.my[0]==="left"?-c.elemWidth:c.my[0]==="right"?c.elemWidth:0,j=c.at[0]==="left"?c.targetWidth:-c.targetWidth,n=-2*c.offset[0];a.left+= -c.collisionPosition.left<0?i+j+n:h>0?i+j+n:0}},top:function(a,c){if(c.at[1]!=="center"){var h=b(window);h=c.collisionPosition.top+c.collisionHeight-h.height()-h.scrollTop();var i=c.my[1]==="top"?-c.elemHeight:c.my[1]==="bottom"?c.elemHeight:0,j=c.at[1]==="top"?c.targetHeight:-c.targetHeight,n=-2*c.offset[1];a.top+=c.collisionPosition.top<0?i+j+n:h>0?i+j+n:0}}}};if(!b.offset.setOffset){b.offset.setOffset=function(a,c){if(/static/.test(b.curCSS(a,"position")))a.style.position="relative";var h=b(a), -i=h.offset(),j=parseInt(b.curCSS(a,"top",true),10)||0,n=parseInt(b.curCSS(a,"left",true),10)||0;i={top:c.top-i.top+j,left:c.left-i.left+n};"using"in c?c.using.call(a,i):h.css(i)};b.fn.offset=function(a){var c=this[0];if(!c||!c.ownerDocument)return null;if(a)return this.each(function(){b.offset.setOffset(this,a)});return g.call(this)}}})(jQuery); -(function(b,d){b.widget("ui.progressbar",{options:{value:0,max:100},min:0,_create:function(){this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this.min,"aria-valuemax":this.options.max,"aria-valuenow":this._value()});this.valueDiv=b("
").appendTo(this.element);this.oldValue=this._value();this._refreshValue()},destroy:function(){this.element.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"); -this.valueDiv.remove();b.Widget.prototype.destroy.apply(this,arguments)},value:function(e){if(e===d)return this._value();this._setOption("value",e);return this},_setOption:function(e,f){if(e==="value"){this.options.value=f;this._refreshValue();this._value()===this.options.max&&this._trigger("complete")}b.Widget.prototype._setOption.apply(this,arguments)},_value:function(){var e=this.options.value;if(typeof e!=="number")e=0;return Math.min(this.options.max,Math.max(this.min,e))},_percentage:function(){return 100* -this._value()/this.options.max},_refreshValue:function(){var e=this.value(),f=this._percentage();if(this.oldValue!==e){this.oldValue=e;this._trigger("change")}this.valueDiv.toggle(e>this.min).toggleClass("ui-corner-right",e===this.options.max).width(f.toFixed(0)+"%");this.element.attr("aria-valuenow",e)}});b.extend(b.ui.progressbar,{version:"1.8.12"})})(jQuery); -(function(b){b.widget("ui.slider",b.ui.mouse,{widgetEventPrefix:"slide",options:{animate:false,distance:0,max:100,min:0,orientation:"horizontal",range:false,step:1,value:0,values:null},_create:function(){var d=this,e=this.options;this._mouseSliding=this._keySliding=false;this._animateOff=true;this._handleIndex=null;this._detectOrientation();this._mouseInit();this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget ui-widget-content ui-corner-all");e.disabled&&this.element.addClass("ui-slider-disabled ui-disabled"); -this.range=b([]);if(e.range){if(e.range===true){this.range=b("
");if(!e.values)e.values=[this._valueMin(),this._valueMin()];if(e.values.length&&e.values.length!==2)e.values=[e.values[0],e.values[0]]}else this.range=b("
");this.range.appendTo(this.element).addClass("ui-slider-range");if(e.range==="min"||e.range==="max")this.range.addClass("ui-slider-range-"+e.range);this.range.addClass("ui-widget-header")}b(".ui-slider-handle",this.element).length===0&&b("").appendTo(this.element).addClass("ui-slider-handle"); -if(e.values&&e.values.length)for(;b(".ui-slider-handle",this.element).length").appendTo(this.element).addClass("ui-slider-handle");this.handles=b(".ui-slider-handle",this.element).addClass("ui-state-default ui-corner-all");this.handle=this.handles.eq(0);this.handles.add(this.range).filter("a").click(function(f){f.preventDefault()}).hover(function(){e.disabled||b(this).addClass("ui-state-hover")},function(){b(this).removeClass("ui-state-hover")}).focus(function(){if(e.disabled)b(this).blur(); -else{b(".ui-slider .ui-state-focus").removeClass("ui-state-focus");b(this).addClass("ui-state-focus")}}).blur(function(){b(this).removeClass("ui-state-focus")});this.handles.each(function(f){b(this).data("index.ui-slider-handle",f)});this.handles.keydown(function(f){var g=true,a=b(this).data("index.ui-slider-handle"),c,h,i;if(!d.options.disabled){switch(f.keyCode){case b.ui.keyCode.HOME:case b.ui.keyCode.END:case b.ui.keyCode.PAGE_UP:case b.ui.keyCode.PAGE_DOWN:case b.ui.keyCode.UP:case b.ui.keyCode.RIGHT:case b.ui.keyCode.DOWN:case b.ui.keyCode.LEFT:g= -false;if(!d._keySliding){d._keySliding=true;b(this).addClass("ui-state-active");c=d._start(f,a);if(c===false)return}break}i=d.options.step;c=d.options.values&&d.options.values.length?(h=d.values(a)):(h=d.value());switch(f.keyCode){case b.ui.keyCode.HOME:h=d._valueMin();break;case b.ui.keyCode.END:h=d._valueMax();break;case b.ui.keyCode.PAGE_UP:h=d._trimAlignValue(c+(d._valueMax()-d._valueMin())/5);break;case b.ui.keyCode.PAGE_DOWN:h=d._trimAlignValue(c-(d._valueMax()-d._valueMin())/5);break;case b.ui.keyCode.UP:case b.ui.keyCode.RIGHT:if(c=== -d._valueMax())return;h=d._trimAlignValue(c+i);break;case b.ui.keyCode.DOWN:case b.ui.keyCode.LEFT:if(c===d._valueMin())return;h=d._trimAlignValue(c-i);break}d._slide(f,a,h);return g}}).keyup(function(f){var g=b(this).data("index.ui-slider-handle");if(d._keySliding){d._keySliding=false;d._stop(f,g);d._change(f,g);b(this).removeClass("ui-state-active")}});this._refreshValue();this._animateOff=false},destroy:function(){this.handles.remove();this.range.remove();this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider"); -this._mouseDestroy();return this},_mouseCapture:function(d){var e=this.options,f,g,a,c,h;if(e.disabled)return false;this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()};this.elementOffset=this.element.offset();f=this._normValueFromMouse({x:d.pageX,y:d.pageY});g=this._valueMax()-this._valueMin()+1;c=this;this.handles.each(function(i){var j=Math.abs(f-c.values(i));if(g>j){g=j;a=b(this);h=i}});if(e.range===true&&this.values(1)===e.min){h+=1;a=b(this.handles[h])}if(this._start(d, -h)===false)return false;this._mouseSliding=true;c._handleIndex=h;a.addClass("ui-state-active").focus();e=a.offset();this._clickOffset=!b(d.target).parents().andSelf().is(".ui-slider-handle")?{left:0,top:0}:{left:d.pageX-e.left-a.width()/2,top:d.pageY-e.top-a.height()/2-(parseInt(a.css("borderTopWidth"),10)||0)-(parseInt(a.css("borderBottomWidth"),10)||0)+(parseInt(a.css("marginTop"),10)||0)};this.handles.hasClass("ui-state-hover")||this._slide(d,h,f);return this._animateOff=true},_mouseStart:function(){return true}, -_mouseDrag:function(d){var e=this._normValueFromMouse({x:d.pageX,y:d.pageY});this._slide(d,this._handleIndex,e);return false},_mouseStop:function(d){this.handles.removeClass("ui-state-active");this._mouseSliding=false;this._stop(d,this._handleIndex);this._change(d,this._handleIndex);this._clickOffset=this._handleIndex=null;return this._animateOff=false},_detectOrientation:function(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(d){var e; -if(this.orientation==="horizontal"){e=this.elementSize.width;d=d.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)}else{e=this.elementSize.height;d=d.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)}e=d/e;if(e>1)e=1;if(e<0)e=0;if(this.orientation==="vertical")e=1-e;d=this._valueMax()-this._valueMin();return this._trimAlignValue(this._valueMin()+e*d)},_start:function(d,e){var f={handle:this.handles[e],value:this.value()};if(this.options.values&&this.options.values.length){f.value= -this.values(e);f.values=this.values()}return this._trigger("start",d,f)},_slide:function(d,e,f){var g;if(this.options.values&&this.options.values.length){g=this.values(e?0:1);if(this.options.values.length===2&&this.options.range===true&&(e===0&&f>g||e===1&&f1){this.options.values[d]=this._trimAlignValue(e);this._refreshValue();this._change(null,d)}else if(arguments.length)if(b.isArray(arguments[0])){f=this.options.values;g=arguments[0];for(a=0;a=this._valueMax())return this._valueMax();var e=this.options.step>0?this.options.step:1,f=(d-this._valueMin())%e;alignValue=d-f;if(Math.abs(f)*2>=e)alignValue+=f>0?e:-e;return parseFloat(alignValue.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max}, -_refreshValue:function(){var d=this.options.range,e=this.options,f=this,g=!this._animateOff?e.animate:false,a,c={},h,i,j,n;if(this.options.values&&this.options.values.length)this.handles.each(function(o){a=(f.values(o)-f._valueMin())/(f._valueMax()-f._valueMin())*100;c[f.orientation==="horizontal"?"left":"bottom"]=a+"%";b(this).stop(1,1)[g?"animate":"css"](c,e.animate);if(f.options.range===true)if(f.orientation==="horizontal"){if(o===0)f.range.stop(1,1)[g?"animate":"css"]({left:a+"%"},e.animate); -if(o===1)f.range[g?"animate":"css"]({width:a-h+"%"},{queue:false,duration:e.animate})}else{if(o===0)f.range.stop(1,1)[g?"animate":"css"]({bottom:a+"%"},e.animate);if(o===1)f.range[g?"animate":"css"]({height:a-h+"%"},{queue:false,duration:e.animate})}h=a});else{i=this.value();j=this._valueMin();n=this._valueMax();a=n!==j?(i-j)/(n-j)*100:0;c[f.orientation==="horizontal"?"left":"bottom"]=a+"%";this.handle.stop(1,1)[g?"animate":"css"](c,e.animate);if(d==="min"&&this.orientation==="horizontal")this.range.stop(1, -1)[g?"animate":"css"]({width:a+"%"},e.animate);if(d==="max"&&this.orientation==="horizontal")this.range[g?"animate":"css"]({width:100-a+"%"},{queue:false,duration:e.animate});if(d==="min"&&this.orientation==="vertical")this.range.stop(1,1)[g?"animate":"css"]({height:a+"%"},e.animate);if(d==="max"&&this.orientation==="vertical")this.range[g?"animate":"css"]({height:100-a+"%"},{queue:false,duration:e.animate})}}});b.extend(b.ui.slider,{version:"1.8.12"})})(jQuery); -(function(b,d){function e(){return++g}function f(){return++a}var g=0,a=0;b.widget("ui.tabs",{options:{add:null,ajaxOptions:null,cache:false,cookie:null,collapsible:false,disable:null,disabled:[],enable:null,event:"click",fx:null,idPrefix:"ui-tabs-",load:null,panelTemplate:"
",remove:null,select:null,show:null,spinner:"Loading…",tabTemplate:"
  • #{label}
  • "},_create:function(){this._tabify(true)},_setOption:function(c,h){if(c=="selected")this.options.collapsible&& -h==this.options.selected||this.select(h);else{this.options[c]=h;this._tabify()}},_tabId:function(c){return c.title&&c.title.replace(/\s/g,"_").replace(/[^\w\u00c0-\uFFFF-]/g,"")||this.options.idPrefix+e()},_sanitizeSelector:function(c){return c.replace(/:/g,"\\:")},_cookie:function(){var c=this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+f());return b.cookie.apply(null,[c].concat(b.makeArray(arguments)))},_ui:function(c,h){return{tab:c,panel:h,index:this.anchors.index(c)}},_cleanup:function(){this.lis.filter(".ui-state-processing").removeClass("ui-state-processing").find("span:data(label.tabs)").each(function(){var c= -b(this);c.html(c.data("label.tabs")).removeData("label.tabs")})},_tabify:function(c){function h(r,u){r.css("display","");!b.support.opacity&&u.opacity&&r[0].style.removeAttribute("filter")}var i=this,j=this.options,n=/^#.+/;this.list=this.element.find("ol,ul").eq(0);this.lis=b(" > li:has(a[href])",this.list);this.anchors=this.lis.map(function(){return b("a",this)[0]});this.panels=b([]);this.anchors.each(function(r,u){var v=b(u).attr("href"),w=v.split("#")[0],y;if(w&&(w===location.toString().split("#")[0]|| -(y=b("base")[0])&&w===y.href)){v=u.hash;u.href=v}if(n.test(v))i.panels=i.panels.add(i.element.find(i._sanitizeSelector(v)));else if(v&&v!=="#"){b.data(u,"href.tabs",v);b.data(u,"load.tabs",v.replace(/#.*$/,""));v=i._tabId(u);u.href="#"+v;u=i.element.find("#"+v);if(!u.length){u=b(j.panelTemplate).attr("id",v).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(i.panels[r-1]||i.list);u.data("destroy.tabs",true)}i.panels=i.panels.add(u)}else j.disabled.push(r)});if(c){this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all"); -this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.lis.addClass("ui-state-default ui-corner-top");this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom");if(j.selected===d){location.hash&&this.anchors.each(function(r,u){if(u.hash==location.hash){j.selected=r;return false}});if(typeof j.selected!=="number"&&j.cookie)j.selected=parseInt(i._cookie(),10);if(typeof j.selected!=="number"&&this.lis.filter(".ui-tabs-selected").length)j.selected= -this.lis.index(this.lis.filter(".ui-tabs-selected"));j.selected=j.selected||(this.lis.length?0:-1)}else if(j.selected===null)j.selected=-1;j.selected=j.selected>=0&&this.anchors[j.selected]||j.selected<0?j.selected:0;j.disabled=b.unique(j.disabled.concat(b.map(this.lis.filter(".ui-state-disabled"),function(r){return i.lis.index(r)}))).sort();b.inArray(j.selected,j.disabled)!=-1&&j.disabled.splice(b.inArray(j.selected,j.disabled),1);this.panels.addClass("ui-tabs-hide");this.lis.removeClass("ui-tabs-selected ui-state-active"); -if(j.selected>=0&&this.anchors.length){i.element.find(i._sanitizeSelector(i.anchors[j.selected].hash)).removeClass("ui-tabs-hide");this.lis.eq(j.selected).addClass("ui-tabs-selected ui-state-active");i.element.queue("tabs",function(){i._trigger("show",null,i._ui(i.anchors[j.selected],i.element.find(i._sanitizeSelector(i.anchors[j.selected].hash))[0]))});this.load(j.selected)}b(window).bind("unload",function(){i.lis.add(i.anchors).unbind(".tabs");i.lis=i.anchors=i.panels=null})}else j.selected=this.lis.index(this.lis.filter(".ui-tabs-selected")); -this.element[j.collapsible?"addClass":"removeClass"]("ui-tabs-collapsible");j.cookie&&this._cookie(j.selected,j.cookie);c=0;for(var o;o=this.lis[c];c++)b(o)[b.inArray(c,j.disabled)!=-1&&!b(o).hasClass("ui-tabs-selected")?"addClass":"removeClass"]("ui-state-disabled");j.cache===false&&this.anchors.removeData("cache.tabs");this.lis.add(this.anchors).unbind(".tabs");if(j.event!=="mouseover"){var l=function(r,u){u.is(":not(.ui-state-disabled)")&&u.addClass("ui-state-"+r)},k=function(r,u){u.removeClass("ui-state-"+ -r)};this.lis.bind("mouseover.tabs",function(){l("hover",b(this))});this.lis.bind("mouseout.tabs",function(){k("hover",b(this))});this.anchors.bind("focus.tabs",function(){l("focus",b(this).closest("li"))});this.anchors.bind("blur.tabs",function(){k("focus",b(this).closest("li"))})}var m,p;if(j.fx)if(b.isArray(j.fx)){m=j.fx[0];p=j.fx[1]}else m=p=j.fx;var q=p?function(r,u){b(r).closest("li").addClass("ui-tabs-selected ui-state-active");u.hide().removeClass("ui-tabs-hide").animate(p,p.duration||"normal", -function(){h(u,p);i._trigger("show",null,i._ui(r,u[0]))})}:function(r,u){b(r).closest("li").addClass("ui-tabs-selected ui-state-active");u.removeClass("ui-tabs-hide");i._trigger("show",null,i._ui(r,u[0]))},s=m?function(r,u){u.animate(m,m.duration||"normal",function(){i.lis.removeClass("ui-tabs-selected ui-state-active");u.addClass("ui-tabs-hide");h(u,m);i.element.dequeue("tabs")})}:function(r,u){i.lis.removeClass("ui-tabs-selected ui-state-active");u.addClass("ui-tabs-hide");i.element.dequeue("tabs")}; -this.anchors.bind(j.event+".tabs",function(){var r=this,u=b(r).closest("li"),v=i.panels.filter(":not(.ui-tabs-hide)"),w=i.element.find(i._sanitizeSelector(r.hash));if(u.hasClass("ui-tabs-selected")&&!j.collapsible||u.hasClass("ui-state-disabled")||u.hasClass("ui-state-processing")||i.panels.filter(":animated").length||i._trigger("select",null,i._ui(this,w[0]))===false){this.blur();return false}j.selected=i.anchors.index(this);i.abort();if(j.collapsible)if(u.hasClass("ui-tabs-selected")){j.selected= --1;j.cookie&&i._cookie(j.selected,j.cookie);i.element.queue("tabs",function(){s(r,v)}).dequeue("tabs");this.blur();return false}else if(!v.length){j.cookie&&i._cookie(j.selected,j.cookie);i.element.queue("tabs",function(){q(r,w)});i.load(i.anchors.index(this));this.blur();return false}j.cookie&&i._cookie(j.selected,j.cookie);if(w.length){v.length&&i.element.queue("tabs",function(){s(r,v)});i.element.queue("tabs",function(){q(r,w)});i.load(i.anchors.index(this))}else throw"jQuery UI Tabs: Mismatching fragment identifier."; -b.browser.msie&&this.blur()});this.anchors.bind("click.tabs",function(){return false})},_getIndex:function(c){if(typeof c=="string")c=this.anchors.index(this.anchors.filter("[href$="+c+"]"));return c},destroy:function(){var c=this.options;this.abort();this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs");this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.anchors.each(function(){var h= -b.data(this,"href.tabs");if(h)this.href=h;var i=b(this).unbind(".tabs");b.each(["href","load","cache"],function(j,n){i.removeData(n+".tabs")})});this.lis.unbind(".tabs").add(this.panels).each(function(){b.data(this,"destroy.tabs")?b(this).remove():b(this).removeClass("ui-state-default ui-corner-top ui-tabs-selected ui-state-active ui-state-hover ui-state-focus ui-state-disabled ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide")});c.cookie&&this._cookie(null,c.cookie);return this},add:function(c, -h,i){if(i===d)i=this.anchors.length;var j=this,n=this.options;h=b(n.tabTemplate.replace(/#\{href\}/g,c).replace(/#\{label\}/g,h));c=!c.indexOf("#")?c.replace("#",""):this._tabId(b("a",h)[0]);h.addClass("ui-state-default ui-corner-top").data("destroy.tabs",true);var o=j.element.find("#"+c);o.length||(o=b(n.panelTemplate).attr("id",c).data("destroy.tabs",true));o.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide");if(i>=this.lis.length){h.appendTo(this.list);o.appendTo(this.list[0].parentNode)}else{h.insertBefore(this.lis[i]); -o.insertBefore(this.panels[i])}n.disabled=b.map(n.disabled,function(l){return l>=i?++l:l});this._tabify();if(this.anchors.length==1){n.selected=0;h.addClass("ui-tabs-selected ui-state-active");o.removeClass("ui-tabs-hide");this.element.queue("tabs",function(){j._trigger("show",null,j._ui(j.anchors[0],j.panels[0]))});this.load(0)}this._trigger("add",null,this._ui(this.anchors[i],this.panels[i]));return this},remove:function(c){c=this._getIndex(c);var h=this.options,i=this.lis.eq(c).remove(),j=this.panels.eq(c).remove(); -if(i.hasClass("ui-tabs-selected")&&this.anchors.length>1)this.select(c+(c+1=c?--n:n});this._tabify();this._trigger("remove",null,this._ui(i.find("a")[0],j[0]));return this},enable:function(c){c=this._getIndex(c);var h=this.options;if(b.inArray(c,h.disabled)!=-1){this.lis.eq(c).removeClass("ui-state-disabled");h.disabled=b.grep(h.disabled,function(i){return i!=c});this._trigger("enable",null, -this._ui(this.anchors[c],this.panels[c]));return this}},disable:function(c){c=this._getIndex(c);var h=this.options;if(c!=h.selected){this.lis.eq(c).addClass("ui-state-disabled");h.disabled.push(c);h.disabled.sort();this._trigger("disable",null,this._ui(this.anchors[c],this.panels[c]))}return this},select:function(c){c=this._getIndex(c);if(c==-1)if(this.options.collapsible&&this.options.selected!=-1)c=this.options.selected;else return this;this.anchors.eq(c).trigger(this.options.event+".tabs");return this}, -load:function(c){c=this._getIndex(c);var h=this,i=this.options,j=this.anchors.eq(c)[0],n=b.data(j,"load.tabs");this.abort();if(!n||this.element.queue("tabs").length!==0&&b.data(j,"cache.tabs"))this.element.dequeue("tabs");else{this.lis.eq(c).addClass("ui-state-processing");if(i.spinner){var o=b("span",j);o.data("label.tabs",o.html()).html(i.spinner)}this.xhr=b.ajax(b.extend({},i.ajaxOptions,{url:n,success:function(l,k){h.element.find(h._sanitizeSelector(j.hash)).html(l);h._cleanup();i.cache&&b.data(j, -"cache.tabs",true);h._trigger("load",null,h._ui(h.anchors[c],h.panels[c]));try{i.ajaxOptions.success(l,k)}catch(m){}},error:function(l,k){h._cleanup();h._trigger("load",null,h._ui(h.anchors[c],h.panels[c]));try{i.ajaxOptions.error(l,k,c,j)}catch(m){}}}));h.element.dequeue("tabs");return this}},abort:function(){this.element.queue([]);this.panels.stop(false,true);this.element.queue("tabs",this.element.queue("tabs").splice(-2,2));if(this.xhr){this.xhr.abort();delete this.xhr}this._cleanup();return this}, -url:function(c,h){this.anchors.eq(c).removeData("cache.tabs").data("load.tabs",h);return this},length:function(){return this.anchors.length}});b.extend(b.ui.tabs,{version:"1.8.12"});b.extend(b.ui.tabs.prototype,{rotation:null,rotate:function(c,h){var i=this,j=this.options,n=i._rotate||(i._rotate=function(o){clearTimeout(i.rotation);i.rotation=setTimeout(function(){var l=j.selected;i.select(++l= (iPages - iPageCountHalf)) - { - iStartButton = iPages - iPageCount + 1; - iEndButton = iPages; - } - else - { - iStartButton = iCurrentPage - Math.ceil(iPageCount / 2) + 1; - iEndButton = iStartButton + iPageCount - 1; - } - } - } - - /* Build the dynamic list */ - for ( i=iStartButton ; i<=iEndButton ; i++ ) - { - if ( iCurrentPage != i ) - { - sList += ''+i+''; - } - else - { - sList += ''+i+''; - } - } - - /* Loop over each instance of the pager */ - var an = oSettings.aanFeatures.p; - var anButtons, anStatic, nPaginateList; - var fnClick = function(e) { - /* Use the information in the element to jump to the required page */ - var iTarget = (this.innerHTML * 1) - 1; - oSettings._iDisplayStart = iTarget * oSettings._iDisplayLength; - fnCallbackDraw( oSettings ); - e.preventDefault(); - }; - var fnFalse = function () { return false; }; - - for ( i=0, iLen=an.length ; i y) ? 1 : 0)); - }, - - "string-desc": function ( a, b ) - { - if ( typeof a != 'string' ) { a = ''; } - if ( typeof b != 'string' ) { b = ''; } - var x = a.toLowerCase(); - var y = b.toLowerCase(); - return ((x < y) ? 1 : ((x > y) ? -1 : 0)); - }, - - - /* - * html sorting (ignore html tags) - */ - "html-asc": function ( a, b ) - { - var x = a.replace( /<.*?>/g, "" ).toLowerCase(); - var y = b.replace( /<.*?>/g, "" ).toLowerCase(); - return ((x < y) ? -1 : ((x > y) ? 1 : 0)); - }, - - "html-desc": function ( a, b ) - { - var x = a.replace( /<.*?>/g, "" ).toLowerCase(); - var y = b.replace( /<.*?>/g, "" ).toLowerCase(); - return ((x < y) ? 1 : ((x > y) ? -1 : 0)); - }, - - - /* - * date sorting - */ - "date-asc": function ( a, b ) - { - var x = Date.parse( a ); - var y = Date.parse( b ); - - if ( isNaN(x) || x==="" ) - { - x = Date.parse( "01/01/1970 00:00:00" ); - } - if ( isNaN(y) || y==="" ) - { - y = Date.parse( "01/01/1970 00:00:00" ); - } - - return x - y; - }, - - "date-desc": function ( a, b ) - { - var x = Date.parse( a ); - var y = Date.parse( b ); - - if ( isNaN(x) || x==="" ) - { - x = Date.parse( "01/01/1970 00:00:00" ); - } - if ( isNaN(y) || y==="" ) - { - y = Date.parse( "01/01/1970 00:00:00" ); - } - - return y - x; - }, - - - /* - * numerical sorting - */ - "numeric-asc": function ( a, b ) - { - var x = (a=="-" || a==="") ? 0 : a*1; - var y = (b=="-" || b==="") ? 0 : b*1; - return x - y; - }, - - "numeric-desc": function ( a, b ) - { - var x = (a=="-" || a==="") ? 0 : a*1; - var y = (b=="-" || b==="") ? 0 : b*1; - return y - x; - } - }; - - - /* - * Variable: aTypes - * Purpose: Container for the various type of type detection that dataTables supports - * Scope: jQuery.fn.dataTableExt - * Notes: The functions in this array are expected to parse a string to see if it is a data - * type that it recognises. If so then the function should return the name of the type (a - * corresponding sort function should be defined!), if the type is not recognised then the - * function should return null such that the parser and move on to check the next type. - * Note that ordering is important in this array - the functions are processed linearly, - * starting at index 0. - * Note that the input for these functions is always a string! It cannot be any other data - * type - */ - _oExt.aTypes = [ - /* - * Function: - - * Purpose: Check to see if a string is numeric - * Returns: string:'numeric' or null - * Inputs: mixed:sText - string to check - */ - function ( sData ) - { - /* Allow zero length strings as a number */ - if ( typeof sData == 'number' ) - { - return 'numeric'; - } - else if ( typeof sData != 'string' ) - { - return null; - } - - var sValidFirstChars = "0123456789-"; - var sValidChars = "0123456789."; - var Char; - var bDecimal = false; - - /* Check for a valid first char (no period and allow negatives) */ - Char = sData.charAt(0); - if (sValidFirstChars.indexOf(Char) == -1) - { - return null; - } - - /* Check all the other characters are valid */ - for ( var i=1 ; i') != -1 ) - { - return 'html'; - } - return null; - } - ]; - - /* - * Function: fnVersionCheck - * Purpose: Check a version string against this version of DataTables. Useful for plug-ins - * Returns: bool:true -this version of DataTables is greater or equal to the required version - * false -this version of DataTales is not suitable - * Inputs: string:sVersion - the version to check against. May be in the following formats: - * "a", "a.b" or "a.b.c" - * Notes: This function will only check the first three parts of a version string. It is - * assumed that beta and dev versions will meet the requirements. This might change in future - */ - _oExt.fnVersionCheck = function( sVersion ) - { - /* This is cheap, but very effective */ - var fnZPad = function (Zpad, count) - { - while(Zpad.length < count) { - Zpad += '0'; - } - return Zpad; - }; - var aThis = _oExt.sVersion.split('.'); - var aThat = sVersion.split('.'); - var sThis = '', sThat = ''; - - for ( var i=0, iLen=aThat.length ; i= parseInt(sThat, 10); - }; - - /* - * Variable: _oExternConfig - * Purpose: Store information for DataTables to access globally about other instances - * Scope: jQuery.fn.dataTableExt - */ - _oExt._oExternConfig = { - /* int:iNextUnique - next unique number for an instance */ - "iNextUnique": 0 - }; - - - /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - * Section - DataTables prototype - * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ - - /* - * Function: dataTable - * Purpose: DataTables information - * Returns: - - * Inputs: object:oInit - initialisation options for the table - */ - $.fn.dataTable = function( oInit ) - { - /* - * Function: classSettings - * Purpose: Settings container function for all 'class' properties which are required - * by dataTables - * Returns: - - * Inputs: - - */ - function classSettings () - { - this.fnRecordsTotal = function () - { - if ( this.oFeatures.bServerSide ) { - return parseInt(this._iRecordsTotal, 10); - } else { - return this.aiDisplayMaster.length; - } - }; - - this.fnRecordsDisplay = function () - { - if ( this.oFeatures.bServerSide ) { - return parseInt(this._iRecordsDisplay, 10); - } else { - return this.aiDisplay.length; - } - }; - - this.fnDisplayEnd = function () - { - if ( this.oFeatures.bServerSide ) { - if ( this.oFeatures.bPaginate === false || this._iDisplayLength == -1 ) { - return this._iDisplayStart+this.aiDisplay.length; - } else { - return Math.min( this._iDisplayStart+this._iDisplayLength, - this._iRecordsDisplay ); - } - } else { - return this._iDisplayEnd; - } - }; - - /* - * Variable: oInstance - * Purpose: The DataTables object for this table - * Scope: jQuery.dataTable.classSettings - */ - this.oInstance = null; - - /* - * Variable: sInstance - * Purpose: Unique idendifier for each instance of the DataTables object - * Scope: jQuery.dataTable.classSettings - */ - this.sInstance = null; - - /* - * Variable: oFeatures - * Purpose: Indicate the enablement of key dataTable features - * Scope: jQuery.dataTable.classSettings - */ - this.oFeatures = { - "bPaginate": true, - "bLengthChange": true, - "bFilter": true, - "bSort": true, - "bInfo": true, - "bAutoWidth": true, - "bProcessing": false, - "bSortClasses": true, - "bStateSave": false, - "bServerSide": false, - "bDeferRender": false - }; - - /* - * Variable: oScroll - * Purpose: Container for scrolling options - * Scope: jQuery.dataTable.classSettings - */ - this.oScroll = { - "sX": "", - "sXInner": "", - "sY": "", - "bCollapse": false, - "bInfinite": false, - "iLoadGap": 100, - "iBarWidth": 0, - "bAutoCss": true - }; - - /* - * Variable: aanFeatures - * Purpose: Array referencing the nodes which are used for the features - * Scope: jQuery.dataTable.classSettings - * Notes: The parameters of this object match what is allowed by sDom - i.e. - * 'l' - Length changing - * 'f' - Filtering input - * 't' - The table! - * 'i' - Information - * 'p' - Pagination - * 'r' - pRocessing - */ - this.aanFeatures = []; - - /* - * Variable: oLanguage - * Purpose: Store the language strings used by dataTables - * Scope: jQuery.dataTable.classSettings - * Notes: The words in the format _VAR_ are variables which are dynamically replaced - * by javascript - */ - this.oLanguage = { - "sProcessing": "Processing...", - "sLengthMenu": "Show _MENU_ entries", - "sZeroRecords": "No matching records found", - "sEmptyTable": "No data available in table", - "sLoadingRecords": "Loading...", - "sInfo": "Showing _START_ to _END_ of _TOTAL_ entries", - "sInfoEmpty": "Showing 0 to 0 of 0 entries", - "sInfoFiltered": "(filtered from _MAX_ total entries)", - "sInfoPostFix": "", - "sInfoThousands": ",", - "sSearch": "Search:", - "sUrl": "", - "oPaginate": { - "sFirst": "First", - "sPrevious": "Previous", - "sNext": "Next", - "sLast": "Last" - }, - "fnInfoCallback": null - }; - - /* - * Variable: aoData - * Purpose: Store data information - * Scope: jQuery.dataTable.classSettings - * Notes: This is an array of objects with the following parameters: - * int: _iId - internal id for tracking - * array: _aData - internal data - used for sorting / filtering etc - * node: nTr - display node - * array node: _anHidden - hidden TD nodes - * string: _sRowStripe - */ - this.aoData = []; - - /* - * Variable: aiDisplay - * Purpose: Array of indexes which are in the current display (after filtering etc) - * Scope: jQuery.dataTable.classSettings - */ - this.aiDisplay = []; - - /* - * Variable: aiDisplayMaster - * Purpose: Array of indexes for display - no filtering - * Scope: jQuery.dataTable.classSettings - */ - this.aiDisplayMaster = []; - - /* - * Variable: aoColumns - * Purpose: Store information about each column that is in use - * Scope: jQuery.dataTable.classSettings - */ - this.aoColumns = []; - - /* - * Variable: aoHeader - * Purpose: Store information about the table's header - * Scope: jQuery.dataTable.classSettings - */ - this.aoHeader = []; - - /* - * Variable: aoFooter - * Purpose: Store information about the table's footer - * Scope: jQuery.dataTable.classSettings - */ - this.aoFooter = []; - - /* - * Variable: iNextId - * Purpose: Store the next unique id to be used for a new row - * Scope: jQuery.dataTable.classSettings - */ - this.iNextId = 0; - - /* - * Variable: asDataSearch - * Purpose: Search data array for regular expression searching - * Scope: jQuery.dataTable.classSettings - */ - this.asDataSearch = []; - - /* - * Variable: oPreviousSearch - * Purpose: Store the previous search incase we want to force a re-search - * or compare the old search to a new one - * Scope: jQuery.dataTable.classSettings - */ - this.oPreviousSearch = { - "sSearch": "", - "bRegex": false, - "bSmart": true - }; - - /* - * Variable: aoPreSearchCols - * Purpose: Store the previous search for each column - * Scope: jQuery.dataTable.classSettings - */ - this.aoPreSearchCols = []; - - /* - * Variable: aaSorting - * Purpose: Sorting information - * Scope: jQuery.dataTable.classSettings - * Notes: Index 0 - column number - * Index 1 - current sorting direction - * Index 2 - index of asSorting for this column - */ - this.aaSorting = [ [0, 'asc', 0] ]; - - /* - * Variable: aaSortingFixed - * Purpose: Sorting information that is always applied - * Scope: jQuery.dataTable.classSettings - */ - this.aaSortingFixed = null; - - /* - * Variable: asStripeClasses - * Purpose: Classes to use for the striping of a table - * Scope: jQuery.dataTable.classSettings - */ - this.asStripeClasses = []; - - /* - * Variable: asDestroyStripes - * Purpose: If restoring a table - we should restore its striping classes as well - * Scope: jQuery.dataTable.classSettings - */ - this.asDestroyStripes = []; - - /* - * Variable: sDestroyWidth - * Purpose: If restoring a table - we should restore its width - * Scope: jQuery.dataTable.classSettings - */ - this.sDestroyWidth = 0; - - /* - * Variable: fnRowCallback - * Purpose: Call this function every time a row is inserted (draw) - * Scope: jQuery.dataTable.classSettings - */ - this.fnRowCallback = null; - - /* - * Variable: fnHeaderCallback - * Purpose: Callback function for the header on each draw - * Scope: jQuery.dataTable.classSettings - */ - this.fnHeaderCallback = null; - - /* - * Variable: fnFooterCallback - * Purpose: Callback function for the footer on each draw - * Scope: jQuery.dataTable.classSettings - */ - this.fnFooterCallback = null; - - /* - * Variable: aoDrawCallback - * Purpose: Array of callback functions for draw callback functions - * Scope: jQuery.dataTable.classSettings - * Notes: Each array element is an object with the following parameters: - * function:fn - function to call - * string:sName - name callback (feature). useful for arranging array - */ - this.aoDrawCallback = []; - - /* - * Variable: fnPreDrawCallback - * Purpose: Callback function for just before the table is redrawn. A return of false - * will be used to cancel the draw. - * Scope: jQuery.dataTable.classSettings - */ - this.fnPreDrawCallback = null; - - /* - * Variable: fnInitComplete - * Purpose: Callback function for when the table has been initialised - * Scope: jQuery.dataTable.classSettings - */ - this.fnInitComplete = null; - - /* - * Variable: sTableId - * Purpose: Cache the table ID for quick access - * Scope: jQuery.dataTable.classSettings - */ - this.sTableId = ""; - - /* - * Variable: nTable - * Purpose: Cache the table node for quick access - * Scope: jQuery.dataTable.classSettings - */ - this.nTable = null; - - /* - * Variable: nTHead - * Purpose: Permanent ref to the thead element - * Scope: jQuery.dataTable.classSettings - */ - this.nTHead = null; - - /* - * Variable: nTFoot - * Purpose: Permanent ref to the tfoot element - if it exists - * Scope: jQuery.dataTable.classSettings - */ - this.nTFoot = null; - - /* - * Variable: nTBody - * Purpose: Permanent ref to the tbody element - * Scope: jQuery.dataTable.classSettings - */ - this.nTBody = null; - - /* - * Variable: nTableWrapper - * Purpose: Cache the wrapper node (contains all DataTables controlled elements) - * Scope: jQuery.dataTable.classSettings - */ - this.nTableWrapper = null; - - /* - * Variable: bDeferLoading - * Purpose: Indicate if when using server-side processing the loading of data - * should be deferred until the second draw - * Scope: jQuery.dataTable.classSettings - */ - this.bDeferLoading = false; - - /* - * Variable: bInitialised - * Purpose: Indicate if all required information has been read in - * Scope: jQuery.dataTable.classSettings - */ - this.bInitialised = false; - - /* - * Variable: aoOpenRows - * Purpose: Information about open rows - * Scope: jQuery.dataTable.classSettings - * Notes: Has the parameters 'nTr' and 'nParent' - */ - this.aoOpenRows = []; - - /* - * Variable: sDom - * Purpose: Dictate the positioning that the created elements will take - * Scope: jQuery.dataTable.classSettings - * Notes: - * The following options are allowed: - * 'l' - Length changing - * 'f' - Filtering input - * 't' - The table! - * 'i' - Information - * 'p' - Pagination - * 'r' - pRocessing - * The following constants are allowed: - * 'H' - jQueryUI theme "header" classes - * 'F' - jQueryUI theme "footer" classes - * The following syntax is expected: - * '<' and '>' - div elements - * '<"class" and '>' - div with a class - * Examples: - * '<"wrapper"flipt>', 'ip>' - */ - this.sDom = 'lfrtip'; - - /* - * Variable: sPaginationType - * Purpose: Note which type of sorting should be used - * Scope: jQuery.dataTable.classSettings - */ - this.sPaginationType = "two_button"; - - /* - * Variable: iCookieDuration - * Purpose: The cookie duration (for bStateSave) in seconds - default 2 hours - * Scope: jQuery.dataTable.classSettings - */ - this.iCookieDuration = 60 * 60 * 2; - - /* - * Variable: sCookiePrefix - * Purpose: The cookie name prefix - * Scope: jQuery.dataTable.classSettings - */ - this.sCookiePrefix = "SpryMedia_DataTables_"; - - /* - * Variable: fnCookieCallback - * Purpose: Callback function for cookie creation - * Scope: jQuery.dataTable.classSettings - */ - this.fnCookieCallback = null; - - /* - * Variable: aoStateSave - * Purpose: Array of callback functions for state saving - * Scope: jQuery.dataTable.classSettings - * Notes: Each array element is an object with the following parameters: - * function:fn - function to call. Takes two parameters, oSettings and the JSON string to - * save that has been thus far created. Returns a JSON string to be inserted into a - * json object (i.e. '"param": [ 0, 1, 2]') - * string:sName - name of callback - */ - this.aoStateSave = []; - - /* - * Variable: aoStateLoad - * Purpose: Array of callback functions for state loading - * Scope: jQuery.dataTable.classSettings - * Notes: Each array element is an object with the following parameters: - * function:fn - function to call. Takes two parameters, oSettings and the object stored. - * May return false to cancel state loading. - * string:sName - name of callback - */ - this.aoStateLoad = []; - - /* - * Variable: oLoadedState - * Purpose: State that was loaded from the cookie. Useful for back reference - * Scope: jQuery.dataTable.classSettings - */ - this.oLoadedState = null; - - /* - * Variable: sAjaxSource - * Purpose: Source url for AJAX data for the table - * Scope: jQuery.dataTable.classSettings - */ - this.sAjaxSource = null; - - /* - * Variable: sAjaxDataProp - * Purpose: Property from a given object from which to read the table data from. This can - * be an empty string (when not server-side processing), in which case it is - * assumed an an array is given directly. - * Scope: jQuery.dataTable.classSettings - */ - this.sAjaxDataProp = 'aaData'; - - /* - * Variable: bAjaxDataGet - * Purpose: Note if draw should be blocked while getting data - * Scope: jQuery.dataTable.classSettings - */ - this.bAjaxDataGet = true; - - /* - * Variable: jqXHR - * Purpose: The last jQuery XHR object that was used for server-side data gathering. - * This can be used for working with the XHR information in one of the callbacks - * Scope: jQuery.dataTable.classSettings - */ - this.jqXHR = null; - - /* - * Variable: fnServerData - * Purpose: Function to get the server-side data - can be overruled by the developer - * Scope: jQuery.dataTable.classSettings - */ - this.fnServerData = function ( url, data, callback, settings ) { - settings.jqXHR = $.ajax( { - "url": url, - "data": data, - "success": function (json) { - $(settings.oInstance).trigger('xhr', settings); - callback( json ); - }, - "dataType": "json", - "cache": false, - "error": function (xhr, error, thrown) { - if ( error == "parsererror" ) { - alert( "DataTables warning: JSON data from server could not be parsed. "+ - "This is caused by a JSON formatting error." ); - } - } - } ); - }; - - /* - * Variable: aoServerParams - * Purpose: Functions which are called prior to sending an Ajax request so extra parameters - * can easily be sent to the server - * Scope: jQuery.dataTable.classSettings - * Notes: Each array element is an object with the following parameters: - * function:fn - function to call - * string:sName - name callback - useful for knowing where it came from (plugin etc) - */ - this.aoServerParams = []; - - /* - * Variable: fnFormatNumber - * Purpose: Format numbers for display - * Scope: jQuery.dataTable.classSettings - */ - this.fnFormatNumber = function ( iIn ) - { - if ( iIn < 1000 ) - { - /* A small optimisation for what is likely to be the vast majority of use cases */ - return iIn; - } - else - { - var s=(iIn+""), a=s.split(""), out="", iLen=s.length; - - for ( var i=0 ; i