text
stringlengths 1
2.83M
| id
stringlengths 16
152
| metadata
dict | __index_level_0__
int64 0
949
|
---|---|---|---|
// Copyright (c) 2022 8th Wall, Inc.
/* globals AFRAME */
AFRAME.registerComponent('target-video', {
schema: {
name: {type: 'string'},
video: {type: 'string'},
},
init() {
const {object3D} = this.el
const {name} = this.data
object3D.visible = false
const v = document.querySelector(this.data.video)
const showImage = ({detail}) => {
if (name !== detail.name) {
return
}
v.play()
object3D.position.copy(detail.position)
object3D.quaternion.copy(detail.rotation)
object3D.scale.set(detail.scale, detail.scale, detail.scale)
object3D.visible = true
}
const hideImage = ({detail}) => {
if (name !== detail.name) {
return
}
v.pause()
object3D.visible = false
}
this.el.sceneEl.addEventListener('xrimagefound', showImage)
this.el.sceneEl.addEventListener('xrimageupdated', showImage)
this.el.sceneEl.addEventListener('xrimagelost', hideImage)
},
})
| 8thwall/web/examples/aframe/alpha-video/target-video.js/0 | {
"file_path": "8thwall/web/examples/aframe/alpha-video/target-video.js",
"repo_id": "8thwall",
"token_count": 416
} | 0 |
// Copyright (c) 2021 8th Wall, Inc.
/* globals AFRAME */
// This component hides and shows certain elements as the camera moves
AFRAME.registerComponent('portal', {
schema: {
width: {default: 4},
height: {default: 6},
depth: {default: 1},
},
init() {
this.camera = document.getElementById('camera')
this.contents = document.getElementById('portal-contents')
this.walls = document.getElementById('hider-walls')
this.portalWall = document.getElementById('portal-wall')
this.isInPortalSpace = false
this.wasOutside = true
},
tick() {
const {position} = this.camera.object3D
const isOutside = position.z > this.data.depth / 2
const withinPortalBounds =
position.y < this.data.height && Math.abs(position.x) < this.data.width / 2
if (this.wasOutside !== isOutside && withinPortalBounds) {
this.isInPortalSpace = !isOutside
}
this.contents.object3D.visible = this.isInPortalSpace || isOutside
this.walls.object3D.visible = !this.isInPortalSpace && isOutside
this.portalWall.object3D.visible = this.isInPortalSpace && !isOutside
this.wasOutside = isOutside
},
})
AFRAME.registerComponent('bob', {
schema: {
distance: {default: 0.15},
duration: {default: 1000},
},
init() {
const {el} = this
const {data} = this
data.initialPosition = this.el.object3D.position.clone()
data.downPosition = data.initialPosition.clone().setY(data.initialPosition.y - data.distance)
data.upPosition = data.initialPosition.clone().setY(data.initialPosition.y + data.distance)
const vectorToString = v => `${v.x} ${v.y} ${v.z}`
data.initialPosition = vectorToString(data.initialPosition)
data.downPosition = vectorToString(data.downPosition)
data.upPosition = vectorToString(data.upPosition)
data.timeout = null
const animatePosition = position => el.setAttribute('animation__bob', {
property: 'position',
to: position,
dur: data.duration,
easing: 'easeInOutQuad',
loop: false,
})
const bobDown = () => {
if (data.shouldStop) {
animatePosition(data.initialPosition)
data.stopped = true
return
}
animatePosition(data.downPosition)
data.timeout = setTimeout(bobUp, data.duration)
}
const bobUp = () => {
if (data.shouldStop) {
animatePosition(data.initialPosition)
data.stopped = true
return
}
animatePosition(data.upPosition)
data.timeout = setTimeout(bobDown, data.duration)
}
const bobStop = () => {
data.shouldStop = true
}
const bobStart = () => {
if (data.stopped) {
data.shouldStop = false
data.stopped = false
bobUp()
}
}
this.el.addEventListener('bobStart', bobStart)
this.el.addEventListener('bobStop', bobStop)
bobUp()
},
})
| 8thwall/web/examples/aframe/portal/portal-components.js/0 | {
"file_path": "8thwall/web/examples/aframe/portal/portal-components.js",
"repo_id": "8thwall",
"token_count": 1123
} | 1 |
const reportWebVitals = (onPerfEntry) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({getCLS, getFID, getFCP, getLCP, getTTFB}) => {
getCLS(onPerfEntry)
getFID(onPerfEntry)
getFCP(onPerfEntry)
getLCP(onPerfEntry)
getTTFB(onPerfEntry)
})
}
}
export default reportWebVitals
| 8thwall/web/examples/aframe/reactapp/src/reportWebVitals.js/0 | {
"file_path": "8thwall/web/examples/aframe/reactapp/src/reportWebVitals.js",
"repo_id": "8thwall",
"token_count": 164
} | 2 |
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>8th Wall Web: babylon.js</title>
<link rel="stylesheet" type="text/css" href="index.css">
<!-- Babylon.js -->
<script src="//cdn.jsdelivr.net/npm/babylonjs@4.1.0/babylon.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/babylonjs-loaders@4.1.0/babylonjs.loaders.min.js"></script>
<!-- Javascript tweening engine -->
<script src="//cdnjs.cloudflare.com/ajax/libs/tween.js/18.6.4/tween.umd.js"></script>
<!-- XR Extras - provides utilities like load screen, almost there, and error handling.
See github.com/8thwall/web/tree/master/xrextras -->
<script src="//cdn.8thwall.com/web/xrextras/xrextras.js"></script>
<!-- 8thWall Web - Replace the app key here with your own app key -->
<script async src="//apps.8thwall.com/xrweb?appKey=XXXXXXXX"></script>
<!-- client code -->
<script src="index.js"></script>
</head>
<body>
<canvas id="renderCanvas"></canvas>
</body>
</html>
| 8thwall/web/examples/babylonjs/placeground/index.html/0 | {
"file_path": "8thwall/web/examples/babylonjs/placeground/index.html",
"repo_id": "8thwall",
"token_count": 466
} | 3 |
/*
Ported to JavaScript by Lazar Laszlo 2011
lazarsoft@gmail.com, www.lazarsoft.info
*/
/*
*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function DataBlock(numDataCodewords, codewords)
{
this.numDataCodewords = numDataCodewords;
this.codewords = codewords;
this.__defineGetter__("NumDataCodewords", function()
{
return this.numDataCodewords;
});
this.__defineGetter__("Codewords", function()
{
return this.codewords;
});
}
DataBlock.getDataBlocks=function(rawCodewords, version, ecLevel)
{
if (rawCodewords.length != version.TotalCodewords)
{
throw "ArgumentException";
}
// Figure out the number and size of data blocks used by this version and
// error correction level
var ecBlocks = version.getECBlocksForLevel(ecLevel);
// First count the total number of data blocks
var totalBlocks = 0;
var ecBlockArray = ecBlocks.getECBlocks();
for (var i = 0; i < ecBlockArray.length; i++)
{
totalBlocks += ecBlockArray[i].Count;
}
// Now establish DataBlocks of the appropriate size and number of data codewords
var result = new Array(totalBlocks);
var numResultBlocks = 0;
for (var j = 0; j < ecBlockArray.length; j++)
{
var ecBlock = ecBlockArray[j];
for (var i = 0; i < ecBlock.Count; i++)
{
var numDataCodewords = ecBlock.DataCodewords;
var numBlockCodewords = ecBlocks.ECCodewordsPerBlock + numDataCodewords;
result[numResultBlocks++] = new DataBlock(numDataCodewords, new Array(numBlockCodewords));
}
}
// All blocks have the same amount of data, except that the last n
// (where n may be 0) have 1 more byte. Figure out where these start.
var shorterBlocksTotalCodewords = result[0].codewords.length;
var longerBlocksStartAt = result.length - 1;
while (longerBlocksStartAt >= 0)
{
var numCodewords = result[longerBlocksStartAt].codewords.length;
if (numCodewords == shorterBlocksTotalCodewords)
{
break;
}
longerBlocksStartAt--;
}
longerBlocksStartAt++;
var shorterBlocksNumDataCodewords = shorterBlocksTotalCodewords - ecBlocks.ECCodewordsPerBlock;
// The last elements of result may be 1 element longer;
// first fill out as many elements as all of them have
var rawCodewordsOffset = 0;
for (var i = 0; i < shorterBlocksNumDataCodewords; i++)
{
for (var j = 0; j < numResultBlocks; j++)
{
result[j].codewords[i] = rawCodewords[rawCodewordsOffset++];
}
}
// Fill out the last data block in the longer ones
for (var j = longerBlocksStartAt; j < numResultBlocks; j++)
{
result[j].codewords[shorterBlocksNumDataCodewords] = rawCodewords[rawCodewordsOffset++];
}
// Now add in error correction blocks
var max = result[0].codewords.length;
for (var i = shorterBlocksNumDataCodewords; i < max; i++)
{
for (var j = 0; j < numResultBlocks; j++)
{
var iOffset = j < longerBlocksStartAt?i:i + 1;
result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++];
}
}
return result;
}
| 8thwall/web/examples/camerapipeline/qrcode/jsqrcode/src/datablock.js/0 | {
"file_path": "8thwall/web/examples/camerapipeline/qrcode/jsqrcode/src/datablock.js",
"repo_id": "8thwall",
"token_count": 1196
} | 4 |
<!doctype html>
<html>
<head>
<title>8thWall Web: Simple Shaders</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<link rel="stylesheet" type="text/css" href="index.css">
<!-- XR Extras - provides utilities like load screen, almost there, and error handling.
See github.com/8thwall/web/tree/master/xrextras -->
<script src="//cdn.8thwall.com/web/xrextras/xrextras.js"></script>
<!-- 8thWall Web - Replace the app key here with your own app key -->
<script async src="//apps.8thwall.com/xrweb?appKey=XXXXXXXX"></script>
<!-- Client code -->
<script defer src="index.js"></script>
</head>
<body>
<canvas id="camerafeed"></canvas>
<div class="nextbutton" id="nextbutton">Next ></div>
</body>
</html>
| 8thwall/web/examples/camerapipeline/simpleshaders/index.html/0 | {
"file_path": "8thwall/web/examples/camerapipeline/simpleshaders/index.html",
"repo_id": "8thwall",
"token_count": 310
} | 5 |
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>8th Wall Web: babylon.js</title>
<link rel="stylesheet" type="text/css" href="index.css">
<!-- Babylon.js -->
<script src="//cdn.jsdelivr.net/npm/babylonjs@5.4.0/babylon.min.js" crossorigin="anonymous"></script>
<script src="//cdn.jsdelivr.net/npm/babylonjs-materials@5.4.0/babylonjs.materials.min.js" crossorigin="anonymous"></script>
<!-- XR Extras - provides utilities like load screen, almost there, and error handling.
See github.com/8thwall/web/tree/master/xrextras -->
<script src="//cdn.8thwall.com/web/xrextras/xrextras.js"></script>
<!-- Landing Pages - see https://www.8thwall.com/docs/web/#landing-pages -->
<script src='//cdn.8thwall.com/web/landing-page/landing-page.js'></script>
<!-- 8thWall Web - Replace the app key here with your own app key -->
<script async src="//apps.8thwall.com/xrweb?appKey=XXXXX"></script>
<!-- client code -->
<script src="index.js"></script>
</head>
<body>
<canvas id="renderCanvas"></canvas>
</body>
</html>
| 8thwall/web/gettingstarted/babylonjs/index.html/0 | {
"file_path": "8thwall/web/gettingstarted/babylonjs/index.html",
"repo_id": "8thwall",
"token_count": 485
} | 6 |
/* globals AFRAME, XRExtras, XR8 */
import {xrComponents} from './xr-components'
import {xrPrimitives} from './xr-primitives'
import {ensureXrAndExtras} from './ensure'
let xrextrasAframe = null
const onxrloaded = () => { XR8.addCameraPipelineModule(XRExtras.Loading.pipelineModule()) }
// We want to start showing the loading screen eagerly (before AFRAME has loaded and parsed the
// scene and set up everything). We also need to work around a bug in the AFRAME loading in iOS
// Webviews for almost there.
const eagerload = () => {
// Manually traverse the dom for an aframe scene and check its attributes.
const scene = document.getElementsByTagName('a-scene')[0]
if (!scene) {
return
}
const attrs = scene.attributes
let foundAlmostThere = false
let foundLoading = false
let redirectUrl = null
let runConfig = null
// Eagerly inspect the dom, and trigger loading or almost there modules early if appropriate.
const xrconfigPresent = Array.from(attrs).map(attr => attr.name).includes('xrconfig')
Object.keys(attrs).forEach((a) => {
const attr = attrs.item(a).name
if (attr === 'xrextras-almost-there') {
foundAlmostThere = true
const redirectMatch = new RegExp('url:([^;]*)').exec(attrs.item(a).value)
if (redirectMatch) {
redirectUrl = redirectMatch[1]
}
}
if (attr === 'xrextras-loading') {
foundLoading = true
}
// We use xrconfig if it is present, else xrweb or xrface or xrlayers.
if (attr === 'xrconfig' ||
(!xrconfigPresent && (attr === 'xrweb' || attr === 'xrface' || attr === 'xrlayers'))) {
const allowedDevicesMatch = new RegExp('allowedDevices:([^;]*)').exec(attrs.item(a).value)
if (allowedDevicesMatch) {
runConfig = {allowedDevices: allowedDevicesMatch[1].trim()}
}
}
})
if (foundAlmostThere) {
if (redirectUrl) {
window.XRExtras.AlmostThere.configure({url: redirectUrl})
}
// eslint-disable-next-line no-unused-expressions
window.XR8
? window.XRExtras.AlmostThere.checkCompatibility(runConfig)
: window.addEventListener(
'xrloaded', () => window.XRExtras.AlmostThere.checkCompatibility(runConfig)
)
}
if (foundLoading) {
const waitForRealityTexture =
!!(scene.attributes.xrweb || scene.attributes.xrface || scene.attributes.xrlayers)
window.XRExtras.Loading.showLoading({onxrloaded, waitForRealityTexture})
}
}
function create() {
let registered = false
// NOTE: new versions of 8frame should be added in descending order, so that the latest version
// is always in position 1.
const allowed8FrameVersions = ['latest', '0.9.0', '0.8.2']
const LATEST_8FRAME = allowed8FrameVersions[1] // The 'latest' version of 8frame.
// Check that the requested version of AFrame has a corresponding 8Frame implementation.
const checkAllowed8FrameVersions = version => new Promise((resolve, reject) => (allowed8FrameVersions.includes(version)
? resolve(version === 'latest' ? LATEST_8FRAME : version)
: reject(`'${version}' is an unsupported AFrame version. Alowed versions: (${allowed8FrameVersions})`)))
// Load an external javascript resource in a promise that resolves when the javascript has loaded.
const loadJsPromise = url => new Promise((resolve, reject) => document.head.appendChild(Object.assign(
document.createElement('script'), {async: true, onload: resolve, onError: reject, src: url}
)))
// If XR or XRExtras load before AFrame, we need to manually register their AFrame components.
const ensureAFrameComponents = () => {
if (window.XR8) {
window.AFRAME.registerComponent('xrconfig', XR8.AFrame.xrconfigComponent())
window.AFRAME.registerComponent('xrweb', XR8.AFrame.xrwebComponent())
window.AFRAME.registerComponent('xrface', XR8.AFrame.xrfaceComponent())
window.AFRAME.registerComponent('xrlayers', XR8.AFrame.xrlayersComponent())
window.AFRAME.registerComponent('xrlayerscene', XR8.AFrame.xrlayersceneComponent())
window.AFRAME.registerPrimitive('sky-scene', XR8.AFrame.skyscenePrimitive())
}
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
window.XRExtras && window.XRExtras.AFrame.registerXrExtrasComponents()
}
// Register a map of component-name -> component, e.g.
// {
// 'component-1': component1,
// 'component-2': component2,
// }
const registerComponents =
components => Object.keys(components).map(k => AFRAME.registerComponent(k, components[k]))
const registerPrimitives =
primitives => Object.keys(primitives).map(k => AFRAME.registerPrimitive(k, primitives[k]))
// Load the 8th Wall preferred version of AFrame at runtime ensuring that xr components are added.
const loadAFrameForXr = (args) => {
const {version = 'latest', components = {}} = args || {}
return checkAllowed8FrameVersions(version)
.then(ver => loadJsPromise(`//cdn.8thwall.com/web/aframe/8frame-${ver}.min.js`))
.then(ensureAFrameComponents)
.then(ensureXrAndExtras)
.then(_ => registerComponents(components))
}
// Register XRExtras AFrame components.
const registerXrExtrasComponents = () => {
// If AFrame is not ready, or we already registered components, skip.
if (registered || !window.AFRAME) {
return
}
// Only register the components once.
registered = true
// Show the loading screen as early as we can - add a System because it will get `init` called
// before assets finish loading, versus a Component which gets `init` after load.
AFRAME.registerSystem('eager-load-system', {
init() {
try {
/* eslint-disable-next-line no-unused-expressions */
window.XRExtras
? eagerload()
: window.addEventListener('xrextrasloaded', eagerload, {once: true})
} catch (err) {
// eslint-disable-next-line no-console
console.error(err)
}
},
})
registerComponents(xrComponents())
registerPrimitives(xrPrimitives())
}
// Eagerly try to register the aframe components, if aframe has already loaded.
registerXrExtrasComponents()
return {
// Load the 8th Wall version of AFrame at runtime ensuring that xr components are added.
loadAFrameForXr,
// Register the XRExtras components. This should only be called after AFrame has loaded.
registerXrExtrasComponents,
}
}
const AFrameFactory = () => {
if (!xrextrasAframe) {
xrextrasAframe = create()
}
return xrextrasAframe
}
export {
AFrameFactory,
}
| 8thwall/web/xrextras/src/aframe/aframe.js/0 | {
"file_path": "8thwall/web/xrextras/src/aframe/aframe.js",
"repo_id": "8thwall",
"token_count": 2343
} | 7 |
* {
font-family: inherit;
box-sizing: inherit;
}
.absolute-fill {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
.hidden {
display: none !important;
}
.error-text-outer-container {
display: flex;
align-items: center;
justify-content: center;
}
.error-text-container {
flex: 0 0 auto;
text-align: center;
width: 100%;
}
.error-text-header {
font-family: 'Nunito', sans-serif;
font-size: 16pt;
color: white;
letter-spacing: .37;
line-height: 23pt;
}
.xrextras-old-style .error-text-header {
color: #323232;
}
.error-text-hint {
font-family: 'Nunito', sans-serif;
font-size: 14pt;
color: #A8A8BA;
letter-spacing: .37;
}
.error-text-detail {
font-family: 'Nunito', sans-serif;
font-size: 14pt;
color: white;
}
.xrextras-old-style .error-text-detail {
color: #323232;
}
.error-margin-top-5 {
margin-top: 5vh;
}
.error-margin-top-20 {
margin-top: 20vh;
}
.desktop-home-link {
font-family: 'Nunito-SemiBold', sans-serif;
padding-top: 5px;
padding-bottom: 5px;
padding-left: 10px;
padding-right: 10px;
border-radius: 10px;
color: white;
background-color: #464766;
-webkit-user-select: all;
/* Chrome 49+ */
-moz-user-select: all;
/* Firefox 43+ */
-ms-user-select: all;
/* No support yet */
user-select: all;
pointer-events: auto;
}
.xrextras-old-style .desktop-home-link {
color: #323232;
background-color:rgba(173, 80, 255, 0.2);
}
.desktop-home-link.mobile {
position: fixed;
width: 100vw;
font-size: 1.1em;
font-weight: 800;
border-radius: 0px;
bottom: 30%;
left: 50%;
transform: translateX(-50%);
}
.xrextras-old-style .foreground-image {
filter: invert(1);
}
| 8thwall/web/xrextras/src/common.css/0 | {
"file_path": "8thwall/web/xrextras/src/common.css",
"repo_id": "8thwall",
"token_count": 723
} | 8 |
<div id="recorder" class="recorder-container">
<svg viewBox="0 0 38 38" class="progress-container">
<circle class="progress-track" r="16" cx="19" cy="19"></circle>
<circle id="progressBar" class="progress-bar" r="16" cx="19" cy="19"></circle>
<circle class="loading-circle" r="16" cx="19" cy="19"></circle>
</svg>
<button id="recorder-button" class="style-reset">
Record
</button>
</div>
<div id="flashElement" class="flash-element"></div>
| 8thwall/web/xrextras/src/mediarecorder/record-button.html/0 | {
"file_path": "8thwall/web/xrextras/src/mediarecorder/record-button.html",
"repo_id": "8thwall",
"token_count": 171
} | 9 |
const STATS_URL = 'https://cdn.8thwall.com/web/aframe/stats.16.min.js'
let statsModule = null
const loadJsPromise = url => new Promise((resolve, reject) => (
document.head.appendChild(
Object.assign(
document.createElement('script'),
{async: true, onload: resolve, onError: reject, src: url}
)
)
))
const StatsFactory = () => {
if (statsModule == null) {
statsModule = create()
}
return statsModule
}
function create() {
const pipelineModule = () => {
let stats_ = null
return {
name: 'stats',
onBeforeRun: () => (
window.Stats ? Promise.resolve() : loadJsPromise(STATS_URL)
),
onAttach: () => {
stats_ = new Stats()
stats_.showPanel(0)
stats_.dom.style.zIndex = 5000
stats_.dom.style.position = 'absolute'
stats_.dom.style.top = '0px'
stats_.dom.style.left = '0px'
document.body.appendChild(stats_.dom)
},
onUpdate: () => {
stats_.update()
},
onDetach: () => {
document.body.removeChild(stats_.dom)
stats_ = null
},
}
}
return {
// Creates a camera pipeline module that, when installed, adds a framerate stats element to
// the window dom. If the Stats package is not yet loaded, it will load it.
pipelineModule,
}
}
export {
StatsFactory,
}
| 8thwall/web/xrextras/src/statsmodule/stats.js/0 | {
"file_path": "8thwall/web/xrextras/src/statsmodule/stats.js",
"repo_id": "8thwall",
"token_count": 557
} | 10 |
## 一、颜色模式
颜色模式有两种:
- RGBA
`rgba(0,0,0,0.5); //黑色,透明度0.5`
- HSLA(颜色(0~360),饱和度(0%~100%),明度(0%~100%),透明度(0~1))
**红橙黄绿青蓝紫红**:颜色从 0~360 顺序,各占30度。比如红色为0,黄色为120,绿色为240。
`HSLA(0, 100%, 50%, 1); // 红色不透明,饱和度100%,亮度50%`
明度默认是50%,一般建议保留50的值,如果加到100后,变成白色,降到0后为黑色。
> 注意:
>
> 1、RGBA和HSLA中的透明度**不会影响子元素的透明度,不具继承性;**
>
> 2、**opacity 会影响子元素的透明度,子元素会继承父元素的透明度。**
>
> 3、**transparent 不可调节透明度,始终完全透明。**(`color: transparent;`)
## 二、文字阴影
语法:
```css
/*阴影可以叠加,使用逗号隔开*/
text-shadow: offsetX offsetY blur color,
offsetX1 offsetY1 blur1 color1, ...
```
> `offsetX`:X方向偏移度
>
> `offsetY`:Y方向偏移度
>
> `blur`:阴影的模糊度
>
> `color`:阴影颜色
示例:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
padding: 0;
margin: 0;
}
.demo {
width: 600px;
padding: 30px;
background-color: #666;
margin: 20px auto;
text-align: center;
font: bold 80px/100% "微软雅黑";
color: #fff;
}
/*添加阴影 text-shadow:offsetX offsetY blur color*/
.demo1 {
text-shadow: -5px -5px 5px orange;
}
.demo2 {
color: #000;
text-shadow: 0 1px 0 #fff;
}
/*立体浮雕效果*/
.demo3 {
text-shadow: -1px -1px 0 red,
-2px -2px 0 orange,
-3px -3px 0 yellow,
-4px -4px 0 green,
-5px -5px 0 cyan,
-6px -6px 0 blue,
-7px -7px 0 purple;
}
.demo4 {
text-shadow: 0 0 30px pink;
}
</style>
</head>
<body>
<div class="demo demo1">我是江小白</div>
<div class="demo demo2">我是江小白</div>
<div class="demo demo3">我是江小白</div>
<div class="demo demo4">我是江小白</div>
</body>
</html>
```
![1](./images/1.png)
## 三、盒模型
1、在默认情况下,CSS 设置的盒子宽度仅仅是内容区的宽度,而非盒子的宽度。同样,高度类似。真正盒子的宽度(在页面呈现出来的宽度)和高度,需要加上一些其它的属性。例如:
- padding + border + width = 盒子的宽度
- padding + border + height = 盒子的高度
很明显,这不直观,很容易出错,造成网页中其它元素的错位。
2、CSS3中可以通过`box-sizing` 来指定盒模型,即可指定为`content-box、border-box`,这样我们计算盒子大小的方式就发生了改变。
- `content-box`:对象的实际宽度等于设置的 width 值和 border、padding 之和。**(盒子实际的宽度 = 设置的 width + padding + border)**
- `border-box`: 对象的实际宽度就等于设置的width值,即使定义有 border 和 padding 也不会改变对象的实际宽度。**(盒子实际的宽度 = 设置的 width)**,相应的盒子的内容的宽度或高度区间会变小。
3、浏览器的兼容性
IE8 及以上版本支持该属性,Firefox 需要加上浏览器厂商前缀 `-moz-`,对于低版本的 IOS 和 Android 浏览器也需要加上 `-webkit-`
欧朋浏览器:前缀 -o-
IE浏览器:前缀 -ms-
## 四、边框圆角
使用 `border-radius` 属性来设置圆角。
```css
/*添加边框圆角*/
/*1.设置一个值:四个角的圆角值都一样*/
border-radius: 10px;
border-radius: 50%;
/*2.设置两个值:第一个值控制左上/右下,第二个值控制右上/左下*/
border-radius: 10px 30px;
/*3.设置三个值:第一个值控制左上,第二值控制右上/左下,第三个值控制右下*/
border-radius: 10px 40px 60px;
/*4.设置四个值:左上 右上 右下 左下*/
border-radius: 10px 30px 60px 100px;
/*5.添加/是用来设置当前水平和垂直方向的半径值:水平x方向/垂直y方向*/
border-radius: 100px/50px;
/*6.添加某个角点的圆角*/
border-radius: 0px 50px 0px 0px;
/*或者:border-上下-左右-radius:*/
border-top-right-radius: 100px;
border-top-left-radius: 100px;*/
border-bottom-left-radius: 100px;
border-bottom-right-radius: 100px;
/*7.设置某个角点的两个方向上的不同圆角*/
border-top-right-radius: 100px 50px; /*设置上偏移100px,右偏移50px样式的圆角*/
border-bottom-left-radius: 80px 40px; /*设置下偏移80px,左偏移40px样式的圆角*/
border-bottom-right-radius: 60px 30px;/*设置下偏移60px,右偏移30px样式的圆角*/
border-top-left-radius: 40px 20px; /*设置上偏移40px,左偏移20px样式的圆角*/
/*8.如果想设置四个角点的不同方向上的不同圆角值*/
/*分别是水平方向的偏移:左上,右上,右下,左下 ,垂直方向的偏移:左上,右上,右下,左下*/
border-radius: 100px 0px 0px 0px/20px 0px 0px 0px;
```
## 五、边框阴影
语法:
```css
box-shadow:h v blur spread color inset
```
> `h`:水平方向的偏移值(必填)
> `v`:垂直方向的偏移值(必填)
> `blur`:模糊度--可选,默认0 (必填)
> `spread`:阴影的尺寸,扩展和收缩阴影的大小--可选 默认0
> `color`:颜色--可选,默认黑色
> `inset`:内阴影--可选,默认是外阴影
当然,box-shadow 和 text-shadow 一样,也是可以添加多个的,之间用逗号隔开。
```css
box-shadow: 10px 10px 5px pink (inset),
-10px -10px 5px pink; /*spread等不需要,省略不写*/
```
![](./images/0.png)
| Daotin/Web/02-CSS/02-CSS3/02-颜色模式,文字阴影,盒模型,边框圆角,边框阴影.md/0 | {
"file_path": "Daotin/Web/02-CSS/02-CSS3/02-颜色模式,文字阴影,盒模型,边框圆角,边框阴影.md",
"repo_id": "Daotin",
"token_count": 3831
} | 11 |
## 1、函数的定义
```javascript
// 第一种:声明式函数-------------------------------
function fn1(){
console.log("我是第一种定义方法!");
}
// 第二种:赋值式函数------------------------------------
var fn2 = function (){
console.log("我是第二种定义方法!");
}; // 注意分号
// 使用方式1:
fn2();
// 使用方式2:函数的自调用
(function (a,b){
console.log("我是第二种定义方法!" + a+b); // 我是第二种定义方法!3
})(1,2); // 后面的额小括号用来传入参数
//第三种-----------------------------------------------------
var fn3 = new Function("a", "b", "console.log('我是第三种定义方法!' + a + b)");
```
> **第一种:**(函数的声明)第一种定义方法最强大,定义完毕后,在哪里使用都可以,无位置限制。
>
> **第二种:**(函数表达式:匿名函数) 后两种定义方法是有局限性的。(使用函数必须在定义函数之后)第二种函数的销毁使用 `fn2 = null;` 第一种方式不可销毁。
>
> **第三种:**new Function 的方式定义的函数非常强大,因为执行的函数代码是以字符串的形式传入的,那么就可以从地址栏传入,还可以从后台传入,这就很牛逼了,函数的代码竟然不写在函数体里面。。。
## 2、函数的调用
```javascript
// 1.函数名();
foo();
//2.函数自调用。
// 函数的自调用,仅执行一次。
// 函数的参数带入通过后面的小括号带入数据.
// 这样写,里面的内容就是私有的变量或者函数,就形成了封闭空间
(function(){})();
// 3.使用call,apply
foo.call(null,参数1,参数2, ...);
foo.apply(null,[参数1,参数2, ...]);
```
## 3、函数名
- 要遵循驼峰命名法。
- 不能同名(函数重载),否则后面的函数会覆盖前面的函数。
```js
//打印函数名,就等于打印整个函数。
console.log(fn);
//打印执行函数,就等于打印函数的返回值。
console.log(fn());
```
## 4、形参和实参
- 形参不需要写 var.
- 形参的个数和实参的个数可以不一致 。
## 5、返回值
1. 如果函数没有显示的使用 return 语句 ,那么函数有默认的返回值:undefined
2. 如果函数使用 return 语句,但是 return 后面没有任何值,那么函数的返回值也是:undefined.
**return 可以返回的类型包含下列几种:**
### 1、工厂模式
要求:
- 函数内部创建一个对象,由一个局部变量接收,然后返回这个对象。
- 可以通过函数参数改变对象的内容
```js
function fn2(w,color) {
var div=document.createElement("div");
Object.assign(div.style,{
width:(w || 50)+"px",
height:(w || 50)+"px",
backgroundColor:color || "red",
position:"absolute"
});
return div;
}
fn2(100, "blue");
```
### 2、单例模式
```js
var obj={
divs:null,
createDiv:function (w,color) {
if(!this.divs){
this.divs=document.createElement("div");
Object.assign(this.divs.style,{
width:(w || 50)+"px",
height:(w || 50)+"px",
backgroundColor:color || "red"
});
}
return this.divs;
}
};
obj.createDiv(100, "blue");
obj.createDiv(100, "blue");
```
### 3、通过参数传入对象
```js
function fn3(obj) {
obj.a=10;
return obj;
}
var objs={
a:1,
b:2
};
var obj2=fn3(objs);
console.log(obj2===objs);//true 传入的是对象的引用
```
### 4、通过参数传入函数
```js
// 参数就是函数,返回的是参数的执行结果
function fn4(fn) {
return fn();
}
function fn5() {
return 5;
}
function fn6() {
return 6;
}
console.log(fn4(fn5)); // 5
console.log(fn4(fn6)); // 6
```
### 5、返回一个私密对象
```js
// 返回一个私密的对象,有私有变量
function fn7() {
return (function () {
var c=10;
return {
a:1,
b:2,
d:c
}
})();
}
console.log(fn7()); // 私有变量 c
```
### 6、返回多个元素的数组(ES5中的解构赋值)
```js
function fn8() {
var div=document.createElement("div");
var input=document.createElement("input");
return [div,input];
}
let [div,input]=fn8();
document.body.appendChild(div);
document.body.appendChild(input);
```
### 7、返回多个元素的对象(ES6中解构赋值)
```js
function fn9() {
return {a:1,b:2}
}
let {a,b}=fn9();
console.log(a,b); // 1,2
```
### 8、传入参数为函数,返回对象
```js
function fn10(fn,obj) {
return fn.bind(obj || {});
}
function fn11(a,b) {
this.a=a;
this.b=b;
return this;
}
function fn12(c,d) {
this.c=c;
this.d=d;
return this;
}
var obj5={f:50};
console.log(fn10(fn11)(10,20)); // {a:10,b:20}
console.log(fn10(fn12,obj5)(30,50)); //{c:30,d:50,f:50}
```
### 9、返回函数
```js
function fn13() {
return function (a,b) {
console.log(a,b);
}
}
fn13()(8,9);
```
## 6、变量和作用域
**全局变量**:
1、在 script 使用 var 定义的变量(所有的 script 共享其全局性,js 里面没有块级作用域概念,只有全局作用域和局部作用域)。
2、在 script 没有 var 的变量(即使在函数内部)。
3、使用window全局对象来声明,全局对象的属性对应也是全局变量。`window.test = 50; `
```javascript
function fn(){
var a = b = c = 1; // b和c就是隐式全局变量(等号)
var a = 1; b = 2; c = 3; // b和c就是隐式全局变量(分号)
var a = 1 , b = 2 , c = 3; // b和c就不是隐式全局变量(逗号)
}
```
(全局变量是不能被删除的,隐式全局变量是可以被删除的)
```javascript
var num1 = 10;
num2 = 20;
delete num1;
delete num2;
console.log(typeof num1); // number
console.log(typeof num2); // undefined
```
**局部变量**:
1、函数内部用 var 定义的变量。
2、函数的形参。
### 6.1、变量声明提升(预解析)
**作用:**查看语法错误。js的解析器在页面加载的时候,首先检查页面上的语法错误。把变量声明提升起来。(变量声明提升和函数整体提升)
### 6.2、变量的提升
**只提升变量名,不提升变量值。**
```javascript
consolas.log(aaa);// 打印的结果是 undefined ,因为只提升变量名,不提升变量值。
var aaa = 111;
```
在函数范围内,照样适用。
### 6.3、函数的提升
function 直接定义的方法:整体提升(上面说的第一种函数定义的方法).
```javascript
fn();
var aaa = 111;
function fn(){
//变量声明提升在函数内部照样实用。
//函数的就近原则(局部变量作用域),打印的aaa不是111,而是 undefined。
console.log(aaa); // undefined
var aaa = 222;
}
```
**预解析会分块:**
多对的 script 标签中函数重名的话,预解析不会冲突。也就是预解析的作用域是每一个的 script 标签。
> **var先提升,function再提升:**
示例:
```javascript
console.log(a); // 输出a函数体
function a() {
console.log("aaaaa");
}
var a = 1;
console.log(a); // 输出1
```
打印第一个结果的时候,var会提升,之后 function 再提升,但是函数a和变量a重名,function的a在后面覆盖掉变量a,所以第一个输出 a 函数体.
第二个前面var a = 1;提升之后,这个位置就相当于只有 a = 1; 赋值,所以第二个打印1.
### 6.4、变量提升与函数提升的机制
(参考链接)https://segmentfault.com/a/1190000008568071
(非常详细) [01-js变量提升与函数提升的详细过程.md](E:\Web\github\Web\QF Phase 2\01-js变量提升与函数提升的详细过程.md)
**注意:ES6 中的 let 将不再进行预编译操作。**
不会进行变量提升,代码将从上到下进行执行,在变量的定义之前,变量的使用会报错。
### 6.5、匿名函数
作用大致如下:
```javascript
//1.直接调用
(function (){
console.log(1);
})();
//2.绑定事件
document.onclick = function () {
alert(1);
}
//3.定时器
setInterval(function () {
console.log(444);
},1000);
```
## 7、Math 函数
```js
Math.random() // 返回 0 ~ 1 之间的随机数。
Math.abs(x) // 返回数的绝对值。
Math.pow(10,2)// 10的2次方。
Math.round(x) //把数四舍五入为最接近的整数。
Math.ceil(x) //对数进行上舍入。
Math.floor(x) //对数进行下舍入。
//----------------------------------------------------------------
//示例:
console.log(Math.ceil(1.2)); // 2
console.log(Math.ceil(1.5)); // 2
console.log(Math.ceil(1.6)); // 2
console.log(Math.ceil(-1.2)); // -1
console.log(Math.ceil(-1.5)); // -1
console.log(Math.ceil(-1.6)); // -1
console.log(Math.floor(1.2)); // 1
console.log(Math.floor(1.5)); // 1
console.log(Math.floor(1.6)); // 1
console.log(Math.floor(-1.2));// -2
console.log(Math.floor(-1.5));// -2
console.log(Math.floor(-1.6));// -2
console.log(Math.round(1.2)); // 1
console.log(Math.round(1.5)); // 2
console.log(Math.round(1.6)); // 2
console.log(Math.round(-1.2)); // -1
console.log(Math.round(-1.5)); // -1
console.log(Math.round(-1.6)); // -2
```
### 7.1、随机生成某个范围的整数
```js
var minNum = 1;
var maxNum = 100;
var num = Math.round(Math.random() * (maxNum - minNum)) + minNum;
```
`toFixed()` :方法可把 数字四舍五入为指定小数位数的数字。
```js
var num = 10;
console.log(num.toFixed(2)); // 10.00
```
## 8、函数也是对象
```js
//函数也是对象
function fn() {}
fn.a=10; // 给函数对象创建一个参数a
fn.fn2=function () { // 给函数对象创建一个参数fn2
return 5;
};
for(var i in fn) {
console..log(i); // a fn2
}
//----------------------------------------
function fn1(a,b) {
if(arguments.callee.length!==arguments.length){
console.log("输入参数错误")
}
// console.log(this.a);//错误的
console.log(arguments.callee.a);//可以获取当前函数对象的属性和方法
console.log(arguments.callee.fn2());
console.log(arguments.length) // 2
for(var str in arguments.callee){
console.log(str)
}
}
fn1(3,5);
// 函数length是形参的个数,和arguments.length不一定相同
console.log(fn1.length); // 2
```
> 注意:
>
> 函数.length === 函数形参的个数
>
> arguments.length === 函数实参的个数
>
> arguments.callee === 在哪个函数里面就表示哪个函数(当前调用其的函数)。
## 9、其他
### 9.1、函数的声明和函数表达式的区别
```js
// 函数的声明
if(true) {
function f1() {
console.log("f1()--1");
}
} else {
function f1() {
console.log("f1()--2");
}
}
f1();
```
> 函数声明如果放在 if-else- 里面,
>
> chrome 和 firefox 输出 f1()--1,
>
> IE8 下输出 f1()--2,因为函数声明会提前,第二个将第一个覆盖了。
```js
// 函数表达式
var func;
if(true) {
func = function () {
console.log("f1()--1");
};
} else {
func = function () {
console.log("f1()--2");
};
}
func();
```
> 函数表达式的方式,输出都是 f1()--1。所以尽量使用函数表达式。
### 9.2、严格模式
```js
function func() {
console.log(this) // window
}
func();
```
> 正常情况下是正确的。
```js
"use strict";
function func() {
console.log(this) // window
}
window.func(); // 严格模式下必须加 window,因为他认为函数是一个方法,方法必须通过对象来调用的。
```
**9.2.1、函数也是对象,对象不一定是函数(比如:Math)。**
只要有 `__proto__` 的就是对象;
只有要 `prototype` 的就是函数,因为函数才会调用 prototype 属性。
对象不一定是函数:比如 Math,中有 `__proto__` ,但是没有 `prototype`。
**9.2.2、所有的函数都是由 Function 构造函数创建的实例对象。**
既然函数是对象,那么是什么构造函数创建的呢?
```js
var f1 = new Function("a", "b", "return a+b");
f1(1,2);
// 上面相当于:函数的声明
function f1(a, b) {
return a+b;
}
f1(1,2);
// 相当于:函数表达式
var f1 = function (a, b) {
return a+b;
}
f1(1,2);
```
那么 Function 是个什么东西呢?
经查看是对象也是函数。然后查看它的 `__proto__` 指向的是 Object的原型对象。所有的对象指向的都是Object的原型对象。 | Daotin/Web/03-JavaScript/01-JavaScript基础知识/04-函数.md/0 | {
"file_path": "Daotin/Web/03-JavaScript/01-JavaScript基础知识/04-函数.md",
"repo_id": "Daotin",
"token_count": 7365
} | 12 |
打飞机小案例
玩法:键盘上下左右方向键控制飞机的移动,子弹打到敌机,敌机消失,计分板显示消灭敌机数量。
代码如下:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.dv {
width: 300px;
height: 600px;
margin: 20px auto;
position: relative;
}
.box {
width: 300px;
height: 500px;
/* margin: 20px auto; */
border: 2px solid #666;
position: relative;
overflow: hidden;
}
.me {
width: 49px;
height: 61px;
background: url("../images/me.png");
background-size: 49px 61px;
border: 1px solid green;
box-sizing: border-box;
position: absolute;
left: 125px;
top: 439px;
}
.zd {
width: 7px;
height: 18px;
background: url("../images/bullet.png");
background-size: 7px 18px;
position: absolute;
}
.plane {
width: 30px;
height: 18px;
background: url("../images/plane1.png");
background-size: 30px 18px;
border: 1px solid red;
box-sizing: border-box;
position: absolute;
}
p {
width: 300px;
height: 50px;
background-color: aqua;
position: absolute;
border: 2px solid #666;
top: 500px;
left: 0;
}
p span {
color: red;
font-size: 30px;
}
.over {
width: 300px;
height: 500px;
background-color: rgba(0, 0, 0, 0.6);
position: absolute;
left: 0;
top: 0;
display: none;
}
.over span {
width: 214px;
height: 52px;
position: absolute;
background-image: url("../images/logo.png");
background-size: 214px 52px;
left: 42px;
top: 250px;
}
</style>
</head>
<body>
<div class="dv">
<div class="box">
<div class="over"><span></span></div>
<div class="me"></div>
<!-- <div class="zd"></div> -->
<!-- <div class="plane"></div> -->
</div>
<p>你已击落敌机 <span>0</span> 架</p>
</div>
</body>
<script src="../js/daotin.js"></script>
<script>
var box = document.querySelector(".box");
// console.log(box);
var me = document.querySelector(".me");
var span = document.querySelector("p span");
var over = document.querySelector(".over");
var step = 5; // me 移动速度
var bulletSpeed = 20; // 子弹移动速度
var planeSpeed = 1;
var bulletCreatTimer = 0;
var planeCreatTimer = 0;
var boxWidth = getStyle(box, "width");
var boxHeight = getStyle(box, "height");
var meWidth = parseInt(getStyle(me, "width"));
var meHeight = parseInt(getStyle(me, "height"));
var bulletWidth = 0;
var bulletHeight = 0;
var planeWidth = 0;
var planeHeight = 0;
// 产生子弹
function creatBullet() {
var bullet = document.createElement("div");
bullet.className = "zd";
box.appendChild(bullet);
bulletWidth = parseInt(getStyle(bullet, "width"));
bulletHeight = parseInt(getStyle(bullet, "height"));
bullet.style.top = parseInt(getStyle(me, "top")) - parseInt(getStyle(bullet, "height")) + "px";
bullet.style.left = parseInt(getStyle(me, "left")) + parseInt(getStyle(me, "width")) / 2 - parseInt(getStyle(
bullet, "width")) / 2 + "px";
// 每个子弹都有自己独立的定时器,所以使用bullet.timer
bullet.timer = setInterval(function () {
bullet.style.top = parseInt(getStyle(bullet, "top")) - bulletSpeed + "px";
var planeAll = document.querySelectorAll(".plane");
if (parseInt(bullet.style.top) <= 0) {
clearInterval(bullet.timer);
bullet.remove();
}
// 每生成一颗子弹,判断子弹与敌机的位置
for (var i = 0; i < planeAll.length; i++) {
var planeItem = planeAll[i];
var tmpplaneLeft = parseInt(getStyle(planeItem, "left"));
var tmpplaneTop = parseInt(getStyle(planeItem, "top"));
var tmpbulletLeft = parseInt(getStyle(bullet, "left"));
var tmpbulletTop = parseInt(getStyle(bullet, "top"));
var meLeft = parseInt(getStyle(me, "left"));
var meTop = parseInt(getStyle(me, "top"));
// 敌机撞到了我方飞机,游戏结束
if ((tmpplaneLeft + planeWidth > meLeft) && (meLeft + meWidth > tmpplaneLeft) &&
(tmpplaneTop + planeHeight > meTop) && (meTop + meHeight > tmpplaneTop)) {
for (var i = 0; i < planeAll.length; i++) {
clearInterval(planeAll[i].timer);
}
document.onkeydown = document.onkeyup = null;
clearInterval(bullet.timer);
clearInterval(bulletCreatTimer);
clearInterval(planeCreatTimer);
over.style.display = "block";
}
// 子弹打到敌机,敌机消失
if ((tmpbulletLeft + bulletWidth > tmpplaneLeft) && (tmpplaneLeft + planeWidth > tmpbulletLeft) &&
(tmpbulletTop + bulletHeight > tmpplaneTop) && (tmpplaneTop + planeHeight > tmpbulletTop)) {
span.innerHTML = span.innerHTML * 1 + 1;
clearInterval(bullet.timer);
bullet.remove();
clearInterval(planeItem.timer);
planeItem.remove();
}
}
}, 100);
};
bulletCreatTimer = setInterval(creatBullet, 200);
// 产生敌机
function creatPlane() {
var plane = document.createElement("div");
plane.className = "plane";
box.appendChild(plane);
planeWidth = parseInt(getStyle(plane, "width"));
planeHeight = parseInt(getStyle(plane, "height"));
plane.style.left = Math.floor(Math.random() *
(parseInt(getStyle(box, "width")) - parseInt(getStyle(plane, "width")))) + "px";
plane.style.top = 0;
plane.timer = setInterval(function (e) {
plane.style.top = parseInt(plane.style.top) + planeSpeed + "px";
if (parseInt(plane.style.top) >= (parseInt(boxHeight) - parseInt(getStyle(plane,
"height")))) {
clearInterval(plane.timer);
plane.remove();
}
}, 10);
};
planeCreatTimer = setInterval(creatPlane, 1000);
// 键盘控制我方飞机移动
document.onkeydown = document.onkeyup = function (e) {
var evt = window.event || e;
var keyCode = evt.which || evt.keyCode;
switch (keyCode) {
case 37: //左
me.style.left = parseInt(getStyle(me, "left")) - step + "px";
parseInt(me.style.left) <= 0 ? me.style.left = 0 : me.style.left = me.style.left;
break;
case 38: //上
me.style.top = parseInt(getStyle(me, "top")) - step + "px";
parseInt(me.style.top) <= 0 ? me.style.top = 0 : me.style.top = me.style.top;
break;
case 39: //右
me.style.left = parseInt(getStyle(me, "left")) + step + "px";
parseInt(me.style.left) >= (parseInt(boxWidth) - parseInt(meWidth)) ?
me.style.left = (parseInt(boxWidth) - parseInt(meWidth)) + "px" :
me.style.left = me.style.left;
break;
case 40: //下
me.style.top = parseInt(getStyle(me, "top")) + step + "px";
parseInt(me.style.top) >= (parseInt(boxHeight) - parseInt(meHeight)) ?
me.style.top = (parseInt(boxHeight) - parseInt(meHeight)) + "px" :
me.style.top = me.style.top;
break;
default:
break;
}
}
</script>
</html
```
![](./images/1.gif) | Daotin/Web/03-JavaScript/02-DOM/案例04:打飞机.md/0 | {
"file_path": "Daotin/Web/03-JavaScript/02-DOM/案例04:打飞机.md",
"repo_id": "Daotin",
"token_count": 4668
} | 13 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.map {
width: 800px;
height: 600px;
background-color: #ccc;
position: relative;
}
</style>
</head>
<body>
<div class="map"></div>
<script src="common.js"></script>
<script>
// 获取地图对象
var map = document.getElementsByClassName("map")[0];
// 产生随机数对象
(function () {
// 产生随机数的构造函数
function Random() {
}
// 把Random暴露给window
window.Random = Random;
// 在原型对象中添加方法
Random.prototype.getRandom = function (min, max) { // 范围 min ~ max-1
return Math.floor(Math.random() * (max - min) + min);
};
}());
// 产生小方块对象-----------------------------------------
(function () {
// 保存食物的数组
var elements = [];
// 食物的构造函数
function Food(width, height, color) {
this.width = width || 20;
this.height = height || 20;
this.color = color || "green";
this.x = 0; // left属性
this.y = 0; // top属性
this.element = document.createElement("div"); // 食物实例对象
}
// 将Food暴露给window
window.Food = Food;
// 初始化小方块的显示效果及位置
Food.prototype.init = function () {
// 每次在创建小方块之前先删除之前的小方块,保证map中只有一个小方块
remove();
var div = this.element;
map.appendChild(div);
div.style.width = this.width + "px";
div.style.height = this.height + "px";
div.style.backgroundColor = this.color;
div.style.position = "absolute";
this.x = new Random().getRandom(0, map.offsetWidth / this.width) * this.width;
this.y = new Random().getRandom(0, map.offsetHeight / this.height) * this.height;
div.style.left = this.x + "px";
div.style.top = this.y + "px";
// 把div加到数组中
elements.push(div);
};
// 私有函数:删除小方块
function remove() {
for (var i = 0; i < elements.length; i++) {
elements[i].parentElement.removeChild(elements[i]);
elements.splice(i, 1); // 清空数组,从i的位置删除1个元素
}
}
}());
// 产生小蛇对象------------------------------------------------------
(function () {
// 创建数组保存小蛇身体的每个div
var elements = [];
function Snack(width, height, direction) {
// 小蛇每一块的宽高
this.width = width || 20;
this.height = height || 20;
this.direction = direction || "right";
this.beforeDirection = this.direction;
// 小蛇组成身体的每个小方块
this.body = [
{x: 3, y: 2, color: "red"},
{x: 2, y: 2, color: "orange"},
{x: 1, y: 2, color: "orange"}
];
}
// 将Snack暴露给window
window.Snack = Snack;
// 为原型添加小蛇初始化的方法
Snack.prototype.init = function (map) {
// 显示小蛇之前删除小蛇
remove();
// 循环创建小蛇身体div
for (var i = 0; i < this.body.length; i++) {
var div = document.createElement("div");
map.appendChild(div);
div.style.width = this.width + "px";
div.style.height = this.height + "px";
div.style.position = "absolute";
// 移动方向,移动的时候设置
// 坐标位置
var tempObj = this.body[i];
div.style.left = tempObj.x * this.width + "px";
div.style.top = tempObj.y * this.width + "px";
div.style.backgroundColor = tempObj.color;
// 将小蛇添加到数组
elements.push(div);
}
};
// 为原型添加小蛇移动方法
Snack.prototype.move = function (food) {
var index = this.body.length - 1; // 小蛇身体的索引
// 不考虑小蛇头部
for (var i = index; i > 0; i--) { // i>0 而不是 i>=0
this.body[i].x = this.body[i - 1].x;
this.body[i].y = this.body[i - 1].y;
}
// 小蛇头部移动
switch (this.direction) {
case "right" :
// if(this.beforeDirection !== "left") {
this.body[0].x += 1;
// }
break;
case "left" :
this.body[0].x -= 1;
break;
case "up" :
this.body[0].y -= 1;
break;
case "down" :
this.body[0].y += 1;
break;
default:
break;
}
// 小蛇移动的时候,当小蛇偷坐标和食物的坐标相同表示吃到食物
var headX = this.body[0].x * this.width;
var headY = this.body[0].y * this.height;
// 吃到食物,将尾巴复制一份加到小蛇body最后
if ((headX === food.x) && (headY === food.y)) {
var last = this.body[this.body.length - 1];
this.body.push({
x: last.x,
y: last.y,
color: last.color
});
// 删除食物
food.init();
}
};
// 私有函数:删除小蛇
function remove() {
var i = elements.length - 1;
for (; i >= 0; i--) {
elements[i].parentNode.removeChild(elements[i]);
elements.splice(i, 1);
}
}
}());
// 产生游戏对象----------------------------------------------------------
(function () {
var that = null;
function Game(map) {
this.food = new Food(20, 20, "purple");
this.snack = new Snack(20, 20);
this.map = map;
that = this;
}
// 初始化游戏
Game.prototype.init = function () {
this.food.init(this.map);
this.snack.init(this.map);
this.autoRun();
this.changeDirection();
};
// 小蛇自动跑起来
Game.prototype.autoRun = function () {
var timeId = setInterval(function () {
this.snack.move(this.food);
this.snack.init(this.map);
// 判断最大X,Y边界
var maxX = this.map.offsetWidth / this.snack.width;
var maxY = this.map.offsetHeight / this.snack.height;
// X方向边界
if ((this.snack.body[0].x < 0) || (this.snack.body[0].x >= maxX)) {
// 撞墙了
clearInterval(timeId);
alert("Oops, Game Over!");
}
// Y方向边界
if ((this.snack.body[0].y < 0) || (this.snack.body[0].y >= maxY)) {
// 撞墙了
clearInterval(timeId);
alert("Oops, Game Over!");
}
}.bind(that), 150); // 使用bind,那么init方法中所有的this都将被bind的参数that替换
};
// 按下键盘改变小蛇移动方向
Game.prototype.changeDirection = function () {
addAnyEventListener(document, "keydown", function (e) {
// 每次按键之前保存按键方向
this.snack.beforeDirection = this.snack.direction;
switch (e.keyCode) {
case 37: // 左
this.snack.beforeDirection !== "right" ? this.snack.direction = "left" : this.snack.direction = "right";
break;
case 38: // 上
this.snack.beforeDirection !== "down" ? this.snack.direction = "up" : this.snack.direction = "down";
break;
case 39: // 右
this.snack.beforeDirection !== "left" ? this.snack.direction = "right" : this.snack.direction = "left";
break;
case 40: // 下
this.snack.beforeDirection !== "up" ? this.snack.direction = "down" : this.snack.direction = "up";
break;
default:
break;
}
}.bind(that));
};
window.Game = Game;
}());
var game = new Game(map);
game.init();
</script>
</body>
</html> | Daotin/Web/03-JavaScript/04-JavaScript高级知识/案例源码/贪吃蛇/index.html/0 | {
"file_path": "Daotin/Web/03-JavaScript/04-JavaScript高级知识/案例源码/贪吃蛇/index.html",
"repo_id": "Daotin",
"token_count": 5407
} | 14 |
前提:我们在mysql创建了一个数据库: mydb.
mydb 里面有个数据表 mytable。
mytable 中的数据为:
| id | name | age |
| ---- | ------ | ---- |
| 1 | daotin | 18 |
| 2 | lvonve | 19 |
| 3 | li | 20 |
PHP代码连接数据库mydb:
```php
<?php
@header("content-type:text/html;charset=utf8");
mysql_connect("localhost:3306", "root", "root"); // 如果无法链接将会报错,报错信息如下:
// Warning: mysql_connect() [function.mysql-connect]: [2002] 由于目标计算机积极拒绝,无法连接。 (trying to connect via tcp://localhost:33062) in
$connect = mysql_select_db("mydb"); // 选择的数据库存在返回1,否则为空
if($connect) {
echo "数据库存在";
} else {
echo "数据库不存在";
}
$sql = 'select * from mytable'; // 定义查询数据表(mytable)语句
$res = mysql_query($sql); // 执行数据表查询语句,返回值是resouce格式的数据。
// mysql_fetch_array 将resouce格式的数据转化成Array数据类型
// 由于mysql_fetch_array每次只能转换数据表的一行数据,所以要循环转换。
// 使用while是因为没有数据的地方转换的结果为false
// 最后将多个array加入数组list中。
$list = array();
while($item = mysql_fetch_array($res)) {
$list[] = $item;
}
// 使用json_encode将转换的array集合变成json对象集合。
echo json_encode($list);
?>
```
获取到的数据如下:
![](./images/2.png)
我们发现一个问题:就是获取到的有两份相同的数据,这就造成数据的冗余,怎么解决呢?
解决办法:
我们用另一个数组来放入获取到的数组中,我们需要的数据。
```php
$list = array();
while($item = mysql_fetch_array($res)) {
$tmp = array();
$tmp["id"] = $item["id"];
$tmp["name"] = $item["name"];
$tmp["age"] = $item["age"];
$tmp["status"] = $item["status"];
$list[] = $tmp;
}
// 使用json_encode将转换的array集合变成json对象集合。
echo json_encode($list);
```
于是就获取到了我们想要的数据:
![](./images/3.png)
得到数据后,我们就可以通过html代码将其渲染到页面:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
div {
width: 400px;
margin: 50px auto;
}
table {
width: 400px;
border: 1px solid #666;
border-collapse: collapse;
text-align: center;
}
</style>
</head>
<body>
<div>
<table border="1">
<tr>
<th>编号</th>
<th>用户名</th>
<th>年龄</th>
<th>操作</th>
</tr>
<!-- <tr>
<td>1</td>
<td>哈哈</td>
<td>18</td>
<td><a href="javascript:;">删除</a></td>
</tr>
<tr>
<td>2</td>
<td>我的</td>
<td>18</td>
<td><a href="javascript:;">删除</a></td>
</tr> -->
</table>
</div>
</body>
<script>
var table = document.querySelector("table");
var xhr = new XMLHttpRequest();
xhr.open("get", "http://localhost/php/1121/connectDB.php", true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
let list = JSON.parse(xhr.responseText);
list.map(function (item) {
let id = item["id"];
let uname = item["name"];
let age = item["age"];
var tr = document.createElement("tr");
var td_id = document.createElement("td");
var td_name = document.createElement("td");
var td_age = document.createElement("td");
var td_del = document.createElement("td");
var a = document.createElement("a");
a.innerHTML = "删除";
a.href = "javascript:;";
td_id.innerHTML = id;
td_name.innerHTML = uname;
td_age.innerHTML = age;
td_del.appendChild(a);
tr.appendChild(td_id);
tr.appendChild(td_name);
tr.appendChild(td_age);
tr.appendChild(td_del);
table.appendChild(tr);
a.onclick = function () {
//?
};
});
}
};
</script>
</html>
```
![](./images/4.png)
需要注意的是,由于ajax受到同源策略的影响,所以我们的html代码一定和php文件在相同的协议,相同的域名,相同的端口下。
好了,上面的代码还有一个问题,就是我们在点击删除的时候,需要将数据库的对应的数据删除吗?
不需要,一般正常的操作是每个数据都对应一个status,表示是否可以访问,我们以status=1可以访问,status=0不可以访问为例,来实现删除操作。
所以我们数据库的数据现在是下面的样子:
![](./images/5.png)
我们php代码也要修改下:
| Daotin/Web/05-PHP&数据库/04-PHP连接mysql数据库.md/0 | {
"file_path": "Daotin/Web/05-PHP&数据库/04-PHP连接mysql数据库.md",
"repo_id": "Daotin",
"token_count": 3243
} | 15 |
// Stacked Icons
// -------------------------
.@{fa-css-prefix}-stack {
position: relative;
display: inline-block;
width: 2em;
height: 2em;
line-height: 2em;
vertical-align: middle;
}
.@{fa-css-prefix}-stack-1x, .@{fa-css-prefix}-stack-2x {
position: absolute;
left: 0;
width: 100%;
text-align: center;
}
.@{fa-css-prefix}-stack-1x { line-height: inherit; }
.@{fa-css-prefix}-stack-2x { font-size: 2em; }
.@{fa-css-prefix}-inverse { color: @fa-inverse; }
| Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/font-awesome-4.7.0/less/stacked.less/0 | {
"file_path": "Daotin/Web/07-移动Web开发/案例源码/03-微金所/lib/font-awesome-4.7.0/less/stacked.less",
"repo_id": "Daotin",
"token_count": 201
} | 16 |
## 一、let
**作用:与var类似, 用于声明一个变量。**
**let和var的区别:**
- 在块作用域内有效(只要有{}出现 则只在该{}范围内生效)
- 不能重复声明
- 不会预处理, 不存在提升
```html
<script type="text/javascript">
console.log(res); //不会预处理, 不存在提升,报错
// 不能重复声明
let res = 10;
let res = 10; // 报错
</script>
```
**应用:循环遍历加监听**
我们先开看一个例子:
```html
<body>
<button>测试1</button>
<button>测试2</button>
<button>测试3</button>
<script type="text/javascript">
let btns = document.getElementsByTagName('button');
for (var i = 0; i < btns.length; i++) {
btns[i].onclick = function () {
alert(i);
}
}
</script>
</body>
```
我们分别点击按钮的时候,分别打印多少?
结果:打印的都是2。**因为回调函数的写法会进行覆盖操作**。如何解决?
**方法一:使用闭包。**
```js
for (var i = 0; i < btns.length; i++) {
(function(){
btns[i].onclick = function () {
alert(i);
}
})(i);
}
```
这种方式相当于,每个回调函数有个自己的区间,各个区间互不干扰。而 let 正好有这个特性。
**方法二:将 for循环的 var改为let即可。**
## 二、const
作用:定义一个常量。
特点:
- 不能修改
- (常量名从规范上来将 最好所有字母大写)
- 其它特点同let。
```js
const uName = 'Daotin';
```
## 三、变量的解构赋值
理解:从对象或数组中提取数据, 并赋值给变量(多个)。
### 1、对象的解构赋值
之前我们要获取一个对象的属性,会定义变量然后接收对象的属性值。
```js
let obj = {name : 'kobe', age : 39};
let name = obj.name;
let age = obj.age;
console.log(name, age);
```
对象的解构赋值可以这样做:
```js
let {name, age} = obj;
console.log(name, age); // name 就是obj.name,age就是obj.age
```
给对象的解构赋值**起个别名**:
```js
let obj = {name:'daotin', age:18};
let {name:myname, age:myage} = obj; // 给name和age分别起个别名myname和myage
```
**指定默认值**(对于对象不存在的属性,可以添加默认值):
```js
let obj = {name:'daotin', age:18};
let {name,age,sex='man'} = obj; // 给定obj对象一个属性默认值
```
> 注意:
> 1、对象的解构赋值必须使用大括号 {}
>
> 2、大括号里面的变量名必须和obj里面的属性名相同
>
> 3、可以只定义一部分变量接收一部分的obj属性,不需要全部接收。
### 2、数组的解构赋值
数组没有对象的数组名,但是有下标可以使用。所以这里的变量名可以随便起。
```js
let arr = ['abc', 23, true];
let [a, b, c] = arr;
console.log(a, b, c);
```
> 注意:
>
> 1、数组的解构赋值必须使用中括号 [],并且对顺序有要求。
>
> 2、可以给定默认值
**如果只想取其中的某几个值,那么变量可以使用逗号隔开。**
`let [,,a,,] = arr;`
**如果定义的变量个数比数组的个数多,多出来的变量的值为** `undefined`。
## 四、模板字符串
作用:简化字符串的拼接。
注意:
1、模板字符串必须用 ``` ` 包含;
2、变化的部分使用`${xxx}`定义
```js
let obj = {
name: 'anverson',
age: 41
};
// 我们之前拼接字符串用的是+
console.log('我叫:' + obj.name + ', 我的年龄是:' + obj.age);
// 使用模板字符串的方式
console.log(`我叫:${obj.name}, 我的年龄是:${obj.age}`);
```
## 五、对象的简化写法
如果有变量和对象的属性名称相同,之前的写法是赋值操作:
```js
let a = 1;
let b = 2;
let Obj = {
a: a,
b: b,
};
```
现在,如果变量和对象的属性名称相同,可以简写如下:
```js
let a = 1;
let b = 2;
let Obj = {
a,
b,
};
```
对于对象的属性,如果是个函数的话,也可以简写:
之前的写法为:
```js
let Obj = {
foo: function(){
//...
}
};
```
现在的写法为:(去掉冒号和function)
```js
let Obj = {
foo(){
//...
}
};
```
## 六、箭头函数
作用:**箭头函数的作用主要是定义匿名函数。**
有下面几种情况的匿名函数都可以使用箭头函数:
```js
let foo = function () {};
// 转换成箭头函数
let foo = () => {};
//------------------------------
let Obj = {
foo: function () { }
}
// 转换成箭头函数
let Obj = {
foo: () => { }
}
```
基本语法**(参数)**:
1、匿名函数没有参数:() 不能省略,占位作用。`let foo = () => {};`
2、只有一个参数:() 可以省略,也可以不省略。`let foo = a => {};`
3、多个参数,() 不能省略。`let foo = (a,b) => {};`
基本语法**(函数体)**:
1、函数体只有一条语句:可以省略{},并且默认返回结果(不需要 return)。
```js
let foo = (x, y) => x + y;
console.log(foo(1, 2));
```
2、函数体如果有多个语句, 需要用{}包围,若有需要返回的内容,需要添加return。
```js
let foo = (x, y) => {
console.log(x, y);
return x + y;
};
console.log(foo(1, 2));
```
**箭头函数的特点:**
1、不能做构造函数(不能实例化)
2、没有 arguments
**3、箭头函数没有自己的this,箭头函数的this不是调用的时候决定的,this指向上下文环境。(意思:箭头函数的外层的是否有函数,如果有,箭头函数的this就是外层函数的this,如果没有,则为 window)**
> 简单方法:箭头函数,this就往外挪一层,外面如果还是箭头函数,继续往外挪,直到没有箭头函数的地方就是当前this的指向。
```html
<script type="text/javascript">
let foo = () => {
console.log(this);
};
foo(); // window 对象
let Obj1 = {
bar() {
let foo = () => {
console.log(this);
};
foo();
}
};
Obj1.bar(); // Obj1 对象,箭头函数外层有函数bar,bar里面的this是Obj1.
let Obj2 = {
bar: () => {
let foo = () => {
console.log(this);
};
foo();
}
};
Obj2.bar(); // window 对象,箭头函数外层有函数bar,bar函数也是箭头函数,bar的外层没有函数,所以bar里面的this是window,所以foo里面的this也是window。
</script>
```
## 七、展开符/三点运算符
**作用:**
**1、用来取代 arguments 但比 arguments 灵活,**
arguments 是个伪数组,但是三点运算符是**真数组**,可以使用 forEach 等方法。
![](./images/9.png)
2、三点(可变参数)运算符只能是**最后部分形参参数。** 但是前面是可以有参数来占位的。
![](./images/11.png)
**3、扩展运算符**
```js
let arr = [1, 6];
let arr1 = [2, 3, 4, 5];
arr = [1, ...arr1, 6];
console.log(arr); // [1,2,3,4,5,6]
console.log(...arr); // 1 2 3 4 5 6
```
语法:`...数组名` :表示遍历数组的所有元素。
## 八、形参默认值
作用:当不传入参数的时候默认使用形参里的默认值。
```html
<script type="text/javascript">
//定义一个点的坐标
function Point(x = 12, y = 12) { // 形参的默认值
this.x = x;
this.y = y;
}
let p = new Point();
console.log(p);
let point = new Point(25, 36);
console.log(point);
</script>
```
| Daotin/Web/08-ES6语法/03-let,const,解构赋值,模板字符串,对象简化,箭头函数,三点运算符,形参默认值.md/0 | {
"file_path": "Daotin/Web/08-ES6语法/03-let,const,解构赋值,模板字符串,对象简化,箭头函数,三点运算符,形参默认值.md",
"repo_id": "Daotin",
"token_count": 4733
} | 17 |
## async模块介绍
*Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Although originally designed for use with Node.js and installable via npm install --save async, it can also be used directly in the browser.*
async是一个实用的模块,对于处理异步javascript来说,它可以提供简介强大的功能。虽然最初设计的时候视为Nodejs设计的,可以通过`npm install --save async` 来引入async模块,但是现在它也可以被直接用在浏览器中,也就是前端js代码中。
## async三个模式
async的异步流程管理主要分为三个模式:
- 并行无关联
- 串行无关联
- 串行有关联
### 并行无关联 parallel
```js
const async = require("async");
/**
* 并行无关联
* 语法:async.parallel([],(err,data)=>{})
* 参数1:可以是个对象或者数组
* 如果是数组:内容为一系列匿名函数集合,匿名函数的参数为一个回调函数
* 如果是对象:内容为一系列属性值为匿名函数组成,匿名函数的参数为一个回调函数
*
* 回调函数的第一个参数:并行任务执行失败的错误信息
* 第二个参数:处理的数据
*
* async.parallel 第二个参数中的data是所有并行任务执行完成后,汇聚成的集合
*/
console.time("time");
// 参数为数组
async.parallel([
(cb) => {
setTimeout(() => {
cb(null, "daotin");
}, 2000);
},
(cb) => {
setTimeout(() => {
cb(null, "lvonve");
}, 1000);
}
], (err, data) => {
if (!err) {
console.timeEnd("time"); // time: 2001.771ms
console.log(data); // ['daotin', 'lvonve']
}
});
// 参数为对象
// 最后获取到的data也是对象,属性名就是前面的属性名。
console.time("time");
async.parallel({
one(cb) {
setTimeout(() => {
cb(null, "123");
}, 2000);
},
two(cb) {
setTimeout(() => {
cb(null, "123");
}, 2000);
}
}, (err, data) => {
console.timeEnd("time"); // time: 2004.775ms
if (!err) {
console.log(data); //{ one: '123', two: '123' }
}
});
```
### 串行无关联 series
```js
console.time("time");
console.time("time1");
async.series({
one(cb) {
setTimeout(() => {
cb(null, "123");
}, 2000);
},
two(cb) {
console.timeEnd("time1"); //time1: 2004.965ms
setTimeout(() => {
cb(null, "456");
}, 1000);
}
}, (err, data) => {
console.timeEnd("time"); // time: 3010.950ms
if (!err) {
console.log(data); //{ one: '123', two: '456' }
}
});
```
可以看到,除了关键词`series`变了之外,格式都一样,只不过已是串行了。
### 串行有关联 waterfall
> 注意:串行有关联的第一个参数必须是数组,不能是对象
>
> 数组中第一个任务的回调函数cb的第二个参数开始是传给下一个任务的实参。
>
> 第二个任务函数形参前几个就是上一个传下来的实参,这里是name形参对应‘daotin’实参。
```js
console.time("time");
console.time("time1");
async.waterfall([
cb => {
setTimeout(() => {
cb(null, 'daotin');
}, 2000);
},
(name, cb) => {
console.timeEnd('time1'); // time1: 2004.008ms
setTimeout(() => {
cb(null, 'lvonve-' + name);
}, 1000);
}
], (err, data) => {
console.timeEnd("time"); // time: 3008.387ms
if (!err) {
console.log(data); //lvonve-daotin
}
});
```
| Daotin/Web/10-Node.js/06-扩展async.md/0 | {
"file_path": "Daotin/Web/10-Node.js/06-扩展async.md",
"repo_id": "Daotin",
"token_count": 2056
} | 18 |
## 一、flux架构
什么是flux?
简单说,Flux 是一种架构思想,专门解决软件的结构问题。
一般**中大型react项目**会用到 Flux,便于管理数据模型。小型项目就没必要使用了。
### 1、基本概念
首先,Flux将一个应用分成四个部分。
- **View**: 视图层
- **Action**(动作):视图层发出的消息,用来修改数据模型(比如mouseClick)
- **Dispatcher**(派发器):用来接收Actions、执行回调函数
- **Store**(数据层):用来存放应用的状态,一旦发生变动,就提醒Views要更新页面
![](./img/3.png)
> Flux 的最大特点,就是数据的"单向流动"。
>
>
>
> 1. 用户访问 View,(同时将View中视图更新的函数赋值给Store的监听函数subscribe)
> 2. View 发出用户的 Action
> 3. Dispatcher 收到 Action,要求 Store 进行相应的更新
> 4. Store 更新后,(触发Store的subscribe函数来更新View视图)
### 2、示例
效果:创建List组件显示列表,点击添加按钮添加数据,点击删除按钮删除最后一个数据。
#### 2.1、创建store,保存数据模型
```jsx
export let store = {
state: {
list: [
{ name: '商品1' },
{ name: '商品2' },
{ name: '商品3' },
{ name: '商品4' },
]
},
}
```
#### 2.2、创建action
点击按钮的时候时候创建。
创建的时候添加`type`属性是为了分辨之后该如何操作store。
```jsx
// List.js
import { store } from './store'
import dispatcher from './dispatcher'
export class List extends React.Component {
constructor() {
super();
// List加载的时候,通过store.getList()函数获取store的数据
this.state = store.getList();
this.add = this.add.bind(this);
this.del = this.del.bind(this);
}
add() {
// 创建action
let action = {
type: 'ADD_ITEM',
name: '新的商品'
}
}
del() {
// 创建action
let action = {
type: 'DEL_ITEM'
}
}
render() {
let domList = this.state.list.map((item, i) => {
return (
<li key={i}>
{item.name}
</li>
);
})
return (
<div>
<button onClick={this.add}>添加</button>
<button onClick={this.del}>删除</button>
<ul>
{domList}
</ul>
</div>
)
}
}
```
> store的数据获取也不能直接操作,而是需要store自己提供自定义方法才可以。
#### 2.3、创建dispatcher
```jsx
// dispatcher.js
import flux from "flux";
import { store } from "./store";
let Dispatcher = flux.Dispatcher;
let dispatcher = new Dispatcher();
dispatcher.register(action => {
// 参数action即是获取到action的值
console.log(action);
})
export default dispatcher;
```
为了能获取到action,所以在创建action之后,还要发送给dispatcher:
```js
import dispatcher from './dispatcher'
add() {
let action = {
type: 'ADD_ITEM',
name: '新的商品'
}
dispatcher.dispatch(action);
}
del() {
let action = {
type: 'DEL_ITEM'
}
dispatcher.dispatch(action);
}
```
#### 2.4、更新store
dispatcher获取到action后需要更新store。也需要调用store提供的自定义方法。
```jsx
// store.js
export let store = {
state: {
list: [
{ name: '商品1' },
{ name: '商品2' },
{ name: '商品3' },
{ name: '商品4' },
]
},
getList() {
return this.state;
},
// 自定义操作store方法
addList(name) {
this.state.list.push({ name });
},
delList(name) {
this.state.list.pop();
},
}
```
```jsx
// dispatcher.js
import flux from "flux";
import { store } from "./store";
let Dispatcher = flux.Dispatcher;
let dispatcher = new Dispatcher();
dispatcher.register(action => {
// 根据type来操作不同的store方法
switch (action.type) {
case 'ADD_ITEM':
store.addList(action.name);
break;
case 'DEL_ITEM':
store.delList();
break;
default:
break;
}
})
export default dispatcher;
```
#### 2.5、更新view
此时store已经更新,但是view没有更新,如何更新view?
> 在store定义一个变量bindUpdate,用来调用view的更新方法。在List加载时就把bindUpdate赋值为view的更新方法,只要store的数据一更新,就调用这个方法来更新视图。
```jsx
export let store = {
state: {
list: [
{ name: '商品1' },
{ name: '商品2' },
{ name: '商品3' },
{ name: '商品4' },
]
},
// 定义更新view变量
bindUpdate: null,
getList() {
return this.state;
},
addList(name) {
// 更新store
this.state.list.push({ name });
// 执行更新view
this.bindUpdate();
},
delList(name) {
// 更新store
this.state.list.pop();
// 执行更新view
this.bindUpdate();
},
}
```
```jsx
import { store } from './store'
import dispatcher from './dispatcher'
export class List extends React.Component {
constructor() {
super();
this.state = store.getList();
this.add = this.add.bind(this);
this.del = this.del.bind(this);
}
componentDidMount = () => {
// List加载完成后将bindUpdate赋值为更新方法
store.bindUpdate = this.updateView.bind(this);
}
add() {
let action = {
type: 'ADD_ITEM',
name: '新的商品'
}
dispatcher.dispatch(action);
}
del() {
let action = {
type: 'DEL_ITEM'
}
dispatcher.dispatch(action);
}
// 更新方法,获取store.state的最新数据进行更新
updateView() {
this.setState(store.state)
}
render() {
let domList = this.state.list.map((item, i) => {
return (
<li key={i}>
{item.name}
</li>
);
})
return (
<div>
<button onClick={this.add}>添加</button>
<button onClick={this.del}>删除</button>
<ul>
{domList}
</ul>
</div>
)
}
}
```
于是乎,整个单向流动循环完成。
##### 优化view更新
之前view的更新是通过将List的一个更新方法赋值给store的一个变量,但是有个问题是,如果有很多个组件的话,就由很多个store,就需要很多个变量,那就太麻烦了,其名称头都起大了。
所以,我们可以通过node自带的event对象来做观察者模式。
```jsx
let EventEmitter = require('events').EventEmitter;
let event = new EventEmitter();
export let store = {
state: {
list: [
{ name: '商品1' },
{ name: '商品2' },
{ name: '商品3' },
{ name: '商品4' },
]
},
getList() {
return this.state;
},
addList(name) {
this.state.list.push({ name });
// 每次数据模型有变更,触发update事件
event.emit('update');
},
delList(name) {
this.state.list.pop();
// 每次数据模型有变更,触发update事件
event.emit('update');
},
bindUpdate(cb) {
// 监听update事件
event.on('update', cb);
},
unBindUpdate(cb) {
this.removeListener('update', cb);
}
}
```
在List里面加载完成后进行绑定`bindUpdate`函数:
卸载的时候绑定`unBindUpdate`函数:
```js
componentDidMount = () => {
store.bindUpdate(this.updateView.bind(this));
}
componentWillUnmount() {
store.unBindUpdate(this.updateView.bind(this));
}
```
这时候不管有多少个组件,都可以使用bindUpdate和unBindUpdate进行视图更新。
##### 继续优化
我们使用event的时候,new了一个对象,可是就只用到了on和emit方法,太浪费内存了。
我们发现event对象中其实没有on和emit方法,这些方法都是EventEmitter原型对象中的,那么我们直接把EventEmitter原型对象拿过来就好了。
```jsx
let EventEmitter = require('events').EventEmitter;
export let store = {
state: {
list: [
{ name: '商品1' },
{ name: '商品2' },
{ name: '商品3' },
{ name: '商品4' },
]
},
// 把EventEmitter.prototype全部copy过来,就不需要new了。
...EventEmitter.prototype,
getList() {
return this.state;
},
addList(name) {
this.state.list.push({ name });
// 执行更新
// this.bindUpdate();
this.emit('update');
},
delList(name) {
this.state.list.pop();
// 执行更新
this.emit('update');
},
bindUpdate(cb) {
this.on('update', cb);
}
}
```
调用的时候,直接使用this.on和this.emit就可以了。
##### 优化store和view更新
之前store的更新方式是在dispatcher中调用store的更新各个更新方法进行更新,如果方法很多的话,就要写很多方法比较麻烦。并且每个方法中都需要emit更新视图。
![](./img/4.png)
![](./img/5.png)
所以我们在store中增加一个类似react的setState方法,一次性更改所有store的state。
![](./img/6.png)
![](./img/7.png)
#### 2.6、视图分层
我们之前List组件视图的显示和逻辑处理代码是写在一起的,视图分层就是把他们分开。
分开后分为`容器组件`和`UI组件`
UI组件复负责视图显示;
容器组件包裹UI,并负责逻辑处理。
现在将List分层:
容器组件为:`ListController.js`
UI组件为:`List.js`
```js
// List.js
export class List extends React.Component {
constructor() {
super();
}
render() {
let domList = this.props.list.map((item, i) => {
return (
<li key={i}>
{item.name}
</li>
);
})
return (
<div>
<button onClick={this.props.add}>添加</button>
<button onClick={this.props.del}>删除</button>
<ul>
{domList}
</ul>
</div>
)
}
}
```
```jsx
//ListController.js
import { store } from '../store'
import dispatcher from '../dispatcher'
import { List } from './List'
export class ListController extends React.Component {
constructor() {
super();
this.state = store.getState();
this.add = this.add.bind(this);
this.del = this.del.bind(this);
}
componentDidMount = () => {
store.bindUpdate(this.updateView.bind(this));
}
componentWillUnmount() {
store.unBindUpdate(this.updateView.bind(this));
}
add() {
let action = {
type: 'ADD_ITEM',
name: '新的商品'
}
dispatcher.dispatch(action);
}
del() {
let action = {
type: 'DEL_ITEM'
}
dispatcher.dispatch(action);
}
updateView() {
this.setState(store.state)
}
render() {
// 调用List UI组件
return <List list={this.state.list} add={this.add} del={this.del} />
}
}
```
### 3、flux项目思路
1、将视图部分的页面组件拆分成容器组件和UI组件
容器组件可继承 封装好的 Controller 以自动实现绑定更新视图方法及卸载组件时自动解绑,避免所有容器组件写相同的代码。
(其中差异部分各个组件的store通过构造函数的第二个参数传入。)
```jsx
export class Controller extends React.Component {
constructor(props, store) {
super(props);
this.store = store;
this.state = this.store.getState();
this.store.subscribe(this.updateView.bind(this));
}
updateView() {
this.setState(this.store.getState());
}
componentWillUnmount() {
this.store.unBindUpdate(this.updateView.bind(this));
}
}
```
> Controller 之所以继承 React.Component是因为容器组件需要,但是又不能同时继承Controller和React.Component,所以采取这种嵌套继承的方式。
UI组件所有数据(点击等各种事件所调用的函数)均来自于props(由容器组件传入)
类似以下方式:
```jsx
render() {
return <Home {...this.state} />
}
```
`<Home />` 即是UI组件。
this.state 哪里来呢?
来自对应的store:this.state = HomeStore.getState();
store的state来自哪里呢?
来自页面加载时ajax请求,请求到数据写入store。
既然要操作store,那么就要通过action->dispatcher->store->view的顺序来。
2、创建action工厂函数
- 定义一个初始化 的action工厂函数
- 请求需要的数据
- 将拿到的数据封装到 action中
- 将action发送到dispatcher (通过.dispatch()方法)
3、在派发器dispatcher中配置对应的case
并且从action中拿到数据后,设置到对应store中即可
通过各自组件的类似`HomeStore.setState(action);`方式进行设置。
store的state更新了,注意需要在容器组件加载完成后绑定视图更新方法,视图更新方法就是组件获取最新store的state数据。
4、在容器组件的加载完成的生命周期函数中,调用上述步骤封装好的action工厂函数(也就是打开页面的时候进行ajax请求)
5、路由部分引入的组件 注意需要切换成容器组件。
## 简易flux项目
链接:https://github.com/Daotin/daotin.github.io/issues/132#issue-602918224
| Daotin/Web/13-React/05-Flux架构.md/0 | {
"file_path": "Daotin/Web/13-React/05-Flux架构.md",
"repo_id": "Daotin",
"token_count": 8268
} | 19 |
## 一、接口
js中类的接口定义:
```typescript
interface Human {
run();
eat();
}
```
> 接口的方法没有方法体。
>
> 实现接口的类,必须实现接口中的所有方法。
## 二、依赖注入(服务)
依赖注入就是自己创建一个服务(服务的本质就是一个类),然后在使用类的时候,不需要自己new类的实例,只需要按照特定的方式注入,类的实例就会被自动创建,然后直接使用即可。
### 1、创建服务
```js
ng g service services/DIYMath // ng g s services/DIYMath
```
创建的时候会有个警告`WARNING Service is generated but not provided, it must be provided to be used` 未引入服务,后面注意引入。
### 2、实现服务逻辑代码
```typescript
import { Injectable } from '@angular/core';
// 服务装饰器
// 作用:此服务可以再调用别的服务
@Injectable()
export class DIYMathService {
// 如果调用别的服务
constructor(private xxx:newDIYMath) { }
// 加
add(a: number, b: number): number {
return a * 1 + b * 1;
}
// 减
reduce(a: number, b: number): number {
return a * 1 - b * 1;
}
}
```
### 3、在主模块中注入服务
```typescript
// app.module.ts
providers: [DIYMathService],
```
> 如果未在主模块中注入服务的话,会报`DI Error` 错误。
### 4、在组件中使用服务
```typescript
// a.component.ts
import { DIYMathService } from 'app/services/diymath.service';
export class AComponent implements OnInit {
constructor(
// 使用DIYMathService服务
private dm: DIYMathService
) { }
a: number = 0;
b: number = 0;
alg: string = '+';
result: number = 0;
opt() {
this.result = this.dm[this.alg](this.a, this.b);
}
ngOnInit() {
}
}
```
```html
<!-- a.component.html -->
<div>
<input type="text" [(ngModel)]="a">
<select (change)="opt()" [(ngModel)]="alg">
<option value="add">+</option>
<option value="reduce">-</option>
</select>
<input type="text" [(ngModel)]="b">
= <span>{{result}}</span>
</div>
```
### 5、Tips
如果此时我们的项目有很多地方使用了DIYMathService服务,但是我们又创建了一个新的服务NewDIYMathService,它比DIYMathService要好,所以我们像将项目中所有的DIYMathService替换成NewDIYMathService,怎么替换?一个个手改?
不需要,只需要在注入主模块的时候,**挂羊头卖狗肉**即可:
```
将
providers: [DIYMathService],
改为:
providers: [{ provide: DIYMathService, useClass: NewDIYMathService }],
```
> 其实`providers: [DIYMathService]`
>
> 就相当于`providers: [{ provide: DIYMathService, useClass: DIYMathService}]`
> 注意:如果挂羊头卖狗肉,那么在狗肉的服务里面不能引入羊头服务,否则报错!
也就是下面的写法报错:
```typescript
import { Injectable } from '@angular/core';
import { DIYMathService } from './diymath.service';
@Injectable()
// 狗肉
export class NewDIYMathService {
// 引入羊头
constructor(public dm: DIYMathService) { }
// ...
}
```
![](./img/8.png)
## 三、http代理
由于angular没有使用webpack,所以http代理的配置和之前的不同。
如何设置http代理?
1、新建http代理文件(⚠ **文件存放在项目根目录下**)
```json
// proxy.config.json
{
"/zhuiszhu": {
"target": "http://www.projectlog.top:3000"
}
}
```
2、添加到项目启动中
```json
// package.json
"scripts": {
"start": "ng serve --proxy-config proxy.config.json",
},
```
> 💡 记得要重启服务哦!
3、发起http请求
angular有内置的http请求服务,只需要注入即可使用。
```js
import { Http } from '@angular/http';
export class HomeComponent implements OnInit {
// 注入使用Http服务
constructor(private http: Http) { }
ngOnInit() {
// 发起ajax请求
this.http.get('/zhuiszhu/goods/getList').subscribe(res => {
// res.json()可以获取的想要的数据
console.log(res.json());
})
}
}
```
| Daotin/Web/14-Angular/04-接口,依赖注入,http代理.md/0 | {
"file_path": "Daotin/Web/14-Angular/04-接口,依赖注入,http代理.md",
"repo_id": "Daotin",
"token_count": 2171
} | 20 |
Manifest-Version: 1.0
Class-Path:
| Humsen/web/web-core/src/META-INF/MANIFEST.MF/0 | {
"file_path": "Humsen/web/web-core/src/META-INF/MANIFEST.MF",
"repo_id": "Humsen",
"token_count": 15
} | 21 |
package pers.husen.web.common.constants;
/**
* 数据库字段常量
*
* @author 何明胜
*
* 2017年11月8日
*/
public class DbConstans {
/** 数据库字段有效状态 */
public static final int FIELD_VALID_FLAG = 0;
/** 数据库字段删除状态 */
public static final int FIELD_DELETED_FLAG = 1;
} | Humsen/web/web-core/src/pers/husen/web/common/constants/DbConstans.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/common/constants/DbConstans.java",
"repo_id": "Humsen",
"token_count": 159
} | 22 |
/**
* 通用助手
*
* @author 何明胜
*
* 2017年10月21日
*/
package pers.husen.web.common.helper; | Humsen/web/web-core/src/pers/husen/web/common/helper/package-info.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/common/helper/package-info.java",
"repo_id": "Humsen",
"token_count": 54
} | 23 |
package pers.husen.web.dao;
/**
* @author 何明胜
*
* 2017年9月30日
*/
public interface VisitTotalDao {
/**
* 查询所有访问量
* @return
*/
public int queryVisitTotal();
/**
* 查询当日访问量
* @return
*/
public int queryVisitToday();
/**
* 更新当日访问量和总访问量
*
* @param visitDate
* @return
*/
public int updateVisitCount();
}
| Humsen/web/web-core/src/pers/husen/web/dao/VisitTotalDao.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/dao/VisitTotalDao.java",
"repo_id": "Humsen",
"token_count": 192
} | 24 |
package pers.husen.web.dbutil.mappingdb;
/**
* @author 何明胜
* @desc 文章分类数据库映射
* @created 2017年12月12日 上午10:14:34
*/
public class ArticleCategoryMapping {
/**
* 数据库名称
*/
public static final String DB_NAME = "article_category";
public static final String CATEGORY_ID = "category_id";
public static final String CATEGORY_NAME = "category_name";
public static final String CREATE_DATE = "create_date";
public static final String CATEGORY_DELETE = "category_delete";
} | Humsen/web/web-core/src/pers/husen/web/dbutil/mappingdb/ArticleCategoryMapping.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/dbutil/mappingdb/ArticleCategoryMapping.java",
"repo_id": "Humsen",
"token_count": 217
} | 25 |
package pers.husen.web.service;
import java.util.ArrayList;
import pers.husen.web.bean.vo.MessageAreaVo;
import pers.husen.web.dao.MessageAreaDao;
import pers.husen.web.dao.impl.MessageAreaDaoImpl;
/**
* @author 何明胜
*
* 2017年9月25日
*/
public class MessageAreaSvc implements MessageAreaDao{
private static final MessageAreaDaoImpl messageAreaDaoImpl = new MessageAreaDaoImpl();
@Override
public ArrayList<MessageAreaVo> queryAllMessageArea(int messageId) {
return messageAreaDaoImpl.queryAllMessageArea(messageId);
}
@Override
public int insertMessageNew(MessageAreaVo mVo) {
return messageAreaDaoImpl.insertMessageNew(mVo);
}
}
| Humsen/web/web-core/src/pers/husen/web/service/MessageAreaSvc.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/service/MessageAreaSvc.java",
"repo_id": "Humsen",
"token_count": 231
} | 26 |
package pers.husen.web.servlet.image;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import pers.husen.web.common.handler.ImageDownloadHandler;
/**
* 图片下载
*
* @author 何明胜
*
* 2017年10月20日
*/
@WebServlet(urlPatterns= {"/imageDownload.hms", "/imageDownload"})
public class ImageDownloadSvt extends HttpServlet {
private static final long serialVersionUID = 1L;
public ImageDownloadSvt() {
super();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ImageDownloadHandler iHandler = new ImageDownloadHandler();
iHandler.imageDownloadHandler(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
} | Humsen/web/web-core/src/pers/husen/web/servlet/image/ImageDownloadSvt.java/0 | {
"file_path": "Humsen/web/web-core/src/pers/husen/web/servlet/image/ImageDownloadSvt.java",
"repo_id": "Humsen",
"token_count": 357
} | 27 |
# web
个人网站项目,包括博客、代码库、文件下载、留言、登录注册等功能
网址:www.hemingsheng.cn
------------
## 主要文件结构如下
- `WebContent` -> 前端源文件 (前端三方插件在`/WebContent/plugins`下)
- `config` -> 配置文件
- `docs` -> 说明文档
- `libs` -> 后端jar包
- `src` -> 后端源文件
------------
### web工程目录结构如下:
web:
│ .classpath
│ .gitattributes
│ .gitignore
│ .project
│ README.md
│
├─config
│ db_connect_info.properties
│ log4j2.xml
│
├─docs
│ web后端命名规范.txt
│ web项目前端命名规范.txt
│ 网站logo图片.png
│
├─libs
│ ├─file
│ │ commons-fileupload-1.3.3.jar
│ │ commons-io-2.5.jar
│ │
│ ├─javamail
│ │ javax.mail.jar
│ │
│ ├─json
│ │ commons-beanutils-1.7.0.jar
│ │ commons-collections-3.1.jar
│ │ commons-lang-2.5.jar
│ │ commons-logging.jar
│ │ ezmorph-1.0.3.jar
│ │ json-lib-2.4-jdk15.jar
│ │
│ ├─log4j
│ │ log4j-api-2.8.2.jar
│ │ log4j-core-2.8.2.jar
│ │
│ ├─psql
│ │ postgresql-42.1.4.jar
│ │
│ └─servlet
│ servlet-api.jar
│
├─src
│ │ rebel.xml
│ │
│ └─pers
│ └─husen
│ └─web
│ │ package-info.java
│ │
│ ├─bean
│ │ │ package-info.java
│ │ │
│ │ ├─po
│ │ │ AccessAtatisticsPo.java
│ │ │ ImageUploadPo.java
│ │ │ package-info.java
│ │ │
│ │ └─vo
│ │ BlogArticleVo.java
│ │ CodeLibraryVo.java
│ │ FileDownloadVo.java
│ │ ImageUploadVo.java
│ │ MessageAreaVo.java
│ │ package-info.java
│ │ ReleaseFeatureVo.java
│ │ UserInfoVo.java
│ │ VisitTotalVo.java
│ │
│ ├─common
│ │ │ package-info.java
│ │ │
│ │ ├─constants
│ │ │ BootstrapConstans.java
│ │ │ CommonConstants.java
│ │ │ package-info.java
│ │ │
│ │ ├─handler
│ │ │ FileDownloadHandler.java
│ │ │ FileUploadHandler.java
│ │ │ ImageDownloadHandler.java
│ │ │ ImageUploadHandler.java
│ │ │ package-info.java
│ │ │
│ │ ├─helper
│ │ │ DateFormatHelper.java
│ │ │ package-info.java
│ │ │ RandomCodeHelper.java
│ │ │ SendEmailHelper.java
│ │ │ StackTrace2Str.java
│ │ │ TypeConvertHelper.java
│ │ │
│ │ └─template
│ │ └─html
│ │ BlogTemplate.java
│ │ CodeTemplate.java
│ │ GenericTemplate.java
│ │
│ ├─config
│ │ DeployPathConfig.java
│ │ Log4j2Config.java
│ │ package-info.java
│ │
│ ├─dao
│ │ │ BlogArticleDao.java
│ │ │ CodeLibraryDao.java
│ │ │ FileDownloadDao.java
│ │ │ ImageUploadDao.java
│ │ │ MessageAreaDao.java
│ │ │ ReleaseFeatureDao.java
│ │ │ UserInfoDao.java
│ │ │ VisitTotalDao.java
│ │ │
│ │ └─impl
│ │ BlogArticleDaoImpl.java
│ │ CodeLibraryDaoImpl.java
│ │ FileDownloadDaoImpl.java
│ │ ImageUploadDaoImpl.java
│ │ MessageAreaDaoImpl.java
│ │ ReleaseFeatureDaoImpl.java
│ │ UserInfoDaoImpl.java
│ │ VisitTotalDaoImpl.java
│ │
│ ├─dbutil
│ │ │ DbDeleteUtils.java
│ │ │ DbInsertUtils.java
│ │ │ DbQueryUtils.java
│ │ │ DbUpdateUtils.java
│ │ │
│ │ ├─assist
│ │ │ AssistUtils.java
│ │ │ DbConnectUtils.java
│ │ │ package-info.java
│ │ │ SetPsParamUtils.java
│ │ │ TypeTransformUtils.java
│ │ │
│ │ └─mappingdb
│ │ BlogDetailsMapping.java
│ │ CodeLibraryMapping.java
│ │ FileDownloadMapping.java
│ │ ImageUploadMapping.java
│ │ MessageAreaMapping.java
│ │ package-info.java
│ │ ReleaseFeatureMapping.java
│ │ UserInfoMapping.java
│ │ VisitTotalMapping.java
│ │
│ ├─listener
│ │ OnlineCountListener.java
│ │ package-info.java
│ │ WebInitConfigListener.java
│ │
│ ├─service
│ │ BlogArticleSvc.java
│ │ CodeLibrarySvc.java
│ │ FileDownloadSvc.java
│ │ ImageUploadSvc.java
│ │ MessageAreaSvc.java
│ │ ReleaseFeatureSvc.java
│ │ UserInfoSvc.java
│ │ VisitTotalSvc.java
│ │
│ └─servlet
│ │ package-info.java
│ │
│ ├─blog
│ │ BlogArticlePerPageServlet.java
│ │ BlogArticleServlet.java
│ │ BlogPerByIdServlet.java
│ │ BlogTotalCountServlet.java
│ │ NewBlogUploadServlet.java
│ │
│ ├─codelib
│ │ CodeLibPerPageServlet.java
│ │ CodeLibraryServlet.java
│ │ CodeLibTotalCountServlet.java
│ │ CodePerByIdServlet.java
│ │ NewCodeUploadServlet.java
│ │
│ ├─common
│ │ AccessAtatisticsServlet.java
│ │
│ ├─contact
│ │ SendEmailServlet.java
│ │
│ ├─download
│ │ FileDownloadServlet.java
│ │ FileDownPerPageServlet.java
│ │ FileDownTotalCountServlet.java
│ │ FileUploadServlet.java
│ │
│ ├─image
│ │ ImageDownloadServlet.java
│ │ ImageUploadServlet.java
│ │ package-info.java
│ │
│ ├─message
│ │ MessageGetServlet.java
│ │ MessageUploadServlet.java
│ │
│ ├─releasefea
│ │ LatestReleaseFeatureServlet.java
│ │ NewReleaseFeatureServlet.java
│ │
│ └─userinfo
│ UserInfoModifyServlet.java
│ UserInfoQueryServlet.java
│ UserInfoRegisterServlet.java
│ UserLoginValidateServlet.java
│
└─WebContent
│ index.jsp
│
├─css
│ ├─article
│ │ article.css
│ │
│ ├─contact
│ │ contact.css
│ │
│ ├─download
│ │ download.css
│ │
│ ├─error
│ │ error.css
│ │
│ ├─index
│ │ article-profile.css
│ │ index.css
│ │ version-feature.css
│ │
│ ├─login
│ │ email-check.css
│ │ login.css
│ │ retrive-pwd.css
│ │
│ ├─message
│ │ message.css
│ │ pager.css
│ │
│ ├─navigation
│ │ left-menu-bar.css
│ │ rightbar.css
│ │ topbar.css
│ │
│ ├─personal_center
│ │ modify-email.css
│ │ modify-pwd.css
│ │ modify-userinfo.css
│ │ mycenter.css
│ │
│ └─upload
│ editor-article.css
│
├─error
│ error.jsp
│
├─images
│ │ favicon.ico
│ │ mainbg.png
│ │
│ ├─background
│ │ bg-1.jpg
│ │ bg-2.jpg
│ │ bg-3.jpg
│ │ bg-4.jpg
│ │
│ └─message
│ head-0.jpg
│ head-1.jpg
│ head-2.jpg
│ head-3.jpg
│ head-4.jpg
│ head-5.jpg
│ head-6.jpg
│ head-7.jpg
│ head-8.jpg
│
├─js
│ │ customize-sdk.js
│ │ is-pc-or-mobile.js
│ │ pagination.js
│ │
│ ├─article
│ │ article-markdown.js
│ │ blog.js
│ │ code-library.js
│ │
│ ├─contact
│ │ contact.js
│ │
│ ├─download
│ │ download.js
│ │
│ ├─editor
│ │ editor.js
│ │
│ ├─index
│ │ latestblog.js
│ │ latestcode.js
│ │ version-feature.js
│ │
│ ├─login
│ │ formvalidator.js
│ │
│ ├─message
│ │ message.js
│ │ pager.js
│ │
│ ├─navigation
│ │ left-menu-bar.js
│ │ topbar.js
│ │
│ └─personal_center
│ modify-email.js
│ modify-pwd.js
│ modify-userinfo.js
│ personal-center.js
│
├─login
│ email_check.html
│ login.jsp
│ retrive_pwd.html
│
├─META-INF
│ MANIFEST.MF
│
├─module
│ blog.jsp
│ code_library.jsp
│ contact.jsp
│ download.jsp
│ message.jsp
│
├─navigation
│ rightbar.jsp
│ topbar.jsp
│
├─personal_center
│ modify_email.html
│ modify_email1.html
│ modify_pwd.html
│ modify_userinfo.html
│ mycenter.jsp
│
├─plugins
│ │ plugins.jsp
│ │
│ ├─bootstrap
│ │ ├─css
│ │ │ bootstrap.css
│ │ │ bootstrap.css.map
│ │ │ bootstrap.min.css
│ │ │ bootstrap.min.css.map
│ │ │
│ │ ├─fonts
│ │ │ glyphicons-halflings-regular.eot
│ │ │ glyphicons-halflings-regular.svg
│ │ │ glyphicons-halflings-regular.ttf
│ │ │ glyphicons-halflings-regular.woff
│ │ │ glyphicons-halflings-regular.woff2
│ │ │
│ │ └─js
│ │ bootstrap.js
│ │ bootstrap.min.js
│ │
│ ├─editormd
│ ├─jquery
│ │ └─js
│ │ jquery-3.2.1.min.js
│ │ jquery.cookie.js
│ │ jquery.easing.1.3.js
│ │ jquery.flexslider-min.js
│ │ jquery.form.min.js
│ │ jquery.waypoints.min.js
│ │
│ ├─jqueryconfirm
│ │ ├─css
│ │ │ jquery-confirm.min.css
│ │ │
│ │ └─js
│ │ jquery-confirm.min.js
│ │
│ ├─json
│ │ └─js
│ │ json2.js
│ │
│ ├─template
│ │ ├─css
│ │ │ animate.css
│ │ │ flexslider.css
│ │ │ icomoon.css
│ │ │ style.css
│ │ │ style.css.map
│ │ │
│ │ └─js
│ │ main.js
│ │ modernizr-2.6.2.min.js
│ │
│ └─validator
│ ├─css
│ │ bootstrapValidator.css
│ │ bootstrapValidator.min.css
│ │
│ └─js
│ │ bootstrapValidator.js
│ │ bootstrapValidator.min.js
│ │
│ └─language
│ ar_MA.js
│ be_FR.js
│ be_NL.js
│ bg_BG.js
│ cs_CZ.js
│ da_DK.js
│ de_DE.js
│ en_US.js
│ es_CL.js
│ es_ES.js
│ fa_IR.js
│ fr_FR.js
│ gr_EL.js
│ he_IL.js
│ hu_HU.js
│ id_ID.js
│ it_IT.js
│ ja_JP.js
│ nl_NL.js
│ no_NO.js
│ pl_PL.js
│ pt_BR.js
│ pt_PT.js
│ ro_RO.js
│ ru_RU.js
│ sq_AL.js
│ sr_RS.js
│ sv_SE.js
│ th_TH.js
│ tr_TR.js
│ ua_UA.js
│ vi_VN.js
│ zh_CN.js
│ zh_TW.js
│
├─upload
│ editor_article.jsp
│ upload_file.jsp
│
└─WEB-INF
│ web.xml
│
└─lib
| Humsen/web/web-mobile/README.md/0 | {
"file_path": "Humsen/web/web-mobile/README.md",
"repo_id": "Humsen",
"token_count": 10856
} | 28 |
@charset "UTF-8";
.topbar-nav {
min-height: 30px;
width: 100%;
margin-bottom: 0;
}
.topbar-nav label {
color: #6e83ab;
}
.navbar-brand-a {
padding: 5px 15px 1px;
height: 30px;
}
.access-today {
margin-left: 5% !important;
}
.online-current {
margin-top: 4px;
margin-left: 20px;
}
.topbar-btn-login {
padding: 2px 2px !important;
font-size: 13px;
border: 1px solid #f0ad4e;
margin-left: 2%;
display: none;
}
.topbar-btn-pers {
padding: 2px 2px !important;
font-size: 13px;
border: 1px solid #5bc0de;
margin-left: 2%;
display: none;
}
.topbar-btn-right {
padding: 2px 2px !important;
font-size: 13px;
border: 1px solid #5bc0de;
display: none;
margin-left: 6px;
}
.choose-theme {
margin: 10px;
}
.web-pc-blank {
float: left;
margin-left: 20px;
}
.header-nav {
float: left;
margin-left: 6%;
}
.choose-theme button {
float: left;
}
.top-bar-div{
margin: 18px 0px 5px 10px;
} | Humsen/web/web-mobile/WebContent/css/navigation/topbar.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/css/navigation/topbar.css",
"repo_id": "Humsen",
"token_count": 426
} | 29 |
/**
* jQuery MD5 hash algorithm function
*
* <code>
* Calculate the md5 hash of a String
* String $.md5 ( String str )
* </code>
*
* Calculates the MD5 hash of str using the » RSA Data Security, Inc. MD5
* Message-Digest Algorithm, and returns that hash. MD5 (Message-Digest
* algorithm 5) is a widely-used cryptographic hash function with a 128-bit hash
* value. MD5 has been employed in a wide variety of security applications, and
* is also commonly used to check the integrity of data. The generated hash is
* also non-reversable. Data cannot be retrieved from the message digest, the
* digest uniquely identifies the data. MD5 was developed by Professor Ronald L.
* Rivest in 1994. Its 128 bit (16 byte) message digest makes it a faster
* implementation than SHA-1. This script is used to process a variable length
* message into a fixed-length output of 128 bits using the MD5 algorithm. It is
* fully compatible with UTF-8 encoding. It is very useful when u want to
* transfer encrypted passwords over the internet. If you plan using UTF-8
* encoding in your project don't forget to set the page encoding to UTF-8
* (Content-Type meta tag). This function orginally get from the WebToolkit and
* rewrite for using as the jQuery plugin.
*
* Example Code <code>
* $.md5("I'm Persian.");
* </code> Result <code>
* "b8c901d0f02223f9761016cfff9d68df"
* </code>
*
* @alias Muhammad Hussein Fattahizadeh < muhammad [AT] semnanweb [DOT] com >
* @link http://www.semnanweb.com/jquery-plugin/md5.html
* @see http://www.webtoolkit.info/
* @license http://www.gnu.org/licenses/gpl.html [GNU General Public License]
* @param {jQuery}
* {md5:function(string))
* @return string
*/
(function($) {
var rotateLeft = function(lValue, iShiftBits) {
return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
}
var addUnsigned = function(lX, lY) {
var lX4, lY4, lX8, lY8, lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
if (lX4 & lY4)
return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
if (lX4 | lY4) {
if (lResult & 0x40000000)
return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
else
return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
} else {
return (lResult ^ lX8 ^ lY8);
}
}
var F = function(x, y, z) {
return (x & y) | ((~x) & z);
}
var G = function(x, y, z) {
return (x & z) | (y & (~z));
}
var H = function(x, y, z) {
return (x ^ y ^ z);
}
var I = function(x, y, z) {
return (y ^ (x | (~z)));
}
var FF = function(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(F(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var GG = function(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(G(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var HH = function(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(H(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var II = function(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(I(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var convertToWordArray = function(string) {
var lWordCount;
var lMessageLength = string.length;
var lNumberOfWordsTempOne = lMessageLength + 8;
var lNumberOfWordsTempTwo = (lNumberOfWordsTempOne - (lNumberOfWordsTempOne % 64)) / 64;
var lNumberOfWords = (lNumberOfWordsTempTwo + 1) * 16;
var lWordArray = Array(lNumberOfWords - 1);
var lBytePosition = 0;
var lByteCount = 0;
while (lByteCount < lMessageLength) {
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = (lWordArray[lWordCount] | (string
.charCodeAt(lByteCount) << lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = lWordArray[lWordCount]
| (0x80 << lBytePosition);
lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
return lWordArray;
};
var wordToHex = function(lValue) {
var WordToHexValue = "", WordToHexValueTemp = "", lByte, lCount;
for (lCount = 0; lCount <= 3; lCount++) {
lByte = (lValue >>> (lCount * 8)) & 255;
WordToHexValueTemp = "0" + lByte.toString(16);
WordToHexValue = WordToHexValue
+ WordToHexValueTemp.substr(WordToHexValueTemp.length - 2,
2);
}
return WordToHexValue;
};
var uTF8Encode = function(string) {
string = string.replace(/\x0d\x0a/g, "\x0a");
var output = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
output += String.fromCharCode(c);
} else if ((c > 127) && (c < 2048)) {
output += String.fromCharCode((c >> 6) | 192);
output += String.fromCharCode((c & 63) | 128);
} else {
output += String.fromCharCode((c >> 12) | 224);
output += String.fromCharCode(((c >> 6) & 63) | 128);
output += String.fromCharCode((c & 63) | 128);
}
}
return output;
};
$.extend({
md5 : function(string) {
var x = Array();
var k, AA, BB, CC, DD, a, b, c, d;
var S11 = 7, S12 = 12, S13 = 17, S14 = 22;
var S21 = 5, S22 = 9, S23 = 14, S24 = 20;
var S31 = 4, S32 = 11, S33 = 16, S34 = 23;
var S41 = 6, S42 = 10, S43 = 15, S44 = 21;
string = uTF8Encode(string);
x = convertToWordArray(string);
a = 0x67452301;
b = 0xEFCDAB89;
c = 0x98BADCFE;
d = 0x10325476;
for (k = 0; k < x.length; k += 16) {
AA = a;
BB = b;
CC = c;
DD = d;
a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);
d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB);
b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);
c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613);
b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501);
a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8);
d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122);
d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193);
c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E);
b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821);
a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);
d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340);
c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);
b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);
d = GG(d, a, b, c, x[k + 10], S22, 0x2441453);
c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);
c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);
a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);
b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681);
c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05);
a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
a = II(a, b, c, d, x[k + 0], S41, 0xF4292244);
d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97);
c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039);
a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3);
d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1);
a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
c = II(c, d, a, b, x[k + 6], S43, 0xA3014314);
b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82);
d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391);
a = addUnsigned(a, AA);
b = addUnsigned(b, BB);
c = addUnsigned(c, CC);
d = addUnsigned(d, DD);
}
var tempValue = wordToHex(a) + wordToHex(b) + wordToHex(c)
+ wordToHex(d);
return tempValue.toLowerCase();
}
});
})(jQuery); | Humsen/web/web-mobile/WebContent/js/customize-jquery.md5.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/js/customize-jquery.md5.js",
"repo_id": "Humsen",
"token_count": 4688
} | 30 |
/**
* 编辑版本特性
*
* @author 何明胜
*
* 2017年11月10日
*/
// 当前最新版本id
var latest_version_id;
// 当前编辑版本id
var curr_version_id;
//当前版本号
var curr_version_num;
$(function() {
// 获取当前最新版本
getLatestVersion();
// 绑定加载上一个版本事件
$('#btn_prevV').click(prevVersionClick);
// 绑定加载下一个版本事件
$('#btn_nextV').click(nextVersionClick);
// 绑定清空当前编辑区
$('#btn_clearCurr').click(clearCurrClick);
// 绑定提交事件
$('#btn_subEditVsion').bind('click', submitNewVerFea);
});
/**
* 获取当前最新版本
*
* @returns
*/
function getLatestVersion() {
$.ajax({
type : 'POST',
url : '/latestRlseFetr.hms',
dataType : 'json',
success : function(response) {
latest_version_id = response.releaseId;
$('#txt_latestV').val(response.releaseNumber);
fillVersionEditor(response);
},
error : function(XMLHttpRequest, textStatus) {
$.confirm({
title : '加载新版特性出错',
content : textStatus + ' : ' + XMLHttpRequest.status,
autoClose : 'ok|2000',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
}
});
}
/**
* 填充版本信息
* @param versionArticle
* @returns
*/
function fillVersionEditor(versionArticle){
//先清空
clearCurrClick();
curr_version_id = versionArticle.releaseId;
curr_version_num = versionArticle.releaseNumber;
$('#txt_newV').val(versionArticle.releaseNumber);
var relContent = versionArticle.releaseContent;
relContent = relContent.match(/<p>(\S*)<\/p>/)[1];
relContent = relContent.split('</p><p>');
$('.version-input').each(function(i) {
$(this).val(relContent[i].split('、')[1]);
});
}
/**
* 绑定加载上一个版本事件
*
* @returns
*/
function prevVersionClick() {
//如果版本超过最新,直接返回
if(curr_version_id+1 > latest_version_id){
return;
}
$.ajax({
type : 'POST',
url : '/latestRlseFetr.hms',
dataType : 'json',
data : {
releaseId : curr_version_id+1,
},
success : function(response) {
fillVersionEditor(response);
},
error : function(XMLHttpRequest, textStatus) {
$.confirm({
title : '加载新版特性出错',
content : textStatus + ' : ' + XMLHttpRequest.status,
autoClose : 'ok|2000',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
}
});
}
/**
* 绑定加载下一个版本事件
*
* @returns
*/
function nextVersionClick() {
//如果版本小于等于0,直接返回
if(curr_version_id-1 <= 0){
return;
}
$.ajax({
type : 'POST',
url : '/latestRlseFetr.hms',
dataType : 'json',
data : {
releaseId : curr_version_id-1,
},
success : function(response) {
fillVersionEditor(response);
},
error : function(XMLHttpRequest, textStatus) {
$.confirm({
title : '加载新版特性出错',
content : textStatus + ' : ' + XMLHttpRequest.status,
autoClose : 'ok|2000',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
}
});
}
/**
* 绑定清空当前编辑区
*
* @returns
*/
function clearCurrClick() {
$('.version-input').each(function(i) {
$(this).val('');
});
$('#txt_newV').val('');
}
/**
* 新版本特性提交
*
* @returns
*/
function submitNewVerFea() {
// 获取文章细节
var article_data = JSON.stringify(articleDetail());
if (typeof (article_data) == 'undefined') {
$.confirm({
title : '收集新版特性出错',
content : '新版特性内容不能为空',
autoClose : 'ok|2000',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
return;
}
$.ajax({
type : 'POST',
async : false,
url : '/editRlseFetr.hms',
dataType : 'json',
data : {
type : $.trim($('#txt_newV').val()) != curr_version_num ? 'create' : 'modify',
releaseId : curr_version_id,
newArticle : article_data,
},
success : function(response, status) {
if (response == 1) {
//如果是新建,最新版本号加1
if($.trim($('#txt_newV').val()) != curr_version_num){
getLatestVersion();
}
$.confirm({
title : '上传成功',
content : '新版特性上传成功',
autoClose : 'ok|2000',
type : 'green',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
} else {
$.confirm({
title : '上传失败',
content : '上传失败',
autoClose : 'ok|2000',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
}
},
error : function(XMLHttpRequest, textStatus) {
$.confirm({
title : '上传出错',
content : textStatus + ' : ' + XMLHttpRequest.status,
autoClose : 'ok|2000',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
}
});
}
/**
* 提交时获取新版特性细节
*
* @returns
*/
function articleDetail() {
var new_version_feature = {};
var version_feature = '';
$('.version-input').each(function(i) {
if ($(this).val() != '') {
version_feature += '<p>' + (i + 1) + '、' + $(this).val() + '</p>';
}
});
// 如果新版特性为空,直接返回
if (version_feature == '') {
return;
}
new_version_feature.releaseAuthor = '何明胜';
new_version_feature.releaseDate = $.nowDateHMS();
new_version_feature.releaseNumber = $('#txt_newV').val();
new_version_feature.releaseContent = version_feature;
return new_version_feature;
} | Humsen/web/web-mobile/WebContent/js/personal_center/editor_version.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/js/personal_center/editor_version.js",
"repo_id": "Humsen",
"token_count": 2845
} | 31 |
<link rel="stylesheet" href="/css/personal_center/modify-pwd.css">
<!-- 修改用户密码脚本 -->
<script src="/js/personal_center/modify-pwd.js"></script>
<form id="modifyPwdForm" class="form-horizontal modify-pwd-form">
<div class="form-group">
<label for="oldPassword" class="col-sm-2 control-label">旧密码</label>
<div class="col-sm-8">
<input type="password" class="form-control" id="oldPassword"
name="oldPassword" placeholder="请输入旧密码" aria-describedby="helpBlock">
</div>
<span id="helpBlock" class="help-block old-pwd-wrong-info">旧密码输入错误</span>
</div>
<div class="form-group">
<label for="newPassword" class="col-sm-2 control-label">新密码</label>
<div class="col-sm-8">
<input type="password" class="form-control" id="newPassword"
name="newPassword" placeholder="请输入新密码">
</div>
</div>
<div class="form-group">
<label for="confirmPwd" class="col-sm-2 control-label">确认新密码</label>
<div class="col-sm-8">
<input type="password" class="form-control" id="confirmPwd"
name="confirmPwd" placeholder="请确认新密码">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-8">
<a id="submitModifyPwd" class="btn btn-default" href="#"
role="button">提交</a>
</div>
</div>
</form> | Humsen/web/web-mobile/WebContent/personal_center/modify_pwd.html/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/personal_center/modify_pwd.html",
"repo_id": "Humsen",
"token_count": 586
} | 32 |
/*
* Editor.md
*
* @file editormd.logo.css
* @version v1.5.0
* @description Open source online markdown editor.
* @license MIT License
* @author Pandao
* {@link https://github.com/pandao/editor.md}
* @updateTime 2015-06-09
*/
/*! prefixes.scss v0.1.0 | Author: Pandao | https://github.com/pandao/prefixes.scss | MIT license | Copyright (c) 2015 */
@font-face {
font-family: 'editormd-logo';
src: url("../fonts/editormd-logo.eot?-5y8q6h");
src: url(".../fonts/editormd-logo.eot?#iefix-5y8q6h") format("embedded-opentype"), url("../fonts/editormd-logo.woff?-5y8q6h") format("woff"), url("../fonts/editormd-logo.ttf?-5y8q6h") format("truetype"), url("../fonts/editormd-logo.svg?-5y8q6h#icomoon") format("svg");
font-weight: normal;
font-style: normal;
}
.editormd-logo,
.editormd-logo-1x,
.editormd-logo-2x,
.editormd-logo-3x,
.editormd-logo-4x,
.editormd-logo-5x,
.editormd-logo-6x,
.editormd-logo-7x,
.editormd-logo-8x {
font-family: 'editormd-logo';
speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
font-size: inherit;
line-height: 1;
display: inline-block;
text-rendering: auto;
vertical-align: inherit;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.editormd-logo:before,
.editormd-logo-1x:before,
.editormd-logo-2x:before,
.editormd-logo-3x:before,
.editormd-logo-4x:before,
.editormd-logo-5x:before,
.editormd-logo-6x:before,
.editormd-logo-7x:before,
.editormd-logo-8x:before {
content: "\e1987";
/*
HTML Entity 󡦇
example: <span class="editormd-logo">󡦇</span>
*/
}
.editormd-logo-1x {
font-size: 1em;
}
.editormd-logo-lg {
font-size: 1.2em;
}
.editormd-logo-2x {
font-size: 2em;
}
.editormd-logo-3x {
font-size: 3em;
}
.editormd-logo-4x {
font-size: 4em;
}
.editormd-logo-5x {
font-size: 5em;
}
.editormd-logo-6x {
font-size: 6em;
}
.editormd-logo-7x {
font-size: 7em;
}
.editormd-logo-8x {
font-size: 8em;
}
.editormd-logo-color {
color: #2196F3;
}
| Humsen/web/web-mobile/WebContent/plugins/editormd/css/editormd.logo.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/css/editormd.logo.css",
"repo_id": "Humsen",
"token_count": 1011
} | 33 |
/*
* Editor.md
*
* @file editormd.amd.js
* @version v1.5.0
* @description Open source online markdown editor.
* @license MIT License
* @author Pandao
* {@link https://github.com/pandao/editor.md}
* @updateTime 2015-06-09
*/
;(function(factory) {
"use strict";
// CommonJS/Node.js
if (typeof require === "function" && typeof exports === "object" && typeof module === "object")
{
module.exports = factory;
}
else if (typeof define === "function") // AMD/CMD/Sea.js
{
if (define.amd) // for Require.js
{
var cmModePath = "./lib/codemirror/mode/";
var cmAddonPath = "./lib/codemirror/addon/";
var codeMirrorModules = [
"jquery", "marked", "prettify",
"katex", "raphael", "underscore", "flowchart", "jqueryflowchart", "sequenceDiagram",
"./lib/codemirror/lib/codemirror",
cmModePath + "css/css",
cmModePath + "sass/sass",
cmModePath + "shell/shell",
cmModePath + "sql/sql",
cmModePath + "clike/clike",
cmModePath + "php/php",
cmModePath + "xml/xml",
cmModePath + "markdown/markdown",
cmModePath + "javascript/javascript",
cmModePath + "htmlmixed/htmlmixed",
cmModePath + "gfm/gfm",
cmModePath + "http/http",
cmModePath + "go/go",
cmModePath + "dart/dart",
cmModePath + "coffeescript/coffeescript",
cmModePath + "nginx/nginx",
cmModePath + "python/python",
cmModePath + "perl/perl",
cmModePath + "lua/lua",
cmModePath + "r/r",
cmModePath + "ruby/ruby",
cmModePath + "rst/rst",
cmModePath + "smartymixed/smartymixed",
cmModePath + "vb/vb",
cmModePath + "vbscript/vbscript",
cmModePath + "velocity/velocity",
cmModePath + "xquery/xquery",
cmModePath + "yaml/yaml",
cmModePath + "erlang/erlang",
cmModePath + "jade/jade",
cmAddonPath + "edit/trailingspace",
cmAddonPath + "dialog/dialog",
cmAddonPath + "search/searchcursor",
cmAddonPath + "search/search",
cmAddonPath + "scroll/annotatescrollbar",
cmAddonPath + "search/matchesonscrollbar",
cmAddonPath + "display/placeholder",
cmAddonPath + "edit/closetag",
cmAddonPath + "fold/foldcode",
cmAddonPath + "fold/foldgutter",
cmAddonPath + "fold/indent-fold",
cmAddonPath + "fold/brace-fold",
cmAddonPath + "fold/xml-fold",
cmAddonPath + "fold/markdown-fold",
cmAddonPath + "fold/comment-fold",
cmAddonPath + "mode/overlay",
cmAddonPath + "selection/active-line",
cmAddonPath + "edit/closebrackets",
cmAddonPath + "display/fullscreen",
cmAddonPath + "search/match-highlighter"
];
define(codeMirrorModules, factory);
}
else
{
define(["jquery"], factory); // for Sea.js
}
}
else
{
window.editormd = factory();
}
}(function() {
if (typeof define == "function" && define.amd) {
$ = arguments[0];
marked = arguments[1];
prettify = arguments[2];
katex = arguments[3];
Raphael = arguments[4];
_ = arguments[5];
flowchart = arguments[6];
CodeMirror = arguments[9];
}
"use strict";
var $ = (typeof (jQuery) !== "undefined") ? jQuery : Zepto;
if (typeof ($) === "undefined") {
return ;
}
/**
* editormd
*
* @param {String} id 编辑器的ID
* @param {Object} options 配置选项 Key/Value
* @returns {Object} editormd 返回editormd对象
*/
var editormd = function (id, options) {
return new editormd.fn.init(id, options);
};
editormd.title = editormd.$name = "Editor.md";
editormd.version = "1.5.0";
editormd.homePage = "https://pandao.github.io/editor.md/";
editormd.classPrefix = "editormd-";
editormd.toolbarModes = {
full : [
"undo", "redo", "|",
"bold", "del", "italic", "quote", "ucwords", "uppercase", "lowercase", "|",
"h1", "h2", "h3", "h4", "h5", "h6", "|",
"list-ul", "list-ol", "hr", "|",
"link", "reference-link", "image", "code", "preformatted-text", "code-block", "table", "datetime", "emoji", "html-entities", "pagebreak", "|",
"goto-line", "watch", "preview", "fullscreen", "clear", "search", "|",
"help", "info"
],
simple : [
"undo", "redo", "|",
"bold", "del", "italic", "quote", "uppercase", "lowercase", "|",
"h1", "h2", "h3", "h4", "h5", "h6", "|",
"list-ul", "list-ol", "hr", "|",
"watch", "preview", "fullscreen", "|",
"help", "info"
],
mini : [
"undo", "redo", "|",
"watch", "preview", "|",
"help", "info"
]
};
editormd.defaults = {
mode : "gfm", //gfm or markdown
name : "", // Form element name
value : "", // value for CodeMirror, if mode not gfm/markdown
theme : "", // Editor.md self themes, before v1.5.0 is CodeMirror theme, default empty
editorTheme : "default", // Editor area, this is CodeMirror theme at v1.5.0
previewTheme : "", // Preview area theme, default empty
markdown : "", // Markdown source code
appendMarkdown : "", // if in init textarea value not empty, append markdown to textarea
width : "100%",
height : "100%",
path : "./lib/", // Dependents module file directory
pluginPath : "", // If this empty, default use settings.path + "../plugins/"
delay : 300, // Delay parse markdown to html, Uint : ms
autoLoadModules : true, // Automatic load dependent module files
watch : true,
placeholder : "Enjoy Markdown! coding now...",
gotoLine : true,
codeFold : false,
autoHeight : false,
autoFocus : true,
autoCloseTags : true,
searchReplace : true,
syncScrolling : true, // true | false | "single", default true
readOnly : false,
tabSize : 4,
indentUnit : 4,
lineNumbers : true,
lineWrapping : true,
autoCloseBrackets : true,
showTrailingSpace : true,
matchBrackets : true,
indentWithTabs : true,
styleSelectedText : true,
matchWordHighlight : true, // options: true, false, "onselected"
styleActiveLine : true, // Highlight the current line
dialogLockScreen : true,
dialogShowMask : true,
dialogDraggable : true,
dialogMaskBgColor : "#fff",
dialogMaskOpacity : 0.1,
fontSize : "13px",
saveHTMLToTextarea : false,
disabledKeyMaps : [],
onload : function() {},
onresize : function() {},
onchange : function() {},
onwatch : null,
onunwatch : null,
onpreviewing : function() {},
onpreviewed : function() {},
onfullscreen : function() {},
onfullscreenExit : function() {},
onscroll : function() {},
onpreviewscroll : function() {},
imageUpload : false,
imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
imageUploadURL : "",
crossDomainUpload : false,
uploadCallbackURL : "",
toc : true, // Table of contents
tocm : false, // Using [TOCM], auto create ToC dropdown menu
tocTitle : "", // for ToC dropdown menu btn
tocDropdown : false,
tocContainer : "",
tocStartLevel : 1, // Said from H1 to create ToC
htmlDecode : false, // Open the HTML tag identification
pageBreak : true, // Enable parse page break [========]
atLink : true, // for @link
emailLink : true, // for email address auto link
taskList : false, // Enable Github Flavored Markdown task lists
emoji : false, // :emoji: , Support Github emoji, Twitter Emoji (Twemoji);
// Support FontAwesome icon emoji :fa-xxx: > Using fontAwesome icon web fonts;
// Support Editor.md logo icon emoji :editormd-logo: :editormd-logo-1x: > 1~8x;
tex : false, // TeX(LaTeX), based on KaTeX
flowChart : false, // flowChart.js only support IE9+
sequenceDiagram : false, // sequenceDiagram.js only support IE9+
previewCodeHighlight : true,
toolbar : true, // show/hide toolbar
toolbarAutoFixed : true, // on window scroll auto fixed position
toolbarIcons : "full",
toolbarTitles : {},
toolbarHandlers : {
ucwords : function() {
return editormd.toolbarHandlers.ucwords;
},
lowercase : function() {
return editormd.toolbarHandlers.lowercase;
}
},
toolbarCustomIcons : { // using html tag create toolbar icon, unused default <a> tag.
lowercase : "<a href=\"javascript:;\" title=\"Lowercase\" unselectable=\"on\"><i class=\"fa\" name=\"lowercase\" style=\"font-size:24px;margin-top: -10px;\">a</i></a>",
"ucwords" : "<a href=\"javascript:;\" title=\"ucwords\" unselectable=\"on\"><i class=\"fa\" name=\"ucwords\" style=\"font-size:20px;margin-top: -3px;\">Aa</i></a>"
},
toolbarIconsClass : {
undo : "fa-undo",
redo : "fa-repeat",
bold : "fa-bold",
del : "fa-strikethrough",
italic : "fa-italic",
quote : "fa-quote-left",
uppercase : "fa-font",
h1 : editormd.classPrefix + "bold",
h2 : editormd.classPrefix + "bold",
h3 : editormd.classPrefix + "bold",
h4 : editormd.classPrefix + "bold",
h5 : editormd.classPrefix + "bold",
h6 : editormd.classPrefix + "bold",
"list-ul" : "fa-list-ul",
"list-ol" : "fa-list-ol",
hr : "fa-minus",
link : "fa-link",
"reference-link" : "fa-anchor",
image : "fa-picture-o",
code : "fa-code",
"preformatted-text" : "fa-file-code-o",
"code-block" : "fa-file-code-o",
table : "fa-table",
datetime : "fa-clock-o",
emoji : "fa-smile-o",
"html-entities" : "fa-copyright",
pagebreak : "fa-newspaper-o",
"goto-line" : "fa-terminal", // fa-crosshairs
watch : "fa-eye-slash",
unwatch : "fa-eye",
preview : "fa-desktop",
search : "fa-search",
fullscreen : "fa-arrows-alt",
clear : "fa-eraser",
help : "fa-question-circle",
info : "fa-info-circle"
},
toolbarIconTexts : {},
lang : {
name : "zh-cn",
description : "开源在线Markdown编辑器<br/>Open source online Markdown editor.",
tocTitle : "目录",
toolbar : {
undo : "撤销(Ctrl+Z)",
redo : "重做(Ctrl+Y)",
bold : "粗体",
del : "删除线",
italic : "斜体",
quote : "引用",
ucwords : "将每个单词首字母转成大写",
uppercase : "将所选转换成大写",
lowercase : "将所选转换成小写",
h1 : "标题1",
h2 : "标题2",
h3 : "标题3",
h4 : "标题4",
h5 : "标题5",
h6 : "标题6",
"list-ul" : "无序列表",
"list-ol" : "有序列表",
hr : "横线",
link : "链接",
"reference-link" : "引用链接",
image : "添加图片",
code : "行内代码",
"preformatted-text" : "预格式文本 / 代码块(缩进风格)",
"code-block" : "代码块(多语言风格)",
table : "添加表格",
datetime : "日期时间",
emoji : "Emoji表情",
"html-entities" : "HTML实体字符",
pagebreak : "插入分页符",
"goto-line" : "跳转到行",
watch : "关闭实时预览",
unwatch : "开启实时预览",
preview : "全窗口预览HTML(按 Shift + ESC还原)",
fullscreen : "全屏(按ESC还原)",
clear : "清空",
search : "搜索",
help : "使用帮助",
info : "关于" + editormd.title
},
buttons : {
enter : "确定",
cancel : "取消",
close : "关闭"
},
dialog : {
link : {
title : "添加链接",
url : "链接地址",
urlTitle : "链接标题",
urlEmpty : "错误:请填写链接地址。"
},
referenceLink : {
title : "添加引用链接",
name : "引用名称",
url : "链接地址",
urlId : "链接ID",
urlTitle : "链接标题",
nameEmpty: "错误:引用链接的名称不能为空。",
idEmpty : "错误:请填写引用链接的ID。",
urlEmpty : "错误:请填写引用链接的URL地址。"
},
image : {
title : "添加图片",
url : "图片地址",
link : "图片链接",
alt : "图片描述",
uploadButton : "本地上传",
imageURLEmpty : "错误:图片地址不能为空。",
uploadFileEmpty : "错误:上传的图片不能为空。",
formatNotAllowed : "错误:只允许上传图片文件,允许上传的图片文件格式有:"
},
preformattedText : {
title : "添加预格式文本或代码块",
emptyAlert : "错误:请填写预格式文本或代码的内容。"
},
codeBlock : {
title : "添加代码块",
selectLabel : "代码语言:",
selectDefaultText : "请选择代码语言",
otherLanguage : "其他语言",
unselectedLanguageAlert : "错误:请选择代码所属的语言类型。",
codeEmptyAlert : "错误:请填写代码内容。"
},
htmlEntities : {
title : "HTML 实体字符"
},
help : {
title : "使用帮助"
}
}
}
};
editormd.classNames = {
tex : editormd.classPrefix + "tex"
};
editormd.dialogZindex = 99999;
editormd.$katex = null;
editormd.$marked = null;
editormd.$CodeMirror = null;
editormd.$prettyPrint = null;
var timer, flowchartTimer;
editormd.prototype = editormd.fn = {
state : {
watching : false,
loaded : false,
preview : false,
fullscreen : false
},
/**
* 构造函数/实例初始化
* Constructor / instance initialization
*
* @param {String} id 编辑器的ID
* @param {Object} [options={}] 配置选项 Key/Value
* @returns {editormd} 返回editormd的实例对象
*/
init : function (id, options) {
options = options || {};
if (typeof id === "object")
{
options = id;
}
var _this = this;
var classPrefix = this.classPrefix = editormd.classPrefix;
var settings = this.settings = $.extend(true, editormd.defaults, options);
id = (typeof id === "object") ? settings.id : id;
var editor = this.editor = $("#" + id);
this.id = id;
this.lang = settings.lang;
var classNames = this.classNames = {
textarea : {
html : classPrefix + "html-textarea",
markdown : classPrefix + "markdown-textarea"
}
};
settings.pluginPath = (settings.pluginPath === "") ? settings.path + "../plugins/" : settings.pluginPath;
this.state.watching = (settings.watch) ? true : false;
if ( !editor.hasClass("editormd") ) {
editor.addClass("editormd");
}
editor.css({
width : (typeof settings.width === "number") ? settings.width + "px" : settings.width,
height : (typeof settings.height === "number") ? settings.height + "px" : settings.height
});
if (settings.autoHeight)
{
editor.css("height", "auto");
}
var markdownTextarea = this.markdownTextarea = editor.children("textarea");
if (markdownTextarea.length < 1)
{
editor.append("<textarea></textarea>");
markdownTextarea = this.markdownTextarea = editor.children("textarea");
}
markdownTextarea.addClass(classNames.textarea.markdown).attr("placeholder", settings.placeholder);
if (typeof markdownTextarea.attr("name") === "undefined" || markdownTextarea.attr("name") === "")
{
markdownTextarea.attr("name", (settings.name !== "") ? settings.name : id + "-markdown-doc");
}
var appendElements = [
(!settings.readOnly) ? "<a href=\"javascript:;\" class=\"fa fa-close " + classPrefix + "preview-close-btn\"></a>" : "",
( (settings.saveHTMLToTextarea) ? "<textarea class=\"" + classNames.textarea.html + "\" name=\"" + id + "-html-code\"></textarea>" : "" ),
"<div class=\"" + classPrefix + "preview\"><div class=\"markdown-body " + classPrefix + "preview-container\"></div></div>",
"<div class=\"" + classPrefix + "container-mask\" style=\"display:block;\"></div>",
"<div class=\"" + classPrefix + "mask\"></div>"
].join("\n");
editor.append(appendElements).addClass(classPrefix + "vertical");
if (settings.theme !== "")
{
editor.addClass(classPrefix + "theme-" + settings.theme);
}
this.mask = editor.children("." + classPrefix + "mask");
this.containerMask = editor.children("." + classPrefix + "container-mask");
if (settings.markdown !== "")
{
markdownTextarea.val(settings.markdown);
}
if (settings.appendMarkdown !== "")
{
markdownTextarea.val(markdownTextarea.val() + settings.appendMarkdown);
}
this.htmlTextarea = editor.children("." + classNames.textarea.html);
this.preview = editor.children("." + classPrefix + "preview");
this.previewContainer = this.preview.children("." + classPrefix + "preview-container");
if (settings.previewTheme !== "")
{
this.preview.addClass(classPrefix + "preview-theme-" + settings.previewTheme);
}
if (typeof define === "function" && define.amd)
{
if (typeof katex !== "undefined")
{
editormd.$katex = katex;
}
if (settings.searchReplace && !settings.readOnly)
{
editormd.loadCSS(settings.path + "codemirror/addon/dialog/dialog");
editormd.loadCSS(settings.path + "codemirror/addon/search/matchesonscrollbar");
}
}
if ((typeof define === "function" && define.amd) || !settings.autoLoadModules)
{
if (typeof CodeMirror !== "undefined") {
editormd.$CodeMirror = CodeMirror;
}
if (typeof marked !== "undefined") {
editormd.$marked = marked;
}
this.setCodeMirror().setToolbar().loadedDisplay();
}
else
{
this.loadQueues();
}
return this;
},
/**
* 所需组件加载队列
* Required components loading queue
*
* @returns {editormd} 返回editormd的实例对象
*/
loadQueues : function() {
var _this = this;
var settings = this.settings;
var loadPath = settings.path;
var loadFlowChartOrSequenceDiagram = function() {
if (editormd.isIE8)
{
_this.loadedDisplay();
return ;
}
if (settings.flowChart || settings.sequenceDiagram)
{
editormd.loadScript(loadPath + "raphael.min", function() {
editormd.loadScript(loadPath + "underscore.min", function() {
if (!settings.flowChart && settings.sequenceDiagram)
{
editormd.loadScript(loadPath + "sequence-diagram.min", function() {
_this.loadedDisplay();
});
}
else if (settings.flowChart && !settings.sequenceDiagram)
{
editormd.loadScript(loadPath + "flowchart.min", function() {
editormd.loadScript(loadPath + "jquery.flowchart.min", function() {
_this.loadedDisplay();
});
});
}
else if (settings.flowChart && settings.sequenceDiagram)
{
editormd.loadScript(loadPath + "flowchart.min", function() {
editormd.loadScript(loadPath + "jquery.flowchart.min", function() {
editormd.loadScript(loadPath + "sequence-diagram.min", function() {
_this.loadedDisplay();
});
});
});
}
});
});
}
else
{
_this.loadedDisplay();
}
};
editormd.loadCSS(loadPath + "codemirror/codemirror.min");
if (settings.searchReplace && !settings.readOnly)
{
editormd.loadCSS(loadPath + "codemirror/addon/dialog/dialog");
editormd.loadCSS(loadPath + "codemirror/addon/search/matchesonscrollbar");
}
if (settings.codeFold)
{
editormd.loadCSS(loadPath + "codemirror/addon/fold/foldgutter");
}
editormd.loadScript(loadPath + "codemirror/codemirror.min", function() {
editormd.$CodeMirror = CodeMirror;
editormd.loadScript(loadPath + "codemirror/modes.min", function() {
editormd.loadScript(loadPath + "codemirror/addons.min", function() {
_this.setCodeMirror();
if (settings.mode !== "gfm" && settings.mode !== "markdown")
{
_this.loadedDisplay();
return false;
}
_this.setToolbar();
editormd.loadScript(loadPath + "marked.min", function() {
editormd.$marked = marked;
if (settings.previewCodeHighlight)
{
editormd.loadScript(loadPath + "prettify.min", function() {
loadFlowChartOrSequenceDiagram();
});
}
else
{
loadFlowChartOrSequenceDiagram();
}
});
});
});
});
return this;
},
/**
* 设置 Editor.md 的整体主题,主要是工具栏
* Setting Editor.md theme
*
* @returns {editormd} 返回editormd的实例对象
*/
setTheme : function(theme) {
var editor = this.editor;
var oldTheme = this.settings.theme;
var themePrefix = this.classPrefix + "theme-";
editor.removeClass(themePrefix + oldTheme).addClass(themePrefix + theme);
this.settings.theme = theme;
return this;
},
/**
* 设置 CodeMirror(编辑区)的主题
* Setting CodeMirror (Editor area) theme
*
* @returns {editormd} 返回editormd的实例对象
*/
setEditorTheme : function(theme) {
var settings = this.settings;
settings.editorTheme = theme;
if (theme !== "default")
{
editormd.loadCSS(settings.path + "codemirror/theme/" + settings.editorTheme);
}
this.cm.setOption("theme", theme);
return this;
},
/**
* setEditorTheme() 的别名
* setEditorTheme() alias
*
* @returns {editormd} 返回editormd的实例对象
*/
setCodeMirrorTheme : function (theme) {
this.setEditorTheme(theme);
return this;
},
/**
* 设置 Editor.md 的主题
* Setting Editor.md theme
*
* @returns {editormd} 返回editormd的实例对象
*/
setPreviewTheme : function(theme) {
var preview = this.preview;
var oldTheme = this.settings.previewTheme;
var themePrefix = this.classPrefix + "preview-theme-";
preview.removeClass(themePrefix + oldTheme).addClass(themePrefix + theme);
this.settings.previewTheme = theme;
return this;
},
/**
* 配置和初始化CodeMirror组件
* CodeMirror initialization
*
* @returns {editormd} 返回editormd的实例对象
*/
setCodeMirror : function() {
var settings = this.settings;
var editor = this.editor;
if (settings.editorTheme !== "default")
{
editormd.loadCSS(settings.path + "codemirror/theme/" + settings.editorTheme);
}
var codeMirrorConfig = {
mode : settings.mode,
theme : settings.editorTheme,
tabSize : settings.tabSize,
dragDrop : false,
autofocus : settings.autoFocus,
autoCloseTags : settings.autoCloseTags,
readOnly : (settings.readOnly) ? "nocursor" : false,
indentUnit : settings.indentUnit,
lineNumbers : settings.lineNumbers,
lineWrapping : settings.lineWrapping,
extraKeys : {
"Ctrl-Q": function(cm) {
cm.foldCode(cm.getCursor());
}
},
foldGutter : settings.codeFold,
gutters : ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
matchBrackets : settings.matchBrackets,
indentWithTabs : settings.indentWithTabs,
styleActiveLine : settings.styleActiveLine,
styleSelectedText : settings.styleSelectedText,
autoCloseBrackets : settings.autoCloseBrackets,
showTrailingSpace : settings.showTrailingSpace,
highlightSelectionMatches : ( (!settings.matchWordHighlight) ? false : { showToken: (settings.matchWordHighlight === "onselected") ? false : /\w/ } )
};
this.codeEditor = this.cm = editormd.$CodeMirror.fromTextArea(this.markdownTextarea[0], codeMirrorConfig);
this.codeMirror = this.cmElement = editor.children(".CodeMirror");
if (settings.value !== "")
{
this.cm.setValue(settings.value);
}
this.codeMirror.css({
fontSize : settings.fontSize,
width : (!settings.watch) ? "100%" : "50%"
});
if (settings.autoHeight)
{
this.codeMirror.css("height", "auto");
this.cm.setOption("viewportMargin", Infinity);
}
if (!settings.lineNumbers)
{
this.codeMirror.find(".CodeMirror-gutters").css("border-right", "none");
}
return this;
},
/**
* 获取CodeMirror的配置选项
* Get CodeMirror setting options
*
* @returns {Mixed} return CodeMirror setting option value
*/
getCodeMirrorOption : function(key) {
return this.cm.getOption(key);
},
/**
* 配置和重配置CodeMirror的选项
* CodeMirror setting options / resettings
*
* @returns {editormd} 返回editormd的实例对象
*/
setCodeMirrorOption : function(key, value) {
this.cm.setOption(key, value);
return this;
},
/**
* 添加 CodeMirror 键盘快捷键
* Add CodeMirror keyboard shortcuts key map
*
* @returns {editormd} 返回editormd的实例对象
*/
addKeyMap : function(map, bottom) {
this.cm.addKeyMap(map, bottom);
return this;
},
/**
* 移除 CodeMirror 键盘快捷键
* Remove CodeMirror keyboard shortcuts key map
*
* @returns {editormd} 返回editormd的实例对象
*/
removeKeyMap : function(map) {
this.cm.removeKeyMap(map);
return this;
},
/**
* 跳转到指定的行
* Goto CodeMirror line
*
* @param {String|Intiger} line line number or "first"|"last"
* @returns {editormd} 返回editormd的实例对象
*/
gotoLine : function (line) {
var settings = this.settings;
if (!settings.gotoLine)
{
return this;
}
var cm = this.cm;
var editor = this.editor;
var count = cm.lineCount();
var preview = this.preview;
if (typeof line === "string")
{
if(line === "last")
{
line = count;
}
if (line === "first")
{
line = 1;
}
}
if (typeof line !== "number")
{
alert("Error: The line number must be an integer.");
return this;
}
line = parseInt(line) - 1;
if (line > count)
{
alert("Error: The line number range 1-" + count);
return this;
}
cm.setCursor( {line : line, ch : 0} );
var scrollInfo = cm.getScrollInfo();
var clientHeight = scrollInfo.clientHeight;
var coords = cm.charCoords({line : line, ch : 0}, "local");
cm.scrollTo(null, (coords.top + coords.bottom - clientHeight) / 2);
if (settings.watch)
{
var cmScroll = this.codeMirror.find(".CodeMirror-scroll")[0];
var height = $(cmScroll).height();
var scrollTop = cmScroll.scrollTop;
var percent = (scrollTop / cmScroll.scrollHeight);
if (scrollTop === 0)
{
preview.scrollTop(0);
}
else if (scrollTop + height >= cmScroll.scrollHeight - 16)
{
preview.scrollTop(preview[0].scrollHeight);
}
else
{
preview.scrollTop(preview[0].scrollHeight * percent);
}
}
cm.focus();
return this;
},
/**
* 扩展当前实例对象,可同时设置多个或者只设置一个
* Extend editormd instance object, can mutil setting.
*
* @returns {editormd} this(editormd instance object.)
*/
extend : function() {
if (typeof arguments[1] !== "undefined")
{
if (typeof arguments[1] === "function")
{
arguments[1] = $.proxy(arguments[1], this);
}
this[arguments[0]] = arguments[1];
}
if (typeof arguments[0] === "object" && typeof arguments[0].length === "undefined")
{
$.extend(true, this, arguments[0]);
}
return this;
},
/**
* 设置或扩展当前实例对象,单个设置
* Extend editormd instance object, one by one
*
* @param {String|Object} key option key
* @param {String|Object} value option value
* @returns {editormd} this(editormd instance object.)
*/
set : function (key, value) {
if (typeof value !== "undefined" && typeof value === "function")
{
value = $.proxy(value, this);
}
this[key] = value;
return this;
},
/**
* 重新配置
* Resetting editor options
*
* @param {String|Object} key option key
* @param {String|Object} value option value
* @returns {editormd} this(editormd instance object.)
*/
config : function(key, value) {
var settings = this.settings;
if (typeof key === "object")
{
settings = $.extend(true, settings, key);
}
if (typeof key === "string")
{
settings[key] = value;
}
this.settings = settings;
this.recreate();
return this;
},
/**
* 注册事件处理方法
* Bind editor event handle
*
* @param {String} eventType event type
* @param {Function} callback 回调函数
* @returns {editormd} this(editormd instance object.)
*/
on : function(eventType, callback) {
var settings = this.settings;
if (typeof settings["on" + eventType] !== "undefined")
{
settings["on" + eventType] = $.proxy(callback, this);
}
return this;
},
/**
* 解除事件处理方法
* Unbind editor event handle
*
* @param {String} eventType event type
* @returns {editormd} this(editormd instance object.)
*/
off : function(eventType) {
var settings = this.settings;
if (typeof settings["on" + eventType] !== "undefined")
{
settings["on" + eventType] = function(){};
}
return this;
},
/**
* 显示工具栏
* Display toolbar
*
* @param {Function} [callback=function(){}] 回调函数
* @returns {editormd} 返回editormd的实例对象
*/
showToolbar : function(callback) {
var settings = this.settings;
if(settings.readOnly) {
return this;
}
if (settings.toolbar && (this.toolbar.length < 1 || this.toolbar.find("." + this.classPrefix + "menu").html() === "") )
{
this.setToolbar();
}
settings.toolbar = true;
this.toolbar.show();
this.resize();
$.proxy(callback || function(){}, this)();
return this;
},
/**
* 隐藏工具栏
* Hide toolbar
*
* @param {Function} [callback=function(){}] 回调函数
* @returns {editormd} this(editormd instance object.)
*/
hideToolbar : function(callback) {
var settings = this.settings;
settings.toolbar = false;
this.toolbar.hide();
this.resize();
$.proxy(callback || function(){}, this)();
return this;
},
/**
* 页面滚动时工具栏的固定定位
* Set toolbar in window scroll auto fixed position
*
* @returns {editormd} 返回editormd的实例对象
*/
setToolbarAutoFixed : function(fixed) {
var state = this.state;
var editor = this.editor;
var toolbar = this.toolbar;
var settings = this.settings;
if (typeof fixed !== "undefined")
{
settings.toolbarAutoFixed = fixed;
}
var autoFixedHandle = function(){
var $window = $(window);
var top = $window.scrollTop();
if (!settings.toolbarAutoFixed)
{
return false;
}
if (top - editor.offset().top > 10 && top < editor.height())
{
toolbar.css({
position : "fixed",
width : editor.width() + "px",
left : ($window.width() - editor.width()) / 2 + "px"
});
}
else
{
toolbar.css({
position : "absolute",
width : "100%",
left : 0
});
}
};
if (!state.fullscreen && !state.preview && settings.toolbar && settings.toolbarAutoFixed)
{
$(window).bind("scroll", autoFixedHandle);
}
return this;
},
/**
* 配置和初始化工具栏
* Set toolbar and Initialization
*
* @returns {editormd} 返回editormd的实例对象
*/
setToolbar : function() {
var settings = this.settings;
if(settings.readOnly) {
return this;
}
var editor = this.editor;
var preview = this.preview;
var classPrefix = this.classPrefix;
var toolbar = this.toolbar = editor.children("." + classPrefix + "toolbar");
if (settings.toolbar && toolbar.length < 1)
{
var toolbarHTML = "<div class=\"" + classPrefix + "toolbar\"><div class=\"" + classPrefix + "toolbar-container\"><ul class=\"" + classPrefix + "menu\"></ul></div></div>";
editor.append(toolbarHTML);
toolbar = this.toolbar = editor.children("." + classPrefix + "toolbar");
}
if (!settings.toolbar)
{
toolbar.hide();
return this;
}
toolbar.show();
var icons = (typeof settings.toolbarIcons === "function") ? settings.toolbarIcons()
: ((typeof settings.toolbarIcons === "string") ? editormd.toolbarModes[settings.toolbarIcons] : settings.toolbarIcons);
var toolbarMenu = toolbar.find("." + this.classPrefix + "menu"), menu = "";
var pullRight = false;
for (var i = 0, len = icons.length; i < len; i++)
{
var name = icons[i];
if (name === "||")
{
pullRight = true;
}
else if (name === "|")
{
menu += "<li class=\"divider\" unselectable=\"on\">|</li>";
}
else
{
var isHeader = (/h(\d)/.test(name));
var index = name;
if (name === "watch" && !settings.watch) {
index = "unwatch";
}
var title = settings.lang.toolbar[index];
var iconTexts = settings.toolbarIconTexts[index];
var iconClass = settings.toolbarIconsClass[index];
title = (typeof title === "undefined") ? "" : title;
iconTexts = (typeof iconTexts === "undefined") ? "" : iconTexts;
iconClass = (typeof iconClass === "undefined") ? "" : iconClass;
var menuItem = pullRight ? "<li class=\"pull-right\">" : "<li>";
if (typeof settings.toolbarCustomIcons[name] !== "undefined" && typeof settings.toolbarCustomIcons[name] !== "function")
{
menuItem += settings.toolbarCustomIcons[name];
}
else
{
menuItem += "<a href=\"javascript:;\" title=\"" + title + "\" unselectable=\"on\">";
menuItem += "<i class=\"fa " + iconClass + "\" name=\""+name+"\" unselectable=\"on\">"+((isHeader) ? name.toUpperCase() : ( (iconClass === "") ? iconTexts : "") ) + "</i>";
menuItem += "</a>";
}
menuItem += "</li>";
menu = pullRight ? menuItem + menu : menu + menuItem;
}
}
toolbarMenu.html(menu);
toolbarMenu.find("[title=\"Lowercase\"]").attr("title", settings.lang.toolbar.lowercase);
toolbarMenu.find("[title=\"ucwords\"]").attr("title", settings.lang.toolbar.ucwords);
this.setToolbarHandler();
this.setToolbarAutoFixed();
return this;
},
/**
* 工具栏图标事件处理对象序列
* Get toolbar icons event handlers
*
* @param {Object} cm CodeMirror的实例对象
* @param {String} name 要获取的事件处理器名称
* @returns {Object} 返回处理对象序列
*/
dialogLockScreen : function() {
$.proxy(editormd.dialogLockScreen, this)();
return this;
},
dialogShowMask : function(dialog) {
$.proxy(editormd.dialogShowMask, this)(dialog);
return this;
},
getToolbarHandles : function(name) {
var toolbarHandlers = this.toolbarHandlers = editormd.toolbarHandlers;
return (name && typeof toolbarIconHandlers[name] !== "undefined") ? toolbarHandlers[name] : toolbarHandlers;
},
/**
* 工具栏图标事件处理器
* Bind toolbar icons event handle
*
* @returns {editormd} 返回editormd的实例对象
*/
setToolbarHandler : function() {
var _this = this;
var settings = this.settings;
if (!settings.toolbar || settings.readOnly) {
return this;
}
var toolbar = this.toolbar;
var cm = this.cm;
var classPrefix = this.classPrefix;
var toolbarIcons = this.toolbarIcons = toolbar.find("." + classPrefix + "menu > li > a");
var toolbarIconHandlers = this.getToolbarHandles();
toolbarIcons.bind(editormd.mouseOrTouch("click", "touchend"), function(event) {
var icon = $(this).children(".fa");
var name = icon.attr("name");
var cursor = cm.getCursor();
var selection = cm.getSelection();
if (name === "") {
return ;
}
_this.activeIcon = icon;
if (typeof toolbarIconHandlers[name] !== "undefined")
{
$.proxy(toolbarIconHandlers[name], _this)(cm);
}
else
{
if (typeof settings.toolbarHandlers[name] !== "undefined")
{
$.proxy(settings.toolbarHandlers[name], _this)(cm, icon, cursor, selection);
}
}
if (name !== "link" && name !== "reference-link" && name !== "image" && name !== "code-block" &&
name !== "preformatted-text" && name !== "watch" && name !== "preview" && name !== "search" && name !== "fullscreen" && name !== "info")
{
cm.focus();
}
return false;
});
return this;
},
/**
* 动态创建对话框
* Creating custom dialogs
*
* @param {Object} options 配置项键值对 Key/Value
* @returns {dialog} 返回创建的dialog的jQuery实例对象
*/
createDialog : function(options) {
return $.proxy(editormd.createDialog, this)(options);
},
/**
* 创建关于Editor.md的对话框
* Create about Editor.md dialog
*
* @returns {editormd} 返回editormd的实例对象
*/
createInfoDialog : function() {
var _this = this;
var editor = this.editor;
var classPrefix = this.classPrefix;
var infoDialogHTML = [
"<div class=\"" + classPrefix + "dialog " + classPrefix + "dialog-info\" style=\"\">",
"<div class=\"" + classPrefix + "dialog-container\">",
"<h1><i class=\"editormd-logo editormd-logo-lg editormd-logo-color\"></i> " + editormd.title + "<small>v" + editormd.version + "</small></h1>",
"<p>" + this.lang.description + "</p>",
"<p style=\"margin: 10px 0 20px 0;\"><a href=\"" + editormd.homePage + "\" target=\"_blank\">" + editormd.homePage + " <i class=\"fa fa-external-link\"></i></a></p>",
"<p style=\"font-size: 0.85em;\">Copyright © 2015 <a href=\"https://github.com/pandao\" target=\"_blank\" class=\"hover-link\">Pandao</a>, The <a href=\"https://github.com/pandao/editor.md/blob/master/LICENSE\" target=\"_blank\" class=\"hover-link\">MIT</a> License.</p>",
"</div>",
"<a href=\"javascript:;\" class=\"fa fa-close " + classPrefix + "dialog-close\"></a>",
"</div>"
].join("\n");
editor.append(infoDialogHTML);
var infoDialog = this.infoDialog = editor.children("." + classPrefix + "dialog-info");
infoDialog.find("." + classPrefix + "dialog-close").bind(editormd.mouseOrTouch("click", "touchend"), function() {
_this.hideInfoDialog();
});
infoDialog.css("border", (editormd.isIE8) ? "1px solid #ddd" : "").css("z-index", editormd.dialogZindex).show();
this.infoDialogPosition();
return this;
},
/**
* 关于Editor.md对话居中定位
* Editor.md dialog position handle
*
* @returns {editormd} 返回editormd的实例对象
*/
infoDialogPosition : function() {
var infoDialog = this.infoDialog;
var _infoDialogPosition = function() {
infoDialog.css({
top : ($(window).height() - infoDialog.height()) / 2 + "px",
left : ($(window).width() - infoDialog.width()) / 2 + "px"
});
};
_infoDialogPosition();
$(window).resize(_infoDialogPosition);
return this;
},
/**
* 显示关于Editor.md
* Display about Editor.md dialog
*
* @returns {editormd} 返回editormd的实例对象
*/
showInfoDialog : function() {
$("html,body").css("overflow-x", "hidden");
var _this = this;
var editor = this.editor;
var settings = this.settings;
var infoDialog = this.infoDialog = editor.children("." + this.classPrefix + "dialog-info");
if (infoDialog.length < 1)
{
this.createInfoDialog();
}
this.lockScreen(true);
this.mask.css({
opacity : settings.dialogMaskOpacity,
backgroundColor : settings.dialogMaskBgColor
}).show();
infoDialog.css("z-index", editormd.dialogZindex).show();
this.infoDialogPosition();
return this;
},
/**
* 隐藏关于Editor.md
* Hide about Editor.md dialog
*
* @returns {editormd} 返回editormd的实例对象
*/
hideInfoDialog : function() {
$("html,body").css("overflow-x", "");
this.infoDialog.hide();
this.mask.hide();
this.lockScreen(false);
return this;
},
/**
* 锁屏
* lock screen
*
* @param {Boolean} lock Boolean 布尔值,是否锁屏
* @returns {editormd} 返回editormd的实例对象
*/
lockScreen : function(lock) {
editormd.lockScreen(lock);
this.resize();
return this;
},
/**
* 编辑器界面重建,用于动态语言包或模块加载等
* Recreate editor
*
* @returns {editormd} 返回editormd的实例对象
*/
recreate : function() {
var _this = this;
var editor = this.editor;
var settings = this.settings;
this.codeMirror.remove();
this.setCodeMirror();
if (!settings.readOnly)
{
if (editor.find(".editormd-dialog").length > 0) {
editor.find(".editormd-dialog").remove();
}
if (settings.toolbar)
{
this.getToolbarHandles();
this.setToolbar();
}
}
this.loadedDisplay(true);
return this;
},
/**
* 高亮预览HTML的pre代码部分
* highlight of preview codes
*
* @returns {editormd} 返回editormd的实例对象
*/
previewCodeHighlight : function() {
var settings = this.settings;
var previewContainer = this.previewContainer;
if (settings.previewCodeHighlight)
{
previewContainer.find("pre").addClass("prettyprint linenums");
if (typeof prettyPrint !== "undefined")
{
prettyPrint();
}
}
return this;
},
/**
* 解析TeX(KaTeX)科学公式
* TeX(KaTeX) Renderer
*
* @returns {editormd} 返回editormd的实例对象
*/
katexRender : function() {
if (timer === null)
{
return this;
}
this.previewContainer.find("." + editormd.classNames.tex).each(function(){
var tex = $(this);
editormd.$katex.render(tex.text(), tex[0]);
tex.find(".katex").css("font-size", "1.6em");
});
return this;
},
/**
* 解析和渲染流程图及时序图
* FlowChart and SequenceDiagram Renderer
*
* @returns {editormd} 返回editormd的实例对象
*/
flowChartAndSequenceDiagramRender : function() {
var $this = this;
var settings = this.settings;
var previewContainer = this.previewContainer;
if (editormd.isIE8) {
return this;
}
if (settings.flowChart) {
if (flowchartTimer === null) {
return this;
}
previewContainer.find(".flowchart").flowChart();
}
if (settings.sequenceDiagram) {
previewContainer.find(".sequence-diagram").sequenceDiagram({theme: "simple"});
}
var preview = $this.preview;
var codeMirror = $this.codeMirror;
var codeView = codeMirror.find(".CodeMirror-scroll");
var height = codeView.height();
var scrollTop = codeView.scrollTop();
var percent = (scrollTop / codeView[0].scrollHeight);
var tocHeight = 0;
preview.find(".markdown-toc-list").each(function(){
tocHeight += $(this).height();
});
var tocMenuHeight = preview.find(".editormd-toc-menu").height();
tocMenuHeight = (!tocMenuHeight) ? 0 : tocMenuHeight;
if (scrollTop === 0)
{
preview.scrollTop(0);
}
else if (scrollTop + height >= codeView[0].scrollHeight - 16)
{
preview.scrollTop(preview[0].scrollHeight);
}
else
{
preview.scrollTop((preview[0].scrollHeight + tocHeight + tocMenuHeight) * percent);
}
return this;
},
/**
* 注册键盘快捷键处理
* Register CodeMirror keyMaps (keyboard shortcuts).
*
* @param {Object} keyMap KeyMap key/value {"(Ctrl/Shift/Alt)-Key" : function(){}}
* @returns {editormd} return this
*/
registerKeyMaps : function(keyMap) {
var _this = this;
var cm = this.cm;
var settings = this.settings;
var toolbarHandlers = editormd.toolbarHandlers;
var disabledKeyMaps = settings.disabledKeyMaps;
keyMap = keyMap || null;
if (keyMap)
{
for (var i in keyMap)
{
if ($.inArray(i, disabledKeyMaps) < 0)
{
var map = {};
map[i] = keyMap[i];
cm.addKeyMap(keyMap);
}
}
}
else
{
for (var k in editormd.keyMaps)
{
var _keyMap = editormd.keyMaps[k];
var handle = (typeof _keyMap === "string") ? $.proxy(toolbarHandlers[_keyMap], _this) : $.proxy(_keyMap, _this);
if ($.inArray(k, ["F9", "F10", "F11"]) < 0 && $.inArray(k, disabledKeyMaps) < 0)
{
var _map = {};
_map[k] = handle;
cm.addKeyMap(_map);
}
}
$(window).keydown(function(event) {
var keymaps = {
"120" : "F9",
"121" : "F10",
"122" : "F11"
};
if ( $.inArray(keymaps[event.keyCode], disabledKeyMaps) < 0 )
{
switch (event.keyCode)
{
case 120:
$.proxy(toolbarHandlers["watch"], _this)();
return false;
break;
case 121:
$.proxy(toolbarHandlers["preview"], _this)();
return false;
break;
case 122:
$.proxy(toolbarHandlers["fullscreen"], _this)();
return false;
break;
default:
break;
}
}
});
}
return this;
},
/**
* 绑定同步滚动
*
* @returns {editormd} return this
*/
bindScrollEvent : function() {
var _this = this;
var preview = this.preview;
var settings = this.settings;
var codeMirror = this.codeMirror;
var mouseOrTouch = editormd.mouseOrTouch;
if (!settings.syncScrolling) {
return this;
}
var cmBindScroll = function() {
codeMirror.find(".CodeMirror-scroll").bind(mouseOrTouch("scroll", "touchmove"), function(event) {
var height = $(this).height();
var scrollTop = $(this).scrollTop();
var percent = (scrollTop / $(this)[0].scrollHeight);
var tocHeight = 0;
preview.find(".markdown-toc-list").each(function(){
tocHeight += $(this).height();
});
var tocMenuHeight = preview.find(".editormd-toc-menu").height();
tocMenuHeight = (!tocMenuHeight) ? 0 : tocMenuHeight;
if (scrollTop === 0)
{
preview.scrollTop(0);
}
else if (scrollTop + height >= $(this)[0].scrollHeight - 16)
{
preview.scrollTop(preview[0].scrollHeight);
}
else
{
preview.scrollTop((preview[0].scrollHeight + tocHeight + tocMenuHeight) * percent);
}
$.proxy(settings.onscroll, _this)(event);
});
};
var cmUnbindScroll = function() {
codeMirror.find(".CodeMirror-scroll").unbind(mouseOrTouch("scroll", "touchmove"));
};
var previewBindScroll = function() {
preview.bind(mouseOrTouch("scroll", "touchmove"), function(event) {
var height = $(this).height();
var scrollTop = $(this).scrollTop();
var percent = (scrollTop / $(this)[0].scrollHeight);
var codeView = codeMirror.find(".CodeMirror-scroll");
if(scrollTop === 0)
{
codeView.scrollTop(0);
}
else if (scrollTop + height >= $(this)[0].scrollHeight)
{
codeView.scrollTop(codeView[0].scrollHeight);
}
else
{
codeView.scrollTop(codeView[0].scrollHeight * percent);
}
$.proxy(settings.onpreviewscroll, _this)(event);
});
};
var previewUnbindScroll = function() {
preview.unbind(mouseOrTouch("scroll", "touchmove"));
};
codeMirror.bind({
mouseover : cmBindScroll,
mouseout : cmUnbindScroll,
touchstart : cmBindScroll,
touchend : cmUnbindScroll
});
if (settings.syncScrolling === "single") {
return this;
}
preview.bind({
mouseover : previewBindScroll,
mouseout : previewUnbindScroll,
touchstart : previewBindScroll,
touchend : previewUnbindScroll
});
return this;
},
bindChangeEvent : function() {
var _this = this;
var cm = this.cm;
var settings = this.settings;
if (!settings.syncScrolling) {
return this;
}
cm.on("change", function(_cm, changeObj) {
if (settings.watch)
{
_this.previewContainer.css("padding", settings.autoHeight ? "20px 20px 50px 40px" : "20px");
}
timer = setTimeout(function() {
clearTimeout(timer);
_this.save();
timer = null;
}, settings.delay);
});
return this;
},
/**
* 加载队列完成之后的显示处理
* Display handle of the module queues loaded after.
*
* @param {Boolean} recreate 是否为重建编辑器
* @returns {editormd} 返回editormd的实例对象
*/
loadedDisplay : function(recreate) {
recreate = recreate || false;
var _this = this;
var editor = this.editor;
var preview = this.preview;
var settings = this.settings;
this.containerMask.hide();
this.save();
if (settings.watch) {
preview.show();
}
editor.data("oldWidth", editor.width()).data("oldHeight", editor.height()); // 为了兼容Zepto
this.resize();
this.registerKeyMaps();
$(window).resize(function(){
_this.resize();
});
this.bindScrollEvent().bindChangeEvent();
if (!recreate)
{
$.proxy(settings.onload, this)();
}
this.state.loaded = true;
return this;
},
/**
* 设置编辑器的宽度
* Set editor width
*
* @param {Number|String} width 编辑器宽度值
* @returns {editormd} 返回editormd的实例对象
*/
width : function(width) {
this.editor.css("width", (typeof width === "number") ? width + "px" : width);
this.resize();
return this;
},
/**
* 设置编辑器的高度
* Set editor height
*
* @param {Number|String} height 编辑器高度值
* @returns {editormd} 返回editormd的实例对象
*/
height : function(height) {
this.editor.css("height", (typeof height === "number") ? height + "px" : height);
this.resize();
return this;
},
/**
* 调整编辑器的尺寸和布局
* Resize editor layout
*
* @param {Number|String} [width=null] 编辑器宽度值
* @param {Number|String} [height=null] 编辑器高度值
* @returns {editormd} 返回editormd的实例对象
*/
resize : function(width, height) {
width = width || null;
height = height || null;
var state = this.state;
var editor = this.editor;
var preview = this.preview;
var toolbar = this.toolbar;
var settings = this.settings;
var codeMirror = this.codeMirror;
if (width)
{
editor.css("width", (typeof width === "number") ? width + "px" : width);
}
if (settings.autoHeight && !state.fullscreen && !state.preview)
{
editor.css("height", "auto");
codeMirror.css("height", "auto");
}
else
{
if (height)
{
editor.css("height", (typeof height === "number") ? height + "px" : height);
}
if (state.fullscreen)
{
editor.height($(window).height());
}
if (settings.toolbar && !settings.readOnly)
{
codeMirror.css("margin-top", toolbar.height() + 1).height(editor.height() - toolbar.height());
}
else
{
codeMirror.css("margin-top", 0).height(editor.height());
}
}
if(settings.watch)
{
codeMirror.width(editor.width() / 2);
preview.width((!state.preview) ? editor.width() / 2 : editor.width());
this.previewContainer.css("padding", settings.autoHeight ? "20px 20px 50px 40px" : "20px");
if (settings.toolbar && !settings.readOnly)
{
preview.css("top", toolbar.height() + 1);
}
else
{
preview.css("top", 0);
}
if (settings.autoHeight && !state.fullscreen && !state.preview)
{
preview.height("");
}
else
{
var previewHeight = (settings.toolbar && !settings.readOnly) ? editor.height() - toolbar.height() : editor.height();
preview.height(previewHeight);
}
}
else
{
codeMirror.width(editor.width());
preview.hide();
}
if (state.loaded)
{
$.proxy(settings.onresize, this)();
}
return this;
},
/**
* 解析和保存Markdown代码
* Parse & Saving Markdown source code
*
* @returns {editormd} 返回editormd的实例对象
*/
save : function() {
if (timer === null)
{
return this;
}
var _this = this;
var state = this.state;
var settings = this.settings;
var cm = this.cm;
var cmValue = cm.getValue();
var previewContainer = this.previewContainer;
if (settings.mode !== "gfm" && settings.mode !== "markdown")
{
this.markdownTextarea.val(cmValue);
return this;
}
var marked = editormd.$marked;
var markdownToC = this.markdownToC = [];
var rendererOptions = this.markedRendererOptions = {
toc : settings.toc,
tocm : settings.tocm,
tocStartLevel : settings.tocStartLevel,
pageBreak : settings.pageBreak,
taskList : settings.taskList,
emoji : settings.emoji,
tex : settings.tex,
atLink : settings.atLink, // for @link
emailLink : settings.emailLink, // for mail address auto link
flowChart : settings.flowChart,
sequenceDiagram : settings.sequenceDiagram,
previewCodeHighlight : settings.previewCodeHighlight,
};
var markedOptions = this.markedOptions = {
renderer : editormd.markedRenderer(markdownToC, rendererOptions),
gfm : true,
tables : true,
breaks : true,
pedantic : false,
sanitize : (settings.htmlDecode) ? false : true, // 关闭忽略HTML标签,即开启识别HTML标签,默认为false
smartLists : true,
smartypants : true
};
marked.setOptions(markedOptions);
var newMarkdownDoc = editormd.$marked(cmValue, markedOptions);
//console.info("cmValue", cmValue, newMarkdownDoc);
newMarkdownDoc = editormd.filterHTMLTags(newMarkdownDoc, settings.htmlDecode);
//console.error("cmValue", cmValue, newMarkdownDoc);
this.markdownTextarea.text(cmValue);
cm.save();
if (settings.saveHTMLToTextarea)
{
this.htmlTextarea.text(newMarkdownDoc);
}
if(settings.watch || (!settings.watch && state.preview))
{
previewContainer.html(newMarkdownDoc);
this.previewCodeHighlight();
if (settings.toc)
{
var tocContainer = (settings.tocContainer === "") ? previewContainer : $(settings.tocContainer);
var tocMenu = tocContainer.find("." + this.classPrefix + "toc-menu");
tocContainer.attr("previewContainer", (settings.tocContainer === "") ? "true" : "false");
if (settings.tocContainer !== "" && tocMenu.length > 0)
{
tocMenu.remove();
}
editormd.markdownToCRenderer(markdownToC, tocContainer, settings.tocDropdown, settings.tocStartLevel);
if (settings.tocDropdown || tocContainer.find("." + this.classPrefix + "toc-menu").length > 0)
{
editormd.tocDropdownMenu(tocContainer, (settings.tocTitle !== "") ? settings.tocTitle : this.lang.tocTitle);
}
if (settings.tocContainer !== "")
{
previewContainer.find(".markdown-toc").css("border", "none");
}
}
if (settings.tex)
{
if (!editormd.kaTeXLoaded && settings.autoLoadModules)
{
editormd.loadKaTeX(function() {
editormd.$katex = katex;
editormd.kaTeXLoaded = true;
_this.katexRender();
});
}
else
{
editormd.$katex = katex;
this.katexRender();
}
}
if (settings.flowChart || settings.sequenceDiagram)
{
flowchartTimer = setTimeout(function(){
clearTimeout(flowchartTimer);
_this.flowChartAndSequenceDiagramRender();
flowchartTimer = null;
}, 10);
}
if (state.loaded)
{
$.proxy(settings.onchange, this)();
}
}
return this;
},
/**
* 聚焦光标位置
* Focusing the cursor position
*
* @returns {editormd} 返回editormd的实例对象
*/
focus : function() {
this.cm.focus();
return this;
},
/**
* 设置光标的位置
* Set cursor position
*
* @param {Object} cursor 要设置的光标位置键值对象,例:{line:1, ch:0}
* @returns {editormd} 返回editormd的实例对象
*/
setCursor : function(cursor) {
this.cm.setCursor(cursor);
return this;
},
/**
* 获取当前光标的位置
* Get the current position of the cursor
*
* @returns {Cursor} 返回一个光标Cursor对象
*/
getCursor : function() {
return this.cm.getCursor();
},
/**
* 设置光标选中的范围
* Set cursor selected ranges
*
* @param {Object} from 开始位置的光标键值对象,例:{line:1, ch:0}
* @param {Object} to 结束位置的光标键值对象,例:{line:1, ch:0}
* @returns {editormd} 返回editormd的实例对象
*/
setSelection : function(from, to) {
this.cm.setSelection(from, to);
return this;
},
/**
* 获取光标选中的文本
* Get the texts from cursor selected
*
* @returns {String} 返回选中文本的字符串形式
*/
getSelection : function() {
return this.cm.getSelection();
},
/**
* 设置光标选中的文本范围
* Set the cursor selection ranges
*
* @param {Array} ranges cursor selection ranges array
* @returns {Array} return this
*/
setSelections : function(ranges) {
this.cm.setSelections(ranges);
return this;
},
/**
* 获取光标选中的文本范围
* Get the cursor selection ranges
*
* @returns {Array} return selection ranges array
*/
getSelections : function() {
return this.cm.getSelections();
},
/**
* 替换当前光标选中的文本或在当前光标处插入新字符
* Replace the text at the current cursor selected or insert a new character at the current cursor position
*
* @param {String} value 要插入的字符值
* @returns {editormd} 返回editormd的实例对象
*/
replaceSelection : function(value) {
this.cm.replaceSelection(value);
return this;
},
/**
* 在当前光标处插入新字符
* Insert a new character at the current cursor position
*
* 同replaceSelection()方法
* With the replaceSelection() method
*
* @param {String} value 要插入的字符值
* @returns {editormd} 返回editormd的实例对象
*/
insertValue : function(value) {
this.replaceSelection(value);
return this;
},
/**
* 追加markdown
* append Markdown to editor
*
* @param {String} md 要追加的markdown源文档
* @returns {editormd} 返回editormd的实例对象
*/
appendMarkdown : function(md) {
var settings = this.settings;
var cm = this.cm;
cm.setValue(cm.getValue() + md);
return this;
},
/**
* 设置和传入编辑器的markdown源文档
* Set Markdown source document
*
* @param {String} md 要传入的markdown源文档
* @returns {editormd} 返回editormd的实例对象
*/
setMarkdown : function(md) {
this.cm.setValue(md || this.settings.markdown);
return this;
},
/**
* 获取编辑器的markdown源文档
* Set Editor.md markdown/CodeMirror value
*
* @returns {editormd} 返回editormd的实例对象
*/
getMarkdown : function() {
return this.cm.getValue();
},
/**
* 获取编辑器的源文档
* Get CodeMirror value
*
* @returns {editormd} 返回editormd的实例对象
*/
getValue : function() {
return this.cm.getValue();
},
/**
* 设置编辑器的源文档
* Set CodeMirror value
*
* @param {String} value set code/value/string/text
* @returns {editormd} 返回editormd的实例对象
*/
setValue : function(value) {
this.cm.setValue(value);
return this;
},
/**
* 清空编辑器
* Empty CodeMirror editor container
*
* @returns {editormd} 返回editormd的实例对象
*/
clear : function() {
this.cm.setValue("");
return this;
},
/**
* 获取解析后存放在Textarea的HTML源码
* Get parsed html code from Textarea
*
* @returns {String} 返回HTML源码
*/
getHTML : function() {
if (!this.settings.saveHTMLToTextarea)
{
alert("Error: settings.saveHTMLToTextarea == false");
return false;
}
return this.htmlTextarea.val();
},
/**
* getHTML()的别名
* getHTML (alias)
*
* @returns {String} Return html code 返回HTML源码
*/
getTextareaSavedHTML : function() {
return this.getHTML();
},
/**
* 获取预览窗口的HTML源码
* Get html from preview container
*
* @returns {editormd} 返回editormd的实例对象
*/
getPreviewedHTML : function() {
if (!this.settings.watch)
{
alert("Error: settings.watch == false");
return false;
}
return this.previewContainer.html();
},
/**
* 开启实时预览
* Enable real-time watching
*
* @returns {editormd} 返回editormd的实例对象
*/
watch : function(callback) {
var settings = this.settings;
if ($.inArray(settings.mode, ["gfm", "markdown"]) < 0)
{
return this;
}
this.state.watching = settings.watch = true;
this.preview.show();
if (this.toolbar)
{
var watchIcon = settings.toolbarIconsClass.watch;
var unWatchIcon = settings.toolbarIconsClass.unwatch;
var icon = this.toolbar.find(".fa[name=watch]");
icon.parent().attr("title", settings.lang.toolbar.watch);
icon.removeClass(unWatchIcon).addClass(watchIcon);
}
this.codeMirror.css("border-right", "1px solid #ddd").width(this.editor.width() / 2);
timer = 0;
this.save().resize();
if (!settings.onwatch)
{
settings.onwatch = callback || function() {};
}
$.proxy(settings.onwatch, this)();
return this;
},
/**
* 关闭实时预览
* Disable real-time watching
*
* @returns {editormd} 返回editormd的实例对象
*/
unwatch : function(callback) {
var settings = this.settings;
this.state.watching = settings.watch = false;
this.preview.hide();
if (this.toolbar)
{
var watchIcon = settings.toolbarIconsClass.watch;
var unWatchIcon = settings.toolbarIconsClass.unwatch;
var icon = this.toolbar.find(".fa[name=watch]");
icon.parent().attr("title", settings.lang.toolbar.unwatch);
icon.removeClass(watchIcon).addClass(unWatchIcon);
}
this.codeMirror.css("border-right", "none").width(this.editor.width());
this.resize();
if (!settings.onunwatch)
{
settings.onunwatch = callback || function() {};
}
$.proxy(settings.onunwatch, this)();
return this;
},
/**
* 显示编辑器
* Show editor
*
* @param {Function} [callback=function()] 回调函数
* @returns {editormd} 返回editormd的实例对象
*/
show : function(callback) {
callback = callback || function() {};
var _this = this;
this.editor.show(0, function() {
$.proxy(callback, _this)();
});
return this;
},
/**
* 隐藏编辑器
* Hide editor
*
* @param {Function} [callback=function()] 回调函数
* @returns {editormd} 返回editormd的实例对象
*/
hide : function(callback) {
callback = callback || function() {};
var _this = this;
this.editor.hide(0, function() {
$.proxy(callback, _this)();
});
return this;
},
/**
* 隐藏编辑器部分,只预览HTML
* Enter preview html state
*
* @returns {editormd} 返回editormd的实例对象
*/
previewing : function() {
var _this = this;
var editor = this.editor;
var preview = this.preview;
var toolbar = this.toolbar;
var settings = this.settings;
var codeMirror = this.codeMirror;
var previewContainer = this.previewContainer;
if ($.inArray(settings.mode, ["gfm", "markdown"]) < 0) {
return this;
}
if (settings.toolbar && toolbar) {
toolbar.toggle();
toolbar.find(".fa[name=preview]").toggleClass("active");
}
codeMirror.toggle();
var escHandle = function(event) {
if (event.shiftKey && event.keyCode === 27) {
_this.previewed();
}
};
if (codeMirror.css("display") === "none") // 为了兼容Zepto,而不使用codeMirror.is(":hidden")
{
this.state.preview = true;
if (this.state.fullscreen) {
preview.css("background", "#fff");
}
editor.find("." + this.classPrefix + "preview-close-btn").show().bind(editormd.mouseOrTouch("click", "touchend"), function(){
_this.previewed();
});
if (!settings.watch)
{
this.save();
}
else
{
previewContainer.css("padding", "");
}
previewContainer.addClass(this.classPrefix + "preview-active");
preview.show().css({
position : "",
top : 0,
width : editor.width(),
height : (settings.autoHeight && !this.state.fullscreen) ? "auto" : editor.height()
});
if (this.state.loaded)
{
$.proxy(settings.onpreviewing, this)();
}
$(window).bind("keyup", escHandle);
}
else
{
$(window).unbind("keyup", escHandle);
this.previewed();
}
},
/**
* 显示编辑器部分,退出只预览HTML
* Exit preview html state
*
* @returns {editormd} 返回editormd的实例对象
*/
previewed : function() {
var editor = this.editor;
var preview = this.preview;
var toolbar = this.toolbar;
var settings = this.settings;
var previewContainer = this.previewContainer;
var previewCloseBtn = editor.find("." + this.classPrefix + "preview-close-btn");
this.state.preview = false;
this.codeMirror.show();
if (settings.toolbar) {
toolbar.show();
}
preview[(settings.watch) ? "show" : "hide"]();
previewCloseBtn.hide().unbind(editormd.mouseOrTouch("click", "touchend"));
previewContainer.removeClass(this.classPrefix + "preview-active");
if (settings.watch)
{
previewContainer.css("padding", "20px");
}
preview.css({
background : null,
position : "absolute",
width : editor.width() / 2,
height : (settings.autoHeight && !this.state.fullscreen) ? "auto" : editor.height() - toolbar.height(),
top : (settings.toolbar) ? toolbar.height() : 0
});
if (this.state.loaded)
{
$.proxy(settings.onpreviewed, this)();
}
return this;
},
/**
* 编辑器全屏显示
* Fullscreen show
*
* @returns {editormd} 返回editormd的实例对象
*/
fullscreen : function() {
var _this = this;
var state = this.state;
var editor = this.editor;
var preview = this.preview;
var toolbar = this.toolbar;
var settings = this.settings;
var fullscreenClass = this.classPrefix + "fullscreen";
if (toolbar) {
toolbar.find(".fa[name=fullscreen]").parent().toggleClass("active");
}
var escHandle = function(event) {
if (!event.shiftKey && event.keyCode === 27)
{
if (state.fullscreen)
{
_this.fullscreenExit();
}
}
};
if (!editor.hasClass(fullscreenClass))
{
state.fullscreen = true;
$("html,body").css("overflow", "hidden");
editor.css({
width : $(window).width(),
height : $(window).height()
}).addClass(fullscreenClass);
this.resize();
$.proxy(settings.onfullscreen, this)();
$(window).bind("keyup", escHandle);
}
else
{
$(window).unbind("keyup", escHandle);
this.fullscreenExit();
}
return this;
},
/**
* 编辑器退出全屏显示
* Exit fullscreen state
*
* @returns {editormd} 返回editormd的实例对象
*/
fullscreenExit : function() {
var editor = this.editor;
var settings = this.settings;
var toolbar = this.toolbar;
var fullscreenClass = this.classPrefix + "fullscreen";
this.state.fullscreen = false;
if (toolbar) {
toolbar.find(".fa[name=fullscreen]").parent().removeClass("active");
}
$("html,body").css("overflow", "");
editor.css({
width : editor.data("oldWidth"),
height : editor.data("oldHeight")
}).removeClass(fullscreenClass);
this.resize();
$.proxy(settings.onfullscreenExit, this)();
return this;
},
/**
* 加载并执行插件
* Load and execute the plugin
*
* @param {String} name plugin name / function name
* @param {String} path plugin load path
* @returns {editormd} 返回editormd的实例对象
*/
executePlugin : function(name, path) {
var _this = this;
var cm = this.cm;
var settings = this.settings;
path = settings.pluginPath + path;
if (typeof define === "function")
{
if (typeof this[name] === "undefined")
{
alert("Error: " + name + " plugin is not found, you are not load this plugin.");
return this;
}
this[name](cm);
return this;
}
if ($.inArray(path, editormd.loadFiles.plugin) < 0)
{
editormd.loadPlugin(path, function() {
editormd.loadPlugins[name] = _this[name];
_this[name](cm);
});
}
else
{
$.proxy(editormd.loadPlugins[name], this)(cm);
}
return this;
},
/**
* 搜索替换
* Search & replace
*
* @param {String} command CodeMirror serach commands, "find, fintNext, fintPrev, clearSearch, replace, replaceAll"
* @returns {editormd} return this
*/
search : function(command) {
var settings = this.settings;
if (!settings.searchReplace)
{
alert("Error: settings.searchReplace == false");
return this;
}
if (!settings.readOnly)
{
this.cm.execCommand(command || "find");
}
return this;
},
searchReplace : function() {
this.search("replace");
return this;
},
searchReplaceAll : function() {
this.search("replaceAll");
return this;
}
};
editormd.fn.init.prototype = editormd.fn;
/**
* 锁屏
* lock screen when dialog opening
*
* @returns {void}
*/
editormd.dialogLockScreen = function() {
var settings = this.settings || {dialogLockScreen : true};
if (settings.dialogLockScreen)
{
$("html,body").css("overflow", "hidden");
this.resize();
}
};
/**
* 显示透明背景层
* Display mask layer when dialog opening
*
* @param {Object} dialog dialog jQuery object
* @returns {void}
*/
editormd.dialogShowMask = function(dialog) {
var editor = this.editor;
var settings = this.settings || {dialogShowMask : true};
dialog.css({
top : ($(window).height() - dialog.height()) / 2 + "px",
left : ($(window).width() - dialog.width()) / 2 + "px"
});
if (settings.dialogShowMask) {
editor.children("." + this.classPrefix + "mask").css("z-index", parseInt(dialog.css("z-index")) - 1).show();
}
};
editormd.toolbarHandlers = {
undo : function() {
this.cm.undo();
},
redo : function() {
this.cm.redo();
},
bold : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
cm.replaceSelection("**" + selection + "**");
if(selection === "") {
cm.setCursor(cursor.line, cursor.ch + 2);
}
},
del : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
cm.replaceSelection("~~" + selection + "~~");
if(selection === "") {
cm.setCursor(cursor.line, cursor.ch + 2);
}
},
italic : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
cm.replaceSelection("*" + selection + "*");
if(selection === "") {
cm.setCursor(cursor.line, cursor.ch + 1);
}
},
quote : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
if (cursor.ch !== 0)
{
cm.setCursor(cursor.line, 0);
cm.replaceSelection("> " + selection);
cm.setCursor(cursor.line, cursor.ch + 2);
}
else
{
cm.replaceSelection("> " + selection);
}
//cm.replaceSelection("> " + selection);
//cm.setCursor(cursor.line, (selection === "") ? cursor.ch + 2 : cursor.ch + selection.length + 2);
},
ucfirst : function() {
var cm = this.cm;
var selection = cm.getSelection();
var selections = cm.listSelections();
cm.replaceSelection(editormd.firstUpperCase(selection));
cm.setSelections(selections);
},
ucwords : function() {
var cm = this.cm;
var selection = cm.getSelection();
var selections = cm.listSelections();
cm.replaceSelection(editormd.wordsFirstUpperCase(selection));
cm.setSelections(selections);
},
uppercase : function() {
var cm = this.cm;
var selection = cm.getSelection();
var selections = cm.listSelections();
cm.replaceSelection(selection.toUpperCase());
cm.setSelections(selections);
},
lowercase : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
var selections = cm.listSelections();
cm.replaceSelection(selection.toLowerCase());
cm.setSelections(selections);
},
h1 : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
if (cursor.ch !== 0)
{
cm.setCursor(cursor.line, 0);
cm.replaceSelection("# " + selection);
cm.setCursor(cursor.line, cursor.ch + 2);
}
else
{
cm.replaceSelection("# " + selection);
}
},
h2 : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
if (cursor.ch !== 0)
{
cm.setCursor(cursor.line, 0);
cm.replaceSelection("## " + selection);
cm.setCursor(cursor.line, cursor.ch + 3);
}
else
{
cm.replaceSelection("## " + selection);
}
},
h3 : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
if (cursor.ch !== 0)
{
cm.setCursor(cursor.line, 0);
cm.replaceSelection("### " + selection);
cm.setCursor(cursor.line, cursor.ch + 4);
}
else
{
cm.replaceSelection("### " + selection);
}
},
h4 : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
if (cursor.ch !== 0)
{
cm.setCursor(cursor.line, 0);
cm.replaceSelection("#### " + selection);
cm.setCursor(cursor.line, cursor.ch + 5);
}
else
{
cm.replaceSelection("#### " + selection);
}
},
h5 : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
if (cursor.ch !== 0)
{
cm.setCursor(cursor.line, 0);
cm.replaceSelection("##### " + selection);
cm.setCursor(cursor.line, cursor.ch + 6);
}
else
{
cm.replaceSelection("##### " + selection);
}
},
h6 : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
if (cursor.ch !== 0)
{
cm.setCursor(cursor.line, 0);
cm.replaceSelection("###### " + selection);
cm.setCursor(cursor.line, cursor.ch + 7);
}
else
{
cm.replaceSelection("###### " + selection);
}
},
"list-ul" : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
if (selection === "")
{
cm.replaceSelection("- " + selection);
}
else
{
var selectionText = selection.split("\n");
for (var i = 0, len = selectionText.length; i < len; i++)
{
selectionText[i] = (selectionText[i] === "") ? "" : "- " + selectionText[i];
}
cm.replaceSelection(selectionText.join("\n"));
}
},
"list-ol" : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
if(selection === "")
{
cm.replaceSelection("1. " + selection);
}
else
{
var selectionText = selection.split("\n");
for (var i = 0, len = selectionText.length; i < len; i++)
{
selectionText[i] = (selectionText[i] === "") ? "" : (i+1) + ". " + selectionText[i];
}
cm.replaceSelection(selectionText.join("\n"));
}
},
hr : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
cm.replaceSelection(((cursor.ch !== 0) ? "\n\n" : "\n") + "------------\n\n");
},
tex : function() {
if (!this.settings.tex)
{
alert("settings.tex === false");
return this;
}
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
cm.replaceSelection("$$" + selection + "$$");
if(selection === "") {
cm.setCursor(cursor.line, cursor.ch + 2);
}
},
link : function() {
this.executePlugin("linkDialog", "link-dialog/link-dialog");
},
"reference-link" : function() {
this.executePlugin("referenceLinkDialog", "reference-link-dialog/reference-link-dialog");
},
pagebreak : function() {
if (!this.settings.pageBreak)
{
alert("settings.pageBreak === false");
return this;
}
var cm = this.cm;
var selection = cm.getSelection();
cm.replaceSelection("\r\n[========]\r\n");
},
image : function() {
this.executePlugin("imageDialog", "image-dialog/image-dialog");
},
code : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
cm.replaceSelection("`" + selection + "`");
if (selection === "") {
cm.setCursor(cursor.line, cursor.ch + 1);
}
},
"code-block" : function() {
this.executePlugin("codeBlockDialog", "code-block-dialog/code-block-dialog");
},
"preformatted-text" : function() {
this.executePlugin("preformattedTextDialog", "preformatted-text-dialog/preformatted-text-dialog");
},
table : function() {
this.executePlugin("tableDialog", "table-dialog/table-dialog");
},
datetime : function() {
var cm = this.cm;
var selection = cm.getSelection();
var date = new Date();
var langName = this.settings.lang.name;
var datefmt = editormd.dateFormat() + " " + editormd.dateFormat((langName === "zh-cn" || langName === "zh-tw") ? "cn-week-day" : "week-day");
cm.replaceSelection(datefmt);
},
emoji : function() {
this.executePlugin("emojiDialog", "emoji-dialog/emoji-dialog");
},
"html-entities" : function() {
this.executePlugin("htmlEntitiesDialog", "html-entities-dialog/html-entities-dialog");
},
"goto-line" : function() {
this.executePlugin("gotoLineDialog", "goto-line-dialog/goto-line-dialog");
},
watch : function() {
this[this.settings.watch ? "unwatch" : "watch"]();
},
preview : function() {
this.previewing();
},
fullscreen : function() {
this.fullscreen();
},
clear : function() {
this.clear();
},
search : function() {
this.search();
},
help : function() {
this.executePlugin("helpDialog", "help-dialog/help-dialog");
},
info : function() {
this.showInfoDialog();
}
};
editormd.keyMaps = {
"Ctrl-1" : "h1",
"Ctrl-2" : "h2",
"Ctrl-3" : "h3",
"Ctrl-4" : "h4",
"Ctrl-5" : "h5",
"Ctrl-6" : "h6",
"Ctrl-B" : "bold", // if this is string == editormd.toolbarHandlers.xxxx
"Ctrl-D" : "datetime",
"Ctrl-E" : function() { // emoji
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
if (!this.settings.emoji)
{
alert("Error: settings.emoji == false");
return ;
}
cm.replaceSelection(":" + selection + ":");
if (selection === "") {
cm.setCursor(cursor.line, cursor.ch + 1);
}
},
"Ctrl-Alt-G" : "goto-line",
"Ctrl-H" : "hr",
"Ctrl-I" : "italic",
"Ctrl-K" : "code",
"Ctrl-L" : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
var title = (selection === "") ? "" : " \""+selection+"\"";
cm.replaceSelection("[" + selection + "]("+title+")");
if (selection === "") {
cm.setCursor(cursor.line, cursor.ch + 1);
}
},
"Ctrl-U" : "list-ul",
"Shift-Ctrl-A" : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
if (!this.settings.atLink)
{
alert("Error: settings.atLink == false");
return ;
}
cm.replaceSelection("@" + selection);
if (selection === "") {
cm.setCursor(cursor.line, cursor.ch + 1);
}
},
"Shift-Ctrl-C" : "code",
"Shift-Ctrl-Q" : "quote",
"Shift-Ctrl-S" : "del",
"Shift-Ctrl-K" : "tex", // KaTeX
"Shift-Alt-C" : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
cm.replaceSelection(["```", selection, "```"].join("\n"));
if (selection === "") {
cm.setCursor(cursor.line, cursor.ch + 3);
}
},
"Shift-Ctrl-Alt-C" : "code-block",
"Shift-Ctrl-H" : "html-entities",
"Shift-Alt-H" : "help",
"Shift-Ctrl-E" : "emoji",
"Shift-Ctrl-U" : "uppercase",
"Shift-Alt-U" : "ucwords",
"Shift-Ctrl-Alt-U" : "ucfirst",
"Shift-Alt-L" : "lowercase",
"Shift-Ctrl-I" : function() {
var cm = this.cm;
var cursor = cm.getCursor();
var selection = cm.getSelection();
var title = (selection === "") ? "" : " \""+selection+"\"";
cm.replaceSelection("![" + selection + "]("+title+")");
if (selection === "") {
cm.setCursor(cursor.line, cursor.ch + 4);
}
},
"Shift-Ctrl-Alt-I" : "image",
"Shift-Ctrl-L" : "link",
"Shift-Ctrl-O" : "list-ol",
"Shift-Ctrl-P" : "preformatted-text",
"Shift-Ctrl-T" : "table",
"Shift-Alt-P" : "pagebreak",
"F9" : "watch",
"F10" : "preview",
"F11" : "fullscreen",
};
/**
* 清除字符串两边的空格
* Clear the space of strings both sides.
*
* @param {String} str string
* @returns {String} trimed string
*/
var trim = function(str) {
return (!String.prototype.trim) ? str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "") : str.trim();
};
editormd.trim = trim;
/**
* 所有单词首字母大写
* Words first to uppercase
*
* @param {String} str string
* @returns {String} string
*/
var ucwords = function (str) {
return str.toLowerCase().replace(/\b(\w)|\s(\w)/g, function($1) {
return $1.toUpperCase();
});
};
editormd.ucwords = editormd.wordsFirstUpperCase = ucwords;
/**
* 字符串首字母大写
* Only string first char to uppercase
*
* @param {String} str string
* @returns {String} string
*/
var firstUpperCase = function(str) {
return str.toLowerCase().replace(/\b(\w)/, function($1){
return $1.toUpperCase();
});
};
var ucfirst = firstUpperCase;
editormd.firstUpperCase = editormd.ucfirst = firstUpperCase;
editormd.urls = {
atLinkBase : "https://github.com/"
};
editormd.regexs = {
atLink : /@(\w+)/g,
email : /(\w+)@(\w+)\.(\w+)\.?(\w+)?/g,
emailLink : /(mailto:)?([\w\.\_]+)@(\w+)\.(\w+)\.?(\w+)?/g,
emoji : /:([\w\+-]+):/g,
emojiDatetime : /(\d{2}:\d{2}:\d{2})/g,
twemoji : /:(tw-([\w]+)-?(\w+)?):/g,
fontAwesome : /:(fa-([\w]+)(-(\w+)){0,}):/g,
editormdLogo : /:(editormd-logo-?(\w+)?):/g,
pageBreak : /^\[[=]{8,}\]$/
};
// Emoji graphics files url path
editormd.emoji = {
//path : "http://www.emoji-cheat-sheet.com/graphics/emojis/",
path : "/plugins/editormd/plugins/emoji-dialog/emoji/",
ext : ".png"
};
// Twitter Emoji (Twemoji) graphics files url path
editormd.twemoji = {
path : "http://twemoji.maxcdn.com/36x36/",
ext : ".png"
};
/**
* 自定义marked的解析器
* Custom Marked renderer rules
*
* @param {Array} markdownToC 传入用于接收TOC的数组
* @returns {Renderer} markedRenderer 返回marked的Renderer自定义对象
*/
editormd.markedRenderer = function(markdownToC, options) {
var defaults = {
toc : true, // Table of contents
tocm : false,
tocStartLevel : 1, // Said from H1 to create ToC
pageBreak : true,
atLink : true, // for @link
emailLink : true, // for mail address auto link
taskList : false, // Enable Github Flavored Markdown task lists
emoji : false, // :emoji: , Support Twemoji, fontAwesome, Editor.md logo emojis.
tex : false, // TeX(LaTeX), based on KaTeX
flowChart : false, // flowChart.js only support IE9+
sequenceDiagram : false, // sequenceDiagram.js only support IE9+
};
var settings = $.extend(defaults, options || {});
var marked = editormd.$marked;
var markedRenderer = new marked.Renderer();
markdownToC = markdownToC || [];
var regexs = editormd.regexs;
var atLinkReg = regexs.atLink;
var emojiReg = regexs.emoji;
var emailReg = regexs.email;
var emailLinkReg = regexs.emailLink;
var twemojiReg = regexs.twemoji;
var faIconReg = regexs.fontAwesome;
var editormdLogoReg = regexs.editormdLogo;
var pageBreakReg = regexs.pageBreak;
markedRenderer.emoji = function(text) {
text = text.replace(editormd.regexs.emojiDatetime, function($1) {
return $1.replace(/:/g, ":");
});
var matchs = text.match(emojiReg);
if (!matchs || !settings.emoji) {
return text;
}
for (var i = 0, len = matchs.length; i < len; i++)
{
if (matchs[i] === ":+1:") {
matchs[i] = ":\\+1:";
}
text = text.replace(new RegExp(matchs[i]), function($1, $2){
var faMatchs = $1.match(faIconReg);
var name = $1.replace(/:/g, "");
if (faMatchs)
{
for (var fa = 0, len1 = faMatchs.length; fa < len1; fa++)
{
var faName = faMatchs[fa].replace(/:/g, "");
return "<i class=\"fa " + faName + " fa-emoji\" title=\"" + faName.replace("fa-", "") + "\"></i>";
}
}
else
{
var emdlogoMathcs = $1.match(editormdLogoReg);
var twemojiMatchs = $1.match(twemojiReg);
if (emdlogoMathcs)
{
for (var x = 0, len2 = emdlogoMathcs.length; x < len2; x++)
{
var logoName = emdlogoMathcs[x].replace(/:/g, "");
return "<i class=\"" + logoName + "\" title=\"Editor.md logo (" + logoName + ")\"></i>";
}
}
else if (twemojiMatchs)
{
for (var t = 0, len3 = twemojiMatchs.length; t < len3; t++)
{
var twe = twemojiMatchs[t].replace(/:/g, "").replace("tw-", "");
return "<img src=\"" + editormd.twemoji.path + twe + editormd.twemoji.ext + "\" title=\"twemoji-" + twe + "\" alt=\"twemoji-" + twe + "\" class=\"emoji twemoji\" />";
}
}
else
{
var src = (name === "+1") ? "plus1" : name;
src = (src === "black_large_square") ? "black_square" : src;
src = (src === "moon") ? "waxing_gibbous_moon" : src;
return "<img src=\"" + editormd.emoji.path + src + editormd.emoji.ext + "\" class=\"emoji\" title=\":" + name + ":\" alt=\":" + name + ":\" />";
}
}
});
}
return text;
};
markedRenderer.atLink = function(text) {
if (atLinkReg.test(text))
{
if (settings.atLink)
{
text = text.replace(emailReg, function($1, $2, $3, $4) {
return $1.replace(/@/g, "_#_@_#_");
});
text = text.replace(atLinkReg, function($1, $2) {
return "<a href=\"" + editormd.urls.atLinkBase + "" + $2 + "\" title=\"@" + $2 + "\" class=\"at-link\">" + $1 + "</a>";
}).replace(/_#_@_#_/g, "@");
}
if (settings.emailLink)
{
text = text.replace(emailLinkReg, function($1, $2, $3, $4, $5) {
return (!$2 && $.inArray($5, "jpg|jpeg|png|gif|webp|ico|icon|pdf".split("|")) < 0) ? "<a href=\"mailto:" + $1 + "\">"+$1+"</a>" : $1;
});
}
return text;
}
return text;
};
markedRenderer.link = function (href, title, text) {
if (this.options.sanitize) {
try {
var prot = decodeURIComponent(unescape(href)).replace(/[^\w:]/g,"").toLowerCase();
} catch(e) {
return "";
}
if (prot.indexOf("javascript:") === 0) {
return "";
}
}
var out = "<a href=\"" + href + "\"";
if (atLinkReg.test(title) || atLinkReg.test(text))
{
if (title)
{
out += " title=\"" + title.replace(/@/g, "@");
}
return out + "\">" + text.replace(/@/g, "@") + "</a>";
}
if (title) {
out += " title=\"" + title + "\"";
}
out += ">" + text + "</a>";
return out;
};
markedRenderer.heading = function(text, level, raw) {
var linkText = text;
var hasLinkReg = /\s*\<a\s*href\=\"(.*)\"\s*([^\>]*)\>(.*)\<\/a\>\s*/;
var getLinkTextReg = /\s*\<a\s*([^\>]+)\>([^\>]*)\<\/a\>\s*/g;
if (hasLinkReg.test(text))
{
var tempText = [];
text = text.split(/\<a\s*([^\>]+)\>([^\>]*)\<\/a\>/);
for (var i = 0, len = text.length; i < len; i++)
{
tempText.push(text[i].replace(/\s*href\=\"(.*)\"\s*/g, ""));
}
text = tempText.join(" ");
}
text = trim(text);
var escapedText = text.toLowerCase().replace(/[^\w]+/g, "-");
var toc = {
text : text,
level : level,
slug : escapedText
};
var isChinese = /^[\u4e00-\u9fa5]+$/.test(text);
var id = (isChinese) ? escape(text).replace(/\%/g, "") : text.toLowerCase().replace(/[^\w]+/g, "-");
markdownToC.push(toc);
var headingHTML = "<h" + level + " id=\"h"+ level + "-" + this.options.headerPrefix + id +"\">";
headingHTML += "<a name=\"" + text + "\" class=\"reference-link\"></a>";
headingHTML += "<span class=\"header-link octicon octicon-link\"></span>";
headingHTML += (hasLinkReg) ? this.atLink(this.emoji(linkText)) : this.atLink(this.emoji(text));
headingHTML += "</h" + level + ">";
return headingHTML;
};
markedRenderer.pageBreak = function(text) {
if (pageBreakReg.test(text) && settings.pageBreak)
{
text = "<hr style=\"page-break-after:always;\" class=\"page-break editormd-page-break\" />";
}
return text;
};
markedRenderer.paragraph = function(text) {
var isTeXInline = /\$\$(.*)\$\$/g.test(text);
var isTeXLine = /^\$\$(.*)\$\$$/.test(text);
var isTeXAddClass = (isTeXLine) ? " class=\"" + editormd.classNames.tex + "\"" : "";
var isToC = (settings.tocm) ? /^(\[TOC\]|\[TOCM\])$/.test(text) : /^\[TOC\]$/.test(text);
var isToCMenu = /^\[TOCM\]$/.test(text);
if (!isTeXLine && isTeXInline)
{
text = text.replace(/(\$\$([^\$]*)\$\$)+/g, function($1, $2) {
return "<span class=\"" + editormd.classNames.tex + "\">" + $2.replace(/\$/g, "") + "</span>";
});
}
else
{
text = (isTeXLine) ? text.replace(/\$/g, "") : text;
}
var tocHTML = "<div class=\"markdown-toc editormd-markdown-toc\">" + text + "</div>";
return (isToC) ? ( (isToCMenu) ? "<div class=\"editormd-toc-menu\">" + tocHTML + "</div><br/>" : tocHTML )
: ( (pageBreakReg.test(text)) ? this.pageBreak(text) : "<p" + isTeXAddClass + ">" + this.atLink(this.emoji(text)) + "</p>\n" );
};
markedRenderer.code = function (code, lang, escaped) {
if (lang === "seq" || lang === "sequence")
{
return "<div class=\"sequence-diagram\">" + code + "</div>";
}
else if ( lang === "flow")
{
return "<div class=\"flowchart\">" + code + "</div>";
}
else if ( lang === "math" || lang === "latex" || lang === "katex")
{
return "<p class=\"" + editormd.classNames.tex + "\">" + code + "</p>";
}
else
{
return marked.Renderer.prototype.code.apply(this, arguments);
}
};
markedRenderer.tablecell = function(content, flags) {
var type = (flags.header) ? "th" : "td";
var tag = (flags.align) ? "<" + type +" style=\"text-align:" + flags.align + "\">" : "<" + type + ">";
return tag + this.atLink(this.emoji(content)) + "</" + type + ">\n";
};
markedRenderer.listitem = function(text) {
if (settings.taskList && /^\s*\[[x\s]\]\s*/.test(text))
{
text = text.replace(/^\s*\[\s\]\s*/, "<input type=\"checkbox\" class=\"task-list-item-checkbox\" /> ")
.replace(/^\s*\[x\]\s*/, "<input type=\"checkbox\" class=\"task-list-item-checkbox\" checked disabled /> ");
return "<li style=\"list-style: none;\">" + this.atLink(this.emoji(text)) + "</li>";
}
else
{
return "<li>" + this.atLink(this.emoji(text)) + "</li>";
}
};
return markedRenderer;
};
/**
*
* 生成TOC(Table of Contents)
* Creating ToC (Table of Contents)
*
* @param {Array} toc 从marked获取的TOC数组列表
* @param {Element} container 插入TOC的容器元素
* @param {Integer} startLevel Hx 起始层级
* @returns {Object} tocContainer 返回ToC列表容器层的jQuery对象元素
*/
editormd.markdownToCRenderer = function(toc, container, tocDropdown, startLevel) {
var html = "";
var lastLevel = 0;
var classPrefix = this.classPrefix;
startLevel = startLevel || 1;
for (var i = 0, len = toc.length; i < len; i++)
{
var text = toc[i].text;
var level = toc[i].level;
if (level < startLevel) {
continue;
}
if (level > lastLevel)
{
html += "";
}
else if (level < lastLevel)
{
html += (new Array(lastLevel - level + 2)).join("</ul></li>");
}
else
{
html += "</ul></li>";
}
html += "<li><a class=\"toc-level-" + level + "\" href=\"#" + text + "\" level=\"" + level + "\">" + text + "</a><ul>";
lastLevel = level;
}
var tocContainer = container.find(".markdown-toc");
if ((tocContainer.length < 1 && container.attr("previewContainer") === "false"))
{
var tocHTML = "<div class=\"markdown-toc " + classPrefix + "markdown-toc\"></div>";
tocHTML = (tocDropdown) ? "<div class=\"" + classPrefix + "toc-menu\">" + tocHTML + "</div>" : tocHTML;
container.html(tocHTML);
tocContainer = container.find(".markdown-toc");
}
if (tocDropdown)
{
tocContainer.wrap("<div class=\"" + classPrefix + "toc-menu\"></div><br/>");
}
tocContainer.html("<ul class=\"markdown-toc-list\"></ul>").children(".markdown-toc-list").html(html.replace(/\r?\n?\<ul\>\<\/ul\>/g, ""));
return tocContainer;
};
/**
*
* 生成TOC下拉菜单
* Creating ToC dropdown menu
*
* @param {Object} container 插入TOC的容器jQuery对象元素
* @param {String} tocTitle ToC title
* @returns {Object} return toc-menu object
*/
editormd.tocDropdownMenu = function(container, tocTitle) {
tocTitle = tocTitle || "Table of Contents";
var zindex = 400;
var tocMenus = container.find("." + this.classPrefix + "toc-menu");
tocMenus.each(function() {
var $this = $(this);
var toc = $this.children(".markdown-toc");
var icon = "<i class=\"fa fa-angle-down\"></i>";
var btn = "<a href=\"javascript:;\" class=\"toc-menu-btn\">" + icon + tocTitle + "</a>";
var menu = toc.children("ul");
var list = menu.find("li");
toc.append(btn);
list.first().before("<li><h1>" + tocTitle + " " + icon + "</h1></li>");
$this.mouseover(function(){
menu.show();
list.each(function(){
var li = $(this);
var ul = li.children("ul");
if (ul.html() === "")
{
ul.remove();
}
if (ul.length > 0 && ul.html() !== "")
{
var firstA = li.children("a").first();
if (firstA.children(".fa").length < 1)
{
firstA.append( $(icon).css({ float:"right", paddingTop:"4px" }) );
}
}
li.mouseover(function(){
ul.css("z-index", zindex).show();
zindex += 1;
}).mouseleave(function(){
ul.hide();
});
});
}).mouseleave(function(){
menu.hide();
});
});
return tocMenus;
};
/**
* 简单地过滤指定的HTML标签
* Filter custom html tags
*
* @param {String} html 要过滤HTML
* @param {String} filters 要过滤的标签
* @returns {String} html 返回过滤的HTML
*/
editormd.filterHTMLTags = function(html, filters) {
if (typeof html !== "string") {
html = new String(html);
}
if (typeof filters !== "string") {
return html;
}
var expression = filters.split("|");
var filterTags = expression[0].split(",");
var attrs = expression[1];
for (var i = 0, len = filterTags.length; i < len; i++)
{
var tag = filterTags[i];
html = html.replace(new RegExp("\<\s*" + tag + "\s*([^\>]*)\>([^\>]*)\<\s*\/" + tag + "\s*\>", "igm"), "");
}
//return html;
if (typeof attrs !== "undefined")
{
var htmlTagRegex = /\<(\w+)\s*([^\>]*)\>([^\>]*)\<\/(\w+)\>/ig;
if (attrs === "*")
{
html = html.replace(htmlTagRegex, function($1, $2, $3, $4, $5) {
return "<" + $2 + ">" + $4 + "</" + $5 + ">";
});
}
else if (attrs === "on*")
{
html = html.replace(htmlTagRegex, function($1, $2, $3, $4, $5) {
var el = $("<" + $2 + ">" + $4 + "</" + $5 + ">");
var _attrs = $($1)[0].attributes;
var $attrs = {};
$.each(_attrs, function(i, e) {
if (e.nodeName !== '"') $attrs[e.nodeName] = e.nodeValue;
});
$.each($attrs, function(i) {
if (i.indexOf("on") === 0) {
delete $attrs[i];
}
});
el.attr($attrs);
var text = (typeof el[1] !== "undefined") ? $(el[1]).text() : "";
return el[0].outerHTML + text;
});
}
else
{
html = html.replace(htmlTagRegex, function($1, $2, $3, $4) {
var filterAttrs = attrs.split(",");
var el = $($1);
el.html($4);
$.each(filterAttrs, function(i) {
el.attr(filterAttrs[i], null);
});
return el[0].outerHTML;
});
}
}
return html;
};
/**
* 将Markdown文档解析为HTML用于前台显示
* Parse Markdown to HTML for Font-end preview.
*
* @param {String} id 用于显示HTML的对象ID
* @param {Object} [options={}] 配置选项,可选
* @returns {Object} div 返回jQuery对象元素
*/
editormd.markdownToHTML = function(id, options) {
var defaults = {
gfm : true,
toc : true,
tocm : false,
tocStartLevel : 1,
tocTitle : "目录",
tocDropdown : false,
tocContainer : "",
markdown : "",
markdownSourceCode : false,
htmlDecode : false,
autoLoadKaTeX : true,
pageBreak : true,
atLink : true, // for @link
emailLink : true, // for mail address auto link
tex : false,
taskList : false, // Github Flavored Markdown task lists
emoji : false,
flowChart : false,
sequenceDiagram : false,
previewCodeHighlight : true
};
editormd.$marked = marked;
var div = $("#" + id);
var settings = div.settings = $.extend(true, defaults, options || {});
var saveTo = div.find("textarea");
if (saveTo.length < 1)
{
div.append("<textarea></textarea>");
saveTo = div.find("textarea");
}
var markdownDoc = (settings.markdown === "") ? saveTo.val() : settings.markdown;
var markdownToC = [];
var rendererOptions = {
toc : settings.toc,
tocm : settings.tocm,
tocStartLevel : settings.tocStartLevel,
taskList : settings.taskList,
emoji : settings.emoji,
tex : settings.tex,
pageBreak : settings.pageBreak,
atLink : settings.atLink, // for @link
emailLink : settings.emailLink, // for mail address auto link
flowChart : settings.flowChart,
sequenceDiagram : settings.sequenceDiagram,
previewCodeHighlight : settings.previewCodeHighlight,
};
var markedOptions = {
renderer : editormd.markedRenderer(markdownToC, rendererOptions),
gfm : settings.gfm,
tables : true,
breaks : true,
pedantic : false,
sanitize : (settings.htmlDecode) ? false : true, // 是否忽略HTML标签,即是否开启HTML标签解析,为了安全性,默认不开启
smartLists : true,
smartypants : true
};
markdownDoc = new String(markdownDoc);
var markdownParsed = marked(markdownDoc, markedOptions);
markdownParsed = editormd.filterHTMLTags(markdownParsed, settings.htmlDecode);
if (settings.markdownSourceCode) {
saveTo.text(markdownDoc);
} else {
saveTo.remove();
}
div.addClass("markdown-body " + this.classPrefix + "html-preview").append(markdownParsed);
var tocContainer = (settings.tocContainer !== "") ? $(settings.tocContainer) : div;
if (settings.tocContainer !== "")
{
tocContainer.attr("previewContainer", false);
}
if (settings.toc)
{
div.tocContainer = this.markdownToCRenderer(markdownToC, tocContainer, settings.tocDropdown, settings.tocStartLevel);
if (settings.tocDropdown || div.find("." + this.classPrefix + "toc-menu").length > 0)
{
this.tocDropdownMenu(div, settings.tocTitle);
}
if (settings.tocContainer !== "")
{
div.find(".editormd-toc-menu, .editormd-markdown-toc").remove();
}
}
if (settings.previewCodeHighlight)
{
div.find("pre").addClass("prettyprint linenums");
prettyPrint();
}
if (!editormd.isIE8)
{
if (settings.flowChart) {
div.find(".flowchart").flowChart();
}
if (settings.sequenceDiagram) {
div.find(".sequence-diagram").sequenceDiagram({theme: "simple"});
}
}
if (settings.tex)
{
var katexHandle = function() {
div.find("." + editormd.classNames.tex).each(function(){
var tex = $(this);
katex.render(tex.html().replace(/</g, "<").replace(/>/g, ">"), tex[0]);
tex.find(".katex").css("font-size", "1.6em");
});
};
if (settings.autoLoadKaTeX && !editormd.$katex && !editormd.kaTeXLoaded)
{
this.loadKaTeX(function() {
editormd.$katex = katex;
editormd.kaTeXLoaded = true;
katexHandle();
});
}
else
{
katexHandle();
}
}
div.getMarkdown = function() {
return saveTo.val();
};
return div;
};
// Editor.md themes, change toolbar themes etc.
// added @1.5.0
editormd.themes = ["default", "dark"];
// Preview area themes
// added @1.5.0
editormd.previewThemes = ["default", "dark"];
// CodeMirror / editor area themes
// @1.5.0 rename -> editorThemes, old version -> themes
editormd.editorThemes = [
"default", "3024-day", "3024-night",
"ambiance", "ambiance-mobile",
"base16-dark", "base16-light", "blackboard",
"cobalt",
"eclipse", "elegant", "erlang-dark",
"lesser-dark",
"mbo", "mdn-like", "midnight", "monokai",
"neat", "neo", "night",
"paraiso-dark", "paraiso-light", "pastel-on-dark",
"rubyblue",
"solarized",
"the-matrix", "tomorrow-night-eighties", "twilight",
"vibrant-ink",
"xq-dark", "xq-light"
];
editormd.loadPlugins = {};
editormd.loadFiles = {
js : [],
css : [],
plugin : []
};
/**
* 动态加载Editor.md插件,但不立即执行
* Load editor.md plugins
*
* @param {String} fileName 插件文件路径
* @param {Function} [callback=function()] 加载成功后执行的回调函数
* @param {String} [into="head"] 嵌入页面的位置
*/
editormd.loadPlugin = function(fileName, callback, into) {
callback = callback || function() {};
this.loadScript(fileName, function() {
editormd.loadFiles.plugin.push(fileName);
callback();
}, into);
};
/**
* 动态加载CSS文件的方法
* Load css file method
*
* @param {String} fileName CSS文件名
* @param {Function} [callback=function()] 加载成功后执行的回调函数
* @param {String} [into="head"] 嵌入页面的位置
*/
editormd.loadCSS = function(fileName, callback, into) {
into = into || "head";
callback = callback || function() {};
var css = document.createElement("link");
css.type = "text/css";
css.rel = "stylesheet";
css.onload = css.onreadystatechange = function() {
editormd.loadFiles.css.push(fileName);
callback();
};
css.href = fileName + ".css";
if(into === "head") {
document.getElementsByTagName("head")[0].appendChild(css);
} else {
document.body.appendChild(css);
}
};
editormd.isIE = (navigator.appName == "Microsoft Internet Explorer");
editormd.isIE8 = (editormd.isIE && navigator.appVersion.match(/8./i) == "8.");
/**
* 动态加载JS文件的方法
* Load javascript file method
*
* @param {String} fileName JS文件名
* @param {Function} [callback=function()] 加载成功后执行的回调函数
* @param {String} [into="head"] 嵌入页面的位置
*/
editormd.loadScript = function(fileName, callback, into) {
into = into || "head";
callback = callback || function() {};
var script = null;
script = document.createElement("script");
script.id = fileName.replace(/[\./]+/g, "-");
script.type = "text/javascript";
script.src = fileName + ".js";
if (editormd.isIE8)
{
script.onreadystatechange = function() {
if(script.readyState)
{
if (script.readyState === "loaded" || script.readyState === "complete")
{
script.onreadystatechange = null;
editormd.loadFiles.js.push(fileName);
callback();
}
}
};
}
else
{
script.onload = function() {
editormd.loadFiles.js.push(fileName);
callback();
};
}
if (into === "head") {
document.getElementsByTagName("head")[0].appendChild(script);
} else {
document.body.appendChild(script);
}
};
// 使用国外的CDN,加载速度有时会很慢,或者自定义URL
// You can custom KaTeX load url.
editormd.katexURL = {
css : "//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min",
js : "//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min"
};
editormd.kaTeXLoaded = false;
/**
* 加载KaTeX文件
* load KaTeX files
*
* @param {Function} [callback=function()] 加载成功后执行的回调函数
*/
editormd.loadKaTeX = function (callback) {
editormd.loadCSS(editormd.katexURL.css, function(){
editormd.loadScript(editormd.katexURL.js, callback || function(){});
});
};
/**
* 锁屏
* lock screen
*
* @param {Boolean} lock Boolean 布尔值,是否锁屏
* @returns {void}
*/
editormd.lockScreen = function(lock) {
$("html,body").css("overflow", (lock) ? "hidden" : "");
};
/**
* 动态创建对话框
* Creating custom dialogs
*
* @param {Object} options 配置项键值对 Key/Value
* @returns {dialog} 返回创建的dialog的jQuery实例对象
*/
editormd.createDialog = function(options) {
var defaults = {
name : "",
width : 420,
height: 240,
title : "",
drag : true,
closed : true,
content : "",
mask : true,
maskStyle : {
backgroundColor : "#fff",
opacity : 0.1
},
lockScreen : true,
footer : true,
buttons : false
};
options = $.extend(true, defaults, options);
var $this = this;
var editor = this.editor;
var classPrefix = editormd.classPrefix;
var guid = (new Date()).getTime();
var dialogName = ( (options.name === "") ? classPrefix + "dialog-" + guid : options.name);
var mouseOrTouch = editormd.mouseOrTouch;
var html = "<div class=\"" + classPrefix + "dialog " + dialogName + "\">";
if (options.title !== "")
{
html += "<div class=\"" + classPrefix + "dialog-header\"" + ( (options.drag) ? " style=\"cursor: move;\"" : "" ) + ">";
html += "<strong class=\"" + classPrefix + "dialog-title\">" + options.title + "</strong>";
html += "</div>";
}
if (options.closed)
{
html += "<a href=\"javascript:;\" class=\"fa fa-close " + classPrefix + "dialog-close\"></a>";
}
html += "<div class=\"" + classPrefix + "dialog-container\">" + options.content;
if (options.footer || typeof options.footer === "string")
{
html += "<div class=\"" + classPrefix + "dialog-footer\">" + ( (typeof options.footer === "boolean") ? "" : options.footer) + "</div>";
}
html += "</div>";
html += "<div class=\"" + classPrefix + "dialog-mask " + classPrefix + "dialog-mask-bg\"></div>";
html += "<div class=\"" + classPrefix + "dialog-mask " + classPrefix + "dialog-mask-con\"></div>";
html += "</div>";
editor.append(html);
var dialog = editor.find("." + dialogName);
dialog.lockScreen = function(lock) {
if (options.lockScreen)
{
$("html,body").css("overflow", (lock) ? "hidden" : "");
$this.resize();
}
return dialog;
};
dialog.showMask = function() {
if (options.mask)
{
editor.find("." + classPrefix + "mask").css(options.maskStyle).css("z-index", editormd.dialogZindex - 1).show();
}
return dialog;
};
dialog.hideMask = function() {
if (options.mask)
{
editor.find("." + classPrefix + "mask").hide();
}
return dialog;
};
dialog.loading = function(show) {
var loading = dialog.find("." + classPrefix + "dialog-mask");
loading[(show) ? "show" : "hide"]();
return dialog;
};
dialog.lockScreen(true).showMask();
dialog.show().css({
zIndex : editormd.dialogZindex,
border : (editormd.isIE8) ? "1px solid #ddd" : "",
width : (typeof options.width === "number") ? options.width + "px" : options.width,
height : (typeof options.height === "number") ? options.height + "px" : options.height
});
var dialogPosition = function(){
dialog.css({
top : ($(window).height() - dialog.height()) / 2 + "px",
left : ($(window).width() - dialog.width()) / 2 + "px"
});
};
dialogPosition();
$(window).resize(dialogPosition);
dialog.children("." + classPrefix + "dialog-close").bind(mouseOrTouch("click", "touchend"), function() {
dialog.hide().lockScreen(false).hideMask();
});
if (typeof options.buttons === "object")
{
var footer = dialog.footer = dialog.find("." + classPrefix + "dialog-footer");
for (var key in options.buttons)
{
var btn = options.buttons[key];
var btnClassName = classPrefix + key + "-btn";
footer.append("<button class=\"" + classPrefix + "btn " + btnClassName + "\">" + btn[0] + "</button>");
btn[1] = $.proxy(btn[1], dialog);
footer.children("." + btnClassName).bind(mouseOrTouch("click", "touchend"), btn[1]);
}
}
if (options.title !== "" && options.drag)
{
var posX, posY;
var dialogHeader = dialog.children("." + classPrefix + "dialog-header");
if (!options.mask) {
dialogHeader.bind(mouseOrTouch("click", "touchend"), function(){
editormd.dialogZindex += 2;
dialog.css("z-index", editormd.dialogZindex);
});
}
dialogHeader.mousedown(function(e) {
e = e || window.event; //IE
posX = e.clientX - parseInt(dialog[0].style.left);
posY = e.clientY - parseInt(dialog[0].style.top);
document.onmousemove = moveAction;
});
var userCanSelect = function (obj) {
obj.removeClass(classPrefix + "user-unselect").off("selectstart");
};
var userUnselect = function (obj) {
obj.addClass(classPrefix + "user-unselect").on("selectstart", function(event) { // selectstart for IE
return false;
});
};
var moveAction = function (e) {
e = e || window.event; //IE
var left, top, nowLeft = parseInt(dialog[0].style.left), nowTop = parseInt(dialog[0].style.top);
if( nowLeft >= 0 ) {
if( nowLeft + dialog.width() <= $(window).width()) {
left = e.clientX - posX;
} else {
left = $(window).width() - dialog.width();
document.onmousemove = null;
}
} else {
left = 0;
document.onmousemove = null;
}
if( nowTop >= 0 ) {
top = e.clientY - posY;
} else {
top = 0;
document.onmousemove = null;
}
document.onselectstart = function() {
return false;
};
userUnselect($("body"));
userUnselect(dialog);
dialog[0].style.left = left + "px";
dialog[0].style.top = top + "px";
};
document.onmouseup = function() {
userCanSelect($("body"));
userCanSelect(dialog);
document.onselectstart = null;
document.onmousemove = null;
};
dialogHeader.touchDraggable = function() {
var offset = null;
var start = function(e) {
var orig = e.originalEvent;
var pos = $(this).parent().position();
offset = {
x : orig.changedTouches[0].pageX - pos.left,
y : orig.changedTouches[0].pageY - pos.top
};
};
var move = function(e) {
e.preventDefault();
var orig = e.originalEvent;
$(this).parent().css({
top : orig.changedTouches[0].pageY - offset.y,
left : orig.changedTouches[0].pageX - offset.x
});
};
this.bind("touchstart", start).bind("touchmove", move);
};
dialogHeader.touchDraggable();
}
editormd.dialogZindex += 2;
return dialog;
};
/**
* 鼠标和触摸事件的判断/选择方法
* MouseEvent or TouchEvent type switch
*
* @param {String} [mouseEventType="click"] 供选择的鼠标事件
* @param {String} [touchEventType="touchend"] 供选择的触摸事件
* @returns {String} EventType 返回事件类型名称
*/
editormd.mouseOrTouch = function(mouseEventType, touchEventType) {
mouseEventType = mouseEventType || "click";
touchEventType = touchEventType || "touchend";
var eventType = mouseEventType;
try {
document.createEvent("TouchEvent");
eventType = touchEventType;
} catch(e) {}
return eventType;
};
/**
* 日期时间的格式化方法
* Datetime format method
*
* @param {String} [format=""] 日期时间的格式,类似PHP的格式
* @returns {String} datefmt 返回格式化后的日期时间字符串
*/
editormd.dateFormat = function(format) {
format = format || "";
var addZero = function(d) {
return (d < 10) ? "0" + d : d;
};
var date = new Date();
var year = date.getFullYear();
var year2 = year.toString().slice(2, 4);
var month = addZero(date.getMonth() + 1);
var day = addZero(date.getDate());
var weekDay = date.getDay();
var hour = addZero(date.getHours());
var min = addZero(date.getMinutes());
var second = addZero(date.getSeconds());
var ms = addZero(date.getMilliseconds());
var datefmt = "";
var ymd = year2 + "-" + month + "-" + day;
var fymd = year + "-" + month + "-" + day;
var hms = hour + ":" + min + ":" + second;
switch (format)
{
case "UNIX Time" :
datefmt = date.getTime();
break;
case "UTC" :
datefmt = date.toUTCString();
break;
case "yy" :
datefmt = year2;
break;
case "year" :
case "yyyy" :
datefmt = year;
break;
case "month" :
case "mm" :
datefmt = month;
break;
case "cn-week-day" :
case "cn-wd" :
var cnWeekDays = ["日", "一", "二", "三", "四", "五", "六"];
datefmt = "星期" + cnWeekDays[weekDay];
break;
case "week-day" :
case "wd" :
var weekDays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
datefmt = weekDays[weekDay];
break;
case "day" :
case "dd" :
datefmt = day;
break;
case "hour" :
case "hh" :
datefmt = hour;
break;
case "min" :
case "ii" :
datefmt = min;
break;
case "second" :
case "ss" :
datefmt = second;
break;
case "ms" :
datefmt = ms;
break;
case "yy-mm-dd" :
datefmt = ymd;
break;
case "yyyy-mm-dd" :
datefmt = fymd;
break;
case "yyyy-mm-dd h:i:s ms" :
case "full + ms" :
datefmt = fymd + " " + hms + " " + ms;
break;
case "full" :
case "yyyy-mm-dd h:i:s" :
default:
datefmt = fymd + " " + hms;
break;
}
return datefmt;
};
return editormd;
}));
| Humsen/web/web-mobile/WebContent/plugins/editormd/js/editormd.amd.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/js/editormd.amd.js",
"repo_id": "Humsen",
"token_count": 96495
} | 34 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
var DEFAULT_BRACKETS = "()[]{}''\"\"";
var DEFAULT_TRIPLES = "'\"";
var DEFAULT_EXPLODE_ON_ENTER = "[]{}";
var SPACE_CHAR_REGEX = /\s/;
var Pos = CodeMirror.Pos;
CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) {
if (old != CodeMirror.Init && old)
cm.removeKeyMap("autoCloseBrackets");
if (!val) return;
var pairs = DEFAULT_BRACKETS, triples = DEFAULT_TRIPLES, explode = DEFAULT_EXPLODE_ON_ENTER;
if (typeof val == "string") pairs = val;
else if (typeof val == "object") {
if (val.pairs != null) pairs = val.pairs;
if (val.triples != null) triples = val.triples;
if (val.explode != null) explode = val.explode;
}
var map = buildKeymap(pairs, triples);
if (explode) map.Enter = buildExplodeHandler(explode);
cm.addKeyMap(map);
});
function charsAround(cm, pos) {
var str = cm.getRange(Pos(pos.line, pos.ch - 1),
Pos(pos.line, pos.ch + 1));
return str.length == 2 ? str : null;
}
// Project the token type that will exists after the given char is
// typed, and use it to determine whether it would cause the start
// of a string token.
function enteringString(cm, pos, ch) {
var line = cm.getLine(pos.line);
var token = cm.getTokenAt(pos);
if (/\bstring2?\b/.test(token.type)) return false;
var stream = new CodeMirror.StringStream(line.slice(0, pos.ch) + ch + line.slice(pos.ch), 4);
stream.pos = stream.start = token.start;
for (;;) {
var type1 = cm.getMode().token(stream, token.state);
if (stream.pos >= pos.ch + 1) return /\bstring2?\b/.test(type1);
stream.start = stream.pos;
}
}
function buildKeymap(pairs, triples) {
var map = {
name : "autoCloseBrackets",
Backspace: function(cm) {
if (cm.getOption("disableInput")) return CodeMirror.Pass;
var ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
if (!ranges[i].empty()) return CodeMirror.Pass;
var around = charsAround(cm, ranges[i].head);
if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass;
}
for (var i = ranges.length - 1; i >= 0; i--) {
var cur = ranges[i].head;
cm.replaceRange("", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1));
}
}
};
var closingBrackets = "";
for (var i = 0; i < pairs.length; i += 2) (function(left, right) {
closingBrackets += right;
map["'" + left + "'"] = function(cm) {
if (cm.getOption("disableInput")) return CodeMirror.Pass;
var ranges = cm.listSelections(), type, next;
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i], cur = range.head, curType;
var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1));
if (!range.empty()) {
curType = "surround";
} else if (left == right && next == right) {
if (cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == left + left + left)
curType = "skipThree";
else
curType = "skip";
} else if (left == right && cur.ch > 1 && triples.indexOf(left) >= 0 &&
cm.getRange(Pos(cur.line, cur.ch - 2), cur) == left + left &&
(cur.ch <= 2 || cm.getRange(Pos(cur.line, cur.ch - 3), Pos(cur.line, cur.ch - 2)) != left)) {
curType = "addFour";
} else if (left == '"' || left == "'") {
if (!CodeMirror.isWordChar(next) && enteringString(cm, cur, left)) curType = "both";
else return CodeMirror.Pass;
} else if (cm.getLine(cur.line).length == cur.ch || closingBrackets.indexOf(next) >= 0 || SPACE_CHAR_REGEX.test(next)) {
curType = "both";
} else {
return CodeMirror.Pass;
}
if (!type) type = curType;
else if (type != curType) return CodeMirror.Pass;
}
cm.operation(function() {
if (type == "skip") {
cm.execCommand("goCharRight");
} else if (type == "skipThree") {
for (var i = 0; i < 3; i++)
cm.execCommand("goCharRight");
} else if (type == "surround") {
var sels = cm.getSelections();
for (var i = 0; i < sels.length; i++)
sels[i] = left + sels[i] + right;
cm.replaceSelections(sels, "around");
} else if (type == "both") {
cm.replaceSelection(left + right, null);
cm.execCommand("goCharLeft");
} else if (type == "addFour") {
cm.replaceSelection(left + left + left + left, "before");
cm.execCommand("goCharRight");
}
});
};
if (left != right) map["'" + right + "'"] = function(cm) {
var ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (!range.empty() ||
cm.getRange(range.head, Pos(range.head.line, range.head.ch + 1)) != right)
return CodeMirror.Pass;
}
cm.execCommand("goCharRight");
};
})(pairs.charAt(i), pairs.charAt(i + 1));
return map;
}
function buildExplodeHandler(pairs) {
return function(cm) {
if (cm.getOption("disableInput")) return CodeMirror.Pass;
var ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
if (!ranges[i].empty()) return CodeMirror.Pass;
var around = charsAround(cm, ranges[i].head);
if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass;
}
cm.operation(function() {
cm.replaceSelection("\n\n", null);
cm.execCommand("goCharLeft");
ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
var line = ranges[i].head.line;
cm.indentLine(line, null, true);
cm.indentLine(line + 1, null, true);
}
});
};
}
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/edit/closebrackets.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/edit/closebrackets.js",
"repo_id": "Humsen",
"token_count": 2898
} | 35 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"), require("./xml-hint"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "./xml-hint"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var langs = "ab aa af ak sq am ar an hy as av ae ay az bm ba eu be bn bh bi bs br bg my ca ch ce ny zh cv kw co cr hr cs da dv nl dz en eo et ee fo fj fi fr ff gl ka de el gn gu ht ha he hz hi ho hu ia id ie ga ig ik io is it iu ja jv kl kn kr ks kk km ki rw ky kv kg ko ku kj la lb lg li ln lo lt lu lv gv mk mg ms ml mt mi mr mh mn na nv nb nd ne ng nn no ii nr oc oj cu om or os pa pi fa pl ps pt qu rm rn ro ru sa sc sd se sm sg sr gd sn si sk sl so st es su sw ss sv ta te tg th ti bo tk tl tn to tr ts tt tw ty ug uk ur uz ve vi vo wa cy wo fy xh yi yo za zu".split(" ");
var targets = ["_blank", "_self", "_top", "_parent"];
var charsets = ["ascii", "utf-8", "utf-16", "latin1", "latin1"];
var methods = ["get", "post", "put", "delete"];
var encs = ["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"];
var media = ["all", "screen", "print", "embossed", "braille", "handheld", "print", "projection", "screen", "tty", "tv", "speech",
"3d-glasses", "resolution [>][<][=] [X]", "device-aspect-ratio: X/Y", "orientation:portrait",
"orientation:landscape", "device-height: [X]", "device-width: [X]"];
var s = { attrs: {} }; // Simple tag, reused for a whole lot of tags
var data = {
a: {
attrs: {
href: null, ping: null, type: null,
media: media,
target: targets,
hreflang: langs
}
},
abbr: s,
acronym: s,
address: s,
applet: s,
area: {
attrs: {
alt: null, coords: null, href: null, target: null, ping: null,
media: media, hreflang: langs, type: null,
shape: ["default", "rect", "circle", "poly"]
}
},
article: s,
aside: s,
audio: {
attrs: {
src: null, mediagroup: null,
crossorigin: ["anonymous", "use-credentials"],
preload: ["none", "metadata", "auto"],
autoplay: ["", "autoplay"],
loop: ["", "loop"],
controls: ["", "controls"]
}
},
b: s,
base: { attrs: { href: null, target: targets } },
basefont: s,
bdi: s,
bdo: s,
big: s,
blockquote: { attrs: { cite: null } },
body: s,
br: s,
button: {
attrs: {
form: null, formaction: null, name: null, value: null,
autofocus: ["", "autofocus"],
disabled: ["", "autofocus"],
formenctype: encs,
formmethod: methods,
formnovalidate: ["", "novalidate"],
formtarget: targets,
type: ["submit", "reset", "button"]
}
},
canvas: { attrs: { width: null, height: null } },
caption: s,
center: s,
cite: s,
code: s,
col: { attrs: { span: null } },
colgroup: { attrs: { span: null } },
command: {
attrs: {
type: ["command", "checkbox", "radio"],
label: null, icon: null, radiogroup: null, command: null, title: null,
disabled: ["", "disabled"],
checked: ["", "checked"]
}
},
data: { attrs: { value: null } },
datagrid: { attrs: { disabled: ["", "disabled"], multiple: ["", "multiple"] } },
datalist: { attrs: { data: null } },
dd: s,
del: { attrs: { cite: null, datetime: null } },
details: { attrs: { open: ["", "open"] } },
dfn: s,
dir: s,
div: s,
dl: s,
dt: s,
em: s,
embed: { attrs: { src: null, type: null, width: null, height: null } },
eventsource: { attrs: { src: null } },
fieldset: { attrs: { disabled: ["", "disabled"], form: null, name: null } },
figcaption: s,
figure: s,
font: s,
footer: s,
form: {
attrs: {
action: null, name: null,
"accept-charset": charsets,
autocomplete: ["on", "off"],
enctype: encs,
method: methods,
novalidate: ["", "novalidate"],
target: targets
}
},
frame: s,
frameset: s,
h1: s, h2: s, h3: s, h4: s, h5: s, h6: s,
head: {
attrs: {},
children: ["title", "base", "link", "style", "meta", "script", "noscript", "command"]
},
header: s,
hgroup: s,
hr: s,
html: {
attrs: { manifest: null },
children: ["head", "body"]
},
i: s,
iframe: {
attrs: {
src: null, srcdoc: null, name: null, width: null, height: null,
sandbox: ["allow-top-navigation", "allow-same-origin", "allow-forms", "allow-scripts"],
seamless: ["", "seamless"]
}
},
img: {
attrs: {
alt: null, src: null, ismap: null, usemap: null, width: null, height: null,
crossorigin: ["anonymous", "use-credentials"]
}
},
input: {
attrs: {
alt: null, dirname: null, form: null, formaction: null,
height: null, list: null, max: null, maxlength: null, min: null,
name: null, pattern: null, placeholder: null, size: null, src: null,
step: null, value: null, width: null,
accept: ["audio/*", "video/*", "image/*"],
autocomplete: ["on", "off"],
autofocus: ["", "autofocus"],
checked: ["", "checked"],
disabled: ["", "disabled"],
formenctype: encs,
formmethod: methods,
formnovalidate: ["", "novalidate"],
formtarget: targets,
multiple: ["", "multiple"],
readonly: ["", "readonly"],
required: ["", "required"],
type: ["hidden", "text", "search", "tel", "url", "email", "password", "datetime", "date", "month",
"week", "time", "datetime-local", "number", "range", "color", "checkbox", "radio",
"file", "submit", "image", "reset", "button"]
}
},
ins: { attrs: { cite: null, datetime: null } },
kbd: s,
keygen: {
attrs: {
challenge: null, form: null, name: null,
autofocus: ["", "autofocus"],
disabled: ["", "disabled"],
keytype: ["RSA"]
}
},
label: { attrs: { "for": null, form: null } },
legend: s,
li: { attrs: { value: null } },
link: {
attrs: {
href: null, type: null,
hreflang: langs,
media: media,
sizes: ["all", "16x16", "16x16 32x32", "16x16 32x32 64x64"]
}
},
map: { attrs: { name: null } },
mark: s,
menu: { attrs: { label: null, type: ["list", "context", "toolbar"] } },
meta: {
attrs: {
content: null,
charset: charsets,
name: ["viewport", "application-name", "author", "description", "generator", "keywords"],
"http-equiv": ["content-language", "content-type", "default-style", "refresh"]
}
},
meter: { attrs: { value: null, min: null, low: null, high: null, max: null, optimum: null } },
nav: s,
noframes: s,
noscript: s,
object: {
attrs: {
data: null, type: null, name: null, usemap: null, form: null, width: null, height: null,
typemustmatch: ["", "typemustmatch"]
}
},
ol: { attrs: { reversed: ["", "reversed"], start: null, type: ["1", "a", "A", "i", "I"] } },
optgroup: { attrs: { disabled: ["", "disabled"], label: null } },
option: { attrs: { disabled: ["", "disabled"], label: null, selected: ["", "selected"], value: null } },
output: { attrs: { "for": null, form: null, name: null } },
p: s,
param: { attrs: { name: null, value: null } },
pre: s,
progress: { attrs: { value: null, max: null } },
q: { attrs: { cite: null } },
rp: s,
rt: s,
ruby: s,
s: s,
samp: s,
script: {
attrs: {
type: ["text/javascript"],
src: null,
async: ["", "async"],
defer: ["", "defer"],
charset: charsets
}
},
section: s,
select: {
attrs: {
form: null, name: null, size: null,
autofocus: ["", "autofocus"],
disabled: ["", "disabled"],
multiple: ["", "multiple"]
}
},
small: s,
source: { attrs: { src: null, type: null, media: null } },
span: s,
strike: s,
strong: s,
style: {
attrs: {
type: ["text/css"],
media: media,
scoped: null
}
},
sub: s,
summary: s,
sup: s,
table: s,
tbody: s,
td: { attrs: { colspan: null, rowspan: null, headers: null } },
textarea: {
attrs: {
dirname: null, form: null, maxlength: null, name: null, placeholder: null,
rows: null, cols: null,
autofocus: ["", "autofocus"],
disabled: ["", "disabled"],
readonly: ["", "readonly"],
required: ["", "required"],
wrap: ["soft", "hard"]
}
},
tfoot: s,
th: { attrs: { colspan: null, rowspan: null, headers: null, scope: ["row", "col", "rowgroup", "colgroup"] } },
thead: s,
time: { attrs: { datetime: null } },
title: s,
tr: s,
track: {
attrs: {
src: null, label: null, "default": null,
kind: ["subtitles", "captions", "descriptions", "chapters", "metadata"],
srclang: langs
}
},
tt: s,
u: s,
ul: s,
"var": s,
video: {
attrs: {
src: null, poster: null, width: null, height: null,
crossorigin: ["anonymous", "use-credentials"],
preload: ["auto", "metadata", "none"],
autoplay: ["", "autoplay"],
mediagroup: ["movie"],
muted: ["", "muted"],
controls: ["", "controls"]
}
},
wbr: s
};
var globalAttrs = {
accesskey: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
"class": null,
contenteditable: ["true", "false"],
contextmenu: null,
dir: ["ltr", "rtl", "auto"],
draggable: ["true", "false", "auto"],
dropzone: ["copy", "move", "link", "string:", "file:"],
hidden: ["hidden"],
id: null,
inert: ["inert"],
itemid: null,
itemprop: null,
itemref: null,
itemscope: ["itemscope"],
itemtype: null,
lang: ["en", "es"],
spellcheck: ["true", "false"],
style: null,
tabindex: ["1", "2", "3", "4", "5", "6", "7", "8", "9"],
title: null,
translate: ["yes", "no"],
onclick: null,
rel: ["stylesheet", "alternate", "author", "bookmark", "help", "license", "next", "nofollow", "noreferrer", "prefetch", "prev", "search", "tag"]
};
function populate(obj) {
for (var attr in globalAttrs) if (globalAttrs.hasOwnProperty(attr))
obj.attrs[attr] = globalAttrs[attr];
}
populate(s);
for (var tag in data) if (data.hasOwnProperty(tag) && data[tag] != s)
populate(data[tag]);
CodeMirror.htmlSchema = data;
function htmlHint(cm, options) {
var local = {schemaInfo: data};
if (options) for (var opt in options) local[opt] = options[opt];
return CodeMirror.hint.xml(cm, local);
}
CodeMirror.registerHelper("hint", "html", htmlHint);
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/hint/html-hint.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/hint/html-hint.js",
"repo_id": "Humsen",
"token_count": 5221
} | 36 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.multiplexingMode = function(outer /*, others */) {
// Others should be {open, close, mode [, delimStyle] [, innerStyle]} objects
var others = Array.prototype.slice.call(arguments, 1);
var n_others = others.length;
function indexOf(string, pattern, from) {
if (typeof pattern == "string") return string.indexOf(pattern, from);
var m = pattern.exec(from ? string.slice(from) : string);
return m ? m.index + from : -1;
}
return {
startState: function() {
return {
outer: CodeMirror.startState(outer),
innerActive: null,
inner: null
};
},
copyState: function(state) {
return {
outer: CodeMirror.copyState(outer, state.outer),
innerActive: state.innerActive,
inner: state.innerActive && CodeMirror.copyState(state.innerActive.mode, state.inner)
};
},
token: function(stream, state) {
if (!state.innerActive) {
var cutOff = Infinity, oldContent = stream.string;
for (var i = 0; i < n_others; ++i) {
var other = others[i];
var found = indexOf(oldContent, other.open, stream.pos);
if (found == stream.pos) {
stream.match(other.open);
state.innerActive = other;
state.inner = CodeMirror.startState(other.mode, outer.indent ? outer.indent(state.outer, "") : 0);
return other.delimStyle;
} else if (found != -1 && found < cutOff) {
cutOff = found;
}
}
if (cutOff != Infinity) stream.string = oldContent.slice(0, cutOff);
var outerToken = outer.token(stream, state.outer);
if (cutOff != Infinity) stream.string = oldContent;
return outerToken;
} else {
var curInner = state.innerActive, oldContent = stream.string;
if (!curInner.close && stream.sol()) {
state.innerActive = state.inner = null;
return this.token(stream, state);
}
var found = curInner.close ? indexOf(oldContent, curInner.close, stream.pos) : -1;
if (found == stream.pos) {
stream.match(curInner.close);
state.innerActive = state.inner = null;
return curInner.delimStyle;
}
if (found > -1) stream.string = oldContent.slice(0, found);
var innerToken = curInner.mode.token(stream, state.inner);
if (found > -1) stream.string = oldContent;
if (curInner.innerStyle) {
if (innerToken) innerToken = innerToken + ' ' + curInner.innerStyle;
else innerToken = curInner.innerStyle;
}
return innerToken;
}
},
indent: function(state, textAfter) {
var mode = state.innerActive ? state.innerActive.mode : outer;
if (!mode.indent) return CodeMirror.Pass;
return mode.indent(state.innerActive ? state.inner : state.outer, textAfter);
},
blankLine: function(state) {
var mode = state.innerActive ? state.innerActive.mode : outer;
if (mode.blankLine) {
mode.blankLine(state.innerActive ? state.inner : state.outer);
}
if (!state.innerActive) {
for (var i = 0; i < n_others; ++i) {
var other = others[i];
if (other.open === "\n") {
state.innerActive = other;
state.inner = CodeMirror.startState(other.mode, mode.indent ? mode.indent(state.outer, "") : 0);
}
}
} else if (state.innerActive.close === "\n") {
state.innerActive = state.inner = null;
}
},
electricChars: outer.electricChars,
innerMode: function(state) {
return state.inner ? {state: state.inner, mode: state.innerActive.mode} : {state: state.outer, mode: outer};
}
};
};
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/mode/multiplex.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/mode/multiplex.js",
"repo_id": "Humsen",
"token_count": 1746
} | 37 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var Pos = CodeMirror.Pos;
function SearchCursor(doc, query, pos, caseFold) {
this.atOccurrence = false; this.doc = doc;
if (caseFold == null && typeof query == "string") caseFold = false;
pos = pos ? doc.clipPos(pos) : Pos(0, 0);
this.pos = {from: pos, to: pos};
// The matches method is filled in based on the type of query.
// It takes a position and a direction, and returns an object
// describing the next occurrence of the query, or null if no
// more matches were found.
if (typeof query != "string") { // Regexp match
if (!query.global) query = new RegExp(query.source, query.ignoreCase ? "ig" : "g");
this.matches = function(reverse, pos) {
if (reverse) {
query.lastIndex = 0;
var line = doc.getLine(pos.line).slice(0, pos.ch), cutOff = 0, match, start;
for (;;) {
query.lastIndex = cutOff;
var newMatch = query.exec(line);
if (!newMatch) break;
match = newMatch;
start = match.index;
cutOff = match.index + (match[0].length || 1);
if (cutOff == line.length) break;
}
var matchLen = (match && match[0].length) || 0;
if (!matchLen) {
if (start == 0 && line.length == 0) {match = undefined;}
else if (start != doc.getLine(pos.line).length) {
matchLen++;
}
}
} else {
query.lastIndex = pos.ch;
var line = doc.getLine(pos.line), match = query.exec(line);
var matchLen = (match && match[0].length) || 0;
var start = match && match.index;
if (start + matchLen != line.length && !matchLen) matchLen = 1;
}
if (match && matchLen)
return {from: Pos(pos.line, start),
to: Pos(pos.line, start + matchLen),
match: match};
};
} else { // String query
var origQuery = query;
if (caseFold) query = query.toLowerCase();
var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
var target = query.split("\n");
// Different methods for single-line and multi-line queries
if (target.length == 1) {
if (!query.length) {
// Empty string would match anything and never progress, so
// we define it to match nothing instead.
this.matches = function() {};
} else {
this.matches = function(reverse, pos) {
if (reverse) {
var orig = doc.getLine(pos.line).slice(0, pos.ch), line = fold(orig);
var match = line.lastIndexOf(query);
if (match > -1) {
match = adjustPos(orig, line, match);
return {from: Pos(pos.line, match), to: Pos(pos.line, match + origQuery.length)};
}
} else {
var orig = doc.getLine(pos.line).slice(pos.ch), line = fold(orig);
var match = line.indexOf(query);
if (match > -1) {
match = adjustPos(orig, line, match) + pos.ch;
return {from: Pos(pos.line, match), to: Pos(pos.line, match + origQuery.length)};
}
}
};
}
} else {
var origTarget = origQuery.split("\n");
this.matches = function(reverse, pos) {
var last = target.length - 1;
if (reverse) {
if (pos.line - (target.length - 1) < doc.firstLine()) return;
if (fold(doc.getLine(pos.line).slice(0, origTarget[last].length)) != target[target.length - 1]) return;
var to = Pos(pos.line, origTarget[last].length);
for (var ln = pos.line - 1, i = last - 1; i >= 1; --i, --ln)
if (target[i] != fold(doc.getLine(ln))) return;
var line = doc.getLine(ln), cut = line.length - origTarget[0].length;
if (fold(line.slice(cut)) != target[0]) return;
return {from: Pos(ln, cut), to: to};
} else {
if (pos.line + (target.length - 1) > doc.lastLine()) return;
var line = doc.getLine(pos.line), cut = line.length - origTarget[0].length;
if (fold(line.slice(cut)) != target[0]) return;
var from = Pos(pos.line, cut);
for (var ln = pos.line + 1, i = 1; i < last; ++i, ++ln)
if (target[i] != fold(doc.getLine(ln))) return;
if (fold(doc.getLine(ln).slice(0, origTarget[last].length)) != target[last]) return;
return {from: from, to: Pos(ln, origTarget[last].length)};
}
};
}
}
}
SearchCursor.prototype = {
findNext: function() {return this.find(false);},
findPrevious: function() {return this.find(true);},
find: function(reverse) {
var self = this, pos = this.doc.clipPos(reverse ? this.pos.from : this.pos.to);
function savePosAndFail(line) {
var pos = Pos(line, 0);
self.pos = {from: pos, to: pos};
self.atOccurrence = false;
return false;
}
for (;;) {
if (this.pos = this.matches(reverse, pos)) {
this.atOccurrence = true;
return this.pos.match || true;
}
if (reverse) {
if (!pos.line) return savePosAndFail(0);
pos = Pos(pos.line-1, this.doc.getLine(pos.line-1).length);
}
else {
var maxLine = this.doc.lineCount();
if (pos.line == maxLine - 1) return savePosAndFail(maxLine);
pos = Pos(pos.line + 1, 0);
}
}
},
from: function() {if (this.atOccurrence) return this.pos.from;},
to: function() {if (this.atOccurrence) return this.pos.to;},
replace: function(newText) {
if (!this.atOccurrence) return;
var lines = CodeMirror.splitLines(newText);
this.doc.replaceRange(lines, this.pos.from, this.pos.to);
this.pos.to = Pos(this.pos.from.line + lines.length - 1,
lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0));
}
};
// Maps a position in a case-folded line back to a position in the original line
// (compensating for codepoints increasing in number during folding)
function adjustPos(orig, folded, pos) {
if (orig.length == folded.length) return pos;
for (var pos1 = Math.min(pos, orig.length);;) {
var len1 = orig.slice(0, pos1).toLowerCase().length;
if (len1 < pos) ++pos1;
else if (len1 > pos) --pos1;
else return pos1;
}
}
CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) {
return new SearchCursor(this.doc, query, pos, caseFold);
});
CodeMirror.defineDocExtension("getSearchCursor", function(query, pos, caseFold) {
return new SearchCursor(this, query, pos, caseFold);
});
CodeMirror.defineExtension("selectMatches", function(query, caseFold) {
var ranges = [], next;
var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold);
while (next = cur.findNext()) {
if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) break;
ranges.push({anchor: cur.from(), head: cur.to()});
}
if (ranges.length)
this.setSelections(ranges, 0);
});
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/search/searchcursor.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/addon/search/searchcursor.js",
"repo_id": "Humsen",
"token_count": 3441
} | 38 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("clike", function(config, parserConfig) {
var indentUnit = config.indentUnit,
statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
dontAlignCalls = parserConfig.dontAlignCalls,
keywords = parserConfig.keywords || {},
builtin = parserConfig.builtin || {},
blockKeywords = parserConfig.blockKeywords || {},
atoms = parserConfig.atoms || {},
hooks = parserConfig.hooks || {},
multiLineStrings = parserConfig.multiLineStrings,
indentStatements = parserConfig.indentStatements !== false;
var isOperatorChar = /[+\-*&%=<>!?|\/]/;
var curPunc;
function tokenBase(stream, state) {
var ch = stream.next();
if (hooks[ch]) {
var result = hooks[ch](stream, state);
if (result !== false) return result;
}
if (ch == '"' || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
}
if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
curPunc = ch;
return null;
}
if (/\d/.test(ch)) {
stream.eatWhile(/[\w\.]/);
return "number";
}
if (ch == "/") {
if (stream.eat("*")) {
state.tokenize = tokenComment;
return tokenComment(stream, state);
}
if (stream.eat("/")) {
stream.skipToEnd();
return "comment";
}
}
if (isOperatorChar.test(ch)) {
stream.eatWhile(isOperatorChar);
return "operator";
}
stream.eatWhile(/[\w\$_\xa1-\uffff]/);
var cur = stream.current();
if (keywords.propertyIsEnumerable(cur)) {
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
return "keyword";
}
if (builtin.propertyIsEnumerable(cur)) {
if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
return "builtin";
}
if (atoms.propertyIsEnumerable(cur)) return "atom";
return "variable";
}
function tokenString(quote) {
return function(stream, state) {
var escaped = false, next, end = false;
while ((next = stream.next()) != null) {
if (next == quote && !escaped) {end = true; break;}
escaped = !escaped && next == "\\";
}
if (end || !(escaped || multiLineStrings))
state.tokenize = null;
return "string";
};
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = null;
break;
}
maybeEnd = (ch == "*");
}
return "comment";
}
function Context(indented, column, type, align, prev) {
this.indented = indented;
this.column = column;
this.type = type;
this.align = align;
this.prev = prev;
}
function pushContext(state, col, type) {
var indent = state.indented;
if (state.context && state.context.type == "statement")
indent = state.context.indented;
return state.context = new Context(indent, col, type, null, state.context);
}
function popContext(state) {
var t = state.context.type;
if (t == ")" || t == "]" || t == "}")
state.indented = state.context.indented;
return state.context = state.context.prev;
}
// Interface
return {
startState: function(basecolumn) {
return {
tokenize: null,
context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
indented: 0,
startOfLine: true
};
},
token: function(stream, state) {
var ctx = state.context;
if (stream.sol()) {
if (ctx.align == null) ctx.align = false;
state.indented = stream.indentation();
state.startOfLine = true;
}
if (stream.eatSpace()) return null;
curPunc = null;
var style = (state.tokenize || tokenBase)(stream, state);
if (style == "comment" || style == "meta") return style;
if (ctx.align == null) ctx.align = true;
if ((curPunc == ";" || curPunc == ":" || curPunc == ",") && ctx.type == "statement") popContext(state);
else if (curPunc == "{") pushContext(state, stream.column(), "}");
else if (curPunc == "[") pushContext(state, stream.column(), "]");
else if (curPunc == "(") pushContext(state, stream.column(), ")");
else if (curPunc == "}") {
while (ctx.type == "statement") ctx = popContext(state);
if (ctx.type == "}") ctx = popContext(state);
while (ctx.type == "statement") ctx = popContext(state);
}
else if (curPunc == ctx.type) popContext(state);
else if (indentStatements &&
(((ctx.type == "}" || ctx.type == "top") && curPunc != ';') ||
(ctx.type == "statement" && curPunc == "newstatement")))
pushContext(state, stream.column(), "statement");
state.startOfLine = false;
return style;
},
indent: function(state, textAfter) {
if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
var closing = firstChar == ctx.type;
if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
else if (ctx.align && (!dontAlignCalls || ctx.type != ")")) return ctx.column + (closing ? 0 : 1);
else if (ctx.type == ")" && !closing) return ctx.indented + statementIndentUnit;
else return ctx.indented + (closing ? 0 : indentUnit);
},
electricChars: "{}",
blockCommentStart: "/*",
blockCommentEnd: "*/",
lineComment: "//",
fold: "brace"
};
});
function words(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
var cKeywords = "auto if break int case long char register continue return default short do sizeof " +
"double static else struct entry switch extern typedef float union for unsigned " +
"goto while enum void const signed volatile";
function cppHook(stream, state) {
if (!state.startOfLine) return false;
for (;;) {
if (stream.skipTo("\\")) {
stream.next();
if (stream.eol()) {
state.tokenize = cppHook;
break;
}
} else {
stream.skipToEnd();
state.tokenize = null;
break;
}
}
return "meta";
}
function cpp11StringHook(stream, state) {
stream.backUp(1);
// Raw strings.
if (stream.match(/(R|u8R|uR|UR|LR)/)) {
var match = stream.match(/"([^\s\\()]{0,16})\(/);
if (!match) {
return false;
}
state.cpp11RawStringDelim = match[1];
state.tokenize = tokenRawString;
return tokenRawString(stream, state);
}
// Unicode strings/chars.
if (stream.match(/(u8|u|U|L)/)) {
if (stream.match(/["']/, /* eat */ false)) {
return "string";
}
return false;
}
// Ignore this hook.
stream.next();
return false;
}
// C#-style strings where "" escapes a quote.
function tokenAtString(stream, state) {
var next;
while ((next = stream.next()) != null) {
if (next == '"' && !stream.eat('"')) {
state.tokenize = null;
break;
}
}
return "string";
}
// C++11 raw string literal is <prefix>"<delim>( anything )<delim>", where
// <delim> can be a string up to 16 characters long.
function tokenRawString(stream, state) {
// Escape characters that have special regex meanings.
var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&');
var match = stream.match(new RegExp(".*?\\)" + delim + '"'));
if (match)
state.tokenize = null;
else
stream.skipToEnd();
return "string";
}
function def(mimes, mode) {
if (typeof mimes == "string") mimes = [mimes];
var words = [];
function add(obj) {
if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop))
words.push(prop);
}
add(mode.keywords);
add(mode.builtin);
add(mode.atoms);
if (words.length) {
mode.helperType = mimes[0];
CodeMirror.registerHelper("hintWords", mimes[0], words);
}
for (var i = 0; i < mimes.length; ++i)
CodeMirror.defineMIME(mimes[i], mode);
}
def(["text/x-csrc", "text/x-c", "text/x-chdr"], {
name: "clike",
keywords: words(cKeywords),
blockKeywords: words("case do else for if switch while struct"),
atoms: words("null"),
hooks: {"#": cppHook},
modeProps: {fold: ["brace", "include"]}
});
def(["text/x-c++src", "text/x-c++hdr"], {
name: "clike",
keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " +
"static_cast typeid catch operator template typename class friend private " +
"this using const_cast inline public throw virtual delete mutable protected " +
"wchar_t alignas alignof constexpr decltype nullptr noexcept thread_local final " +
"static_assert override"),
blockKeywords: words("catch class do else finally for if struct switch try while"),
atoms: words("true false null"),
hooks: {
"#": cppHook,
"u": cpp11StringHook,
"U": cpp11StringHook,
"L": cpp11StringHook,
"R": cpp11StringHook
},
modeProps: {fold: ["brace", "include"]}
});
def("text/x-java", {
name: "clike",
keywords: words("abstract assert boolean break byte case catch char class const continue default " +
"do double else enum extends final finally float for goto if implements import " +
"instanceof int interface long native new package private protected public " +
"return short static strictfp super switch synchronized this throw throws transient " +
"try void volatile while"),
blockKeywords: words("catch class do else finally for if switch try while"),
atoms: words("true false null"),
hooks: {
"@": function(stream) {
stream.eatWhile(/[\w\$_]/);
return "meta";
}
},
modeProps: {fold: ["brace", "import"]}
});
def("text/x-csharp", {
name: "clike",
keywords: words("abstract as base break case catch checked class const continue" +
" default delegate do else enum event explicit extern finally fixed for" +
" foreach goto if implicit in interface internal is lock namespace new" +
" operator out override params private protected public readonly ref return sealed" +
" sizeof stackalloc static struct switch this throw try typeof unchecked" +
" unsafe using virtual void volatile while add alias ascending descending dynamic from get" +
" global group into join let orderby partial remove select set value var yield"),
blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
builtin: words("Boolean Byte Char DateTime DateTimeOffset Decimal Double" +
" Guid Int16 Int32 Int64 Object SByte Single String TimeSpan UInt16 UInt32" +
" UInt64 bool byte char decimal double short int long object" +
" sbyte float string ushort uint ulong"),
atoms: words("true false null"),
hooks: {
"@": function(stream, state) {
if (stream.eat('"')) {
state.tokenize = tokenAtString;
return tokenAtString(stream, state);
}
stream.eatWhile(/[\w\$_]/);
return "meta";
}
}
});
function tokenTripleString(stream, state) {
var escaped = false;
while (!stream.eol()) {
if (!escaped && stream.match('"""')) {
state.tokenize = null;
break;
}
escaped = stream.next() == "\\" && !escaped;
}
return "string";
}
def("text/x-scala", {
name: "clike",
keywords: words(
/* scala */
"abstract case catch class def do else extends false final finally for forSome if " +
"implicit import lazy match new null object override package private protected return " +
"sealed super this throw trait try trye type val var while with yield _ : = => <- <: " +
"<% >: # @ " +
/* package scala */
"assert assume require print println printf readLine readBoolean readByte readShort " +
"readChar readInt readLong readFloat readDouble " +
"AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " +
"Enumeration Equiv Error Exception Fractional Function IndexedSeq Integral Iterable " +
"Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " +
"Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " +
"StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector :: #:: " +
/* package java.lang */
"Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
"Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
"Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
"StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
),
multiLineStrings: true,
blockKeywords: words("catch class do else finally for forSome if match switch try while"),
atoms: words("true false null"),
indentStatements: false,
hooks: {
"@": function(stream) {
stream.eatWhile(/[\w\$_]/);
return "meta";
},
'"': function(stream, state) {
if (!stream.match('""')) return false;
state.tokenize = tokenTripleString;
return state.tokenize(stream, state);
},
"'": function(stream) {
stream.eatWhile(/[\w\$_\xa1-\uffff]/);
return "atom";
}
}
});
def(["x-shader/x-vertex", "x-shader/x-fragment"], {
name: "clike",
keywords: words("float int bool void " +
"vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " +
"mat2 mat3 mat4 " +
"sampler1D sampler2D sampler3D samplerCube " +
"sampler1DShadow sampler2DShadow " +
"const attribute uniform varying " +
"break continue discard return " +
"for while do if else struct " +
"in out inout"),
blockKeywords: words("for while do if else struct"),
builtin: words("radians degrees sin cos tan asin acos atan " +
"pow exp log exp2 sqrt inversesqrt " +
"abs sign floor ceil fract mod min max clamp mix step smoothstep " +
"length distance dot cross normalize ftransform faceforward " +
"reflect refract matrixCompMult " +
"lessThan lessThanEqual greaterThan greaterThanEqual " +
"equal notEqual any all not " +
"texture1D texture1DProj texture1DLod texture1DProjLod " +
"texture2D texture2DProj texture2DLod texture2DProjLod " +
"texture3D texture3DProj texture3DLod texture3DProjLod " +
"textureCube textureCubeLod " +
"shadow1D shadow2D shadow1DProj shadow2DProj " +
"shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " +
"dFdx dFdy fwidth " +
"noise1 noise2 noise3 noise4"),
atoms: words("true false " +
"gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " +
"gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " +
"gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " +
"gl_FogCoord gl_PointCoord " +
"gl_Position gl_PointSize gl_ClipVertex " +
"gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " +
"gl_TexCoord gl_FogFragCoord " +
"gl_FragCoord gl_FrontFacing " +
"gl_FragData gl_FragDepth " +
"gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " +
"gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " +
"gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " +
"gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose " +
"gl_ProjectionMatrixInverseTranspose " +
"gl_ModelViewProjectionMatrixInverseTranspose " +
"gl_TextureMatrixInverseTranspose " +
"gl_NormalScale gl_DepthRange gl_ClipPlane " +
"gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " +
"gl_FrontLightModelProduct gl_BackLightModelProduct " +
"gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " +
"gl_FogParameters " +
"gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " +
"gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " +
"gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " +
"gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " +
"gl_MaxDrawBuffers"),
hooks: {"#": cppHook},
modeProps: {fold: ["brace", "include"]}
});
def("text/x-nesc", {
name: "clike",
keywords: words(cKeywords + "as atomic async call command component components configuration event generic " +
"implementation includes interface module new norace nx_struct nx_union post provides " +
"signal task uses abstract extends"),
blockKeywords: words("case do else for if switch while struct"),
atoms: words("null"),
hooks: {"#": cppHook},
modeProps: {fold: ["brace", "include"]}
});
def("text/x-objectivec", {
name: "clike",
keywords: words(cKeywords + "inline restrict _Bool _Complex _Imaginery BOOL Class bycopy byref id IMP in " +
"inout nil oneway out Protocol SEL self super atomic nonatomic retain copy readwrite readonly"),
atoms: words("YES NO NULL NILL ON OFF"),
hooks: {
"@": function(stream) {
stream.eatWhile(/[\w\$]/);
return "keyword";
},
"#": cppHook
},
modeProps: {fold: "brace"}
});
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/clike/clike.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/clike/clike.js",
"repo_id": "Humsen",
"token_count": 7947
} | 39 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("dylan", function(_config) {
// Words
var words = {
// Words that introduce unnamed definitions like "define interface"
unnamedDefinition: ["interface"],
// Words that introduce simple named definitions like "define library"
namedDefinition: ["module", "library", "macro",
"C-struct", "C-union",
"C-function", "C-callable-wrapper"
],
// Words that introduce type definitions like "define class".
// These are also parameterized like "define method" and are
// appended to otherParameterizedDefinitionWords
typeParameterizedDefinition: ["class", "C-subtype", "C-mapped-subtype"],
// Words that introduce trickier definitions like "define method".
// These require special definitions to be added to startExpressions
otherParameterizedDefinition: ["method", "function",
"C-variable", "C-address"
],
// Words that introduce module constant definitions.
// These must also be simple definitions and are
// appended to otherSimpleDefinitionWords
constantSimpleDefinition: ["constant"],
// Words that introduce module variable definitions.
// These must also be simple definitions and are
// appended to otherSimpleDefinitionWords
variableSimpleDefinition: ["variable"],
// Other words that introduce simple definitions
// (without implicit bodies).
otherSimpleDefinition: ["generic", "domain",
"C-pointer-type",
"table"
],
// Words that begin statements with implicit bodies.
statement: ["if", "block", "begin", "method", "case",
"for", "select", "when", "unless", "until",
"while", "iterate", "profiling", "dynamic-bind"
],
// Patterns that act as separators in compound statements.
// This may include any general pattern that must be indented
// specially.
separator: ["finally", "exception", "cleanup", "else",
"elseif", "afterwards"
],
// Keywords that do not require special indentation handling,
// but which should be highlighted
other: ["above", "below", "by", "from", "handler", "in",
"instance", "let", "local", "otherwise", "slot",
"subclass", "then", "to", "keyed-by", "virtual"
],
// Condition signaling function calls
signalingCalls: ["signal", "error", "cerror",
"break", "check-type", "abort"
]
};
words["otherDefinition"] =
words["unnamedDefinition"]
.concat(words["namedDefinition"])
.concat(words["otherParameterizedDefinition"]);
words["definition"] =
words["typeParameterizedDefinition"]
.concat(words["otherDefinition"]);
words["parameterizedDefinition"] =
words["typeParameterizedDefinition"]
.concat(words["otherParameterizedDefinition"]);
words["simpleDefinition"] =
words["constantSimpleDefinition"]
.concat(words["variableSimpleDefinition"])
.concat(words["otherSimpleDefinition"]);
words["keyword"] =
words["statement"]
.concat(words["separator"])
.concat(words["other"]);
// Patterns
var symbolPattern = "[-_a-zA-Z?!*@<>$%]+";
var symbol = new RegExp("^" + symbolPattern);
var patterns = {
// Symbols with special syntax
symbolKeyword: symbolPattern + ":",
symbolClass: "<" + symbolPattern + ">",
symbolGlobal: "\\*" + symbolPattern + "\\*",
symbolConstant: "\\$" + symbolPattern
};
var patternStyles = {
symbolKeyword: "atom",
symbolClass: "tag",
symbolGlobal: "variable-2",
symbolConstant: "variable-3"
};
// Compile all patterns to regular expressions
for (var patternName in patterns)
if (patterns.hasOwnProperty(patternName))
patterns[patternName] = new RegExp("^" + patterns[patternName]);
// Names beginning "with-" and "without-" are commonly
// used as statement macro
patterns["keyword"] = [/^with(?:out)?-[-_a-zA-Z?!*@<>$%]+/];
var styles = {};
styles["keyword"] = "keyword";
styles["definition"] = "def";
styles["simpleDefinition"] = "def";
styles["signalingCalls"] = "builtin";
// protected words lookup table
var wordLookup = {};
var styleLookup = {};
[
"keyword",
"definition",
"simpleDefinition",
"signalingCalls"
].forEach(function(type) {
words[type].forEach(function(word) {
wordLookup[word] = type;
styleLookup[word] = styles[type];
});
});
function chain(stream, state, f) {
state.tokenize = f;
return f(stream, state);
}
var type, content;
function ret(_type, style, _content) {
type = _type;
content = _content;
return style;
}
function tokenBase(stream, state) {
// String
var ch = stream.peek();
if (ch == "'" || ch == '"') {
stream.next();
return chain(stream, state, tokenString(ch, "string", "string"));
}
// Comment
else if (ch == "/") {
stream.next();
if (stream.eat("*")) {
return chain(stream, state, tokenComment);
} else if (stream.eat("/")) {
stream.skipToEnd();
return ret("comment", "comment");
} else {
stream.skipTo(" ");
return ret("operator", "operator");
}
}
// Decimal
else if (/\d/.test(ch)) {
stream.match(/^\d*(?:\.\d*)?(?:e[+\-]?\d+)?/);
return ret("number", "number");
}
// Hash
else if (ch == "#") {
stream.next();
// Symbol with string syntax
ch = stream.peek();
if (ch == '"') {
stream.next();
return chain(stream, state, tokenString('"', "symbol", "string-2"));
}
// Binary number
else if (ch == "b") {
stream.next();
stream.eatWhile(/[01]/);
return ret("number", "number");
}
// Hex number
else if (ch == "x") {
stream.next();
stream.eatWhile(/[\da-f]/i);
return ret("number", "number");
}
// Octal number
else if (ch == "o") {
stream.next();
stream.eatWhile(/[0-7]/);
return ret("number", "number");
}
// Hash symbol
else {
stream.eatWhile(/[-a-zA-Z]/);
return ret("hash", "keyword");
}
} else if (stream.match("end")) {
return ret("end", "keyword");
}
for (var name in patterns) {
if (patterns.hasOwnProperty(name)) {
var pattern = patterns[name];
if ((pattern instanceof Array && pattern.some(function(p) {
return stream.match(p);
})) || stream.match(pattern))
return ret(name, patternStyles[name], stream.current());
}
}
if (stream.match("define")) {
return ret("definition", "def");
} else {
stream.eatWhile(/[\w\-]/);
// Keyword
if (wordLookup[stream.current()]) {
return ret(wordLookup[stream.current()], styleLookup[stream.current()], stream.current());
} else if (stream.current().match(symbol)) {
return ret("variable", "variable");
} else {
stream.next();
return ret("other", "variable-2");
}
}
}
function tokenComment(stream, state) {
var maybeEnd = false,
ch;
while ((ch = stream.next())) {
if (ch == "/" && maybeEnd) {
state.tokenize = tokenBase;
break;
}
maybeEnd = (ch == "*");
}
return ret("comment", "comment");
}
function tokenString(quote, type, style) {
return function(stream, state) {
var next, end = false;
while ((next = stream.next()) != null) {
if (next == quote) {
end = true;
break;
}
}
if (end)
state.tokenize = tokenBase;
return ret(type, style);
};
}
// Interface
return {
startState: function() {
return {
tokenize: tokenBase,
currentIndent: 0
};
},
token: function(stream, state) {
if (stream.eatSpace())
return null;
var style = state.tokenize(stream, state);
return style;
},
blockCommentStart: "/*",
blockCommentEnd: "*/"
};
});
CodeMirror.defineMIME("text/x-dylan", "dylan");
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/dylan/dylan.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/dylan/dylan.js",
"repo_id": "Humsen",
"token_count": 3546
} | 40 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("haxe", function(config, parserConfig) {
var indentUnit = config.indentUnit;
// Tokenizer
var keywords = function(){
function kw(type) {return {type: type, style: "keyword"};}
var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
var operator = kw("operator"), atom = {type: "atom", style: "atom"}, attribute = {type:"attribute", style: "attribute"};
var type = kw("typedef");
return {
"if": A, "while": A, "else": B, "do": B, "try": B,
"return": C, "break": C, "continue": C, "new": C, "throw": C,
"var": kw("var"), "inline":attribute, "static": attribute, "using":kw("import"),
"public": attribute, "private": attribute, "cast": kw("cast"), "import": kw("import"), "macro": kw("macro"),
"function": kw("function"), "catch": kw("catch"), "untyped": kw("untyped"), "callback": kw("cb"),
"for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
"in": operator, "never": kw("property_access"), "trace":kw("trace"),
"class": type, "abstract":type, "enum":type, "interface":type, "typedef":type, "extends":type, "implements":type, "dynamic":type,
"true": atom, "false": atom, "null": atom
};
}();
var isOperatorChar = /[+\-*&%=<>!?|]/;
function chain(stream, state, f) {
state.tokenize = f;
return f(stream, state);
}
function nextUntilUnescaped(stream, end) {
var escaped = false, next;
while ((next = stream.next()) != null) {
if (next == end && !escaped)
return false;
escaped = !escaped && next == "\\";
}
return escaped;
}
// Used as scratch variables to communicate multiple values without
// consing up tons of objects.
var type, content;
function ret(tp, style, cont) {
type = tp; content = cont;
return style;
}
function haxeTokenBase(stream, state) {
var ch = stream.next();
if (ch == '"' || ch == "'")
return chain(stream, state, haxeTokenString(ch));
else if (/[\[\]{}\(\),;\:\.]/.test(ch))
return ret(ch);
else if (ch == "0" && stream.eat(/x/i)) {
stream.eatWhile(/[\da-f]/i);
return ret("number", "number");
}
else if (/\d/.test(ch) || ch == "-" && stream.eat(/\d/)) {
stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
return ret("number", "number");
}
else if (state.reAllowed && (ch == "~" && stream.eat(/\//))) {
nextUntilUnescaped(stream, "/");
stream.eatWhile(/[gimsu]/);
return ret("regexp", "string-2");
}
else if (ch == "/") {
if (stream.eat("*")) {
return chain(stream, state, haxeTokenComment);
}
else if (stream.eat("/")) {
stream.skipToEnd();
return ret("comment", "comment");
}
else {
stream.eatWhile(isOperatorChar);
return ret("operator", null, stream.current());
}
}
else if (ch == "#") {
stream.skipToEnd();
return ret("conditional", "meta");
}
else if (ch == "@") {
stream.eat(/:/);
stream.eatWhile(/[\w_]/);
return ret ("metadata", "meta");
}
else if (isOperatorChar.test(ch)) {
stream.eatWhile(isOperatorChar);
return ret("operator", null, stream.current());
}
else {
var word;
if(/[A-Z]/.test(ch))
{
stream.eatWhile(/[\w_<>]/);
word = stream.current();
return ret("type", "variable-3", word);
}
else
{
stream.eatWhile(/[\w_]/);
var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
return (known && state.kwAllowed) ? ret(known.type, known.style, word) :
ret("variable", "variable", word);
}
}
}
function haxeTokenString(quote) {
return function(stream, state) {
if (!nextUntilUnescaped(stream, quote))
state.tokenize = haxeTokenBase;
return ret("string", "string");
};
}
function haxeTokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = haxeTokenBase;
break;
}
maybeEnd = (ch == "*");
}
return ret("comment", "comment");
}
// Parser
var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true};
function HaxeLexical(indented, column, type, align, prev, info) {
this.indented = indented;
this.column = column;
this.type = type;
this.prev = prev;
this.info = info;
if (align != null) this.align = align;
}
function inScope(state, varname) {
for (var v = state.localVars; v; v = v.next)
if (v.name == varname) return true;
}
function parseHaxe(state, style, type, content, stream) {
var cc = state.cc;
// Communicate our context to the combinators.
// (Less wasteful than consing up a hundred closures on every call.)
cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc;
if (!state.lexical.hasOwnProperty("align"))
state.lexical.align = true;
while(true) {
var combinator = cc.length ? cc.pop() : statement;
if (combinator(type, content)) {
while(cc.length && cc[cc.length - 1].lex)
cc.pop()();
if (cx.marked) return cx.marked;
if (type == "variable" && inScope(state, content)) return "variable-2";
if (type == "variable" && imported(state, content)) return "variable-3";
return style;
}
}
}
function imported(state, typename)
{
if (/[a-z]/.test(typename.charAt(0)))
return false;
var len = state.importedtypes.length;
for (var i = 0; i<len; i++)
if(state.importedtypes[i]==typename) return true;
}
function registerimport(importname) {
var state = cx.state;
for (var t = state.importedtypes; t; t = t.next)
if(t.name == importname) return;
state.importedtypes = { name: importname, next: state.importedtypes };
}
// Combinator utils
var cx = {state: null, column: null, marked: null, cc: null};
function pass() {
for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
}
function cont() {
pass.apply(null, arguments);
return true;
}
function register(varname) {
var state = cx.state;
if (state.context) {
cx.marked = "def";
for (var v = state.localVars; v; v = v.next)
if (v.name == varname) return;
state.localVars = {name: varname, next: state.localVars};
}
}
// Combinators
var defaultVars = {name: "this", next: null};
function pushcontext() {
if (!cx.state.context) cx.state.localVars = defaultVars;
cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
}
function popcontext() {
cx.state.localVars = cx.state.context.vars;
cx.state.context = cx.state.context.prev;
}
function pushlex(type, info) {
var result = function() {
var state = cx.state;
state.lexical = new HaxeLexical(state.indented, cx.stream.column(), type, null, state.lexical, info);
};
result.lex = true;
return result;
}
function poplex() {
var state = cx.state;
if (state.lexical.prev) {
if (state.lexical.type == ")")
state.indented = state.lexical.indented;
state.lexical = state.lexical.prev;
}
}
poplex.lex = true;
function expect(wanted) {
function f(type) {
if (type == wanted) return cont();
else if (wanted == ";") return pass();
else return cont(f);
};
return f;
}
function statement(type) {
if (type == "@") return cont(metadef);
if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex);
if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
if (type == "{") return cont(pushlex("}"), pushcontext, block, poplex, popcontext);
if (type == ";") return cont();
if (type == "attribute") return cont(maybeattribute);
if (type == "function") return cont(functiondef);
if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"),
poplex, statement, poplex);
if (type == "variable") return cont(pushlex("stat"), maybelabel);
if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
block, poplex, poplex);
if (type == "case") return cont(expression, expect(":"));
if (type == "default") return cont(expect(":"));
if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
statement, poplex, popcontext);
if (type == "import") return cont(importdef, expect(";"));
if (type == "typedef") return cont(typedef);
return pass(pushlex("stat"), expression, expect(";"), poplex);
}
function expression(type) {
if (atomicTypes.hasOwnProperty(type)) return cont(maybeoperator);
if (type == "function") return cont(functiondef);
if (type == "keyword c") return cont(maybeexpression);
if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeoperator);
if (type == "operator") return cont(expression);
if (type == "[") return cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator);
if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator);
return cont();
}
function maybeexpression(type) {
if (type.match(/[;\}\)\],]/)) return pass();
return pass(expression);
}
function maybeoperator(type, value) {
if (type == "operator" && /\+\+|--/.test(value)) return cont(maybeoperator);
if (type == "operator" || type == ":") return cont(expression);
if (type == ";") return;
if (type == "(") return cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator);
if (type == ".") return cont(property, maybeoperator);
if (type == "[") return cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator);
}
function maybeattribute(type) {
if (type == "attribute") return cont(maybeattribute);
if (type == "function") return cont(functiondef);
if (type == "var") return cont(vardef1);
}
function metadef(type) {
if(type == ":") return cont(metadef);
if(type == "variable") return cont(metadef);
if(type == "(") return cont(pushlex(")"), commasep(metaargs, ")"), poplex, statement);
}
function metaargs(type) {
if(type == "variable") return cont();
}
function importdef (type, value) {
if(type == "variable" && /[A-Z]/.test(value.charAt(0))) { registerimport(value); return cont(); }
else if(type == "variable" || type == "property" || type == "." || value == "*") return cont(importdef);
}
function typedef (type, value)
{
if(type == "variable" && /[A-Z]/.test(value.charAt(0))) { registerimport(value); return cont(); }
else if (type == "type" && /[A-Z]/.test(value.charAt(0))) { return cont(); }
}
function maybelabel(type) {
if (type == ":") return cont(poplex, statement);
return pass(maybeoperator, expect(";"), poplex);
}
function property(type) {
if (type == "variable") {cx.marked = "property"; return cont();}
}
function objprop(type) {
if (type == "variable") cx.marked = "property";
if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expression);
}
function commasep(what, end) {
function proceed(type) {
if (type == ",") return cont(what, proceed);
if (type == end) return cont();
return cont(expect(end));
}
return function(type) {
if (type == end) return cont();
else return pass(what, proceed);
};
}
function block(type) {
if (type == "}") return cont();
return pass(statement, block);
}
function vardef1(type, value) {
if (type == "variable"){register(value); return cont(typeuse, vardef2);}
return cont();
}
function vardef2(type, value) {
if (value == "=") return cont(expression, vardef2);
if (type == ",") return cont(vardef1);
}
function forspec1(type, value) {
if (type == "variable") {
register(value);
}
return cont(pushlex(")"), pushcontext, forin, expression, poplex, statement, popcontext);
}
function forin(_type, value) {
if (value == "in") return cont();
}
function functiondef(type, value) {
if (type == "variable") {register(value); return cont(functiondef);}
if (value == "new") return cont(functiondef);
if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, typeuse, statement, popcontext);
}
function typeuse(type) {
if(type == ":") return cont(typestring);
}
function typestring(type) {
if(type == "type") return cont();
if(type == "variable") return cont();
if(type == "{") return cont(pushlex("}"), commasep(typeprop, "}"), poplex);
}
function typeprop(type) {
if(type == "variable") return cont(typeuse);
}
function funarg(type, value) {
if (type == "variable") {register(value); return cont(typeuse);}
}
// Interface
return {
startState: function(basecolumn) {
var defaulttypes = ["Int", "Float", "String", "Void", "Std", "Bool", "Dynamic", "Array"];
return {
tokenize: haxeTokenBase,
reAllowed: true,
kwAllowed: true,
cc: [],
lexical: new HaxeLexical((basecolumn || 0) - indentUnit, 0, "block", false),
localVars: parserConfig.localVars,
importedtypes: defaulttypes,
context: parserConfig.localVars && {vars: parserConfig.localVars},
indented: 0
};
},
token: function(stream, state) {
if (stream.sol()) {
if (!state.lexical.hasOwnProperty("align"))
state.lexical.align = false;
state.indented = stream.indentation();
}
if (stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
if (type == "comment") return style;
state.reAllowed = !!(type == "operator" || type == "keyword c" || type.match(/^[\[{}\(,;:]$/));
state.kwAllowed = type != '.';
return parseHaxe(state, style, type, content, stream);
},
indent: function(state, textAfter) {
if (state.tokenize != haxeTokenBase) return 0;
var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;
if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev;
var type = lexical.type, closing = firstChar == type;
if (type == "vardef") return lexical.indented + 4;
else if (type == "form" && firstChar == "{") return lexical.indented;
else if (type == "stat" || type == "form") return lexical.indented + indentUnit;
else if (lexical.info == "switch" && !closing)
return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
else if (lexical.align) return lexical.column + (closing ? 0 : 1);
else return lexical.indented + (closing ? 0 : indentUnit);
},
electricChars: "{}",
blockCommentStart: "/*",
blockCommentEnd: "*/",
lineComment: "//"
};
});
CodeMirror.defineMIME("text/x-haxe", "haxe");
CodeMirror.defineMode("hxml", function () {
return {
startState: function () {
return {
define: false,
inString: false
};
},
token: function (stream, state) {
var ch = stream.peek();
var sol = stream.sol();
///* comments */
if (ch == "#") {
stream.skipToEnd();
return "comment";
}
if (sol && ch == "-") {
var style = "variable-2";
stream.eat(/-/);
if (stream.peek() == "-") {
stream.eat(/-/);
style = "keyword a";
}
if (stream.peek() == "D") {
stream.eat(/[D]/);
style = "keyword c";
state.define = true;
}
stream.eatWhile(/[A-Z]/i);
return style;
}
var ch = stream.peek();
if (state.inString == false && ch == "'") {
state.inString = true;
ch = stream.next();
}
if (state.inString == true) {
if (stream.skipTo("'")) {
} else {
stream.skipToEnd();
}
if (stream.peek() == "'") {
stream.next();
state.inString = false;
}
return "string";
}
stream.next();
return null;
},
lineComment: "#"
};
});
CodeMirror.defineMIME("text/x-hxml", "hxml");
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/haxe/haxe.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/haxe/haxe.js",
"repo_id": "Humsen",
"token_count": 6878
} | 41 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
//mIRC mode by Ford_Lawnmower :: Based on Velocity mode by Steve O'Hara
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMIME("text/mirc", "mirc");
CodeMirror.defineMode("mirc", function() {
function parseWords(str) {
var obj = {}, words = str.split(" ");
for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
return obj;
}
var specials = parseWords("$! $$ $& $? $+ $abook $abs $active $activecid " +
"$activewid $address $addtok $agent $agentname $agentstat $agentver " +
"$alias $and $anick $ansi2mirc $aop $appactive $appstate $asc $asctime " +
"$asin $atan $avoice $away $awaymsg $awaytime $banmask $base $bfind " +
"$binoff $biton $bnick $bvar $bytes $calc $cb $cd $ceil $chan $chanmodes " +
"$chantypes $chat $chr $cid $clevel $click $cmdbox $cmdline $cnick $color " +
"$com $comcall $comchan $comerr $compact $compress $comval $cos $count " +
"$cr $crc $creq $crlf $ctime $ctimer $ctrlenter $date $day $daylight " +
"$dbuh $dbuw $dccignore $dccport $dde $ddename $debug $decode $decompress " +
"$deltok $devent $dialog $did $didreg $didtok $didwm $disk $dlevel $dll " +
"$dllcall $dname $dns $duration $ebeeps $editbox $emailaddr $encode $error " +
"$eval $event $exist $feof $ferr $fgetc $file $filename $filtered $finddir " +
"$finddirn $findfile $findfilen $findtok $fline $floor $fopen $fread $fserve " +
"$fulladdress $fulldate $fullname $fullscreen $get $getdir $getdot $gettok $gmt " +
"$group $halted $hash $height $hfind $hget $highlight $hnick $hotline " +
"$hotlinepos $ial $ialchan $ibl $idle $iel $ifmatch $ignore $iif $iil " +
"$inelipse $ini $inmidi $inpaste $inpoly $input $inrect $inroundrect " +
"$insong $instok $int $inwave $ip $isalias $isbit $isdde $isdir $isfile " +
"$isid $islower $istok $isupper $keychar $keyrpt $keyval $knick $lactive " +
"$lactivecid $lactivewid $left $len $level $lf $line $lines $link $lock " +
"$lock $locked $log $logstamp $logstampfmt $longfn $longip $lower $ltimer " +
"$maddress $mask $matchkey $matchtok $md5 $me $menu $menubar $menucontext " +
"$menutype $mid $middir $mircdir $mircexe $mircini $mklogfn $mnick $mode " +
"$modefirst $modelast $modespl $mouse $msfile $network $newnick $nick $nofile " +
"$nopath $noqt $not $notags $notify $null $numeric $numok $oline $onpoly " +
"$opnick $or $ord $os $passivedcc $pic $play $pnick $port $portable $portfree " +
"$pos $prefix $prop $protect $puttok $qt $query $rand $r $rawmsg $read $readomo " +
"$readn $regex $regml $regsub $regsubex $remove $remtok $replace $replacex " +
"$reptok $result $rgb $right $round $scid $scon $script $scriptdir $scriptline " +
"$sdir $send $server $serverip $sfile $sha1 $shortfn $show $signal $sin " +
"$site $sline $snick $snicks $snotify $sock $sockbr $sockerr $sockname " +
"$sorttok $sound $sqrt $ssl $sreq $sslready $status $strip $str $stripped " +
"$syle $submenu $switchbar $tan $target $ticks $time $timer $timestamp " +
"$timestampfmt $timezone $tip $titlebar $toolbar $treebar $trust $ulevel " +
"$ulist $upper $uptime $url $usermode $v1 $v2 $var $vcmd $vcmdstat $vcmdver " +
"$version $vnick $vol $wid $width $wildsite $wildtok $window $wrap $xor");
var keywords = parseWords("abook ajinvite alias aline ame amsg anick aop auser autojoin avoice " +
"away background ban bcopy beep bread break breplace bset btrunc bunset bwrite " +
"channel clear clearall cline clipboard close cnick color comclose comopen " +
"comreg continue copy creq ctcpreply ctcps dcc dccserver dde ddeserver " +
"debug dec describe dialog did didtok disable disconnect dlevel dline dll " +
"dns dqwindow drawcopy drawdot drawfill drawline drawpic drawrect drawreplace " +
"drawrot drawsave drawscroll drawtext ebeeps echo editbox emailaddr enable " +
"events exit fclose filter findtext finger firewall flash flist flood flush " +
"flushini font fopen fseek fsend fserve fullname fwrite ghide gload gmove " +
"gopts goto gplay gpoint gqreq groups gshow gsize gstop gtalk gunload hadd " +
"halt haltdef hdec hdel help hfree hinc hload hmake hop hsave ial ialclear " +
"ialmark identd if ignore iline inc invite iuser join kick linesep links list " +
"load loadbuf localinfo log mdi me menubar mkdir mnick mode msg nick noop notice " +
"notify omsg onotice part partall pdcc perform play playctrl pop protect pvoice " +
"qme qmsg query queryn quit raw reload remini remote remove rename renwin " +
"reseterror resetidle return rlevel rline rmdir run ruser save savebuf saveini " +
"say scid scon server set showmirc signam sline sockaccept sockclose socklist " +
"socklisten sockmark sockopen sockpause sockread sockrename sockudp sockwrite " +
"sound speak splay sreq strip switchbar timer timestamp titlebar tnick tokenize " +
"toolbar topic tray treebar ulist unload unset unsetall updatenl url uwho " +
"var vcadd vcmd vcrem vol while whois window winhelp write writeint if isalnum " +
"isalpha isaop isavoice isban ischan ishop isignore isin isincs isletter islower " +
"isnotify isnum ison isop isprotect isreg isupper isvoice iswm iswmcs " +
"elseif else goto menu nicklist status title icon size option text edit " +
"button check radio box scroll list combo link tab item");
var functions = parseWords("if elseif else and not or eq ne in ni for foreach while switch");
var isOperatorChar = /[+\-*&%=<>!?^\/\|]/;
function chain(stream, state, f) {
state.tokenize = f;
return f(stream, state);
}
function tokenBase(stream, state) {
var beforeParams = state.beforeParams;
state.beforeParams = false;
var ch = stream.next();
if (/[\[\]{}\(\),\.]/.test(ch)) {
if (ch == "(" && beforeParams) state.inParams = true;
else if (ch == ")") state.inParams = false;
return null;
}
else if (/\d/.test(ch)) {
stream.eatWhile(/[\w\.]/);
return "number";
}
else if (ch == "\\") {
stream.eat("\\");
stream.eat(/./);
return "number";
}
else if (ch == "/" && stream.eat("*")) {
return chain(stream, state, tokenComment);
}
else if (ch == ";" && stream.match(/ *\( *\(/)) {
return chain(stream, state, tokenUnparsed);
}
else if (ch == ";" && !state.inParams) {
stream.skipToEnd();
return "comment";
}
else if (ch == '"') {
stream.eat(/"/);
return "keyword";
}
else if (ch == "$") {
stream.eatWhile(/[$_a-z0-9A-Z\.:]/);
if (specials && specials.propertyIsEnumerable(stream.current().toLowerCase())) {
return "keyword";
}
else {
state.beforeParams = true;
return "builtin";
}
}
else if (ch == "%") {
stream.eatWhile(/[^,^\s^\(^\)]/);
state.beforeParams = true;
return "string";
}
else if (isOperatorChar.test(ch)) {
stream.eatWhile(isOperatorChar);
return "operator";
}
else {
stream.eatWhile(/[\w\$_{}]/);
var word = stream.current().toLowerCase();
if (keywords && keywords.propertyIsEnumerable(word))
return "keyword";
if (functions && functions.propertyIsEnumerable(word)) {
state.beforeParams = true;
return "keyword";
}
return null;
}
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = tokenBase;
break;
}
maybeEnd = (ch == "*");
}
return "comment";
}
function tokenUnparsed(stream, state) {
var maybeEnd = 0, ch;
while (ch = stream.next()) {
if (ch == ";" && maybeEnd == 2) {
state.tokenize = tokenBase;
break;
}
if (ch == ")")
maybeEnd++;
else if (ch != " ")
maybeEnd = 0;
}
return "meta";
}
return {
startState: function() {
return {
tokenize: tokenBase,
beforeParams: false,
inParams: false
};
},
token: function(stream, state) {
if (stream.eatSpace()) return null;
return state.tokenize(stream, state);
}
};
});
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/mirc/mirc.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/mirc/mirc.js",
"repo_id": "Humsen",
"token_count": 4855
} | 42 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("r", function(config) {
function wordObj(str) {
var words = str.split(" "), res = {};
for (var i = 0; i < words.length; ++i) res[words[i]] = true;
return res;
}
var atoms = wordObj("NULL NA Inf NaN NA_integer_ NA_real_ NA_complex_ NA_character_");
var builtins = wordObj("list quote bquote eval return call parse deparse");
var keywords = wordObj("if else repeat while function for in next break");
var blockkeywords = wordObj("if else repeat while function for");
var opChars = /[+\-*\/^<>=!&|~$:]/;
var curPunc;
function tokenBase(stream, state) {
curPunc = null;
var ch = stream.next();
if (ch == "#") {
stream.skipToEnd();
return "comment";
} else if (ch == "0" && stream.eat("x")) {
stream.eatWhile(/[\da-f]/i);
return "number";
} else if (ch == "." && stream.eat(/\d/)) {
stream.match(/\d*(?:e[+\-]?\d+)?/);
return "number";
} else if (/\d/.test(ch)) {
stream.match(/\d*(?:\.\d+)?(?:e[+\-]\d+)?L?/);
return "number";
} else if (ch == "'" || ch == '"') {
state.tokenize = tokenString(ch);
return "string";
} else if (ch == "." && stream.match(/.[.\d]+/)) {
return "keyword";
} else if (/[\w\.]/.test(ch) && ch != "_") {
stream.eatWhile(/[\w\.]/);
var word = stream.current();
if (atoms.propertyIsEnumerable(word)) return "atom";
if (keywords.propertyIsEnumerable(word)) {
// Block keywords start new blocks, except 'else if', which only starts
// one new block for the 'if', no block for the 'else'.
if (blockkeywords.propertyIsEnumerable(word) &&
!stream.match(/\s*if(\s+|$)/, false))
curPunc = "block";
return "keyword";
}
if (builtins.propertyIsEnumerable(word)) return "builtin";
return "variable";
} else if (ch == "%") {
if (stream.skipTo("%")) stream.next();
return "variable-2";
} else if (ch == "<" && stream.eat("-")) {
return "arrow";
} else if (ch == "=" && state.ctx.argList) {
return "arg-is";
} else if (opChars.test(ch)) {
if (ch == "$") return "dollar";
stream.eatWhile(opChars);
return "operator";
} else if (/[\(\){}\[\];]/.test(ch)) {
curPunc = ch;
if (ch == ";") return "semi";
return null;
} else {
return null;
}
}
function tokenString(quote) {
return function(stream, state) {
if (stream.eat("\\")) {
var ch = stream.next();
if (ch == "x") stream.match(/^[a-f0-9]{2}/i);
else if ((ch == "u" || ch == "U") && stream.eat("{") && stream.skipTo("}")) stream.next();
else if (ch == "u") stream.match(/^[a-f0-9]{4}/i);
else if (ch == "U") stream.match(/^[a-f0-9]{8}/i);
else if (/[0-7]/.test(ch)) stream.match(/^[0-7]{1,2}/);
return "string-2";
} else {
var next;
while ((next = stream.next()) != null) {
if (next == quote) { state.tokenize = tokenBase; break; }
if (next == "\\") { stream.backUp(1); break; }
}
return "string";
}
};
}
function push(state, type, stream) {
state.ctx = {type: type,
indent: state.indent,
align: null,
column: stream.column(),
prev: state.ctx};
}
function pop(state) {
state.indent = state.ctx.indent;
state.ctx = state.ctx.prev;
}
return {
startState: function() {
return {tokenize: tokenBase,
ctx: {type: "top",
indent: -config.indentUnit,
align: false},
indent: 0,
afterIdent: false};
},
token: function(stream, state) {
if (stream.sol()) {
if (state.ctx.align == null) state.ctx.align = false;
state.indent = stream.indentation();
}
if (stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
if (style != "comment" && state.ctx.align == null) state.ctx.align = true;
var ctype = state.ctx.type;
if ((curPunc == ";" || curPunc == "{" || curPunc == "}") && ctype == "block") pop(state);
if (curPunc == "{") push(state, "}", stream);
else if (curPunc == "(") {
push(state, ")", stream);
if (state.afterIdent) state.ctx.argList = true;
}
else if (curPunc == "[") push(state, "]", stream);
else if (curPunc == "block") push(state, "block", stream);
else if (curPunc == ctype) pop(state);
state.afterIdent = style == "variable" || style == "keyword";
return style;
},
indent: function(state, textAfter) {
if (state.tokenize != tokenBase) return 0;
var firstChar = textAfter && textAfter.charAt(0), ctx = state.ctx,
closing = firstChar == ctx.type;
if (ctx.type == "block") return ctx.indent + (firstChar == "{" ? 0 : config.indentUnit);
else if (ctx.align) return ctx.column + (closing ? 0 : 1);
else return ctx.indent + (closing ? 0 : config.indentUnit);
},
lineComment: "#"
};
});
CodeMirror.defineMIME("text/x-rsrc", "r");
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/r/r.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/r/r.js",
"repo_id": "Humsen",
"token_count": 2490
} | 43 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("solr", function() {
"use strict";
var isStringChar = /[^\s\|\!\+\-\*\?\~\^\&\:\(\)\[\]\{\}\^\"\\]/;
var isOperatorChar = /[\|\!\+\-\*\?\~\^\&]/;
var isOperatorString = /^(OR|AND|NOT|TO)$/i;
function isNumber(word) {
return parseFloat(word, 10).toString() === word;
}
function tokenString(quote) {
return function(stream, state) {
var escaped = false, next;
while ((next = stream.next()) != null) {
if (next == quote && !escaped) break;
escaped = !escaped && next == "\\";
}
if (!escaped) state.tokenize = tokenBase;
return "string";
};
}
function tokenOperator(operator) {
return function(stream, state) {
var style = "operator";
if (operator == "+")
style += " positive";
else if (operator == "-")
style += " negative";
else if (operator == "|")
stream.eat(/\|/);
else if (operator == "&")
stream.eat(/\&/);
else if (operator == "^")
style += " boost";
state.tokenize = tokenBase;
return style;
};
}
function tokenWord(ch) {
return function(stream, state) {
var word = ch;
while ((ch = stream.peek()) && ch.match(isStringChar) != null) {
word += stream.next();
}
state.tokenize = tokenBase;
if (isOperatorString.test(word))
return "operator";
else if (isNumber(word))
return "number";
else if (stream.peek() == ":")
return "field";
else
return "string";
};
}
function tokenBase(stream, state) {
var ch = stream.next();
if (ch == '"')
state.tokenize = tokenString(ch);
else if (isOperatorChar.test(ch))
state.tokenize = tokenOperator(ch);
else if (isStringChar.test(ch))
state.tokenize = tokenWord(ch);
return (state.tokenize != tokenBase) ? state.tokenize(stream, state) : null;
}
return {
startState: function() {
return {
tokenize: tokenBase
};
},
token: function(stream, state) {
if (stream.eatSpace()) return null;
return state.tokenize(stream, state);
}
};
});
CodeMirror.defineMIME("text/x-solr", "solr");
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/solr/solr.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/solr/solr.js",
"repo_id": "Humsen",
"token_count": 1122
} | 44 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed"),
require("../../addon/mode/overlay"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "../htmlmixed/htmlmixed",
"../../addon/mode/overlay"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("tornado:inner", function() {
var keywords = ["and","as","assert","autoescape","block","break","class","comment","context",
"continue","datetime","def","del","elif","else","end","escape","except",
"exec","extends","false","finally","for","from","global","if","import","in",
"include","is","json_encode","lambda","length","linkify","load","module",
"none","not","or","pass","print","put","raise","raw","return","self","set",
"squeeze","super","true","try","url_escape","while","with","without","xhtml_escape","yield"];
keywords = new RegExp("^((" + keywords.join(")|(") + "))\\b");
function tokenBase (stream, state) {
stream.eatWhile(/[^\{]/);
var ch = stream.next();
if (ch == "{") {
if (ch = stream.eat(/\{|%|#/)) {
state.tokenize = inTag(ch);
return "tag";
}
}
}
function inTag (close) {
if (close == "{") {
close = "}";
}
return function (stream, state) {
var ch = stream.next();
if ((ch == close) && stream.eat("}")) {
state.tokenize = tokenBase;
return "tag";
}
if (stream.match(keywords)) {
return "keyword";
}
return close == "#" ? "comment" : "string";
};
}
return {
startState: function () {
return {tokenize: tokenBase};
},
token: function (stream, state) {
return state.tokenize(stream, state);
}
};
});
CodeMirror.defineMode("tornado", function(config) {
var htmlBase = CodeMirror.getMode(config, "text/html");
var tornadoInner = CodeMirror.getMode(config, "tornado:inner");
return CodeMirror.overlayMode(htmlBase, tornadoInner);
});
CodeMirror.defineMIME("text/x-tornado", "tornado");
});
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/tornado/tornado.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/mode/tornado/tornado.js",
"repo_id": "Humsen",
"token_count": 1061
} | 45 |
/*
Name: 3024 night
Author: Jan T. Sott (http://github.com/idleberg)
CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror)
Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)
*/
.cm-s-3024-night.CodeMirror {background: #090300; color: #d6d5d4;}
.cm-s-3024-night div.CodeMirror-selected {background: #3a3432 !important;}
.cm-s-3024-night.CodeMirror ::selection { background: rgba(58, 52, 50, .99); }
.cm-s-3024-night.CodeMirror ::-moz-selection { background: rgba(58, 52, 50, .99); }
.cm-s-3024-night .CodeMirror-gutters {background: #090300; border-right: 0px;}
.cm-s-3024-night .CodeMirror-guttermarker { color: #db2d20; }
.cm-s-3024-night .CodeMirror-guttermarker-subtle { color: #5c5855; }
.cm-s-3024-night .CodeMirror-linenumber {color: #5c5855;}
.cm-s-3024-night .CodeMirror-cursor {border-left: 1px solid #807d7c !important;}
.cm-s-3024-night span.cm-comment {color: #cdab53;}
.cm-s-3024-night span.cm-atom {color: #a16a94;}
.cm-s-3024-night span.cm-number {color: #a16a94;}
.cm-s-3024-night span.cm-property, .cm-s-3024-night span.cm-attribute {color: #01a252;}
.cm-s-3024-night span.cm-keyword {color: #db2d20;}
.cm-s-3024-night span.cm-string {color: #fded02;}
.cm-s-3024-night span.cm-variable {color: #01a252;}
.cm-s-3024-night span.cm-variable-2 {color: #01a0e4;}
.cm-s-3024-night span.cm-def {color: #e8bbd0;}
.cm-s-3024-night span.cm-bracket {color: #d6d5d4;}
.cm-s-3024-night span.cm-tag {color: #db2d20;}
.cm-s-3024-night span.cm-link {color: #a16a94;}
.cm-s-3024-night span.cm-error {background: #db2d20; color: #807d7c;}
.cm-s-3024-night .CodeMirror-activeline-background {background: #2F2F2F !important;}
.cm-s-3024-night .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;}
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/theme/3024-night.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/theme/3024-night.css",
"repo_id": "Humsen",
"token_count": 800
} | 46 |
.cm-s-neat span.cm-comment { color: #a86; }
.cm-s-neat span.cm-keyword { line-height: 1em; font-weight: bold; color: blue; }
.cm-s-neat span.cm-string { color: #a22; }
.cm-s-neat span.cm-builtin { line-height: 1em; font-weight: bold; color: #077; }
.cm-s-neat span.cm-special { line-height: 1em; font-weight: bold; color: #0aa; }
.cm-s-neat span.cm-variable { color: black; }
.cm-s-neat span.cm-number, .cm-s-neat span.cm-atom { color: #3a3; }
.cm-s-neat span.cm-meta {color: #555;}
.cm-s-neat span.cm-link { color: #3a3; }
.cm-s-neat .CodeMirror-activeline-background {background: #e8f2ff !important;}
.cm-s-neat .CodeMirror-matchingbracket {outline:1px solid grey; color:black !important;}
| Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/theme/neat.css/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/lib/codemirror/theme/neat.css",
"repo_id": "Humsen",
"token_count": 301
} | 47 |
/*!
* Help dialog plugin for Editor.md
*
* @file help-dialog.js
* @author pandao
* @version 1.2.0
* @updateTime 2015-03-08
* {@link https://github.com/pandao/editor.md}
* @license MIT
*/
(function() {
var factory = function (exports) {
var $ = jQuery;
var pluginName = "help-dialog";
exports.fn.helpDialog = function() {
var _this = this;
var lang = this.lang;
var editor = this.editor;
var settings = this.settings;
var path = settings.pluginPath + pluginName + "/";
var classPrefix = this.classPrefix;
var dialogName = classPrefix + pluginName, dialog;
var dialogLang = lang.dialog.help;
if (editor.find("." + dialogName).length < 1)
{
var dialogContent = "<div class=\"markdown-body\" style=\"font-family:微软雅黑, Helvetica, Tahoma, STXihei,Arial;height:390px;overflow:auto;font-size:14px;border-bottom:1px solid #ddd;padding:0 20px 20px 0;\"></div>";
dialog = this.createDialog({
name : dialogName,
title : dialogLang.title,
width : 840,
height : 540,
mask : settings.dialogShowMask,
drag : settings.dialogDraggable,
content : dialogContent,
lockScreen : settings.dialogLockScreen,
maskStyle : {
opacity : settings.dialogMaskOpacity,
backgroundColor : settings.dialogMaskBgColor
},
buttons : {
close : [lang.buttons.close, function() {
this.hide().lockScreen(false).hideMask();
return false;
}]
}
});
}
dialog = editor.find("." + dialogName);
this.dialogShowMask(dialog);
this.dialogLockScreen();
dialog.show();
var helpContent = dialog.find(".markdown-body");
if (helpContent.html() === "")
{
$.get(path + "help.md", function(text) {
var md = exports.$marked(text);
helpContent.html(md);
helpContent.find("a").attr("target", "_blank");
});
}
};
};
// CommonJS/Node.js
if (typeof require === "function" && typeof exports === "object" && typeof module === "object")
{
module.exports = factory;
}
else if (typeof define === "function") // AMD/CMD/Sea.js
{
if (define.amd) { // for Require.js
define(["editormd"], function(editormd) {
factory(editormd);
});
} else { // for Sea.js
define(function(require) {
var editormd = require("./../../editormd");
factory(editormd);
});
}
}
else
{
factory(window.editormd);
}
})();
| Humsen/web/web-mobile/WebContent/plugins/editormd/plugins/help-dialog/help-dialog.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/editormd/plugins/help-dialog/help-dialog.js",
"repo_id": "Humsen",
"token_count": 1241
} | 48 |
(function($) {
/**
* Indonesian language package
* Translated by @egig
*/
$.fn.bootstrapValidator.i18n = $.extend(true, $.fn.bootstrapValidator.i18n, {
base64: {
'default': 'Silahkan isi karakter base 64 tersandi yang valid'
},
between: {
'default': 'Silahkan isi nilai antara %s dan %s',
notInclusive: 'Silahkan isi nilai antara %s dan %s, strictly'
},
callback: {
'default': 'Silahkan isi nilai yang valid'
},
choice: {
'default': 'Silahkan isi nilai yang valid',
less: 'Silahkan pilih pilihan %s pada minimum',
more: 'Silahkan pilih pilihan %s pada maksimum',
between: 'Silahkan pilih pilihan %s - %s'
},
color: {
'default': 'Silahkan isi karakter warna yang valid'
},
creditCard: {
'default': 'Silahkan isi nomor kartu kredit yang valid'
},
cusip: {
'default': 'Silahkan isi nomor CUSIP yang valid'
},
cvv: {
'default': 'Silahkan isi nomor CVV yang valid'
},
date: {
'default': 'Silahkan isi tanggal yang benar',
min: 'Silahkan isi tanggal setelah tanggal %s',
max: 'Silahkan isi tanggal sebelum tanggal %s',
range: 'Silahkan isi tanggal antara %s - %s'
},
different: {
'default': 'Silahkan isi nilai yang berbeda'
},
digits: {
'default': 'Silahkan isi dengan hanya digit'
},
ean: {
'default': 'Silahkan isi nomor EAN yang valid'
},
emailAddress: {
'default': 'Silahkan isi alamat email yang valid'
},
file: {
'default': 'Silahkan pilih file yang valid'
},
greaterThan: {
'default': 'Silahkan isi nilai yang lebih besar atau sama dengan %s',
notInclusive: 'Silahkan is nilai yang lebih besar dari %s'
},
grid: {
'default': 'Silahkan nomor GRId yang valid'
},
hex: {
'default': 'Silahkan isi karakter hexadecimal yang valid'
},
hexColor: {
'default': 'Silahkan isi karakter warna hex yang valid'
},
iban: {
'default': 'silahkan isi nomor IBAN yang valid',
countryNotSupported: 'Kode negara %s belum didukung',
country: 'Silahkan isi nomor IBAN yang valid dalam %s',
countries: {
AD: 'Andorra',
AE: 'Uni Emirat Arab',
AL: 'Albania',
AO: 'Angola',
AT: 'Austria',
AZ: 'Azerbaijan',
BA: 'Bosnia and Herzegovina',
BE: 'Belgia',
BF: 'Burkina Faso',
BG: 'Bulgaria',
BH: 'Bahrain',
BI: 'Burundi',
BJ: 'Benin',
BR: 'Brazil',
CH: 'Switzerland',
CI: 'Pantai Gading',
CM: 'Kamerun',
CR: 'Costa Rica',
CV: 'Cape Verde',
CY: 'Cyprus',
CZ: 'Czech',
DE: 'Jerman',
DK: 'Denmark',
DO: 'Republik Dominika',
DZ: 'Algeria',
EE: 'Estonia',
ES: 'Spanyol',
FI: 'Finlandia',
FO: 'Faroe Islands',
FR: 'Francis',
GB: 'Inggris',
GE: 'Georgia',
GI: 'Gibraltar',
GL: 'Greenland',
GR: 'Yunani',
GT: 'Guatemala',
HR: 'Kroasia',
HU: 'Hungary',
IE: 'Irlandia',
IL: 'Israel',
IR: 'Iran',
IS: 'Iceland',
IT: 'Italia',
JO: 'Jordan',
KW: 'Kuwait',
KZ: 'Kazakhstan',
LB: 'Libanon',
LI: 'Liechtenstein',
LT: 'Lithuania',
LU: 'Luxembourg',
LV: 'Latvia',
MC: 'Monaco',
MD: 'Moldova',
ME: 'Montenegro',
MG: 'Madagascar',
MK: 'Macedonia',
ML: 'Mali',
MR: 'Mauritania',
MT: 'Malta',
MU: 'Mauritius',
MZ: 'Mozambique',
NL: 'Netherlands',
NO: 'Norway',
PK: 'Pakistan',
PL: 'Polandia',
PS: 'Palestina',
PT: 'Portugal',
QA: 'Qatar',
RO: 'Romania',
RS: 'Serbia',
SA: 'Saudi Arabia',
SE: 'Swedia',
SI: 'Slovenia',
SK: 'Slovakia',
SM: 'San Marino',
SN: 'Senegal',
TN: 'Tunisia',
TR: 'Turki',
VG: 'Virgin Islands, British'
}
},
id: {
'default': 'Silahkan isi nomor identitas yang valid',
countryNotSupported: 'Kode negara %s tidak didukung',
country: 'Silahkan isi nomor identitas yang valid dalam %s',
countries: {
BA: 'Bosnia and Herzegovina',
BG: 'Bulgaria',
BR: 'Brazil',
CH: 'Switzerland',
CL: 'Chile',
CN: 'Cina',
CZ: 'Czech',
DK: 'Denmark',
EE: 'Estonia',
ES: 'Spanyol',
FI: 'Finlandia',
HR: 'Kroasia',
IE: 'Irlandia',
IS: 'Iceland',
LT: 'Lithuania',
LV: 'Latvia',
ME: 'Montenegro',
MK: 'Macedonia',
NL: 'Netherlands',
RO: 'Romania',
RS: 'Serbia',
SE: 'Sweden',
SI: 'Slovenia',
SK: 'Slovakia',
SM: 'San Marino',
TH: 'Thailand',
ZA: 'Africa Selatan'
}
},
identical: {
'default': 'Silahkan isi nilai yang sama'
},
imei: {
'default': 'Silahkan isi nomor IMEI yang valid'
},
imo: {
'default': 'Silahkan isi nomor IMO yang valid'
},
integer: {
'default': 'Silahkan isi angka yang valid'
},
ip: {
'default': 'Silahkan isi alamat IP yang valid',
ipv4: 'Silahkan isi alamat IPv4 yang valid',
ipv6: 'Silahkan isi alamat IPv6 yang valid'
},
isbn: {
'default': 'Slilahkan isi nomor ISBN yang valid'
},
isin: {
'default': 'Silahkan isi ISIN yang valid'
},
ismn: {
'default': 'Silahkan isi nomor ISMN yang valid'
},
issn: {
'default': 'Silahkan isi nomor ISSN yang valid'
},
lessThan: {
'default': 'Silahkan isi nilai kurang dari atau sama dengan %s',
notInclusive: 'Silahkan isi nilai kurang dari %s'
},
mac: {
'default': 'Silahkan isi MAC address yang valid'
},
meid: {
'default': 'Silahkan isi nomor MEID yang valid'
},
notEmpty: {
'default': 'Silahkan isi'
},
numeric: {
'default': 'Silahkan isi nomor yang valid'
},
phone: {
'default': 'Silahkan isi nomor telepon yang valid',
countryNotSupported: 'Kode negara %s belum didukung',
country: 'Silahkan isi nomor telepon yang valid dalam %s',
countries: {
BR: 'Brazil',
CN: 'Cina',
CZ: 'Czech',
DE: 'Jerman',
DK: 'Denmark',
ES: 'Spanyol',
FR: 'Francis',
GB: 'Inggris',
MA: 'Maroko',
PK: 'Pakistan',
RO: 'Romania',
RU: 'Russia',
SK: 'Slovakia',
TH: 'Thailand',
US: 'Amerika Serikat',
VE: 'Venezuela'
}
},
regexp: {
'default': 'Silahkan isi nilai yang cocok dengan pola'
},
remote: {
'default': 'Silahkan isi nilai yang valid'
},
rtn: {
'default': 'Silahkan isi nomor RTN yang valid'
},
sedol: {
'default': 'Silahkan isi nomor SEDOL yang valid'
},
siren: {
'default': 'Silahkan isi nomor SIREN yang valid'
},
siret: {
'default': 'Silahkan isi nomor SIRET yang valid'
},
step: {
'default': 'Silahkan isi langkah yang benar pada %s'
},
stringCase: {
'default': 'Silahkan isi hanya huruf kecil',
upper: 'Silahkan isi hanya huruf besar'
},
stringLength: {
'default': 'Silahkan isi nilai dengan panjang karakter yang benar',
less: 'Silahkan isi kurang dari %s karakter',
more: 'Silahkan isi lebih dari %s karakter',
between: 'Silahkan isi antara %s dan %s panjang karakter'
},
uri: {
'default': 'Silahkan isi URI yang valid'
},
uuid: {
'default': 'Silahkan isi nomor UUID yang valid',
version: 'Silahkan si nomor versi %s UUID yang valid'
},
vat: {
'default': 'Silahkan isi nomor VAT yang valid',
countryNotSupported: 'Kode negara %s belum didukung',
country: 'Silahkan nomor VAT yang valid dalam %s',
countries: {
AT: 'Austria',
BE: 'Belgium',
BG: 'Bulgaria',
BR: 'Brazil',
CH: 'Switzerland',
CY: 'Cyprus',
CZ: 'Czech',
DE: 'Jerman',
DK: 'Denmark',
EE: 'Estonia',
ES: 'Spanyol',
FI: 'Finlandia',
FR: 'Francis',
GB: 'Inggris',
GR: 'Yunani',
EL: 'Yunani',
HU: 'Hungaria',
HR: 'Kroasia',
IE: 'Irlandia',
IS: 'Iceland',
IT: 'Italy',
LT: 'Lithuania',
LU: 'Luxembourg',
LV: 'Latvia',
MT: 'Malta',
NL: 'Belanda',
NO: 'Norway',
PL: 'Polandia',
PT: 'Portugal',
RO: 'Romania',
RU: 'Russia',
RS: 'Serbia',
SE: 'Sweden',
SI: 'Slovenia',
SK: 'Slovakia',
VE: 'Venezuela',
ZA: 'Afrika Selatan'
}
},
vin: {
'default': 'Silahkan isi nomor VIN yang valid'
},
zipCode: {
'default': 'Silahkan isi kode pos yang valid',
countryNotSupported: 'Kode negara %s belum didukung',
country: 'Silahkan isi kode pos yang valid di %s',
countries: {
AT: 'Austria',
BR: 'Brazil',
CA: 'Kanada',
CH: 'Switzerland',
CZ: 'Czech',
DE: 'Jerman',
DK: 'Denmark',
FR: 'Francis',
GB: 'Inggris',
IE: 'Irlandia',
IT: 'Italia',
MA: 'Maroko',
NL: 'Belanda',
PT: 'Portugal',
RO: 'Romania',
RU: 'Russia',
SE: 'Sweden',
SG: 'Singapura',
SK: 'Slovakia',
US: 'Amerika Serikat'
}
}
});
}(window.jQuery));
| Humsen/web/web-mobile/WebContent/plugins/validator/js/language/id_ID.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/validator/js/language/id_ID.js",
"repo_id": "Humsen",
"token_count": 7551
} | 49 |
(function($) {
/**
* Vietnamese language package
* Translated by @nghuuphuoc
*/
$.fn.bootstrapValidator.i18n = $.extend(true, $.fn.bootstrapValidator.i18n, {
base64: {
'default': 'Vui lòng nhập chuỗi mã hoá base64 hợp lệ'
},
between: {
'default': 'Vui lòng nhập giá trị nằm giữa %s và %s',
notInclusive: 'Vui lòng nhập giá trị nằm giữa %s và %s'
},
callback: {
'default': 'Vui lòng nhập giá trị hợp lệ'
},
choice: {
'default': 'Vui lòng nhập giá trị hợp lệ',
less: 'Vui lòng chọn ít nhất %s lựa chọn',
more: 'Vui lòng chọn nhiều nhất %s lựa chọn',
between: 'Vui lòng chọn %s - %s lựa chọn'
},
color: {
'default': 'Vui lòng nhập mã màu hợp lệ'
},
creditCard: {
'default': 'Vui lòng nhập số thẻ tín dụng hợp lệ'
},
cusip: {
'default': 'Vui lòng nhập số CUSIP hợp lệ'
},
cvv: {
'default': 'Vui lòng nhập số CVV hợp lệ'
},
date: {
'default': 'Vui lòng nhập ngày hợp lệ',
min: 'Vui lòng nhập ngày sau %s',
max: 'Vui lòng nhập ngày trước %s',
range: 'Vui lòng nhập ngày trong khoảng %s - %s'
},
different: {
'default': 'Vui lòng nhập một giá trị khác'
},
digits: {
'default': 'Vui lòng chỉ nhập số'
},
ean: {
'default': 'Vui lòng nhập số EAN hợp lệ'
},
emailAddress: {
'default': 'Vui lòng nhập địa chỉ email hợp lệ'
},
file: {
'default': 'Vui lòng chọn file hợp lệ'
},
greaterThan: {
'default': 'Vui lòng nhập giá trị lớn hơn hoặc bằng %s',
notInclusive: 'Vui lòng nhập giá trị lớn hơn %s'
},
grid: {
'default': 'Vui lòng nhập số GRId hợp lệ'
},
hex: {
'default': 'Vui lòng nhập số hexa hợp lệ'
},
hexColor: {
'default': 'Vui lòng nhập mã màu hợp lệ'
},
iban: {
'default': 'Vui lòng nhập số IBAN hợp lệ',
countryNotSupported: 'Mã quốc gia %s không được hỗ trợ',
country: 'Vui lòng nhập mã IBAN hợp lệ của %s',
countries: {
AD: 'Andorra',
AE: 'Tiểu vương quốc Ả Rập thống nhất',
AL: 'Albania',
AO: 'Angola',
AT: 'Áo',
AZ: 'Azerbaijan',
BA: 'Bosnia và Herzegovina',
BE: 'Bỉ',
BF: 'Burkina Faso',
BG: 'Bulgaria',
BH: 'Bahrain',
BI: 'Burundi',
BJ: 'Benin',
BR: 'Brazil',
CH: 'Thuỵ Sĩ',
CI: 'Bờ Biển Ngà',
CM: 'Cameroon',
CR: 'Costa Rica',
CV: 'Cape Verde',
CY: 'Síp',
CZ: 'Séc',
DE: 'Đức',
DK: 'Đan Mạch',
DO: 'Dominican',
DZ: 'Algeria',
EE: 'Estonia',
ES: 'Tây Ban Nha',
FI: 'Phần Lan',
FO: 'Đảo Faroe',
FR: 'Pháp',
GB: 'Vương quốc Anh',
GE: 'Georgia',
GI: 'Gibraltar',
GL: 'Greenland',
GR: 'Hy Lạp',
GT: 'Guatemala',
HR: 'Croatia',
HU: 'Hungary',
IE: 'Ireland',
IL: 'Israel',
IR: 'Iran',
IS: 'Iceland',
IT: 'Ý',
JO: 'Jordan',
KW: 'Kuwait',
KZ: 'Kazakhstan',
LB: 'Lebanon',
LI: 'Liechtenstein',
LT: 'Lithuania',
LU: 'Luxembourg',
LV: 'Latvia',
MC: 'Monaco',
MD: 'Moldova',
ME: 'Montenegro',
MG: 'Madagascar',
MK: 'Macedonia',
ML: 'Mali',
MR: 'Mauritania',
MT: 'Malta',
MU: 'Mauritius',
MZ: 'Mozambique',
NL: 'Hà Lan',
NO: 'Na Uy',
PK: 'Pakistan',
PL: 'Ba Lan',
PS: 'Palestine',
PT: 'Bồ Đào Nha',
QA: 'Qatar',
RO: 'Romania',
RS: 'Serbia',
SA: 'Ả Rập Xê Út',
SE: 'Thuỵ Điển',
SI: 'Slovenia',
SK: 'Slovakia',
SM: 'San Marino',
SN: 'Senegal',
TN: 'Tunisia',
TR: 'Thổ Nhĩ Kỳ',
VG: 'Đảo Virgin, Anh quốc'
}
},
id: {
'default': 'Vui lòng nhập mã ID hợp lệ',
countryNotSupported: 'Mã quốc gia %s không được hỗ trợ',
country: 'Vui lòng nhập mã ID hợp lệ của %s',
countries: {
BA: 'Bosnia và Herzegovina',
BG: 'Bulgaria',
BR: 'Brazil',
CH: 'Thuỵ Sĩ',
CL: 'Chi Lê',
CN: 'Trung Quốc',
CZ: 'Séc',
DK: 'Đan Mạch',
EE: 'Estonia',
ES: 'Tây Ban Nha',
FI: 'Phần Lan',
HR: 'Croatia',
IE: 'Ireland',
IS: 'Iceland',
LT: 'Lithuania',
LV: 'Latvia',
ME: 'Montenegro',
MK: 'Macedonia',
NL: 'Hà Lan',
RO: 'Romania',
RS: 'Serbia',
SE: 'Thuỵ Điển',
SI: 'Slovenia',
SK: 'Slovakia',
SM: 'San Marino',
TH: 'Thái Lan',
ZA: 'Nam Phi'
}
},
identical: {
'default': 'Vui lòng nhập cùng giá trị'
},
imei: {
'default': 'Vui lòng nhập số IMEI hợp lệ'
},
imo: {
'default': 'Vui lòng nhập số IMO hợp lệ'
},
integer: {
'default': 'Vui lòng nhập số hợp lệ'
},
ip: {
'default': 'Vui lòng nhập địa chỉ IP hợp lệ',
ipv4: 'Vui lòng nhập địa chỉ IPv4 hợp lệ',
ipv6: 'Vui lòng nhập địa chỉ IPv6 hợp lệ'
},
isbn: {
'default': 'Vui lòng nhập số ISBN hợp lệ'
},
isin: {
'default': 'Vui lòng nhập số ISIN hợp lệ'
},
ismn: {
'default': 'Vui lòng nhập số ISMN hợp lệ'
},
issn: {
'default': 'Vui lòng nhập số ISSN hợp lệ'
},
lessThan: {
'default': 'Vui lòng nhập giá trị nhỏ hơn hoặc bằng %s',
notInclusive: 'Vui lòng nhập giá trị nhỏ hơn %s'
},
mac: {
'default': 'Vui lòng nhập địa chỉ MAC hợp lệ'
},
meid: {
'default': 'Vui lòng nhập số MEID hợp lệ'
},
notEmpty: {
'default': 'Vui lòng nhập giá trị'
},
numeric: {
'default': 'Vui lòng nhập số hợp lệ'
},
phone: {
'default': 'Vui lòng nhập số điện thoại hợp lệ',
countryNotSupported: 'Mã quốc gia %s không được hỗ trợ',
country: 'Vui lòng nhập số điện thoại hợp lệ của %s',
countries: {
BR: 'Brazil',
CN: 'Trung Quốc',
CZ: 'Séc',
DE: 'Đức',
DK: 'Đan Mạch',
ES: 'Tây Ban Nha',
FR: 'Pháp',
GB: 'Vương quốc Anh',
MA: 'Maroc',
PK: 'Pakistan',
RO: 'Romania',
RU: 'Nga',
SK: 'Slovakia',
TH: 'Thái Lan',
US: 'Mỹ',
VE: 'Venezuela'
}
},
regexp: {
'default': 'Vui lòng nhập giá trị thích hợp với biểu mẫu'
},
remote: {
'default': 'Vui lòng nhập giá trị hợp lệ'
},
rtn: {
'default': 'Vui lòng nhập số RTN hợp lệ'
},
sedol: {
'default': 'Vui lòng nhập số SEDOL hợp lệ'
},
siren: {
'default': 'Vui lòng nhập số Siren hợp lệ'
},
siret: {
'default': 'Vui lòng nhập số Siret hợp lệ'
},
step: {
'default': 'Vui lòng nhập bước nhảy của %s'
},
stringCase: {
'default': 'Vui lòng nhập ký tự thường',
upper: 'Vui lòng nhập ký tự in hoa'
},
stringLength: {
'default': 'Vui lòng nhập giá trị có độ dài hợp lệ',
less: 'Vui lòng nhập ít hơn %s ký tự',
more: 'Vui lòng nhập nhiều hơn %s ký tự',
between: 'Vui lòng nhập giá trị có độ dài trong khoảng %s và %s ký tự'
},
uri: {
'default': 'Vui lòng nhập địa chỉ URI hợp lệ'
},
uuid: {
'default': 'Vui lòng nhập số UUID hợp lệ',
version: 'Vui lòng nhập số UUID phiên bản %s hợp lệ'
},
vat: {
'default': 'Vui lòng nhập số VAT hợp lệ',
countryNotSupported: 'Mã quốc gia %s không được hỗ trợ',
country: 'Vui lòng nhập số VAT hợp lệ của %s',
countries: {
AT: 'Áo',
BE: 'Bỉ',
BG: 'Bulgaria',
BR: 'Brazil',
CH: 'Thuỵ Sĩ',
CY: 'Síp',
CZ: 'Séc',
DE: 'Đức',
DK: 'Đan Mạch',
EE: 'Estonia',
ES: 'Tây Ban Nha',
FI: 'Phần Lan',
FR: 'Pháp',
GB: 'Vương quốc Anh',
GR: 'Hy Lạp',
EL: 'Hy Lạp',
HU: 'Hungari',
HR: 'Croatia',
IE: 'Ireland',
IS: 'Iceland',
IT: 'Ý',
LT: 'Lithuania',
LU: 'Luxembourg',
LV: 'Latvia',
MT: 'Malta',
NL: 'Hà Lan',
NO: 'Na Uy',
PL: 'Ba Lan',
PT: 'Bồ Đào Nha',
RO: 'Romania',
RU: 'Nga',
RS: 'Serbia',
SE: 'Thuỵ Điển',
SI: 'Slovenia',
SK: 'Slovakia',
VE: 'Venezuela',
ZA: 'Nam Phi'
}
},
vin: {
'default': 'Vui lòng nhập số VIN hợp lệ'
},
zipCode: {
'default': 'Vui lòng nhập mã bưu điện hợp lệ',
countryNotSupported: 'Mã quốc gia %s không được hỗ trợ',
country: 'Vui lòng nhập mã bưu điện hợp lệ của %s',
countries: {
AT: 'Áo',
BR: 'Brazil',
CA: 'Canada',
CH: 'Thuỵ Sĩ',
CZ: 'Séc',
DE: 'Đức',
DK: 'Đan Mạch',
FR: 'Pháp',
GB: 'Vương quốc Anh',
IE: 'Ireland',
IT: 'Ý',
MA: 'Maroc',
NL: 'Hà Lan',
PT: 'Bồ Đào Nha',
RO: 'Romania',
RU: 'Nga',
SE: 'Thuỵ Sĩ',
SG: 'Singapore',
SK: 'Slovakia',
US: 'Mỹ'
}
}
});
}(window.jQuery));
| Humsen/web/web-mobile/WebContent/plugins/validator/js/language/vi_VN.js/0 | {
"file_path": "Humsen/web/web-mobile/WebContent/plugins/validator/js/language/vi_VN.js",
"repo_id": "Humsen",
"token_count": 9104
} | 50 |
## 使用时请将此文件改成 mysql_connect_info.properties
# 数据库url
url_psql=jdbc:mysql://127.0.0.1:3306/
# 在linux服务器运行时查询此数据库
dbname_official=web
# 在windows本地运行时查询此数据库
dbname_test=web_test
# 数据库用户名称
username_webuser=web_user
# 数据库用户密码
password_webuser=123456
# 数据库驱动
driver_class=com.mysql.jdbc.Driver | Humsen/web/web-mobile/config/mysql_connect_info_template.properties/0 | {
"file_path": "Humsen/web/web-mobile/config/mysql_connect_info_template.properties",
"repo_id": "Humsen",
"token_count": 226
} | 51 |
@charset "UTF-8";
#bar_left {
float: left;
width: 15%;
margin-left: 1%;
}
.latest-version {
font-size: smaller;
float: right;
}
.category-hide {
display: none;
}
.category-show {
margin-left: 20px;
} | Humsen/web/web-pc/WebContent/css/navigation/leftbar.css/0 | {
"file_path": "Humsen/web/web-pc/WebContent/css/navigation/leftbar.css",
"repo_id": "Humsen",
"token_count": 94
} | 52 |
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>何明胜的个人网站</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description"
content="欢迎来到何明胜的个人网站.本站主要用于记录和分享本人的学习心得和编程经验,并分享常见可复用代码、推荐书籍以及软件等资源.本站源码已托管github,欢迎访问:https://github.com/HelloHusen/web" />
<meta name="keywords" content="何明胜,何明胜的个人网站,何明胜的博客,一格的程序人生" />
<meta name="author" content="何明胜,一格">
<!-- 网站图标 -->
<link rel="shortcut icon" href="/images/favicon.ico">
<!-- jQuery -->
<script src="/plugins/jquery/js/jquery-3.2.1.min.js"></script>
<!-- 最新更新文章简介 -->
<link rel="stylesheet" href="/css/index/article-profile.css">
<!-- 最新更新文章简介 -->
<link rel="stylesheet" href="/css/index/index.css">
<!-- 加载最新3篇博客 -->
<script src="/js/index/latestblog.js"></script>
<!-- 加载最近3篇代码 -->
<script src="/js/index/latestcode.js"></script>
<!-- js文件 -->
<script src="/js/index/index.js"></script>
</head>
<body>
<input id="menuBarNo" type="hidden" value="0" />
<div id="fh5co-page">
<!-- 左侧导航 -->
<!-- 中间内容 -->
<div id="fh5co-main">
<!-- 首页轮播 -->
<div id="indexCarousel" class="carousel slide carousel-height carousel-margin">
<!-- 轮播(Carousel)指标 -->
<ol class="carousel-indicators">
<li data-target="#indexCarousel" data-slide-to="0" class="active"></li>
<li data-target="#indexCarousel" data-slide-to="1"></li>
<li data-target="#indexCarousel" data-slide-to="2"></li>
</ol>
<!-- 轮播(Carousel)项目 -->
<div class="carousel-inner">
<div class="item carousel-height active">
<img src="/images/carousel/casel-1.jpg" alt="First slide">
</div>
<div class="item carousel-height">
<img src="/images/carousel/casel-2.jpg" alt="Second slide">
</div>
<div class="item carousel-height">
<img src="/images/carousel/casel-3.jpg" alt="Third slide">
</div>
</div>
<!-- 轮播(Carousel)导航 -->
<a class="left carousel-control" href="#indexCarousel" role="button"
data-slide="prev"> <span
class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a> <a class="right carousel-control" href="#indexCarousel" role="button"
data-slide="next"> <span
class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
<div class="fh5co-narrow-content article-box-div">
<h2 class="fh5co-heading article-bar"
data-animate-effect="fadeInLeft">最近更新的博客</h2>
<a href="/module/blog.hms" class="read-more-article"><span
class="glyphicon glyphicon-hand-right"></span> 阅读更多博客</a>
<div id="latestBlog" class="row"></div>
</div>
<hr class="index-hr" />
<div class="fh5co-narrow-content article-box-div">
<h2 class="fh5co-heading article-bar"
data-animate-effect="fadeInLeft">最近更新的代码</h2>
<a href="/module/code.hms" class="read-more-article"><span
class="glyphicon glyphicon-hand-right"></span> 阅读更多代码</a>
<div id="latestCode" class="row"></div>
</div>
<!-- 每日一言 -->
<script
src="https://api.lwl12.com/hitokoto/main/get?encode=js&charset=utf-8"></script>
<div id="lwlhitokoto">
<script>
lwlhitokoto();
</script>
</div>
</div>
<!-- 右侧导航 -->
</div>
</body>
</html> | Humsen/web/web-pc/WebContent/index.jsp/0 | {
"file_path": "Humsen/web/web-pc/WebContent/index.jsp",
"repo_id": "Humsen",
"token_count": 1813
} | 53 |
/**
* @author 何明胜
*
* 2017年9月26日
*/
/**
* 按钮初始化
*/
$(function() {
showLoginStatus();// 显示登录状态
enterKeyClick();// 登录框和注册框绑定回车事件
});
/** 初始化 */
$(document).ready(function() {
// 登录框添加校验
loginValidator();
// 注册表单添加验证
registerValidator();
// 重置登录表单
if($('#loginForm').length > 0){
$('#loginForm').clearForm();
$('#loginForm').data('bootstrapValidator').resetForm(true);
}
// 重置注册表单
if($('#registerForm').length > 0){
$('#registerForm').clearForm();
$('#registerForm').data('bootstrapValidator').resetForm(true);
}
});
/** 绑定点击事件 */
$(function() {
/** 登录按钮点击 */
$('#btnLogin').click(submitLoginForm);
/** 忘记密码点击 */
$('#btn_forgetPwd').click(retrievePassword);
/** 退出登录按钮点击 */
$('#quitLoginBtn').click(quitLoginClick);
/** 点击个人中心按钮事件,判断是否登录,否则不能访问 */
$('#persCenterBtn').click(persCenterBtnClick);
/** 注册提交按钮点击 */
$('#btn_submitRegister').click(submitRegisterForm);
/** 注册取消按钮点击 */
$('#btnCancel').click(function() {
$('#registerForm').clearForm();
$('#registerForm').data('bootstrapValidator').resetForm(true);
});
});
/**
* 显示登录状态
*
* @returns
*/
function showLoginStatus() {
if ($.cookie('username')) {
$('#loginBtn').hide();
$('#registerBtn').hide();
$('#persCenterBtn').show();
$('#quitLoginBtn').show();
} else {
$('#loginBtn').show();
$('#registerBtn').show();
$('#persCenterBtn').hide();
$('#quitLoginBtn').hide();
}
// 重置登录表单
$('#loginForm').clearForm();
// 重置注册表单
$('#registerForm').clearForm();
}
/**
* 个人中心点击
*
* @returns
*/
function persCenterBtnClick() {
// 如果没有登录,跳转到错误页面
if (!$.cookie('username')) {
window.open('/module/error/error.html');
} else {
window.open('/usercenter.hms');
}
}
/**
* 退出登录点击
*
* @returns
*/
function quitLoginClick() {
// 删除 cookie
$.cookie('username', null, {
path : '/',
expires : -1
});
// 判断是否在后台
if (window.location.href.indexOf('usercenter') > 0) {
showLoginStatus();
} else {
// 刷新页面
window.location.reload();
}
}
/**
* 绑定回车键
*
* @returns
*/
function enterKeyClick() {
$('#loginForm').keydown(function(e) {
if (e.keyCode == 13) {
// 模拟点击登陆按钮,触发上面的 Click 事件
$('#btnLogin').click();
}
});
$('#registerForm').keydown(function(e) {
if (e.keyCode == 13) {
// 模拟点击登陆按钮,触发上面的 Click 事件
$('#btn_submitRegister').click();
}
});
}
/**
* 提交登录表单
*
* @returns
*/
function submitLoginForm() {
// 进行表单验证
var $loginValidate = $('#loginForm').data('bootstrapValidator');
$loginValidate.validate();
if ($loginValidate.isValid()) {
$.ajax({
url : '/userInfo.hms',
async : false,// 同步,会阻塞操作
type : 'POST',
data : {
type : 'auth_login',
userName : $('#txt_userNameLogin').val(),
password : $.md5($('#txt_userPwdLogin').val())
},
success : function(result) {
if (result == 1) {
$.confirm({
title : '登录成功',
content : '登录成功',
autoClose : 'ok|2000',
type : 'green',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
showLoginStatus();
$('#login').modal('hide');
$('#loginForm')[0].reset();
// cookie 放在后端设置
} else {
$.confirm({
title : '登录失败',
content : '登录失败',
autoClose : 'ok|2000',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
$('#txt_userPwdLogin').val('');
}
},
error : function(XMLHttpRequest, textStatus) {
$.confirm({
title : '登录出错',
content : textStatus + ' : ' + XMLHttpRequest.status,
autoClose : 'ok|2000',
type : 'green',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
$('#txt_userPwdLogin').val('');
}
});
}
}
/**
* 提交注册表单
*
* @returns
*/
function submitRegisterForm() {
// 进行表单验证
var $registerValidate = $('#registerForm').data('bootstrapValidator');
$registerValidate.validate();
if ($registerValidate.isValid()) {
$('#register').modal('hide');
var email = $('#txt_userEmailRegister').val();
// 验证邮箱
var validateEmail = $.confirm({
title : false,
closeIcon : true,
content : 'url:/module/login/email_check.html',
// theme: 'supervan',
onContentReady : function() {
// 显示邮件
$('#txt_emailShow').text(email);
// 修改邮件点击
this.$content.find('a').click(function() {
validateEmail.close();
$('#register').modal('show');
});
// 如果是手机,调整排版
if ($.isMobile()) {
$('#txt_emailShow').css('float', 'left');
$('#form_emailValidate').find('.modify-email').css({
'float' : 'left',
'margin-top' : '6px'
});
$('#btn_sendCode').css('margin-top', '10px');
}
// 禁用Ok按钮
validateEmail.buttons.ok.disable();
validateEmail.buttons.ok.removeClass('btn-blue');
// 添加表单校验
registerEmailCodeValidator();
// 获取验证码点击
$('#btn_sendCode').click(
function() {
// 注册发送验证码
$.ajax({
url : '/userInfo/code.hms',
async : true,// 同步,会阻塞操作
type : 'POST',// PUT DELETE POST
data : {
type : 'send_code_register',
email : email,
},
success : function(response) {
if (response != 1) {
$.confirm({
title : false,
content : '验证码发送失败',
autoClose : 'ok|2000',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
}
},
error : function(XMLHttpRequest, textStatus) {
$.confirm({
title : '验证码发送失败',
content : textStatus + ' : '
+ XMLHttpRequest.status,
autoClose : 'ok|2000',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
}
});
// 60s倒计时
$.codeCountDown($('#btn_sendCode'));
});
// 绑定表单监听
$('#txt_validateCode').on(
'input propertychange',
function() {
// 点击下一步,先看表单是否合法
var $formRetrivePwd = $('#form_emailValidate')
.data('bootstrapValidator');
$formRetrivePwd.validate();
if ($formRetrivePwd.isValid()) {
validateEmail.buttons.ok.enable();
validateEmail.buttons.ok.addClass('btn-blue');
}
});
},
buttons : {
ok : {
text : '下一步',
btnClass : 'btn-blue',
keys : [ 'enter' ],
action : function() {
// 注册校验验证码
$.ajax({
url : '/userInfo/code.hms',
async : true,// 同步,会阻塞操作
type : 'POST',// PUT DELETE POST
data : {
type : 'auth_code_register',
randomCode : $('#txt_validateCode').val(),
},
success : function(response) {
if (response == 1) {
// 发送注册信息
sendRegisterInfo();
} else {
// 按钮设置重新发送
$.confirm({
title : '验证失败',
content : '是否需要重新尝试?',
autoClose : 'ok|3000',
type : 'green',
buttons : {
ok : {
text : '是,立即前往',
btnClass : 'btn-primary',
keys : [ 'enter' ],
action : function() {
// 重新打开该对话框
submitRegisterForm();
}
},
cancel : {
text : '否,不再尝试',
btnClass : 'btn-primary',
keys : [ 'ESC' ],
}
}
});
}
},
error : function(XMLHttpRequest, textStatus) {
$.confirm({
title : '验证码校验发送失败',
content : textStatus + ' : '
+ XMLHttpRequest.status,
autoClose : 'ok|2000',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
}
});
}
}
}
});
}
}
/**
* 邮箱验证通过后发送注册信息
*
* @returns
*/
function sendRegisterInfo() {
// 发送ajax请求
$.ajax({
url : '/userInfo.hms',
async : false,// 同步,会阻塞操作
type : 'POST',
data : registerInfo2Json(),
success : function(result) {
if (result == 1) {
$.confirm({
title : '注册成功',
content : '注册成功',
autoClose : 'ok|1500',
type : 'green',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
$('#btnCancel').click();
} else {
$.confirm({
title : '注册失败',
content : '注册失败',
autoClose : 'ok|3000',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
}
},
error : function(XMLHttpRequest, textStatus) {
$.confirm({
title : '注册错误',
content : textStatus + ' : ' + XMLHttpRequest.status,
autoClose : 'ok|2000',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
}
});
}
/**
* 注册用户信息2json
*
* @returns
*/
function registerInfo2Json() {
var newUserInfo = {};
newUserInfo.type = 'create_user_info';
newUserInfo.userName = $('#txt_userNameRegister').val();
newUserInfo.password = $.md5($('#txt_userPwdRegister').val());
newUserInfo.email = $('#txt_userEmailRegister').val();
return newUserInfo;
}
/**
* 找回密码点击事件
*
* @returns
*/
function retrievePassword() {
// 验证邮箱
var retrivePwdConfirm = $
.confirm({
title : false,
closeIcon : true,
content : 'url:/module/login/retrive_pwd.html',
// theme: 'supervan',
onContentReady : function() {
// 如果是手机,调整排版
if ($.isMobile()) {
$('#form_retrivePwd').find('.form-div-label').css(
'width', '100%');
$('#btn_sendValidateCode').css('margin-top', '10px');
}
// 禁用Ok按钮
retrivePwdConfirm.buttons.ok.disable();
retrivePwdConfirm.buttons.ok.removeClass('btn-blue');
// 添加表单检验
retrievePwdValidator();
$('#btn_sendValidateCode')
.click(
function() {
// 判断邮箱格式是否正确
var $emailValidate = $(
'#form_retrivePwd').data(
'bootstrapValidator');
$emailValidate.validateField('email');
var isEmailValid = $emailValidate
.isValidField('email');
if (!isEmailValid) {
return;
}
// 找回密码, 发送验证码
$
.ajax({
url : '/userInfo/code.hms',
async : true,// 异步,启动倒计时
type : 'POST',
data : {
type : 'send_code_retrive_pwd',
email : $(
'#txt_emailInput')
.val(),
},
success : function(response) {
if (response != 1) {
$
.confirm({
title : '验证码发送失败',
content : textStatus
+ ' : '
+ XMLHttpRequest.status,
autoClose : 'ok|2000',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
}
},
error : function(
XMLHttpRequest,
textStatus) {
$
.confirm({
title : '验证码发送失败',
content : textStatus
+ ' : '
+ XMLHttpRequest.status,
autoClose : 'ok|2000',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
}
});
// 60s倒计时
$
.codeCountDown($('#btn_sendValidateCode'));
});
// 绑定表单监听
$('#form_retrivePwd').find('input').on(
'input propertychange',
function() {
// 点击下一步,先看表单是否合法
var $formRetrivePwd = $('#form_retrivePwd')
.data('bootstrapValidator');
$formRetrivePwd.validate();
if ($formRetrivePwd.isValid()) {
retrivePwdConfirm.buttons.ok.enable();
retrivePwdConfirm.buttons.ok
.addClass('btn-blue');
}
});
},
buttons : {
ok : {
text : '下一步',
btnClass : 'btn-blue',
keys : [ 'enter' ],
action : function() {
// 先判断有没有发送过验证码,有可能关闭后又开
// 验证码有效期10分钟
// 暂时不考虑这个
// 找回密码, 校验验证码
$
.ajax({
url : '/userInfo/code.hms',
async : false,
type : 'POST',
data : {
type : 'auth_code_retrive_pwd',
randomCode : $('#txt_validateCode1')
.val(),
userName : $('#txt_username').val(),
email : $('#txt_emailInput').val(),
},
success : function(response) {
if (response != 0) {
$
.confirm({
title : '密码重置成功',
content : '您的密码已成功重置为123456,请尽快修改!',
autoClose : 'ok|4000',
type : 'green',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
} else {
$
.confirm({
title : '验证失败',
content : '是否需要重新尝试?',
autoClose : 'ok|3000',
type : 'green',
buttons : {
ok : {
text : '是,立即前往',
btnClass : 'btn-primary',
keys : [
'enter',
'a' ],
action : function() {
// 重新打开该对话框
retrievePassword();
}
},
cancel : {
text : '否,不再尝试',
btnClass : 'btn-primary',
keys : [ 'ESC' ],
}
}
});
}
},
error : function(XMLHttpRequest,
textStatus) {
$
.confirm({
title : '验证码校验发送失败',
content : textStatus
+ ' : '
+ XMLHttpRequest.status,
autoClose : 'ok|2000',
type : 'red',
buttons : {
ok : {
text : '确认',
btnClass : 'btn-primary',
},
}
});
}
});
}
}
}
});
}
/**
* 登录表单添加验证
*
* @returns
*/
function loginValidator() {
$('#loginForm').bootstrapValidator({
message : '输入无效!',
feedbackIcons : {
valid : 'glyphicon glyphicon-ok',
invalid : 'glyphicon glyphicon-remove',
validating : 'glyphicon glyphicon-refresh'
},
fields : {
username : {
message : '用户名无效!',
validators : {
notEmpty : {
message : '用户名不能为空!'
},
stringLength : {
min : 5,
max : 15,
message : '用户名长度必须在5到15位之间!'
},
regexp : {
regexp : /^[a-zA-Z0-9_\.]+$/,
message : '用户名只能由字母,数字,点和下划线几种组成!'
}
}
},
password : {
message : '密码无效!',
validators : {
notEmpty : {
message : '密码不能为空!'
},
stringLength : {
min : 6,
max : 15,
message : '密码长度必须在6到15位之间!'
}
}
}
}
});
}
/**
* 注册表单添加验证
*
* @returns
*/
function registerValidator() {
$('#registerForm')
.bootstrapValidator(
{
message : '输入无效!',
feedbackIcons : {
valid : 'glyphicon glyphicon-ok',
invalid : 'glyphicon glyphicon-remove',
validating : 'glyphicon glyphicon-refresh'
},
fields : {
username : {
message : '用户名无效!',
validators : {
notEmpty : {
message : '用户名不能为空!'
},
stringLength : {
min : 5,
max : 15,
message : '用户名长度必须在5到15位之间!'
},
/*
* remote: { url: 'remote.php', message:
* 'The username is not available' },
*/
regexp : {
regexp : /^[a-zA-Z0-9_\.]+$/,
message : '用户名只能由字母,数字,点和下划线几种组成!'
}
}
},
password : {
message : '密码无效!',
validators : {
notEmpty : {
message : '密码不能为空!'
},
stringLength : {
min : 6,
max : 15,
message : '密码长度必须在6到15位之间!'
},
different : {
field : 'username',
message : '密码不能和用户名相同!'
}
}
},
confirmPassword : {
message : '确认密码无效!',
validators : {
notEmpty : {
message : '密码不能为空!'
},
identical : {
field : 'password',
message : '两次输入密码不一致!'
},
different : {
field : 'username',
message : '密码不能和用户名相同!'
}
}
},
email : {
message1 : '邮件输入无效!',
validators : {
notEmpty : {
message : '邮箱为必填哦!'
},
regexp : {
regexp : /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
message : '邮箱格式不正确'
}
}
}
}
});
}
/**
* 找回密码表单添加验证
*
* @returns
*/
function retrievePwdValidator() {
$('#form_retrivePwd')
.bootstrapValidator(
{
message : '输入无效!',
feedbackIcons : {
valid : 'glyphicon glyphicon-ok',
invalid : 'glyphicon glyphicon-remove',
validating : 'glyphicon glyphicon-refresh'
},
fields : {
username : {
message : '用户名无效!',
validators : {
notEmpty : {
message : '用户名不能为空!'
},
stringLength : {
min : 5,
max : 15,
message : '用户名长度必须在5到15位之间!'
},
regexp : {
regexp : /^[a-zA-Z0-9_\.]+$/,
message : '用户名只能由字母,数字,点和下划线几种组成!'
}
}
},
email : {
message : '用户名无效!',
validators : {
notEmpty : {
message : '邮箱不能为空!'
},
regexp : {
regexp : /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
message : '邮箱格式不正确'
}
}
},
validateCode : {
message : '验证码无效!',
validators : {
notEmpty : {
message : '验证码不能为空!'
},
regexp : {
regexp : /^\d{6}$/,
message : '验证码为6位数字'
}
}
}
}
});
}
/**
* 注册时 验证码合法校验
*
* @returns
*/
function registerEmailCodeValidator() {
$('#form_emailValidate').bootstrapValidator({
message : '输入无效!',
feedbackIcons : {
valid : 'glyphicon glyphicon-ok',
invalid : 'glyphicon glyphicon-remove',
validating : 'glyphicon glyphicon-refresh'
},
fields : {
validateCode : {
message : '验证码无效!',
validators : {
notEmpty : {
message : '验证码不能为空!'
},
regexp : {
regexp : /^\d{6}$/,
message : '验证码为6位数字'
}
}
}
}
});
} | Humsen/web/web-pc/WebContent/js/login/formvalidator.js/0 | {
"file_path": "Humsen/web/web-pc/WebContent/js/login/formvalidator.js",
"repo_id": "Humsen",
"token_count": 12961
} | 54 |
<link rel="stylesheet" href="/css/login/retrive-pwd.css">
<form id="form_retrivePwd" class="form-horizontal">
<div class="form-group form-group-div-label">
<label class="col-sm-3 control-label form-div-label" for="txt_username">用户名</label>
<div class="col-sm-9 form-group-div-input" >
<input type="text" class="form-control form-div-input" id="txt_username"
name="username" placeholder="请输入用户名">
</div>
</div>
<div class="form-group form-group-div-label">
<label class="col-sm-3 control-label form-div-label" for="txt_emailInput">邮箱</label>
<div class="col-sm-9 form-group-div-input">
<input type="text" class="form-control form-div-input" id="txt_emailInput"
name="email" placeholder="请输入邮箱">
</div>
</div>
<div class="form-group form-group-div-label">
<label for="txt_validateCode1"
class="col-sm-3 control-label form-div-label">验证码</label>
<div class="col-sm-5 form-group-div-input" >
<input type="text" class="form-control form-div-input" id="txt_validateCode1"
name="validateCode" placeholder="请输入验证码">
</div>
<button id="btn_sendValidateCode" type="button" class="btn btn-default">获取验证码</button>
</div>
</form> | Humsen/web/web-pc/WebContent/module/login/retrive_pwd.html/0 | {
"file_path": "Humsen/web/web-pc/WebContent/module/login/retrive_pwd.html",
"repo_id": "Humsen",
"token_count": 515
} | 55 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
CodeMirror.defineOption("placeholder", "", function(cm, val, old) {
var prev = old && old != CodeMirror.Init;
if (val && !prev) {
cm.on("blur", onBlur);
cm.on("change", onChange);
onChange(cm);
} else if (!val && prev) {
cm.off("blur", onBlur);
cm.off("change", onChange);
clearPlaceholder(cm);
var wrapper = cm.getWrapperElement();
wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
}
if (val && !cm.hasFocus()) onBlur(cm);
});
function clearPlaceholder(cm) {
if (cm.state.placeholder) {
cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
cm.state.placeholder = null;
}
}
function setPlaceholder(cm) {
clearPlaceholder(cm);
var elt = cm.state.placeholder = document.createElement("pre");
elt.style.cssText = "height: 0; overflow: visible";
elt.className = "CodeMirror-placeholder";
elt.appendChild(document.createTextNode(cm.getOption("placeholder")));
cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
}
function onBlur(cm) {
if (isEmpty(cm)) setPlaceholder(cm);
}
function onChange(cm) {
var wrapper = cm.getWrapperElement(), empty = isEmpty(cm);
wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : "");
if (empty) setPlaceholder(cm);
else clearPlaceholder(cm);
}
function isEmpty(cm) {
return (cm.lineCount() === 1) && (cm.getLine(0) === "");
}
});
| Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/addon/display/placeholder.js/0 | {
"file_path": "Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/addon/display/placeholder.js",
"repo_id": "Humsen",
"token_count": 748
} | 56 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var WORD = /[\w$]+/, RANGE = 500;
CodeMirror.registerHelper("hint", "anyword", function(editor, options) {
var word = options && options.word || WORD;
var range = options && options.range || RANGE;
var cur = editor.getCursor(), curLine = editor.getLine(cur.line);
var end = cur.ch, start = end;
while (start && word.test(curLine.charAt(start - 1))) --start;
var curWord = start != end && curLine.slice(start, end);
var list = [], seen = {};
var re = new RegExp(word.source, "g");
for (var dir = -1; dir <= 1; dir += 2) {
var line = cur.line, endLine = Math.min(Math.max(line + dir * range, editor.firstLine()), editor.lastLine()) + dir;
for (; line != endLine; line += dir) {
var text = editor.getLine(line), m;
while (m = re.exec(text)) {
if (line == cur.line && m[0] === curWord) continue;
if ((!curWord || m[0].lastIndexOf(curWord, 0) == 0) && !Object.prototype.hasOwnProperty.call(seen, m[0])) {
seen[m[0]] = true;
list.push(m[0]);
}
}
}
}
return {list: list, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end)};
});
});
| Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/addon/hint/anyword-hint.js/0 | {
"file_path": "Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/addon/hint/anyword-hint.js",
"repo_id": "Humsen",
"token_count": 668
} | 57 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
// declare global: diff_match_patch, DIFF_INSERT, DIFF_DELETE, DIFF_EQUAL
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"), require("diff_match_patch"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "diff_match_patch"], mod);
else // Plain browser env
mod(CodeMirror, diff_match_patch);
})(function(CodeMirror, diff_match_patch) {
"use strict";
var Pos = CodeMirror.Pos;
var svgNS = "http://www.w3.org/2000/svg";
function DiffView(mv, type) {
this.mv = mv;
this.type = type;
this.classes = type == "left"
? {chunk: "CodeMirror-merge-l-chunk",
start: "CodeMirror-merge-l-chunk-start",
end: "CodeMirror-merge-l-chunk-end",
insert: "CodeMirror-merge-l-inserted",
del: "CodeMirror-merge-l-deleted",
connect: "CodeMirror-merge-l-connect"}
: {chunk: "CodeMirror-merge-r-chunk",
start: "CodeMirror-merge-r-chunk-start",
end: "CodeMirror-merge-r-chunk-end",
insert: "CodeMirror-merge-r-inserted",
del: "CodeMirror-merge-r-deleted",
connect: "CodeMirror-merge-r-connect"};
}
DiffView.prototype = {
constructor: DiffView,
init: function(pane, orig, options) {
this.edit = this.mv.edit;
this.orig = CodeMirror(pane, copyObj({value: orig, readOnly: !this.mv.options.allowEditingOriginals}, copyObj(options)));
this.diff = getDiff(asString(orig), asString(options.value));
this.chunks = getChunks(this.diff);
this.diffOutOfDate = this.dealigned = false;
this.showDifferences = options.showDifferences !== false;
this.forceUpdate = registerUpdate(this);
setScrollLock(this, true, false);
registerScroll(this);
},
setShowDifferences: function(val) {
val = val !== false;
if (val != this.showDifferences) {
this.showDifferences = val;
this.forceUpdate("full");
}
}
};
function ensureDiff(dv) {
if (dv.diffOutOfDate) {
dv.diff = getDiff(dv.orig.getValue(), dv.edit.getValue());
dv.chunks = getChunks(dv.diff);
dv.diffOutOfDate = false;
CodeMirror.signal(dv.edit, "updateDiff", dv.diff);
}
}
var updating = false;
function registerUpdate(dv) {
var edit = {from: 0, to: 0, marked: []};
var orig = {from: 0, to: 0, marked: []};
var debounceChange, updatingFast = false;
function update(mode) {
updating = true;
updatingFast = false;
if (mode == "full") {
if (dv.svg) clear(dv.svg);
if (dv.copyButtons) clear(dv.copyButtons);
clearMarks(dv.edit, edit.marked, dv.classes);
clearMarks(dv.orig, orig.marked, dv.classes);
edit.from = edit.to = orig.from = orig.to = 0;
}
ensureDiff(dv);
if (dv.showDifferences) {
updateMarks(dv.edit, dv.diff, edit, DIFF_INSERT, dv.classes);
updateMarks(dv.orig, dv.diff, orig, DIFF_DELETE, dv.classes);
}
makeConnections(dv);
if (dv.mv.options.connect == "align")
alignChunks(dv);
updating = false;
}
function setDealign(fast) {
if (updating) return;
dv.dealigned = true;
set(fast);
}
function set(fast) {
if (updating || updatingFast) return;
clearTimeout(debounceChange);
if (fast === true) updatingFast = true;
debounceChange = setTimeout(update, fast === true ? 20 : 250);
}
function change(_cm, change) {
if (!dv.diffOutOfDate) {
dv.diffOutOfDate = true;
edit.from = edit.to = orig.from = orig.to = 0;
}
// Update faster when a line was added/removed
setDealign(change.text.length - 1 != change.to.line - change.from.line);
}
dv.edit.on("change", change);
dv.orig.on("change", change);
dv.edit.on("markerAdded", setDealign);
dv.edit.on("markerCleared", setDealign);
dv.orig.on("markerAdded", setDealign);
dv.orig.on("markerCleared", setDealign);
dv.edit.on("viewportChange", function() { set(false); });
dv.orig.on("viewportChange", function() { set(false); });
update();
return update;
}
function registerScroll(dv) {
dv.edit.on("scroll", function() {
syncScroll(dv, DIFF_INSERT) && makeConnections(dv);
});
dv.orig.on("scroll", function() {
syncScroll(dv, DIFF_DELETE) && makeConnections(dv);
});
}
function syncScroll(dv, type) {
// Change handler will do a refresh after a timeout when diff is out of date
if (dv.diffOutOfDate) return false;
if (!dv.lockScroll) return true;
var editor, other, now = +new Date;
if (type == DIFF_INSERT) { editor = dv.edit; other = dv.orig; }
else { editor = dv.orig; other = dv.edit; }
// Don't take action if the position of this editor was recently set
// (to prevent feedback loops)
if (editor.state.scrollSetBy == dv && (editor.state.scrollSetAt || 0) + 50 > now) return false;
var sInfo = editor.getScrollInfo();
if (dv.mv.options.connect == "align") {
targetPos = sInfo.top;
} else {
var halfScreen = .5 * sInfo.clientHeight, midY = sInfo.top + halfScreen;
var mid = editor.lineAtHeight(midY, "local");
var around = chunkBoundariesAround(dv.chunks, mid, type == DIFF_INSERT);
var off = getOffsets(editor, type == DIFF_INSERT ? around.edit : around.orig);
var offOther = getOffsets(other, type == DIFF_INSERT ? around.orig : around.edit);
var ratio = (midY - off.top) / (off.bot - off.top);
var targetPos = (offOther.top - halfScreen) + ratio * (offOther.bot - offOther.top);
var botDist, mix;
// Some careful tweaking to make sure no space is left out of view
// when scrolling to top or bottom.
if (targetPos > sInfo.top && (mix = sInfo.top / halfScreen) < 1) {
targetPos = targetPos * mix + sInfo.top * (1 - mix);
} else if ((botDist = sInfo.height - sInfo.clientHeight - sInfo.top) < halfScreen) {
var otherInfo = other.getScrollInfo();
var botDistOther = otherInfo.height - otherInfo.clientHeight - targetPos;
if (botDistOther > botDist && (mix = botDist / halfScreen) < 1)
targetPos = targetPos * mix + (otherInfo.height - otherInfo.clientHeight - botDist) * (1 - mix);
}
}
other.scrollTo(sInfo.left, targetPos);
other.state.scrollSetAt = now;
other.state.scrollSetBy = dv;
return true;
}
function getOffsets(editor, around) {
var bot = around.after;
if (bot == null) bot = editor.lastLine() + 1;
return {top: editor.heightAtLine(around.before || 0, "local"),
bot: editor.heightAtLine(bot, "local")};
}
function setScrollLock(dv, val, action) {
dv.lockScroll = val;
if (val && action != false) syncScroll(dv, DIFF_INSERT) && makeConnections(dv);
dv.lockButton.innerHTML = val ? "\u21db\u21da" : "\u21db \u21da";
}
// Updating the marks for editor content
function clearMarks(editor, arr, classes) {
for (var i = 0; i < arr.length; ++i) {
var mark = arr[i];
if (mark instanceof CodeMirror.TextMarker) {
mark.clear();
} else if (mark.parent) {
editor.removeLineClass(mark, "background", classes.chunk);
editor.removeLineClass(mark, "background", classes.start);
editor.removeLineClass(mark, "background", classes.end);
}
}
arr.length = 0;
}
// FIXME maybe add a margin around viewport to prevent too many updates
function updateMarks(editor, diff, state, type, classes) {
var vp = editor.getViewport();
editor.operation(function() {
if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {
clearMarks(editor, state.marked, classes);
markChanges(editor, diff, type, state.marked, vp.from, vp.to, classes);
state.from = vp.from; state.to = vp.to;
} else {
if (vp.from < state.from) {
markChanges(editor, diff, type, state.marked, vp.from, state.from, classes);
state.from = vp.from;
}
if (vp.to > state.to) {
markChanges(editor, diff, type, state.marked, state.to, vp.to, classes);
state.to = vp.to;
}
}
});
}
function markChanges(editor, diff, type, marks, from, to, classes) {
var pos = Pos(0, 0);
var top = Pos(from, 0), bot = editor.clipPos(Pos(to - 1));
var cls = type == DIFF_DELETE ? classes.del : classes.insert;
function markChunk(start, end) {
var bfrom = Math.max(from, start), bto = Math.min(to, end);
for (var i = bfrom; i < bto; ++i) {
var line = editor.addLineClass(i, "background", classes.chunk);
if (i == start) editor.addLineClass(line, "background", classes.start);
if (i == end - 1) editor.addLineClass(line, "background", classes.end);
marks.push(line);
}
// When the chunk is empty, make sure a horizontal line shows up
if (start == end && bfrom == end && bto == end) {
if (bfrom)
marks.push(editor.addLineClass(bfrom - 1, "background", classes.end));
else
marks.push(editor.addLineClass(bfrom, "background", classes.start));
}
}
var chunkStart = 0;
for (var i = 0; i < diff.length; ++i) {
var part = diff[i], tp = part[0], str = part[1];
if (tp == DIFF_EQUAL) {
var cleanFrom = pos.line + (startOfLineClean(diff, i) ? 0 : 1);
moveOver(pos, str);
var cleanTo = pos.line + (endOfLineClean(diff, i) ? 1 : 0);
if (cleanTo > cleanFrom) {
if (i) markChunk(chunkStart, cleanFrom);
chunkStart = cleanTo;
}
} else {
if (tp == type) {
var end = moveOver(pos, str, true);
var a = posMax(top, pos), b = posMin(bot, end);
if (!posEq(a, b))
marks.push(editor.markText(a, b, {className: cls}));
pos = end;
}
}
}
if (chunkStart <= pos.line) markChunk(chunkStart, pos.line + 1);
}
// Updating the gap between editor and original
function makeConnections(dv) {
if (!dv.showDifferences) return;
if (dv.svg) {
clear(dv.svg);
var w = dv.gap.offsetWidth;
attrs(dv.svg, "width", w, "height", dv.gap.offsetHeight);
}
if (dv.copyButtons) clear(dv.copyButtons);
var vpEdit = dv.edit.getViewport(), vpOrig = dv.orig.getViewport();
var sTopEdit = dv.edit.getScrollInfo().top, sTopOrig = dv.orig.getScrollInfo().top;
for (var i = 0; i < dv.chunks.length; i++) {
var ch = dv.chunks[i];
if (ch.editFrom <= vpEdit.to && ch.editTo >= vpEdit.from &&
ch.origFrom <= vpOrig.to && ch.origTo >= vpOrig.from)
drawConnectorsForChunk(dv, ch, sTopOrig, sTopEdit, w);
}
}
function getMatchingOrigLine(editLine, chunks) {
var editStart = 0, origStart = 0;
for (var i = 0; i < chunks.length; i++) {
var chunk = chunks[i];
if (chunk.editTo > editLine && chunk.editFrom <= editLine) return null;
if (chunk.editFrom > editLine) break;
editStart = chunk.editTo;
origStart = chunk.origTo;
}
return origStart + (editLine - editStart);
}
function findAlignedLines(dv, other) {
var linesToAlign = [];
for (var i = 0; i < dv.chunks.length; i++) {
var chunk = dv.chunks[i];
linesToAlign.push([chunk.origTo, chunk.editTo, other ? getMatchingOrigLine(chunk.editTo, other.chunks) : null]);
}
if (other) {
for (var i = 0; i < other.chunks.length; i++) {
var chunk = other.chunks[i];
for (var j = 0; j < linesToAlign.length; j++) {
var align = linesToAlign[j];
if (align[1] == chunk.editTo) {
j = -1;
break;
} else if (align[1] > chunk.editTo) {
break;
}
}
if (j > -1)
linesToAlign.splice(j - 1, 0, [getMatchingOrigLine(chunk.editTo, dv.chunks), chunk.editTo, chunk.origTo]);
}
}
return linesToAlign;
}
function alignChunks(dv, force) {
if (!dv.dealigned && !force) return;
if (!dv.orig.curOp) return dv.orig.operation(function() {
alignChunks(dv, force);
});
dv.dealigned = false;
var other = dv.mv.left == dv ? dv.mv.right : dv.mv.left;
if (other) {
ensureDiff(other);
other.dealigned = false;
}
var linesToAlign = findAlignedLines(dv, other);
// Clear old aligners
var aligners = dv.mv.aligners;
for (var i = 0; i < aligners.length; i++)
aligners[i].clear();
aligners.length = 0;
var cm = [dv.orig, dv.edit], scroll = [];
if (other) cm.push(other.orig);
for (var i = 0; i < cm.length; i++)
scroll.push(cm[i].getScrollInfo().top);
for (var ln = 0; ln < linesToAlign.length; ln++)
alignLines(cm, linesToAlign[ln], aligners);
for (var i = 0; i < cm.length; i++)
cm[i].scrollTo(null, scroll[i]);
}
function alignLines(cm, lines, aligners) {
var maxOffset = 0, offset = [];
for (var i = 0; i < cm.length; i++) if (lines[i] != null) {
var off = cm[i].heightAtLine(lines[i], "local");
offset[i] = off;
maxOffset = Math.max(maxOffset, off);
}
for (var i = 0; i < cm.length; i++) if (lines[i] != null) {
var diff = maxOffset - offset[i];
if (diff > 1)
aligners.push(padAbove(cm[i], lines[i], diff));
}
}
function padAbove(cm, line, size) {
var above = true;
if (line > cm.lastLine()) {
line--;
above = false;
}
var elt = document.createElement("div");
elt.className = "CodeMirror-merge-spacer";
elt.style.height = size + "px"; elt.style.minWidth = "1px";
return cm.addLineWidget(line, elt, {height: size, above: above});
}
function drawConnectorsForChunk(dv, chunk, sTopOrig, sTopEdit, w) {
var flip = dv.type == "left";
var top = dv.orig.heightAtLine(chunk.origFrom, "local") - sTopOrig;
if (dv.svg) {
var topLpx = top;
var topRpx = dv.edit.heightAtLine(chunk.editFrom, "local") - sTopEdit;
if (flip) { var tmp = topLpx; topLpx = topRpx; topRpx = tmp; }
var botLpx = dv.orig.heightAtLine(chunk.origTo, "local") - sTopOrig;
var botRpx = dv.edit.heightAtLine(chunk.editTo, "local") - sTopEdit;
if (flip) { var tmp = botLpx; botLpx = botRpx; botRpx = tmp; }
var curveTop = " C " + w/2 + " " + topRpx + " " + w/2 + " " + topLpx + " " + (w + 2) + " " + topLpx;
var curveBot = " C " + w/2 + " " + botLpx + " " + w/2 + " " + botRpx + " -1 " + botRpx;
attrs(dv.svg.appendChild(document.createElementNS(svgNS, "path")),
"d", "M -1 " + topRpx + curveTop + " L " + (w + 2) + " " + botLpx + curveBot + " z",
"class", dv.classes.connect);
}
if (dv.copyButtons) {
var copy = dv.copyButtons.appendChild(elt("div", dv.type == "left" ? "\u21dd" : "\u21dc",
"CodeMirror-merge-copy"));
var editOriginals = dv.mv.options.allowEditingOriginals;
copy.title = editOriginals ? "Push to left" : "Revert chunk";
copy.chunk = chunk;
copy.style.top = top + "px";
if (editOriginals) {
var topReverse = dv.orig.heightAtLine(chunk.editFrom, "local") - sTopEdit;
var copyReverse = dv.copyButtons.appendChild(elt("div", dv.type == "right" ? "\u21dd" : "\u21dc",
"CodeMirror-merge-copy-reverse"));
copyReverse.title = "Push to right";
copyReverse.chunk = {editFrom: chunk.origFrom, editTo: chunk.origTo,
origFrom: chunk.editFrom, origTo: chunk.editTo};
copyReverse.style.top = topReverse + "px";
dv.type == "right" ? copyReverse.style.left = "2px" : copyReverse.style.right = "2px";
}
}
}
function copyChunk(dv, to, from, chunk) {
if (dv.diffOutOfDate) return;
to.replaceRange(from.getRange(Pos(chunk.origFrom, 0), Pos(chunk.origTo, 0)),
Pos(chunk.editFrom, 0), Pos(chunk.editTo, 0));
}
// Merge view, containing 0, 1, or 2 diff views.
var MergeView = CodeMirror.MergeView = function(node, options) {
if (!(this instanceof MergeView)) return new MergeView(node, options);
this.options = options;
var origLeft = options.origLeft, origRight = options.origRight == null ? options.orig : options.origRight;
var hasLeft = origLeft != null, hasRight = origRight != null;
var panes = 1 + (hasLeft ? 1 : 0) + (hasRight ? 1 : 0);
var wrap = [], left = this.left = null, right = this.right = null;
var self = this;
if (hasLeft) {
left = this.left = new DiffView(this, "left");
var leftPane = elt("div", null, "CodeMirror-merge-pane");
wrap.push(leftPane);
wrap.push(buildGap(left));
}
var editPane = elt("div", null, "CodeMirror-merge-pane");
wrap.push(editPane);
if (hasRight) {
right = this.right = new DiffView(this, "right");
wrap.push(buildGap(right));
var rightPane = elt("div", null, "CodeMirror-merge-pane");
wrap.push(rightPane);
}
(hasRight ? rightPane : editPane).className += " CodeMirror-merge-pane-rightmost";
wrap.push(elt("div", null, null, "height: 0; clear: both;"));
var wrapElt = this.wrap = node.appendChild(elt("div", wrap, "CodeMirror-merge CodeMirror-merge-" + panes + "pane"));
this.edit = CodeMirror(editPane, copyObj(options));
if (left) left.init(leftPane, origLeft, options);
if (right) right.init(rightPane, origRight, options);
if (options.collapseIdentical) {
updating = true;
this.editor().operation(function() {
collapseIdenticalStretches(self, options.collapseIdentical);
});
updating = false;
}
if (options.connect == "align") {
this.aligners = [];
alignChunks(this.left || this.right, true);
}
var onResize = function() {
if (left) makeConnections(left);
if (right) makeConnections(right);
};
CodeMirror.on(window, "resize", onResize);
var resizeInterval = setInterval(function() {
for (var p = wrapElt.parentNode; p && p != document.body; p = p.parentNode) {}
if (!p) { clearInterval(resizeInterval); CodeMirror.off(window, "resize", onResize); }
}, 5000);
};
function buildGap(dv) {
var lock = dv.lockButton = elt("div", null, "CodeMirror-merge-scrolllock");
lock.title = "Toggle locked scrolling";
var lockWrap = elt("div", [lock], "CodeMirror-merge-scrolllock-wrap");
CodeMirror.on(lock, "click", function() { setScrollLock(dv, !dv.lockScroll); });
var gapElts = [lockWrap];
if (dv.mv.options.revertButtons !== false) {
dv.copyButtons = elt("div", null, "CodeMirror-merge-copybuttons-" + dv.type);
CodeMirror.on(dv.copyButtons, "click", function(e) {
var node = e.target || e.srcElement;
if (!node.chunk) return;
if (node.className == "CodeMirror-merge-copy-reverse") {
copyChunk(dv, dv.orig, dv.edit, node.chunk);
return;
}
copyChunk(dv, dv.edit, dv.orig, node.chunk);
});
gapElts.unshift(dv.copyButtons);
}
if (dv.mv.options.connect != "align") {
var svg = document.createElementNS && document.createElementNS(svgNS, "svg");
if (svg && !svg.createSVGRect) svg = null;
dv.svg = svg;
if (svg) gapElts.push(svg);
}
return dv.gap = elt("div", gapElts, "CodeMirror-merge-gap");
}
MergeView.prototype = {
constuctor: MergeView,
editor: function() { return this.edit; },
rightOriginal: function() { return this.right && this.right.orig; },
leftOriginal: function() { return this.left && this.left.orig; },
setShowDifferences: function(val) {
if (this.right) this.right.setShowDifferences(val);
if (this.left) this.left.setShowDifferences(val);
},
rightChunks: function() {
if (this.right) { ensureDiff(this.right); return this.right.chunks; }
},
leftChunks: function() {
if (this.left) { ensureDiff(this.left); return this.left.chunks; }
}
};
function asString(obj) {
if (typeof obj == "string") return obj;
else return obj.getValue();
}
// Operations on diffs
var dmp = new diff_match_patch();
function getDiff(a, b) {
var diff = dmp.diff_main(a, b);
dmp.diff_cleanupSemantic(diff);
// The library sometimes leaves in empty parts, which confuse the algorithm
for (var i = 0; i < diff.length; ++i) {
var part = diff[i];
if (!part[1]) {
diff.splice(i--, 1);
} else if (i && diff[i - 1][0] == part[0]) {
diff.splice(i--, 1);
diff[i][1] += part[1];
}
}
return diff;
}
function getChunks(diff) {
var chunks = [];
var startEdit = 0, startOrig = 0;
var edit = Pos(0, 0), orig = Pos(0, 0);
for (var i = 0; i < diff.length; ++i) {
var part = diff[i], tp = part[0];
if (tp == DIFF_EQUAL) {
var startOff = startOfLineClean(diff, i) ? 0 : 1;
var cleanFromEdit = edit.line + startOff, cleanFromOrig = orig.line + startOff;
moveOver(edit, part[1], null, orig);
var endOff = endOfLineClean(diff, i) ? 1 : 0;
var cleanToEdit = edit.line + endOff, cleanToOrig = orig.line + endOff;
if (cleanToEdit > cleanFromEdit) {
if (i) chunks.push({origFrom: startOrig, origTo: cleanFromOrig,
editFrom: startEdit, editTo: cleanFromEdit});
startEdit = cleanToEdit; startOrig = cleanToOrig;
}
} else {
moveOver(tp == DIFF_INSERT ? edit : orig, part[1]);
}
}
if (startEdit <= edit.line || startOrig <= orig.line)
chunks.push({origFrom: startOrig, origTo: orig.line + 1,
editFrom: startEdit, editTo: edit.line + 1});
return chunks;
}
function endOfLineClean(diff, i) {
if (i == diff.length - 1) return true;
var next = diff[i + 1][1];
if (next.length == 1 || next.charCodeAt(0) != 10) return false;
if (i == diff.length - 2) return true;
next = diff[i + 2][1];
return next.length > 1 && next.charCodeAt(0) == 10;
}
function startOfLineClean(diff, i) {
if (i == 0) return true;
var last = diff[i - 1][1];
if (last.charCodeAt(last.length - 1) != 10) return false;
if (i == 1) return true;
last = diff[i - 2][1];
return last.charCodeAt(last.length - 1) == 10;
}
function chunkBoundariesAround(chunks, n, nInEdit) {
var beforeE, afterE, beforeO, afterO;
for (var i = 0; i < chunks.length; i++) {
var chunk = chunks[i];
var fromLocal = nInEdit ? chunk.editFrom : chunk.origFrom;
var toLocal = nInEdit ? chunk.editTo : chunk.origTo;
if (afterE == null) {
if (fromLocal > n) { afterE = chunk.editFrom; afterO = chunk.origFrom; }
else if (toLocal > n) { afterE = chunk.editTo; afterO = chunk.origTo; }
}
if (toLocal <= n) { beforeE = chunk.editTo; beforeO = chunk.origTo; }
else if (fromLocal <= n) { beforeE = chunk.editFrom; beforeO = chunk.origFrom; }
}
return {edit: {before: beforeE, after: afterE}, orig: {before: beforeO, after: afterO}};
}
function collapseSingle(cm, from, to) {
cm.addLineClass(from, "wrap", "CodeMirror-merge-collapsed-line");
var widget = document.createElement("span");
widget.className = "CodeMirror-merge-collapsed-widget";
widget.title = "Identical text collapsed. Click to expand.";
var mark = cm.markText(Pos(from, 0), Pos(to - 1), {
inclusiveLeft: true,
inclusiveRight: true,
replacedWith: widget,
clearOnEnter: true
});
function clear() {
mark.clear();
cm.removeLineClass(from, "wrap", "CodeMirror-merge-collapsed-line");
}
widget.addEventListener("click", clear);
return {mark: mark, clear: clear};
}
function collapseStretch(size, editors) {
var marks = [];
function clear() {
for (var i = 0; i < marks.length; i++) marks[i].clear();
}
for (var i = 0; i < editors.length; i++) {
var editor = editors[i];
var mark = collapseSingle(editor.cm, editor.line, editor.line + size);
marks.push(mark);
mark.mark.on("clear", clear);
}
return marks[0].mark;
}
function unclearNearChunks(dv, margin, off, clear) {
for (var i = 0; i < dv.chunks.length; i++) {
var chunk = dv.chunks[i];
for (var l = chunk.editFrom - margin; l < chunk.editTo + margin; l++) {
var pos = l + off;
if (pos >= 0 && pos < clear.length) clear[pos] = false;
}
}
}
function collapseIdenticalStretches(mv, margin) {
if (typeof margin != "number") margin = 2;
var clear = [], edit = mv.editor(), off = edit.firstLine();
for (var l = off, e = edit.lastLine(); l <= e; l++) clear.push(true);
if (mv.left) unclearNearChunks(mv.left, margin, off, clear);
if (mv.right) unclearNearChunks(mv.right, margin, off, clear);
for (var i = 0; i < clear.length; i++) {
if (clear[i]) {
var line = i + off;
for (var size = 1; i < clear.length - 1 && clear[i + 1]; i++, size++) {}
if (size > margin) {
var editors = [{line: line, cm: edit}];
if (mv.left) editors.push({line: getMatchingOrigLine(line, mv.left.chunks), cm: mv.left.orig});
if (mv.right) editors.push({line: getMatchingOrigLine(line, mv.right.chunks), cm: mv.right.orig});
var mark = collapseStretch(size, editors);
if (mv.options.onCollapse) mv.options.onCollapse(mv, line, size, mark);
}
}
}
}
// General utilities
function elt(tag, content, className, style) {
var e = document.createElement(tag);
if (className) e.className = className;
if (style) e.style.cssText = style;
if (typeof content == "string") e.appendChild(document.createTextNode(content));
else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
return e;
}
function clear(node) {
for (var count = node.childNodes.length; count > 0; --count)
node.removeChild(node.firstChild);
}
function attrs(elt) {
for (var i = 1; i < arguments.length; i += 2)
elt.setAttribute(arguments[i], arguments[i+1]);
}
function copyObj(obj, target) {
if (!target) target = {};
for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop];
return target;
}
function moveOver(pos, str, copy, other) {
var out = copy ? Pos(pos.line, pos.ch) : pos, at = 0;
for (;;) {
var nl = str.indexOf("\n", at);
if (nl == -1) break;
++out.line;
if (other) ++other.line;
at = nl + 1;
}
out.ch = (at ? 0 : out.ch) + (str.length - at);
if (other) other.ch = (at ? 0 : other.ch) + (str.length - at);
return out;
}
function posMin(a, b) { return (a.line - b.line || a.ch - b.ch) < 0 ? a : b; }
function posMax(a, b) { return (a.line - b.line || a.ch - b.ch) > 0 ? a : b; }
function posEq(a, b) { return a.line == b.line && a.ch == b.ch; }
});
| Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/addon/merge/merge.js/0 | {
"file_path": "Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/addon/merge/merge.js",
"repo_id": "Humsen",
"token_count": 11816
} | 58 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"), require("./searchcursor"), require("../scroll/annotatescrollbar"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "./searchcursor", "../scroll/annotatescrollbar"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineExtension("showMatchesOnScrollbar", function(query, caseFold, options) {
if (typeof options == "string") options = {className: options};
if (!options) options = {};
return new SearchAnnotation(this, query, caseFold, options);
});
function SearchAnnotation(cm, query, caseFold, options) {
this.cm = cm;
var annotateOptions = {listenForChanges: false};
for (var prop in options) annotateOptions[prop] = options[prop];
if (!annotateOptions.className) annotateOptions.className = "CodeMirror-search-match";
this.annotation = cm.annotateScrollbar(annotateOptions);
this.query = query;
this.caseFold = caseFold;
this.gap = {from: cm.firstLine(), to: cm.lastLine() + 1};
this.matches = [];
this.update = null;
this.findMatches();
this.annotation.update(this.matches);
var self = this;
cm.on("change", this.changeHandler = function(_cm, change) { self.onChange(change); });
}
var MAX_MATCHES = 1000;
SearchAnnotation.prototype.findMatches = function() {
if (!this.gap) return;
for (var i = 0; i < this.matches.length; i++) {
var match = this.matches[i];
if (match.from.line >= this.gap.to) break;
if (match.to.line >= this.gap.from) this.matches.splice(i--, 1);
}
var cursor = this.cm.getSearchCursor(this.query, CodeMirror.Pos(this.gap.from, 0), this.caseFold);
while (cursor.findNext()) {
var match = {from: cursor.from(), to: cursor.to()};
if (match.from.line >= this.gap.to) break;
this.matches.splice(i++, 0, match);
if (this.matches.length > MAX_MATCHES) break;
}
this.gap = null;
};
function offsetLine(line, changeStart, sizeChange) {
if (line <= changeStart) return line;
return Math.max(changeStart, line + sizeChange);
}
SearchAnnotation.prototype.onChange = function(change) {
var startLine = change.from.line;
var endLine = CodeMirror.changeEnd(change).line;
var sizeChange = endLine - change.to.line;
if (this.gap) {
this.gap.from = Math.min(offsetLine(this.gap.from, startLine, sizeChange), change.from.line);
this.gap.to = Math.max(offsetLine(this.gap.to, startLine, sizeChange), change.from.line);
} else {
this.gap = {from: change.from.line, to: endLine + 1};
}
if (sizeChange) for (var i = 0; i < this.matches.length; i++) {
var match = this.matches[i];
var newFrom = offsetLine(match.from.line, startLine, sizeChange);
if (newFrom != match.from.line) match.from = CodeMirror.Pos(newFrom, match.from.ch);
var newTo = offsetLine(match.to.line, startLine, sizeChange);
if (newTo != match.to.line) match.to = CodeMirror.Pos(newTo, match.to.ch);
}
clearTimeout(this.update);
var self = this;
this.update = setTimeout(function() { self.updateAfterChange(); }, 250);
};
SearchAnnotation.prototype.updateAfterChange = function() {
this.findMatches();
this.annotation.update(this.matches);
};
SearchAnnotation.prototype.clear = function() {
this.cm.off("change", this.changeHandler);
this.annotation.clear();
};
});
| Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/addon/search/matchesonscrollbar.js/0 | {
"file_path": "Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/addon/search/matchesonscrollbar.js",
"repo_id": "Humsen",
"token_count": 1373
} | 59 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("apl", function() {
var builtInOps = {
".": "innerProduct",
"\\": "scan",
"/": "reduce",
"⌿": "reduce1Axis",
"⍀": "scan1Axis",
"¨": "each",
"⍣": "power"
};
var builtInFuncs = {
"+": ["conjugate", "add"],
"−": ["negate", "subtract"],
"×": ["signOf", "multiply"],
"÷": ["reciprocal", "divide"],
"⌈": ["ceiling", "greaterOf"],
"⌊": ["floor", "lesserOf"],
"∣": ["absolute", "residue"],
"⍳": ["indexGenerate", "indexOf"],
"?": ["roll", "deal"],
"⋆": ["exponentiate", "toThePowerOf"],
"⍟": ["naturalLog", "logToTheBase"],
"○": ["piTimes", "circularFuncs"],
"!": ["factorial", "binomial"],
"⌹": ["matrixInverse", "matrixDivide"],
"<": [null, "lessThan"],
"≤": [null, "lessThanOrEqual"],
"=": [null, "equals"],
">": [null, "greaterThan"],
"≥": [null, "greaterThanOrEqual"],
"≠": [null, "notEqual"],
"≡": ["depth", "match"],
"≢": [null, "notMatch"],
"∈": ["enlist", "membership"],
"⍷": [null, "find"],
"∪": ["unique", "union"],
"∩": [null, "intersection"],
"∼": ["not", "without"],
"∨": [null, "or"],
"∧": [null, "and"],
"⍱": [null, "nor"],
"⍲": [null, "nand"],
"⍴": ["shapeOf", "reshape"],
",": ["ravel", "catenate"],
"⍪": [null, "firstAxisCatenate"],
"⌽": ["reverse", "rotate"],
"⊖": ["axis1Reverse", "axis1Rotate"],
"⍉": ["transpose", null],
"↑": ["first", "take"],
"↓": [null, "drop"],
"⊂": ["enclose", "partitionWithAxis"],
"⊃": ["diclose", "pick"],
"⌷": [null, "index"],
"⍋": ["gradeUp", null],
"⍒": ["gradeDown", null],
"⊤": ["encode", null],
"⊥": ["decode", null],
"⍕": ["format", "formatByExample"],
"⍎": ["execute", null],
"⊣": ["stop", "left"],
"⊢": ["pass", "right"]
};
var isOperator = /[\.\/⌿⍀¨⍣]/;
var isNiladic = /⍬/;
var isFunction = /[\+−×÷⌈⌊∣⍳\?⋆⍟○!⌹<≤=>≥≠≡≢∈⍷∪∩∼∨∧⍱⍲⍴,⍪⌽⊖⍉↑↓⊂⊃⌷⍋⍒⊤⊥⍕⍎⊣⊢]/;
var isArrow = /←/;
var isComment = /[⍝#].*$/;
var stringEater = function(type) {
var prev;
prev = false;
return function(c) {
prev = c;
if (c === type) {
return prev === "\\";
}
return true;
};
};
return {
startState: function() {
return {
prev: false,
func: false,
op: false,
string: false,
escape: false
};
},
token: function(stream, state) {
var ch, funcName, word;
if (stream.eatSpace()) {
return null;
}
ch = stream.next();
if (ch === '"' || ch === "'") {
stream.eatWhile(stringEater(ch));
stream.next();
state.prev = true;
return "string";
}
if (/[\[{\(]/.test(ch)) {
state.prev = false;
return null;
}
if (/[\]}\)]/.test(ch)) {
state.prev = true;
return null;
}
if (isNiladic.test(ch)) {
state.prev = false;
return "niladic";
}
if (/[¯\d]/.test(ch)) {
if (state.func) {
state.func = false;
state.prev = false;
} else {
state.prev = true;
}
stream.eatWhile(/[\w\.]/);
return "number";
}
if (isOperator.test(ch)) {
return "operator apl-" + builtInOps[ch];
}
if (isArrow.test(ch)) {
return "apl-arrow";
}
if (isFunction.test(ch)) {
funcName = "apl-";
if (builtInFuncs[ch] != null) {
if (state.prev) {
funcName += builtInFuncs[ch][1];
} else {
funcName += builtInFuncs[ch][0];
}
}
state.func = true;
state.prev = false;
return "function " + funcName;
}
if (isComment.test(ch)) {
stream.skipToEnd();
return "comment";
}
if (ch === "∘" && stream.peek() === ".") {
stream.next();
return "function jot-dot";
}
stream.eatWhile(/[\w\$_]/);
word = stream.current();
state.prev = true;
return "keyword";
}
};
});
CodeMirror.defineMIME("text/apl", "apl");
});
| Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/mode/apl/apl.js/0 | {
"file_path": "Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/mode/apl/apl.js",
"repo_id": "Humsen",
"token_count": 2401
} | 60 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"), require("../../addon/mode/simple"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "../../addon/mode/simple"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
// Collect all Dockerfile directives
var instructions = ["from", "maintainer", "run", "cmd", "expose", "env",
"add", "copy", "entrypoint", "volume", "user",
"workdir", "onbuild"],
instructionRegex = "(" + instructions.join('|') + ")",
instructionOnlyLine = new RegExp(instructionRegex + "\\s*$", "i"),
instructionWithArguments = new RegExp(instructionRegex + "(\\s+)", "i");
CodeMirror.defineSimpleMode("dockerfile", {
start: [
// Block comment: This is a line starting with a comment
{
regex: /#.*$/,
token: "comment"
},
// Highlight an instruction without any arguments (for convenience)
{
regex: instructionOnlyLine,
token: "variable-2"
},
// Highlight an instruction followed by arguments
{
regex: instructionWithArguments,
token: ["variable-2", null],
next: "arguments"
},
{
regex: /./,
token: null
}
],
arguments: [
{
// Line comment without instruction arguments is an error
regex: /#.*$/,
token: "error",
next: "start"
},
{
regex: /[^#]+\\$/,
token: null
},
{
// Match everything except for the inline comment
regex: /[^#]+/,
token: null,
next: "start"
},
{
regex: /$/,
token: null,
next: "start"
},
// Fail safe return to start
{
token: null,
next: "start"
}
]
});
CodeMirror.defineMIME("text/x-dockerfile", "dockerfile");
});
| Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/mode/dockerfile/dockerfile.js/0 | {
"file_path": "Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/mode/dockerfile/dockerfile.js",
"repo_id": "Humsen",
"token_count": 943
} | 61 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function() {
var mode = CodeMirror.getMode({tabSize: 4, indentUnit: 2}, "haml");
function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
// Requires at least one media query
MT("elementName",
"[tag %h1] Hey There");
MT("oneElementPerLine",
"[tag %h1] Hey There %h2");
MT("idSelector",
"[tag %h1][attribute #test] Hey There");
MT("classSelector",
"[tag %h1][attribute .hello] Hey There");
MT("docType",
"[tag !!! XML]");
MT("comment",
"[comment / Hello WORLD]");
MT("notComment",
"[tag %h1] This is not a / comment ");
MT("attributes",
"[tag %a]([variable title][operator =][string \"test\"]){[atom :title] [operator =>] [string \"test\"]}");
MT("htmlCode",
"[tag&bracket <][tag h1][tag&bracket >]Title[tag&bracket </][tag h1][tag&bracket >]");
MT("rubyBlock",
"[operator =][variable-2 @item]");
MT("selectorRubyBlock",
"[tag %a.selector=] [variable-2 @item]");
MT("nestedRubyBlock",
"[tag %a]",
" [operator =][variable puts] [string \"test\"]");
MT("multilinePlaintext",
"[tag %p]",
" Hello,",
" World");
MT("multilineRuby",
"[tag %p]",
" [comment -# this is a comment]",
" [comment and this is a comment too]",
" Date/Time",
" [operator -] [variable now] [operator =] [tag DateTime][operator .][property now]",
" [tag %strong=] [variable now]",
" [operator -] [keyword if] [variable now] [operator >] [tag DateTime][operator .][property parse]([string \"December 31, 2006\"])",
" [operator =][string \"Happy\"]",
" [operator =][string \"Belated\"]",
" [operator =][string \"Birthday\"]");
MT("multilineComment",
"[comment /]",
" [comment Multiline]",
" [comment Comment]");
MT("hamlComment",
"[comment -# this is a comment]");
MT("multilineHamlComment",
"[comment -# this is a comment]",
" [comment and this is a comment too]");
MT("multilineHTMLComment",
"[comment <!--]",
" [comment what a comment]",
" [comment -->]");
MT("hamlAfterRubyTag",
"[attribute .block]",
" [tag %strong=] [variable now]",
" [attribute .test]",
" [operator =][variable now]",
" [attribute .right]");
MT("stretchedRuby",
"[operator =] [variable puts] [string \"Hello\"],",
" [string \"World\"]");
MT("interpolationInHashAttribute",
//"[tag %div]{[atom :id] [operator =>] [string \"#{][variable test][string }_#{][variable ting][string }\"]} test");
"[tag %div]{[atom :id] [operator =>] [string \"#{][variable test][string }_#{][variable ting][string }\"]} test");
MT("interpolationInHTMLAttribute",
"[tag %div]([variable title][operator =][string \"#{][variable test][string }_#{][variable ting]()[string }\"]) Test");
})();
| Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/mode/haml/test.js/0 | {
"file_path": "Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/mode/haml/test.js",
"repo_id": "Humsen",
"token_count": 1178
} | 62 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function() {
var mode = CodeMirror.getMode({tabSize: 4}, "markdown");
function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
var modeHighlightFormatting = CodeMirror.getMode({tabSize: 4}, {name: "markdown", highlightFormatting: true});
function FT(name) { test.mode(name, modeHighlightFormatting, Array.prototype.slice.call(arguments, 1)); }
FT("formatting_emAsterisk",
"[em&formatting&formatting-em *][em foo][em&formatting&formatting-em *]");
FT("formatting_emUnderscore",
"[em&formatting&formatting-em _][em foo][em&formatting&formatting-em _]");
FT("formatting_strongAsterisk",
"[strong&formatting&formatting-strong **][strong foo][strong&formatting&formatting-strong **]");
FT("formatting_strongUnderscore",
"[strong&formatting&formatting-strong __][strong foo][strong&formatting&formatting-strong __]");
FT("formatting_codeBackticks",
"[comment&formatting&formatting-code `][comment foo][comment&formatting&formatting-code `]");
FT("formatting_doubleBackticks",
"[comment&formatting&formatting-code ``][comment foo ` bar][comment&formatting&formatting-code ``]");
FT("formatting_atxHeader",
"[header&header-1&formatting&formatting-header&formatting-header-1 #][header&header-1 foo # bar ][header&header-1&formatting&formatting-header&formatting-header-1 #]");
FT("formatting_setextHeader",
"foo",
"[header&header-1&formatting&formatting-header&formatting-header-1 =]");
FT("formatting_blockquote",
"[quote"e-1&formatting&formatting-quote&formatting-quote-1 > ][quote"e-1 foo]");
FT("formatting_list",
"[variable-2&formatting&formatting-list&formatting-list-ul - ][variable-2 foo]");
FT("formatting_list",
"[variable-2&formatting&formatting-list&formatting-list-ol 1. ][variable-2 foo]");
FT("formatting_link",
"[link&formatting&formatting-link [][link foo][link&formatting&formatting-link ]]][string&formatting&formatting-link-string (][string http://example.com/][string&formatting&formatting-link-string )]");
FT("formatting_linkReference",
"[link&formatting&formatting-link [][link foo][link&formatting&formatting-link ]]][string&formatting&formatting-link-string [][string bar][string&formatting&formatting-link-string ]]]",
"[link&formatting&formatting-link [][link bar][link&formatting&formatting-link ]]:] [string http://example.com/]");
FT("formatting_linkWeb",
"[link&formatting&formatting-link <][link http://example.com/][link&formatting&formatting-link >]");
FT("formatting_linkEmail",
"[link&formatting&formatting-link <][link user@example.com][link&formatting&formatting-link >]");
FT("formatting_escape",
"[formatting-escape \\*]");
MT("plainText",
"foo");
// Don't style single trailing space
MT("trailingSpace1",
"foo ");
// Two or more trailing spaces should be styled with line break character
MT("trailingSpace2",
"foo[trailing-space-a ][trailing-space-new-line ]");
MT("trailingSpace3",
"foo[trailing-space-a ][trailing-space-b ][trailing-space-new-line ]");
MT("trailingSpace4",
"foo[trailing-space-a ][trailing-space-b ][trailing-space-a ][trailing-space-new-line ]");
// Code blocks using 4 spaces (regardless of CodeMirror.tabSize value)
MT("codeBlocksUsing4Spaces",
" [comment foo]");
// Code blocks using 4 spaces with internal indentation
MT("codeBlocksUsing4SpacesIndentation",
" [comment bar]",
" [comment hello]",
" [comment world]",
" [comment foo]",
"bar");
// Code blocks using 4 spaces with internal indentation
MT("codeBlocksUsing4SpacesIndentation",
" foo",
" [comment bar]",
" [comment hello]",
" [comment world]");
// Code blocks should end even after extra indented lines
MT("codeBlocksWithTrailingIndentedLine",
" [comment foo]",
" [comment bar]",
" [comment baz]",
" ",
"hello");
// Code blocks using 1 tab (regardless of CodeMirror.indentWithTabs value)
MT("codeBlocksUsing1Tab",
"\t[comment foo]");
// Inline code using backticks
MT("inlineCodeUsingBackticks",
"foo [comment `bar`]");
// Block code using single backtick (shouldn't work)
MT("blockCodeSingleBacktick",
"[comment `]",
"foo",
"[comment `]");
// Unclosed backticks
// Instead of simply marking as CODE, it would be nice to have an
// incomplete flag for CODE, that is styled slightly different.
MT("unclosedBackticks",
"foo [comment `bar]");
// Per documentation: "To include a literal backtick character within a
// code span, you can use multiple backticks as the opening and closing
// delimiters"
MT("doubleBackticks",
"[comment ``foo ` bar``]");
// Tests based on Dingus
// http://daringfireball.net/projects/markdown/dingus
//
// Multiple backticks within an inline code block
MT("consecutiveBackticks",
"[comment `foo```bar`]");
// Multiple backticks within an inline code block with a second code block
MT("consecutiveBackticks",
"[comment `foo```bar`] hello [comment `world`]");
// Unclosed with several different groups of backticks
MT("unclosedBackticks",
"[comment ``foo ``` bar` hello]");
// Closed with several different groups of backticks
MT("closedBackticks",
"[comment ``foo ``` bar` hello``] world");
// atx headers
// http://daringfireball.net/projects/markdown/syntax#header
MT("atxH1",
"[header&header-1 # foo]");
MT("atxH2",
"[header&header-2 ## foo]");
MT("atxH3",
"[header&header-3 ### foo]");
MT("atxH4",
"[header&header-4 #### foo]");
MT("atxH5",
"[header&header-5 ##### foo]");
MT("atxH6",
"[header&header-6 ###### foo]");
// H6 - 7x '#' should still be H6, per Dingus
// http://daringfireball.net/projects/markdown/dingus
MT("atxH6NotH7",
"[header&header-6 ####### foo]");
// Inline styles should be parsed inside headers
MT("atxH1inline",
"[header&header-1 # foo ][header&header-1&em *bar*]");
// Setext headers - H1, H2
// Per documentation, "Any number of underlining =’s or -’s will work."
// http://daringfireball.net/projects/markdown/syntax#header
// Ideally, the text would be marked as `header` as well, but this is
// not really feasible at the moment. So, instead, we're testing against
// what works today, to avoid any regressions.
//
// Check if single underlining = works
MT("setextH1",
"foo",
"[header&header-1 =]");
// Check if 3+ ='s work
MT("setextH1",
"foo",
"[header&header-1 ===]");
// Check if single underlining - works
MT("setextH2",
"foo",
"[header&header-2 -]");
// Check if 3+ -'s work
MT("setextH2",
"foo",
"[header&header-2 ---]");
// Single-line blockquote with trailing space
MT("blockquoteSpace",
"[quote"e-1 > foo]");
// Single-line blockquote
MT("blockquoteNoSpace",
"[quote"e-1 >foo]");
// No blank line before blockquote
MT("blockquoteNoBlankLine",
"foo",
"[quote"e-1 > bar]");
// Nested blockquote
MT("blockquoteSpace",
"[quote"e-1 > foo]",
"[quote"e-1 >][quote"e-2 > foo]",
"[quote"e-1 >][quote"e-2 >][quote"e-3 > foo]");
// Single-line blockquote followed by normal paragraph
MT("blockquoteThenParagraph",
"[quote"e-1 >foo]",
"",
"bar");
// Multi-line blockquote (lazy mode)
MT("multiBlockquoteLazy",
"[quote"e-1 >foo]",
"[quote"e-1 bar]");
// Multi-line blockquote followed by normal paragraph (lazy mode)
MT("multiBlockquoteLazyThenParagraph",
"[quote"e-1 >foo]",
"[quote"e-1 bar]",
"",
"hello");
// Multi-line blockquote (non-lazy mode)
MT("multiBlockquote",
"[quote"e-1 >foo]",
"[quote"e-1 >bar]");
// Multi-line blockquote followed by normal paragraph (non-lazy mode)
MT("multiBlockquoteThenParagraph",
"[quote"e-1 >foo]",
"[quote"e-1 >bar]",
"",
"hello");
// Check list types
MT("listAsterisk",
"foo",
"bar",
"",
"[variable-2 * foo]",
"[variable-2 * bar]");
MT("listPlus",
"foo",
"bar",
"",
"[variable-2 + foo]",
"[variable-2 + bar]");
MT("listDash",
"foo",
"bar",
"",
"[variable-2 - foo]",
"[variable-2 - bar]");
MT("listNumber",
"foo",
"bar",
"",
"[variable-2 1. foo]",
"[variable-2 2. bar]");
// Lists require a preceding blank line (per Dingus)
MT("listBogus",
"foo",
"1. bar",
"2. hello");
// List after header
MT("listAfterHeader",
"[header&header-1 # foo]",
"[variable-2 - bar]");
// Formatting in lists (*)
MT("listAsteriskFormatting",
"[variable-2 * ][variable-2&em *foo*][variable-2 bar]",
"[variable-2 * ][variable-2&strong **foo**][variable-2 bar]",
"[variable-2 * ][variable-2&strong **][variable-2&em&strong *foo**][variable-2&em *][variable-2 bar]",
"[variable-2 * ][variable-2&comment `foo`][variable-2 bar]");
// Formatting in lists (+)
MT("listPlusFormatting",
"[variable-2 + ][variable-2&em *foo*][variable-2 bar]",
"[variable-2 + ][variable-2&strong **foo**][variable-2 bar]",
"[variable-2 + ][variable-2&strong **][variable-2&em&strong *foo**][variable-2&em *][variable-2 bar]",
"[variable-2 + ][variable-2&comment `foo`][variable-2 bar]");
// Formatting in lists (-)
MT("listDashFormatting",
"[variable-2 - ][variable-2&em *foo*][variable-2 bar]",
"[variable-2 - ][variable-2&strong **foo**][variable-2 bar]",
"[variable-2 - ][variable-2&strong **][variable-2&em&strong *foo**][variable-2&em *][variable-2 bar]",
"[variable-2 - ][variable-2&comment `foo`][variable-2 bar]");
// Formatting in lists (1.)
MT("listNumberFormatting",
"[variable-2 1. ][variable-2&em *foo*][variable-2 bar]",
"[variable-2 2. ][variable-2&strong **foo**][variable-2 bar]",
"[variable-2 3. ][variable-2&strong **][variable-2&em&strong *foo**][variable-2&em *][variable-2 bar]",
"[variable-2 4. ][variable-2&comment `foo`][variable-2 bar]");
// Paragraph lists
MT("listParagraph",
"[variable-2 * foo]",
"",
"[variable-2 * bar]");
// Multi-paragraph lists
//
// 4 spaces
MT("listMultiParagraph",
"[variable-2 * foo]",
"",
"[variable-2 * bar]",
"",
" [variable-2 hello]");
// 4 spaces, extra blank lines (should still be list, per Dingus)
MT("listMultiParagraphExtra",
"[variable-2 * foo]",
"",
"[variable-2 * bar]",
"",
"",
" [variable-2 hello]");
// 4 spaces, plus 1 space (should still be list, per Dingus)
MT("listMultiParagraphExtraSpace",
"[variable-2 * foo]",
"",
"[variable-2 * bar]",
"",
" [variable-2 hello]",
"",
" [variable-2 world]");
// 1 tab
MT("listTab",
"[variable-2 * foo]",
"",
"[variable-2 * bar]",
"",
"\t[variable-2 hello]");
// No indent
MT("listNoIndent",
"[variable-2 * foo]",
"",
"[variable-2 * bar]",
"",
"hello");
// Blockquote
MT("blockquote",
"[variable-2 * foo]",
"",
"[variable-2 * bar]",
"",
" [variable-2"e"e-1 > hello]");
// Code block
MT("blockquoteCode",
"[variable-2 * foo]",
"",
"[variable-2 * bar]",
"",
" [comment > hello]",
"",
" [variable-2 world]");
// Code block followed by text
MT("blockquoteCodeText",
"[variable-2 * foo]",
"",
" [variable-2 bar]",
"",
" [comment hello]",
"",
" [variable-2 world]");
// Nested list
MT("listAsteriskNested",
"[variable-2 * foo]",
"",
" [variable-3 * bar]");
MT("listPlusNested",
"[variable-2 + foo]",
"",
" [variable-3 + bar]");
MT("listDashNested",
"[variable-2 - foo]",
"",
" [variable-3 - bar]");
MT("listNumberNested",
"[variable-2 1. foo]",
"",
" [variable-3 2. bar]");
MT("listMixed",
"[variable-2 * foo]",
"",
" [variable-3 + bar]",
"",
" [keyword - hello]",
"",
" [variable-2 1. world]");
MT("listBlockquote",
"[variable-2 * foo]",
"",
" [variable-3 + bar]",
"",
" [quote"e-1&variable-3 > hello]");
MT("listCode",
"[variable-2 * foo]",
"",
" [variable-3 + bar]",
"",
" [comment hello]");
// Code with internal indentation
MT("listCodeIndentation",
"[variable-2 * foo]",
"",
" [comment bar]",
" [comment hello]",
" [comment world]",
" [comment foo]",
" [variable-2 bar]");
// List nesting edge cases
MT("listNested",
"[variable-2 * foo]",
"",
" [variable-3 * bar]",
"",
" [variable-2 hello]"
);
MT("listNested",
"[variable-2 * foo]",
"",
" [variable-3 * bar]",
"",
" [variable-3 * foo]"
);
// Code followed by text
MT("listCodeText",
"[variable-2 * foo]",
"",
" [comment bar]",
"",
"hello");
// Following tests directly from official Markdown documentation
// http://daringfireball.net/projects/markdown/syntax#hr
MT("hrSpace",
"[hr * * *]");
MT("hr",
"[hr ***]");
MT("hrLong",
"[hr *****]");
MT("hrSpaceDash",
"[hr - - -]");
MT("hrDashLong",
"[hr ---------------------------------------]");
// Inline link with title
MT("linkTitle",
"[link [[foo]]][string (http://example.com/ \"bar\")] hello");
// Inline link without title
MT("linkNoTitle",
"[link [[foo]]][string (http://example.com/)] bar");
// Inline link with image
MT("linkImage",
"[link [[][tag ![[foo]]][string (http://example.com/)][link ]]][string (http://example.com/)] bar");
// Inline link with Em
MT("linkEm",
"[link [[][link&em *foo*][link ]]][string (http://example.com/)] bar");
// Inline link with Strong
MT("linkStrong",
"[link [[][link&strong **foo**][link ]]][string (http://example.com/)] bar");
// Inline link with EmStrong
MT("linkEmStrong",
"[link [[][link&strong **][link&em&strong *foo**][link&em *][link ]]][string (http://example.com/)] bar");
// Image with title
MT("imageTitle",
"[tag ![[foo]]][string (http://example.com/ \"bar\")] hello");
// Image without title
MT("imageNoTitle",
"[tag ![[foo]]][string (http://example.com/)] bar");
// Image with asterisks
MT("imageAsterisks",
"[tag ![[*foo*]]][string (http://example.com/)] bar");
// Not a link. Should be normal text due to square brackets being used
// regularly in text, especially in quoted material, and no space is allowed
// between square brackets and parentheses (per Dingus).
MT("notALink",
"[[foo]] (bar)");
// Reference-style links
MT("linkReference",
"[link [[foo]]][string [[bar]]] hello");
// Reference-style links with Em
MT("linkReferenceEm",
"[link [[][link&em *foo*][link ]]][string [[bar]]] hello");
// Reference-style links with Strong
MT("linkReferenceStrong",
"[link [[][link&strong **foo**][link ]]][string [[bar]]] hello");
// Reference-style links with EmStrong
MT("linkReferenceEmStrong",
"[link [[][link&strong **][link&em&strong *foo**][link&em *][link ]]][string [[bar]]] hello");
// Reference-style links with optional space separator (per docuentation)
// "You can optionally use a space to separate the sets of brackets"
MT("linkReferenceSpace",
"[link [[foo]]] [string [[bar]]] hello");
// Should only allow a single space ("...use *a* space...")
MT("linkReferenceDoubleSpace",
"[[foo]] [[bar]] hello");
// Reference-style links with implicit link name
MT("linkImplicit",
"[link [[foo]]][string [[]]] hello");
// @todo It would be nice if, at some point, the document was actually
// checked to see if the referenced link exists
// Link label, for reference-style links (taken from documentation)
MT("labelNoTitle",
"[link [[foo]]:] [string http://example.com/]");
MT("labelIndented",
" [link [[foo]]:] [string http://example.com/]");
MT("labelSpaceTitle",
"[link [[foo bar]]:] [string http://example.com/ \"hello\"]");
MT("labelDoubleTitle",
"[link [[foo bar]]:] [string http://example.com/ \"hello\"] \"world\"");
MT("labelTitleDoubleQuotes",
"[link [[foo]]:] [string http://example.com/ \"bar\"]");
MT("labelTitleSingleQuotes",
"[link [[foo]]:] [string http://example.com/ 'bar']");
MT("labelTitleParenthese",
"[link [[foo]]:] [string http://example.com/ (bar)]");
MT("labelTitleInvalid",
"[link [[foo]]:] [string http://example.com/] bar");
MT("labelLinkAngleBrackets",
"[link [[foo]]:] [string <http://example.com/> \"bar\"]");
MT("labelTitleNextDoubleQuotes",
"[link [[foo]]:] [string http://example.com/]",
"[string \"bar\"] hello");
MT("labelTitleNextSingleQuotes",
"[link [[foo]]:] [string http://example.com/]",
"[string 'bar'] hello");
MT("labelTitleNextParenthese",
"[link [[foo]]:] [string http://example.com/]",
"[string (bar)] hello");
MT("labelTitleNextMixed",
"[link [[foo]]:] [string http://example.com/]",
"(bar\" hello");
MT("linkWeb",
"[link <http://example.com/>] foo");
MT("linkWebDouble",
"[link <http://example.com/>] foo [link <http://example.com/>]");
MT("linkEmail",
"[link <user@example.com>] foo");
MT("linkEmailDouble",
"[link <user@example.com>] foo [link <user@example.com>]");
MT("emAsterisk",
"[em *foo*] bar");
MT("emUnderscore",
"[em _foo_] bar");
MT("emInWordAsterisk",
"foo[em *bar*]hello");
MT("emInWordUnderscore",
"foo[em _bar_]hello");
// Per documentation: "...surround an * or _ with spaces, it’ll be
// treated as a literal asterisk or underscore."
MT("emEscapedBySpaceIn",
"foo [em _bar _ hello_] world");
MT("emEscapedBySpaceOut",
"foo _ bar[em _hello_]world");
MT("emEscapedByNewline",
"foo",
"_ bar[em _hello_]world");
// Unclosed emphasis characters
// Instead of simply marking as EM / STRONG, it would be nice to have an
// incomplete flag for EM and STRONG, that is styled slightly different.
MT("emIncompleteAsterisk",
"foo [em *bar]");
MT("emIncompleteUnderscore",
"foo [em _bar]");
MT("strongAsterisk",
"[strong **foo**] bar");
MT("strongUnderscore",
"[strong __foo__] bar");
MT("emStrongAsterisk",
"[em *foo][em&strong **bar*][strong hello**] world");
MT("emStrongUnderscore",
"[em _foo][em&strong __bar_][strong hello__] world");
// "...same character must be used to open and close an emphasis span.""
MT("emStrongMixed",
"[em _foo][em&strong **bar*hello__ world]");
MT("emStrongMixed",
"[em *foo][em&strong __bar_hello** world]");
// These characters should be escaped:
// \ backslash
// ` backtick
// * asterisk
// _ underscore
// {} curly braces
// [] square brackets
// () parentheses
// # hash mark
// + plus sign
// - minus sign (hyphen)
// . dot
// ! exclamation mark
MT("escapeBacktick",
"foo \\`bar\\`");
MT("doubleEscapeBacktick",
"foo \\\\[comment `bar\\\\`]");
MT("escapeAsterisk",
"foo \\*bar\\*");
MT("doubleEscapeAsterisk",
"foo \\\\[em *bar\\\\*]");
MT("escapeUnderscore",
"foo \\_bar\\_");
MT("doubleEscapeUnderscore",
"foo \\\\[em _bar\\\\_]");
MT("escapeHash",
"\\# foo");
MT("doubleEscapeHash",
"\\\\# foo");
MT("escapeNewline",
"\\",
"[em *foo*]");
// Tests to make sure GFM-specific things aren't getting through
MT("taskList",
"[variable-2 * [ ]] bar]");
MT("fencedCodeBlocks",
"[comment ```]",
"foo",
"[comment ```]");
// Tests that require XML mode
MT("xmlMode",
"[tag&bracket <][tag div][tag&bracket >]",
"*foo*",
"[tag&bracket <][tag http://github.com][tag&bracket />]",
"[tag&bracket </][tag div][tag&bracket >]",
"[link <http://github.com/>]");
MT("xmlModeWithMarkdownInside",
"[tag&bracket <][tag div] [attribute markdown]=[string 1][tag&bracket >]",
"[em *foo*]",
"[link <http://github.com/>]",
"[tag </div>]",
"[link <http://github.com/>]",
"[tag&bracket <][tag div][tag&bracket >]",
"[tag&bracket </][tag div][tag&bracket >]");
})();
| Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/mode/markdown/test.js/0 | {
"file_path": "Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/mode/markdown/test.js",
"repo_id": "Humsen",
"token_count": 8151
} | 63 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
function wordRegexp(words) {
return new RegExp("^((" + words.join(")|(") + "))\\b");
}
var wordOperators = wordRegexp(["and", "or", "not", "is"]);
var commonKeywords = ["as", "assert", "break", "class", "continue",
"def", "del", "elif", "else", "except", "finally",
"for", "from", "global", "if", "import",
"lambda", "pass", "raise", "return",
"try", "while", "with", "yield", "in"];
var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr",
"classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod",
"enumerate", "eval", "filter", "float", "format", "frozenset",
"getattr", "globals", "hasattr", "hash", "help", "hex", "id",
"input", "int", "isinstance", "issubclass", "iter", "len",
"list", "locals", "map", "max", "memoryview", "min", "next",
"object", "oct", "open", "ord", "pow", "property", "range",
"repr", "reversed", "round", "set", "setattr", "slice",
"sorted", "staticmethod", "str", "sum", "super", "tuple",
"type", "vars", "zip", "__import__", "NotImplemented",
"Ellipsis", "__debug__"];
var py2 = {builtins: ["apply", "basestring", "buffer", "cmp", "coerce", "execfile",
"file", "intern", "long", "raw_input", "reduce", "reload",
"unichr", "unicode", "xrange", "False", "True", "None"],
keywords: ["exec", "print"]};
var py3 = {builtins: ["ascii", "bytes", "exec", "print"],
keywords: ["nonlocal", "False", "True", "None"]};
CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins));
function top(state) {
return state.scopes[state.scopes.length - 1];
}
CodeMirror.defineMode("python", function(conf, parserConf) {
var ERRORCLASS = "error";
var singleDelimiters = parserConf.singleDelimiters || new RegExp("^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]");
var doubleOperators = parserConf.doubleOperators || new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
var doubleDelimiters = parserConf.doubleDelimiters || new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
var tripleDelimiters = parserConf.tripleDelimiters || new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
if (parserConf.version && parseInt(parserConf.version, 10) == 3){
// since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator
var singleOperators = parserConf.singleOperators || new RegExp("^[\\+\\-\\*/%&|\\^~<>!@]");
var identifiers = parserConf.identifiers|| new RegExp("^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*");
} else {
var singleOperators = parserConf.singleOperators || new RegExp("^[\\+\\-\\*/%&|\\^~<>!]");
var identifiers = parserConf.identifiers|| new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
}
var hangingIndent = parserConf.hangingIndent || conf.indentUnit;
var myKeywords = commonKeywords, myBuiltins = commonBuiltins;
if(parserConf.extra_keywords != undefined){
myKeywords = myKeywords.concat(parserConf.extra_keywords);
}
if(parserConf.extra_builtins != undefined){
myBuiltins = myBuiltins.concat(parserConf.extra_builtins);
}
if (parserConf.version && parseInt(parserConf.version, 10) == 3) {
myKeywords = myKeywords.concat(py3.keywords);
myBuiltins = myBuiltins.concat(py3.builtins);
var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");
} else {
myKeywords = myKeywords.concat(py2.keywords);
myBuiltins = myBuiltins.concat(py2.builtins);
var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
}
var keywords = wordRegexp(myKeywords);
var builtins = wordRegexp(myBuiltins);
// tokenizers
function tokenBase(stream, state) {
// Handle scope changes
if (stream.sol() && top(state).type == "py") {
var scopeOffset = top(state).offset;
if (stream.eatSpace()) {
var lineOffset = stream.indentation();
if (lineOffset > scopeOffset)
pushScope(stream, state, "py");
else if (lineOffset < scopeOffset && dedent(stream, state))
state.errorToken = true;
return null;
} else {
var style = tokenBaseInner(stream, state);
if (scopeOffset > 0 && dedent(stream, state))
style += " " + ERRORCLASS;
return style;
}
}
return tokenBaseInner(stream, state);
}
function tokenBaseInner(stream, state) {
if (stream.eatSpace()) return null;
var ch = stream.peek();
// Handle Comments
if (ch == "#") {
stream.skipToEnd();
return "comment";
}
// Handle Number Literals
if (stream.match(/^[0-9\.]/, false)) {
var floatLiteral = false;
// Floats
if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
if (stream.match(/^\.\d+/)) { floatLiteral = true; }
if (floatLiteral) {
// Float literals may be "imaginary"
stream.eat(/J/i);
return "number";
}
// Integers
var intLiteral = false;
// Hex
if (stream.match(/^0x[0-9a-f]+/i)) intLiteral = true;
// Binary
if (stream.match(/^0b[01]+/i)) intLiteral = true;
// Octal
if (stream.match(/^0o[0-7]+/i)) intLiteral = true;
// Decimal
if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
// Decimal literals may be "imaginary"
stream.eat(/J/i);
// TODO - Can you have imaginary longs?
intLiteral = true;
}
// Zero by itself with no other piece of number.
if (stream.match(/^0(?![\dx])/i)) intLiteral = true;
if (intLiteral) {
// Integer literals may be "long"
stream.eat(/L/i);
return "number";
}
}
// Handle Strings
if (stream.match(stringPrefixes)) {
state.tokenize = tokenStringFactory(stream.current());
return state.tokenize(stream, state);
}
// Handle operators and Delimiters
if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters))
return null;
if (stream.match(doubleOperators)
|| stream.match(singleOperators)
|| stream.match(wordOperators))
return "operator";
if (stream.match(singleDelimiters))
return null;
if (stream.match(keywords))
return "keyword";
if (stream.match(builtins))
return "builtin";
if (stream.match(/^(self|cls)\b/))
return "variable-2";
if (stream.match(identifiers)) {
if (state.lastToken == "def" || state.lastToken == "class")
return "def";
return "variable";
}
// Handle non-detected items
stream.next();
return ERRORCLASS;
}
function tokenStringFactory(delimiter) {
while ("rub".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
delimiter = delimiter.substr(1);
var singleline = delimiter.length == 1;
var OUTCLASS = "string";
function tokenString(stream, state) {
while (!stream.eol()) {
stream.eatWhile(/[^'"\\]/);
if (stream.eat("\\")) {
stream.next();
if (singleline && stream.eol())
return OUTCLASS;
} else if (stream.match(delimiter)) {
state.tokenize = tokenBase;
return OUTCLASS;
} else {
stream.eat(/['"]/);
}
}
if (singleline) {
if (parserConf.singleLineStringErrors)
return ERRORCLASS;
else
state.tokenize = tokenBase;
}
return OUTCLASS;
}
tokenString.isString = true;
return tokenString;
}
function pushScope(stream, state, type) {
var offset = 0, align = null;
if (type == "py") {
while (top(state).type != "py")
state.scopes.pop();
}
offset = top(state).offset + (type == "py" ? conf.indentUnit : hangingIndent);
if (type != "py" && !stream.match(/^(\s|#.*)*$/, false))
align = stream.column() + 1;
state.scopes.push({offset: offset, type: type, align: align});
}
function dedent(stream, state) {
var indented = stream.indentation();
while (top(state).offset > indented) {
if (top(state).type != "py") return true;
state.scopes.pop();
}
return top(state).offset != indented;
}
function tokenLexer(stream, state) {
var style = state.tokenize(stream, state);
var current = stream.current();
// Handle '.' connected identifiers
if (current == ".") {
style = stream.match(identifiers, false) ? null : ERRORCLASS;
if (style == null && state.lastStyle == "meta") {
// Apply 'meta' style to '.' connected identifiers when
// appropriate.
style = "meta";
}
return style;
}
// Handle decorators
if (current == "@"){
if(parserConf.version && parseInt(parserConf.version, 10) == 3){
return stream.match(identifiers, false) ? "meta" : "operator";
} else {
return stream.match(identifiers, false) ? "meta" : ERRORCLASS;
}
}
if ((style == "variable" || style == "builtin")
&& state.lastStyle == "meta")
style = "meta";
// Handle scope changes.
if (current == "pass" || current == "return")
state.dedent += 1;
if (current == "lambda") state.lambda = true;
if (current == ":" && !state.lambda && top(state).type == "py")
pushScope(stream, state, "py");
var delimiter_index = current.length == 1 ? "[({".indexOf(current) : -1;
if (delimiter_index != -1)
pushScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1));
delimiter_index = "])}".indexOf(current);
if (delimiter_index != -1) {
if (top(state).type == current) state.scopes.pop();
else return ERRORCLASS;
}
if (state.dedent > 0 && stream.eol() && top(state).type == "py") {
if (state.scopes.length > 1) state.scopes.pop();
state.dedent -= 1;
}
return style;
}
var external = {
startState: function(basecolumn) {
return {
tokenize: tokenBase,
scopes: [{offset: basecolumn || 0, type: "py", align: null}],
lastStyle: null,
lastToken: null,
lambda: false,
dedent: 0
};
},
token: function(stream, state) {
var addErr = state.errorToken;
if (addErr) state.errorToken = false;
var style = tokenLexer(stream, state);
state.lastStyle = style;
var current = stream.current();
if (current && style)
state.lastToken = current;
if (stream.eol() && state.lambda)
state.lambda = false;
return addErr ? style + " " + ERRORCLASS : style;
},
indent: function(state, textAfter) {
if (state.tokenize != tokenBase)
return state.tokenize.isString ? CodeMirror.Pass : 0;
var scope = top(state);
var closing = textAfter && textAfter.charAt(0) == scope.type;
if (scope.align != null)
return scope.align - (closing ? 1 : 0);
else if (closing && state.scopes.length > 1)
return state.scopes[state.scopes.length - 2].offset;
else
return scope.offset;
},
lineComment: "#",
fold: "indent"
};
return external;
});
CodeMirror.defineMIME("text/x-python", "python");
var words = function(str) { return str.split(" "); };
CodeMirror.defineMIME("text/x-cython", {
name: "python",
extra_keywords: words("by cdef cimport cpdef ctypedef enum except"+
"extern gil include nogil property public"+
"readonly struct union DEF IF ELIF ELSE")
});
});
| Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/mode/python/python.js/0 | {
"file_path": "Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/mode/python/python.js",
"repo_id": "Humsen",
"token_count": 5909
} | 64 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
/**
* Smarty 2 and 3 mode.
*/
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("smarty", function(config) {
"use strict";
// our default settings; check to see if they're overridden
var settings = {
rightDelimiter: '}',
leftDelimiter: '{',
smartyVersion: 2 // for backward compatibility
};
if (config.hasOwnProperty("leftDelimiter")) {
settings.leftDelimiter = config.leftDelimiter;
}
if (config.hasOwnProperty("rightDelimiter")) {
settings.rightDelimiter = config.rightDelimiter;
}
if (config.hasOwnProperty("smartyVersion") && config.smartyVersion === 3) {
settings.smartyVersion = 3;
}
var keyFunctions = ["debug", "extends", "function", "include", "literal"];
var last;
var regs = {
operatorChars: /[+\-*&%=<>!?]/,
validIdentifier: /[a-zA-Z0-9_]/,
stringChar: /['"]/
};
var helpers = {
cont: function(style, lastType) {
last = lastType;
return style;
},
chain: function(stream, state, parser) {
state.tokenize = parser;
return parser(stream, state);
}
};
// our various parsers
var parsers = {
// the main tokenizer
tokenizer: function(stream, state) {
if (stream.match(settings.leftDelimiter, true)) {
if (stream.eat("*")) {
return helpers.chain(stream, state, parsers.inBlock("comment", "*" + settings.rightDelimiter));
} else {
// Smarty 3 allows { and } surrounded by whitespace to NOT slip into Smarty mode
state.depth++;
var isEol = stream.eol();
var isFollowedByWhitespace = /\s/.test(stream.peek());
if (settings.smartyVersion === 3 && settings.leftDelimiter === "{" && (isEol || isFollowedByWhitespace)) {
state.depth--;
return null;
} else {
state.tokenize = parsers.smarty;
last = "startTag";
return "tag";
}
}
} else {
stream.next();
return null;
}
},
// parsing Smarty content
smarty: function(stream, state) {
if (stream.match(settings.rightDelimiter, true)) {
if (settings.smartyVersion === 3) {
state.depth--;
if (state.depth <= 0) {
state.tokenize = parsers.tokenizer;
}
} else {
state.tokenize = parsers.tokenizer;
}
return helpers.cont("tag", null);
}
if (stream.match(settings.leftDelimiter, true)) {
state.depth++;
return helpers.cont("tag", "startTag");
}
var ch = stream.next();
if (ch == "$") {
stream.eatWhile(regs.validIdentifier);
return helpers.cont("variable-2", "variable");
} else if (ch == "|") {
return helpers.cont("operator", "pipe");
} else if (ch == ".") {
return helpers.cont("operator", "property");
} else if (regs.stringChar.test(ch)) {
state.tokenize = parsers.inAttribute(ch);
return helpers.cont("string", "string");
} else if (regs.operatorChars.test(ch)) {
stream.eatWhile(regs.operatorChars);
return helpers.cont("operator", "operator");
} else if (ch == "[" || ch == "]") {
return helpers.cont("bracket", "bracket");
} else if (ch == "(" || ch == ")") {
return helpers.cont("bracket", "operator");
} else if (/\d/.test(ch)) {
stream.eatWhile(/\d/);
return helpers.cont("number", "number");
} else {
if (state.last == "variable") {
if (ch == "@") {
stream.eatWhile(regs.validIdentifier);
return helpers.cont("property", "property");
} else if (ch == "|") {
stream.eatWhile(regs.validIdentifier);
return helpers.cont("qualifier", "modifier");
}
} else if (state.last == "pipe") {
stream.eatWhile(regs.validIdentifier);
return helpers.cont("qualifier", "modifier");
} else if (state.last == "whitespace") {
stream.eatWhile(regs.validIdentifier);
return helpers.cont("attribute", "modifier");
} if (state.last == "property") {
stream.eatWhile(regs.validIdentifier);
return helpers.cont("property", null);
} else if (/\s/.test(ch)) {
last = "whitespace";
return null;
}
var str = "";
if (ch != "/") {
str += ch;
}
var c = null;
while (c = stream.eat(regs.validIdentifier)) {
str += c;
}
for (var i=0, j=keyFunctions.length; i<j; i++) {
if (keyFunctions[i] == str) {
return helpers.cont("keyword", "keyword");
}
}
if (/\s/.test(ch)) {
return null;
}
return helpers.cont("tag", "tag");
}
},
inAttribute: function(quote) {
return function(stream, state) {
var prevChar = null;
var currChar = null;
while (!stream.eol()) {
currChar = stream.peek();
if (stream.next() == quote && prevChar !== '\\') {
state.tokenize = parsers.smarty;
break;
}
prevChar = currChar;
}
return "string";
};
},
inBlock: function(style, terminator) {
return function(stream, state) {
while (!stream.eol()) {
if (stream.match(terminator)) {
state.tokenize = parsers.tokenizer;
break;
}
stream.next();
}
return style;
};
}
};
// the public API for CodeMirror
return {
startState: function() {
return {
tokenize: parsers.tokenizer,
mode: "smarty",
last: null,
depth: 0
};
},
token: function(stream, state) {
var style = state.tokenize(stream, state);
state.last = last;
return style;
},
electricChars: ""
};
});
CodeMirror.defineMIME("text/x-smarty", "smarty");
});
| Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/mode/smarty/smarty.js/0 | {
"file_path": "Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/mode/smarty/smarty.js",
"repo_id": "Humsen",
"token_count": 2895
} | 65 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode('tiki', function(config) {
function inBlock(style, terminator, returnTokenizer) {
return function(stream, state) {
while (!stream.eol()) {
if (stream.match(terminator)) {
state.tokenize = inText;
break;
}
stream.next();
}
if (returnTokenizer) state.tokenize = returnTokenizer;
return style;
};
}
function inLine(style) {
return function(stream, state) {
while(!stream.eol()) {
stream.next();
}
state.tokenize = inText;
return style;
};
}
function inText(stream, state) {
function chain(parser) {
state.tokenize = parser;
return parser(stream, state);
}
var sol = stream.sol();
var ch = stream.next();
//non start of line
switch (ch) { //switch is generally much faster than if, so it is used here
case "{": //plugin
stream.eat("/");
stream.eatSpace();
var tagName = "";
var c;
while ((c = stream.eat(/[^\s\u00a0=\"\'\/?(}]/))) tagName += c;
state.tokenize = inPlugin;
return "tag";
break;
case "_": //bold
if (stream.eat("_")) {
return chain(inBlock("strong", "__", inText));
}
break;
case "'": //italics
if (stream.eat("'")) {
// Italic text
return chain(inBlock("em", "''", inText));
}
break;
case "(":// Wiki Link
if (stream.eat("(")) {
return chain(inBlock("variable-2", "))", inText));
}
break;
case "[":// Weblink
return chain(inBlock("variable-3", "]", inText));
break;
case "|": //table
if (stream.eat("|")) {
return chain(inBlock("comment", "||"));
}
break;
case "-":
if (stream.eat("=")) {//titleBar
return chain(inBlock("header string", "=-", inText));
} else if (stream.eat("-")) {//deleted
return chain(inBlock("error tw-deleted", "--", inText));
}
break;
case "=": //underline
if (stream.match("==")) {
return chain(inBlock("tw-underline", "===", inText));
}
break;
case ":":
if (stream.eat(":")) {
return chain(inBlock("comment", "::"));
}
break;
case "^": //box
return chain(inBlock("tw-box", "^"));
break;
case "~": //np
if (stream.match("np~")) {
return chain(inBlock("meta", "~/np~"));
}
break;
}
//start of line types
if (sol) {
switch (ch) {
case "!": //header at start of line
if (stream.match('!!!!!')) {
return chain(inLine("header string"));
} else if (stream.match('!!!!')) {
return chain(inLine("header string"));
} else if (stream.match('!!!')) {
return chain(inLine("header string"));
} else if (stream.match('!!')) {
return chain(inLine("header string"));
} else {
return chain(inLine("header string"));
}
break;
case "*": //unordered list line item, or <li /> at start of line
case "#": //ordered list line item, or <li /> at start of line
case "+": //ordered list line item, or <li /> at start of line
return chain(inLine("tw-listitem bracket"));
break;
}
}
//stream.eatWhile(/[&{]/); was eating up plugins, turned off to act less like html and more like tiki
return null;
}
var indentUnit = config.indentUnit;
// Return variables for tokenizers
var pluginName, type;
function inPlugin(stream, state) {
var ch = stream.next();
var peek = stream.peek();
if (ch == "}") {
state.tokenize = inText;
//type = ch == ")" ? "endPlugin" : "selfclosePlugin"; inPlugin
return "tag";
} else if (ch == "(" || ch == ")") {
return "bracket";
} else if (ch == "=") {
type = "equals";
if (peek == ">") {
ch = stream.next();
peek = stream.peek();
}
//here we detect values directly after equal character with no quotes
if (!/[\'\"]/.test(peek)) {
state.tokenize = inAttributeNoQuote();
}
//end detect values
return "operator";
} else if (/[\'\"]/.test(ch)) {
state.tokenize = inAttribute(ch);
return state.tokenize(stream, state);
} else {
stream.eatWhile(/[^\s\u00a0=\"\'\/?]/);
return "keyword";
}
}
function inAttribute(quote) {
return function(stream, state) {
while (!stream.eol()) {
if (stream.next() == quote) {
state.tokenize = inPlugin;
break;
}
}
return "string";
};
}
function inAttributeNoQuote() {
return function(stream, state) {
while (!stream.eol()) {
var ch = stream.next();
var peek = stream.peek();
if (ch == " " || ch == "," || /[ )}]/.test(peek)) {
state.tokenize = inPlugin;
break;
}
}
return "string";
};
}
var curState, setStyle;
function pass() {
for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]);
}
function cont() {
pass.apply(null, arguments);
return true;
}
function pushContext(pluginName, startOfLine) {
var noIndent = curState.context && curState.context.noIndent;
curState.context = {
prev: curState.context,
pluginName: pluginName,
indent: curState.indented,
startOfLine: startOfLine,
noIndent: noIndent
};
}
function popContext() {
if (curState.context) curState.context = curState.context.prev;
}
function element(type) {
if (type == "openPlugin") {curState.pluginName = pluginName; return cont(attributes, endplugin(curState.startOfLine));}
else if (type == "closePlugin") {
var err = false;
if (curState.context) {
err = curState.context.pluginName != pluginName;
popContext();
} else {
err = true;
}
if (err) setStyle = "error";
return cont(endcloseplugin(err));
}
else if (type == "string") {
if (!curState.context || curState.context.name != "!cdata") pushContext("!cdata");
if (curState.tokenize == inText) popContext();
return cont();
}
else return cont();
}
function endplugin(startOfLine) {
return function(type) {
if (
type == "selfclosePlugin" ||
type == "endPlugin"
)
return cont();
if (type == "endPlugin") {pushContext(curState.pluginName, startOfLine); return cont();}
return cont();
};
}
function endcloseplugin(err) {
return function(type) {
if (err) setStyle = "error";
if (type == "endPlugin") return cont();
return pass();
};
}
function attributes(type) {
if (type == "keyword") {setStyle = "attribute"; return cont(attributes);}
if (type == "equals") return cont(attvalue, attributes);
return pass();
}
function attvalue(type) {
if (type == "keyword") {setStyle = "string"; return cont();}
if (type == "string") return cont(attvaluemaybe);
return pass();
}
function attvaluemaybe(type) {
if (type == "string") return cont(attvaluemaybe);
else return pass();
}
return {
startState: function() {
return {tokenize: inText, cc: [], indented: 0, startOfLine: true, pluginName: null, context: null};
},
token: function(stream, state) {
if (stream.sol()) {
state.startOfLine = true;
state.indented = stream.indentation();
}
if (stream.eatSpace()) return null;
setStyle = type = pluginName = null;
var style = state.tokenize(stream, state);
if ((style || type) && style != "comment") {
curState = state;
while (true) {
var comb = state.cc.pop() || element;
if (comb(type || style)) break;
}
}
state.startOfLine = false;
return setStyle || style;
},
indent: function(state, textAfter) {
var context = state.context;
if (context && context.noIndent) return 0;
if (context && /^{\//.test(textAfter))
context = context.prev;
while (context && !context.startOfLine)
context = context.prev;
if (context) return context.indent + indentUnit;
else return 0;
},
electricChars: "/"
};
});
CodeMirror.defineMIME("text/tiki", "tiki");
});
| Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/mode/tiki/tiki.js/0 | {
"file_path": "Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/mode/tiki/tiki.js",
"repo_id": "Humsen",
"token_count": 3598
} | 66 |
{
"name": "codemirror",
"version":"5.0.0",
"main": "lib/codemirror.js",
"description": "In-browser code editing made bearable",
"licenses": [{"type": "MIT",
"url": "http://codemirror.net/LICENSE"}],
"directories": {"lib": "./lib"},
"scripts": {"test": "node ./test/run.js"},
"devDependencies": {"node-static": "0.6.0",
"phantomjs": "1.9.2-5",
"blint": ">=0.1.1"},
"bugs": "http://github.com/codemirror/CodeMirror/issues",
"keywords": ["JavaScript", "CodeMirror", "Editor"],
"homepage": "http://codemirror.net",
"maintainers":[{"name": "Marijn Haverbeke",
"email": "marijnh@gmail.com",
"web": "http://marijnhaverbeke.nl"}],
"repository": {"type": "git",
"url": "https://github.com/codemirror/CodeMirror.git"}
}
| Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/package.json/0 | {
"file_path": "Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/package.json",
"repo_id": "Humsen",
"token_count": 454
} | 67 |
/* Based on the theme at http://bonsaiden.github.com/JavaScript-Garden */
/*<!--match-->*/
.cm-s-midnight span.CodeMirror-matchhighlight { background: #494949; }
.cm-s-midnight.CodeMirror-focused span.CodeMirror-matchhighlight { background: #314D67 !important; }
/*<!--activeline-->*/
.cm-s-midnight .CodeMirror-activeline-background {background: #253540 !important;}
.cm-s-midnight.CodeMirror {
background: #0F192A;
color: #D1EDFF;
}
.cm-s-midnight.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}
.cm-s-midnight div.CodeMirror-selected {background: #314D67 !important;}
.cm-s-midnight.CodeMirror ::selection { background: rgba(49, 77, 103, .99); }
.cm-s-midnight.CodeMirror ::-moz-selection { background: rgba(49, 77, 103, .99); }
.cm-s-midnight .CodeMirror-gutters {background: #0F192A; border-right: 1px solid;}
.cm-s-midnight .CodeMirror-guttermarker { color: white; }
.cm-s-midnight .CodeMirror-guttermarker-subtle { color: #d0d0d0; }
.cm-s-midnight .CodeMirror-linenumber {color: #D0D0D0;}
.cm-s-midnight .CodeMirror-cursor {
border-left: 1px solid #F8F8F0 !important;
}
.cm-s-midnight span.cm-comment {color: #428BDD;}
.cm-s-midnight span.cm-atom {color: #AE81FF;}
.cm-s-midnight span.cm-number {color: #D1EDFF;}
.cm-s-midnight span.cm-property, .cm-s-midnight span.cm-attribute {color: #A6E22E;}
.cm-s-midnight span.cm-keyword {color: #E83737;}
.cm-s-midnight span.cm-string {color: #1DC116;}
.cm-s-midnight span.cm-variable {color: #FFAA3E;}
.cm-s-midnight span.cm-variable-2 {color: #FFAA3E;}
.cm-s-midnight span.cm-def {color: #4DD;}
.cm-s-midnight span.cm-bracket {color: #D1EDFF;}
.cm-s-midnight span.cm-tag {color: #449;}
.cm-s-midnight span.cm-link {color: #AE81FF;}
.cm-s-midnight span.cm-error {background: #F92672; color: #F8F8F0;}
.cm-s-midnight .CodeMirror-matchingbracket {
text-decoration: underline;
color: white !important;
}
| Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/theme/midnight.css/0 | {
"file_path": "Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/theme/midnight.css",
"repo_id": "Humsen",
"token_count": 788
} | 68 |
/*
Copyright (C) 2011 by MarkLogic Corporation
Author: Mike Brevoort <mike@brevoort.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
.cm-s-xq-light span.cm-keyword {line-height: 1em; font-weight: bold; color: #5A5CAD; }
.cm-s-xq-light span.cm-atom {color: #6C8CD5;}
.cm-s-xq-light span.cm-number {color: #164;}
.cm-s-xq-light span.cm-def {text-decoration:underline;}
.cm-s-xq-light span.cm-variable {color: black; }
.cm-s-xq-light span.cm-variable-2 {color:black;}
.cm-s-xq-light span.cm-variable-3 {color: black; }
.cm-s-xq-light span.cm-property {}
.cm-s-xq-light span.cm-operator {}
.cm-s-xq-light span.cm-comment {color: #0080FF; font-style: italic;}
.cm-s-xq-light span.cm-string {color: red;}
.cm-s-xq-light span.cm-meta {color: yellow;}
.cm-s-xq-light span.cm-qualifier {color: grey}
.cm-s-xq-light span.cm-builtin {color: #7EA656;}
.cm-s-xq-light span.cm-bracket {color: #cc7;}
.cm-s-xq-light span.cm-tag {color: #3F7F7F;}
.cm-s-xq-light span.cm-attribute {color: #7F007F;}
.cm-s-xq-light span.cm-error {color: #f00;}
.cm-s-xq-light .CodeMirror-activeline-background {background: #e8f2ff !important;}
.cm-s-xq-light .CodeMirror-matchingbracket {outline:1px solid grey;color:black !important;background:yellow;} | Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/theme/xq-light.css/0 | {
"file_path": "Humsen/web/web-pc/WebContent/plugins/editormd/lib/codemirror/theme/xq-light.css",
"repo_id": "Humsen",
"token_count": 778
} | 69 |
(function($) {
/**
* Danish language package
* Translated by @Djarnis
*/
$.fn.bootstrapValidator.i18n = $.extend(true, $.fn.bootstrapValidator.i18n, {
base64: {
'default': 'Udfyld venligst dette felt med en gyldig base64-kodet værdi'
},
between: {
'default': 'Udfyld venligst dette felt med en værdi mellem %s og %s',
notInclusive: 'Indtast venligst kun en værdi mellem %s og %s'
},
callback: {
'default': 'Udfyld venligst dette felt med en gyldig værdi'
},
choice: {
'default': 'Udfyld venligst dette felt med en gyldig værdi',
less: 'Vælg venligst mindst %s valgmuligheder',
more: 'Vælg venligst højst %s valgmuligheder',
between: 'Vælg venligst %s - %s valgmuligheder'
},
color: {
'default': 'Udfyld venligst dette felt med en gyldig farve'
},
creditCard: {
'default': 'Udfyld venligst dette felt med et gyldigt kreditkort-nummer'
},
cusip: {
'default': 'Udfyld venligst dette felt med et gyldigt CUSIP-nummer'
},
cvv: {
'default': 'Udfyld venligst dette felt med et gyldigt CVV-nummer'
},
date: {
'default': 'Udfyld venligst dette felt med en gyldig dato',
min: 'Angiv venligst en dato efter %s',
max: 'Angiv venligst en dato før %s',
range: 'Angiv venligst en dato mellem %s - %s'
},
different: {
'default': 'Udfyld venligst dette felt med en anden værdi'
},
digits: {
'default': 'Indtast venligst kun cifre'
},
ean: {
'default': 'Udfyld venligst dette felt med et gyldigt EAN-nummer'
},
emailAddress: {
'default': 'Udfyld venligst dette felt med en gyldig e-mail-adresse'
},
file: {
'default': 'Vælg venligst en gyldig fil'
},
greaterThan: {
'default': 'Udfyld venligst dette felt med en værdi større eller lig med %s',
notInclusive: 'Udfyld venligst dette felt med en værdi større end %s'
},
grid: {
'default': 'Udfyld venligst dette felt med et gyldigt GRId-nummer'
},
hex: {
'default': 'Udfyld venligst dette felt med et gyldigt hexadecimal-nummer'
},
hexColor: {
'default': 'Udfyld venligst dette felt med en gyldig hex-farve'
},
iban: {
'default': 'Udfyld venligst dette felt med et gyldigt IBAN-nummer',
countryNotSupported: 'Landekoden %s understøttes desværre ikke',
country: 'Udfyld venligst dette felt med et gyldigt IBAN-nummer i %s',
countries: {
AD: 'Andorra',
AE: 'De Forenede Arabiske Emirater',
AL: 'Albanien',
AO: 'Angola',
AT: 'Østrig',
AZ: 'Aserbajdsjan',
BA: 'Bosnien-Hercegovina',
BE: 'Belgien',
BF: 'Burkina Faso',
BG: 'Bulgarien',
BH: 'Bahrain',
BI: 'Burundi',
BJ: 'Benin',
BR: 'Brasilien',
CH: 'Schweiz',
CI: 'Elfenbenskysten',
CM: 'Cameroun',
CR: 'Costa Rica',
CV: 'Kap Verde',
CY: 'Cypern',
CZ: 'Tjekkiet',
DE: 'Tyskland',
DK: 'Danmark',
DO: 'Den Dominikanske Republik',
DZ: 'Algeriet',
EE: 'Estland',
ES: 'Spanien',
FI: 'Finland',
FO: 'Færøerne',
FR: 'Frankrig',
GB: 'Storbritannien',
GE: 'Georgien',
GI: 'Gibraltar',
GL: 'Grønland',
GR: 'Grækenland',
GT: 'Guatemala',
HR: 'Kroatien',
HU: 'Ungarn',
IE: 'Irland',
IL: 'Israel',
IR: 'Iran',
IS: 'Island',
IT: 'Italien',
JO: 'Jordan',
KW: 'Kuwait',
KZ: 'Kasakhstan',
LB: 'Libanon',
LI: 'Liechtenstein',
LT: 'Litauen',
LU: 'Luxembourg',
LV: 'Letland',
MC: 'Monaco',
MD: 'Moldova',
ME: 'Montenegro',
MG: 'Madagaskar',
MK: 'Makedonien',
ML: 'Mali',
MR: 'Mauretanien',
MT: 'Malta',
MU: 'Mauritius',
MZ: 'Mozambique',
NL: 'Holland',
NO: 'Norge',
PK: 'Pakistan',
PL: 'Polen',
PS: 'Palæstina',
PT: 'Portugal',
QA: 'Qatar',
RO: 'Rumænien',
RS: 'Serbien',
SA: 'Saudi-Arabien',
SE: 'Sverige',
SI: 'Slovenien',
SK: 'Slovakiet',
SM: 'San Marino',
SN: 'Senegal',
TN: 'Tunesien',
TR: 'Tyrkiet',
VG: 'Britiske Jomfruøer'
}
},
id: {
'default': 'Udfyld venligst dette felt med et gyldigt identifikations-nummer',
countryNotSupported: 'Landekoden %s understøttes desværre ikke',
country: 'Udfyld venligst dette felt med et gyldigt identifikations-nummer i %s',
countries: {
BA: 'Bosnien-Hercegovina',
BG: 'Bulgarien',
BR: 'Brasilien',
CH: 'Schweiz',
CL: 'Chile',
CN: 'Kina',
CZ: 'Tjekkiet',
DK: 'Danmark',
EE: 'Estland',
ES: 'Spanien',
FI: 'Finland',
HR: 'Kroatien',
IE: 'Irland',
IS: 'Island',
LT: 'Litauen',
LV: 'Letland',
ME: 'Montenegro',
MK: 'Makedonien',
NL: 'Holland',
RO: 'Rumænien',
RS: 'Serbien',
SE: 'Sverige',
SI: 'Slovenien',
SK: 'Slovakiet',
SM: 'San Marino',
TH: 'Thailand',
ZA: 'Sydafrika'
}
},
identical: {
'default': 'Udfyld venligst dette felt med den samme værdi'
},
imei: {
'default': 'Udfyld venligst dette felt med et gyldigt IMEI-nummer'
},
imo: {
'default': 'Udfyld venligst dette felt med et gyldigt IMO-nummer'
},
integer: {
'default': 'Udfyld venligst dette felt med et gyldigt tal'
},
ip: {
'default': 'Udfyld venligst dette felt med en gyldig IP adresse',
ipv4: 'Udfyld venligst dette felt med en gyldig IPv4 adresse',
ipv6: 'Udfyld venligst dette felt med en gyldig IPv6 adresse'
},
isbn: {
'default': 'Udfyld venligst dette felt med et gyldigt ISBN-nummer'
},
isin: {
'default': 'Udfyld venligst dette felt med et gyldigt ISIN-nummer'
},
ismn: {
'default': 'Udfyld venligst dette felt med et gyldigt ISMN-nummer'
},
issn: {
'default': 'Udfyld venligst dette felt med et gyldigt ISSN-nummer'
},
lessThan: {
'default': 'Udfyld venligst dette felt med en værdi mindre eller lig med %s',
notInclusive: 'Udfyld venligst dette felt med en værdi mindre end %s'
},
mac: {
'default': 'Udfyld venligst dette felt med en gyldig MAC adresse'
},
meid: {
'default': 'Udfyld venligst dette felt med et gyldigt MEID-nummer'
},
notEmpty: {
'default': 'Udfyld venligst dette felt'
},
numeric: {
'default': 'Udfyld venligst dette felt med et gyldigt flydende decimaltal'
},
phone: {
'default': 'Udfyld venligst dette felt med et gyldigt telefonnummer',
countryNotSupported: 'Landekoden %s understøttes desværre ikke',
country: 'Udfyld venligst dette felt med et gyldigt telefonnummer i %s',
countries: {
BR: 'Brasilien',
CN: 'Kina',
CZ: 'Tjekkiet',
DE: 'Tyskland',
DK: 'Danmark',
ES: 'Spanien',
FR: 'Frankrig',
GB: 'Storbritannien',
MA: 'Marokko',
PK: 'Pakistan',
RO: 'Rumænien',
RU: 'Rusland',
SK: 'Slovakiet',
TH: 'Thailand',
US: 'USA',
VE: 'Venezuela'
}
},
regexp: {
'default': 'Udfyld venligst dette felt med en værdi der matcher mønsteret'
},
remote: {
'default': 'Udfyld venligst dette felt med en gyldig værdi'
},
rtn: {
'default': 'Udfyld venligst dette felt med et gyldigt RTN-nummer'
},
sedol: {
'default': 'Udfyld venligst dette felt med et gyldigt SEDOL-nummer'
},
siren: {
'default': 'Udfyld venligst dette felt med et gyldigt SIREN-nummer'
},
siret: {
'default': 'Udfyld venligst dette felt med et gyldigt SIRET-nummer'
},
step: {
'default': 'Udfyld venligst dette felt med et gyldigt trin af %s'
},
stringCase: {
'default': 'Udfyld venligst kun dette felt med små bogstaver',
upper: 'Udfyld venligst kun dette felt med store bogstaver'
},
stringLength: {
'default': 'Udfyld venligst dette felt med en værdi af gyldig længde',
less: 'Udfyld venligst dette felt med mindre end %s tegn',
more: 'Udfyld venligst dette felt med mere end %s tegn',
between: 'Udfyld venligst dette felt med en værdi mellem %s og %s tegn'
},
uri: {
'default': 'Udfyld venligst dette felt med en gyldig URI'
},
uuid: {
'default': 'Udfyld venligst dette felt med et gyldigt UUID-nummer',
version: 'Udfyld venligst dette felt med en gyldig UUID version %s-nummer'
},
vat: {
'default': 'Udfyld venligst dette felt med et gyldig moms-nummer',
countryNotSupported: 'Landekoden %s understøttes desværre ikke',
country: 'Udfyld venligst dette felt med et gyldigt moms-nummer i %s',
countries: {
AT: 'Østrig',
BE: 'Belgien',
BG: 'Bulgarien',
BR: 'Brasilien',
CH: 'Schweiz',
CY: 'Cypern',
CZ: 'Tjekkiet',
DE: 'Tyskland',
DK: 'Danmark',
EE: 'Estland',
ES: 'Spanien',
FI: 'Finland',
FR: 'Frankrig',
GB: 'Storbritannien',
GR: 'Grækenland',
EL: 'Grækenland',
HU: 'Ungarn',
HR: 'Kroatien',
IE: 'Irland',
IS: 'Island',
IT: 'Italien',
LT: 'Litauen',
LU: 'Luxembourg',
LV: 'Letland',
MT: 'Malta',
NL: 'Holland',
NO: 'Norge',
PL: 'Polen',
PT: 'Portugal',
RO: 'Rumænien',
RU: 'Rusland',
RS: 'Serbien',
SE: 'Sverige',
SI: 'Slovenien',
SK: 'Slovakiet',
VE: 'Venezuela',
ZA: 'Sydafrika'
}
},
vin: {
'default': 'Udfyld venligst dette felt med et gyldigt VIN-nummer'
},
zipCode: {
'default': 'Udfyld venligst dette felt med et gyldigt postnummer',
countryNotSupported: 'Landekoden %s understøttes desværre ikke',
country: 'Udfyld venligst dette felt med et gyldigt postnummer i %s',
countries: {
AT: 'Østrig',
BR: 'Brasilien',
CA: 'Canada',
CH: 'Schweiz',
CZ: 'Tjekkiet',
DE: 'Tyskland',
DK: 'Danmark',
FR: 'Frankrig',
GB: 'Storbritannien',
IE: 'Irland',
IT: 'Italien',
MA: 'Marokko',
NL: 'Holland',
PT: 'Portugal',
RO: 'Rumænien',
RU: 'Rusland',
SE: 'Sverige',
SG: 'Singapore',
SK: 'Slovakiet',
US: 'USA'
}
}
});
}(window.jQuery));
| Humsen/web/web-pc/WebContent/plugins/validator/js/language/da_DK.js/0 | {
"file_path": "Humsen/web/web-pc/WebContent/plugins/validator/js/language/da_DK.js",
"repo_id": "Humsen",
"token_count": 8184
} | 70 |
(function ($) {
/**
* Portuguese (Brazil) language package
* Translated by @marcuscarvalho6. Improved by @dgmike
*/
$.fn.bootstrapValidator.i18n = $.extend(true, $.fn.bootstrapValidator.i18n, {
base64: {
'default': 'Por favor insira um código base 64 válido'
},
between: {
'default': 'Por favor insira um valor entre %s e %s',
notInclusive: 'Por favor insira um valor estritamente entre %s e %s'
},
callback: {
'default': 'Por favor insira um valor válido'
},
choice: {
'default': 'Por favor insira um valor válido',
less: 'Por favor escolha %s opções no mínimo',
more: 'Por favor escolha %s opções no máximo',
between: 'Por favor escolha de %s a %s opções'
},
color: {
'default': 'Por favor insira uma cor válida'
},
creditCard: {
'default': 'Por favor insira um número de cartão de crédito válido'
},
cusip: {
'default': 'Por favor insira um número CUSIP válido'
},
cvv: {
'default': 'Por favor insira um número CVV válido'
},
date: {
'default': 'Por favor insira uma data válida',
min: 'Por favor insira uma data posterior a %s',
max: 'Por favor insira uma data anterior a %s',
range: 'Por favor insira uma data entre %s e %s'
},
different: {
'default': 'Por favor insira valores diferentes'
},
digits: {
'default': 'Por favor insira somente dígitos'
},
ean: {
'default': 'Por favor insira um número EAN válido'
},
emailAddress: {
'default': 'Por favor insira um email válido'
},
file: {
'default': 'Por favor escolha um arquivo válido'
},
greaterThan: {
'default': 'Por favor insira um valor maior ou igual a %s',
notInclusive: 'Por favor insira um valor maior do que %s'
},
grid: {
'default': 'Por favor insira uma GRID válida'
},
hex: {
'default': 'Por favor insira um hexadecimal válido'
},
hexColor: {
'default': 'Por favor insira uma cor hexadecimal válida'
},
iban: {
'default': 'Por favor insira um número IBAN válido',
countryNotSupported: 'O código do país %s não é suportado',
country: 'Por favor insira um número IBAN válido em %s',
countries: {
AD: 'Andorra',
AE: 'Emirados Árabes',
AL: 'Albânia',
AO: 'Angola',
AT: 'Áustria',
AZ: 'Azerbaijão',
BA: 'Bósnia-Herzegovina',
BE: 'Bélgica',
BF: 'Burkina Faso',
BG: 'Bulgária',
BH: 'Bahrain',
BI: 'Burundi',
BJ: 'Benin',
BR: 'Brasil',
CH: 'Suíça',
IC: 'Costa do Marfim',
CM: 'Camarões',
CR: 'Costa Rica',
CV: 'Cabo Verde',
CY: 'Chipre',
CZ: 'República Checa',
DE: 'Alemanha',
DK: 'Dinamarca',
DO: 'República Dominicana',
DZ: 'Argélia',
EE: 'Estónia',
ES: 'Espanha',
FI: 'Finlândia',
FO: 'Ilhas Faroé',
FR: 'França',
GB: 'Reino Unido',
GE: 'Georgia',
GI: 'Gibraltar',
GL: 'Groenlândia',
GR: 'Grécia',
GT: 'Guatemala',
HR: 'Croácia',
HU: 'Hungria',
IE: 'Ireland',
IL: 'Israel',
IR: 'Irão',
IS: 'Islândia',
TI: 'Itália',
JO: 'Jordan',
KW: 'Kuwait',
KZ: 'Cazaquistão',
LB: 'Líbano',
LI: 'Liechtenstein',
LT: 'Lituânia',
LU: 'Luxemburgo',
LV: 'Letónia',
MC: 'Mônaco',
MD: 'Moldávia',
ME: 'Montenegro',
MG: 'Madagascar',
MK: 'Macedónia',
ML: 'Mali',
MR: 'Mauritânia',
MT: 'Malta',
MU: 'Maurício',
MZ: 'Moçambique',
NL: 'Países Baixos',
NO: 'Noruega',
PK: 'Paquistão',
PL: 'Polônia',
PS: 'Palestino',
PT: 'Portugal',
QA: 'Qatar',
RO: 'Roménia',
RS: 'Sérvia',
SA: 'Arábia Saudita',
SE: 'Suécia',
SI: 'Eslovénia',
SK: 'Eslováquia',
SM: 'San Marino',
SN: 'Senegal',
TN: 'Tunísia',
TR: 'Turquia',
VG: 'Ilhas Virgens Britânicas'
}
},
id: {
'default': 'Por favor insira um código de identificação válido',
countryNotSupported: 'O código do país %s não é suportado',
country: 'Por favor insira um número de indentificação válido em %s',
countries: {
BA: 'Bósnia e Herzegovina',
BG: 'Bulgária',
BR: 'Brasil',
CH: 'Suíça',
CL: 'Chile',
CN: 'China',
CZ: 'República Checa',
DK: 'Dinamarca',
EE: 'Estônia',
ES: 'Espanha',
FI: 'Finlândia',
HR: 'Croácia',
IE: 'Irlanda',
IS: 'Islândia',
LT: 'Lituânia',
LV: 'Letónia',
ME: 'Montenegro',
MK: 'Macedónia',
NL: 'Holanda',
RO: 'Roménia',
RS: 'Sérvia',
SE: 'Suécia',
SI: 'Eslovênia',
SK: 'Eslováquia',
SM: 'San Marino',
TH: 'Tailândia',
ZA: 'África do Sul'
}
},
identical: {
'default': 'Por favor, insira o mesmo valor'
},
imei: {
'default': 'Por favor insira um IMEI válido'
},
imo: {
'default': 'Por favor insira um IMO válido'
},
integer: {
'default': 'Por favor insira um número inteiro válido'
},
ip: {
'default': 'Por favor insira um IP válido',
ipv4: 'Por favor insira um endereço de IPv4 válido',
ipv6: 'Por favor insira um endereço de IPv6 válido'
},
isbn: {
'default': 'Por favor insira um ISBN válido'
},
isin: {
'default': 'Por favor insira um ISIN válido'
},
ismn: {
'default': 'Por favor insira um ISMN válido'
},
issn: {
'default': 'Por favor insira um ISSN válido'
},
lessThan: {
'default': 'Por favor insira um valor menor ou igual a %s',
notInclusive: 'Por favor insira um valor menor do que %s'
},
mac: {
'default': 'Por favor insira um endereço MAC válido'
},
meid: {
'default': 'Por favor insira um MEID válido'
},
notEmpty: {
'default': 'Por favor insira um valor'
},
numeric: {
'default': 'Por favor insira um número real válido'
},
phone: {
'default': 'Por favor insira um número de telefone válido',
countryNotSupported: 'O código de país %s não é suportado',
country: 'Por favor insira um número de telefone válido em %s',
countries: {
BR: 'Brasil',
CN: 'China',
CZ: 'República Checa',
DE: 'Alemanha',
DK: 'Dinamarca',
ES: 'Espanha',
FR: 'França',
GB: 'Reino Unido',
MA: 'Marrocos',
PK: 'Paquistão',
RO: 'Roménia',
RU: 'Rússia',
SK: 'Eslováquia',
TH: 'Tailândia',
US: 'EUA',
VE: 'Venezuela'
}
},
regexp: {
'default': 'Por favor insira um valor correspondente ao padrão'
},
remote: {
'default': 'Por favor insira um valor válido'
},
rtn: {
'default': 'Por favor insira um número válido RTN'
},
sedol: {
'default': 'Por favor insira um número válido SEDOL'
},
siren: {
'default': 'Por favor insira um número válido SIREN'
},
siret: {
'default': 'Por favor insira um número válido SIRET'
},
step: {
'default': 'Por favor insira um passo válido %s'
},
stringCase: {
'default': 'Por favor, digite apenas caracteres minúsculos',
upper: 'Por favor, digite apenas caracteres maiúsculos'
},
stringLength: {
'default': 'Por favor insira um valor com comprimento válido',
less: 'Por favor insira menos de %s caracteres',
more: 'Por favor insira mais de %s caracteres',
between: 'Por favor insira um valor entre %s e %s caracteres'
},
uri: {
'default': 'Por favor insira um URI válido'
},
uuid: {
'default': 'Por favor insira um número válido UUID',
version: 'Por favor insira uma versão %s UUID válida'
},
vat: {
'default': 'Por favor insira um VAT válido',
countryNotSupported: 'O código do país %s não é suportado',
country: 'Por favor insira um número VAT válido em %s',
countries: {
AT: 'Áustria',
BE: 'Bélgica',
BG: 'Bulgária',
BR: 'Brasil',
CH: 'Suíça',
CY: 'Chipre',
CZ: 'República Checa',
DE: 'Alemanha',
DK: 'Dinamarca',
EE: 'Estônia',
ES: 'Espanha',
FI: 'Finlândia',
FR: 'França',
GB: 'Reino Unido',
GR: 'Grécia',
EL: 'Grécia',
HU: 'Hungria',
HR: 'Croácia',
IE: 'Irlanda',
IS: 'Islândia',
IT: 'Itália',
LT: 'Lituânia',
LU: 'Luxemburgo',
LV: 'Letónia',
MT: 'Malta',
NL: 'Holanda',
NO: 'Norway',
PL: 'Polônia',
PT: 'Portugal',
RO: 'Roménia',
RU: 'Rússia',
RS: 'Sérvia',
SE: 'Suécia',
SI: 'Eslovênia',
SK: 'Eslováquia',
VE: 'Venezuela',
ZA: 'África do Sul'
}
},
vin: {
'default': 'Por favor insira um VIN válido'
},
zipCode: {
'default': 'Por favor insira um código postal válido',
countryNotSupported: 'O código postal do país %s não é suportado',
country: 'Por favor insira um código postal válido em %s',
countries: {
AT: 'Áustria',
BR: 'Brasil',
CA: 'Canadá',
CH: 'Suíça',
CZ: 'República Checa',
DE: 'Alemanha',
DK: 'Dinamarca',
FR: 'França',
GB: 'Reino Unido',
IE: 'Irlanda',
IT: 'Itália',
MA: 'Marrocos',
NL: 'Holanda',
PT: 'Portugal',
RO: 'Roménia',
RU: 'Rússia',
SE: 'Suécia',
SG: 'Cingapura',
SK: 'Eslováquia',
US: 'EUA'
}
}
});
}(window.jQuery));
| Humsen/web/web-pc/WebContent/plugins/validator/js/language/pt_BR.js/0 | {
"file_path": "Humsen/web/web-pc/WebContent/plugins/validator/js/language/pt_BR.js",
"repo_id": "Humsen",
"token_count": 7909
} | 71 |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>文章</title>
<meta name="description"
content="欢迎来到何明胜的个人网站.本站主要用于记录和分享本人的学习心得和编程经验,并分享常见可复用代码、推荐书籍以及软件等资源.本站源码已托管github,欢迎访问:https://github.com/HelloHusen/web" />
<meta name="keywords" content="何明胜,何明胜的个人网站,何明胜的博客,一格的程序人生" />
<meta name="author" content="何明胜,一格">
<!-- 网站图标 -->
<link rel="shortcut icon" href="/images/favicon.ico">
<!-- jQuery -->
<script src="/plugins/jquery/js/jquery-3.2.1.min.js"></script>
<!-- editor.md -->
<link rel="stylesheet"
href="/plugins/editormd/css/editormd.preview.min.css" />
<link rel="stylesheet" href="/plugins/editormd/css/editormd.min.css" />
<!-- editor.md -->
<script src="/plugins/editormd/lib/marked.min.js"></script>
<script src="/plugins/editormd/lib/prettify.min.js"></script>
<script src="/plugins/editormd/js/editormd.min.js"></script>
<!-- 自定义CSS -->
<link rel="stylesheet" href="/css/article/article.css">
<!-- 自定义脚本 -->
<script src="/js/article/blog.js"></script>
<script src="/js/pagination.js"></script>
</head>
<body>
<input id="menuBarNo" type="hidden" value="1" />
<div id="fh5co-page">
<!-- 左侧导航 -->
<!-- 中间内容 -->
<div id="fh5co-main">
<div id="list_blog" class="fh5co-post">
<!-- js脚本动态添加内容 -->
</div>
</div>
<!-- 右侧导航 -->
</div>
</body>
</html> | Humsen/web/web-pc/WebContent/topic/blog/blog.html/0 | {
"file_path": "Humsen/web/web-pc/WebContent/topic/blog/blog.html",
"repo_id": "Humsen",
"token_count": 790
} | 72 |
[MASTER]
load-plugins=pylint_odoo
score=n
[ODOOLINT]
readme-template-url="https://github.com/OCA/maintainer-tools/blob/master/template/module/README.rst"
manifest-required-authors=Odoo Community Association (OCA)
manifest-required-keys=license
manifest-deprecated-keys=description,active
license-allowed=AGPL-3,GPL-2,GPL-2 or any later version,GPL-3,GPL-3 or any later version,LGPL-3
valid-odoo-versions=16.0
[MESSAGES CONTROL]
disable=all
# This .pylintrc contains optional AND mandatory checks and is meant to be
# loaded in an IDE to have it check everything, in the hope this will make
# optional checks more visible to contributors who otherwise never look at a
# green travis to see optional checks that failed.
# .pylintrc-mandatory containing only mandatory checks is used the pre-commit
# config as a blocking check.
enable=anomalous-backslash-in-string,
api-one-deprecated,
api-one-multi-together,
assignment-from-none,
attribute-deprecated,
class-camelcase,
dangerous-default-value,
dangerous-view-replace-wo-priority,
development-status-allowed,
duplicate-id-csv,
duplicate-key,
duplicate-xml-fields,
duplicate-xml-record-id,
eval-referenced,
eval-used,
incoherent-interpreter-exec-perm,
license-allowed,
manifest-author-string,
manifest-deprecated-key,
manifest-required-author,
manifest-required-key,
manifest-version-format,
method-compute,
method-inverse,
method-required-super,
method-search,
openerp-exception-warning,
pointless-statement,
pointless-string-statement,
print-used,
redundant-keyword-arg,
redundant-modulename-xml,
reimported,
relative-import,
return-in-init,
rst-syntax-error,
sql-injection,
too-few-format-args,
translation-field,
translation-required,
unreachable,
use-vim-comment,
wrong-tabs-instead-of-spaces,
xml-syntax-error,
attribute-string-redundant,
character-not-valid-in-resource-link,
consider-merging-classes-inherited,
context-overridden,
create-user-wo-reset-password,
dangerous-filter-wo-user,
dangerous-qweb-replace-wo-priority,
deprecated-data-xml-node,
deprecated-openerp-xml-node,
duplicate-po-message-definition,
except-pass,
file-not-used,
invalid-commit,
manifest-maintainers-list,
missing-newline-extrafiles,
missing-readme,
missing-return,
odoo-addons-relative-import,
old-api7-method-defined,
po-msgstr-variables,
po-syntax-error,
renamed-field-parameter,
resource-not-exist,
str-format-used,
test-folder-imported,
translation-contains-variable,
translation-positional-used,
unnecessary-utf8-coding-comment,
website-manifest-key-not-valid-uri,
xml-attribute-translatable,
xml-deprecated-qweb-directive,
xml-deprecated-tree-attribute,
external-request-timeout,
# messages that do not cause the lint step to fail
consider-merging-classes-inherited,
create-user-wo-reset-password,
dangerous-filter-wo-user,
deprecated-module,
file-not-used,
invalid-commit,
missing-manifest-dependency,
missing-newline-extrafiles,
missing-readme,
no-utf8-coding-comment,
odoo-addons-relative-import,
old-api7-method-defined,
redefined-builtin,
too-complex,
unnecessary-utf8-coding-comment
[REPORTS]
msg-template={path}:{line}: [{msg_id}({symbol}), {obj}] {msg}
output-format=colorized
reports=no
| OCA/web/.pylintrc/0 | {
"file_path": "OCA/web/.pylintrc",
"repo_id": "OCA",
"token_count": 1334
} | 73 |
import setuptools
setuptools.setup(
setup_requires=['setuptools-odoo'],
odoo_addon=True,
)
| OCA/web/setup/web_calendar_slot_duration/setup.py/0 | {
"file_path": "OCA/web/setup/web_calendar_slot_duration/setup.py",
"repo_id": "OCA",
"token_count": 43
} | 74 |
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "web_action_conditionable",
"version": "16.0.1.0.0",
"depends": ["base", "web"],
"data": [],
"author": "Cristian Salamea,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/web",
"license": "AGPL-3",
"assets": {
"web.assets_backend": [
"web_action_conditionable/static/src/components/*",
],
},
"installable": True,
}
| OCA/web/web_action_conditionable/__manifest__.py/0 | {
"file_path": "OCA/web/web_action_conditionable/__manifest__.py",
"repo_id": "OCA",
"token_count": 220
} | 75 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_advanced_search
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 11.0\n"
"Report-Msgid-Bugs-To: \n"
"PO-Revision-Date: 2018-09-01 05:03+0000\n"
"Last-Translator: Hans Henrik Gabelgaard <hhg@gabelgaard.org>\n"
"Language-Team: none\n"
"Language: da\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"X-Generator: Weblate 3.1.1\n"
#. module: web_advanced_search
#. odoo-javascript
#: code:addons/web_advanced_search/static/src/js/utils.esm.js:0
#, python-format
msgid " and "
msgstr ""
#. module: web_advanced_search
#. odoo-javascript
#: code:addons/web_advanced_search/static/src/js/utils.esm.js:0
#, python-format
msgid " is not "
msgstr ""
#. module: web_advanced_search
#. odoo-javascript
#: code:addons/web_advanced_search/static/src/js/utils.esm.js:0
#, python-format
msgid " or "
msgstr ""
#. module: web_advanced_search
#. odoo-javascript
#: code:addons/web_advanced_search/static/src/search/filter_menu/advanced_filter_item.xml:0
#, python-format
msgid "Add Advanced Filter"
msgstr "Tilføj avanceret filter"
| OCA/web/web_advanced_search/i18n/da.po/0 | {
"file_path": "OCA/web/web_advanced_search/i18n/da.po",
"repo_id": "OCA",
"token_count": 493
} | 76 |
Improvements to the ``domain`` widget, not exclusively related to this addon:
* Use relational widgets when filtering a relational field
* Allow to filter field names
Improvements to the search view in this addon:
* Use widgets ``one2many_tags`` when searching ``one2many`` fields
* Use widgets ``many2many_tags`` when searching ``many2many`` fields
* Allow to edit current full search using the advanced domain editor
Issues:
* Grouped totals can show incorrect values. See https://github.com/odoo/odoo/issues/47950
| OCA/web/web_advanced_search/readme/ROADMAP.rst/0 | {
"file_path": "OCA/web/web_advanced_search/readme/ROADMAP.rst",
"repo_id": "OCA",
"token_count": 132
} | 77 |
<?xml version="1.0" encoding="UTF-8" ?>
<!--
Copyright 2017-2018 Jairo Llopis <jairo.llopis@tecnativa.com>
Copyright 2022 Camptocamp SA (https://www.camptocamp.com).
License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
-->
<templates>
<t t-inherit="web.legacy.FilterMenu" t-inherit-mode="extension" owl="1">
<CustomFilterItem position="after">
<AdvancedFilterItem />
</CustomFilterItem>
</t>
<t t-inherit="web.FilterMenu" t-inherit-mode="extension" owl="1">
<CustomFilterItem position="after">
<AdvancedFilterItem />
</CustomFilterItem>
</t>
</templates>
| OCA/web/web_advanced_search/static/src/search/filter_menu/filter_menu.xml/0 | {
"file_path": "OCA/web/web_advanced_search/static/src/search/filter_menu/filter_menu.xml",
"repo_id": "OCA",
"token_count": 282
} | 78 |
from . import res_users
| OCA/web/web_chatter_position/models/__init__.py/0 | {
"file_path": "OCA/web/web_chatter_position/models/__init__.py",
"repo_id": "OCA",
"token_count": 7
} | 79 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_company_color
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 13.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2022-03-02 15:55+0000\n"
"PO-Revision-Date: 2023-11-07 22:38+0000\n"
"Last-Translator: Ivorra78 <informatica@totmaterial.es>\n"
"Language-Team: none\n"
"Language: es\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"X-Generator: Weblate 4.17\n"
#. module: web_company_color
#: model_terms:ir.ui.view,arch_db:web_company_color.view_company_form
msgid ""
"<span class=\"fa fa-info fa-2x me-2\"/>\n"
" In order for the changes to take effect, please "
"refresh\n"
" the page."
msgstr ""
"<span class=\"fa fa-info fa-2x me-2\"/>\n"
" Para que los cambios surtan efecto, actualice\n"
" la página."
#. module: web_company_color
#: model:ir.model.fields,field_description:web_company_color.field_res_company__color_button_bg
msgid "Button Background Color"
msgstr "Color de Fondo del Botón"
#. module: web_company_color
#: model:ir.model.fields,field_description:web_company_color.field_res_company__color_button_bg_hover
msgid "Button Background Color Hover"
msgstr "Color de fondo del Botón Hover"
#. module: web_company_color
#: model:ir.model.fields,field_description:web_company_color.field_res_company__color_button_text
msgid "Button Text Color"
msgstr "Color del Texto del Botón"
#. module: web_company_color
#: model_terms:ir.ui.view,arch_db:web_company_color.view_company_form
msgid "Colors"
msgstr "Colores"
#. module: web_company_color
#: model:ir.model,name:web_company_color.model_res_company
msgid "Companies"
msgstr "Compañías"
#. module: web_company_color
#: model:ir.model.fields,field_description:web_company_color.field_res_company__company_colors
msgid "Company Colors"
msgstr "Colores de la compañía"
#. module: web_company_color
#: model_terms:ir.ui.view,arch_db:web_company_color.view_company_form
msgid "Company Styles"
msgstr "Estilos de compañía"
#. module: web_company_color
#: model_terms:ir.ui.view,arch_db:web_company_color.view_company_form
msgid "Compute colors from logo"
msgstr "Calcular colores a partir del logo"
#. module: web_company_color
#: model:ir.model.fields,field_description:web_company_color.field_res_company__color_link_text
msgid "Link Text Color"
msgstr "Color del Texto del Enlace"
#. module: web_company_color
#: model:ir.model.fields,field_description:web_company_color.field_res_company__color_link_text_hover
msgid "Link Text Color Hover"
msgstr "Color del Texto del Enlace Hover"
#. module: web_company_color
#: model:ir.model.fields,field_description:web_company_color.field_res_company__color_navbar_bg
msgid "Navbar Background Color"
msgstr "Color de fondo de la barra de navegación"
#. module: web_company_color
#: model:ir.model.fields,field_description:web_company_color.field_res_company__color_navbar_bg_hover
msgid "Navbar Background Color Hover"
msgstr "Desplazamiento del color de fondo de la barra de navegación"
#. module: web_company_color
#: model:ir.model.fields,field_description:web_company_color.field_res_company__color_navbar_text
msgid "Navbar Text Color"
msgstr "Color de texto de la barra de navegación"
#. module: web_company_color
#: model:ir.model,name:web_company_color.model_ir_qweb
msgid "Qweb"
msgstr "Qweb"
#. module: web_company_color
#: model:ir.model.fields,field_description:web_company_color.field_res_company__scss_modif_timestamp
msgid "SCSS Modif. Timestamp"
msgstr "SCSS Modif. Marca de tiempo"
#~ msgid "Navbar Colors"
#~ msgstr "Colores de la barra de navegación"
#~ msgid ""
#~ "<span class=\"fa fa-info fa-2x\"/>\n"
#~ " In order for the changes to take effect, please "
#~ "refresh\n"
#~ " the page."
#~ msgstr ""
#~ "<span class = \"fa fa-info fa-2x\" />\n"
#~ " Para que los cambios surtan efecto, actualice\n"
#~ " la página."
| OCA/web/web_company_color/i18n/es.po/0 | {
"file_path": "OCA/web/web_company_color/i18n/es.po",
"repo_id": "OCA",
"token_count": 1680
} | 80 |
# © 2022 Florian Kantelberg - initOS GmbH
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
from odoo.http import request
class IrHttp(models.AbstractModel):
_inherit = "ir.http"
@classmethod
def _set_color_scheme(cls, response):
scheme = request.httprequest.cookies.get("color_scheme")
user = request.env.user
user_scheme = "dark" if getattr(user, "dark_mode", None) else "light"
device_dependent = getattr(user, "dark_mode_device_dependent", None)
if (not device_dependent) and scheme != user_scheme:
response.set_cookie("color_scheme", user_scheme)
@classmethod
def _post_dispatch(cls, response):
cls._set_color_scheme(response)
return super()._post_dispatch(response)
| OCA/web/web_dark_mode/models/ir_http.py/0 | {
"file_path": "OCA/web/web_dark_mode/models/ir_http.py",
"repo_id": "OCA",
"token_count": 321
} | 81 |
<?xml version="1.0" encoding="utf-8" ?>
<odoo>
<record id="installed_modules" model="tile.tile">
<field name="name">Installed Modules</field>
<field name="category_id" ref="category_module" />
<field name="model_id" ref="base.model_ir_module_module" />
<field name="action_id" ref="base.open_module_tree" />
<field
name="domain"
>[['state', 'in', ['installed', 'to upgrade', 'to remove']]]</field>
</record>
<record id="installed_OCA_modules" model="tile.tile">
<field name="name">Installed OCA Modules</field>
<field name="category_id" ref="category_module" />
<field name="model_id" ref="base.model_ir_module_module" />
<field name="action_id" ref="base.open_module_tree" />
<field
name="domain"
>[['state', 'in', ['installed', 'to upgrade', 'to remove']], ['author', 'ilike', 'Odoo Community Association (OCA)']]</field>
</record>
<record id="all_currency_with_rate" model="tile.tile">
<field name="name">Currencies (Max Rate)</field>
<field name="category_id" ref="category_currency" />
<field name="model_id" ref="base.model_res_currency" />
<field name="secondary_function">max</field>
<field name="secondary_field_id" ref="base.field_res_currency__rate" />
<field name="domain">[]</field>
</record>
</odoo>
| OCA/web/web_dashboard_tile/demo/tile_tile.xml/0 | {
"file_path": "OCA/web/web_dashboard_tile/demo/tile_tile.xml",
"repo_id": "OCA",
"token_count": 586
} | 82 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_dialog_size
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 14.0\n"
"Report-Msgid-Bugs-To: \n"
"PO-Revision-Date: 2021-05-14 20:47+0000\n"
"Last-Translator: Yves Le Doeuff <yld@alliasys.fr>\n"
"Language-Team: none\n"
"Language: fr\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=2; plural=n > 1;\n"
"X-Generator: Weblate 4.3.2\n"
#. module: web_dialog_size
#: model:ir.model,name:web_dialog_size.model_ir_config_parameter
msgid "System Parameter"
msgstr "Paramètre système"
#~ msgid "Display Name"
#~ msgstr "Nom affiché"
| OCA/web/web_dialog_size/i18n/fr.po/0 | {
"file_path": "OCA/web/web_dialog_size/i18n/fr.po",
"repo_id": "OCA",
"token_count": 304
} | 83 |
.modal {
.modal-dialog_full_screen {
@include media-breakpoint-up(sm) {
max-width: 100%;
width: calc(100% - 50px);
}
}
.dialog_button_restore,
.dialog_button_extend {
margin-left: auto;
+ .btn-close {
margin: -8px -8px -8px 0px;
}
}
}
| OCA/web/web_dialog_size/static/src/scss/web_dialog_size.scss/0 | {
"file_path": "OCA/web/web_dialog_size/static/src/scss/web_dialog_size.scss",
"repo_id": "OCA",
"token_count": 190
} | 84 |
# Copyright 2018 Tecnativa - David Vidal
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import models
from odoo.http import request
class Http(models.AbstractModel):
_inherit = "ir.http"
def session_info(self):
res = super().session_info()
user = request.env.user
res.update(
{
"group_xlsx_export_data": user
and user.has_group("web_disable_export_group.group_export_xlsx_data"),
}
)
return res
| OCA/web/web_disable_export_group/models/ir_http.py/0 | {
"file_path": "OCA/web/web_disable_export_group/models/ir_http.py",
"repo_id": "OCA",
"token_count": 247
} | 85 |
================
Web Domain Field
================
..
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! This file is generated by oca-gen-addon-readme !!
!! changes will be overwritten. !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! source digest: sha256:38caddd3efd0bf3c90c5b3a84068ef6e757e1bb72698ee16451a62c210e7a154
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png
:target: https://odoo-community.org/page/development-status
:alt: Beta
.. |badge2| image:: https://img.shields.io/badge/licence-AGPL--3-blue.png
:target: http://www.gnu.org/licenses/agpl-3.0-standalone.html
:alt: License: AGPL-3
.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fweb-lightgray.png?logo=github
:target: https://github.com/OCA/web/tree/16.0/web_domain_field
:alt: OCA/web
.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png
:target: https://translation.odoo-community.org/projects/web-16-0/web-16-0-web_domain_field
:alt: Translate me on Weblate
.. |badge5| image:: https://img.shields.io/badge/runboat-Try%20me-875A7B.png
:target: https://runboat.odoo-community.org/builds?repo=OCA/web&target_branch=16.0
:alt: Try me on Runboat
|badge1| |badge2| |badge3| |badge4| |badge5|
.. warning::
This module is deprecated.
If you want to use this functionality you can assign a unserialised
domain to a fields.Binary, `example <https://github.com/OCA/OCB/blob/16.0/addons/account/models/account_tax.py#L1308>`_
This technical addon allows developers to specify a field domain in a view
using the value of another field in that view, rather than as a static
XML attribute.
**Table of contents**
.. contents::
:local:
Usage
=====
When you define a view you can specify on the relational fields a domain
attribute. This attribute is evaluated as filter to apply when displaying
existing records for selection.
.. code-block:: xml
<field name="product_id" domain="[('type','=','product')]"/>
The value provided for the domain attribute must be a string representing a
valid Odoo domain. This string is evaluated on the client side in a
restricted context where we can reference as right operand the values of
fields present into the form and a limited set of functions.
In this context it's hard to build complex domain and we are facing to some
limitations as:
* The syntax to include in your domain a criteria involving values from a
x2many field is complex.
* The right side of domain in case of x2many can involve huge amount of ids
(performance problem).
* Domains computed by an onchange on an other field are not recomputed when
you modify the form and don't modify the field triggering the onchange.
* It's not possible to extend an existing domain. You must completely redefine
the domain in your specialized addon
* etc...
In order to mitigate these limitations this new addon allows you to use the
value of a field as domain of an other field in the xml definition of your
view.
.. code-block:: xml
<field name="product_id_domain" invisible="1"/>
<field name="product_id" domain="product_id_domain"/>
The field used as domain must provide the domain as a JSON encoded string.
.. code-block:: python
product_id_domain = fields.Char(
compute="_compute_product_id_domain",
readonly=True,
store=False,
)
@api.depends('name')
def _compute_product_id_domain(self):
for rec in self:
rec.product_id_domain = json.dumps(
[('type', '=', 'product'), ('name', 'like', rec.name)]
)
.. note::
You do not actually need this module to craft a dynamic domain. Odoo comes
with its own `py.js <https://github.com/odoo/odoo/tree/16.0/addons/web/static/lib/py.js>`_
web library to parse expressions such as domains. `py.js` supports more
complex expressions than just static lists.
Here is an example of a conditional domain based on the value of another
field:
.. code-block:: python
(order_id or partner_id) and [('id', 'in', allowed_picking_ids)]
or [('state', '=', 'done'), ('picking_type_id.code', '=', 'outgoing')]
For OCA modules, this method is preferred over adding this module as an
additional dependency.
Bug Tracker
===========
Bugs are tracked on `GitHub Issues <https://github.com/OCA/web/issues>`_.
In case of trouble, please check there if your issue has already been reported.
If you spotted it first, help us to smash it by providing a detailed and welcomed
`feedback <https://github.com/OCA/web/issues/new?body=module:%20web_domain_field%0Aversion:%2016.0%0A%0A**Steps%20to%20reproduce**%0A-%20...%0A%0A**Current%20behavior**%0A%0A**Expected%20behavior**>`_.
Do not contact contributors directly about support or help with technical issues.
Credits
=======
Authors
~~~~~~~
* ACSONE SA/NV
Contributors
~~~~~~~~~~~~
* Laurent Mignon <laurent.mignon@acsone.eu>
* Denis Roussel <denis.roussel@acsone.eu>
* Raf Ven <raf.ven@dynapps.be>
Maintainers
~~~~~~~~~~~
This module is maintained by the OCA.
.. image:: https://odoo-community.org/logo.png
:alt: Odoo Community Association
:target: https://odoo-community.org
OCA, or the Odoo Community Association, is a nonprofit organization whose
mission is to support the collaborative development of Odoo features and
promote its widespread use.
This module is part of the `OCA/web <https://github.com/OCA/web/tree/16.0/web_domain_field>`_ project on GitHub.
You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.
| OCA/web/web_domain_field/README.rst/0 | {
"file_path": "OCA/web/web_domain_field/README.rst",
"repo_id": "OCA",
"token_count": 1884
} | 86 |
# Copyright 2015 Francesco OpenCode Apruzzese <cescoap@gmail.com>
# Copyright 2016 Antonio Espinosa <antonio.espinosa@tecnativa.com>
# Copyright 2017 Thomas Binsfeld <thomas.binsfeld@acsone.eu>
# Copyright 2017 Xavier Jiménez <xavier.jimenez@qubiq.es>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Web Environment Ribbon",
"version": "16.0.1.0.0",
"category": "Web",
"author": "Francesco OpenCode Apruzzese, "
"Tecnativa, "
"Odoo Community Association (OCA)",
"website": "https://github.com/OCA/web",
"license": "AGPL-3",
"depends": ["web"],
"data": [
"data/ribbon_data.xml",
],
"auto_install": False,
"installable": True,
"assets": {
"web.assets_common": [
"web_environment_ribbon/static/**/*",
],
},
}
| OCA/web/web_environment_ribbon/__manifest__.py/0 | {
"file_path": "OCA/web/web_environment_ribbon/__manifest__.py",
"repo_id": "OCA",
"token_count": 361
} | 87 |
from . import web_environment_ribbon_backend
| OCA/web/web_environment_ribbon/models/__init__.py/0 | {
"file_path": "OCA/web/web_environment_ribbon/models/__init__.py",
"repo_id": "OCA",
"token_count": 13
} | 88 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 16.0\n"
"Report-Msgid-Bugs-To: \n"
"Last-Translator: Automatically generated\n"
"Language-Team: none\n"
"Language: it\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
| OCA/web/web_field_numeric_formatting/i18n/it.po/0 | {
"file_path": "OCA/web/web_field_numeric_formatting/i18n/it.po",
"repo_id": "OCA",
"token_count": 161
} | 89 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_group_expand
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 16.0\n"
"Report-Msgid-Bugs-To: \n"
"PO-Revision-Date: 2023-11-27 11:34+0000\n"
"Last-Translator: mymage <stefano.consolaro@mymage.it>\n"
"Language-Team: none\n"
"Language: it\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"X-Generator: Weblate 4.17\n"
#. module: web_group_expand
#. odoo-javascript
#: code:addons/web_group_expand/static/src/xml/list_controller.xml:0
#, python-format
msgid "Compress"
msgstr "Comprimi"
#. module: web_group_expand
#. odoo-javascript
#: code:addons/web_group_expand/static/src/xml/list_controller.xml:0
#, python-format
msgid "Expand"
msgstr "Espandi"
| OCA/web/web_group_expand/i18n/it.po/0 | {
"file_path": "OCA/web/web_group_expand/i18n/it.po",
"repo_id": "OCA",
"token_count": 358
} | 90 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_help
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 16.0\n"
"Report-Msgid-Bugs-To: \n"
"Last-Translator: \n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: \n"
#. module: web_help
#. odoo-javascript
#: code:addons/web_help/static/src/user_trip.esm.js:0
#, python-format
msgid "Cancel"
msgstr ""
#. module: web_help
#. odoo-javascript
#: code:addons/web_help/static/src/change_password_trip.esm.js:0
#, python-format
msgid "Change the password here, make sure it's secure."
msgstr ""
#. module: web_help
#. odoo-javascript
#: code:addons/web_help/static/src/change_password_trip.esm.js:0
#, python-format
msgid "Click here to confirm it."
msgstr ""
#. module: web_help
#. odoo-javascript
#: code:addons/web_help/static/src/trip.esm.js:0
#, python-format
msgid "Close"
msgstr ""
#. module: web_help
#. odoo-javascript
#: code:addons/web_help/static/src/trip.esm.js:0
#, python-format
msgid "Finish"
msgstr ""
#. module: web_help
#. odoo-javascript
#: code:addons/web_help/static/src/trip.esm.js:0
#, python-format
msgid "Got it"
msgstr ""
#. module: web_help
#. odoo-javascript
#: code:addons/web_help/static/src/user_trip.esm.js:0
#, python-format
msgid "Next"
msgstr ""
#. module: web_help
#. odoo-javascript
#: code:addons/web_help/static/src/user_trip.esm.js:0
#, python-format
msgid "To create a new user click here."
msgstr ""
#. module: web_help
#. odoo-javascript
#: code:addons/web_help/static/src/user_trip.esm.js:0
#, python-format
msgid "Use the searchbar to find specific users."
msgstr ""
#. module: web_help
#. odoo-javascript
#: code:addons/web_help/static/src/user_trip.esm.js:0
#, python-format
msgid "You can switch to different views here."
msgstr ""
| OCA/web/web_help/i18n/web_help.pot/0 | {
"file_path": "OCA/web/web_help/i18n/web_help.pot",
"repo_id": "OCA",
"token_count": 736
} | 91 |
/** @odoo-module **/
import {registry} from "@web/core/registry";
import {Component} from "@odoo/owl";
export async function findTrip(model, viewType) {
const trips = registry.category("trips").getAll();
const selectorResults = await Promise.all(
trips.map((trip) => trip.selector(model, viewType))
);
const matchedTrips = trips.filter((trip, i) => selectorResults[i]);
if (matchedTrips.length >= 1) {
if (matchedTrips.length != 1) {
console.warn("More than one trip found", model, viewType);
}
return matchedTrips[0].Trip;
}
return null;
}
export function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export async function waitUntilAvailable(selector, ms = 50) {
const selection = $(selector);
if (!selection.length) {
await wait(ms);
return await waitUntilAvailable(selector, ms);
}
return selection;
}
export async function doAction(xmlId, options = {}) {
Component.env.bus.trigger("do-action", {
action: xmlId,
options: options,
});
}
| OCA/web/web_help/static/src/helpers.esm.js/0 | {
"file_path": "OCA/web/web_help/static/src/helpers.esm.js",
"repo_id": "OCA",
"token_count": 417
} | 92 |
# Copyright 2017 - 2018 Modoolar <info@modoolar.com>
# Copyright 2018 Brainbean Apps
# Copyright 2020 Manuel Calero
# Copyright 2020 CorporateHub (https://corporatehub.eu)
# License LGPLv3.0 or later (https://www.gnu.org/licenses/lgpl-3.0.en.html).
{
"name": "Web Actions Multi",
"summary": "Enables triggering of more than one action on ActionManager",
"category": "Web",
"version": "16.0.1.0.0",
"license": "LGPL-3",
"author": "Modoolar, " "CorporateHub, " "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/web",
"depends": ["web"],
"data": ["security/ir.model.access.csv"],
"assets": {
"web.assets_backend": [
"web_ir_actions_act_multi/static/src/**/*.esm.js",
],
},
"installable": True,
}
| OCA/web/web_ir_actions_act_multi/__manifest__.py/0 | {
"file_path": "OCA/web/web_ir_actions_act_multi/__manifest__.py",
"repo_id": "OCA",
"token_count": 320
} | 93 |
# Copyright 2017 Therp BV, ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Client side message boxes",
"version": "16.0.1.0.1",
"author": "Therp BV, " "ACSONE SA/NV, " "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/web",
"license": "AGPL-3",
"category": "Hidden/Dependency",
"summary": "Show a message box to users",
"depends": ["web"],
"data": ["security/ir.model.access.csv"],
"assets": {
"web.assets_backend": [
"web_ir_actions_act_window_message/static/src/**/**.esm.js",
],
"web.assets_qweb": [
"web_ir_actions_act_window_message/static/src/**/**.xml",
],
},
}
| OCA/web/web_ir_actions_act_window_message/__manifest__.py/0 | {
"file_path": "OCA/web/web_ir_actions_act_window_message/__manifest__.py",
"repo_id": "OCA",
"token_count": 332
} | 94 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_ir_actions_act_window_message
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 16.0\n"
"Report-Msgid-Bugs-To: \n"
"Last-Translator: \n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: \n"
#. module: web_ir_actions_act_window_message
#: model:ir.model.fields,field_description:web_ir_actions_act_window_message.field_ir_actions_act_window_message__help
msgid "Action Description"
msgstr ""
#. module: web_ir_actions_act_window_message
#: model:ir.model.fields,field_description:web_ir_actions_act_window_message.field_ir_actions_act_window_message__name
msgid "Action Name"
msgstr ""
#. module: web_ir_actions_act_window_message
#: model:ir.model.fields,field_description:web_ir_actions_act_window_message.field_ir_actions_act_window_message__type
msgid "Action Type"
msgstr ""
#. module: web_ir_actions_act_window_message
#: model:ir.model,name:web_ir_actions_act_window_message.model_ir_actions_act_window_message
msgid "Action Window Message"
msgstr ""
#. module: web_ir_actions_act_window_message
#: model:ir.model.fields,field_description:web_ir_actions_act_window_message.field_ir_actions_act_window_message__binding_model_id
msgid "Binding Model"
msgstr ""
#. module: web_ir_actions_act_window_message
#: model:ir.model.fields,field_description:web_ir_actions_act_window_message.field_ir_actions_act_window_message__binding_type
msgid "Binding Type"
msgstr ""
#. module: web_ir_actions_act_window_message
#: model:ir.model.fields,field_description:web_ir_actions_act_window_message.field_ir_actions_act_window_message__binding_view_types
msgid "Binding View Types"
msgstr ""
#. module: web_ir_actions_act_window_message
#. odoo-javascript
#: code:addons/web_ir_actions_act_window_message/static/src/js/web_ir_actions_act_window_message.esm.js:0
#, python-format
msgid "Close"
msgstr ""
#. module: web_ir_actions_act_window_message
#: model:ir.model.fields,field_description:web_ir_actions_act_window_message.field_ir_actions_act_window_message__create_uid
msgid "Created by"
msgstr ""
#. module: web_ir_actions_act_window_message
#: model:ir.model.fields,field_description:web_ir_actions_act_window_message.field_ir_actions_act_window_message__create_date
msgid "Created on"
msgstr ""
#. module: web_ir_actions_act_window_message
#: model:ir.model.fields,field_description:web_ir_actions_act_window_message.field_ir_actions_act_window_message__display_name
msgid "Display Name"
msgstr ""
#. module: web_ir_actions_act_window_message
#: model:ir.model.fields,field_description:web_ir_actions_act_window_message.field_ir_actions_act_window_message__xml_id
msgid "External ID"
msgstr ""
#. module: web_ir_actions_act_window_message
#: model:ir.model.fields,field_description:web_ir_actions_act_window_message.field_ir_actions_act_window_message__id
msgid "ID"
msgstr ""
#. module: web_ir_actions_act_window_message
#: model:ir.model.fields,field_description:web_ir_actions_act_window_message.field_ir_actions_act_window_message____last_update
msgid "Last Modified on"
msgstr ""
#. module: web_ir_actions_act_window_message
#: model:ir.model.fields,field_description:web_ir_actions_act_window_message.field_ir_actions_act_window_message__write_uid
msgid "Last Updated by"
msgstr ""
#. module: web_ir_actions_act_window_message
#: model:ir.model.fields,field_description:web_ir_actions_act_window_message.field_ir_actions_act_window_message__write_date
msgid "Last Updated on"
msgstr ""
#. module: web_ir_actions_act_window_message
#: model:ir.model.fields,help:web_ir_actions_act_window_message.field_ir_actions_act_window_message__help
msgid ""
"Optional help text for the users with a description of the target view, such"
" as its usage and purpose."
msgstr ""
#. module: web_ir_actions_act_window_message
#: model:ir.model.fields,help:web_ir_actions_act_window_message.field_ir_actions_act_window_message__binding_model_id
msgid ""
"Setting a value makes this action available in the sidebar for the given "
"model."
msgstr ""
| OCA/web/web_ir_actions_act_window_message/i18n/web_ir_actions_act_window_message.pot/0 | {
"file_path": "OCA/web/web_ir_actions_act_window_message/i18n/web_ir_actions_act_window_message.pot",
"repo_id": "OCA",
"token_count": 1455
} | 95 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_ir_actions_act_window_page
#
# Translators:
# Rudolf Schnapka <rs@techno-flex.de>, 2018
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 10.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2018-01-03 03:50+0000\n"
"PO-Revision-Date: 2018-01-03 03:50+0000\n"
"Last-Translator: Rudolf Schnapka <rs@techno-flex.de>, 2018\n"
"Language-Team: German (https://www.transifex.com/oca/teams/23907/de/)\n"
"Language: de\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#. module: web_ir_actions_act_window_page
#: model:ir.model,name:web_ir_actions_act_window_page.model_ir_actions_act_window_page_next
msgid "Action to page to the next record from a form view button"
msgstr ""
#. module: web_ir_actions_act_window_page
#: model:ir.model,name:web_ir_actions_act_window_page.model_ir_actions_act_window_page_prev
msgid "Action to page to the previous record from a form view button"
msgstr ""
#. module: web_ir_actions_act_window_page
#: model:ir.model,name:web_ir_actions_act_window_page.model_ir_actions_act_window_page_list
msgid "Action to switch to the list view"
msgstr ""
#. module: web_ir_actions_act_window_page
#: model_terms:ir.ui.view,arch_db:web_ir_actions_act_window_page.view_partner_form
msgid "Next Partner"
msgstr "Nächster Partner"
#. module: web_ir_actions_act_window_page
#: model:ir.actions.server,name:web_ir_actions_act_window_page.demo_pager_next
msgid "Next partner"
msgstr "Nächster Partner"
#. module: web_ir_actions_act_window_page
#: model_terms:ir.ui.view,arch_db:web_ir_actions_act_window_page.view_partner_form
msgid "Previous Partner"
msgstr "Voriger Partner"
#. module: web_ir_actions_act_window_page
#: model:ir.actions.server,name:web_ir_actions_act_window_page.demo_pager_previous
msgid "Previous partner"
msgstr "Voriger Partner"
| OCA/web/web_ir_actions_act_window_page/i18n/de.po/0 | {
"file_path": "OCA/web/web_ir_actions_act_window_page/i18n/de.po",
"repo_id": "OCA",
"token_count": 764
} | 96 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_m2x_options
#
# Translators:
# OCA Transbot <transbot@odoo-community.org>, 2017
# Rudolf Schnapka <rs@techno-flex.de>, 2018
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 10.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2018-01-03 03:50+0000\n"
"PO-Revision-Date: 2023-06-20 11:09+0000\n"
"Last-Translator: Nils Coenen <nils.coenen@nico-solutions.de>\n"
"Language-Team: German (https://www.transifex.com/oca/teams/23907/de/)\n"
"Language: de\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"X-Generator: Weblate 4.17\n"
#. module: web_m2x_options
#. odoo-javascript
#: code:addons/web_m2x_options/static/src/components/base.xml:0
#, python-format
msgid ", are you sure it does not exist yet?"
msgstr ", bist du sicher, dass es noch nicht existiert?"
#. module: web_m2x_options
#. odoo-javascript
#: code:addons/web_m2x_options/static/src/components/base.xml:0
#, python-format
msgid "Create"
msgstr "Anlegen"
#. module: web_m2x_options
#. odoo-javascript
#: code:addons/web_m2x_options/static/src/components/relational_utils.esm.js:0
#, python-format
msgid "Create \"%s\""
msgstr "Erstelle \"%s\""
#. module: web_m2x_options
#. odoo-javascript
#: code:addons/web_m2x_options/static/src/components/base.xml:0
#, python-format
msgid "Create and Edit"
msgstr "Erstellen und bearbeiten"
#. module: web_m2x_options
#. odoo-javascript
#: code:addons/web_m2x_options/static/src/components/relational_utils.esm.js:0
#, python-format
msgid "Create and edit..."
msgstr "Erstellen und bearbeiten..."
#. module: web_m2x_options
#. odoo-javascript
#: code:addons/web_m2x_options/static/src/components/base.xml:0
#, python-format
msgid "Discard"
msgstr "Verwerfen"
#. module: web_m2x_options
#: model:ir.model,name:web_m2x_options.model_ir_http
msgid "HTTP Routing"
msgstr ""
#. module: web_m2x_options
#. odoo-javascript
#: code:addons/web_m2x_options/static/src/components/form.esm.js:0
#, python-format
msgid "New: %s"
msgstr "Neu: %s"
#. module: web_m2x_options
#. odoo-javascript
#: code:addons/web_m2x_options/static/src/components/relational_utils.esm.js:0
#, python-format
msgid "No records"
msgstr "Keine Datensätze"
#. module: web_m2x_options
#. odoo-javascript
#: code:addons/web_m2x_options/static/src/components/form.esm.js:0
#, python-format
msgid "Open: "
msgstr "Öffnen: "
#. module: web_m2x_options
#. odoo-javascript
#: code:addons/web_m2x_options/static/src/components/relational_utils.esm.js:0
#, python-format
msgid "Search More..."
msgstr "Suche weitere..."
#. module: web_m2x_options
#. odoo-javascript
#: code:addons/web_m2x_options/static/src/components/relational_utils.esm.js:0
#, python-format
msgid "Start typing..."
msgstr "Beginne zu tippen..."
#. module: web_m2x_options
#: model:ir.model,name:web_m2x_options.model_ir_config_parameter
msgid "System Parameter"
msgstr "Systemparameter"
#. module: web_m2x_options
#. odoo-javascript
#: code:addons/web_m2x_options/static/src/components/base.xml:0
#, python-format
msgid "You are creating a new"
msgstr "Du erstellst ein Neues"
#. module: web_m2x_options
#. odoo-javascript
#: code:addons/web_m2x_options/static/src/components/base.xml:0
#, python-format
msgid "as a new"
msgstr "als neu"
#, python-format
#~ msgid "Cancel"
#~ msgstr "Abbrechen"
#, python-format
#~ msgid "Create \"<strong>%s</strong>\""
#~ msgstr "Anlegen \"<strong>%s</strong>"
#, python-format
#~ msgid "Create a %s"
#~ msgstr "Eine %s anlegen"
#, python-format
#~ msgid "Create and Edit..."
#~ msgstr "Anlegen und Bearbeiten"
#, python-format
#~ msgid "Create and edit"
#~ msgstr "Anlegen und bearbeiten"
#, python-format
#~ msgid "No results to show..."
#~ msgstr "Keine Resultate zu zeigen..."
#, python-format
#~ msgid "Quick search: %s"
#~ msgstr "Schnellsuche: %s"
#, python-format
#~ msgid "You are creating a new %s, are you sure it does not exist yet?"
#~ msgstr ""
#~ "Sie legen eine neue %s an, sind Sie sicher, dass diese nicht bereits "
#~ "vorhanden ist?"
#~ msgid "!(widget.nodeOptions.no_open || widget.nodeOptions.no_open_edit)"
#~ msgstr "!(widget.nodeOptions.no_open || widget.nodeOptions.no_open_edit)"
| OCA/web/web_m2x_options/i18n/de.po/0 | {
"file_path": "OCA/web/web_m2x_options/i18n/de.po",
"repo_id": "OCA",
"token_count": 1760
} | 97 |
from odoo import models
class Http(models.AbstractModel):
_inherit = "ir.http"
def session_info(self):
IrConfigSudo = self.env["ir.config_parameter"].sudo()
session_info = super().session_info()
session_info.update({"web_m2x_options": IrConfigSudo.get_web_m2x_options()})
return session_info
| OCA/web/web_m2x_options/models/ir_http.py/0 | {
"file_path": "OCA/web/web_m2x_options/models/ir_http.py",
"repo_id": "OCA",
"token_count": 138
} | 98 |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * web_notify
#
# Translators:
# Pedro M. Baeza <pedro.baeza@gmail.com>, 2016
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 10.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2016-12-23 02:13+0000\n"
"PO-Revision-Date: 2023-09-02 20:35+0000\n"
"Last-Translator: Ivorra78 <informatica@totmaterial.es>\n"
"Language-Team: Spanish (https://www.transifex.com/oca/teams/23907/es/)\n"
"Language: es\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"X-Generator: Weblate 4.17\n"
#. module: web_notify
#. odoo-python
#: code:addons/web_notify/models/res_users.py:0
#, python-format
msgid "Danger"
msgstr "Peligro"
#. module: web_notify
#. odoo-python
#: code:addons/web_notify/models/res_users.py:0
#, python-format
msgid "Default"
msgstr "Predeterminado"
#. module: web_notify
#. odoo-python
#: code:addons/web_notify/models/res_users.py:0
#, python-format
msgid "Information"
msgstr "Información"
#. module: web_notify
#: model:ir.model.fields,field_description:web_notify.field_res_users__notify_danger_channel_name
msgid "Notify Danger Channel Name"
msgstr "Notificar el nombre del canal de peligro"
#. module: web_notify
#: model:ir.model.fields,field_description:web_notify.field_res_users__notify_default_channel_name
msgid "Notify Default Channel Name"
msgstr "Notificar Nombre de Canal por Defecto"
#. module: web_notify
#: model:ir.model.fields,field_description:web_notify.field_res_users__notify_info_channel_name
msgid "Notify Info Channel Name"
msgstr "Notificar información Nombre del canal"
#. module: web_notify
#: model:ir.model.fields,field_description:web_notify.field_res_users__notify_success_channel_name
msgid "Notify Success Channel Name"
msgstr "Notificar con éxito Nombre del canal"
#. module: web_notify
#: model:ir.model.fields,field_description:web_notify.field_res_users__notify_warning_channel_name
msgid "Notify Warning Channel Name"
msgstr "Notificar advertencia Nombre del canal"
#. module: web_notify
#. odoo-python
#: code:addons/web_notify/models/res_users.py:0
#, python-format
msgid "Sending a notification to another user is forbidden."
msgstr "Está prohibido enviar una notificación a otro usuario."
#. module: web_notify
#. odoo-python
#: code:addons/web_notify/models/res_users.py:0
#, python-format
msgid "Success"
msgstr "Éxito"
#. module: web_notify
#: model_terms:ir.ui.view,arch_db:web_notify.view_users_form_simple_modif_inherit
msgid "Test danger notification"
msgstr "Notificación de peligro de prueba"
#. module: web_notify
#: model_terms:ir.ui.view,arch_db:web_notify.view_users_form_simple_modif_inherit
msgid "Test default notification"
msgstr "Probar notificación predeterminada"
#. module: web_notify
#: model_terms:ir.ui.view,arch_db:web_notify.view_users_form_simple_modif_inherit
msgid "Test info notification"
msgstr "Notificación de información de prueba"
#. module: web_notify
#: model_terms:ir.ui.view,arch_db:web_notify.view_users_form_simple_modif_inherit
msgid "Test success notification"
msgstr "Notificación de éxito de la prueba"
#. module: web_notify
#: model_terms:ir.ui.view,arch_db:web_notify.view_users_form_simple_modif_inherit
msgid "Test warning notification"
msgstr "Notificación de advertencia de prueba"
#. module: web_notify
#: model_terms:ir.ui.view,arch_db:web_notify.view_users_form_simple_modif_inherit
msgid "Test web notify"
msgstr "Notificación web de prueba"
#. module: web_notify
#: model:ir.model,name:web_notify.model_res_users
msgid "User"
msgstr "Usuario"
#. module: web_notify
#. odoo-python
#: code:addons/web_notify/models/res_users.py:0
#, python-format
msgid "Warning"
msgstr "Aviso"
#~ msgid "Users"
#~ msgstr "Usuarios"
| OCA/web/web_notify/i18n/es.po/0 | {
"file_path": "OCA/web/web_notify/i18n/es.po",
"repo_id": "OCA",
"token_count": 1507
} | 99 |